Tue Mar 2 17:31:46 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: 244385 $")
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 #define CALLERID_UNKNOWN             "Anonymous"
00247 #define FROMDOMAIN_INVALID           "anonymous.invalid"
00248 
00249 #define DEFAULT_MAXMS                2000             /*!< Qualification: Must be faster than 2 seconds by default */
00250 #define DEFAULT_QUALIFYFREQ          60 * 1000        /*!< Qualification: How often to check for the host to be up */
00251 #define DEFAULT_FREQ_NOTOK           10 * 1000        /*!< Qualification: How often to check, if the host is down... */
00252 
00253 #define DEFAULT_RETRANS              1000             /*!< How frequently to retransmit Default: 2 * 500 ms in RFC 3261 */
00254 #define MAX_RETRANS                  6                /*!< Try only 6 times for retransmissions, a total of 7 transmissions */
00255 #define SIP_TIMER_T1                 500              /* SIP timer T1 (according to RFC 3261) */
00256 #define SIP_TRANS_TIMEOUT            64 * SIP_TIMER_T1/*!< SIP request timeout (rfc 3261) 64*T1 
00257                                                       \todo Use known T1 for timeout (peerpoke)
00258                                                       */
00259 #define DEFAULT_TRANS_TIMEOUT        -1               /* Use default SIP transaction timeout */
00260 #define PROVIS_KEEPALIVE_TIMEOUT     60000            /*!< How long to wait before retransmitting a provisional response (rfc 3261 13.3.1.1) */
00261 #define MAX_AUTHTRIES                3                /*!< Try authentication three times, then fail */
00262 
00263 #define SIP_MAX_HEADERS              64               /*!< Max amount of SIP headers to read */
00264 #define SIP_MAX_LINES                64               /*!< Max amount of lines in SIP attachment (like SDP) */
00265 #define SIP_MAX_PACKET               4096             /*!< Also from RFC 3261 (2543), should sub headers tho */
00266 #define SIP_MIN_PACKET               1024             /*!< Initialize size of memory to allocate for packets */
00267 
00268 #define INITIAL_CSEQ                 101              /*!< our initial sip sequence number */
00269 
00270 #define DEFAULT_MAX_SE               1800             /*!< Session-Timer Default Session-Expires period (RFC 4028) */
00271 #define DEFAULT_MIN_SE               90               /*!< Session-Timer Default Min-SE period (RFC 4028) */
00272 
00273 #define SDP_MAX_RTPMAP_CODECS        32               /*!< Maximum number of codecs allowed in received SDP */
00274 
00275 /*! \brief Global jitterbuffer configuration - by default, jb is disabled */
00276 static struct ast_jb_conf default_jbconf =
00277 {
00278    .flags = 0,
00279    .max_size = -1,
00280    .resync_threshold = -1,
00281    .impl = ""
00282 };
00283 static struct ast_jb_conf global_jbconf;  /*!< Global jitterbuffer configuration */
00284 
00285 static const char config[] = "sip.conf";  /*!< Main configuration file */
00286 static const char notify_config[] = "sip_notify.conf";   /*!< Configuration file for sending Notify with CLI commands to reconfigure or reboot phones */
00287 
00288 #define RTP    1
00289 #define NO_RTP 0
00290 
00291 /*! \brief Authorization scheme for call transfers 
00292 \note Not a bitfield flag, since there are plans for other modes,
00293    like "only allow transfers for authenticated devices" */
00294 enum transfermodes {
00295    TRANSFER_OPENFORALL,            /*!< Allow all SIP transfers */
00296    TRANSFER_CLOSED,                /*!< Allow no SIP transfers */
00297 };
00298 
00299 
00300 /*! \brief The result of a lot of functions */
00301 enum sip_result {
00302    AST_SUCCESS = 0,     /*! FALSE means success, funny enough */
00303    AST_FAILURE = -1,    
00304 };
00305 
00306 /*! \brief States for the INVITE transaction, not the dialog 
00307    \note this is for the INVITE that sets up the dialog
00308 */
00309 enum invitestates {
00310    INV_NONE = 0,          /*!< No state at all, maybe not an INVITE dialog */
00311    INV_CALLING = 1,  /*!< Invite sent, no answer */
00312    INV_PROCEEDING = 2,  /*!< We got/sent 1xx message */
00313    INV_EARLY_MEDIA = 3,    /*!< We got 18x message with to-tag back */
00314    INV_COMPLETED = 4,   /*!< Got final response with error. Wait for ACK, then CONFIRMED */
00315    INV_CONFIRMED = 5,   /*!< Confirmed response - we've got an ack (Incoming calls only) */
00316    INV_TERMINATED = 6,  /*!< Transaction done - either successful (AST_STATE_UP) or failed, but done 
00317                  The only way out of this is a BYE from one side */
00318    INV_CANCELLED = 7,   /*!< Transaction cancelled by client or server in non-terminated state */
00319 };
00320 
00321 /*! \brief Readable descriptions of device states.
00322        \note Should be aligned to above table as index */
00323 static const struct invstate2stringtable {
00324    const enum invitestates state;
00325    const char *desc;
00326 } invitestate2string[] = {
00327    {INV_NONE,              "None"  },
00328    {INV_CALLING,           "Calling (Trying)"},
00329    {INV_PROCEEDING,        "Proceeding "},
00330    {INV_EARLY_MEDIA,       "Early media"},
00331    {INV_COMPLETED,         "Completed (done)"},
00332    {INV_CONFIRMED,         "Confirmed (up)"},
00333    {INV_TERMINATED,        "Done"},
00334    {INV_CANCELLED,         "Cancelled"}
00335 };
00336 
00337 /*! \brief When sending a SIP message, we can send with a few options, depending on
00338    type of SIP request. UNRELIABLE is moslty used for responses to repeated requests,
00339    where the original response would be sent RELIABLE in an INVITE transaction */
00340 enum xmittype {
00341    XMIT_CRITICAL = 2,              /*!< Transmit critical SIP message reliably, with re-transmits.
00342                                               If it fails, it's critical and will cause a teardown of the session */
00343    XMIT_RELIABLE = 1,              /*!< Transmit SIP message reliably, with re-transmits */
00344    XMIT_UNRELIABLE = 0,            /*!< Transmit SIP message without bothering with re-transmits */
00345 };
00346 
00347 enum parse_register_result {
00348    PARSE_REGISTER_DENIED,
00349    PARSE_REGISTER_FAILED,
00350    PARSE_REGISTER_UPDATE,
00351    PARSE_REGISTER_QUERY,
00352 };
00353 
00354 /*! \brief Type of subscription, based on the packages we do support */
00355 enum subscriptiontype { 
00356    NONE = 0,
00357    XPIDF_XML,
00358    DIALOG_INFO_XML,
00359    CPIM_PIDF_XML,
00360    PIDF_XML,
00361    MWI_NOTIFICATION
00362 };
00363 
00364 /*! \brief Subscription types that we support. We support
00365    - dialoginfo updates (really device status, not dialog info as was the original intent of the standard)
00366    - SIMPLE presence used for device status
00367    - Voicemail notification subscriptions
00368 */
00369 static const struct cfsubscription_types {
00370    enum subscriptiontype type;
00371    const char * const event;
00372    const char * const mediatype;
00373    const char * const text;
00374 } subscription_types[] = {
00375    { NONE,        "-",        "unknown",               "unknown" },
00376    /* RFC 4235: SIP Dialog event package */
00377    { DIALOG_INFO_XML, "dialog",   "application/dialog-info+xml", "dialog-info+xml" },
00378    { CPIM_PIDF_XML,   "presence", "application/cpim-pidf+xml",   "cpim-pidf+xml" },  /* RFC 3863 */
00379    { PIDF_XML,        "presence", "application/pidf+xml",        "pidf+xml" },       /* RFC 3863 */
00380    { XPIDF_XML,       "presence", "application/xpidf+xml",       "xpidf+xml" },       /* Pre-RFC 3863 with MS additions */
00381    { MWI_NOTIFICATION,  "message-summary", "application/simple-message-summary", "mwi" } /* RFC 3842: Mailbox notification */
00382 };
00383 
00384 
00385 /*! \brief Authentication types - proxy or www authentication 
00386    \note Endpoints, like Asterisk, should always use WWW authentication to
00387    allow multiple authentications in the same call - to the proxy and
00388    to the end point.
00389 */
00390 enum sip_auth_type {
00391    PROXY_AUTH = 407,
00392    WWW_AUTH = 401,
00393 };
00394 
00395 /*! \brief Authentication result from check_auth* functions */
00396 enum check_auth_result {
00397    AUTH_DONT_KNOW = -100,  /*!< no result, need to check further */
00398       /* XXX maybe this is the same as AUTH_NOT_FOUND */
00399 
00400    AUTH_SUCCESSFUL = 0,
00401    AUTH_CHALLENGE_SENT = 1,
00402    AUTH_SECRET_FAILED = -1,
00403    AUTH_USERNAME_MISMATCH = -2,
00404    AUTH_NOT_FOUND = -3, /*!< returned by register_verify */
00405    AUTH_FAKE_AUTH = -4,
00406    AUTH_UNKNOWN_DOMAIN = -5,
00407    AUTH_PEER_NOT_DYNAMIC = -6,
00408    AUTH_ACL_FAILED = -7,
00409    AUTH_BAD_TRANSPORT = -8,
00410 };
00411 
00412 /*! \brief States for outbound registrations (with register= lines in sip.conf */
00413 enum sipregistrystate {
00414    REG_STATE_UNREGISTERED = 0,   /*!< We are not registered 
00415        *  \note Initial state. We should have a timeout scheduled for the initial
00416        * (or next) registration transmission, calling sip_reregister
00417        */
00418 
00419    REG_STATE_REGSENT,   /*!< Registration request sent 
00420        * \note sent initial request, waiting for an ack or a timeout to
00421        * retransmit the initial request.
00422       */
00423 
00424    REG_STATE_AUTHSENT,  /*!< We have tried to authenticate 
00425        * \note entered after transmit_register with auth info,
00426        * waiting for an ack.
00427        */
00428 
00429    REG_STATE_REGISTERED,   /*!< Registered and done */
00430 
00431    REG_STATE_REJECTED,  /*!< Registration rejected *
00432        * \note only used when the remote party has an expire larger than
00433        * our max-expire. This is a final state from which we do not
00434        * recover (not sure how correctly).
00435        */
00436 
00437    REG_STATE_TIMEOUT,   /*!< Registration timed out *
00438       * \note XXX unused */
00439 
00440    REG_STATE_NOAUTH, /*!< We have no accepted credentials
00441        * \note fatal - no chance to proceed */
00442 
00443    REG_STATE_FAILED, /*!< Registration failed after several tries
00444        * \note fatal - no chance to proceed */
00445 };
00446 
00447 /*! \brief Modes in which Asterisk can be configured to run SIP Session-Timers */
00448 enum st_mode {
00449         SESSION_TIMER_MODE_INVALID = 0, /*!< Invalid value */ 
00450         SESSION_TIMER_MODE_ACCEPT,      /*!< Honor inbound Session-Timer requests */
00451         SESSION_TIMER_MODE_ORIGINATE,   /*!< Originate outbound and honor inbound requests */
00452         SESSION_TIMER_MODE_REFUSE       /*!< Ignore inbound Session-Timers requests */
00453 };
00454 
00455 /*! \brief The entity playing the refresher role for Session-Timers */
00456 enum st_refresher {
00457         SESSION_TIMER_REFRESHER_AUTO,    /*!< Negotiated                      */
00458         SESSION_TIMER_REFRESHER_UAC,     /*!< Session is refreshed by the UAC */
00459         SESSION_TIMER_REFRESHER_UAS      /*!< Session is refreshed by the UAS */
00460 };
00461 
00462 /*! \brief Define some implemented SIP transports 
00463    \note Asterisk does not support SCTP or UDP/DTLS 
00464 */
00465 enum sip_transport {
00466    SIP_TRANSPORT_UDP = 1,     /*!< Unreliable transport for SIP, needs retransmissions */
00467    SIP_TRANSPORT_TCP = 1 << 1,   /*!< Reliable, but unsecure */
00468    SIP_TRANSPORT_TLS = 1 << 2,   /*!< TCP/TLS - reliable and secure transport for signalling */
00469 };
00470 
00471 /*! \brief definition of a sip proxy server
00472  *
00473  * For outbound proxies, this is allocated in the SIP peer dynamically or
00474  * statically as the global_outboundproxy. The pointer in a SIP message is just
00475  * a pointer and should *not* be de-allocated.
00476  */
00477 struct sip_proxy {
00478    char name[MAXHOSTNAMELEN];      /*!< DNS name of domain/host or IP */
00479    struct sockaddr_in ip;          /*!< Currently used IP address and port */
00480    time_t last_dnsupdate;          /*!< When this was resolved */
00481    enum sip_transport transport;
00482    int force;                      /*!< If it's an outbound proxy, Force use of this outbound proxy for all outbound requests */
00483    /* Room for a SRV record chain based on the name */
00484 };
00485 
00486 /*! \brief argument for the 'show channels|subscriptions' callback. */
00487 struct __show_chan_arg { 
00488    int fd;
00489    int subscriptions;
00490    int numchans;   /* return value */
00491 };
00492 
00493 
00494 /*! \brief States whether a SIP message can create a dialog in Asterisk. */
00495 enum can_create_dialog {
00496    CAN_NOT_CREATE_DIALOG,
00497    CAN_CREATE_DIALOG,
00498    CAN_CREATE_DIALOG_UNSUPPORTED_METHOD,
00499 };
00500 
00501 /*! \brief SIP Request methods known by Asterisk 
00502 
00503    \note Do _NOT_ make any changes to this enum, or the array following it;
00504    if you think you are doing the right thing, you are probably
00505    not doing the right thing. If you think there are changes
00506    needed, get someone else to review them first _before_
00507    submitting a patch. If these two lists do not match properly
00508    bad things will happen.
00509 */
00510 
00511 enum sipmethod {
00512    SIP_UNKNOWN,      /*!< Unknown response */
00513    SIP_RESPONSE,     /*!< Not request, response to outbound request */
00514    SIP_REGISTER,     /*!< Registration to the mothership, tell us where you are located */
00515    SIP_OPTIONS,      /*!< Check capabilities of a device, used for "ping" too */
00516    SIP_NOTIFY,    /*!< Status update, Part of the event package standard, result of a SUBSCRIBE or a REFER */
00517    SIP_INVITE,    /*!< Set up a session */
00518    SIP_ACK,    /*!< End of a three-way handshake started with INVITE. */
00519    SIP_PRACK,     /*!< Reliable pre-call signalling. Not supported in Asterisk. */
00520    SIP_BYE,    /*!< End of a session */
00521    SIP_REFER,     /*!< Refer to another URI (transfer) */
00522    SIP_SUBSCRIBE,    /*!< Subscribe for updates (voicemail, session status, device status, presence) */
00523    SIP_MESSAGE,      /*!< Text messaging */
00524    SIP_UPDATE,    /*!< Update a dialog. We can send UPDATE; but not accept it */
00525    SIP_INFO,      /*!< Information updates during a session */
00526    SIP_CANCEL,    /*!< Cancel an INVITE */
00527    SIP_PUBLISH,      /*!< Not supported in Asterisk */
00528    SIP_PING,      /*!< Not supported at all, no standard but still implemented out there */
00529 };
00530 
00531 /*! \brief The core structure to setup dialogs. We parse incoming messages by using
00532    structure and then route the messages according to the type.
00533 
00534       \note Note that sip_methods[i].id == i must hold or the code breaks */
00535 static const struct  cfsip_methods { 
00536    enum sipmethod id;
00537    int need_rtp;     /*!< when this is the 'primary' use for a pvt structure, does it need RTP? */
00538    char * const text;
00539    enum can_create_dialog can_create;
00540 } sip_methods[] = {
00541    { SIP_UNKNOWN,  RTP,    "-UNKNOWN-",   CAN_CREATE_DIALOG },
00542    { SIP_RESPONSE,    NO_RTP, "SIP/2.0",  CAN_NOT_CREATE_DIALOG },
00543    { SIP_REGISTER,    NO_RTP, "REGISTER",    CAN_CREATE_DIALOG },
00544    { SIP_OPTIONS,  NO_RTP, "OPTIONS",  CAN_CREATE_DIALOG },
00545    { SIP_NOTIFY,   NO_RTP, "NOTIFY",   CAN_CREATE_DIALOG },
00546    { SIP_INVITE,   RTP,    "INVITE",   CAN_CREATE_DIALOG },
00547    { SIP_ACK,   NO_RTP, "ACK",   CAN_NOT_CREATE_DIALOG },
00548    { SIP_PRACK,    NO_RTP, "PRACK",    CAN_NOT_CREATE_DIALOG },
00549    { SIP_BYE,   NO_RTP, "BYE",   CAN_NOT_CREATE_DIALOG },
00550    { SIP_REFER,    NO_RTP, "REFER",    CAN_CREATE_DIALOG },
00551    { SIP_SUBSCRIBE, NO_RTP, "SUBSCRIBE",  CAN_CREATE_DIALOG },
00552    { SIP_MESSAGE,  NO_RTP, "MESSAGE",  CAN_CREATE_DIALOG },
00553    { SIP_UPDATE,   NO_RTP, "UPDATE",   CAN_NOT_CREATE_DIALOG },
00554    { SIP_INFO,  NO_RTP, "INFO",  CAN_NOT_CREATE_DIALOG },
00555    { SIP_CANCEL,   NO_RTP, "CANCEL",   CAN_NOT_CREATE_DIALOG },
00556    { SIP_PUBLISH,  NO_RTP, "PUBLISH",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD },
00557    { SIP_PING,  NO_RTP, "PING",  CAN_CREATE_DIALOG_UNSUPPORTED_METHOD }
00558 };
00559 
00560 static unsigned int chan_idx;
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_prematuremediafilter;   /*!< Enable/disable premature frames in a call (causing 183 early media) */
00765 static int global_relaxdtmf;        /*!< Relax DTMF */
00766 static int global_rtptimeout;    /*!< Time out call if no RTP */
00767 static int global_rtpholdtimeout;   /*!< Time out call if no RTP during hold */
00768 static int global_rtpkeepalive;     /*!< Send RTP keepalives */
00769 static int global_reg_timeout;   
00770 static int global_regattempts_max;  /*!< Registration attempts before giving up */
00771 static int global_shrinkcallerid;   /*!< enable or disable shrinking of caller id  */
00772 static int global_allowguest;    /*!< allow unauthenticated peers to connect? */
00773 static int global_callcounter;      /*!< Enable call counters for all devices. This is currently enabled by setting the peer
00774                   call-limit to 999. When we remove the call-limit from the code, we can make it
00775                   with just a boolean flag in the device structure */
00776 static int global_allowsubscribe;   /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
00777                    the global setting is in globals_flags[1] */
00778 static unsigned int global_tos_sip;    /*!< IP type of service for SIP packets */
00779 static unsigned int global_tos_audio;     /*!< IP type of service for audio RTP packets */
00780 static unsigned int global_tos_video;     /*!< IP type of service for video RTP packets */
00781 static unsigned int global_tos_text;      /*!< IP type of service for text RTP packets */
00782 static unsigned int global_cos_sip;    /*!< 802.1p class of service for SIP packets */
00783 static unsigned int global_cos_audio;     /*!< 802.1p class of service for audio RTP packets */
00784 static unsigned int global_cos_video;     /*!< 802.1p class of service for video RTP packets */
00785 static unsigned int global_cos_text;      /*!< 802.1p class of service for text RTP packets */
00786 static int compactheaders;    /*!< send compact sip headers */
00787 static int recordhistory;     /*!< Record SIP history. Off by default */
00788 static int dumphistory;       /*!< Dump history to verbose before destroying SIP dialog */
00789 static char global_realm[MAXHOSTNAMELEN];       /*!< Default realm */
00790 static char global_regcontext[AST_MAX_CONTEXT];    /*!< Context for auto-extensions */
00791 static char global_useragent[AST_MAX_EXTENSION];   /*!< Useragent for the SIP channel */
00792 static char global_sdpsession[AST_MAX_EXTENSION];  /*!< SDP session name for the SIP channel */
00793 static char global_sdpowner[AST_MAX_EXTENSION]; /*!< SDP owner name for the SIP channel */
00794 static int allow_external_domains;  /*!< Accept calls to external SIP domains? */
00795 static int global_callevents;    /*!< Whether we send manager events or not */
00796 static int global_authfailureevents;      /*!< Whether we send authentication failure manager events or not. Default no. */
00797 static int global_t1;         /*!< T1 time */
00798 static int global_t1min;      /*!< T1 roundtrip time minimum */
00799 static int global_timer_b;             /*!< Timer B - RFC 3261 Section 17.1.1.2 */
00800 static int global_regextenonqualify;      /*!< Whether to add/remove regexten when qualifying peers */
00801 static int global_autoframing;            /*!< Turn autoframing on or off. */
00802 static enum transfermodes global_allowtransfer; /*!< SIP Refer restriction scheme */
00803 static struct sip_proxy global_outboundproxy;   /*!< Outbound proxy */
00804 static int global_matchexterniplocally;      /*!< Match externip/externhost setting against localnet setting */
00805 static int global_qualifyfreq;         /*!< Qualify frequency */
00806 
00807 
00808 /*! \brief Codecs that we support by default: */
00809 static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
00810 
00811 static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
00812 static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
00813 static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
00814 static int global_max_se;                     /*!< Highest threshold for session refresh interval */
00815 
00816 static int global_dynamic_exclude_static = 0;   /*!< Exclude static peers from contact registrations */
00817 /*@}*/
00818 
00819 /*! \brief Global list of addresses dynamic peers are not allowed to use */
00820 static struct ast_ha *global_contact_ha = NULL;
00821 
00822 /*! \name Object counters @{
00823  * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
00824  * should be used to modify these values. */
00825 static int speerobjs = 0;                /*!< Static peers */
00826 static int rpeerobjs = 0;                /*!< Realtime peers */
00827 static int apeerobjs = 0;                /*!< Autocreated peer objects */
00828 static int regobjs = 0;                  /*!< Registry objects */
00829 /* }@ */
00830 
00831 static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
00832 static int global_t38_maxdatagram;        /*!< global T.38 FaxMaxDatagram override */
00833 
00834 static char used_context[AST_MAX_CONTEXT];      /*!< name of automatically created context for unloading */
00835 
00836 
00837 AST_MUTEX_DEFINE_STATIC(netlock);
00838 
00839 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
00840    when it's doing something critical. */
00841 AST_MUTEX_DEFINE_STATIC(monlock);
00842 
00843 AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
00844 
00845 /*! \brief This is the thread for the monitor which checks for input on the channels
00846    which are not currently in use.  */
00847 static pthread_t monitor_thread = AST_PTHREADT_NULL;
00848 
00849 static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
00850 static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
00851 
00852 static struct sched_context *sched;     /*!< The scheduling context */
00853 static struct io_context *io;           /*!< The IO context */
00854 static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
00855 
00856 #define DEC_CALL_LIMIT  0
00857 #define INC_CALL_LIMIT  1
00858 #define DEC_CALL_RINGING 2
00859 #define INC_CALL_RINGING 3
00860 
00861 /*! \brief The SIP socket definition */
00862 struct sip_socket {
00863    enum sip_transport type;   /*!< UDP, TCP or TLS */
00864    int fd;           /*!< Filed descriptor, the actual socket */
00865    uint16_t port;
00866    struct ast_tcptls_session_instance *tcptls_session;   /* If tcp or tls, a socket manager */
00867 };
00868 
00869 /*! \brief sip_request: The data grabbed from the UDP socket
00870  *
00871  * \verbatim
00872  * Incoming messages: we first store the data from the socket in data[],
00873  * adding a trailing \0 to make string parsing routines happy.
00874  * Then call parse_request() and req.method = find_sip_method();
00875  * to initialize the other fields. The \r\n at the end of each line is   
00876  * replaced by \0, so that data[] is not a conforming SIP message anymore.
00877  * After this processing, rlPart1 is set to non-NULL to remember
00878  * that we can run get_header() on this kind of packet.
00879  *
00880  * parse_request() splits the first line as follows:
00881  * Requests have in the first line      method uri SIP/2.0
00882  *      rlPart1 = method; rlPart2 = uri;
00883  * Responses have in the first line     SIP/2.0 NNN description
00884  *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
00885  *
00886  * For outgoing packets, we initialize the fields with init_req() or init_resp()
00887  * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
00888  * and then fill the rest with add_header() and add_line().
00889  * The \r\n at the end of the line are still there, so the get_header()
00890  * and similar functions don't work on these packets. 
00891  * \endverbatim
00892  */
00893 struct sip_request {
00894    ptrdiff_t rlPart1;           /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
00895    ptrdiff_t rlPart2;           /*!< Offset of the Request URI or Response Status */
00896    int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
00897    int headers;            /*!< # of SIP Headers */
00898    int method;             /*!< Method of this request */
00899    int lines;              /*!< Body Content */
00900    unsigned int sdp_start; /*!< the line number where the SDP begins */
00901    unsigned int sdp_count; /*!< the number of lines of SDP */
00902    char debug;    /*!< print extra debugging if non zero */
00903    char has_to_tag;  /*!< non-zero if packet has To: tag */
00904    char ignore;      /*!< if non-zero This is a re-transmit, ignore it */
00905    /* Array of offsets into the request string of each SIP header*/
00906    ptrdiff_t header[SIP_MAX_HEADERS];
00907    /* Array of offsets into the request string of each SDP line*/
00908    ptrdiff_t line[SIP_MAX_LINES];
00909    struct ast_str *data;   
00910    /* XXX Do we need to unref socket.ser when the request goes away? */
00911    struct sip_socket socket;  /*!< The socket used for this request */
00912    AST_LIST_ENTRY(sip_request) next;
00913 };
00914 
00915 /* \brief given a sip_request and an offset, return the char * that resides there
00916  *
00917  * It used to be that rlPart1, rlPart2, and the header and line arrays were character
00918  * pointers. They are now offsets into the ast_str portion of the sip_request structure.
00919  * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
00920  * provided to retrieve the string at a particular offset within the request's buffer
00921  */
00922 #define REQ_OFFSET_TO_STR(req,offset) ((req)->data->str + ((req)->offset))
00923 
00924 /*! \brief structure used in transfers */
00925 struct sip_dual {
00926    struct ast_channel *chan1; /*!< First channel involved */
00927    struct ast_channel *chan2; /*!< Second channel involved */
00928    struct sip_request req;    /*!< Request that caused the transfer (REFER) */
00929    int seqno;        /*!< Sequence number */
00930 };
00931 
00932 struct sip_pkt;
00933 
00934 /*! \brief Parameters to the transmit_invite function */
00935 struct sip_invite_param {
00936    int addsipheaders;      /*!< Add extra SIP headers */
00937    const char *uri_options;   /*!< URI options to add to the URI */
00938    const char *vxml_url;      /*!< VXML url for Cisco phones */
00939    char *auth;       /*!< Authentication */
00940    char *authheader;    /*!< Auth header */
00941    enum sip_auth_type auth_type; /*!< Authentication type */
00942    const char *replaces;      /*!< Replaces header for call transfers */
00943    int transfer;        /*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
00944 };
00945 
00946 /*! \brief Structure to save routing information for a SIP session */
00947 struct sip_route {
00948    struct sip_route *next;
00949    char hop[0];
00950 };
00951 
00952 /*! \brief Modes for SIP domain handling in the PBX */
00953 enum domain_mode {
00954    SIP_DOMAIN_AUTO,     /*!< This domain is auto-configured */
00955    SIP_DOMAIN_CONFIG,      /*!< This domain is from configuration */
00956 };
00957 
00958 /*! \brief Domain data structure. 
00959    \note In the future, we will connect this to a configuration tree specific
00960    for this domain
00961 */
00962 struct domain {
00963    char domain[MAXHOSTNAMELEN];     /*!< SIP domain we are responsible for */
00964    char context[AST_MAX_EXTENSION]; /*!< Incoming context for this domain */
00965    enum domain_mode mode;        /*!< How did we find this domain? */
00966    AST_LIST_ENTRY(domain) list;     /*!< List mechanics */
00967 };
00968 
00969 static AST_LIST_HEAD_STATIC(domain_list, domain);  /*!< The SIP domain list */
00970 
00971 
00972 /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
00973 struct sip_history {
00974    AST_LIST_ENTRY(sip_history) list;
00975    char event[0]; /* actually more, depending on needs */
00976 };
00977 
00978 AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
00979 
00980 /*! \brief sip_auth: Credentials for authentication to other SIP services */
00981 struct sip_auth {
00982    char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
00983    char username[256];             /*!< Username */
00984    char secret[256];               /*!< Secret */
00985    char md5secret[256];            /*!< MD5Secret */
00986    struct sip_auth *next;          /*!< Next auth structure in list */
00987 };
00988 
00989 /*! \name SIPflags
00990    Various flags for the flags field in the pvt structure 
00991    Trying to sort these up (one or more of the following):
00992    D: Dialog
00993    P: Peer/user
00994    G: Global flag
00995    When flags are used by multiple structures, it is important that
00996    they have a common layout so it is easy to copy them.
00997 */
00998 /*@{*/ 
00999 #define SIP_OUTGOING    (1 << 0) /*!< D: Direction of the last transaction in this dialog */
01000 #define SIP_RINGING     (1 << 2) /*!< D: Have sent 180 ringing */
01001 #define SIP_PROGRESS_SENT  (1 << 3) /*!< D: Have sent 183 message progress */
01002 #define SIP_NEEDREINVITE   (1 << 4) /*!< D: Do we need to send another reinvite? */
01003 #define SIP_PENDINGBYE     (1 << 5) /*!< D: Need to send bye after we ack? */
01004 #define SIP_GOTREFER    (1 << 6) /*!< D: Got a refer? */
01005 #define SIP_CALL_LIMIT     (1 << 7) /*!< D: Call limit enforced for this call */
01006 #define SIP_INC_COUNT      (1 << 8) /*!< D: Did this dialog increment the counter of in-use calls? */
01007 #define SIP_INC_RINGING    (1 << 9) /*!< D: Did this connection increment the counter of in-use calls? */
01008 #define SIP_DEFER_BYE_ON_TRANSFER   (1 << 10)   /*!< D: Do not hangup at first ast_hangup */
01009 
01010 #define SIP_PROMISCREDIR   (1 << 11)   /*!< DP: Promiscuous redirection */
01011 #define SIP_TRUSTRPID      (1 << 12)   /*!< DP: Trust RPID headers? */
01012 #define SIP_USEREQPHONE    (1 << 13)   /*!< DP: Add user=phone to numeric URI. Default off */
01013 #define SIP_USECLIENTCODE  (1 << 14)   /*!< DP: Trust X-ClientCode info message */
01014 
01015 /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
01016 #define SIP_DTMF     (7 << 15)   /*!< DP: DTMF Support: five settings, uses three bits */
01017 #define SIP_DTMF_RFC2833   (0 << 15)   /*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
01018 #define SIP_DTMF_INBAND    (1 << 15)   /*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
01019 #define SIP_DTMF_INFO      (2 << 15)   /*!< DP: DTMF Support: SIP Info messages - "info" */
01020 #define SIP_DTMF_AUTO      (3 << 15)   /*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
01021 #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
01022 
01023 /* NAT settings - see nat2str() */
01024 #define SIP_NAT         (3 << 18)   /*!< DP: four settings, uses two bits */
01025 #define SIP_NAT_NEVER      (0 << 18)   /*!< DP: No nat support */
01026 #define SIP_NAT_RFC3581    (1 << 18)   /*!< DP: NAT RFC3581 */
01027 #define SIP_NAT_ROUTE      (2 << 18)   /*!< DP: NAT Only ROUTE */
01028 #define SIP_NAT_ALWAYS     (3 << 18)   /*!< DP: NAT Both ROUTE and RFC3581 */
01029 
01030 /* re-INVITE related settings */
01031 #define SIP_REINVITE    (7 << 20)   /*!< DP: four settings, uses three bits */
01032 #define SIP_REINVITE_NONE  (0 << 20)   /*!< DP: no reinvite allowed */
01033 #define SIP_CAN_REINVITE   (1 << 20)   /*!< DP: allow peers to be reinvited to send media directly p2p */
01034 #define SIP_CAN_REINVITE_NAT  (2 << 20)   /*!< DP: allow media reinvite when new peer is behind NAT */
01035 #define SIP_REINVITE_UPDATE   (4 << 20)   /*!< DP: use UPDATE (RFC3311) when reinviting this peer */
01036 
01037 /* "insecure" settings - see insecure2str() */
01038 #define SIP_INSECURE    (3 << 23)   /*!< DP: three settings, uses two bits */
01039 #define SIP_INSECURE_NONE  (0 << 23)   /*!< DP: secure mode */
01040 #define SIP_INSECURE_PORT  (1 << 23)   /*!< DP: don't require matching port for incoming requests */
01041 #define SIP_INSECURE_INVITE   (1 << 24)   /*!< DP: don't require authentication for incoming INVITEs */
01042 
01043 /* Sending PROGRESS in-band settings */
01044 #define SIP_PROG_INBAND    (3 << 25)   /*!< DP: three settings, uses two bits */
01045 #define SIP_PROG_INBAND_NEVER (0 << 25)
01046 #define SIP_PROG_INBAND_NO (1 << 25)
01047 #define SIP_PROG_INBAND_YES   (2 << 25)
01048 
01049 #define SIP_SENDRPID    (1 << 29)   /*!< DP: Remote Party-ID Support */
01050 #define SIP_G726_NONSTANDARD  (1 << 31)   /*!< DP: Use non-standard packing for G726-32 data */
01051 
01052 /*! \brief Flags to copy from peer/user to dialog */
01053 #define SIP_FLAGS_TO_COPY \
01054    (SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
01055     SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT | SIP_G726_NONSTANDARD | \
01056     SIP_USEREQPHONE | SIP_INSECURE)
01057 /*@}*/ 
01058 
01059 /*! \name SIPflags2
01060    a second page of flags (for flags[1] */
01061 /*@{*/ 
01062 /* realtime flags */
01063 #define SIP_PAGE2_RTCACHEFRIENDS (1 << 0) /*!< GP: Should we keep RT objects in memory for extended time? */
01064 #define SIP_PAGE2_RTAUTOCLEAR    (1 << 2) /*!< GP: Should we clean memory from peers after expiry? */
01065 /* Space for addition of other realtime flags in the future */
01066 #define SIP_PAGE2_CONSTANT_SSRC     (1 << 8) /*!< GDP: Don't change SSRC on reinvite */
01067 #define SIP_PAGE2_STATECHANGEQUEUE  (1 << 9) /*!< D: Unsent state pending change exists */
01068 
01069 #define SIP_PAGE2_RPORT_PRESENT         (1 << 10)       /*!< Was rport received in the Via header? */
01070 #define SIP_PAGE2_VIDEOSUPPORT      (1 << 14)   /*!< DP: Video supported if offered? */
01071 #define SIP_PAGE2_TEXTSUPPORT    (1 << 15)   /*!< GDP: Global text enable */
01072 #define SIP_PAGE2_ALLOWSUBSCRIBE (1 << 16)   /*!< GP: Allow subscriptions from this peer? */
01073 #define SIP_PAGE2_ALLOWOVERLAP      (1 << 17)   /*!< DP: Allow overlap dialing ? */
01074 #define SIP_PAGE2_SUBSCRIBEMWIONLY  (1 << 18)   /*!< GP: Only issue MWI notification if subscribed to */
01075 #define SIP_PAGE2_IGNORESDPVERSION  (1 << 19)   /*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
01076 
01077 #define SIP_PAGE2_T38SUPPORT             (3 << 20) /*!< GDP: T.38 Fax Support */
01078 #define SIP_PAGE2_T38SUPPORT_UDPTL          (1 << 20) /*!< GDP: T.38 Fax Support (no error correction) */
01079 #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC         (2 << 20) /*!< GDP: T.38 Fax Support (FEC error correction) */
01080 #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY   (3 << 20)   /*!< GDP: T.38 Fax Support (redundancy error correction) */
01081 
01082 #define SIP_PAGE2_CALL_ONHOLD    (3 << 23)   /*!< D: Call hold states: */
01083 #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
01084 #define SIP_PAGE2_CALL_ONHOLD_ONEDIR   (2 << 23)   /*!< D: One directional hold */
01085 #define SIP_PAGE2_CALL_ONHOLD_INACTIVE (3 << 23)   /*!< D: Inactive hold */
01086 
01087 #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)  /*!< DP: Compensate for buggy RFC2833 implementations */
01088 #define SIP_PAGE2_BUGGY_MWI      (1 << 26)   /*!< DP: Buggy CISCO MWI fix */
01089 #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
01090 #define SIP_PAGE2_FAX_DETECT     (1 << 28)      /*!< DP: Fax Detection support */
01091 #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
01092 #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
01093 #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS  (1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
01094 
01095 #define SIP_PAGE2_FLAGS_TO_COPY \
01096    (SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
01097    SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
01098    SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | \
01099    SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_CONSTANT_SSRC | SIP_PAGE2_FAX_DETECT)
01100 
01101 /*@}*/ 
01102 
01103 /*! \brief debugging state
01104  * We store separately the debugging requests from the config file
01105  * and requests from the CLI. Debugging is enabled if either is set
01106  * (which means that if sipdebug is set in the config file, we can
01107  * only turn it off by reloading the config).
01108  */
01109 enum sip_debug_e {
01110    sip_debug_none = 0,
01111    sip_debug_config = 1,
01112    sip_debug_console = 2,
01113 };
01114 
01115 static enum sip_debug_e sipdebug;
01116 
01117 /*! \brief extra debugging for 'text' related events.
01118  * At the moment this is set together with sip_debug_console.
01119  * \note It should either go away or be implemented properly.
01120  */
01121 static int sipdebug_text;
01122 
01123 /*! \brief T38 States for a call */
01124 enum t38state {
01125    T38_DISABLED = 0,                /*!< Not enabled */
01126    T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
01127    T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
01128    T38_ENABLED                      /*!< Negotiated (enabled) */
01129 };
01130 
01131 /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
01132 struct t38properties {
01133    enum t38state state;    /*!< T.38 state */
01134    struct ast_control_t38_parameters our_parms;
01135    struct ast_control_t38_parameters their_parms;
01136 };
01137 
01138 /*! \brief Parameters to know status of transfer */
01139 enum referstatus {
01140    REFER_IDLE,                    /*!< No REFER is in progress */
01141    REFER_SENT,                    /*!< Sent REFER to transferee */
01142    REFER_RECEIVED,                /*!< Received REFER from transferrer */
01143    REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
01144    REFER_ACCEPTED,                /*!< Accepted by transferee */
01145    REFER_RINGING,                 /*!< Target Ringing */
01146    REFER_200OK,                   /*!< Answered by transfer target */
01147    REFER_FAILED,                  /*!< REFER declined - go on */
01148    REFER_NOAUTH                   /*!< We had no auth for REFER */
01149 };
01150 
01151 /*! \brief generic struct to map between strings and integers.
01152  * Fill it with x-s pairs, terminate with an entry with s = NULL;
01153  * Then you can call map_x_s(...) to map an integer to a string,
01154  * and map_s_x() for the string -> integer mapping.
01155  */
01156 struct _map_x_s {
01157    int x;
01158    const char *s;
01159 };              
01160 
01161 static const struct _map_x_s referstatusstrings[] = {
01162    { REFER_IDLE,     "<none>" },
01163    { REFER_SENT,     "Request sent" },
01164    { REFER_RECEIVED, "Request received" },
01165    { REFER_CONFIRMED,   "Confirmed" },
01166    { REFER_ACCEPTED, "Accepted" },
01167    { REFER_RINGING,  "Target ringing" },
01168    { REFER_200OK,    "Done" },
01169    { REFER_FAILED,      "Failed" },
01170    { REFER_NOAUTH,      "Failed - auth failure" },
01171    { -1,       NULL} /* terminator */
01172 };
01173 
01174 /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
01175    \note OEJ: Should be moved to string fields */
01176 struct sip_refer {
01177    char refer_to[AST_MAX_EXTENSION];      /*!< Place to store REFER-TO extension */
01178    char refer_to_domain[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO domain */
01179    char refer_to_urioption[AST_MAX_EXTENSION];  /*!< Place to store REFER-TO uri options */
01180    char refer_to_context[AST_MAX_EXTENSION]; /*!< Place to store REFER-TO context */
01181    char referred_by[AST_MAX_EXTENSION];      /*!< Place to store REFERRED-BY extension */
01182    char referred_by_name[AST_MAX_EXTENSION]; /*!< Place to store REFERRED-BY extension */
01183    char refer_contact[AST_MAX_EXTENSION];    /*!< Place to store Contact info from a REFER extension */
01184    char replaces_callid[SIPBUFSIZE];         /*!< Replace info: callid */
01185    char replaces_callid_totag[SIPBUFSIZE/2];    /*!< Replace info: to-tag */
01186    char replaces_callid_fromtag[SIPBUFSIZE/2];     /*!< Replace info: from-tag */
01187    struct sip_pvt *refer_call;         /*!< Call we are referring. This is just a reference to a
01188                       * dialog owned by someone else, so we should not destroy
01189                       * it when the sip_refer object goes.
01190                       */
01191    int attendedtransfer;            /*!< Attended or blind transfer? */
01192    int localtransfer;            /*!< Transfer to local domain? */
01193    enum referstatus status;         /*!< REFER status */
01194 };
01195 
01196 
01197 /*! \brief Structure that encapsulates all attributes related to running 
01198  *   SIP Session-Timers feature on a per dialog basis.
01199  */
01200 struct sip_st_dlg {
01201    int st_active;                          /*!< Session-Timers on/off */ 
01202    int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
01203    int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
01204    enum st_refresher st_ref;               /*!< Session-Timers session refresher */
01205    int st_expirys;                         /*!< Session-Timers number of expirys */
01206    int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
01207    int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
01208    int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
01209    enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
01210    enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
01211    unsigned char quit_flag:1;              /*!< Stop trying to lock; just quit */
01212 };
01213 
01214 
01215 /*! \brief Structure that encapsulates all attributes related to configuration 
01216  *   of SIP Session-Timers feature on a per user/peer basis.
01217  */
01218 struct sip_st_cfg {
01219    enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
01220    enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
01221    int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
01222    int st_max_se;                  /*!< Highest threshold for session refresh interval */
01223 };
01224 
01225 struct offered_media {
01226    int offered;
01227    char text[128];
01228 };
01229 
01230 /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
01231  * Created and initialized by sip_alloc(), the descriptor goes into the list of
01232  * descriptors (dialoglist).
01233  */
01234 struct sip_pvt {
01235    struct sip_pvt *next;         /*!< Next dialog in chain */
01236    enum invitestates invitestate;      /*!< Track state of SIP_INVITEs */
01237    int method;          /*!< SIP method that opened this dialog */
01238    AST_DECLARE_STRING_FIELDS(
01239       AST_STRING_FIELD(callid);  /*!< Global CallID */
01240       AST_STRING_FIELD(randdata);   /*!< Random data */
01241       AST_STRING_FIELD(accountcode);   /*!< Account code */
01242       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01243       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01244       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01245       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01246       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01247       AST_STRING_FIELD(from);    /*!< The From: header */
01248       AST_STRING_FIELD(useragent);  /*!< User agent in SIP request */
01249       AST_STRING_FIELD(exten);   /*!< Extension where to start */
01250       AST_STRING_FIELD(context); /*!< Context for this call */
01251       AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
01252       AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
01253       AST_STRING_FIELD(fromdomain); /*!< Domain to show in the from field */
01254       AST_STRING_FIELD(fromuser);   /*!< User to show in the user field */
01255       AST_STRING_FIELD(fromname);   /*!< Name to show in the user field */
01256       AST_STRING_FIELD(tohost);  /*!< Host we should put in the "to" field */
01257       AST_STRING_FIELD(todnid);  /*!< DNID of this call (overrides host) */
01258       AST_STRING_FIELD(language);   /*!< Default language for this call */
01259       AST_STRING_FIELD(mohinterpret);  /*!< MOH class to use when put on hold */
01260       AST_STRING_FIELD(mohsuggest); /*!< MOH class to suggest when putting a peer on hold */
01261       AST_STRING_FIELD(rdnis);   /*!< Referring DNIS */
01262       AST_STRING_FIELD(redircause); /*!< Referring cause */
01263       AST_STRING_FIELD(theirtag);   /*!< Their tag */
01264       AST_STRING_FIELD(username);   /*!< [user] name */
01265       AST_STRING_FIELD(peername);   /*!< [peer] name, not set if [user] */
01266       AST_STRING_FIELD(authname);   /*!< Who we use for authentication */
01267       AST_STRING_FIELD(uri);     /*!< Original requested URI */
01268       AST_STRING_FIELD(okcontacturi);  /*!< URI from the 200 OK on INVITE */
01269       AST_STRING_FIELD(peersecret); /*!< Password */
01270       AST_STRING_FIELD(peermd5secret);
01271       AST_STRING_FIELD(cid_num); /*!< Caller*ID number */
01272       AST_STRING_FIELD(cid_name);   /*!< Caller*ID name */
01273       AST_STRING_FIELD(fullcontact);   /*!< The Contact: that the UA registers with us */
01274          /* we only store the part in <brackets> in this field. */
01275       AST_STRING_FIELD(our_contact);   /*!< Our contact header */
01276       AST_STRING_FIELD(rpid);    /*!< Our RPID header */
01277       AST_STRING_FIELD(rpid_from);  /*!< Our RPID From header */
01278       AST_STRING_FIELD(url);     /*!< URL to be sent with next message to peer */
01279       AST_STRING_FIELD(parkinglot);    /*!< Parkinglot */
01280    );
01281    char via[128];                          /*!< Via: header */
01282    struct sip_socket socket;     /*!< The socket used for this dialog */
01283    unsigned int ocseq;        /*!< Current outgoing seqno */
01284    unsigned int icseq;        /*!< Current incoming seqno */
01285    ast_group_t callgroup;        /*!< Call group */
01286    ast_group_t pickupgroup;      /*!< Pickup group */
01287    int lastinvite;            /*!< Last Cseq of invite */
01288    struct ast_flags flags[2];    /*!< SIP_ flags */
01289 
01290    /* boolean or small integers that don't belong in flags */
01291    char do_history;        /*!< Set if we want to record history */
01292    char alreadygone;       /*!< already destroyed by our peer */
01293    char needdestroy;       /*!< need to be destroyed by the monitor thread */
01294    char outgoing_call;        /*!< this is an outgoing call */
01295    char answered_elsewhere;      /*!< This call is cancelled due to answer on another channel */
01296    char novideo;           /*!< Didn't get video in invite, don't offer */
01297    char notext;            /*!< Text not supported  (?) */
01298 
01299    int timer_t1;           /*!< SIP timer T1, ms rtt */
01300    int timer_b;                            /*!< SIP timer B, ms */
01301    unsigned int sipoptions;      /*!< Supported SIP options on the other end */
01302    unsigned int reqsipoptions;      /*!< Required SIP options on the other end */
01303    struct ast_codec_pref prefs;     /*!< codec prefs */
01304    int capability;            /*!< Special capability (codec) */
01305    int jointcapability;       /*!< Supported capability at both ends (codecs) */
01306    int peercapability;        /*!< Supported peer capability */
01307    int prefcodec;          /*!< Preferred codec (outbound only) */
01308    int noncodeccapability;       /*!< DTMF RFC2833 telephony-event */
01309    int jointnoncodeccapability;            /*!< Joint Non codec capability */
01310    int redircodecs;        /*!< Redirect codecs */
01311    int maxcallbitrate;        /*!< Maximum Call Bitrate for Video Calls */ 
01312    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly */
01313    int t38_maxdatagram;       /*!< T.38 FaxMaxDatagram override */
01314    struct t38properties t38;     /*!< T38 settings */
01315    struct sockaddr_in udptlredirip; /*!< Where our T.38 UDPTL should be going if not to us */
01316    struct ast_udptl *udptl;      /*!< T.38 UDPTL session */
01317    int callingpres;        /*!< Calling presentation */
01318    int authtries;          /*!< Times we've tried to authenticate */
01319    int expiry;          /*!< How long we take to expire */
01320    long branch;            /*!< The branch identifier of this session */
01321    long invite_branch;        /*!< The branch used when we sent the initial INVITE */
01322    char tag[11];           /*!< Our tag for this session */
01323    int sessionid;          /*!< SDP Session ID */
01324    int sessionversion;        /*!< SDP Session Version */
01325    int64_t sessionversion_remote;      /*!< Remote UA's SDP Session Version */
01326    int session_modify;        /*!< Session modification request true/false  */
01327    unsigned int portinuri:1;     /*!< Non zero if a port has been specified, will also disable srv lookups */
01328    struct sockaddr_in sa;        /*!< Our peer */
01329    struct sockaddr_in redirip;      /*!< Where our RTP should be going if not to us */
01330    struct sockaddr_in vredirip;     /*!< Where our Video RTP should be going if not to us */
01331    struct sockaddr_in tredirip;     /*!< Where our Text RTP should be going if not to us */
01332    time_t lastrtprx;       /*!< Last RTP received */
01333    time_t lastrtptx;       /*!< Last RTP sent */
01334    int rtptimeout;            /*!< RTP timeout time */
01335    struct sockaddr_in recv;      /*!< Received as */
01336    struct sockaddr_in ourip;     /*!< Our IP (as seen from the outside) */
01337    struct ast_channel *owner;    /*!< Who owns us (if we have an owner) */
01338    struct sip_route *route;      /*!< Head of linked list of routing steps (fm Record-Route) */
01339    int route_persistant;         /*!< Is this the "real" route? */
01340    struct ast_variable *notify_headers;    /*!< Custom notify type */
01341    struct sip_auth *peerauth;    /*!< Realm authentication */
01342    int noncecount;            /*!< Nonce-count */
01343    unsigned int stalenonce:1; /*!< Marks the current nonce as responded too */
01344    char lastmsg[256];         /*!< Last Message sent/received */
01345    int amaflags;           /*!< AMA Flags */
01346    int pendinginvite;         /*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
01347    int glareinvite;        /*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
01348                   value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
01349                   held in order to properly process acknowledgements for our 491 response. */
01350    struct sip_request initreq;      /*!< Latest request that opened a new transaction
01351                      within this dialog.
01352                      NOT the request that opened the dialog */
01353 
01354    int initid;          /*!< Auto-congest ID if appropriate (scheduler) */
01355    int waitid;          /*!< Wait ID for scheduler after 491 or other delays */
01356    int autokillid;            /*!< Auto-kill ID (scheduler) */
01357    int t38id;                              /*!< T.38 Response ID */
01358    enum transfermodes allowtransfer;   /*!< REFER: restriction scheme */
01359    struct sip_refer *refer;      /*!< REFER: SIP transfer data structure */
01360    enum subscriptiontype subscribed;   /*!< SUBSCRIBE: Is this dialog a subscription?  */
01361    int stateid;            /*!< SUBSCRIBE: ID for devicestate subscriptions */
01362    int laststate;          /*!< SUBSCRIBE: Last known extension state */
01363    int dialogver;          /*!< SUBSCRIBE: Version for subscription dialog-info */
01364 
01365    struct ast_dsp *dsp;       /*!< A DSP for inband DTMF and fax CNG tone detection */
01366 
01367    struct sip_peer *relatedpeer;    /*!< If this dialog is related to a peer, which one 
01368                      Used in peerpoke, mwi subscriptions */
01369    struct sip_registry *registry;      /*!< If this is a REGISTER dialog, to which registry */
01370    struct ast_rtp *rtp;       /*!< RTP Session */
01371    struct ast_rtp *vrtp;         /*!< Video RTP session */
01372    struct ast_rtp *trtp;         /*!< Text RTP session */
01373    struct sip_pkt *packets;      /*!< Packets scheduled for re-transmission */
01374    struct sip_history_head *history;   /*!< History of this SIP dialog */
01375    size_t history_entries;       /*!< Number of entires in the history */
01376    struct ast_variable *chanvars;      /*!< Channel variables to set for inbound call */
01377    AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
01378    int request_queue_sched_id;      /*!< Scheduler ID of any scheduled action to process queued requests */
01379    int provisional_keepalive_sched_id; /*!< Scheduler ID for provisional responses that need to be sent out to avoid cancellation */
01380    const char *last_provisional;   /*!< The last successfully transmitted provisonal response message */
01381    struct sip_invite_param *options;   /*!< Options for INVITE */
01382    int autoframing;        /*!< The number of Asters we group in a Pyroflax
01383                      before strolling to the Grokyzpå
01384                      (A bit unsure of this, please correct if
01385                      you know more) */
01386    struct sip_st_dlg *stimer;    /*!< SIP Session-Timers */              
01387    int red;             /*!< T.140 RTP Redundancy */
01388    int hangupcause;        /*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
01389    /*! When receiving an SDP offer, it is important to take note of what media types were offered.
01390     * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
01391     * still put an m= line in our answer with the port set to 0.
01392     *
01393     * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
01394     * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
01395     *
01396     * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
01397     * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
01398     * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
01399     * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
01400     *
01401     * The large-scale changes would be a good idea for implementing during an SDP rewrite.
01402     */
01403    struct offered_media offered_media[4];
01404 }; 
01405 
01406 /*! Max entires in the history list for a sip_pvt */
01407 #define MAX_HISTORY_ENTRIES 50
01408 
01409 /*! \brief
01410  * Here we implement the container for dialogs (sip_pvt), defining
01411  * generic wrapper functions to ease the transition from the current
01412  * implementation (a single linked list) to a different container.
01413  * In addition to a reference to the container, we need functions to lock/unlock
01414  * the container and individual items, and functions to add/remove
01415  * references to the individual items.
01416  */
01417 struct ao2_container *dialogs;
01418 
01419 #define sip_pvt_lock(x) ao2_lock(x)
01420 #define sip_pvt_trylock(x) ao2_trylock(x)
01421 #define sip_pvt_unlock(x) ao2_unlock(x)
01422 
01423 /*! \brief
01424  * when we create or delete references, make sure to use these
01425  * functions so we keep track of the refcounts.
01426  * To simplify the code, we allow a NULL to be passed to dialog_unref().
01427  */
01428 #ifdef REF_DEBUG
01429 #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01430 #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
01431 
01432 static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01433 {
01434    if (p)
01435       _ao2_ref_debug(p, 1, tag, file, line, func);
01436    else
01437       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01438    return p;
01439 }
01440 
01441 static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
01442 {
01443    if (p)
01444       _ao2_ref_debug(p, -1, tag, file, line, func);
01445    return NULL;
01446 }
01447 #else
01448 static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
01449 {
01450    if (p)
01451       ao2_ref(p, 1);
01452    else
01453       ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
01454    return p;
01455 }
01456 
01457 static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
01458 {
01459    if (p)
01460       ao2_ref(p, -1);
01461    return NULL;
01462 }
01463 #endif
01464 
01465 /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
01466  * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
01467  * Each packet holds a reference to the parent struct sip_pvt.
01468  * This structure is allocated in __sip_reliable_xmit() and only for packets that
01469  * require retransmissions.
01470  */
01471 struct sip_pkt {
01472    struct sip_pkt *next;         /*!< Next packet in linked list */
01473    int retrans;            /*!< Retransmission number */
01474    int method;          /*!< SIP method for this packet */
01475    int seqno;           /*!< Sequence number */
01476    char is_resp;           /*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
01477    char is_fatal;          /*!< non-zero if there is a fatal error */
01478    int response_code;      /*!< If this is a response, the response code */
01479    struct sip_pvt *owner;        /*!< Owner AST call */
01480    int retransid;          /*!< Retransmission ID */
01481    int timer_a;            /*!< SIP timer A, retransmission timer */
01482    int timer_t1;           /*!< SIP Timer T1, estimated RTT or 500 ms */
01483    int packetlen;          /*!< Length of packet */
01484    struct ast_str *data;
01485 }; 
01486 
01487 /*!
01488  * \brief A peer's mailbox
01489  *
01490  * We could use STRINGFIELDS here, but for only two strings, it seems like
01491  * too much effort ...
01492  */
01493 struct sip_mailbox {
01494    char *mailbox;
01495    char *context;
01496    /*! Associated MWI subscription */
01497    struct ast_event_sub *event_sub;
01498    AST_LIST_ENTRY(sip_mailbox) entry;
01499 };
01500 
01501 enum sip_peer_type {
01502    SIP_TYPE_PEER = (1 << 0),
01503    SIP_TYPE_USER = (1 << 1),
01504 };
01505 
01506 /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
01507 */
01508 /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
01509 struct sip_peer {
01510    char name[80];       /*!< peer->name is the unique name of this object */
01511    struct sip_socket socket;  /*!< Socket used for this peer */
01512    enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport. */
01513    unsigned int transports:3; /*!< Transports (enum sip_transport) that are acceptable for this peer */
01514    char secret[80];     /*!< Password */
01515    char md5secret[80];     /*!< Password in MD5 */
01516    struct sip_auth *auth;     /*!< Realm authentication list */
01517    char context[AST_MAX_CONTEXT];   /*!< Default context for incoming calls */
01518    char subscribecontext[AST_MAX_CONTEXT];   /*!< Default context for subscriptions */
01519    char username[80];      /*!< Temporary username until registration */ 
01520    char accountcode[AST_MAX_ACCOUNT_CODE];   /*!< Account code */
01521    int amaflags;        /*!< AMA Flags (for billing) */
01522    char tohost[MAXHOSTNAMELEN];  /*!< If not dynamic, IP address */
01523    char regexten[AST_MAX_EXTENSION]; /*!< Extension to register (if regcontext is used) */
01524    char fromuser[80];      /*!< From: user when calling this peer */
01525    char fromdomain[MAXHOSTNAMELEN]; /*!< From: domain when calling this peer */
01526    char fullcontact[256];     /*!< Contact registered with us (not in sip.conf) */
01527    char cid_num[80];    /*!< Caller ID num */
01528    char cid_name[80];      /*!< Caller ID name */
01529    int callingpres;     /*!< Calling id presentation */
01530    int inUse;        /*!< Number of calls in use */
01531    int inRinging;       /*!< Number of calls ringing */
01532    int onHold;                     /*!< Peer has someone on hold */
01533    int call_limit;         /*!< Limit of concurrent calls */
01534    int t38_maxdatagram;    /*!< T.38 FaxMaxDatagram override */
01535    int busy_level;         /*!< Level of active channels where we signal busy */
01536    enum transfermodes allowtransfer;   /*! SIP Refer restriction scheme */
01537    char vmexten[AST_MAX_EXTENSION]; /*!< Dialplan extension for MWI notify message*/
01538    char language[MAX_LANGUAGE];  /*!<  Default language for prompts */
01539    char mohinterpret[MAX_MUSICCLASS];/*!<  Music on Hold class */
01540    char mohsuggest[MAX_MUSICCLASS];/*!<  Music on Hold class */
01541    char parkinglot[AST_MAX_CONTEXT];/*!<  Parkinglot */
01542    char useragent[256];    /*!<  User agent in SIP request (saved from registration) */
01543    struct ast_codec_pref prefs;  /*!<  codec prefs */
01544    int lastmsgssent;
01545    unsigned int sipoptions;   /*!<  Supported SIP options */
01546    struct ast_flags flags[2]; /*!<  SIP_ flags */
01547 
01548    /*! Mailboxes that this peer cares about */
01549    AST_LIST_HEAD_NOLOCK(, sip_mailbox) mailboxes;
01550 
01551    /* things that don't belong in flags */
01552    char is_realtime;    /*!< this is a 'realtime' peer */
01553    char rt_fromcontact;    /*!< P: copy fromcontact from realtime */
01554    char host_dynamic;      /*!< P: Dynamic Peers register with Asterisk */
01555    char selfdestruct;      /*!< P: Automatic peers need to destruct themselves */
01556    char the_mark;       /*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
01557 
01558    int expire;       /*!<  When to expire this peer registration */
01559    int capability;         /*!<  Codec capability */
01560    int rtptimeout;         /*!<  RTP timeout */
01561    int rtpholdtimeout;     /*!<  RTP Hold Timeout */
01562    int rtpkeepalive;    /*!<  Send RTP packets for keepalive */
01563    ast_group_t callgroup;     /*!<  Call group */
01564    ast_group_t pickupgroup;   /*!<  Pickup group */
01565    struct sip_proxy *outboundproxy; /*!< Outbound proxy for this peer */
01566    struct ast_dnsmgr_entry *dnsmgr;/*!<  DNS refresh manager for peer */
01567    struct sockaddr_in addr;   /*!<  IP address of peer */
01568    int maxcallbitrate;     /*!< Maximum Bitrate for a video call */
01569    unsigned int portinuri:1;  /*!< Whether the port should be included in the URI */
01570 
01571    /* Qualification */
01572    struct sip_pvt *call;      /*!<  Call pointer */
01573    int pokeexpire;         /*!<  When to expire poke (qualify= checking) */
01574    int lastms;       /*!<  How long last response took (in ms), or -1 for no response */
01575    int maxms;        /*!<  Max ms we will accept for the host to be up, 0 to not monitor */
01576    int qualifyfreq;     /*!<  Qualification: How often to check for the host to be up */
01577    struct timeval ps;      /*!<  Time for sending SIP OPTION in sip_pke_peer() */
01578    struct sockaddr_in defaddr;   /*!<  Default IP address, used until registration */
01579    struct ast_ha *ha;      /*!<  Access control list */
01580    struct ast_ha *contactha;       /*!<  Restrict what IPs are allowed in the Contact header (for registration) */
01581    struct ast_variable *chanvars;   /*!<  Variables to set for channel created by user */
01582    struct sip_pvt *mwipvt;    /*!<  Subscription for MWI */
01583    int autoframing;
01584    struct sip_st_cfg stimer;  /*!<  SIP Session-Timers */
01585    int timer_t1;        /*!<  The maximum T1 value for the peer */
01586    int timer_b;         /*!<  The maximum timer B (transaction timeouts) */
01587    int deprecated_username; /*!< If it's a realtime peer, are they using the deprecated "username" instead of "defaultuser" */
01588    enum sip_peer_type type; /*!< Distinguish between "user" and "peer" types. This is used solely for CLI and manager commands */
01589 };
01590 
01591 
01592 /*! 
01593  * \brief Registrations with other SIP proxies
01594  *
01595  * Created by sip_register(), the entry is linked in the 'regl' list,
01596  * and never deleted (other than at 'sip reload' or module unload times).
01597  * The entry always has a pending timeout, either waiting for an ACK to
01598  * the REGISTER message (in which case we have to retransmit the request),
01599  * or waiting for the next REGISTER message to be sent (either the initial one,
01600  * or once the previously completed registration one expires).
01601  * The registration can be in one of many states, though at the moment
01602  * the handling is a bit mixed.
01603  */
01604 struct sip_registry {
01605    ASTOBJ_COMPONENTS_FULL(struct sip_registry,1,1);
01606    AST_DECLARE_STRING_FIELDS(
01607       AST_STRING_FIELD(callid);  /*!< Global Call-ID */
01608       AST_STRING_FIELD(realm);   /*!< Authorization realm */
01609       AST_STRING_FIELD(nonce);   /*!< Authorization nonce */
01610       AST_STRING_FIELD(opaque);  /*!< Opaque nonsense */
01611       AST_STRING_FIELD(qop);     /*!< Quality of Protection, since SIP wasn't complicated enough yet. */
01612       AST_STRING_FIELD(domain);  /*!< Authorization domain */
01613       AST_STRING_FIELD(username);   /*!< Who we are registering as */
01614       AST_STRING_FIELD(authuser);   /*!< Who we *authenticate* as */
01615       AST_STRING_FIELD(hostname);   /*!< Domain or host we register to */
01616       AST_STRING_FIELD(secret);  /*!< Password in clear text */   
01617       AST_STRING_FIELD(md5secret);  /*!< Password in md5 */
01618       AST_STRING_FIELD(callback);   /*!< Contact extension */
01619       AST_STRING_FIELD(random);
01620       AST_STRING_FIELD(peername);   /*!< Peer registering to */
01621    );
01622    enum sip_transport transport; /*!< Transport for this registration UDP, TCP or TLS */
01623    int portno;       /*!<  Optional port override */
01624    int expire;       /*!< Sched ID of expiration */
01625    int configured_expiry;     /*!< Configured value to use for the Expires header */
01626    int expiry;       /*!< Negotiated value used for the Expires header */
01627    int regattempts;     /*!< Number of attempts (since the last success) */
01628    int timeout;         /*!< sched id of sip_reg_timeout */
01629    int refresh;         /*!< How often to refresh */
01630    struct sip_pvt *call;      /*!< create a sip_pvt structure for each outbound "registration dialog" in progress */
01631    enum sipregistrystate regstate;  /*!< Registration state (see above) */
01632    struct timeval regtime;    /*!< Last successful registration time */
01633    int callid_valid;    /*!< 0 means we haven't chosen callid for this registry yet. */
01634    unsigned int ocseq;     /*!< Sequence number we got to for REGISTERs for this registry */
01635    struct ast_dnsmgr_entry *dnsmgr; /*!<  DNS refresh manager for register */
01636    struct sockaddr_in us;     /*!< Who the server thinks we are */
01637    int noncecount;         /*!< Nonce-count */
01638    char lastmsg[256];      /*!< Last Message sent/received */
01639 };
01640 
01641 enum sip_tcptls_alert {
01642    /*! \brief There is new data to be sent out */
01643    TCPTLS_ALERT_DATA,
01644    /*! \brief A request to stop the tcp_handler thread */
01645    TCPTLS_ALERT_STOP,
01646 };
01647 
01648 struct tcptls_packet {
01649    AST_LIST_ENTRY(tcptls_packet) entry;
01650    struct ast_str *data;
01651    size_t len;
01652 };
01653 /*! \brief Definition of a thread that handles a socket */
01654 struct sip_threadinfo {
01655    int stop;
01656    int alert_pipe[2]; /*! Used to alert tcptls thread when packet is ready to be written */
01657    pthread_t threadid;
01658    struct ast_tcptls_session_instance *tcptls_session;
01659    enum sip_transport type;   /*!< We keep a copy of the type here so we can display it in the connection list */
01660    AST_LIST_HEAD_NOLOCK(, tcptls_packet) packet_q;
01661 };
01662 
01663 /* --- Hash tables of various objects --------*/
01664 
01665 #ifdef LOW_MEMORY
01666 static int hash_peer_size = 17;
01667 static int hash_dialog_size = 17;
01668 static int hash_user_size = 17;
01669 #else
01670 static int hash_peer_size = 563; /*!< Size of peer hash table, prime number preferred! */
01671 static int hash_dialog_size = 563;
01672 static int hash_user_size = 563;
01673 #endif
01674 
01675 /*! \brief  The table of TCP threads */
01676 static struct ao2_container *threadt;
01677 
01678 /*! \brief  The peer list: Users, Peers and Friends */
01679 struct ao2_container *peers;
01680 struct ao2_container *peers_by_ip;
01681 
01682 /*! \brief  The register list: Other SIP proxies we register with and place calls to */
01683 static struct ast_register_list {
01684    ASTOBJ_CONTAINER_COMPONENTS(struct sip_registry);
01685    int recheck;
01686 } regl;
01687 
01688 /*! \brief
01689  * \note The only member of the peer used here is the name field
01690  */
01691 static int peer_hash_cb(const void *obj, const int flags)
01692 {
01693    const struct sip_peer *peer = obj;
01694 
01695    return ast_str_case_hash(peer->name);
01696 }
01697 
01698 /*!
01699  * \note The only member of the peer used here is the name field
01700  */
01701 static int peer_cmp_cb(void *obj, void *arg, int flags)
01702 {
01703    struct sip_peer *peer = obj, *peer2 = arg;
01704 
01705    return !strcasecmp(peer->name, peer2->name) ? CMP_MATCH | CMP_STOP : 0;
01706 }
01707 
01708 /*!
01709  * \note the peer's ip address field is used to create key.
01710  */
01711 static int peer_iphash_cb(const void *obj, const int flags)
01712 {
01713    const struct sip_peer *peer = obj;
01714    int ret1 = peer->addr.sin_addr.s_addr;
01715    if (ret1 < 0)
01716       ret1 = -ret1;
01717 
01718    return ret1;
01719 }
01720 
01721 /*!
01722  * Match Peers by IP and Port number.
01723  *
01724  * This function has two modes.
01725  *  - If the peer arg does not have INSECURE_PORT set, then we will only return
01726  *    a match for a peer that matches both the IP and port.
01727  *  - If the peer arg does have the INSECURE_PORT flag set, then we will only
01728  *    return a match for a peer that matches the IP and has insecure=port
01729  *    in its configuration.
01730  *
01731  * This callback will be used twice when doing peer matching.  There is a first
01732  * pass for full IP+port matching, and a second pass in case there is a match
01733  * that meets the insecure=port criteria.
01734  *
01735  * \note Connections coming in over TCP or TLS should never be matched by port.
01736  *
01737  * \note the peer's addr struct provides to fields combined to make a key: the sin_addr.s_addr and sin_port fields.
01738  */
01739 static int peer_ipcmp_cb(void *obj, void *arg, int flags)
01740 {
01741    struct sip_peer *peer = obj, *peer2 = arg;
01742 
01743    if (peer->addr.sin_addr.s_addr != peer2->addr.sin_addr.s_addr) {
01744       /* IP doesn't match */
01745       return 0;
01746    }
01747 
01748    /* We matched the IP, check to see if we need to match by port as well. */
01749    if ((peer->transports & peer2->transports) & (SIP_TRANSPORT_TLS | SIP_TRANSPORT_TCP)) {
01750       /* peer matching on port is not possible with TCP/TLS */
01751       return CMP_MATCH | CMP_STOP;
01752    } else if (ast_test_flag(&peer2->flags[0], SIP_INSECURE_PORT)) {
01753       /* We are allowing match without port for peers configured that
01754        * way in this pass through the peers. */
01755       return ast_test_flag(&peer->flags[0], SIP_INSECURE_PORT) ?
01756             (CMP_MATCH | CMP_STOP) : 0;
01757    }
01758 
01759    /* Now only return a match if the port matches, as well. */
01760    return peer->addr.sin_port == peer2->addr.sin_port ? (CMP_MATCH | CMP_STOP) : 0;
01761 }
01762 
01763 
01764 static int threadt_hash_cb(const void *obj, const int flags)
01765 {
01766    const struct sip_threadinfo *th = obj;
01767 
01768    return (int) th->tcptls_session->remote_address.sin_addr.s_addr;
01769 }
01770 
01771 static int threadt_cmp_cb(void *obj, void *arg, int flags)
01772 {
01773    struct sip_threadinfo *th = obj, *th2 = arg;
01774 
01775    return (th->tcptls_session == th2->tcptls_session) ? CMP_MATCH | CMP_STOP : 0;
01776 }
01777 
01778 /*!
01779  * \note The only member of the dialog used here callid string
01780  */
01781 static int dialog_hash_cb(const void *obj, const int flags)
01782 {
01783    const struct sip_pvt *pvt = obj;
01784 
01785    return ast_str_case_hash(pvt->callid);
01786 }
01787 
01788 /*!
01789  * \note The only member of the dialog used here callid string
01790  */
01791 static int dialog_cmp_cb(void *obj, void *arg, int flags)
01792 {
01793    struct sip_pvt *pvt = obj, *pvt2 = arg;
01794    
01795    return !strcasecmp(pvt->callid, pvt2->callid) ? CMP_MATCH | CMP_STOP : 0;
01796 }
01797 
01798 static int temp_pvt_init(void *);
01799 static void temp_pvt_cleanup(void *);
01800 
01801 /*! \brief A per-thread temporary pvt structure */
01802 AST_THREADSTORAGE_CUSTOM(ts_temp_pvt, temp_pvt_init, temp_pvt_cleanup);
01803 
01804 #ifdef LOW_MEMORY
01805 static void ts_ast_rtp_destroy(void *);
01806 
01807 AST_THREADSTORAGE_CUSTOM(ts_audio_rtp, NULL, ts_ast_rtp_destroy);
01808 AST_THREADSTORAGE_CUSTOM(ts_video_rtp, NULL, ts_ast_rtp_destroy);
01809 AST_THREADSTORAGE_CUSTOM(ts_text_rtp, NULL, ts_ast_rtp_destroy);
01810 #endif
01811 
01812 /*! \brief Authentication list for realm authentication 
01813  * \todo Move the sip_auth list to AST_LIST */
01814 static struct sip_auth *authl = NULL;
01815 
01816 
01817 /* --- Sockets and networking --------------*/
01818 
01819 /*! \brief Main socket for SIP communication.
01820  *
01821  * sipsock is shared between the SIP manager thread (which handles reload
01822  * requests), the io handler (sipsock_read()) and the user routines that
01823  * issue writes (using __sip_xmit()).
01824  * The socket is -1 only when opening fails (this is a permanent condition),
01825  * or when we are handling a reload() that changes its address (this is
01826  * a transient situation during which we might have a harmless race, see
01827  * below). Because the conditions for the race to be possible are extremely
01828  * rare, we don't want to pay the cost of locking on every I/O.
01829  * Rather, we remember that when the race may occur, communication is
01830  * bound to fail anyways, so we just live with this event and let
01831  * the protocol handle this above us.
01832  */
01833 static int sipsock  = -1;
01834 
01835 static struct sockaddr_in bindaddr; /*!< UDP: The address we bind to */
01836 
01837 /*! \brief our (internal) default address/port to put in SIP/SDP messages
01838  *  internip is initialized picking a suitable address from one of the
01839  * interfaces, and the same port number we bind to. It is used as the
01840  * default address/port in SIP messages, and as the default address
01841  * (but not port) in SDP messages.
01842  */
01843 static struct sockaddr_in internip;
01844 
01845 /*! \brief our external IP address/port for SIP sessions.
01846  * externip.sin_addr is only set when we know we might be behind
01847  * a NAT, and this is done using a variety of (mutually exclusive)
01848  * ways from the config file:
01849  *
01850  * + with "externip = host[:port]" we specify the address/port explicitly.
01851  *   The address is looked up only once when (re)loading the config file;
01852  * 
01853  * + with "externhost = host[:port]" we do a similar thing, but the
01854  *   hostname is stored in externhost, and the hostname->IP mapping
01855  *   is refreshed every 'externrefresh' seconds;
01856  * 
01857  * + with "stunaddr = host[:port]" we run queries every externrefresh seconds
01858  *   to the specified server, and store the result in externip.
01859  *
01860  * Other variables (externhost, externexpire, externrefresh) are used
01861  * to support the above functions.
01862  */
01863 static struct sockaddr_in externip;    /*!< External IP address if we are behind NAT */
01864 
01865 static char externhost[MAXHOSTNAMELEN];      /*!< External host name */
01866 static time_t externexpire;         /*!< Expiration counter for re-resolving external host name in dynamic DNS */
01867 static int externrefresh = 10;
01868 static struct sockaddr_in stunaddr;    /*!< stun server address */
01869 
01870 /*! \brief  List of local networks
01871  * We store "localnet" addresses from the config file into an access list,
01872  * marked as 'DENY', so the call to ast_apply_ha() will return
01873  * AST_SENSE_DENY for 'local' addresses, and AST_SENSE_ALLOW for 'non local'
01874  * (i.e. presumably public) addresses.
01875  */
01876 static struct ast_ha *localaddr;    /*!< List of local networks, on the same side of NAT as this Asterisk */
01877 
01878 static int ourport_tcp;          /*!< The port used for TCP connections */
01879 static int ourport_tls;          /*!< The port used for TCP/TLS connections */
01880 static struct sockaddr_in debugaddr;
01881 
01882 static struct ast_config *notify_types;      /*!< The list of manual NOTIFY types we know how to send */
01883 
01884 /*! some list management macros. */
01885  
01886 #define UNLINK(element, head, prev) do {  \
01887    if (prev)            \
01888       (prev)->next = (element)->next;  \
01889    else              \
01890       (head) = (element)->next;  \
01891    } while (0)
01892 
01893 enum t38_action_flag {
01894    SDP_T38_NONE = 0, /*!< Do not modify T38 information at all */
01895    SDP_T38_INITIATE, /*!< Remote side has requested T38 with us */
01896    SDP_T38_ACCEPT,   /*!< Remote side accepted our T38 request */
01897 };
01898 
01899 /*---------------------------- Forward declarations of functions in chan_sip.c */
01900 /* Note: This is added to help splitting up chan_sip.c into several files
01901    in coming releases. */
01902 
01903 /*--- PBX interface functions */
01904 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause);
01905 static int sip_devicestate(void *data);
01906 static int sip_sendtext(struct ast_channel *ast, const char *text);
01907 static int sip_call(struct ast_channel *ast, char *dest, int timeout);
01908 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen);
01909 static int sip_hangup(struct ast_channel *ast);
01910 static int sip_answer(struct ast_channel *ast);
01911 static struct ast_frame *sip_read(struct ast_channel *ast);
01912 static int sip_write(struct ast_channel *ast, struct ast_frame *frame);
01913 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
01914 static int sip_transfer(struct ast_channel *ast, const char *dest);
01915 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
01916 static int sip_senddigit_begin(struct ast_channel *ast, char digit);
01917 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration);
01918 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
01919 static const char *sip_get_callid(struct ast_channel *chan);
01920 
01921 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin);
01922 static int sip_standard_port(enum sip_transport type, int port);
01923 static int sip_prepare_socket(struct sip_pvt *p);
01924 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport);
01925 
01926 /*--- Transmitting responses and requests */
01927 static int sipsock_read(int *id, int fd, short events, void *ignore);
01928 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len);
01929 static int __sip_reliable_xmit(struct sip_pvt *p, int seqno, int resp, struct ast_str *data, int len, int fatal, int sipmethod);
01930 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01931 static int retrans_pkt(const void *data);
01932 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);
01933 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01934 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01935 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req);
01936 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp);
01937 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported);
01938 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);
01939 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp);
01940 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable);
01941 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable);
01942 static int transmit_request(struct sip_pvt *p, int sipmethod, int inc, enum xmittype reliable, int newbranch);
01943 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch);
01944 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init);
01945 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp);
01946 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration);
01947 static int transmit_info_with_vidupdate(struct sip_pvt *p);
01948 static int transmit_message_with_text(struct sip_pvt *p, const char *text);
01949 static int transmit_refer(struct sip_pvt *p, const char *dest);
01950 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten);
01951 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate);
01952 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars);
01953 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader);
01954 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01955 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno);
01956 static void copy_request(struct sip_request *dst, const struct sip_request *src);
01957 static void receive_message(struct sip_pvt *p, struct sip_request *req);
01958 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req);
01959 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only);
01960 
01961 /*--- Dialog management */
01962 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
01963              int useglobal_nat, const int intended_method, struct sip_request *req);
01964 static int __sip_autodestruct(const void *data);
01965 static void sip_scheddestroy(struct sip_pvt *p, int ms);
01966 static int sip_cancel_destroy(struct sip_pvt *p);
01967 static struct sip_pvt *sip_destroy(struct sip_pvt *p);
01968 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist);
01969 static void *registry_unref(struct sip_registry *reg, char *tag);
01970 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist);
01971 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01972 static void __sip_pretend_ack(struct sip_pvt *p);
01973 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod);
01974 static int auto_congest(const void *arg);
01975 static int update_call_counter(struct sip_pvt *fup, int event);
01976 static int hangup_sip2cause(int cause);
01977 static const char *hangup_cause2sip(int cause);
01978 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method);
01979 static void free_old_route(struct sip_route *route);
01980 static void list_route(struct sip_route *route);
01981 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards);
01982 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
01983                      struct sip_request *req, char *uri);
01984 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag);
01985 static void check_pendings(struct sip_pvt *p);
01986 static void *sip_park_thread(void *stuff);
01987 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno);
01988 static int sip_sipredirect(struct sip_pvt *p, const char *dest);
01989 
01990 /*--- Codec handling / SDP */
01991 static void try_suggested_sip_codec(struct sip_pvt *p);
01992 static const char *get_sdp_iterate(int* start, struct sip_request *req, const char *name);
01993 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value);
01994 static int find_sdp(struct sip_request *req);
01995 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action);
01996 static int process_sdp_o(const char *o, struct sip_pvt *p);
01997 static int process_sdp_c(const char *c, struct ast_hostent *hp);
01998 static int process_sdp_a_sendonly(const char *a, int *sendonly);
01999 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec);
02000 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec);
02001 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec);
02002 static int process_sdp_a_image(const char *a, struct sip_pvt *p);
02003 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
02004               struct ast_str **m_buf, struct ast_str **a_buf,
02005               int debug, int *min_packet_size);
02006 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
02007             struct ast_str **m_buf, struct ast_str **a_buf,
02008             int debug);
02009 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38);
02010 static void do_setnat(struct sip_pvt *p, int natflags);
02011 static void stop_media_flows(struct sip_pvt *p);
02012 
02013 /*--- Authentication stuff */
02014 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod, char *digest, int digest_len);
02015 static int build_reply_digest(struct sip_pvt *p, int method, char *digest, int digest_len);
02016 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
02017                 const char *secret, const char *md5secret, int sipmethod,
02018                 char *uri, enum xmittype reliable, int ignore);
02019 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
02020                      int sipmethod, char *uri, enum xmittype reliable,
02021                      struct sockaddr_in *sin, struct sip_peer **authpeer);
02022 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin);
02023 
02024 /*--- Domain handling */
02025 static int check_sip_domain(const char *domain, char *context, size_t len); /* Check if domain is one of our local domains */
02026 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context);
02027 static void clear_sip_domains(void);
02028 
02029 /*--- SIP realm authentication */
02030 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno);
02031 static int clear_realm_authentication(struct sip_auth *authlist); /* Clear realm authentication list (at reload) */
02032 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm);
02033 
02034 /*--- Misc functions */
02035 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t);
02036 static int sip_do_reload(enum channelreloadreason reason);
02037 static int reload_config(enum channelreloadreason reason);
02038 static int expire_register(const void *data);
02039 static void *do_monitor(void *data);
02040 static int restart_monitor(void);
02041 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer);
02042 /* static int sip_addrcmp(char *name, struct sockaddr_in *sin);   Support for peer matching */
02043 static int sip_refer_allocate(struct sip_pvt *p);
02044 static void ast_quiet_chan(struct ast_channel *chan);
02045 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target);
02046 /*!
02047  * \brief generic function for determining if a correct transport is being 
02048  * used to contact a peer
02049  *
02050  * this is done as a macro so that the "tmpl" var can be passed either a 
02051  * sip_request or a sip_peer 
02052  */
02053 #define check_request_transport(peer, tmpl) ({ \
02054    int ret = 0; \
02055    if (peer->socket.type == tmpl->socket.type) \
02056       ; \
02057    else if (!(peer->transports & tmpl->socket.type)) {\
02058       ast_log(LOG_ERROR, \
02059          "'%s' is not a valid transport for '%s'. we only use '%s'! ending call.\n", \
02060          get_transport(tmpl->socket.type), peer->name, get_transport_list(peer) \
02061          ); \
02062       ret = 1; \
02063    } else if (peer->socket.type & SIP_TRANSPORT_TLS) { \
02064       ast_log(LOG_WARNING, \
02065          "peer '%s' HAS NOT USED (OR SWITCHED TO) TLS in favor of '%s' (but this was allowed in sip.conf)!\n", \
02066          peer->name, get_transport(tmpl->socket.type) \
02067       ); \
02068    } else { \
02069       ast_debug(1, \
02070          "peer '%s' has contacted us over %s even though we prefer %s.\n", \
02071          peer->name, get_transport(tmpl->socket.type), get_transport(peer->socket.type) \
02072       ); \
02073    }\
02074    (ret); \
02075 })
02076 
02077 
02078 /*--- Device monitoring and Device/extension state/event handling */
02079 static int cb_extensionstate(char *context, char* exten, int state, void *data);
02080 static int sip_devicestate(void *data);
02081 static int sip_poke_noanswer(const void *data);
02082 static int sip_poke_peer(struct sip_peer *peer, int force);
02083 static void sip_poke_all_peers(void);
02084 static void sip_peer_hold(struct sip_pvt *p, int hold);
02085 static void mwi_event_cb(const struct ast_event *, void *);
02086 
02087 /*--- Applications, functions, CLI and manager command helpers */
02088 static const char *sip_nat_mode(const struct sip_pvt *p);
02089 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02090 static char *transfermode2str(enum transfermodes mode) attribute_const;
02091 static const char *nat2str(int nat) attribute_const;
02092 static int peer_status(struct sip_peer *peer, char *status, int statuslen);
02093 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02094 static char * _sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02095 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02096 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02097 static void  print_group(int fd, ast_group_t group, int crlf);
02098 static const char *dtmfmode2str(int mode) attribute_const;
02099 static int str2dtmfmode(const char *str) attribute_unused;
02100 static const char *insecure2str(int mode) attribute_const;
02101 static void cleanup_stale_contexts(char *new, char *old);
02102 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref);
02103 static const char *domain_mode_to_text(const enum domain_mode mode);
02104 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02105 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02106 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02107 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[]);
02108 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02109 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02110 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02111 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02112 static const char *subscription_type2str(enum subscriptiontype subtype) attribute_pure;
02113 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02114 static char *complete_sip_peer(const char *word, int state, int flags2);
02115 static char *complete_sip_registered_peer(const char *word, int state, int flags2);
02116 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state);
02117 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state);
02118 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state);
02119 static char *complete_sipnotify(const char *line, const char *word, int pos, int state);
02120 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02121 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02122 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02123 static char *sip_do_debug_ip(int fd, char *arg);
02124 static char *sip_do_debug_peer(int fd, char *arg);
02125 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02126 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02127 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02128 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02129 static int sip_dtmfmode(struct ast_channel *chan, void *data);
02130 static int sip_addheader(struct ast_channel *chan, void *data);
02131 static int sip_do_reload(enum channelreloadreason reason);
02132 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02133 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen);
02134 
02135 /*--- Debugging 
02136    Functions for enabling debug per IP or fully, or enabling history logging for
02137    a SIP dialog
02138 */
02139 static void sip_dump_history(struct sip_pvt *dialog); /* Dump history to debuglog at end of dialog, before destroying data */
02140 static inline int sip_debug_test_addr(const struct sockaddr_in *addr);
02141 static inline int sip_debug_test_pvt(struct sip_pvt *p);
02142 
02143 
02144 /*! \brief Append to SIP dialog history 
02145    \return Always returns 0 */
02146 #define append_history(p, event, fmt , args... )   append_history_full(p, "%-15s " fmt, event, ## args)
02147 static void append_history_full(struct sip_pvt *p, const char *fmt, ...);
02148 static void sip_dump_history(struct sip_pvt *dialog);
02149 
02150 /*--- Device object handling */
02151 static struct sip_peer *temp_peer(const char *name);
02152 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only);
02153 static int update_call_counter(struct sip_pvt *fup, int event);
02154 static void sip_destroy_peer(struct sip_peer *peer);
02155 static void sip_destroy_peer_fn(void *peer);
02156 static void set_peer_defaults(struct sip_peer *peer);
02157 static struct sip_peer *temp_peer(const char *name);
02158 static void register_peer_exten(struct sip_peer *peer, int onoff);
02159 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport);
02160 static int sip_poke_peer_s(const void *data);
02161 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *p, struct sip_request *req);
02162 static void reg_source_db(struct sip_peer *peer);
02163 static void destroy_association(struct sip_peer *peer);
02164 static void set_insecure_flags(struct ast_flags *flags, const char *value, int lineno);
02165 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v);
02166 static void set_socket_transport(struct sip_socket *socket, int transport);
02167 
02168 /* Realtime device support */
02169 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);
02170 static void update_peer(struct sip_peer *p, int expire);
02171 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *config);
02172 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername);
02173 static struct sip_peer *realtime_peer(const char *peername, struct sockaddr_in *sin, int devstate_only);
02174 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a);
02175 
02176 /*--- Internal UA client handling (outbound registrations) */
02177 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p);
02178 static void sip_registry_destroy(struct sip_registry *reg);
02179 static int sip_register(const char *value, int lineno);
02180 static const char *regstate2str(enum sipregistrystate regstate) attribute_const;
02181 static int sip_reregister(const void *data);
02182 static int __sip_do_register(struct sip_registry *r);
02183 static int sip_reg_timeout(const void *data);
02184 static void sip_send_all_registers(void);
02185 static int sip_reinvite_retry(const void *data);
02186 
02187 /*--- Parsing SIP requests and responses */
02188 static void append_date(struct sip_request *req);  /* Append date to SIP packet */
02189 static int determine_firstline_parts(struct sip_request *req);
02190 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype);
02191 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize);
02192 static int find_sip_method(const char *msg);
02193 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported);
02194 static int parse_request(struct sip_request *req);
02195 static const char *get_header(const struct sip_request *req, const char *name);
02196 static const char *referstatus2str(enum referstatus rstatus) attribute_pure;
02197 static int method_match(enum sipmethod id, const char *name);
02198 static void parse_copy(struct sip_request *dst, const struct sip_request *src);
02199 static char *get_in_brackets(char *tmp);
02200 static const char *find_alias(const char *name, const char *_default);
02201 static const char *__get_header(const struct sip_request *req, const char *name, int *start);
02202 static int lws2sws(char *msgbuf, int len);
02203 static void extract_uri(struct sip_pvt *p, struct sip_request *req);
02204 static char *remove_uri_parameters(char *uri);
02205 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req);
02206 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq);
02207 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req);
02208 static int set_address_from_contact(struct sip_pvt *pvt);
02209 static void check_via(struct sip_pvt *p, struct sip_request *req);
02210 static char *get_calleridname(const char *input, char *output, size_t outputsize);
02211 static int get_rpid_num(const char *input, char *output, int maxlen);
02212 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq);
02213 static int get_destination(struct sip_pvt *p, struct sip_request *oreq);
02214 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline);
02215 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout);
02216 
02217 /*-- TCP connection handling ---*/
02218 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session);
02219 static void *sip_tcp_worker_fn(void *);
02220 
02221 /*--- Constructing requests and responses */
02222 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req);
02223 static int init_req(struct sip_request *req, int sipmethod, const char *recip);
02224 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch);
02225 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod);
02226 static int init_resp(struct sip_request *resp, const char *msg);
02227 static inline int resp_needs_contact(const char *msg, enum sipmethod method);
02228 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req);
02229 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p);
02230 static void build_via(struct sip_pvt *p);
02231 static int create_addr_from_peer(struct sip_pvt *r, struct sip_peer *peer);
02232 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog);
02233 static char *generate_random_string(char *buf, size_t size);
02234 static void build_callid_pvt(struct sip_pvt *pvt);
02235 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain);
02236 static void make_our_tag(char *tagbuf, size_t len);
02237 static int add_header(struct sip_request *req, const char *var, const char *value);
02238 static int add_header_contentLength(struct sip_request *req, int len);
02239 static int add_line(struct sip_request *req, const char *line);
02240 static int add_text(struct sip_request *req, const char *text);
02241 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode);
02242 static int add_vidupdate(struct sip_request *req);
02243 static void add_route(struct sip_request *req, struct sip_route *route);
02244 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02245 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field);
02246 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field);
02247 static void set_destination(struct sip_pvt *p, char *uri);
02248 static void append_date(struct sip_request *req);
02249 static void build_contact(struct sip_pvt *p);
02250 static void build_rpid(struct sip_pvt *p);
02251 
02252 /*------Request handling functions */
02253 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock);
02254 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);
02255 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock);
02256 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req);
02257 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e);
02258 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req);
02259 static int handle_request_message(struct sip_pvt *p, struct sip_request *req);
02260 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02261 static void handle_request_info(struct sip_pvt *p, struct sip_request *req);
02262 static int handle_request_options(struct sip_pvt *p, struct sip_request *req);
02263 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock);
02264 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e);
02265 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno);
02266 
02267 /*------Response handling functions */
02268 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02269 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02270 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02271 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02272 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno);
02273 
02274 /*----- RTP interface functions */
02275 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);
02276 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02277 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02278 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp);
02279 static int sip_get_codec(struct ast_channel *chan);
02280 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect);
02281 
02282 /*------ T38 Support --------- */
02283 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans);
02284 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan);
02285 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl);
02286 static void change_t38_state(struct sip_pvt *p, int state);
02287 
02288 /*------ Session-Timers functions --------- */
02289 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp);
02290 static int  proc_session_timer(const void *vp);
02291 static void stop_session_timer(struct sip_pvt *p);
02292 static void start_session_timer(struct sip_pvt *p);
02293 static void restart_session_timer(struct sip_pvt *p);
02294 static const char *strefresher2str(enum st_refresher r);
02295 static int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref);
02296 static int parse_minse(const char *p_hdrval, int *const p_interval);
02297 static int st_get_se(struct sip_pvt *, int max);
02298 static enum st_refresher st_get_refresher(struct sip_pvt *);
02299 static enum st_mode st_get_mode(struct sip_pvt *);
02300 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p);
02301 
02302 
02303 /*! \brief Definition of this channel for PBX channel registration */
02304 static const struct ast_channel_tech sip_tech = {
02305    .type = "SIP",
02306    .description = "Session Initiation Protocol (SIP)",
02307    .capabilities = AST_FORMAT_AUDIO_MASK, /* all audio formats */
02308    .properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER,
02309    .requester = sip_request_call,         /* called with chan unlocked */
02310    .devicestate = sip_devicestate,        /* called with chan unlocked (not chan-specific) */
02311    .call = sip_call,       /* called with chan locked */
02312    .send_html = sip_sendhtml,
02313    .hangup = sip_hangup,         /* called with chan locked */
02314    .answer = sip_answer,         /* called with chan locked */
02315    .read = sip_read,       /* called with chan locked */
02316    .write = sip_write,        /* called with chan locked */
02317    .write_video = sip_write,     /* called with chan locked */
02318    .write_text = sip_write,
02319    .indicate = sip_indicate,     /* called with chan locked */
02320    .transfer = sip_transfer,     /* called with chan locked */
02321    .fixup = sip_fixup,        /* called with chan locked */
02322    .send_digit_begin = sip_senddigit_begin,  /* called with chan unlocked */
02323    .send_digit_end = sip_senddigit_end,
02324    .bridge = ast_rtp_bridge,        /* XXX chan unlocked ? */
02325    .early_bridge = ast_rtp_early_bridge,
02326    .send_text = sip_sendtext,    /* called with chan locked */
02327    .func_channel_read = acf_channel_read,
02328    .queryoption = sip_queryoption,
02329    .get_pvt_uniqueid = sip_get_callid,
02330 };
02331 
02332 /*! \brief This version of the sip channel tech has no send_digit_begin
02333  * callback so that the core knows that the channel does not want
02334  * DTMF BEGIN frames.
02335  * The struct is initialized just before registering the channel driver,
02336  * and is for use with channels using SIP INFO DTMF.
02337  */
02338 static struct ast_channel_tech sip_tech_info;
02339 
02340 
02341 /*! \brief Working TLS connection configuration */
02342 static struct ast_tls_config sip_tls_cfg;
02343 
02344 /*! \brief Default TLS connection configuration */
02345 static struct ast_tls_config default_tls_cfg;
02346 
02347 /*! \brief The TCP server definition */
02348 static struct ast_tcptls_session_args sip_tcp_desc = {
02349    .accept_fd = -1,
02350    .master = AST_PTHREADT_NULL,
02351    .tls_cfg = NULL,
02352    .poll_timeout = -1,
02353    .name = "sip tcp server",
02354    .accept_fn = ast_tcptls_server_root,
02355    .worker_fn = sip_tcp_worker_fn,
02356 };
02357 
02358 /*! \brief The TCP/TLS server definition */
02359 static struct ast_tcptls_session_args sip_tls_desc = {
02360    .accept_fd = -1,
02361    .master = AST_PTHREADT_NULL,
02362    .tls_cfg = &sip_tls_cfg,
02363    .poll_timeout = -1,
02364    .name = "sip tls server",
02365    .accept_fn = ast_tcptls_server_root,
02366    .worker_fn = sip_tcp_worker_fn,
02367 };
02368 
02369 /* wrapper macro to tell whether t points to one of the sip_tech descriptors */
02370 #define IS_SIP_TECH(t)  ((t) == &sip_tech || (t) == &sip_tech_info)
02371 
02372 /*! \brief map from an integer value to a string.
02373  * If no match is found, return errorstring
02374  */
02375 static const char *map_x_s(const struct _map_x_s *table, int x, const char *errorstring)
02376 {
02377    const struct _map_x_s *cur;
02378 
02379    for (cur = table; cur->s; cur++)
02380       if (cur->x == x)
02381          return cur->s;
02382    return errorstring;
02383 }
02384 
02385 /*! \brief map from a string to an integer value, case insensitive.
02386  * If no match is found, return errorvalue.
02387  */
02388 static int map_s_x(const struct _map_x_s *table, const char *s, int errorvalue)
02389 {
02390    const struct _map_x_s *cur;
02391 
02392    for (cur = table; cur->s; cur++)
02393       if (!strcasecmp(cur->s, s))
02394          return cur->x;
02395    return errorvalue;
02396 }
02397 
02398 
02399 /*! \brief Interface structure with callbacks used to connect to RTP module */
02400 static struct ast_rtp_protocol sip_rtp = {
02401    .type = "SIP",
02402    .get_rtp_info = sip_get_rtp_peer,
02403    .get_vrtp_info = sip_get_vrtp_peer,
02404    .get_trtp_info = sip_get_trtp_peer,
02405    .set_rtp_peer = sip_set_rtp_peer,
02406    .get_codec = sip_get_codec,
02407 };
02408 
02409 
02410 static void tcptls_packet_destructor(void *obj)
02411 {
02412    struct tcptls_packet *packet = obj;
02413 
02414    ast_free(packet->data);
02415 }
02416 
02417 static void sip_tcptls_client_args_destructor(void *obj)
02418 {
02419    struct ast_tcptls_session_args *args = obj;
02420    if (args->tls_cfg) {
02421       ast_free(args->tls_cfg->certfile);
02422       ast_free(args->tls_cfg->cipher);
02423       ast_free(args->tls_cfg->cafile);
02424       ast_free(args->tls_cfg->capath);
02425    }
02426    ast_free(args->tls_cfg);
02427    ast_free((char *) args->name);
02428 }
02429 
02430 static void sip_threadinfo_destructor(void *obj)
02431 {
02432    struct sip_threadinfo *th = obj;
02433    struct tcptls_packet *packet;
02434    if (th->alert_pipe[1] > -1) {
02435       close(th->alert_pipe[0]);
02436    }
02437    if (th->alert_pipe[1] > -1) {
02438       close(th->alert_pipe[1]);
02439    }
02440    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02441 
02442    while ((packet = AST_LIST_REMOVE_HEAD(&th->packet_q, entry))) {
02443       ao2_t_ref(packet, -1, "thread destruction, removing packet from frame queue");
02444    }
02445 
02446    if (th->tcptls_session) {
02447       ao2_t_ref(th->tcptls_session, -1, "remove tcptls_session for sip_threadinfo object");
02448    }
02449 }
02450 
02451 /*! \brief creates a sip_threadinfo object and links it into the threadt table. */
02452 static struct sip_threadinfo *sip_threadinfo_create(struct ast_tcptls_session_instance *tcptls_session, int transport)
02453 {
02454    struct sip_threadinfo *th;
02455 
02456    if (!tcptls_session || !(th = ao2_alloc(sizeof(*th), sip_threadinfo_destructor))) {
02457       return NULL;
02458    }
02459 
02460    th->alert_pipe[0] = th->alert_pipe[1] = -1;
02461 
02462    if (pipe(th->alert_pipe) == -1) {
02463       ao2_t_ref(th, -1, "Failed to open alert pipe on sip_threadinfo");
02464       ast_log(LOG_ERROR, "Could not create sip alert pipe in tcptls thread, error %s\n", strerror(errno));
02465       return NULL;
02466    }
02467    ao2_t_ref(tcptls_session, +1, "tcptls_session ref for sip_threadinfo object");
02468    th->tcptls_session = tcptls_session;
02469    th->type = transport ? transport : (tcptls_session->ssl ? SIP_TRANSPORT_TLS: SIP_TRANSPORT_TCP);
02470    ao2_t_link(threadt, th, "Adding new tcptls helper thread");
02471    ao2_t_ref(th, -1, "Decrementing threadinfo ref from alloc, only table ref remains");
02472    return th;
02473 }
02474 
02475 /*! \brief used to indicate to a tcptls thread that data is ready to be written */
02476 static int sip_tcptls_write(struct ast_tcptls_session_instance *tcptls_session, const void *buf, size_t len)
02477 {
02478    int res = len;
02479    struct sip_threadinfo *th = NULL;
02480    struct tcptls_packet *packet = NULL;
02481    struct sip_threadinfo tmp = {
02482       .tcptls_session = tcptls_session,
02483    };
02484    enum sip_tcptls_alert alert = TCPTLS_ALERT_DATA;
02485 
02486    if (!tcptls_session) {
02487       return XMIT_ERROR;
02488    }
02489 
02490    ast_mutex_lock(&tcptls_session->lock);
02491 
02492    if ((tcptls_session->fd == -1) ||
02493       !(th = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread")) ||
02494       !(packet = ao2_alloc(sizeof(*packet), tcptls_packet_destructor)) ||
02495       !(packet->data = ast_str_create(len))) {
02496       goto tcptls_write_setup_error;
02497    }
02498 
02499    /* goto tcptls_write_error should _NOT_ be used beyond this point */
02500    ast_str_set(&packet->data, 0, "%s", (char *) buf);
02501    packet->len = len;
02502 
02503    /* alert tcptls thread handler that there is a packet to be sent.
02504     * must lock the thread info object to guarantee control of the
02505     * packet queue */
02506    ao2_lock(th);
02507    if (write(th->alert_pipe[1], &alert, sizeof(alert)) == -1) {
02508       ast_log(LOG_ERROR, "write() to alert pipe failed: %s\n", strerror(errno));
02509       ao2_t_ref(packet, -1, "could not write to alert pipe, remove packet");
02510       packet = NULL;
02511       res = XMIT_ERROR;
02512    } else { /* it is safe to queue the frame after issuing the alert when we hold the threadinfo lock */
02513       AST_LIST_INSERT_TAIL(&th->packet_q, packet, entry);
02514    }
02515    ao2_unlock(th);
02516 
02517    ast_mutex_unlock(&tcptls_session->lock);
02518    ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo object after finding it");
02519    return res;
02520 
02521 tcptls_write_setup_error:
02522    if (th) {
02523       ao2_t_ref(th, -1, "In sip_tcptls_write, unref threadinfo obj, could not create packet");
02524    }
02525    if (packet) {
02526       ao2_t_ref(packet, -1, "could not allocate packet's data");
02527    }
02528    ast_mutex_unlock(&tcptls_session->lock);
02529 
02530    return XMIT_ERROR;
02531 }
02532 
02533 /*! \brief SIP TCP connection handler */
02534 static void *sip_tcp_worker_fn(void *data)
02535 {
02536    struct ast_tcptls_session_instance *tcptls_session = data;
02537 
02538    return _sip_tcp_helper_thread(NULL, tcptls_session);
02539 }
02540 
02541 /*! \brief SIP TCP thread management function */
02542 static void *_sip_tcp_helper_thread(struct sip_pvt *pvt, struct ast_tcptls_session_instance *tcptls_session) 
02543 {
02544    int res, cl;
02545    struct sip_request req = { 0, } , reqcpy = { 0, };
02546    struct sip_threadinfo *me = NULL;
02547    char buf[1024] = "";
02548    struct pollfd fds[2] = { { 0 }, { 0 }, };
02549    struct ast_tcptls_session_args *ca = NULL;
02550 
02551    /* If this is a server session, then the connection has already been setup,
02552     * simply create the threadinfo object so we can access this thread for writing.
02553     * 
02554     * if this is a client connection more work must be done.
02555     * 1. We own the parent session args for a client connection.  This pointer needs
02556     *    to be held on to so we can decrement it's ref count on thread destruction.
02557     * 2. The threadinfo object was created before this thread was launched, however
02558     *    it must be found within the threadt table.
02559     * 3. Last, the tcptls_session must be started.
02560     */
02561    if (!tcptls_session->client) {
02562       if (!(me = sip_threadinfo_create(tcptls_session, tcptls_session->ssl ? SIP_TRANSPORT_TLS : SIP_TRANSPORT_TCP))) {
02563          goto cleanup;
02564       }
02565       ao2_t_ref(me, +1, "Adding threadinfo ref for tcp_helper_thread");
02566    } else {
02567       struct sip_threadinfo tmp = {
02568          .tcptls_session = tcptls_session,
02569       };
02570 
02571       if ((!(ca = tcptls_session->parent)) ||
02572          (!(me = ao2_t_find(threadt, &tmp, OBJ_POINTER, "ao2_find, getting sip_threadinfo in tcp helper thread"))) ||
02573          (!(tcptls_session = ast_tcptls_client_start(tcptls_session)))) {
02574          goto cleanup;
02575       }
02576    }
02577 
02578    me->threadid = pthread_self();
02579    ast_debug(2, "Starting thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02580 
02581    /* set up pollfd to watch for reads on both the socket and the alert_pipe */
02582    fds[0].fd = tcptls_session->fd;
02583    fds[1].fd = me->alert_pipe[0];
02584    fds[0].events = fds[1].events = POLLIN | POLLPRI;
02585 
02586    if (!(req.data = ast_str_create(SIP_MIN_PACKET)))
02587       goto cleanup;
02588    if (!(reqcpy.data = ast_str_create(SIP_MIN_PACKET)))
02589       goto cleanup;
02590 
02591    for (;;) {
02592       struct ast_str *str_save;
02593 
02594       res = ast_poll(fds, 2, -1); /* polls for both socket and alert_pipe */
02595       if (res < 0) {
02596          ast_debug(2, "SIP %s server :: ast_wait_for_input returned %d\n", tcptls_session->ssl ? "SSL": "TCP", res);
02597          goto cleanup;
02598       }
02599 
02600       /* handle the socket event, check for both reads from the socket fd,
02601        * and writes from alert_pipe fd */
02602       if (fds[0].revents) { /* there is data on the socket to be read */
02603 
02604          fds[0].revents = 0;
02605 
02606          /* clear request structure */
02607          str_save = req.data;
02608          memset(&req, 0, sizeof(req));
02609          req.data = str_save;
02610          ast_str_reset(req.data);
02611 
02612          str_save = reqcpy.data;
02613          memset(&reqcpy, 0, sizeof(reqcpy));
02614          reqcpy.data = str_save;
02615          ast_str_reset(reqcpy.data);
02616 
02617          memset(buf, 0, sizeof(buf));
02618 
02619          if (tcptls_session->ssl) {
02620             set_socket_transport(&req.socket, SIP_TRANSPORT_TLS);
02621             req.socket.port = htons(ourport_tls);
02622          } else {
02623             set_socket_transport(&req.socket, SIP_TRANSPORT_TCP);
02624             req.socket.port = htons(ourport_tcp);
02625          }
02626          req.socket.fd = tcptls_session->fd;
02627 
02628          /* Read in headers one line at a time */
02629          while (req.len < 4 || strncmp(REQ_OFFSET_TO_STR(&req, len - 4), "\r\n\r\n", 4)) {
02630             ast_mutex_lock(&tcptls_session->lock);
02631             if (!fgets(buf, sizeof(buf), tcptls_session->f)) {
02632                ast_mutex_unlock(&tcptls_session->lock);
02633                goto cleanup;
02634             }
02635             ast_mutex_unlock(&tcptls_session->lock);
02636             if (me->stop)
02637                 goto cleanup;
02638             ast_str_append(&req.data, 0, "%s", buf);
02639             req.len = req.data->used;
02640          }
02641          copy_request(&reqcpy, &req);
02642          parse_request(&reqcpy);
02643          /* In order to know how much to read, we need the content-length header */
02644          if (sscanf(get_header(&reqcpy, "Content-Length"), "%30d", &cl)) {
02645             while (cl > 0) {
02646                size_t bytes_read;
02647                ast_mutex_lock(&tcptls_session->lock);
02648                if (!(bytes_read = fread(buf, 1, MIN(sizeof(buf) - 1, cl), tcptls_session->f))) {
02649                   ast_mutex_unlock(&tcptls_session->lock);
02650                   goto cleanup;
02651                }
02652                buf[bytes_read] = '\0';
02653                ast_mutex_unlock(&tcptls_session->lock);
02654                if (me->stop)
02655                   goto cleanup;
02656                cl -= strlen(buf);
02657                ast_str_append(&req.data, 0, "%s", buf);
02658                req.len = req.data->used;
02659             }
02660          }
02661          /*! \todo XXX If there's no Content-Length or if the content-length and what
02662                we receive is not the same - we should generate an error */
02663 
02664          req.socket.tcptls_session = tcptls_session;
02665          handle_request_do(&req, &tcptls_session->remote_address);
02666       }
02667       if (fds[1].revents) { /* alert_pipe indicates there is data in the send queue to be sent */
02668          enum sip_tcptls_alert alert;
02669          struct tcptls_packet *packet;
02670 
02671          fds[1].revents = 0;
02672 
02673          if (read(me->alert_pipe[0], &alert, sizeof(alert)) == -1) {
02674             ast_log(LOG_ERROR, "read() failed: %s\n", strerror(errno));
02675             continue;
02676          }
02677 
02678          switch (alert) {
02679          case TCPTLS_ALERT_STOP:
02680             goto cleanup;
02681          case TCPTLS_ALERT_DATA:
02682             ao2_lock(me);
02683             if (!(packet = AST_LIST_REMOVE_HEAD(&me->packet_q, entry))) {
02684                ast_log(LOG_WARNING, "TCPTLS thread alert_pipe indicated packet should be sent, but frame_q is empty");
02685             } else if (ast_tcptls_server_write(tcptls_session, ast_str_buffer(packet->data), packet->len) == -1) {
02686                ast_log(LOG_WARNING, "Failure to write to tcp/tls socket\n");
02687             }
02688 
02689             if (packet) {
02690                ao2_t_ref(packet, -1, "tcptls packet sent, this is no longer needed");
02691             }
02692             ao2_unlock(me);
02693             break;
02694          default:
02695             ast_log(LOG_ERROR, "Unknown tcptls thread alert '%d'\n", alert);
02696          }
02697       }
02698    }
02699 
02700    ast_debug(2, "Shutting down thread for %s server\n", tcptls_session->ssl ? "SSL" : "TCP");
02701 
02702 cleanup:
02703    if (me) {
02704       ao2_t_unlink(threadt, me, "Removing tcptls helper thread, thread is closing");
02705       ao2_t_ref(me, -1, "Removing tcp_helper_threads threadinfo ref");
02706    }
02707    if (reqcpy.data) {
02708       ast_free(reqcpy.data);
02709    }
02710 
02711    if (req.data) {
02712       ast_free(req.data);
02713       req.data = NULL;
02714    }
02715 
02716    /* if client, we own the parent session arguments and must decrement ref */
02717    if (ca) {
02718       ao2_t_ref(ca, -1, "closing tcptls thread, getting rid of client tcptls_session arguments");
02719    }
02720 
02721    if (tcptls_session) {
02722       ast_mutex_lock(&tcptls_session->lock);
02723       if (tcptls_session->f) {
02724          fclose(tcptls_session->f);
02725          tcptls_session->f = NULL;
02726       }
02727       if (tcptls_session->fd != -1) {
02728          close(tcptls_session->fd);
02729          tcptls_session->fd = -1;
02730       }
02731       tcptls_session->parent = NULL;
02732       ast_mutex_unlock(&tcptls_session->lock);
02733 
02734       ao2_ref(tcptls_session, -1);
02735       tcptls_session = NULL;
02736    }
02737 
02738    return NULL;
02739 }
02740 
02741 
02742 /*!
02743  * helper functions to unreference various types of objects.
02744  * By handling them this way, we don't have to declare the
02745  * destructor on each call, which removes the chance of errors.
02746  */
02747 static void *unref_peer(struct sip_peer *peer, char *tag)
02748 {
02749    ao2_t_ref(peer, -1, tag);
02750    return NULL;
02751 }
02752 
02753 static struct sip_peer *ref_peer(struct sip_peer *peer, char *tag)
02754 {
02755    ao2_t_ref(peer, 1, tag);
02756    return peer;
02757 }
02758 
02759 /*! \brief maintain proper refcounts for a sip_pvt's outboundproxy
02760  *
02761  * This function sets pvt's outboundproxy pointer to the one referenced
02762  * by the proxy parameter. Because proxy may be a refcounted object, and
02763  * because pvt's old outboundproxy may also be a refcounted object, we need
02764  * to maintain the proper refcounts.
02765  *
02766  * \param pvt The sip_pvt for which we wish to set the outboundproxy
02767  * \param proxy The sip_proxy which we will point pvt towards.
02768  * \return Returns void
02769  */
02770 static struct sip_proxy *ref_proxy(struct sip_pvt *pvt, struct sip_proxy *proxy)
02771 {
02772    struct sip_proxy *old_obproxy = pvt->outboundproxy;
02773    /* Cool, now get the refs correct */
02774    if (proxy && proxy != &global_outboundproxy) {
02775       ao2_ref(proxy, +1);
02776    }
02777    pvt->outboundproxy = proxy;
02778    if (old_obproxy && old_obproxy != &global_outboundproxy) {
02779       ao2_ref(old_obproxy, -1);
02780    }
02781    return proxy;
02782 }
02783 
02784 /*!
02785  * \brief Unlink a dialog from the dialogs container, as well as any other places
02786  * that it may be currently stored.
02787  *
02788  * \note A reference to the dialog must be held before calling this function, and this
02789  * function does not release that reference.
02790  */
02791 static void *dialog_unlink_all(struct sip_pvt *dialog, int lockowner, int lockdialoglist)
02792 {
02793    struct sip_pkt *cp;
02794 
02795    dialog_ref(dialog, "Let's bump the count in the unlink so it doesn't accidentally become dead before we are done");
02796 
02797    ao2_t_unlink(dialogs, dialog, "unlinking dialog via ao2_unlink");
02798 
02799    /* Unlink us from the owner (channel) if we have one */
02800    if (dialog->owner) {
02801       if (lockowner)
02802          ast_channel_lock(dialog->owner);
02803       ast_debug(1, "Detaching from channel %s\n", dialog->owner->name);
02804       dialog->owner->tech_pvt = dialog_unref(dialog->owner->tech_pvt, "resetting channel dialog ptr in unlink_all");
02805       if (lockowner)
02806          ast_channel_unlock(dialog->owner);
02807    }
02808    if (dialog->registry) {
02809       if (dialog->registry->call == dialog)
02810          dialog->registry->call = dialog_unref(dialog->registry->call, "nulling out the registry's call dialog field in unlink_all");
02811       dialog->registry = registry_unref(dialog->registry, "delete dialog->registry");
02812    }
02813    if (dialog->stateid > -1) {
02814       ast_extension_state_del(dialog->stateid, NULL);
02815       dialog_unref(dialog, "removing extension_state, should unref the associated dialog ptr that was stored there.");
02816       dialog->stateid = -1; /* shouldn't we 'zero' this out? */
02817    }
02818    /* Remove link from peer to subscription of MWI */
02819    if (dialog->relatedpeer && dialog->relatedpeer->mwipvt == dialog)
02820       dialog->relatedpeer->mwipvt = dialog_unref(dialog->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
02821    if (dialog->relatedpeer && dialog->relatedpeer->call == dialog)
02822       dialog->relatedpeer->call = dialog_unref(dialog->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
02823 
02824    /* remove all current packets in this dialog */
02825    while((cp = dialog->packets)) {
02826       dialog->packets = dialog->packets->next;
02827       AST_SCHED_DEL(sched, cp->retransid);
02828       dialog_unref(cp->owner, "remove all current packets in this dialog, and the pointer to the dialog too as part of __sip_destroy");
02829       if (cp->data) {
02830          ast_free(cp->data);
02831       }
02832       ast_free(cp);
02833    }
02834 
02835    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"));
02836 
02837    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"));
02838    
02839    if (dialog->autokillid > -1)
02840       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"));
02841 
02842    if (dialog->request_queue_sched_id > -1) {
02843       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"));
02844    }
02845 
02846    AST_SCHED_DEL_UNREF(sched, dialog->provisional_keepalive_sched_id, dialog_unref(dialog, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
02847 
02848    if (dialog->t38id > -1) {
02849       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"));
02850    }
02851 
02852    dialog_unref(dialog, "Let's unbump the count in the unlink so the poor pvt can disappear if it is time");
02853    return NULL;
02854 }
02855 
02856 static void *registry_unref(struct sip_registry *reg, char *tag)
02857 {
02858    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount - 1);
02859    ASTOBJ_UNREF(reg, sip_registry_destroy);
02860    return NULL;
02861 }
02862 
02863 /*! \brief Add object reference to SIP registry */
02864 static struct sip_registry *registry_addref(struct sip_registry *reg, char *tag)
02865 {
02866    ast_debug(3, "SIP Registry %s: refcount now %d\n", reg->hostname, reg->refcount + 1);
02867    return ASTOBJ_REF(reg); /* Add pointer to registry in packet */
02868 }
02869 
02870 /*! \brief Interface structure with callbacks used to connect to UDPTL module*/
02871 static struct ast_udptl_protocol sip_udptl = {
02872    type: "SIP",
02873    get_udptl_info: sip_get_udptl_peer,
02874    set_udptl_peer: sip_set_udptl_peer,
02875 };
02876 
02877 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
02878    __attribute__((format(printf, 2, 3)));
02879 
02880 
02881 /*! \brief Convert transfer status to string */
02882 static const char *referstatus2str(enum referstatus rstatus)
02883 {
02884    return map_x_s(referstatusstrings, rstatus, "");
02885 }
02886 
02887 /*! \brief Initialize the initital request packet in the pvt structure.
02888    This packet is used for creating replies and future requests in
02889    a dialog */
02890 static void initialize_initreq(struct sip_pvt *p, struct sip_request *req)
02891 {
02892    if (p->initreq.headers)
02893       ast_debug(1, "Initializing already initialized SIP dialog %s (presumably reinvite)\n", p->callid);
02894    else
02895       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
02896    /* Use this as the basis */
02897    copy_request(&p->initreq, req);
02898    parse_request(&p->initreq);
02899    if (req->debug)
02900       ast_verbose("Initreq: %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
02901 }
02902 
02903 /*! \brief Encapsulate setting of SIP_ALREADYGONE to be able to trace it with debugging */
02904 static void sip_alreadygone(struct sip_pvt *dialog)
02905 {
02906    ast_debug(3, "Setting SIP_ALREADYGONE on dialog %s\n", dialog->callid);
02907    dialog->alreadygone = 1;
02908 }
02909 
02910 /*! Resolve DNS srv name or host name in a sip_proxy structure */
02911 static int proxy_update(struct sip_proxy *proxy)
02912 {
02913    /* if it's actually an IP address and not a name,
02914            there's no need for a managed lookup */
02915    if (!inet_aton(proxy->name, &proxy->ip.sin_addr)) {
02916       /* Ok, not an IP address, then let's check if it's a domain or host */
02917       /* XXX Todo - if we have proxy port, don't do SRV */
02918       if (ast_get_ip_or_srv(&proxy->ip, proxy->name, global_srvlookup ? "_sip._udp" : NULL) < 0) {
02919          ast_log(LOG_WARNING, "Unable to locate host '%s'\n", proxy->name);
02920          return FALSE;
02921       }
02922    }
02923    proxy->last_dnsupdate = time(NULL);
02924    return TRUE;
02925 }
02926 
02927 /*! \brief converts ascii port to int representation. If no
02928  *  pt buffer is provided or the pt has errors when being converted
02929  *  to an int value, the port provided as the standard is used.
02930  */
02931 static int port_str2int(const char *pt, unsigned int standard)
02932 {
02933    int port = standard;
02934    if (ast_strlen_zero(pt) || (sscanf(pt, "%30d", &port) != 1) || (port < 1) || (port > 65535)) {
02935       port = standard;
02936    }
02937 
02938    return port;
02939 }
02940 
02941 /*! \brief Allocate and initialize sip proxy */
02942 static struct sip_proxy *proxy_allocate(char *name, char *port, int force)
02943 {
02944    struct sip_proxy *proxy;
02945 
02946    if (ast_strlen_zero(name)) {
02947       return NULL;
02948    }
02949 
02950    proxy = ao2_alloc(sizeof(*proxy), NULL);
02951    if (!proxy)
02952       return NULL;
02953    proxy->force = force;
02954    ast_copy_string(proxy->name, name, sizeof(proxy->name));
02955    proxy->ip.sin_port = htons(port_str2int(port, STANDARD_SIP_PORT));
02956    proxy_update(proxy);
02957    return proxy;
02958 }
02959 
02960 /*! \brief Get default outbound proxy or global proxy */
02961 static struct sip_proxy *obproxy_get(struct sip_pvt *dialog, struct sip_peer *peer)
02962 {
02963    if (peer && peer->outboundproxy) {
02964       if (sipdebug)
02965          ast_debug(1, "OBPROXY: Applying peer OBproxy to this call\n");
02966       append_history(dialog, "OBproxy", "Using peer obproxy %s", peer->outboundproxy->name);
02967       return peer->outboundproxy;
02968    }
02969    if (global_outboundproxy.name[0]) {
02970       if (sipdebug)
02971          ast_debug(1, "OBPROXY: Applying global OBproxy to this call\n");
02972       append_history(dialog, "OBproxy", "Using global obproxy %s", global_outboundproxy.name);
02973       return &global_outboundproxy;
02974    }
02975    if (sipdebug)
02976       ast_debug(1, "OBPROXY: Not applying OBproxy to this call\n");
02977    return NULL;
02978 }
02979 
02980 /*! \brief returns true if 'name' (with optional trailing whitespace)
02981  * matches the sip method 'id'.
02982  * Strictly speaking, SIP methods are case SENSITIVE, but we do
02983  * a case-insensitive comparison to be more tolerant.
02984  * following Jon Postel's rule: Be gentle in what you accept, strict with what you send
02985  */
02986 static int method_match(enum sipmethod id, const char *name)
02987 {
02988    int len = strlen(sip_methods[id].text);
02989    int l_name = name ? strlen(name) : 0;
02990    /* true if the string is long enough, and ends with whitespace, and matches */
02991    return (l_name >= len && name[len] < 33 &&
02992       !strncasecmp(sip_methods[id].text, name, len));
02993 }
02994 
02995 /*! \brief  find_sip_method: Find SIP method from header */
02996 static int find_sip_method(const char *msg)
02997 {
02998    int i, res = 0;
02999    
03000    if (ast_strlen_zero(msg))
03001       return 0;
03002    for (i = 1; i < ARRAY_LEN(sip_methods) && !res; i++) {
03003       if (method_match(i, msg))
03004          res = sip_methods[i].id;
03005    }
03006    return res;
03007 }
03008 
03009 /*! \brief Parse supported header in incoming packet */
03010 static unsigned int parse_sip_options(struct sip_pvt *pvt, const char *supported)
03011 {
03012    char *next, *sep;
03013    char *temp;
03014    unsigned int profile = 0;
03015    int i, found;
03016 
03017    if (ast_strlen_zero(supported) )
03018       return 0;
03019    temp = ast_strdupa(supported);
03020 
03021    if (sipdebug)
03022       ast_debug(3, "Begin: parsing SIP \"Supported: %s\"\n", supported);
03023 
03024    for (next = temp; next; next = sep) {
03025       found = FALSE;
03026       if ( (sep = strchr(next, ',')) != NULL)
03027          *sep++ = '\0';
03028       next = ast_skip_blanks(next);
03029       if (sipdebug)
03030          ast_debug(3, "Found SIP option: -%s-\n", next);
03031       for (i = 0; i < ARRAY_LEN(sip_options); i++) {
03032          if (!strcasecmp(next, sip_options[i].text)) {
03033             profile |= sip_options[i].id;
03034             found = TRUE;
03035             if (sipdebug)
03036                ast_debug(3, "Matched SIP option: %s\n", next);
03037             break;
03038          }
03039       }
03040 
03041       /* This function is used to parse both Suported: and Require: headers.
03042       Let the caller of this function know that an unknown option tag was 
03043       encountered, so that if the UAC requires it then the request can be 
03044       rejected with a 420 response. */
03045       if (!found)
03046          profile |= SIP_OPT_UNKNOWN;
03047 
03048       if (!found && sipdebug) {
03049          if (!strncasecmp(next, "x-", 2))
03050             ast_debug(3, "Found private SIP option, not supported: %s\n", next);
03051          else
03052             ast_debug(3, "Found no match for SIP option: %s (Please file bug report!)\n", next);
03053       }
03054    }
03055 
03056    if (pvt)
03057       pvt->sipoptions = profile;
03058    return profile;
03059 }
03060 
03061 /*! \brief See if we pass debug IP filter */
03062 static inline int sip_debug_test_addr(const struct sockaddr_in *addr) 
03063 {
03064    if (!sipdebug)
03065       return 0;
03066    if (debugaddr.sin_addr.s_addr) {
03067       if (((ntohs(debugaddr.sin_port) != 0)
03068          && (debugaddr.sin_port != addr->sin_port))
03069          || (debugaddr.sin_addr.s_addr != addr->sin_addr.s_addr))
03070          return 0;
03071    }
03072    return 1;
03073 }
03074 
03075 /*! \brief The real destination address for a write */
03076 static const struct sockaddr_in *sip_real_dst(const struct sip_pvt *p)
03077 {
03078    if (p->outboundproxy)
03079       return &p->outboundproxy->ip;
03080 
03081    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? &p->recv : &p->sa;
03082 }
03083 
03084 /*! \brief Display SIP nat mode */
03085 static const char *sip_nat_mode(const struct sip_pvt *p)
03086 {
03087    return ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE ? "NAT" : "no NAT";
03088 }
03089 
03090 /*! \brief Test PVT for debugging output */
03091 static inline int sip_debug_test_pvt(struct sip_pvt *p) 
03092 {
03093    if (!sipdebug)
03094       return 0;
03095    return sip_debug_test_addr(sip_real_dst(p));
03096 }
03097    /*! \brief Return int representing a bit field of transport types found in const char *transport */
03098    static int get_transport_str2enum(const char *transport)
03099    {
03100    int res = 0;
03101 
03102    if (ast_strlen_zero(transport)) {
03103       return res;
03104    }
03105 
03106    if (!strcasecmp(transport, "udp")) {
03107       res |= SIP_TRANSPORT_UDP;
03108    }
03109    if (!strcasecmp(transport, "tcp")) {
03110       res |= SIP_TRANSPORT_TCP;
03111    }
03112    if (!strcasecmp(transport, "tls")) {
03113       res |= SIP_TRANSPORT_TLS;
03114    }
03115 
03116    return res;
03117 }
03118 
03119 static inline const char *get_transport_list(struct sip_peer *peer) {
03120    switch (peer->transports) {
03121       case SIP_TRANSPORT_UDP:
03122          return "UDP";
03123       case SIP_TRANSPORT_TCP:
03124          return "TCP";
03125       case SIP_TRANSPORT_TLS:
03126          return "TLS";
03127       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TCP:
03128          return "TCP,UDP";
03129       case SIP_TRANSPORT_UDP | SIP_TRANSPORT_TLS:
03130          return "TLS,UDP";
03131       case SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS:
03132          return "TLS,TCP";
03133       default:
03134          return peer->transports ? 
03135             "TLS,TCP,UDP" : "UNKNOWN"; 
03136    }
03137 }
03138 
03139 static inline const char *get_transport(enum sip_transport t)
03140 {
03141    switch (t) {
03142    case SIP_TRANSPORT_UDP:
03143       return "UDP";
03144    case SIP_TRANSPORT_TCP:
03145       return "TCP";
03146    case SIP_TRANSPORT_TLS:
03147       return "TLS";
03148    }
03149 
03150    return "UNKNOWN";
03151 }
03152 
03153 static inline const char *get_transport_pvt(struct sip_pvt *p)
03154 {
03155    if (p->outboundproxy && p->outboundproxy->transport) {
03156       set_socket_transport(&p->socket, p->outboundproxy->transport);
03157    }
03158 
03159    return get_transport(p->socket.type);
03160 }
03161 
03162 /*! \brief Transmit SIP message 
03163    Sends a SIP request or response on a given socket (in the pvt)
03164    Called by retrans_pkt, send_request, send_response and 
03165    __sip_reliable_xmit
03166 */
03167 static int __sip_xmit(struct sip_pvt *p, struct ast_str *data, int len)
03168 {
03169    int res = 0;
03170    const struct sockaddr_in *dst = sip_real_dst(p);
03171 
03172    ast_debug(1, "Trying to put '%.11s' onto %s socket destined for %s:%d\n", data->str, get_transport_pvt(p), ast_inet_ntoa(dst->sin_addr), htons(dst->sin_port));
03173 
03174    if (sip_prepare_socket(p) < 0)
03175       return XMIT_ERROR;
03176 
03177    if (p->socket.type == SIP_TRANSPORT_UDP) {
03178       res = sendto(p->socket.fd, data->str, len, 0, (const struct sockaddr *)dst, sizeof(struct sockaddr_in));
03179    } else if (p->socket.tcptls_session) {
03180       res = sip_tcptls_write(p->socket.tcptls_session, data->str, len);
03181    } else {
03182       ast_debug(2, "Socket type is TCP but no tcptls_session is present to write to\n");
03183       return XMIT_ERROR;
03184    }
03185 
03186    if (res == -1) {
03187       switch (errno) {
03188       case EBADF:       /* Bad file descriptor - seems like this is generated when the host exist, but doesn't accept the UDP packet */
03189       case EHOSTUNREACH:   /* Host can't be reached */
03190       case ENETDOWN:       /* Inteface down */
03191       case ENETUNREACH: /* Network failure */
03192       case ECONNREFUSED:      /* ICMP port unreachable */ 
03193          res = XMIT_ERROR; /* Don't bother with trying to transmit again */
03194       }
03195    }
03196    if (res != len)
03197       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));
03198 
03199    return res;
03200 }
03201 
03202 /*! \brief Build a Via header for a request */
03203 static void build_via(struct sip_pvt *p)
03204 {
03205    /* Work around buggy UNIDEN UIP200 firmware */
03206    const char *rport = ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_RFC3581 ? ";rport" : "";
03207 
03208    /* z9hG4bK is a magic cookie.  See RFC 3261 section 8.1.1.7 */
03209    snprintf(p->via, sizeof(p->via), "SIP/2.0/%s %s:%d;branch=z9hG4bK%08x%s",
03210        get_transport_pvt(p),
03211        ast_inet_ntoa(p->ourip.sin_addr),
03212        ntohs(p->ourip.sin_port), (int) p->branch, rport);
03213 }
03214 
03215 /*! \brief NAT fix - decide which IP address to use for Asterisk server?
03216  *
03217  * Using the localaddr structure built up with localnet statements in sip.conf
03218  * apply it to their address to see if we need to substitute our
03219  * externip or can get away with our internal bindaddr
03220  * 'us' is always overwritten.
03221  */
03222 static void ast_sip_ouraddrfor(struct in_addr *them, struct sockaddr_in *us, struct sip_pvt *p)
03223 {
03224    struct sockaddr_in theirs;
03225    /* Set want_remap to non-zero if we want to remap 'us' to an externally
03226     * reachable IP address and port. This is done if:
03227     * 1. we have a localaddr list (containing 'internal' addresses marked
03228     *    as 'deny', so ast_apply_ha() will return AST_SENSE_DENY on them,
03229     *    and AST_SENSE_ALLOW on 'external' ones);
03230     * 2. either stunaddr or externip is set, so we know what to use as the
03231     *    externally visible address;
03232     * 3. the remote address, 'them', is external;
03233     * 4. the address returned by ast_ouraddrfor() is 'internal' (AST_SENSE_DENY
03234     *    when passed to ast_apply_ha() so it does need to be remapped.
03235     *    This fourth condition is checked later.
03236     */
03237    int want_remap;
03238 
03239    *us = internip;      /* starting guess for the internal address */
03240    /* now ask the system what would it use to talk to 'them' */
03241    ast_ouraddrfor(them, &us->sin_addr);
03242    theirs.sin_addr = *them;
03243 
03244    want_remap = localaddr &&
03245       (externip.sin_addr.s_addr || stunaddr.sin_addr.s_addr) &&
03246       ast_apply_ha(localaddr, &theirs) == AST_SENSE_ALLOW ;
03247 
03248    if (want_remap &&
03249        (!global_matchexterniplocally || !ast_apply_ha(localaddr, us)) ) {
03250       /* if we used externhost or stun, see if it is time to refresh the info */
03251       if (externexpire && time(NULL) >= externexpire) {
03252          if (stunaddr.sin_addr.s_addr) {
03253             ast_stun_request(sipsock, &stunaddr, NULL, &externip);
03254          } else {
03255             if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
03256                ast_log(LOG_NOTICE, "Warning: Re-lookup of '%s' failed!\n", externhost);
03257          }
03258          externexpire = time(NULL) + externrefresh;
03259       }
03260       if (externip.sin_addr.s_addr)
03261          *us = externip;
03262       else
03263          ast_log(LOG_WARNING, "stun failed\n");
03264       ast_debug(1, "Target address %s is not local, substituting externip\n", 
03265          ast_inet_ntoa(*(struct in_addr *)&them->s_addr));
03266    } else if (p) {
03267       /* no remapping, but we bind to a specific address, so use it. */
03268       switch (p->socket.type) {
03269       case SIP_TRANSPORT_TCP:
03270          if (sip_tcp_desc.local_address.sin_addr.s_addr) {
03271             *us = sip_tcp_desc.local_address;
03272          } else {
03273             us->sin_port = sip_tcp_desc.local_address.sin_port;
03274          }
03275          break;
03276       case SIP_TRANSPORT_TLS:
03277          if (sip_tls_desc.local_address.sin_addr.s_addr) {
03278             *us = sip_tls_desc.local_address;
03279          } else {
03280             us->sin_port = sip_tls_desc.local_address.sin_port;
03281          }
03282             break;
03283       case SIP_TRANSPORT_UDP:
03284          /* fall through on purpose */
03285       default:
03286          if (bindaddr.sin_addr.s_addr) {
03287             *us = bindaddr;
03288          }
03289       }
03290    } else if (bindaddr.sin_addr.s_addr) {
03291       *us = bindaddr;
03292    }
03293    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));
03294 }
03295 
03296 /*! \brief Append to SIP dialog history with arg list  */
03297 static __attribute__((format(printf, 2, 0))) void append_history_va(struct sip_pvt *p, const char *fmt, va_list ap)
03298 {
03299    char buf[80], *c = buf; /* max history length */
03300    struct sip_history *hist;
03301    int l;
03302 
03303    vsnprintf(buf, sizeof(buf), fmt, ap);
03304    strsep(&c, "\r\n"); /* Trim up everything after \r or \n */
03305    l = strlen(buf) + 1;
03306    if (!(hist = ast_calloc(1, sizeof(*hist) + l)))
03307       return;
03308    if (!p->history && !(p->history = ast_calloc(1, sizeof(*p->history)))) {
03309       ast_free(hist);
03310       return;
03311    }
03312    memcpy(hist->event, buf, l);
03313    if (p->history_entries == MAX_HISTORY_ENTRIES) {
03314       struct sip_history *oldest;
03315       oldest = AST_LIST_REMOVE_HEAD(p->history, list);
03316       p->history_entries--;
03317       ast_free(oldest);
03318    }
03319    AST_LIST_INSERT_TAIL(p->history, hist, list);
03320    p->history_entries++;
03321 }
03322 
03323 /*! \brief Append to SIP dialog history with arg list  */
03324 static void append_history_full(struct sip_pvt *p, const char *fmt, ...)
03325 {
03326    va_list ap;
03327 
03328    if (!p)
03329       return;
03330 
03331    if (!p->do_history && !recordhistory && !dumphistory)
03332       return;
03333 
03334    va_start(ap, fmt);
03335    append_history_va(p, fmt, ap);
03336    va_end(ap);
03337 
03338    return;
03339 }
03340 
03341 /*! \brief Retransmit SIP message if no answer (Called from scheduler) */
03342 static int retrans_pkt(const void *data)
03343 {
03344    struct sip_pkt *pkt = (struct sip_pkt *)data, *prev, *cur = NULL;
03345    int reschedule = DEFAULT_RETRANS;
03346    int xmitres = 0;
03347    
03348    /* Lock channel PVT */
03349    sip_pvt_lock(pkt->owner);
03350 
03351    if (pkt->retrans < MAX_RETRANS) {
03352       pkt->retrans++;
03353       if (!pkt->timer_t1) {   /* Re-schedule using timer_a and timer_t1 */
03354          if (sipdebug)
03355             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);
03356       } else {
03357          int siptimer_a;
03358 
03359          if (sipdebug)
03360             ast_debug(4, "SIP TIMER: Rescheduling retransmission #%d (%d) %s - %d\n", pkt->retransid, pkt->retrans, sip_methods[pkt->method].text, pkt->method);
03361          if (!pkt->timer_a)
03362             pkt->timer_a = 2 ;
03363          else
03364             pkt->timer_a = 2 * pkt->timer_a;
03365  
03366          /* For non-invites, a maximum of 4 secs */
03367          siptimer_a = pkt->timer_t1 * pkt->timer_a;   /* Double each time */
03368          if (pkt->method != SIP_INVITE && siptimer_a > 4000)
03369             siptimer_a = 4000;
03370       
03371          /* Reschedule re-transmit */
03372          reschedule = siptimer_a;
03373          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);
03374       } 
03375 
03376       if (sip_debug_test_pvt(pkt->owner)) {
03377          const struct sockaddr_in *dst = sip_real_dst(pkt->owner);
03378          ast_verbose("Retransmitting #%d (%s) to %s:%d:\n%s\n---\n",
03379             pkt->retrans, sip_nat_mode(pkt->owner),
03380             ast_inet_ntoa(dst->sin_addr),
03381             ntohs(dst->sin_port), pkt->data->str);
03382       }
03383 
03384       append_history(pkt->owner, "ReTx", "%d %s", reschedule, pkt->data->str);
03385       xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);
03386       sip_pvt_unlock(pkt->owner);
03387       if (xmitres == XMIT_ERROR)
03388          ast_log(LOG_WARNING, "Network error on retransmit in dialog %s\n", pkt->owner->callid);
03389       else 
03390          return  reschedule;
03391    } 
03392    /* Too many retries */
03393    if (pkt->owner && pkt->method != SIP_OPTIONS && xmitres == 0) {
03394       if (pkt->is_fatal || sipdebug)   /* Tell us if it's critical or if we're debugging */
03395          ast_log(LOG_WARNING, "Maximum retries exceeded on transmission %s for seqno %d (%s %s) -- See doc/sip-retransmit.txt.\n",
03396             pkt->owner->callid, pkt->seqno,
03397             pkt->is_fatal ? "Critical" : "Non-critical", pkt->is_resp ? "Response" : "Request");
03398    } else if (pkt->method == SIP_OPTIONS && sipdebug) {
03399          ast_log(LOG_WARNING, "Cancelling retransmit of OPTIONs (call id %s)  -- See doc/sip-retransmit.txt.\n", pkt->owner->callid);
03400 
03401    } 
03402    if (xmitres == XMIT_ERROR) {
03403       ast_log(LOG_WARNING, "Transmit error :: Cancelling transmission on Call ID %s\n", pkt->owner->callid);
03404       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03405    } else 
03406       append_history(pkt->owner, "MaxRetries", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03407       
03408    pkt->retransid = -1;
03409 
03410    if (pkt->is_fatal) {
03411       while(pkt->owner->owner && ast_channel_trylock(pkt->owner->owner)) {
03412          sip_pvt_unlock(pkt->owner);   /* SIP_PVT, not channel */
03413          usleep(1);
03414          sip_pvt_lock(pkt->owner);
03415       }
03416 
03417       if (pkt->owner->owner && !pkt->owner->owner->hangupcause) 
03418          pkt->owner->owner->hangupcause = AST_CAUSE_NO_USER_RESPONSE;
03419       
03420       if (pkt->owner->owner) {
03421          sip_alreadygone(pkt->owner);
03422          ast_log(LOG_WARNING, "Hanging up call %s - no reply to our critical packet (see doc/sip-retransmit.txt).\n", pkt->owner->callid);
03423          ast_queue_hangup_with_cause(pkt->owner->owner, AST_CAUSE_PROTOCOL_ERROR);
03424          ast_channel_unlock(pkt->owner->owner);
03425       } else {
03426          /* If no channel owner, destroy now */
03427 
03428          /* Let the peerpoke system expire packets when the timer expires for poke_noanswer */
03429          if (pkt->method != SIP_OPTIONS && pkt->method != SIP_REGISTER) {
03430             pkt->owner->needdestroy = 1;
03431             sip_alreadygone(pkt->owner);
03432             append_history(pkt->owner, "DialogKill", "Killing this failed dialog immediately");
03433          }
03434       }
03435    }
03436 
03437    if (pkt->method == SIP_BYE) {
03438       /* We're not getting answers on SIP BYE's.  Tear down the call anyway. */
03439       if (pkt->owner->owner) 
03440          ast_channel_unlock(pkt->owner->owner);
03441       append_history(pkt->owner, "ByeFailure", "Remote peer doesn't respond to bye. Destroying call anyway.");
03442       pkt->owner->needdestroy = 1;
03443    }
03444 
03445    /* Remove the packet */
03446    for (prev = NULL, cur = pkt->owner->packets; cur; prev = cur, cur = cur->next) {
03447       if (cur == pkt) {
03448          UNLINK(cur, pkt->owner->packets, prev);
03449          sip_pvt_unlock(pkt->owner);
03450          if (pkt->owner)
03451             pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03452          if (pkt->data)
03453             ast_free(pkt->data);
03454          pkt->data = NULL;
03455          ast_free(pkt);
03456          return 0;
03457       }
03458    }
03459    /* error case */
03460    ast_log(LOG_WARNING, "Weird, couldn't find packet owner!\n");
03461    sip_pvt_unlock(pkt->owner);
03462    return 0;
03463 }
03464 
03465 /*! \brief Transmit packet with retransmits 
03466    \return 0 on success, -1 on failure to allocate packet 
03467 */
03468 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)
03469 {
03470    struct sip_pkt *pkt = NULL;
03471    int siptimer_a = DEFAULT_RETRANS;
03472    int xmitres = 0;
03473    int respid;
03474 
03475    if (sipmethod == SIP_INVITE) {
03476       /* Note this is a pending invite */
03477       p->pendinginvite = seqno;
03478    }
03479 
03480    /* If the transport is something reliable (TCP or TLS) then don't really send this reliably */
03481    /* I removed the code from retrans_pkt that does the same thing so it doesn't get loaded into the scheduler */
03482    /* According to the RFC some packets need to be retransmitted even if its TCP, so this needs to get revisited */
03483    if (!(p->socket.type & SIP_TRANSPORT_UDP)) {
03484       xmitres = __sip_xmit(p, data, len); /* Send packet */
03485       if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03486          append_history(p, "XmitErr", "%s", fatal ? "(Critical)" : "(Non-critical)");
03487          return AST_FAILURE;
03488       } else
03489          return AST_SUCCESS;
03490    }
03491 
03492    if (!(pkt = ast_calloc(1, sizeof(*pkt) + len + 1)))
03493       return AST_FAILURE;
03494    /* copy data, add a terminator and save length */
03495    if (!(pkt->data = ast_str_create(len))) {
03496       ast_free(pkt);
03497       return AST_FAILURE;
03498    }
03499    ast_str_set(&pkt->data, 0, "%s%s", data->str, "\0");
03500    pkt->packetlen = len;
03501    /* copy other parameters from the caller */
03502    pkt->method = sipmethod;
03503    pkt->seqno = seqno;
03504    pkt->is_resp = resp;
03505    pkt->is_fatal = fatal;
03506    pkt->owner = dialog_ref(p, "__sip_reliable_xmit: setting pkt->owner");
03507    pkt->next = p->packets;
03508    p->packets = pkt; /* Add it to the queue */
03509    if (resp) {
03510       /* Parse out the response code */
03511       if (sscanf(ast_str_buffer(pkt->data), "SIP/2.0 %30u", &respid) == 1) {
03512          pkt->response_code = respid;
03513       }
03514    }
03515    pkt->timer_t1 = p->timer_t1;  /* Set SIP timer T1 */
03516    pkt->retransid = -1;
03517    if (pkt->timer_t1)
03518       siptimer_a = pkt->timer_t1 * 2;
03519 
03520    /* Schedule retransmission */
03521    AST_SCHED_REPLACE_VARIABLE(pkt->retransid, sched, siptimer_a, retrans_pkt, pkt, 1);
03522    if (sipdebug)
03523       ast_debug(4, "*** SIP TIMER: Initializing retransmit timer on packet: Id  #%d\n", pkt->retransid);
03524 
03525    xmitres = __sip_xmit(pkt->owner, pkt->data, pkt->packetlen);   /* Send packet */
03526 
03527    if (xmitres == XMIT_ERROR) {  /* Serious network trouble, no need to try again */
03528       append_history(pkt->owner, "XmitErr", "%s", pkt->is_fatal ? "(Critical)" : "(Non-critical)");
03529       ast_log(LOG_ERROR, "Serious Network Trouble; __sip_xmit returns error for pkt data\n");
03530       AST_SCHED_DEL(sched, pkt->retransid);
03531       p->packets = pkt->next;
03532       pkt->owner = dialog_unref(pkt->owner,"pkt is being freed, its dialog ref is dead now");
03533       ast_free(pkt->data);
03534       ast_free(pkt);
03535       return AST_FAILURE;
03536    } else {
03537       return AST_SUCCESS;
03538    }
03539 }
03540 
03541 /*! \brief Kill a SIP dialog (called only by the scheduler)
03542  * The scheduler has a reference to this dialog when p->autokillid != -1,
03543  * and we are called using that reference. So if the event is not
03544  * rescheduled, we need to call dialog_unref().
03545  */
03546 static int __sip_autodestruct(const void *data)
03547 {
03548    struct sip_pvt *p = (struct sip_pvt *)data;
03549 
03550    /* If this is a subscription, tell the phone that we got a timeout */
03551    if (p->subscribed) {
03552       transmit_state_notify(p, AST_EXTENSION_DEACTIVATED, 1, TRUE);  /* Send last notification */
03553       p->subscribed = NONE;
03554       append_history(p, "Subscribestatus", "timeout");
03555       ast_debug(3, "Re-scheduled destruction of SIP subscription %s\n", p->callid ? p->callid : "<unknown>");
03556       return 10000;  /* Reschedule this destruction so that we know that it's gone */
03557    }
03558 
03559    /* If there are packets still waiting for delivery, delay the destruction */
03560    if (p->packets) {
03561       if (!p->needdestroy) {
03562          char method_str[31];
03563          ast_debug(3, "Re-scheduled destruction of SIP call %s\n", p->callid ? p->callid : "<unknown>");
03564          append_history(p, "ReliableXmit", "timeout");
03565          if (sscanf(p->lastmsg, "Tx: %30s", method_str) == 1 || sscanf(p->lastmsg, "Rx: %30s", method_str) == 1) {
03566             if (method_match(SIP_CANCEL, method_str) || method_match(SIP_BYE, method_str)) {
03567                p->needdestroy = 1;
03568             }
03569          }
03570          return 10000;
03571       } else {
03572          /* They've had their chance to respond. Time to bail */
03573          __sip_pretend_ack(p);
03574       }
03575    }
03576 
03577    if (p->subscribed == MWI_NOTIFICATION)
03578       if (p->relatedpeer)
03579          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) */
03580 
03581    /* Reset schedule ID */
03582    p->autokillid = -1;
03583 
03584    if (p->owner) {
03585       ast_log(LOG_WARNING, "Autodestruct on dialog '%s' with owner in place (Method: %s)\n", p->callid, sip_methods[p->method].text);
03586       ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
03587    } else if (p->refer && !p->alreadygone) {
03588       ast_debug(3, "Finally hanging up channel after transfer: %s\n", p->callid);
03589       transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
03590       append_history(p, "ReferBYE", "Sending BYE on transferer call leg %s", p->callid);
03591       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
03592    } else {
03593       append_history(p, "AutoDestroy", "%s", p->callid);
03594       ast_debug(3, "Auto destroying SIP dialog '%s'\n", p->callid);
03595       dialog_unlink_all(p, TRUE, TRUE); /* once it's unlinked and unrefd everywhere, it'll be freed automagically */
03596       /* dialog_unref(p, "unref dialog-- no other matching conditions"); -- unlink all now should finish off the dialog's references and free it. */
03597       /* sip_destroy(p); */      /* Go ahead and destroy dialog. All attempts to recover is done */
03598       /* sip_destroy also absorbs the reference */
03599    }
03600    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
03601    return 0;
03602 }
03603 
03604 /*! \brief Schedule destruction of SIP dialog */
03605 static void sip_scheddestroy(struct sip_pvt *p, int ms)
03606 {
03607    if (ms < 0) {
03608       if (p->timer_t1 == 0) {
03609          p->timer_t1 = global_t1;   /* Set timer T1 if not set (RFC 3261) */
03610          p->timer_b = global_timer_b;  /* Set timer B if not set (RFC 3261) */
03611       }
03612       ms = p->timer_t1 * 64;
03613    }
03614    if (sip_debug_test_pvt(p))
03615       ast_verbose("Scheduling destruction of SIP dialog '%s' in %d ms (Method: %s)\n", p->callid, ms, sip_methods[p->method].text);
03616    if (sip_cancel_destroy(p))
03617       ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
03618 
03619    if (p->do_history)
03620       append_history(p, "SchedDestroy", "%d ms", ms);
03621    p->autokillid = ast_sched_add(sched, ms, __sip_autodestruct, dialog_ref(p, "setting ref as passing into ast_sched_add for __sip_autodestruct"));
03622 
03623    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_schedid > 0)
03624       stop_session_timer(p);
03625 }
03626 
03627 /*! \brief Cancel destruction of SIP dialog.
03628  * Be careful as this also absorbs the reference - if you call it
03629  * from within the scheduler, this might be the last reference.
03630  */
03631 static int sip_cancel_destroy(struct sip_pvt *p)
03632 {
03633    int res = 0;
03634    if (p->autokillid > -1) {
03635       int res3;
03636 
03637       if (!(res3 = ast_sched_del(sched, p->autokillid))) {
03638          append_history(p, "CancelDestroy", "");
03639          p->autokillid = -1;
03640          dialog_unref(p, "dialog unrefd because autokillid is de-sched'd");
03641       }
03642    }
03643    return res;
03644 }
03645 
03646 /*! \brief Acknowledges receipt of a packet and stops retransmission 
03647  * called with p locked*/
03648 static int __sip_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03649 {
03650    struct sip_pkt *cur, *prev = NULL;
03651    const char *msg = "Not Found";   /* used only for debugging */
03652    int res = FALSE;
03653 
03654    /* If we have an outbound proxy for this dialog, then delete it now since
03655      the rest of the requests in this dialog needs to follow the routing.
03656      If obforcing is set, we will keep the outbound proxy during the whole
03657      dialog, regardless of what the SIP rfc says
03658    */
03659    if (p->outboundproxy && !p->outboundproxy->force){
03660       ref_proxy(p, NULL);
03661    }
03662 
03663    for (cur = p->packets; cur; prev = cur, cur = cur->next) {
03664       if (cur->seqno != seqno || cur->is_resp != resp)
03665          continue;
03666       if (cur->is_resp || cur->method == sipmethod) {
03667          res = TRUE;
03668          msg = "Found";
03669          if (!resp && (seqno == p->pendinginvite)) {
03670             ast_debug(1, "Acked pending invite %d\n", p->pendinginvite);
03671             p->pendinginvite = 0;
03672          }
03673          if (cur->retransid > -1) {
03674             if (sipdebug)
03675                ast_debug(4, "** SIP TIMER: Cancelling retransmit of packet (reply received) Retransid #%d\n", cur->retransid);
03676          }
03677          /* This odd section is designed to thwart a 
03678           * race condition in the packet scheduler. There are
03679           * two conditions under which deleting the packet from the
03680           * scheduler can fail.
03681           *
03682           * 1. The packet has been removed from the scheduler because retransmission
03683           * is being attempted. The problem is that if the packet is currently attempting
03684           * retransmission and we are at this point in the code, then that MUST mean
03685           * that retrans_pkt is waiting on p's lock. Therefore we will relinquish the
03686           * lock temporarily to allow retransmission.
03687           *
03688           * 2. The packet has reached its maximum number of retransmissions and has
03689           * been permanently removed from the packet scheduler. If this is the case, then
03690           * the packet's retransid will be set to -1. The atomicity of the setting and checking
03691           * of the retransid to -1 is ensured since in both cases p's lock is held.
03692           */
03693          while (cur->retransid > -1 && ast_sched_del(sched, cur->retransid)) {
03694             sip_pvt_unlock(p);
03695             usleep(1);
03696             sip_pvt_lock(p);
03697          }
03698          UNLINK(cur, p->packets, prev);
03699          dialog_unref(cur->owner, "unref pkt cur->owner dialog from sip ack before freeing pkt");
03700          if (cur->data)
03701             ast_free(cur->data);
03702          ast_free(cur);
03703          break;
03704       }
03705    }
03706    ast_debug(1, "Stopping retransmission on '%s' of %s %d: Match %s\n",
03707       p->callid, resp ? "Response" : "Request", seqno, msg);
03708    return res;
03709 }
03710 
03711 /*! \brief Pretend to ack all packets
03712  * called with p locked */
03713 static void __sip_pretend_ack(struct sip_pvt *p)
03714 {
03715    struct sip_pkt *cur = NULL;
03716 
03717    while (p->packets) {
03718       int method;
03719       if (cur == p->packets) {
03720          ast_log(LOG_WARNING, "Have a packet that doesn't want to give up! %s\n", sip_methods[cur->method].text);
03721          return;
03722       }
03723       cur = p->packets;
03724       method = (cur->method) ? cur->method : find_sip_method(cur->data->str);
03725       __sip_ack(p, cur->seqno, cur->is_resp, method);
03726    }
03727 }
03728 
03729 /*! \brief Acks receipt of packet, keep it around (used for provisional responses) */
03730 static int __sip_semi_ack(struct sip_pvt *p, int seqno, int resp, int sipmethod)
03731 {
03732    struct sip_pkt *cur;
03733    int res = FALSE;
03734 
03735    for (cur = p->packets; cur; cur = cur->next) {
03736       if (cur->seqno == seqno && cur->is_resp == resp &&
03737          (cur->is_resp || method_match(sipmethod, cur->data->str))) {
03738          /* this is our baby */
03739          if (cur->retransid > -1) {
03740             if (sipdebug)
03741                ast_debug(4, "*** SIP TIMER: Cancelling retransmission #%d - %s (got response)\n", cur->retransid, sip_methods[sipmethod].text);
03742          }
03743          AST_SCHED_DEL(sched, cur->retransid);
03744          res = TRUE;
03745          break;
03746       }
03747    }
03748    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");
03749    return res;
03750 }
03751 
03752 
03753 /*! \brief Copy SIP request, parse it */
03754 static void parse_copy(struct sip_request *dst, const struct sip_request *src)
03755 {
03756    copy_request(dst, src);
03757    parse_request(dst);
03758 }
03759 
03760 /*! \brief add a blank line if no body */
03761 static void add_blank(struct sip_request *req)
03762 {
03763    if (!req->lines) {
03764       /* Add extra empty return. add_header() reserves 4 bytes so cannot be truncated */
03765       ast_str_append(&req->data, 0, "\r\n");
03766       req->len = req->data->used;
03767    }
03768 }
03769 
03770 static int send_provisional_keepalive_full(struct sip_pvt *pvt, int with_sdp)
03771 {
03772    const char *msg = NULL;
03773 
03774    if (!pvt->last_provisional || !strncasecmp(pvt->last_provisional, "100", 3)) {
03775       msg = "183 Session Progress";
03776    }
03777 
03778    if (pvt->invitestate < INV_COMPLETED) {
03779       if (with_sdp) {
03780          transmit_response_with_sdp(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq, XMIT_UNRELIABLE, FALSE);
03781       } else {
03782          transmit_response(pvt, S_OR(msg, pvt->last_provisional), &pvt->initreq);
03783       }
03784       return PROVIS_KEEPALIVE_TIMEOUT;
03785    }
03786 
03787    return 0;
03788 }
03789 
03790 static int send_provisional_keepalive(const void *data) {
03791    struct sip_pvt *pvt = (struct sip_pvt *) data;
03792 
03793    return send_provisional_keepalive_full(pvt, 0);
03794 }
03795 
03796 static int send_provisional_keepalive_with_sdp(const void *data) {
03797    struct sip_pvt *pvt = (void *)data;
03798 
03799    return send_provisional_keepalive_full(pvt, 1);
03800 }
03801 
03802 static void update_provisional_keepalive(struct sip_pvt *pvt, int with_sdp)
03803 {
03804    AST_SCHED_DEL_UNREF(sched, pvt->provisional_keepalive_sched_id, dialog_unref(pvt, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03805 
03806    pvt->provisional_keepalive_sched_id = ast_sched_add(sched, PROVIS_KEEPALIVE_TIMEOUT,
03807       with_sdp ? send_provisional_keepalive_with_sdp : send_provisional_keepalive, dialog_ref(pvt, "Increment refcount to pass dialog pointer to sched callback"));
03808 }
03809 
03810 /*! \brief Transmit response on SIP request*/
03811 static int send_response(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03812 {
03813    int res;
03814 
03815    add_blank(req);
03816    if (sip_debug_test_pvt(p)) {
03817       const struct sockaddr_in *dst = sip_real_dst(p);
03818 
03819       ast_verbose("\n<--- %sTransmitting (%s) to %s:%d --->\n%s\n<------------>\n",
03820          reliable ? "Reliably " : "", sip_nat_mode(p),
03821          ast_inet_ntoa(dst->sin_addr),
03822          ntohs(dst->sin_port), req->data->str);
03823    }
03824    if (p->do_history) {
03825       struct sip_request tmp = { .rlPart1 = 0, };
03826       parse_copy(&tmp, req);
03827       append_history(p, reliable ? "TxRespRel" : "TxResp", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), 
03828          (tmp.method == SIP_RESPONSE || tmp.method == SIP_UNKNOWN) ? REQ_OFFSET_TO_STR(&tmp, rlPart2) : sip_methods[tmp.method].text);
03829       ast_free(tmp.data);
03830    }
03831 
03832    /* If we are sending a final response to an INVITE, stop retransmitting provisional responses */
03833    if (p->initreq.method == SIP_INVITE && reliable == XMIT_CRITICAL) {
03834       AST_SCHED_DEL_UNREF(sched, p->provisional_keepalive_sched_id, dialog_unref(p, "when you delete the provisional_keepalive_sched_id, you should dec the refcount for the stored dialog ptr"));
03835    }
03836 
03837    res = (reliable) ?
03838        __sip_reliable_xmit(p, seqno, 1, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03839       __sip_xmit(p, req->data, req->len);
03840    ast_free(req->data);
03841    req->data = NULL;
03842    if (res > 0)
03843       return 0;
03844    return res;
03845 }
03846 
03847 /*! \brief Send SIP Request to the other part of the dialogue */
03848 static int send_request(struct sip_pvt *p, struct sip_request *req, enum xmittype reliable, int seqno)
03849 {
03850    int res;
03851 
03852    /* If we have an outbound proxy, reset peer address 
03853       Only do this once.
03854    */
03855    if (p->outboundproxy) {
03856       p->sa = p->outboundproxy->ip;
03857    }
03858 
03859    add_blank(req);
03860    if (sip_debug_test_pvt(p)) {
03861       if (ast_test_flag(&p->flags[0], SIP_NAT_ROUTE))
03862          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);
03863       else
03864          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);
03865    }
03866    if (p->do_history) {
03867       struct sip_request tmp = { .rlPart1 = 0, };
03868       parse_copy(&tmp, req);
03869       append_history(p, reliable ? "TxReqRel" : "TxReq", "%s / %s - %s", tmp.data->str, get_header(&tmp, "CSeq"), sip_methods[tmp.method].text);
03870       ast_free(tmp.data);
03871    }
03872    res = (reliable) ?
03873       __sip_reliable_xmit(p, seqno, 0, req->data, req->len, (reliable == XMIT_CRITICAL), req->method) :
03874       __sip_xmit(p, req->data, req->len);
03875    if (req->data) {
03876       ast_free(req->data);
03877       req->data = NULL;
03878    }
03879    return res;
03880 }
03881 
03882 /*! \brief Query an option on a SIP dialog */
03883 static int sip_queryoption(struct ast_channel *chan, int option, void *data, int *datalen)
03884 {
03885    int res = -1;
03886    enum ast_t38_state state = T38_STATE_UNAVAILABLE;
03887    struct sip_pvt *p = (struct sip_pvt *) chan->tech_pvt;
03888 
03889    switch (option) {
03890    case AST_OPTION_T38_STATE:
03891       /* Make sure we got an ast_t38_state enum passed in */
03892       if (*datalen != sizeof(enum ast_t38_state)) {
03893          ast_log(LOG_ERROR, "Invalid datalen for AST_OPTION_T38_STATE option. Expected %d, got %d\n", (int)sizeof(enum ast_t38_state), *datalen);
03894          return -1;
03895       }
03896 
03897       sip_pvt_lock(p);
03898 
03899       /* 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 */
03900       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
03901          switch (p->t38.state) {
03902          case T38_LOCAL_REINVITE:
03903          case T38_PEER_REINVITE:
03904             state = T38_STATE_NEGOTIATING;
03905             break;
03906          case T38_ENABLED:
03907             state = T38_STATE_NEGOTIATED;
03908             break;
03909          default:
03910             state = T38_STATE_UNKNOWN;
03911          }
03912       }
03913 
03914       sip_pvt_unlock(p);
03915 
03916       *((enum ast_t38_state *) data) = state;
03917       res = 0;
03918 
03919       break;
03920    default:
03921       break;
03922    }
03923 
03924    return res;
03925 }
03926 
03927 /*! \brief Locate closing quote in a string, skipping escaped quotes.
03928  * optionally with a limit on the search.
03929  * start must be past the first quote.
03930  */
03931 static const char *find_closing_quote(const char *start, const char *lim)
03932 {
03933    char last_char = '\0';
03934    const char *s;
03935    for (s = start; *s && s != lim; last_char = *s++) {
03936       if (*s == '"' && last_char != '\\')
03937          break;
03938    }
03939    return s;
03940 }
03941 
03942 /*! \brief Pick out text in brackets from character string
03943    \return pointer to terminated stripped string
03944    \param tmp input string that will be modified
03945    Examples:
03946 \verbatim
03947    "foo" <bar> valid input, returns bar
03948    foo      returns the whole string
03949    < "foo ... >   returns the string between brackets
03950    < "foo...   bogus (missing closing bracket), returns the whole string
03951          XXX maybe should still skip the opening bracket
03952 \endverbatim
03953  */
03954 static char *get_in_brackets(char *tmp)
03955 {
03956    const char *parse = tmp;
03957    char *first_bracket;
03958 
03959    /*
03960     * Skip any quoted text until we find the part in brackets.
03961    * On any error give up and return the full string.
03962    */
03963    while ( (first_bracket = strchr(parse, '<')) ) {
03964       char *first_quote = strchr(parse, '"');
03965 
03966       if (!first_quote || first_quote > first_bracket)
03967          break; /* no need to look at quoted part */
03968       /* the bracket is within quotes, so ignore it */
03969       parse = find_closing_quote(first_quote + 1, NULL);
03970       if (!*parse) { /* not found, return full string ? */
03971          /* XXX or be robust and return in-bracket part ? */
03972          ast_log(LOG_WARNING, "No closing quote found in '%s'\n", tmp);
03973          break;
03974       }
03975       parse++;
03976    }
03977    if (first_bracket) {
03978       char *second_bracket = strchr(first_bracket + 1, '>');
03979       if (second_bracket) {
03980          *second_bracket = '\0';
03981          tmp = first_bracket + 1;
03982       } else {
03983          ast_log(LOG_WARNING, "No closing bracket found in '%s'\n", tmp);
03984       }
03985    }
03986    
03987    return tmp;
03988 }
03989 
03990 /*! \brief * parses a URI in its components.
03991  *
03992  * \note 
03993  * - If scheme is specified, drop it from the top.
03994  * - If a component is not requested, do not split around it.
03995  * - Multiple scheme's can be specified ',' delimited. ex: "sip:,sips:"
03996  *
03997  * This means that if we don't have domain, we cannot split
03998  * name:pass and domain:port.
03999  * It is safe to call with ret_name, pass, domain, port
04000  * pointing all to the same place.
04001  * Init pointers to empty string so we never get NULL dereferencing.
04002  * Overwrites the string.
04003  * return 0 on success, other values on error.
04004  * \verbatim 
04005  * general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] 
04006  * \endverbatim
04007  */
04008 static int parse_uri(char *uri, const char *scheme,
04009    char **ret_name, char **pass, char **domain, char **port, char **options, char **transport)
04010 {
04011    char *name = NULL;
04012    int error = 0;
04013 
04014    /* init field as required */
04015    if (pass)
04016       *pass = "";
04017    if (port)
04018       *port = "";
04019    if (scheme) {
04020       int l;
04021       char *scheme2 = ast_strdupa(scheme);
04022       char *cur = strsep(&scheme2, ",");
04023       for (; !ast_strlen_zero(cur); cur = strsep(&scheme2, ",")) {
04024          l = strlen(cur);
04025          if (!strncasecmp(uri, cur, l)) {
04026             uri += l;
04027             break;
04028          }
04029       }
04030       if (ast_strlen_zero(cur)) {
04031          ast_debug(1, "No supported scheme found in '%s' using the scheme[s] %s\n", uri, scheme);
04032          error = -1;
04033       }
04034    }
04035    if (transport) {
04036       char *t, *type = "";
04037       *transport = "";
04038       if ((t = strstr(uri, "transport="))) {
04039          strsep(&t, "=");
04040          if ((type = strsep(&t, ";"))) {
04041             *transport = type;
04042          }
04043       }
04044    }
04045 
04046    if (!domain) {
04047       /* if we don't want to split around domain, keep everything as a name,
04048        * so we need to do nothing here, except remember why.
04049        */
04050    } else {
04051       /* store the result in a temp. variable to avoid it being
04052        * overwritten if arguments point to the same place.
04053        */
04054       char *c, *dom = "";
04055 
04056       if ((c = strchr(uri, '@')) == NULL) {
04057          /* domain-only URI, according to the SIP RFC. */
04058          dom = uri;
04059          name = "";
04060       } else {
04061          *c++ = '\0';
04062          dom = c;
04063          name = uri;
04064       }
04065 
04066       /* Remove options in domain and name */
04067       dom = strsep(&dom, ";");
04068       name = strsep(&name, ";");
04069 
04070       if (port && (c = strchr(dom, ':'))) { /* Remove :port */
04071          *c++ = '\0';
04072          *port = c;
04073       }
04074       if (pass && (c = strchr(name, ':'))) { /* user:password */
04075          *c++ = '\0';
04076          *pass = c;
04077       }
04078       *domain = dom;
04079    }
04080    if (ret_name)  /* same as for domain, store the result only at the end */
04081       *ret_name = name;
04082    if (options)
04083       *options = uri ? uri : "";
04084 
04085    return error;
04086 }
04087 
04088 /*! \brief Send message with Access-URL header, if this is an HTML URL only! */
04089 static int sip_sendhtml(struct ast_channel *chan, int subclass, const char *data, int datalen)
04090 {
04091    struct sip_pvt *p = chan->tech_pvt;
04092 
04093    if (subclass != AST_HTML_URL)
04094       return -1;
04095 
04096    ast_string_field_build(p, url, "<%s>;mode=active", data);
04097 
04098    if (sip_debug_test_pvt(p))
04099       ast_debug(1, "Send URL %s, state = %d!\n", data, chan->_state);
04100 
04101    switch (chan->_state) {
04102    case AST_STATE_RING:
04103       transmit_response(p, "100 Trying", &p->initreq);
04104       break;
04105    case AST_STATE_RINGING:
04106       transmit_response(p, "180 Ringing", &p->initreq);
04107       break;
04108    case AST_STATE_UP:
04109       if (!p->pendinginvite) {      /* We are up, and have no outstanding invite */
04110          transmit_reinvite_with_sdp(p, FALSE, FALSE);
04111       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
04112          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
04113       }  
04114       break;
04115    default:
04116       ast_log(LOG_WARNING, "Don't know how to send URI when state is %d!\n", chan->_state);
04117    }
04118 
04119    return 0;
04120 }
04121 
04122 /*! \brief Deliver SIP call ID for the call */
04123 static const char *sip_get_callid(struct ast_channel *chan)
04124 {
04125    return chan->tech_pvt ? ((struct sip_pvt *) chan->tech_pvt)->callid : "";
04126 }
04127 
04128 /*! \brief Send SIP MESSAGE text within a call
04129    Called from PBX core sendtext() application */
04130 static int sip_sendtext(struct ast_channel *ast, const char *text)
04131 {
04132    struct sip_pvt *p = ast->tech_pvt;
04133    int debug = sip_debug_test_pvt(p);
04134 
04135    if (debug)
04136       ast_verbose("Sending text %s on %s\n", text, ast->name);
04137    if (!p)
04138       return -1;
04139    /* NOT ast_strlen_zero, because a zero-length message is specifically
04140     * allowed by RFC 3428 (See section 10, Examples) */
04141    if (!text)
04142       return 0;
04143    if (debug)
04144       ast_verbose("Really sending text %s on %s\n", text, ast->name);
04145    transmit_message_with_text(p, text);
04146    return 0;   
04147 }
04148 
04149 /*! \brief Update peer object in realtime storage 
04150    If the Asterisk system name is set in asterisk.conf, we will use
04151    that name and store that in the "regserver" field in the sippeers
04152    table to facilitate multi-server setups.
04153 */
04154 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)
04155 {
04156    char port[10];
04157    char ipaddr[INET_ADDRSTRLEN];
04158    char regseconds[20];
04159    char *tablename = NULL;
04160    char str_lastms[20];
04161 
04162    const char *sysname = ast_config_AST_SYSTEM_NAME;
04163    char *syslabel = NULL;
04164 
04165    time_t nowtime = time(NULL) + expirey;
04166    const char *fc = fullcontact ? "fullcontact" : NULL;
04167 
04168    int realtimeregs = ast_check_realtime("sipregs");
04169 
04170    tablename = realtimeregs ? "sipregs" : "sippeers";
04171    
04172 
04173    snprintf(str_lastms, sizeof(str_lastms), "%d", lastms);
04174    snprintf(regseconds, sizeof(regseconds), "%d", (int)nowtime);  /* Expiration time */
04175    ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04176    snprintf(port, sizeof(port), "%d", ntohs(sin->sin_port));
04177    
04178    if (ast_strlen_zero(sysname)) /* No system name, disable this */
04179       sysname = NULL;
04180    else if (sip_cfg.rtsave_sysname)
04181       syslabel = "regserver";
04182 
04183    if (fc) {
04184       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04185          "port", port, "regseconds", regseconds,
04186          deprecated_username ? "username" : "defaultuser", defaultuser,
04187          "useragent", useragent, "lastms", str_lastms,
04188          fc, fullcontact, syslabel, sysname, SENTINEL); /* note fc and syslabel _can_ be NULL */
04189    } else {
04190       ast_update_realtime(tablename, "name", peername, "ipaddr", ipaddr,
04191          "port", port, "regseconds", regseconds,
04192          "useragent", useragent, "lastms", str_lastms,
04193          deprecated_username ? "username" : "defaultuser", defaultuser,
04194          syslabel, sysname, SENTINEL); /* note syslabel _can_ be NULL */
04195    }
04196 }
04197 
04198 /*! \brief Automatically add peer extension to dial plan */
04199 static void register_peer_exten(struct sip_peer *peer, int onoff)
04200 {
04201    char multi[256];
04202    char *stringp, *ext, *context;
04203    struct pbx_find_info q = { .stacklen = 0 };
04204 
04205    /* XXX note that global_regcontext is both a global 'enable' flag and
04206     * the name of the global regexten context, if not specified
04207     * individually.
04208     */
04209    if (ast_strlen_zero(global_regcontext))
04210       return;
04211 
04212    ast_copy_string(multi, S_OR(peer->regexten, peer->name), sizeof(multi));
04213    stringp = multi;
04214    while ((ext = strsep(&stringp, "&"))) {
04215       if ((context = strchr(ext, '@'))) {
04216          *context++ = '\0';   /* split ext@context */
04217          if (!ast_context_find(context)) {
04218             ast_log(LOG_WARNING, "Context %s must exist in regcontext= in sip.conf!\n", context);
04219             continue;
04220          }
04221       } else {
04222          context = global_regcontext;
04223       }
04224       if (onoff) {
04225          if (!ast_exists_extension(NULL, context, ext, 1, NULL)) {
04226             ast_add_extension(context, 1, ext, 1, NULL, NULL, "Noop",
04227                 ast_strdup(peer->name), ast_free_ptr, "SIP");
04228          }
04229       } else if (pbx_find_extension(NULL, NULL, &q, context, ext, 1, NULL, "", E_MATCH)) {
04230          ast_context_remove_extension(context, ext, 1, NULL);
04231       }
04232    }
04233 }
04234 
04235 /*! Destroy mailbox subscriptions */
04236 static void destroy_mailbox(struct sip_mailbox *mailbox)
04237 {
04238    if (mailbox->mailbox)
04239       ast_free(mailbox->mailbox);
04240    if (mailbox->context)
04241       ast_free(mailbox->context);
04242    if (mailbox->event_sub)
04243       ast_event_unsubscribe(mailbox->event_sub);
04244    ast_free(mailbox);
04245 }
04246 
04247 /*! Destroy all peer-related mailbox subscriptions */
04248 static void clear_peer_mailboxes(struct sip_peer *peer)
04249 {
04250    struct sip_mailbox *mailbox;
04251 
04252    while ((mailbox = AST_LIST_REMOVE_HEAD(&peer->mailboxes, entry)))
04253       destroy_mailbox(mailbox);
04254 }
04255 
04256 static void sip_destroy_peer_fn(void *peer)
04257 {
04258    sip_destroy_peer(peer);
04259 }
04260 
04261 /*! \brief Destroy peer object from memory */
04262 static void sip_destroy_peer(struct sip_peer *peer)
04263 {
04264    ast_debug(3, "Destroying SIP peer %s\n", peer->name);
04265    if (peer->outboundproxy)
04266       ao2_ref(peer->outboundproxy, -1);
04267    peer->outboundproxy = NULL;
04268 
04269    /* Delete it, it needs to disappear */
04270    if (peer->call) {
04271       dialog_unlink_all(peer->call, TRUE, TRUE);
04272       peer->call = dialog_unref(peer->call, "peer->call is being unset");
04273    }
04274    
04275 
04276    if (peer->mwipvt) {  /* We have an active subscription, delete it */
04277       dialog_unlink_all(peer->mwipvt, TRUE, TRUE);
04278       peer->mwipvt = dialog_unref(peer->mwipvt, "unreffing peer->mwipvt");
04279    }
04280    
04281    if (peer->chanvars) {
04282       ast_variables_destroy(peer->chanvars);
04283       peer->chanvars = NULL;
04284    }
04285    
04286    register_peer_exten(peer, FALSE);
04287    ast_free_ha(peer->ha);
04288    if (peer->selfdestruct)
04289       ast_atomic_fetchadd_int(&apeerobjs, -1);
04290    else if (peer->is_realtime) {
04291       ast_atomic_fetchadd_int(&rpeerobjs, -1);
04292       ast_debug(3, "-REALTIME- peer Destroyed. Name: %s. Realtime Peer objects: %d\n", peer->name, rpeerobjs);
04293    } else
04294       ast_atomic_fetchadd_int(&speerobjs, -1);
04295    clear_realm_authentication(peer->auth);
04296    peer->auth = NULL;
04297    if (peer->dnsmgr)
04298       ast_dnsmgr_release(peer->dnsmgr);
04299    clear_peer_mailboxes(peer);
04300 
04301    if (peer->socket.tcptls_session) {
04302       ao2_ref(peer->socket.tcptls_session, -1);
04303       peer->socket.tcptls_session = NULL;
04304    }
04305 }
04306 
04307 /*! \brief Update peer data in database (if used) */
04308 static void update_peer(struct sip_peer *p, int expire)
04309 {
04310    int rtcachefriends = ast_test_flag(&p->flags[1], SIP_PAGE2_RTCACHEFRIENDS);
04311    if (sip_cfg.peer_rtupdate &&
04312        (p->is_realtime || rtcachefriends)) {
04313       realtime_update_peer(p->name, &p->addr, p->username, rtcachefriends ? p->fullcontact : NULL, p->useragent, expire, p->deprecated_username, p->lastms);
04314    }
04315 }
04316 
04317 static struct ast_variable *get_insecure_variable_from_config(struct ast_config *cfg)
04318 {
04319    struct ast_variable *var = NULL;
04320    struct ast_flags flags = {0};
04321    char *cat = NULL;
04322    const char *insecure;
04323    while ((cat = ast_category_browse(cfg, cat))) {
04324       insecure = ast_variable_retrieve(cfg, cat, "insecure");
04325       set_insecure_flags(&flags, insecure, -1);
04326       if (ast_test_flag(&flags, SIP_INSECURE_PORT)) {
04327          var = ast_category_root(cfg, cat);
04328          break;
04329       }
04330    }
04331    return var;
04332 }
04333 
04334 static const char *get_name_from_variable(struct ast_variable *var, const char *newpeername)
04335 {
04336    struct ast_variable *tmp;
04337    for (tmp = var; tmp; tmp = tmp->next) {
04338       if (!newpeername && !strcasecmp(tmp->name, "name"))
04339          newpeername = tmp->value;
04340    }
04341    return newpeername;
04342 }
04343 
04344 /*! \brief  realtime_peer: Get peer from realtime storage
04345  * Checks the "sippeers" realtime family from extconfig.conf 
04346  * Checks the "sipregs" realtime family from extconfig.conf if it's configured.
04347  * This returns a pointer to a peer and because we use build_peer, we can rest
04348  * assured that the refcount is bumped.
04349 */
04350 static struct sip_peer *realtime_peer(const char *newpeername, struct sockaddr_in *sin, int devstate_only)
04351 {
04352    struct sip_peer *peer;
04353    struct ast_variable *var = NULL;
04354    struct ast_variable *varregs = NULL;
04355    struct ast_variable *tmp;
04356    struct ast_config *peerlist = NULL;
04357    char ipaddr[INET_ADDRSTRLEN];
04358    char portstring[6]; /*up to 5 digits plus null terminator*/
04359    char *cat = NULL;
04360    unsigned short portnum;
04361    int realtimeregs = ast_check_realtime("sipregs");
04362 
04363    /* First check on peer name */
04364    if (newpeername) {
04365       if (realtimeregs)
04366          varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04367 
04368       var = ast_load_realtime("sippeers", "name", newpeername, "host", "dynamic", SENTINEL);
04369       if (!var && sin)
04370          var = ast_load_realtime("sippeers", "name", newpeername, "host", ast_inet_ntoa(sin->sin_addr), SENTINEL);
04371       if (!var) {
04372          var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04373          /*!\note
04374           * If this one loaded something, then we need to ensure that the host
04375           * field matched.  The only reason why we can't have this as a criteria
04376           * is because we only have the IP address and the host field might be
04377           * set as a name (and the reverse PTR might not match).
04378           */
04379          if (var && sin) {
04380             for (tmp = var; tmp; tmp = tmp->next) {
04381                if (!strcasecmp(tmp->name, "host")) {
04382                   struct hostent *hp;
04383                   struct ast_hostent ahp;
04384                   if (!(hp = ast_gethostbyname(tmp->value, &ahp)) || (memcmp(hp->h_addr, &sin->sin_addr, sizeof(hp->h_addr)))) {
04385                      /* No match */
04386                      ast_variables_destroy(var);
04387                      var = NULL;
04388                   }
04389                   break;
04390                }
04391             }
04392          }
04393       }
04394    }
04395 
04396    if (!var && sin) {   /* Then check on IP address for dynamic peers */
04397       ast_copy_string(ipaddr, ast_inet_ntoa(sin->sin_addr), sizeof(ipaddr));
04398       portnum = ntohs(sin->sin_port);
04399       sprintf(portstring, "%u", portnum);
04400       var = ast_load_realtime("sippeers", "host", ipaddr, "port", portstring, SENTINEL);  /* First check for fixed IP hosts */
04401       if (var) {
04402          if (realtimeregs) {
04403             newpeername = get_name_from_variable(var, newpeername);
04404             varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04405          }
04406       } else {
04407          if (realtimeregs)
04408             varregs = ast_load_realtime("sipregs", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04409          else
04410             var = ast_load_realtime("sippeers", "ipaddr", ipaddr, "port", portstring, SENTINEL); /* Then check for registered hosts */
04411          if (varregs) {
04412             newpeername = get_name_from_variable(varregs, newpeername);
04413             var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04414          }
04415       }
04416       if (!var) { /*We couldn't match on ipaddress and port, so we need to check if port is insecure*/
04417          peerlist = ast_load_realtime_multientry("sippeers", "host", ipaddr, SENTINEL);
04418          if (peerlist) {
04419             var = get_insecure_variable_from_config(peerlist);
04420             if(var) {
04421                if (realtimeregs) {
04422                   newpeername = get_name_from_variable(var, newpeername);
04423                   varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04424                }
04425             } else { /*var wasn't found in the list of "hosts", so try "ipaddr"*/
04426                peerlist = NULL;
04427                cat = NULL;
04428                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04429                if(peerlist) {
04430                   var = get_insecure_variable_from_config(peerlist);
04431                   if(var) {
04432                      if (realtimeregs) {
04433                         newpeername = get_name_from_variable(var, newpeername);
04434                         varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04435                      }
04436                   }
04437                }
04438             }
04439          } else {
04440             if (realtimeregs) {
04441                peerlist = ast_load_realtime_multientry("sipregs", "ipaddr", ipaddr, SENTINEL);
04442                if (peerlist) {
04443                   varregs = get_insecure_variable_from_config(peerlist);
04444                   if (varregs) {
04445                      newpeername = get_name_from_variable(varregs, newpeername);
04446                      var = ast_load_realtime("sippeers", "name", newpeername, SENTINEL);
04447                   }
04448                }
04449             } else {
04450                peerlist = ast_load_realtime_multientry("sippeers", "ipaddr", ipaddr, SENTINEL);
04451                if (peerlist) {
04452                   var = get_insecure_variable_from_config(peerlist);
04453                   if (var) {
04454                      newpeername = get_name_from_variable(var, newpeername);
04455                      varregs = ast_load_realtime("sipregs", "name", newpeername, SENTINEL);
04456                   }
04457                }
04458             }
04459          }
04460       }
04461    }
04462 
04463    if (!var) {
04464       if (peerlist)
04465          ast_config_destroy(peerlist);
04466       return NULL;
04467    }
04468 
04469    for (tmp = var; tmp; tmp = tmp->next) {
04470       /* If this is type=user, then skip this object. */
04471       if (!strcasecmp(tmp->name, "type") &&
04472           !strcasecmp(tmp->value, "user")) {
04473          if(peerlist)
04474             ast_config_destroy(peerlist);
04475          else {
04476             ast_variables_destroy(var);
04477             ast_variables_destroy(varregs);
04478          }
04479          return NULL;
04480       } else if (!newpeername && !strcasecmp(tmp->name, "name")) {
04481          newpeername = tmp->value;
04482       }
04483    }
04484    
04485    if (!newpeername) {  /* Did not find peer in realtime */
04486       ast_log(LOG_WARNING, "Cannot Determine peer name ip=%s\n", ipaddr);
04487       if(peerlist)
04488          ast_config_destroy(peerlist);
04489       else
04490          ast_variables_destroy(var);
04491       return NULL;
04492    }
04493 
04494 
04495    /* Peer found in realtime, now build it in memory */
04496    peer = build_peer(newpeername, var, varregs, TRUE, devstate_only);
04497    if (!peer) {
04498       if(peerlist)
04499          ast_config_destroy(peerlist);
04500       else {
04501          ast_variables_destroy(var);
04502          ast_variables_destroy(varregs);
04503       }
04504       return NULL;
04505    }
04506 
04507    ast_debug(3, "-REALTIME- loading peer from database to memory. Name: %s. Peer objects: %d\n", peer->name, rpeerobjs);
04508 
04509    if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && !devstate_only) {
04510       /* Cache peer */
04511       ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_RTAUTOCLEAR|SIP_PAGE2_RTCACHEFRIENDS);
04512       if (ast_test_flag(&global_flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
04513          AST_SCHED_REPLACE_UNREF(peer->expire, sched, global_rtautoclear * 1000, expire_register, peer,
04514                unref_peer(_data, "remove registration ref"),
04515                unref_peer(peer, "remove registration ref"),
04516                ref_peer(peer, "add registration ref"));
04517       }
04518       ao2_t_link(peers, peer, "link peer into peers table");
04519       if (peer->addr.sin_addr.s_addr) {
04520          ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
04521       }
04522    }
04523    peer->is_realtime = 1;
04524    if (peerlist)
04525       ast_config_destroy(peerlist);
04526    else {
04527       ast_variables_destroy(var);
04528       ast_variables_destroy(varregs);
04529    }
04530 
04531    return peer;
04532 }
04533 
04534 /* The first element here must *always* be tmp_peer. This is because the user of this function
04535  * passes it in using OBJ_POINTER which causes astobj2 to perform hashing on the name to find
04536  * where the peer is. Since tmp_peer is at the beginning this just magically works. Move it and it
04537  * will break. People will be angry. Just don't do it.
04538  */
04539 struct peer_finding_info {
04540    struct sip_peer tmp_peer;
04541    int which_objects;
04542 };
04543 
04544 /* Function to assist finding peers by name only */
04545 static int find_by_name(void *obj, void *arg, int flags)
04546 {
04547    struct sip_peer *search = obj;
04548    struct peer_finding_info *pfi = arg;
04549 
04550    /* Usernames in SIP uri's are case sensitive. Domains are not */
04551    if (strcmp(search->name, pfi->tmp_peer.name)) {
04552       return 0;
04553    }
04554 
04555    switch (pfi->which_objects) {
04556    case FINDUSERS:
04557       if (!(search->type & SIP_TYPE_USER)) {
04558          return 0;
04559       }
04560       break;
04561    case FINDPEERS:
04562       if (!(search->type & SIP_TYPE_PEER)) {
04563          return 0;
04564       }
04565       break;
04566    case FINDALLDEVICES:
04567       break;
04568    }
04569 
04570    return CMP_MATCH | CMP_STOP;
04571 }
04572 
04573 /*! 
04574  * \brief Locate device by name or ip address 
04575  *
04576  * \param which_objects Define which objects should be matched when doing a lookup
04577  *        by name.  Valid options are FINDUSERS, FINDPEERS, or FINDALLDEVICES.
04578  *        Note that this option is not used at all when doing a lookup by IP.
04579  *
04580  * This is used on find matching device on name or ip/port.
04581  * If the device was declared as type=peer, we don't match on peer name on incoming INVITEs.
04582  *
04583  * \note Avoid using this function in new functions if there is a way to avoid it,
04584  * since it might cause a database lookup.
04585  */
04586 static struct sip_peer *find_peer(const char *peer, struct sockaddr_in *sin, int realtime, int which_objects, int devstate_only, int transport)
04587 {
04588    struct sip_peer *p = NULL;
04589 
04590    if (peer) {
04591       struct peer_finding_info pfi = {
04592          .which_objects = which_objects,
04593       };
04594       ast_copy_string(pfi.tmp_peer.name, peer, sizeof(pfi.tmp_peer.name));
04595       p = ao2_t_callback(peers, OBJ_POINTER, find_by_name, &pfi, "ao2_callback in peers table");
04596    } else if (sin) { /* search by addr? */
04597       struct sip_peer tmp_peer;
04598       tmp_peer.addr.sin_addr.s_addr = sin->sin_addr.s_addr;
04599       tmp_peer.addr.sin_port = sin->sin_port;
04600       tmp_peer.flags[0].flags = 0;
04601       tmp_peer.transports = transport;
04602       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); */
04603       if (!p) {
04604          ast_set_flag(&tmp_peer.flags[0], SIP_INSECURE_PORT);
04605          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); */
04606          if (p) {
04607             return p;
04608          }
04609       }
04610    }
04611 
04612    if (!p && (realtime || devstate_only))
04613       p = realtime_peer(peer, sin, devstate_only);
04614 
04615    return p;
04616 }
04617 
04618 /*! \brief Set nat mode on the various data sockets */
04619 static void do_setnat(struct sip_pvt *p, int natflags)
04620 {
04621    const char *mode = natflags ? "On" : "Off";
04622 
04623    if (p->rtp) {
04624       ast_debug(1, "Setting NAT on RTP to %s\n", mode);
04625       ast_rtp_setnat(p->rtp, natflags);
04626    }
04627    if (p->vrtp) {
04628       ast_debug(1, "Setting NAT on VRTP to %s\n", mode);
04629       ast_rtp_setnat(p->vrtp, natflags);
04630    }
04631    if (p->udptl) {
04632       ast_debug(1, "Setting NAT on UDPTL to %s\n", mode);
04633       ast_udptl_setnat(p->udptl, natflags);
04634    }
04635    if (p->trtp) {
04636       ast_debug(1, "Setting NAT on TRTP to %s\n", mode);
04637       ast_rtp_setnat(p->trtp, natflags);
04638    }
04639 }
04640 
04641 /*! \brief Change the T38 state on a SIP dialog */
04642 static void change_t38_state(struct sip_pvt *p, int state)
04643 {
04644    int old = p->t38.state;
04645    struct ast_channel *chan = p->owner;
04646    struct ast_control_t38_parameters parameters = { .request_response = 0 };
04647 
04648    /* Don't bother changing if we are already in the state wanted */
04649    if (old == state)
04650       return;
04651 
04652    p->t38.state = state;
04653    ast_debug(2, "T38 state changed to %d on channel %s\n", p->t38.state, chan ? chan->name : "<none>");
04654 
04655    /* If no channel was provided we can't send off a control frame */
04656    if (!chan)
04657       return;
04658 
04659    /* Given the state requested and old state determine what control frame we want to queue up */
04660    switch (state) {
04661    case T38_PEER_REINVITE:
04662       parameters = p->t38.their_parms;
04663       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04664       parameters.request_response = AST_T38_REQUEST_NEGOTIATE;
04665       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04666       break;
04667    case T38_ENABLED:
04668       parameters = p->t38.their_parms;
04669       parameters.max_ifp = ast_udptl_get_far_max_ifp(p->udptl);
04670       parameters.request_response = AST_T38_NEGOTIATED;
04671       ast_udptl_set_tag(p->udptl, "SIP/%s", p->username);
04672       break;
04673    case T38_DISABLED:
04674       if (old == T38_ENABLED) {
04675          parameters.request_response = AST_T38_TERMINATED;
04676       } else if (old == T38_LOCAL_REINVITE) {
04677          parameters.request_response = AST_T38_REFUSED;
04678       }
04679       break;
04680    case T38_LOCAL_REINVITE:
04681       /* wait until we get a peer response before responding to local reinvite */
04682       break;
04683    }
04684 
04685    /* Woot we got a message, create a control frame and send it on! */
04686    if (parameters.request_response)
04687       ast_queue_control_data(chan, AST_CONTROL_T38_PARAMETERS, &parameters, sizeof(parameters));
04688 }
04689 
04690 /*! \brief Set the global T38 capabilities on a SIP dialog structure */
04691 static void set_t38_capabilities(struct sip_pvt *p)
04692 {
04693    if (p->udptl) {
04694       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY) {
04695                         ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
04696       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL_FEC) {
04697          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
04698       } else if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) == SIP_PAGE2_T38SUPPORT_UDPTL) {
04699          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
04700       }
04701    }
04702 }
04703 
04704 static void copy_socket_data(struct sip_socket *to_sock, const struct sip_socket *from_sock)
04705 {
04706    if (to_sock->tcptls_session) {
04707       ao2_ref(to_sock->tcptls_session, -1);
04708       to_sock->tcptls_session = NULL;
04709    }
04710 
04711    if (from_sock->tcptls_session) {
04712       ao2_ref(from_sock->tcptls_session, +1);
04713    }
04714 
04715    *to_sock = *from_sock;
04716 }
04717 
04718 /*! \brief Create address structure from peer reference.
04719  * This function copies data from peer to the dialog, so we don't have to look up the peer
04720  * again from memory or database during the life time of the dialog.
04721  *
04722  * \return -1 on error, 0 on success.
04723  *
04724  */
04725 static int create_addr_from_peer(struct sip_pvt *dialog, struct sip_peer *peer)
04726 {
04727    /* this checks that the dialog is contacting the peer on a valid
04728     * transport type based on the peers transport configuration,
04729     * otherwise, this function bails out */
04730    if (dialog->socket.type && check_request_transport(peer, dialog))
04731       return -1;
04732    copy_socket_data(&dialog->socket, &peer->socket);
04733 
04734    if ((peer->addr.sin_addr.s_addr || peer->defaddr.sin_addr.s_addr) &&
04735        (!peer->maxms || ((peer->lastms >= 0)  && (peer->lastms <= peer->maxms)))) {
04736       dialog->sa = (peer->addr.sin_addr.s_addr) ? peer->addr : peer->defaddr;
04737       dialog->recv = dialog->sa;
04738    } else 
04739       return -1;
04740 
04741    ast_copy_flags(&dialog->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
04742    ast_copy_flags(&dialog->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
04743    dialog->capability = peer->capability;
04744    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
04745          (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
04746             !(dialog->capability & AST_FORMAT_VIDEO_MASK)) &&
04747          dialog->vrtp) {
04748       ast_rtp_destroy(dialog->vrtp);
04749       dialog->vrtp = NULL;
04750    }
04751    if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_TEXTSUPPORT) && dialog->trtp) {
04752       ast_rtp_destroy(dialog->trtp);
04753       dialog->trtp = NULL;
04754    }
04755    dialog->prefs = peer->prefs;
04756    if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_T38SUPPORT)) {
04757       if (!dialog->udptl) {
04758          /* t38pt_udptl was enabled in the peer and not in [general] */
04759          dialog->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
04760       }
04761       dialog->t38_maxdatagram = peer->t38_maxdatagram;
04762       set_t38_capabilities(dialog);
04763    } else if (dialog->udptl) {
04764       ast_udptl_destroy(dialog->udptl);
04765       dialog->udptl = NULL;
04766    }
04767    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04768 
04769    if (dialog->rtp) { /* Audio */
04770       ast_rtp_setdtmf(dialog->rtp, ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
04771       ast_rtp_setdtmfcompensate(dialog->rtp, ast_test_flag(&dialog->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
04772       ast_rtp_set_rtptimeout(dialog->rtp, peer->rtptimeout);
04773       ast_rtp_set_rtpholdtimeout(dialog->rtp, peer->rtpholdtimeout);
04774       ast_rtp_set_rtpkeepalive(dialog->rtp, peer->rtpkeepalive);
04775       if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
04776          ast_rtp_set_constantssrc(dialog->rtp);
04777       }
04778       /* Set Frame packetization */
04779       ast_rtp_codec_setpref(dialog->rtp, &dialog->prefs);
04780       dialog->autoframing = peer->autoframing;
04781    }
04782    if (dialog->vrtp) { /* Video */
04783       ast_rtp_setdtmf(dialog->vrtp, 0);
04784       ast_rtp_setdtmfcompensate(dialog->vrtp, 0);
04785       ast_rtp_set_rtptimeout(dialog->vrtp, peer->rtptimeout);
04786       ast_rtp_set_rtpholdtimeout(dialog->vrtp, peer->rtpholdtimeout);
04787       ast_rtp_set_rtpkeepalive(dialog->vrtp, peer->rtpkeepalive);
04788       if (ast_test_flag(&dialog->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
04789          ast_rtp_set_constantssrc(dialog->vrtp);
04790       }
04791    }
04792    if (dialog->trtp) { /* Realtime text */
04793       ast_rtp_setdtmf(dialog->trtp, 0);
04794       ast_rtp_setdtmfcompensate(dialog->trtp, 0);
04795       ast_rtp_set_rtptimeout(dialog->trtp, peer->rtptimeout);
04796       ast_rtp_set_rtpholdtimeout(dialog->trtp, peer->rtpholdtimeout);
04797       ast_rtp_set_rtpkeepalive(dialog->trtp, peer->rtpkeepalive);
04798    }
04799 
04800    ast_string_field_set(dialog, peername, peer->name);
04801    ast_string_field_set(dialog, authname, peer->username);
04802    ast_string_field_set(dialog, username, peer->username);
04803    ast_string_field_set(dialog, peersecret, peer->secret);
04804    ast_string_field_set(dialog, peermd5secret, peer->md5secret);
04805    ast_string_field_set(dialog, mohsuggest, peer->mohsuggest);
04806    ast_string_field_set(dialog, mohinterpret, peer->mohinterpret);
04807    ast_string_field_set(dialog, tohost, peer->tohost);
04808    ast_string_field_set(dialog, fullcontact, peer->fullcontact);
04809    ast_string_field_set(dialog, context, peer->context);
04810    ast_string_field_set(dialog, parkinglot, peer->parkinglot);
04811    ref_proxy(dialog, obproxy_get(dialog, peer));
04812    dialog->callgroup = peer->callgroup;
04813    dialog->pickupgroup = peer->pickupgroup;
04814    dialog->allowtransfer = peer->allowtransfer;
04815    dialog->jointnoncodeccapability = dialog->noncodeccapability;
04816    dialog->rtptimeout = peer->rtptimeout;
04817    dialog->peerauth = peer->auth;
04818    dialog->maxcallbitrate = peer->maxcallbitrate;
04819    if (ast_strlen_zero(dialog->tohost))
04820       ast_string_field_set(dialog, tohost, ast_inet_ntoa(dialog->sa.sin_addr));
04821    if (!ast_strlen_zero(peer->fromdomain)) {
04822       ast_string_field_set(dialog, fromdomain, peer->fromdomain);
04823       if (!dialog->initreq.headers) {
04824          char *c;
04825          char *tmpcall = ast_strdupa(dialog->callid);
04826          /* this sure looks to me like we are going to change the callid on this dialog!! */
04827          c = strchr(tmpcall, '@');
04828          if (c) {
04829             *c = '\0';
04830             ao2_t_unlink(dialogs, dialog, "About to change the callid -- remove the old name");
04831             ast_string_field_build(dialog, callid, "%s@%s", tmpcall, peer->fromdomain);
04832             ao2_t_link(dialogs, dialog, "New dialog callid -- inserted back into table");
04833          }
04834       }
04835    }
04836    if (!ast_strlen_zero(peer->fromuser)) 
04837       ast_string_field_set(dialog, fromuser, peer->fromuser);
04838    if (!ast_strlen_zero(peer->language))
04839       ast_string_field_set(dialog, language, peer->language);
04840    /* Set timer T1 to RTT for this peer (if known by qualify=) */
04841    /* Minimum is settable or default to 100 ms */
04842    /* If there is a maxms and lastms from a qualify use that over a manual T1
04843       value. Otherwise, use the peer's T1 value. */
04844    if (peer->maxms && peer->lastms)
04845       dialog->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
04846    else
04847       dialog->timer_t1 = peer->timer_t1;
04848 
04849    /* Set timer B to control transaction timeouts, the peer setting is the default and overrides
04850       the known timer */
04851    if (peer->timer_b)
04852       dialog->timer_b = peer->timer_b;
04853    else
04854       dialog->timer_b = 64 * dialog->timer_t1;
04855 
04856    if ((ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
04857        (ast_test_flag(&dialog->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
04858       dialog->noncodeccapability |= AST_RTP_DTMF;
04859    else
04860       dialog->noncodeccapability &= ~AST_RTP_DTMF;
04861    if (peer->call_limit)
04862       ast_set_flag(&dialog->flags[0], SIP_CALL_LIMIT);
04863    if (!dialog->portinuri)
04864       dialog->portinuri = peer->portinuri;
04865    
04866    return 0;
04867 }
04868 
04869 /*! \brief create address structure from device name
04870  *      Or, if peer not found, find it in the global DNS 
04871  *      returns TRUE (-1) on failure, FALSE on success */
04872 static int create_addr(struct sip_pvt *dialog, const char *opeer, struct sockaddr_in *sin, int newdialog)
04873 {
04874    struct hostent *hp;
04875    struct ast_hostent ahp;
04876    struct sip_peer *peer;
04877    char *port;
04878    int portno = 0;
04879    char host[MAXHOSTNAMELEN], *hostn;
04880    char peername[256];
04881    int srv_ret = 0;
04882 
04883    ast_copy_string(peername, opeer, sizeof(peername));
04884    port = strchr(peername, ':');
04885    if (port) {
04886       *port++ = '\0';
04887       dialog->portinuri = 1;
04888    }
04889    dialog->sa.sin_family = AF_INET;
04890    dialog->timer_t1 = global_t1; /* Default SIP retransmission timer T1 (RFC 3261) */
04891    dialog->timer_b = global_timer_b; /* Default SIP transaction timer B (RFC 3261) */
04892    peer = find_peer(peername, NULL, TRUE, FINDPEERS, FALSE, 0);
04893 
04894    if (peer) {
04895       int res;
04896       if (newdialog) {
04897          set_socket_transport(&dialog->socket, 0);
04898       }
04899       res = create_addr_from_peer(dialog, peer);
04900       if (!ast_strlen_zero(port)) {
04901          if ((portno = atoi(port))) {
04902             dialog->sa.sin_port = dialog->recv.sin_port = htons(portno);
04903          }
04904       }
04905       unref_peer(peer, "create_addr: unref peer from find_peer hashtab lookup");
04906       return res;
04907    }
04908 
04909    do_setnat(dialog, ast_test_flag(&dialog->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
04910 
04911    ast_string_field_set(dialog, tohost, peername);
04912 
04913    /* Get the outbound proxy information */
04914    ref_proxy(dialog, obproxy_get(dialog, NULL));
04915 
04916    if (sin) {
04917       /* This address should be updated using dnsmgr */
04918       memcpy(&dialog->sa.sin_addr, &sin->sin_addr, sizeof(dialog->sa.sin_addr));
04919       if (!sin->sin_port) {
04920          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
04921       } else {
04922          portno = ntohs(sin->sin_port);
04923       }
04924    } else {
04925 
04926       /* Let's see if we can find the host in DNS. First try DNS SRV records,
04927          then hostname lookup */
04928       /*! \todo Fix this function. When we ask SRC, we should check all transports 
04929            In the future, we should first check NAPTR to find out transport preference
04930        */
04931       hostn = peername;
04932       /* Section 4.2 of RFC 3263 specifies that if a port number is specified, then
04933        * an A record lookup should be used instead of SRV.
04934        */
04935       if (!port && global_srvlookup) {
04936          char service[MAXHOSTNAMELEN];
04937          int tportno;
04938    
04939          snprintf(service, sizeof(service), "_sip._%s.%s", get_transport(dialog->socket.type), peername);
04940          srv_ret = ast_get_srv(NULL, host, sizeof(host), &tportno, service);
04941          if (srv_ret > 0) {
04942             hostn = host;
04943             portno = tportno;
04944          }
04945       }
04946       if (!portno)
04947          portno = port_str2int(port, (dialog->socket.type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
04948       hp = ast_gethostbyname(hostn, &ahp);
04949       if (!hp) {
04950          ast_log(LOG_WARNING, "No such host: %s\n", peername);
04951          return -1;
04952       }
04953       memcpy(&dialog->sa.sin_addr, hp->h_addr, sizeof(dialog->sa.sin_addr));
04954    }
04955 
04956    if (!dialog->socket.type)
04957       set_socket_transport(&dialog->socket, SIP_TRANSPORT_UDP);
04958    if (!dialog->socket.port)
04959       dialog->socket.port = bindaddr.sin_port;
04960    dialog->sa.sin_port = htons(portno);
04961    dialog->recv = dialog->sa;
04962    return 0;
04963 }
04964 
04965 /*! \brief Scheduled congestion on a call.
04966  * Only called by the scheduler, must return the reference when done.
04967  */
04968 static int auto_congest(const void *arg)
04969 {
04970    struct sip_pvt *p = (struct sip_pvt *)arg;
04971 
04972    sip_pvt_lock(p);
04973    p->initid = -1;   /* event gone, will not be rescheduled */
04974    if (p->owner) {
04975       /* XXX fails on possible deadlock */
04976       if (!ast_channel_trylock(p->owner)) {
04977          append_history(p, "Cong", "Auto-congesting (timer)");
04978          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
04979          ast_channel_unlock(p->owner);
04980       }
04981 
04982       /* Give the channel a chance to act before we proceed with destruction */
04983       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
04984    }
04985    sip_pvt_unlock(p);
04986    dialog_unref(p, "unreffing arg passed into auto_congest callback (p->initid)");
04987    return 0;
04988 }
04989 
04990 
04991 /*! \brief Initiate SIP call from PBX 
04992  *      used from the dial() application      */
04993 static int sip_call(struct ast_channel *ast, char *dest, int timeout)
04994 {
04995    int res;
04996    struct sip_pvt *p = ast->tech_pvt;  /* chan is locked, so the reference cannot go away */
04997    struct varshead *headp;
04998    struct ast_var_t *current;
04999    const char *referer = NULL;   /* SIP referrer */
05000 
05001    if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
05002       ast_log(LOG_WARNING, "sip_call called on %s, neither down nor reserved\n", ast->name);
05003       return -1;
05004    }
05005 
05006    /* Check whether there is vxml_url, distinctive ring variables */
05007    headp=&ast->varshead;
05008    AST_LIST_TRAVERSE(headp, current, entries) {
05009       /* Check whether there is a VXML_URL variable */
05010       if (!p->options->vxml_url && !strcasecmp(ast_var_name(current), "VXML_URL")) {
05011          p->options->vxml_url = ast_var_value(current);
05012       } else if (!p->options->uri_options && !strcasecmp(ast_var_name(current), "SIP_URI_OPTIONS")) {
05013          p->options->uri_options = ast_var_value(current);
05014       } else if (!p->options->addsipheaders && !strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
05015          /* Check whether there is a variable with a name starting with SIPADDHEADER */
05016          p->options->addsipheaders = 1;
05017       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER")) {
05018          /* This is a transfered call */
05019          p->options->transfer = 1;
05020       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REFERER")) {
05021          /* This is the referrer */
05022          referer = ast_var_value(current);
05023       } else if (!strcasecmp(ast_var_name(current), "SIPTRANSFER_REPLACES")) {
05024          /* We're replacing a call. */
05025          p->options->replaces = ast_var_value(current);
05026       }
05027    }
05028 
05029    res = 0;
05030    ast_set_flag(&p->flags[0], SIP_OUTGOING);
05031 
05032    if (p->options->transfer) {
05033       char buf[SIPBUFSIZE/2];
05034 
05035       if (referer) {
05036          if (sipdebug)
05037             ast_debug(3, "Call for %s transfered by %s\n", p->username, referer);
05038          snprintf(buf, sizeof(buf)-1, "-> %s (via %s)", p->cid_name, referer);
05039       } else 
05040          snprintf(buf, sizeof(buf)-1, "-> %s", p->cid_name);
05041       ast_string_field_set(p, cid_name, buf);
05042    } 
05043    ast_debug(1, "Outgoing Call for %s\n", p->username);
05044 
05045    res = update_call_counter(p, INC_CALL_RINGING);
05046 
05047    if (res == -1) {
05048       ast->hangupcause = AST_CAUSE_USER_BUSY;
05049       return res;
05050    }
05051    p->callingpres = ast->cid.cid_pres;
05052    p->jointcapability = ast_translate_available_formats(p->capability, p->prefcodec);
05053    p->jointnoncodeccapability = p->noncodeccapability;
05054 
05055    /* If there are no audio formats left to offer, punt */
05056    if (!(p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
05057       ast_log(LOG_WARNING, "No audio format found to offer. Cancelling call to %s\n", p->username);
05058       res = -1;
05059    } else {
05060       int xmitres;
05061 
05062       xmitres = transmit_invite(p, SIP_INVITE, 1, 2);
05063       if (xmitres == XMIT_ERROR)
05064          return -1;
05065       p->invitestate = INV_CALLING;
05066    
05067       /* Initialize auto-congest time */
05068       AST_SCHED_REPLACE_UNREF(p->initid, sched, p->timer_b, auto_congest, p, 
05069                         dialog_unref(_data, "dialog ptr dec when SCHED_REPLACE del op succeeded"), 
05070                         dialog_unref(p, "dialog ptr dec when SCHED_REPLACE add failed"),
05071                         dialog_ref(p, "dialog ptr inc when SCHED_REPLACE add succeeded") );
05072    }
05073    return res;
05074 }
05075 
05076 /*! \brief Destroy registry object
05077    Objects created with the register= statement in static configuration */
05078 static void sip_registry_destroy(struct sip_registry *reg)
05079 {
05080    /* Really delete */
05081    ast_debug(3, "Destroying registry entry for %s@%s\n", reg->username, reg->hostname);
05082 
05083    if (reg->call) {
05084       /* Clear registry before destroying to ensure
05085          we don't get reentered trying to grab the registry lock */
05086       reg->call->registry = registry_unref(reg->call->registry, "destroy reg->call->registry");
05087       ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", reg->username, reg->hostname);
05088       dialog_unlink_all(reg->call, TRUE, TRUE);
05089       reg->call = dialog_unref(reg->call, "unref reg->call");
05090       /* reg->call = sip_destroy(reg->call); */
05091    }
05092    AST_SCHED_DEL(sched, reg->expire);  
05093    AST_SCHED_DEL(sched, reg->timeout);
05094    
05095    ast_string_field_free_memory(reg);
05096    ast_atomic_fetchadd_int(&regobjs, -1);
05097    ast_dnsmgr_release(reg->dnsmgr);
05098    ast_free(reg);
05099 }
05100 
05101 /*! \brief Execute destruction of SIP dialog structure, release memory */
05102 static void __sip_destroy(struct sip_pvt *p, int lockowner, int lockdialoglist)
05103 {
05104    struct sip_request *req;
05105 
05106    if (p->stimer) {
05107       ast_free(p->stimer);
05108       p->stimer = NULL;
05109    }
05110 
05111    if (sip_debug_test_pvt(p))
05112       ast_verbose("Really destroying SIP dialog '%s' Method: %s\n", p->callid, sip_methods[p->method].text);
05113 
05114    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05115       update_call_counter(p, DEC_CALL_LIMIT);
05116       ast_debug(2, "This call did not properly clean up call limits. Call ID %s\n", p->callid);
05117    }
05118 
05119    /* Unlink us from the owner if we have one */
05120    if (p->owner) {
05121       if (lockowner)
05122          ast_channel_lock(p->owner);
05123       if (option_debug)
05124          ast_log(LOG_DEBUG, "Detaching from %s\n", p->owner->name);
05125       p->owner->tech_pvt = NULL;
05126       /* Make sure that the channel knows its backend is going away */
05127       p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
05128       if (lockowner)
05129          ast_channel_unlock(p->owner);
05130       /* Give the channel a chance to react before deallocation */
05131       usleep(1);
05132    }
05133 
05134    /* Remove link from peer to subscription of MWI */
05135    if (p->relatedpeer && p->relatedpeer->mwipvt)
05136       p->relatedpeer->mwipvt = dialog_unref(p->relatedpeer->mwipvt, "delete ->relatedpeer->mwipvt");
05137    if (p->relatedpeer && p->relatedpeer->call == p)
05138       p->relatedpeer->call = dialog_unref(p->relatedpeer->call, "unset the relatedpeer->call field in tandem with relatedpeer field itself");
05139    
05140    if (p->relatedpeer)
05141       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting a dialog relatedpeer field in sip_destroy");
05142    
05143    if (p->registry) {
05144       if (p->registry->call == p)
05145          p->registry->call = dialog_unref(p->registry->call, "nulling out the registry's call dialog field in unlink_all");
05146       p->registry = registry_unref(p->registry, "delete p->registry");
05147    }
05148    
05149    if (dumphistory)
05150       sip_dump_history(p);
05151 
05152    if (p->options)
05153       ast_free(p->options);
05154 
05155    if (p->notify_headers) {
05156       ast_variables_destroy(p->notify_headers);
05157       p->notify_headers = NULL;
05158    }
05159    if (p->rtp) {
05160       ast_rtp_destroy(p->rtp);
05161    }
05162    if (p->vrtp) {
05163       ast_rtp_destroy(p->vrtp);
05164    }
05165    if (p->trtp) {
05166       while (ast_rtp_get_bridged(p->trtp))
05167          usleep(1);
05168       ast_rtp_destroy(p->trtp);
05169    }
05170    if (p->udptl)
05171       ast_udptl_destroy(p->udptl);
05172    if (p->refer)
05173       ast_free(p->refer);
05174    if (p->route) {
05175       free_old_route(p->route);
05176       p->route = NULL;
05177    }
05178    if (p->initreq.data)
05179       ast_free(p->initreq.data);
05180 
05181    /* Destroy Session-Timers if allocated */
05182    if (p->stimer) {
05183       p->stimer->quit_flag = 1;
05184       if (p->stimer->st_active == TRUE && p->stimer->st_schedid > -1) {
05185          AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
05186                dialog_unref(p, "removing session timer ref"));
05187       }
05188       ast_free(p->stimer);
05189       p->stimer = NULL;
05190    }
05191 
05192    /* Clear history */
05193    if (p->history) {
05194       struct sip_history *hist;
05195       while ( (hist = AST_LIST_REMOVE_HEAD(p->history, list)) ) {
05196          ast_free(hist);
05197          p->history_entries--;
05198       }
05199       ast_free(p->history);
05200       p->history = NULL;
05201    }
05202 
05203    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
05204       ast_free(req);
05205    }
05206 
05207    if (p->chanvars) {
05208       ast_variables_destroy(p->chanvars);
05209       p->chanvars = NULL;
05210    }
05211 
05212    ast_string_field_free_memory(p);
05213 
05214    if (p->socket.tcptls_session) {
05215       ao2_ref(p->socket.tcptls_session, -1);
05216       p->socket.tcptls_session = NULL;
05217    }
05218 }
05219 
05220 /*! \brief  update_call_counter: Handle call_limit for SIP devices
05221  * Setting a call-limit will cause calls above the limit not to be accepted.
05222  *
05223  * Remember that for a type=friend, there's one limit for the user and
05224  * another for the peer, not a combined call limit.
05225  * This will cause unexpected behaviour in subscriptions, since a "friend"
05226  * is *two* devices in Asterisk, not one.
05227  *
05228  * Thought: For realtime, we should probably update storage with inuse counter... 
05229  *
05230  * \return 0 if call is ok (no call limit, below threshold)
05231  * -1 on rejection of call
05232  *    
05233  */
05234 static int update_call_counter(struct sip_pvt *fup, int event)
05235 {
05236    char name[256];
05237    int *inuse = NULL, *call_limit = NULL, *inringing = NULL;
05238    int outgoing = fup->outgoing_call;
05239    struct sip_peer *p = NULL;
05240 
05241    ast_debug(3, "Updating call counter for %s call\n", outgoing ? "outgoing" : "incoming");
05242 
05243 
05244    /* Test if we need to check call limits, in order to avoid 
05245       realtime lookups if we do not need it */
05246    if (!ast_test_flag(&fup->flags[0], SIP_CALL_LIMIT) && !ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD))
05247       return 0;
05248 
05249    ast_copy_string(name, fup->username, sizeof(name));
05250 
05251    /* Check the list of devices */
05252    if ((p = find_peer(ast_strlen_zero(fup->peername) ? name : fup->peername, NULL, TRUE, FINDALLDEVICES, FALSE, 0))) { /* Try to find peer */
05253       inuse = &p->inUse;
05254       call_limit = &p->call_limit;
05255       inringing = &p->inRinging;
05256       ast_copy_string(name, fup->peername, sizeof(name));
05257    }
05258    if (!p) {
05259       ast_debug(2, "%s is not a local device, no call limit\n", name);
05260       return 0;
05261    }
05262 
05263    switch(event) {
05264    /* incoming and outgoing affects the inUse counter */
05265    case DEC_CALL_LIMIT:
05266       /* Decrement inuse count if applicable */
05267       if (inuse) {
05268          sip_pvt_lock(fup);
05269          ao2_lock(p);
05270          if (*inuse > 0) {
05271             if (ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05272                (*inuse)--;
05273                ast_clear_flag(&fup->flags[0], SIP_INC_COUNT);
05274             }
05275          } else {
05276             *inuse = 0;
05277          }
05278          ao2_unlock(p);
05279          sip_pvt_unlock(fup);
05280       }
05281 
05282       /* Decrement ringing count if applicable */
05283       if (inringing) {
05284          sip_pvt_lock(fup);
05285          ao2_lock(p);
05286          if (*inringing > 0) {
05287             if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05288                (*inringing)--;
05289                ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05290             }
05291          } else {
05292             *inringing = 0;
05293          }
05294          ao2_unlock(p);
05295          sip_pvt_unlock(fup);
05296       }
05297 
05298       /* Decrement onhold count if applicable */
05299       sip_pvt_lock(fup);
05300       ao2_lock(p);
05301       if (ast_test_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD) && global_notifyhold) {
05302          ast_clear_flag(&fup->flags[1], SIP_PAGE2_CALL_ONHOLD);
05303          ao2_unlock(p);
05304          sip_pvt_unlock(fup);
05305          sip_peer_hold(fup, FALSE);
05306       } else {
05307          ao2_unlock(p);
05308          sip_pvt_unlock(fup);
05309       }
05310       if (sipdebug)
05311          ast_debug(2, "Call %s %s '%s' removed from call limit %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05312       break;
05313 
05314    case INC_CALL_RINGING:
05315    case INC_CALL_LIMIT:
05316       /* If call limit is active and we have reached the limit, reject the call */
05317       if (*call_limit > 0 ) {
05318          if (*inuse >= *call_limit) {
05319             ast_log(LOG_ERROR, "Call %s %s '%s' rejected due to usage limit of %d\n", outgoing ? "to" : "from", "peer", name, *call_limit);
05320             unref_peer(p, "update_call_counter: unref peer p, call limit exceeded");
05321             return -1; 
05322          }
05323       }
05324       if (inringing && (event == INC_CALL_RINGING)) {
05325          sip_pvt_lock(fup);
05326          ao2_lock(p);
05327          if (!ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05328             (*inringing)++;
05329             ast_set_flag(&fup->flags[0], SIP_INC_RINGING);
05330          }
05331          ao2_unlock(p);
05332          sip_pvt_unlock(fup);
05333       }
05334       if (inuse) {
05335          sip_pvt_lock(fup);
05336          ao2_lock(p);
05337          if (!ast_test_flag(&fup->flags[0], SIP_INC_COUNT)) {
05338             (*inuse)++;
05339             ast_set_flag(&fup->flags[0], SIP_INC_COUNT);
05340          }
05341          ao2_unlock(p);
05342          sip_pvt_unlock(fup);
05343       }
05344       if (sipdebug) {
05345          ast_debug(2, "Call %s %s '%s' is %d out of %d\n", outgoing ? "to" : "from", "peer", name, *inuse, *call_limit);
05346       }
05347       break;
05348 
05349    case DEC_CALL_RINGING:
05350       if (inringing) {
05351          sip_pvt_lock(fup);
05352          ao2_lock(p);
05353          if (ast_test_flag(&fup->flags[0], SIP_INC_RINGING)) {
05354             if (*inringing > 0) {
05355                (*inringing)--;
05356             }
05357             ast_clear_flag(&fup->flags[0], SIP_INC_RINGING);
05358          }
05359          ao2_unlock(p);
05360          sip_pvt_unlock(fup);
05361       }
05362       break;
05363 
05364    default:
05365       ast_log(LOG_ERROR, "update_call_counter(%s, %d) called with no event!\n", name, event);
05366    }
05367 
05368    if (p) {
05369       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", p->name);
05370       unref_peer(p, "update_call_counter: unref_peer from call counter");
05371    } 
05372    return 0;
05373 }
05374 
05375 
05376 static void sip_destroy_fn(void *p)
05377 {
05378    sip_destroy(p);
05379 }
05380 
05381 /*! \brief Destroy SIP call structure.
05382  * Make it return NULL so the caller can do things like
05383  * foo = sip_destroy(foo);
05384  * and reduce the chance of bugs due to dangling pointers.
05385  */
05386 static struct sip_pvt * sip_destroy(struct sip_pvt *p)
05387 {
05388    ast_debug(3, "Destroying SIP dialog %s\n", p->callid);
05389    __sip_destroy(p, TRUE, TRUE);
05390    return NULL;
05391 }
05392 
05393 /*! \brief Convert SIP hangup causes to Asterisk hangup causes */
05394 static int hangup_sip2cause(int cause)
05395 {
05396    /* Possible values taken from causes.h */
05397 
05398    switch(cause) {
05399       case 401:   /* Unauthorized */
05400          return AST_CAUSE_CALL_REJECTED;
05401       case 403:   /* Not found */
05402          return AST_CAUSE_CALL_REJECTED;
05403       case 404:   /* Not found */
05404          return AST_CAUSE_UNALLOCATED;
05405       case 405:   /* Method not allowed */
05406          return AST_CAUSE_INTERWORKING;
05407       case 407:   /* Proxy authentication required */
05408          return AST_CAUSE_CALL_REJECTED;
05409       case 408:   /* No reaction */
05410          return AST_CAUSE_NO_USER_RESPONSE;
05411       case 409:   /* Conflict */
05412          return AST_CAUSE_NORMAL_TEMPORARY_FAILURE;
05413       case 410:   /* Gone */
05414          return AST_CAUSE_NUMBER_CHANGED;
05415       case 411:   /* Length required */
05416          return AST_CAUSE_INTERWORKING;
05417       case 413:   /* Request entity too large */
05418          return AST_CAUSE_INTERWORKING;
05419       case 414:   /* Request URI too large */
05420          return AST_CAUSE_INTERWORKING;
05421       case 415:   /* Unsupported media type */
05422          return AST_CAUSE_INTERWORKING;
05423       case 420:   /* Bad extension */
05424          return AST_CAUSE_NO_ROUTE_DESTINATION;
05425       case 480:   /* No answer */
05426          return AST_CAUSE_NO_ANSWER;
05427       case 481:   /* No answer */
05428          return AST_CAUSE_INTERWORKING;
05429       case 482:   /* Loop detected */
05430          return AST_CAUSE_INTERWORKING;
05431       case 483:   /* Too many hops */
05432          return AST_CAUSE_NO_ANSWER;
05433       case 484:   /* Address incomplete */
05434          return AST_CAUSE_INVALID_NUMBER_FORMAT;
05435       case 485:   /* Ambiguous */
05436          return AST_CAUSE_UNALLOCATED;
05437       case 486:   /* Busy everywhere */
05438          return AST_CAUSE_BUSY;
05439       case 487:   /* Request terminated */
05440          return AST_CAUSE_INTERWORKING;
05441       case 488:   /* No codecs approved */
05442          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05443       case 491:   /* Request pending */
05444          return AST_CAUSE_INTERWORKING;
05445       case 493:   /* Undecipherable */
05446          return AST_CAUSE_INTERWORKING;
05447       case 500:   /* Server internal failure */
05448          return AST_CAUSE_FAILURE;
05449       case 501:   /* Call rejected */
05450          return AST_CAUSE_FACILITY_REJECTED;
05451       case 502:   
05452          return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
05453       case 503:   /* Service unavailable */
05454          return AST_CAUSE_CONGESTION;
05455       case 504:   /* Gateway timeout */
05456          return AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE;
05457       case 505:   /* SIP version not supported */
05458          return AST_CAUSE_INTERWORKING;
05459       case 600:   /* Busy everywhere */
05460          return AST_CAUSE_USER_BUSY;
05461       case 603:   /* Decline */
05462          return AST_CAUSE_CALL_REJECTED;
05463       case 604:   /* Does not exist anywhere */
05464          return AST_CAUSE_UNALLOCATED;
05465       case 606:   /* Not acceptable */
05466          return AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;
05467       default:
05468          return AST_CAUSE_NORMAL;
05469    }
05470    /* Never reached */
05471    return 0;
05472 }
05473 
05474 /*! \brief Convert Asterisk hangup causes to SIP codes 
05475 \verbatim
05476  Possible values from causes.h
05477         AST_CAUSE_NOTDEFINED    AST_CAUSE_NORMAL        AST_CAUSE_BUSY
05478         AST_CAUSE_FAILURE       AST_CAUSE_CONGESTION    AST_CAUSE_UNALLOCATED
05479 
05480    In addition to these, a lot of PRI codes is defined in causes.h 
05481    ...should we take care of them too ?
05482    
05483    Quote RFC 3398
05484 
05485    ISUP Cause value                        SIP response
05486    ----------------                        ------------
05487    1  unallocated number                   404 Not Found
05488    2  no route to network                  404 Not found
05489    3  no route to destination              404 Not found
05490    16 normal call clearing                 --- (*)
05491    17 user busy                            486 Busy here
05492    18 no user responding                   408 Request Timeout
05493    19 no answer from the user              480 Temporarily unavailable
05494    20 subscriber absent                    480 Temporarily unavailable
05495    21 call rejected                        403 Forbidden (+)
05496    22 number changed (w/o diagnostic)      410 Gone
05497    22 number changed (w/ diagnostic)       301 Moved Permanently
05498    23 redirection to new destination       410 Gone
05499    26 non-selected user clearing           404 Not Found (=)
05500    27 destination out of order             502 Bad Gateway
05501    28 address incomplete                   484 Address incomplete
05502    29 facility rejected                    501 Not implemented
05503    31 normal unspecified                   480 Temporarily unavailable
05504 \endverbatim
05505 */
05506 static const char *hangup_cause2sip(int cause)
05507 {
05508    switch (cause) {
05509       case AST_CAUSE_UNALLOCATED:      /* 1 */
05510       case AST_CAUSE_NO_ROUTE_DESTINATION:   /* 3 IAX2: Can't find extension in context */
05511       case AST_CAUSE_NO_ROUTE_TRANSIT_NET:   /* 2 */
05512          return "404 Not Found";
05513       case AST_CAUSE_CONGESTION:    /* 34 */
05514       case AST_CAUSE_SWITCH_CONGESTION:   /* 42 */
05515          return "503 Service Unavailable";
05516       case AST_CAUSE_NO_USER_RESPONSE: /* 18 */
05517          return "408 Request Timeout";
05518       case AST_CAUSE_NO_ANSWER:     /* 19 */
05519       case AST_CAUSE_UNREGISTERED:        /* 20 */
05520          return "480 Temporarily unavailable";
05521       case AST_CAUSE_CALL_REJECTED:    /* 21 */
05522          return "403 Forbidden";
05523       case AST_CAUSE_NUMBER_CHANGED:      /* 22 */
05524          return "410 Gone";
05525       case AST_CAUSE_NORMAL_UNSPECIFIED:  /* 31 */
05526          return "480 Temporarily unavailable";
05527       case AST_CAUSE_INVALID_NUMBER_FORMAT:
05528          return "484 Address incomplete";
05529       case AST_CAUSE_USER_BUSY:
05530          return "486 Busy here";
05531       case AST_CAUSE_FAILURE:
05532          return "500 Server internal failure";
05533       case AST_CAUSE_FACILITY_REJECTED:   /* 29 */
05534          return "501 Not Implemented";
05535       case AST_CAUSE_CHAN_NOT_IMPLEMENTED:
05536          return "503 Service Unavailable";
05537       /* Used in chan_iax2 */
05538       case AST_CAUSE_DESTINATION_OUT_OF_ORDER:
05539          return "502 Bad Gateway";
05540       case AST_CAUSE_BEARERCAPABILITY_NOTAVAIL: /* Can't find codec to connect to host */
05541          return "488 Not Acceptable Here";
05542          
05543       case AST_CAUSE_NOTDEFINED:
05544       default:
05545          ast_debug(1, "AST hangup cause %d (no match found in SIP)\n", cause);
05546          return NULL;
05547    }
05548 
05549    /* Never reached */
05550    return 0;
05551 }
05552 
05553 
05554 /*! \brief  sip_hangup: Hangup SIP call
05555  * Part of PBX interface, called from ast_hangup */
05556 static int sip_hangup(struct ast_channel *ast)
05557 {
05558    struct sip_pvt *p = ast->tech_pvt;
05559    int needcancel = FALSE;
05560    int needdestroy = 0;
05561    struct ast_channel *oldowner = ast;
05562 
05563    if (!p) {
05564       ast_debug(1, "Asked to hangup channel that was not connected\n");
05565       return 0;
05566    }
05567    if (ast_test_flag(ast, AST_FLAG_ANSWERED_ELSEWHERE)) {
05568       ast_debug(1, "This call was answered elsewhere");
05569       append_history(p, "Cancel", "Call answered elsewhere");
05570       p->answered_elsewhere = TRUE;
05571    }
05572 
05573    /* Store hangupcause locally in PVT so we still have it before disconnect */
05574    if (p->owner)
05575       p->hangupcause = p->owner->hangupcause;
05576 
05577    if (ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
05578       if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05579          if (sipdebug)
05580             ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05581          update_call_counter(p, DEC_CALL_LIMIT);
05582       }
05583       ast_debug(4, "SIP Transfer: Not hanging up right now... Rescheduling hangup for %s.\n", p->callid);
05584       if (p->autokillid > -1 && sip_cancel_destroy(p))
05585          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05586       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05587       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Really hang up next time */
05588       p->needdestroy = 0;
05589       p->owner->tech_pvt = dialog_unref(p->owner->tech_pvt, "unref p->owner->tech_pvt");
05590       sip_pvt_lock(p);
05591       p->owner = NULL;  /* Owner will be gone after we return, so take it away */
05592       sip_pvt_unlock(p);
05593       return 0;
05594    }
05595 
05596    if (ast_test_flag(ast, AST_FLAG_ZOMBIE)) {
05597       if (p->refer)
05598          ast_debug(1, "SIP Transfer: Hanging up Zombie channel %s after transfer ... Call-ID: %s\n", ast->name, p->callid);
05599       else
05600          ast_debug(1, "Hanging up zombie call. Be scared.\n");
05601    } else
05602       ast_debug(1, "Hangup call %s, SIP callid %s\n", ast->name, p->callid);
05603 
05604    sip_pvt_lock(p);
05605    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
05606       if (sipdebug)
05607          ast_debug(1, "update_call_counter(%s) - decrement call limit counter on hangup\n", p->username);
05608       update_call_counter(p, DEC_CALL_LIMIT);
05609    }
05610 
05611    /* Determine how to disconnect */
05612    if (p->owner != ast) {
05613       ast_log(LOG_WARNING, "Huh?  We aren't the owner? Can't hangup call.\n");
05614       sip_pvt_unlock(p);
05615       return 0;
05616    }
05617    /* If the call is not UP, we need to send CANCEL instead of BYE */
05618    /* In case of re-invites, the call might be UP even though we have an incomplete invite transaction */
05619    if (p->invitestate < INV_COMPLETED && p->owner->_state != AST_STATE_UP) {
05620       needcancel = TRUE;
05621       ast_debug(4, "Hanging up channel in state %s (not UP)\n", ast_state2str(ast->_state));
05622    }
05623 
05624    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
05625 
05626    append_history(p, needcancel ? "Cancel" : "Hangup", "Cause %s", p->owner ? ast_cause2str(p->hangupcause) : "Unknown");
05627 
05628    /* Disconnect */
05629    if (p->dsp)
05630       ast_dsp_free(p->dsp);
05631 
05632    p->owner = NULL;
05633    ast->tech_pvt = dialog_unref(ast->tech_pvt, "unref ast->tech_pvt");
05634 
05635    ast_module_unref(ast_module_info->self);
05636    /* Do not destroy this pvt until we have timeout or
05637       get an answer to the BYE or INVITE/CANCEL 
05638       If we get no answer during retransmit period, drop the call anyway.
05639       (Sorry, mother-in-law, you can't deny a hangup by sending
05640       603 declined to BYE...)
05641    */
05642    if (p->alreadygone)
05643       needdestroy = 1;  /* Set destroy flag at end of this function */
05644    else if (p->invitestate != INV_CALLING)
05645       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05646 
05647    /* Start the process if it's not already started */
05648    if (!p->alreadygone && p->initreq.data && !ast_strlen_zero(p->initreq.data->str)) {
05649       if (needcancel) { /* Outgoing call, not up */
05650          if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05651             /* stop retransmitting an INVITE that has not received a response */
05652             /* if we can't send right now, mark it pending */
05653             if (p->invitestate == INV_CALLING) {
05654                /* We can't send anything in CALLING state */
05655                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
05656                __sip_pretend_ack(p);
05657                /* Do we need a timer here if we don't hear from them at all? Yes we do or else we will get hung dialogs and those are no fun. */
05658                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05659                append_history(p, "DELAY", "Not sending cancel, waiting for timeout");
05660             } else {
05661                struct sip_pkt *cur;
05662 
05663                for (cur = p->packets; cur; cur = cur->next) {
05664                   __sip_semi_ack(p, cur->seqno, cur->is_resp, cur->method ? cur->method : find_sip_method(cur->data->str));
05665                }
05666                p->invitestate = INV_CANCELLED;
05667                /* Send a new request: CANCEL */
05668                transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
05669                /* Actually don't destroy us yet, wait for the 487 on our original 
05670                   INVITE, but do set an autodestruct just in case we never get it. */
05671                needdestroy = 0;
05672                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
05673             }
05674          } else { /* Incoming call, not up */
05675             const char *res;
05676             AST_SCHED_DEL(sched, p->provisional_keepalive_sched_id);
05677             if (p->hangupcause && (res = hangup_cause2sip(p->hangupcause)))
05678                transmit_response_reliable(p, res, &p->initreq);
05679             else 
05680                transmit_response_reliable(p, "603 Declined", &p->initreq);
05681             p->invitestate = INV_TERMINATED;
05682          }
05683       } else { /* Call is in UP state, send BYE */
05684          if (p->stimer->st_active == TRUE) {
05685             stop_session_timer(p);
05686          }
05687 
05688          if (!p->pendinginvite) {
05689             struct ast_channel *bridge = ast_bridged_channel(oldowner);
05690             char *audioqos = "";
05691             char *videoqos = "";
05692             char *textqos = "";
05693 
05694             /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
05695              * to lock the bridge. This may get hairy...
05696              */
05697             while (bridge && ast_channel_trylock(bridge)) {
05698                sip_pvt_unlock(p);
05699                do {
05700                   /* Use oldowner since p->owner is already NULL */
05701                   CHANNEL_DEADLOCK_AVOIDANCE(oldowner);
05702                } while (sip_pvt_trylock(p));
05703                bridge = ast_bridged_channel(oldowner);
05704             }
05705 
05706             if (p->rtp)
05707                ast_rtp_set_vars(oldowner, p->rtp);
05708 
05709             if (bridge) {
05710                struct sip_pvt *q = bridge->tech_pvt;
05711 
05712                if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
05713                   ast_rtp_set_vars(bridge, q->rtp);
05714                ast_channel_unlock(bridge);
05715             }
05716 
05717             if (p->vrtp)
05718                videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
05719             if (p->trtp)
05720                textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
05721             /* Send a hangup */
05722             if (oldowner->_state == AST_STATE_UP) {
05723                transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, 1);
05724             }
05725 
05726             /* Get RTCP quality before end of call */
05727             if (p->do_history) {
05728                if (p->rtp)
05729                   append_history(p, "RTCPaudio", "Quality:%s", audioqos);
05730                if (p->vrtp)
05731                   append_history(p, "RTCPvideo", "Quality:%s", videoqos);
05732                if (p->trtp)
05733                   append_history(p, "RTCPtext", "Quality:%s", textqos);
05734             }
05735             if (p->rtp && oldowner)
05736                pbx_builtin_setvar_helper(oldowner, "RTPAUDIOQOS", audioqos);
05737             if (p->vrtp && oldowner)
05738                pbx_builtin_setvar_helper(oldowner, "RTPVIDEOQOS", videoqos);
05739             if (p->trtp && oldowner)
05740                pbx_builtin_setvar_helper(oldowner, "RTPTEXTQOS", textqos);
05741          } else {
05742             /* Note we will need a BYE when this all settles out
05743                but we can't send one while we have "INVITE" outstanding. */
05744             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
05745             ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
05746             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"));
05747             if (sip_cancel_destroy(p))
05748                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
05749          }
05750       }
05751    }
05752    if (needdestroy)
05753       p->needdestroy = 1;
05754    sip_pvt_unlock(p);
05755    return 0;
05756 }
05757 
05758 /*! \brief Try setting codec suggested by the SIP_CODEC channel variable */
05759 static void try_suggested_sip_codec(struct sip_pvt *p)
05760 {
05761    int fmt;
05762    const char *codec;
05763 
05764    codec = pbx_builtin_getvar_helper(p->owner, "SIP_CODEC");
05765    if (!codec) 
05766       return;
05767 
05768    fmt = ast_getformatbyname(codec);
05769    if (fmt) {
05770       ast_log(LOG_NOTICE, "Changing codec to '%s' for this call because of ${SIP_CODEC} variable\n", codec);
05771       if (p->jointcapability & fmt) {
05772          p->jointcapability &= fmt;
05773          p->capability &= fmt;
05774       } else
05775          ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because it is not shared by both ends.\n");
05776    } else
05777       ast_log(LOG_NOTICE, "Ignoring ${SIP_CODEC} variable because of unrecognized/not configured codec (check allow/disallow in sip.conf): %s\n", codec);
05778    return;  
05779 }
05780 
05781 /*! \brief  sip_answer: Answer SIP call , send 200 OK on Invite 
05782  * Part of PBX interface */
05783 static int sip_answer(struct ast_channel *ast)
05784 {
05785    int res = 0;
05786    struct sip_pvt *p = ast->tech_pvt;
05787 
05788    sip_pvt_lock(p);
05789    if (ast->_state != AST_STATE_UP) {
05790       try_suggested_sip_codec(p);   
05791 
05792       ast_setstate(ast, AST_STATE_UP);
05793       ast_debug(1, "SIP answering channel: %s\n", ast->name);
05794       ast_rtp_new_source(p->rtp);
05795       res = transmit_response_with_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL, FALSE);
05796       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
05797    }
05798    sip_pvt_unlock(p);
05799    return res;
05800 }
05801 
05802 /*! \brief Send frame to media channel (rtp) */
05803 static int sip_write(struct ast_channel *ast, struct ast_frame *frame)
05804 {
05805    struct sip_pvt *p = ast->tech_pvt;
05806    int res = 0;
05807 
05808    switch (frame->frametype) {
05809    case AST_FRAME_VOICE:
05810       if (!(frame->subclass & ast->nativeformats)) {
05811          char s1[512], s2[512], s3[512];
05812          ast_log(LOG_WARNING, "Asked to transmit frame type %d, while native formats is %s(%d) read/write = %s(%d)/%s(%d)\n",
05813             frame->subclass, 
05814             ast_getformatname_multiple(s1, sizeof(s1) - 1, ast->nativeformats & AST_FORMAT_AUDIO_MASK),
05815             ast->nativeformats & AST_FORMAT_AUDIO_MASK,
05816             ast_getformatname_multiple(s2, sizeof(s2) - 1, ast->readformat),
05817             ast->readformat,
05818             ast_getformatname_multiple(s3, sizeof(s3) - 1, ast->writeformat),
05819             ast->writeformat);
05820          return 0;
05821       }
05822       if (p) {
05823          sip_pvt_lock(p);
05824          if (p->rtp) {
05825             /* If channel is not up, activate early media session */
05826             if ((ast->_state != AST_STATE_UP) &&
05827                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05828                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05829                ast_rtp_new_source(p->rtp);
05830                if (!global_prematuremediafilter) {
05831                   p->invitestate = INV_EARLY_MEDIA;
05832                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05833                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05834                }
05835             } else if (p->t38.state == T38_ENABLED) {
05836                /* drop frame, can't sent VOICE frames while in T.38 mode */
05837             } else {
05838                p->lastrtptx = time(NULL);
05839                res = ast_rtp_write(p->rtp, frame);
05840             }
05841          }
05842          sip_pvt_unlock(p);
05843       }
05844       break;
05845    case AST_FRAME_VIDEO:
05846       if (p) {
05847          sip_pvt_lock(p);
05848          if (p->vrtp) {
05849             /* Activate video early media */
05850             if ((ast->_state != AST_STATE_UP) &&
05851                 !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05852                 !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05853                p->invitestate = INV_EARLY_MEDIA;
05854                transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05855                ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05856             }
05857             p->lastrtptx = time(NULL);
05858             res = ast_rtp_write(p->vrtp, frame);
05859          }
05860          sip_pvt_unlock(p);
05861       }
05862       break;
05863    case AST_FRAME_TEXT:
05864       if (p) {
05865          sip_pvt_lock(p);
05866          if (p->red) {
05867             red_buffer_t140(p->trtp, frame);
05868          } else {
05869             if (p->trtp) {
05870                /* Activate text early media */
05871                if ((ast->_state != AST_STATE_UP) &&
05872                    !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
05873                    !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
05874                   p->invitestate = INV_EARLY_MEDIA;
05875                   transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
05876                   ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
05877                }
05878                p->lastrtptx = time(NULL);
05879                res = ast_rtp_write(p->trtp, frame);
05880             }
05881          }
05882          sip_pvt_unlock(p);
05883       }
05884       break;
05885    case AST_FRAME_IMAGE:
05886       return 0;
05887       break;
05888    case AST_FRAME_MODEM:
05889       if (p) {
05890          sip_pvt_lock(p);
05891          /* UDPTL requires two-way communication, so early media is not needed here.
05892             we simply forget the frames if we get modem frames before the bridge is up.
05893             Fax will re-transmit.
05894          */
05895          if ((ast->_state == AST_STATE_UP) &&
05896              p->udptl &&
05897              (p->t38.state == T38_ENABLED)) {
05898             res = ast_udptl_write(p->udptl, frame);
05899          }
05900          sip_pvt_unlock(p);
05901       }
05902       break;
05903    default: 
05904       ast_log(LOG_WARNING, "Can't send %d type frames with SIP write\n", frame->frametype);
05905       return 0;
05906    }
05907 
05908    return res;
05909 }
05910 
05911 /*! \brief  sip_fixup: Fix up a channel:  If a channel is consumed, this is called.
05912         Basically update any ->owner links */
05913 static int sip_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
05914 {
05915    int ret = -1;
05916    struct sip_pvt *p;
05917 
05918    if (newchan && ast_test_flag(newchan, AST_FLAG_ZOMBIE))
05919       ast_debug(1, "New channel is zombie\n");
05920    if (oldchan && ast_test_flag(oldchan, AST_FLAG_ZOMBIE))
05921       ast_debug(1, "Old channel is zombie\n");
05922 
05923    if (!newchan || !newchan->tech_pvt) {
05924       if (!newchan)
05925          ast_log(LOG_WARNING, "No new channel! Fixup of %s failed.\n", oldchan->name);
05926       else
05927          ast_log(LOG_WARNING, "No SIP tech_pvt! Fixup of %s failed.\n", oldchan->name);
05928       return -1;
05929    }
05930    p = newchan->tech_pvt;
05931 
05932    sip_pvt_lock(p);
05933    append_history(p, "Masq", "Old channel: %s\n", oldchan->name);
05934    append_history(p, "Masq (cont)", "...new owner: %s\n", newchan->name);
05935    if (p->owner != oldchan)
05936       ast_log(LOG_WARNING, "old channel wasn't %p but was %p\n", oldchan, p->owner);
05937    else {
05938       p->owner = newchan;
05939       /* Re-invite RTP back to Asterisk. Needed if channel is masqueraded out of a native
05940          RTP bridge (i.e., RTP not going through Asterisk): RTP bridge code might not be
05941          able to do this if the masquerade happens before the bridge breaks (e.g., AMI
05942          redirect of both channels). Note that a channel can not be masqueraded *into*
05943          a native bridge. So there is no danger that this breaks a native bridge that
05944          should stay up. */
05945       sip_set_rtp_peer(newchan, NULL, NULL, 0, 0, 0);
05946       ret = 0;
05947    }
05948    ast_debug(3, "SIP Fixup: New owner for dialogue %s: %s (Old parent: %s)\n", p->callid, p->owner->name, oldchan->name);
05949 
05950    sip_pvt_unlock(p);
05951    return ret;
05952 }
05953 
05954 static int sip_senddigit_begin(struct ast_channel *ast, char digit)
05955 {
05956    struct sip_pvt *p = ast->tech_pvt;
05957    int res = 0;
05958 
05959    sip_pvt_lock(p);
05960    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05961    case SIP_DTMF_INBAND:
05962       res = -1; /* Tell Asterisk to generate inband indications */
05963       break;
05964    case SIP_DTMF_RFC2833:
05965       if (p->rtp)
05966          ast_rtp_senddigit_begin(p->rtp, digit);
05967       break;
05968    default:
05969       break;
05970    }
05971    sip_pvt_unlock(p);
05972 
05973    return res;
05974 }
05975 
05976 /*! \brief Send DTMF character on SIP channel
05977    within one call, we're able to transmit in many methods simultaneously */
05978 static int sip_senddigit_end(struct ast_channel *ast, char digit, unsigned int duration)
05979 {
05980    struct sip_pvt *p = ast->tech_pvt;
05981    int res = 0;
05982 
05983    sip_pvt_lock(p);
05984    switch (ast_test_flag(&p->flags[0], SIP_DTMF)) {
05985    case SIP_DTMF_INFO:
05986    case SIP_DTMF_SHORTINFO:
05987       transmit_info_with_digit(p, digit, duration);
05988       break;
05989    case SIP_DTMF_RFC2833:
05990       if (p->rtp)
05991          ast_rtp_senddigit_end(p->rtp, digit);
05992       break;
05993    case SIP_DTMF_INBAND:
05994       res = -1; /* Tell Asterisk to stop inband indications */
05995       break;
05996    }
05997    sip_pvt_unlock(p);
05998 
05999    return res;
06000 }
06001 
06002 /*! \brief Transfer SIP call */
06003 static int sip_transfer(struct ast_channel *ast, const char *dest)
06004 {
06005    struct sip_pvt *p = ast->tech_pvt;
06006    int res;
06007 
06008    if (dest == NULL) /* functions below do not take a NULL */
06009       dest = "";
06010    sip_pvt_lock(p);
06011    if (ast->_state == AST_STATE_RING)
06012       res = sip_sipredirect(p, dest);
06013    else
06014       res = transmit_refer(p, dest);
06015    sip_pvt_unlock(p);
06016    return res;
06017 }
06018 
06019 /*! \brief Helper function which updates T.38 capability information and triggers a reinvite */
06020 static void interpret_t38_parameters(struct sip_pvt *p, const struct ast_control_t38_parameters *parameters)
06021 {
06022    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT)) {
06023       return;
06024    }
06025    switch (parameters->request_response) {
06026    case AST_T38_NEGOTIATED:
06027    case AST_T38_REQUEST_NEGOTIATE:         /* Request T38 */
06028       /* Negotiation can not take place without a valid max_ifp value. */
06029       if (!parameters->max_ifp) {
06030             change_t38_state(p, T38_DISABLED);
06031             if (p->t38.state == T38_PEER_REINVITE) {
06032                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"));
06033                transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06034             }
06035             break;
06036       } else if (p->t38.state == T38_PEER_REINVITE) {
06037          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"));
06038          p->t38.our_parms = *parameters;
06039          /* modify our parameters to conform to the peer's parameters,
06040           * based on the rules in the ITU T.38 recommendation
06041           */
06042          if (!p->t38.their_parms.fill_bit_removal) {
06043             p->t38.our_parms.fill_bit_removal = FALSE;
06044          }
06045          if (!p->t38.their_parms.transcoding_mmr) {
06046             p->t38.our_parms.transcoding_mmr = FALSE;
06047          }
06048          if (!p->t38.their_parms.transcoding_jbig) {
06049             p->t38.our_parms.transcoding_jbig = FALSE;
06050          }
06051          p->t38.our_parms.version = MIN(p->t38.our_parms.version, p->t38.their_parms.version);
06052          p->t38.our_parms.rate_management = p->t38.their_parms.rate_management;
06053          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06054          change_t38_state(p, T38_ENABLED);
06055          transmit_response_with_t38_sdp(p, "200 OK", &p->initreq, XMIT_CRITICAL);
06056       } else if (p->t38.state != T38_ENABLED) {
06057          p->t38.our_parms = *parameters;
06058          ast_udptl_set_local_max_ifp(p->udptl, p->t38.our_parms.max_ifp);
06059          change_t38_state(p, T38_LOCAL_REINVITE);
06060          if (!p->pendinginvite) {
06061             transmit_reinvite_with_sdp(p, TRUE, FALSE);
06062          } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
06063             ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
06064          }
06065       }
06066       break;
06067    case AST_T38_TERMINATED:
06068    case AST_T38_REFUSED:
06069    case AST_T38_REQUEST_TERMINATE:         /* Shutdown T38 */
06070       if (p->t38.state == T38_PEER_REINVITE) {
06071          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"));
06072          change_t38_state(p, T38_DISABLED);
06073          transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
06074       } else if (p->t38.state == T38_ENABLED)
06075          transmit_reinvite_with_sdp(p, FALSE, FALSE);
06076       break;
06077    default:
06078       break;
06079    }
06080 }
06081 
06082 /*! \brief Play indication to user 
06083  * With SIP a lot of indications is sent as messages, letting the device play
06084    the indication - busy signal, congestion etc 
06085    \return -1 to force ast_indicate to send indication in audio, 0 if SIP can handle the indication by sending a message
06086 */
06087 static int sip_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen)
06088 {
06089    struct sip_pvt *p = ast->tech_pvt;
06090    int res = 0;
06091 
06092    sip_pvt_lock(p);
06093    switch(condition) {
06094    case AST_CONTROL_RINGING:
06095       if (ast->_state == AST_STATE_RING) {
06096          p->invitestate = INV_EARLY_MEDIA;
06097          if (!ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) ||
06098              (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) == SIP_PROG_INBAND_NEVER)) {            
06099             /* Send 180 ringing if out-of-band seems reasonable */
06100             transmit_provisional_response(p, "180 Ringing", &p->initreq, 0);
06101             ast_set_flag(&p->flags[0], SIP_RINGING);
06102             if (ast_test_flag(&p->flags[0], SIP_PROG_INBAND) != SIP_PROG_INBAND_YES)
06103                break;
06104          } else {
06105             /* Well, if it's not reasonable, just send in-band */
06106          }
06107       }
06108       res = -1;
06109       break;
06110    case AST_CONTROL_BUSY:
06111       if (ast->_state != AST_STATE_UP) {
06112          transmit_response_reliable(p, "486 Busy Here", &p->initreq);
06113          p->invitestate = INV_COMPLETED;
06114          sip_alreadygone(p);
06115          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06116          break;
06117       }
06118       res = -1;
06119       break;
06120    case AST_CONTROL_CONGESTION:
06121       if (ast->_state != AST_STATE_UP) {
06122          transmit_response_reliable(p, "503 Service Unavailable", &p->initreq);
06123          p->invitestate = INV_COMPLETED;
06124          sip_alreadygone(p);
06125          ast_softhangup_nolock(ast, AST_SOFTHANGUP_DEV);
06126          break;
06127       }
06128       res = -1;
06129       break;
06130    case AST_CONTROL_PROCEEDING:
06131       if ((ast->_state != AST_STATE_UP) &&
06132           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06133           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06134          transmit_response(p, "100 Trying", &p->initreq);
06135          p->invitestate = INV_PROCEEDING;  
06136          break;
06137       }
06138       res = -1;
06139       break;
06140    case AST_CONTROL_PROGRESS:
06141       if ((ast->_state != AST_STATE_UP) &&
06142           !ast_test_flag(&p->flags[0], SIP_PROGRESS_SENT) &&
06143           !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
06144          p->invitestate = INV_EARLY_MEDIA;
06145          transmit_provisional_response(p, "183 Session Progress", &p->initreq, TRUE);
06146          ast_set_flag(&p->flags[0], SIP_PROGRESS_SENT);
06147          break;
06148       }
06149       res = -1;
06150       break;
06151    case AST_CONTROL_HOLD:
06152       ast_rtp_new_source(p->rtp);
06153       ast_moh_start(ast, data, p->mohinterpret);
06154       break;
06155    case AST_CONTROL_UNHOLD:
06156       ast_rtp_new_source(p->rtp);
06157       ast_moh_stop(ast);
06158       break;
06159    case AST_CONTROL_VIDUPDATE:   /* Request a video frame update */
06160       if (p->vrtp && !p->novideo) {
06161          transmit_info_with_vidupdate(p);
06162          /* ast_rtcp_send_h261fur(p->vrtp); */
06163       } else
06164          res = -1;
06165       break;
06166    case AST_CONTROL_T38_PARAMETERS:
06167       if (datalen != sizeof(struct ast_control_t38_parameters)) {
06168          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);
06169       } else {
06170          const struct ast_control_t38_parameters *parameters = data;
06171          interpret_t38_parameters(p, parameters);
06172       }
06173       break;
06174    case AST_CONTROL_SRCUPDATE:
06175       ast_rtp_new_source(p->rtp);
06176       break;
06177    case -1:
06178       res = -1;
06179       break;
06180    default:
06181       ast_log(LOG_WARNING, "Don't know how to indicate condition %d\n", condition);
06182       res = -1;
06183       break;
06184    }
06185    sip_pvt_unlock(p);
06186    return res;
06187 }
06188 
06189 
06190 /*! \brief Initiate a call in the SIP channel
06191    called from sip_request_call (calls from the pbx ) for outbound channels
06192    and from handle_request_invite for inbound channels
06193    
06194 */
06195 static struct ast_channel *sip_new(struct sip_pvt *i, int state, const char *title)
06196 {
06197    struct ast_channel *tmp;
06198    struct ast_variable *v = NULL;
06199    int fmt;
06200    int what;
06201    int video;
06202    int text;
06203    int needvideo = 0;
06204    int needtext = 0;
06205    char buf[SIPBUFSIZE];
06206    char *decoded_exten;
06207 
06208    {
06209       const char *my_name; /* pick a good name */
06210    
06211       if (title)
06212          my_name = title;
06213       else if ( (my_name = strchr(i->fromdomain, ':')) )
06214          my_name++;  /* skip ':' */
06215       else
06216          my_name = i->fromdomain;
06217 
06218       sip_pvt_unlock(i);
06219       /* Don't hold a sip pvt lock while we allocate a channel */
06220       tmp = ast_channel_alloc(1, state, i->cid_num, i->cid_name, i->accountcode, i->exten, i->context, i->amaflags, "SIP/%s-%08x", my_name, ast_atomic_fetchadd_int((int *)&chan_idx, +1));
06221 
06222    }
06223    if (!tmp) {
06224       ast_log(LOG_WARNING, "Unable to allocate AST channel structure for SIP channel\n");
06225       sip_pvt_lock(i);
06226       return NULL;
06227    }
06228    sip_pvt_lock(i);
06229 
06230    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;
06231 
06232    /* Select our native format based on codec preference until we receive
06233       something from another device to the contrary. */
06234    if (i->jointcapability) {  /* The joint capabilities of us and peer */
06235       what = i->jointcapability;
06236       video = i->jointcapability & AST_FORMAT_VIDEO_MASK;
06237       text = i->jointcapability & AST_FORMAT_TEXT_MASK;
06238    } else if (i->capability) {      /* Our configured capability for this peer */
06239       what = i->capability;
06240       video = i->capability & AST_FORMAT_VIDEO_MASK;
06241       text = i->capability & AST_FORMAT_TEXT_MASK;
06242    } else {
06243       what = global_capability;  /* Global codec support */
06244       video = global_capability & AST_FORMAT_VIDEO_MASK;
06245       text = global_capability & AST_FORMAT_TEXT_MASK;
06246    }
06247 
06248    /* Set the native formats for audio  and merge in video */
06249    tmp->nativeformats = ast_codec_choose(&i->prefs, what, 1) | video | text;
06250    ast_debug(3, "*** Our native formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, tmp->nativeformats));
06251    ast_debug(3, "*** Joint capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->jointcapability));
06252    ast_debug(3, "*** Our capabilities are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->capability));
06253    ast_debug(3, "*** AST_CODEC_CHOOSE formats are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, ast_codec_choose(&i->prefs, what, 1)));
06254    if (i->prefcodec)
06255       ast_debug(3, "*** Our preferred formats from the incoming channel are %s \n", ast_getformatname_multiple(buf, SIPBUFSIZE, i->prefcodec));
06256 
06257    /* XXX Why are we choosing a codec from the native formats?? */
06258    fmt = ast_best_codec(tmp->nativeformats);
06259 
06260    /* If we have a prefcodec setting, we have an inbound channel that set a 
06261       preferred format for this call. Otherwise, we check the jointcapability
06262       We also check for vrtp. If it's not there, we are not allowed do any video anyway.
06263     */
06264    if (i->vrtp) {
06265       if (ast_test_flag(&i->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06266          needvideo = AST_FORMAT_VIDEO_MASK;
06267       else if (i->prefcodec)
06268          needvideo = i->prefcodec & AST_FORMAT_VIDEO_MASK;  /* Outbound call */
06269       else
06270          needvideo = i->jointcapability & AST_FORMAT_VIDEO_MASK;  /* Inbound call */
06271    }
06272 
06273    if (i->trtp) {
06274       if (i->prefcodec)
06275          needtext = i->prefcodec & AST_FORMAT_TEXT_MASK; /* Outbound call */
06276       else
06277          needtext = i->jointcapability & AST_FORMAT_TEXT_MASK; /* Inbound call */
06278    }
06279 
06280    if (needvideo) 
06281       ast_debug(3, "This channel can handle video! HOLLYWOOD next!\n");
06282    else
06283       ast_debug(3, "This channel will not be able to handle video.\n");
06284 
06285    if ((ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || (ast_test_flag(&i->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) ||
06286        (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT))) {
06287       int features = DSP_FEATURE_DIGIT_DETECT;
06288 
06289       if (ast_test_flag(&i->flags[1], SIP_PAGE2_FAX_DETECT)) {
06290          features |= DSP_FEATURE_FAX_DETECT;
06291       }
06292 
06293       i->dsp = ast_dsp_new();
06294       ast_dsp_set_features(i->dsp, features);
06295       if (global_relaxdtmf)
06296          ast_dsp_set_digitmode(i->dsp, DSP_DIGITMODE_DTMF | DSP_DIGITMODE_RELAXDTMF);
06297          }
06298 
06299    /* Set file descriptors for audio, video, realtime text and UDPTL as needed */
06300    if (i->rtp) {
06301       ast_channel_set_fd(tmp, 0, ast_rtp_fd(i->rtp));
06302       ast_channel_set_fd(tmp, 1, ast_rtcp_fd(i->rtp));
06303    }
06304    if (needvideo && i->vrtp) {
06305       ast_channel_set_fd(tmp, 2, ast_rtp_fd(i->vrtp));
06306       ast_channel_set_fd(tmp, 3, ast_rtcp_fd(i->vrtp));
06307    }
06308    if (needtext && i->trtp) 
06309       ast_channel_set_fd(tmp, 4, ast_rtp_fd(i->trtp));
06310    if (i->udptl)
06311       ast_channel_set_fd(tmp, 5, ast_udptl_fd(i->udptl));
06312 
06313    if (state == AST_STATE_RING)
06314       tmp->rings = 1;
06315    tmp->adsicpe = AST_ADSI_UNAVAILABLE;
06316    tmp->writeformat = fmt;
06317    tmp->rawwriteformat = fmt;
06318    tmp->readformat = fmt;
06319    tmp->rawreadformat = fmt;
06320    tmp->tech_pvt = dialog_ref(i, "sip_new: set chan->tech_pvt to i");
06321 
06322    tmp->callgroup = i->callgroup;
06323    tmp->pickupgroup = i->pickupgroup;
06324    tmp->cid.cid_pres = i->callingpres;
06325    if (!ast_strlen_zero(i->parkinglot))
06326       ast_string_field_set(tmp, parkinglot, i->parkinglot);
06327    if (!ast_strlen_zero(i->accountcode))
06328       ast_string_field_set(tmp, accountcode, i->accountcode);
06329    if (i->amaflags)
06330       tmp->amaflags = i->amaflags;
06331    if (!ast_strlen_zero(i->language))
06332       ast_string_field_set(tmp, language, i->language);
06333    i->owner = tmp;
06334    ast_module_ref(ast_module_info->self);
06335    ast_copy_string(tmp->context, i->context, sizeof(tmp->context));
06336    /*Since it is valid to have extensions in the dialplan that have unescaped characters in them
06337     * we should decode the uri before storing it in the channel, but leave it encoded in the sip_pvt
06338     * structure so that there aren't issues when forming URI's
06339     */
06340    decoded_exten = ast_strdupa(i->exten);
06341    ast_uri_decode(decoded_exten);
06342    ast_copy_string(tmp->exten, decoded_exten, sizeof(tmp->exten));
06343 
06344    /* Don't use ast_set_callerid() here because it will
06345     * generate an unnecessary NewCallerID event  */
06346    tmp->cid.cid_ani = ast_strdup(i->cid_num);
06347    if (!ast_strlen_zero(i->rdnis))
06348       tmp->cid.cid_rdnis = ast_strdup(i->rdnis);
06349    
06350    if (!ast_strlen_zero(i->exten) && strcmp(i->exten, "s"))
06351       tmp->cid.cid_dnid = ast_strdup(i->exten);
06352 
06353    tmp->priority = 1;
06354    if (!ast_strlen_zero(i->uri))
06355       pbx_builtin_setvar_helper(tmp, "SIPURI", i->uri);
06356    if (!ast_strlen_zero(i->domain))
06357       pbx_builtin_setvar_helper(tmp, "SIPDOMAIN", i->domain);
06358    if (!ast_strlen_zero(i->callid))
06359       pbx_builtin_setvar_helper(tmp, "SIPCALLID", i->callid);
06360    if (i->rtp)
06361       ast_jb_configure(tmp, &global_jbconf);
06362 
06363    /* Set channel variables for this call from configuration */
06364    for (v = i->chanvars ; v ; v = v->next)
06365       pbx_builtin_setvar_helper(tmp, v->name, v->value);
06366 
06367    if (state != AST_STATE_DOWN && ast_pbx_start(tmp)) {
06368       ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
06369       tmp->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
06370       ast_hangup(tmp);
06371       tmp = NULL;
06372    }
06373 
06374    if (i->do_history)
06375       append_history(i, "NewChan", "Channel %s - from %s", tmp->name, i->callid);
06376 
06377    /* Inform manager user about new channel and their SIP call ID */
06378    if (global_callevents)
06379       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
06380          "Channel: %s\r\nUniqueid: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\n",
06381          tmp->name, tmp->uniqueid, "SIP", i->callid, i->fullcontact);
06382 
06383    return tmp;
06384 }
06385 
06386 /*! \brief Reads one line of SIP message body */
06387 static char *get_body_by_line(const char *line, const char *name, int nameLen)
06388 {
06389    if (!strncasecmp(line, name, nameLen) && line[nameLen] == '=')
06390       return ast_skip_blanks(line + nameLen + 1);
06391 
06392    return "";
06393 }
06394 
06395 /*! \brief Lookup 'name' in the SDP starting
06396  * at the 'start' line. Returns the matching line, and 'start'
06397  * is updated with the next line number.
06398  */
06399 static const char *get_sdp_iterate(int *start, struct sip_request *req, const char *name)
06400 {
06401    int len = strlen(name);
06402 
06403    while (*start < (req->sdp_start + req->sdp_count)) {
06404       const char *r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[(*start)++]), name, len);
06405       if (r[0] != '\0')
06406          return r;
06407    }
06408 
06409    /* if the line was not found, ensure that *start points past the SDP */
06410    (*start)++;
06411 
06412    return "";
06413 }
06414 
06415 /*! \brief Fetches the next valid SDP line between the 'start' line
06416  * (inclusive) and the 'stop' line (exclusive). Returns the type
06417  * ('a', 'c', ...) and matching line in reference 'start' is updated
06418  * with the next line number.
06419  */
06420 static char get_sdp_line(int *start, int stop, struct sip_request *req, const char **value)
06421 {
06422    char type = '\0';
06423    const char *line = NULL;
06424 
06425    if (stop > (req->sdp_start + req->sdp_count)) {
06426       stop = req->sdp_start + req->sdp_count;
06427    }
06428 
06429    while (*start < stop) {
06430       line = REQ_OFFSET_TO_STR(req, line[(*start)++]);
06431       if (line[1] == '=') {
06432          type = line[0];
06433          *value = ast_skip_blanks(line + 2);
06434          break;
06435       }
06436    }
06437 
06438    return type;
06439 }
06440 
06441 /*! \brief Get a specific line from the message body */
06442 static char *get_body(struct sip_request *req, char *name) 
06443 {
06444    int x;
06445    int len = strlen(name);
06446    char *r;
06447 
06448    for (x = 0; x < req->lines; x++) {
06449       r = get_body_by_line(REQ_OFFSET_TO_STR(req, line[x]), name, len);
06450       if (r[0] != '\0')
06451          return r;
06452    }
06453 
06454    return "";
06455 }
06456 
06457 /*! \brief Find compressed SIP alias */
06458 static const char *find_alias(const char *name, const char *_default)
06459 {
06460    /*! \brief Structure for conversion between compressed SIP and "normal" SIP */
06461    static const struct cfalias {
06462       char * const fullname;
06463       char * const shortname;
06464    } aliases[] = {
06465       { "Content-Type",  "c" },
06466       { "Content-Encoding",    "e" },
06467       { "From",       "f" },
06468       { "Call-ID",       "i" },
06469       { "Contact",       "m" },
06470       { "Content-Length",   "l" },
06471       { "Subject",       "s" },
06472       { "To",         "t" },
06473       { "Supported",     "k" },
06474       { "Refer-To",      "r" },
06475       { "Referred-By",   "b" },
06476       { "Allow-Events",  "u" },
06477       { "Event",      "o" },
06478       { "Via",     "v" },
06479       { "Accept-Contact",      "a" },
06480       { "Reject-Contact",      "j" },
06481       { "Request-Disposition", "d" },
06482       { "Session-Expires",     "x" },
06483       { "Identity",            "y" },
06484       { "Identity-Info",       "n" },
06485    };
06486    int x;
06487 
06488    for (x = 0; x < ARRAY_LEN(aliases); x++) {
06489       if (!strcasecmp(aliases[x].fullname, name))
06490          return aliases[x].shortname;
06491    }
06492 
06493    return _default;
06494 }
06495 
06496 static const char *__get_header(const struct sip_request *req, const char *name, int *start)
06497 {
06498    int pass;
06499 
06500    /*
06501     * Technically you can place arbitrary whitespace both before and after the ':' in
06502     * a header, although RFC3261 clearly says you shouldn't before, and place just
06503     * one afterwards.  If you shouldn't do it, what absolute idiot decided it was 
06504     * a good idea to say you can do it, and if you can do it, why in the hell would.
06505     * you say you shouldn't.
06506     * Anyways, pedanticsipchecking controls whether we allow spaces before ':',
06507     * and we always allow spaces after that for compatibility.
06508     */
06509    for (pass = 0; name && pass < 2;pass++) {
06510       int x, len = strlen(name);
06511       for (x = *start; x < req->headers; x++) {
06512          char *header = REQ_OFFSET_TO_STR(req, header[x]);
06513          if (!strncasecmp(header, name, len)) {
06514             char *r = header + len; /* skip name */
06515             if (pedanticsipchecking)
06516                r = ast_skip_blanks(r);
06517 
06518             if (*r == ':') {
06519                *start = x+1;
06520                return ast_skip_blanks(r+1);
06521             }
06522          }
06523       }
06524       if (pass == 0) /* Try aliases */
06525          name = find_alias(name, NULL);
06526    }
06527 
06528    /* Don't return NULL, so get_header is always a valid pointer */
06529    return "";
06530 }
06531 
06532 /*! \brief Get header from SIP request 
06533    \return Always return something, so don't check for NULL because it won't happen :-)
06534 */
06535 static const char *get_header(const struct sip_request *req, const char *name)
06536 {
06537    int start = 0;
06538    return __get_header(req, name, &start);
06539 }
06540 
06541 /*! \brief Read RTP from network */
06542 static struct ast_frame *sip_rtp_read(struct ast_channel *ast, struct sip_pvt *p, int *faxdetect)
06543 {
06544    /* Retrieve audio/etc from channel.  Assumes p->lock is already held. */
06545    struct ast_frame *f;
06546    
06547    if (!p->rtp) {
06548       /* We have no RTP allocated for this channel */
06549       return &ast_null_frame;
06550    }
06551 
06552    switch(ast->fdno) {
06553    case 0:
06554       f = ast_rtp_read(p->rtp);  /* RTP Audio */
06555       break;
06556    case 1:
06557       f = ast_rtcp_read(p->rtp); /* RTCP Control Channel */
06558       break;
06559    case 2:
06560       f = ast_rtp_read(p->vrtp); /* RTP Video */
06561       break;
06562    case 3:
06563       f = ast_rtcp_read(p->vrtp);   /* RTCP Control Channel for video */
06564       break;
06565    case 4:
06566       f = ast_rtp_read(p->trtp); /* RTP Text */
06567       if (sipdebug_text) {
06568          int i;
06569          unsigned char* arr = f->data.ptr;
06570          for (i=0; i < f->datalen; i++)
06571             ast_verbose("%c", (arr[i] > ' ' && arr[i] < '}') ? arr[i] : '.');
06572          ast_verbose(" -> ");
06573          for (i=0; i < f->datalen; i++)
06574             ast_verbose("%02X ", arr[i]);
06575          ast_verbose("\n");
06576       }
06577       break;
06578    case 5:
06579       f = ast_udptl_read(p->udptl); /* UDPTL for T.38 */
06580       break;
06581    default:
06582       f = &ast_null_frame;
06583    }
06584    /* Don't forward RFC2833 if we're not supposed to */
06585    if (f && (f->frametype == AST_FRAME_DTMF_BEGIN || f->frametype == AST_FRAME_DTMF_END) &&
06586        (ast_test_flag(&p->flags[0], SIP_DTMF) != SIP_DTMF_RFC2833)) {
06587       ast_debug(1, "Ignoring DTMF (%c) RTP frame because dtmfmode is not RFC2833\n", f->subclass);
06588       return &ast_null_frame;
06589    }
06590 
06591    /* We already hold the channel lock */
06592    if (!p->owner || (f && f->frametype != AST_FRAME_VOICE))
06593       return f;
06594 
06595    if (f && f->subclass != (p->owner->nativeformats & AST_FORMAT_AUDIO_MASK)) {
06596       if (!(f->subclass & p->jointcapability)) {
06597          ast_debug(1, "Bogus frame of format '%s' received from '%s'!\n",
06598             ast_getformatname(f->subclass), p->owner->name);
06599          return &ast_null_frame;
06600       }
06601       ast_debug(1, "Oooh, format changed to %d %s\n",
06602          f->subclass, ast_getformatname(f->subclass));
06603       p->owner->nativeformats = (p->owner->nativeformats & (AST_FORMAT_VIDEO_MASK | AST_FORMAT_TEXT_MASK)) | f->subclass;
06604       ast_set_read_format(p->owner, p->owner->readformat);
06605       ast_set_write_format(p->owner, p->owner->writeformat);
06606    }
06607 
06608    if (f && ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) || ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) && p->dsp) {
06609       f = ast_dsp_process(p->owner, p->dsp, f);
06610                 if (f && f->frametype == AST_FRAME_DTMF) {
06611          if (f->subclass == 'f') {
06612                                 if (option_debug)
06613                                         ast_log(LOG_DEBUG, "Fax CNG detected on %s\n", ast->name);
06614                                 *faxdetect = 1;
06615             /* If we only needed this DSP for fax detection purposes we can just drop it now */
06616             if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
06617                ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
06618             } else {
06619                ast_dsp_free(p->dsp);
06620                p->dsp = NULL;
06621             }
06622          } else {
06623             ast_debug(1, "* Detected inband DTMF '%c'\n", f->subclass);
06624          }
06625       }
06626    }
06627    
06628    return f;
06629 }
06630 
06631 /*! \brief Read SIP RTP from channel */
06632 static struct ast_frame *sip_read(struct ast_channel *ast)
06633 {
06634    struct ast_frame *fr;
06635    struct sip_pvt *p = ast->tech_pvt;
06636    int faxdetected = FALSE;
06637 
06638    sip_pvt_lock(p);
06639    fr = sip_rtp_read(ast, p, &faxdetected);
06640    p->lastrtprx = time(NULL);
06641 
06642    /* If we detect a CNG tone and fax detection is enabled then send us off to the fax extension */
06643    if (faxdetected && ast_test_flag(&p->flags[1], SIP_PAGE2_FAX_DETECT)) {
06644       ast_channel_lock(ast);
06645       if (strcmp(ast->exten, "fax")) {
06646          const char *target_context = S_OR(ast->macrocontext, ast->context);
06647          ast_channel_unlock(ast);
06648          if (ast_exists_extension(ast, target_context, "fax", 1, ast->cid.cid_num)) {
06649             ast_verbose(VERBOSE_PREFIX_2 "Redirecting '%s' to fax extension\n", ast->name);
06650             pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast->exten);
06651             if (ast_async_goto(ast, target_context, "fax", 1)) {
06652                ast_log(LOG_NOTICE, "Failed to async goto '%s' into fax of '%s'\n", ast->name, target_context);
06653             }
06654             fr = &ast_null_frame;
06655          } else {
06656             ast_log(LOG_NOTICE, "Fax detected but no fax extension\n");
06657                         }
06658       } else {
06659          ast_channel_unlock(ast);
06660                 }
06661         }
06662 
06663    /* Only allow audio through if they sent progress with SDP, or if the channel is actually answered */
06664    if (fr && fr->frametype == AST_FRAME_VOICE && p->invitestate != INV_EARLY_MEDIA && ast->_state != AST_STATE_UP) {
06665       fr = &ast_null_frame;
06666    }
06667 
06668    sip_pvt_unlock(p);
06669 
06670    return fr;
06671 }
06672 
06673 
06674 /*! \brief Generate 32 byte random string for callid's etc */
06675 static char *generate_random_string(char *buf, size_t size)
06676 {
06677    long val[4];
06678    int x;
06679 
06680    for (x=0; x<4; x++)
06681       val[x] = ast_random();
06682    snprintf(buf, size, "%08lx%08lx%08lx%08lx", val[0], val[1], val[2], val[3]);
06683 
06684    return buf;
06685 }
06686 
06687 /*! \brief Build SIP Call-ID value for a non-REGISTER transaction */
06688 static void build_callid_pvt(struct sip_pvt *pvt)
06689 {
06690    char buf[33];
06691 
06692    const char *host = S_OR(pvt->fromdomain, ast_inet_ntoa(pvt->ourip.sin_addr));
06693    
06694    ast_string_field_build(pvt, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06695 
06696 }
06697 
06698 /*! \brief Build SIP Call-ID value for a REGISTER transaction */
06699 static void build_callid_registry(struct sip_registry *reg, struct in_addr ourip, const char *fromdomain)
06700 {
06701    char buf[33];
06702 
06703    const char *host = S_OR(fromdomain, ast_inet_ntoa(ourip));
06704 
06705    ast_string_field_build(reg, callid, "%s@%s", generate_random_string(buf, sizeof(buf)), host);
06706 }
06707 
06708 /*! \brief Make our SIP dialog tag */
06709 static void make_our_tag(char *tagbuf, size_t len)
06710 {
06711    snprintf(tagbuf, len, "as%08lx", ast_random());
06712 }
06713 
06714 /*! \brief Allocate Session-Timers struct w/in dialog */
06715 static struct sip_st_dlg* sip_st_alloc(struct sip_pvt *const p)
06716 {
06717    struct sip_st_dlg *stp;
06718 
06719    if (p->stimer) {
06720       ast_log(LOG_ERROR, "Session-Timer struct already allocated\n");
06721       return p->stimer;
06722    }
06723 
06724    if (!(stp = ast_calloc(1, sizeof(struct sip_st_dlg))))
06725       return NULL;
06726 
06727    p->stimer = stp;
06728 
06729    stp->st_schedid = -1;           /* Session-Timers ast_sched scheduler id */
06730 
06731    return p->stimer;
06732 }
06733 
06734 /*! \brief Allocate sip_pvt structure, set defaults and link in the container.
06735  * Returns a reference to the object so whoever uses it later must
06736  * remember to release the reference.
06737  */
06738 static struct sip_pvt *sip_alloc(ast_string_field callid, struct sockaddr_in *sin,
06739              int useglobal_nat, const int intended_method, struct sip_request *req)
06740 {
06741    struct sip_pvt *p;
06742 
06743    if (!(p = ao2_t_alloc(sizeof(*p), sip_destroy_fn, "allocate a dialog(pvt) struct")))
06744       return NULL;
06745 
06746    if (ast_string_field_init(p, 512)) {
06747       ao2_t_ref(p, -1, "failed to string_field_init, drop p");
06748       return NULL;
06749    }
06750 
06751    if (req) {
06752       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 */
06753    } else {
06754       set_socket_transport(&p->socket, SIP_TRANSPORT_UDP);
06755    }
06756 
06757    p->socket.fd = -1;
06758    p->method = intended_method;
06759    p->initid = -1;
06760    p->waitid = -1;
06761    p->autokillid = -1;
06762    p->request_queue_sched_id = -1;
06763    p->provisional_keepalive_sched_id = -1;
06764    p->t38id = -1;
06765    p->subscribed = NONE;
06766    p->stateid = -1;
06767    p->sessionversion_remote = -1;
06768    p->session_modify = TRUE;
06769    p->stimer = NULL;
06770    p->prefs = default_prefs;     /* Set default codecs for this call */
06771 
06772    if (intended_method != SIP_OPTIONS) {  /* Peerpoke has it's own system */
06773       p->timer_t1 = global_t1;   /* Default SIP retransmission timer T1 (RFC 3261) */
06774       p->timer_b = global_timer_b;  /* Default SIP transaction timer B (RFC 3261) */
06775    }
06776 
06777    if (!sin)
06778       p->ourip = internip;
06779    else {
06780       p->sa = *sin;
06781       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
06782    }
06783 
06784    /* Copy global flags to this PVT at setup. */
06785    ast_copy_flags(&p->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
06786    ast_copy_flags(&p->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
06787 
06788    p->do_history = recordhistory;
06789 
06790    p->branch = ast_random();  
06791    make_our_tag(p->tag, sizeof(p->tag));
06792    p->ocseq = INITIAL_CSEQ;
06793 
06794    if (sip_methods[intended_method].need_rtp) {
06795       p->rtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06796       /* If the global videosupport flag is on, we always create a RTP interface for video */
06797       if (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT))
06798          p->vrtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06799       if (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT))
06800          p->trtp = ast_rtp_new_with_bindaddr(sched, io, 1, 0, bindaddr.sin_addr);
06801       if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT))
06802          p->udptl = ast_udptl_new_with_bindaddr(sched, io, 0, bindaddr.sin_addr);
06803       if (!p->rtp|| (ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) && !p->vrtp) 
06804             || (ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) && !p->trtp)) {
06805          ast_log(LOG_WARNING, "Unable to create RTP audio %s%ssession: %s\n",
06806             ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "and video " : "",
06807             ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "and text " : "", strerror(errno));
06808          if (p->chanvars) {
06809             ast_variables_destroy(p->chanvars);
06810             p->chanvars = NULL;
06811          }
06812          ao2_t_ref(p, -1, "failed to create RTP audio session, drop p");
06813          return NULL;
06814          p->t38_maxdatagram = global_t38_maxdatagram;
06815       }
06816       ast_rtp_setqos(p->rtp, global_tos_audio, global_cos_audio, "SIP RTP");
06817       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
06818       ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
06819       ast_rtp_set_rtptimeout(p->rtp, global_rtptimeout);
06820       ast_rtp_set_rtpholdtimeout(p->rtp, global_rtpholdtimeout);
06821       ast_rtp_set_rtpkeepalive(p->rtp, global_rtpkeepalive);
06822       if (p->vrtp) {
06823          ast_rtp_setqos(p->vrtp, global_tos_video, global_cos_video, "SIP VRTP");
06824          ast_rtp_setdtmf(p->vrtp, 0);
06825          ast_rtp_setdtmfcompensate(p->vrtp, 0);
06826          ast_rtp_set_rtptimeout(p->vrtp, global_rtptimeout);
06827          ast_rtp_set_rtpholdtimeout(p->vrtp, global_rtpholdtimeout);
06828          ast_rtp_set_rtpkeepalive(p->vrtp, global_rtpkeepalive);
06829       }
06830       if (p->trtp) {
06831          ast_rtp_setqos(p->trtp, global_tos_text, global_cos_text, "SIP TRTP");
06832          ast_rtp_setdtmf(p->trtp, 0);
06833          ast_rtp_setdtmfcompensate(p->trtp, 0);
06834       }
06835       if (p->udptl)
06836          ast_udptl_setqos(p->udptl, global_tos_audio, global_cos_audio);
06837       p->maxcallbitrate = default_maxcallbitrate;
06838       p->autoframing = global_autoframing;
06839       ast_rtp_codec_setpref(p->rtp, &p->prefs);
06840    }
06841 
06842    if (useglobal_nat && sin) {
06843       /* Setup NAT structure according to global settings if we have an address */
06844       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
06845       p->recv = *sin;
06846       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
06847    }
06848 
06849    if (p->method != SIP_REGISTER)
06850       ast_string_field_set(p, fromdomain, default_fromdomain);
06851    build_via(p);
06852    if (!callid)
06853       build_callid_pvt(p);
06854    else
06855       ast_string_field_set(p, callid, callid);
06856    /* Assign default music on hold class */
06857    ast_string_field_set(p, mohinterpret, default_mohinterpret);
06858    ast_string_field_set(p, mohsuggest, default_mohsuggest);
06859    p->capability = global_capability;
06860    p->allowtransfer = global_allowtransfer;
06861    if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
06862        (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
06863       p->noncodeccapability |= AST_RTP_DTMF;
06864    if (p->udptl) {
06865       p->t38_maxdatagram = global_t38_maxdatagram;
06866       set_t38_capabilities(p);
06867    }
06868    ast_string_field_set(p, context, default_context);
06869    ast_string_field_set(p, parkinglot, default_parkinglot);
06870 
06871    AST_LIST_HEAD_INIT_NOLOCK(&p->request_queue);
06872 
06873    /* Add to active dialog list */
06874 
06875    ao2_t_link(dialogs, p, "link pvt into dialogs table");
06876    
06877    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");
06878    return p;
06879 }
06880 
06881 /*! \brief argument to the helper function to identify a call */
06882 struct find_call_cb_arg {
06883    enum sipmethod method;
06884    const char *callid;
06885    const char *fromtag;
06886    const char *totag;
06887    const char *tag;
06888 };
06889 
06890 /*!
06891  * code to determine whether this is the pvt that we are looking for.
06892  * Return FALSE if not found, true otherwise. p is unlocked.
06893  */
06894 static int find_call_cb(void *__pvt, void *__arg, int flags)
06895 {
06896    struct sip_pvt *p = __pvt;
06897    struct find_call_cb_arg *arg = __arg;
06898    /* In pedantic, we do not want packets with bad syntax to be connected to a PVT */
06899    int found = FALSE;
06900    
06901    if (!ast_strlen_zero(p->callid)) { /* XXX double check, do we allow match on empty p->callid ? */
06902       if (arg->method == SIP_REGISTER)
06903          found = (!strcmp(p->callid, arg->callid));
06904       else {
06905          found = !strcmp(p->callid, arg->callid);
06906          if (pedanticsipchecking && found) {
06907             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);
06908          } 
06909       }
06910       
06911       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);
06912       
06913       /* If we get a new request within an existing to-tag - check the to tag as well */
06914       if (pedanticsipchecking && found && arg->method != SIP_RESPONSE) { /* SIP Request */
06915          if (p->tag[0] == '\0' && arg->totag[0]) {
06916             /* We have no to tag, but they have. Wrong dialog */
06917             found = FALSE;
06918          } else if (arg->totag[0]) { /* Both have tags, compare them */
06919             if (strcmp(arg->totag, p->tag)) {
06920                found = FALSE; /* This is not our packet */
06921             }
06922          }
06923          if (!found)
06924             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);
06925       }
06926    }
06927    return found;
06928 }
06929 
06930 /*! \brief find or create a dialog structure for an incoming SIP message.
06931  * Connect incoming SIP message to current dialog or create new dialog structure
06932  * Returns a reference to the sip_pvt object, remember to give it back once done.
06933  *     Called by handle_incoming(), sipsock_read
06934  */
06935 static struct sip_pvt *find_call(struct sip_request *req, struct sockaddr_in *sin, const int intended_method)
06936 {
06937    struct sip_pvt *p = NULL;
06938    char *tag = "";   /* note, tag is never NULL */
06939    char totag[128];
06940    char fromtag[128];
06941    struct find_call_cb_arg arg;
06942    const char *callid = get_header(req, "Call-ID");
06943    const char *from = get_header(req, "From");
06944    const char *to = get_header(req, "To");
06945    const char *cseq = get_header(req, "Cseq");
06946    struct sip_pvt *sip_pvt_ptr;
06947 
06948    /* Call-ID, to, from and Cseq are required by RFC 3261. (Max-forwards and via too - ignored now) */
06949    /* get_header always returns non-NULL so we must use ast_strlen_zero() */
06950    if (ast_strlen_zero(callid) || ast_strlen_zero(to) ||
06951          ast_strlen_zero(from) || ast_strlen_zero(cseq))
06952       return NULL;   /* Invalid packet */
06953 
06954    arg.method = req->method;
06955    arg.callid = callid;
06956    arg.fromtag = fromtag;
06957    arg.totag = totag;
06958    arg.tag = ""; /* make sure tag is never NULL */
06959 
06960    if (pedanticsipchecking) {
06961       /* In principle Call-ID's uniquely identify a call, but with a forking SIP proxy
06962          we need more to identify a branch - so we have to check branch, from
06963          and to tags to identify a call leg.
06964          For Asterisk to behave correctly, you need to turn on pedanticsipchecking
06965          in sip.conf
06966          */
06967       if (gettag(req, "To", totag, sizeof(totag)))
06968          req->has_to_tag = 1; /* Used in handle_request/response */
06969       gettag(req, "From", fromtag, sizeof(fromtag));
06970 
06971       tag = (req->method == SIP_RESPONSE) ? totag : fromtag;
06972 
06973       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);
06974 
06975       /* All messages must always have From: tag */
06976       if (ast_strlen_zero(fromtag)) {
06977          ast_debug(5, "%s request has no from tag, dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06978          return NULL;
06979       }
06980       /* reject requests that must always have a To: tag */
06981       if (ast_strlen_zero(totag) && (req->method == SIP_ACK || req->method == SIP_BYE || req->method == SIP_INFO )) {
06982          ast_debug(5, "%s must have a to tag. dropping callid: %s from: %s\n", sip_methods[req->method].text , callid, from );
06983          return NULL;
06984       }
06985    }
06986 
06987 restartsearch:
06988    if (!pedanticsipchecking) {
06989       struct sip_pvt tmp_dialog = {
06990          .callid = callid,
06991       };       
06992       sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find in dialogs");
06993       if (sip_pvt_ptr) {  /* well, if we don't find it-- what IS in there? */
06994          /* Found the call */
06995          sip_pvt_lock(sip_pvt_ptr);
06996          return sip_pvt_ptr;
06997       }
06998    } else { /* in pedantic mode! -- do the fancy linear search */
06999       ao2_lock(dialogs);
07000       p = ao2_t_callback(dialogs, 0 /* single, data */, find_call_cb, &arg, "pedantic linear search for dialog");
07001       if (p) {
07002          if (sip_pvt_trylock(p)) {
07003             ao2_unlock(dialogs);
07004             usleep(1);
07005             goto restartsearch;
07006          }
07007          ao2_unlock(dialogs);
07008          return p;
07009       }
07010       ao2_unlock(dialogs);
07011    }
07012  
07013    /* See if the method is capable of creating a dialog */
07014    if (sip_methods[intended_method].can_create == CAN_CREATE_DIALOG) {
07015       if (intended_method == SIP_REFER) {
07016          /* We do support REFER, but not outside of a dialog yet */
07017          transmit_response_using_temp(callid, sin, 1, intended_method, req, "603 Declined (no dialog)");
07018       } else if (intended_method == SIP_NOTIFY) {
07019          /* We do not support out-of-dialog NOTIFY either,
07020             like voicemail notification, so cancel that early */
07021          transmit_response_using_temp(callid, sin, 1, intended_method, req, "489 Bad event");
07022       } else {
07023          /* Ok, time to create a new SIP dialog object, a pvt */
07024          if ((p = sip_alloc(callid, sin, 1, intended_method, req)))  {
07025             /* Ok, we've created a dialog, let's go and process it */
07026             sip_pvt_lock(p);
07027          } else {
07028             /* We have a memory or file/socket error (can't allocate RTP sockets or something) so we're not
07029                getting a dialog from sip_alloc. 
07030    
07031                Without a dialog we can't retransmit and handle ACKs and all that, but at least
07032                send an error message.
07033    
07034                Sorry, we apologize for the inconvienience
07035             */
07036             transmit_response_using_temp(callid, sin, 1, intended_method, req, "500 Server internal error");
07037             ast_debug(4, "Failed allocating SIP dialog, sending 500 Server internal error and giving up\n");
07038          }
07039       }
07040       return p; /* can be NULL */
07041    } else if( sip_methods[intended_method].can_create == CAN_CREATE_DIALOG_UNSUPPORTED_METHOD) {
07042       /* A method we do not support, let's take it on the volley */
07043       transmit_response_using_temp(callid, sin, 1, intended_method, req, "501 Method Not Implemented");
07044       ast_debug(2, "Got a request with unsupported SIP method.\n");
07045    } else if (intended_method != SIP_RESPONSE && intended_method != SIP_ACK) {
07046       /* This is a request outside of a dialog that we don't know about */
07047       transmit_response_using_temp(callid, sin, 1, intended_method, req, "481 Call leg/transaction does not exist");
07048       ast_debug(2, "That's odd...  Got a request in unknown dialog. Callid %s\n", callid ? callid : "<unknown>");
07049    }
07050    /* We do not respond to responses for dialogs that we don't know about, we just drop
07051       the session quickly */
07052    if (intended_method == SIP_RESPONSE)
07053       ast_debug(2, "That's odd...  Got a response on a call we dont know about. Callid %s\n", callid ? callid : "<unknown>");
07054 
07055    return NULL;
07056 }
07057 
07058 /*! \brief Parse register=> line in sip.conf and add to registry */
07059 static int sip_register(const char *value, int lineno)
07060 {
07061    struct sip_registry *reg;
07062    int portnum = 0;
07063    enum sip_transport transport = SIP_TRANSPORT_UDP;
07064    char buf[256] = "";
07065    char *username = NULL;
07066    char *hostname=NULL, *secret=NULL, *authuser=NULL, *expire=NULL, *tmp=NULL;
07067    char *callback=NULL, *peername=NULL;
07068 
07069    if (!value)
07070       return -1;
07071    ast_copy_string(buf, value, sizeof(buf));
07072    tmp = strrchr(buf, '@');
07073 
07074    /* split [/extension][~expiry] */
07075    expire = strchr(tmp, '~');
07076    if (expire)
07077       *expire++ = '\0';
07078    callback = strrchr(tmp, '/');
07079    if (callback)
07080       *callback++ = '\0';
07081    if (ast_strlen_zero(callback))
07082       callback = "s";
07083 
07084    /* split [peername?][transport://] */
07085    tmp = strchr(buf, '?');
07086    if (tmp) {
07087       *tmp++ = '\0';
07088       peername = buf;
07089    } else {
07090       tmp = buf;
07091    }
07092    /* tmp is set at the beginning of [transport://] */
07093    sip_parse_host(tmp, lineno, &username, &portnum, &transport);
07094 
07095    /* First split around the last '@' then parse the two components. */
07096    hostname = strrchr(username, '@'); /* allow @ in the first part */
07097    if (hostname)
07098       *hostname++ = '\0';
07099    if (ast_strlen_zero(username) || ast_strlen_zero(hostname)) {
07100       ast_log(LOG_WARNING, "Format for registration is [transport://]user[@domain][:secret[:authuser]]@host[:port][/extension][~expiry] at line %d\n", lineno);
07101       return -1;
07102    }
07103    /* split user[:secret[:authuser]] */
07104    secret = strchr(username, ':');
07105    if (secret) {
07106       *secret++ = '\0';
07107       authuser = strchr(secret, ':');
07108       if (authuser)
07109          *authuser++ = '\0';
07110    }
07111 
07112    if (!(reg = ast_calloc(1, sizeof(*reg)))) {
07113       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry entry\n");
07114       return -1;
07115    }
07116 
07117    if (ast_string_field_init(reg, 256)) {
07118       ast_log(LOG_ERROR, "Out of memory. Can't allocate SIP registry strings\n");
07119       ast_free(reg);
07120       return -1;
07121    }
07122 
07123    ast_atomic_fetchadd_int(&regobjs, 1);
07124    ASTOBJ_INIT(reg);
07125    ast_string_field_set(reg, callback, callback);
07126    if (!ast_strlen_zero(username))
07127       ast_string_field_set(reg, username, username);
07128    if (hostname)
07129       ast_string_field_set(reg, hostname, hostname);
07130    if (authuser)
07131       ast_string_field_set(reg, authuser, authuser);
07132    if (secret)
07133       ast_string_field_set(reg, secret, secret);
07134    if (peername) {
07135       ast_string_field_set(reg, peername, peername);
07136    }
07137    reg->transport = transport;
07138    reg->expire = -1;
07139    reg->configured_expiry = (expire ? atoi(expire) : default_expiry);
07140    reg->expiry = reg->configured_expiry;
07141    reg->timeout =  -1;
07142    reg->refresh = reg->expiry;
07143    reg->portno = portnum;
07144    reg->callid_valid = FALSE;
07145    reg->ocseq = INITIAL_CSEQ;
07146    ASTOBJ_CONTAINER_LINK(&regl, reg); /* Add the new registry entry to the list */
07147    registry_unref(reg, "unref the reg pointer");   /* release the reference given by ASTOBJ_INIT. The container has another reference */
07148    return 0;
07149 }
07150 
07151 /*! \brief  Parse multiline SIP headers into one header
07152    This is enabled if pedanticsipchecking is enabled */
07153 static int lws2sws(char *msgbuf, int len) 
07154 {
07155    int h = 0, t = 0; 
07156    int lws = 0; 
07157 
07158    for (; h < len;) { 
07159       /* Eliminate all CRs */ 
07160       if (msgbuf[h] == '\r') { 
07161          h++; 
07162          continue; 
07163       } 
07164       /* Check for end-of-line */ 
07165       if (msgbuf[h] == '\n') { 
07166          /* Check for end-of-message */ 
07167          if (h + 1 == len) 
07168             break; 
07169          /* Check for a continuation line */ 
07170          if (msgbuf[h + 1] == ' ' || msgbuf[h + 1] == '\t') { 
07171             /* Merge continuation line */ 
07172             h++; 
07173             continue; 
07174          } 
07175          /* Propagate LF and start new line */ 
07176          msgbuf[t++] = msgbuf[h++]; 
07177          lws = 0;
07178          continue; 
07179       } 
07180       if (msgbuf[h] == ' ' || msgbuf[h] == '\t') { 
07181          if (lws) { 
07182             h++; 
07183             continue; 
07184          } 
07185          msgbuf[t++] = msgbuf[h++]; 
07186          lws = 1; 
07187          continue; 
07188       } 
07189       msgbuf[t++] = msgbuf[h++]; 
07190       if (lws) 
07191          lws = 0; 
07192    } 
07193    msgbuf[t] = '\0'; 
07194    return t; 
07195 }
07196 
07197 /*! \brief Parse a SIP message 
07198    \note this function is used both on incoming and outgoing packets
07199 */
07200 static int parse_request(struct sip_request *req)
07201 {
07202    char *c = req->data->str;
07203    ptrdiff_t *dst = req->header;
07204    int i = 0, lim = SIP_MAX_HEADERS - 1;
07205    unsigned int skipping_headers = 0;
07206    ptrdiff_t current_header_offset = 0;
07207    char *previous_header = "";
07208 
07209    req->header[0] = 0;
07210    req->headers = -1;   /* mark that we are working on the header */
07211    for (; *c; c++) {
07212       if (*c == '\r') {    /* remove \r */
07213          *c = '\0';
07214       } else if (*c == '\n') {   /* end of this line */
07215          *c = '\0';
07216          current_header_offset = (c + 1) - req->data->str;
07217          previous_header = req->data->str + dst[i];
07218          if (skipping_headers) {
07219             /* check to see if this line is blank; if so, turn off
07220                the skipping flag, so the next line will be processed
07221                as a body line */
07222             if (ast_strlen_zero(previous_header)) {
07223                skipping_headers = 0;
07224             }
07225             dst[i] = current_header_offset; /* record start of next line */
07226             continue;
07227          }
07228          if (sipdebug) {
07229             ast_debug(4, "%7s %2d [%3d]: %s\n",
07230                  req->headers < 0 ? "Header" : "Body",
07231                  i, (int) strlen(previous_header), previous_header);
07232          }
07233          if (ast_strlen_zero(previous_header) && req->headers < 0) {
07234             req->headers = i; /* record number of header lines */
07235             dst = req->line;  /* start working on the body */
07236             i = 0;
07237             lim = SIP_MAX_LINES - 1;
07238          } else { /* move to next line, check for overflows */
07239             if (i++ == lim) {
07240                /* if we're processing headers, then skip any remaining
07241                   headers and move on to processing the body, otherwise
07242                   we're done */
07243                if (req->headers != -1) {
07244                   break;
07245                } else {
07246                   req->headers = i;
07247                   dst = req->line;
07248                   i = 0;
07249                   lim = SIP_MAX_LINES - 1;
07250                   skipping_headers = 1;
07251                }
07252             }
07253          }
07254          dst[i] = current_header_offset; /* record start of next line */
07255       }
07256    }
07257 
07258    /* Check for last header or body line without CRLF. The RFC for SDP requires CRLF,
07259       but since some devices send without, we'll be generous in what we accept. However,
07260       if we've already reached the maximum number of lines for portion of the message
07261       we were parsing, we can't accept any more, so just ignore it.
07262    */
07263    previous_header = req->data->str + dst[i];
07264    if ((i < lim) && !ast_strlen_zero(previous_header)) {
07265       if (sipdebug) {
07266          ast_debug(4, "%7s %2d [%3d]: %s\n",
07267               req->headers < 0 ? "Header" : "Body",
07268               i, (int) strlen(previous_header), previous_header );
07269       }
07270       i++;
07271    }
07272 
07273    /* update count of header or body lines */
07274    if (req->headers >= 0) {   /* we are in the body */
07275       req->lines = i;
07276    } else {       /* no body */
07277       req->headers = i;
07278       req->lines = 0;
07279       /* req->data->used will be a NULL byte */
07280       req->line[0] = req->data->used;
07281    }
07282 
07283    if (*c) {
07284       ast_log(LOG_WARNING, "Too many lines, skipping <%s>\n", c);
07285    }
07286 
07287    /* Split up the first line parts */
07288    return determine_firstline_parts(req);
07289 }
07290 
07291 /*!
07292   \brief Determine whether a SIP message contains an SDP in its body
07293   \param req the SIP request to process
07294   \return 1 if SDP found, 0 if not found
07295 
07296   Also updates req->sdp_start and req->sdp_count to indicate where the SDP
07297   lives in the message body.
07298 */
07299 static int find_sdp(struct sip_request *req)
07300 {
07301    const char *content_type;
07302    const char *content_length;
07303    const char *search;
07304    char *boundary;
07305    unsigned int x;
07306    int boundaryisquoted = FALSE;
07307    int found_application_sdp = FALSE;
07308    int found_end_of_headers = FALSE;
07309 
07310    content_length = get_header(req, "Content-Length");
07311 
07312    if (!ast_strlen_zero(content_length)) {
07313       if (sscanf(content_length, "%30u", &x) != 1) {
07314          ast_log(LOG_WARNING, "Invalid Content-Length: %s\n", content_length);
07315          return 0;
07316       }
07317 
07318       /* Content-Length of zero means there can't possibly be an
07319          SDP here, even if the Content-Type says there is */
07320       if (x == 0)
07321          return 0;
07322    }
07323 
07324    content_type = get_header(req, "Content-Type");
07325 
07326    /* if the body contains only SDP, this is easy */
07327    if (!strncasecmp(content_type, "application/sdp", 15)) {
07328       req->sdp_start = 0;
07329       req->sdp_count = req->lines;
07330       return req->lines ? 1 : 0;
07331    }
07332 
07333    /* if it's not multipart/mixed, there cannot be an SDP */
07334    if (strncasecmp(content_type, "multipart/mixed", 15))
07335       return 0;
07336 
07337    /* if there is no boundary marker, it's invalid */
07338    if ((search = strcasestr(content_type, ";boundary=")))
07339       search += 10;
07340    else if ((search = strcasestr(content_type, "; boundary=")))
07341       search += 11;
07342    else
07343       return 0;
07344 
07345    if (ast_strlen_zero(search))
07346       return 0;
07347 
07348    /* If the boundary is quoted with ", remove quote */
07349    if (*search == '\"')  {
07350       search++;
07351       boundaryisquoted = TRUE;
07352    }
07353 
07354    /* make a duplicate of the string, with two extra characters
07355       at the beginning */
07356    boundary = ast_strdupa(search - 2);
07357    boundary[0] = boundary[1] = '-';
07358    /* Remove final quote */
07359    if (boundaryisquoted)
07360       boundary[strlen(boundary) - 1] = '\0';
07361 
07362    /* search for the boundary marker, the empty line delimiting headers from
07363       sdp part and the end boundry if it exists */
07364 
07365    for (x = 0; x < (req->lines); x++) {
07366       char *line = REQ_OFFSET_TO_STR(req, line[x]);
07367       if (!strncasecmp(line, boundary, strlen(boundary))){
07368          if (found_application_sdp && found_end_of_headers) {
07369             req->sdp_count = (x - 1) - req->sdp_start;
07370             return 1;
07371          }
07372          found_application_sdp = FALSE;
07373       }
07374       if (!strcasecmp(line, "Content-Type: application/sdp"))
07375          found_application_sdp = TRUE;
07376       
07377       if (ast_strlen_zero(line)) {
07378          if (found_application_sdp && !found_end_of_headers){
07379             req->sdp_start = x;
07380             found_end_of_headers = TRUE;
07381          }
07382       }
07383    }
07384    if (found_application_sdp && found_end_of_headers) {
07385       req->sdp_count = x - req->sdp_start;
07386       return TRUE;
07387    }
07388    return FALSE;
07389 }
07390 
07391 enum media_type {
07392    SDP_AUDIO,
07393    SDP_VIDEO,
07394    SDP_IMAGE,
07395    SDP_TEXT,
07396 };
07397 
07398 static int get_ip_and_port_from_sdp(struct sip_request *req, const enum media_type media, struct sockaddr_in *sin)
07399 {
07400    const char *m;
07401    const char *c;
07402    int miterator = req->sdp_start;
07403    int citerator = req->sdp_start;
07404    int x = 0;
07405    int numberofports;
07406    int len;
07407    char host[258] = ""; /*Initialize to empty so we will know if we have any input */
07408    struct ast_hostent audiohp;
07409    struct hostent *hp;
07410 
07411    c = get_sdp_iterate(&citerator, req, "c");
07412    if (sscanf(c, "IN IP4 %256s", host) != 1) {
07413       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
07414       /* Continue since there may be a valid host in a c= line specific to the audio stream */
07415    }
07416    /* We only want the m and c lines for audio */
07417    for (m = get_sdp_iterate(&miterator, req, "m"); !ast_strlen_zero(m); m = get_sdp_iterate(&miterator, req, "m")) {
07418       if ((media == SDP_AUDIO && ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07419           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0))) ||
07420          (media == SDP_VIDEO && ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07421           (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len > 0)))) {
07422          /* See if there's a c= line for this media stream.
07423           * XXX There is no guarantee that we'll be grabbing the c= line for this
07424           * particular media stream here. However, this is the same logic used in process_sdp.
07425           */
07426          c = get_sdp_iterate(&citerator, req, "c");
07427          if (!ast_strlen_zero(c)) {
07428             sscanf(c, "IN IP4 %256s", host);
07429          }
07430          break;
07431       }
07432    }
07433 
07434    if (ast_strlen_zero(host) || x == 0) {
07435       ast_log(LOG_WARNING, "Failed to read an alternate host or port in SDP. Expect %s problems\n", media == SDP_AUDIO ? "audio" : "video");
07436       return -1;
07437    }
07438 
07439    hp = ast_gethostbyname(host, &audiohp);
07440    if (!hp) {
07441       ast_log(LOG_WARNING, "Could not look up IP address of alternate hostname. Expect %s problems\n", media == SDP_AUDIO? "audio" : "video");
07442       return -1;
07443    }
07444 
07445    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
07446    sin->sin_port = htons(x);
07447    return 0;
07448 }
07449 
07450 /*! \brief Process SIP SDP offer, select formats and activate RTP channels
07451    If offer is rejected, we will not change any properties of the call
07452    Return 0 on success, a negative value on errors.
07453    Must be called after find_sdp().
07454 */
07455 static int process_sdp(struct sip_pvt *p, struct sip_request *req, int t38action)
07456 {
07457    /* Iterators for SDP parsing */
07458    int start = req->sdp_start;
07459    int next = start;
07460    int iterator = start;
07461 
07462    /* Temporary vars for SDP parsing */
07463    char type = '\0';
07464    const char *value = NULL;
07465    const char *m = NULL;           /* SDP media offer */
07466    const char *nextm = NULL;
07467    int len = -1;
07468 
07469    /* Host information */
07470    struct ast_hostent sessionhp;
07471    struct ast_hostent audiohp;
07472    struct ast_hostent videohp;
07473    struct ast_hostent texthp;
07474    struct ast_hostent imagehp;
07475    struct hostent *hp = NULL; /*!< RTP Audio host IP */
07476    struct hostent *vhp = NULL;   /*!< RTP video host IP */
07477    struct hostent *thp = NULL;   /*!< RTP text host IP */
07478    struct hostent *ihp = NULL;     /*!< UDPTL host ip */
07479    int portno = -1;     /*!< RTP Audio port number */
07480    int vportno = -1;    /*!< RTP Video port number */
07481    int tportno = -1;    /*!< RTP Text port number */
07482    int udptlportno = -1;      /*!< UDPTL Image port number */
07483    struct sockaddr_in sin;    /*!< media socket address */
07484    struct sockaddr_in vsin;   /*!< video socket address */
07485    struct sockaddr_in isin;   /*!< image socket address */
07486    struct sockaddr_in tsin;   /*!< text socket address */
07487 
07488    /* Peer capability is the capability in the SDP, non codec is RFC2833 DTMF (101) */ 
07489    int peercapability = 0, peernoncodeccapability = 0;
07490    int vpeercapability = 0, vpeernoncodeccapability = 0;
07491    int tpeercapability = 0, tpeernoncodeccapability = 0;
07492 
07493    struct ast_rtp *newaudiortp, *newvideortp, *newtextrtp;
07494    int newjointcapability;          /* Negotiated capability */
07495    int newpeercapability;
07496    int newnoncodeccapability;
07497 
07498    const char *codecs;
07499    int codec;
07500 
07501    /* Others */
07502    int sendonly = -1;
07503    int vsendonly = -1;
07504    int numberofports;
07505    int numberofmediastreams = 0;
07506    int last_rtpmap_codec = 0;
07507    int red_data_pt[10];    /* For T.140 red */
07508    int red_num_gen = 0;    /* For T.140 red */
07509    char red_fmtp[100] = "empty"; /* For T.140 red */
07510    int debug = sip_debug_test_pvt(p);
07511 
07512    /* START UNKNOWN */
07513    char buf[SIPBUFSIZE];
07514    /* END UNKNOWN */
07515 
07516    /* Initial check */
07517    if (!p->rtp) {
07518       ast_log(LOG_ERROR, "Got SDP but have no RTP session allocated.\n");
07519       return -1;
07520    }
07521 
07522    /* Initialize the temporary RTP structures we use to evaluate the offer from the peer */
07523 #ifdef LOW_MEMORY
07524    newaudiortp = ast_threadstorage_get(&ts_audio_rtp, ast_rtp_alloc_size());
07525 #else
07526    newaudiortp = alloca(ast_rtp_alloc_size());
07527 #endif
07528    memset(newaudiortp, 0, ast_rtp_alloc_size());
07529    ast_rtp_new_init(newaudiortp);
07530    ast_rtp_pt_clear(newaudiortp);
07531 
07532 #ifdef LOW_MEMORY
07533    newvideortp = ast_threadstorage_get(&ts_video_rtp, ast_rtp_alloc_size());
07534 #else
07535    newvideortp = alloca(ast_rtp_alloc_size());
07536 #endif
07537    memset(newvideortp, 0, ast_rtp_alloc_size());
07538    ast_rtp_new_init(newvideortp);
07539    ast_rtp_pt_clear(newvideortp);
07540 
07541 #ifdef LOW_MEMORY
07542    newtextrtp = ast_threadstorage_get(&ts_text_rtp, ast_rtp_alloc_size());
07543 #else
07544    newtextrtp = alloca(ast_rtp_alloc_size());
07545 #endif
07546    memset(newtextrtp, 0, ast_rtp_alloc_size());
07547    ast_rtp_new_init(newtextrtp);
07548    ast_rtp_pt_clear(newtextrtp);
07549 
07550    /* Update our last rtprx when we receive an SDP, too */
07551    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
07552 
07553    memset(p->offered_media, 0, sizeof(p->offered_media));
07554 
07555 
07556    /* default: novideo and notext set */
07557    p->novideo = TRUE;
07558    p->notext = TRUE;
07559 
07560    if (p->vrtp)
07561       ast_rtp_pt_clear(newvideortp);  /* Must be cleared in case no m=video line exists */
07562  
07563    if (p->trtp)
07564       ast_rtp_pt_clear(newtextrtp);  /* Must be cleared in case no m=text line exists */
07565    
07566    /* Scan for the first media stream (m=) line to limit scanning of globals */
07567    nextm = get_sdp_iterate(&next, req, "m");
07568    if (ast_strlen_zero(nextm)) {
07569       ast_log(LOG_WARNING, "Insufficient information for SDP (m= not found)\n");
07570       return -1;
07571    }
07572 
07573    /* Scan session level SDP parameters (lines before first media stream) */
07574    while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
07575       int processed = FALSE;
07576       switch (type) {
07577       case 'o':
07578          /* If we end up receiving SDP that doesn't actually modify the session we don't want to treat this as a fatal
07579           * error. We just want to ignore the SDP and let the rest of the packet be handled as normal.
07580           */
07581          if (!process_sdp_o(value, p))
07582             return (p->session_modify == FALSE) ? 0 : -1;
07583          break;
07584       case 'c':
07585          if (process_sdp_c(value, &sessionhp)) {
07586             processed = TRUE;
07587             hp = &sessionhp.hp;
07588             vhp = hp;
07589             thp = hp;
07590             ihp = hp;
07591          }
07592          break;
07593       case 'a':
07594          if (process_sdp_a_sendonly(value, &sendonly)) {
07595             processed = TRUE;
07596             vsendonly = sendonly;
07597          }
07598          else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
07599             processed = TRUE;
07600          else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
07601             processed = TRUE;
07602          else if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
07603             processed = TRUE;
07604          else if (process_sdp_a_image(value, p))
07605             processed = TRUE;
07606          break;
07607       }
07608 
07609       if (option_debug > 2)
07610          ast_log(LOG_DEBUG, "Processing session-level SDP %c=%s... %s\n", type, value, (processed == TRUE)? "OK." : "UNSUPPORTED.");
07611    }
07612 
07613 
07614 
07615    /* Scan media stream (m=) specific parameters loop */
07616    while (!ast_strlen_zero(nextm)) {
07617       int audio = FALSE;
07618       int video = FALSE;
07619       int image = FALSE;
07620       int text = FALSE;
07621       int x;
07622 
07623       numberofports = 1;
07624       len = -1;
07625       start = next;
07626       m = nextm;
07627       iterator = next;
07628       nextm = get_sdp_iterate(&next, req, "m");
07629 
07630       /* Search for audio media definition */
07631       if ((sscanf(m, "audio %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07632           (sscanf(m, "audio %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07633          audio = TRUE;
07634          p->offered_media[SDP_AUDIO].offered = TRUE;
07635          numberofmediastreams++;
07636          portno = x;
07637 
07638          /* Scan through the RTP payload types specified in a "m=" line: */
07639          codecs = m + len;
07640          ast_copy_string(p->offered_media[SDP_AUDIO].text, codecs, sizeof(p->offered_media[SDP_AUDIO].text));
07641          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07642             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07643                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07644                return -1;
07645             }
07646             if (debug)
07647                ast_verbose("Found RTP audio format %d\n", codec);
07648 
07649             ast_rtp_set_m_type(newaudiortp, codec);
07650          }
07651       /* Search for video media definition */
07652       } else if ((sscanf(m, "video %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07653             (sscanf(m, "video %30u RTP/AVP %n", &x, &len) == 1 && len >= 0)) {
07654          video = TRUE;
07655          p->novideo = FALSE;
07656          p->offered_media[SDP_VIDEO].offered = TRUE;
07657          numberofmediastreams++;
07658          vportno = x;
07659 
07660          /* Scan through the RTP payload types specified in a "m=" line: */
07661          codecs = m + len;
07662          ast_copy_string(p->offered_media[SDP_VIDEO].text, codecs, sizeof(p->offered_media[SDP_VIDEO].text));
07663          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07664             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07665                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07666                return -1;
07667             }
07668             if (debug)
07669                ast_verbose("Found RTP video format %d\n", codec);
07670             ast_rtp_set_m_type(newvideortp, codec);
07671          }
07672       /* Search for text media definition */
07673       } else if ((sscanf(m, "text %30u/%30u RTP/AVP %n", &x, &numberofports, &len) == 2 && len > 0) ||
07674             (sscanf(m, "text %30u RTP/AVP %n", &x, &len) == 1 && len > 0)) {
07675          text = TRUE;
07676          p->notext = FALSE;
07677          p->offered_media[SDP_TEXT].offered = TRUE;
07678          numberofmediastreams++;
07679          tportno = x;
07680 
07681          /* Scan through the RTP payload types specified in a "m=" line: */
07682          codecs = m + len;
07683          ast_copy_string(p->offered_media[SDP_TEXT].text, codecs, sizeof(p->offered_media[SDP_TEXT].text));
07684          for (; !ast_strlen_zero(codecs); codecs = ast_skip_blanks(codecs + len)) {
07685             if (sscanf(codecs, "%30u%n", &codec, &len) != 1) {
07686                ast_log(LOG_WARNING, "Error in codec string '%s'\n", codecs);
07687                return -1;
07688             }
07689             if (debug)
07690                ast_verbose("Found RTP text format %d\n", codec);
07691             ast_rtp_set_m_type(newtextrtp, codec);
07692          }
07693       /* Search for image media definition */
07694       } else if (p->udptl && ((sscanf(m, "image %30u udptl t38%n", &x, &len) == 1 && len > 0) ||
07695                (sscanf(m, "image %30u UDPTL t38%n", &x, &len) == 1 && len > 0) )) {
07696          image = TRUE;
07697          if (debug)
07698             ast_verbose("Got T.38 offer in SDP in dialog %s\n", p->callid);
07699          p->offered_media[SDP_IMAGE].offered = TRUE;
07700          udptlportno = x;
07701          numberofmediastreams++;
07702 
07703          if (p->t38.state != T38_ENABLED) {
07704             memset(&p->t38.their_parms, 0, sizeof(p->t38.their_parms));
07705          }
07706       } else {
07707          ast_log(LOG_WARNING, "Unsupported SDP media type in offer: %s\n", m);
07708          continue;
07709       }
07710 
07711       /* Check for number of ports */
07712       if (numberofports > 1)
07713          ast_log(LOG_WARNING, "SDP offered %d ports for media, not supported by Asterisk. Will try anyway...\n", numberofports);
07714       
07715 
07716 
07717       /* Media stream specific parameters */
07718       while ((type = get_sdp_line(&iterator, next - 1, req, &value)) != '\0') {
07719          int processed = FALSE;
07720 
07721          switch (type) {
07722          case 'c':
07723             if (audio) {
07724                if (process_sdp_c(value, &audiohp)) {
07725                   processed = TRUE;
07726                   hp = &audiohp.hp;
07727                }
07728             } else if (video) {
07729                if (process_sdp_c(value, &videohp)) {
07730                   processed = TRUE;
07731                   vhp = &videohp.hp;
07732                }
07733             } else if (text) {
07734                if (process_sdp_c(value, &texthp)) {
07735                   processed = TRUE;
07736                   thp = &texthp.hp;
07737                }
07738             } else if (image) {
07739                if (process_sdp_c(value, &imagehp)) {
07740                   processed = TRUE;
07741                   ihp = &imagehp.hp;
07742                }
07743             }
07744             break;
07745          case 'a':
07746             /* Audio specific scanning */
07747             if (audio) {
07748                if (process_sdp_a_sendonly(value, &sendonly))
07749                   processed = TRUE;
07750                else if (process_sdp_a_audio(value, p, newaudiortp, &last_rtpmap_codec))
07751                   processed = TRUE;
07752             }
07753             /* Video specific scanning */
07754             else if (video) {
07755                if (process_sdp_a_sendonly(value, &vsendonly))
07756                   processed = TRUE;
07757                else if (process_sdp_a_video(value, p, newvideortp, &last_rtpmap_codec))
07758                   processed = TRUE;
07759             }
07760             /* Text (T.140) specific scanning */
07761             else if (text) {
07762                if (process_sdp_a_text(value, p, newtextrtp, red_fmtp, &red_num_gen, red_data_pt, &last_rtpmap_codec))
07763                   processed = TRUE;
07764             }
07765             /* Image (T.38 FAX) specific scanning */
07766             else if (image) {
07767                if (process_sdp_a_image(value, p))
07768                   processed = TRUE;
07769             }
07770             break;
07771          }
07772 
07773          if (option_debug > 2)
07774             ast_log(LOG_DEBUG, "Processing media-level (%s) SDP %c=%s... %s\n",
07775                   (audio == TRUE)? "audio" : (video == TRUE)? "video" : "image",
07776                   type, value,
07777                   (processed == TRUE)? "OK." : "UNSUPPORTED.");
07778       }
07779    }
07780 
07781 
07782    /* Sanity checks */
07783    if (!hp && !vhp && !thp && !ihp) {
07784       ast_log(LOG_WARNING, "Insufficient information in SDP (c=)...\n");
07785       return -1;
07786    }
07787 
07788    if (portno == -1 && vportno == -1 && udptlportno == -1  && tportno == -1)
07789       /* No acceptable offer found in SDP  - we have no ports */
07790       /* Do not change RTP or VRTP if this is a re-invite */
07791       return -2;
07792 
07793    if (numberofmediastreams > 3)
07794       /* We have too many fax, audio and/or video and/or text media streams, fail this offer */
07795       return -3;
07796 
07797    if (udptlportno == -1) {
07798       change_t38_state(p, T38_DISABLED);
07799    }
07800 
07801    /* Now gather all of the codecs that we are asked for: */
07802    ast_rtp_get_current_formats(newaudiortp, &peercapability, &peernoncodeccapability);
07803    ast_rtp_get_current_formats(newvideortp, &vpeercapability, &vpeernoncodeccapability);
07804    ast_rtp_get_current_formats(newtextrtp, &tpeercapability, &tpeernoncodeccapability);
07805  
07806    newjointcapability = p->capability & (peercapability | vpeercapability | tpeercapability);
07807    newpeercapability = (peercapability | vpeercapability | tpeercapability);
07808    newnoncodeccapability = p->noncodeccapability & peernoncodeccapability;
07809       
07810       
07811    if (debug) {
07812       /* shame on whoever coded this.... */
07813       char s1[SIPBUFSIZE], s2[SIPBUFSIZE], s3[SIPBUFSIZE], s4[SIPBUFSIZE], s5[SIPBUFSIZE];
07814 
07815       ast_verbose("Capabilities: us - %s, peer - audio=%s/video=%s/text=%s, combined - %s\n",
07816              ast_getformatname_multiple(s1, SIPBUFSIZE, p->capability),
07817              ast_getformatname_multiple(s2, SIPBUFSIZE, peercapability),
07818              ast_getformatname_multiple(s3, SIPBUFSIZE, vpeercapability),
07819              ast_getformatname_multiple(s4, SIPBUFSIZE, tpeercapability),
07820              ast_getformatname_multiple(s5, SIPBUFSIZE, newjointcapability));
07821 
07822       ast_verbose("Non-codec capabilities (dtmf): us - %s, peer - %s, combined - %s\n",
07823              ast_rtp_lookup_mime_multiple(s1, SIPBUFSIZE, p->noncodeccapability, 0, 0),
07824              ast_rtp_lookup_mime_multiple(s2, SIPBUFSIZE, peernoncodeccapability, 0, 0),
07825              ast_rtp_lookup_mime_multiple(s3, SIPBUFSIZE, newnoncodeccapability, 0, 0));
07826    }
07827    if (!newjointcapability && (portno != -1)) {
07828       ast_log(LOG_NOTICE, "No compatible codecs, not accepting this offer!\n");
07829       /* Do NOT Change current setting */
07830       return -1;
07831    }
07832 
07833    /* Setup audio address and port */
07834    if (p->rtp) {
07835       if (portno > 0) {
07836          sin.sin_family = AF_INET;
07837          sin.sin_port = htons(portno);
07838          memcpy(&sin.sin_addr, hp->h_addr, sizeof(sin.sin_addr));
07839          ast_rtp_set_peer(p->rtp, &sin);
07840          if (debug)
07841             ast_verbose("Peer audio RTP is at port %s:%d\n", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
07842          /* We are now ready to change the sip session and p->rtp and p->vrtp with the offered codecs, since                                                                                                    
07843             they are acceptable */
07844          p->jointcapability = newjointcapability;                /* Our joint codec profile for this call */
07845          p->peercapability = newpeercapability;                  /* The other sides capability in latest offer */
07846          p->jointnoncodeccapability = newnoncodeccapability;     /* DTMF capabilities */
07847 
07848          ast_rtp_pt_copy(p->rtp, newaudiortp);
07849 
07850          if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO) {
07851             ast_clear_flag(&p->flags[0], SIP_DTMF);
07852             if (newnoncodeccapability & AST_RTP_DTMF) {
07853                /* XXX Would it be reasonable to drop the DSP at this point? XXX */
07854                ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
07855                /* Since RFC2833 is now negotiated we need to change some properties of the RTP stream */
07856                ast_rtp_setdtmf(p->rtp, 1);
07857                ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
07858             } else {
07859                ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
07860             }
07861          }
07862       } else if (udptlportno > 0) {
07863          if (debug)
07864             ast_verbose("Got T.38 Re-invite without audio. Keeping RTP active during T.38 session.\n");
07865       } else {
07866          ast_rtp_stop(p->rtp);
07867          if (debug)
07868             ast_verbose("Peer doesn't provide audio\n");
07869       }
07870    }
07871 
07872    /* Setup video address and port */
07873    if (p->vrtp) {
07874       if (vportno > 0) {
07875          vsin.sin_family = AF_INET;
07876          vsin.sin_port = htons(vportno);
07877          memcpy(&vsin.sin_addr, vhp->h_addr, sizeof(vsin.sin_addr));
07878          ast_rtp_set_peer(p->vrtp, &vsin);
07879          if (debug) 
07880             ast_verbose("Peer video RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07881          ast_rtp_pt_copy(p->vrtp, newvideortp);
07882       } else {
07883          ast_rtp_stop(p->vrtp);
07884          if (debug)
07885             ast_verbose("Peer doesn't provide video\n");
07886       }
07887    }
07888 
07889    /* Setup text address and port */
07890    if (p->trtp) {
07891       if (tportno > 0) {
07892          tsin.sin_family = AF_INET;
07893          tsin.sin_port = htons(tportno);
07894          memcpy(&tsin.sin_addr, thp->h_addr, sizeof(tsin.sin_addr));
07895          ast_rtp_set_peer(p->trtp, &tsin);
07896          if (debug) 
07897             ast_verbose("Peer T.140 RTP is at port %s:%d\n", ast_inet_ntoa(vsin.sin_addr), ntohs(vsin.sin_port));
07898          if ((p->jointcapability & AST_FORMAT_T140RED)) {
07899             p->red = 1;
07900             rtp_red_init(p->trtp, 300, red_data_pt, 2);
07901          } else {
07902             p->red = 0;
07903          }
07904          ast_rtp_pt_copy(p->trtp, newtextrtp);
07905       } else {
07906          ast_rtp_stop(p->trtp);
07907          if (debug)
07908             ast_verbose("Peer doesn't provide T.140\n");
07909       }
07910    }
07911    /* Setup image address and port */
07912    if (p->udptl) {
07913       if (udptlportno > 0) {
07914          isin.sin_family = AF_INET;
07915          isin.sin_port = htons(udptlportno);
07916          if (ast_test_flag(&p->flags[0], SIP_NAT) && ast_test_flag(&p->flags[1], SIP_PAGE2_UDPTL_DESTINATION)) {
07917             struct sockaddr_in remote_address = { 0, };
07918             ast_rtp_get_peer(p->rtp, &remote_address);
07919             if (remote_address.sin_addr.s_addr) {
07920                memcpy(&isin, &remote_address, sizeof(isin));
07921                if (debug) {
07922                   ast_log(LOG_DEBUG, "Peer T.38 UDPTL is set behind NAT and with destination, destination address now %s\n", ast_inet_ntoa(isin.sin_addr));
07923                }
07924             }
07925          } else {
07926             memcpy(&isin.sin_addr, ihp->h_addr, sizeof(sin.sin_addr));
07927          }
07928          ast_udptl_set_peer(p->udptl, &isin);
07929          if (debug)
07930             ast_debug(1,"Peer T.38 UDPTL is at port %s:%d\n", ast_inet_ntoa(isin.sin_addr), ntohs(isin.sin_port));
07931 
07932          /* verify the far max ifp can be calculated. this requires far max datagram to be set. */
07933          if (!ast_udptl_get_far_max_datagram(p->udptl)) {
07934             /* setting to zero will force a default if none was provided by the SDP */
07935             ast_udptl_set_far_max_datagram(p->udptl, 0);
07936          }
07937 
07938          /* Remote party offers T38, we need to update state */
07939          if ((t38action == SDP_T38_ACCEPT) &&
07940              (p->t38.state == T38_LOCAL_REINVITE)) {
07941             change_t38_state(p, T38_ENABLED);
07942          } else if ((t38action == SDP_T38_INITIATE) &&
07943                p->owner && p->lastinvite) {
07944             change_t38_state(p, T38_PEER_REINVITE); /* T38 Offered in re-invite from remote party */
07945          }
07946       } else {
07947          ast_udptl_stop(p->udptl);
07948          if (debug)
07949             ast_debug(1, "Peer doesn't provide T.38 UDPTL\n");
07950       }
07951    }
07952 
07953    if ((portno == -1) && (p->t38.state != T38_DISABLED)) {
07954       ast_debug(3, "Have T.38 but no audio, accepting offer anyway\n");
07955                 return 0;
07956         }
07957 
07958    /* Ok, we're going with this offer */
07959    ast_debug(2, "We're settling with these formats: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, p->jointcapability));
07960 
07961    if (!p->owner)    /* There's no open channel owning us so we can return here. For a re-invite or so, we proceed */
07962       return 0;
07963 
07964    ast_debug(4, "We have an owner, now see if we need to change this call\n");
07965 
07966    if (!(p->owner->nativeformats & p->jointcapability) && (p->jointcapability & AST_FORMAT_AUDIO_MASK)) {
07967       if (debug) {
07968          char s1[SIPBUFSIZE], s2[SIPBUFSIZE];
07969          ast_debug(1, "Oooh, we need to change our audio formats since our peer supports only %s and not %s\n", 
07970             ast_getformatname_multiple(s1, SIPBUFSIZE, p->jointcapability),
07971             ast_getformatname_multiple(s2, SIPBUFSIZE, p->owner->nativeformats));
07972       }
07973       p->owner->nativeformats = ast_codec_choose(&p->prefs, p->jointcapability, 1) | (p->capability & vpeercapability) | (p->capability & tpeercapability);
07974       ast_set_read_format(p->owner, p->owner->readformat);
07975       ast_set_write_format(p->owner, p->owner->writeformat);
07976    }
07977    
07978    if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) && sin.sin_addr.s_addr && (!sendonly || sendonly == -1)) {
07979       ast_queue_control(p->owner, AST_CONTROL_UNHOLD);
07980       /* Activate a re-invite */
07981       ast_queue_frame(p->owner, &ast_null_frame);
07982       /* Queue Manager Unhold event */
07983       append_history(p, "Unhold", "%s", req->data->str);
07984       if (global_callevents)
07985          manager_event(EVENT_FLAG_CALL, "Hold",
07986                   "Status: Off\r\n"
07987                   "Channel: %s\r\n"
07988                   "Uniqueid: %s\r\n",
07989                   p->owner->name,
07990                   p->owner->uniqueid);
07991       if (global_notifyhold)
07992          sip_peer_hold(p, FALSE);
07993       ast_clear_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD); /* Clear both flags */
07994    } else if (!sin.sin_addr.s_addr || (sendonly && sendonly != -1)) {
07995       int already_on_hold = ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD);
07996       ast_queue_control_data(p->owner, AST_CONTROL_HOLD, 
07997                    S_OR(p->mohsuggest, NULL),
07998                    !ast_strlen_zero(p->mohsuggest) ? strlen(p->mohsuggest) + 1 : 0);
07999       if (sendonly)
08000          ast_rtp_stop(p->rtp);
08001       /* RTCP needs to go ahead, even if we're on hold!!! */
08002       /* Activate a re-invite */
08003       ast_queue_frame(p->owner, &ast_null_frame);
08004       /* Queue Manager Hold event */
08005       append_history(p, "Hold", "%s", req->data->str);
08006       if (global_callevents && !ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) {
08007          manager_event(EVENT_FLAG_CALL, "Hold",
08008                   "Status: On\r\n"
08009                   "Channel: %s\r\n"
08010                   "Uniqueid: %s\r\n",
08011                   p->owner->name, 
08012                   p->owner->uniqueid);
08013       }
08014       if (sendonly == 1)   /* One directional hold (sendonly/recvonly) */
08015          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ONEDIR);
08016       else if (sendonly == 2) /* Inactive stream */
08017          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_INACTIVE);
08018       else
08019          ast_set_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD_ACTIVE);
08020       if (global_notifyhold && !already_on_hold)
08021          sip_peer_hold(p, TRUE);
08022    }
08023    
08024    return 0;
08025 }
08026 
08027 static int process_sdp_o(const char *o, struct sip_pvt *p)
08028 {
08029    char *o_copy;
08030    char *token;
08031    int64_t rua_version;
08032 
08033    /* Store the SDP version number of remote UA. This will allow us to
08034    distinguish between session modifications and session refreshes. If
08035    the remote UA does not send an incremented SDP version number in a
08036    subsequent RE-INVITE then that means its not changing media session.
08037    The RE-INVITE may have been sent to update connected party, remote
08038    target or to refresh the session (Session-Timers).  Asterisk must not
08039    change media session and increment its own version number in answer
08040    SDP in this case. */
08041 
08042    p->session_modify = TRUE;
08043 
08044    if (ast_strlen_zero(o)) {
08045       ast_log(LOG_WARNING, "SDP syntax error. SDP without an o= line\n");
08046       return FALSE;
08047    }
08048 
08049    o_copy = ast_strdupa(o);
08050    token = strsep(&o_copy, " ");  /* Skip username   */
08051    if (!o_copy) {
08052       ast_log(LOG_WARNING, "SDP syntax error in o= line username\n");
08053       return FALSE;
08054    }
08055    token = strsep(&o_copy, " ");  /* Skip session-id */
08056    if (!o_copy) {
08057       ast_log(LOG_WARNING, "SDP syntax error in o= line session-id\n");
08058       return FALSE;
08059    }
08060    token = strsep(&o_copy, " ");  /* Version         */
08061    if (!o_copy) {
08062       ast_log(LOG_WARNING, "SDP syntax error in o= line\n");
08063       return FALSE;
08064    }
08065    if (!sscanf(token, "%30" SCNd64, &rua_version)) {
08066       ast_log(LOG_WARNING, "SDP syntax error in o= line version\n");
08067       return FALSE;
08068    }
08069 
08070    /* we need to check the SDP version number the other end sent us;
08071     * our rules for deciding what to accept are a bit complex.
08072     *
08073     * 1) if 'ignoresdpversion' has been set for this dialog, then
08074     *    we will just accept whatever they sent and assume it is
08075     *    a modification of the session, even if it is not
08076     * 2) otherwise, if this is the first SDP we've seen from them
08077     *    we accept it
08078     * 3) otherwise, if the new SDP version number is higher than the
08079     *    old one, we accept it
08080     * 4) otherwise, if this SDP is in response to us requesting a switch
08081     *    to T.38, we accept the SDP, but also generate a warning message
08082     *    that this peer should have the 'ignoresdpversion' option set,
08083     *    because it is not following the SDP offer/answer RFC; if we did
08084     *    not request a switch to T.38, then we stop parsing the SDP, as it
08085     *    has not changed from the previous version
08086     */
08087 
08088    if (ast_test_flag(&p->flags[1], SIP_PAGE2_IGNORESDPVERSION) ||
08089        (p->sessionversion_remote < 0) ||
08090        (p->sessionversion_remote < rua_version)) {
08091       p->sessionversion_remote = rua_version;
08092    } else {
08093       if (p->t38.state == T38_LOCAL_REINVITE) {
08094          p->sessionversion_remote = rua_version;
08095          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);
08096       } else {
08097          p->session_modify = FALSE;
08098          ast_debug(2, "Call %s responded to our reinvite without changing SDP version; ignoring SDP.\n", p->callid);
08099          return FALSE;
08100       }
08101    }
08102 
08103    return TRUE;
08104 }
08105 
08106 static int process_sdp_c(const char *c, struct ast_hostent *ast_hp)
08107 {
08108    char host[258];
08109    struct hostent *hp;
08110 
08111    /* Check for Media-description-level-address */
08112    if (sscanf(c, "IN IP4 %255s", host) != 1) {
08113       ast_log(LOG_WARNING, "Invalid host in c= line, '%s'\n", c);
08114       return FALSE;
08115    } else {
08116       if (!(hp = ast_gethostbyname(host, ast_hp))) {
08117          ast_log(LOG_WARNING, "Unable to lookup RTP Audio host in c= line, '%s'\n", c);
08118          return FALSE;
08119       }
08120       return TRUE;
08121    }
08122    return FALSE;
08123 }
08124 
08125 static int process_sdp_a_sendonly(const char *a, int *sendonly)
08126 {
08127    int found = FALSE;
08128 
08129    if (!strcasecmp(a, "sendonly")) {
08130       if (*sendonly == -1)
08131          *sendonly = 1;
08132       found = TRUE;
08133    } else if (!strcasecmp(a, "inactive")) {
08134       if (*sendonly == -1)
08135          *sendonly = 2;
08136       found = TRUE;
08137    }  else if (!strcasecmp(a, "sendrecv")) {
08138       if (*sendonly == -1)
08139          *sendonly = 0;
08140       found = TRUE;
08141    }
08142    return found;
08143 }
08144 
08145 static int process_sdp_a_audio(const char *a, struct sip_pvt *p, struct ast_rtp *newaudiortp, int *last_rtpmap_codec)
08146 {
08147    int found = FALSE;
08148    int codec;
08149    char mimeSubtype[128];
08150    int debug = sip_debug_test_pvt(p);
08151 
08152    if (!strncasecmp(a, "ptime", 5)) {
08153       char *tmp = strrchr(a, ':');
08154       long int framing = 0;
08155       if (tmp) {
08156          tmp++;
08157          framing = strtol(tmp, NULL, 10);
08158          if (framing == LONG_MIN || framing == LONG_MAX) {
08159             framing = 0;
08160             ast_debug(1, "Can't read framing from SDP: %s\n", a);
08161          }
08162       }
08163       if (framing && p->autoframing) {
08164          struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
08165          int codec_n;
08166          int format = 0;
08167          for (codec_n = 0; codec_n < MAX_RTP_PT; codec_n++) {
08168             format = ast_rtp_codec_getformat(codec_n);
08169             if (!format)   /* non-codec or not found */
08170                continue;
08171             if (option_debug)
08172                ast_log(LOG_DEBUG, "Setting framing for %d to %ld\n", format, framing);
08173             ast_codec_pref_setsize(pref, format, framing);
08174          }
08175          ast_rtp_codec_setpref(p->rtp, pref);
08176       }
08177       found = TRUE;
08178    } else if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08179       /* We have a rtpmap to handle */
08180       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08181          if (ast_rtp_set_rtpmap_type(newaudiortp, codec, "audio", mimeSubtype,
08182              ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0) != -1) {
08183             if (debug)
08184                ast_verbose("Found audio description format %s for ID %d\n", mimeSubtype, codec);
08185             //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08186             (*last_rtpmap_codec)++;
08187             found = TRUE;
08188          } else {
08189             ast_rtp_unset_m_type(newaudiortp, codec);
08190             if (debug)
08191                ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08192          }
08193       } else {
08194          if (debug)
08195             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08196       }
08197    }
08198 
08199    return found;
08200 }
08201 
08202 static int process_sdp_a_video(const char *a, struct sip_pvt *p, struct ast_rtp *newvideortp, int *last_rtpmap_codec)
08203 {
08204    int found = FALSE;
08205    int codec;
08206    char mimeSubtype[128];
08207    int debug = sip_debug_test_pvt(p);
08208 
08209    if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08210       /* We have a rtpmap to handle */
08211       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08212          /* Note: should really look at the '#chans' params too */
08213          if (!strncasecmp(mimeSubtype, "H26", 3) || !strncasecmp(mimeSubtype, "MP4", 3)) {
08214             if (ast_rtp_set_rtpmap_type(newvideortp, codec, "video", mimeSubtype, 0) != -1) {
08215                if (debug)
08216                   ast_verbose("Found video description format %s for ID %d\n", mimeSubtype, codec);
08217                //found_rtpmap_codecs[last_rtpmap_codec] = codec;
08218                (*last_rtpmap_codec)++;
08219                found = TRUE;
08220             } else {
08221                ast_rtp_unset_m_type(newvideortp, codec);
08222                if (debug) 
08223                   ast_verbose("Found unknown media description format %s for ID %d\n", mimeSubtype, codec);
08224             }
08225          }
08226       } else {
08227          if (debug)
08228             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08229       }
08230    }
08231 
08232    return found;
08233 }
08234 
08235 static int process_sdp_a_text(const char *a, struct sip_pvt *p, struct ast_rtp *newtextrtp, char *red_fmtp, int *red_num_gen, int *red_data_pt, int *last_rtpmap_codec)
08236 {
08237    int found = FALSE;
08238    int codec;
08239    char mimeSubtype[128];
08240    char *red_cp;
08241    int debug = sip_debug_test_pvt(p);
08242 
08243    if (sscanf(a, "rtpmap: %30u %127[^/]/", &codec, mimeSubtype) == 2) {
08244       /* We have a rtpmap to handle */
08245       if (*last_rtpmap_codec < SDP_MAX_RTPMAP_CODECS) {
08246          if (!strncasecmp(mimeSubtype, "T140", 4)) { /* Text */
08247             if (p->trtp) {
08248                /* ast_verbose("Adding t140 mimeSubtype to textrtp struct\n"); */
08249                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08250                found = TRUE;
08251             }
08252          } else if (!strncasecmp(mimeSubtype, "RED", 3)) { /* Text with Redudancy */
08253             if (p->trtp) {
08254                ast_rtp_set_rtpmap_type(newtextrtp, codec, "text", mimeSubtype, 0);
08255                sprintf(red_fmtp, "fmtp:%d ", codec); 
08256                if (debug)
08257                   ast_verbose("RED submimetype has payload type: %d\n", codec);
08258                found = TRUE;
08259             }
08260          }
08261       } else {
08262          if (debug)
08263             ast_verbose("Discarded description format %s for ID %d\n", mimeSubtype, codec);
08264       }
08265    } else if (!strncmp(a, red_fmtp, strlen(red_fmtp))) {
08266       /* count numbers of generations in fmtp */
08267       red_cp = &red_fmtp[strlen(red_fmtp)];
08268       strncpy(red_fmtp, a, 100);
08269 
08270       sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08271       red_cp = strtok(red_cp, "/");
08272       while (red_cp && (*red_num_gen)++ < RED_MAX_GENERATION) {
08273          sscanf(red_cp, "%30u", &red_data_pt[*red_num_gen]);
08274          red_cp = strtok(NULL, "/");
08275       }
08276       red_cp = red_fmtp;
08277       found = TRUE;
08278    }
08279 
08280    return found;
08281 }
08282 
08283 static int process_sdp_a_image(const char *a, struct sip_pvt *p)
08284 {
08285    int found = FALSE;
08286    char s[256];
08287    unsigned int x;
08288 
08289    if ((sscanf(a, "T38FaxMaxBuffer:%30u", &x) == 1)) {
08290       ast_debug(3, "MaxBufferSize:%d\n", x);
08291       found = TRUE;
08292    } else if ((sscanf(a, "T38MaxBitRate:%30u", &x) == 1) || (sscanf(a, "T38FaxMaxRate:%30u", &x) == 1)) {
08293       ast_debug(3, "T38MaxBitRate: %d\n", x);
08294       switch (x) {
08295       case 14400:
08296          p->t38.their_parms.rate = AST_T38_RATE_14400;
08297          break;
08298       case 12000:
08299          p->t38.their_parms.rate = AST_T38_RATE_12000;
08300          break;
08301       case 9600:
08302          p->t38.their_parms.rate = AST_T38_RATE_9600;
08303          break;
08304       case 7200:
08305          p->t38.their_parms.rate = AST_T38_RATE_7200;
08306          break;
08307       case 4800:
08308          p->t38.their_parms.rate = AST_T38_RATE_4800;
08309          break;
08310       case 2400:
08311          p->t38.their_parms.rate = AST_T38_RATE_2400;
08312          break;
08313       }
08314       found = TRUE;
08315    } else if ((sscanf(a, "T38FaxVersion:%30u", &x) == 1)) {
08316       ast_debug(3, "FaxVersion: %u\n", x);
08317       p->t38.their_parms.version = x;
08318       found = TRUE;
08319    } else if ((sscanf(a, "T38FaxMaxDatagram:%30u", &x) == 1) || (sscanf(a, "T38MaxDatagram:%30u", &x) == 1)) {
08320       /* override the supplied value if the configuration requests it */
08321       if (p->t38_maxdatagram > x) {
08322          ast_debug(1, "Overriding T38FaxMaxDatagram '%d' with '%d'\n", x, p->t38_maxdatagram);
08323          x = p->t38_maxdatagram;
08324       }
08325       ast_debug(3, "FaxMaxDatagram: %u\n", x);
08326       ast_udptl_set_far_max_datagram(p->udptl, x);
08327       found = TRUE;
08328    } else if ((strncmp(a, "T38FaxFillBitRemoval", 20) == 0)) {
08329       if (sscanf(a, "T38FaxFillBitRemoval:%30u", &x) == 1) {
08330          ast_debug(3, "FillBitRemoval: %d\n", x);
08331          if (x == 1) {
08332             p->t38.their_parms.fill_bit_removal = TRUE;
08333          }
08334       } else {
08335          ast_debug(3, "FillBitRemoval\n");
08336          p->t38.their_parms.fill_bit_removal = TRUE;
08337       }
08338       found = TRUE;
08339    } else if ((strncmp(a, "T38FaxTranscodingMMR", 20) == 0)) {
08340       if (sscanf(a, "T38FaxTranscodingMMR:%30u", &x) == 1) {
08341          ast_debug(3, "Transcoding MMR: %d\n", x);
08342          if (x == 1) {
08343             p->t38.their_parms.transcoding_mmr = TRUE;
08344          }
08345       } else {
08346          ast_debug(3, "Transcoding MMR\n");
08347          p->t38.their_parms.transcoding_mmr = TRUE;
08348       }
08349       found = TRUE;
08350    } else if ((strncmp(a, "T38FaxTranscodingJBIG", 21) == 0)) {
08351       if (sscanf(a, "T38FaxTranscodingJBIG:%30u", &x) == 1) {
08352          ast_debug(3, "Transcoding JBIG: %d\n", x);
08353          if (x == 1) {
08354             p->t38.their_parms.transcoding_jbig = TRUE;
08355          }
08356       } else {
08357          ast_debug(3, "Transcoding JBIG\n");
08358          p->t38.their_parms.transcoding_jbig = TRUE;
08359       }
08360       found = TRUE;
08361    } else if ((sscanf(a, "T38FaxRateManagement:%255s", s) == 1)) {
08362       ast_debug(3, "RateManagement: %s\n", s);
08363       if (!strcasecmp(s, "localTCF"))
08364          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_LOCAL_TCF;
08365       else if (!strcasecmp(s, "transferredTCF"))
08366          p->t38.their_parms.rate_management = AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF;
08367       found = TRUE;
08368    } else if ((sscanf(a, "T38FaxUdpEC:%255s", s) == 1)) {
08369       ast_debug(3, "UDP EC: %s\n", s);
08370       if (!strcasecmp(s, "t38UDPRedundancy")) {
08371          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_REDUNDANCY);
08372       } else if (!strcasecmp(s, "t38UDPFEC")) {
08373          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_FEC);
08374       } else {
08375          ast_udptl_set_error_correction_scheme(p->udptl, UDPTL_ERROR_CORRECTION_NONE);
08376       }
08377       found = TRUE;
08378    }
08379 
08380    return found;
08381 }
08382 
08383 
08384 #ifdef LOW_MEMORY
08385 static void ts_ast_rtp_destroy(void *data)
08386 {
08387     struct ast_rtp *tmp = data;
08388     ast_rtp_destroy(tmp);
08389 }
08390 #endif
08391 
08392 /*! \brief Add header to SIP message */
08393 static int add_header(struct sip_request *req, const char *var, const char *value)
08394 {
08395    if (req->headers == SIP_MAX_HEADERS) {
08396       ast_log(LOG_WARNING, "Out of SIP header space\n");
08397       return -1;
08398    }
08399 
08400    if (req->lines) {
08401       ast_log(LOG_WARNING, "Can't add more headers when lines have been added\n");
08402       return -1;
08403    }
08404 
08405    if (compactheaders)
08406       var = find_alias(var, var);
08407 
08408    ast_str_append(&req->data, 0, "%s: %s\r\n", var, value);
08409    req->header[req->headers] = req->len;
08410 
08411    req->len = req->data->used;
08412    req->headers++;
08413 
08414    return 0;   
08415 }
08416 
08417 /*! \brief Add 'Content-Length' header to SIP message */
08418 static int add_header_contentLength(struct sip_request *req, int len)
08419 {
08420    char clen[10];
08421 
08422    snprintf(clen, sizeof(clen), "%d", len);
08423    return add_header(req, "Content-Length", clen);
08424 }
08425 
08426 /*! \brief Add content (not header) to SIP message */
08427 static int add_line(struct sip_request *req, const char *line)
08428 {
08429    if (req->lines == SIP_MAX_LINES)  {
08430       ast_log(LOG_WARNING, "Out of SIP line space\n");
08431       return -1;
08432    }
08433    if (!req->lines)
08434       /* Add extra empty return */
08435       req->len += ast_str_append(&req->data, 0, "\r\n");
08436    req->line[req->lines] = req->len;
08437    ast_str_append(&req->data, 0, "%s", line);
08438    req->len = req->data->used;
08439    req->lines++;
08440    return 0;   
08441 }
08442 
08443 /*! \brief Copy one header field from one request to another */
08444 static int copy_header(struct sip_request *req, const struct sip_request *orig, const char *field)
08445 {
08446    const char *tmp = get_header(orig, field);
08447 
08448    if (!ast_strlen_zero(tmp)) /* Add what we're responding to */
08449       return add_header(req, field, tmp);
08450    ast_log(LOG_NOTICE, "No field '%s' present to copy\n", field);
08451    return -1;
08452 }
08453 
08454 /*! \brief Copy all headers from one request to another */
08455 static int copy_all_header(struct sip_request *req, const struct sip_request *orig, const char *field)
08456 {
08457    int start = 0;
08458    int copied = 0;
08459    for (;;) {
08460       const char *tmp = __get_header(orig, field, &start);
08461 
08462       if (ast_strlen_zero(tmp))
08463          break;
08464       /* Add what we're responding to */
08465       add_header(req, field, tmp);
08466       copied++;
08467    }
08468    return copied ? 0 : -1;
08469 }
08470 
08471 /*! \brief Copy SIP VIA Headers from the request to the response
08472 \note If the client indicates that it wishes to know the port we received from,
08473    it adds ;rport without an argument to the topmost via header. We need to
08474    add the port number (from our point of view) to that parameter.
08475 \verbatim
08476    We always add ;received=<ip address> to the topmost via header.
08477 \endverbatim
08478    Received: RFC 3261, rport RFC 3581 */
08479 static int copy_via_headers(struct sip_pvt *p, struct sip_request *req, const struct sip_request *orig, const char *field)
08480 {
08481    int copied = 0;
08482    int start = 0;
08483 
08484    for (;;) {
08485       char new[512];
08486       const char *oh = __get_header(orig, field, &start);
08487 
08488       if (ast_strlen_zero(oh))
08489          break;
08490 
08491       if (!copied) { /* Only check for empty rport in topmost via header */
08492          char leftmost[512], *others, *rport;
08493 
08494          /* Only work on leftmost value */
08495          ast_copy_string(leftmost, oh, sizeof(leftmost));
08496          others = strchr(leftmost, ',');
08497          if (others)
08498              *others++ = '\0';
08499 
08500          /* Find ;rport;  (empty request) */
08501          rport = strstr(leftmost, ";rport");
08502          if (rport && *(rport+6) == '=') 
08503             rport = NULL;     /* We already have a parameter to rport */
08504 
08505          /* Check rport if NAT=yes or NAT=rfc3581 (which is the default setting)  */
08506          if (rport && ((ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_ALWAYS) || (ast_test_flag(&p->flags[0], SIP_NAT) == SIP_NAT_RFC3581))) {
08507             /* We need to add received port - rport */
08508             char *end;
08509 
08510             rport = strstr(leftmost, ";rport");
08511 
08512             if (rport) {
08513                end = strchr(rport + 1, ';');
08514                if (end)
08515                   memmove(rport, end, strlen(end) + 1);
08516                else
08517                   *rport = '\0';
08518             }
08519 
08520             /* Add rport to first VIA header if requested */
08521             snprintf(new, sizeof(new), "%s;received=%s;rport=%d%s%s",
08522                leftmost, ast_inet_ntoa(p->recv.sin_addr),
08523                ntohs(p->recv.sin_port),
08524                others ? "," : "", others ? others : "");
08525          } else {
08526             /* We should *always* add a received to the topmost via */
08527             snprintf(new, sizeof(new), "%s;received=%s%s%s",
08528                leftmost, ast_inet_ntoa(p->recv.sin_addr),
08529                others ? "," : "", others ? others : "");
08530          }
08531          oh = new;   /* the header to copy */
08532       }  /* else add the following via headers untouched */
08533       add_header(req, field, oh);
08534       copied++;
08535    }
08536    if (!copied) {
08537       ast_log(LOG_NOTICE, "No header field '%s' present to copy\n", field);
08538       return -1;
08539    }
08540    return 0;
08541 }
08542 
08543 /*! \brief Add route header into request per learned route */
08544 static void add_route(struct sip_request *req, struct sip_route *route)
08545 {
08546    char r[SIPBUFSIZE*2], *p;
08547    int n, rem = sizeof(r);
08548 
08549    if (!route)
08550       return;
08551 
08552    p = r;
08553    for (;route ; route = route->next) {
08554       n = strlen(route->hop);
08555       if (rem < n+3) /* we need room for ",<route>" */
08556          break;
08557       if (p != r) {  /* add a separator after fist route */
08558          *p++ = ',';
08559          --rem;
08560       }
08561       *p++ = '<';
08562       ast_copy_string(p, route->hop, rem); /* cannot fail */
08563       p += n;
08564       *p++ = '>';
08565       rem -= (n+2);
08566    }
08567    *p = '\0';
08568    add_header(req, "Route", r);
08569 }
08570 
08571 /*! \brief Set destination from SIP URI */
08572 static void set_destination(struct sip_pvt *p, char *uri)
08573 {
08574    char *h, *maddr, hostname[256];
08575    int port, hn;
08576    struct hostent *hp;
08577    struct ast_hostent ahp;
08578    int debug=sip_debug_test_pvt(p);
08579 
08580    /* Parse uri to h (host) and port - uri is already just the part inside the <> */
08581    /* general form we are expecting is sip[s]:username[:password][;parameter]@host[:port][;...] */
08582 
08583    if (debug)
08584       ast_verbose("set_destination: Parsing <%s> for address/port to send to\n", uri);
08585 
08586    /* Find and parse hostname */
08587    h = strchr(uri, '@');
08588    if (h)
08589       ++h;
08590    else {
08591       h = uri;
08592       if (!strncasecmp(h, "sip:", 4))
08593          h += 4;
08594       else if (!strncasecmp(h, "sips:", 5))
08595          h += 5;
08596    }
08597    hn = strcspn(h, ":;>") + 1;
08598    if (hn > sizeof(hostname)) 
08599       hn = sizeof(hostname);
08600    ast_copy_string(hostname, h, hn);
08601    /* XXX bug here if string has been trimmed to sizeof(hostname) */
08602    h += hn - 1;
08603 
08604    /* Is "port" present? if not default to STANDARD_SIP_PORT */
08605    if (*h == ':') {
08606       /* Parse port */
08607       ++h;
08608       port = strtol(h, &h, 10);
08609    }
08610    else
08611       port = STANDARD_SIP_PORT;
08612 
08613    /* Got the hostname:port - but maybe there's a "maddr=" to override address? */
08614    maddr = strstr(h, "maddr=");
08615    if (maddr) {
08616       maddr += 6;
08617       hn = strspn(maddr, "0123456789.") + 1;
08618       if (hn > sizeof(hostname))
08619          hn = sizeof(hostname);
08620       ast_copy_string(hostname, maddr, hn);
08621    }
08622    
08623    hp = ast_gethostbyname(hostname, &ahp);
08624    if (hp == NULL)  {
08625       ast_log(LOG_WARNING, "Can't find address for host '%s'\n", hostname);
08626       return;
08627    }
08628    p->sa.sin_family = AF_INET;
08629    memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
08630    p->sa.sin_port = htons(port);
08631    if (debug)
08632       ast_verbose("set_destination: set destination to %s, port %d\n", ast_inet_ntoa(p->sa.sin_addr), port);
08633 }
08634 
08635 /*! \brief Initialize SIP response, based on SIP request */
08636 static int init_resp(struct sip_request *resp, const char *msg)
08637 {
08638    /* Initialize a response */
08639    memset(resp, 0, sizeof(*resp));
08640    resp->method = SIP_RESPONSE;
08641    if (!(resp->data = ast_str_create(SIP_MIN_PACKET)))
08642       return -1;
08643    resp->header[0] = 0;
08644    ast_str_set(&resp->data, 0, "SIP/2.0 %s\r\n", msg);
08645    resp->len = resp->data->used;
08646    resp->headers++;
08647    return 0;
08648 }
08649 
08650 /*! \brief Initialize SIP request */
08651 static int init_req(struct sip_request *req, int sipmethod, const char *recip)
08652 {
08653    /* Initialize a request */
08654    memset(req, 0, sizeof(*req));
08655    if (!(req->data = ast_str_create(SIP_MIN_PACKET)))
08656       return -1;
08657    req->method = sipmethod;
08658    req->header[0] = 0;
08659    ast_str_set(&req->data, 0, "%s %s SIP/2.0\r\n", sip_methods[sipmethod].text, recip);
08660    req->len = req->data->used;
08661    req->headers++;
08662    return 0;
08663 }
08664 
08665 /*! \brief Test if this response needs a contact header */
08666 static inline int resp_needs_contact(const char *msg, enum sipmethod method) {
08667    /* Requirements for Contact header inclusion in responses generated
08668     * from the header tables found in the following RFCs.  Where the
08669     * Contact header was marked mandatory (m) or optional (o) this
08670     * function returns 1.
08671     *
08672     * - RFC 3261 (ACK, BYE, CANCEL, INVITE, OPTIONS, REGISTER)
08673     * - RFC 2976 (INFO)
08674     * - RFC 3262 (PRACK)
08675     * - RFC 3265 (SUBSCRIBE, NOTIFY)
08676     * - RFC 3311 (UPDATE)
08677     * - RFC 3428 (MESSAGE)
08678     * - RFC 3515 (REFER)
08679     * - RFC 3903 (PUBLISH)
08680     */
08681 
08682    switch (method) {
08683       /* 1xx, 2xx, 3xx, 485 */
08684       case SIP_INVITE:
08685       case SIP_UPDATE:
08686       case SIP_SUBSCRIBE:
08687       case SIP_NOTIFY:
08688          if ((msg[0] >= '1' && msg[0] <= '3') || !strncmp(msg, "485", 3))
08689             return 1;
08690          break;
08691 
08692       /* 2xx, 3xx, 485 */
08693       case SIP_REGISTER:
08694       case SIP_OPTIONS:
08695          if (msg[0] == '2' || msg[0] == '3' || !strncmp(msg, "485", 3))
08696             return 1;
08697          break;
08698 
08699       /* 3xx, 485 */
08700       case SIP_BYE:
08701       case SIP_PRACK:
08702       case SIP_MESSAGE:
08703       case SIP_PUBLISH:
08704          if (msg[0] == '3' || !strncmp(msg, "485", 3))
08705             return 1;
08706          break;
08707 
08708       /* 2xx, 3xx, 4xx, 5xx, 6xx */
08709       case SIP_REFER:
08710          if (msg[0] >= '2' && msg[0] <= '6')
08711             return 1;
08712          break;
08713 
08714       /* contact will not be included for everything else */
08715       case SIP_ACK:
08716       case SIP_CANCEL:
08717       case SIP_INFO:
08718       case SIP_PING:
08719       default:
08720          return 0;
08721    }
08722    return 0;
08723 }
08724 
08725 /*! \brief Prepare SIP response packet */
08726 static int respprep(struct sip_request *resp, struct sip_pvt *p, const char *msg, const struct sip_request *req)
08727 {
08728    char newto[256];
08729    const char *ot;
08730 
08731    init_resp(resp, msg);
08732    copy_via_headers(p, resp, req, "Via");
08733    if (msg[0] == '1' || msg[0] == '2')
08734       copy_all_header(resp, req, "Record-Route");
08735    copy_header(resp, req, "From");
08736    ot = get_header(req, "To");
08737    if (!strcasestr(ot, "tag=") && strncmp(msg, "100", 3)) {
08738       /* Add the proper tag if we don't have it already.  If they have specified
08739          their tag, use it.  Otherwise, use our own tag */
08740       if (!ast_strlen_zero(p->theirtag) && ast_test_flag(&p->flags[0], SIP_OUTGOING))
08741          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08742       else if (p->tag && !ast_test_flag(&p->flags[0], SIP_OUTGOING))
08743          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08744       else
08745          ast_copy_string(newto, ot, sizeof(newto));
08746       ot = newto;
08747    }
08748    add_header(resp, "To", ot);
08749    copy_header(resp, req, "Call-ID");
08750    copy_header(resp, req, "CSeq");
08751    if (!ast_strlen_zero(global_useragent))
08752       add_header(resp, "Server", global_useragent);
08753    add_header(resp, "Allow", ALLOWED_METHODS);
08754    add_header(resp, "Supported", SUPPORTED_EXTENSIONS);
08755 
08756    /* If this is an invite, add Session-Timers related headers if the feature is active for this session */
08757    if (p->method == SIP_INVITE && p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE) {
08758       char se_hdr[256];
08759       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
08760          strefresher2str(p->stimer->st_ref));
08761       add_header(resp, "Require", "timer");
08762       add_header(resp, "Session-Expires", se_hdr);
08763    }
08764 
08765    if (msg[0] == '2' && (p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER)) {
08766       /* For registration responses, we also need expiry and
08767          contact info */
08768       char tmp[256];
08769 
08770       snprintf(tmp, sizeof(tmp), "%d", p->expiry);
08771       add_header(resp, "Expires", tmp);
08772       if (p->expiry) {  /* Only add contact if we have an expiry time */
08773          char contact[SIPBUFSIZE];
08774          const char *contact_uri = p->method == SIP_SUBSCRIBE ? p->our_contact : p->fullcontact;
08775          char *brackets = strchr(contact_uri, '<');
08776          snprintf(contact, sizeof(contact), "%s%s%s;expires=%d", brackets ? "" : "<", contact_uri, brackets ? "" : ">", p->expiry);
08777          add_header(resp, "Contact", contact);  /* Not when we unregister */
08778       }
08779    } else if (!ast_strlen_zero(p->our_contact) && resp_needs_contact(msg, p->method)) {
08780       add_header(resp, "Contact", p->our_contact);
08781    }
08782 
08783    if (!ast_strlen_zero(p->url)) {
08784       add_header(resp, "Access-URL", p->url);
08785       ast_string_field_set(p, url, NULL);
08786    }
08787 
08788    return 0;
08789 }
08790 
08791 /*! \brief Initialize a SIP request message (not the initial one in a dialog) */
08792 static int reqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod, int seqno, int newbranch)
08793 {
08794    struct sip_request *orig = &p->initreq;
08795    char stripped[80];
08796    char tmp[80];
08797    char newto[256];
08798    const char *c;
08799    const char *ot, *of;
08800    int is_strict = FALSE;     /*!< Strict routing flag */
08801    int is_outbound = ast_test_flag(&p->flags[0], SIP_OUTGOING);   /* Session direction */
08802 
08803    memset(req, 0, sizeof(struct sip_request));
08804    
08805    snprintf(p->lastmsg, sizeof(p->lastmsg), "Tx: %s", sip_methods[sipmethod].text);
08806    
08807    if (!seqno) {
08808       p->ocseq++;
08809       seqno = p->ocseq;
08810    }
08811    
08812    /* A CANCEL must have the same branch as the INVITE that it is canceling. */
08813    if (sipmethod == SIP_CANCEL) {
08814       p->branch = p->invite_branch;
08815       build_via(p);
08816    } else if (newbranch && (sipmethod == SIP_INVITE)) {
08817       p->branch ^= ast_random();
08818       p->invite_branch = p->branch;
08819       build_via(p);
08820    } else if (newbranch) {
08821       p->branch ^= ast_random();
08822       build_via(p);
08823    }
08824 
08825    /* Check for strict or loose router */
08826    if (p->route && !ast_strlen_zero(p->route->hop) && strstr(p->route->hop, ";lr") == NULL) {
08827       is_strict = TRUE;
08828       if (sipdebug)
08829          ast_debug(1, "Strict routing enforced for session %s\n", p->callid);
08830    }
08831    
08832    if (sipmethod == SIP_CANCEL)
08833       c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2); /* Use original URI */
08834    else if (sipmethod == SIP_ACK) {
08835       /* Use URI from Contact: in 200 OK (if INVITE) 
08836       (we only have the contacturi on INVITEs) */
08837       if (!ast_strlen_zero(p->okcontacturi))
08838          c = is_strict ? p->route->hop : p->okcontacturi;
08839       else
08840          c = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
08841    } else if (!ast_strlen_zero(p->okcontacturi)) 
08842       c = is_strict ? p->route->hop : p->okcontacturi; /* Use for BYE or REINVITE */
08843    else if (!ast_strlen_zero(p->uri)) 
08844       c = p->uri;
08845    else {
08846       char *n;
08847       /* We have no URI, use To: or From:  header as URI (depending on direction) */
08848       ast_copy_string(stripped, get_header(orig, is_outbound ? "To" : "From"),
08849             sizeof(stripped));
08850       n = get_in_brackets(stripped);
08851       c = remove_uri_parameters(n);
08852    }  
08853    init_req(req, sipmethod, c);
08854 
08855    snprintf(tmp, sizeof(tmp), "%d %s", seqno, sip_methods[sipmethod].text);
08856 
08857    add_header(req, "Via", p->via);
08858    if (p->route) {
08859       set_destination(p, p->route->hop);
08860       add_route(req, is_strict ? p->route->next : p->route);
08861    }
08862    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
08863 
08864    ot = get_header(orig, "To");
08865    of = get_header(orig, "From");
08866 
08867    /* Add tag *unless* this is a CANCEL, in which case we need to send it exactly
08868       as our original request, including tag (or presumably lack thereof) */
08869    if (!strcasestr(ot, "tag=") && sipmethod != SIP_CANCEL) {
08870       /* Add the proper tag if we don't have it already.  If they have specified
08871          their tag, use it.  Otherwise, use our own tag */
08872       if (is_outbound && !ast_strlen_zero(p->theirtag))
08873          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->theirtag);
08874       else if (!is_outbound)
08875          snprintf(newto, sizeof(newto), "%s;tag=%s", ot, p->tag);
08876       else
08877          snprintf(newto, sizeof(newto), "%s", ot);
08878       ot = newto;
08879    }
08880 
08881    if (is_outbound) {
08882       add_header(req, "From", of);
08883       add_header(req, "To", ot);
08884    } else {
08885       add_header(req, "From", ot);
08886       add_header(req, "To", of);
08887    }
08888    /* Do not add Contact for MESSAGE, BYE and Cancel requests */
08889    if (sipmethod != SIP_BYE && sipmethod != SIP_CANCEL && sipmethod != SIP_MESSAGE)
08890       add_header(req, "Contact", p->our_contact);
08891 
08892    copy_header(req, orig, "Call-ID");
08893    add_header(req, "CSeq", tmp);
08894 
08895    if (!ast_strlen_zero(global_useragent))
08896       add_header(req, "User-Agent", global_useragent);
08897 
08898    if (!ast_strlen_zero(p->rpid))
08899       add_header(req, "Remote-Party-ID", p->rpid);
08900 
08901    if (!ast_strlen_zero(p->url)) {
08902       add_header(req, "Access-URL", p->url);
08903       ast_string_field_set(p, url, NULL);
08904    }
08905 
08906    /* Add Session-Timers related headers if the feature is active for this session.
08907       An exception to this behavior is the ACK request. Since Asterisk never requires 
08908       session-timers support from a remote end-point (UAS) in an INVITE, it must 
08909       not send 'Require: timer' header in the ACK request. 
08910       This should only be added in the INVITE transactions, not MESSAGE or REFER or other
08911       in-dialog messages.
08912    */
08913    if (p->stimer && p->stimer->st_active == TRUE && p->stimer->st_active_peer_ua == TRUE 
08914        && sipmethod == SIP_INVITE) {
08915       char se_hdr[256];
08916       snprintf(se_hdr, sizeof(se_hdr), "%d;refresher=%s", p->stimer->st_interval, 
08917          strefresher2str(p->stimer->st_ref));
08918       add_header(req, "Require", "timer");
08919       add_header(req, "Session-Expires", se_hdr);
08920       snprintf(se_hdr, sizeof(se_hdr), "%d", st_get_se(p, FALSE));
08921       add_header(req, "Min-SE", se_hdr);
08922    }
08923 
08924    return 0;
08925 }
08926 
08927 /*! \brief Base transmit response function */
08928 static int __transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
08929 {
08930    struct sip_request resp;
08931    int seqno = 0;
08932 
08933    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
08934       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
08935       return -1;
08936    }
08937    respprep(&resp, p, msg, req);
08938    add_header_contentLength(&resp, 0);
08939    /* If we are cancelling an incoming invite for some reason, add information
08940       about the reason why we are doing this in clear text */
08941    if (p->method == SIP_INVITE && msg[0] != '1' && p->owner && p->owner->hangupcause) {
08942       char buf[10];
08943 
08944       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->owner->hangupcause));
08945       snprintf(buf, sizeof(buf), "%d", p->owner->hangupcause);
08946       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
08947    }
08948    return send_response(p, &resp, reliable, seqno);
08949 }
08950 
08951 static int temp_pvt_init(void *data)
08952 {
08953    struct sip_pvt *p = data;
08954 
08955    p->do_history = 0;   /* XXX do we need it ? isn't already all 0 ? */
08956    return ast_string_field_init(p, 512);
08957 }
08958 
08959 static void temp_pvt_cleanup(void *data)
08960 {
08961    struct sip_pvt *p = data;
08962 
08963    ast_string_field_free_memory(p);
08964 
08965    ast_free(data);
08966 }
08967 
08968 /*! \brief Transmit response, no retransmits, using a temporary pvt structure */
08969 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)
08970 {
08971    struct sip_pvt *p = NULL;
08972 
08973    if (!(p = ast_threadstorage_get(&ts_temp_pvt, sizeof(*p)))) {
08974       ast_log(LOG_ERROR, "Failed to get temporary pvt\n");
08975       return -1;
08976    }
08977 
08978    /* XXX the structure may be dirty from previous usage.
08979     * Here we should state clearly how we should reinitialize it
08980     * before using it.
08981     * E.g. certainly the threadstorage should be left alone,
08982     * but other thihngs such as flags etc. maybe need cleanup ?
08983     */
08984     
08985    /* Initialize the bare minimum */
08986    p->method = intended_method;
08987 
08988    if (!sin)
08989       p->ourip = internip;
08990    else {
08991       p->sa = *sin;
08992       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
08993    }
08994 
08995    p->branch = ast_random();
08996    make_our_tag(p->tag, sizeof(p->tag));
08997    p->ocseq = INITIAL_CSEQ;
08998 
08999    if (useglobal_nat && sin) {
09000       ast_copy_flags(&p->flags[0], &global_flags[0], SIP_NAT);
09001       p->recv = *sin;
09002       do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT) & SIP_NAT_ROUTE);
09003    }
09004 
09005    ast_string_field_set(p, fromdomain, default_fromdomain);
09006    build_via(p);
09007    ast_string_field_set(p, callid, callid);
09008 
09009    copy_socket_data(&p->socket, &req->socket);
09010 
09011    /* Use this temporary pvt structure to send the message */
09012    __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09013 
09014    /* Free the string fields, but not the pool space */
09015    ast_string_field_init(p, 0);
09016 
09017    return 0;
09018 }
09019 
09020 /*! \brief Transmit response, no retransmits */
09021 static int transmit_response(struct sip_pvt *p, const char *msg, const struct sip_request *req) 
09022 {
09023    return __transmit_response(p, msg, req, XMIT_UNRELIABLE);
09024 }
09025 
09026 /*! \brief Transmit response, no retransmits */
09027 static int transmit_response_with_unsupported(struct sip_pvt *p, const char *msg, const struct sip_request *req, const char *unsupported) 
09028 {
09029    struct sip_request resp;
09030    respprep(&resp, p, msg, req);
09031    append_date(&resp);
09032    add_header(&resp, "Unsupported", unsupported);
09033    add_header_contentLength(&resp, 0);
09034    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09035 }
09036 
09037 /*! \brief Transmit 422 response with Min-SE header (Session-Timers)  */
09038 static int transmit_response_with_minse(struct sip_pvt *p, const char *msg, const struct sip_request *req, int minse_int)
09039 {
09040    struct sip_request resp;
09041    char minse_str[20];
09042 
09043    respprep(&resp, p, msg, req);
09044    append_date(&resp);
09045 
09046    snprintf(minse_str, sizeof(minse_str), "%d", minse_int);
09047    add_header(&resp, "Min-SE", minse_str);
09048 
09049    add_header_contentLength(&resp, 0);
09050    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09051 }
09052 
09053 
09054 /*! \brief Transmit response, Make sure you get an ACK
09055    This is only used for responses to INVITEs, where we need to make sure we get an ACK
09056 */
09057 static int transmit_response_reliable(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09058 {
09059    return __transmit_response(p, msg, req, req->ignore ? XMIT_UNRELIABLE : XMIT_CRITICAL);
09060 }
09061 
09062 /*! \brief Append date to SIP message */
09063 static void append_date(struct sip_request *req)
09064 {
09065    char tmpdat[256];
09066    struct tm tm;
09067    time_t t = time(NULL);
09068 
09069    gmtime_r(&t, &tm);
09070    strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T GMT", &tm);
09071    add_header(req, "Date", tmpdat);
09072 }
09073 
09074 /*! \brief Append date and content length before transmitting response */
09075 static int transmit_response_with_date(struct sip_pvt *p, const char *msg, const struct sip_request *req)
09076 {
09077    struct sip_request resp;
09078    respprep(&resp, p, msg, req);
09079    append_date(&resp);
09080    add_header_contentLength(&resp, 0);
09081    return send_response(p, &resp, XMIT_UNRELIABLE, 0);
09082 }
09083 
09084 /*! \brief Append Accept header, content length before transmitting response */
09085 static int transmit_response_with_allow(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable)
09086 {
09087    struct sip_request resp;
09088    respprep(&resp, p, msg, req);
09089    add_header(&resp, "Accept", "application/sdp");
09090    add_header_contentLength(&resp, 0);
09091    return send_response(p, &resp, reliable, 0);
09092 }
09093 
09094 /*! \brief Respond with authorization request */
09095 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)
09096 {
09097    struct sip_request resp;
09098    char tmp[512];
09099    int seqno = 0;
09100 
09101    if (reliable && (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1)) {
09102       ast_log(LOG_WARNING, "Unable to determine sequence number from '%s'\n", get_header(req, "CSeq"));
09103       return -1;
09104    }
09105    /* Stale means that they sent us correct authentication, but 
09106       based it on an old challenge (nonce) */
09107    snprintf(tmp, sizeof(tmp), "Digest algorithm=MD5, realm=\"%s\", nonce=\"%s\"%s", global_realm, randdata, stale ? ", stale=true" : "");
09108    respprep(&resp, p, msg, req);
09109    add_header(&resp, header, tmp);
09110    add_header_contentLength(&resp, 0);
09111    append_history(p, "AuthChal", "Auth challenge sent for %s - nc %d", p->username, p->noncecount);
09112    return send_response(p, &resp, reliable, seqno);
09113 }
09114 
09115 /* Only use a static string for the msg, here! */
09116 static int transmit_provisional_response(struct sip_pvt *p, const char *msg, const struct sip_request *req, int with_sdp)
09117 {
09118    int res;
09119 
09120    if (!(res = with_sdp ? transmit_response_with_sdp(p, msg, req, XMIT_UNRELIABLE, FALSE) : transmit_response(p, msg, req))) {
09121       p->last_provisional = msg;
09122       update_provisional_keepalive(p, with_sdp);
09123    }
09124 
09125    return res;
09126 }
09127 
09128 /*! \brief Add text body to SIP message */
09129 static int add_text(struct sip_request *req, const char *text)
09130 {
09131    /* XXX Convert \n's to \r\n's XXX */
09132    add_header(req, "Content-Type", "text/plain;charset=UTF-8");
09133    add_header_contentLength(req, strlen(text));
09134    add_line(req, text);
09135    return 0;
09136 }
09137 
09138 /*! \brief Add DTMF INFO tone to sip message 
09139    Mode =   0 for application/dtmf-relay (Cisco)
09140       1 for application/dtmf
09141 */
09142 static int add_digit(struct sip_request *req, char digit, unsigned int duration, int mode)
09143 {
09144    char tmp[256];
09145    int event;
09146    if (mode) {
09147       /* Application/dtmf short version used by some implementations */
09148       if (digit == '*')
09149          event = 10;
09150       else if (digit == '#')
09151          event = 11;
09152       else if ((digit >= 'A') && (digit <= 'D'))
09153          event = 12 + digit - 'A';
09154       else
09155          event = atoi(&digit);
09156       snprintf(tmp, sizeof(tmp), "%d\r\n", event);
09157       add_header(req, "Content-Type", "application/dtmf");
09158       add_header_contentLength(req, strlen(tmp));
09159       add_line(req, tmp);
09160    } else {
09161       /* Application/dtmf-relay as documented by Cisco */
09162       snprintf(tmp, sizeof(tmp), "Signal=%c\r\nDuration=%u\r\n", digit, duration);
09163       add_header(req, "Content-Type", "application/dtmf-relay");
09164       add_header_contentLength(req, strlen(tmp));
09165       add_line(req, tmp);
09166    }
09167    return 0;
09168 }
09169 
09170 /*! \brief add XML encoded media control with update 
09171    \note XML: The only way to turn 0 bits of information into a few hundred. (markster) */
09172 static int add_vidupdate(struct sip_request *req)
09173 {
09174    const char *xml_is_a_huge_waste_of_space =
09175       "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\r\n"
09176       " <media_control>\r\n"
09177       "  <vc_primitive>\r\n"
09178       "   <to_encoder>\r\n"
09179       "    <picture_fast_update>\r\n"
09180       "    </picture_fast_update>\r\n"
09181       "   </to_encoder>\r\n"
09182       "  </vc_primitive>\r\n"
09183       " </media_control>\r\n";
09184    add_header(req, "Content-Type", "application/media_control+xml");
09185    add_header_contentLength(req, strlen(xml_is_a_huge_waste_of_space));
09186    add_line(req, xml_is_a_huge_waste_of_space);
09187    return 0;
09188 }
09189 
09190 /*! \brief Add codec offer to SDP offer/answer body in INVITE or 200 OK */
09191 static void add_codec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09192               struct ast_str **m_buf, struct ast_str **a_buf,
09193               int debug, int *min_packet_size)
09194 {
09195    int rtp_code;
09196    struct ast_format_list fmt;
09197 
09198 
09199    if (debug)
09200       ast_verbose("Adding codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09201    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 1, codec)) == -1)
09202       return;
09203 
09204    if (p->rtp) {
09205       struct ast_codec_pref *pref = ast_rtp_codec_getpref(p->rtp);
09206       fmt = ast_codec_pref_getsize(pref, codec);
09207    } 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 */
09208       return;
09209    ast_str_append(m_buf, 0, " %d", rtp_code);
09210    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09211           ast_rtp_lookup_mime_subtype(1, codec,
09212                        ast_test_flag(&p->flags[0], SIP_G726_NONSTANDARD) ? AST_RTP_OPT_G726_NONSTANDARD : 0),
09213           sample_rate);
09214    if (codec == AST_FORMAT_G729A) {
09215       /* Indicate that we don't support VAD (G.729 annex B) */
09216       ast_str_append(a_buf, 0, "a=fmtp:%d annexb=no\r\n", rtp_code);
09217    } else if (codec == AST_FORMAT_G723_1) {
09218       /* Indicate that we don't support VAD (G.723.1 annex A) */
09219       ast_str_append(a_buf, 0, "a=fmtp:%d annexa=no\r\n", rtp_code);
09220    } else if (codec == AST_FORMAT_ILBC) {
09221       /* Add information about us using only 20/30 ms packetization */
09222       ast_str_append(a_buf, 0, "a=fmtp:%d mode=%d\r\n", rtp_code, fmt.cur_ms);
09223    }
09224 
09225    if (fmt.cur_ms && (fmt.cur_ms < *min_packet_size))
09226       *min_packet_size = fmt.cur_ms;
09227 
09228    /* Our first codec packetization processed cannot be zero */
09229    if ((*min_packet_size)==0 && fmt.cur_ms)
09230       *min_packet_size = fmt.cur_ms;
09231 }
09232 
09233 /*! \brief Add video codec offer to SDP offer/answer body in INVITE or 200 OK */
09234 /* This is different to the audio one now so we can add more caps later */
09235 static void add_vcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09236               struct ast_str **m_buf, struct ast_str **a_buf,
09237               int debug, int *min_packet_size)
09238 {
09239    int rtp_code;
09240 
09241    if (!p->vrtp)
09242       return;
09243 
09244    if (debug)
09245       ast_verbose("Adding video codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09246 
09247    if ((rtp_code = ast_rtp_lookup_code(p->vrtp, 1, codec)) == -1)
09248       return;
09249 
09250    ast_str_append(m_buf, 0, " %d", rtp_code);
09251    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09252           ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
09253    /* Add fmtp code here */
09254 }
09255 
09256 /*! \brief Add text codec offer to SDP offer/answer body in INVITE or 200 OK */
09257 static void add_tcodec_to_sdp(const struct sip_pvt *p, int codec, int sample_rate,
09258               struct ast_str **m_buf, struct ast_str **a_buf,
09259               int debug, int *min_packet_size)
09260 {
09261    int rtp_code;
09262 
09263    if (!p->trtp)
09264       return;
09265 
09266    if (debug)
09267       ast_verbose("Adding text codec 0x%x (%s) to SDP\n", codec, ast_getformatname(codec));
09268 
09269    if ((rtp_code = ast_rtp_lookup_code(p->trtp, 1, codec)) == -1)
09270       return;
09271 
09272    ast_str_append(m_buf, 0, " %d", rtp_code);
09273    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09274           ast_rtp_lookup_mime_subtype(1, codec, 0), sample_rate);
09275    /* Add fmtp code here */
09276 
09277    if (codec == AST_FORMAT_T140RED) {
09278       ast_str_append(a_buf, 0, "a=fmtp:%d %d/%d/%d\r\n", rtp_code, 
09279           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09280           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140),
09281           ast_rtp_lookup_code(p->trtp, 1, AST_FORMAT_T140));
09282 
09283    }
09284 }
09285 
09286 
09287 /*! \brief Get Max T.38 Transmission rate from T38 capabilities */
09288 static unsigned int t38_get_rate(enum ast_control_t38_rate rate)
09289 {
09290    switch (rate) {
09291    case AST_T38_RATE_2400:
09292       return 2400;
09293    case AST_T38_RATE_4800:
09294       return 4800;
09295    case AST_T38_RATE_7200:
09296       return 7200;
09297    case AST_T38_RATE_9600:
09298       return 9600;
09299    case AST_T38_RATE_12000:
09300       return 12000;
09301    case AST_T38_RATE_14400:
09302       return 14400;
09303    default:
09304       return 0;
09305    }
09306 }
09307 
09308 /*! \brief Add RFC 2833 DTMF offer to SDP */
09309 static void add_noncodec_to_sdp(const struct sip_pvt *p, int format, int sample_rate,
09310             struct ast_str **m_buf, struct ast_str **a_buf,
09311             int debug)
09312 {
09313    int rtp_code;
09314 
09315    if (debug)
09316       ast_verbose("Adding non-codec 0x%x (%s) to SDP\n", format, ast_rtp_lookup_mime_subtype(0, format, 0));
09317    if ((rtp_code = ast_rtp_lookup_code(p->rtp, 0, format)) == -1)
09318       return;
09319 
09320    ast_str_append(m_buf, 0, " %d", rtp_code);
09321    ast_str_append(a_buf, 0, "a=rtpmap:%d %s/%d\r\n", rtp_code,
09322           ast_rtp_lookup_mime_subtype(0, format, 0),
09323           sample_rate);
09324    if (format == AST_RTP_DTMF)   /* Indicate we support DTMF and FLASH... */
09325       ast_str_append(a_buf, 0, "a=fmtp:%d 0-16\r\n", rtp_code);
09326 }
09327 
09328 /*! \brief Set all IP media addresses for this call 
09329    \note called from add_sdp()
09330 */
09331 static void get_our_media_address(struct sip_pvt *p, int needvideo,
09332    struct sockaddr_in *sin, struct sockaddr_in *vsin, struct sockaddr_in *tsin,
09333    struct sockaddr_in *dest, struct sockaddr_in *vdest)
09334 {
09335    /* First, get our address */
09336    ast_rtp_get_us(p->rtp, sin);
09337    if (p->vrtp)
09338       ast_rtp_get_us(p->vrtp, vsin);
09339    if (p->trtp)
09340       ast_rtp_get_us(p->trtp, tsin);
09341 
09342    /* Now, try to figure out where we want them to send data */
09343    /* Is this a re-invite to move the media out, then use the original offer from caller  */
09344    if (p->redirip.sin_addr.s_addr) {   /* If we have a redirection IP, use it */
09345       dest->sin_port = p->redirip.sin_port;
09346       dest->sin_addr = p->redirip.sin_addr;
09347    } else {
09348       dest->sin_addr = p->ourip.sin_addr;
09349       dest->sin_port = sin->sin_port;
09350    }
09351    if (needvideo) {
09352       /* Determine video destination */
09353       if (p->vredirip.sin_addr.s_addr) {
09354          vdest->sin_addr = p->vredirip.sin_addr;
09355          vdest->sin_port = p->vredirip.sin_port;
09356       } else {
09357          vdest->sin_addr = p->ourip.sin_addr;
09358          vdest->sin_port = vsin->sin_port;
09359       }
09360    }
09361 
09362 }
09363 
09364 /*!
09365  * \note G.722 actually is supposed to specified as 8 kHz, even though it is
09366  * really 16 kHz.  Update this macro for other formats as they are added in
09367  * the future.
09368  */
09369 #define SDP_SAMPLE_RATE(x) 8000
09370 
09371 /*! \brief Add Session Description Protocol message 
09372 
09373     If oldsdp is TRUE, then the SDP version number is not incremented. This mechanism
09374     is used in Session-Timers where RE-INVITEs are used for refreshing SIP sessions 
09375     without modifying the media session in any way. 
09376 */
09377 static enum sip_result add_sdp(struct sip_request *resp, struct sip_pvt *p, int oldsdp, int add_audio, int add_t38)
09378 {
09379    int len = 0;
09380    int alreadysent = 0;
09381 
09382    struct sockaddr_in sin;
09383    struct sockaddr_in vsin;
09384    struct sockaddr_in tsin;
09385    struct sockaddr_in dest;
09386    struct sockaddr_in udptlsin;
09387    struct sockaddr_in vdest = { 0, };
09388    struct sockaddr_in tdest = { 0, };
09389    struct sockaddr_in udptldest = { 0, };
09390 
09391    /* SDP fields */
09392    char *version =   "v=0\r\n";     /* Protocol version */
09393    char subject[256];            /* Subject of the session */
09394    char owner[256];           /* Session owner/creator */
09395    char connection[256];            /* Connection data */
09396    char *session_time = "t=0 0\r\n";         /* Time the session is active */
09397    char bandwidth[256] = "";        /* Max bitrate */
09398    char *hold = "";
09399    struct ast_str *m_audio = ast_str_alloca(256);  /* Media declaration line for audio */
09400    struct ast_str *m_video = ast_str_alloca(256);  /* Media declaration line for video */
09401    struct ast_str *m_text = ast_str_alloca(256);   /* Media declaration line for text */
09402    struct ast_str *m_modem = ast_str_alloca(256);  /* Media declaration line for modem */
09403    struct ast_str *a_audio = ast_str_alloca(1024); /* Attributes for audio */
09404    struct ast_str *a_video = ast_str_alloca(1024); /* Attributes for video */
09405    struct ast_str *a_text = ast_str_alloca(1024);  /* Attributes for text */
09406    struct ast_str *a_modem = ast_str_alloca(1024); /* Attributes for modem */
09407 
09408    int x;
09409    int capability = 0;
09410    int needaudio = FALSE;
09411    int needvideo = FALSE;
09412    int needtext = FALSE;
09413    int debug = sip_debug_test_pvt(p);
09414    int min_audio_packet_size = 0;
09415    int min_video_packet_size = 0;
09416    int min_text_packet_size = 0;
09417 
09418    char codecbuf[SIPBUFSIZE];
09419    char buf[SIPBUFSIZE];
09420    char dummy_answer[256];
09421 
09422    /* Set the SDP session name */
09423    snprintf(subject, sizeof(subject), "s=%s\r\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
09424 
09425    if (!p->rtp) {
09426       ast_log(LOG_WARNING, "No way to add SDP without an RTP structure\n");
09427       return AST_FAILURE;
09428    }
09429    /* XXX We should not change properties in the SIP dialog until 
09430       we have acceptance of the offer if this is a re-invite */
09431 
09432    /* Set RTP Session ID and version */
09433    if (!p->sessionid) {
09434       p->sessionid = (int)ast_random();
09435       p->sessionversion = p->sessionid;
09436    } else {
09437       if (oldsdp == FALSE)
09438          p->sessionversion++;
09439    }
09440 
09441    /* Check if we need video in this call */
09442    if (add_audio && (p->jointcapability & AST_FORMAT_VIDEO_MASK) && !p->novideo) {
09443       if (p->vrtp) {
09444          needvideo = TRUE;
09445          ast_debug(2, "This call needs video offers!\n");
09446       } else
09447          ast_debug(2, "This call needs video offers, but there's no video support enabled!\n");
09448    }
09449 
09450    get_our_media_address(p, needvideo, &sin, &vsin, &tsin, &dest, &vdest);
09451 
09452    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));
09453    snprintf(connection, sizeof(connection), "c=IN IP4 %s\r\n", ast_inet_ntoa(dest.sin_addr));
09454 
09455    if (add_audio) {
09456       capability = p->jointcapability;
09457 
09458       /* XXX note, Video and Text are negated - 'true' means 'no' */
09459       ast_debug(1, "** Our capability: %s Video flag: %s Text flag: %s\n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), capability), 
09460            p->novideo ? "True" : "False", p->notext ? "True" : "False");
09461       ast_debug(1, "** Our prefcodec: %s \n", ast_getformatname_multiple(codecbuf, sizeof(codecbuf), p->prefcodec));
09462 
09463       /* Check if we need audio */
09464       if (capability & AST_FORMAT_AUDIO_MASK)
09465          needaudio = TRUE;
09466 
09467       if (debug) 
09468          ast_verbose("Audio is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(sin.sin_port)); 
09469 
09470       /* Ok, we need video. Let's add what we need for video and set codecs.
09471          Video is handled differently than audio since we can not transcode. */
09472       if (needvideo) {
09473          ast_str_append(&m_video, 0, "m=video %d RTP/AVP", ntohs(vdest.sin_port));
09474 
09475          /* Build max bitrate string */
09476          if (p->maxcallbitrate)
09477             snprintf(bandwidth, sizeof(bandwidth), "b=CT:%d\r\n", p->maxcallbitrate);
09478          if (debug) 
09479             ast_verbose("Video is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(vdest.sin_port));  
09480       }
09481 
09482       /* Check if we need text in this call */
09483       if((capability & AST_FORMAT_TEXT_MASK) && !p->notext) {
09484          if (sipdebug_text)
09485             ast_verbose("We think we can do text\n");
09486          if (p->trtp) {
09487             if (sipdebug_text)
09488                ast_verbose("And we have a text rtp object\n");
09489             needtext = TRUE;
09490             ast_debug(2, "This call needs text offers! \n");
09491          } else
09492             ast_debug(2, "This call needs text offers, but there's no text support enabled ! \n");
09493       }
09494       
09495       /* Ok, we need text. Let's add what we need for text and set codecs.
09496          Text is handled differently than audio since we can not transcode. */
09497       if (needtext) {
09498          if (sipdebug_text)
09499             ast_verbose("Lets set up the text sdp\n");
09500          /* Determine text destination */
09501          if (p->tredirip.sin_addr.s_addr) {
09502             tdest.sin_addr = p->tredirip.sin_addr;
09503             tdest.sin_port = p->tredirip.sin_port;
09504          } else {
09505             tdest.sin_addr = p->ourip.sin_addr;
09506             tdest.sin_port = tsin.sin_port;
09507          }
09508          ast_str_append(&m_text, 0, "m=text %d RTP/AVP", ntohs(tdest.sin_port));
09509 
09510          if (debug) /* XXX should I use tdest below ? */
09511             ast_verbose("Text is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(tsin.sin_port)); 
09512 
09513       }
09514 
09515       /* Start building generic SDP headers */
09516 
09517       /* We break with the "recommendation" and send our IP, in order that our
09518          peer doesn't have to ast_gethostbyname() us */
09519 
09520       ast_str_append(&m_audio, 0, "m=audio %d RTP/AVP", ntohs(dest.sin_port));
09521 
09522       if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_ONEDIR)
09523          hold = "a=recvonly\r\n";
09524       else if (ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD) == SIP_PAGE2_CALL_ONHOLD_INACTIVE)
09525          hold = "a=inactive\r\n";
09526       else
09527          hold = "a=sendrecv\r\n";
09528 
09529       /* Now, start adding audio codecs. These are added in this order:
09530          - First what was requested by the calling channel
09531          - Then preferences in order from sip.conf device config for this peer/user
09532          - Then other codecs in capabilities, including video
09533       */
09534 
09535       /* Prefer the audio codec we were requested to use, first, no matter what 
09536          Note that p->prefcodec can include video codecs, so mask them out
09537       */
09538       if (capability & p->prefcodec) {
09539          int codec = p->prefcodec & AST_FORMAT_AUDIO_MASK;
09540 
09541          add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09542                 &m_audio, &a_audio,
09543                 debug, &min_audio_packet_size);
09544          alreadysent |= codec;
09545       }
09546 
09547       /* Start by sending our preferred audio/video codecs */
09548       for (x = 0; x < 32; x++) {
09549          int codec;
09550 
09551          if (!(codec = ast_codec_pref_index(&p->prefs, x)))
09552             break; 
09553 
09554          if (!(capability & codec))
09555             continue;
09556 
09557          if (alreadysent & codec)
09558          continue;
09559 
09560          add_codec_to_sdp(p, codec, SDP_SAMPLE_RATE(codec),
09561                 &m_audio, &a_audio,
09562                 debug, &min_audio_packet_size);
09563          alreadysent |= codec;
09564       }
09565 
09566       /* Now send any other common audio and video codecs, and non-codec formats: */
09567       for (x = 1; x <= (needtext ? AST_FORMAT_TEXT_MASK : (needvideo ? AST_FORMAT_VIDEO_MASK : AST_FORMAT_AUDIO_MASK)); x <<= 1) {
09568          if (!(capability & x))  /* Codec not requested */
09569             continue;
09570 
09571          if (alreadysent & x) /* Already added to SDP */
09572             continue;
09573 
09574          if (x & AST_FORMAT_AUDIO_MASK)
09575             add_codec_to_sdp(p, x, SDP_SAMPLE_RATE(x),
09576                    &m_audio, &a_audio, debug, &min_audio_packet_size);
09577          else if (x & AST_FORMAT_VIDEO_MASK) 
09578             add_vcodec_to_sdp(p, x, 90000,
09579                     &m_video, &a_video, debug, &min_video_packet_size);
09580          else if (x & AST_FORMAT_TEXT_MASK)
09581             add_tcodec_to_sdp(p, x, 1000,
09582                     &m_text, &a_text, debug, &min_text_packet_size);
09583       }
09584 
09585       /* Now add DTMF RFC2833 telephony-event as a codec */
09586       for (x = 1; x <= AST_RTP_MAX; x <<= 1) {
09587          if (!(p->jointnoncodeccapability & x))
09588             continue;
09589 
09590          add_noncodec_to_sdp(p, x, 8000, &m_audio, &a_audio, debug);
09591       }
09592 
09593       ast_debug(3, "-- Done with adding codecs to SDP\n");
09594 
09595       if (!p->owner || !ast_internal_timing_enabled(p->owner))
09596          ast_str_append(&a_audio, 0, "a=silenceSupp:off - - - -\r\n");
09597 
09598       if (min_audio_packet_size)
09599          ast_str_append(&a_audio, 0, "a=ptime:%d\r\n", min_audio_packet_size);
09600 
09601       /* XXX don't think you can have ptime for video */
09602       if (min_video_packet_size)
09603          ast_str_append(&a_video, 0, "a=ptime:%d\r\n", min_video_packet_size);
09604 
09605       /* XXX don't think you can have ptime for text */
09606       if (min_text_packet_size)
09607          ast_str_append(&a_text, 0, "a=ptime:%d\r\n", min_text_packet_size);
09608    }
09609 
09610    if (add_t38) {
09611       ast_udptl_get_us(p->udptl, &udptlsin);
09612 
09613       /* Determine T.38 UDPTL destination */
09614       if (p->udptlredirip.sin_addr.s_addr) {
09615          udptldest.sin_port = p->udptlredirip.sin_port;
09616          udptldest.sin_addr = p->udptlredirip.sin_addr;
09617       } else {
09618          udptldest.sin_addr = p->ourip.sin_addr;
09619          udptldest.sin_port = udptlsin.sin_port;
09620       }
09621 
09622       if (debug)
09623          ast_debug(1, "T.38 UDPTL is at %s port %d\n", ast_inet_ntoa(p->ourip.sin_addr), ntohs(udptlsin.sin_port));
09624 
09625       /* We break with the "recommendation" and send our IP, in order that our
09626          peer doesn't have to ast_gethostbyname() us */
09627 
09628       ast_str_append(&m_modem, 0, "m=image %d udptl t38\r\n", ntohs(udptldest.sin_port));
09629 
09630       ast_str_append(&a_modem, 0, "a=T38FaxVersion:%d\r\n", p->t38.our_parms.version);
09631       ast_str_append(&a_modem, 0, "a=T38MaxBitRate:%d\r\n", t38_get_rate(p->t38.our_parms.rate));
09632       if (p->t38.our_parms.fill_bit_removal) {
09633          ast_str_append(&a_modem, 0, "a=T38FaxFillBitRemoval\r\n");
09634       }
09635       if (p->t38.our_parms.transcoding_mmr) {
09636          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingMMR\r\n");
09637       }
09638       if (p->t38.our_parms.transcoding_jbig) {
09639          ast_str_append(&a_modem, 0, "a=T38FaxTranscodingJBIG\r\n");
09640       }
09641       switch (p->t38.our_parms.rate_management) {
09642       case AST_T38_RATE_MANAGEMENT_TRANSFERRED_TCF:
09643          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:transferredTCF\r\n");
09644          break;
09645       case AST_T38_RATE_MANAGEMENT_LOCAL_TCF:
09646          ast_str_append(&a_modem, 0, "a=T38FaxRateManagement:localTCF\r\n");
09647          break;
09648       }
09649       ast_str_append(&a_modem, 0, "a=T38FaxMaxDatagram:%u\r\n", ast_udptl_get_local_max_datagram(p->udptl));
09650       switch (ast_udptl_get_error_correction_scheme(p->udptl)) {
09651       case UDPTL_ERROR_CORRECTION_NONE:
09652          break;
09653       case UDPTL_ERROR_CORRECTION_FEC:
09654          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPFEC\r\n");
09655          break;
09656       case UDPTL_ERROR_CORRECTION_REDUNDANCY:
09657          ast_str_append(&a_modem, 0, "a=T38FaxUdpEC:t38UDPRedundancy\r\n");
09658          break;
09659       }
09660    }
09661 
09662    if (m_audio->len - m_audio->used < 2 || m_video->len - m_video->used < 2 ||
09663        m_text->len - m_text->used < 2 || a_text->len - a_text->used < 2 ||
09664        a_audio->len - a_audio->used < 2 || a_video->len - a_video->used < 2)
09665       ast_log(LOG_WARNING, "SIP SDP may be truncated due to undersized buffer!!\n");
09666 
09667    if (needaudio)
09668       ast_str_append(&m_audio, 0, "\r\n");
09669    if (needvideo)
09670       ast_str_append(&m_video, 0, "\r\n");
09671    if (needtext)
09672       ast_str_append(&m_text, 0, "\r\n");
09673 
09674    len = strlen(version) + strlen(subject) + strlen(owner) +
09675       strlen(connection) + strlen(session_time);
09676    if (needaudio)
09677       len += m_audio->used + a_audio->used + strlen(hold);
09678    if (needvideo) /* only if video response is appropriate */
09679       len += m_video->used + a_video->used + strlen(bandwidth) + strlen(hold);
09680    if (needtext) /* only if text response is appropriate */
09681       len += m_text->used + a_text->used + strlen(hold);
09682    if (add_t38)
09683       len += m_modem->used + a_modem->used;
09684 
09685    add_header(resp, "Content-Type", "application/sdp");
09686    add_header_contentLength(resp, len);
09687    add_line(resp, version);
09688    add_line(resp, owner);
09689    add_line(resp, subject);
09690    add_line(resp, connection);
09691    if (needvideo)    /* only if video response is appropriate */
09692       add_line(resp, bandwidth);
09693    add_line(resp, session_time);
09694    if (needaudio) {
09695       add_line(resp, m_audio->str);
09696       add_line(resp, a_audio->str);
09697       add_line(resp, hold);
09698    } else if (p->offered_media[SDP_AUDIO].offered) {
09699       snprintf(dummy_answer, sizeof(dummy_answer), "m=audio 0 RTP/AVP %s\r\n", p->offered_media[SDP_AUDIO].text);
09700       add_line(resp, dummy_answer);
09701    }
09702    if (needvideo) { /* only if video response is appropriate */
09703       add_line(resp, m_video->str);
09704       add_line(resp, a_video->str);
09705       add_line(resp, hold);   /* Repeat hold for the video stream */
09706    } else if (p->offered_media[SDP_VIDEO].offered) {
09707       snprintf(dummy_answer, sizeof(dummy_answer), "m=video 0 RTP/AVP %s\r\n", p->offered_media[SDP_VIDEO].text);
09708       add_line(resp, dummy_answer);
09709    }
09710    if (needtext) { /* only if text response is appropriate */
09711       add_line(resp, m_text->str);
09712       add_line(resp, a_text->str);
09713       add_line(resp, hold);   /* Repeat hold for the text stream */
09714    } else if (p->offered_media[SDP_TEXT].offered) {
09715       snprintf(dummy_answer, sizeof(dummy_answer), "m=text 0 RTP/AVP %s\r\n", p->offered_media[SDP_TEXT].text);
09716       add_line(resp, dummy_answer);
09717    }
09718    if (add_t38) {
09719       add_line(resp, m_modem->str);
09720       add_line(resp, a_modem->str);
09721    } else if (p->offered_media[SDP_IMAGE].offered) {
09722       add_line(resp, "m=image 0 udptl t38\r\n");
09723    }
09724 
09725    /* Update lastrtprx when we send our SDP */
09726    p->lastrtprx = p->lastrtptx = time(NULL); /* XXX why both ? */
09727 
09728    ast_debug(3, "Done building SDP. Settling with this capability: %s\n", ast_getformatname_multiple(buf, SIPBUFSIZE, capability));
09729 
09730    return AST_SUCCESS;
09731 }
09732 
09733 /*! \brief Used for 200 OK and 183 early media */
09734 static int transmit_response_with_t38_sdp(struct sip_pvt *p, char *msg, struct sip_request *req, int retrans)
09735 {
09736    struct sip_request resp;
09737    int seqno;
09738    
09739    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09740       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09741       return -1;
09742    }
09743    respprep(&resp, p, msg, req);
09744    if (p->udptl) {
09745       add_sdp(&resp, p, 0, 0, 1);
09746    } else 
09747       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no UDPTL session allocated. Call-ID %s\n", p->callid);
09748    if (retrans && !p->pendinginvite)
09749       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
09750    return send_response(p, &resp, retrans, seqno);
09751 }
09752 
09753 /*! \brief copy SIP request (mostly used to save request for responses) */
09754 static void copy_request(struct sip_request *dst, const struct sip_request *src)
09755 {
09756    struct ast_str *duplicate = dst->data;
09757 
09758    /* First copy stuff */
09759    memcpy(dst, src, sizeof(*dst));
09760    dst->data = duplicate;
09761 
09762    /* All these + 1's are to account for the need to include the NULL terminator
09763     * Using typical string functions like ast_copy_string or ast_str_set will not
09764     * work in this case because the src's data string is riddled with \0's all over
09765     * the place and so a memcpy is the only way to accurately copy the string
09766     */
09767 
09768    if (!dst->data && !(dst->data = ast_str_create(src->data->used + 1)))
09769       return;
09770    else if (dst->data->len < src->data->used + 1)
09771       ast_str_make_space(&dst->data, src->data->used + 1);
09772       
09773    memcpy(dst->data->str, src->data->str, src->data->used + 1);
09774    dst->data->used = src->data->used;
09775 }
09776 
09777 /*! \brief Used for 200 OK and 183 early media 
09778    \return Will return XMIT_ERROR for network errors.
09779 */
09780 static int transmit_response_with_sdp(struct sip_pvt *p, const char *msg, const struct sip_request *req, enum xmittype reliable, int oldsdp)
09781 {
09782    struct sip_request resp;
09783    int seqno;
09784    if (sscanf(get_header(req, "CSeq"), "%30d ", &seqno) != 1) {
09785       ast_log(LOG_WARNING, "Unable to get seqno from '%s'\n", get_header(req, "CSeq"));
09786       return -1;
09787    }
09788    respprep(&resp, p, msg, req);
09789    if (p->rtp) {
09790       if (!p->autoframing && !ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
09791          ast_debug(1, "Setting framing from config on incoming call\n");
09792          ast_rtp_codec_setpref(p->rtp, &p->prefs);
09793       }
09794       try_suggested_sip_codec(p);
09795       if (p->t38.state == T38_ENABLED) {
09796          add_sdp(&resp, p, oldsdp, TRUE, TRUE);
09797       } else {
09798          add_sdp(&resp, p, oldsdp, TRUE, FALSE);
09799       }
09800    } else 
09801       ast_log(LOG_ERROR, "Can't add SDP to response, since we have no RTP session allocated. Call-ID %s\n", p->callid);
09802    if (reliable && !p->pendinginvite)
09803       p->pendinginvite = seqno;     /* Buggy clients sends ACK on RINGING too */
09804    return send_response(p, &resp, reliable, seqno);
09805 }
09806 
09807 /*! \brief Parse first line of incoming SIP request */
09808 static int determine_firstline_parts(struct sip_request *req) 
09809 {
09810    char *e = ast_skip_blanks(req->data->str);   /* there shouldn't be any */
09811    char *local_rlPart1;
09812 
09813    if (!*e)
09814       return -1;
09815    req->rlPart1 = e - req->data->str;  /* method or protocol */
09816    local_rlPart1 = e;
09817    e = ast_skip_nonblanks(e);
09818    if (*e)
09819       *e++ = '\0';
09820    /* Get URI or status code */
09821    e = ast_skip_blanks(e);
09822    if ( !*e )
09823       return -1;
09824    ast_trim_blanks(e);
09825 
09826    if (!strcasecmp(local_rlPart1, "SIP/2.0") ) { /* We have a response */
09827       if (strlen(e) < 3)   /* status code is 3 digits */
09828          return -1;
09829       req->rlPart2 = e - req->data->str;
09830    } else { /* We have a request */
09831       if ( *e == '<' ) { /* XXX the spec says it must not be in <> ! */
09832          ast_debug(3, "Oops. Bogus uri in <> %s\n", e);
09833          e++;
09834          if (!*e)
09835             return -1; 
09836       }
09837       req->rlPart2 = e - req->data->str;  /* URI */
09838       e = ast_skip_nonblanks(e);
09839       if (*e)
09840          *e++ = '\0';
09841       e = ast_skip_blanks(e);
09842       if (strcasecmp(e, "SIP/2.0") ) {
09843          ast_debug(3, "Skipping packet - Bad request protocol %s\n", e);
09844          return -1;
09845       }
09846    }
09847    return 1;
09848 }
09849 
09850 /*! \brief Transmit reinvite with SDP
09851 \note    A re-invite is basically a new INVITE with the same CALL-ID and TAG as the
09852    INVITE that opened the SIP dialogue 
09853    We reinvite so that the audio stream (RTP) go directly between
09854    the SIP UAs. SIP Signalling stays with * in the path.
09855    
09856    If t38version is TRUE, we send T38 SDP for re-invite from audio/video to
09857    T38 UDPTL transmission on the channel
09858 
09859     If oldsdp is TRUE then the SDP version number is not incremented. This
09860     is needed for Session-Timers so we can send a re-invite to refresh the
09861     SIP session without modifying the media session. 
09862 */
09863 static int transmit_reinvite_with_sdp(struct sip_pvt *p, int t38version, int oldsdp)
09864 {
09865    struct sip_request req;
09866    
09867    reqprep(&req, p, ast_test_flag(&p->flags[0], SIP_REINVITE_UPDATE) ?  SIP_UPDATE : SIP_INVITE, 0, 1);
09868 
09869    add_header(&req, "Allow", ALLOWED_METHODS);
09870    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
09871    if (sipdebug) {
09872       if (oldsdp == TRUE)
09873          add_header(&req, "X-asterisk-Info", "SIP re-invite (Session-Timers)");
09874       else
09875          add_header(&req, "X-asterisk-Info", "SIP re-invite (External RTP bridge)");
09876    }
09877 
09878    if (p->do_history)
09879       append_history(p, "ReInv", "Re-invite sent");
09880    memset(p->offered_media, 0, sizeof(p->offered_media));
09881 
09882    if (t38version)
09883       add_sdp(&req, p, oldsdp, FALSE, TRUE);
09884    else
09885       add_sdp(&req, p, oldsdp, TRUE, FALSE);
09886 
09887    /* Use this as the basis */
09888    initialize_initreq(p, &req);
09889    p->lastinvite = p->ocseq;
09890    ast_set_flag(&p->flags[0], SIP_OUTGOING);       /* Change direction of this dialog */
09891 
09892    return send_request(p, &req, XMIT_CRITICAL, p->ocseq);
09893 }
09894 
09895 /* \brief Remove URI parameters at end of URI, not in username part though */
09896 static char *remove_uri_parameters(char *uri)
09897 {
09898    char *atsign;
09899    atsign = strchr(uri, '@'); /* First, locate the at sign */
09900    if (!atsign)
09901       atsign = uri;  /* Ok hostname only, let's stick with the rest */
09902    atsign = strchr(atsign, ';'); /* Locate semi colon */
09903    if (atsign)
09904       *atsign = '\0';   /* Kill at the semi colon */
09905    return uri;
09906 }
09907 
09908 /*! \brief Check Contact: URI of SIP message */
09909 static void extract_uri(struct sip_pvt *p, struct sip_request *req)
09910 {
09911    char stripped[SIPBUFSIZE];
09912    char *c;
09913 
09914    ast_copy_string(stripped, get_header(req, "Contact"), sizeof(stripped));
09915    c = get_in_brackets(stripped);
09916    /* Cut the URI at the at sign after the @, not in the username part */
09917    c = remove_uri_parameters(c);
09918    if (!ast_strlen_zero(c))
09919       ast_string_field_set(p, uri, c);
09920 
09921 }
09922 
09923 /*! \brief Build contact header - the contact header we send out */
09924 static void build_contact(struct sip_pvt *p)
09925 {
09926    int ourport = ntohs(p->ourip.sin_port);
09927    /* only add port if it's non-standard for the transport type */
09928    if (!sip_standard_port(p->socket.type, ourport)) {
09929       if (p->socket.type == SIP_TRANSPORT_UDP)
09930          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);
09931       else
09932          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));
09933    } else {
09934       if (p->socket.type == SIP_TRANSPORT_UDP)
09935          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));
09936       else
09937          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));
09938    }
09939 }
09940 
09941 /*! \brief Build the Remote Party-ID & From using callingpres options */
09942 static void build_rpid(struct sip_pvt *p)
09943 {
09944    int send_pres_tags = TRUE;
09945    const char *privacy=NULL;
09946    const char *screen=NULL;
09947    char buf[256];
09948    const char *clid = default_callerid;
09949    const char *clin = NULL;
09950    const char *fromdomain;
09951 
09952    if (!ast_strlen_zero(p->rpid) || !ast_strlen_zero(p->rpid_from))  
09953       return;
09954 
09955    if (p->owner && !ast_strlen_zero(p->owner->cid.cid_num))
09956       clid = p->owner->cid.cid_num;
09957    if (p->owner && p->owner->cid.cid_name)
09958       clin = p->owner->cid.cid_name;
09959    if (ast_strlen_zero(clin))
09960       clin = clid;
09961 
09962    switch (p->callingpres) {
09963    case AST_PRES_ALLOWED_USER_NUMBER_NOT_SCREENED:
09964       privacy = "off";
09965       screen = "no";
09966       break;
09967    case AST_PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN:
09968       privacy = "off";
09969       screen = "yes";
09970       break;
09971    case AST_PRES_ALLOWED_USER_NUMBER_FAILED_SCREEN:
09972       privacy = "off";
09973       screen = "no";
09974       break;
09975    case AST_PRES_ALLOWED_NETWORK_NUMBER:
09976       privacy = "off";
09977       screen = "yes";
09978       break;
09979    case AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED:
09980       privacy = "full";
09981       screen = "no";
09982       break;
09983    case AST_PRES_PROHIB_USER_NUMBER_PASSED_SCREEN:
09984       privacy = "full";
09985       screen = "yes";
09986       break;
09987    case AST_PRES_PROHIB_USER_NUMBER_FAILED_SCREEN:
09988       privacy = "full";
09989       screen = "no";
09990       break;
09991    case AST_PRES_PROHIB_NETWORK_NUMBER:
09992       privacy = "full";
09993       screen = "yes";
09994       break;
09995    case AST_PRES_NUMBER_NOT_AVAILABLE:
09996       send_pres_tags = FALSE;
09997       break;
09998    default:
09999       ast_log(LOG_WARNING, "Unsupported callingpres (%d)\n", p->callingpres);
10000       if ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)
10001          privacy = "full";
10002       else
10003          privacy = "off";
10004       screen = "no";
10005       break;
10006    }
10007    
10008    fromdomain = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10009 
10010    snprintf(buf, sizeof(buf), "\"%s\" <sip:%s@%s>", clin, clid, fromdomain);
10011    if (send_pres_tags)
10012       snprintf(buf + strlen(buf), sizeof(buf) - strlen(buf), ";privacy=%s;screen=%s", privacy, screen);
10013    ast_string_field_set(p, rpid, buf);
10014 
10015    ast_string_field_build(p, rpid_from, "\"%s\" <sip:%s@%s>;tag=%s", clin,
10016                 S_OR(p->fromuser, clid),
10017                 fromdomain, p->tag);
10018 }
10019 
10020 /*! \brief Initiate new SIP request to peer/user */
10021 static void initreqprep(struct sip_request *req, struct sip_pvt *p, int sipmethod)
10022 {
10023    struct ast_str *invite = ast_str_alloca(256);
10024    char from[256];
10025    char to[256];
10026    char tmp_n[SIPBUFSIZE/2];  /* build a local copy of 'n' if needed */
10027    char tmp_l[SIPBUFSIZE/2];  /* build a local copy of 'l' if needed */
10028    const char *l = NULL;   /* XXX what is this, exactly ? */
10029    const char *n = NULL;   /* XXX what is this, exactly ? */
10030    const char *d = NULL;   /* domain in from header */
10031    const char *urioptions = "";
10032    int ourport;
10033 
10034    if (ast_test_flag(&p->flags[0], SIP_USEREQPHONE)) {
10035       const char *s = p->username;  /* being a string field, cannot be NULL */
10036 
10037       /* Test p->username against allowed characters in AST_DIGIT_ANY
10038          If it matches the allowed characters list, then sipuser = ";user=phone"
10039          If not, then sipuser = ""
10040       */
10041       /* + is allowed in first position in a tel: uri */
10042       if (*s == '+')
10043          s++;
10044       for (; *s; s++) {
10045          if (!strchr(AST_DIGIT_ANYNUM, *s) )
10046             break;
10047       }
10048       /* If we have only digits, add ;user=phone to the uri */
10049       if (!*s)
10050          urioptions = ";user=phone";
10051    }
10052 
10053 
10054    snprintf(p->lastmsg, sizeof(p->lastmsg), "Init: %s", sip_methods[sipmethod].text);
10055 
10056    d = S_OR(p->fromdomain, ast_inet_ntoa(p->ourip.sin_addr));
10057    if (p->owner) {
10058       l = p->owner->cid.cid_num;
10059       n = p->owner->cid.cid_name;
10060    }
10061    /* if we are not sending RPID and user wants his callerid restricted */
10062    if (!ast_test_flag(&p->flags[0], SIP_SENDRPID) &&
10063        ((p->callingpres & AST_PRES_RESTRICTION) != AST_PRES_ALLOWED)) {
10064       l = CALLERID_UNKNOWN;
10065       n = l;
10066       d = FROMDOMAIN_INVALID;
10067    }
10068    if (ast_strlen_zero(l))
10069       l = default_callerid;
10070    if (ast_strlen_zero(n))
10071       n = l;
10072    /* Allow user to be overridden */
10073    if (!ast_strlen_zero(p->fromuser))
10074       l = p->fromuser;
10075    else /* Save for any further attempts */
10076       ast_string_field_set(p, fromuser, l);
10077 
10078    /* Allow user to be overridden */
10079    if (!ast_strlen_zero(p->fromname))
10080       n = p->fromname;
10081    else /* Save for any further attempts */
10082       ast_string_field_set(p, fromname, n);
10083 
10084    if (pedanticsipchecking) {
10085       ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10086       n = tmp_n;
10087       ast_uri_encode(l, tmp_l, sizeof(tmp_l), 0);
10088       l = tmp_l;
10089    }
10090 
10091    ourport = ntohs(p->ourip.sin_port);
10092    if (!sip_standard_port(p->socket.type, ourport) && ast_strlen_zero(p->fromdomain))
10093       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s:%d>;tag=%s", n, l, d, ourport, p->tag);
10094    else
10095       snprintf(from, sizeof(from), "\"%s\" <sip:%s@%s>;tag=%s", n, l, d, p->tag);
10096 
10097    /* If we're calling a registered SIP peer, use the fullcontact to dial to the peer */
10098    if (!ast_strlen_zero(p->fullcontact)) {
10099       /* If we have full contact, trust it */
10100       ast_str_append(&invite, 0, "%s", p->fullcontact);
10101    } else {
10102       /* Otherwise, use the username while waiting for registration */
10103       ast_str_append(&invite, 0, "sip:");
10104       if (!ast_strlen_zero(p->username)) {
10105          n = p->username;
10106          if (pedanticsipchecking) {
10107             ast_uri_encode(n, tmp_n, sizeof(tmp_n), 0);
10108             n = tmp_n;
10109          }
10110          ast_str_append(&invite, 0, "%s@", n);
10111       }
10112       ast_str_append(&invite, 0, "%s", p->tohost);
10113       if (p->portinuri)
10114          ast_str_append(&invite, 0, ":%d", ntohs(p->sa.sin_port));
10115       ast_str_append(&invite, 0, "%s", urioptions);
10116    }
10117 
10118    /* If custom URI options have been provided, append them */
10119    if (p->options && !ast_strlen_zero(p->options->uri_options))
10120       ast_str_append(&invite, 0, ";%s", p->options->uri_options);
10121    
10122    /* This is the request URI, which is the next hop of the call
10123       which may or may not be the destination of the call
10124    */
10125    ast_string_field_set(p, uri, invite->str);
10126   
10127    if (!ast_strlen_zero(p->todnid)) {
10128       /*! \todo Need to add back the VXML URL here at some point, possibly use build_string for all this junk */
10129       if (!strchr(p->todnid, '@')) {
10130          /* We have no domain in the dnid */
10131          snprintf(to, sizeof(to), "<sip:%s@%s>%s%s", p->todnid, p->tohost, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10132       } else {
10133          snprintf(to, sizeof(to), "<sip:%s>%s%s", p->todnid, ast_strlen_zero(p->theirtag) ? "" : ";tag=", p->theirtag);
10134       }
10135    } else {
10136       if (sipmethod == SIP_NOTIFY && !ast_strlen_zero(p->theirtag)) { 
10137          /* If this is a NOTIFY, use the From: tag in the subscribe (RFC 3265) */
10138          snprintf(to, sizeof(to), "<%s%s>;tag=%s", (!strncasecmp(p->uri, "sip:", 4) ? "sip:" : ""), p->uri, p->theirtag);
10139       } else if (p->options && p->options->vxml_url) {
10140          /* If there is a VXML URL append it to the SIP URL */
10141          snprintf(to, sizeof(to), "<%s>;%s", p->uri, p->options->vxml_url);
10142       } else 
10143          snprintf(to, sizeof(to), "<%s>", p->uri);
10144    }
10145 
10146    init_req(req, sipmethod, p->uri);
10147    /* now tmp_n is available so reuse it to build the CSeq */
10148    snprintf(tmp_n, sizeof(tmp_n), "%d %s", ++p->ocseq, sip_methods[sipmethod].text);
10149 
10150    add_header(req, "Via", p->via);
10151    add_header(req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10152    /* This will be a no-op most of the time. However, under certain circumstances,
10153     * NOTIFY messages will use this function for preparing the request and should
10154     * have Route headers present.
10155     */
10156    add_route(req, p->route);
10157 
10158    /* Build Remote Party-ID and From */
10159    if (ast_test_flag(&p->flags[0], SIP_SENDRPID) && (sipmethod == SIP_INVITE)) {
10160       build_rpid(p);
10161       add_header(req, "From", p->rpid_from);
10162    } else 
10163       add_header(req, "From", from);
10164    add_header(req, "To", to);
10165    ast_string_field_set(p, exten, l);
10166    build_contact(p);
10167    add_header(req, "Contact", p->our_contact);
10168    add_header(req, "Call-ID", p->callid);
10169    add_header(req, "CSeq", tmp_n);
10170    if (!ast_strlen_zero(global_useragent))
10171       add_header(req, "User-Agent", global_useragent);
10172    if (!ast_strlen_zero(p->rpid))
10173       add_header(req, "Remote-Party-ID", p->rpid);
10174 }
10175 
10176 /*! \brief Build REFER/INVITE/OPTIONS message and transmit it 
10177    \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
10178  \param p sip_pvt structure
10179  \param sdp unknown 
10180  \param sipmethod unknown 
10181  
10182 */
10183 static int transmit_invite(struct sip_pvt *p, int sipmethod, int sdp, int init)
10184 {
10185    struct sip_request req;
10186    struct ast_variable *var;
10187    
10188    req.method = sipmethod;
10189    if (init) {/* Bump branch even on initial requests */
10190       p->branch ^= ast_random();
10191       p->invite_branch = p->branch;
10192       build_via(p);
10193    }
10194    if (init > 1)
10195       initreqprep(&req, p, sipmethod);
10196    else
10197       /* If init=1, we should not generate a new branch. If it's 0, we need a new branch. */
10198       reqprep(&req, p, sipmethod, 0, init ? 0 : 1);
10199       
10200    if (p->options && p->options->auth)
10201       add_header(&req, p->options->authheader, p->options->auth);
10202    append_date(&req);
10203    if (sipmethod == SIP_REFER) { /* Call transfer */
10204       if (p->refer) {
10205          char buf[SIPBUFSIZE];
10206          if (!ast_strlen_zero(p->refer->refer_to))
10207             add_header(&req, "Refer-To", p->refer->refer_to);
10208          if (!ast_strlen_zero(p->refer->referred_by)) {
10209             snprintf(buf, sizeof(buf), "%s <%s>", p->refer->referred_by_name, p->refer->referred_by);
10210             add_header(&req, "Referred-By", buf);
10211          }
10212       }
10213    }
10214    /* This new INVITE is part of an attended transfer. Make sure that the
10215    other end knows and replace the current call with this new call */
10216    if (p->options && !ast_strlen_zero(p->options->replaces)) {
10217       add_header(&req, "Replaces", p->options->replaces);
10218       add_header(&req, "Require", "replaces");
10219    }
10220 
10221    /* Add Session-Timers related headers */
10222    if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
10223       char i2astr[10];
10224 
10225       if (!p->stimer->st_interval)
10226          p->stimer->st_interval = st_get_se(p, TRUE);
10227 
10228       p->stimer->st_active = TRUE;
10229       
10230       snprintf(i2astr, sizeof(i2astr), "%d", p->stimer->st_interval);
10231       add_header(&req, "Session-Expires", i2astr);
10232       snprintf(i2astr, sizeof(i2astr), "%d", st_get_se(p, FALSE));
10233       add_header(&req, "Min-SE", i2astr);
10234    }
10235 
10236    add_header(&req, "Allow", ALLOWED_METHODS);
10237    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10238 
10239    if(p->notify_headers) {
10240       char buf[512];
10241       for (var = p->notify_headers; var; var = var->next) {
10242          ast_copy_string(buf, var->value, sizeof(buf));
10243          add_header(&req, var->name, ast_unescape_semicolon(buf));
10244       }
10245    }
10246    if (p->options && p->options->addsipheaders && p->owner) {
10247       struct ast_channel *chan = p->owner; /* The owner channel */
10248       struct varshead *headp;
10249    
10250       ast_channel_lock(chan);
10251 
10252       headp = &chan->varshead;
10253 
10254       if (!headp)
10255          ast_log(LOG_WARNING, "No Headp for the channel...ooops!\n");
10256       else {
10257          const struct ast_var_t *current;
10258          AST_LIST_TRAVERSE(headp, current, entries) {  
10259             /* SIPADDHEADER: Add SIP header to outgoing call */
10260             if (!strncasecmp(ast_var_name(current), "SIPADDHEADER", strlen("SIPADDHEADER"))) {
10261                char *content, *end;
10262                const char *header = ast_var_value(current);
10263                char *headdup = ast_strdupa(header);
10264 
10265                /* Strip of the starting " (if it's there) */
10266                if (*headdup == '"')
10267                   headdup++;
10268                if ((content = strchr(headdup, ':'))) {
10269                   *content++ = '\0';
10270                   content = ast_skip_blanks(content); /* Skip white space */
10271                   /* Strip the ending " (if it's there) */
10272                   end = content + strlen(content) -1; 
10273                   if (*end == '"')
10274                      *end = '\0';
10275                
10276                   add_header(&req, headdup, content);
10277                   if (sipdebug)
10278                      ast_debug(1, "Adding SIP Header \"%s\" with content :%s: \n", headdup, content);
10279                }
10280             }
10281          }
10282       }
10283 
10284       ast_channel_unlock(chan);
10285    }
10286    if (sdp) {
10287       memset(p->offered_media, 0, sizeof(p->offered_media));
10288       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
10289          ast_debug(1, "T38 is in state %d on channel %s\n", p->t38.state, p->owner ? p->owner->name : "<none>");
10290          add_sdp(&req, p, FALSE, FALSE, TRUE);
10291       } else if (p->rtp) 
10292          add_sdp(&req, p, FALSE, TRUE, FALSE);
10293    } else {
10294       if (!p->notify_headers) {
10295          add_header_contentLength(&req, 0);
10296       }
10297    }
10298 
10299    if (!p->initreq.headers || init > 2)
10300       initialize_initreq(p, &req);
10301    p->lastinvite = p->ocseq;
10302    return send_request(p, &req, init ? XMIT_CRITICAL : XMIT_RELIABLE, p->ocseq);
10303 }
10304 
10305 /*! \brief Used in the SUBSCRIBE notification subsystem (RFC3265) */
10306 static int transmit_state_notify(struct sip_pvt *p, int state, int full, int timeout)
10307 {
10308    struct ast_str *tmp = ast_str_alloca(4000);
10309    char from[256], to[256];
10310    char *c, *mfrom, *mto;
10311    struct sip_request req;
10312    char hint[AST_MAX_EXTENSION];
10313    char *statestring = "terminated";
10314    const struct cfsubscription_types *subscriptiontype;
10315    enum state { NOTIFY_OPEN, NOTIFY_INUSE, NOTIFY_CLOSED } local_state = NOTIFY_OPEN;
10316    char *pidfstate = "--";
10317    char *pidfnote= "Ready";
10318    
10319    memset(from, 0, sizeof(from));
10320    memset(to, 0, sizeof(to));
10321 
10322    switch (state) {
10323    case (AST_EXTENSION_RINGING | AST_EXTENSION_INUSE):
10324       statestring = (global_notifyringing) ? "early" : "confirmed";
10325       local_state = NOTIFY_INUSE;
10326       pidfstate = "busy";
10327       pidfnote = "Ringing";
10328       break;
10329    case AST_EXTENSION_RINGING:
10330       statestring = "early";
10331       local_state = NOTIFY_INUSE;
10332       pidfstate = "busy";
10333       pidfnote = "Ringing";
10334       break;
10335    case AST_EXTENSION_INUSE:
10336       statestring = "confirmed";
10337       local_state = NOTIFY_INUSE;
10338       pidfstate = "busy";
10339       pidfnote = "On the phone";
10340       break;
10341    case AST_EXTENSION_BUSY:
10342       statestring = "confirmed";
10343       local_state = NOTIFY_CLOSED;
10344       pidfstate = "busy";
10345       pidfnote = "On the phone";
10346       break;
10347    case AST_EXTENSION_UNAVAILABLE:
10348       statestring = "terminated";
10349       local_state = NOTIFY_CLOSED;
10350       pidfstate = "away";
10351       pidfnote = "Unavailable";
10352       break;
10353    case AST_EXTENSION_ONHOLD:
10354       statestring = "confirmed";
10355       local_state = NOTIFY_CLOSED;
10356       pidfstate = "busy";
10357       pidfnote = "On hold";
10358       break;
10359    case AST_EXTENSION_NOT_INUSE:
10360    default:
10361       /* Default setting */
10362       break;
10363    }
10364 
10365    subscriptiontype = find_subscription_type(p->subscribed);
10366    
10367    /* Check which device/devices we are watching  and if they are registered */
10368    if (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten)) {
10369       char *hint2 = hint, *individual_hint = NULL;
10370       int hint_count = 0, unavailable_count = 0;
10371 
10372       while ((individual_hint = strsep(&hint2, "&"))) {
10373          hint_count++;
10374 
10375          if (ast_device_state(individual_hint) == AST_DEVICE_UNAVAILABLE)
10376             unavailable_count++;
10377       }
10378 
10379       /* If none of the hinted devices are registered, we will
10380        * override notification and show no availability.
10381        */
10382       if (hint_count > 0 && hint_count == unavailable_count) {
10383          local_state = NOTIFY_CLOSED;
10384          pidfstate = "away";
10385          pidfnote = "Not online";
10386       }
10387    }
10388 
10389    ast_copy_string(from, get_header(&p->initreq, "From"), sizeof(from));
10390    c = get_in_brackets(from);
10391    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
10392       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
10393       return -1;
10394    }
10395    
10396    mfrom = remove_uri_parameters(c);
10397 
10398    ast_copy_string(to, get_header(&p->initreq, "To"), sizeof(to));
10399    c = get_in_brackets(to);
10400    if (strncasecmp(c, "sip:", 4) && strncasecmp(c, "sips:", 5)) {
10401       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", c);
10402       return -1;
10403    }
10404    mto = remove_uri_parameters(c);
10405 
10406    reqprep(&req, p, SIP_NOTIFY, 0, 1);
10407 
10408    
10409    add_header(&req, "Event", subscriptiontype->event);
10410    add_header(&req, "Content-Type", subscriptiontype->mediatype);
10411    switch(state) {
10412    case AST_EXTENSION_DEACTIVATED:
10413       if (timeout)
10414          add_header(&req, "Subscription-State", "terminated;reason=timeout");
10415       else {
10416          add_header(&req, "Subscription-State", "terminated;reason=probation");
10417          add_header(&req, "Retry-After", "60");
10418       }
10419       break;
10420    case AST_EXTENSION_REMOVED:
10421       add_header(&req, "Subscription-State", "terminated;reason=noresource");
10422       break;
10423    default:
10424       if (p->expiry)
10425          add_header(&req, "Subscription-State", "active");
10426       else  /* Expired */
10427          add_header(&req, "Subscription-State", "terminated;reason=timeout");
10428    }
10429    switch (p->subscribed) {
10430    case XPIDF_XML:
10431    case CPIM_PIDF_XML:
10432       ast_str_append(&tmp, 0,
10433          "<?xml version=\"1.0\"?>\n"
10434          "<!DOCTYPE presence PUBLIC \"-//IETF//DTD RFCxxxx XPIDF 1.0//EN\" \"xpidf.dtd\">\n"
10435          "<presence>\n");
10436       ast_str_append(&tmp, 0, "<presentity uri=\"%s;method=SUBSCRIBE\" />\n", mfrom);
10437       ast_str_append(&tmp, 0, "<atom id=\"%s\">\n", p->exten);
10438       ast_str_append(&tmp, 0, "<address uri=\"%s;user=ip\" priority=\"0.800000\">\n", mto);
10439       ast_str_append(&tmp, 0, "<status status=\"%s\" />\n", (local_state ==  NOTIFY_OPEN) ? "open" : (local_state == NOTIFY_INUSE) ? "inuse" : "closed");
10440       ast_str_append(&tmp, 0, "<msnsubstatus substatus=\"%s\" />\n", (local_state == NOTIFY_OPEN) ? "online" : (local_state == NOTIFY_INUSE) ? "onthephone" : "offline");
10441       ast_str_append(&tmp, 0, "</address>\n</atom>\n</presence>\n");
10442       break;
10443    case PIDF_XML: /* Eyebeam supports this format */
10444       ast_str_append(&tmp, 0,
10445          "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"
10446          "<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);
10447       ast_str_append(&tmp, 0, "<pp:person><status>\n");
10448       if (pidfstate[0] != '-')
10449          ast_str_append(&tmp, 0, "<ep:activities><ep:%s/></ep:activities>\n", pidfstate);
10450       ast_str_append(&tmp, 0, "</status></pp:person>\n");
10451       ast_str_append(&tmp, 0, "<note>%s</note>\n", pidfnote); /* Note */
10452       ast_str_append(&tmp, 0, "<tuple id=\"%s\">\n", p->exten); /* Tuple start */
10453       ast_str_append(&tmp, 0, "<contact priority=\"1\">%s</contact>\n", mto);
10454       if (pidfstate[0] == 'b') /* Busy? Still open ... */
10455          ast_str_append(&tmp, 0, "<status><basic>open</basic></status>\n");
10456       else
10457          ast_str_append(&tmp, 0, "<status><basic>%s</basic></status>\n", (local_state != NOTIFY_CLOSED) ? "open" : "closed");
10458       ast_str_append(&tmp, 0, "</tuple>\n</presence>\n");
10459       break;
10460    case DIALOG_INFO_XML: /* SNOM subscribes in this format */
10461       ast_str_append(&tmp, 0, "<?xml version=\"1.0\"?>\n");
10462       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);
10463       if ((state & AST_EXTENSION_RINGING) && global_notifyringing)
10464          ast_str_append(&tmp, 0, "<dialog id=\"%s\" direction=\"recipient\">\n", p->exten);
10465       else
10466          ast_str_append(&tmp, 0, "<dialog id=\"%s\">\n", p->exten);
10467       ast_str_append(&tmp, 0, "<state>%s</state>\n", statestring);
10468       if (state == AST_EXTENSION_ONHOLD) {
10469          ast_str_append(&tmp, 0, "<local>\n<target uri=\"%s\">\n"
10470                                          "<param pname=\"+sip.rendering\" pvalue=\"no\"/>\n"
10471                                          "</target>\n</local>\n", mto);
10472       }
10473       ast_str_append(&tmp, 0, "</dialog>\n</dialog-info>\n");
10474       break;
10475    case NONE:
10476    default:
10477       break;
10478    }
10479 
10480    add_header_contentLength(&req, tmp->used);
10481    add_line(&req, tmp->str);
10482 
10483    p->pendinginvite = p->ocseq;  /* Remember that we have a pending NOTIFY in order not to confuse the NOTIFY subsystem */
10484 
10485    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10486 }
10487 
10488 /*! \brief Notify user of messages waiting in voicemail (RFC3842)
10489 \note - Notification only works for registered peers with mailbox= definitions
10490    in sip.conf
10491    - We use the SIP Event package message-summary
10492     MIME type defaults to  "application/simple-message-summary";
10493  */
10494 static int transmit_notify_with_mwi(struct sip_pvt *p, int newmsgs, int oldmsgs, char *vmexten)
10495 {
10496    struct sip_request req;
10497    struct ast_str *out = ast_str_alloca(500);
10498    int ourport = ntohs(p->ourip.sin_port);
10499    const char *exten = S_OR(vmexten, default_vmexten);
10500 
10501    initreqprep(&req, p, SIP_NOTIFY);
10502    add_header(&req, "Event", "message-summary");
10503    add_header(&req, "Content-Type", default_notifymime);
10504    ast_str_append(&out, 0, "Messages-Waiting: %s\r\n", newmsgs ? "yes" : "no");
10505 
10506    if (!ast_strlen_zero(p->fromdomain)) {
10507       ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, p->fromdomain);
10508    } else if (!sip_standard_port(p->socket.type, ourport)) {
10509       if (p->socket.type == SIP_TRANSPORT_UDP) {
10510          ast_str_append(&out, 0, "Message-Account: sip:%s@%s:%d\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr), ourport);
10511       } else {
10512          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));
10513       }
10514    } else {
10515       if (p->socket.type == SIP_TRANSPORT_UDP) {
10516          ast_str_append(&out, 0, "Message-Account: sip:%s@%s\r\n", exten, ast_inet_ntoa(p->ourip.sin_addr));
10517       } else {
10518          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));
10519       }
10520    }
10521    /* Cisco has a bug in the SIP stack where it can't accept the
10522       (0/0) notification. This can temporarily be disabled in
10523       sip.conf with the "buggymwi" option */
10524    ast_str_append(&out, 0, "Voice-Message: %d/%d%s\r\n",
10525       newmsgs, oldmsgs, (ast_test_flag(&p->flags[1], SIP_PAGE2_BUGGY_MWI) ? "" : " (0/0)"));
10526 
10527    if (p->subscribed) {
10528       if (p->expiry)
10529          add_header(&req, "Subscription-State", "active");
10530       else  /* Expired */
10531          add_header(&req, "Subscription-State", "terminated;reason=timeout");
10532    }
10533 
10534    add_header_contentLength(&req, out->used);
10535    add_line(&req, out->str);
10536 
10537    if (!p->initreq.headers) 
10538       initialize_initreq(p, &req);
10539    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10540 }
10541 
10542 /*! \brief Notify a transferring party of the status of transfer (RFC3515) */
10543 static int transmit_notify_with_sipfrag(struct sip_pvt *p, int cseq, char *message, int terminate)
10544 {
10545    struct sip_request req;
10546    char tmp[SIPBUFSIZE/2];
10547    
10548    reqprep(&req, p, SIP_NOTIFY, 0, 1);
10549    snprintf(tmp, sizeof(tmp), "refer;id=%d", cseq);
10550    add_header(&req, "Event", tmp);
10551    add_header(&req, "Subscription-state", terminate ? "terminated;reason=noresource" : "active");
10552    add_header(&req, "Content-Type", "message/sipfrag;version=2.0");
10553    add_header(&req, "Allow", ALLOWED_METHODS);
10554    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
10555 
10556    snprintf(tmp, sizeof(tmp), "SIP/2.0 %s\r\n", message);
10557    add_header_contentLength(&req, strlen(tmp));
10558    add_line(&req, tmp);
10559 
10560    if (!p->initreq.headers)
10561       initialize_initreq(p, &req);
10562 
10563    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
10564 }
10565 
10566 /*! \brief Notify device with custom headers from sip_notify.conf */
10567 static int transmit_notify_custom(struct sip_pvt *p, struct ast_variable *vars) {
10568    struct sip_request req;
10569    struct ast_variable *var, *newvar;
10570 
10571    initreqprep(&req, p, SIP_NOTIFY);
10572 
10573    /* Copy notify vars and add headers */
10574    p->notify_headers = newvar = ast_variable_new("Subscription-State", "terminated", "");
10575    add_header(&req, newvar->name, newvar->value);
10576    for (var = vars; var; var = var->next) {
10577       char buf[512];
10578       ast_debug(2, "  Adding pair %s=%s\n", var->name, var->value);
10579       ast_copy_string(buf, var->value, sizeof(buf));
10580       add_header(&req, var->name, ast_unescape_semicolon(buf));
10581       newvar->next = ast_variable_new(var->name, var->value, "");
10582       newvar = newvar->next;
10583    }
10584 
10585    if (!p->initreq.headers) { /* Initialize first request before sending */
10586       initialize_initreq(p, &req);
10587    }
10588 
10589    return send_request(p, &req, XMIT_UNRELIABLE, p->ocseq);
10590 }
10591 
10592 static int manager_sipnotify(struct mansession *s, const struct message *m)
10593 {
10594    const char *channame = astman_get_header(m, "Channel");
10595    struct ast_variable *vars = astman_get_variables(m);
10596    struct sip_pvt *p;
10597 
10598    if (ast_strlen_zero(channame)) {
10599       astman_send_error(s, m, "SIPNotify requires a channel name");
10600       return 0;
10601    }
10602 
10603    if (!strncasecmp(channame, "sip/", 4)) {
10604       channame += 4;
10605    }
10606 
10607    if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
10608       astman_send_error(s, m, "Unable to build sip pvt data for notify (memory/socket error)");
10609       return 0;
10610    }
10611 
10612    if (create_addr(p, channame, NULL, 0)) {
10613       /* Maybe they're not registered, etc. */
10614       dialog_unlink_all(p, TRUE, TRUE);
10615       dialog_unref(p, "unref dialog inside for loop" );
10616       /* sip_destroy(p); */
10617       astman_send_error(s, m, "Could not create address");
10618       return 0;
10619    }
10620 
10621    /* Notify is outgoing call */
10622    ast_set_flag(&p->flags[0], SIP_OUTGOING);
10623 
10624    /* Recalculate our side, and recalculate Call ID */
10625    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10626    build_via(p);
10627    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
10628    build_callid_pvt(p);
10629    ao2_t_link(dialogs, p, "Linking in new name");
10630    dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
10631    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
10632 
10633    if (!transmit_notify_custom(p, vars)) {
10634       astman_send_ack(s, m, "Notify Sent");
10635    } else {
10636       astman_send_error(s, m, "Unable to send notify");
10637    }
10638    ast_variables_destroy(vars);
10639    return 0;
10640 }
10641 
10642 static char mandescr_sipnotify[] =
10643 "Description: Sends a SIP Notify event\n"
10644 "All parameters for this event must be specified in the body of this request\n"
10645 "via multiple Variable: name=value sequences.\n"
10646 "Variables: \n"
10647 "  *Channel: <peername>       Peer to receive the notify. Required.\n"
10648 "  *Variable: <name>=<value>  At least one variable pair must be specified.\n"
10649 "  ActionID: <id>             Action ID for this transaction. Will be returned.\n";
10650 
10651 static const struct _map_x_s regstatestrings[] = {
10652    { REG_STATE_FAILED,     "Failed" },
10653    { REG_STATE_UNREGISTERED, "Unregistered"},
10654    { REG_STATE_REGSENT, "Request Sent"},
10655    { REG_STATE_AUTHSENT, "Auth. Sent"},
10656    { REG_STATE_REGISTERED, "Registered"},
10657    { REG_STATE_REJECTED, "Rejected"},
10658    { REG_STATE_TIMEOUT, "Timeout"},
10659    { REG_STATE_NOAUTH, "No Authentication"},
10660    { -1, NULL } /* terminator */
10661 };
10662 
10663 /*! \brief Convert registration state status to string */
10664 static const char *regstate2str(enum sipregistrystate regstate)
10665 {
10666    return map_x_s(regstatestrings, regstate, "Unknown");
10667 }
10668 
10669 /*! \brief Update registration with SIP Proxy.
10670  * Called from the scheduler when the previous registration expires,
10671  * so we don't have to cancel the pending event.
10672  * We assume the reference so the sip_registry is valid, since it
10673  * is stored in the scheduled event anyways.
10674  */
10675 static int sip_reregister(const void *data) 
10676 {
10677    /* if we are here, we know that we need to reregister. */
10678    struct sip_registry *r= (struct sip_registry *) data;
10679 
10680    /* if we couldn't get a reference to the registry object, punt */
10681    if (!r)
10682       return 0;
10683 
10684    if (r->call && r->call->do_history)
10685       append_history(r->call, "RegistryRenew", "Account: %s@%s", r->username, r->hostname);
10686    /* Since registry's are only added/removed by the the monitor thread, this
10687       may be overkill to reference/dereference at all here */
10688    if (sipdebug)
10689       ast_log(LOG_NOTICE, "   -- Re-registration for  %s@%s\n", r->username, r->hostname);
10690 
10691    r->expire = -1;
10692    r->expiry = r->configured_expiry;
10693    __sip_do_register(r);
10694    registry_unref(r, "unref the re-register scheduled event");
10695    return 0;
10696 }
10697 
10698 /*! \brief Register with SIP proxy */
10699 static int __sip_do_register(struct sip_registry *r)
10700 {
10701    int res;
10702 
10703    res = transmit_register(r, SIP_REGISTER, NULL, NULL);
10704    return res;
10705 }
10706 
10707 /*! \brief Registration timeout, register again
10708  * Registered as a timeout handler during transmit_register(),
10709  * to retransmit the packet if a reply does not come back.
10710  * This is called by the scheduler so the event is not pending anymore when
10711  * we are called.
10712  */
10713 static int sip_reg_timeout(const void *data)
10714 {
10715 
10716    /* if we are here, our registration timed out, so we'll just do it over */
10717    struct sip_registry *r = (struct sip_registry *)data; /* the ref count should have been bumped when the sched item was added */
10718    struct sip_pvt *p;
10719    int res;
10720 
10721    /* if we couldn't get a reference to the registry object, punt */
10722    if (!r)
10723       return 0;
10724 
10725    if (r->dnsmgr) {
10726       /* If the registration has timed out, maybe the IP changed.  Force a refresh. */
10727       ast_dnsmgr_refresh(r->dnsmgr);
10728    }
10729 
10730    ast_log(LOG_NOTICE, "   -- Registration for '%s@%s' timed out, trying again (Attempt #%d)\n", r->username, r->hostname, r->regattempts); 
10731    /* If the initial tranmission failed, we may not have an existing dialog,
10732     * so it is possible that r->call == NULL.
10733     * Otherwise destroy it, as we have a timeout so we don't want it.
10734     */
10735    if (r->call) {
10736       /* Unlink us, destroy old call.  Locking is not relevant here because all this happens
10737          in the single SIP manager thread. */
10738       p = r->call;
10739       sip_pvt_lock(p);
10740       p->needdestroy = 1;
10741       /* Pretend to ACK anything just in case */
10742       __sip_pretend_ack(p);
10743       sip_pvt_unlock(p);
10744 
10745       /* decouple the two objects */
10746       /* p->registry == r, so r has 2 refs, and the unref won't take the object away */
10747       if (p->registry)
10748          p->registry = registry_unref(p->registry, "p->registry unreffed");
10749       r->call = dialog_unref(r->call, "unrefing r->call");
10750    }
10751    /* If we have a limit, stop registration and give up */
10752    r->timeout = -1;
10753    if (global_regattempts_max && r->regattempts > global_regattempts_max) {
10754       /* Ok, enough is enough. Don't try any more */
10755       /* We could add an external notification here... 
10756          steal it from app_voicemail :-) */
10757       ast_log(LOG_NOTICE, "   -- Giving up forever trying to register '%s@%s'\n", r->username, r->hostname);
10758       r->regstate = REG_STATE_FAILED;
10759    } else {
10760       r->regstate = REG_STATE_UNREGISTERED;
10761       res=transmit_register(r, SIP_REGISTER, NULL, NULL);
10762    }
10763    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));
10764    registry_unref(r, "unreffing registry_unref r");
10765    return 0;
10766 }
10767 
10768 /*! \brief Transmit register to SIP proxy or UA
10769  * auth = NULL on the initial registration (from sip_reregister())
10770  */
10771 static int transmit_register(struct sip_registry *r, int sipmethod, const char *auth, const char *authheader)
10772 {
10773    struct sip_request req;
10774    char from[256];
10775    char to[256];
10776    char tmp[80];
10777    char addr[80];
10778    struct sip_pvt *p;
10779    struct sip_peer *peer = NULL;
10780    int res;
10781    char *fromdomain;
10782 
10783    /* exit if we are already in process with this registrar ?*/
10784    if (r == NULL || ((auth == NULL) && (r->regstate == REG_STATE_REGSENT || r->regstate == REG_STATE_AUTHSENT))) {
10785       if (r) {
10786          ast_log(LOG_NOTICE, "Strange, trying to register %s@%s when registration already pending\n", r->username, r->hostname);
10787       }
10788       return 0;
10789    }
10790 
10791    if (r->dnsmgr == NULL) {
10792       char transport[MAXHOSTNAMELEN];
10793       peer = find_peer(r->hostname, NULL, TRUE, FINDPEERS, FALSE, 0);
10794       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(r->transport)); /* have to use static get_transport function */
10795       ast_dnsmgr_lookup(peer ? peer->tohost : r->hostname, &r->us, &r->dnsmgr, global_srvlookup ? transport : NULL);
10796       if (peer) {
10797          peer = unref_peer(peer, "removing peer ref for dnsmgr_lookup");
10798       }
10799    }
10800 
10801    if (r->call) { /* We have a registration */
10802       if (!auth) {
10803          ast_log(LOG_WARNING, "Already have a REGISTER going on to %s@%s?? \n", r->username, r->hostname);
10804          return 0;
10805       } else {
10806          p = dialog_ref(r->call, "getting a copy of the r->call dialog in transmit_register");
10807          make_our_tag(p->tag, sizeof(p->tag));  /* create a new local tag for every register attempt */
10808          ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
10809       }
10810    } else {
10811       /* Build callid for registration if we haven't registered before */
10812       if (!r->callid_valid) {
10813          build_callid_registry(r, internip.sin_addr, default_fromdomain);
10814          r->callid_valid = TRUE;
10815       }
10816       /* Allocate SIP dialog for registration */
10817       if (!(p = sip_alloc( r->callid, NULL, 0, SIP_REGISTER, NULL))) {
10818          ast_log(LOG_WARNING, "Unable to allocate registration transaction (memory or socket error)\n");
10819          return 0;
10820       }
10821       
10822       if (p->do_history)
10823          append_history(p, "RegistryInit", "Account: %s@%s", r->username, r->hostname);
10824 
10825       if (!ast_strlen_zero(r->peername)) {
10826          if (!(peer = find_peer(r->peername, NULL, 1, FINDPEERS, FALSE, 0))) {
10827             ast_log(LOG_WARNING, "Could not find peer %s in transmit_register\n", r->peername);
10828          } else {
10829             p->peerauth = peer->auth;
10830          }
10831       }
10832       ref_proxy(p, obproxy_get(p, peer)); /* it is ok to pass a NULL peer into obproxy_get() */
10833       if (peer) {
10834          unref_peer(peer, "transmit_registration: from find_peer operation");
10835       }
10836       /* Use port number specified if no SRV record was found */
10837       if (!r->us.sin_port && r->portno)
10838          r->us.sin_port = htons(r->portno);
10839 
10840       /* Find address to hostname */
10841       if (create_addr(p, r->hostname, &r->us, 0)) {
10842          /* we have what we hope is a temporary network error,
10843           * probably DNS.  We need to reschedule a registration try */
10844          dialog_unlink_all(p, TRUE, TRUE);
10845          p = dialog_unref(p, "unref dialog after unlink_all");
10846          if (r->timeout > -1) {
10847             AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10848                               registry_unref(_data, "del for REPLACE of registry ptr"), 
10849                               registry_unref(r, "object ptr dec when SCHED_REPLACE add failed"),
10850                               registry_addref(r,"add for REPLACE registry ptr"));
10851             ast_log(LOG_WARNING, "Still have a registration timeout for %s@%s (create_addr() error), %d\n", r->username, r->hostname, r->timeout);
10852          } else {
10853             r->timeout = ast_sched_add(sched, global_reg_timeout * 1000, sip_reg_timeout, registry_addref(r, "add for REPLACE registry ptr"));
10854             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);
10855          }
10856          r->regattempts++;
10857          return 0;
10858       }
10859 
10860       /* Copy back Call-ID in case create_addr changed it */
10861       ast_string_field_set(r, callid, p->callid);
10862       if (!r->dnsmgr && r->portno) {
10863          p->sa.sin_port = htons(r->portno);
10864          p->recv.sin_port = htons(r->portno);
10865       } else { /* Set registry port to the port set from the peer definition/srv or default */
10866          r->portno = ntohs(p->sa.sin_port);
10867       }
10868       ast_set_flag(&p->flags[0], SIP_OUTGOING); /* Registration is outgoing call */
10869       r->call = dialog_ref(p, "copying dialog into registry r->call");     /* Save pointer to SIP dialog */
10870       p->registry = registry_addref(r, "transmit_register: addref to p->registry in transmit_register"); /* Add pointer to registry in packet */
10871       if (!ast_strlen_zero(r->secret)) /* Secret (password) */
10872          ast_string_field_set(p, peersecret, r->secret);
10873       if (!ast_strlen_zero(r->md5secret))
10874          ast_string_field_set(p, peermd5secret, r->md5secret);
10875       /* User name in this realm  
10876       - if authuser is set, use that, otherwise use username */
10877       if (!ast_strlen_zero(r->authuser)) {   
10878          ast_string_field_set(p, peername, r->authuser);
10879          ast_string_field_set(p, authname, r->authuser);
10880       } else if (!ast_strlen_zero(r->username)) {
10881          ast_string_field_set(p, peername, r->username);
10882          ast_string_field_set(p, authname, r->username);
10883          ast_string_field_set(p, fromuser, r->username);
10884       }
10885       if (!ast_strlen_zero(r->username))
10886          ast_string_field_set(p, username, r->username);
10887       /* Save extension in packet */
10888       if (!ast_strlen_zero(r->callback))
10889          ast_string_field_set(p, exten, r->callback);
10890 
10891       /* Set transport and port so the correct contact is built */
10892       set_socket_transport(&p->socket, r->transport);
10893       if (r->transport == SIP_TRANSPORT_TLS || r->transport == SIP_TRANSPORT_TCP) {
10894          p->socket.port = sip_tcp_desc.local_address.sin_port;
10895       }
10896 
10897       /*
10898         check which address we should use in our contact header 
10899         based on whether the remote host is on the external or
10900         internal network so we can register through nat
10901        */
10902       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
10903       build_contact(p);
10904    }
10905 
10906    /* set up a timeout */
10907    if (auth == NULL)  {
10908       if (r->timeout > -1)
10909          ast_log(LOG_WARNING, "Still have a registration timeout, #%d - deleting it\n", r->timeout);
10910       AST_SCHED_REPLACE_UNREF(r->timeout, sched, global_reg_timeout * 1000, sip_reg_timeout, r,
10911                         registry_unref(_data,"reg ptr unrefed from del in SCHED_REPLACE"),
10912                         registry_unref(r,"reg ptr unrefed from add failure in SCHED_REPLACE"),
10913                         registry_addref(r,"reg ptr reffed from add in SCHED_REPLACE"));
10914       ast_debug(1, "Scheduled a registration timeout for %s id  #%d \n", r->hostname, r->timeout);
10915    }
10916 
10917    if ((fromdomain = strchr(r->username, '@'))) {
10918       /* the domain name is just behind '@' */
10919       fromdomain++ ;
10920       /* We have a domain in the username for registration */
10921       snprintf(from, sizeof(from), "<sip:%s>;tag=%s", r->username, p->tag);
10922       if (!ast_strlen_zero(p->theirtag))
10923          snprintf(to, sizeof(to), "<sip:%s>;tag=%s", r->username, p->theirtag);
10924       else
10925          snprintf(to, sizeof(to), "<sip:%s>", r->username);
10926 
10927       /* If the registration username contains '@', then the domain should be used as
10928          the equivalent of "fromdomain" for the registration */
10929       if (ast_strlen_zero(p->fromdomain)) {
10930          ast_string_field_set(p, fromdomain, fromdomain);
10931       }
10932    } else {
10933       snprintf(from, sizeof(from), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->tag);
10934       if (!ast_strlen_zero(p->theirtag))
10935          snprintf(to, sizeof(to), "<sip:%s@%s>;tag=%s", r->username, p->tohost, p->theirtag);
10936       else
10937          snprintf(to, sizeof(to), "<sip:%s@%s>", r->username, p->tohost);
10938    }
10939    
10940    /* Fromdomain is what we are registering to, regardless of actual
10941       host name from SRV */
10942    if (!ast_strlen_zero(p->fromdomain)) {
10943       if (r->portno && r->portno != STANDARD_SIP_PORT)
10944          snprintf(addr, sizeof(addr), "sip:%s:%d", p->fromdomain, r->portno);
10945       else
10946          snprintf(addr, sizeof(addr), "sip:%s", p->fromdomain);
10947    } else {
10948       if (r->portno && r->portno != STANDARD_SIP_PORT)
10949          snprintf(addr, sizeof(addr), "sip:%s:%d", r->hostname, r->portno);
10950       else
10951          snprintf(addr, sizeof(addr), "sip:%s", r->hostname);
10952    }
10953    ast_string_field_set(p, uri, addr);
10954 
10955    p->branch ^= ast_random();
10956 
10957    init_req(&req, sipmethod, addr);
10958 
10959    /* Add to CSEQ */
10960    snprintf(tmp, sizeof(tmp), "%u %s", ++r->ocseq, sip_methods[sipmethod].text);
10961    p->ocseq = r->ocseq;
10962 
10963    build_via(p);
10964    add_header(&req, "Via", p->via);
10965    add_header(&req, "Max-Forwards", DEFAULT_MAX_FORWARDS);
10966    add_header(&req, "From", from);
10967    add_header(&req, "To", to);
10968    add_header(&req, "Call-ID", p->callid);
10969    add_header(&req, "CSeq", tmp);
10970    if (!ast_strlen_zero(global_useragent))
10971       add_header(&req, "User-Agent", global_useragent);
10972 
10973    
10974    if (auth)   /* Add auth header */
10975       add_header(&req, authheader, auth);
10976    else if (!ast_strlen_zero(r->nonce)) {
10977       char digest[1024];
10978 
10979       /* We have auth data to reuse, build a digest header.
10980        * Note, this is not always useful because some parties do not
10981        * like nonces to be reused (for good reasons!) so they will
10982        * challenge us anyways.
10983        */
10984       if (sipdebug)
10985          ast_debug(1, "   >>> Re-using Auth data for %s@%s\n", r->username, r->hostname);
10986       ast_string_field_set(p, realm, r->realm);
10987       ast_string_field_set(p, nonce, r->nonce);
10988       ast_string_field_set(p, domain, r->domain);
10989       ast_string_field_set(p, opaque, r->opaque);
10990       ast_string_field_set(p, qop, r->qop);
10991       p->noncecount = ++r->noncecount;
10992 
10993       memset(digest, 0, sizeof(digest));
10994       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest)))
10995          add_header(&req, "Authorization", digest);
10996       else
10997          ast_log(LOG_NOTICE, "No authorization available for authentication of registration to %s@%s\n", r->username, r->hostname);
10998    
10999    }
11000 
11001    snprintf(tmp, sizeof(tmp), "%d", r->expiry);
11002    add_header(&req, "Expires", tmp);
11003    add_header(&req, "Contact", p->our_contact);
11004    add_header_contentLength(&req, 0);
11005 
11006    initialize_initreq(p, &req);
11007    if (sip_debug_test_pvt(p)) {
11008       ast_verbose("REGISTER %d headers, %d lines\n", p->initreq.headers, p->initreq.lines);
11009    }
11010    r->regstate = auth ? REG_STATE_AUTHSENT : REG_STATE_REGSENT;
11011    r->regattempts++; /* Another attempt */
11012    ast_debug(4, "REGISTER attempt %d to %s@%s\n", r->regattempts, r->username, r->hostname);
11013    res = send_request(p, &req, XMIT_CRITICAL, p->ocseq);
11014    dialog_unref(p, "p is finished here at the end of transmit_register");
11015    return res;
11016 }
11017 
11018 /*! \brief Transmit text with SIP MESSAGE method */
11019 static int transmit_message_with_text(struct sip_pvt *p, const char *text)
11020 {
11021    struct sip_request req;
11022    
11023    reqprep(&req, p, SIP_MESSAGE, 0, 1);
11024    add_text(&req, text);
11025    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11026 }
11027 
11028 /*! \brief Allocate SIP refer structure */
11029 static int sip_refer_allocate(struct sip_pvt *p)
11030 {
11031    p->refer = ast_calloc(1, sizeof(struct sip_refer)); 
11032    return p->refer ? 1 : 0;
11033 }
11034 
11035 /*! \brief Transmit SIP REFER message (initiated by the transfer() dialplan application
11036    \note this is currently broken as we have no way of telling the dialplan
11037    engine whether a transfer succeeds or fails.
11038    \todo Fix the transfer() dialplan function so that a transfer may fail
11039 */
11040 static int transmit_refer(struct sip_pvt *p, const char *dest)
11041 {
11042    struct sip_request req = { 
11043       .headers = 0,  
11044    };
11045    char from[256];
11046    const char *of;
11047    char *c;
11048    char referto[256];
11049    char *ttag, *ftag;
11050    char *theirtag = ast_strdupa(p->theirtag);
11051 
11052    if (sipdebug)
11053       ast_debug(1, "SIP transfer of %s to %s\n", p->callid, dest);
11054 
11055    /* Are we transfering an inbound or outbound call ? */
11056    if (ast_test_flag(&p->flags[0], SIP_OUTGOING))  {
11057       of = get_header(&p->initreq, "To");
11058       ttag = theirtag;
11059       ftag = p->tag;
11060    } else {
11061       of = get_header(&p->initreq, "From");
11062       ftag = theirtag;
11063       ttag = p->tag;
11064    }
11065 
11066    ast_copy_string(from, of, sizeof(from));
11067    of = get_in_brackets(from);
11068    ast_string_field_set(p, from, of);
11069    if (!strncasecmp(of, "sip:", 4))
11070       of += 4;
11071    else if (!strncasecmp(of, "sips:", 5))
11072       of += 5;
11073    else
11074       ast_log(LOG_NOTICE, "From address missing 'sip(s):', using it anyway\n");
11075    /* Get just the username part */
11076    if ((c = strchr(dest, '@')))
11077       c = NULL;
11078    else if ((c = strchr(of, '@')))
11079       *c++ = '\0';
11080    if (c) 
11081       snprintf(referto, sizeof(referto), "<sip:%s@%s>", dest, c);
11082    else
11083       snprintf(referto, sizeof(referto), "<sip:%s>", dest);
11084 
11085    /* save in case we get 407 challenge */
11086    sip_refer_allocate(p);
11087    ast_copy_string(p->refer->refer_to, referto, sizeof(p->refer->refer_to));
11088    ast_copy_string(p->refer->referred_by, p->our_contact, sizeof(p->refer->referred_by));
11089    p->refer->status = REFER_SENT;   /* Set refer status */
11090 
11091    reqprep(&req, p, SIP_REFER, 0, 1);
11092 
11093    add_header(&req, "Refer-To", referto);
11094    add_header(&req, "Allow", ALLOWED_METHODS);
11095    add_header(&req, "Supported", SUPPORTED_EXTENSIONS);
11096    if (!ast_strlen_zero(p->our_contact))
11097       add_header(&req, "Referred-By", p->our_contact);
11098 
11099    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11100 
11101    /* We should propably wait for a NOTIFY here until we ack the transfer */
11102    /* Maybe fork a new thread and wait for a STATUS of REFER_200OK on the refer status before returning to app_transfer */
11103 
11104    /*! \todo In theory, we should hang around and wait for a reply, before
11105    returning to the dial plan here. Don't know really how that would
11106    affect the transfer() app or the pbx, but, well, to make this
11107    useful we should have a STATUS code on transfer().
11108    */
11109 }
11110 
11111 
11112 /*! \brief Send SIP INFO dtmf message, see Cisco documentation on cisco.com */
11113 static int transmit_info_with_digit(struct sip_pvt *p, const char digit, unsigned int duration)
11114 {
11115    struct sip_request req;
11116    
11117    reqprep(&req, p, SIP_INFO, 0, 1);
11118    add_digit(&req, digit, duration, (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_SHORTINFO));
11119    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11120 }
11121 
11122 /*! \brief Send SIP INFO with video update request */
11123 static int transmit_info_with_vidupdate(struct sip_pvt *p)
11124 {
11125    struct sip_request req;
11126    
11127    reqprep(&req, p, SIP_INFO, 0, 1);
11128    add_vidupdate(&req);
11129    return send_request(p, &req, XMIT_RELIABLE, p->ocseq);
11130 }
11131 
11132 /*! \brief Transmit generic SIP request 
11133    returns XMIT_ERROR if transmit failed with a critical error (don't retry)
11134 */
11135 static int transmit_request(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11136 {
11137    struct sip_request resp;
11138    
11139    if (sipmethod == SIP_ACK)
11140       p->invitestate = INV_CONFIRMED;
11141 
11142    reqprep(&resp, p, sipmethod, seqno, newbranch);
11143    if (sipmethod == SIP_CANCEL && p->answered_elsewhere) 
11144       add_header(&resp, "Reason", "SIP;cause=200;text=\"Call completed elsewhere\"");
11145 
11146    add_header_contentLength(&resp, 0);
11147    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);
11148 }
11149 
11150 /*! \brief return the request and response heade for a 401 or 407 code */
11151 static void auth_headers(enum sip_auth_type code, char **header, char **respheader)
11152 {
11153    if (code == WWW_AUTH) {       /* 401 */
11154       *header = "WWW-Authenticate";
11155       *respheader = "Authorization";
11156    } else if (code == PROXY_AUTH) { /* 407 */
11157       *header = "Proxy-Authenticate";
11158       *respheader = "Proxy-Authorization";
11159    } else {
11160       ast_verbose("-- wrong response code %d\n", code);
11161       *header = *respheader = "Invalid";
11162    }
11163 }
11164 
11165 /*! \brief Transmit SIP request, auth added */
11166 static int transmit_request_with_auth(struct sip_pvt *p, int sipmethod, int seqno, enum xmittype reliable, int newbranch)
11167 {
11168    struct sip_request resp;
11169    
11170    reqprep(&resp, p, sipmethod, seqno, newbranch);
11171    if (!ast_strlen_zero(p->realm)) {
11172       char digest[1024];
11173 
11174       memset(digest, 0, sizeof(digest));
11175       if(!build_reply_digest(p, sipmethod, digest, sizeof(digest))) {
11176          char *dummy, *response;
11177          enum sip_auth_type code = p->options ? p->options->auth_type : PROXY_AUTH; /* XXX force 407 if unknown */
11178          auth_headers(code, &dummy, &response);
11179          add_header(&resp, response, digest);
11180       } else
11181          ast_log(LOG_WARNING, "No authentication available for call %s\n", p->callid);
11182    }
11183    /* If we are hanging up and know a cause for that, send it in clear text to make
11184       debugging easier. */
11185    if (sipmethod == SIP_BYE)  {
11186       char buf[10];
11187 
11188       add_header(&resp, "X-Asterisk-HangupCause", ast_cause2str(p->hangupcause));
11189       snprintf(buf, sizeof(buf), "%d", p->hangupcause);
11190       add_header(&resp, "X-Asterisk-HangupCauseCode", buf);
11191    }
11192 
11193    add_header_contentLength(&resp, 0);
11194    return send_request(p, &resp, reliable, seqno ? seqno : p->ocseq);   
11195 }
11196 
11197 /*! \brief Remove registration data from realtime database or AST/DB when registration expires */
11198 static void destroy_association(struct sip_peer *peer)
11199 {
11200    int realtimeregs = ast_check_realtime("sipregs");
11201    char *tablename = (realtimeregs) ? "sipregs" : "sippeers";
11202 
11203    if (!sip_cfg.ignore_regexpire) {
11204       if (peer->rt_fromcontact && sip_cfg.peer_rtupdate) {
11205          ast_update_realtime(tablename, "name", peer->name, "fullcontact", "", "ipaddr", "", "port", "", "regseconds", "0", peer->deprecated_username ? "username" : "defaultuser", "", "regserver", "", "useragent", "", "lastms", "", SENTINEL);
11206       } else {
11207          ast_db_del("SIP/Registry", peer->name);
11208       }
11209    }
11210 }
11211 
11212 static void set_socket_transport(struct sip_socket *socket, int transport)
11213 {
11214    /* if the transport type changes, clear all socket data */
11215    if (socket->type != transport) {
11216       socket->fd = -1;
11217       socket->type = transport;
11218       if (socket->tcptls_session) {
11219          ao2_ref(socket->tcptls_session, -1);
11220          socket->tcptls_session = NULL;
11221       }
11222    }
11223 }
11224 
11225 /*! \brief Expire registration of SIP peer */
11226 static int expire_register(const void *data)
11227 {
11228    struct sip_peer *peer = (struct sip_peer *)data;
11229 
11230    if (!peer)     /* Hmmm. We have no peer. Weird. */
11231       return 0;
11232 
11233    peer->expire = -1;
11234    peer->portinuri = 0;
11235    memset(&peer->addr, 0, sizeof(peer->addr));
11236 
11237    destroy_association(peer); /* remove registration data from storage */
11238    set_socket_transport(&peer->socket, peer->default_outbound_transport);
11239 
11240    if (peer->socket.tcptls_session) {
11241       ao2_ref(peer->socket.tcptls_session, -1);
11242       peer->socket.tcptls_session = NULL;
11243    }
11244 
11245    manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\nCause: Expired\r\n", peer->name);
11246    register_peer_exten(peer, FALSE);   /* Remove regexten */
11247    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11248 
11249    /* Do we need to release this peer from memory? 
11250       Only for realtime peers and autocreated peers
11251    */
11252    if (peer->is_realtime)
11253       ast_debug(3, "-REALTIME- peer expired registration. Name: %s. Realtime peer objects now %d\n", peer->name, rpeerobjs);
11254 
11255    if (peer->selfdestruct ||
11256        ast_test_flag(&peer->flags[1], SIP_PAGE2_RTAUTOCLEAR)) {
11257       ao2_t_unlink(peers, peer, "ao2_unlink of peer from peers table");
11258       if (peer->addr.sin_addr.s_addr) {
11259          ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
11260       }
11261    }
11262 
11263    unref_peer(peer, "removing peer ref for expire_register");
11264 
11265    return 0;
11266 }
11267 
11268 /*! \brief Poke peer (send qualify to check if peer is alive and well) */
11269 static int sip_poke_peer_s(const void *data)
11270 {
11271    struct sip_peer *peer = (struct sip_peer *)data;
11272 
11273    peer->pokeexpire = -1;
11274 
11275    sip_poke_peer(peer, 0);
11276 
11277    unref_peer(peer, "removing poke peer ref");
11278 
11279    return 0;
11280 }
11281 
11282 /*! \brief Get registration details from Asterisk DB */
11283 static void reg_source_db(struct sip_peer *peer)
11284 {
11285    char data[256];
11286    struct in_addr in;
11287    int expire;
11288    int port;
11289    char *scan, *addr, *port_str, *expiry_str, *username, *contact;
11290 
11291    if (peer->rt_fromcontact) 
11292       return;
11293    if (ast_db_get("SIP/Registry", peer->name, data, sizeof(data)))
11294       return;
11295 
11296    scan = data;
11297    addr = strsep(&scan, ":");
11298    port_str = strsep(&scan, ":");
11299    expiry_str = strsep(&scan, ":");
11300    username = strsep(&scan, ":");
11301    contact = scan;   /* Contact include sip: and has to be the last part of the database entry as long as we use : as a separator */
11302 
11303    if (!inet_aton(addr, &in))
11304       return;
11305 
11306    if (port_str)
11307       port = atoi(port_str);
11308    else
11309       return;
11310 
11311    if (expiry_str)
11312       expire = atoi(expiry_str);
11313    else
11314       return;
11315 
11316    if (username)
11317       ast_copy_string(peer->username, username, sizeof(peer->username));
11318    if (contact)
11319       ast_copy_string(peer->fullcontact, contact, sizeof(peer->fullcontact));
11320 
11321    ast_debug(2, "SIP Seeding peer from astdb: '%s' at %s@%s:%d for %d\n",
11322        peer->name, peer->username, ast_inet_ntoa(in), port, expire);
11323 
11324    memset(&peer->addr, 0, sizeof(peer->addr));
11325    peer->addr.sin_family = AF_INET;
11326    peer->addr.sin_addr = in;
11327    peer->addr.sin_port = htons(port);
11328    if (sipsock < 0) {
11329       /* SIP isn't up yet, so schedule a poke only, pretty soon */
11330       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ast_random() % 5000 + 1, sip_poke_peer_s, peer,
11331             unref_peer(_data, "removing poke peer ref"),
11332             unref_peer(peer, "removing poke peer ref"),
11333             ref_peer(peer, "adding poke peer ref"));
11334    } else {
11335       sip_poke_peer(peer, 0);
11336    }
11337    AST_SCHED_REPLACE_UNREF(peer->expire, sched, (expire + 10) * 1000, expire_register, peer,
11338          unref_peer(_data, "remove registration ref"),
11339          unref_peer(peer, "remove registration ref"),
11340          ref_peer(peer, "add registration ref"));
11341    register_peer_exten(peer, TRUE);
11342 }
11343 
11344 /*! \brief Save contact header for 200 OK on INVITE */
11345 static int parse_ok_contact(struct sip_pvt *pvt, struct sip_request *req)
11346 {
11347    char contact[SIPBUFSIZE]; 
11348    char *c;
11349 
11350    /* Look for brackets */
11351    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
11352    c = get_in_brackets(contact);
11353 
11354    /* Save full contact to call pvt for later bye or re-invite */
11355    ast_string_field_set(pvt, fullcontact, c);
11356 
11357    /* Save URI for later ACKs, BYE or RE-invites */
11358    ast_string_field_set(pvt, okcontacturi, c);
11359 
11360    /* We should return false for URI:s we can't handle,
11361       like tel:, mailto:,ldap: etc */
11362    return TRUE;      
11363 }
11364 
11365 static int __set_address_from_contact(const char *fullcontact, struct sockaddr_in *sin, int tcp)
11366 {
11367    struct hostent *hp;
11368    struct ast_hostent ahp;
11369    int port = STANDARD_SIP_PORT;
11370    char *host, *pt, *transport;
11371    char contact_buf[256];
11372    char *contact;
11373 
11374    /* Work on a copy */
11375    ast_copy_string(contact_buf, fullcontact, sizeof(contact_buf));
11376    contact = contact_buf;
11377 
11378    /* 
11379     * We have only the part in <brackets> here so we just need to parse a SIP URI.
11380     *
11381     * Note: The outbound proxy could be using UDP between the proxy and Asterisk.
11382     * We still need to be able to send to the remote agent through the proxy.
11383    */
11384 
11385    if (parse_uri(contact, "sip:,sips:", &contact, NULL, &host, &pt, NULL, &transport)) {
11386       ast_log(LOG_WARNING, "Invalid contact uri %s (missing sip: or sips:), attempting to use anyway\n", fullcontact);
11387    }
11388 
11389    /* set port */
11390    if (((get_transport_str2enum(transport) == SIP_TRANSPORT_TLS)) || !(strncasecmp(fullcontact, "sips", 4))) {
11391       port = port_str2int(pt, STANDARD_TLS_PORT);
11392    } else {
11393       port = port_str2int(pt, STANDARD_SIP_PORT);
11394    }
11395 
11396    /* XXX This could block for a long time XXX */
11397    /* We should only do this if it's a name, not an IP */
11398    hp = ast_gethostbyname(host, &ahp);
11399    if (!hp)  {
11400       ast_log(LOG_WARNING, "Invalid host name in Contact: (can't resolve in DNS) : '%s'\n", host);
11401       return -1;
11402    }
11403    sin->sin_family = AF_INET;
11404    memcpy(&sin->sin_addr, hp->h_addr, sizeof(sin->sin_addr));
11405    sin->sin_port = htons(port);
11406 
11407    return 0;
11408 }
11409 
11410 /*! \brief Change the other partys IP address based on given contact */
11411 static int set_address_from_contact(struct sip_pvt *pvt)
11412 {
11413    if (ast_test_flag(&pvt->flags[0], SIP_NAT_ROUTE)) {
11414       /* NAT: Don't trust the contact field.  Just use what they came to us
11415          with. */
11416       pvt->sa = pvt->recv;
11417       return 0;
11418    }
11419 
11420    return __set_address_from_contact(pvt->fullcontact, &pvt->sa, pvt->socket.type == SIP_TRANSPORT_TLS ? 1 : 0);
11421 }
11422 
11423 /*! \brief Parse contact header and save registration (peer registration) */
11424 static enum parse_register_result parse_register_contact(struct sip_pvt *pvt, struct sip_peer *peer, struct sip_request *req)
11425 {
11426    char contact[SIPBUFSIZE];
11427    char data[SIPBUFSIZE];
11428    const char *expires = get_header(req, "Expires");
11429    int expire = atoi(expires);
11430    char *curi, *host, *pt, *transport;
11431    int port;
11432    int transport_type;
11433    const char *useragent;
11434    struct hostent *hp;
11435    struct ast_hostent ahp;
11436    struct sockaddr_in oldsin, testsin;
11437 
11438 
11439    ast_copy_string(contact, get_header(req, "Contact"), sizeof(contact));
11440 
11441    if (ast_strlen_zero(expires)) {  /* No expires header, try look in Contact: */
11442       char *s = strcasestr(contact, ";expires=");
11443       if (s) {
11444          expires = strsep(&s, ";"); /* trim ; and beyond */
11445          if (sscanf(expires + 9, "%30d", &expire) != 1)
11446             expire = default_expiry;
11447       } else {
11448          /* Nothing has been specified */
11449          expire = default_expiry;
11450       }
11451    }
11452 
11453    copy_socket_data(&pvt->socket, &req->socket);
11454 
11455    /* Look for brackets */
11456    curi = contact;
11457    if (strchr(contact, '<') == NULL)   /* No <, check for ; and strip it */
11458       strsep(&curi, ";");  /* This is Header options, not URI options */
11459    curi = get_in_brackets(contact);
11460 
11461    /* if they did not specify Contact: or Expires:, they are querying
11462       what we currently have stored as their contact address, so return
11463       it
11464    */
11465    if (ast_strlen_zero(curi) && ast_strlen_zero(expires)) {
11466       /* If we have an active registration, tell them when the registration is going to expire */
11467       if (peer->expire > -1 && !ast_strlen_zero(peer->fullcontact))
11468          pvt->expiry = ast_sched_when(sched, peer->expire);
11469       return PARSE_REGISTER_QUERY;
11470    } else if (!strcasecmp(curi, "*") || !expire) { /* Unregister this peer */
11471       /* This means remove all registrations and return OK */
11472       memset(&peer->addr, 0, sizeof(peer->addr));
11473       set_socket_transport(&peer->socket, peer->default_outbound_transport);
11474 
11475       AST_SCHED_DEL_UNREF(sched, peer->expire,
11476             unref_peer(peer, "remove register expire ref"));
11477 
11478       destroy_association(peer);
11479 
11480       register_peer_exten(peer, FALSE);   /* Remove extension from regexten= setting in sip.conf */
11481       peer->fullcontact[0] = '\0';
11482       peer->useragent[0] = '\0';
11483       peer->sipoptions = 0;
11484       peer->lastms = 0;
11485       peer->portinuri = 0;
11486       pvt->expiry = 0;
11487 
11488       ast_verb(3, "Unregistered SIP '%s'\n", peer->name);
11489 
11490       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unregistered\r\n", peer->name);
11491       return PARSE_REGISTER_UPDATE;
11492    }
11493 
11494    /* Store whatever we got as a contact from the client */
11495    ast_copy_string(peer->fullcontact, curi, sizeof(peer->fullcontact));
11496 
11497    /* For the 200 OK, we should use the received contact */
11498    ast_string_field_build(pvt, our_contact, "<%s>", curi);
11499 
11500    /* Make sure it's a SIP URL */
11501    if (parse_uri(curi, "sip:,sips:", &curi, NULL, &host, &pt, NULL, &transport)) {
11502       ast_log(LOG_NOTICE, "Not a valid SIP contact (missing sip:) trying to use anyway\n");
11503    }
11504 
11505    /* If we have a port number in the given URI, make sure we do remember to not check for NAPTR/SRV records. 
11506       The domain part is actually a host. */
11507    peer->portinuri = !ast_strlen_zero(pt) ? TRUE : FALSE;
11508 
11509    /* handle the transport type specified in Contact header. */
11510    if ((transport_type = get_transport_str2enum(transport))) {
11511       /* if the port is not specified but the transport is, make sure to set the
11512        * default port to match the specified transport.  This may or may not be the
11513        * same transport used by the pvt struct for the Register dialog. */
11514       
11515       port = port_str2int(pt, (transport_type == SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT);
11516    } else {
11517       port = port_str2int(pt, STANDARD_SIP_PORT);
11518       transport_type = pvt->socket.type;
11519    }
11520 
11521    /* if the peer's socket type is different than the Registration
11522     * transport type, change it.  If it got this far, it is a
11523     * supported type, but check just in case */
11524    if ((peer->socket.type != transport_type) && (peer->transports & transport_type)) {
11525       set_socket_transport(&peer->socket, transport_type);
11526    }
11527 
11528    oldsin = peer->addr;
11529 
11530    /* If we were already linked into the peers_by_ip container unlink ourselves so nobody can find us */
11531    if (peer->addr.sin_addr.s_addr) {
11532       ao2_t_unlink(peers_by_ip, peer, "ao2_unlink of peer from peers_by_ip table");
11533    }
11534 
11535    /* Check that they're allowed to register at this IP */
11536    /* XXX This could block for a long time XXX */
11537    hp = ast_gethostbyname(host, &ahp);
11538    if (!hp)  {
11539       ast_log(LOG_WARNING, "Invalid host '%s'\n", host);
11540       *peer->fullcontact = '\0';
11541       ast_string_field_set(pvt, our_contact, "");
11542       return PARSE_REGISTER_FAILED;
11543    }
11544    memcpy(&testsin.sin_addr, hp->h_addr, sizeof(testsin.sin_addr));
11545    if (  ast_apply_ha(global_contact_ha, &testsin) != AST_SENSE_ALLOW ||
11546          ast_apply_ha(peer->contactha, &testsin) != AST_SENSE_ALLOW) {
11547       ast_log(LOG_WARNING, "Host '%s' disallowed by contact ACL (violating IP %s)\n", host, ast_inet_ntoa(testsin.sin_addr));
11548       *peer->fullcontact = '\0';
11549       ast_string_field_set(pvt, our_contact, "");
11550       return PARSE_REGISTER_DENIED;
11551    }
11552 
11553    if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE)) {
11554       peer->addr.sin_family = AF_INET;
11555       memcpy(&peer->addr.sin_addr, hp->h_addr, sizeof(peer->addr.sin_addr));
11556       peer->addr.sin_port = htons(port);
11557    } else {
11558       /* Don't trust the contact field.  Just use what they came to us
11559          with */
11560       peer->addr = pvt->recv;
11561    }
11562 
11563    /* if the Contact header information copied into peer->addr matches the
11564     * received address, and the transport types are the same, then copy socket
11565     * data into the peer struct */
11566    if ((peer->socket.type == pvt->socket.type) &&
11567       (peer->addr.sin_addr.s_addr == pvt->recv.sin_addr.s_addr) &&
11568       (peer->addr.sin_port == pvt->recv.sin_port)){
11569 
11570       copy_socket_data(&peer->socket, &pvt->socket);
11571    }
11572 
11573    /* Now that our address has been updated put ourselves back into the container for lookups */
11574    ao2_t_link(peers_by_ip, peer, "ao2_link into peers_by_ip table");
11575 
11576    /* Save SIP options profile */
11577    peer->sipoptions = pvt->sipoptions;
11578 
11579    if (!ast_strlen_zero(curi) && ast_strlen_zero(peer->username))
11580       ast_copy_string(peer->username, curi, sizeof(peer->username));
11581 
11582    AST_SCHED_DEL_UNREF(sched, peer->expire,
11583          unref_peer(peer, "remove register expire ref"));
11584 
11585    if (expire > max_expiry)
11586       expire = max_expiry;
11587    if (expire < min_expiry)
11588       expire = min_expiry;
11589    if (peer->is_realtime && !ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
11590       peer->expire = -1;
11591    } else {
11592       peer->expire = ast_sched_add(sched, (expire + 10) * 1000, expire_register,
11593             ref_peer(peer, "add registration ref"));
11594       if (peer->expire == -1) {
11595          unref_peer(peer, "remote registration ref");
11596       }
11597    }
11598    pvt->expiry = expire;
11599    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);
11600    /* Saving TCP connections is useless, we won't be able to reconnect 
11601       XXX WHY???? XXX
11602       \todo check this
11603    */
11604    if (!peer->rt_fromcontact && (peer->socket.type & SIP_TRANSPORT_UDP))
11605       ast_db_put("SIP/Registry", peer->name, data);
11606    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));
11607 
11608    /* Is this a new IP address for us? */
11609    if (VERBOSITY_ATLEAST(2) && inaddrcmp(&peer->addr, &oldsin)) {
11610       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));
11611    }
11612    sip_poke_peer(peer, 0);
11613    register_peer_exten(peer, 1);
11614    
11615    /* Save User agent */
11616    useragent = get_header(req, "User-Agent");
11617    if (strcasecmp(useragent, peer->useragent)) {   /* XXX copy if they are different ? */
11618       ast_copy_string(peer->useragent, useragent, sizeof(peer->useragent));
11619       ast_verb(4, "Saved useragent \"%s\" for peer %s\n", peer->useragent, peer->name);
11620    }
11621    return PARSE_REGISTER_UPDATE;
11622 }
11623 
11624 /*! \brief Remove route from route list */
11625 static void free_old_route(struct sip_route *route)
11626 {
11627    struct sip_route *next;
11628 
11629    while (route) {
11630       next = route->next;
11631       ast_free(route);
11632       route = next;
11633    }
11634 }
11635 
11636 /*! \brief List all routes - mostly for debugging */
11637 static void list_route(struct sip_route *route)
11638 {
11639    if (!route)
11640       ast_verbose("list_route: no route\n");
11641    else {
11642       for (;route; route = route->next)
11643          ast_verbose("list_route: hop: <%s>\n", route->hop);
11644    }
11645 }
11646 
11647 /*! \brief Build route list from Record-Route header */
11648 static void build_route(struct sip_pvt *p, struct sip_request *req, int backwards)
11649 {
11650    struct sip_route *thishop, *head, *tail;
11651    int start = 0;
11652    int len;
11653    const char *rr, *contact, *c;
11654 
11655    /* Once a persistant route is set, don't fool with it */
11656    if (p->route && p->route_persistant) {
11657       ast_debug(1, "build_route: Retaining previous route: <%s>\n", p->route->hop);
11658       return;
11659    }
11660 
11661    if (p->route) {
11662       free_old_route(p->route);
11663       p->route = NULL;
11664    }
11665 
11666    /* We only want to create the route set the first time this is called */
11667    p->route_persistant = 1;
11668    
11669    /* Build a tailq, then assign it to p->route when done.
11670     * If backwards, we add entries from the head so they end up
11671     * in reverse order. However, we do need to maintain a correct
11672     * tail pointer because the contact is always at the end.
11673     */
11674    head = NULL;
11675    tail = head;
11676    /* 1st we pass through all the hops in any Record-Route headers */
11677    for (;;) {
11678       /* Each Record-Route header */
11679       rr = __get_header(req, "Record-Route", &start);
11680       if (*rr == '\0')
11681          break;
11682       for (; (rr = strchr(rr, '<')) ; rr += len) { /* Each route entry */
11683          ++rr;
11684          len = strcspn(rr, ">") + 1;
11685          /* Make a struct route */
11686          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11687             /* ast_calloc is not needed because all fields are initialized in this block */
11688             ast_copy_string(thishop->hop, rr, len);
11689             ast_debug(2, "build_route: Record-Route hop: <%s>\n", thishop->hop);
11690             /* Link in */
11691             if (backwards) {
11692                /* Link in at head so they end up in reverse order */
11693                thishop->next = head;
11694                head = thishop;
11695                /* If this was the first then it'll be the tail */
11696                if (!tail)
11697                   tail = thishop;
11698             } else {
11699                thishop->next = NULL;
11700                /* Link in at the end */
11701                if (tail)
11702                   tail->next = thishop;
11703                else
11704                   head = thishop;
11705                tail = thishop;
11706             }
11707          }
11708       }
11709    }
11710 
11711    /* Only append the contact if we are dealing with a strict router */
11712    if (!head || (!ast_strlen_zero(head->hop) && strstr(head->hop, ";lr") == NULL) ) {
11713       /* 2nd append the Contact: if there is one */
11714       /* Can be multiple Contact headers, comma separated values - we just take the first */
11715       contact = get_header(req, "Contact");
11716       if (!ast_strlen_zero(contact)) {
11717          ast_debug(2, "build_route: Contact hop: %s\n", contact);
11718          /* Look for <: delimited address */
11719          c = strchr(contact, '<');
11720          if (c) {
11721             /* Take to > */
11722             ++c;
11723             len = strcspn(c, ">") + 1;
11724          } else {
11725             /* No <> - just take the lot */
11726             c = contact;
11727             len = strlen(contact) + 1;
11728          }
11729          if ((thishop = ast_malloc(sizeof(*thishop) + len))) {
11730             /* ast_calloc is not needed because all fields are initialized in this block */
11731             ast_copy_string(thishop->hop, c, len);
11732             thishop->next = NULL;
11733             /* Goes at the end */
11734             if (tail)
11735                tail->next = thishop;
11736             else
11737                head = thishop;
11738          }
11739       }
11740    }
11741 
11742    /* Store as new route */
11743    p->route = head;
11744 
11745    /* For debugging dump what we ended up with */
11746    if (sip_debug_test_pvt(p))
11747       list_route(p->route);
11748 }
11749 
11750 /*! \brief builds the sip_pvt's randdata field which is used for the nonce
11751  *  challenge.  When forceupdate is not set, the nonce is only updated if
11752  *  the current one is stale.  In this case, a stalenonce is one which
11753  *  has already received a response, if a nonce has not received a response
11754  *  it is not always necessary or beneficial to create a new one. */
11755 
11756 static void set_nonce_randdata(struct sip_pvt *p, int forceupdate)
11757 {
11758    if (p->stalenonce || forceupdate || ast_strlen_zero(p->randdata)) {
11759       ast_string_field_build(p, randdata, "%08lx", ast_random()); /* Create nonce for challenge */
11760       p->stalenonce = 0;
11761    }
11762 }
11763 
11764 AST_THREADSTORAGE(check_auth_buf);
11765 #define CHECK_AUTH_BUF_INITLEN   256
11766 
11767 /*! \brief  Check user authorization from peer definition 
11768    Some actions, like REGISTER and INVITEs from peers require
11769    authentication (if peer have secret set) 
11770     \return 0 on success, non-zero on error
11771 */
11772 static enum check_auth_result check_auth(struct sip_pvt *p, struct sip_request *req, const char *username,
11773                 const char *secret, const char *md5secret, int sipmethod,
11774                 char *uri, enum xmittype reliable, int ignore)
11775 {
11776    const char *response;
11777    char *reqheader, *respheader;
11778    const char *authtoken;
11779    char a1_hash[256];
11780    char resp_hash[256]="";
11781    char *c;
11782    int  wrongnonce = FALSE;
11783    int  good_response;
11784    const char *usednonce = p->randdata;
11785    struct ast_str *buf;
11786    int res;
11787 
11788    /* table of recognised keywords, and their value in the digest */
11789    enum keys { K_RESP, K_URI, K_USER, K_NONCE, K_LAST };
11790    struct x {
11791       const char *key;
11792       const char *s;
11793    } *i, keys[] = {
11794       [K_RESP] = { "response=", "" },
11795       [K_URI] = { "uri=", "" },
11796       [K_USER] = { "username=", "" },
11797       [K_NONCE] = { "nonce=", "" },
11798       [K_LAST] = { NULL, NULL}
11799    };
11800 
11801    /* Always OK if no secret */
11802    if (ast_strlen_zero(secret) && ast_strlen_zero(md5secret))
11803       return AUTH_SUCCESSFUL;
11804 
11805    /* Always auth with WWW-auth since we're NOT a proxy */
11806    /* Using proxy-auth in a B2BUA may block proxy authorization in the same transaction */
11807    response = "401 Unauthorized";
11808 
11809    /*
11810     * Note the apparent swap of arguments below, compared to other
11811     * usages of auth_headers().
11812     */
11813    auth_headers(WWW_AUTH, &respheader, &reqheader);
11814 
11815    authtoken =  get_header(req, reqheader);  
11816    if (ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
11817       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
11818          information */
11819       if (!reliable) {
11820          /* Resend message if this was NOT a reliable delivery.   Otherwise the
11821             retransmission should get it */
11822          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11823          /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
11824          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11825       }
11826       return AUTH_CHALLENGE_SENT;
11827    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
11828       /* We have no auth, so issue challenge and request authentication */
11829       set_nonce_randdata(p, 1); /* Create nonce for challenge */
11830       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, 0);
11831       /* Schedule auto destroy in 32 seconds */
11832       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11833       return AUTH_CHALLENGE_SENT;
11834    } 
11835 
11836    /* --- We have auth, so check it */
11837 
11838    /* Whoever came up with the authentication section of SIP can suck my %&#$&* for not putting
11839       an example in the spec of just what it is you're doing a hash on. */
11840 
11841    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN)))
11842       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
11843 
11844    /* Make a copy of the response and parse it */
11845    res = ast_str_set(&buf, 0, "%s", authtoken);
11846 
11847    if (res == AST_DYNSTR_BUILD_FAILED)
11848       return AUTH_SECRET_FAILED; /*! XXX \todo need a better return code here */
11849 
11850    c = buf->str;
11851 
11852    while(c && *(c = ast_skip_blanks(c)) ) { /* lookup for keys */
11853       for (i = keys; i->key != NULL; i++) {
11854          const char *separator = ",";  /* default */
11855 
11856          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
11857             continue;
11858          /* Found. Skip keyword, take text in quotes or up to the separator. */
11859          c += strlen(i->key);
11860          if (*c == '"') { /* in quotes. Skip first and look for last */
11861             c++;
11862             separator = "\"";
11863          }
11864          i->s = c;
11865          strsep(&c, separator);
11866          break;
11867       }
11868       if (i->key == NULL) /* not found, jump after space or comma */
11869          strsep(&c, " ,");
11870    }
11871 
11872    /* Verify that digest username matches  the username we auth as */
11873    if (strcmp(username, keys[K_USER].s)) {
11874       ast_log(LOG_WARNING, "username mismatch, have <%s>, digest has <%s>\n",
11875          username, keys[K_USER].s);
11876       /* Oops, we're trying something here */
11877       return AUTH_USERNAME_MISMATCH;
11878    }
11879 
11880    /* Verify nonce from request matches our nonce, and the nonce has not already been responded to.
11881     * If this check fails, send 401 with new nonce */
11882    if (strcasecmp(p->randdata, keys[K_NONCE].s) || p->stalenonce) { /* XXX it was 'n'casecmp ? */
11883       wrongnonce = TRUE;
11884       usednonce = keys[K_NONCE].s;
11885    } else {
11886       p->stalenonce = 1; /* now, since the nonce has a response, mark it as stale so it can't be sent or responded to again */
11887    }
11888 
11889    if (!ast_strlen_zero(md5secret))
11890       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
11891    else {
11892       char a1[256];
11893       snprintf(a1, sizeof(a1), "%s:%s:%s", username, global_realm, secret);
11894       ast_md5_hash(a1_hash, a1);
11895    }
11896 
11897    /* compute the expected response to compare with what we received */
11898    {
11899       char a2[256];
11900       char a2_hash[256];
11901       char resp[256];
11902 
11903       snprintf(a2, sizeof(a2), "%s:%s", sip_methods[sipmethod].text,
11904             S_OR(keys[K_URI].s, uri));
11905       ast_md5_hash(a2_hash, a2);
11906       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, usednonce, a2_hash);
11907       ast_md5_hash(resp_hash, resp);
11908    }
11909 
11910    good_response = keys[K_RESP].s &&
11911          !strncasecmp(keys[K_RESP].s, resp_hash, strlen(resp_hash));
11912    if (wrongnonce) {
11913       if (good_response) {
11914          if (sipdebug)
11915             ast_log(LOG_NOTICE, "Correct auth, but based on stale nonce received from '%s'\n", get_header(req, "To"));
11916          /* We got working auth token, based on stale nonce . */
11917          set_nonce_randdata(p, 0);
11918          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, TRUE);
11919       } else {
11920          /* Everything was wrong, so give the device one more try with a new challenge */
11921          if (!req->ignore) {
11922             if (sipdebug)
11923                ast_log(LOG_NOTICE, "Bad authentication received from '%s'\n", get_header(req, "To"));
11924             set_nonce_randdata(p, 1);
11925          } else {
11926             if (sipdebug)
11927                ast_log(LOG_NOTICE, "Duplicate authentication received from '%s'\n", get_header(req, "To"));
11928          }
11929          transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
11930       }
11931 
11932       /* Schedule auto destroy in 32 seconds */
11933       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
11934       return AUTH_CHALLENGE_SENT;
11935    } 
11936    if (good_response) {
11937       append_history(p, "AuthOK", "Auth challenge succesful for %s", username);
11938       return AUTH_SUCCESSFUL;
11939    }
11940 
11941    /* Ok, we have a bad username/secret pair */
11942    /* Tell the UAS not to re-send this authentication data, because
11943       it will continue to fail
11944    */
11945 
11946    return AUTH_SECRET_FAILED;
11947 }
11948 
11949 /*! \brief Change onhold state of a peer using a pvt structure */
11950 static void sip_peer_hold(struct sip_pvt *p, int hold)
11951 {
11952    struct sip_peer *peer = find_peer(p->peername, NULL, 1, FINDALLDEVICES, FALSE, 0);
11953 
11954    if (!peer)
11955       return;
11956 
11957    /* If they put someone on hold, increment the value... otherwise decrement it */
11958    ast_atomic_fetchadd_int(&peer->onHold, (hold ? +1 : -1));
11959 
11960    /* Request device state update */
11961    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
11962    unref_peer(peer, "sip_peer_hold: from find_peer operation");
11963    
11964    return;
11965 }
11966 
11967 /*! \brief Receive MWI events that we have subscribed to */
11968 static void mwi_event_cb(const struct ast_event *event, void *userdata)
11969 {
11970    struct sip_peer *peer = userdata;
11971 
11972    ao2_lock(peer);
11973    sip_send_mwi_to_peer(peer, event, 0);
11974    ao2_unlock(peer);
11975 }
11976 
11977 /*! \brief Callback for the devicestate notification (SUBSCRIBE) support subsystem
11978 \note If you add an "hint" priority to the extension in the dial plan,
11979    you will get notifications on device state changes */
11980 static int cb_extensionstate(char *context, char* exten, int state, void *data)
11981 {
11982    struct sip_pvt *p = data;
11983 
11984    sip_pvt_lock(p);
11985 
11986    switch(state) {
11987    case AST_EXTENSION_DEACTIVATED:  /* Retry after a while */
11988    case AST_EXTENSION_REMOVED:   /* Extension is gone */
11989       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
11990          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
11991       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);  /* Delete subscription in 32 secs */
11992       ast_verb(2, "Extension state: Watcher for hint %s %s. Notify User %s\n", exten, state == AST_EXTENSION_DEACTIVATED ? "deactivated" : "removed", p->username);
11993       p->stateid = -1;
11994       p->subscribed = NONE;
11995       append_history(p, "Subscribestatus", "%s", state == AST_EXTENSION_REMOVED ? "HintRemoved" : "Deactivated");
11996       break;
11997    default: /* Tell user */
11998       p->laststate = state;
11999       break;
12000    }
12001    if (p->subscribed != NONE) {  /* Only send state NOTIFY if we know the format */
12002       if (!p->pendinginvite) {
12003          transmit_state_notify(p, state, 1, FALSE);
12004       } else {
12005          /* We already have a NOTIFY sent that is not answered. Queue the state up.
12006             if many state changes happen meanwhile, we will only send a notification of the last one */
12007          ast_set_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
12008       }
12009    }
12010    ast_verb(2, "Extension Changed %s[%s] new state %s for Notify User %s %s\n", exten, context, ast_extension_state2str(state), p->username,
12011          ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE) ? "(queued)" : "");
12012 
12013    sip_pvt_unlock(p);
12014 
12015    return 0;
12016 }
12017 
12018 /*! \brief Send a fake 401 Unauthorized response when the administrator
12019   wants to hide the names of local devices  from fishers
12020  */
12021 static void transmit_fake_auth_response(struct sip_pvt *p, int sipmethod, struct sip_request *req, enum xmittype reliable)
12022 {
12023    /* We have to emulate EXACTLY what we'd get with a good peer
12024     * and a bad password, or else we leak information. */
12025    const char *response = "407 Proxy Authentication Required";
12026    const char *reqheader = "Proxy-Authorization";
12027    const char *respheader = "Proxy-Authenticate";
12028    const char *authtoken;
12029    struct ast_str *buf;
12030    char *c;
12031 
12032    /* table of recognised keywords, and their value in the digest */
12033    enum keys { K_NONCE, K_LAST };
12034    struct x {
12035       const char *key;
12036       const char *s;
12037    } *i, keys[] = {
12038       [K_NONCE] = { "nonce=", "" },
12039       [K_LAST] = { NULL, NULL}
12040    };
12041 
12042    if (sipmethod == SIP_REGISTER || sipmethod == SIP_SUBSCRIBE) {
12043       response = "401 Unauthorized";
12044       reqheader = "Authorization";
12045       respheader = "WWW-Authenticate";
12046    }
12047    authtoken = get_header(req, reqheader);
12048    if (req->ignore && !ast_strlen_zero(p->randdata) && ast_strlen_zero(authtoken)) {
12049       /* This is a retransmitted invite/register/etc, don't reconstruct authentication
12050        * information */
12051       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12052       /* Schedule auto destroy in 32 seconds (according to RFC 3261) */
12053       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12054       return;
12055    } else if (ast_strlen_zero(p->randdata) || ast_strlen_zero(authtoken)) {
12056       /* We have no auth, so issue challenge and request authentication */
12057       set_nonce_randdata(p, 1);
12058       transmit_response_with_auth(p, response, req, p->randdata, 0, respheader, 0);
12059       /* Schedule auto destroy in 32 seconds */
12060       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12061       return;
12062    }
12063 
12064    if (!(buf = ast_str_thread_get(&check_auth_buf, CHECK_AUTH_BUF_INITLEN))) {
12065       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12066       return;
12067    }
12068 
12069    /* Make a copy of the response and parse it */
12070    if (ast_str_set(&buf, 0, "%s", authtoken) == AST_DYNSTR_BUILD_FAILED) {
12071       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12072       return;
12073    }
12074 
12075    c = buf->str;
12076 
12077    while (c && *(c = ast_skip_blanks(c))) { /* lookup for keys */
12078       for (i = keys; i->key != NULL; i++) {
12079          const char *separator = ",";  /* default */
12080 
12081          if (strncasecmp(c, i->key, strlen(i->key)) != 0) {
12082             continue;
12083          }
12084          /* Found. Skip keyword, take text in quotes or up to the separator. */
12085          c += strlen(i->key);
12086          if (*c == '"') { /* in quotes. Skip first and look for last */
12087             c++;
12088             separator = "\"";
12089          }
12090          i->s = c;
12091          strsep(&c, separator);
12092          break;
12093       }
12094       if (i->key == NULL) { /* not found, jump after space or comma */
12095          strsep(&c, " ,");
12096       }
12097    }
12098 
12099    /* Verify nonce from request matches our nonce.  If not, send 401 with new nonce */
12100    if (strcasecmp(p->randdata, keys[K_NONCE].s)) {
12101       if (!req->ignore) {
12102          set_nonce_randdata(p, 1);
12103       }
12104       transmit_response_with_auth(p, response, req, p->randdata, reliable, respheader, FALSE);
12105 
12106       /* Schedule auto destroy in 32 seconds */
12107       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
12108    } else {
12109       transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12110    }
12111 }
12112 
12113 /*!
12114  * Terminate the uri at the first ';' or space.
12115  * Technically we should ignore escaped space per RFC3261 (19.1.1 etc)
12116  * but don't do it for the time being. Remember the uri format is:
12117  *\verbatim
12118  *
12119  * sip:user:password@host:port;uri-parameters?headers
12120  * sips:user:password@host:port;uri-parameters?headers
12121  *
12122  *\endverbatim
12123  */
12124 static char *terminate_uri(char *uri)
12125 {
12126    char *t = uri;
12127    while (*t && *t > ' ' && *t != ';')
12128       t++;
12129    *t = '\0';
12130    return uri;
12131 }
12132 
12133 /*! \brief Verify registration of user 
12134    - Registration is done in several steps, first a REGISTER without auth
12135      to get a challenge (nonce) then a second one with auth
12136    - Registration requests are only matched with peers that are marked as "dynamic"
12137  */
12138 static enum check_auth_result register_verify(struct sip_pvt *p, struct sockaddr_in *sin,
12139                      struct sip_request *req, char *uri)
12140 {
12141    enum check_auth_result res = AUTH_NOT_FOUND;
12142    struct sip_peer *peer;
12143    char tmp[256];
12144    char *name, *c;
12145    char *domain;
12146 
12147    terminate_uri(uri);  /* warning, overwrite the string */
12148 
12149    ast_copy_string(tmp, get_header(req, "To"), sizeof(tmp));
12150    if (pedanticsipchecking)
12151       ast_uri_decode(tmp);
12152 
12153    c = get_in_brackets(tmp);
12154    c = remove_uri_parameters(c);
12155 
12156    if (!strncasecmp(c, "sip:", 4)) {
12157       name = c + 4;
12158    } else if (!strncasecmp(c, "sips:", 5)) {
12159       name = c + 5;
12160    } else {
12161       name = c;
12162       ast_log(LOG_NOTICE, "Invalid to address: '%s' from %s (missing sip:) trying to use anyway...\n", c, ast_inet_ntoa(sin->sin_addr));
12163    }
12164 
12165    /* XXX here too we interpret a missing @domain as a name-only
12166     * URI, whereas the RFC says this is a domain-only uri.
12167     */
12168    /* Strip off the domain name */
12169    if ((c = strchr(name, '@'))) {
12170       *c++ = '\0';
12171       domain = c;
12172       if ((c = strchr(domain, ':')))   /* Remove :port */
12173          *c = '\0';
12174       if (!AST_LIST_EMPTY(&domain_list)) {
12175          if (!check_sip_domain(domain, NULL, 0)) {
12176             transmit_response(p, "404 Not found (unknown domain)", &p->initreq);
12177             return AUTH_UNKNOWN_DOMAIN;
12178          }
12179       }
12180    }
12181    c = strchr(name, ';');  /* Remove any Username parameters */
12182    if (c)
12183       *c = '\0';
12184 
12185    ast_string_field_set(p, exten, name);
12186    build_contact(p);
12187    peer = find_peer(name, NULL, TRUE, FINDPEERS, FALSE, 0);
12188    if (!(peer && ast_apply_ha(peer->ha, sin))) {
12189       /* Peer fails ACL check */
12190       if (peer) {
12191          unref_peer(peer, "register_verify: unref_peer: from find_peer operation");
12192          peer = NULL;
12193          res = AUTH_ACL_FAILED;
12194       } else
12195          res = AUTH_NOT_FOUND;
12196    }
12197 
12198    if (peer) {
12199       /* Set Frame packetization */
12200       if (p->rtp) {
12201          ast_rtp_codec_setpref(p->rtp, &peer->prefs);
12202          p->autoframing = peer->autoframing;
12203       }
12204       if (!peer->host_dynamic) {
12205          ast_log(LOG_ERROR, "Peer '%s' is trying to register, but not configured as host=dynamic\n", peer->name);
12206          res = AUTH_PEER_NOT_DYNAMIC;
12207       } else {
12208          ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_NAT);
12209          if (ast_test_flag(&p->flags[1], SIP_PAGE2_REGISTERTRYING))
12210             transmit_response(p, "100 Trying", req);
12211          if (!(res = check_auth(p, req, peer->name, peer->secret, peer->md5secret, SIP_REGISTER, uri, XMIT_UNRELIABLE, req->ignore))) {
12212             if (sip_cancel_destroy(p))
12213                ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12214 
12215             if (check_request_transport(peer, req)) {
12216                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);
12217                transmit_response_with_date(p, "403 Forbidden", req);
12218                res = AUTH_BAD_TRANSPORT;
12219             } else {
12220 
12221                /* We have a successful registration attempt with proper authentication,
12222                   now, update the peer */
12223                switch (parse_register_contact(p, peer, req)) {
12224                case PARSE_REGISTER_DENIED:
12225                   transmit_response_with_date(p, "603 Denied", req);
12226                   peer->lastmsgssent = -1;
12227                   res = 0;
12228                   break;
12229                case PARSE_REGISTER_FAILED:
12230                   ast_log(LOG_WARNING, "Failed to parse contact info\n");
12231                   transmit_response_with_date(p, "400 Bad Request", req);
12232                   peer->lastmsgssent = -1;
12233                   res = 0;
12234                   break;
12235                case PARSE_REGISTER_QUERY:
12236                   ast_string_field_set(p, fullcontact, peer->fullcontact);
12237                   transmit_response_with_date(p, "200 OK", req);
12238                   peer->lastmsgssent = -1;
12239                   res = 0;
12240                   break;
12241                case PARSE_REGISTER_UPDATE:
12242                   ast_string_field_set(p, fullcontact, peer->fullcontact);
12243                   update_peer(peer, p->expiry);
12244                   /* Say OK and ask subsystem to retransmit msg counter */
12245                   transmit_response_with_date(p, "200 OK", req);
12246                   if (!ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY))
12247                      peer->lastmsgssent = -1;
12248                   res = 0;
12249                   break;
12250                }
12251             }
12252 
12253          } 
12254       }
12255    }
12256    if (!peer && autocreatepeer) {
12257       /* Create peer if we have autocreate mode enabled */
12258       peer = temp_peer(name);
12259       if (peer) {
12260          ao2_t_link(peers, peer, "link peer into peer table");
12261          if (peer->addr.sin_addr.s_addr) {
12262             ao2_t_link(peers_by_ip, peer, "link peer into peers-by-ip table");
12263          }
12264          
12265          if (sip_cancel_destroy(p))
12266             ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
12267          switch (parse_register_contact(p, peer, req)) {
12268          case PARSE_REGISTER_DENIED:
12269             transmit_response_with_date(p, "403 Forbidden (ACL)", req);
12270             peer->lastmsgssent = -1;
12271             res = 0;
12272             break;
12273          case PARSE_REGISTER_FAILED:
12274             ast_log(LOG_WARNING, "Failed to parse contact info\n");
12275             transmit_response_with_date(p, "400 Bad Request", req);
12276             peer->lastmsgssent = -1;
12277             res = 0;
12278             break;
12279          case PARSE_REGISTER_QUERY:
12280             ast_string_field_set(p, fullcontact, peer->fullcontact);
12281             transmit_response_with_date(p, "200 OK", req);
12282             peer->lastmsgssent = -1;
12283             res = 0;
12284             break;
12285          case PARSE_REGISTER_UPDATE:
12286             ast_string_field_set(p, fullcontact, peer->fullcontact);
12287             /* Say OK and ask subsystem to retransmit msg counter */
12288             transmit_response_with_date(p, "200 OK", req);
12289             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));
12290             peer->lastmsgssent = -1;
12291             res = 0;
12292             break;
12293          }
12294       }
12295    }
12296    if (!peer && global_alwaysauthreject) {
12297       /* If we found a peer, we transmit a 100 Trying.  Therefore, if we're
12298        * trying to avoid leaking information, we MUST also transmit the same
12299        * response when we DON'T find a peer. */
12300       transmit_response(p, "100 Trying", req);
12301       /* Insert a fake delay between the 100 and the subsequent failure. */
12302       sched_yield();
12303    }
12304    if (!res) {
12305       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
12306    }
12307    if (res < 0) {
12308       switch (res) {
12309       case AUTH_SECRET_FAILED:
12310          /* Wrong password in authentication. Go away, don't try again until you fixed it */
12311          transmit_response(p, "403 Forbidden (Bad auth)", &p->initreq);
12312          if (global_authfailureevents)
12313             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", 
12314                name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12315          break;
12316       case AUTH_USERNAME_MISMATCH:
12317          /* Username and digest username does not match.
12318             Asterisk uses the From: username for authentication. We need the
12319             devices to use the same authentication user name until we support
12320             proper authentication by digest auth name */
12321       case AUTH_NOT_FOUND:
12322       case AUTH_PEER_NOT_DYNAMIC:
12323       case AUTH_ACL_FAILED:
12324          if (global_alwaysauthreject) {
12325             transmit_fake_auth_response(p, SIP_REGISTER, &p->initreq, XMIT_UNRELIABLE);
12326          } else {
12327             /* URI not found */
12328             if (res == AUTH_PEER_NOT_DYNAMIC) {
12329                transmit_response(p, "403 Forbidden", &p->initreq);
12330                if (global_authfailureevents)
12331                   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", 
12332                      name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12333                }
12334             else
12335                transmit_response(p, "404 Not found", &p->initreq);
12336                if (global_authfailureevents)
12337                   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", 
12338                            (res == AUTH_USERNAME_MISMATCH) ? "AUTH_USERNAME_MISMATCH" : "URI_NOT_FOUND", name, ast_inet_ntoa(sin->sin_addr), ntohs(sin->sin_port));
12339          }
12340          break;
12341       case AUTH_BAD_TRANSPORT:
12342       default:
12343          break;
12344       }
12345    }
12346    if (peer)
12347       unref_peer(peer, "register_verify: unref_peer: tossing stack peer pointer at end of func");
12348 
12349    return res;
12350 }
12351 
12352 /*! \brief Translate referring cause */
12353 static void sip_set_redirstr(struct sip_pvt *p, char *reason) {
12354 
12355    if (!strcmp(reason, "unknown")) {
12356       ast_string_field_set(p, redircause, "UNKNOWN");
12357    } else if (!strcmp(reason, "user-busy")) {
12358       ast_string_field_set(p, redircause, "BUSY");
12359    } else if (!strcmp(reason, "no-answer")) {
12360       ast_string_field_set(p, redircause, "NOANSWER");
12361    } else if (!strcmp(reason, "unavailable")) {
12362       ast_string_field_set(p, redircause, "UNREACHABLE");
12363    } else if (!strcmp(reason, "unconditional")) {
12364       ast_string_field_set(p, redircause, "UNCONDITIONAL");
12365    } else if (!strcmp(reason, "time-of-day")) {
12366       ast_string_field_set(p, redircause, "UNKNOWN");
12367    } else if (!strcmp(reason, "do-not-disturb")) {
12368       ast_string_field_set(p, redircause, "UNKNOWN");
12369    } else if (!strcmp(reason, "deflection")) {
12370       ast_string_field_set(p, redircause, "UNKNOWN");
12371    } else if (!strcmp(reason, "follow-me")) {
12372       ast_string_field_set(p, redircause, "UNKNOWN");
12373    } else if (!strcmp(reason, "out-of-service")) {
12374       ast_string_field_set(p, redircause, "UNREACHABLE");
12375    } else if (!strcmp(reason, "away")) {
12376       ast_string_field_set(p, redircause, "UNREACHABLE");
12377    } else {
12378       ast_string_field_set(p, redircause, "UNKNOWN");
12379    }
12380 }
12381 
12382 /*! \brief Get referring dnis */
12383 static int get_rdnis(struct sip_pvt *p, struct sip_request *oreq)
12384 {
12385    char tmp[256], *exten, *rexten, *rdomain;
12386    char *params, *reason = NULL;
12387    struct sip_request *req;
12388    
12389    req = oreq ? oreq : &p->initreq;
12390 
12391    ast_copy_string(tmp, get_header(req, "Diversion"), sizeof(tmp));
12392    if (ast_strlen_zero(tmp))
12393       return 0;
12394 
12395    params = strchr(tmp, ';');
12396 
12397    exten = get_in_brackets(tmp);
12398    if (!strncasecmp(exten, "sip:", 4)) {
12399       exten += 4;
12400    } else if (!strncasecmp(exten, "sips:", 5)) {
12401       exten += 5;
12402    } else {
12403       ast_log(LOG_WARNING, "Huh?  Not an RDNIS SIP header (%s)?\n", exten);
12404       return -1;
12405    }
12406 
12407    /* Get diversion-reason param if present */
12408    if (params) {
12409       *params = '\0';   /* Cut off parameters  */
12410       params++;
12411       while (*params == ';' || *params == ' ')
12412          params++;
12413       /* Check if we have a reason parameter */
12414       if ((reason = strcasestr(params, "reason="))) {
12415          reason+=7;
12416          /* Remove enclosing double-quotes */
12417          if (*reason == '"') 
12418             ast_strip_quoted(reason, "\"", "\"");
12419          if (!ast_strlen_zero(reason)) {
12420             sip_set_redirstr(p, reason);
12421             if (p->owner) {
12422                pbx_builtin_setvar_helper(p->owner, "__PRIREDIRECTREASON", p->redircause);
12423                pbx_builtin_setvar_helper(p->owner, "__SIPREDIRECTREASON", reason);
12424             }
12425          }
12426       }
12427    }
12428 
12429    rdomain = exten;
12430    rexten = strsep(&rdomain, "@");  /* trim anything after @ */
12431    if (p->owner) 
12432       pbx_builtin_setvar_helper(p->owner, "__SIPRDNISDOMAIN", rdomain);
12433 
12434    if (sip_debug_test_pvt(p))
12435       ast_verbose("RDNIS for this call is is %s (reason %s)\n", exten, reason ? reason : "");
12436 
12437    ast_string_field_set(p, rdnis, rexten);
12438 
12439    return 0;
12440 }
12441 
12442 /*! \brief Find out who the call is for.
12443    We use the request uri as a destination. 
12444    This code assumes authentication has been done, so that the
12445    device (peer/user) context is already set.
12446    \return 0 on success (found a matching extension),
12447    1 for pickup extension or overlap dialling support (if we support it),
12448    -1 on error.
12449 */
12450 static int get_destination(struct sip_pvt *p, struct sip_request *oreq)
12451 {
12452    char tmp[256] = "", *uri, *a;
12453    char tmpf[256] = "", *from = NULL;
12454    struct sip_request *req;
12455    char *colon;
12456    char *decoded_uri;
12457    
12458    req = oreq;
12459    if (!req)
12460       req = &p->initreq;
12461 
12462    /* Find the request URI */
12463    if (req->rlPart2)
12464       ast_copy_string(tmp, REQ_OFFSET_TO_STR(req, rlPart2), sizeof(tmp));
12465    
12466    if (pedanticsipchecking)
12467       ast_uri_decode(tmp);
12468 
12469    uri = get_in_brackets(tmp);
12470    
12471    if (!strncasecmp(uri, "sip:", 4)) {
12472       uri += 4;
12473    } else if (!strncasecmp(uri, "sips:", 5)) {
12474       uri += 5;
12475    } else {
12476       ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", uri);
12477       return -1;
12478    }
12479 
12480    /* Now find the From: caller ID and name */
12481    /* XXX Why is this done in get_destination? Isn't it already done?
12482       Needs to be checked 
12483         */
12484    ast_copy_string(tmpf, get_header(req, "From"), sizeof(tmpf));
12485    if (!ast_strlen_zero(tmpf)) {
12486       if (pedanticsipchecking)
12487          ast_uri_decode(tmpf);
12488       from = get_in_brackets(tmpf);
12489    } 
12490    
12491    if (!ast_strlen_zero(from)) {
12492       if (!strncasecmp(from, "sip:", 4)) {
12493          from += 4;
12494       } else if (!strncasecmp(from, "sips:", 5)) {
12495          from += 5;
12496       } else {
12497          ast_log(LOG_WARNING, "Huh?  Not a SIP header (%s)?\n", from);
12498          return -1;
12499       }
12500       if ((a = strchr(from, '@')))
12501          *a++ = '\0';
12502       else
12503          a = from;   /* just a domain */
12504       from = strsep(&from, ";"); /* Remove userinfo options */
12505       a = strsep(&a, ";");    /* Remove URI options */
12506       ast_string_field_set(p, fromdomain, a);
12507    }
12508 
12509    /* Skip any options and find the domain */
12510 
12511    /* Get the target domain */
12512    if ((a = strchr(uri, '@'))) {
12513       *a++ = '\0';
12514    } else { /* No username part */
12515       a = uri;
12516       uri = "s";  /* Set extension to "s" */
12517    }
12518    colon = strchr(a, ':'); /* Remove :port */
12519    if (colon)
12520       *colon = '\0';
12521 
12522    uri = strsep(&uri, ";");   /* Remove userinfo options */
12523    a = strsep(&a, ";");    /* Remove URI options */
12524 
12525    ast_string_field_set(p, domain, a);
12526 
12527    if (!AST_LIST_EMPTY(&domain_list)) {
12528       char domain_context[AST_MAX_EXTENSION];
12529 
12530       domain_context[0] = '\0';
12531       if (!check_sip_domain(p->domain, domain_context, sizeof(domain_context))) {
12532          if (!allow_external_domains && (req->method == SIP_INVITE || req->method == SIP_REFER)) {
12533             ast_debug(1, "Got SIP %s to non-local domain '%s'; refusing request.\n", sip_methods[req->method].text, p->domain);
12534             return -2;
12535          }
12536       }
12537       /* If we have a context defined, overwrite the original context */
12538       if (!ast_strlen_zero(domain_context))
12539          ast_string_field_set(p, context, domain_context);
12540    }
12541 
12542    /* If the request coming in is a subscription and subscribecontext has been specified use it */
12543    if (req->method == SIP_SUBSCRIBE && !ast_strlen_zero(p->subscribecontext))
12544       ast_string_field_set(p, context, p->subscribecontext);
12545 
12546    if (sip_debug_test_pvt(p))
12547       ast_verbose("Looking for %s in %s (domain %s)\n", uri, p->context, p->domain);
12548 
12549    /* If this is a subscription we actually just need to see if a hint exists for the extension */
12550    if (req->method == SIP_SUBSCRIBE) {
12551       char hint[AST_MAX_EXTENSION];
12552       return (ast_get_hint(hint, sizeof(hint), NULL, 0, NULL, p->context, p->exten) ? 0 : -1);
12553    } else {
12554       decoded_uri = ast_strdupa(uri);
12555       ast_uri_decode(decoded_uri);
12556       /* Check the dialplan for the username part of the request URI,
12557          the domain will be stored in the SIPDOMAIN variable
12558          Since extensions.conf can have unescaped characters, try matching a decoded
12559          uri in addition to the non-decoded uri
12560          Return 0 if we have a matching extension */
12561       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)) ||
12562           !strcmp(decoded_uri, ast_pickup_ext())) {
12563          if (!oreq)
12564             ast_string_field_set(p, exten, decoded_uri);
12565          return 0;
12566       } 
12567    }
12568 
12569    /* Return 1 for pickup extension or overlap dialling support (if we support it) */
12570    if((ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP) && 
12571        ast_canmatch_extension(NULL, p->context, decoded_uri, 1, S_OR(p->cid_num, from))) ||
12572        !strncmp(decoded_uri, ast_pickup_ext(), strlen(decoded_uri))) {
12573       return 1;
12574    }
12575    
12576    return -1;
12577 }
12578 
12579 /*! \brief Lock dialog lock and find matching pvt lock  
12580    \return a reference, remember to release it when done 
12581 */
12582 static struct sip_pvt *get_sip_pvt_byid_locked(const char *callid, const char *totag, const char *fromtag) 
12583 {
12584    struct sip_pvt *sip_pvt_ptr;
12585    struct sip_pvt tmp_dialog = {
12586       .callid = callid,
12587    };
12588 
12589    if (totag)
12590       ast_debug(4, "Looking for callid %s (fromtag %s totag %s)\n", callid, fromtag ? fromtag : "<no fromtag>", totag ? totag : "<no totag>");
12591 
12592    /* Search dialogs and find the match */
12593    
12594    sip_pvt_ptr = ao2_t_find(dialogs, &tmp_dialog, OBJ_POINTER, "ao2_find of dialog in dialogs table");
12595    if (sip_pvt_ptr) {
12596       /* Go ahead and lock it (and its owner) before returning */
12597       sip_pvt_lock(sip_pvt_ptr);
12598       if (pedanticsipchecking) {
12599          unsigned char frommismatch = 0, tomismatch = 0;
12600 
12601          if (ast_strlen_zero(fromtag)) {
12602             sip_pvt_unlock(sip_pvt_ptr);
12603             ast_debug(4, "Matched %s call for callid=%s - no from tag specified, pedantic check fails\n",
12604                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12605             return NULL;
12606          }
12607 
12608          if (ast_strlen_zero(totag)) {
12609             sip_pvt_unlock(sip_pvt_ptr);
12610             ast_debug(4, "Matched %s call for callid=%s - no to tag specified, pedantic check fails\n",
12611                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid);
12612             return NULL;
12613          }
12614          /* RFC 3891
12615           * > 3.  User Agent Server Behavior: Receiving a Replaces Header
12616           * > The Replaces header contains information used to match an existing
12617           * > SIP dialog (call-id, to-tag, and from-tag).  Upon receiving an INVITE
12618           * > with a Replaces header, the User Agent (UA) attempts to match this
12619           * > information with a confirmed or early dialog.  The User Agent Server
12620           * > (UAS) matches the to-tag and from-tag parameters as if they were tags
12621           * > present in an incoming request.  In other words, the to-tag parameter
12622           * > is compared to the local tag, and the from-tag parameter is compared
12623           * > to the remote tag.
12624           *
12625           * Thus, the totag is always compared to the local tag, regardless if
12626           * this our call is an incoming or outgoing call.
12627           */
12628          frommismatch = !!strcmp(fromtag, sip_pvt_ptr->theirtag);
12629          tomismatch = !!strcmp(totag, sip_pvt_ptr->tag);
12630          if (frommismatch || tomismatch) {
12631             sip_pvt_unlock(sip_pvt_ptr);
12632             if (frommismatch) {
12633                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",
12634                        sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
12635                        fromtag, sip_pvt_ptr->theirtag);
12636             }
12637             if (tomismatch) {
12638                ast_debug(4, "Matched %s call for callid=%s - pedantic to tag check fails; their tag is %s our tag is %s\n",
12639                     sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING", sip_pvt_ptr->callid, 
12640                     totag, sip_pvt_ptr->tag);
12641             }
12642             return NULL;
12643          }
12644       }
12645       
12646       if (totag)
12647          ast_debug(4, "Matched %s call - their tag is %s Our tag is %s\n",
12648                  sip_pvt_ptr->outgoing_call == TRUE ? "OUTGOING": "INCOMING",
12649                  sip_pvt_ptr->theirtag, sip_pvt_ptr->tag);
12650 
12651       /* deadlock avoidance... */
12652       while (sip_pvt_ptr->owner && ast_channel_trylock(sip_pvt_ptr->owner)) {
12653          sip_pvt_unlock(sip_pvt_ptr);
12654          usleep(1);
12655          sip_pvt_lock(sip_pvt_ptr);
12656       }
12657    }
12658    
12659    return sip_pvt_ptr;
12660 }
12661 
12662 /*! \brief Call transfer support (the REFER method) 
12663  *    Extracts Refer headers into pvt dialog structure */
12664 static int get_refer_info(struct sip_pvt *transferer, struct sip_request *outgoing_req)
12665 {
12666 
12667    const char *p_referred_by = NULL;
12668    char *h_refer_to = NULL; 
12669    char *h_referred_by = NULL;
12670    char *refer_to;
12671    const char *p_refer_to;
12672    char *referred_by_uri = NULL;
12673    char *ptr;
12674    struct sip_request *req = NULL;
12675    const char *transfer_context = NULL;
12676    struct sip_refer *referdata;
12677 
12678 
12679    req = outgoing_req;
12680    referdata = transferer->refer;
12681 
12682    if (!req)
12683       req = &transferer->initreq;
12684 
12685    p_refer_to = get_header(req, "Refer-To");
12686    if (ast_strlen_zero(p_refer_to)) {
12687       ast_log(LOG_WARNING, "Refer-To Header missing. Skipping transfer.\n");
12688       return -2;  /* Syntax error */
12689    }
12690    h_refer_to = ast_strdupa(p_refer_to);
12691    refer_to = get_in_brackets(h_refer_to);
12692    if (pedanticsipchecking)
12693       ast_uri_decode(refer_to);
12694 
12695    if (!strncasecmp(refer_to, "sip:", 4)) {
12696       refer_to += 4;       /* Skip sip: */
12697    } else if (!strncasecmp(refer_to, "sips:", 5)) {
12698       refer_to += 5;
12699    } else {
12700       ast_log(LOG_WARNING, "Can't transfer to non-sip: URI.  (Refer-to: %s)?\n", refer_to);
12701       return -3;
12702    }
12703 
12704    /* Get referred by header if it exists */
12705    p_referred_by = get_header(req, "Referred-By");
12706 
12707    /* Give useful transfer information to the dialplan */
12708    if (transferer->owner) {
12709       struct ast_channel *peer = ast_bridged_channel(transferer->owner);
12710       if (peer) {
12711          pbx_builtin_setvar_helper(peer, "SIPREFERRINGCONTEXT", transferer->context);
12712          pbx_builtin_setvar_helper(peer, "SIPREFERREDBYHDR", p_referred_by);
12713       }
12714    }
12715 
12716    if (!ast_strlen_zero(p_referred_by)) {
12717       char *lessthan;
12718       h_referred_by = ast_strdupa(p_referred_by);
12719       if (pedanticsipchecking)
12720          ast_uri_decode(h_referred_by);
12721 
12722       /* Store referrer's caller ID name */
12723       ast_copy_string(referdata->referred_by_name, h_referred_by, sizeof(referdata->referred_by_name));
12724       if ((lessthan = strchr(referdata->referred_by_name, '<'))) {
12725          *(lessthan - 1) = '\0'; /* Space */
12726       }
12727 
12728       referred_by_uri = get_in_brackets(h_referred_by);
12729       if (!strncasecmp(referred_by_uri, "sip:", 4)) {
12730          referred_by_uri += 4;      /* Skip sip: */
12731       } else if (!strncasecmp(referred_by_uri, "sips:", 5)) {
12732          referred_by_uri += 5;      /* Skip sips: */
12733       } else {
12734          ast_log(LOG_WARNING, "Huh?  Not a sip: header (Referred-by: %s). Skipping.\n", referred_by_uri);
12735          referred_by_uri = NULL;
12736       }
12737    }
12738 
12739    /* Check for arguments in the refer_to header */
12740    if ((ptr = strcasestr(refer_to, "replaces="))) {
12741       char *to = NULL, *from = NULL;
12742       
12743       /* This is an attended transfer */
12744       referdata->attendedtransfer = 1;
12745       ast_copy_string(referdata->replaces_callid, ptr+9, sizeof(referdata->replaces_callid));
12746       ast_uri_decode(referdata->replaces_callid);
12747       if ((ptr = strchr(referdata->replaces_callid, ';')))  /* Find options */ {
12748          *ptr++ = '\0';
12749       }
12750       
12751       if (ptr) {
12752          /* Find the different tags before we destroy the string */
12753          to = strcasestr(ptr, "to-tag=");
12754          from = strcasestr(ptr, "from-tag=");
12755       }
12756       
12757       /* Grab the to header */
12758       if (to) {
12759          ptr = to + 7;
12760          if ((to = strchr(ptr, '&')))
12761             *to = '\0';
12762          if ((to = strchr(ptr, ';')))
12763             *to = '\0';
12764          ast_copy_string(referdata->replaces_callid_totag, ptr, sizeof(referdata->replaces_callid_totag));
12765       }
12766       
12767       if (from) {
12768          ptr = from + 9;
12769          if ((to = strchr(ptr, '&')))
12770             *to = '\0';
12771          if ((to = strchr(ptr, ';')))
12772             *to = '\0';
12773          ast_copy_string(referdata->replaces_callid_fromtag, ptr, sizeof(referdata->replaces_callid_fromtag));
12774       }
12775       
12776       if (!pedanticsipchecking)
12777          ast_debug(2, "Attended transfer: Will use Replace-Call-ID : %s (No check of from/to tags)\n", referdata->replaces_callid );
12778       else
12779          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>" );
12780    }
12781    
12782    if ((ptr = strchr(refer_to, '@'))) {   /* Separate domain */
12783       char *urioption = NULL, *domain;
12784       *ptr++ = '\0';
12785 
12786       if ((urioption = strchr(ptr, ';'))) /* Separate urioptions */
12787          *urioption++ = '\0';
12788       
12789       domain = ptr;
12790       if ((ptr = strchr(domain, ':'))) /* Remove :port */
12791          *ptr = '\0';
12792       
12793       /* Save the domain for the dial plan */
12794       ast_copy_string(referdata->refer_to_domain, domain, sizeof(referdata->refer_to_domain));
12795       if (urioption)
12796          ast_copy_string(referdata->refer_to_urioption, urioption, sizeof(referdata->refer_to_urioption));
12797    }
12798 
12799    if ((ptr = strchr(refer_to, ';')))  /* Remove options */
12800       *ptr = '\0';
12801    ast_copy_string(referdata->refer_to, refer_to, sizeof(referdata->refer_to));
12802    
12803    if (referred_by_uri) {
12804       if ((ptr = strchr(referred_by_uri, ';')))    /* Remove options */
12805          *ptr = '\0';
12806       ast_copy_string(referdata->referred_by, referred_by_uri, sizeof(referdata->referred_by));
12807    } else {
12808       referdata->referred_by[0] = '\0';
12809    }
12810 
12811    /* Determine transfer context */
12812    if (transferer->owner)  /* Mimic behaviour in res_features.c */
12813       transfer_context = pbx_builtin_getvar_helper(transferer->owner, "TRANSFER_CONTEXT");
12814 
12815    /* By default, use the context in the channel sending the REFER */
12816    if (ast_strlen_zero(transfer_context)) {
12817       transfer_context = S_OR(transferer->owner->macrocontext,
12818                S_OR(transferer->context, default_context));
12819    }
12820 
12821    ast_copy_string(referdata->refer_to_context, transfer_context, sizeof(referdata->refer_to_context));
12822    
12823    /* Either an existing extension or the parking extension */
12824    if (referdata->attendedtransfer || ast_exists_extension(NULL, transfer_context, refer_to, 1, NULL) ) {
12825       if (sip_debug_test_pvt(transferer)) {
12826          ast_verbose("SIP transfer to extension %s@%s by %s\n", refer_to, transfer_context, referred_by_uri);
12827       }
12828       /* We are ready to transfer to the extension */
12829       return 0;
12830    } 
12831    if (sip_debug_test_pvt(transferer))
12832       ast_verbose("Failed SIP Transfer to non-existing extension %s in context %s\n n", refer_to, transfer_context);
12833 
12834    /* Failure, we can't find this extension */
12835    return -1;
12836 }
12837 
12838 
12839 /*! \brief Call transfer support (old way, deprecated by the IETF)--*/
12840 static int get_also_info(struct sip_pvt *p, struct sip_request *oreq)
12841 {
12842    char tmp[256] = "", *c, *a;
12843    struct sip_request *req = oreq ? oreq : &p->initreq;
12844    struct sip_refer *referdata = NULL;
12845    const char *transfer_context = NULL;
12846    
12847    if (!p->refer && !sip_refer_allocate(p))
12848       return -1;
12849 
12850    referdata = p->refer;
12851 
12852    ast_copy_string(tmp, get_header(req, "Also"), sizeof(tmp));
12853    c = get_in_brackets(tmp);
12854 
12855    if (pedanticsipchecking)
12856       ast_uri_decode(c);
12857 
12858    if (!strncasecmp(c, "sip:", 4)) {
12859       c += 4;
12860    } else if (!strncasecmp(c, "sips:", 5)) {
12861       c += 5;
12862    } else {
12863       ast_log(LOG_WARNING, "Huh?  Not a SIP header in Also: transfer (%s)?\n", c);
12864       return -1;
12865    }
12866 
12867    if ((a = strchr(c, ';')))  /* Remove arguments */
12868       *a = '\0';
12869    
12870    if ((a = strchr(c, '@'))) {   /* Separate Domain */
12871       *a++ = '\0';
12872       ast_copy_string(referdata->refer_to_domain, a, sizeof(referdata->refer_to_domain));
12873    }
12874    
12875    if (sip_debug_test_pvt(p))
12876       ast_verbose("Looking for %s in %s\n", c, p->context);
12877 
12878    if (p->owner)  /* Mimic behaviour in res_features.c */
12879       transfer_context = pbx_builtin_getvar_helper(p->owner, "TRANSFER_CONTEXT");
12880 
12881    /* By default, use the context in the channel sending the REFER */
12882    if (ast_strlen_zero(transfer_context)) {
12883       transfer_context = S_OR(p->owner->macrocontext,
12884                S_OR(p->context, default_context));
12885    }
12886    if (ast_exists_extension(NULL, transfer_context, c, 1, NULL)) {
12887       /* This is a blind transfer */
12888       ast_debug(1, "SIP Bye-also transfer to Extension %s@%s \n", c, transfer_context);
12889       ast_copy_string(referdata->refer_to, c, sizeof(referdata->refer_to));
12890       ast_copy_string(referdata->referred_by, "", sizeof(referdata->referred_by));
12891       ast_copy_string(referdata->refer_contact, "", sizeof(referdata->refer_contact));
12892       referdata->refer_call = dialog_unref(referdata->refer_call, "unreffing referdata->refer_call");
12893       /* Set new context */
12894       ast_string_field_set(p, context, transfer_context);
12895       return 0;
12896    } else if (ast_canmatch_extension(NULL, p->context, c, 1, NULL)) {
12897       return 1;
12898    }
12899 
12900    return -1;
12901 }
12902 
12903 /*! \brief check received= and rport= in a SIP response.
12904  * If we get a response with received= and/or rport= in the Via:
12905  * line, use them as 'p->ourip' (see RFC 3581 for rport,
12906  * and RFC 3261 for received).
12907  * Using these two fields SIP can produce the correct
12908  * address and port in the SIP headers without the need for STUN.
12909  * The address part is also reused for the media sessions.
12910  * Note that ast_sip_ouraddrfor() still rewrites p->ourip
12911  * if you specify externip/seternaddr/stunaddr.
12912  */
12913 static attribute_unused void check_via_response(struct sip_pvt *p, struct sip_request *req)
12914 {
12915    char via[256];
12916    char *cur, *opts;
12917 
12918    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12919 
12920    /* Work on the leftmost value of the topmost Via header */
12921    opts = strchr(via, ',');
12922    if (opts)
12923       *opts = '\0';
12924 
12925    /* parse all relevant options */
12926    opts = strchr(via, ';');
12927    if (!opts)
12928       return;  /* no options to parse */
12929    *opts++ = '\0';
12930    while ( (cur = strsep(&opts, ";")) ) {
12931       if (!strncmp(cur, "rport=", 6)) {
12932          int port = strtol(cur+6, NULL, 10);
12933          /* XXX add error checking */
12934          p->ourip.sin_port = ntohs(port);
12935       } else if (!strncmp(cur, "received=", 9)) {
12936          if (ast_parse_arg(cur+9, PARSE_INADDR, &p->ourip))
12937             ;  /* XXX add error checking */
12938       }
12939    }
12940 }
12941 
12942 /*! \brief check Via: header for hostname, port and rport request/answer */
12943 static void check_via(struct sip_pvt *p, struct sip_request *req)
12944 {
12945    char via[512];
12946    char *c, *pt, *maddr;
12947    struct hostent *hp;
12948    struct ast_hostent ahp;
12949 
12950    ast_copy_string(via, get_header(req, "Via"), sizeof(via));
12951 
12952    /* Work on the leftmost value of the topmost Via header */
12953    c = strchr(via, ',');
12954    if (c)
12955       *c = '\0';
12956 
12957    /* Check for rport */
12958    c = strstr(via, ";rport");
12959    if (c && (c[6] != '=')) /* rport query, not answer */
12960       ast_set_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT);
12961 
12962    /* Check for maddr */
12963    maddr = strstr(via, "maddr=");
12964    if (maddr) {
12965       maddr += 6;
12966       c = maddr + strspn(maddr, "0123456789.");
12967       *c = '\0';
12968    }
12969 
12970    c = strchr(via, ';');
12971    if (c)
12972       *c = '\0';
12973 
12974    c = strchr(via, ' ');
12975    if (c) {
12976       *c = '\0';
12977       c = ast_skip_blanks(c+1);
12978       if (strcasecmp(via, "SIP/2.0/UDP") && strcasecmp(via, "SIP/2.0/TCP") && strcasecmp(via, "SIP/2.0/TLS")) {
12979          ast_log(LOG_WARNING, "Don't know how to respond via '%s'\n", via);
12980          return;
12981       }
12982       pt = strchr(c, ':');
12983       if (pt)
12984          *pt++ = '\0';  /* remember port pointer */
12985       /* Use maddr if found */
12986       if (maddr)
12987          c = maddr;
12988       hp = ast_gethostbyname(c, &ahp);
12989       if (!hp) {
12990          ast_log(LOG_WARNING, "'%s' is not a valid host\n", c);
12991          return;
12992       }
12993       memset(&p->sa, 0, sizeof(p->sa));
12994       p->sa.sin_family = AF_INET;
12995       memcpy(&p->sa.sin_addr, hp->h_addr, sizeof(p->sa.sin_addr));
12996       p->sa.sin_port = htons(port_str2int(pt, STANDARD_SIP_PORT));
12997 
12998       if (sip_debug_test_pvt(p)) {
12999          const struct sockaddr_in *dst = sip_real_dst(p);
13000          ast_verbose("Sending to %s : %d (%s)\n", ast_inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), sip_nat_mode(p));
13001       }
13002    }
13003 }
13004 
13005 /*! \brief  Get caller id name from SIP headers */
13006 static char *get_calleridname(const char *input, char *output, size_t outputsize)
13007 {
13008    const char *end = strchr(input, '<');  /* first_bracket */
13009    const char *tmp = strchr(input, '"');  /* first quote */
13010    int bytes = 0;
13011    int maxbytes = outputsize - 1;
13012 
13013    if (!end || end == input)  /* we require a part in brackets */
13014       return NULL;
13015 
13016    end--; /* move just before "<" */
13017 
13018    if (tmp && tmp <= end) {
13019       /* The quote (tmp) precedes the bracket (end+1).
13020        * Find the matching quote and return the content.
13021        */
13022       end = strchr(tmp+1, '"');
13023       if (!end)
13024          return NULL;
13025       bytes = (int) (end - tmp);
13026       /* protect the output buffer */
13027       if (bytes > maxbytes)
13028          bytes = maxbytes;
13029       ast_copy_string(output, tmp + 1, bytes);
13030    } else {
13031       /* No quoted string, or it is inside brackets. */
13032       /* clear the empty characters in the begining*/
13033       input = ast_skip_blanks(input);
13034       /* clear the empty characters in the end */
13035       while(*end && *end < 33 && end > input)
13036          end--;
13037       if (end >= input) {
13038          bytes = (int) (end - input) + 2;
13039          /* protect the output buffer */
13040          if (bytes > maxbytes)
13041             bytes = maxbytes;
13042          ast_copy_string(output, input, bytes);
13043       } else
13044          return NULL;
13045    }
13046    return output;
13047 }
13048 
13049 /*! \brief  Get caller id number from Remote-Party-ID header field 
13050  * Returns true if number should be restricted (privacy setting found)
13051  * output is set to NULL if no number found
13052  */
13053 static int get_rpid_num(const char *input, char *output, int maxlen)
13054 {
13055    char *start;
13056    char *end;
13057 
13058    start = strchr(input, ':');
13059    if (!start) {
13060       output[0] = '\0';
13061       return 0;
13062    }
13063    start++;
13064 
13065    /* we found "number" */
13066    ast_copy_string(output, start, maxlen);
13067    output[maxlen-1] = '\0';
13068 
13069    end = strchr(output, '@');
13070    if (end)
13071       *end = '\0';
13072    else
13073       output[0] = '\0';
13074    if (strstr(input, "privacy=full") || strstr(input, "privacy=uri"))
13075       return AST_PRES_PROHIB_USER_NUMBER_NOT_SCREENED;
13076 
13077    return 0;
13078 }
13079 
13080 /*!
13081  * duplicate a list of channel variables, \return the copy.
13082  */
13083 static struct ast_variable *copy_vars(struct ast_variable *src)
13084 {
13085    struct ast_variable *res = NULL, *tmp, *v = NULL;
13086 
13087    for (v = src ; v ; v = v->next) {
13088       if ((tmp = ast_variable_new(v->name, v->value, v->file))) {
13089          tmp->next = res;
13090          res = tmp;
13091       }
13092    }
13093    return res;
13094 }
13095 
13096 /*! \brief helper function for check_{user|peer}_ok() */
13097 static void replace_cid(struct sip_pvt *p, const char *rpid_num, const char *calleridname)
13098 {
13099    /* replace callerid if rpid found, and not restricted */
13100    if (!ast_strlen_zero(rpid_num) && ast_test_flag(&p->flags[0], SIP_TRUSTRPID)) {
13101       char *tmp = ast_strdupa(rpid_num); /* XXX the copy can be done later */
13102       if (!ast_strlen_zero(calleridname))
13103          ast_string_field_set(p, cid_name, calleridname);
13104       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13105          ast_shrink_phone_number(tmp);
13106       ast_string_field_set(p, cid_num, tmp);
13107    }
13108 }
13109 
13110 /*! \brief Validate device authentication */
13111 static enum check_auth_result check_peer_ok(struct sip_pvt *p, char *of,
13112    struct sip_request *req, int sipmethod, struct sockaddr_in *sin,
13113    struct sip_peer **authpeer,
13114    enum xmittype reliable,
13115    char *rpid_num, char *calleridname, char *uri2)
13116 {
13117    enum check_auth_result res;
13118    int debug=sip_debug_test_addr(sin);
13119    struct sip_peer *peer;
13120 
13121    if (sipmethod == SIP_SUBSCRIBE) {
13122       /* For subscribes, match on device name only; for other methods,
13123       * match on IP address-port of the incoming request.
13124       */
13125       peer = find_peer(of, NULL, TRUE, FINDALLDEVICES, FALSE, 0);
13126    } else {
13127       /* First find devices based on username (avoid all type=peer's) */
13128       peer = find_peer(of, NULL, TRUE, FINDUSERS, FALSE, 0);
13129 
13130       /* Then find devices based on IP */
13131       if (!peer) {
13132          peer = find_peer(NULL, &p->recv, TRUE, FINDPEERS, FALSE, p->socket.type);
13133       }
13134    }
13135 
13136    if (!peer) {
13137       if (debug)
13138          ast_verbose("No matching peer for '%s' from '%s:%d'\n",
13139             of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13140       return AUTH_DONT_KNOW;
13141    }
13142    if (!ast_apply_ha(peer->ha, sin)) {
13143       ast_debug(2, "Found peer '%s' for '%s', but fails host access\n", peer->name, of);
13144       unref_peer(peer, "unref_peer: check_peer_ok: from find_peer call, early return of AUTH_ACL_FAILED");
13145       return AUTH_ACL_FAILED;
13146    }
13147    if (debug)
13148       ast_verbose("Found peer '%s' for '%s' from %s:%d\n",
13149          peer->name, of, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
13150 
13151    /* XXX what about p->prefs = peer->prefs; ? */
13152    /* Set Frame packetization */
13153    if (p->rtp) {
13154       ast_rtp_codec_setpref(p->rtp, &peer->prefs);
13155       p->autoframing = peer->autoframing;
13156    }
13157 
13158    /* Take the peer */
13159    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
13160    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
13161 
13162    if (ast_test_flag(&p->flags[1], SIP_PAGE2_T38SUPPORT) && p->udptl) {
13163       p->t38_maxdatagram = peer->t38_maxdatagram;
13164       set_t38_capabilities(p);
13165    }
13166 
13167    /* Copy SIP extensions profile to peer */
13168    /* XXX is this correct before a successful auth ? */
13169    if (p->sipoptions)
13170       peer->sipoptions = p->sipoptions;
13171 
13172    replace_cid(p, rpid_num, calleridname);
13173    do_setnat(p, ast_test_flag(&p->flags[0], SIP_NAT_ROUTE));
13174 
13175    ast_string_field_set(p, peersecret, peer->secret);
13176    ast_string_field_set(p, peermd5secret, peer->md5secret);
13177    ast_string_field_set(p, subscribecontext, peer->subscribecontext);
13178    ast_string_field_set(p, mohinterpret, peer->mohinterpret);
13179    ast_string_field_set(p, mohsuggest, peer->mohsuggest);
13180    ast_string_field_set(p, parkinglot, peer->parkinglot);
13181    if (peer->callingpres)  /* Peer calling pres setting will override RPID */
13182       p->callingpres = peer->callingpres;
13183    if (peer->maxms && peer->lastms)
13184       p->timer_t1 = peer->lastms < global_t1min ? global_t1min : peer->lastms;
13185    else
13186       p->timer_t1 = peer->timer_t1;
13187  
13188    /* Set timer B to control transaction timeouts */
13189    if (peer->timer_b)
13190       p->timer_b = peer->timer_b;
13191    else
13192       p->timer_b = 64 * p->timer_t1;
13193  
13194    if (ast_test_flag(&peer->flags[0], SIP_INSECURE_INVITE)) {
13195       /* Pretend there is no required authentication */
13196       ast_string_field_set(p, peersecret, NULL);
13197       ast_string_field_set(p, peermd5secret, NULL);
13198    }
13199    if (!(res = check_auth(p, req, peer->name, p->peersecret, p->peermd5secret, sipmethod, uri2, reliable, req->ignore))) {
13200       ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
13201       ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
13202       /* If we have a call limit, set flag */
13203       if (peer->call_limit)
13204          ast_set_flag(&p->flags[0], SIP_CALL_LIMIT);
13205       ast_string_field_set(p, peername, peer->name);
13206       ast_string_field_set(p, authname, peer->name);
13207 
13208       if (sipmethod == SIP_INVITE) {
13209          /* copy channel vars */
13210          p->chanvars = copy_vars(peer->chanvars);
13211       }
13212 
13213       if (authpeer) {
13214          ao2_t_ref(peer, 1, "copy pointer into (*authpeer)");
13215          (*authpeer) = peer;  /* Add a ref to the object here, to keep it in memory a bit longer if it is realtime */
13216       }
13217 
13218       if (!ast_strlen_zero(peer->username)) {
13219          ast_string_field_set(p, username, peer->username);
13220          /* Use the default username for authentication on outbound calls */
13221          /* XXX this takes the name from the caller... can we override ? */
13222          ast_string_field_set(p, authname, peer->username);
13223       }
13224       if (!ast_strlen_zero(peer->cid_num)) {
13225          char *tmp = ast_strdupa(peer->cid_num);
13226          if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13227             ast_shrink_phone_number(tmp);
13228          ast_string_field_set(p, cid_num, tmp);
13229       }
13230       if (!ast_strlen_zero(peer->cid_name)) 
13231          ast_string_field_set(p, cid_name, peer->cid_name);
13232       ast_string_field_set(p, fullcontact, peer->fullcontact);
13233       if (!ast_strlen_zero(peer->context))
13234          ast_string_field_set(p, context, peer->context);
13235       ast_string_field_set(p, peersecret, peer->secret);
13236       ast_string_field_set(p, peermd5secret, peer->md5secret);
13237       ast_string_field_set(p, language, peer->language);
13238       ast_string_field_set(p, accountcode, peer->accountcode);
13239       p->amaflags = peer->amaflags;
13240       p->callgroup = peer->callgroup;
13241       p->pickupgroup = peer->pickupgroup;
13242       p->capability = peer->capability;
13243       p->prefs = peer->prefs;
13244       p->jointcapability = peer->capability;
13245       if (p->peercapability)
13246          p->jointcapability &= p->peercapability;
13247       p->maxcallbitrate = peer->maxcallbitrate;
13248       if (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS) &&
13249             (!ast_test_flag(&p->flags[1], SIP_PAGE2_VIDEOSUPPORT) ||
13250                !(p->capability & AST_FORMAT_VIDEO_MASK)) &&
13251             p->vrtp) {
13252          ast_rtp_destroy(p->vrtp);
13253          p->vrtp = NULL;
13254       }
13255       if ((!ast_test_flag(&p->flags[1], SIP_PAGE2_TEXTSUPPORT) || !(p->capability & AST_FORMAT_TEXT_MASK)) && p->trtp) {
13256          ast_rtp_destroy(p->trtp);
13257          p->trtp = NULL;
13258       }
13259       if ((ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833) ||
13260           (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_AUTO))
13261          p->noncodeccapability |= AST_RTP_DTMF;
13262       else
13263          p->noncodeccapability &= ~AST_RTP_DTMF;
13264       p->jointnoncodeccapability = p->noncodeccapability;
13265    }
13266    unref_peer(peer, "check_peer_ok: unref_peer: tossing temp ptr to peer from find_peer");
13267    return res;
13268 }
13269 
13270 
13271 /*! \brief  Check if matching user or peer is defined 
13272    Match user on From: user name and peer on IP/port
13273    This is used on first invite (not re-invites) and subscribe requests 
13274     \return 0 on success, non-zero on failure
13275 */
13276 static enum check_auth_result check_user_full(struct sip_pvt *p, struct sip_request *req,
13277                      int sipmethod, char *uri, enum xmittype reliable,
13278                      struct sockaddr_in *sin, struct sip_peer **authpeer)
13279 {
13280    char from[256];
13281    char *dummy;   /* dummy return value for parse_uri */
13282    char *domain;  /* dummy return value for parse_uri */
13283    char *of;
13284    char rpid_num[50];
13285    const char *rpid;
13286    enum check_auth_result res;
13287    char calleridname[50];
13288    char *uri2 = ast_strdupa(uri);
13289 
13290    terminate_uri(uri2); /* trim extra stuff */
13291 
13292    ast_copy_string(from, get_header(req, "From"), sizeof(from));
13293    if (pedanticsipchecking)
13294       ast_uri_decode(from);
13295    /* XXX here tries to map the username for invite things */
13296    memset(calleridname, 0, sizeof(calleridname));
13297    get_calleridname(from, calleridname, sizeof(calleridname));
13298    if (calleridname[0])
13299       ast_string_field_set(p, cid_name, calleridname);
13300 
13301    rpid = get_header(req, "Remote-Party-ID");
13302    memset(rpid_num, 0, sizeof(rpid_num));
13303    if (!ast_strlen_zero(rpid)) 
13304       p->callingpres = get_rpid_num(rpid, rpid_num, sizeof(rpid_num));
13305 
13306    of = get_in_brackets(from);
13307    if (ast_strlen_zero(p->exten)) {
13308       char *t = uri2;
13309       if (!strncasecmp(t, "sip:", 4))
13310          t+= 4;
13311       else if (!strncasecmp(t, "sips:", 5))
13312          t += 5;
13313       ast_string_field_set(p, exten, t);
13314       t = strchr(p->exten, '@');
13315       if (t)
13316          *t = '\0';
13317       if (ast_strlen_zero(p->our_contact))
13318          build_contact(p);
13319    }
13320    /* save the URI part of the From header */
13321    ast_string_field_set(p, from, of);
13322 
13323 
13324    /* ignore all fields but name */
13325    if (parse_uri(of, "sip:,sips:", &of, &dummy, &domain, &dummy, &dummy, NULL)) {
13326       ast_log(LOG_NOTICE, "From address missing 'sip:', using it anyway\n");
13327    }
13328 
13329    if (ast_strlen_zero(of)) {
13330       /* XXX note: the original code considered a missing @host
13331        * as a username-only URI. The SIP RFC (19.1.1) says that
13332        * this is wrong, and it should be considered as a domain-only URI.
13333        * For backward compatibility, we keep this block, but it is
13334        * really a mistake and should go away.
13335        */
13336       of = domain;
13337    } else {
13338       char *tmp = ast_strdupa(of);
13339       /* We need to be able to handle auth-headers looking like
13340          <sip:8164444422;phone-context=+1@1.2.3.4:5060;user=phone;tag=SDadkoa01-gK0c3bdb43>
13341       */
13342       tmp = strsep(&tmp, ";");
13343       if (global_shrinkcallerid && ast_is_shrinkable_phonenumber(tmp))
13344          ast_shrink_phone_number(tmp);
13345       ast_string_field_set(p, cid_num, tmp);
13346    }
13347 
13348    if (global_match_auth_username) {
13349       /*
13350        * XXX This is experimental code to grab the search key from the
13351        * Auth header's username instead of the 'From' name, if available.
13352        * Do not enable this block unless you understand the side effects (if any!)
13353        * Note, the search for "username" should be done in a more robust way.
13354        * Note2, at the moment we check both fields, though maybe we should
13355        * pick one or another depending on the request ? XXX
13356        */
13357       const char *hdr = get_header(req, "Authorization");
13358       if (ast_strlen_zero(hdr))
13359          hdr = get_header(req, "Proxy-Authorization");
13360 
13361       if ( !ast_strlen_zero(hdr) && (hdr = strstr(hdr, "username=\"")) ) {
13362          ast_copy_string(from, hdr + strlen("username=\""), sizeof(from));
13363          of = from;
13364          of = strsep(&of, "\"");
13365       }
13366    }
13367 
13368    res = check_peer_ok(p, of, req, sipmethod, sin,
13369          authpeer, reliable, rpid_num, calleridname, uri2);
13370    if (res != AUTH_DONT_KNOW)
13371       return res;
13372 
13373    /* Finally, apply the guest policy */
13374    if (global_allowguest) {
13375       replace_cid(p, rpid_num, calleridname);
13376       res = AUTH_SUCCESSFUL;
13377    } else if (global_alwaysauthreject)
13378       res = AUTH_FAKE_AUTH; /* reject with fake authorization request */
13379    else
13380       res = AUTH_SECRET_FAILED; /* we don't want any guests, authentication will fail */
13381 
13382 
13383    if (ast_test_flag(&p->flags[1], SIP_PAGE2_RPORT_PRESENT)) {
13384       ast_set_flag(&p->flags[0], SIP_NAT_ROUTE);
13385    }
13386 
13387    return res;
13388 }
13389 
13390 /*! \brief  Find user 
13391    If we get a match, this will add a reference pointer to the user object in ASTOBJ, that needs to be unreferenced
13392 */
13393 static int check_user(struct sip_pvt *p, struct sip_request *req, int sipmethod, char *uri, enum xmittype reliable, struct sockaddr_in *sin)
13394 {
13395    return check_user_full(p, req, sipmethod, uri, reliable, sin, NULL);
13396 }
13397 
13398 /*! \brief  Get text out of a SIP MESSAGE packet */
13399 static int get_msg_text(char *buf, int len, struct sip_request *req, int addnewline)
13400 {
13401    int x;
13402    int y;
13403 
13404    buf[0] = '\0';
13405    /*XXX isn't strlen(buf) going to always be 0? */
13406    y = len - strlen(buf) - 5;
13407    if (y < 0)
13408       y = 0;
13409    for (x = 0; x < req->lines; x++) {
13410       char *line = REQ_OFFSET_TO_STR(req, line[x]);
13411       strncat(buf, line, y); /* safe */
13412       y -= strlen(line) + 1;
13413       if (y < 0)
13414          y = 0;
13415       if (y != 0 && addnewline)
13416          strcat(buf, "\n"); /* safe */
13417    }
13418    return 0;
13419 }
13420 
13421 
13422 /*! \brief  Receive SIP MESSAGE method messages
13423 \note We only handle messages within current calls currently 
13424    Reference: RFC 3428 */
13425 static void receive_message(struct sip_pvt *p, struct sip_request *req)
13426 {
13427    char buf[1400];   
13428    struct ast_frame f;
13429    const char *content_type = get_header(req, "Content-Type");
13430 
13431    if (strncmp(content_type, "text/plain", strlen("text/plain"))) { /* No text/plain attachment */
13432       transmit_response(p, "415 Unsupported Media Type", req); /* Good enough, or? */
13433       if (!p->owner)
13434          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13435       return;
13436    }
13437 
13438    if (get_msg_text(buf, sizeof(buf), req, FALSE)) {
13439       ast_log(LOG_WARNING, "Unable to retrieve text from %s\n", p->callid);
13440       transmit_response(p, "202 Accepted", req);
13441       if (!p->owner)
13442          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13443       return;
13444    }
13445 
13446    if (p->owner) {
13447       if (sip_debug_test_pvt(p))
13448          ast_verbose("SIP Text message received: '%s'\n", buf);
13449       memset(&f, 0, sizeof(f));
13450       f.frametype = AST_FRAME_TEXT;
13451       f.subclass = 0;
13452       f.offset = 0;
13453       f.data.ptr = buf;
13454       f.datalen = strlen(buf);
13455       ast_queue_frame(p->owner, &f);
13456       transmit_response(p, "202 Accepted", req); /* We respond 202 accepted, since we relay the message */
13457       return;
13458    }
13459 
13460    /* Message outside of a call, we do not support that */
13461    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);
13462    transmit_response(p, "405 Method Not Allowed", req);
13463    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
13464    return;
13465 }
13466 
13467 /*! \brief  CLI Command to show calls within limits set by call_limit */
13468 static char *sip_show_inuse(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13469 {
13470 #define FORMAT "%-25.25s %-15.15s %-15.15s \n"
13471 #define FORMAT2 "%-25.25s %-15.15s %-15.15s \n"
13472    char ilimits[40];
13473    char iused[40];
13474    int showall = FALSE;
13475    struct ao2_iterator i;
13476    struct sip_peer *peer;
13477    
13478    switch (cmd) {
13479    case CLI_INIT:
13480       e->command = "sip show inuse";
13481       e->usage =
13482          "Usage: sip show inuse [all]\n"
13483          "       List all SIP devices usage counters and limits.\n"
13484          "       Add option \"all\" to show all devices, not only those with a limit.\n";
13485       return NULL;
13486    case CLI_GENERATE:
13487       return NULL;
13488    }
13489 
13490    if (a->argc < 3) 
13491       return CLI_SHOWUSAGE;
13492 
13493    if (a->argc == 4 && !strcmp(a->argv[3], "all")) 
13494       showall = TRUE;
13495    
13496    ast_cli(a->fd, FORMAT, "* Peer name", "In use", "Limit");
13497 
13498    i = ao2_iterator_init(peers, 0);
13499    while ((peer = ao2_t_iterator_next(&i, "iterate thru peer table"))) {
13500       ao2_lock(peer);
13501       if (peer->call_limit)
13502          snprintf(ilimits, sizeof(ilimits), "%d", peer->call_limit);
13503       else 
13504          ast_copy_string(ilimits, "N/A", sizeof(ilimits));
13505       snprintf(iused, sizeof(iused), "%d/%d/%d", peer->inUse, peer->inRinging, peer->onHold);
13506       if (showall || peer->call_limit)
13507          ast_cli(a->fd, FORMAT2, peer->name, iused, ilimits);
13508       ao2_unlock(peer);
13509       unref_peer(peer, "toss iterator pointer");
13510    }
13511    ao2_iterator_destroy(&i);
13512 
13513    return CLI_SUCCESS;
13514 #undef FORMAT
13515 #undef FORMAT2
13516 }
13517 
13518 
13519 /*! \brief Convert transfer mode to text string */
13520 static char *transfermode2str(enum transfermodes mode)
13521 {
13522    if (mode == TRANSFER_OPENFORALL)
13523       return "open";
13524    else if (mode == TRANSFER_CLOSED)
13525       return "closed";
13526    return "strict";
13527 }
13528 
13529 static struct _map_x_s natmodes[] = {
13530    { SIP_NAT_NEVER,        "No"},
13531    { SIP_NAT_ROUTE,        "Route"},
13532    { SIP_NAT_ALWAYS,       "Always"},
13533    { SIP_NAT_RFC3581,      "RFC3581"},
13534    { -1,                   NULL}, /* terminator */
13535 };
13536 
13537 /*! \brief  Convert NAT setting to text string */
13538 static const char *nat2str(int nat)
13539 {
13540    return map_x_s(natmodes, nat, "Unknown");
13541 }
13542 
13543 #ifdef NOTUSED
13544 /* OEJ: This is not used, but may be useful in the future, so I don't want to 
13545    delete it. Keeping it enabled generates compiler warnings.
13546  */
13547 
13548 static struct _map_x_s natcfgmodes[] = {
13549    { SIP_NAT_NEVER,        "never"},
13550    { SIP_NAT_ROUTE,        "route"},
13551    { SIP_NAT_ALWAYS,       "yes"},
13552    { SIP_NAT_RFC3581,      "no"},
13553    { -1,                   NULL}, /* terminator */
13554 };
13555 
13556 /*! \brief  Convert NAT setting to text string appropriate for config files */
13557 static const char *nat2strconfig(int nat)
13558 {
13559    return map_x_s(natcfgmodes, nat, "Unknown");
13560 }
13561 #endif
13562 
13563 /*! \brief  Report Peer status in character string
13564  *  \return 0 if peer is unreachable, 1 if peer is online, -1 if unmonitored
13565  */
13566 
13567 
13568 /* Session-Timer Modes */
13569 static struct _map_x_s stmodes[] = {
13570         { SESSION_TIMER_MODE_ACCEPT,    "Accept"},
13571         { SESSION_TIMER_MODE_ORIGINATE, "Originate"},
13572         { SESSION_TIMER_MODE_REFUSE,    "Refuse"},
13573         { -1,                           NULL},
13574 };
13575 
13576 static const char *stmode2str(enum st_mode m)
13577 {
13578    return map_x_s(stmodes, m, "Unknown");
13579 }
13580 
13581 static enum st_mode str2stmode(const char *s)
13582 {
13583    return map_s_x(stmodes, s, -1);
13584 }
13585 
13586 /* Session-Timer Refreshers */
13587 static struct _map_x_s strefreshers[] = {
13588         { SESSION_TIMER_REFRESHER_AUTO,     "auto"},
13589         { SESSION_TIMER_REFRESHER_UAC,      "uac"},
13590         { SESSION_TIMER_REFRESHER_UAS,      "uas"},
13591         { -1,                               NULL},
13592 };
13593 
13594 static const char *strefresher2str(enum st_refresher r)
13595 {
13596    return map_x_s(strefreshers, r, "Unknown");
13597 }
13598 
13599 static enum st_refresher str2strefresher(const char *s)
13600 {
13601    return map_s_x(strefreshers, s, -1);
13602 }
13603 
13604 
13605 static int peer_status(struct sip_peer *peer, char *status, int statuslen)
13606 {
13607    int res = 0;
13608    if (peer->maxms) {
13609       if (peer->lastms < 0) {
13610          ast_copy_string(status, "UNREACHABLE", statuslen);
13611       } else if (peer->lastms > peer->maxms) {
13612          snprintf(status, statuslen, "LAGGED (%d ms)", peer->lastms);
13613          res = 1;
13614       } else if (peer->lastms) {
13615          snprintf(status, statuslen, "OK (%d ms)", peer->lastms);
13616          res = 1;
13617       } else {
13618          ast_copy_string(status, "UNKNOWN", statuslen);
13619       }
13620    } else { 
13621       ast_copy_string(status, "Unmonitored", statuslen);
13622       /* Checking if port is 0 */
13623       res = -1;
13624    }
13625    return res;
13626 }
13627 
13628 /*! \brief return Yes or No depending on the argument.
13629  * This is used in many places in CLI command, having a function to generate
13630  * this helps maintaining a consistent output (and possibly emitting the
13631  * output in other languages, at some point).
13632  */
13633 static const char *cli_yesno(int x)
13634 {
13635    return x ? "Yes" : "No";
13636 }
13637 
13638 /*! \brief  Show active TCP connections */
13639 static char *sip_show_tcp(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13640 {
13641    struct sip_threadinfo *th;
13642    struct ao2_iterator i;
13643 
13644 #define FORMAT2 "%-30.30s %3.6s %9.9s %6.6s\n"
13645 #define FORMAT  "%-30.30s %-6d %-9.9s %-6.6s\n"
13646 
13647    switch (cmd) {
13648    case CLI_INIT:
13649       e->command = "sip show tcp";
13650       e->usage =
13651          "Usage: sip show tcp\n"
13652          "       Lists all active TCP/TLS sessions.\n";
13653       return NULL;
13654    case CLI_GENERATE:
13655       return NULL;
13656    }
13657 
13658    if (a->argc != 3)
13659       return CLI_SHOWUSAGE;
13660 
13661    ast_cli(a->fd, FORMAT2, "Host", "Port", "Transport", "Type");
13662    i = ao2_iterator_init(threadt, 0);
13663    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
13664       ast_cli(a->fd, FORMAT, ast_inet_ntoa(th->tcptls_session->remote_address.sin_addr), 
13665          ntohs(th->tcptls_session->remote_address.sin_port), 
13666          get_transport(th->type), 
13667          (th->tcptls_session->client ? "Client" : "Server"));
13668       ao2_t_ref(th, -1, "decrement ref from iterator");
13669    }
13670    ao2_iterator_destroy(&i);
13671    return CLI_SUCCESS;
13672 #undef FORMAT
13673 #undef FORMAT2
13674 }
13675 
13676 /*! \brief  CLI Command 'SIP Show Users' */
13677 static char *sip_show_users(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13678 {
13679    regex_t regexbuf;
13680    int havepattern = FALSE;
13681    struct ao2_iterator user_iter;
13682    struct sip_peer *user;
13683 
13684 #define FORMAT  "%-25.25s  %-15.15s  %-15.15s  %-15.15s  %-5.5s%-10.10s\n"
13685 
13686    switch (cmd) {
13687    case CLI_INIT:
13688       e->command = "sip show users";
13689       e->usage =
13690          "Usage: sip show users [like <pattern>]\n"
13691          "       Lists all known SIP users.\n"
13692          "       Optional regular expression pattern is used to filter the user list.\n";
13693       return NULL;
13694    case CLI_GENERATE:
13695       return NULL;
13696    }
13697 
13698    switch (a->argc) {
13699    case 5:
13700       if (!strcasecmp(a->argv[3], "like")) {
13701          if (regcomp(&regexbuf, a->argv[4], REG_EXTENDED | REG_NOSUB))
13702             return CLI_SHOWUSAGE;
13703          havepattern = TRUE;
13704       } else
13705          return CLI_SHOWUSAGE;
13706    case 3:
13707       break;
13708    default:
13709       return CLI_SHOWUSAGE;
13710    }
13711 
13712    ast_cli(a->fd, FORMAT, "Username", "Secret", "Accountcode", "Def.Context", "ACL", "NAT");
13713 
13714    user_iter = ao2_iterator_init(peers, 0);
13715    while ((user = ao2_iterator_next(&user_iter))) {
13716       ao2_lock(user);
13717       if (!(user->type & SIP_TYPE_USER)) {
13718          ao2_unlock(user);
13719          unref_peer(user, "sip show users");
13720          continue;
13721       }
13722 
13723       if (havepattern && regexec(&regexbuf, user->name, 0, NULL, 0)) {
13724          ao2_unlock(user);
13725          unref_peer(user, "sip show users");
13726          continue;
13727       }
13728 
13729       ast_cli(a->fd, FORMAT, user->name, 
13730          user->secret, 
13731          user->accountcode,
13732          user->context,
13733          cli_yesno(user->ha != NULL),
13734          nat2str(ast_test_flag(&user->flags[0], SIP_NAT)));
13735       ao2_unlock(user);
13736       unref_peer(user, "sip show users");
13737    }
13738    ao2_iterator_destroy(&user_iter);
13739 
13740    if (havepattern)
13741       regfree(&regexbuf);
13742 
13743    return CLI_SUCCESS;
13744 #undef FORMAT
13745 }
13746 
13747 /*! \brief Manager Action SIPShowRegistry description */
13748 static char mandescr_show_registry[] =
13749 "Description: Lists all registration requests and status\n"
13750 "Registrations will follow as separate events. followed by a final event called\n"
13751 "RegistrationsComplete.\n"
13752 "Variables: \n"
13753 "  ActionID: <id>       Action ID for this transaction. Will be returned.\n";
13754 
13755 /*! \brief Show SIP registrations in the manager API */
13756 static int manager_show_registry(struct mansession *s, const struct message *m)
13757 {
13758    const char *id = astman_get_header(m, "ActionID");
13759    char idtext[256] = "";
13760    int total = 0;
13761 
13762    if (!ast_strlen_zero(id))
13763       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13764 
13765    astman_send_listack(s, m, "Registrations will follow", "start");
13766 
13767    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
13768       ASTOBJ_RDLOCK(iterator);
13769       astman_append(s,
13770          "Event: RegistryEntry\r\n"
13771          "%s"
13772          "Host: %s\r\n"
13773          "Port: %d\r\n"
13774          "Username: %s\r\n"
13775          "Refresh: %d\r\n"
13776          "State: %s\r\n"
13777          "RegistrationTime: %ld\r\n"
13778          "\r\n", idtext, iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT,
13779                  iterator->username, iterator->refresh, regstate2str(iterator->regstate), (long) iterator->regtime.tv_sec);
13780       ASTOBJ_UNLOCK(iterator);
13781       total++;
13782    } while(0));
13783 
13784    astman_append(s,
13785       "Event: RegistrationsComplete\r\n"
13786       "EventList: Complete\r\n"
13787       "ListItems: %d\r\n"
13788       "%s"
13789       "\r\n", total, idtext);
13790    
13791    return 0;
13792 }
13793 
13794 static char mandescr_show_peers[] = 
13795 "Description: Lists SIP peers in text format with details on current status.\n"
13796 "Peerlist will follow as separate events, followed by a final event called\n"
13797 "PeerlistComplete.\n"
13798 "Variables: \n"
13799 "  ActionID: <id> Action ID for this transaction. Will be returned.\n";
13800 
13801 /*! \brief  Show SIP peers in the manager API */
13802 /*    Inspired from chan_iax2 */
13803 static int manager_sip_show_peers(struct mansession *s, const struct message *m)
13804 {
13805    const char *id = astman_get_header(m, "ActionID");
13806    const char *a[] = {"sip", "show", "peers"};
13807    char idtext[256] = "";
13808    int total = 0;
13809 
13810    if (!ast_strlen_zero(id))
13811       snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13812 
13813    astman_send_listack(s, m, "Peer status list will follow", "start");
13814    /* List the peers in separate manager events */
13815    _sip_show_peers(-1, &total, s, m, 3, a);
13816    /* Send final confirmation */
13817    astman_append(s,
13818    "Event: PeerlistComplete\r\n"
13819    "EventList: Complete\r\n"
13820    "ListItems: %d\r\n"
13821    "%s"
13822    "\r\n", total, idtext);
13823    return 0;
13824 }
13825 
13826 /*! \brief  CLI Show Peers command */
13827 static char *sip_show_peers(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
13828 {
13829    switch (cmd) {
13830    case CLI_INIT:
13831       e->command = "sip show peers";
13832       e->usage =
13833          "Usage: sip show peers [like <pattern>]\n"
13834          "       Lists all known SIP peers.\n"
13835          "       Optional regular expression pattern is used to filter the peer list.\n";
13836       return NULL;
13837    case CLI_GENERATE:
13838       return NULL;
13839    }
13840 
13841    return _sip_show_peers(a->fd, NULL, NULL, NULL, a->argc, (const char **) a->argv);
13842 }
13843 
13844 int peercomparefunc(const void *a, const void *b);
13845 
13846 int peercomparefunc(const void *a, const void *b)
13847 {
13848    struct sip_peer **ap = (struct sip_peer **)a;
13849    struct sip_peer **bp = (struct sip_peer **)b;
13850    return strcmp((*ap)->name, (*bp)->name);
13851 }
13852 
13853 
13854 /*! \brief Execute sip show peers command */
13855 static char *_sip_show_peers(int fd, int *total, struct mansession *s, const struct message *m, int argc, const char *argv[])
13856 {
13857    regex_t regexbuf;
13858    int havepattern = FALSE;
13859    struct sip_peer *peer;
13860    struct ao2_iterator i;
13861    
13862 /* the last argument is left-aligned, so we don't need a size anyways */
13863 #define FORMAT2 "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8s %-10s %s\n"
13864 #define FORMAT  "%-25.25s  %-15.15s %-3.3s %-3.3s %-3.3s %-8d %-10s %s\n"
13865 
13866    char name[256];
13867    int total_peers = 0;
13868    int peers_mon_online = 0;
13869    int peers_mon_offline = 0;
13870    int peers_unmon_offline = 0;
13871    int peers_unmon_online = 0;
13872    const char *id;
13873    char idtext[256] = "";
13874    int realtimepeers;
13875    int objcount = ao2_container_count(peers);
13876    struct sip_peer **peerarray;
13877    int k;
13878    
13879    
13880    realtimepeers = ast_check_realtime("sippeers");
13881    peerarray = ast_calloc(sizeof(struct sip_peer *), objcount);
13882 
13883    if (s) { /* Manager - get ActionID */
13884       id = astman_get_header(m, "ActionID");
13885       if (!ast_strlen_zero(id))
13886          snprintf(idtext, sizeof(idtext), "ActionID: %s\r\n", id);
13887    }
13888 
13889    switch (argc) {
13890    case 5:
13891       if (!strcasecmp(argv[3], "like")) {
13892          if (regcomp(&regexbuf, argv[4], REG_EXTENDED | REG_NOSUB))
13893             return CLI_SHOWUSAGE;
13894          havepattern = TRUE;
13895       } else
13896          return CLI_SHOWUSAGE;
13897    case 3:
13898       break;
13899    default:
13900       return CLI_SHOWUSAGE;
13901    }
13902 
13903    if (!s) /* Normal list */
13904       ast_cli(fd, FORMAT2, "Name/username", "Host", "Dyn", "Nat", "ACL", "Port", "Status", (realtimepeers ? "Realtime" : ""));
13905    
13906 
13907    i = ao2_iterator_init(peers, 0);
13908    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {  
13909       ao2_lock(peer);
13910 
13911       if (!(peer->type & SIP_TYPE_PEER)) {
13912          ao2_unlock(peer);
13913          unref_peer(peer, "unref peer because it's actually a user");
13914          continue;
13915       }
13916 
13917       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
13918          objcount--;
13919          ao2_unlock(peer);
13920          unref_peer(peer, "toss iterator peer ptr before continue");
13921          continue;
13922       }
13923 
13924       peerarray[total_peers++] = peer;
13925       ao2_unlock(peer);
13926    }
13927    ao2_iterator_destroy(&i);
13928    
13929    qsort(peerarray, total_peers, sizeof(struct sip_peer *), peercomparefunc);
13930 
13931    for(k=0; k < total_peers; k++) {
13932       char status[20] = "";
13933       char srch[2000];
13934       char pstatus;
13935       peer = peerarray[k];
13936       
13937       ao2_lock(peer);
13938       if (havepattern && regexec(&regexbuf, peer->name, 0, NULL, 0)) {
13939          ao2_unlock(peer);
13940          unref_peer(peer, "toss iterator peer ptr before continue");
13941          continue;
13942       }
13943 
13944       if (!ast_strlen_zero(peer->username) && !s)
13945          snprintf(name, sizeof(name), "%s/%s", peer->name, peer->username);
13946       else
13947          ast_copy_string(name, peer->name, sizeof(name));
13948       
13949       pstatus = peer_status(peer, status, sizeof(status));
13950       if (pstatus == 1)
13951          peers_mon_online++;
13952       else if (pstatus == 0)
13953          peers_mon_offline++;
13954       else {
13955          if (peer->addr.sin_port == 0)
13956             peers_unmon_offline++;
13957          else
13958             peers_unmon_online++;
13959       }
13960 
13961       snprintf(srch, sizeof(srch), FORMAT, name,
13962          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13963          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
13964          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
13965          peer->ha ? " A " : "   ",  /* permit/deny */
13966          ntohs(peer->addr.sin_port), status,
13967          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13968 
13969       if (!s)  {/* Normal CLI list */
13970          ast_cli(fd, FORMAT, name, 
13971          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "(Unspecified)",
13972          peer->host_dynamic ? " D " : "   ",    /* Dynamic or not? */
13973          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? " N " : "   ", /* NAT=yes? */
13974          peer->ha ? " A " : "   ",       /* permit/deny */
13975          
13976          ntohs(peer->addr.sin_port), status,
13977          realtimepeers ? (peer->is_realtime ? "Cached RT":"") : "");
13978       } else { /* Manager format */
13979          /* The names here need to be the same as other channels */
13980          astman_append(s, 
13981          "Event: PeerEntry\r\n%s"
13982          "Channeltype: SIP\r\n"
13983          "ObjectName: %s\r\n"
13984          "ChanObjectType: peer\r\n" /* "peer" or "user" */
13985          "IPaddress: %s\r\n"
13986          "IPport: %d\r\n"
13987          "Dynamic: %s\r\n"
13988          "Natsupport: %s\r\n"
13989          "VideoSupport: %s\r\n"
13990          "TextSupport: %s\r\n"
13991          "ACL: %s\r\n"
13992          "Status: %s\r\n"
13993          "RealtimeDevice: %s\r\n\r\n", 
13994          idtext,
13995          peer->name, 
13996          peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "-none-",
13997          ntohs(peer->addr.sin_port), 
13998          peer->host_dynamic ? "yes" : "no",  /* Dynamic or not? */
13999          ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) ? "yes" : "no",  /* NAT=yes? */
14000          ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT) ? "yes" : "no",  /* VIDEOSUPPORT=yes? */
14001          ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT) ? "yes" : "no",   /* TEXTSUPPORT=yes? */
14002          peer->ha ? "yes" : "no",       /* permit/deny */
14003          status,
14004          realtimepeers ? (peer->is_realtime ? "yes":"no") : "no");
14005       }
14006       ao2_unlock(peer);
14007       unref_peer(peer, "toss iterator peer ptr");
14008    }
14009    
14010    if (!s)
14011       ast_cli(fd, "%d sip peers [Monitored: %d online, %d offline Unmonitored: %d online, %d offline]\n",
14012               total_peers, peers_mon_online, peers_mon_offline, peers_unmon_online, peers_unmon_offline);
14013 
14014    if (havepattern)
14015       regfree(&regexbuf);
14016 
14017    if (total)
14018       *total = total_peers;
14019    
14020    ast_free(peerarray);
14021    
14022    return CLI_SUCCESS;
14023 #undef FORMAT
14024 #undef FORMAT2
14025 }
14026 
14027 static int peer_dump_func(void *userobj, void *arg, int flags)
14028 {
14029    struct sip_peer *peer = userobj;
14030    int refc = ao2_t_ref(userobj, 0, "");
14031    int *fd = arg;
14032    
14033    ast_cli(*fd, "name: %s\ntype: peer\nobjflags: %d\nrefcount: %d\n\n", 
14034           peer->name, 0, refc);
14035    return 0;
14036 }
14037 
14038 static int dialog_dump_func(void *userobj, void *arg, int flags)
14039 {
14040    struct sip_pvt *pvt = userobj;
14041    int refc = ao2_t_ref(userobj, 0, "");
14042    int *fd = arg;
14043    
14044    ast_cli(*fd, "name: %s\ntype: dialog\nobjflags: %d\nrefcount: %d\n\n", 
14045           pvt->callid, 0, refc);
14046    return 0;
14047 }
14048 
14049 
14050 /*! \brief List all allocated SIP Objects (realtime or static) */
14051 static char *sip_show_objects(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14052 {
14053    char tmp[256];
14054    
14055    switch (cmd) {
14056    case CLI_INIT:
14057       e->command = "sip show objects";
14058       e->usage =
14059          "Usage: sip show objects\n"
14060          "       Lists status of known SIP objects\n";
14061       return NULL;
14062    case CLI_GENERATE:
14063       return NULL;
14064    }  
14065 
14066    if (a->argc != 3)
14067       return CLI_SHOWUSAGE;
14068    ast_cli(a->fd, "-= Peer objects: %d static, %d realtime, %d autocreate =-\n\n", speerobjs, rpeerobjs, apeerobjs);
14069    ao2_t_callback(peers, OBJ_NODATA, peer_dump_func, &a->fd, "initiate ao2_callback to dump peers");
14070    ast_cli(a->fd, "-= Registry objects: %d =-\n\n", regobjs);
14071    ASTOBJ_CONTAINER_DUMP(a->fd, tmp, sizeof(tmp), &regl);
14072    ast_cli(a->fd, "-= Dialog objects:\n\n");
14073    ao2_t_callback(dialogs, OBJ_NODATA, dialog_dump_func, &a->fd, "initiate ao2_callback to dump dialogs");
14074    return CLI_SUCCESS;
14075 }
14076 /*! \brief Print call group and pickup group */
14077 static void  print_group(int fd, ast_group_t group, int crlf)
14078 {
14079    char buf[256];
14080    ast_cli(fd, crlf ? "%s\r\n" : "%s\n", ast_print_group(buf, sizeof(buf), group) );
14081 }
14082 
14083 /*! \brief mapping between dtmf flags and strings */
14084 static struct _map_x_s dtmfstr[] = {
14085    { SIP_DTMF_RFC2833,     "rfc2833" },
14086    { SIP_DTMF_INFO,        "info" },
14087    { SIP_DTMF_SHORTINFO,   "shortinfo" },
14088    { SIP_DTMF_INBAND,      "inband" },
14089    { SIP_DTMF_AUTO,        "auto" },
14090    { -1,                   NULL }, /* terminator */
14091 };
14092 
14093 /*! \brief Convert DTMF mode to printable string */
14094 static const char *dtmfmode2str(int mode)
14095 {
14096    return map_x_s(dtmfstr, mode, "<error>");
14097 }
14098 
14099 /*! \brief maps a string to dtmfmode, returns -1 on error */
14100 static int str2dtmfmode(const char *str)
14101 {
14102    return map_s_x(dtmfstr, str, -1);
14103 }
14104 
14105 static struct _map_x_s insecurestr[] = {
14106    { SIP_INSECURE_PORT,    "port" },
14107    { SIP_INSECURE_INVITE,  "invite" },
14108    { SIP_INSECURE_PORT | SIP_INSECURE_INVITE, "port,invite" },
14109    { 0,                    "no" },
14110    { -1,                   NULL }, /* terminator */
14111 };
14112 
14113 /*! \brief Convert Insecure setting to printable string */
14114 static const char *insecure2str(int mode)
14115 {
14116    return map_x_s(insecurestr, mode, "<error>");
14117 }
14118 
14119 /*! \brief Destroy disused contexts between reloads
14120    Only used in reload_config so the code for regcontext doesn't get ugly
14121 */
14122 static void cleanup_stale_contexts(char *new, char *old)
14123 {
14124    char *oldcontext, *newcontext, *stalecontext, *stringp, newlist[AST_MAX_CONTEXT];
14125 
14126    while ((oldcontext = strsep(&old, "&"))) {
14127       stalecontext = '\0';
14128       ast_copy_string(newlist, new, sizeof(newlist));
14129       stringp = newlist;
14130       while ((newcontext = strsep(&stringp, "&"))) {
14131          if (!strcmp(newcontext, oldcontext)) {
14132             /* This is not the context you're looking for */
14133             stalecontext = '\0';
14134             break;
14135          } else if (strcmp(newcontext, oldcontext)) {
14136             stalecontext = oldcontext;
14137          }
14138          
14139       }
14140       if (stalecontext)
14141          ast_context_destroy(ast_context_find(stalecontext), "SIP");
14142    }
14143 }
14144 
14145 /* this func is used with ao2_callback to unlink/delete all dialogs that
14146    are marked needdestroy. It will return CMP_MATCH for candidates, and they
14147    will be unlinked */
14148 
14149 /* TODO: Implement a queue and instead of marking a dialog 
14150    to be destroyed, toss it into the queue. Have a separate
14151    thread do the locking and destruction */
14152 
14153 static int dialog_needdestroy(void *dialogobj, void *arg, int flags) 
14154 {
14155    struct sip_pvt *dialog = dialogobj;
14156    time_t *t = arg;
14157    
14158    /* log_show_lock(ao2_object_get_lockaddr(dialog)); this is an example of how to use log_show_lock() */
14159 
14160    if (sip_pvt_trylock(dialog)) {
14161       /* In very short-duration calls via sipp,
14162          this path gets executed fairly frequently (3% or so) even in low load
14163          situations; the routines we most commonly fight for a lock with:
14164          sip_answer (7 out of 9)
14165          sip_hangup (2 out of 9)
14166       */
14167       ao2_unlock(dialogs);
14168       usleep(1);
14169       ao2_lock(dialogs);
14170 
14171       /* I had previously returned CMP_STOP here; but changed it to return
14172          a zero instead, because there is no need to stop at the first sign
14173          of trouble. The old algorithm would restart in such circumstances,
14174          but there is no need for this now in astobj2-land. We'll
14175          just skip over this element this time, and catch it on the
14176          next traversal, which is about once a second or so. See the 
14177          ao2_callback call in do_monitor. We don't want the number of
14178          dialogs to back up too much between runs.
14179       */
14180       return 0;
14181    }
14182    
14183    /* Check RTP timeouts and kill calls if we have a timeout set and do not get RTP */
14184    check_rtp_timeout(dialog, *t);
14185 
14186    /* If we have sessions that needs to be destroyed, do it now */
14187    /* Check if we have outstanding requests not responsed to or an active call
14188       - if that's the case, wait with destruction */
14189    if (dialog->needdestroy && !dialog->packets && !dialog->owner) {
14190       /* We absolutely cannot destroy the rtp struct while a bridge is active or we WILL crash */
14191       if (dialog->rtp && ast_rtp_get_bridged(dialog->rtp)) {
14192          ast_debug(2, "Bridge still active.  Delaying destruction of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14193          sip_pvt_unlock(dialog);
14194          return 0;
14195       }
14196       
14197       if (dialog->vrtp && ast_rtp_get_bridged(dialog->vrtp)) {
14198          ast_debug(2, "Bridge still active.  Delaying destroy of SIP dialog '%s' Method: %s\n", dialog->callid, sip_methods[dialog->method].text);
14199          sip_pvt_unlock(dialog);
14200          return 0;
14201       }
14202 
14203       sip_pvt_unlock(dialog);
14204       /* no, the unlink should handle this: dialog_unref(dialog, "needdestroy: one more refcount decrement to allow dialog to be destroyed"); */
14205       /* the CMP_MATCH will unlink this dialog from the dialog hash table */
14206       dialog_unlink_all(dialog, TRUE, FALSE);
14207       return 0; /* the unlink_all should unlink this from the table, so.... no need to return a match */
14208    }
14209 
14210    sip_pvt_unlock(dialog);
14211 
14212    return 0;
14213 }
14214 
14215 /* this func is used with ao2_callback to unlink/delete all marked
14216    peers */
14217 static int peer_is_marked(void *peerobj, void *arg, int flags) 
14218 {
14219    struct sip_peer *peer = peerobj;
14220    return peer->the_mark ? CMP_MATCH : 0;
14221 }
14222 
14223 /*! \brief Remove temporary realtime objects from memory (CLI) */
14224 /*! \todo XXXX Propably needs an overhaul after removal of the devices */
14225 static char *sip_prune_realtime(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14226 {
14227    struct sip_peer *peer, *pi;
14228    int prunepeer = FALSE;
14229    int multi = FALSE;
14230    char *name = NULL;
14231    regex_t regexbuf;
14232    struct ao2_iterator i;
14233    
14234    if (cmd == CLI_INIT) {
14235       e->command = "sip prune realtime [peer|all] [all|like]";
14236       e->usage =
14237          "Usage: sip prune realtime [peer [<name>|all|like <pattern>]|all]\n"
14238          "       Prunes object(s) from the cache.\n"
14239          "       Optional regular expression pattern is used to filter the objects.\n";
14240       return NULL;
14241    } else if (cmd == CLI_GENERATE) {
14242       if (a->pos == 4) {
14243          if (strcasestr(a->line, "realtime peer"))
14244             return complete_sip_peer(a->word, a->n, SIP_PAGE2_RTCACHEFRIENDS);
14245       }
14246       return NULL;
14247    }
14248    switch (a->argc) {
14249    case 4:
14250       name = a->argv[3];
14251       /* we accept a name in position 3, but keywords are not good. */
14252       if (!strcasecmp(name, "peer") || !strcasecmp(name, "like"))
14253          return CLI_SHOWUSAGE;
14254       prunepeer = TRUE;
14255       if (!strcasecmp(name, "all")) {
14256          multi = TRUE;
14257          name = NULL;
14258       }
14259       /* else a single name, already set */
14260       break;
14261    case 5:
14262       /* sip prune realtime {peer|like} name */
14263       name = a->argv[4];
14264       if (!strcasecmp(a->argv[3], "peer"))
14265          prunepeer = TRUE;
14266       else if (!strcasecmp(a->argv[3], "like")) {
14267          prunepeer = TRUE;
14268          multi = TRUE;
14269       } else
14270          return CLI_SHOWUSAGE;
14271       if (!strcasecmp(a->argv[4], "like"))
14272          return CLI_SHOWUSAGE;
14273       if (!multi && !strcasecmp(a->argv[4], "all")) {
14274          multi = TRUE;
14275          name = NULL;
14276       }
14277       break;
14278    case 6:
14279       name = a->argv[5];
14280       multi = TRUE;
14281       /* sip prune realtime {peer} like name */
14282       if (strcasecmp(a->argv[4], "like"))
14283          return CLI_SHOWUSAGE;
14284       if (!strcasecmp(a->argv[3], "peer")) {
14285          prunepeer = TRUE;
14286       } else
14287          return CLI_SHOWUSAGE;
14288       break;
14289    default:
14290       return CLI_SHOWUSAGE;
14291    }
14292 
14293    if (multi && name) {
14294       if (regcomp(&regexbuf, name, REG_EXTENDED | REG_NOSUB))
14295          return CLI_SHOWUSAGE;
14296    }
14297 
14298    if (multi) {
14299       if (prunepeer) {
14300          int pruned = 0;
14301          
14302          i = ao2_iterator_init(peers, 0);
14303          while ((pi = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
14304             ao2_lock(pi);
14305             if (name && regexec(&regexbuf, pi->name, 0, NULL, 0)) {
14306                unref_peer(pi, "toss iterator peer ptr before continue");
14307                ao2_unlock(pi);
14308                continue;
14309             };
14310             if (ast_test_flag(&pi->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14311                pi->the_mark = 1;
14312                pruned++;
14313             }
14314             ao2_unlock(pi);
14315             unref_peer(pi, "toss iterator peer ptr");
14316          }
14317          ao2_iterator_destroy(&i);
14318          if (pruned) {
14319             ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0, 
14320                   "initiating callback to remove marked peers");
14321             ast_cli(a->fd, "%d peers pruned.\n", pruned);
14322          } else
14323             ast_cli(a->fd, "No peers found to prune.\n");
14324       }
14325    } else {
14326       if (prunepeer) {
14327          struct sip_peer tmp;
14328          ast_copy_string(tmp.name, name, sizeof(tmp.name));
14329          if ((peer = ao2_t_find(peers, &tmp, OBJ_POINTER | OBJ_UNLINK, "finding to unlink from peers"))) {
14330             if (peer->addr.sin_addr.s_addr) {
14331                ao2_t_unlink(peers_by_ip, peer, "unlinking peer from peers_by_ip also");
14332             }
14333             if (!ast_test_flag(&peer->flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
14334                ast_cli(a->fd, "Peer '%s' is not a Realtime peer, cannot be pruned.\n", name);
14335                /* put it back! */
14336                ao2_t_link(peers, peer, "link peer into peer table");
14337                if (peer->addr.sin_addr.s_addr) {
14338                   ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
14339                }
14340                
14341             } else
14342                ast_cli(a->fd, "Peer '%s' pruned.\n", name);
14343             unref_peer(peer, "sip_prune_realtime: unref_peer: tossing temp peer ptr");
14344          } else
14345             ast_cli(a->fd, "Peer '%s' not found.\n", name);
14346       }
14347    }
14348 
14349    return CLI_SUCCESS;
14350 }
14351 
14352 /*! \brief Print codec list from preference to CLI/manager */
14353 static void print_codec_to_cli(int fd, struct ast_codec_pref *pref)
14354 {
14355    int x, codec;
14356 
14357    for(x = 0; x < 32 ; x++) {
14358       codec = ast_codec_pref_index(pref, x);
14359       if (!codec)
14360          break;
14361       ast_cli(fd, "%s", ast_getformatname(codec));
14362       ast_cli(fd, ":%d", pref->framing[x]);
14363       if (x < 31 && ast_codec_pref_index(pref, x + 1))
14364          ast_cli(fd, ",");
14365    }
14366    if (!x)
14367       ast_cli(fd, "none");
14368 }
14369 
14370 /*! \brief Print domain mode to cli */
14371 static const char *domain_mode_to_text(const enum domain_mode mode)
14372 {
14373    switch (mode) {
14374    case SIP_DOMAIN_AUTO:
14375       return "[Automatic]";
14376    case SIP_DOMAIN_CONFIG:
14377       return "[Configured]";
14378    }
14379 
14380    return "";
14381 }
14382 
14383 /*! \brief CLI command to list local domains */
14384 static char *sip_show_domains(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14385 {
14386    struct domain *d;
14387 #define FORMAT "%-40.40s %-20.20s %-16.16s\n"
14388 
14389    switch (cmd) {
14390    case CLI_INIT:
14391       e->command = "sip show domains";
14392       e->usage =
14393          "Usage: sip show domains\n"
14394          "       Lists all configured SIP local domains.\n"
14395          "       Asterisk only responds to SIP messages to local domains.\n";
14396       return NULL;
14397    case CLI_GENERATE:
14398       return NULL;
14399    }
14400 
14401    if (AST_LIST_EMPTY(&domain_list)) {
14402       ast_cli(a->fd, "SIP Domain support not enabled.\n\n");
14403       return CLI_SUCCESS;
14404    } else {
14405       ast_cli(a->fd, FORMAT, "Our local SIP domains:", "Context", "Set by");
14406       AST_LIST_LOCK(&domain_list);
14407       AST_LIST_TRAVERSE(&domain_list, d, list)
14408          ast_cli(a->fd, FORMAT, d->domain, S_OR(d->context, "(default)"),
14409             domain_mode_to_text(d->mode));
14410       AST_LIST_UNLOCK(&domain_list);
14411       ast_cli(a->fd, "\n");
14412       return CLI_SUCCESS;
14413    }
14414 }
14415 #undef FORMAT
14416 
14417 static char mandescr_show_peer[] = 
14418 "Description: Show one SIP peer with details on current status.\n"
14419 "Variables: \n"
14420 "  Peer: <name>           The peer name you want to check.\n"
14421 "  ActionID: <id>   Optional action ID for this AMI transaction.\n";
14422 
14423 /*! \brief Show SIP peers in the manager API  */
14424 static int manager_sip_show_peer(struct mansession *s, const struct message *m)
14425 {
14426    const char *a[4];
14427    const char *peer;
14428 
14429    peer = astman_get_header(m, "Peer");
14430    if (ast_strlen_zero(peer)) {
14431       astman_send_error(s, m, "Peer: <name> missing.");
14432       return 0;
14433    }
14434    a[0] = "sip";
14435    a[1] = "show";
14436    a[2] = "peer";
14437    a[3] = peer;
14438 
14439    _sip_show_peer(1, -1, s, m, 4, a);
14440    astman_append(s, "\r\n\r\n" );
14441    return 0;
14442 }
14443 
14444 /*! \brief Show one peer in detail */
14445 static char *sip_show_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14446 {
14447    switch (cmd) {
14448    case CLI_INIT:
14449       e->command = "sip show peer";
14450       e->usage =
14451          "Usage: sip show peer <name> [load]\n"
14452          "       Shows all details on one SIP peer and the current status.\n"
14453          "       Option \"load\" forces lookup of peer in realtime storage.\n";
14454       return NULL;
14455    case CLI_GENERATE:
14456       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
14457    }
14458    return _sip_show_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
14459 }
14460 
14461 /*! \brief Send qualify message to peer from cli or manager. Mostly for debugging. */
14462 static char *_sip_qualify_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
14463 {
14464    struct sip_peer *peer;
14465    int load_realtime;
14466 
14467    if (argc < 4)
14468       return CLI_SHOWUSAGE;
14469 
14470    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
14471    if ((peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0))) {
14472       sip_poke_peer(peer, 1);
14473       unref_peer(peer, "qualify: done with peer");
14474    } else if (type == 0) {
14475       ast_cli(fd, "Peer '%s' not found\n", argv[3]);
14476    } else {
14477       astman_send_error(s, m, "Peer not found");
14478    }
14479    return CLI_SUCCESS;
14480 }
14481 
14482 /*! \brief Qualify SIP peers in the manager API  */
14483 static int manager_sip_qualify_peer(struct mansession *s, const struct message *m)
14484 {
14485    const char *a[4];
14486    const char *peer;
14487 
14488    peer = astman_get_header(m, "Peer");
14489    if (ast_strlen_zero(peer)) {
14490       astman_send_error(s, m, "Peer: <name> missing.");
14491       return 0;
14492    }
14493    a[0] = "sip";
14494    a[1] = "qualify";
14495    a[2] = "peer";
14496    a[3] = peer;
14497 
14498    _sip_qualify_peer(1, -1, s, m, 4, a);
14499    astman_append(s, "\r\n\r\n" );
14500    return 0;
14501 }
14502 
14503 /*! \brief Send an OPTIONS packet to a SIP peer */
14504 static char *sip_qualify_peer(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14505 {
14506    switch (cmd) {
14507    case CLI_INIT:
14508       e->command = "sip qualify peer";
14509       e->usage =
14510          "Usage: sip qualify peer <name> [load]\n"
14511          "       Requests a response from one SIP peer and the current status.\n"
14512          "       Option \"load\" forces lookup of peer in realtime storage.\n";
14513       return NULL;
14514    case CLI_GENERATE:
14515       return complete_sip_show_peer(a->line, a->word, a->pos, a->n);
14516    }
14517    return _sip_qualify_peer(0, a->fd, NULL, NULL, a->argc, (const char **) a->argv);
14518 }
14519 
14520 /*! \brief list peer mailboxes to CLI */
14521 static void peer_mailboxes_to_str(struct ast_str **mailbox_str, struct sip_peer *peer)
14522 {
14523    struct sip_mailbox *mailbox;
14524 
14525    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
14526       ast_str_append(mailbox_str, 0, "%s%s%s%s",
14527          mailbox->mailbox,
14528          ast_strlen_zero(mailbox->context) ? "" : "@",
14529          S_OR(mailbox->context, ""),
14530          AST_LIST_NEXT(mailbox, entry) ? "," : "");
14531    }
14532 }
14533 
14534 static struct _map_x_s faxecmodes[] = {
14535    { SIP_PAGE2_T38SUPPORT_UDPTL,       "None"},
14536    { SIP_PAGE2_T38SUPPORT_UDPTL_FEC,      "FEC"},
14537    { SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY,  "Redundancy"},
14538    { -1,                NULL},
14539 };
14540 
14541 static const char *faxec2str(int faxec)
14542 {
14543    return map_x_s(faxecmodes, faxec, "Unknown");
14544 }
14545 
14546 /*! \brief Show one peer in detail (main function) */
14547 static char *_sip_show_peer(int type, int fd, struct mansession *s, const struct message *m, int argc, const char *argv[])
14548 {
14549    char status[30] = "";
14550    char cbuf[256];
14551    struct sip_peer *peer;
14552    char codec_buf[512];
14553    struct ast_codec_pref *pref;
14554    struct ast_variable *v;
14555    struct sip_auth *auth;
14556    int x = 0, codec = 0, load_realtime;
14557    int realtimepeers;
14558 
14559    realtimepeers = ast_check_realtime("sippeers");
14560 
14561    if (argc < 4)
14562       return CLI_SHOWUSAGE;
14563 
14564    load_realtime = (argc == 5 && !strcmp(argv[4], "load")) ? TRUE : FALSE;
14565    peer = find_peer(argv[3], NULL, load_realtime, FINDPEERS, FALSE, 0);
14566 
14567    if (s) {    /* Manager */
14568       if (peer) {
14569          const char *id = astman_get_header(m, "ActionID");
14570 
14571          astman_append(s, "Response: Success\r\n");
14572          if (!ast_strlen_zero(id))
14573             astman_append(s, "ActionID: %s\r\n", id);
14574       } else {
14575          snprintf (cbuf, sizeof(cbuf), "Peer %s not found.", argv[3]);
14576          astman_send_error(s, m, cbuf);
14577          return CLI_SUCCESS;
14578       }
14579    }
14580    if (peer && type==0 ) { /* Normal listing */
14581       struct ast_str *mailbox_str = ast_str_alloca(512);
14582       ast_cli(fd, "\n\n");
14583       ast_cli(fd, "  * Name       : %s\n", peer->name);
14584       if (realtimepeers) { /* Realtime is enabled */
14585          ast_cli(fd, "  Realtime peer: %s\n", peer->is_realtime ? "Yes, cached" : "No");
14586       }
14587       ast_cli(fd, "  Secret       : %s\n", ast_strlen_zero(peer->secret)?"<Not set>":"<Set>");
14588       ast_cli(fd, "  MD5Secret    : %s\n", ast_strlen_zero(peer->md5secret)?"<Not set>":"<Set>");
14589       for (auth = peer->auth; auth; auth = auth->next) {
14590          ast_cli(fd, "  Realm-auth   : Realm %-15.15s User %-10.20s ", auth->realm, auth->username);
14591          ast_cli(fd, "%s\n", !ast_strlen_zero(auth->secret)?"<Secret set>":(!ast_strlen_zero(auth->md5secret)?"<MD5secret set>" : "<Not set>"));
14592       }
14593       ast_cli(fd, "  Context      : %s\n", peer->context);
14594       ast_cli(fd, "  Subscr.Cont. : %s\n", S_OR(peer->subscribecontext, "<Not set>") );
14595       ast_cli(fd, "  Language     : %s\n", peer->language);
14596       if (!ast_strlen_zero(peer->accountcode))
14597          ast_cli(fd, "  Accountcode  : %s\n", peer->accountcode);
14598       ast_cli(fd, "  AMA flags    : %s\n", ast_cdr_flags2str(peer->amaflags));
14599       ast_cli(fd, "  Transfer mode: %s\n", transfermode2str(peer->allowtransfer));
14600       ast_cli(fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(peer->callingpres));
14601       if (!ast_strlen_zero(peer->fromuser))
14602          ast_cli(fd, "  FromUser     : %s\n", peer->fromuser);
14603       if (!ast_strlen_zero(peer->fromdomain))
14604          ast_cli(fd, "  FromDomain   : %s\n", peer->fromdomain);
14605       ast_cli(fd, "  Callgroup    : ");
14606       print_group(fd, peer->callgroup, 0);
14607       ast_cli(fd, "  Pickupgroup  : ");
14608       print_group(fd, peer->pickupgroup, 0);
14609       peer_mailboxes_to_str(&mailbox_str, peer);
14610       ast_cli(fd, "  Mailbox      : %s\n", mailbox_str->str);
14611       ast_cli(fd, "  VM Extension : %s\n", peer->vmexten);
14612       ast_cli(fd, "  LastMsgsSent : %d/%d\n", (peer->lastmsgssent & 0x7fff0000) >> 16, peer->lastmsgssent & 0xffff);
14613       ast_cli(fd, "  Call limit   : %d\n", peer->call_limit);
14614       if (peer->busy_level)
14615          ast_cli(fd, "  Busy level   : %d\n", peer->busy_level);
14616       ast_cli(fd, "  Dynamic      : %s\n", cli_yesno(peer->host_dynamic));
14617       ast_cli(fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, "<unspecified>"));
14618       ast_cli(fd, "  MaxCallBR    : %d kbps\n", peer->maxcallbitrate);
14619       ast_cli(fd, "  Expire       : %ld\n", ast_sched_when(sched, peer->expire));
14620       ast_cli(fd, "  Insecure     : %s\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14621       ast_cli(fd, "  Nat          : %s\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14622       ast_cli(fd, "  ACL          : %s\n", cli_yesno(peer->ha != NULL));
14623       ast_cli(fd, "  T.38 support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14624       ast_cli(fd, "  T.38 EC mode : %s\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14625       ast_cli(fd, "  T.38 MaxDtgrm: %d\n", peer->t38_maxdatagram);
14626       ast_cli(fd, "  CanReinvite  : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)));
14627       ast_cli(fd, "  PromiscRedir : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)));
14628       ast_cli(fd, "  User=Phone   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)));
14629       ast_cli(fd, "  Video Support: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)));
14630       ast_cli(fd, "  Text Support : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)));
14631       ast_cli(fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14632       ast_cli(fd, "  Trust RPID   : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_TRUSTRPID)));
14633       ast_cli(fd, "  Send RPID    : %s\n", cli_yesno(ast_test_flag(&peer->flags[0], SIP_SENDRPID)));
14634       ast_cli(fd, "  Subscriptions: %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
14635       ast_cli(fd, "  Overlap dial : %s\n", cli_yesno(ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWOVERLAP)));
14636       if (peer->outboundproxy)
14637          ast_cli(fd, "  Outb. proxy  : %s %s\n", ast_strlen_zero(peer->outboundproxy->name) ? "<not set>" : peer->outboundproxy->name,
14638                      peer->outboundproxy->force ? "(forced)" : "");
14639 
14640       /* - is enumerated */
14641       ast_cli(fd, "  DTMFmode     : %s\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14642       ast_cli(fd, "  Timer T1     : %d\n", peer->timer_t1);
14643       ast_cli(fd, "  Timer B      : %d\n", peer->timer_b);
14644       ast_cli(fd, "  ToHost       : %s\n", peer->tohost);
14645       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));
14646       ast_cli(fd, "  Defaddr->IP  : %s Port %d\n", ast_inet_ntoa(peer->defaddr.sin_addr), ntohs(peer->defaddr.sin_port));
14647       ast_cli(fd, "  Transport    : %s\n", get_transport(peer->socket.type));
14648       if (!ast_strlen_zero(global_regcontext))
14649          ast_cli(fd, "  Reg. exten   : %s\n", peer->regexten);
14650       ast_cli(fd, "  Def. Username: %s\n", peer->username);
14651       ast_cli(fd, "  SIP Options  : ");
14652       if (peer->sipoptions) {
14653          int lastoption = -1;
14654          for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
14655             if (sip_options[x].id != lastoption) {
14656                if (peer->sipoptions & sip_options[x].id)
14657                   ast_cli(fd, "%s ", sip_options[x].text);
14658                lastoption = x;
14659             }
14660          }
14661       } else
14662          ast_cli(fd, "(none)");
14663 
14664       ast_cli(fd, "\n");
14665       ast_cli(fd, "  Codecs       : ");
14666       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14667       ast_cli(fd, "%s\n", codec_buf);
14668       ast_cli(fd, "  Codec Order  : (");
14669       print_codec_to_cli(fd, &peer->prefs);
14670       ast_cli(fd, ")\n");
14671 
14672       ast_cli(fd, "  Auto-Framing :  %s \n", cli_yesno(peer->autoframing));
14673       ast_cli(fd, "  100 on REG   : %s\n", ast_test_flag(&peer->flags[1], SIP_PAGE2_REGISTERTRYING) ? "Yes" : "No");
14674       ast_cli(fd, "  Status       : ");
14675       peer_status(peer, status, sizeof(status));
14676       ast_cli(fd, "%s\n", status);
14677       ast_cli(fd, "  Useragent    : %s\n", peer->useragent);
14678       ast_cli(fd, "  Reg. Contact : %s\n", peer->fullcontact);
14679       ast_cli(fd, "  Qualify Freq : %d ms\n", peer->qualifyfreq);
14680       if (peer->chanvars) {
14681          ast_cli(fd, "  Variables    :\n");
14682          for (v = peer->chanvars ; v ; v = v->next)
14683             ast_cli(fd, "                 %s = %s\n", v->name, v->value);
14684       }
14685 
14686       ast_cli(fd, "  Sess-Timers  : %s\n", stmode2str(peer->stimer.st_mode_oper));
14687       ast_cli(fd, "  Sess-Refresh : %s\n", strefresher2str(peer->stimer.st_ref));
14688       ast_cli(fd, "  Sess-Expires : %d secs\n", peer->stimer.st_max_se);
14689       ast_cli(fd, "  Min-Sess     : %d secs\n", peer->stimer.st_min_se);
14690       ast_cli(fd, "  Parkinglot   : %s\n", peer->parkinglot);
14691       ast_cli(fd, "\n");
14692       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer ptr");
14693    } else  if (peer && type == 1) { /* manager listing */
14694       char buffer[256];
14695       struct ast_str *mailbox_str = ast_str_alloca(512);
14696       astman_append(s, "Channeltype: SIP\r\n");
14697       astman_append(s, "ObjectName: %s\r\n", peer->name);
14698       astman_append(s, "ChanObjectType: peer\r\n");
14699       astman_append(s, "SecretExist: %s\r\n", ast_strlen_zero(peer->secret)?"N":"Y");
14700       astman_append(s, "MD5SecretExist: %s\r\n", ast_strlen_zero(peer->md5secret)?"N":"Y");
14701       astman_append(s, "Context: %s\r\n", peer->context);
14702       astman_append(s, "Language: %s\r\n", peer->language);
14703       if (!ast_strlen_zero(peer->accountcode))
14704          astman_append(s, "Accountcode: %s\r\n", peer->accountcode);
14705       astman_append(s, "AMAflags: %s\r\n", ast_cdr_flags2str(peer->amaflags));
14706       astman_append(s, "CID-CallingPres: %s\r\n", ast_describe_caller_presentation(peer->callingpres));
14707       if (!ast_strlen_zero(peer->fromuser))
14708          astman_append(s, "SIP-FromUser: %s\r\n", peer->fromuser);
14709       if (!ast_strlen_zero(peer->fromdomain))
14710          astman_append(s, "SIP-FromDomain: %s\r\n", peer->fromdomain);
14711       astman_append(s, "Callgroup: ");
14712       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->callgroup));
14713       astman_append(s, "Pickupgroup: ");
14714       astman_append(s, "%s\r\n", ast_print_group(buffer, sizeof(buffer), peer->pickupgroup));
14715       peer_mailboxes_to_str(&mailbox_str, peer);
14716       astman_append(s, "VoiceMailbox: %s\r\n", mailbox_str->str);
14717       astman_append(s, "TransferMode: %s\r\n", transfermode2str(peer->allowtransfer));
14718       astman_append(s, "LastMsgsSent: %d\r\n", peer->lastmsgssent);
14719       astman_append(s, "Call-limit: %d\r\n", peer->call_limit);
14720       astman_append(s, "Busy-level: %d\r\n", peer->busy_level);
14721       astman_append(s, "MaxCallBR: %d kbps\r\n", peer->maxcallbitrate);
14722       astman_append(s, "Dynamic: %s\r\n", peer->host_dynamic?"Y":"N");
14723       astman_append(s, "Callerid: %s\r\n", ast_callerid_merge(cbuf, sizeof(cbuf), peer->cid_name, peer->cid_num, ""));
14724       astman_append(s, "RegExpire: %ld seconds\r\n", ast_sched_when(sched, peer->expire));
14725       astman_append(s, "SIP-AuthInsecure: %s\r\n", insecure2str(ast_test_flag(&peer->flags[0], SIP_INSECURE)));
14726       astman_append(s, "SIP-NatSupport: %s\r\n", nat2str(ast_test_flag(&peer->flags[0], SIP_NAT)));
14727       astman_append(s, "ACL: %s\r\n", (peer->ha?"Y":"N"));
14728       astman_append(s, "SIP-CanReinvite: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_CAN_REINVITE)?"Y":"N"));
14729       astman_append(s, "SIP-PromiscRedir: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_PROMISCREDIR)?"Y":"N"));
14730       astman_append(s, "SIP-UserPhone: %s\r\n", (ast_test_flag(&peer->flags[0], SIP_USEREQPHONE)?"Y":"N"));
14731       astman_append(s, "SIP-VideoSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_VIDEOSUPPORT)?"Y":"N"));
14732       astman_append(s, "SIP-TextSupport: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_TEXTSUPPORT)?"Y":"N"));
14733       astman_append(s, "SIP-T.38Support: %s\r\n", (ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)?"Y":"N"));
14734       astman_append(s, "SIP-T.38EC: %s\r\n", faxec2str(ast_test_flag(&peer->flags[1], SIP_PAGE2_T38SUPPORT)));
14735       astman_append(s, "SIP-T.38MaxDtgrm: %d\r\n", peer->t38_maxdatagram);
14736       astman_append(s, "SIP-Sess-Timers: %s\r\n", stmode2str(peer->stimer.st_mode_oper));
14737       astman_append(s, "SIP-Sess-Refresh: %s\r\n", strefresher2str(peer->stimer.st_ref));
14738       astman_append(s, "SIP-Sess-Expires: %d\r\n", peer->stimer.st_max_se);
14739       astman_append(s, "SIP-Sess-Min: %d\r\n", peer->stimer.st_min_se);
14740 
14741       /* - is enumerated */
14742       astman_append(s, "SIP-DTMFmode: %s\r\n", dtmfmode2str(ast_test_flag(&peer->flags[0], SIP_DTMF)));
14743       astman_append(s, "ToHost: %s\r\n", peer->tohost);
14744       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));
14745       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));
14746       astman_append(s, "Default-Username: %s\r\n", peer->username);
14747       if (!ast_strlen_zero(global_regcontext))
14748          astman_append(s, "RegExtension: %s\r\n", peer->regexten);
14749       astman_append(s, "Codecs: ");
14750       ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, peer->capability);
14751       astman_append(s, "%s\r\n", codec_buf);
14752       astman_append(s, "CodecOrder: ");
14753       pref = &peer->prefs;
14754       for(x = 0; x < 32 ; x++) {
14755          codec = ast_codec_pref_index(pref, x);
14756          if (!codec)
14757             break;
14758          astman_append(s, "%s", ast_getformatname(codec));
14759          if (x < 31 && ast_codec_pref_index(pref, x+1))
14760             astman_append(s, ",");
14761       }
14762 
14763       astman_append(s, "\r\n");
14764       astman_append(s, "Status: ");
14765       peer_status(peer, status, sizeof(status));
14766       astman_append(s, "%s\r\n", status);
14767       astman_append(s, "SIP-Useragent: %s\r\n", peer->useragent);
14768       astman_append(s, "Reg-Contact: %s\r\n", peer->fullcontact);
14769       astman_append(s, "QualifyFreq: %d ms\r\n", peer->qualifyfreq);
14770       astman_append(s, "Parkinglot: %s\r\n", peer->parkinglot);
14771       if (peer->chanvars) {
14772          for (v = peer->chanvars ; v ; v = v->next) {
14773             astman_append(s, "ChanVariable: %s=%s\r\n", v->name, v->value);
14774          }
14775       }
14776 
14777       peer = unref_peer(peer, "sip_show_peer: unref_peer: done with peer");
14778 
14779    } else {
14780       ast_cli(fd, "Peer %s not found.\n", argv[3]);
14781       ast_cli(fd, "\n");
14782    }
14783 
14784    return CLI_SUCCESS;
14785 }
14786 
14787 /*! \brief Do completion on user name */
14788 static char *complete_sip_user(const char *word, int state)
14789 {
14790    char *result = NULL;
14791    int wordlen = strlen(word);
14792    int which = 0;
14793    struct ao2_iterator user_iter;
14794    struct sip_peer *user;
14795 
14796    user_iter = ao2_iterator_init(peers, 0);
14797    while ((user = ao2_iterator_next(&user_iter))) {
14798       ao2_lock(user);
14799       if (!(user->type & SIP_TYPE_USER)) {
14800          ao2_unlock(user);
14801          unref_peer(user, "complete sip user");
14802          continue;
14803       }
14804       /* locking of the object is not required because only the name and flags are being compared */
14805       if (!strncasecmp(word, user->name, wordlen) && ++which > state) {
14806          result = ast_strdup(user->name);
14807       }
14808       ao2_unlock(user);
14809       unref_peer(user, "complete sip user");
14810    }
14811    ao2_iterator_destroy(&user_iter);
14812    return result;
14813 }
14814 /*! \brief Support routine for 'sip show user' CLI */
14815 static char *complete_sip_show_user(const char *line, const char *word, int pos, int state)
14816 {
14817    if (pos == 3)
14818       return complete_sip_user(word, state);
14819 
14820    return NULL;
14821 }
14822 
14823 /*! \brief Show one user in detail */
14824 static char *sip_show_user(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14825 {
14826    char cbuf[256];
14827    struct sip_peer *user;
14828    struct ast_variable *v;
14829    int load_realtime;
14830 
14831    switch (cmd) {
14832    case CLI_INIT:
14833       e->command = "sip show user";
14834       e->usage =
14835          "Usage: sip show user <name> [load]\n"
14836          "       Shows all details on one SIP user and the current status.\n"
14837          "       Option \"load\" forces lookup of peer in realtime storage.\n";
14838       return NULL;
14839    case CLI_GENERATE:
14840       return complete_sip_show_user(a->line, a->word, a->pos, a->n);
14841    }
14842 
14843    if (a->argc < 4)
14844       return CLI_SHOWUSAGE;
14845 
14846    /* Load from realtime storage? */
14847    load_realtime = (a->argc == 5 && !strcmp(a->argv[4], "load")) ? TRUE : FALSE;
14848 
14849    if ((user = find_peer(a->argv[3], NULL, load_realtime, FINDUSERS, FALSE, 0))) {
14850       ao2_lock(user);
14851       ast_cli(a->fd, "\n\n");
14852       ast_cli(a->fd, "  * Name       : %s\n", user->name);
14853       ast_cli(a->fd, "  Secret       : %s\n", ast_strlen_zero(user->secret)?"<Not set>":"<Set>");
14854       ast_cli(a->fd, "  MD5Secret    : %s\n", ast_strlen_zero(user->md5secret)?"<Not set>":"<Set>");
14855       ast_cli(a->fd, "  Context      : %s\n", user->context);
14856       ast_cli(a->fd, "  Language     : %s\n", user->language);
14857       if (!ast_strlen_zero(user->accountcode))
14858          ast_cli(a->fd, "  Accountcode  : %s\n", user->accountcode);
14859       ast_cli(a->fd, "  AMA flags    : %s\n", ast_cdr_flags2str(user->amaflags));
14860       ast_cli(a->fd, "  Transfer mode: %s\n", transfermode2str(user->allowtransfer));
14861       ast_cli(a->fd, "  MaxCallBR    : %d kbps\n", user->maxcallbitrate);
14862       ast_cli(a->fd, "  CallingPres  : %s\n", ast_describe_caller_presentation(user->callingpres));
14863       ast_cli(a->fd, "  Call limit   : %d\n", user->call_limit);
14864       ast_cli(a->fd, "  Callgroup    : ");
14865       print_group(a->fd, user->callgroup, 0);
14866       ast_cli(a->fd, "  Pickupgroup  : ");
14867       print_group(a->fd, user->pickupgroup, 0);
14868       ast_cli(a->fd, "  Callerid     : %s\n", ast_callerid_merge(cbuf, sizeof(cbuf), user->cid_name, user->cid_num, "<unspecified>"));
14869       ast_cli(a->fd, "  ACL          : %s\n", cli_yesno(user->ha != NULL));
14870       ast_cli(a->fd, "  Sess-Timers  : %s\n", stmode2str(user->stimer.st_mode_oper));
14871       ast_cli(a->fd, "  Sess-Refresh : %s\n", strefresher2str(user->stimer.st_ref));
14872       ast_cli(a->fd, "  Sess-Expires : %d secs\n", user->stimer.st_max_se);
14873       ast_cli(a->fd, "  Sess-Min-SE  : %d secs\n", user->stimer.st_min_se);
14874       ast_cli(a->fd, "  Ign SDP ver  : %s\n", cli_yesno(ast_test_flag(&user->flags[1], SIP_PAGE2_IGNORESDPVERSION)));
14875 
14876       ast_cli(a->fd, "  Codec Order  : (");
14877       print_codec_to_cli(a->fd, &user->prefs);
14878       ast_cli(a->fd, ")\n");
14879 
14880       ast_cli(a->fd, "  Auto-Framing:  %s \n", cli_yesno(user->autoframing));
14881       if (user->chanvars) {
14882          ast_cli(a->fd, "  Variables    :\n");
14883          for (v = user->chanvars ; v ; v = v->next)
14884             ast_cli(a->fd, "                 %s = %s\n", v->name, v->value);
14885       }
14886 
14887       ast_cli(a->fd, "\n");
14888 
14889       ao2_unlock(user);
14890       unref_peer(user, "sip show user");
14891    } else {
14892       ast_cli(a->fd, "User %s not found.\n", a->argv[3]);
14893       ast_cli(a->fd, "\n");
14894    }
14895 
14896    return CLI_SUCCESS;
14897 }
14898 
14899 
14900 static char *sip_show_sched(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14901 {
14902    struct ast_str *cbuf;
14903    struct ast_cb_names cbnames = {9, { "retrans_pkt",
14904                                         "__sip_autodestruct",
14905                                         "expire_register",
14906                                         "auto_congest",
14907                                         "sip_reg_timeout",
14908                                         "sip_poke_peer_s",
14909                                         "sip_poke_noanswer",
14910                                         "sip_reregister",
14911                                         "sip_reinvite_retry"},
14912                            { retrans_pkt,
14913                                      __sip_autodestruct,
14914                                      expire_register,
14915                                      auto_congest,
14916                                      sip_reg_timeout,
14917                                      sip_poke_peer_s,
14918                                      sip_poke_noanswer,
14919                                      sip_reregister,
14920                                      sip_reinvite_retry}};
14921    
14922    switch (cmd) {
14923    case CLI_INIT:
14924       e->command = "sip show sched";
14925       e->usage =
14926          "Usage: sip show sched\n"
14927          "       Shows stats on what's in the sched queue at the moment\n";
14928       return NULL;
14929    case CLI_GENERATE:
14930       return NULL;
14931    }
14932 
14933    cbuf = ast_str_alloca(2048);
14934 
14935    ast_cli(a->fd, "\n");
14936    ast_sched_report(sched, &cbuf, &cbnames);
14937    ast_cli(a->fd, "%s", cbuf->str);
14938 
14939    return CLI_SUCCESS;
14940 }
14941 
14942 /*! \brief  Show SIP Registry (registrations with other SIP proxies */
14943 static char *sip_show_registry(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14944 {
14945 #define FORMAT2 "%-30.30s %-6.6s %-12.12s  %8.8s %-20.20s %-25.25s\n"
14946 #define FORMAT  "%-30.30s %-6.6s %-12.12s  %8d %-20.20s %-25.25s\n"
14947    char host[80];
14948    char tmpdat[256];
14949    struct ast_tm tm;
14950    int counter = 0;
14951 
14952    switch (cmd) {
14953    case CLI_INIT:
14954       e->command = "sip show registry";
14955       e->usage =
14956          "Usage: sip show registry\n"
14957          "       Lists all registration requests and status.\n";
14958       return NULL;
14959    case CLI_GENERATE:
14960       return NULL;
14961    }
14962 
14963    if (a->argc != 3)
14964       return CLI_SHOWUSAGE;
14965    ast_cli(a->fd, FORMAT2, "Host", "dnsmgr", "Username", "Refresh", "State", "Reg.Time");
14966    
14967    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
14968       ASTOBJ_RDLOCK(iterator);
14969       snprintf(host, sizeof(host), "%s:%d", iterator->hostname, iterator->portno ? iterator->portno : STANDARD_SIP_PORT);
14970       if (iterator->regtime.tv_sec) {
14971          ast_localtime(&iterator->regtime, &tm, NULL);
14972          ast_strftime(tmpdat, sizeof(tmpdat), "%a, %d %b %Y %T", &tm);
14973       } else 
14974          tmpdat[0] = '\0';
14975       ast_cli(a->fd, FORMAT, host, (iterator->dnsmgr) ? "Y" : "N", iterator->username, iterator->refresh, regstate2str(iterator->regstate), tmpdat);
14976       ASTOBJ_UNLOCK(iterator);
14977       counter++;
14978    } while(0));
14979    ast_cli(a->fd, "%d SIP registrations.\n", counter);
14980    return CLI_SUCCESS;
14981 #undef FORMAT
14982 #undef FORMAT2
14983 }
14984 
14985 /*! \brief Unregister (force expiration) a SIP peer in the registry via CLI 
14986    \note This function does not tell the SIP device what's going on,
14987    so use it with great care.
14988 */
14989 static char *sip_unregister(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
14990 {
14991    struct sip_peer *peer;
14992    int load_realtime = 0;
14993 
14994    switch (cmd) {
14995    case CLI_INIT:
14996       e->command = "sip unregister";
14997       e->usage =
14998          "Usage: sip unregister <peer>\n"
14999          "       Unregister (force expiration) a SIP peer from the registry\n";
15000       return NULL;
15001    case CLI_GENERATE:
15002       return complete_sip_unregister(a->line, a->word, a->pos, a->n);
15003    }
15004    
15005    if (a->argc != 3)
15006       return CLI_SHOWUSAGE;
15007    
15008    if ((peer = find_peer(a->argv[2], NULL, load_realtime, FINDPEERS, TRUE, 0))) {
15009       if (peer->expire > 0) {
15010          AST_SCHED_DEL_UNREF(sched, peer->expire,
15011             unref_peer(peer, "remove register expire ref"));
15012          expire_register(ref_peer(peer, "ref for expire_register"));
15013          ast_cli(a->fd, "Unregistered peer \'%s\'\n\n", a->argv[2]);
15014       } else {
15015          ast_cli(a->fd, "Peer %s not registered\n", a->argv[2]);
15016       }
15017       unref_peer(peer, "sip_unregister: unref_peer via sip_unregister: done with peer from find_peer call");
15018    } else {
15019       ast_cli(a->fd, "Peer unknown: \'%s\'. Not unregistered.\n", a->argv[2]);
15020    }
15021    
15022    return CLI_SUCCESS;
15023 }
15024 
15025 /*! \brief Callback for show_chanstats */
15026 static int show_chanstats_cb(void *__cur, void *__arg, int flags)
15027 {
15028 #define FORMAT2 "%-15.15s  %-11.11s  %-8.8s %-10.10s  %-10.10s (%-2.2s) %-6.6s %-10.10s  %-10.10s ( %%) %-6.6s\n"
15029 #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"
15030    struct sip_pvt *cur = __cur;
15031    unsigned int rxcount;
15032    unsigned int txcount;
15033    char durbuf[10];
15034         int duration;
15035         int durh, durm, durs;
15036    struct ast_channel *c = cur->owner;
15037    struct __show_chan_arg *arg = __arg;
15038    int fd = arg->fd;
15039 
15040 
15041    if (cur->subscribed != NONE) /* Subscriptions */
15042       return 0;   /* don't care, we scan all channels */
15043 
15044    if (!cur->rtp) {
15045       if (sipdebug)
15046          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");
15047       return 0;   /* don't care, we scan all channels */
15048    }
15049    rxcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXCOUNT);
15050    txcount = ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXCOUNT);
15051 
15052    /* Find the duration of this channel */
15053    if (c && c->cdr && !ast_tvzero(c->cdr->start)) {
15054       duration = (int)(ast_tvdiff_ms(ast_tvnow(), c->cdr->start) / 1000);
15055       durh = duration / 3600;
15056       durm = (duration % 3600) / 60;
15057       durs = duration % 60;
15058       snprintf(durbuf, sizeof(durbuf), "%02d:%02d:%02d", durh, durm, durs);
15059    } else {
15060       durbuf[0] = '\0';
15061    }
15062    /* Print stats for every call with RTP */
15063    ast_cli(fd, FORMAT, 
15064       ast_inet_ntoa(cur->sa.sin_addr), 
15065       cur->callid, 
15066       durbuf,
15067       rxcount > (unsigned int) 100000 ? (unsigned int) (rxcount)/(unsigned int) 1000 : rxcount,
15068       rxcount > (unsigned int) 100000 ? "K":" ",
15069       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS),
15070       rxcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXPLOSS) / rxcount * 100) : 0,
15071       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_RXJITTER),
15072       txcount > (unsigned int) 100000 ? (unsigned int) (txcount)/(unsigned int) 1000 : txcount,
15073       txcount > (unsigned int) 100000 ? "K":" ",
15074       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS),
15075       txcount > ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS) ? (unsigned int) (ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXPLOSS)/ txcount * 100) : 0,
15076       ast_rtp_get_qosvalue(cur->rtp, AST_RTP_TXJITTER)
15077    );
15078    arg->numchans++;
15079 
15080    return 0;   /* don't care, we scan all channels */
15081 }
15082 
15083 /*! \brief SIP show channelstats CLI (main function) */
15084 static char *sip_show_channelstats(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15085 {
15086    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15087 
15088    switch (cmd) {
15089    case CLI_INIT:
15090       e->command = "sip show channelstats";
15091       e->usage =
15092          "Usage: sip show channelstats\n"
15093          "       Lists all currently active SIP channel's RTCP statistics.\n"
15094          "       Note that calls in the much optimized RTP P2P bridge mode will not show any packets here.";
15095       return NULL;
15096    case CLI_GENERATE:
15097       return NULL;
15098    }
15099 
15100    if (a->argc != 3)
15101       return CLI_SHOWUSAGE;
15102 
15103    ast_cli(a->fd, FORMAT2, "Peer", "Call ID", "Duration", "Recv: Pack", "Lost", "%", "Jitter", "Send: Pack", "Lost", "Jitter");
15104    /* iterate on the container and invoke the callback on each item */
15105    ao2_t_callback(dialogs, OBJ_NODATA, show_chanstats_cb, &arg, "callback to sip show chanstats");
15106    ast_cli(a->fd, "%d active SIP channel%s\n", arg.numchans, (arg.numchans != 1) ? "s" : ""); 
15107    return CLI_SUCCESS;
15108 }
15109 #undef FORMAT
15110 #undef FORMAT2
15111 
15112 /*! \brief List global settings for the SIP channel */
15113 static char *sip_show_settings(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15114 {
15115    int realtimepeers;
15116    int realtimeregs;
15117    char codec_buf[SIPBUFSIZE];
15118    const char *msg;  /* temporary msg pointer */
15119 
15120    switch (cmd) {
15121    case CLI_INIT:
15122       e->command = "sip show settings";
15123       e->usage =
15124          "Usage: sip show settings\n"
15125          "       Provides detailed list of the configuration of the SIP channel.\n";
15126       return NULL;
15127    case CLI_GENERATE:
15128       return NULL;
15129    }
15130 
15131 
15132    realtimepeers = ast_check_realtime("sippeers");
15133    realtimeregs = ast_check_realtime("sipregs");
15134 
15135    if (a->argc != 3)
15136       return CLI_SHOWUSAGE;
15137    ast_cli(a->fd, "\n\nGlobal Settings:\n");
15138    ast_cli(a->fd, "----------------\n");
15139    ast_cli(a->fd, "  UDP SIP Port:           %d\n", ntohs(bindaddr.sin_port));
15140    ast_cli(a->fd, "  UDP Bindaddress:        %s\n", ast_inet_ntoa(bindaddr.sin_addr));
15141    ast_cli(a->fd, "  TCP SIP Port:           ");
15142    if (sip_tcp_desc.local_address.sin_family == AF_INET) {
15143       ast_cli(a->fd, "%d\n", ntohs(sip_tcp_desc.local_address.sin_port));
15144       ast_cli(a->fd, "  TCP Bindaddress:        %s\n", ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr));
15145    } else {
15146       ast_cli(a->fd, "Disabled\n");
15147    }
15148    ast_cli(a->fd, "  TLS SIP Port:           ");
15149    if (default_tls_cfg.enabled != FALSE) {
15150       ast_cli(a->fd, "%d\n", ntohs(sip_tls_desc.local_address.sin_port));
15151       ast_cli(a->fd, "  TLS Bindaddress:        %s\n", ast_inet_ntoa(sip_tls_desc.local_address.sin_addr));
15152    } else {
15153       ast_cli(a->fd, "Disabled\n");
15154    }
15155    ast_cli(a->fd, "  Videosupport:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT)));
15156    ast_cli(a->fd, "  Textsupport:            %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT)));
15157    ast_cli(a->fd, "  AutoCreate Peer:        %s\n", cli_yesno(autocreatepeer));
15158    ast_cli(a->fd, "  Ignore SDP sess. ver.:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION)));
15159    ast_cli(a->fd, "  Match Auth Username:    %s\n", cli_yesno(global_match_auth_username));
15160    ast_cli(a->fd, "  Allow unknown access:   %s\n", cli_yesno(global_allowguest));
15161    ast_cli(a->fd, "  Allow subscriptions:    %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)));
15162    ast_cli(a->fd, "  Allow overlap dialing:  %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP)));
15163    ast_cli(a->fd, "  Allow promsic. redir:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_PROMISCREDIR)));
15164    ast_cli(a->fd, "  Enable call counters:   %s\n", cli_yesno(global_callcounter));
15165    ast_cli(a->fd, "  SIP domain support:     %s\n", cli_yesno(!AST_LIST_EMPTY(&domain_list)));
15166    ast_cli(a->fd, "  Realm. auth:            %s\n", cli_yesno(authl != NULL));
15167    ast_cli(a->fd, "  Our auth realm          %s\n", global_realm);
15168    ast_cli(a->fd, "  Call to non-local dom.: %s\n", cli_yesno(allow_external_domains));
15169    ast_cli(a->fd, "  URI user is phone no:   %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USEREQPHONE)));
15170    ast_cli(a->fd, "  Always auth rejects:    %s\n", cli_yesno(global_alwaysauthreject));
15171    ast_cli(a->fd, "  Direct RTP setup:       %s\n", cli_yesno(global_directrtpsetup));
15172    ast_cli(a->fd, "  User Agent:             %s\n", global_useragent);
15173    ast_cli(a->fd, "  SDP Session Name:       %s\n", ast_strlen_zero(global_sdpsession) ? "-" : global_sdpsession);
15174    ast_cli(a->fd, "  SDP Owner Name:         %s\n", ast_strlen_zero(global_sdpowner) ? "-" : global_sdpowner);
15175    ast_cli(a->fd, "  Reg. context:           %s\n", S_OR(global_regcontext, "(not set)"));
15176    ast_cli(a->fd, "  Regexten on Qualify:    %s\n", cli_yesno(global_regextenonqualify));
15177    ast_cli(a->fd, "  Caller ID:              %s\n", default_callerid);
15178    ast_cli(a->fd, "  From: Domain:           %s\n", default_fromdomain);
15179    ast_cli(a->fd, "  Record SIP history:     %s\n", recordhistory ? "On" : "Off");
15180    ast_cli(a->fd, "  Call Events:            %s\n", global_callevents ? "On" : "Off");
15181    ast_cli(a->fd, "  Auth. Failure Events:   %s\n", global_authfailureevents ? "On" : "Off");
15182 
15183    ast_cli(a->fd, "  T.38 support:           %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15184    ast_cli(a->fd, "  T.38 EC mode:           %s\n", faxec2str(ast_test_flag(&global_flags[1], SIP_PAGE2_T38SUPPORT)));
15185    ast_cli(a->fd, "  T.38 MaxDtgrm:          %d\n", global_t38_maxdatagram);
15186 
15187    if (!realtimepeers && !realtimeregs)
15188       ast_cli(a->fd, "  SIP realtime:           Disabled\n" );
15189    else
15190       ast_cli(a->fd, "  SIP realtime:           Enabled\n" );
15191    ast_cli(a->fd, "  Qualify Freq :          %d ms\n", global_qualifyfreq);
15192    ast_cli(a->fd, "\nNetwork QoS Settings:\n");
15193    ast_cli(a->fd, "---------------------------\n");
15194    ast_cli(a->fd, "  IP ToS SIP:             %s\n", ast_tos2str(global_tos_sip));
15195    ast_cli(a->fd, "  IP ToS RTP audio:       %s\n", ast_tos2str(global_tos_audio));
15196    ast_cli(a->fd, "  IP ToS RTP video:       %s\n", ast_tos2str(global_tos_video));
15197    ast_cli(a->fd, "  IP ToS RTP text:        %s\n", ast_tos2str(global_tos_text));
15198    ast_cli(a->fd, "  802.1p CoS SIP:         %d\n", global_cos_sip);
15199    ast_cli(a->fd, "  802.1p CoS RTP audio:   %d\n", global_cos_audio);
15200    ast_cli(a->fd, "  802.1p CoS RTP video:   %d\n", global_cos_video);
15201    ast_cli(a->fd, "  802.1p CoS RTP text:    %d\n", global_cos_text);
15202    ast_cli(a->fd, "  Jitterbuffer enabled:   %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_ENABLED)));
15203    ast_cli(a->fd, "  Jitterbuffer forced:    %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_FORCED)));
15204    ast_cli(a->fd, "  Jitterbuffer max size:  %ld\n", global_jbconf.max_size);
15205    ast_cli(a->fd, "  Jitterbuffer resync:    %ld\n", global_jbconf.resync_threshold);
15206    ast_cli(a->fd, "  Jitterbuffer impl:      %s\n", global_jbconf.impl);
15207    ast_cli(a->fd, "  Jitterbuffer log:       %s\n", cli_yesno(ast_test_flag(&global_jbconf, AST_JB_LOG)));
15208 
15209    ast_cli(a->fd, "\nNetwork Settings:\n");
15210    ast_cli(a->fd, "---------------------------\n");
15211    /* determine if/how SIP address can be remapped */
15212    if (localaddr == NULL)
15213       msg = "Disabled, no localnet list";
15214    else if (externip.sin_addr.s_addr == 0)
15215       msg = "Disabled, externip is 0.0.0.0";
15216    else if (stunaddr.sin_addr.s_addr != 0)
15217       msg = "Enabled using STUN";
15218    else if (!ast_strlen_zero(externhost))
15219       msg = "Enabled using externhost";
15220    else
15221       msg = "Enabled using externip";
15222    ast_cli(a->fd, "  SIP address remapping:  %s\n", msg);
15223    ast_cli(a->fd, "  Externhost:             %s\n", S_OR(externhost, "<none>"));
15224    ast_cli(a->fd, "  Externip:               %s:%d\n", ast_inet_ntoa(externip.sin_addr), ntohs(externip.sin_port));
15225    ast_cli(a->fd, "  Externrefresh:          %d\n", externrefresh);
15226    ast_cli(a->fd, "  Internal IP:            %s:%d\n", ast_inet_ntoa(internip.sin_addr), ntohs(internip.sin_port));
15227    {
15228       struct ast_ha *d;
15229       const char *prefix = "Localnet:";
15230       char buf[INET_ADDRSTRLEN]; /* need to print two addresses */
15231 
15232       for (d = localaddr; d ; prefix = "", d = d->next) {
15233          ast_cli(a->fd, "  %-24s%s/%s\n",
15234              prefix, ast_inet_ntoa(d->netaddr),
15235              inet_ntop(AF_INET, &d->netmask, buf, sizeof(buf)) );
15236       }
15237    }
15238    ast_cli(a->fd, "  STUN server:            %s:%d\n", ast_inet_ntoa(stunaddr.sin_addr), ntohs(stunaddr.sin_port));
15239  
15240    ast_cli(a->fd, "\nGlobal Signalling Settings:\n");
15241    ast_cli(a->fd, "---------------------------\n");
15242    ast_cli(a->fd, "  Codecs:                 ");
15243    ast_getformatname_multiple(codec_buf, sizeof(codec_buf) -1, global_capability);
15244    ast_cli(a->fd, "%s\n", codec_buf);
15245    ast_cli(a->fd, "  Codec Order:            ");
15246    print_codec_to_cli(a->fd, &default_prefs);
15247    ast_cli(a->fd, "\n");
15248    ast_cli(a->fd, "  Relax DTMF:             %s\n", cli_yesno(global_relaxdtmf));
15249    ast_cli(a->fd, "  RFC2833 Compensation:   %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RFC2833_COMPENSATE)));
15250    ast_cli(a->fd, "  Compact SIP headers:    %s\n", cli_yesno(compactheaders));
15251    ast_cli(a->fd, "  RTP Keepalive:          %d %s\n", global_rtpkeepalive, global_rtpkeepalive ? "" : "(Disabled)" );
15252    ast_cli(a->fd, "  RTP Timeout:            %d %s\n", global_rtptimeout, global_rtptimeout ? "" : "(Disabled)" );
15253    ast_cli(a->fd, "  RTP Hold Timeout:       %d %s\n", global_rtpholdtimeout, global_rtpholdtimeout ? "" : "(Disabled)");
15254    ast_cli(a->fd, "  MWI NOTIFY mime type:   %s\n", default_notifymime);
15255    ast_cli(a->fd, "  DNS SRV lookup:         %s\n", cli_yesno(global_srvlookup));
15256    ast_cli(a->fd, "  Pedantic SIP support:   %s\n", cli_yesno(pedanticsipchecking));
15257    ast_cli(a->fd, "  Reg. min duration       %d secs\n", min_expiry);
15258    ast_cli(a->fd, "  Reg. max duration:      %d secs\n", max_expiry);
15259    ast_cli(a->fd, "  Reg. default duration:  %d secs\n", default_expiry);
15260    ast_cli(a->fd, "  Outbound reg. timeout:  %d secs\n", global_reg_timeout);
15261    ast_cli(a->fd, "  Outbound reg. attempts: %d\n", global_regattempts_max);
15262    ast_cli(a->fd, "  Notify ringing state:   %s\n", cli_yesno(global_notifyringing));
15263    ast_cli(a->fd, "  Notify hold state:      %s\n", cli_yesno(global_notifyhold));
15264    ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(global_allowtransfer));
15265    ast_cli(a->fd, "  Max Call Bitrate:       %d kbps\n", default_maxcallbitrate);
15266    ast_cli(a->fd, "  Auto-Framing:           %s\n", cli_yesno(global_autoframing));
15267    ast_cli(a->fd, "  Outb. proxy:            %s %s\n", ast_strlen_zero(global_outboundproxy.name) ? "<not set>" : global_outboundproxy.name,
15268                      global_outboundproxy.force ? "(forced)" : "");
15269    ast_cli(a->fd, "  Session Timers:         %s\n", stmode2str(global_st_mode));
15270    ast_cli(a->fd, "  Session Refresher:      %s\n", strefresher2str (global_st_refresher));
15271    ast_cli(a->fd, "  Session Expires:        %d secs\n", global_max_se);
15272    ast_cli(a->fd, "  Session Min-SE:         %d secs\n", global_min_se);
15273    ast_cli(a->fd, "  Timer T1:               %d\n", global_t1);
15274    ast_cli(a->fd, "  Timer T1 minimum:       %d\n", global_t1min);
15275    ast_cli(a->fd, "  Timer B:                %d\n", global_timer_b);
15276    ast_cli(a->fd, "  No premature media:     %s\n", global_prematuremediafilter ? "Yes" : "No");
15277 
15278    ast_cli(a->fd, "\nDefault Settings:\n");
15279    ast_cli(a->fd, "-----------------\n");
15280    ast_cli(a->fd, "  Context:                %s\n", default_context);
15281    ast_cli(a->fd, "  Nat:                    %s\n", nat2str(ast_test_flag(&global_flags[0], SIP_NAT)));
15282    ast_cli(a->fd, "  DTMF:                   %s\n", dtmfmode2str(ast_test_flag(&global_flags[0], SIP_DTMF)));
15283    ast_cli(a->fd, "  Qualify:                %d\n", default_qualify);
15284    ast_cli(a->fd, "  Use ClientCode:         %s\n", cli_yesno(ast_test_flag(&global_flags[0], SIP_USECLIENTCODE)));
15285    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" );
15286    ast_cli(a->fd, "  Language:               %s\n", default_language);
15287    ast_cli(a->fd, "  MOH Interpret:          %s\n", default_mohinterpret);
15288    ast_cli(a->fd, "  MOH Suggest:            %s\n", default_mohsuggest);
15289    ast_cli(a->fd, "  Voice Mail Extension:   %s\n", default_vmexten);
15290 
15291    
15292    if (realtimepeers || realtimeregs) {
15293       ast_cli(a->fd, "\nRealtime SIP Settings:\n");
15294       ast_cli(a->fd, "----------------------\n");
15295       ast_cli(a->fd, "  Realtime Peers:         %s\n", cli_yesno(realtimepeers));
15296       ast_cli(a->fd, "  Realtime Regs:          %s\n", cli_yesno(realtimeregs));
15297       ast_cli(a->fd, "  Cache Friends:          %s\n", cli_yesno(ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)));
15298       ast_cli(a->fd, "  Update:                 %s\n", cli_yesno(sip_cfg.peer_rtupdate));
15299       ast_cli(a->fd, "  Ignore Reg. Expire:     %s\n", cli_yesno(sip_cfg.ignore_regexpire));
15300       ast_cli(a->fd, "  Save sys. name:         %s\n", cli_yesno(sip_cfg.rtsave_sysname));
15301       ast_cli(a->fd, "  Auto Clear:             %d\n", global_rtautoclear);
15302    }
15303    ast_cli(a->fd, "\n----\n");
15304    return CLI_SUCCESS;
15305 }
15306 
15307 /*! \brief Show subscription type in string format */
15308 static const char *subscription_type2str(enum subscriptiontype subtype)
15309 {
15310    int i;
15311 
15312    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
15313       if (subscription_types[i].type == subtype) {
15314          return subscription_types[i].text;
15315       }
15316    }
15317    return subscription_types[0].text;
15318 }
15319 
15320 /*! \brief Find subscription type in array */
15321 static const struct cfsubscription_types *find_subscription_type(enum subscriptiontype subtype)
15322 {
15323    int i;
15324 
15325    for (i = 1; i < ARRAY_LEN(subscription_types); i++) {
15326       if (subscription_types[i].type == subtype) {
15327          return &subscription_types[i];
15328       }
15329    }
15330    return &subscription_types[0];
15331 }
15332 
15333 /*
15334  * We try to structure all functions that loop on data structures as
15335  * a handler for individual entries, and a mainloop that iterates
15336  * on the main data structure. This way, moving the code to containers
15337  * that support iteration through callbacks will be a lot easier.
15338  */
15339 
15340 #define FORMAT4 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6d\n"
15341 #define FORMAT3 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-13.13s  %-15.15s %-10.10s %-6.6s\n"
15342 #define FORMAT2 "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-7.7s  %-15.15s %-6.6s\n"
15343 #define FORMAT  "%-15.15s  %-15.15s  %-15.15s  %-15.15s  %-3.3s %-3.3s  %-15.15s %-10.10s\n"
15344 
15345 /*! \brief callback for show channel|subscription */
15346 static int show_channels_cb(void *__cur, void *__arg, int flags)
15347 {
15348    struct sip_pvt *cur = __cur;
15349    struct __show_chan_arg *arg = __arg;
15350    const struct sockaddr_in *dst = sip_real_dst(cur);
15351    
15352    /* XXX indentation preserved to reduce diff. Will be fixed later */
15353    if (cur->subscribed == NONE && !arg->subscriptions) {
15354       /* set if SIP transfer in progress */
15355       const char *referstatus = cur->refer ? referstatus2str(cur->refer->status) : "";
15356       char formatbuf[SIPBUFSIZE/2];
15357       
15358       ast_cli(arg->fd, FORMAT, ast_inet_ntoa(dst->sin_addr), 
15359             S_OR(cur->username, S_OR(cur->cid_num, "(None)")),
15360             cur->callid, 
15361             ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0),
15362             cli_yesno(ast_test_flag(&cur->flags[1], SIP_PAGE2_CALL_ONHOLD)),
15363             cur->needdestroy ? "(d)" : "",
15364             cur->lastmsg ,
15365             referstatus
15366          );
15367       arg->numchans++;
15368    }
15369    if (cur->subscribed != NONE && arg->subscriptions) {
15370       struct ast_str *mailbox_str = ast_str_alloca(512);
15371       if (cur->subscribed == MWI_NOTIFICATION && cur->relatedpeer)
15372          peer_mailboxes_to_str(&mailbox_str, cur->relatedpeer);
15373       ast_cli(arg->fd, FORMAT4, ast_inet_ntoa(dst->sin_addr),
15374             S_OR(cur->username, S_OR(cur->cid_num, "(None)")), 
15375                cur->callid,
15376             /* the 'complete' exten/context is hidden in the refer_to field for subscriptions */
15377             cur->subscribed == MWI_NOTIFICATION ? "--" : cur->subscribeuri,
15378             cur->subscribed == MWI_NOTIFICATION ? "<none>" : ast_extension_state2str(cur->laststate), 
15379             subscription_type2str(cur->subscribed),
15380             cur->subscribed == MWI_NOTIFICATION ? S_OR(mailbox_str->str, "<none>") : "<none>",
15381             cur->expiry
15382          );
15383       arg->numchans++;
15384    }
15385    return 0;   /* don't care, we scan all channels */
15386 }
15387 
15388 /*! \brief CLI for show channels or subscriptions.
15389  * This is a new-style CLI handler so a single function contains
15390  * the prototype for the function, the 'generator' to produce multiple
15391  * entries in case it is required, and the actual handler for the command.
15392  */
15393 static char *sip_show_channels(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15394 {
15395    struct __show_chan_arg arg = { .fd = a->fd, .numchans = 0 };
15396 
15397 
15398    if (cmd == CLI_INIT) {
15399       e->command = "sip show {channels|subscriptions}";
15400       e->usage =
15401          "Usage: sip show channels\n"
15402          "       Lists all currently active SIP calls (dialogs).\n"
15403          "Usage: sip show subscriptions\n"
15404          "       Lists active SIP subscriptions.\n";
15405       return NULL;
15406    } else if (cmd == CLI_GENERATE)
15407       return NULL;
15408 
15409    if (a->argc != e->args)
15410       return CLI_SHOWUSAGE;
15411    arg.subscriptions = !strcasecmp(a->argv[e->args - 1], "subscriptions");
15412    if (!arg.subscriptions)
15413       ast_cli(arg.fd, FORMAT2, "Peer", "User/ANR", "Call ID", "Format", "Hold", "Last Message", "Expiry");
15414    else
15415       ast_cli(arg.fd, FORMAT3, "Peer", "User", "Call ID", "Extension", "Last state", "Type", "Mailbox", "Expiry");
15416 
15417    /* iterate on the container and invoke the callback on each item */
15418    ao2_t_callback(dialogs, OBJ_NODATA, show_channels_cb, &arg, "callback to show channels");
15419    
15420    /* print summary information */
15421    ast_cli(arg.fd, "%d active SIP %s%s\n", arg.numchans,
15422       (arg.subscriptions ? "subscription" : "dialog"),
15423       ESS(arg.numchans));  /* ESS(n) returns an "s" if n>1 */
15424    return CLI_SUCCESS;
15425 #undef FORMAT
15426 #undef FORMAT2
15427 #undef FORMAT3
15428 }
15429 
15430 /*! \brief Support routine for 'sip show channel' and 'sip show history' CLI
15431  * This is in charge of generating all strings that match a prefix in the
15432  * given position. As many functions of this kind, each invokation has
15433  * O(state) time complexity so be careful in using it.
15434  */
15435 static char *complete_sipch(const char *line, const char *word, int pos, int state)
15436 {
15437    int which=0;
15438    struct sip_pvt *cur;
15439    char *c = NULL;
15440    int wordlen = strlen(word);
15441    struct ao2_iterator i;
15442 
15443    if (pos != 3) {
15444       return NULL;
15445    }
15446 
15447    i = ao2_iterator_init(dialogs, 0);
15448    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15449       sip_pvt_lock(cur);
15450       if (!strncasecmp(word, cur->callid, wordlen) && ++which > state) {
15451          c = ast_strdup(cur->callid);
15452          sip_pvt_unlock(cur);
15453          dialog_unref(cur, "drop ref in iterator loop break");
15454          break;
15455       }
15456       sip_pvt_unlock(cur);
15457       dialog_unref(cur, "drop ref in iterator loop");
15458    }
15459    ao2_iterator_destroy(&i);
15460    return c;
15461 }
15462 
15463 
15464 /*! \brief Do completion on peer name */
15465 static char *complete_sip_peer(const char *word, int state, int flags2)
15466 {
15467    char *result = NULL;
15468    int wordlen = strlen(word);
15469    int which = 0;
15470    struct ao2_iterator i = ao2_iterator_init(peers, 0);
15471    struct sip_peer *peer;
15472 
15473    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15474       /* locking of the object is not required because only the name and flags are being compared */
15475       if (!strncasecmp(word, peer->name, wordlen) &&
15476             (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
15477             ++which > state)
15478          result = ast_strdup(peer->name);
15479       unref_peer(peer, "toss iterator peer ptr before break");
15480       if (result) {
15481          break;
15482       }
15483    }
15484    ao2_iterator_destroy(&i);
15485    return result;
15486 }
15487 
15488 /*! \brief Do completion on registered peer name */
15489 static char *complete_sip_registered_peer(const char *word, int state, int flags2)
15490 {
15491        char *result = NULL;
15492        int wordlen = strlen(word);
15493        int which = 0;
15494        struct ao2_iterator i;
15495        struct sip_peer *peer;
15496        
15497        i = ao2_iterator_init(peers, 0);
15498        while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
15499           if (!strncasecmp(word, peer->name, wordlen) &&
15500          (!flags2 || ast_test_flag(&peer->flags[1], flags2)) &&
15501          ++which > state && peer->expire > 0)
15502              result = ast_strdup(peer->name);
15503           if (result) {
15504              unref_peer(peer, "toss iterator peer ptr before break");
15505              break;
15506           }
15507           unref_peer(peer, "toss iterator peer ptr");
15508        }
15509        ao2_iterator_destroy(&i);
15510        return result;
15511 }
15512 
15513 /*! \brief Support routine for 'sip show history' CLI */
15514 static char *complete_sip_show_history(const char *line, const char *word, int pos, int state)
15515 {
15516    if (pos == 3)
15517       return complete_sipch(line, word, pos, state);
15518 
15519    return NULL;
15520 }
15521 
15522 /*! \brief Support routine for 'sip show peer' CLI */
15523 static char *complete_sip_show_peer(const char *line, const char *word, int pos, int state)
15524 {
15525    if (pos == 3) {
15526       return complete_sip_peer(word, state, 0);
15527    }
15528 
15529    return NULL;
15530 }
15531 
15532 /*! \brief Support routine for 'sip unregister' CLI */
15533 static char *complete_sip_unregister(const char *line, const char *word, int pos, int state)
15534 {
15535        if (pos == 2)
15536                return complete_sip_registered_peer(word, state, 0);
15537 
15538        return NULL;
15539 }
15540 
15541 /*! \brief Support routine for 'sip notify' CLI */
15542 static char *complete_sipnotify(const char *line, const char *word, int pos, int state)
15543 {
15544    char *c = NULL;
15545 
15546    if (pos == 2) {
15547       int which = 0;
15548       char *cat = NULL;
15549       int wordlen = strlen(word);
15550 
15551       /* do completion for notify type */
15552 
15553       if (!notify_types)
15554          return NULL;
15555       
15556       while ( (cat = ast_category_browse(notify_types, cat)) ) {
15557          if (!strncasecmp(word, cat, wordlen) && ++which > state) {
15558             c = ast_strdup(cat);
15559             break;
15560          }
15561       }
15562       return c;
15563    }
15564 
15565    if (pos > 2)
15566       return complete_sip_peer(word, state, 0);
15567 
15568    return NULL;
15569 }
15570 
15571 /*! \brief Show details of one active dialog */
15572 static char *sip_show_channel(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15573 {
15574    struct sip_pvt *cur;
15575    size_t len;
15576    int found = 0;
15577    struct ao2_iterator i;
15578 
15579    switch (cmd) {
15580    case CLI_INIT:
15581       e->command = "sip show channel";
15582       e->usage =
15583          "Usage: sip show channel <call-id>\n"
15584          "       Provides detailed status on a given SIP dialog (identified by SIP call-id).\n";
15585       return NULL;
15586    case CLI_GENERATE:
15587       return complete_sipch(a->line, a->word, a->pos, a->n);
15588    }
15589 
15590    if (a->argc != 4)
15591       return CLI_SHOWUSAGE;
15592    len = strlen(a->argv[3]);
15593    
15594    i = ao2_iterator_init(dialogs, 0);
15595    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15596       sip_pvt_lock(cur);
15597 
15598       if (!strncasecmp(cur->callid, a->argv[3], len)) {
15599          char formatbuf[SIPBUFSIZE/2];
15600          ast_cli(a->fd, "\n");
15601          if (cur->subscribed != NONE)
15602             ast_cli(a->fd, "  * Subscription (type: %s)\n", subscription_type2str(cur->subscribed));
15603          else
15604             ast_cli(a->fd, "  * SIP Call\n");
15605          ast_cli(a->fd, "  Curr. trans. direction:  %s\n", ast_test_flag(&cur->flags[0], SIP_OUTGOING) ? "Outgoing" : "Incoming");
15606          ast_cli(a->fd, "  Call-ID:                %s\n", cur->callid);
15607          ast_cli(a->fd, "  Owner channel ID:       %s\n", cur->owner ? cur->owner->name : "<none>");
15608          ast_cli(a->fd, "  Our Codec Capability:   %d\n", cur->capability);
15609          ast_cli(a->fd, "  Non-Codec Capability (DTMF):   %d\n", cur->noncodeccapability);
15610          ast_cli(a->fd, "  Their Codec Capability:   %d\n", cur->peercapability);
15611          ast_cli(a->fd, "  Joint Codec Capability:   %d\n", cur->jointcapability);
15612          ast_cli(a->fd, "  Format:                 %s\n", ast_getformatname_multiple(formatbuf, sizeof(formatbuf), cur->owner ? cur->owner->nativeformats : 0) );
15613          ast_cli(a->fd, "  T.38 support            %s\n", cli_yesno(cur->udptl != NULL));
15614          ast_cli(a->fd, "  Video support           %s\n", cli_yesno(cur->vrtp != NULL));
15615          ast_cli(a->fd, "  MaxCallBR:              %d kbps\n", cur->maxcallbitrate);
15616          ast_cli(a->fd, "  Theoretical Address:    %s:%d\n", ast_inet_ntoa(cur->sa.sin_addr), ntohs(cur->sa.sin_port));
15617          ast_cli(a->fd, "  Received Address:       %s:%d\n", ast_inet_ntoa(cur->recv.sin_addr), ntohs(cur->recv.sin_port));
15618          ast_cli(a->fd, "  SIP Transfer mode:      %s\n", transfermode2str(cur->allowtransfer));
15619          ast_cli(a->fd, "  NAT Support:            %s\n", nat2str(ast_test_flag(&cur->flags[0], SIP_NAT)));
15620          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)" );
15621          ast_cli(a->fd, "  Our Tag:                %s\n", cur->tag);
15622          ast_cli(a->fd, "  Their Tag:              %s\n", cur->theirtag);
15623          ast_cli(a->fd, "  SIP User agent:         %s\n", cur->useragent);
15624          if (!ast_strlen_zero(cur->username))
15625             ast_cli(a->fd, "  Username:               %s\n", cur->username);
15626          if (!ast_strlen_zero(cur->peername))
15627             ast_cli(a->fd, "  Peername:               %s\n", cur->peername);
15628          if (!ast_strlen_zero(cur->uri))
15629             ast_cli(a->fd, "  Original uri:           %s\n", cur->uri);
15630          if (!ast_strlen_zero(cur->cid_num))
15631             ast_cli(a->fd, "  Caller-ID:              %s\n", cur->cid_num);
15632          ast_cli(a->fd, "  Need Destroy:           %s\n", cli_yesno(cur->needdestroy));
15633          ast_cli(a->fd, "  Last Message:           %s\n", cur->lastmsg);
15634          ast_cli(a->fd, "  Promiscuous Redir:      %s\n", cli_yesno(ast_test_flag(&cur->flags[0], SIP_PROMISCREDIR)));
15635          ast_cli(a->fd, "  Route:                  %s\n", cur->route ? cur->route->hop : "N/A");
15636          ast_cli(a->fd, "  DTMF Mode:              %s\n", dtmfmode2str(ast_test_flag(&cur->flags[0], SIP_DTMF)));
15637          ast_cli(a->fd, "  SIP Options:            ");
15638          if (cur->sipoptions) {
15639             int x;
15640             for (x = 0 ; x < ARRAY_LEN(sip_options); x++) {
15641                if (cur->sipoptions & sip_options[x].id)
15642                   ast_cli(a->fd, "%s ", sip_options[x].text);
15643             }
15644             ast_cli(a->fd, "\n");
15645          } else
15646             ast_cli(a->fd, "(none)\n");
15647 
15648          if (!cur->stimer)
15649             ast_cli(a->fd, "  Session-Timer:          Uninitiallized\n");
15650          else {
15651             ast_cli(a->fd, "  Session-Timer:          %s\n", cur->stimer->st_active ? "Active" : "Inactive");
15652             if (cur->stimer->st_active == TRUE) {
15653                ast_cli(a->fd, "  S-Timer Interval:       %d\n", cur->stimer->st_interval);
15654                ast_cli(a->fd, "  S-Timer Refresher:      %s\n", strefresher2str(cur->stimer->st_ref));
15655                ast_cli(a->fd, "  S-Timer Expirys:        %d\n", cur->stimer->st_expirys);
15656                ast_cli(a->fd, "  S-Timer Sched Id:       %d\n", cur->stimer->st_schedid);
15657                ast_cli(a->fd, "  S-Timer Peer Sts:       %s\n", cur->stimer->st_active_peer_ua ? "Active" : "Inactive");
15658                ast_cli(a->fd, "  S-Timer Cached Min-SE:  %d\n", cur->stimer->st_cached_min_se);
15659                ast_cli(a->fd, "  S-Timer Cached SE:      %d\n", cur->stimer->st_cached_max_se);
15660                ast_cli(a->fd, "  S-Timer Cached Ref:     %s\n", strefresher2str(cur->stimer->st_cached_ref));
15661                ast_cli(a->fd, "  S-Timer Cached Mode:    %s\n", stmode2str(cur->stimer->st_cached_mode));
15662             }
15663          }
15664 
15665          ast_cli(a->fd, "\n\n");
15666 
15667          found++;
15668       }
15669 
15670       sip_pvt_unlock(cur);
15671 
15672       ao2_t_ref(cur, -1, "toss dialog ptr set by iterator_next");
15673    }
15674    ao2_iterator_destroy(&i);
15675 
15676    if (!found) 
15677       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15678 
15679    return CLI_SUCCESS;
15680 }
15681 
15682 /*! \brief Show history details of one dialog */
15683 static char *sip_show_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
15684 {
15685    struct sip_pvt *cur;
15686    size_t len;
15687    int found = 0;
15688    struct ao2_iterator i;
15689 
15690    switch (cmd) {
15691    case CLI_INIT:
15692       e->command = "sip show history";
15693       e->usage =
15694          "Usage: sip show history <call-id>\n"
15695          "       Provides detailed dialog history on a given SIP call (specified by call-id).\n";
15696       return NULL;
15697    case CLI_GENERATE:
15698       return complete_sip_show_history(a->line, a->word, a->pos, a->n);
15699    }
15700 
15701    if (a->argc != 4)
15702       return CLI_SHOWUSAGE;
15703 
15704    if (!recordhistory)
15705       ast_cli(a->fd, "\n***Note: History recording is currently DISABLED.  Use 'sip set history on' to ENABLE.\n");
15706 
15707    len = strlen(a->argv[3]);
15708 
15709    i = ao2_iterator_init(dialogs, 0);
15710    while ((cur = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
15711       sip_pvt_lock(cur);
15712       if (!strncasecmp(cur->callid, a->argv[3], len)) {
15713          struct sip_history *hist;
15714          int x = 0;
15715 
15716          ast_cli(a->fd, "\n");
15717          if (cur->subscribed != NONE)
15718             ast_cli(a->fd, "  * Subscription\n");
15719          else
15720             ast_cli(a->fd, "  * SIP Call\n");
15721          if (cur->history)
15722             AST_LIST_TRAVERSE(cur->history, hist, list)
15723                ast_cli(a->fd, "%d. %s\n", ++x, hist->event);
15724          if (x == 0)
15725             ast_cli(a->fd, "Call '%s' has no history\n", cur->callid);
15726          found++;
15727       }
15728       sip_pvt_unlock(cur);
15729       ao2_t_ref(cur, -1, "toss dialog ptr from iterator_next");
15730    }
15731    ao2_iterator_destroy(&i);
15732 
15733    if (!found) 
15734       ast_cli(a->fd, "No such SIP Call ID starting with '%s'\n", a->argv[3]);
15735 
15736    return CLI_SUCCESS;
15737 }
15738 
15739 /*! \brief Dump SIP history to debug log file at end of lifespan for SIP dialog */
15740 static void sip_dump_history(struct sip_pvt *dialog)
15741 {
15742    int x = 0;
15743    struct sip_history *hist;
15744    static int errmsg = 0;
15745 
15746    if (!dialog)
15747       return;
15748 
15749    if (!option_debug && !sipdebug) {
15750       if (!errmsg) {
15751          ast_log(LOG_NOTICE, "You must have debugging enabled (SIP or Asterisk) in order to dump SIP history.\n");
15752          errmsg = 1;
15753       }
15754       return;
15755    }
15756 
15757    ast_debug(1, "\n---------- SIP HISTORY for '%s' \n", dialog->callid);
15758    if (dialog->subscribed)
15759       ast_debug(1, "  * Subscription\n");
15760    else
15761       ast_debug(1, "  * SIP Call\n");
15762    if (dialog->history)
15763       AST_LIST_TRAVERSE(dialog->history, hist, list)
15764          ast_debug(1, "  %-3.3d. %s\n", ++x, hist->event);
15765    if (!x)
15766       ast_debug(1, "Call '%s' has no history\n", dialog->callid);
15767    ast_debug(1, "\n---------- END SIP HISTORY for '%s' \n", dialog->callid);
15768 }
15769 
15770 
15771 /*! \brief  Receive SIP INFO Message */
15772 static void handle_request_info(struct sip_pvt *p, struct sip_request *req)
15773 {
15774    char buf[1024];
15775    unsigned int event;
15776    const char *c = get_header(req, "Content-Type");
15777 
15778    /* Need to check the media/type */
15779    if (!strcasecmp(c, "application/dtmf-relay") ||
15780        !strcasecmp(c, "application/vnd.nortelnetworks.digits")) {
15781       unsigned int duration = 0;
15782 
15783       if (!p->owner) {  /* not a PBX call */
15784          transmit_response(p, "481 Call leg/transaction does not exist", req);
15785          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15786          return;
15787       }
15788 
15789       /* Try getting the "signal=" part */
15790       if (ast_strlen_zero(c = get_body(req, "Signal")) && ast_strlen_zero(c = get_body(req, "d"))) {
15791          ast_log(LOG_WARNING, "Unable to retrieve DTMF signal from INFO message from %s\n", p->callid);
15792          transmit_response(p, "200 OK", req); /* Should return error */
15793          return;
15794       } else {
15795          ast_copy_string(buf, c, sizeof(buf));
15796       }
15797 
15798       if (!ast_strlen_zero((c = get_body(req, "Duration"))))
15799          duration = atoi(c);
15800       if (!duration)
15801          duration = 100; /* 100 ms */
15802 
15803 
15804       if (ast_strlen_zero(buf)) {
15805          transmit_response(p, "200 OK", req);
15806          return;
15807       }
15808 
15809       if (buf[0] == '*')
15810          event = 10;
15811       else if (buf[0] == '#')
15812          event = 11;
15813       else if ((buf[0] >= 'A') && (buf[0] <= 'D'))
15814          event = 12 + buf[0] - 'A';
15815       else if (buf[0] == '!')
15816          event = 16;
15817       else
15818          event = atoi(buf);
15819       if (event == 16) {
15820          /* send a FLASH event */
15821          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15822          ast_queue_frame(p->owner, &f);
15823          if (sipdebug)
15824             ast_verbose("* DTMF-relay event received: FLASH\n");
15825       } else {
15826          /* send a DTMF event */
15827          struct ast_frame f = { AST_FRAME_DTMF, };
15828          if (event < 10) {
15829             f.subclass = '0' + event;
15830          } else if (event < 11) {
15831             f.subclass = '*';
15832          } else if (event < 12) {
15833             f.subclass = '#';
15834          } else if (event < 16) {
15835             f.subclass = 'A' + (event - 12);
15836          }
15837          f.len = duration;
15838          ast_queue_frame(p->owner, &f);
15839          if (sipdebug)
15840             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15841       }
15842       transmit_response(p, "200 OK", req);
15843       return;
15844    } else if (!strcasecmp(c, "application/dtmf")) {
15845       /*! \todo Note: Doesn't read the duration of the DTMF. Should be fixed. */
15846       unsigned int duration = 0;
15847 
15848       if (!p->owner) {  /* not a PBX call */
15849          transmit_response(p, "481 Call leg/transaction does not exist", req);
15850          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
15851          return;
15852       }
15853 
15854       get_msg_text(buf, sizeof(buf), req, TRUE);
15855       duration = 100; /* 100 ms */
15856 
15857       if (ast_strlen_zero(buf)) {
15858          transmit_response(p, "200 OK", req);
15859          return;
15860       }
15861       event = atoi(buf);
15862       if (event == 16) {
15863          /* send a FLASH event */
15864          struct ast_frame f = { AST_FRAME_CONTROL, AST_CONTROL_FLASH, };
15865          ast_queue_frame(p->owner, &f);
15866          if (sipdebug)
15867             ast_verbose("* DTMF-relay event received: FLASH\n");
15868       } else {
15869          /* send a DTMF event */
15870          struct ast_frame f = { AST_FRAME_DTMF, };
15871          if (event < 10) {
15872             f.subclass = '0' + event;
15873          } else if (event < 11) {
15874             f.subclass = '*';
15875          } else if (event < 12) {
15876             f.subclass = '#';
15877          } else if (event < 16) {
15878             f.subclass = 'A' + (event - 12);
15879          }
15880          f.len = duration;
15881          ast_queue_frame(p->owner, &f);
15882          if (sipdebug)
15883             ast_verbose("* DTMF-relay event received: %c\n", f.subclass);
15884       }
15885       transmit_response(p, "200 OK", req);
15886       return;
15887 
15888    } else if (!strcasecmp(c, "application/media_control+xml")) {
15889       /* Eh, we'll just assume it's a fast picture update for now */
15890       if (p->owner)
15891          ast_queue_control(p->owner, AST_CONTROL_VIDUPDATE);
15892       transmit_response(p, "200 OK", req);
15893       return;
15894    } else if (!ast_strlen_zero(c = get_header(req, "X-ClientCode"))) {
15895       /* Client code (from SNOM phone) */
15896       if (ast_test_flag(&p->flags[0], SIP_USECLIENTCODE)) {
15897          if (p->owner && p->owner->cdr)
15898             ast_cdr_setuserfield(p->owner, c);
15899          if (p->owner && ast_bridged_channel(p->owner) && ast_bridged_channel(p->owner)->cdr)
15900             ast_cdr_setuserfield(ast_bridged_channel(p->owner), c);
15901          transmit_response(p, "200 OK", req);
15902       } else {
15903          transmit_response(p, "403 Forbidden", req);
15904       }
15905       return;
15906    } else if (!ast_strlen_zero(c = get_header(req, "Record"))) {
15907       /* INFO messages generated by some phones to start/stop recording
15908          on phone calls. 
15909          OEJ: I think this should be something that is enabled/disabled
15910          per device. I don't want incoming callers to record calls in my
15911          pbx.
15912       */
15913       /* first, get the feature string, if it exists */
15914       struct ast_call_feature *feat;
15915       int j;
15916       struct ast_frame f = { AST_FRAME_DTMF, };
15917 
15918       ast_rdlock_call_features();
15919       feat = ast_find_call_feature("automon");
15920       if (!feat || ast_strlen_zero(feat->exten)) {
15921          ast_log(LOG_WARNING, "Recording requested, but no One Touch Monitor registered. (See features.conf)\n");
15922          /* 403 means that we don't support this feature, so don't request it again */
15923          transmit_response(p, "403 Forbidden", req);
15924          ast_unlock_call_features();
15925          return;
15926       } 
15927       /* Send the feature code to the PBX as DTMF, just like the handset had sent it */
15928       f.len = 100;
15929       for (j=0; j < strlen(feat->exten); j++) {
15930          f.subclass = feat->exten[j];
15931          ast_queue_frame(p->owner, &f);
15932          if (sipdebug)
15933             ast_verbose("* DTMF-relay event faked: %c\n", f.subclass);
15934       }
15935       ast_unlock_call_features();
15936 
15937       ast_debug(1, "Got a Request to Record the channel, state %s\n", c);
15938       transmit_response(p, "200 OK", req);
15939       return;
15940    } else if (ast_strlen_zero(c = get_header(req, "Content-Length")) || !strcasecmp(c, "0")) {
15941       /* This is probably just a packet making sure the signalling is still up, just send back a 200 OK */
15942       transmit_response(p, "200 OK", req);
15943       return;
15944    }
15945 
15946    /* Other type of INFO message, not really understood by Asterisk */
15947    /* if (get_msg_text(buf, sizeof(buf), req)) { */
15948 
15949    ast_log(LOG_WARNING, "Unable to parse INFO message from %s. Content %s\n", p->callid, buf);
15950    transmit_response(p, "415 Unsupported media type", req);
15951    return;
15952 }
15953 
15954 /*! \brief Enable SIP Debugging for a single IP */
15955 static char *sip_do_debug_ip(int fd, char *arg)
15956 {
15957    struct hostent *hp;
15958    struct ast_hostent ahp;
15959    int port = 0;
15960    char *p;
15961 
15962    p = arg;
15963    strsep(&p, ":");
15964    if (p)
15965       port = atoi(p);
15966    hp = ast_gethostbyname(arg, &ahp);
15967    if (hp == NULL)
15968       return CLI_SHOWUSAGE;
15969 
15970    debugaddr.sin_family = AF_INET;
15971    memcpy(&debugaddr.sin_addr, hp->h_addr, sizeof(debugaddr.sin_addr));
15972    debugaddr.sin_port = htons(port);
15973    if (port == 0)
15974       ast_cli(fd, "SIP Debugging Enabled for IP: %s\n", ast_inet_ntoa(debugaddr.sin_addr));
15975    else
15976       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n", ast_inet_ntoa(debugaddr.sin_addr), port);
15977 
15978    sipdebug |= sip_debug_console;
15979 
15980    return CLI_SUCCESS;
15981 }
15982 
15983 /*! \brief  Turn on SIP debugging for a given peer */
15984 static char *sip_do_debug_peer(int fd, char *arg)
15985 {
15986    struct sip_peer *peer = find_peer(arg, NULL, TRUE, FINDPEERS, FALSE, 0);
15987    if (!peer)
15988       ast_cli(fd, "No such peer '%s'\n", arg);
15989    else if (peer->addr.sin_addr.s_addr == 0)
15990       ast_cli(fd, "Unable to get IP address of peer '%s'\n", arg);
15991    else {
15992       debugaddr.sin_family = AF_INET;
15993       debugaddr.sin_addr = peer->addr.sin_addr;
15994       debugaddr.sin_port = peer->addr.sin_port;
15995       ast_cli(fd, "SIP Debugging Enabled for IP: %s:%d\n",
15996          ast_inet_ntoa(debugaddr.sin_addr), ntohs(debugaddr.sin_port));
15997       sipdebug |= sip_debug_console;
15998    }
15999    if (peer)
16000       unref_peer(peer, "sip_do_debug_peer: unref_peer, from find_peer call");
16001    return CLI_SUCCESS;
16002 }
16003 
16004 /*! \brief Turn on SIP debugging (CLI command) */
16005 static char *sip_do_debug(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16006 {
16007    int oldsipdebug = sipdebug & sip_debug_console;
16008    char *what;
16009 
16010    if (cmd == CLI_INIT) {
16011       e->command = "sip set debug {on|off|ip|peer}";
16012       e->usage =
16013          "Usage: sip set debug {off|on|ip addr[:port]|peer peername}\n"
16014          "       Globally disables dumping of SIP packets,\n"
16015          "       or enables it either globally or for a (single)\n"
16016          "       IP address or registered peer.\n";
16017       return NULL;
16018    } else if (cmd == CLI_GENERATE) {
16019       if (a->pos == 4 && strcasestr(a->line, " peer")) /* XXX should check on argv too */
16020          return complete_sip_peer(a->word, a->n, 0);
16021       return NULL;
16022         }
16023 
16024    what = a->argv[e->args-1];      /* guaranteed to exist */
16025    if (a->argc == e->args) {       /* on/off */
16026       if (!strcasecmp(what, "on")) {
16027          sipdebug |= sip_debug_console;
16028          sipdebug_text = 1;   /*! \note this can be a special debug command - "sip debug text" or something */
16029          memset(&debugaddr, 0, sizeof(debugaddr));
16030          ast_cli(a->fd, "SIP Debugging %senabled\n", oldsipdebug ? "re-" : "");
16031          return CLI_SUCCESS;
16032       } else if (!strcasecmp(what, "off")) {
16033          sipdebug &= ~sip_debug_console;
16034          sipdebug_text = 0;
16035          ast_cli(a->fd, "SIP Debugging Disabled\n");
16036          return CLI_SUCCESS;
16037       }
16038    } else if (a->argc == e->args +1) {/* ip/peer */
16039       if (!strcasecmp(what, "ip"))
16040          return sip_do_debug_ip(a->fd, a->argv[e->args]);
16041       else if (!strcasecmp(what, "peer"))
16042          return sip_do_debug_peer(a->fd, a->argv[e->args]);
16043    }
16044    return CLI_SHOWUSAGE;   /* default, failure */
16045 }
16046 
16047 /*! \brief Cli command to send SIP notify to peer */
16048 static char *sip_cli_notify(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16049 {
16050    struct ast_variable *varlist;
16051    int i;
16052 
16053    switch (cmd) {
16054    case CLI_INIT:
16055       e->command = "sip notify";
16056       e->usage =
16057          "Usage: sip notify <type> <peer> [<peer>...]\n"
16058          "       Send a NOTIFY message to a SIP peer or peers\n"
16059          "       Message types are defined in sip_notify.conf\n";
16060       return NULL;
16061    case CLI_GENERATE:
16062       return complete_sipnotify(a->line, a->word, a->pos, a->n);
16063    }
16064 
16065    if (a->argc < 4)
16066       return CLI_SHOWUSAGE;
16067 
16068    if (!notify_types) {
16069       ast_cli(a->fd, "No %s file found, or no types listed there\n", notify_config);
16070       return CLI_FAILURE;
16071    }
16072 
16073    varlist = ast_variable_browse(notify_types, a->argv[2]);
16074 
16075    if (!varlist) {
16076       ast_cli(a->fd, "Unable to find notify type '%s'\n", a->argv[2]);
16077       return CLI_FAILURE;
16078    }
16079 
16080    for (i = 3; i < a->argc; i++) {
16081       struct sip_pvt *p;
16082 
16083       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) {
16084          ast_log(LOG_WARNING, "Unable to build sip pvt data for notify (memory/socket error)\n");
16085          return CLI_FAILURE;
16086       }
16087 
16088       if (create_addr(p, a->argv[i], NULL, 1)) {
16089          /* Maybe they're not registered, etc. */
16090          dialog_unlink_all(p, TRUE, TRUE);
16091          dialog_unref(p, "unref dialog inside for loop" );
16092          /* sip_destroy(p); */
16093          ast_cli(a->fd, "Could not create address for '%s'\n", a->argv[i]);
16094          continue;
16095       }
16096 
16097       /* Notify is outgoing call */
16098       ast_set_flag(&p->flags[0], SIP_OUTGOING);
16099 
16100       /* Recalculate our side, and recalculate Call ID */
16101       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
16102       build_via(p);
16103       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
16104       build_callid_pvt(p);
16105       ao2_t_link(dialogs, p, "Linking in new name");
16106       ast_cli(a->fd, "Sending NOTIFY of type '%s' to '%s'\n", a->argv[2], a->argv[i]);
16107       dialog_ref(p, "bump the count of p, which transmit_sip_request will decrement.");
16108       sip_scheddestroy(p, SIP_TRANS_TIMEOUT);
16109       transmit_notify_custom(p, varlist);
16110    }
16111 
16112    return CLI_SUCCESS;
16113 }
16114 
16115 /*! \brief Enable/Disable SIP History logging (CLI) - deprecated. use sip_set_history instead */
16116 static char *sip_do_history_deprecated(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16117 {
16118    switch (cmd) {
16119    case CLI_INIT:
16120       e->command = "sip history [off]";
16121       e->usage =
16122          "Usage: sip history [off]\n"
16123          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
16124          "       Use 'sip show history' to view the history of a call number.\n";
16125       return NULL;
16126    case CLI_GENERATE:
16127       return NULL;
16128    }
16129 
16130    if (a->argc < 2 || a->argc > 3) {
16131       return CLI_SHOWUSAGE;
16132    }
16133    if (a->argc == 2) {
16134       recordhistory = TRUE;
16135       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
16136    } else {
16137       if (strncasecmp(a->argv[2], "off", 3))
16138          return CLI_SHOWUSAGE;
16139       recordhistory = FALSE;
16140       ast_cli(a->fd, "SIP History Recording Disabled\n");
16141    }
16142    return CLI_SUCCESS;
16143 }
16144 
16145 /*! \brief Enable/Disable SIP History logging (CLI) */
16146 static char *sip_set_history(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
16147 {
16148    switch (cmd) {
16149    case CLI_INIT:
16150       e->command = "sip set history {on|off}";
16151       e->usage =
16152          "Usage: sip set history {on|off}\n"
16153          "       Enables/Disables recording of SIP dialog history for debugging purposes.\n"
16154          "       Use 'sip show history' to view the history of a call number.\n";
16155       return NULL;
16156    case CLI_GENERATE:
16157       return NULL;
16158    }
16159 
16160    if (a->argc != e->args)
16161       return CLI_SHOWUSAGE;
16162 
16163    if (!strncasecmp(a->argv[e->args - 1], "on", 2)) {
16164       recordhistory = TRUE;
16165       ast_cli(a->fd, "SIP History Recording Enabled (use 'sip show history')\n");
16166    } else if (!strncasecmp(a->argv[e->args - 1], "off", 3)) {
16167       recordhistory = FALSE;
16168       ast_cli(a->fd, "SIP History Recording Disabled\n");
16169    } else {
16170       return CLI_SHOWUSAGE;
16171    }
16172    return CLI_SUCCESS;
16173 }
16174 
16175 /*! \brief Authenticate for outbound registration */
16176 static int do_register_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code)
16177 {
16178    char *header, *respheader;
16179    char digest[1024];
16180 
16181    p->authtries++;
16182    auth_headers(code, &header, &respheader);
16183    memset(digest, 0, sizeof(digest));
16184    if (reply_digest(p, req, header, SIP_REGISTER, digest, sizeof(digest))) {
16185       /* There's nothing to use for authentication */
16186       /* No digest challenge in request */
16187       if (sip_debug_test_pvt(p) && p->registry)
16188          ast_verbose("No authentication challenge, sending blank registration to domain/host name %s\n", p->registry->hostname);
16189          /* No old challenge */
16190       return -1;
16191    }
16192    if (p->do_history)
16193       append_history(p, "RegistryAuth", "Try: %d", p->authtries);
16194    if (sip_debug_test_pvt(p) && p->registry)
16195       ast_verbose("Responding to challenge, registration to domain/host name %s\n", p->registry->hostname);
16196    return transmit_register(p->registry, SIP_REGISTER, digest, respheader); 
16197 }
16198 
16199 /*! \brief Add authentication on outbound SIP packet */
16200 static int do_proxy_auth(struct sip_pvt *p, struct sip_request *req, enum sip_auth_type code, int sipmethod, int init)
16201 {
16202    char *header, *respheader;
16203    char digest[1024];
16204 
16205    if (!p->options && !(p->options = ast_calloc(1, sizeof(*p->options))))
16206       return -2;
16207 
16208    p->authtries++;
16209    auth_headers(code, &header, &respheader);
16210    ast_debug(2, "Auth attempt %d on %s\n", p->authtries, sip_methods[sipmethod].text);
16211    memset(digest, 0, sizeof(digest));
16212    if (reply_digest(p, req, header, sipmethod, digest, sizeof(digest) )) {
16213       /* No way to authenticate */
16214       return -1;
16215    }
16216    /* Now we have a reply digest */
16217    p->options->auth = digest;
16218    p->options->authheader = respheader;
16219    return transmit_invite(p, sipmethod, sipmethod == SIP_INVITE, init); 
16220 }
16221 
16222 /*! \brief  reply to authentication for outbound registrations
16223 \return  Returns -1 if we have no auth 
16224 \note This is used for register= servers in sip.conf, SIP proxies we register
16225    with  for receiving calls from.  */
16226 static int reply_digest(struct sip_pvt *p, struct sip_request *req, char *header, int sipmethod,  char *digest, int digest_len)
16227 {
16228    char tmp[512];
16229    char *c;
16230    char oldnonce[256];
16231 
16232    /* table of recognised keywords, and places where they should be copied */
16233    const struct x {
16234       const char *key;
16235       const ast_string_field *field;
16236    } *i, keys[] = {
16237       { "realm=", &p->realm },
16238       { "nonce=", &p->nonce },
16239       { "opaque=", &p->opaque },
16240       { "qop=", &p->qop },
16241       { "domain=", &p->domain },
16242       { NULL, 0 },
16243    };
16244 
16245    ast_copy_string(tmp, get_header(req, header), sizeof(tmp));
16246    if (ast_strlen_zero(tmp)) 
16247       return -1;
16248    if (strncasecmp(tmp, "Digest ", strlen("Digest "))) {
16249       ast_log(LOG_WARNING, "missing Digest.\n");
16250       return -1;
16251    }
16252    c = tmp + strlen("Digest ");
16253    ast_copy_string(oldnonce, p->nonce, sizeof(oldnonce));
16254    while (c && *(c = ast_skip_blanks(c))) {  /* lookup for keys */
16255       for (i = keys; i->key != NULL; i++) {
16256          char *src, *separator;
16257          if (strncasecmp(c, i->key, strlen(i->key)) != 0)
16258             continue;
16259          /* Found. Skip keyword, take text in quotes or up to the separator. */
16260          c += strlen(i->key);
16261          if (*c == '"') {
16262             src = ++c;
16263             separator = "\"";
16264          } else {
16265             src = c;
16266             separator = ",";
16267          }
16268          strsep(&c, separator); /* clear separator and move ptr */
16269          ast_string_field_ptr_set(p, i->field, src);
16270          break;
16271       }
16272       if (i->key == NULL) /* not found, try ',' */
16273          strsep(&c, ",");
16274    }
16275    /* Reset nonce count */
16276    if (strcmp(p->nonce, oldnonce)) 
16277       p->noncecount = 0;
16278 
16279    /* Save auth data for following registrations */
16280    if (p->registry) {
16281       struct sip_registry *r = p->registry;
16282 
16283       if (strcmp(r->nonce, p->nonce)) {
16284          ast_string_field_set(r, realm, p->realm);
16285          ast_string_field_set(r, nonce, p->nonce);
16286          ast_string_field_set(r, domain, p->domain);
16287          ast_string_field_set(r, opaque, p->opaque);
16288          ast_string_field_set(r, qop, p->qop);
16289          r->noncecount = 0;
16290       }
16291    }
16292    return build_reply_digest(p, sipmethod, digest, digest_len); 
16293 }
16294 
16295 /*! \brief  Build reply digest 
16296 \return  Returns -1 if we have no auth 
16297 \note Build digest challenge for authentication of registrations and calls
16298    Also used for authentication of BYE 
16299 */
16300 static int build_reply_digest(struct sip_pvt *p, int method, char* digest, int digest_len)
16301 {
16302    char a1[256];
16303    char a2[256];
16304    char a1_hash[256];
16305    char a2_hash[256];
16306    char resp[256];
16307    char resp_hash[256];
16308    char uri[256];
16309    char opaque[256] = "";
16310    char cnonce[80];
16311    const char *username;
16312    const char *secret;
16313    const char *md5secret;
16314    struct sip_auth *auth = NULL; /* Realm authentication */
16315 
16316    if (!ast_strlen_zero(p->domain))
16317       ast_copy_string(uri, p->domain, sizeof(uri));
16318    else if (!ast_strlen_zero(p->uri))
16319       ast_copy_string(uri, p->uri, sizeof(uri));
16320    else
16321       snprintf(uri, sizeof(uri), "sip:%s@%s", p->username, ast_inet_ntoa(p->sa.sin_addr));
16322 
16323    snprintf(cnonce, sizeof(cnonce), "%08lx", ast_random());
16324 
16325    /* Check if we have separate auth credentials */
16326    if(!(auth = find_realm_authentication(p->peerauth, p->realm))) /* Start with peer list */
16327       auth = find_realm_authentication(authl, p->realm); /* If not, global list */
16328 
16329    if (auth) {
16330       ast_log(LOG_DEBUG, "use realm [%s] from peer [%s][%s]\n", auth->username, p->peername, p->username);
16331       username = auth->username;
16332       secret = auth->secret;
16333       md5secret = auth->md5secret;
16334       if (sipdebug)
16335          ast_debug(1, "Using realm %s authentication for call %s\n", p->realm, p->callid);
16336    } else {
16337       /* No authentication, use peer or register= config */
16338       username = p->authname;
16339       secret =  p->peersecret;
16340       md5secret = p->peermd5secret;
16341    }
16342    if (ast_strlen_zero(username))   /* We have no authentication */
16343       return -1;
16344 
16345    /* Calculate SIP digest response */
16346    snprintf(a1, sizeof(a1), "%s:%s:%s", username, p->realm, secret);
16347    snprintf(a2, sizeof(a2), "%s:%s", sip_methods[method].text, uri);
16348    if (!ast_strlen_zero(md5secret))
16349       ast_copy_string(a1_hash, md5secret, sizeof(a1_hash));
16350    else
16351       ast_md5_hash(a1_hash, a1);
16352    ast_md5_hash(a2_hash, a2);
16353 
16354    p->noncecount++;
16355    if (!ast_strlen_zero(p->qop))
16356       snprintf(resp, sizeof(resp), "%s:%s:%08x:%s:%s:%s", a1_hash, p->nonce, p->noncecount, cnonce, "auth", a2_hash);
16357    else
16358       snprintf(resp, sizeof(resp), "%s:%s:%s", a1_hash, p->nonce, a2_hash);
16359    ast_md5_hash(resp_hash, resp);
16360 
16361    /* only include the opaque string if it's set */
16362    if (!ast_strlen_zero(p->opaque)) {
16363      snprintf(opaque, sizeof(opaque), ", opaque=\"%s\"", p->opaque);
16364    }
16365 
16366    /* XXX We hard code our qop to "auth" for now.  XXX */
16367    if (!ast_strlen_zero(p->qop))
16368       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);
16369    else
16370       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);
16371 
16372    append_history(p, "AuthResp", "Auth response sent for %s in realm %s - nc %d", username, p->realm, p->noncecount);
16373 
16374    return 0;
16375 }
16376    
16377 /*! \brief Read SIP header (dialplan function) */
16378 static int func_header_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len) 
16379 {
16380    struct sip_pvt *p;
16381    const char *content = NULL;
16382    AST_DECLARE_APP_ARGS(args,
16383       AST_APP_ARG(header);
16384       AST_APP_ARG(number);
16385    );
16386    int i, number, start = 0;
16387 
16388    if (ast_strlen_zero(data)) {
16389       ast_log(LOG_WARNING, "This function requires a header name.\n");
16390       return -1;
16391    }
16392 
16393    ast_channel_lock(chan);
16394    if (!IS_SIP_TECH(chan->tech)) {
16395       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16396       ast_channel_unlock(chan);
16397       return -1;
16398    }
16399 
16400    AST_STANDARD_APP_ARGS(args, data);
16401    if (!args.number) {
16402       number = 1;
16403    } else {
16404       sscanf(args.number, "%30d", &number);
16405       if (number < 1)
16406          number = 1;
16407    }
16408 
16409    p = chan->tech_pvt;
16410 
16411    /* If there is no private structure, this channel is no longer alive */
16412    if (!p) {
16413       ast_channel_unlock(chan);
16414       return -1;
16415    }
16416 
16417    for (i = 0; i < number; i++)
16418       content = __get_header(&p->initreq, args.header, &start);
16419 
16420    if (ast_strlen_zero(content)) {
16421       ast_channel_unlock(chan);
16422       return -1;
16423    }
16424 
16425    ast_copy_string(buf, content, len);
16426    ast_channel_unlock(chan);
16427 
16428    return 0;
16429 }
16430 
16431 static struct ast_custom_function sip_header_function = {
16432    .name = "SIP_HEADER",
16433    .synopsis = "Gets the specified SIP header",
16434    .syntax = "SIP_HEADER(<name>[,<number>])",
16435    .desc = "Since there are several headers (such as Via) which can occur multiple\n"
16436    "times, SIP_HEADER takes an optional second argument to specify which header with\n"
16437    "that name to retrieve. Headers start at offset 1.\n",
16438    .read = func_header_read,
16439 };
16440 
16441 /*! \brief  Dial plan function to check if domain is local */
16442 static int func_check_sipdomain(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16443 {
16444    if (ast_strlen_zero(data)) {
16445       ast_log(LOG_WARNING, "CHECKSIPDOMAIN requires an argument - A domain name\n");
16446       return -1;
16447    }
16448    if (check_sip_domain(data, NULL, 0))
16449       ast_copy_string(buf, data, len);
16450    else
16451       buf[0] = '\0';
16452    return 0;
16453 }
16454 
16455 static struct ast_custom_function checksipdomain_function = {
16456    .name = "CHECKSIPDOMAIN",
16457    .synopsis = "Checks if domain is a local domain",
16458    .syntax = "CHECKSIPDOMAIN(<domain|IP>)",
16459    .read = func_check_sipdomain,
16460    .desc = "This function checks if the domain in the argument is configured\n"
16461       "as a local SIP domain that this Asterisk server is configured to handle.\n"
16462       "Returns the domain name if it is locally handled, otherwise an empty string.\n"
16463       "Check the domain= configuration in sip.conf\n",
16464 };
16465 
16466 /*! \brief  ${SIPPEER()} Dialplan function - reads peer data */
16467 static int function_sippeer(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16468 {
16469    struct sip_peer *peer;
16470    char *colname;
16471 
16472    if ((colname = strchr(data, ':'))) {   /*! \todo Will be deprecated after 1.4 */
16473       static int deprecation_warning = 0;
16474       *colname++ = '\0';
16475       if (deprecation_warning++ % 10 == 0)
16476          ast_log(LOG_WARNING, "SIPPEER(): usage of ':' to separate arguments is deprecated.  Please use ',' instead.\n");
16477    } else if ((colname = strchr(data, ',')))
16478       *colname++ = '\0';
16479    else
16480       colname = "ip";
16481 
16482    if (!(peer = find_peer(data, NULL, TRUE, FINDPEERS, FALSE, 0)))
16483       return -1;
16484 
16485    if (!strcasecmp(colname, "ip")) {
16486       ast_copy_string(buf, peer->addr.sin_addr.s_addr ? ast_inet_ntoa(peer->addr.sin_addr) : "", len);
16487    } else  if (!strcasecmp(colname, "port")) {
16488       snprintf(buf, len, "%d", ntohs(peer->addr.sin_port));
16489    } else  if (!strcasecmp(colname, "status")) {
16490       peer_status(peer, buf, len);
16491    } else  if (!strcasecmp(colname, "language")) {
16492       ast_copy_string(buf, peer->language, len);
16493    } else  if (!strcasecmp(colname, "regexten")) {
16494       ast_copy_string(buf, peer->regexten, len);
16495    } else  if (!strcasecmp(colname, "limit")) {
16496       snprintf(buf, len, "%d", peer->call_limit);
16497    } else  if (!strcasecmp(colname, "busylevel")) {
16498       snprintf(buf, len, "%d", peer->busy_level);
16499    } else  if (!strcasecmp(colname, "curcalls")) {
16500       snprintf(buf, len, "%d", peer->inUse);
16501    } else  if (!strcasecmp(colname, "accountcode")) {
16502       ast_copy_string(buf, peer->accountcode, len);
16503    } else  if (!strcasecmp(colname, "callgroup")) {
16504       ast_print_group(buf, len, peer->callgroup);
16505    } else  if (!strcasecmp(colname, "pickupgroup")) {
16506       ast_print_group(buf, len, peer->pickupgroup);
16507    } else  if (!strcasecmp(colname, "useragent")) {
16508       ast_copy_string(buf, peer->useragent, len);
16509    } else  if (!strcasecmp(colname, "mailbox")) {
16510       struct ast_str *mailbox_str = ast_str_alloca(512);
16511       peer_mailboxes_to_str(&mailbox_str, peer);
16512       ast_copy_string(buf, mailbox_str->str, len);
16513    } else  if (!strcasecmp(colname, "context")) {
16514       ast_copy_string(buf, peer->context, len);
16515    } else  if (!strcasecmp(colname, "expire")) {
16516       snprintf(buf, len, "%d", peer->expire);
16517    } else  if (!strcasecmp(colname, "dynamic")) {
16518       ast_copy_string(buf, peer->host_dynamic ? "yes" : "no", len);
16519    } else  if (!strcasecmp(colname, "callerid_name")) {
16520       ast_copy_string(buf, peer->cid_name, len);
16521    } else  if (!strcasecmp(colname, "callerid_num")) {
16522       ast_copy_string(buf, peer->cid_num, len);
16523    } else  if (!strcasecmp(colname, "codecs")) {
16524       ast_getformatname_multiple(buf, len -1, peer->capability);
16525    } else  if (!strncasecmp(colname, "chanvar[", 8)) {
16526       char *chanvar=colname + 8;
16527       struct ast_variable *v;
16528    
16529       chanvar = strsep(&chanvar, "]");
16530       for (v = peer->chanvars ; v ; v = v->next)
16531          if (!strcasecmp(v->name, chanvar))
16532             ast_copy_string(buf, v->value, len);
16533    } else  if (!strncasecmp(colname, "codec[", 6)) {
16534       char *codecnum;
16535       int codec = 0;
16536       
16537       codecnum = colname + 6; /* move past the '[' */
16538       codecnum = strsep(&codecnum, "]"); /* trim trailing ']' if any */
16539       if((codec = ast_codec_pref_index(&peer->prefs, atoi(codecnum)))) {
16540          ast_copy_string(buf, ast_getformatname(codec), len);
16541       } else {
16542          buf[0] = '\0';
16543       }
16544    } else {
16545       buf[0] = '\0';
16546    }
16547 
16548    unref_peer(peer, "unref_peer from function_sippeer, just before return");
16549 
16550    return 0;
16551 }
16552 
16553 /*! \brief Structure to declare a dialplan function: SIPPEER */
16554 struct ast_custom_function sippeer_function = {
16555    .name = "SIPPEER",
16556    .synopsis = "Gets SIP peer information",
16557    .syntax = "SIPPEER(<peername>[,item])",
16558    .read = function_sippeer,
16559    .desc = "Valid items are:\n"
16560    "- ip (default)          The IP address.\n"
16561    "- port                  The port number\n"
16562    "- mailbox               The configured mailbox.\n"
16563    "- context               The configured context.\n"
16564    "- expire                The epoch time of the next expire.\n"
16565    "- dynamic               Is it dynamic? (yes/no).\n"
16566    "- callerid_name         The configured Caller ID name.\n"
16567    "- callerid_num          The configured Caller ID number.\n"
16568    "- callgroup             The configured Callgroup.\n"
16569    "- pickupgroup           The configured Pickupgroup.\n"
16570    "- codecs                The configured codecs.\n"
16571    "- status                Status (if qualify=yes).\n"
16572    "- regexten              Registration extension\n"
16573    "- limit                 Call limit (call-limit)\n"
16574    "- busylevel             Configured call level for signalling busy\n"
16575    "- curcalls              Current amount of calls \n"
16576    "                        Only available if call-limit is set\n"
16577    "- language              Default language for peer\n"
16578    "- accountcode           Account code for this peer\n"
16579    "- useragent             Current user agent id for peer\n"
16580    "- chanvar[name]         A channel variable configured with setvar for this peer.\n"
16581    "- codec[x]              Preferred codec index number 'x' (beginning with zero).\n"
16582    "\n"
16583 };
16584 
16585 /*! \brief ${SIPCHANINFO()} Dialplan function - reads sip channel data */
16586 static int function_sipchaninfo_read(struct ast_channel *chan, const char *cmd, char *data, char *buf, size_t len)
16587 {
16588    struct sip_pvt *p;
16589    static int deprecated = 0;
16590 
16591    *buf = 0;
16592    
16593    if (!data) {
16594       ast_log(LOG_WARNING, "This function requires a parameter name.\n");
16595       return -1;
16596    }
16597 
16598    ast_channel_lock(chan);
16599    if (!IS_SIP_TECH(chan->tech)) {
16600       ast_log(LOG_WARNING, "This function can only be used on SIP channels.\n");
16601       ast_channel_unlock(chan);
16602       return -1;
16603    }
16604 
16605    if (deprecated++ % 20 == 0) {
16606       /* Deprecated in 1.6.1 */
16607       ast_log(LOG_WARNING, "SIPCHANINFO() is deprecated.  Please transition to using CHANNEL().\n");
16608    }
16609 
16610    p = chan->tech_pvt;
16611 
16612    /* If there is no private structure, this channel is no longer alive */
16613    if (!p) {
16614       ast_channel_unlock(chan);
16615       return -1;
16616    }
16617 
16618    if (!strcasecmp(data, "peerip")) {
16619       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", len);
16620    } else  if (!strcasecmp(data, "recvip")) {
16621       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", len);
16622    } else  if (!strcasecmp(data, "from")) {
16623       ast_copy_string(buf, p->from, len);
16624    } else  if (!strcasecmp(data, "uri")) {
16625       ast_copy_string(buf, p->uri, len);
16626    } else  if (!strcasecmp(data, "useragent")) {
16627       ast_copy_string(buf, p->useragent, len);
16628    } else  if (!strcasecmp(data, "peername")) {
16629       ast_copy_string(buf, p->peername, len);
16630    } else if (!strcasecmp(data, "t38passthrough")) {
16631       if (p->t38.state == T38_DISABLED)
16632          ast_copy_string(buf, "0", sizeof("0"));
16633       else    /* T38 is offered or enabled in this call */
16634          ast_copy_string(buf, "1", sizeof("1"));
16635    } else {
16636       ast_channel_unlock(chan);
16637       return -1;
16638    }
16639    ast_channel_unlock(chan);
16640 
16641    return 0;
16642 }
16643 
16644 /*! \brief Structure to declare a dialplan function: SIPCHANINFO */
16645 static struct ast_custom_function sipchaninfo_function = {
16646    .name = "SIPCHANINFO",
16647    .synopsis = "Gets the specified SIP parameter from the current channel",
16648    .syntax = "SIPCHANINFO(item)",
16649    .read = function_sipchaninfo_read,
16650    .desc = "Valid items are:\n"
16651    "- peerip                The IP address of the peer.\n"
16652    "- recvip                The source IP address of the peer.\n"
16653    "- from                  The URI from the From: header.\n"
16654    "- uri                   The URI from the Contact: header.\n"
16655    "- useragent             The useragent.\n"
16656    "- peername              The name of the peer.\n"
16657    "- t38passthrough        1 if T38 is offered or enabled in this channel, otherwise 0\n"
16658 };
16659 
16660 /*! \brief Parse 302 Moved temporalily response */
16661 static void parse_moved_contact(struct sip_pvt *p, struct sip_request *req)
16662 {
16663    char tmp[SIPBUFSIZE];
16664    char *s, *e, *t, *trans;
16665    char *domain;
16666    enum sip_transport transport = SIP_TRANSPORT_UDP;
16667 
16668    ast_copy_string(tmp, get_header(req, "Contact"), sizeof(tmp));
16669    if ((t = strchr(tmp, ',')))
16670       *t = '\0';
16671 
16672    s = get_in_brackets(tmp);
16673    if ((trans = strcasestr(s, ";transport="))) do {
16674       trans += 11;
16675 
16676       if ((e = strchr(trans, ';')))
16677          *e = '\0';
16678 
16679       if (!strncasecmp(trans, "tcp", 3))
16680          transport = SIP_TRANSPORT_TCP;
16681       else if (!strncasecmp(trans, "tls", 3))
16682          transport = SIP_TRANSPORT_TLS;
16683       else {
16684          if (strncasecmp(trans, "udp", 3))
16685             ast_debug(1, "received contact with an invalid transport, '%s'\n", s);
16686          transport = SIP_TRANSPORT_UDP;
16687       }
16688    } while(0);
16689    s = remove_uri_parameters(s);
16690 
16691    if (p->socket.tcptls_session) {
16692       ao2_ref(p->socket.tcptls_session, -1);
16693       p->socket.tcptls_session = NULL;
16694    }
16695 
16696    set_socket_transport(&p->socket, transport);
16697 
16698    if (ast_test_flag(&p->flags[0], SIP_PROMISCREDIR)) {
16699       char *host = NULL;
16700       if (!strncasecmp(s, "sip:", 4))
16701          s += 4;
16702       else if (!strncasecmp(s, "sips:", 5))
16703          s += 5;
16704       e = strchr(s, '/');
16705       if (e)
16706          *e = '\0';
16707       if ((host = strchr(s, '@'))) {
16708          *host++ = '\0';
16709          ast_debug(2, "Found promiscuous redirection to 'SIP/%s::::%s@%s'\n", s, get_transport(transport), host);
16710          if (p->owner)
16711             ast_string_field_build(p->owner, call_forward, "SIP/%s::::%s@%s", s, get_transport(transport), host);
16712       } else {
16713          ast_debug(2, "Found promiscuous redirection to 'SIP/::::%s@%s'\n", get_transport(transport), s);
16714          if (p->owner)
16715             ast_string_field_build(p->owner, call_forward, "SIP/::::%s@%s", get_transport(transport), s);
16716       }
16717    } else {
16718       e = strchr(tmp, '@');
16719       if (e) {
16720          *e++ = '\0';
16721          domain = e;
16722       } else {
16723          /* No username part */
16724          domain = tmp;
16725       }
16726       e = strchr(tmp, '/');   /* WHEN do we hae a forward slash in the URI? */
16727       if (e)
16728          *e = '\0';
16729 
16730       if (!strncasecmp(s, "sip:", 4))
16731          s += 4;
16732       else if (!strncasecmp(s, "sips:", 5))
16733          s += 5;
16734       e = strchr(s, ';');  /* And username ; parameters? */
16735       if (e)
16736          *e = '\0';  
16737       ast_debug(2, "Received 302 Redirect to extension '%s' (domain %s)\n", s, domain);
16738       if (p->owner) {
16739          pbx_builtin_setvar_helper(p->owner, "SIPDOMAIN", domain);
16740          ast_string_field_set(p->owner, call_forward, s);
16741       }
16742    }
16743 }
16744 
16745 /*! \brief Check pending actions on SIP call */
16746 static void check_pendings(struct sip_pvt *p)
16747 {
16748    if (ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
16749       /* if we can't BYE, then this is really a pending CANCEL */
16750       if (p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA)
16751          transmit_request(p, SIP_CANCEL, p->lastinvite, XMIT_RELIABLE, FALSE);
16752          /* Actually don't destroy us yet, wait for the 487 on our original 
16753             INVITE, but do set an autodestruct just in case we never get it. */
16754       else {
16755          /* We have a pending outbound invite, don't send someting
16756             new in-transaction */
16757          if (p->pendinginvite)
16758             return;
16759 
16760          /* Perhaps there is an SD change INVITE outstanding */
16761          transmit_request_with_auth(p, SIP_BYE, 0, XMIT_RELIABLE, TRUE);
16762       }
16763       ast_clear_flag(&p->flags[0], SIP_PENDINGBYE);   
16764       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
16765    } else if (ast_test_flag(&p->flags[0], SIP_NEEDREINVITE)) {
16766       /* if we can't REINVITE, hold it for later */
16767       if (p->pendinginvite || p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA || p->waitid > 0) {
16768          ast_debug(2, "NOT Sending pending reinvite (yet) on '%s'\n", p->callid);
16769       } else {
16770          ast_debug(2, "Sending pending reinvite on '%s'\n", p->callid);
16771          /* Didn't get to reinvite yet, so do it now */
16772          transmit_reinvite_with_sdp(p, (p->t38.state == T38_LOCAL_REINVITE ? TRUE : FALSE), FALSE);
16773          ast_clear_flag(&p->flags[0], SIP_NEEDREINVITE); 
16774       }
16775    }
16776 }
16777 
16778 /*! \brief Reset the NEEDREINVITE flag after waiting when we get 491 on a Re-invite
16779    to avoid race conditions between asterisk servers.
16780    Called from the scheduler.
16781 */
16782 static int sip_reinvite_retry(const void *data)
16783 {
16784    struct sip_pvt *p = (struct sip_pvt *) data;
16785 
16786    sip_pvt_lock(p); /* called from schedule thread which requires a lock */
16787    ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
16788    p->waitid = -1;
16789    check_pendings(p);
16790    sip_pvt_unlock(p);
16791    dialog_unref(p, "unref the dialog ptr from sip_reinvite_retry, because it held a dialog ptr");
16792    return 0;
16793 }
16794 
16795 
16796 /*! \brief Handle SIP response to INVITE dialogue */
16797 static void handle_response_invite(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
16798 {
16799    int outgoing = ast_test_flag(&p->flags[0], SIP_OUTGOING);
16800    int res = 0;
16801    int xmitres = 0;
16802    int reinvite = (p->owner && p->owner->_state == AST_STATE_UP);
16803    char *p_hdrval;
16804    int rtn;
16805 
16806    if (reinvite)
16807       ast_debug(4, "SIP response %d to RE-invite on %s call %s\n", resp, outgoing ? "outgoing" : "incoming", p->callid);
16808    else
16809       ast_debug(4, "SIP response %d to standard invite\n", resp);
16810 
16811    if (p->alreadygone) { /* This call is already gone */
16812       ast_debug(1, "Got response on call that is already terminated: %s (ignoring)\n", p->callid);
16813       return;
16814    }
16815 
16816    /* Acknowledge sequence number - This only happens on INVITE from SIP-call */
16817    /* Don't auto congest anymore since we've gotten something useful back */
16818    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"));
16819 
16820    /* RFC3261 says we must treat every 1xx response (but not 100)
16821       that we don't recognize as if it was 183.
16822    */
16823    if (resp > 100 && resp < 200 && resp!=101 && resp != 180 && resp != 182 && resp != 183)
16824       resp = 183;
16825 
16826    /* Any response between 100 and 199 is PROCEEDING */
16827    if (resp >= 100 && resp < 200 && p->invitestate == INV_CALLING)
16828       p->invitestate = INV_PROCEEDING;
16829  
16830    /* Final response, not 200 ? */
16831    if (resp >= 300 && (p->invitestate == INV_CALLING || p->invitestate == INV_PROCEEDING || p->invitestate == INV_EARLY_MEDIA ))
16832       p->invitestate = INV_COMPLETED;
16833    
16834    /* Final response, clear out pending invite */
16835    if ((resp == 200 || resp >= 300) && p->pendinginvite && seqno == p->pendinginvite)
16836       p->pendinginvite = 0;
16837 
16838    switch (resp) {
16839    case 100:   /* Trying */
16840    case 101:   /* Dialog establishment */
16841       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16842          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16843       check_pendings(p);
16844       break;
16845 
16846    case 180:   /* 180 Ringing */
16847    case 182:       /* 182 Queued */
16848       if (!req->ignore && p->invitestate != INV_CANCELLED && sip_cancel_destroy(p))
16849          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16850       if (!req->ignore && p->owner) {
16851          ast_queue_control(p->owner, AST_CONTROL_RINGING);
16852          if (p->owner->_state != AST_STATE_UP) {
16853             ast_setstate(p->owner, AST_STATE_RINGING);
16854          }
16855       }
16856       if (find_sdp(req)) {
16857          if (p->invitestate != INV_CANCELLED)
16858             p->invitestate = INV_EARLY_MEDIA;
16859          res = process_sdp(p, req, SDP_T38_NONE);
16860          if (!req->ignore && p->owner) {
16861             /* Queue a progress frame only if we have SDP in 180 or 182 */
16862             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16863          }
16864       }
16865       check_pendings(p);
16866       break;
16867 
16868    case 183:   /* Session progress */
16869       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16870          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16871       if (find_sdp(req)) {
16872          if (p->invitestate != INV_CANCELLED)
16873             p->invitestate = INV_EARLY_MEDIA;
16874          res = process_sdp(p, req, SDP_T38_NONE);
16875          if (!req->ignore && p->owner) {
16876             /* Queue a progress frame */
16877             ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
16878          }
16879       } else {
16880          /* Alcatel PBXs are known to send 183s with no SDP after sending
16881           * a 100 Trying response. We're just going to treat this sort of thing
16882           * the same as we would treat a 180 Ringing
16883           */
16884          if (!req->ignore && p->owner) {
16885             ast_queue_control(p->owner, AST_CONTROL_RINGING);
16886          }
16887       }
16888       check_pendings(p);
16889       break;
16890 
16891    case 200:   /* 200 OK on invite - someone's answering our call */
16892       if (!req->ignore && (p->invitestate != INV_CANCELLED) && sip_cancel_destroy(p))
16893          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
16894       p->authtries = 0;
16895       if (find_sdp(req)) {
16896          if ((res = process_sdp(p, req, SDP_T38_ACCEPT)) && !req->ignore)
16897             if (!reinvite)
16898                /* This 200 OK's SDP is not acceptable, so we need to ack, then hangup */
16899                /* For re-invites, we try to recover */
16900                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16901       }
16902 
16903       /* Parse contact header for continued conversation */
16904       /* When we get 200 OK, we know which device (and IP) to contact for this call */
16905       /* This is important when we have a SIP proxy between us and the phone */
16906       if (outgoing) {
16907          update_call_counter(p, DEC_CALL_RINGING);
16908          parse_ok_contact(p, req);
16909          /* Save Record-Route for any later requests we make on this dialogue */
16910          if (!reinvite)
16911             build_route(p, req, 1);
16912 
16913          if(set_address_from_contact(p)) {
16914             /* Bad contact - we don't know how to reach this device */
16915             /* We need to ACK, but then send a bye */
16916             if (!p->route && !req->ignore)
16917                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16918          } 
16919 
16920       }
16921 
16922       if (!req->ignore && p->owner) {
16923          if (!reinvite) {
16924             ast_queue_control(p->owner, AST_CONTROL_ANSWER);
16925             if (global_callevents)
16926                manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
16927                   "Channel: %s\r\nChanneltype: %s\r\nUniqueid: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
16928                   p->owner->name, "SIP", p->owner->uniqueid, p->callid, p->fullcontact, p->peername);
16929          } else { /* RE-invite */
16930             ast_queue_frame(p->owner, &ast_null_frame);
16931          }
16932       } else {
16933           /* It's possible we're getting an 200 OK after we've tried to disconnect
16934               by sending CANCEL */
16935          /* First send ACK, then send bye */
16936          if (!req->ignore)
16937             ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16938       }
16939 
16940       /* Check for Session-Timers related headers */
16941       if (st_get_mode(p) != SESSION_TIMER_MODE_REFUSE && p->outgoing_call == TRUE && !reinvite) {
16942          p_hdrval = (char*)get_header(req, "Session-Expires");
16943             if (!ast_strlen_zero(p_hdrval)) {
16944             /* UAS supports Session-Timers */
16945             enum st_refresher tmp_st_ref = SESSION_TIMER_REFRESHER_AUTO;
16946             int tmp_st_interval = 0;
16947             rtn = parse_session_expires(p_hdrval, &tmp_st_interval, &tmp_st_ref);
16948             if (rtn != 0) {
16949                ast_set_flag(&p->flags[0], SIP_PENDINGBYE);  
16950             }
16951             if (tmp_st_ref == SESSION_TIMER_REFRESHER_UAC || 
16952                tmp_st_ref == SESSION_TIMER_REFRESHER_UAS) {
16953                p->stimer->st_ref = tmp_st_ref;
16954             } 
16955             if (tmp_st_interval) {
16956                p->stimer->st_interval = tmp_st_interval;
16957             }
16958             p->stimer->st_active = TRUE;
16959             p->stimer->st_active_peer_ua = TRUE;
16960             start_session_timer(p);
16961          } else {
16962             /* UAS doesn't support Session-Timers */
16963             if (st_get_mode(p) == SESSION_TIMER_MODE_ORIGINATE) {
16964                p->stimer->st_ref = SESSION_TIMER_REFRESHER_UAC;
16965                p->stimer->st_active_peer_ua = FALSE;
16966                start_session_timer(p);
16967             }
16968          }
16969       }
16970 
16971 
16972       /* If I understand this right, the branch is different for a non-200 ACK only */
16973       p->invitestate = INV_TERMINATED;
16974       ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
16975       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, TRUE);
16976       check_pendings(p);
16977       break;
16978 
16979    case 407: /* Proxy authentication */
16980    case 401: /* Www auth */
16981       /* First we ACK */
16982       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
16983       if (p->options)
16984          p->options->auth_type = resp;
16985 
16986       /* Then we AUTH */
16987       ast_string_field_set(p, theirtag, NULL);  /* forget their old tag, so we don't match tags when getting response */
16988       if (!req->ignore) {
16989          if (p->authtries < MAX_AUTHTRIES)
16990             p->invitestate = INV_CALLING;
16991          if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, SIP_INVITE, 1)) {
16992             ast_log(LOG_NOTICE, "Failed to authenticate on INVITE to '%s'\n", get_header(&p->initreq, "From"));
16993             p->needdestroy = 1;
16994             sip_alreadygone(p);
16995             if (p->owner)
16996                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
16997          }
16998       }
16999       break;
17000 
17001    case 403: /* Forbidden */
17002       /* First we ACK */
17003       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17004       ast_log(LOG_WARNING, "Received response: \"Forbidden\" from '%s'\n", get_header(&p->initreq, "From"));
17005       if (!req->ignore && p->owner)
17006          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17007       p->needdestroy = 1;
17008       sip_alreadygone(p);
17009       break;
17010 
17011    case 404: /* Not found */
17012       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17013       if (p->owner && !req->ignore)
17014          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17015       sip_alreadygone(p);
17016       break;
17017 
17018    case 408: /* Request timeout */
17019    case 481: /* Call leg does not exist */
17020       /* Could be REFER caused INVITE with replaces */
17021       ast_log(LOG_WARNING, "Re-invite to non-existing call leg on other UA. SIP dialog '%s'. Giving up.\n", p->callid);
17022       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17023       if (p->owner)
17024          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17025       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17026       break;
17027 
17028    case 422: /* Session-Timers: Session interval too small */
17029       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17030       ast_string_field_set(p, theirtag, NULL);
17031       proc_422_rsp(p, req);
17032       break;
17033 
17034    case 487: /* Cancelled transaction */
17035       /* We have sent CANCEL on an outbound INVITE 
17036          This transaction is already scheduled to be killed by sip_hangup().
17037       */
17038       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17039       if (p->owner && !req->ignore) {
17040          ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_CLEARING);
17041          append_history(p, "Hangup", "Got 487 on CANCEL request from us. Queued AST hangup request");
17042       } else if (!req->ignore) {
17043          update_call_counter(p, DEC_CALL_LIMIT);
17044          append_history(p, "Hangup", "Got 487 on CANCEL request from us on call without owner. Killing this dialog.");
17045          p->needdestroy = 1;
17046          sip_alreadygone(p);
17047       }
17048       break;
17049    case 415: /* Unsupported media type */
17050    case 488: /* Not acceptable here */
17051       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17052       if (p->udptl && p->t38.state == T38_LOCAL_REINVITE) {
17053          change_t38_state(p, T38_DISABLED);
17054          /* Try to reset RTP timers */
17055          ast_rtp_set_rtptimers_onhold(p->rtp);
17056 
17057          /* Trigger a reinvite back to audio */
17058          transmit_reinvite_with_sdp(p, FALSE, FALSE);
17059       } else {
17060          /* We can't set up this call, so give up */
17061          if (p->owner && !req->ignore)
17062             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17063          p->needdestroy = 1;
17064          /* If there's no dialog to end, then mark p as already gone */
17065          if (!reinvite)
17066             sip_alreadygone(p);
17067       }
17068       break;
17069    case 491: /* Pending */
17070       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17071       if (p->owner && !req->ignore) {
17072          if (p->owner->_state != AST_STATE_UP) {
17073             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17074             p->needdestroy = 1;
17075          } else {
17076             /* This is a re-invite that failed. */
17077             /* Reset the flag after a while 
17078              */
17079             int wait;
17080             /* RFC 3261, if owner of call, wait between 2.1 to 4 seconds,
17081              * if not owner of call, wait 0 to 2 seconds */
17082             if (p->outgoing_call) {
17083                wait = 2100 + ast_random() % 2000;
17084             } else {
17085                wait = ast_random() % 2000;
17086             }
17087             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."));
17088             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);
17089             ast_debug(2, "Reinvite race. Waiting %d secs before retry\n", wait);
17090          }
17091       }
17092       break;
17093 
17094    case 501: /* Not implemented */
17095       xmitres = transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17096       if (p->owner)
17097          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17098       break;
17099    }
17100    if (xmitres == XMIT_ERROR)
17101       ast_log(LOG_WARNING, "Could not transmit message in dialog %s\n", p->callid);
17102 }
17103 
17104 /* \brief Handle SIP response in NOTIFY transaction
17105        We've sent a NOTIFY, now handle responses to it
17106   */
17107 static void handle_response_notify(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17108 {
17109    switch (resp) {
17110    case 200:   /* Notify accepted */
17111       /* They got the notify, this is the end */
17112       if (p->owner) {
17113          if (!p->refer) {
17114             ast_log(LOG_WARNING, "Notify answer on an owned channel? - %s\n", p->owner->name);
17115             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_NORMAL_UNSPECIFIED);
17116          } else {
17117             ast_debug(4, "Got OK on REFER Notify message\n");
17118          }
17119       } else {
17120          if (p->subscribed == NONE) {
17121             ast_debug(4, "Got 200 accepted on NOTIFY\n");
17122             p->needdestroy = 1;
17123          }
17124          if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17125             /* Ready to send the next state we have on queue */
17126             ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17127             cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17128          }
17129       }
17130       break;
17131    case 401:   /* Not www-authorized on SIP method */
17132    case 407:   /* Proxy auth */
17133       if (!p->notify_headers) {
17134          break; /* Only device notify can use NOTIFY auth */
17135       }
17136       ast_string_field_set(p, theirtag, NULL);
17137       if (ast_strlen_zero(p->authname)) {
17138          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));
17139          p->needdestroy = 1;
17140       }
17141       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_NOTIFY, 0)) {
17142          ast_log(LOG_NOTICE, "Failed to authenticate on NOTYFY to '%s'\n", get_header(&p->initreq, "From"));
17143          p->needdestroy = 1;
17144       }
17145       break;
17146    }
17147 }
17148 
17149 /* \brief Handle SIP response in REFER transaction
17150    We've sent a REFER, now handle responses to it 
17151   */
17152 static void handle_response_refer(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17153 {
17154    /* If no refer structure exists, then do nothing */
17155    if (!p->refer)
17156       return;
17157 
17158    switch (resp) {
17159    case 202:   /* Transfer accepted */
17160       /* We need  to do something here */
17161       /* The transferee is now sending INVITE to target */
17162       p->refer->status = REFER_ACCEPTED;
17163       /* Now wait for next message */
17164       ast_debug(3, "Got 202 accepted on transfer\n");
17165       /* We should hang along, waiting for NOTIFY's here */
17166       break;
17167 
17168    case 401:   /* Not www-authorized on SIP method */
17169    case 407:   /* Proxy auth */
17170       if (ast_strlen_zero(p->authname)) {
17171          ast_log(LOG_WARNING, "Asked to authenticate REFER to %s:%d but we have no matching peer or realm auth!\n",
17172             ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17173          p->needdestroy = 1;
17174       }
17175       if (p->authtries > 1 || do_proxy_auth(p, req, resp, SIP_REFER, 0)) {
17176          ast_log(LOG_NOTICE, "Failed to authenticate on REFER to '%s'\n", get_header(&p->initreq, "From"));
17177          p->refer->status = REFER_NOAUTH;
17178          p->needdestroy = 1;
17179       }
17180       break;
17181    case 481: /* Call leg does not exist */
17182 
17183       /* A transfer with Replaces did not work */
17184       /* OEJ: We should Set flag, cancel the REFER, go back
17185       to original call - but right now we can't */
17186       ast_log(LOG_WARNING, "Remote host can't match REFER request to call '%s'. Giving up.\n", p->callid);
17187       if (p->owner)
17188          ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17189       p->needdestroy = 1;
17190       break;
17191 
17192    case 500:   /* Server error */
17193    case 501:   /* Method not implemented */
17194       /* Return to the current call onhold */
17195       /* Status flag needed to be reset */
17196       ast_log(LOG_NOTICE, "SIP transfer to %s failed, call miserably fails. \n", p->refer->refer_to);
17197       p->needdestroy = 1;
17198       p->refer->status = REFER_FAILED;
17199       break;
17200    case 603:   /* Transfer declined */
17201       ast_log(LOG_NOTICE, "SIP transfer to %s declined, call miserably fails. \n", p->refer->refer_to);
17202       p->refer->status = REFER_FAILED;
17203       p->needdestroy = 1;
17204       break;
17205    }
17206 }
17207 
17208 /*! \brief Handle responses on REGISTER to services */
17209 static int handle_response_register(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17210 {
17211    int expires, expires_ms;
17212    struct sip_registry *r;
17213    r=p->registry;
17214    
17215    switch (resp) {
17216    case 401:   /* Unauthorized */
17217       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
17218          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s@%s' (Tries %d)\n", p->registry->username, p->registry->hostname, p->authtries);
17219          p->needdestroy = 1;
17220       }
17221       break;
17222    case 403:   /* Forbidden */
17223       ast_log(LOG_WARNING, "Forbidden - wrong password on authentication for REGISTER for '%s' to '%s'\n", p->registry->username, p->registry->hostname);
17224       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 403"));
17225       r->regstate = REG_STATE_NOAUTH;
17226       p->needdestroy = 1;
17227       break;
17228    case 404:   /* Not found */
17229       ast_log(LOG_WARNING, "Got 404 Not found on SIP register to service %s@%s, giving up\n", p->registry->username, p->registry->hostname);
17230       p->needdestroy = 1;
17231       if (r->call)
17232          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 404");
17233       r->regstate = REG_STATE_REJECTED;
17234       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 404"));
17235       break;
17236    case 407:   /* Proxy auth */
17237       if (p->authtries == MAX_AUTHTRIES || do_register_auth(p, req, resp)) {
17238          ast_log(LOG_NOTICE, "Failed to authenticate on REGISTER to '%s' (tries '%d')\n", get_header(&p->initreq, "From"), p->authtries);
17239          p->needdestroy = 1;
17240       }
17241       break;
17242    case 408:   /* Request timeout */
17243       /* Got a timeout response, so reset the counter of failed responses */
17244       if (r) {
17245          r->regattempts = 0;
17246       } else {
17247          ast_log(LOG_WARNING, "Got a 408 response to our REGISTER on call %s after we had destroyed the registry object\n", p->callid);
17248       }
17249       break;
17250    case 423:   /* Interval too brief */
17251       r->expiry = atoi(get_header(req, "Min-Expires"));
17252       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);
17253       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 423"));
17254       if (r->call) {
17255          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 423");
17256          p->needdestroy = 1;
17257       }
17258       if (r->expiry > max_expiry) {
17259          ast_log(LOG_WARNING, "Required expiration time from %s@%s is too high, giving up\n", p->registry->username, p->registry->hostname);
17260          r->expiry = r->configured_expiry;
17261          r->regstate = REG_STATE_REJECTED;
17262       } else {
17263          r->regstate = REG_STATE_UNREGISTERED;
17264          transmit_register(r, SIP_REGISTER, NULL, NULL);
17265       }
17266       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));
17267       break;
17268    case 479:   /* SER: Not able to process the URI - address is wrong in register*/
17269       ast_log(LOG_WARNING, "Got error 479 on register to %s@%s, giving up (check config)\n", p->registry->username, p->registry->hostname);
17270       p->needdestroy = 1;
17271       if (r->call)
17272          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 479");
17273       r->regstate = REG_STATE_REJECTED;
17274       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 479"));
17275       break;
17276    case 200:   /* 200 OK */
17277       if (!r) {
17278          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));
17279          p->needdestroy = 1;
17280          return 0;
17281       }
17282       
17283       r->regstate = REG_STATE_REGISTERED;
17284       r->regtime = ast_tvnow();     /* Reset time of last succesful registration */
17285       manager_event(EVENT_FLAG_SYSTEM, "Registry", "ChannelType: SIP\r\nDomain: %s\r\nStatus: %s\r\n", r->hostname, regstate2str(r->regstate));
17286       r->regattempts = 0;
17287       ast_debug(1, "Registration successful\n");
17288       if (r->timeout > -1) {
17289          ast_debug(1, "Cancelling timeout %d\n", r->timeout);
17290       }
17291       AST_SCHED_DEL_UNREF(sched, r->timeout, registry_unref(r, "reg ptr unref from handle_response_register 200"));
17292       if (r->call)
17293          r->call = dialog_unref(r->call, "unsetting registry->call pointer-- case 200");
17294       p->registry = registry_unref(p->registry, "unref registry entry p->registry");
17295       /* Let this one hang around until we have all the responses */
17296       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
17297       /* p->needdestroy = 1; */
17298       
17299       /* set us up for re-registering
17300        * figure out how long we got registered for
17301        * according to section 6.13 of RFC, contact headers override
17302        * expires headers, so check those first */
17303       expires = 0;
17304 
17305       /* XXX todo: try to save the extra call */
17306       if (!ast_strlen_zero(get_header(req, "Contact"))) {
17307          const char *contact = NULL;
17308          const char *tmptmp = NULL;
17309          int start = 0;
17310          for(;;) {
17311             contact = __get_header(req, "Contact", &start);
17312             /* this loop ensures we get a contact header about our register request */
17313             if(!ast_strlen_zero(contact)) {
17314                if( (tmptmp=strstr(contact, p->our_contact))) {
17315                   contact=tmptmp;
17316                   break;
17317                }
17318             } else
17319                break;
17320          }
17321          tmptmp = strcasestr(contact, "expires=");
17322          if (tmptmp) {
17323             if (sscanf(tmptmp + 8, "%30d;", &expires) != 1)
17324                expires = 0;
17325          }
17326          
17327       }
17328       if (!expires) 
17329          expires=atoi(get_header(req, "expires"));
17330       if (!expires)
17331          expires=default_expiry;
17332       
17333       expires_ms = expires * 1000;
17334       if (expires <= EXPIRY_GUARD_LIMIT)
17335          expires_ms -= MAX((expires_ms * EXPIRY_GUARD_PCT), EXPIRY_GUARD_MIN);
17336       else
17337          expires_ms -= EXPIRY_GUARD_SECS * 1000;
17338       if (sipdebug)
17339          ast_log(LOG_NOTICE, "Outbound Registration: Expiry for %s is %d sec (Scheduling reregistration in %d s)\n", r->hostname, expires, expires_ms/1000); 
17340       
17341       r->refresh= (int) expires_ms / 1000;
17342       
17343       /* Schedule re-registration before we expire */
17344       AST_SCHED_REPLACE_UNREF(r->expire, sched, expires_ms, sip_reregister, r, 
17345                         registry_unref(_data,"unref in REPLACE del fail"), 
17346                         registry_unref(r,"unref in REPLACE add fail"), 
17347                         registry_addref(r,"The Addition side of REPLACE")); 
17348    }
17349    return 1;
17350 }
17351 
17352 /*! \brief Handle qualification responses (OPTIONS) */
17353 static void handle_response_peerpoke(struct sip_pvt *p, int resp, struct sip_request *req)
17354 {
17355    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! */
17356    int statechanged, is_reachable, was_reachable;
17357    int pingtime = ast_tvdiff_ms(ast_tvnow(), peer->ps);
17358 
17359    /*
17360     * Compute the response time to a ping (goes in peer->lastms.)
17361     * -1 means did not respond, 0 means unknown,
17362     * 1..maxms is a valid response, >maxms means late response.
17363     */
17364    if (pingtime < 1) /* zero = unknown, so round up to 1 */
17365       pingtime = 1;
17366 
17367    /* Now determine new state and whether it has changed.
17368     * Use some helper variables to simplify the writing
17369     * of the expressions.
17370     */
17371    was_reachable = peer->lastms > 0 && peer->lastms <= peer->maxms;
17372    is_reachable = pingtime <= peer->maxms;
17373    statechanged = peer->lastms == 0 /* yes, unknown before */
17374       || was_reachable != is_reachable;
17375 
17376    peer->lastms = pingtime;
17377    peer->call = dialog_unref(peer->call, "unref dialog peer->call");
17378    if (statechanged) {
17379       const char *s = is_reachable ? "Reachable" : "Lagged";
17380       char str_lastms[20];
17381       snprintf(str_lastms, sizeof(str_lastms), "%d", pingtime);
17382 
17383       ast_log(LOG_NOTICE, "Peer '%s' is now %s. (%dms / %dms)\n",
17384          peer->name, s, pingtime, peer->maxms);
17385       ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
17386       if (sip_cfg.peer_rtupdate) {
17387          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", str_lastms, SENTINEL);
17388       }
17389       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus",
17390          "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: %s\r\nTime: %d\r\n",
17391          peer->name, s, pingtime);
17392       if (is_reachable && global_regextenonqualify)
17393          register_peer_exten(peer, TRUE);
17394    }
17395 
17396    p->needdestroy = 1;
17397 
17398    /* Try again eventually */
17399    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched,
17400          is_reachable ? peer->qualifyfreq : DEFAULT_FREQ_NOTOK,
17401          sip_poke_peer_s, peer,
17402          unref_peer(_data, "removing poke peer ref"),
17403          unref_peer(peer, "removing poke peer ref"),
17404          ref_peer(peer, "adding poke peer ref"));
17405 }
17406 
17407 /*! \brief Immediately stop RTP, VRTP and UDPTL as applicable */
17408 static void stop_media_flows(struct sip_pvt *p)
17409 {
17410    /* Immediately stop RTP, VRTP and UDPTL as applicable */
17411    if (p->rtp)
17412       ast_rtp_stop(p->rtp);
17413    if (p->vrtp)
17414       ast_rtp_stop(p->vrtp);
17415    if (p->trtp)
17416       ast_rtp_stop(p->trtp);
17417    if (p->udptl)
17418       ast_udptl_stop(p->udptl);
17419 }
17420 
17421 /*! \brief Handle SIP response in dialogue
17422    \note only called by handle_incoming */
17423 static void handle_response(struct sip_pvt *p, int resp, char *rest, struct sip_request *req, int seqno)
17424 {
17425    struct ast_channel *owner;
17426    int sipmethod;
17427    int res = 1;
17428    const char *c = get_header(req, "Cseq");
17429    /* 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 */
17430    char *c_copy = ast_strdupa(c);
17431    /* Skip the Cseq and its subsequent spaces */
17432    const char *msg = ast_skip_blanks(ast_skip_nonblanks(c_copy));
17433 
17434    if (!msg)
17435       msg = "";
17436 
17437    sipmethod = find_sip_method(msg);
17438 
17439    owner = p->owner;
17440    if (owner) 
17441       owner->hangupcause = hangup_sip2cause(resp);
17442 
17443    if (p->socket.type == SIP_TRANSPORT_UDP) {
17444       int ack_res;
17445 
17446       /* Acknowledge whatever it is destined for */
17447       if ((resp >= 100) && (resp <= 199)) {
17448          ack_res = __sip_semi_ack(p, seqno, 0, sipmethod);
17449       } else {
17450          ack_res = __sip_ack(p, seqno, 0, sipmethod);
17451       }
17452 
17453       if (ack_res == FALSE) {
17454          append_history(p, "Ignore", "Ignoring this retransmit\n");
17455          return;
17456       }
17457    }
17458 
17459    /* If this is a NOTIFY for a subscription clear the flag that indicates that we have a NOTIFY pending */
17460    if (!p->owner && sipmethod == SIP_NOTIFY && p->pendinginvite) 
17461       p->pendinginvite = 0;
17462 
17463    /* Get their tag if we haven't already */
17464    if (ast_strlen_zero(p->theirtag) || (resp >= 200)) {
17465       char tag[128];
17466 
17467       gettag(req, "To", tag, sizeof(tag));
17468       ast_string_field_set(p, theirtag, tag);
17469    }
17470    /* This needs to be configurable on a channel/peer level,
17471       not mandatory for all communication. Sadly enough, NAT implementations
17472       are not so stable so we can always rely on these headers. 
17473       Temporarily disabled, while waiting for fix.
17474       Fix assigned to Rizzo :-)
17475    */
17476    /* check_via_response(p, req); */
17477 
17478    /* RFC 3261 Section 15 specifies that if we receive a 408 or 481
17479     * in response to a BYE, then we should end the current dialog
17480     * and session.  It is known that at least one phone manufacturer
17481     * potentially will send a 404 in response to a BYE, so we'll be
17482     * liberal in what we accept and end the dialog and session if we
17483     * receive any of those responses to a BYE.
17484     */
17485    if ((resp == 404 || resp == 408 || resp == 481) && sipmethod == SIP_BYE) {
17486       p->needdestroy = 1;
17487       return;
17488    }
17489 
17490    if (p->relatedpeer && p->method == SIP_OPTIONS) {
17491       /* We don't really care what the response is, just that it replied back. 
17492          Well, as long as it's not a 100 response...  since we might
17493          need to hang around for something more "definitive" */
17494       if (resp != 100)
17495          handle_response_peerpoke(p, resp, req);
17496    } else if (ast_test_flag(&p->flags[0], SIP_OUTGOING)) {
17497       switch(resp) {
17498       case 100:   /* 100 Trying */
17499       case 101:   /* 101 Dialog establishment */
17500          if (sipmethod == SIP_INVITE) 
17501             handle_response_invite(p, resp, rest, req, seqno);
17502          break;
17503       case 183:   /* 183 Session Progress */
17504          if (sipmethod == SIP_INVITE) 
17505             handle_response_invite(p, resp, rest, req, seqno);
17506          break;
17507       case 180:   /* 180 Ringing */
17508          if (sipmethod == SIP_INVITE) 
17509             handle_response_invite(p, resp, rest, req, seqno);
17510          break;
17511       case 182:       /* 182 Queued */
17512          if (sipmethod == SIP_INVITE)
17513             handle_response_invite(p, resp, rest, req, seqno);
17514          break;
17515       case 200:   /* 200 OK */
17516          p->authtries = 0; /* Reset authentication counter */
17517          if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO) {
17518             /* We successfully transmitted a message 
17519                or a video update request in INFO */
17520             /* Nothing happens here - the message is inside a dialog */
17521          } else if (sipmethod == SIP_INVITE) {
17522             handle_response_invite(p, resp, rest, req, seqno);
17523          } else if (sipmethod == SIP_NOTIFY) {
17524             handle_response_notify(p, resp, rest, req, seqno);
17525          } else if (sipmethod == SIP_REGISTER) 
17526             res = handle_response_register(p, resp, rest, req, seqno);
17527          else if (sipmethod == SIP_BYE) {    /* Ok, we're ready to go */
17528             p->needdestroy = 1;
17529             ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17530          } else if (sipmethod == SIP_SUBSCRIBE) {
17531             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
17532          }
17533          break;
17534       case 202:   /* Transfer accepted */
17535          if (sipmethod == SIP_REFER) 
17536             handle_response_refer(p, resp, rest, req, seqno);
17537          break;
17538       case 401: /* Not www-authorized on SIP method */
17539       case 407: /* Proxy auth required */
17540          if (sipmethod == SIP_INVITE)
17541             handle_response_invite(p, resp, rest, req, seqno);
17542          else if (sipmethod == SIP_NOTIFY)
17543             handle_response_notify(p, resp, rest, req, seqno);
17544          else if (sipmethod == SIP_REFER)
17545             handle_response_refer(p, resp, rest, req, seqno);
17546          else if (p->registry && sipmethod == SIP_REGISTER)
17547             res = handle_response_register(p, resp, rest, req, seqno);
17548          else if (sipmethod == SIP_BYE) {
17549             if (p->options)
17550                p->options->auth_type = resp;
17551             if (ast_strlen_zero(p->authname)) {
17552                ast_log(LOG_WARNING, "Asked to authenticate %s, to %s:%d but we have no matching peer!\n",
17553                      msg, ast_inet_ntoa(p->recv.sin_addr), ntohs(p->recv.sin_port));
17554                p->needdestroy = 1;
17555             } else if ((p->authtries == MAX_AUTHTRIES) || do_proxy_auth(p, req, resp,  sipmethod, 0)) {
17556                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17557                p->needdestroy = 1;
17558             }
17559          } else {
17560             ast_log(LOG_WARNING, "Got authentication request (%d) on %s to '%s'\n", resp, sip_methods[sipmethod].text, get_header(req, "To"));
17561             p->needdestroy = 1;
17562          }
17563          break;
17564       case 403: /* Forbidden - we failed authentication */
17565          if (sipmethod == SIP_INVITE)
17566             handle_response_invite(p, resp, rest, req, seqno);
17567          else if (p->registry && sipmethod == SIP_REGISTER) 
17568             res = handle_response_register(p, resp, rest, req, seqno);
17569          else {
17570             ast_log(LOG_WARNING, "Forbidden - maybe wrong password on authentication for %s\n", msg);
17571             p->needdestroy = 1;
17572          }
17573          break;
17574       case 404: /* Not found */
17575          if (p->registry && sipmethod == SIP_REGISTER)
17576             res = handle_response_register(p, resp, rest, req, seqno);
17577          else if (sipmethod == SIP_INVITE)
17578             handle_response_invite(p, resp, rest, req, seqno);
17579          else if (owner)
17580             ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17581          break;
17582       case 423: /* Interval too brief */
17583          if (sipmethod == SIP_REGISTER)
17584             res = handle_response_register(p, resp, rest, req, seqno);
17585          break;
17586       case 408: /* Request timeout - terminate dialog */
17587          if (sipmethod == SIP_INVITE)
17588             handle_response_invite(p, resp, rest, req, seqno);
17589          else if (sipmethod == SIP_REGISTER) 
17590             res = handle_response_register(p, resp, rest, req, seqno);
17591          else if (sipmethod == SIP_BYE) {
17592             p->needdestroy = 1;
17593             ast_debug(4, "Got timeout on bye. Thanks for the answer. Now, kill this call\n");
17594          } else {
17595             if (owner)
17596                ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17597             p->needdestroy = 1;
17598          }
17599          break;
17600 
17601       case 422: /* Session-Timers: Session Interval Too Small */
17602          if (sipmethod == SIP_INVITE) {
17603             handle_response_invite(p, resp, rest, req, seqno);
17604          }
17605          break;
17606 
17607       case 481: /* Call leg does not exist */
17608          if (sipmethod == SIP_INVITE) {
17609             handle_response_invite(p, resp, rest, req, seqno);
17610          } else if (sipmethod == SIP_REFER) {
17611             handle_response_refer(p, resp, rest, req, seqno);
17612          } else if (sipmethod == SIP_BYE) {
17613             /* The other side has no transaction to bye,
17614             just assume it's all right then */
17615             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17616          } else if (sipmethod == SIP_CANCEL) {
17617             /* The other side has no transaction to cancel,
17618             just assume it's all right then */
17619             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17620          } else {
17621             ast_log(LOG_WARNING, "Remote host can't match request %s to call '%s'. Giving up.\n", sip_methods[sipmethod].text, p->callid);
17622             /* Guessing that this is not an important request */
17623          }
17624          break;
17625       case 487:
17626          if (sipmethod == SIP_INVITE)
17627             handle_response_invite(p, resp, rest, req, seqno);
17628          break;
17629       case 415: /* Unsupported media type */
17630       case 488: /* Not acceptable here - codec error */
17631          if (sipmethod == SIP_INVITE)
17632             handle_response_invite(p, resp, rest, req, seqno);
17633          break;
17634       case 491: /* Pending */
17635          if (sipmethod == SIP_INVITE)
17636             handle_response_invite(p, resp, rest, req, seqno);
17637          else {
17638             ast_debug(1, "Got 491 on %s, unspported. Call ID %s\n", sip_methods[sipmethod].text, p->callid);
17639             p->needdestroy = 1;
17640          }
17641          break;
17642       case 501: /* Not Implemented */
17643          if (sipmethod == SIP_INVITE)
17644             handle_response_invite(p, resp, rest, req, seqno);
17645          else if (sipmethod == SIP_REFER)
17646             handle_response_refer(p, resp, rest, req, seqno);
17647          else
17648             ast_log(LOG_WARNING, "Host '%s' does not implement '%s'\n", ast_inet_ntoa(p->sa.sin_addr), msg);
17649          break;
17650       case 603:   /* Declined transfer */
17651          if (sipmethod == SIP_REFER) {
17652             handle_response_refer(p, resp, rest, req, seqno);
17653             break;
17654          }
17655          /* Fallthrough */
17656       default:
17657          if ((resp >= 300) && (resp < 700)) {
17658             /* Fatal response */
17659             if ((resp != 487))
17660                ast_verb(3, "Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17661    
17662             if (sipmethod == SIP_INVITE)
17663                stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
17664 
17665             /* XXX Locking issues?? XXX */
17666             switch(resp) {
17667             case 300: /* Multiple Choices */
17668             case 301: /* Moved permanently */
17669             case 302: /* Moved temporarily */
17670             case 305: /* Use Proxy */
17671                parse_moved_contact(p, req);
17672                /* Fall through */
17673             case 486: /* Busy here */
17674             case 600: /* Busy everywhere */
17675             case 603: /* Decline */
17676                if (p->owner)
17677                   ast_queue_control(p->owner, AST_CONTROL_BUSY);
17678                break;
17679             case 482: /*!
17680                \note SIP is incapable of performing a hairpin call, which
17681                is yet another failure of not having a layer 2 (again, YAY
17682                 IETF for thinking ahead).  So we treat this as a call
17683                 forward and hope we end up at the right place... */
17684                ast_debug(1, "Hairpin detected, setting up call forward for what it's worth\n");
17685                if (p->owner)
17686                   ast_string_field_build(p->owner, call_forward,
17687                                "Local/%s@%s", p->username, p->context);
17688                /* Fall through */
17689             case 480: /* Temporarily Unavailable */
17690             case 404: /* Not Found */
17691             case 410: /* Gone */
17692             case 400: /* Bad Request */
17693             case 500: /* Server error */
17694                if (sipmethod == SIP_REFER) {
17695                   handle_response_refer(p, resp, rest, req, seqno);
17696                   break;
17697                }
17698                /* Fall through */
17699             case 502: /* Bad gateway */
17700             case 503: /* Service Unavailable */
17701             case 504: /* Server Timeout */
17702                if (owner)
17703                   ast_queue_control(p->owner, AST_CONTROL_CONGESTION);
17704                break;
17705             default:
17706                /* Send hangup */ 
17707                if (owner && sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO && sipmethod != SIP_BYE)
17708                   ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
17709                break;
17710             }
17711             /* ACK on invite */
17712             if (sipmethod == SIP_INVITE) 
17713                transmit_request(p, SIP_ACK, seqno, XMIT_UNRELIABLE, FALSE);
17714             if (sipmethod != SIP_MESSAGE && sipmethod != SIP_INFO) 
17715                sip_alreadygone(p);
17716             if (!p->owner)
17717                p->needdestroy = 1;
17718          } else if ((resp >= 100) && (resp < 200)) {
17719             if (sipmethod == SIP_INVITE) {
17720                if (!req->ignore && sip_cancel_destroy(p))
17721                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17722                if (find_sdp(req))
17723                   process_sdp(p, req, SDP_T38_NONE);
17724                if (p->owner) {
17725                   /* Queue a progress frame */
17726                   ast_queue_control(p->owner, AST_CONTROL_PROGRESS);
17727                }
17728             }
17729          } else
17730             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));
17731       }
17732    } else { 
17733       /* Responses to OUTGOING SIP requests on INCOMING calls 
17734          get handled here. As well as out-of-call message responses */
17735       if (req->debug)
17736          ast_verbose("SIP Response message for INCOMING dialog %s arrived\n", msg);
17737 
17738       if (sipmethod == SIP_INVITE && resp == 200) {
17739          /* Tags in early session is replaced by the tag in 200 OK, which is 
17740          the final reply to our INVITE */
17741          char tag[128];
17742 
17743          gettag(req, "To", tag, sizeof(tag));
17744          ast_string_field_set(p, theirtag, tag);
17745       }
17746 
17747       switch(resp) {
17748       case 200:
17749          if (sipmethod == SIP_INVITE) {
17750             handle_response_invite(p, resp, rest, req, seqno);
17751          } else if (sipmethod == SIP_CANCEL) {
17752             ast_debug(1, "Got 200 OK on CANCEL\n");
17753 
17754             /* Wait for 487, then destroy */
17755          } else if (sipmethod == SIP_NOTIFY) {
17756             /* They got the notify, this is the end */
17757             if (p->owner) {
17758                if (p->refer) {
17759                   ast_debug(1, "Got 200 OK on NOTIFY for transfer\n");
17760                } else
17761                   ast_log(LOG_WARNING, "Notify answer on an owned channel?\n");
17762                /* ast_queue_hangup(p->owner); Disabled */
17763             } else {
17764                if (!p->subscribed && !p->refer)
17765                   p->needdestroy = 1;
17766                if (ast_test_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE)) {
17767                   /* Ready to send the next state we have on queue */
17768                   ast_clear_flag(&p->flags[1], SIP_PAGE2_STATECHANGEQUEUE);
17769                   cb_extensionstate((char *)p->context, (char *)p->exten, p->laststate, (void *) p);
17770                }
17771             }
17772          } else if (sipmethod == SIP_BYE)
17773             p->needdestroy = 1;
17774          else if (sipmethod == SIP_MESSAGE || sipmethod == SIP_INFO)
17775             /* We successfully transmitted a message or
17776                a video update request in INFO */
17777             ;
17778          else if (sipmethod == SIP_BYE) 
17779             /* Ok, we're ready to go */
17780             p->needdestroy = 1;
17781          break;
17782       case 202:   /* Transfer accepted */
17783          if (sipmethod == SIP_REFER) 
17784             handle_response_refer(p, resp, rest, req, seqno);
17785          break;
17786       case 401:   /* www-auth */
17787       case 407:
17788          if (sipmethod == SIP_REFER)
17789             handle_response_refer(p, resp, rest, req, seqno);
17790          else if (sipmethod == SIP_INVITE) 
17791             handle_response_invite(p, resp, rest, req, seqno);
17792          else if (sipmethod == SIP_BYE) {
17793             if (p->authtries == MAX_AUTHTRIES || do_proxy_auth(p, req, resp, sipmethod, 0)) {
17794                ast_log(LOG_NOTICE, "Failed to authenticate on %s to '%s'\n", msg, get_header(&p->initreq, "From"));
17795                p->needdestroy = 1;
17796             }
17797          }
17798          break;
17799       case 481:   /* Call leg does not exist */
17800          if (sipmethod == SIP_INVITE) {
17801             /* Re-invite failed */
17802             handle_response_invite(p, resp, rest, req, seqno);
17803          } else if (sipmethod == SIP_BYE) {
17804             p->needdestroy = 1;
17805          } else if (sipdebug) {
17806             ast_debug(1, "Remote host can't match request %s to call '%s'. Giving up\n", sip_methods[sipmethod].text, p->callid);
17807          }
17808          break;
17809       case 501: /* Not Implemented */
17810          if (sipmethod == SIP_INVITE) 
17811             handle_response_invite(p, resp, rest, req, seqno);
17812          else if (sipmethod == SIP_REFER) 
17813             handle_response_refer(p, resp, rest, req, seqno);
17814          break;
17815       case 603:   /* Declined transfer */
17816          if (sipmethod == SIP_REFER) {
17817             handle_response_refer(p, resp, rest, req, seqno);
17818             break;
17819          }
17820          /* Fallthrough */
17821       default: /* Errors without handlers */
17822          if ((resp >= 100) && (resp < 200)) {
17823             if (sipmethod == SIP_INVITE) {   /* re-invite */
17824                if (!req->ignore && sip_cancel_destroy(p))
17825                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17826             }
17827          }
17828          if ((resp >= 300) && (resp < 700)) {
17829             if ((resp != 487))
17830                ast_verb(3, "Incoming call: Got SIP response %d \"%s\" back from %s\n", resp, rest, ast_inet_ntoa(p->sa.sin_addr));
17831             switch(resp) {
17832             case 415: /* Unsupported media type */
17833             case 488: /* Not acceptable here - codec error */
17834             case 603: /* Decline */
17835             case 500: /* Server error */
17836             case 502: /* Bad gateway */
17837             case 503: /* Service Unavailable */
17838             case 504: /* Server timeout */
17839 
17840                /* re-invite failed */
17841                if (sipmethod == SIP_INVITE && sip_cancel_destroy(p))
17842                   ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
17843                break;
17844             }
17845          }
17846          break;
17847       }
17848    }
17849 }
17850 
17851 
17852 /*! \brief Park SIP call support function 
17853    Starts in a new thread, then parks the call
17854    XXX Should we add a wait period after streaming audio and before hangup?? Sometimes the
17855       audio can't be heard before hangup
17856 */
17857 static void *sip_park_thread(void *stuff)
17858 {
17859    struct ast_channel *transferee, *transferer; /* Chan1: The transferee, Chan2: The transferer */
17860    struct sip_dual *d;
17861    struct sip_request req = {0,};
17862    int ext;
17863    int res;
17864 
17865    d = stuff;
17866    transferee = d->chan1;
17867    transferer = d->chan2;
17868    copy_request(&req, &d->req);
17869 
17870    if (!transferee || !transferer) {
17871       ast_log(LOG_ERROR, "Missing channels for parking! Transferer %s Transferee %s\n", transferer ? "<available>" : "<missing>", transferee ? "<available>" : "<missing>" );
17872       if (d->req.data)
17873          ast_free(d->req.data);
17874       free(d);
17875       return NULL;
17876    }
17877    ast_debug(4, "SIP Park: Transferer channel %s, Transferee %s\n", transferer->name, transferee->name);
17878 
17879    ast_channel_lock(transferee);
17880    if (ast_do_masquerade(transferee)) {
17881       ast_log(LOG_WARNING, "Masquerade failed.\n");
17882       transmit_response(transferer->tech_pvt, "503 Internal error", &req);
17883       ast_channel_unlock(transferee);
17884       if (d->req.data)
17885          ast_free(d->req.data);
17886       free(d);
17887       return NULL;
17888    } 
17889    ast_channel_unlock(transferee);
17890 
17891    res = ast_park_call(transferee, transferer, 0, &ext);
17892    
17893 
17894 #ifdef WHEN_WE_KNOW_THAT_THE_CLIENT_SUPPORTS_MESSAGE
17895    if (!res) {
17896       transmit_message_with_text(transferer->tech_pvt, "Unable to park call.\n");
17897    } else {
17898       /* Then tell the transferer what happened */
17899       sprintf(buf, "Call parked on extension '%d'", ext);
17900       transmit_message_with_text(transferer->tech_pvt, buf);
17901    }
17902 #endif
17903 
17904    /* Any way back to the current call??? */
17905    /* Transmit response to the REFER request */
17906    transmit_response(transferer->tech_pvt, "202 Accepted", &req);
17907    if (!res)   {
17908       /* Transfer succeeded */
17909       append_history(transferer->tech_pvt, "SIPpark", "Parked call on %d", ext);
17910       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "200 OK", TRUE);
17911       transferer->hangupcause = AST_CAUSE_NORMAL_CLEARING;
17912       ast_hangup(transferer); /* This will cause a BYE */
17913       ast_debug(1, "SIP Call parked on extension '%d'\n", ext);
17914    } else {
17915       transmit_notify_with_sipfrag(transferer->tech_pvt, d->seqno, "503 Service Unavailable", TRUE);
17916       append_history(transferer->tech_pvt, "SIPpark", "Parking failed\n");
17917       ast_debug(1, "SIP Call parked failed \n");
17918       /* Do not hangup call */
17919    }
17920    if (d->req.data)
17921       ast_free(d->req.data);
17922    free(d);
17923    return NULL;
17924 }
17925 
17926 /*! \brief Park a call using the subsystem in res_features.c 
17927    This is executed in a separate thread
17928 */
17929 static int sip_park(struct ast_channel *chan1, struct ast_channel *chan2, struct sip_request *req, int seqno)
17930 {
17931    struct sip_dual *d;
17932    struct ast_channel *transferee, *transferer;
17933       /* Chan2m: The transferer, chan1m: The transferee */
17934    pthread_t th;
17935 
17936    transferee = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan1->accountcode, chan1->exten, chan1->context, chan1->amaflags, "Parking/%s", chan1->name);
17937    transferer = ast_channel_alloc(0, AST_STATE_DOWN, 0, 0, chan2->accountcode, chan2->exten, chan2->context, chan2->amaflags, "SIPPeer/%s", chan2->name);
17938    if ((!transferer) || (!transferee)) {
17939       if (transferee) {
17940          transferee->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17941          ast_hangup(transferee);
17942       }
17943       if (transferer) {
17944          transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17945          ast_hangup(transferer);
17946       }
17947       return -1;
17948    }
17949 
17950    /* Make formats okay */
17951    transferee->readformat = chan1->readformat;
17952    transferee->writeformat = chan1->writeformat;
17953 
17954    /* Prepare for taking over the channel */
17955    ast_channel_masquerade(transferee, chan1);
17956 
17957    /* Setup the extensions and such */
17958    ast_copy_string(transferee->context, chan1->context, sizeof(transferee->context));
17959    ast_copy_string(transferee->exten, chan1->exten, sizeof(transferee->exten));
17960    transferee->priority = chan1->priority;
17961       
17962    /* We make a clone of the peer channel too, so we can play
17963       back the announcement */
17964 
17965    /* Make formats okay */
17966    transferer->readformat = chan2->readformat;
17967    transferer->writeformat = chan2->writeformat;
17968    if (!ast_strlen_zero(chan2->parkinglot))
17969       ast_string_field_set(transferer, parkinglot, chan2->parkinglot);
17970 
17971    /* Prepare for taking over the channel.  Go ahead and grab this channel
17972     * lock here to avoid a deadlock with callbacks into the channel driver
17973     * that hold the channel lock and want the pvt lock.  */
17974    while (ast_channel_trylock(chan2)) {
17975       struct sip_pvt *pvt = chan2->tech_pvt;
17976       sip_pvt_unlock(pvt);
17977       usleep(1);
17978       sip_pvt_lock(pvt);
17979    }
17980    ast_channel_masquerade(transferer, chan2);
17981    ast_channel_unlock(chan2);
17982 
17983    /* Setup the extensions and such */
17984    ast_copy_string(transferer->context, chan2->context, sizeof(transferer->context));
17985    ast_copy_string(transferer->exten, chan2->exten, sizeof(transferer->exten));
17986    transferer->priority = chan2->priority;
17987 
17988    ast_channel_lock(transferer);
17989    if (ast_do_masquerade(transferer)) {
17990       ast_log(LOG_WARNING, "Masquerade failed :(\n");
17991       ast_channel_unlock(transferer);
17992       transferer->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
17993       ast_hangup(transferer);
17994       return -1;
17995    }
17996    ast_channel_unlock(transferer);
17997    if (!transferer || !transferee) {
17998       if (!transferer) { 
17999          ast_debug(1, "No transferer channel, giving up parking\n");
18000       }
18001       if (!transferee) {
18002          ast_debug(1, "No transferee channel, giving up parking\n");
18003       }
18004       return -1;
18005    }
18006    if ((d = ast_calloc(1, sizeof(*d)))) {
18007 
18008       /* Save original request for followup */
18009       copy_request(&d->req, req);
18010       d->chan1 = transferee;  /* Transferee */
18011       d->chan2 = transferer;  /* Transferer */
18012       d->seqno = seqno;
18013       if (ast_pthread_create_detached_background(&th, NULL, sip_park_thread, d) < 0) {
18014          /* Could not start thread */
18015          if (d->req.data)
18016             ast_free(d->req.data);
18017          ast_free(d);   /* We don't need it anymore. If thread is created, d will be free'd
18018                   by sip_park_thread() */
18019          return 0;
18020       }
18021    } 
18022    return -1;
18023 }
18024 
18025 /*! \brief Turn off generator data 
18026    XXX Does this function belong in the SIP channel?
18027 */
18028 static void ast_quiet_chan(struct ast_channel *chan) 
18029 {
18030    if (chan && chan->_state == AST_STATE_UP) {
18031       if (ast_test_flag(chan, AST_FLAG_MOH))
18032          ast_moh_stop(chan);
18033       else if (chan->generatordata)
18034          ast_deactivate_generator(chan);
18035    }
18036 }
18037 
18038 /*! \brief Attempt transfer of SIP call 
18039    This fix for attended transfers on a local PBX */
18040 static int attempt_transfer(struct sip_dual *transferer, struct sip_dual *target)
18041 {
18042    int res = 0;
18043    struct ast_channel *peera = NULL,   
18044       *peerb = NULL,
18045       *peerc = NULL,
18046       *peerd = NULL;
18047 
18048 
18049    /* We will try to connect the transferee with the target and hangup
18050       all channels to the transferer */   
18051    ast_debug(4, "Sip transfer:--------------------\n");
18052    if (transferer->chan1)
18053       ast_debug(4, "-- Transferer to PBX channel: %s State %s\n", transferer->chan1->name, ast_state2str(transferer->chan1->_state));
18054    else
18055       ast_debug(4, "-- No transferer first channel - odd??? \n");
18056    if (target->chan1)
18057       ast_debug(4, "-- Transferer to PBX second channel (target): %s State %s\n", target->chan1->name, ast_state2str(target->chan1->_state));
18058    else
18059       ast_debug(4, "-- No target first channel ---\n");
18060    if (transferer->chan2)
18061       ast_debug(4, "-- Bridged call to transferee: %s State %s\n", transferer->chan2->name, ast_state2str(transferer->chan2->_state));
18062    else
18063       ast_debug(4, "-- No bridged call to transferee\n");
18064    if (target->chan2)
18065       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)");
18066    else
18067       ast_debug(4, "-- No target second channel ---\n");
18068    ast_debug(4, "-- END Sip transfer:--------------------\n");
18069    if (transferer->chan2) { /* We have a bridge on the transferer's channel */
18070       peera = transferer->chan1; /* Transferer - PBX -> transferee channel * the one we hangup */
18071       peerb = target->chan1;     /* Transferer - PBX -> target channel - This will get lost in masq */
18072       peerc = transferer->chan2; /* Asterisk to Transferee */
18073       peerd = target->chan2;     /* Asterisk to Target */
18074       ast_debug(3, "SIP transfer: Four channels to handle\n");
18075    } else if (target->chan2) {   /* Transferer has no bridge (IVR), but transferee */
18076       peera = target->chan1;     /* Transferer to PBX -> target channel */
18077       peerb = transferer->chan1; /* Transferer to IVR*/
18078       peerc = target->chan2;     /* Asterisk to Target */
18079       peerd = transferer->chan2; /* Nothing */
18080       ast_debug(3, "SIP transfer: Three channels to handle\n");
18081    }
18082 
18083    if (peera && peerb && peerc && (peerb != peerc)) {
18084       ast_quiet_chan(peera);     /* Stop generators */
18085       ast_quiet_chan(peerb);  
18086       ast_quiet_chan(peerc);
18087       if (peerd)
18088          ast_quiet_chan(peerd);
18089 
18090       ast_debug(4, "SIP transfer: trying to masquerade %s into %s\n", peerc->name, peerb->name);
18091       if (ast_channel_masquerade(peerb, peerc)) {
18092          ast_log(LOG_WARNING, "Failed to masquerade %s into %s\n", peerb->name, peerc->name);
18093          res = -1;
18094       } else
18095          ast_debug(4, "SIP transfer: Succeeded to masquerade channels.\n");
18096       return res;
18097    } else {
18098       ast_log(LOG_NOTICE, "SIP Transfer attempted with no appropriate bridged calls to transfer\n");
18099       if (transferer->chan1)
18100          ast_softhangup_nolock(transferer->chan1, AST_SOFTHANGUP_DEV);
18101       if (target->chan1)
18102          ast_softhangup_nolock(target->chan1, AST_SOFTHANGUP_DEV);
18103       return -1;
18104    }
18105    return 0;
18106 }
18107 
18108 /*! \brief Get tag from packet 
18109  *
18110  * \return Returns the pointer to the provided tag buffer,
18111  *         or NULL if the tag was not found.
18112  */
18113 static const char *gettag(const struct sip_request *req, const char *header, char *tagbuf, int tagbufsize)
18114 {
18115    const char *thetag;
18116 
18117    if (!tagbuf)
18118       return NULL;
18119    tagbuf[0] = '\0';    /* reset the buffer */
18120    thetag = get_header(req, header);
18121    thetag = strcasestr(thetag, ";tag=");
18122    if (thetag) {
18123       thetag += 5;
18124       ast_copy_string(tagbuf, thetag, tagbufsize);
18125       return strsep(&tagbuf, ";");
18126    }
18127    return NULL;
18128 }
18129 
18130 /*! \brief Handle incoming notifications */
18131 static int handle_request_notify(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
18132 {
18133    /* This is mostly a skeleton for future improvements */
18134    /* Mostly created to return proper answers on notifications on outbound REFER's */
18135    int res = 0;
18136    const char *event = get_header(req, "Event");
18137    char *eventid = NULL;
18138    char *sep;
18139 
18140    if( (sep = strchr(event, ';')) ) {  /* XXX bug here - overwriting string ? */
18141       *sep++ = '\0';
18142       eventid = sep;
18143    }
18144    
18145    if (sipdebug)
18146       ast_debug(2, "Got NOTIFY Event: %s\n", event);
18147 
18148    if (strcmp(event, "refer")) {
18149       /* We don't understand this event. */
18150       /* Here's room to implement incoming voicemail notifications :-) */
18151       transmit_response(p, "489 Bad event", req);
18152       res = -1;
18153    } else {
18154       /* Save nesting depth for now, since there might be other events we will
18155          support in the future */
18156 
18157       /* Handle REFER notifications */
18158 
18159       char buf[1024];
18160       char *cmd, *code;
18161       int respcode;
18162       int success = TRUE;
18163 
18164       /* EventID for each transfer... EventID is basically the REFER cseq 
18165 
18166        We are getting notifications on a call that we transfered
18167        We should hangup when we are getting a 200 OK in a sipfrag
18168        Check if we have an owner of this event */
18169       
18170       /* Check the content type */
18171       if (strncasecmp(get_header(req, "Content-Type"), "message/sipfrag", strlen("message/sipfrag"))) {
18172          /* We need a sipfrag */
18173          transmit_response(p, "400 Bad request", req);
18174          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18175          return -1;
18176       }
18177 
18178       /* Get the text of the attachment */
18179       if (get_msg_text(buf, sizeof(buf), req, TRUE)) {
18180          ast_log(LOG_WARNING, "Unable to retrieve attachment from NOTIFY %s\n", p->callid);
18181          transmit_response(p, "400 Bad request", req);
18182          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18183          return -1;
18184       }
18185 
18186       /*
18187       From the RFC...
18188       A minimal, but complete, implementation can respond with a single
18189       NOTIFY containing either the body:
18190          SIP/2.0 100 Trying
18191       
18192       if the subscription is pending, the body:
18193          SIP/2.0 200 OK
18194       if the reference was successful, the body:
18195          SIP/2.0 503 Service Unavailable
18196       if the reference failed, or the body:
18197          SIP/2.0 603 Declined
18198 
18199       if the REFER request was accepted before approval to follow the
18200       reference could be obtained and that approval was subsequently denied
18201       (see Section 2.4.7).
18202       
18203       If there are several REFERs in the same dialog, we need to
18204       match the ID of the event header...
18205       */
18206       ast_debug(3, "* SIP Transfer NOTIFY Attachment: \n---%s\n---\n", buf);
18207       cmd = ast_skip_blanks(buf);
18208       code = cmd;
18209       /* We are at SIP/2.0 */
18210       while(*code && (*code > 32)) {   /* Search white space */
18211          code++;
18212       }
18213       *code++ = '\0';
18214       code = ast_skip_blanks(code);
18215       sep = code;
18216       sep++;
18217       while(*sep && (*sep > 32)) {  /* Search white space */
18218          sep++;
18219       }
18220       *sep++ = '\0';       /* Response string */
18221       respcode = atoi(code);
18222       switch (respcode) {
18223       case 100:   /* Trying: */
18224       case 101:   /* dialog establishment */
18225          /* Don't do anything yet */
18226          break;
18227       case 183:   /* Ringing: */
18228          /* Don't do anything yet */
18229          break;
18230       case 200:   /* OK: The new call is up, hangup this call */
18231          /* Hangup the call that we are replacing */
18232          break;
18233       case 301: /* Moved permenantly */
18234       case 302: /* Moved temporarily */
18235          /* Do we get the header in the packet in this case? */
18236          success = FALSE;
18237          break;
18238       case 503:   /* Service Unavailable: The new call failed */
18239             /* Cancel transfer, continue the call */
18240          success = FALSE;
18241          break;
18242       case 603:   /* Declined: Not accepted */
18243             /* Cancel transfer, continue the current call */
18244          success = FALSE;
18245          break;
18246       }
18247       if (!success) {
18248          ast_log(LOG_NOTICE, "Transfer failed. Sorry. Nothing further to do with this call\n");
18249       }
18250       
18251       /* Confirm that we received this packet */
18252       transmit_response(p, "200 OK", req);
18253    };
18254 
18255    if (!p->lastinvite)
18256       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18257 
18258    return res;
18259 }
18260 
18261 /*! \brief Handle incoming OPTIONS request 
18262    An OPTIONS request should be answered like an INVITE from the same UA, including SDP
18263 */
18264 static int handle_request_options(struct sip_pvt *p, struct sip_request *req)
18265 {
18266    int res;
18267 
18268    /*! XXX get_destination assumes we're already authenticated. This means that a request from
18269       a known device (peer) will end up in the wrong context if this is out-of-dialog.
18270       However, we want to handle OPTIONS as light as possible, so we might want to have
18271       a configuration option whether we care or not. Some devices use this for testing
18272       capabilities, which means that we need to match device to answer with proper 
18273       capabilities (including SDP).
18274       \todo Fix handle_request_options device handling with optional authentication
18275          (this needs to be fixed in 1.4 as well)
18276    */
18277 
18278    if (p->lastinvite) {
18279       /* if this is a request in an active dialog, just confirm that the dialog exists. */
18280       transmit_response_with_allow(p, "200 OK", req, 0);
18281       return 0;
18282    }
18283 
18284    res = get_destination(p, req);
18285    build_contact(p);
18286 
18287    if (ast_strlen_zero(p->context))
18288       ast_string_field_set(p, context, default_context);
18289 
18290    if (ast_shutting_down())
18291       transmit_response_with_allow(p, "503 Unavailable", req, 0);
18292    else if (res < 0)
18293       transmit_response_with_allow(p, "404 Not Found", req, 0);
18294    else 
18295       transmit_response_with_allow(p, "200 OK", req, 0);
18296 
18297    /* Destroy if this OPTIONS was the opening request, but not if
18298       it's in the middle of a normal call flow. */
18299    sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18300 
18301    return res;
18302 }
18303 
18304 /*! \brief Handle the transfer part of INVITE with a replaces: header, 
18305     meaning a target pickup or an attended transfer.
18306     Used only once.
18307    XXX 'ignore' is unused.
18308 
18309    \note this function is called by handle_request_invite(). Four locks
18310    held at the beginning of this function, p, p->owner, p->refer->refer_call->owner...
18311    only p's lock should remain at the end of this function.  p's lock is held by sipsock_read()
18312  */
18313 static int handle_invite_replaces(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, struct sockaddr_in *sin, int *nounlock)
18314 {
18315    int earlyreplace = 0;
18316    int oneleggedreplace = 0;     /* Call with no bridge, propably IVR or voice message */
18317    struct ast_channel *c = p->owner;   /* Our incoming call */
18318    struct ast_channel *replacecall = p->refer->refer_call->owner; /* The channel we're about to take over */
18319    struct ast_channel *targetcall;     /* The bridge to the take-over target */
18320 
18321    struct ast_channel *test;
18322 
18323    /* Check if we're in ring state */
18324    if (replacecall->_state == AST_STATE_RING)
18325       earlyreplace = 1;
18326 
18327    /* Check if we have a bridge */
18328    if (!(targetcall = ast_bridged_channel(replacecall))) {
18329       /* We have no bridge */
18330       if (!earlyreplace) {
18331          ast_debug(2, " Attended transfer attempted to replace call with no bridge (maybe ringing). Channel %s!\n", replacecall->name);
18332          oneleggedreplace = 1;
18333       }
18334    } 
18335    if (targetcall && targetcall->_state == AST_STATE_RINGING)
18336       ast_debug(4, "SIP transfer: Target channel is in ringing state\n");
18337 
18338    if (targetcall) 
18339       ast_debug(4, "SIP transfer: Invite Replace incoming channel should bridge to channel %s while hanging up channel %s\n", targetcall->name, replacecall->name); 
18340    else
18341       ast_debug(4, "SIP transfer: Invite Replace incoming channel should replace and hang up channel %s (one call leg)\n", replacecall->name); 
18342 
18343    if (req->ignore) {
18344       ast_log(LOG_NOTICE, "Ignoring this INVITE with replaces in a stupid way.\n");
18345       /* We should answer something here. If we are here, the
18346          call we are replacing exists, so an accepted 
18347          can't harm */
18348       transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
18349       /* Do something more clever here */
18350       if (c) {
18351          *nounlock = 1;
18352          ast_channel_unlock(c);
18353       }
18354       ast_channel_unlock(replacecall);
18355       sip_pvt_unlock(p->refer->refer_call);
18356       return 1;
18357    } 
18358    if (!c) {
18359       /* What to do if no channel ??? */
18360       ast_log(LOG_ERROR, "Unable to create new channel.  Invite/replace failed.\n");
18361       transmit_response_reliable(p, "503 Service Unavailable", req);
18362       append_history(p, "Xfer", "INVITE/Replace Failed. No new channel.");
18363       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18364       ast_channel_unlock(replacecall);
18365       sip_pvt_unlock(p->refer->refer_call);
18366       return 1;
18367    }
18368    append_history(p, "Xfer", "INVITE/Replace received");
18369    /* We have three channels to play with
18370       channel c: New incoming call
18371       targetcall: Call from PBX to target
18372       p->refer->refer_call: SIP pvt dialog from transferer to pbx.
18373       replacecall: The owner of the previous
18374       We need to masq C into refer_call to connect to 
18375       targetcall;
18376       If we are talking to internal audio stream, target call is null.
18377    */
18378 
18379    /* Fake call progress */
18380    transmit_response(p, "100 Trying", req);
18381    ast_setstate(c, AST_STATE_RING);
18382 
18383    /* Masquerade the new call into the referred call to connect to target call 
18384       Targetcall is not touched by the masq */
18385 
18386    /* Answer the incoming call and set channel to UP state */
18387    transmit_response_with_sdp(p, "200 OK", req, XMIT_RELIABLE, FALSE);
18388       
18389    ast_setstate(c, AST_STATE_UP);
18390    
18391    /* Stop music on hold and other generators */
18392    ast_quiet_chan(replacecall);
18393    ast_quiet_chan(targetcall);
18394    ast_debug(4, "Invite/Replaces: preparing to masquerade %s into %s\n", c->name, replacecall->name);
18395 
18396    /* Make sure that the masq does not free our PVT for the old call */
18397    if (! earlyreplace && ! oneleggedreplace )
18398       ast_set_flag(&p->refer->refer_call->flags[0], SIP_DEFER_BYE_ON_TRANSFER);  /* Delay hangup */
18399 
18400    /* Prepare the masquerade - if this does not happen, we will be gone */
18401    if(ast_channel_masquerade(replacecall, c))
18402       ast_log(LOG_ERROR, "Failed to masquerade C into Replacecall\n");
18403    else
18404       ast_debug(4, "Invite/Replaces: Going to masquerade %s into %s\n", c->name, replacecall->name);
18405 
18406    /* C should now be in place of replacecall */
18407    if (ast_do_masquerade(replacecall)) {
18408       ast_log(LOG_WARNING, "Failed to perform masquerade with INVITE replaces\n");
18409    }
18410 
18411    if (earlyreplace || oneleggedreplace ) {
18412       c->hangupcause = AST_CAUSE_SWITCH_CONGESTION;
18413    }
18414 
18415    ast_setstate(c, AST_STATE_DOWN);
18416    ast_debug(4, "After transfer:----------------------------\n");
18417    ast_debug(4, " -- C:        %s State %s\n", c->name, ast_state2str(c->_state));
18418    if (replacecall)
18419       ast_debug(4, " -- replacecall:        %s State %s\n", replacecall->name, ast_state2str(replacecall->_state));
18420    if (p->owner) {
18421       ast_debug(4, " -- P->owner: %s State %s\n", p->owner->name, ast_state2str(p->owner->_state));
18422       test = ast_bridged_channel(p->owner);
18423       if (test)
18424          ast_debug(4, " -- Call bridged to P->owner: %s State %s\n", test->name, ast_state2str(test->_state));
18425       else
18426          ast_debug(4, " -- No call bridged to C->owner \n");
18427    } else 
18428       ast_debug(4, " -- No channel yet \n");
18429    ast_debug(4, "End After transfer:----------------------------\n");
18430 
18431    /* unlock sip pvt and owner so hangup can do its thing */
18432    ast_channel_unlock(replacecall);
18433    ast_channel_unlock(c);
18434    sip_pvt_unlock(p->refer->refer_call);
18435    sip_pvt_unlock(p);
18436    *nounlock = 1;
18437 
18438    /* The call should be down with no ast_channel, so hang it up */
18439    c->tech_pvt = dialog_unref(c->tech_pvt, "unref dialog c->tech_pvt");
18440    ast_hangup(c);
18441    sip_pvt_lock(p); /* lock PVT structure again after hangup */
18442 
18443    return 0;
18444 }
18445 
18446 /*! \brief helper routine for sip_uri_cmp
18447  *
18448  * This takes the parameters from two SIP URIs and determines
18449  * if the URIs match. The rules for parameters *suck*. Here's a breakdown
18450  * 1. If a parameter appears in both URIs, then they must have the same value
18451  *    in order for the URIs to match
18452  * 2. If one URI has a user, maddr, ttl, or method parameter, then the other
18453  *    URI must also have that parameter and must have the same value
18454  *    in order for the URIs to match
18455  * 3. All other headers appearing in only one URI are not considered when
18456  *    determining if URIs match
18457  *
18458  * \param input1 Parameters from URI 1
18459  * \param input2 Parameters from URI 2
18460  * \return Return 0 if the URIs' parameters match, 1 if they do not
18461  */
18462 static int sip_uri_params_cmp(const char *input1, const char *input2) 
18463 {
18464    char *params1 = NULL;
18465    char *params2 = NULL;
18466    char *pos1;
18467    char *pos2;
18468    int zerolength1 = 0;
18469    int zerolength2 = 0;
18470    int maddrmatch = 0;
18471    int ttlmatch = 0;
18472    int usermatch = 0;
18473    int methodmatch = 0;
18474 
18475    if (ast_strlen_zero(input1)) {
18476       zerolength1 = 1;
18477    } else {
18478       params1 = ast_strdupa(input1);
18479    }
18480    if (ast_strlen_zero(input2)) {
18481       zerolength2 = 1;
18482    } else {
18483       params2 = ast_strdupa(input2);
18484    }
18485 
18486    /*Quick optimization. If both params are zero-length, then
18487     * they match
18488     */
18489    if (zerolength1 && zerolength2) {
18490       return 0;
18491    }
18492 
18493    pos1 = params1;
18494    while (!ast_strlen_zero(pos1)) {
18495       char *name1 = pos1;
18496       char *value1 = strchr(pos1, '=');
18497       char *semicolon1 = strchr(pos1, ';');
18498       int matched = 0;
18499       if (semicolon1) {
18500          *semicolon1++ = '\0';
18501       }
18502       if (!value1) {
18503          goto fail;
18504       }
18505       *value1++ = '\0';
18506       /* Checkpoint reached. We have the name and value parsed for param1 
18507        * We have to duplicate params2 each time through the second loop
18508        * or else we can't search and replace the semicolons with \0 each
18509        * time
18510        */
18511       pos2 = ast_strdupa(params2);
18512       while (!ast_strlen_zero(pos2)) {
18513          char *name2 = pos2;
18514          char *value2 = strchr(pos2, '=');
18515          char *semicolon2 = strchr(pos2, ';');
18516          if (semicolon2) {
18517             *semicolon2++ = '\0';
18518          }
18519          if (!value2) {
18520             goto fail;
18521          }
18522          *value2++ = '\0';
18523          if (!strcasecmp(name1, name2)) {
18524             if (strcasecmp(value1, value2)) {
18525                goto fail;
18526             } else {
18527                matched = 1;
18528                break;
18529             }
18530          }
18531          pos2 = semicolon2;
18532       }
18533       /* Need to see if the parameter we're looking at is one of the 'must-match' parameters */
18534       if (!strcasecmp(name1, "maddr")) {
18535          if (matched) {
18536             maddrmatch = 1;
18537          } else {
18538             goto fail;
18539          }
18540       } else if (!strcasecmp(name1, "ttl")) {
18541          if (matched) {
18542             ttlmatch = 1;
18543          } else {
18544             goto fail;
18545          }
18546       } else if (!strcasecmp(name1, "user")) {
18547          if (matched) {
18548             usermatch = 1;
18549          } else {
18550             goto fail;
18551          }
18552       } else if (!strcasecmp(name1, "method")) {
18553          if (matched) {
18554             methodmatch = 1;
18555          } else {
18556             goto fail;
18557          }
18558       }
18559       pos1 = semicolon1;
18560    }
18561 
18562    /* We've made it out of that horrible O(m*n) construct and there are no
18563     * failures yet. We're not done yet, though, because params2 could have
18564     * an maddr, ttl, user, or method header and params1 did not.
18565     */
18566    pos2 = params2;
18567    while (!ast_strlen_zero(pos2)) {
18568       char *name2 = pos2;
18569       char *value2 = strchr(pos2, '=');
18570       char *semicolon2 = strchr(pos2, ';');
18571       if (semicolon2) {
18572          *semicolon2++ = '\0';
18573       }
18574       if (!value2) {
18575          goto fail;
18576       }
18577       *value2++ = '\0';
18578       if ((!strcasecmp(name2, "maddr") && !maddrmatch) ||
18579             (!strcasecmp(name2, "ttl") && !ttlmatch) ||
18580             (!strcasecmp(name2, "user") && !usermatch) ||
18581             (!strcasecmp(name2, "method") && !methodmatch)) {
18582          goto fail;
18583       }
18584    }
18585    return 0;
18586 
18587 fail:
18588    return 1;
18589 }
18590 
18591 /*! \brief helper routine for sip_uri_cmp
18592  *
18593  * This takes the "headers" from two SIP URIs and determines
18594  * if the URIs match. The rules for headers is simple. If a header
18595  * appears in one URI, then it must also appear in the other URI. The
18596  * order in which the headers appear does not matter.
18597  *
18598  * \param input1 Headers from URI 1
18599  * \param input2 Headers from URI 2
18600  * \return Return 0 if the URIs' headers match, 1 if they do not
18601  */
18602 static int sip_uri_headers_cmp(const char *input1, const char *input2)
18603 {
18604    char *headers1 = NULL;
18605    char *headers2 = NULL;
18606    int zerolength1 = 0;
18607    int zerolength2 = 0;
18608    int different = 0;
18609    char *header1;
18610 
18611    if (ast_strlen_zero(input1)) {
18612       zerolength1 = 1;
18613    } else {
18614       headers1 = ast_strdupa(input1);
18615    }
18616    
18617    if (ast_strlen_zero(input2)) {
18618       zerolength2 = 1;
18619    } else {
18620       headers2 = ast_strdupa(input2);
18621    }
18622 
18623    if ((zerolength1 && !zerolength2) ||
18624          (zerolength2 && !zerolength1))
18625       return 1;
18626 
18627    if (zerolength1 && zerolength2)
18628       return 0;
18629 
18630    /* At this point, we can definitively state that both inputs are
18631     * not zero-length. First, one more optimization. If the length
18632     * of the headers is not equal, then we definitely have no match
18633     */
18634    if (strlen(headers1) != strlen(headers2)) {
18635       return 1;
18636    }
18637 
18638    for (header1 = strsep(&headers1, "&"); header1; header1 = strsep(&headers1, "&")) {
18639       if (!strcasestr(headers2, header1)) {
18640          different = 1;
18641          break;
18642       }
18643    }
18644 
18645    return different;
18646 }
18647 
18648 static int sip_uri_cmp(const char *input1, const char *input2)
18649 {
18650    char *uri1 = ast_strdupa(input1);
18651    char *uri2 = ast_strdupa(input2);
18652    char *host1;
18653    char *host2;
18654    char *params1;
18655    char *params2;
18656    char *headers1;
18657    char *headers2;
18658 
18659    /* Strip off "sip:" from the URI. We know this is present
18660     * because it was checked back in parse_request()
18661     */
18662    strsep(&uri1, ":");
18663    strsep(&uri2, ":");
18664 
18665    if ((host1 = strchr(uri1, '@'))) {
18666       *host1++ = '\0';
18667    }
18668    if ((host2 = strchr(uri2, '@'))) {
18669       *host2++ = '\0';
18670    }
18671 
18672    /* Check for mismatched username and passwords. This is the
18673     * only case-sensitive comparison of a SIP URI
18674     */
18675    if ((host1 && !host2) ||
18676          (host2 && !host1) ||
18677          (host1 && host2 && strcmp(uri1, uri2))) {
18678       return 1;
18679    }
18680 
18681    if (!host1)
18682       host1 = uri1;
18683    if (!host2)
18684       host2 = uri2;
18685 
18686    /* Strip off the parameters and headers so we can compare
18687     * host and port
18688     */
18689 
18690    if ((params1 = strchr(host1, ';'))) {
18691       *params1++ = '\0';
18692    }
18693    if ((params2 = strchr(host2, ';'))) {
18694       *params2++ = '\0';
18695    }
18696 
18697    /* Headers come after parameters, but there may be headers without
18698     * parameters, thus the S_OR
18699     */
18700    if ((headers1 = strchr(S_OR(params1, host1), '?'))) {
18701       *headers1++ = '\0';
18702    }
18703    if ((headers2 = strchr(S_OR(params2, host2), '?'))) {
18704       *headers2++ = '\0';
18705    }
18706 
18707    /* Now the host/port are properly isolated. We can get by with a string comparison
18708     * because the SIP URI checking rules have some interesting exceptions that make
18709     * this possible. I will note 2 in particular
18710     * 1. hostnames which resolve to the same IP address as well as a hostname and its
18711     *    IP address are not considered a match with SIP URI's.
18712     * 2. If one URI specifies a port and the other does not, then the URIs do not match.
18713     *    This includes if one URI explicitly contains port 5060 and the other implies it
18714     *    by not having a port specified.
18715     */
18716 
18717    if (strcasecmp(host1, host2)) {
18718       return 1;
18719    }
18720 
18721    /* Headers have easier rules to follow, so do those first */
18722    if (sip_uri_headers_cmp(headers1, headers2)) {
18723       return 1;
18724    }
18725 
18726    /* And now the parameters. Ugh */
18727    return sip_uri_params_cmp(params1, params2);
18728 }
18729 
18730 
18731 static int sip_t38_abort(const void *data)
18732 {
18733    struct sip_pvt *p = (struct sip_pvt *) data;
18734 
18735    change_t38_state(p, T38_DISABLED);
18736    transmit_response_reliable(p, "488 Not acceptable here", &p->initreq);
18737    p->t38id = -1;
18738    dialog_unref(p, "unref the dialog ptr from sip_t38_abort, because it held a dialog ptr");
18739 
18740    return 0;
18741 }
18742 
18743 /*! \brief Handle incoming INVITE request
18744 \note    If the INVITE has a Replaces header, it is part of an
18745  * attended transfer. If so, we do not go through the dial
18746  * plan but tries to find the active call and masquerade
18747  * into it 
18748  */
18749 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)
18750 {
18751    int res = 1;
18752    int gotdest;
18753    const char *p_replaces;
18754    char *replace_id = NULL;
18755    const char *required;
18756    unsigned int required_profile = 0;
18757    struct ast_channel *c = NULL;    /* New channel */
18758    int reinvite = 0;
18759    int rtn;
18760 
18761    const char *p_uac_se_hdr;       /* UAC's Session-Expires header string                      */
18762    const char *p_uac_min_se;       /* UAC's requested Min-SE interval (char string)            */
18763    int uac_max_se = -1;            /* UAC's Session-Expires in integer format                  */
18764    int uac_min_se = -1;            /* UAC's Min-SE in integer format                           */
18765    int st_active = FALSE;          /* Session-Timer on/off boolean                             */
18766    int st_interval = 0;            /* Session-Timer negotiated refresh interval                */
18767    enum st_refresher st_ref;       /* Session-Timer session refresher                          */
18768    int dlg_min_se = -1;
18769    st_ref = SESSION_TIMER_REFRESHER_AUTO;
18770 
18771    /* Find out what they support */
18772    if (!p->sipoptions) {
18773       const char *supported = get_header(req, "Supported");
18774       if (!ast_strlen_zero(supported))
18775          parse_sip_options(p, supported);
18776    }
18777 
18778    /* Find out what they require */
18779    required = get_header(req, "Require");
18780    if (!ast_strlen_zero(required)) {
18781       required_profile = parse_sip_options(NULL, required);
18782       if (required_profile && !(required_profile & (SIP_OPT_REPLACES | SIP_OPT_TIMER))) {
18783          /* At this point we only support REPLACES and Session-Timer */
18784          transmit_response_with_unsupported(p, "420 Bad extension (unsupported)", req, required);
18785          ast_log(LOG_WARNING, "Received SIP INVITE with unsupported required extension: %s\n", required);
18786          p->invitestate = INV_COMPLETED;
18787          if (!p->lastinvite)
18788             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18789          return -1;
18790       }
18791    }
18792 
18793    /* The option tags may be present in Supported: or Require: headers.
18794    Include the Require: option tags for further processing as well */
18795    p->sipoptions |= required_profile;
18796    p->reqsipoptions = required_profile;
18797 
18798    /* Check if this is a loop */
18799    if (ast_test_flag(&p->flags[0], SIP_OUTGOING) && p->owner && (p->invitestate != INV_TERMINATED && p->invitestate != INV_CONFIRMED)) {
18800       /* This is a call to ourself.  Send ourselves an error code and stop
18801          processing immediately, as SIP really has no good mechanism for
18802          being able to call yourself */
18803       /* If pedantic is on, we need to check the tags. If they're different, this is
18804          in fact a forked call through a SIP proxy somewhere. */
18805       int different;
18806       char *initial_rlPart2 = REQ_OFFSET_TO_STR(&p->initreq, rlPart2);
18807       char *this_rlPart2 = REQ_OFFSET_TO_STR(req, rlPart2);
18808       if (pedanticsipchecking)
18809          different = sip_uri_cmp(initial_rlPart2, this_rlPart2);
18810       else
18811          different = strcmp(initial_rlPart2, this_rlPart2);
18812       if (!different) {
18813          transmit_response(p, "482 Loop Detected", req);
18814          p->invitestate = INV_COMPLETED;
18815          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18816          return 0;
18817       } else {
18818          /*! This is a spiral. What we need to do is to just change the outgoing INVITE
18819           * so that it now routes to the new Request URI. Since we created the INVITE ourselves
18820           * that should be all we need to do.
18821           * 
18822           * \todo XXX This needs to be reviewed.  YOu don't change the request URI really, you route the packet
18823           * correctly instead...
18824           */
18825          char *uri = ast_strdupa(this_rlPart2);
18826          char *at = strchr(uri, '@');
18827          char *peerorhost;
18828          ast_debug(2, "Potential spiral detected. Original RURI was %s, new RURI is %s\n", initial_rlPart2, this_rlPart2);
18829          transmit_response(p, "100 Trying", req);
18830          if (at) {
18831             *at = '\0';
18832          }
18833          /* Parse out "sip:" */
18834          if ((peerorhost = strchr(uri, ':'))) {
18835             *peerorhost++ = '\0';
18836          }
18837          ast_string_field_set(p, theirtag, NULL);
18838          /* Treat this as if there were a call forward instead...
18839           */
18840          ast_string_field_set(p->owner, call_forward, peerorhost);
18841          ast_queue_control(p->owner, AST_CONTROL_BUSY);
18842          return 0;
18843       }
18844    }
18845 
18846    if (!req->ignore && p->pendinginvite) {
18847       if (!ast_test_flag(&p->flags[0], SIP_OUTGOING) && (p->invitestate == INV_COMPLETED || p->invitestate == INV_TERMINATED)) {
18848          /* What do these circumstances mean? We have received an INVITE for an "incoming" dialog for which we
18849           * have sent a final response. We have not yet received an ACK, though (which is why p->pendinginvite is non-zero).
18850           * We also know that the INVITE is not a retransmission, because otherwise the "ignore" flag would be set.
18851           * This means that either we are receiving a reinvite for a terminated dialog, or we are receiving an INVITE with
18852           * credentials based on one we challenged earlier.
18853           *
18854           * The action to take in either case is to treat the INVITE as though it contains an implicit ACK for the previous
18855           * transaction. Calling __sip_ack will take care of this by clearing the p->pendinginvite and removing the response
18856           * from the previous transaction from the list of outstanding packets.
18857           */
18858          __sip_ack(p, p->pendinginvite, 1, 0);
18859       } else {
18860          /* We already have a pending invite. Sorry. You are on hold. */
18861          p->glareinvite = seqno;
18862          if (p->rtp && find_sdp(req)) {
18863             struct sockaddr_in sin;
18864             if (get_ip_and_port_from_sdp(req, SDP_AUDIO, &sin)) {
18865                ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Audio may not work properly on this call.\n");
18866             } else {
18867                ast_rtp_set_alt_peer(p->rtp, &sin);
18868             }
18869             if (p->vrtp) {
18870                if (get_ip_and_port_from_sdp(req, SDP_VIDEO, &sin)) {
18871                   ast_log(LOG_WARNING, "Failed to set an alternate media source on glared reinvite. Video may not work properly on this call.\n");
18872                } else {
18873                   ast_rtp_set_alt_peer(p->vrtp, &sin);
18874                }
18875             }
18876          }
18877          transmit_response_reliable(p, "491 Request Pending", req);
18878          ast_debug(1, "Got INVITE on call where we already have pending INVITE, deferring that - %s\n", p->callid);
18879          /* Don't destroy dialog here */
18880          return 0;
18881       }
18882    }
18883 
18884    p_replaces = get_header(req, "Replaces");
18885    if (!ast_strlen_zero(p_replaces)) {
18886       /* We have a replaces header */
18887       char *ptr;
18888       char *fromtag = NULL;
18889       char *totag = NULL;
18890       char *start, *to;
18891       int error = 0;
18892 
18893       if (p->owner) {
18894          ast_debug(3, "INVITE w Replaces on existing call? Refusing action. [%s]\n", p->callid);
18895          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
18896          /* Do not destroy existing call */
18897          return -1;
18898       }
18899 
18900       if (sipdebug)
18901          ast_debug(3, "INVITE part of call transfer. Replaces [%s]\n", p_replaces);
18902       /* Create a buffer we can manipulate */
18903       replace_id = ast_strdupa(p_replaces);
18904       ast_uri_decode(replace_id);
18905 
18906       if (!p->refer && !sip_refer_allocate(p)) {
18907          transmit_response_reliable(p, "500 Server Internal Error", req);
18908          append_history(p, "Xfer", "INVITE/Replace Failed. Out of memory.");
18909          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18910          p->invitestate = INV_COMPLETED;
18911          return -1;
18912       }
18913 
18914       /*  Todo: (When we find phones that support this)
18915          if the replaces header contains ";early-only"
18916          we can only replace the call in early
18917          stage, not after it's up.
18918 
18919          If it's not in early mode, 486 Busy.
18920       */
18921       
18922       /* Skip leading whitespace */
18923       replace_id = ast_skip_blanks(replace_id);
18924 
18925       start = replace_id;
18926       while ( (ptr = strsep(&start, ";")) ) {
18927          ptr = ast_skip_blanks(ptr); /* XXX maybe unnecessary ? */
18928          if ( (to = strcasestr(ptr, "to-tag=") ) )
18929             totag = to + 7;   /* skip the keyword */
18930          else if ( (to = strcasestr(ptr, "from-tag=") ) ) {
18931             fromtag = to + 9; /* skip the keyword */
18932             fromtag = strsep(&fromtag, "&"); /* trim what ? */
18933          }
18934       }
18935 
18936       if (sipdebug) 
18937          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>");
18938 
18939 
18940       /* Try to find call that we are replacing 
18941          If we have a Replaces  header, we need to cancel that call if we succeed with this call 
18942       */
18943       if ((p->refer->refer_call = get_sip_pvt_byid_locked(replace_id, totag, fromtag)) == NULL) {
18944          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existent call id (%s)!\n", replace_id);
18945          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replaces)", req);
18946          error = 1;
18947       }
18948 
18949       /* At this point, bot the pvt and the owner of the call to be replaced is locked */
18950 
18951       /* The matched call is the call from the transferer to Asterisk .
18952          We want to bridge the bridged part of the call to the 
18953          incoming invite, thus taking over the refered call */
18954 
18955       if (p->refer->refer_call == p) {
18956          ast_log(LOG_NOTICE, "INVITE with replaces into it's own call id (%s == %s)!\n", replace_id, p->callid);
18957          p->refer->refer_call = dialog_unref(p->refer->refer_call, "unref dialog p->refer->refer_call");
18958          transmit_response_reliable(p, "400 Bad request", req);   /* The best way to not not accept the transfer */
18959          error = 1;
18960       }
18961 
18962       if (!error && !p->refer->refer_call->owner) {
18963          /* Oops, someting wrong anyway, no owner, no call */
18964          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-existing call id (%s)!\n", replace_id);
18965          /* Check for better return code */
18966          transmit_response_reliable(p, "481 Call Leg Does Not Exist (Replace)", req);
18967          error = 1;
18968       }
18969 
18970       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 ) {
18971          ast_log(LOG_NOTICE, "Supervised transfer attempted to replace non-ringing or active call id (%s)!\n", replace_id);
18972          transmit_response_reliable(p, "603 Declined (Replaces)", req);
18973          error = 1;
18974       }
18975 
18976       if (error) {   /* Give up this dialog */
18977          append_history(p, "Xfer", "INVITE/Replace Failed.");
18978          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
18979          sip_pvt_unlock(p);
18980          if (p->refer->refer_call) {
18981             sip_pvt_unlock(p->refer->refer_call);
18982             if (p->refer->refer_call->owner) {
18983                ast_channel_unlock(p->refer->refer_call->owner);
18984             }
18985          }
18986          p->invitestate = INV_COMPLETED;
18987          return -1;
18988       }
18989    }
18990 
18991    /* Check if this is an INVITE that sets up a new dialog or
18992       a re-invite in an existing dialog */
18993 
18994    if (!req->ignore) {
18995       int newcall = (p->initreq.headers ? TRUE : FALSE);
18996 
18997       if (sip_cancel_destroy(p))
18998          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
18999       /* This also counts as a pending invite */
19000       p->pendinginvite = seqno;
19001       check_via(p, req);
19002 
19003       copy_request(&p->initreq, req);     /* Save this INVITE as the transaction basis */
19004       if (sipdebug)
19005          ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
19006       if (!p->owner) {  /* Not a re-invite */
19007          if (debug)
19008             ast_verbose("Using INVITE request as basis request - %s\n", p->callid);
19009          if (newcall)
19010             append_history(p, "Invite", "New call: %s", p->callid);
19011          parse_ok_contact(p, req);
19012       } else { /* Re-invite on existing call */
19013          ast_clear_flag(&p->flags[0], SIP_OUTGOING);  /* This is now an inbound dialog */
19014          /* Handle SDP here if we already have an owner */
19015          if (find_sdp(req)) {
19016             if (process_sdp(p, req, SDP_T38_INITIATE)) {
19017                transmit_response_reliable(p, "488 Not acceptable here", req);
19018                if (!p->lastinvite)
19019                   sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19020                return -1;
19021             }
19022             ast_queue_control(p->owner, AST_CONTROL_SRCUPDATE);
19023          } else {
19024             p->jointcapability = p->capability;
19025             ast_debug(1, "Hm....  No sdp for the moment\n");
19026          }
19027          if (p->do_history) /* This is a response, note what it was for */
19028             append_history(p, "ReInv", "Re-invite received");
19029       }
19030    } else if (debug)
19031       ast_verbose("Ignoring this INVITE request\n");
19032 
19033    
19034    if (!p->lastinvite && !req->ignore && !p->owner) {
19035       /* This is a new invite */
19036       /* Handle authentication if this is our first invite */
19037       res = check_user(p, req, SIP_INVITE, e, XMIT_RELIABLE, sin);
19038       if (res == AUTH_CHALLENGE_SENT) {
19039          p->invitestate = INV_COMPLETED;     /* Needs to restart in another INVITE transaction */
19040          return 0;
19041       }
19042       if (res < 0) { /* Something failed in authentication */
19043          if (res == AUTH_FAKE_AUTH) {
19044             ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
19045             transmit_fake_auth_response(p, SIP_INVITE, req, XMIT_RELIABLE);
19046          } else {
19047             ast_log(LOG_NOTICE, "Failed to authenticate device %s\n", get_header(req, "From"));
19048             transmit_response_reliable(p, "403 Forbidden", req);
19049          }
19050          p->invitestate = INV_COMPLETED;  
19051          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19052          ast_string_field_set(p, theirtag, NULL);
19053          return 0;
19054       }
19055 
19056       /* If T38 is needed but not present, then make it magically appear */
19057       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))) {
19058          p->t38_maxdatagram = global_t38_maxdatagram;
19059          set_t38_capabilities(p);
19060       }
19061 
19062       /* We have a succesful authentication, process the SDP portion if there is one */
19063       if (find_sdp(req)) {
19064          if (process_sdp(p, req, SDP_T38_INITIATE)) {
19065             /* Unacceptable codecs */
19066             transmit_response_reliable(p, "488 Not acceptable here", req);
19067             p->invitestate = INV_COMPLETED;  
19068             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19069             ast_debug(1, "No compatible codecs for this SIP call.\n");
19070             return -1;
19071          }
19072          if (ast_test_flag(&p->flags[1], SIP_PAGE2_CONSTANT_SSRC)) {
19073             if (p->rtp) {
19074                ast_rtp_set_constantssrc(p->rtp);
19075             }
19076             if (p->vrtp) {
19077                ast_rtp_set_constantssrc(p->vrtp);
19078             }
19079          }
19080       } else { /* No SDP in invite, call control session */
19081          p->jointcapability = p->capability;
19082          ast_debug(2, "No SDP in Invite, third party call control\n");
19083       }
19084 
19085       /* Queue NULL frame to prod ast_rtp_bridge if appropriate */
19086       /* This seems redundant ... see !p-owner above */
19087       if (p->owner)
19088          ast_queue_frame(p->owner, &ast_null_frame);
19089 
19090 
19091       /* Initialize the context if it hasn't been already */
19092       if (ast_strlen_zero(p->context))
19093          ast_string_field_set(p, context, default_context);
19094 
19095 
19096       /* Check number of concurrent calls -vs- incoming limit HERE */
19097       ast_debug(1, "Checking SIP call limits for device %s\n", p->username);
19098       if ((res = update_call_counter(p, INC_CALL_LIMIT))) {
19099          if (res < 0) {
19100             ast_log(LOG_NOTICE, "Failed to place call for device %s, too many calls\n", p->username);
19101             transmit_response_reliable(p, "480 Temporarily Unavailable (Call limit) ", req);
19102             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19103             p->invitestate = INV_COMPLETED;  
19104          }
19105          return 0;
19106       }
19107       gotdest = get_destination(p, NULL); /* Get destination right away */
19108       get_rdnis(p, NULL);        /* Get redirect information */
19109       extract_uri(p, req);       /* Get the Contact URI */
19110       build_contact(p);       /* Build our contact header */
19111 
19112       if (p->rtp) {
19113          ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
19114          ast_rtp_setdtmfcompensate(p->rtp, ast_test_flag(&p->flags[1], SIP_PAGE2_RFC2833_COMPENSATE));
19115       }
19116 
19117       if (!replace_id && gotdest) { /* No matching extension found */
19118          if (gotdest == 1 && ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWOVERLAP))
19119             transmit_response_reliable(p, "484 Address Incomplete", req);
19120          else {
19121             char *decoded_exten = ast_strdupa(p->exten);
19122             
19123             transmit_response_reliable(p, "404 Not Found", req);
19124             ast_uri_decode(decoded_exten);
19125             ast_log(LOG_NOTICE, "Call from '%s' to extension"
19126                " '%s' rejected because extension not found.\n",
19127                S_OR(p->username, p->peername), decoded_exten);
19128          }
19129          p->invitestate = INV_COMPLETED;  
19130          update_call_counter(p, DEC_CALL_LIMIT);
19131          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19132          return 0;
19133       } else {
19134 
19135          /* If no extension was specified, use the s one */
19136          /* Basically for calling to IP/Host name only */
19137          if (ast_strlen_zero(p->exten))
19138             ast_string_field_set(p, exten, "s");
19139          /* Initialize our tag */   
19140 
19141          make_our_tag(p->tag, sizeof(p->tag));
19142          /* First invitation - create the channel */
19143          c = sip_new(p, AST_STATE_DOWN, S_OR(p->peername, NULL));
19144          *recount = 1;
19145 
19146          /* Save Record-Route for any later requests we make on this dialogue */
19147          build_route(p, req, 0);
19148 
19149          if (c) {
19150             /* Pre-lock the call */
19151             ast_channel_lock(c);
19152          }
19153       }
19154    } else {
19155       if (sipdebug) {
19156          if (!req->ignore)
19157             ast_debug(2, "Got a SIP re-invite for call %s\n", p->callid);
19158          else
19159             ast_debug(2, "Got a SIP re-transmit of INVITE for call %s\n", p->callid);
19160       }
19161       if (!req->ignore)
19162          reinvite = 1;
19163       c = p->owner;
19164    }
19165 
19166    /* Session-Timers */
19167    if (p->sipoptions & SIP_OPT_TIMER) {
19168       /* The UAC has requested session-timers for this session. Negotiate
19169       the session refresh interval and who will be the refresher */
19170       ast_debug(2, "Incoming INVITE with 'timer' option enabled\n");
19171 
19172       /* Allocate Session-Timers struct w/in the dialog */
19173       if (!p->stimer)
19174          sip_st_alloc(p);
19175 
19176       /* Parse the Session-Expires header */
19177       p_uac_se_hdr = get_header(req, "Session-Expires");
19178       if (!ast_strlen_zero(p_uac_se_hdr)) {
19179          rtn = parse_session_expires(p_uac_se_hdr, &uac_max_se, &st_ref);
19180          if (rtn != 0) {
19181             transmit_response_reliable(p, "400 Session-Expires Invalid Syntax", req);
19182             p->invitestate = INV_COMPLETED;
19183             if (!p->lastinvite) {
19184                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19185             }
19186             return -1;
19187          }
19188       }
19189 
19190       /* Parse the Min-SE header */
19191       p_uac_min_se = get_header(req, "Min-SE");
19192       if (!ast_strlen_zero(p_uac_min_se)) {
19193          rtn = parse_minse(p_uac_min_se, &uac_min_se); 
19194          if (rtn != 0) {
19195                transmit_response_reliable(p, "400 Min-SE Invalid Syntax", req);
19196                      p->invitestate = INV_COMPLETED;
19197                      if (!p->lastinvite) {
19198                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19199             }
19200             return -1;
19201          }
19202       }
19203 
19204       dlg_min_se = st_get_se(p, FALSE);
19205       switch (st_get_mode(p)) {
19206       case SESSION_TIMER_MODE_ACCEPT:
19207       case SESSION_TIMER_MODE_ORIGINATE:
19208          if (uac_max_se > 0 && uac_max_se < dlg_min_se) {
19209             transmit_response_with_minse(p, "422 Session Interval Too Small", req, dlg_min_se);
19210             p->invitestate = INV_COMPLETED;
19211             if (!p->lastinvite) {
19212                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19213             }
19214             return -1;
19215          }
19216 
19217          p->stimer->st_active_peer_ua = TRUE;
19218          st_active = TRUE;
19219          if (st_ref == SESSION_TIMER_REFRESHER_AUTO) {
19220             st_ref = st_get_refresher(p);
19221          }
19222 
19223          if (uac_max_se > 0) {
19224             int dlg_max_se = st_get_se(p, TRUE);
19225             if (dlg_max_se >= uac_min_se) {
19226                st_interval = (uac_max_se < dlg_max_se) ? uac_max_se : dlg_max_se;
19227             } else {
19228                st_interval = uac_max_se;
19229             }
19230          } else {
19231             /* Set to default max value */
19232             st_interval = global_max_se;
19233          }
19234          break;
19235 
19236       case SESSION_TIMER_MODE_REFUSE:
19237          if (p->reqsipoptions & SIP_OPT_TIMER) {
19238             transmit_response_with_unsupported(p, "420 Option Disabled", req, required);
19239             ast_log(LOG_WARNING, "Received SIP INVITE with supported but disabled option: %s\n", required);
19240             p->invitestate = INV_COMPLETED;
19241             if (!p->lastinvite) {
19242                sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19243             }
19244             return -1;
19245          }
19246          break;
19247 
19248       default:
19249          ast_log(LOG_ERROR, "Internal Error %d at %s:%d\n", st_get_mode(p), __FILE__, __LINE__);
19250          break;
19251       }
19252    } else {
19253       /* The UAC did not request session-timers.  Asterisk (UAS), will now decide
19254       (based on session-timer-mode in sip.conf) whether to run session-timers for
19255       this session or not. */
19256       switch (st_get_mode(p)) {
19257       case SESSION_TIMER_MODE_ORIGINATE:
19258          st_active = TRUE;
19259          st_interval = st_get_se(p, TRUE);
19260          st_ref = SESSION_TIMER_REFRESHER_UAS;
19261          p->stimer->st_active_peer_ua = FALSE;
19262          break;
19263 
19264       default:
19265          break;
19266       }
19267    }
19268 
19269    if (reinvite == 0) {
19270       /* Session-Timers: Start session refresh timer based on negotiation/config */
19271       if (st_active == TRUE) {
19272          p->stimer->st_active   = TRUE;
19273          p->stimer->st_interval = st_interval;
19274          p->stimer->st_ref      = st_ref;
19275          start_session_timer(p);
19276       }
19277    } else {
19278       if (p->stimer->st_active == TRUE) {
19279          /* Session-Timers:  A re-invite request sent within a dialog will serve as 
19280          a refresh request, no matter whether the re-invite was sent for refreshing 
19281          the session or modifying it.*/
19282          ast_debug (2, "Restarting session-timers on a refresh - %s\n", p->callid);
19283 
19284          /* The UAC may be adjusting the session-timers mid-session */
19285          if (st_interval > 0) {
19286             p->stimer->st_interval = st_interval;
19287             p->stimer->st_ref      = st_ref;
19288          }
19289 
19290          restart_session_timer(p);
19291          if (p->stimer->st_expirys > 0) {
19292             p->stimer->st_expirys--;
19293          }
19294       }
19295    }
19296 
19297    if (!req->ignore && p)
19298       p->lastinvite = seqno;
19299 
19300    if (replace_id) {    /* Attended transfer or call pickup - we're the target */
19301       /* Go and take over the target call */
19302       if (sipdebug)
19303          ast_debug(4, "Sending this call to the invite/replcaes handler %s\n", p->callid);
19304       return handle_invite_replaces(p, req, debug, seqno, sin, nounlock);
19305    }
19306 
19307 
19308    if (c) { /* We have a call  -either a new call or an old one (RE-INVITE) */
19309       enum ast_channel_state c_state = c->_state;
19310 
19311       if (c_state != AST_STATE_UP && reinvite &&
19312          (p->invitestate == INV_TERMINATED || p->invitestate == INV_CONFIRMED)) {
19313          /* If these conditions are true, and the channel is still in the 'ringing'
19314           * state, then this likely means that we have a situation where the initial
19315           * INVITE transaction has completed *but* the channel's state has not yet been
19316           * changed to UP. The reason this could happen is if the reinvite is received
19317           * on the SIP socket prior to an application calling ast_read on this channel
19318           * to read the answer frame we earlier queued on it. In this case, the reinvite
19319           * is completely legitimate so we need to handle this the same as if the channel 
19320           * were already UP. Thus we are purposely falling through to the AST_STATE_UP case.
19321           */
19322          c_state = AST_STATE_UP;
19323       }
19324 
19325       switch(c_state) {
19326       case AST_STATE_DOWN:
19327          ast_debug(2, "%s: New call is still down.... Trying... \n", c->name);
19328          transmit_provisional_response(p, "100 Trying", req, 0);
19329          p->invitestate = INV_PROCEEDING;
19330          ast_setstate(c, AST_STATE_RING);
19331          if (strcmp(p->exten, ast_pickup_ext())) { /* Call to extension -start pbx on this call */
19332             enum ast_pbx_result result;
19333 
19334             result = ast_pbx_start(c);
19335 
19336             switch(result) {
19337             case AST_PBX_FAILED:
19338                ast_log(LOG_WARNING, "Failed to start PBX :(\n");
19339                p->invitestate = INV_COMPLETED;
19340                transmit_response_reliable(p, "503 Unavailable", req);
19341                break;
19342             case AST_PBX_CALL_LIMIT:
19343                ast_log(LOG_WARNING, "Failed to start PBX (call limit reached) \n");
19344                p->invitestate = INV_COMPLETED;
19345                transmit_response_reliable(p, "480 Temporarily Unavailable", req);
19346                break;
19347             case AST_PBX_SUCCESS:
19348                /* nothing to do */
19349                break;
19350             }
19351 
19352             if (result) {
19353 
19354                /* Unlock locks so ast_hangup can do its magic */
19355                ast_channel_unlock(c);
19356                sip_pvt_unlock(p);
19357                ast_hangup(c);
19358                sip_pvt_lock(p);
19359                c = NULL;
19360             }
19361          } else { /* Pickup call in call group */
19362             ast_channel_unlock(c);
19363             *nounlock = 1;
19364             if (ast_pickup_call(c)) {
19365                ast_log(LOG_NOTICE, "Nothing to pick up for %s\n", p->callid);
19366                transmit_response_reliable(p, "503 Unavailable", req);
19367                sip_alreadygone(p);
19368                /* Unlock locks so ast_hangup can do its magic */
19369                sip_pvt_unlock(p);
19370                c->hangupcause = AST_CAUSE_CALL_REJECTED;
19371             } else {
19372                sip_pvt_unlock(p);
19373                ast_setstate(c, AST_STATE_DOWN);
19374                c->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19375             }
19376             p->invitestate = INV_COMPLETED;
19377             ast_hangup(c);
19378             sip_pvt_lock(p);
19379             c = NULL;
19380          }
19381          break;
19382       case AST_STATE_RING:
19383          transmit_provisional_response(p, "100 Trying", req, 0);
19384          p->invitestate = INV_PROCEEDING;
19385          break;
19386       case AST_STATE_RINGING:
19387          transmit_provisional_response(p, "180 Ringing", req, 0);
19388          p->invitestate = INV_PROCEEDING;
19389          break;
19390       case AST_STATE_UP:
19391          ast_debug(2, "%s: This call is UP.... \n", c->name);
19392 
19393          transmit_response(p, "100 Trying", req);
19394 
19395          if (p->t38.state == T38_PEER_REINVITE) {
19396             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."));
19397          } else if (p->t38.state == T38_ENABLED) {
19398             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19399             transmit_response_with_t38_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)));
19400          } else if (p->t38.state == T38_DISABLED) {
19401             /* If this is not a re-invite or something to ignore - it's critical */
19402             ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
19403             transmit_response_with_sdp(p, "200 OK", req, (reinvite ? XMIT_RELIABLE : (req->ignore ?  XMIT_UNRELIABLE : XMIT_CRITICAL)), p->session_modify == TRUE ? FALSE:TRUE); 
19404          }
19405 
19406          p->invitestate = INV_TERMINATED;
19407          break;
19408       default:
19409          ast_log(LOG_WARNING, "Don't know how to handle INVITE in state %d\n", c->_state);
19410          transmit_response(p, "100 Trying", req);
19411          break;
19412       }
19413    } else {
19414       if (p && (p->autokillid == -1)) {
19415          const char *msg;
19416 
19417          if (!p->jointcapability)
19418             msg = "488 Not Acceptable Here (codec error)";
19419          else {
19420             ast_log(LOG_NOTICE, "Unable to create/find SIP channel for this INVITE\n");
19421             msg = "503 Unavailable";
19422          }
19423          transmit_response_reliable(p, msg, req);
19424          p->invitestate = INV_COMPLETED;
19425          sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19426       }
19427    }
19428    return res;
19429 }
19430 
19431 /*! \brief  Find all call legs and bridge transferee with target 
19432  * called from handle_request_refer */
19433 static int local_attended_transfer(struct sip_pvt *transferer, struct sip_dual *current, struct sip_request *req, int seqno)
19434 {
19435    struct sip_dual target;    /* Chan 1: Call from tranferer to Asterisk */
19436                /* Chan 2: Call from Asterisk to target */
19437    int res = 0;
19438    struct sip_pvt *targetcall_pvt;
19439 
19440    /* Check if the call ID of the replaces header does exist locally */
19441    if (!(targetcall_pvt = get_sip_pvt_byid_locked(transferer->refer->replaces_callid, transferer->refer->replaces_callid_totag, 
19442       transferer->refer->replaces_callid_fromtag))) {
19443       if (transferer->refer->localtransfer) {
19444          /* We did not find the refered call. Sorry, can't accept then */
19445          transmit_response(transferer, "202 Accepted", req);
19446          /* Let's fake a response from someone else in order
19447             to follow the standard */
19448          transmit_notify_with_sipfrag(transferer, seqno, "481 Call leg/transaction does not exist", TRUE);
19449          append_history(transferer, "Xfer", "Refer failed");
19450          ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);  
19451          transferer->refer->status = REFER_FAILED;
19452          return -1;
19453       }
19454       /* Fall through for remote transfers that we did not find locally */
19455       ast_debug(3, "SIP attended transfer: Not our call - generating INVITE with replaces\n");
19456       return 0;
19457    }
19458 
19459    /* Ok, we can accept this transfer */
19460    transmit_response(transferer, "202 Accepted", req);
19461    append_history(transferer, "Xfer", "Refer accepted");
19462    if (!targetcall_pvt->owner) { /* No active channel */
19463       ast_debug(4, "SIP attended transfer: Error: No owner of target call\n");
19464       /* Cancel transfer */
19465       transmit_notify_with_sipfrag(transferer, seqno, "503 Service Unavailable", TRUE);
19466       append_history(transferer, "Xfer", "Refer failed");
19467       ast_clear_flag(&transferer->flags[0], SIP_GOTREFER);
19468       transferer->refer->status = REFER_FAILED;
19469       sip_pvt_unlock(targetcall_pvt);
19470       if (targetcall_pvt)
19471          ao2_t_ref(targetcall_pvt, -1, "Drop targetcall_pvt pointer");
19472       return -1;
19473    }
19474 
19475    /* We have a channel, find the bridge */
19476    target.chan1 = targetcall_pvt->owner;           /* Transferer to Asterisk */
19477    target.chan2 = ast_bridged_channel(targetcall_pvt->owner);  /* Asterisk to target */
19478 
19479    if (!target.chan2 || !(target.chan2->_state == AST_STATE_UP || target.chan2->_state == AST_STATE_RINGING) ) {
19480       /* Wrong state of new channel */
19481       if (target.chan2) 
19482          ast_debug(4, "SIP attended transfer: Error: Wrong state of target call: %s\n", ast_state2str(target.chan2->_state));
19483       else if (target.chan1->_state != AST_STATE_RING)
19484          ast_debug(4, "SIP attended transfer: Error: No target channel\n");
19485       else
19486          ast_debug(4, "SIP attended transfer: Attempting transfer in ringing state\n");
19487    }
19488 
19489    /* Transfer */
19490    if (sipdebug) {
19491       if (current->chan2)  /* We have two bridges */
19492          ast_debug(4, "SIP attended transfer: trying to bridge %s and %s\n", target.chan1->name, current->chan2->name);
19493       else        /* One bridge, propably transfer of IVR/voicemail etc */
19494          ast_debug(4, "SIP attended transfer: trying to make %s take over (masq) %s\n", target.chan1->name, current->chan1->name);
19495    }
19496 
19497    ast_set_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
19498 
19499    /* Perform the transfer */
19500    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",
19501       transferer->owner->name,
19502       transferer->owner->uniqueid,
19503       transferer->callid,
19504       target.chan1->name,
19505       target.chan1->uniqueid);
19506    res = attempt_transfer(current, &target);
19507    sip_pvt_unlock(targetcall_pvt);
19508    if (res) {
19509       /* Failed transfer */
19510       transmit_notify_with_sipfrag(transferer, seqno, "486 Busy Here", TRUE);
19511       append_history(transferer, "Xfer", "Refer failed");
19512       if (targetcall_pvt->owner)
19513          ast_channel_unlock(targetcall_pvt->owner);
19514       ast_clear_flag(&transferer->flags[0], SIP_DEFER_BYE_ON_TRANSFER);
19515    } else {
19516       /* Transfer succeeded! */
19517 
19518       /* Tell transferer that we're done. */
19519       transmit_notify_with_sipfrag(transferer, seqno, "200 OK", TRUE);
19520       append_history(transferer, "Xfer", "Refer succeeded");
19521       transferer->refer->status = REFER_200OK;
19522       if (targetcall_pvt->owner) {
19523          ast_debug(1, "SIP attended transfer: Unlocking channel %s\n", targetcall_pvt->owner->name);
19524          ast_channel_unlock(targetcall_pvt->owner);
19525       }
19526    }
19527    if (targetcall_pvt)
19528       ao2_t_ref(targetcall_pvt, -1, "drop targetcall_pvt");
19529    return 1;
19530 }
19531 
19532 
19533 /*! \brief Handle incoming REFER request */
19534 /*! \page SIP_REFER SIP transfer Support (REFER)
19535 
19536    REFER is used for call transfer in SIP. We get a REFER
19537    to place a new call with an INVITE somwhere and then
19538    keep the transferor up-to-date of the transfer. If the
19539    transfer fails, get back on line with the orginal call. 
19540 
19541    - REFER can be sent outside or inside of a dialog.
19542      Asterisk only accepts REFER inside of a dialog.
19543 
19544    - If we get a replaces header, it is an attended transfer
19545 
19546    \par Blind transfers
19547    The transferor provides the transferee
19548    with the transfer targets contact. The signalling between
19549    transferer or transferee should not be cancelled, so the
19550    call is recoverable if the transfer target can not be reached 
19551    by the transferee.
19552 
19553    In this case, Asterisk receives a TRANSFER from
19554    the transferor, thus is the transferee. We should
19555    try to set up a call to the contact provided
19556    and if that fails, re-connect the current session.
19557    If the new call is set up, we issue a hangup.
19558    In this scenario, we are following section 5.2
19559    in the SIP CC Transfer draft. (Transfer without
19560    a GRUU)
19561 
19562    \par Transfer with consultation hold
19563    In this case, the transferor
19564    talks to the transfer target before the transfer takes place.
19565    This is implemented with SIP hold and transfer.
19566    Note: The invite From: string could indicate a transfer.
19567    (Section 6. Transfer with consultation hold)
19568    The transferor places the transferee on hold, starts a call
19569    with the transfer target to alert them to the impending
19570    transfer, terminates the connection with the target, then
19571    proceeds with the transfer (as in Blind transfer above)
19572 
19573    \par Attended transfer
19574    The transferor places the transferee
19575    on hold, calls the transfer target to alert them,
19576    places the target on hold, then proceeds with the transfer
19577    using a Replaces header field in the Refer-to header. This
19578    will force the transfee to send an Invite to the target,
19579    with a replaces header that instructs the target to
19580    hangup the call between the transferor and the target.
19581    In this case, the Refer/to: uses the AOR address. (The same
19582    URI that the transferee used to establish the session with
19583    the transfer target (To: ). The Require: replaces header should
19584    be in the INVITE to avoid the wrong UA in a forked SIP proxy
19585    scenario to answer and have no call to replace with.
19586 
19587    The referred-by header is *NOT* required, but if we get it,
19588    can be copied into the INVITE to the transfer target to 
19589    inform the target about the transferor
19590 
19591    "Any REFER request has to be appropriately authenticated.".
19592    
19593    We can't destroy dialogs, since we want the call to continue.
19594    
19595    */
19596 static int handle_request_refer(struct sip_pvt *p, struct sip_request *req, int debug, int seqno, int *nounlock)
19597 {
19598    struct sip_dual current;   /* Chan1: Call between asterisk and transferer */
19599                /* Chan2: Call between asterisk and transferee */
19600 
19601    int res = 0;
19602    current.req.data = NULL;
19603 
19604    if (req->debug)
19605       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");
19606 
19607    if (!p->owner) {
19608       /* This is a REFER outside of an existing SIP dialog */
19609       /* We can't handle that, so decline it */
19610       ast_debug(3, "Call %s: Declined REFER, outside of dialog...\n", p->callid);
19611       transmit_response(p, "603 Declined (No dialog)", req);
19612       if (!req->ignore) {
19613          append_history(p, "Xfer", "Refer failed. Outside of dialog.");
19614          sip_alreadygone(p);
19615          p->needdestroy = 1;
19616       }
19617       return 0;
19618    }  
19619 
19620 
19621    /* Check if transfer is allowed from this device */
19622    if (p->allowtransfer == TRANSFER_CLOSED ) {
19623       /* Transfer not allowed, decline */
19624       transmit_response(p, "603 Declined (policy)", req);
19625       append_history(p, "Xfer", "Refer failed. Allowtransfer == closed.");
19626       /* Do not destroy SIP session */
19627       return 0;
19628    }
19629 
19630    if (!req->ignore && ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
19631       /* Already have a pending REFER */  
19632       transmit_response(p, "491 Request pending", req);
19633       append_history(p, "Xfer", "Refer failed. Request pending.");
19634       return 0;
19635    }
19636 
19637    /* Allocate memory for call transfer data */
19638    if (!p->refer && !sip_refer_allocate(p)) {
19639       transmit_response(p, "500 Internal Server Error", req);
19640       append_history(p, "Xfer", "Refer failed. Memory allocation error.");
19641       return -3;
19642    }
19643 
19644    res = get_refer_info(p, req); /* Extract headers */
19645 
19646    p->refer->status = REFER_SENT;
19647 
19648    if (res != 0) {
19649       switch (res) {
19650       case -2: /* Syntax error */
19651          transmit_response(p, "400 Bad Request (Refer-to missing)", req);
19652          append_history(p, "Xfer", "Refer failed. Refer-to missing.");
19653          if (req->debug)
19654             ast_debug(1, "SIP transfer to black hole can't be handled (no refer-to: )\n");
19655          break;
19656       case -3:
19657          transmit_response(p, "603 Declined (Non sip: uri)", req);
19658          append_history(p, "Xfer", "Refer failed. Non SIP uri");
19659          if (req->debug)
19660             ast_debug(1, "SIP transfer to non-SIP uri denied\n");
19661          break;
19662       default:
19663          /* Refer-to extension not found, fake a failed transfer */
19664          transmit_response(p, "202 Accepted", req);
19665          append_history(p, "Xfer", "Refer failed. Bad extension.");
19666          transmit_notify_with_sipfrag(p, seqno, "404 Not found", TRUE);
19667          ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19668          if (req->debug)
19669             ast_debug(1, "SIP transfer to bad extension: %s\n", p->refer->refer_to);
19670          break;
19671       } 
19672       return 0;
19673    }
19674    if (ast_strlen_zero(p->context))
19675       ast_string_field_set(p, context, default_context);
19676 
19677    /* If we do not support SIP domains, all transfers are local */
19678    if (allow_external_domains && check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19679       p->refer->localtransfer = 1;
19680       if (sipdebug)
19681          ast_debug(3, "This SIP transfer is local : %s\n", p->refer->refer_to_domain);
19682    } else if (AST_LIST_EMPTY(&domain_list) || check_sip_domain(p->refer->refer_to_domain, NULL, 0)) {
19683       /* This PBX doesn't bother with SIP domains or domain is local, so this transfer is local */
19684       p->refer->localtransfer = 1;
19685    } else if (sipdebug)
19686          ast_debug(3, "This SIP transfer is to a remote SIP extension (remote domain %s)\n", p->refer->refer_to_domain);
19687    
19688    /* Is this a repeat of a current request? Ignore it */
19689    /* Don't know what else to do right now. */
19690    if (req->ignore) 
19691       return res;
19692 
19693    /* If this is a blind transfer, we have the following
19694    channels to work with:
19695    - chan1, chan2: The current call between transferer and transferee (2 channels)
19696    - target_channel: A new call from the transferee to the target (1 channel)
19697    We need to stay tuned to what happens in order to be able
19698    to bring back the call to the transferer */
19699 
19700    /* If this is a attended transfer, we should have all call legs within reach:
19701    - chan1, chan2: The call between the transferer and transferee (2 channels)
19702    - target_channel, targetcall_pvt: The call between the transferer and the target (2 channels)
19703    We want to bridge chan2 with targetcall_pvt!
19704    
19705    The replaces call id in the refer message points
19706    to the call leg between Asterisk and the transferer.
19707    So we need to connect the target and the transferee channel
19708    and hangup the two other channels silently 
19709    
19710    If the target is non-local, the call ID could be on a remote
19711    machine and we need to send an INVITE with replaces to the
19712    target. We basically handle this as a blind transfer
19713    and let the sip_call function catch that we need replaces
19714    header in the INVITE.
19715    */
19716 
19717 
19718    /* Get the transferer's channel */
19719    current.chan1 = p->owner;
19720 
19721    /* Find the other part of the bridge (2) - transferee */
19722    current.chan2 = ast_bridged_channel(current.chan1);
19723    
19724    if (sipdebug)
19725       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>");
19726 
19727    if (!current.chan2 && !p->refer->attendedtransfer) {
19728       /* No bridged channel, propably IVR or echo or similar... */
19729       /* Guess we should masquerade or something here */
19730       /* Until we figure it out, refuse transfer of such calls */
19731       if (sipdebug)
19732          ast_debug(3, "Refused SIP transfer on non-bridged channel.\n");
19733       p->refer->status = REFER_FAILED;
19734       append_history(p, "Xfer", "Refer failed. Non-bridged channel.");
19735       transmit_response(p, "603 Declined", req);
19736       return -1;
19737    }
19738 
19739    if (current.chan2) {
19740       if (sipdebug)
19741          ast_debug(4, "Got SIP transfer, applying to bridged peer '%s'\n", current.chan2->name);
19742 
19743       ast_queue_control(current.chan1, AST_CONTROL_UNHOLD);
19744    }
19745 
19746    ast_set_flag(&p->flags[0], SIP_GOTREFER); 
19747 
19748    /* Attended transfer: Find all call legs and bridge transferee with target*/
19749    if (p->refer->attendedtransfer) {
19750       if ((res = local_attended_transfer(p, &current, req, seqno)))
19751          return res; /* We're done with the transfer */
19752       /* Fall through for remote transfers that we did not find locally */
19753       if (sipdebug)
19754          ast_debug(4, "SIP attended transfer: Still not our call - generating INVITE with replaces\n");
19755       /* Fallthrough if we can't find the call leg internally */
19756    }
19757 
19758 
19759    /* Parking a call */
19760    if (p->refer->localtransfer && !strcmp(p->refer->refer_to, ast_parking_ext())) {
19761       /* Must release c's lock now, because it will not longer be accessible after the transfer! */
19762       *nounlock = 1;
19763       ast_channel_unlock(current.chan1);
19764       copy_request(&current.req, req);
19765       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19766       p->refer->status = REFER_200OK;
19767       append_history(p, "Xfer", "REFER to call parking.");
19768       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",
19769          current.chan1->name,
19770          current.chan1->uniqueid,
19771          p->callid,
19772          current.chan2->name,
19773          current.chan2->uniqueid,
19774          p->refer->refer_to);
19775       if (sipdebug)
19776          ast_debug(4, "SIP transfer to parking: trying to park %s. Parked by %s\n", current.chan2->name, current.chan1->name);
19777       sip_park(current.chan2, current.chan1, req, seqno);
19778       return res;
19779    } 
19780 
19781    /* Blind transfers and remote attended xfers */
19782    transmit_response(p, "202 Accepted", req);
19783 
19784    if (current.chan1 && current.chan2) {
19785       ast_debug(3, "chan1->name: %s\n", current.chan1->name);
19786       pbx_builtin_setvar_helper(current.chan1, "BLINDTRANSFER", current.chan2->name);
19787    }
19788    if (current.chan2) {
19789       pbx_builtin_setvar_helper(current.chan2, "BLINDTRANSFER", current.chan1->name);
19790       pbx_builtin_setvar_helper(current.chan2, "SIPDOMAIN", p->refer->refer_to_domain);
19791       pbx_builtin_setvar_helper(current.chan2, "SIPTRANSFER", "yes");
19792       /* One for the new channel */
19793       pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER", "yes");
19794       /* Attended transfer to remote host, prepare headers for the INVITE */
19795       if (p->refer->referred_by) 
19796          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REFERER", p->refer->referred_by);
19797    }
19798    /* Generate a Replaces string to be used in the INVITE during attended transfer */
19799    if (!ast_strlen_zero(p->refer->replaces_callid)) {
19800       char tempheader[SIPBUFSIZE];
19801       snprintf(tempheader, sizeof(tempheader), "%s%s%s%s%s", p->refer->replaces_callid, 
19802             p->refer->replaces_callid_totag ? ";to-tag=" : "", 
19803             p->refer->replaces_callid_totag, 
19804             p->refer->replaces_callid_fromtag ? ";from-tag=" : "",
19805             p->refer->replaces_callid_fromtag);
19806       if (current.chan2)
19807          pbx_builtin_setvar_helper(current.chan2, "_SIPTRANSFER_REPLACES", tempheader);
19808    }
19809    /* Must release lock now, because it will not longer
19810       be accessible after the transfer! */
19811    *nounlock = 1;
19812    ast_channel_unlock(current.chan1);
19813 
19814    /* Connect the call */
19815 
19816    /* FAKE ringing if not attended transfer */
19817    if (!p->refer->attendedtransfer)
19818       transmit_notify_with_sipfrag(p, seqno, "183 Ringing", FALSE); 
19819       
19820    /* For blind transfer, this will lead to a new call */
19821    /* For attended transfer to remote host, this will lead to
19822       a new SIP call with a replaces header, if the dial plan allows it 
19823    */
19824    if (!current.chan2) {
19825       /* We have no bridge, so we're talking with Asterisk somehow */
19826       /* We need to masquerade this call */
19827       /* What to do to fix this situation:
19828          * Set up the new call in a new channel 
19829          * Let the new channel masq into this channel
19830          Please add that code here :-)
19831       */
19832       p->refer->status = REFER_FAILED;
19833       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable (can't handle one-legged xfers)", TRUE);
19834       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19835       append_history(p, "Xfer", "Refer failed (only bridged calls).");
19836       return -1;
19837    }
19838    ast_set_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER);   /* Delay hangup */
19839 
19840 
19841    /* For blind transfers, move the call to the new extensions. For attended transfers on multiple
19842       servers - generate an INVITE with Replaces. Either way, let the dial plan decided  */
19843    res = ast_async_goto(current.chan2, p->refer->refer_to_context, p->refer->refer_to, 1);
19844 
19845    if (!res) {
19846       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",
19847          current.chan1->name,
19848          current.chan1->uniqueid,
19849          p->callid,
19850          current.chan2->name,
19851          current.chan2->uniqueid,
19852          p->refer->refer_to, p->refer->refer_to_context);
19853       /* Success  - we have a new channel */
19854       ast_debug(3, "%s transfer succeeded. Telling transferer.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19855       transmit_notify_with_sipfrag(p, seqno, "200 Ok", TRUE);
19856       if (p->refer->localtransfer)
19857          p->refer->status = REFER_200OK;
19858       if (p->owner)
19859          p->owner->hangupcause = AST_CAUSE_NORMAL_CLEARING;
19860       append_history(p, "Xfer", "Refer succeeded.");
19861       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19862       /* Do not hangup call, the other side do that when we say 200 OK */
19863       /* We could possibly implement a timer here, auto congestion */
19864       res = 0;
19865    } else {
19866       ast_clear_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER); /* Don't delay hangup */
19867       ast_debug(3, "%s transfer failed. Resuming original call.\n", p->refer->attendedtransfer? "Attended" : "Blind");
19868       append_history(p, "Xfer", "Refer failed.");
19869       /* Failure of some kind */
19870       p->refer->status = REFER_FAILED;
19871       transmit_notify_with_sipfrag(p, seqno, "503 Service Unavailable", TRUE);
19872       ast_clear_flag(&p->flags[0], SIP_GOTREFER);  
19873       res = -1;
19874    }
19875    return res;
19876 }
19877 
19878 /*! \brief Handle incoming CANCEL request */
19879 static int handle_request_cancel(struct sip_pvt *p, struct sip_request *req)
19880 {
19881       
19882    check_via(p, req);
19883    sip_alreadygone(p);
19884 
19885    /* At this point, we could have cancelled the invite at the same time
19886       as the other side sends a CANCEL. Our final reply with error code
19887       might not have been received by the other side before the CANCEL
19888       was sent, so let's just give up retransmissions and waiting for
19889       ACK on our error code. The call is hanging up any way. */
19890    if (p->invitestate == INV_TERMINATED)
19891       __sip_pretend_ack(p);
19892    else
19893       p->invitestate = INV_CANCELLED;
19894    
19895    if (p->owner && p->owner->_state == AST_STATE_UP) {
19896       /* This call is up, cancel is ignored, we need a bye */
19897       transmit_response(p, "200 OK", req);
19898       ast_debug(1, "Got CANCEL on an answered call. Ignoring... \n");
19899       return 0;
19900    }
19901 
19902    if (ast_test_flag(&p->flags[0], SIP_INC_COUNT) || ast_test_flag(&p->flags[1], SIP_PAGE2_CALL_ONHOLD)) 
19903       update_call_counter(p, DEC_CALL_LIMIT);
19904 
19905    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
19906    if (p->owner)
19907       ast_queue_hangup(p->owner);
19908    else
19909       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
19910    if (p->initreq.len > 0) {
19911       struct sip_pkt *pkt, *prev_pkt;
19912       /* If the CANCEL we are receiving is a retransmission, and we already have scheduled
19913        * a reliable 487, then we don't want to schedule another one on top of the previous
19914        * one.
19915        *
19916        * As odd as this may sound, we can't rely on the previously-transmitted "reliable" 
19917        * response in this situation. What if we've sent all of our reliable responses 
19918        * already and now all of a sudden, we get this second CANCEL?
19919        *
19920        * The only way to do this correctly is to cancel our previously-scheduled reliably-
19921        * transmitted response and send a new one in its place.
19922        */
19923       for (pkt = p->packets, prev_pkt = NULL; pkt; prev_pkt = pkt, pkt = pkt->next) {
19924          if (pkt->seqno == p->lastinvite && pkt->response_code == 487) {
19925             AST_SCHED_DEL(sched, pkt->retransid);
19926             UNLINK(pkt, p->packets, prev_pkt);
19927             ast_free(pkt);
19928             break;
19929          }
19930       }
19931       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
19932       transmit_response(p, "200 OK", req);
19933       return 1;
19934    } else {
19935       transmit_response(p, "481 Call Leg Does Not Exist", req);
19936       return 0;
19937    }
19938 }
19939 
19940 static int acf_channel_read(struct ast_channel *chan, const char *funcname, char *preparse, char *buf, size_t buflen)
19941 {
19942    struct sip_pvt *p = chan->tech_pvt;
19943    char *all = "", *parse = ast_strdupa(preparse);
19944    int res = 0;
19945    AST_DECLARE_APP_ARGS(args,
19946       AST_APP_ARG(param);
19947       AST_APP_ARG(type);
19948       AST_APP_ARG(field);
19949    );
19950    AST_STANDARD_APP_ARGS(args, parse);
19951 
19952    /* Sanity check */
19953    if (!IS_SIP_TECH(chan->tech)) {
19954       ast_log(LOG_ERROR, "Cannot call %s on a non-SIP channel\n", funcname);
19955       return 0;
19956    }
19957 
19958    memset(buf, 0, buflen);
19959 
19960    if (p == NULL) {
19961       return -1;
19962    }
19963 
19964    if (!strcasecmp(args.param, "peerip")) {
19965       ast_copy_string(buf, p->sa.sin_addr.s_addr ? ast_inet_ntoa(p->sa.sin_addr) : "", buflen);
19966    } else if (!strcasecmp(args.param, "recvip")) {
19967       ast_copy_string(buf, p->recv.sin_addr.s_addr ? ast_inet_ntoa(p->recv.sin_addr) : "", buflen);
19968    } else if (!strcasecmp(args.param, "from")) {
19969       ast_copy_string(buf, p->from, buflen);
19970    } else if (!strcasecmp(args.param, "uri")) {
19971       ast_copy_string(buf, p->uri, buflen);
19972    } else if (!strcasecmp(args.param, "useragent")) {
19973       ast_copy_string(buf, p->useragent, buflen);
19974    } else if (!strcasecmp(args.param, "peername")) {
19975       ast_copy_string(buf, p->peername, buflen);
19976    } else if (!strcasecmp(args.param, "t38passthrough")) {
19977       ast_copy_string(buf, (p->t38.state == T38_DISABLED) ? "0" : "1", buflen);
19978    } else if (!strcasecmp(args.param, "rtpdest")) {
19979       struct sockaddr_in sin;
19980 
19981       if (ast_strlen_zero(args.type))
19982          args.type = "audio";
19983 
19984       if (!strcasecmp(args.type, "audio"))
19985          ast_rtp_get_peer(p->rtp, &sin);
19986       else if (!strcasecmp(args.type, "video"))
19987          ast_rtp_get_peer(p->vrtp, &sin);
19988       else if (!strcasecmp(args.type, "text"))
19989          ast_rtp_get_peer(p->trtp, &sin);
19990       else
19991          return -1;
19992 
19993       snprintf(buf, buflen, "%s:%d", ast_inet_ntoa(sin.sin_addr), ntohs(sin.sin_port));
19994    } else if (!strcasecmp(args.param, "rtpqos")) {
19995       struct ast_rtp_quality qos;
19996       struct ast_rtp *rtp = p->rtp;
19997       
19998       memset(&qos, 0, sizeof(qos));
19999 
20000       if (ast_strlen_zero(args.type))
20001          args.type = "audio";
20002       if (ast_strlen_zero(args.field))
20003          args.field = "all";
20004       
20005       if (!strcasecmp(args.type, "AUDIO")) {
20006          all = ast_rtp_get_quality(rtp = p->rtp, &qos, RTPQOS_SUMMARY);
20007       } else if (!strcasecmp(args.type, "VIDEO")) {
20008          all = ast_rtp_get_quality(rtp = p->vrtp, &qos, RTPQOS_SUMMARY);
20009       } else if (!strcasecmp(args.type, "TEXT")) {
20010          all = ast_rtp_get_quality(rtp = p->trtp, &qos, RTPQOS_SUMMARY);
20011       } else {
20012          return -1;
20013       }
20014       
20015       if (!strcasecmp(args.field, "local_ssrc"))
20016          snprintf(buf, buflen, "%u", qos.local_ssrc);
20017       else if (!strcasecmp(args.field, "local_lostpackets"))
20018          snprintf(buf, buflen, "%u", qos.local_lostpackets);
20019       else if (!strcasecmp(args.field, "local_jitter"))
20020          snprintf(buf, buflen, "%.0f", qos.local_jitter * 1000.0);
20021       else if (!strcasecmp(args.field, "local_count"))
20022          snprintf(buf, buflen, "%u", qos.local_count);
20023       else if (!strcasecmp(args.field, "remote_ssrc"))
20024          snprintf(buf, buflen, "%u", qos.remote_ssrc);
20025       else if (!strcasecmp(args.field, "remote_lostpackets"))
20026          snprintf(buf, buflen, "%u", qos.remote_lostpackets);
20027       else if (!strcasecmp(args.field, "remote_jitter"))
20028          snprintf(buf, buflen, "%.0f", qos.remote_jitter * 1000.0);
20029       else if (!strcasecmp(args.field, "remote_count"))
20030          snprintf(buf, buflen, "%u", qos.remote_count);
20031       else if (!strcasecmp(args.field, "rtt"))
20032          snprintf(buf, buflen, "%.0f", qos.rtt * 1000.0);
20033       else if (!strcasecmp(args.field, "all"))
20034          ast_copy_string(buf, all, buflen);
20035       else if (!ast_rtp_get_qos(rtp, args.field, buf, buflen))
20036           ;
20037       else {
20038          ast_log(LOG_WARNING, "Unrecognized argument '%s' to %s\n", preparse, funcname);
20039          return -1;
20040       }
20041    } else {
20042       res = -1;
20043    }
20044    return res;
20045 }
20046 
20047 /*! \brief Handle incoming BYE request */
20048 static int handle_request_bye(struct sip_pvt *p, struct sip_request *req)
20049 {
20050    struct ast_channel *c=NULL;
20051    int res;
20052    struct ast_channel *bridged_to;
20053    
20054    /* If we have an INCOMING invite that we haven't answered, terminate that transaction */
20055    if (p->pendinginvite && !ast_test_flag(&p->flags[0], SIP_OUTGOING) && !req->ignore) {
20056       transmit_response_reliable(p, "487 Request Terminated", &p->initreq);
20057    }
20058 
20059    __sip_pretend_ack(p);
20060 
20061    p->invitestate = INV_TERMINATED;
20062 
20063    copy_request(&p->initreq, req);
20064    if (sipdebug)
20065       ast_debug(1, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20066    check_via(p, req);
20067    sip_alreadygone(p);
20068 
20069    /* Get RTCP quality before end of call */
20070    if (p->do_history || p->owner) {
20071       struct ast_channel *bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
20072       char *videoqos, *textqos;
20073 
20074       /* We need to get the lock on bridge because ast_rtp_set_vars will attempt
20075        * to lock the bridge. This may get hairy...
20076        */
20077       while (bridge && ast_channel_trylock(bridge)) {
20078          ast_channel_unlock(p->owner);
20079          do {
20080             /* Can't use DEADLOCK_AVOIDANCE since p is an ao2 object */
20081             sip_pvt_unlock(p);
20082             usleep(1);
20083             sip_pvt_lock(p);
20084          } while (p->owner && ast_channel_trylock(p->owner));
20085          bridge = p->owner ? ast_bridged_channel(p->owner) : NULL;
20086       }
20087 
20088       if (p->rtp) {  
20089          if (p->do_history) {
20090             char *audioqos,
20091                  *audioqos_jitter,
20092                  *audioqos_loss,
20093                  *audioqos_rtt;
20094 
20095             audioqos        = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_SUMMARY);
20096             audioqos_jitter = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_JITTER);
20097             audioqos_loss   = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_LOSS);
20098             audioqos_rtt    = ast_rtp_get_quality(p->rtp, NULL, RTPQOS_RTT);
20099 
20100             append_history(p, "RTCPaudio", "Quality:%s", audioqos);
20101             append_history(p, "RTCPaudioJitter", "Quality:%s", audioqos_jitter);
20102             append_history(p, "RTCPaudioLoss", "Quality:%s", audioqos_loss);
20103             append_history(p, "RTCPaudioRTT", "Quality:%s", audioqos_rtt);
20104          }
20105          
20106          if (p->owner) {
20107             ast_rtp_set_vars(p->owner, p->rtp);
20108          }
20109       }
20110 
20111       if (bridge) {
20112          struct sip_pvt *q = bridge->tech_pvt;
20113 
20114          if (IS_SIP_TECH(bridge->tech) && q && q->rtp)
20115             ast_rtp_set_vars(bridge, q->rtp);
20116          ast_channel_unlock(bridge);
20117       }
20118 
20119       if (p->vrtp) {
20120          videoqos = ast_rtp_get_quality(p->vrtp, NULL, RTPQOS_SUMMARY);
20121          if (p->do_history)
20122             append_history(p, "RTCPvideo", "Quality:%s", videoqos);
20123          if (p->owner)
20124             pbx_builtin_setvar_helper(p->owner, "RTPVIDEOQOS", videoqos);
20125       }
20126 
20127       if (p->trtp) {
20128          textqos = ast_rtp_get_quality(p->trtp, NULL, RTPQOS_SUMMARY);
20129          if (p->do_history)
20130             append_history(p, "RTCPtext", "Quality:%s", textqos);
20131          if (p->owner)
20132             pbx_builtin_setvar_helper(p->owner, "RTPTEXTQOS", textqos);
20133       }
20134    }
20135 
20136    stop_media_flows(p); /* Immediately stop RTP, VRTP and UDPTL as applicable */
20137    stop_session_timer(p); /* Stop Session-Timer */
20138 
20139    if (!ast_strlen_zero(get_header(req, "Also"))) {
20140       ast_log(LOG_NOTICE, "Client '%s' using deprecated BYE/Also transfer method.  Ask vendor to support REFER instead\n",
20141          ast_inet_ntoa(p->recv.sin_addr));
20142       if (ast_strlen_zero(p->context))
20143          ast_string_field_set(p, context, default_context);
20144       res = get_also_info(p, req);
20145       if (!res) {
20146          c = p->owner;
20147          if (c) {
20148             bridged_to = ast_bridged_channel(c);
20149             if (bridged_to) {
20150                /* Don't actually hangup here... */
20151                ast_queue_control(c, AST_CONTROL_UNHOLD);
20152                ast_async_goto(bridged_to, p->context, p->refer->refer_to, 1);
20153             } else
20154                ast_queue_hangup(p->owner);
20155          }
20156       } else {
20157          ast_log(LOG_WARNING, "Invalid transfer information from '%s'\n", ast_inet_ntoa(p->recv.sin_addr));
20158          if (p->owner)
20159             ast_queue_hangup_with_cause(p->owner, AST_CAUSE_PROTOCOL_ERROR);
20160       }
20161    } else if (p->owner) {
20162       ast_queue_hangup(p->owner);
20163       ast_debug(3, "Received bye, issuing owner hangup\n");
20164    } else {
20165       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20166       ast_debug(3, "Received bye, no owner, selfdestruct soon.\n");
20167    }
20168    ast_clear_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20169    transmit_response(p, "200 OK", req);
20170 
20171    return 1;
20172 }
20173 
20174 /*! \brief Handle incoming MESSAGE request */
20175 static int handle_request_message(struct sip_pvt *p, struct sip_request *req)
20176 {
20177    if (!req->ignore) {
20178       if (req->debug)
20179          ast_verbose("Receiving message!\n");
20180       receive_message(p, req);
20181    } else
20182       transmit_response(p, "202 Accepted", req);
20183    return 1;
20184 }
20185 
20186 static void add_peer_mwi_subs(struct sip_peer *peer)
20187 {
20188    struct sip_mailbox *mailbox;
20189 
20190    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
20191       mailbox->event_sub = ast_event_subscribe(AST_EVENT_MWI, mwi_event_cb, peer,
20192          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
20193          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
20194          AST_EVENT_IE_END);
20195    }
20196 }
20197 
20198 /*! \brief  Handle incoming SUBSCRIBE request */
20199 static int handle_request_subscribe(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int seqno, char *e)
20200 {
20201    int gotdest = 0;
20202    int res = 0;
20203    int firststate = AST_EXTENSION_REMOVED;
20204    struct sip_peer *authpeer = NULL;
20205    const char *eventheader = get_header(req, "Event");   /* Get Event package name */
20206    const char *acceptheader = get_header(req, "Accept");
20207    int resubscribe = (p->subscribed != NONE);
20208    char *temp, *event;
20209    struct ao2_iterator i;
20210 
20211    if (p->initreq.headers) {  
20212       /* We already have a dialog */
20213       if (p->initreq.method != SIP_SUBSCRIBE) {
20214          /* This is a SUBSCRIBE within another SIP dialog, which we do not support */
20215          /* For transfers, this could happen, but since we haven't seen it happening, let us just refuse this */
20216          transmit_response(p, "403 Forbidden (within dialog)", req);
20217          /* Do not destroy session, since we will break the call if we do */
20218          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);
20219          return 0;
20220       } else if (req->debug) {
20221          if (resubscribe)
20222             ast_debug(1, "Got a re-subscribe on existing subscription %s\n", p->callid);
20223          else
20224             ast_debug(1, "Got a new subscription %s (possibly with auth)\n", p->callid);
20225       }
20226    }
20227 
20228    /* Check if we have a global disallow setting on subscriptions. 
20229       if so, we don't have to check peer settings after auth, which saves a lot of processing
20230    */
20231    if (!global_allowsubscribe) {
20232       transmit_response(p, "403 Forbidden (policy)", req);
20233       p->needdestroy = 1;
20234       return 0;
20235    }
20236 
20237    if (!req->ignore && !resubscribe) { /* Set up dialog, new subscription */
20238       const char *to = get_header(req, "To");
20239       char totag[128];
20240 
20241       /* Check to see if a tag was provided, if so this is actually a resubscription of a dialog we no longer know about */
20242       if (!ast_strlen_zero(to) && gettag(req, "To", totag, sizeof(totag))) {
20243          if (req->debug)
20244             ast_verbose("Received resubscription for a dialog we no longer know about. Telling remote side to subscribe again.\n");
20245          transmit_response(p, "481 Subscription does not exist", req);
20246          p->needdestroy = 1;
20247          return 0;
20248       }
20249 
20250       /* Use this as the basis */
20251       if (req->debug)
20252          ast_verbose("Creating new subscription\n");
20253 
20254       copy_request(&p->initreq, req);
20255       if (sipdebug)
20256          ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20257       check_via(p, req);
20258       build_route(p, req, 0);
20259    } else if (req->debug && req->ignore)
20260       ast_verbose("Ignoring this SUBSCRIBE request\n");
20261 
20262    /* Find parameters to Event: header value and remove them for now */
20263    if (ast_strlen_zero(eventheader)) {
20264       transmit_response(p, "489 Bad Event", req);
20265       ast_debug(2, "Received SIP subscribe for unknown event package: <none>\n");
20266       p->needdestroy = 1;
20267       return 0;
20268    }
20269 
20270    if ( (strchr(eventheader, ';'))) {
20271       event = ast_strdupa(eventheader);   /* Since eventheader is a const, we can't change it */
20272       temp = strchr(event, ';');       
20273       *temp = '\0';           /* Remove any options for now */
20274                      /* We might need to use them later :-) */
20275    } else
20276       event = (char *) eventheader;    /* XXX is this legal ? */
20277 
20278    /* Handle authentication */
20279    res = check_user_full(p, req, SIP_SUBSCRIBE, e, 0, sin, &authpeer);
20280    /* if an authentication response was sent, we are done here */
20281    if (res == AUTH_CHALLENGE_SENT)  /* authpeer = NULL here */
20282       return 0;
20283    if (res < 0) {
20284       if (res == AUTH_FAKE_AUTH) {
20285          ast_log(LOG_NOTICE, "Sending fake auth rejection for device %s\n", get_header(req, "From"));
20286          transmit_fake_auth_response(p, SIP_SUBSCRIBE, req, XMIT_UNRELIABLE);
20287       } else {
20288          ast_log(LOG_NOTICE, "Failed to authenticate device %s for SUBSCRIBE\n", get_header(req, "From"));
20289          transmit_response_reliable(p, "403 Forbidden", req);
20290       }
20291       p->needdestroy = 1;
20292       return 0;
20293    }
20294 
20295    /* At this point, authpeer cannot be NULL. Remember we hold a reference,
20296     * so we must release it when done.
20297     * XXX must remove all the checks for authpeer == NULL.
20298     */
20299 
20300    /* Check if this device  is allowed to subscribe at all */
20301    if (!ast_test_flag(&p->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
20302       transmit_response(p, "403 Forbidden (policy)", req);
20303       p->needdestroy = 1;
20304       if (authpeer)
20305          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 1)");
20306       return 0;
20307    }
20308 
20309    if (strcmp(event, "message-summary")) {
20310       /* Get destination right away */
20311       gotdest = get_destination(p, NULL);
20312    }
20313 
20314    /* Get full contact header - this needs to be used as a request URI in NOTIFY's */
20315    parse_ok_contact(p, req);
20316 
20317    build_contact(p);
20318    if (gotdest) {
20319       transmit_response(p, "404 Not Found", req);
20320       p->needdestroy = 1;
20321       if (authpeer)
20322          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
20323       return 0;
20324    }
20325 
20326    /* Initialize tag for new subscriptions */   
20327    if (ast_strlen_zero(p->tag))
20328       make_our_tag(p->tag, sizeof(p->tag));
20329 
20330    if (!strcmp(event, "presence") || !strcmp(event, "dialog")) { /* Presence, RFC 3842 */
20331       unsigned int pidf_xml;
20332 
20333       if (authpeer)  /* We do not need the authpeer any more */
20334          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 2)");
20335 
20336       /* Header from Xten Eye-beam Accept: multipart/related, application/rlmi+xml, application/pidf+xml, application/xpidf+xml */
20337 
20338       pidf_xml = strstr(acceptheader, "application/pidf+xml") ? 1 : 0;
20339 
20340       /* Older versions of Polycom firmware will claim pidf+xml, but really
20341        * they only support xpidf+xml. */
20342       if (pidf_xml && strstr(p->useragent, "Polycom")) {
20343          p->subscribed = XPIDF_XML;
20344       } else if (pidf_xml) {
20345          p->subscribed = PIDF_XML;         /* RFC 3863 format */
20346       } else if (strstr(acceptheader, "application/dialog-info+xml")) {
20347          p->subscribed = DIALOG_INFO_XML;
20348          /* IETF draft: draft-ietf-sipping-dialog-package-05.txt */
20349       } else if (strstr(acceptheader, "application/cpim-pidf+xml")) {
20350          p->subscribed = CPIM_PIDF_XML;    /* RFC 3863 format */
20351       } else if (strstr(acceptheader, "application/xpidf+xml")) {
20352          p->subscribed = XPIDF_XML;        /* Early pre-RFC 3863 format with MSN additions (Microsoft Messenger) */
20353       } else if (ast_strlen_zero(acceptheader)) {
20354          if (p->subscribed == NONE) { /* if the subscribed field is not already set, and there is no accept header... */
20355             transmit_response(p, "489 Bad Event", req);
20356   
20357             ast_log(LOG_WARNING, "SUBSCRIBE failure: no Accept header: pvt: stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
20358                p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
20359             p->needdestroy = 1;
20360             return 0;
20361          }
20362          /* if p->subscribed is non-zero, then accept is not obligatory; according to rfc 3265 section 3.1.3, at least.
20363             so, we'll just let it ride, keeping the value from a previous subscription, and not abort the subscription */
20364       } else {
20365          /* Can't find a format for events that we know about */
20366          char mybuf[200];
20367          snprintf(mybuf, sizeof(mybuf), "489 Bad Event (format %s)", acceptheader);
20368          transmit_response(p, mybuf, req);
20369  
20370          ast_log(LOG_WARNING, "SUBSCRIBE failure: unrecognized format: '%s' pvt: subscribed: %d, stateid: %d, laststate: %d, dialogver: %d, subscribecont: '%s', subscribeuri: '%s'\n",
20371             acceptheader, (int)p->subscribed, p->stateid, p->laststate, p->dialogver, p->subscribecontext, p->subscribeuri);
20372          p->needdestroy = 1;
20373          return 0;
20374       }
20375    } else if (!strcmp(event, "message-summary")) { 
20376       if (!ast_strlen_zero(acceptheader) && strcmp(acceptheader, "application/simple-message-summary")) {
20377          /* Format requested that we do not support */
20378          transmit_response(p, "406 Not Acceptable", req);
20379          ast_debug(2, "Received SIP mailbox subscription for unknown format: %s\n", acceptheader);
20380          p->needdestroy = 1;
20381          if (authpeer)
20382             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 3)");
20383          return 0;
20384       }
20385       /* Looks like they actually want a mailbox status 
20386         This version of Asterisk supports mailbox subscriptions
20387         The subscribed URI needs to exist in the dial plan
20388         In most devices, this is configurable to the voicemailmain extension you use
20389       */
20390       if (!authpeer || AST_LIST_EMPTY(&authpeer->mailboxes)) {
20391          transmit_response(p, "404 Not found (no mailbox)", req);
20392          p->needdestroy = 1;
20393          ast_log(LOG_NOTICE, "Received SIP subscribe for peer without mailbox: %s\n", authpeer->name);
20394          if (authpeer)
20395             unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 4)");
20396          return 0;
20397       }
20398 
20399       p->subscribed = MWI_NOTIFICATION;
20400       if (ast_test_flag(&authpeer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY)) {
20401          add_peer_mwi_subs(authpeer);
20402       }
20403       if (authpeer->mwipvt && authpeer->mwipvt != p) {   /* Destroy old PVT if this is a new one */
20404          /* We only allow one subscription per peer */
20405          dialog_unlink_all(authpeer->mwipvt, TRUE, TRUE);
20406          authpeer->mwipvt = dialog_unref(authpeer->mwipvt, "unref dialog authpeer->mwipvt");
20407          /* sip_destroy(authpeer->mwipvt); */
20408       }
20409       if (authpeer->mwipvt)
20410          dialog_unref(authpeer->mwipvt, "Unref previously stored mwipvt dialog pointer");
20411       authpeer->mwipvt = dialog_ref(p, "setting peers' mwipvt to p");      /* Link from peer to pvt UH- should this be dialog_ref()? */
20412       if (p->relatedpeer)
20413          unref_peer(p->relatedpeer, "Unref previously stored relatedpeer ptr");
20414       p->relatedpeer = ref_peer(authpeer, "setting dialog's relatedpeer pointer");  /* already refcounted...Link from pvt to peer UH- should this be dialog_ref()? */
20415       /* Do not release authpeer here */
20416    } else { /* At this point, Asterisk does not understand the specified event */
20417       transmit_response(p, "489 Bad Event", req);
20418       ast_debug(2, "Received SIP subscribe for unknown event package: %s\n", event);
20419       p->needdestroy = 1;
20420       if (authpeer)
20421          unref_peer(authpeer, "unref_peer, from handle_request_subscribe (authpeer 5)");
20422       return 0;
20423    }
20424 
20425    /* Add subscription for extension state from the PBX core */
20426    if (p->subscribed != MWI_NOTIFICATION && !resubscribe) {
20427       if (p->stateid > -1) {
20428          ast_extension_state_del(p->stateid, cb_extensionstate);
20429          /* we need to dec the refcount, now that the extensionstate is removed */
20430          dialog_unref(p, "the extensionstate containing this dialog ptr was deleted");
20431       }
20432       p->stateid = ast_extension_state_add(p->context, p->exten, cb_extensionstate, dialog_ref(p,"copying dialog ptr into extension state struct"));
20433    }
20434 
20435    if (!req->ignore && p)
20436       p->lastinvite = seqno;
20437    if (p && !p->needdestroy) {
20438       p->expiry = atoi(get_header(req, "Expires"));
20439 
20440       /* check if the requested expiry-time is within the approved limits from sip.conf */
20441       if (p->expiry > max_expiry)
20442          p->expiry = max_expiry;
20443       if (p->expiry < min_expiry && p->expiry > 0)
20444          p->expiry = min_expiry;
20445 
20446       if (sipdebug) {
20447          if (p->subscribed == MWI_NOTIFICATION && p->relatedpeer)
20448             ast_debug(2, "Adding subscription for mailbox notification - peer %s\n", p->relatedpeer->name);
20449          else
20450             ast_debug(2, "Adding subscription for extension %s context %s for peer %s\n", p->exten, p->context, p->username);
20451       }
20452       if (p->autokillid > -1 && sip_cancel_destroy(p))   /* Remove subscription expiry for renewals */
20453          ast_log(LOG_WARNING, "Unable to cancel SIP destruction.  Expect bad things.\n");
20454       if (p->expiry > 0)
20455          sip_scheddestroy(p, (p->expiry + 10) * 1000);   /* Set timer for destruction of call at expiration */
20456 
20457       if (p->subscribed == MWI_NOTIFICATION) {
20458          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20459          transmit_response(p, "200 OK", req);
20460          if (p->relatedpeer) {   /* Send first notification */
20461             ao2_lock(p->relatedpeer); /* was WRLOCK */
20462             sip_send_mwi_to_peer(p->relatedpeer, NULL, 0);
20463             ao2_unlock(p->relatedpeer);
20464          }
20465       } else {
20466          struct sip_pvt *p_old;
20467 
20468          if ((firststate = ast_extension_state(NULL, p->context, p->exten)) < 0) {
20469 
20470             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));
20471             transmit_response(p, "404 Not found", req);
20472             p->needdestroy = 1;
20473             return 0;
20474          }
20475          ast_set_flag(&p->flags[1], SIP_PAGE2_DIALOG_ESTABLISHED);
20476          transmit_response(p, "200 OK", req);
20477          transmit_state_notify(p, firststate, 1, FALSE); /* Send first notification */
20478          append_history(p, "Subscribestatus", "%s", ast_extension_state2str(firststate));
20479          /* hide the 'complete' exten/context in the refer_to field for later display */
20480          ast_string_field_build(p, subscribeuri, "%s@%s", p->exten, p->context);
20481 
20482          /* remove any old subscription from this peer for the same exten/context,
20483          as the peer has obviously forgotten about it and it's wasteful to wait
20484          for it to expire and send NOTIFY messages to the peer only to have them
20485          ignored (or generate errors)
20486          */
20487          i = ao2_iterator_init(dialogs, 0);
20488          while ((p_old = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
20489             if (p_old == p) {
20490                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20491                continue;
20492             }
20493             if (p_old->initreq.method != SIP_SUBSCRIBE) {
20494                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20495                continue;
20496             }
20497             if (p_old->subscribed == NONE) {
20498                ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before continue");
20499                continue;
20500             }
20501             sip_pvt_lock(p_old);
20502             if (!strcmp(p_old->username, p->username)) {
20503                if (!strcmp(p_old->exten, p->exten) &&
20504                    !strcmp(p_old->context, p->context)) {
20505                   p_old->needdestroy = 1;
20506                   sip_pvt_unlock(p_old);
20507                   ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next before break");
20508                   break;
20509                }
20510             }
20511             sip_pvt_unlock(p_old);
20512             ao2_t_ref(p_old, -1, "toss dialog ptr from iterator_next");
20513          }
20514          ao2_iterator_destroy(&i);
20515       }
20516       if (!p->expiry)
20517          p->needdestroy = 1;
20518    }
20519    return 1;
20520 }
20521 
20522 /*! \brief Handle incoming REGISTER request */
20523 static int handle_request_register(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, char *e)
20524 {
20525    enum check_auth_result res;
20526 
20527    /* Use this as the basis */
20528    copy_request(&p->initreq, req);
20529    if (sipdebug)
20530       ast_debug(4, "Initializing initreq for method %s - callid %s\n", sip_methods[req->method].text, p->callid);
20531    check_via(p, req);
20532    if ((res = register_verify(p, sin, req, e)) < 0) {
20533       const char *reason;
20534 
20535       switch (res) {
20536       case AUTH_SECRET_FAILED:
20537          reason = "Wrong password";
20538          break;
20539       case AUTH_USERNAME_MISMATCH:
20540          reason = "Username/auth name mismatch";
20541          break;
20542       case AUTH_NOT_FOUND:
20543          reason = "No matching peer found";
20544          break;
20545       case AUTH_UNKNOWN_DOMAIN:
20546          reason = "Not a local domain";
20547          break;
20548       case AUTH_PEER_NOT_DYNAMIC:
20549          reason = "Peer is not supposed to register";
20550          break;
20551       case AUTH_ACL_FAILED:
20552          reason = "Device does not match ACL";
20553          break;
20554       case AUTH_BAD_TRANSPORT:
20555          reason = "Device not configured to use this transport type";
20556          break;
20557       default:
20558          reason = "Unknown failure";
20559          break;
20560       }
20561       ast_log(LOG_NOTICE, "Registration from '%s' failed for '%s' - %s\n",
20562          get_header(req, "To"), ast_inet_ntoa(sin->sin_addr),
20563          reason);
20564       append_history(p, "RegRequest", "Failed : Account %s : %s", get_header(req, "To"), reason);
20565    } else
20566       append_history(p, "RegRequest", "Succeeded : Account %s", get_header(req, "To"));
20567 
20568    if (res < 1) {
20569       /* Destroy the session, but keep us around for just a bit in case they don't
20570          get our 200 OK */
20571       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20572    }
20573    return res;
20574 }
20575 
20576 /*! \brief Handle incoming SIP requests (methods) 
20577 \note This is where all incoming requests go first   */
20578 /* called with p and p->owner locked */
20579 static int handle_incoming(struct sip_pvt *p, struct sip_request *req, struct sockaddr_in *sin, int *recount, int *nounlock)
20580 {
20581    /* Called with p->lock held, as well as p->owner->lock if appropriate, keeping things
20582       relatively static */
20583    const char *cmd;
20584    const char *cseq;
20585    const char *useragent;
20586    int seqno;
20587    int len;
20588    int respid;
20589    int res = 0;
20590    int debug = sip_debug_test_pvt(p);
20591    char *e;
20592    int error = 0;
20593    int oldmethod = p->method;
20594    int acked = 0;
20595 
20596    /* Get Method and Cseq */
20597    cseq = get_header(req, "Cseq");
20598    cmd = REQ_OFFSET_TO_STR(req, header[0]);
20599 
20600    /* Must have Cseq */
20601    if (ast_strlen_zero(cmd) || ast_strlen_zero(cseq)) {
20602       ast_log(LOG_ERROR, "Missing Cseq. Dropping this SIP message, it's incomplete.\n");
20603       error = 1;
20604    }
20605    if (!error && sscanf(cseq, "%30d%n", &seqno, &len) != 1) {
20606       ast_log(LOG_ERROR, "No seqno in '%s'. Dropping incomplete message.\n", cmd);
20607       error = 1;
20608    }
20609    if (error) {
20610       if (!p->initreq.headers)   /* New call */
20611          p->needdestroy = 1; /* Make sure we destroy this dialog */
20612       return -1;
20613    }
20614    /* Get the command XXX */
20615 
20616    cmd = REQ_OFFSET_TO_STR(req, rlPart1);
20617    e = ast_skip_blanks(REQ_OFFSET_TO_STR(req, rlPart2));
20618 
20619    /* Save useragent of the client */
20620    useragent = get_header(req, "User-Agent");
20621    if (!ast_strlen_zero(useragent))
20622       ast_string_field_set(p, useragent, useragent);
20623 
20624    /* Find out SIP method for incoming request */
20625    if (req->method == SIP_RESPONSE) {  /* Response to our request */
20626       /* ignore means "don't do anything with it" but still have to 
20627        * respond appropriately.
20628        * But in this case this is a response already, so we really
20629        * have nothing to do with this message, and even setting the
20630        * ignore flag is pointless.
20631        */
20632       if (ast_strlen_zero(e)) {
20633          return 0;
20634       }
20635       if (sscanf(e, "%30d %n", &respid, &len) != 1) {
20636          ast_log(LOG_WARNING, "Invalid response: '%s'\n", e);
20637          return 0;
20638       }
20639       if (respid <= 0) {
20640          ast_log(LOG_WARNING, "Invalid SIP response code: '%d'\n", respid);
20641          return 0;
20642       }
20643       if (p->ocseq && (p->ocseq < seqno)) {
20644          if (option_debug)
20645             ast_log(LOG_DEBUG, "Ignoring out of order response %d (expecting %d)\n", seqno, p->ocseq);
20646          return -1;
20647       } else {
20648          if ((respid == 200) || ((respid >= 300) && (respid <= 399))) {
20649             extract_uri(p, req);
20650          }
20651          handle_response(p, respid, e + len, req, seqno);
20652       }
20653       return 0;
20654    }
20655 
20656    /* New SIP request coming in 
20657       (could be new request in existing SIP dialog as well...) 
20658     */         
20659    
20660    p->method = req->method;   /* Find out which SIP method they are using */
20661    ast_debug(4, "**** Received %s (%d) - Command in SIP %s\n", sip_methods[p->method].text, sip_methods[p->method].id, cmd); 
20662 
20663    if (p->icseq && (p->icseq > seqno) ) {
20664       if (p->pendinginvite && seqno == p->pendinginvite && (req->method == SIP_ACK || req->method == SIP_CANCEL)) {
20665          ast_debug(2, "Got CANCEL or ACK on INVITE with transactions in between.\n");
20666       }  else {
20667          ast_debug(1, "Ignoring too old SIP packet packet %d (expecting >= %d)\n", seqno, p->icseq);
20668          if (req->method != SIP_ACK)
20669             transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
20670          return -1;
20671       }
20672    } else if (p->icseq &&
20673          p->icseq == seqno &&
20674          req->method != SIP_ACK &&
20675          (p->method != SIP_CANCEL || p->alreadygone)) {
20676       /* ignore means "don't do anything with it" but still have to 
20677          respond appropriately.  We do this if we receive a repeat of
20678          the last sequence number  */
20679       req->ignore = 1;
20680       ast_debug(3, "Ignoring SIP message because of retransmit (%s Seqno %d, ours %d)\n", sip_methods[p->method].text, p->icseq, seqno);
20681    }
20682       
20683    if (seqno >= p->icseq)
20684       /* Next should follow monotonically (but not necessarily 
20685          incrementally -- thanks again to the genius authors of SIP --
20686          increasing */
20687       p->icseq = seqno;
20688 
20689    /* Find their tag if we haven't got it */
20690    if (ast_strlen_zero(p->theirtag)) {
20691       char tag[128];
20692 
20693       gettag(req, "From", tag, sizeof(tag));
20694       ast_string_field_set(p, theirtag, tag);
20695    }
20696    snprintf(p->lastmsg, sizeof(p->lastmsg), "Rx: %s", cmd);
20697 
20698    if (pedanticsipchecking) {
20699       /* If this is a request packet without a from tag, it's not
20700          correct according to RFC 3261  */
20701       /* Check if this a new request in a new dialog with a totag already attached to it,
20702          RFC 3261 - section 12.2 - and we don't want to mess with recovery  */
20703       if (!p->initreq.headers && req->has_to_tag) {
20704          /* If this is a first request and it got a to-tag, it is not for us */
20705          if (!req->ignore && req->method == SIP_INVITE) {
20706             transmit_response_reliable(p, "481 Call/Transaction Does Not Exist", req);
20707             /* Will cease to exist after ACK */
20708          } else if (req->method != SIP_ACK) {
20709             transmit_response(p, "481 Call/Transaction Does Not Exist", req);
20710             sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20711          } else {
20712             ast_debug(1, "Got ACK for unknown dialog... strange.\n");
20713          }
20714          return res;
20715       }
20716    }
20717 
20718    if (!e && (p->method == SIP_INVITE || p->method == SIP_SUBSCRIBE || p->method == SIP_REGISTER || p->method == SIP_NOTIFY)) {
20719       transmit_response(p, "400 Bad request", req);
20720       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
20721       return -1;
20722    }
20723 
20724    /* Handle various incoming SIP methods in requests */
20725    switch (p->method) {
20726    case SIP_OPTIONS:
20727       res = handle_request_options(p, req);
20728       break;
20729    case SIP_INVITE:
20730       res = handle_request_invite(p, req, debug, seqno, sin, recount, e, nounlock);
20731       break;
20732    case SIP_REFER:
20733       res = handle_request_refer(p, req, debug, seqno, nounlock);
20734       break;
20735    case SIP_CANCEL:
20736       res = handle_request_cancel(p, req);
20737       break;
20738    case SIP_BYE:
20739       res = handle_request_bye(p, req);
20740       break;
20741    case SIP_MESSAGE:
20742       res = handle_request_message(p, req);
20743       break;
20744    case SIP_SUBSCRIBE:
20745       res = handle_request_subscribe(p, req, sin, seqno, e);
20746       break;
20747    case SIP_REGISTER:
20748       res = handle_request_register(p, req, sin, e);
20749       break;
20750    case SIP_INFO:
20751       if (req->debug)
20752          ast_verbose("Receiving INFO!\n");
20753       if (!req->ignore) 
20754          handle_request_info(p, req);
20755       else  /* if ignoring, transmit response */
20756          transmit_response(p, "200 OK", req);
20757       break;
20758    case SIP_NOTIFY:
20759       res = handle_request_notify(p, req, sin, seqno, e);
20760       break;
20761    case SIP_ACK:
20762       /* Make sure we don't ignore this */
20763       if (seqno == p->pendinginvite) {
20764          p->invitestate = INV_TERMINATED;
20765          p->pendinginvite = 0;
20766          acked = __sip_ack(p, seqno, 1 /* response */, 0);
20767          if (find_sdp(req)) {
20768             if (process_sdp(p, req, SDP_T38_NONE))
20769                return -1;
20770          }
20771          check_pendings(p);
20772       } else if (p->glareinvite == seqno) {
20773          /* handle ack for the 491 pending sent for glareinvite */
20774          p->glareinvite = 0;
20775          acked = __sip_ack(p, seqno, 1, 0);
20776       }
20777       if (!acked) {
20778          /* Got an ACK that did not match anything. Ignore
20779           * silently and restore previous method */
20780          p->method = oldmethod;
20781       }
20782       if (!p->lastinvite && ast_strlen_zero(p->randdata))
20783          p->needdestroy = 1;
20784       break;
20785    default:
20786       transmit_response_with_allow(p, "501 Method Not Implemented", req, 0);
20787       ast_log(LOG_NOTICE, "Unknown SIP command '%s' from '%s'\n", 
20788          cmd, ast_inet_ntoa(p->sa.sin_addr));
20789       /* If this is some new method, and we don't have a call, destroy it now */
20790       if (!p->initreq.headers)
20791          p->needdestroy = 1;
20792       break;
20793    }
20794    return res;
20795 }
20796 
20797 static void process_request_queue(struct sip_pvt *p, int *recount, int *nounlock)
20798 {
20799    struct sip_request *req;
20800 
20801    while ((req = AST_LIST_REMOVE_HEAD(&p->request_queue, next))) {
20802       if (handle_incoming(p, req, &p->recv, recount, nounlock) == -1) {
20803          /* Request failed */
20804          if (option_debug) {
20805             ast_log(LOG_DEBUG, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
20806          }
20807       }
20808       ast_free(req);
20809    }
20810 }
20811 
20812 static int scheduler_process_request_queue(const void *data)
20813 {
20814    struct sip_pvt *p = (struct sip_pvt *) data;
20815    int recount = 0;
20816    int nounlock = 0;
20817    int lockretry;
20818 
20819    for (lockretry = 10; lockretry > 0; lockretry--) {
20820       sip_pvt_lock(p);
20821 
20822       /* lock the owner if it has one -- we may need it */
20823       /* because this is deadlock-prone, we need to try and unlock if failed */
20824       if (!p->owner || !ast_channel_trylock(p->owner)) {
20825          break;   /* locking succeeded */
20826       }
20827 
20828       if (lockretry != 1) {
20829          sip_pvt_unlock(p);
20830          /* Sleep for a very short amount of time */
20831          usleep(1);
20832       }
20833    }
20834 
20835    if (!lockretry) {
20836       int retry = !AST_LIST_EMPTY(&p->request_queue);
20837 
20838       /* we couldn't get the owner lock, which is needed to process
20839          the queued requests, so return a non-zero value, which will
20840          cause the scheduler to run this request again later if there
20841          still requests to be processed
20842       */
20843       sip_pvt_unlock(p);
20844       if (!retry) {
20845          dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20846       }
20847       return retry;
20848    };
20849 
20850    process_request_queue(p, &recount, &nounlock);
20851    p->request_queue_sched_id = -1;
20852 
20853    if (p->owner && !nounlock) {
20854       ast_channel_unlock(p->owner);
20855    }
20856    sip_pvt_unlock(p);
20857 
20858    if (recount) {
20859       ast_update_use_count();
20860    }
20861 
20862    dialog_unref(p, "The ref to a dialog passed to this sched callback is going out of scope; unref it.");
20863 
20864    return 0;
20865 }
20866 
20867 static int queue_request(struct sip_pvt *p, const struct sip_request *req)
20868 {
20869    struct sip_request *newreq;
20870 
20871    if (!(newreq = ast_calloc(1, sizeof(*newreq)))) {
20872       return -1;
20873    }
20874 
20875    copy_request(newreq, req);
20876    AST_LIST_INSERT_TAIL(&p->request_queue, newreq, next);
20877    if (p->request_queue_sched_id == -1) {
20878       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) {
20879          dialog_unref(p, "Decrement refcount due to sched_add failure");
20880       }
20881    }
20882 
20883    return 0;
20884 }
20885 
20886 /*! \brief Read data from SIP socket
20887 \note sipsock_read locks the owner channel while we are processing the SIP message
20888 \return 1 on error, 0 on success
20889 \note Successful messages is connected to SIP call and forwarded to handle_incoming() 
20890 */
20891 static int sipsock_read(int *id, int fd, short events, void *ignore)
20892 {
20893    struct sip_request req;
20894    struct sockaddr_in sin = { 0, };
20895    int res;
20896    socklen_t len = sizeof(sin);
20897    static char readbuf[65535];
20898 
20899    memset(&req, 0, sizeof(req));
20900    res = recvfrom(fd, readbuf, sizeof(readbuf) - 1, 0, (struct sockaddr *)&sin, &len);
20901    if (res < 0) {
20902 #if !defined(__FreeBSD__)
20903       if (errno == EAGAIN)
20904          ast_log(LOG_NOTICE, "SIP: Received packet with bad UDP checksum\n");
20905       else 
20906 #endif
20907       if (errno != ECONNREFUSED)
20908          ast_log(LOG_WARNING, "Recv error: %s\n", strerror(errno));
20909       return 1;
20910    }
20911 
20912    readbuf[res] = '\0';
20913 
20914    if (!(req.data = ast_str_create(SIP_MIN_PACKET))) {
20915       return 1;
20916    }
20917 
20918    if (ast_str_set(&req.data, 0, "%s", readbuf) == AST_DYNSTR_BUILD_FAILED) {
20919       return -1;
20920    }
20921 
20922    req.len = res;
20923    req.socket.fd = sipsock;
20924    set_socket_transport(&req.socket, SIP_TRANSPORT_UDP);
20925    req.socket.tcptls_session  = NULL;
20926    req.socket.port = bindaddr.sin_port;
20927 
20928    handle_request_do(&req, &sin);
20929    if (req.data) {
20930       ast_free(req.data);
20931       req.data = NULL;
20932    }
20933 
20934    return 1;
20935 }
20936 
20937 static int handle_request_do(struct sip_request *req, struct sockaddr_in *sin) 
20938 {
20939    struct sip_pvt *p;
20940    int recount = 0;
20941    int nounlock = 0;
20942    int lockretry;
20943 
20944    if (sip_debug_test_addr(sin)) /* Set the debug flag early on packet level */
20945       req->debug = 1;
20946    if (pedanticsipchecking)
20947       req->len = lws2sws(req->data->str, req->len);   /* Fix multiline headers */
20948    if (req->debug) {
20949       ast_verbose("\n<--- SIP read from %s://%s:%d --->\n%s\n<------------->\n", 
20950          get_transport(req->socket.type), ast_inet_ntoa(sin->sin_addr), 
20951          ntohs(sin->sin_port), req->data->str);
20952    }
20953 
20954    if (parse_request(req) == -1) { /* Bad packet, can't parse */
20955       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
20956       return 1;
20957    }
20958    req->method = find_sip_method(REQ_OFFSET_TO_STR(req, rlPart1));
20959 
20960    if (req->debug)
20961       ast_verbose("--- (%d headers %d lines)%s ---\n", req->headers, req->lines, (req->headers + req->lines == 0) ? " Nat keepalive" : "");
20962 
20963    if (req->headers < 2) { /* Must have at least two headers */
20964       ast_str_reset(req->data); /* nulling this out is NOT a good idea here. */
20965       return 1;
20966    }
20967 
20968    /* Process request, with netlock held, and with usual deadlock avoidance */
20969    for (lockretry = 10; lockretry > 0; lockretry--) {
20970       ast_mutex_lock(&netlock);
20971 
20972       /* Find the active SIP dialog or create a new one */
20973       p = find_call(req, sin, req->method);  /* returns p locked */
20974       if (p == NULL) {
20975          ast_debug(1, "Invalid SIP message - rejected , no callid, len %d\n", req->len);
20976          ast_mutex_unlock(&netlock);
20977          return 1;
20978       }
20979 
20980       copy_socket_data(&p->socket, &req->socket);
20981 
20982       /* Go ahead and lock the owner if it has one -- we may need it */
20983       /* becaues this is deadlock-prone, we need to try and unlock if failed */
20984       if (!p->owner || !ast_channel_trylock(p->owner))
20985          break;   /* locking succeeded */
20986 
20987       if (lockretry != 1) {
20988          sip_pvt_unlock(p);
20989          ao2_t_ref(p, -1, "release p (from find_call) inside lockretry loop"); /* we'll look for it again, but p is dead now */
20990          ast_mutex_unlock(&netlock);
20991          /* Sleep for a very short amount of time */
20992          usleep(1);
20993       }
20994    }
20995    p->recv = *sin;
20996 
20997    if (p->do_history) /* This is a request or response, note what it was for */
20998       append_history(p, "Rx", "%s / %s / %s", req->data->str, get_header(req, "CSeq"), REQ_OFFSET_TO_STR(req, rlPart2));
20999 
21000    if (!lockretry) {
21001       if (!queue_request(p, req)) {
21002          /* the request has been queued for later handling */
21003          sip_pvt_unlock(p);
21004          ao2_t_ref(p, -1, "release p (from find_call) after queueing request");
21005          ast_mutex_unlock(&netlock);
21006          return 1;
21007       }
21008 
21009       if (p->owner)
21010          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 ??? - "));
21011       ast_log(LOG_ERROR, "SIP transaction failed: %s \n", p->callid);
21012       if (req->method != SIP_ACK)
21013          transmit_response(p, "503 Server error", req);  /* We must respond according to RFC 3261 sec 12.2 */
21014       /* XXX We could add retry-after to make sure they come back */
21015       append_history(p, "LockFail", "Owner lock failed, transaction failed.");
21016       sip_pvt_unlock(p);
21017       ao2_t_ref(p, -1, "release p (from find_call) at end of lockretry"); /* p is gone after the return */
21018       ast_mutex_unlock(&netlock);
21019       return 1;
21020    }
21021 
21022    /* if there are queued requests on this sip_pvt, process them first, so that everything is
21023       handled in order
21024    */
21025    if (!AST_LIST_EMPTY(&p->request_queue)) {
21026       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"));
21027       process_request_queue(p, &recount, &nounlock);
21028    }
21029 
21030    if (handle_incoming(p, req, sin, &recount, &nounlock) == -1) {
21031       /* Request failed */
21032       ast_debug(1, "SIP message could not be handled, bad request: %-70.70s\n", p->callid[0] ? p->callid : "<no callid>");
21033    }
21034       
21035    if (recount)
21036       ast_update_use_count();
21037 
21038    if (p->owner && !nounlock)
21039       ast_channel_unlock(p->owner);
21040    sip_pvt_unlock(p);
21041    ast_mutex_unlock(&netlock);
21042    ao2_t_ref(p, -1, "throw away dialog ptr from find_call at end of routine"); /* p is gone after the return */
21043    return 1;
21044 }
21045 
21046 /*! \brief Returns the port to use for this socket
21047  *
21048  * \param type The type of transport used
21049  * \param port Port we are checking to see if it's the standard port.
21050  * \note port is expected in host byte order
21051  */
21052 static int sip_standard_port(enum sip_transport type, int port)
21053 {
21054    if (type & SIP_TRANSPORT_TLS)
21055       return port == STANDARD_TLS_PORT;
21056    else
21057       return port == STANDARD_SIP_PORT;
21058 }
21059 
21060 static int threadinfo_locate_cb(void *obj, void *arg, int flags)
21061 {
21062    struct sip_threadinfo *th = obj;
21063    struct sockaddr_in *s = arg;
21064 
21065    if (!inaddrcmp(&th->tcptls_session->remote_address, s)) {
21066       return CMP_MATCH | CMP_STOP;
21067    }
21068 
21069    return 0;
21070 }
21071 
21072 /*! 
21073  * \brief Find thread for TCP/TLS session (based on IP/Port 
21074  *
21075  * \note This function returns an astobj2 reference
21076  */
21077 static struct ast_tcptls_session_instance *sip_tcp_locate(struct sockaddr_in *s)
21078 {
21079    struct sip_threadinfo *th;
21080    struct ast_tcptls_session_instance *tcptls_instance = NULL;
21081 
21082    if ((th = ao2_callback(threadt, 0, threadinfo_locate_cb, s))) {
21083       tcptls_instance = (ao2_ref(th->tcptls_session, +1), th->tcptls_session);
21084       ao2_t_ref(th, -1, "decrement ref from callback");
21085    }
21086    return tcptls_instance;
21087 }
21088 
21089 /*! \todo document this function. */
21090 static int sip_prepare_socket(struct sip_pvt *p) 
21091 {
21092    struct sip_socket *s = &p->socket;
21093    static const char name[] = "SIP socket";
21094    struct sip_threadinfo *th = NULL;
21095    struct ast_tcptls_session_instance *tcptls_session;
21096    struct ast_tcptls_session_args tmp_ca = {
21097       .name = name,
21098       .accept_fd = -1,
21099    };
21100    struct ast_tcptls_session_args *ca;
21101 
21102    /* check to see if a socket is already active */
21103    if ((s->fd != -1) && (s->type == SIP_TRANSPORT_UDP)) {
21104       return s->fd;
21105    }
21106    if ((s->type & (SIP_TRANSPORT_TCP | SIP_TRANSPORT_TLS)) &&
21107          (s->tcptls_session) &&
21108          (s->tcptls_session->fd != -1)) {
21109       return s->tcptls_session->fd;
21110    }
21111 
21112    if (p->outboundproxy && p->outboundproxy->transport) {
21113       s->type = p->outboundproxy->transport;
21114    }
21115 
21116    if (s->type == SIP_TRANSPORT_UDP) {
21117       s->fd = sipsock;
21118       return s->fd;
21119    }
21120 
21121    /* At this point we are dealing with a TCP/TLS connection
21122     * 1. We need to check to see if a connectin thread exists
21123     *    for this address, if so use that.
21124     * 2. If a thread does not exist for this address, but the tcptls_session
21125     *    exists on the socket, the connection was closed.
21126     * 3. If no tcptls_session thread exists for the address, and no tcptls_session
21127     *    already exists on the socket, create a new one and launch a new thread.
21128     */
21129 
21130    /* 1.  check for existing threads */
21131    tmp_ca.remote_address = *(sip_real_dst(p));
21132    if ((tcptls_session = sip_tcp_locate(&tmp_ca.remote_address))) {
21133       s->fd = tcptls_session->fd;
21134       if (s->tcptls_session) {
21135          ao2_ref(s->tcptls_session, -1);
21136          s->tcptls_session = NULL;
21137       }
21138       s->tcptls_session = tcptls_session;
21139       return s->fd;
21140    /* 2.  Thread not found, if tcptls_session already exists, it once had a thread and is now terminated */
21141    } else if (s->tcptls_session) {
21142       return s->fd; /* XXX whether reconnection is ever necessary here needs to be investigated further */
21143    }
21144 
21145    /* 3.  Create a new TCP/TLS client connection */
21146    /* create new session arguments for the client connection */
21147    if (!(ca = ao2_alloc(sizeof(*ca), sip_tcptls_client_args_destructor)) ||
21148       !(ca->name = ast_strdup(name))) {
21149       goto create_tcptls_session_fail;
21150    }
21151    ca->accept_fd = -1;
21152    ca->remote_address = *(sip_real_dst(p));
21153    /* if type is TLS, we need to create a tls cfg for this session arg */
21154    if (s->type == SIP_TRANSPORT_TLS) {
21155       if (!(ca->tls_cfg = ast_calloc(1, sizeof(*ca->tls_cfg)))) {
21156          goto create_tcptls_session_fail;
21157       }
21158       memcpy(ca->tls_cfg, &default_tls_cfg, sizeof(*ca->tls_cfg));
21159 
21160       if (!(ca->tls_cfg->certfile = ast_strdup(default_tls_cfg.certfile)) ||
21161          !(ca->tls_cfg->cipher = ast_strdup(default_tls_cfg.cipher)) ||
21162          !(ca->tls_cfg->cafile = ast_strdup(default_tls_cfg.cafile)) ||
21163          !(ca->tls_cfg->capath = ast_strdup(default_tls_cfg.capath))) {
21164 
21165          goto create_tcptls_session_fail;
21166       }
21167 
21168       /* this host is used as the common name in ssl/tls */
21169       if (!ast_strlen_zero(p->tohost)) {
21170          ast_copy_string(ca->hostname, p->tohost, sizeof(ca->hostname));
21171       }
21172    }
21173    /* Create a client connection for address, this does not start the connection, just sets it up. */
21174    if (!(s->tcptls_session = ast_tcptls_client_create(ca))) {
21175       goto create_tcptls_session_fail;
21176    }
21177 
21178    s->fd = s->tcptls_session->fd;
21179 
21180    /* client connections need to have the sip_threadinfo object created before
21181     * the thread is detached.  This ensures the alert_pipe is up before it will
21182     * be used.  Note that this function links the new threadinfo object into the
21183     * threadt container. */
21184    if (!(th = sip_threadinfo_create(s->tcptls_session, s->type))) {
21185       goto create_tcptls_session_fail;
21186 
21187    }
21188 
21189    /* Give the new thread a reference to the tcptls_session */
21190    ao2_ref(s->tcptls_session, +1);
21191 
21192    if (ast_pthread_create_background(&ca->master, NULL, sip_tcp_worker_fn, s->tcptls_session)) {
21193       ast_debug(1, "Unable to launch '%s'.", ca->name);
21194       ao2_ref(s->tcptls_session, -1); /* take away the thread ref we just gave it */
21195       goto create_tcptls_session_fail;
21196    }
21197 
21198    return s->fd;
21199 
21200 create_tcptls_session_fail:
21201    if (ca) {
21202       ao2_t_ref(ca, -1, "failed to create client, getting rid of client tcptls_session arguments");
21203    }
21204    if (s->tcptls_session) {
21205       close(tcptls_session->fd);
21206       s->fd = tcptls_session->fd = -1;
21207       ao2_ref(s->tcptls_session, -1);
21208       s->tcptls_session = NULL;
21209    }
21210    if (th) {
21211       ao2_t_unlink(threadt, th, "Removing tcptls thread info object, thread failed to open");
21212    }
21213 
21214    return -1;
21215 }
21216 
21217 /*!
21218  * \brief Small function to parse a config line for a host with a transport
21219  *        i.e. tls://www.google.com:8056
21220  */
21221 static int sip_parse_host(char *line, int lineno, char **hostname, int *portnum, enum sip_transport *transport)
21222 {
21223    char *port;
21224 
21225    if ((*hostname = strstr(line, "://"))) {
21226       *hostname += 3;
21227 
21228       if (!strncasecmp(line, "tcp", 3))
21229          *transport = SIP_TRANSPORT_TCP;
21230       else if (!strncasecmp(line, "tls", 3))
21231          *transport = SIP_TRANSPORT_TLS;
21232       else if (!strncasecmp(line, "udp", 3))
21233          *transport = SIP_TRANSPORT_UDP;
21234       else
21235          ast_log(LOG_NOTICE, "'%.3s' is not a valid transport type on line %d of sip.conf. defaulting to udp.\n", line, lineno);
21236    } else {
21237       *hostname = line;
21238       *transport = SIP_TRANSPORT_UDP;
21239    }
21240 
21241    if ((line = strrchr(*hostname, '@')))
21242       line++;
21243    else
21244       line = *hostname;
21245 
21246    if ((port = strrchr(line, ':'))) {
21247       *port++ = '\0';
21248 
21249       if (!sscanf(port, "%5u", portnum)) {
21250          ast_log(LOG_NOTICE, "'%s' is not a valid port number on line %d of sip.conf. using default.\n", port, lineno);
21251          port = NULL;
21252       }
21253    }
21254 
21255    if (!port) {
21256       if (*transport & SIP_TRANSPORT_TLS) {
21257          *portnum = STANDARD_TLS_PORT;
21258       } else {
21259          *portnum = STANDARD_SIP_PORT;
21260       }
21261    }
21262 
21263    return 0;
21264 }
21265 
21266 /*!
21267  * \brief Get cached MWI info
21268  * \retval 0 At least one message is waiting
21269  * \retval 1 no messages waiting
21270  */
21271 static int get_cached_mwi(struct sip_peer *peer, int *new, int *old)
21272 {
21273    struct sip_mailbox *mailbox;
21274 
21275    AST_LIST_TRAVERSE(&peer->mailboxes, mailbox, entry) {
21276       struct ast_event *event;
21277       event = ast_event_get_cached(AST_EVENT_MWI,
21278          AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox->mailbox,
21279          AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, S_OR(mailbox->context, "default"),
21280          AST_EVENT_IE_END);
21281       if (!event)
21282          continue;
21283       *new += ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
21284       *old += ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
21285       ast_event_destroy(event);
21286    }
21287 
21288    return (*new || *old) ? 0 : 1;
21289 }
21290 
21291 /*! \brief Send message waiting indication to alert peer that they've got voicemail */
21292 static int sip_send_mwi_to_peer(struct sip_peer *peer, const struct ast_event *event, int cache_only)
21293 {
21294    /* Called with peerl lock, but releases it */
21295    struct sip_pvt *p;
21296    int newmsgs = 0, oldmsgs = 0;
21297 
21298    if (ast_test_flag((&peer->flags[1]), SIP_PAGE2_SUBSCRIBEMWIONLY) && !peer->mwipvt)
21299       return 0;
21300 
21301    /* Do we have an IP address? If not, skip this peer */
21302    if (!peer->addr.sin_addr.s_addr && !peer->defaddr.sin_addr.s_addr) 
21303       return 0;
21304 
21305    if (event) {
21306       newmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
21307       oldmsgs = ast_event_get_ie_uint(event, AST_EVENT_IE_OLDMSGS);
21308    } else if (!get_cached_mwi(peer, &newmsgs, &oldmsgs)) {
21309       /* got it!  Don't keep looking. */
21310    } else if (cache_only) {
21311       return 0;
21312    } else { /* Fall back to manually checking the mailbox */
21313       struct ast_str *mailbox_str = ast_str_alloca(512);
21314       peer_mailboxes_to_str(&mailbox_str, peer);
21315       ast_app_inboxcount(mailbox_str->str, &newmsgs, &oldmsgs);
21316    }
21317    
21318    if (peer->mwipvt) {
21319       /* Base message on subscription */
21320       p = dialog_ref(peer->mwipvt, "sip_send_mwi_to_peer: Setting dialog ptr p from peer->mwipvt-- should this be done?");
21321    } else {
21322       /* Build temporary dialog for this message */
21323       if (!(p = sip_alloc(NULL, NULL, 0, SIP_NOTIFY, NULL))) 
21324          return -1;
21325       /* If we don't set the socket type to 0, then create_addr_from_peer will fail immediately if the peer
21326        * uses any transport other than UDP. We set the type to 0 here and then let create_addr_from_peer copy 
21327        * the peer's socket information to the sip_pvt we just allocated
21328        */
21329       set_socket_transport(&p->socket, 0);
21330       if (create_addr_from_peer(p, peer)) {
21331          /* Maybe they're not registered, etc. */
21332          dialog_unlink_all(p, TRUE, TRUE);
21333          dialog_unref(p, "unref dialog p just created via sip_alloc");
21334          /* sip_destroy(p); */
21335          return 0;
21336       }
21337       /* Recalculate our side, and recalculate Call ID */
21338       ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21339       build_via(p);
21340       ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21341       build_callid_pvt(p);
21342       ao2_t_link(dialogs, p, "Linking in under new name");
21343       /* Destroy this session after 32 secs */
21344       sip_scheddestroy(p, DEFAULT_TRANS_TIMEOUT);
21345    }
21346 
21347    /* Send MWI */
21348    ast_set_flag(&p->flags[0], SIP_OUTGOING);
21349    /* the following will decrement the refcount on p as it finishes */
21350    transmit_notify_with_mwi(p, newmsgs, oldmsgs, peer->vmexten);
21351    dialog_unref(p, "unref dialog ptr p just before it goes out of scope at the end of sip_send_mwi_to_peer.");
21352    return 0;
21353 }
21354 
21355 /*! \brief helper function for the monitoring thread -- seems to be called with the assumption that the dialog is locked */
21356 static void check_rtp_timeout(struct sip_pvt *dialog, time_t t)
21357 {
21358    /* If we have no RTP or no active owner, no need to check timers */
21359    if (!dialog->rtp || !dialog->owner)
21360       return;
21361    /* If the call is not in UP state or redirected outside Asterisk, no need to check timers */
21362 
21363    if (dialog->owner->_state != AST_STATE_UP || dialog->redirip.sin_addr.s_addr)
21364       return;
21365 
21366    /* If the call is involved in a T38 fax session do not check RTP timeout */
21367    if (dialog->t38.state == T38_ENABLED)
21368       return;
21369 
21370    /* If we have no timers set, return now */
21371    if ((ast_rtp_get_rtpkeepalive(dialog->rtp) == 0) && (ast_rtp_get_rtptimeout(dialog->rtp) == 0) && (ast_rtp_get_rtpholdtimeout(dialog->rtp) == 0))
21372       return;
21373 
21374    /* Check AUDIO RTP keepalives */
21375    if (dialog->lastrtptx && ast_rtp_get_rtpkeepalive(dialog->rtp) &&
21376           (t > dialog->lastrtptx + ast_rtp_get_rtpkeepalive(dialog->rtp))) {
21377       /* Need to send an empty RTP packet */
21378       dialog->lastrtptx = time(NULL);
21379       ast_rtp_sendcng(dialog->rtp, 0);
21380    }
21381 
21382    /*! \todo Check video RTP keepalives
21383 
21384       Do we need to move the lastrtptx to the RTP structure to have one for audio and one
21385       for video? It really does belong to the RTP structure.
21386    */
21387 
21388    /* Check AUDIO RTP timers */
21389    if (dialog->lastrtprx && (ast_rtp_get_rtptimeout(dialog->rtp) || ast_rtp_get_rtpholdtimeout(dialog->rtp)) &&
21390           (t > dialog->lastrtprx + ast_rtp_get_rtptimeout(dialog->rtp))) {
21391 
21392       /* Might be a timeout now -- see if we're on hold */
21393       struct sockaddr_in sin;
21394       ast_rtp_get_peer(dialog->rtp, &sin);
21395       if (!ast_test_flag(&dialog->flags[1], SIP_PAGE2_CALL_ONHOLD) || (ast_rtp_get_rtpholdtimeout(dialog->rtp) &&
21396            (t > dialog->lastrtprx + ast_rtp_get_rtpholdtimeout(dialog->rtp)))) {
21397          /* Needs a hangup */
21398          if (ast_rtp_get_rtptimeout(dialog->rtp)) {
21399             while (dialog->owner && ast_channel_trylock(dialog->owner)) {
21400                sip_pvt_unlock(dialog);
21401                usleep(1);
21402                sip_pvt_lock(dialog);
21403             }
21404             ast_log(LOG_NOTICE, "Disconnecting call '%s' for lack of RTP activity in %ld seconds\n",
21405                dialog->owner->name, (long) (t - dialog->lastrtprx));
21406             /* Issue a softhangup */
21407             ast_softhangup_nolock(dialog->owner, AST_SOFTHANGUP_DEV);
21408             ast_channel_unlock(dialog->owner);
21409             /* forget the timeouts for this call, since a hangup
21410                has already been requested and we don't want to
21411                repeatedly request hangups
21412             */
21413             ast_rtp_set_rtptimeout(dialog->rtp, 0);
21414             ast_rtp_set_rtpholdtimeout(dialog->rtp, 0);
21415             if (dialog->vrtp) {
21416                ast_rtp_set_rtptimeout(dialog->vrtp, 0);
21417                ast_rtp_set_rtpholdtimeout(dialog->vrtp, 0);
21418             }
21419          }
21420       }
21421    }
21422 }
21423 
21424 /*! \brief The SIP monitoring thread 
21425 \note This thread monitors all the SIP sessions and peers that needs notification of mwi
21426    (and thus do not have a separate thread) indefinitely 
21427 */
21428 static void *do_monitor(void *data)
21429 {
21430    int res;
21431    time_t t;
21432    int reloading;
21433 
21434    /* Add an I/O event to our SIP UDP socket */
21435    if (sipsock > -1) 
21436       sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
21437 
21438    /* From here on out, we die whenever asked */
21439    for(;;) {
21440       /* Check for a reload request */
21441       ast_mutex_lock(&sip_reload_lock);
21442       reloading = sip_reloading;
21443       sip_reloading = FALSE;
21444       ast_mutex_unlock(&sip_reload_lock);
21445       if (reloading) {
21446          ast_verb(1, "Reloading SIP\n");
21447          sip_do_reload(sip_reloadreason);
21448 
21449          /* Change the I/O fd of our UDP socket */
21450          if (sipsock > -1) {
21451             if (sipsock_read_id)
21452                sipsock_read_id = ast_io_change(io, sipsock_read_id, sipsock, NULL, 0, NULL);
21453             else
21454                sipsock_read_id = ast_io_add(io, sipsock, sipsock_read, AST_IO_IN, NULL);
21455          } else if (sipsock_read_id) {
21456             ast_io_remove(io, sipsock_read_id);
21457             sipsock_read_id = NULL;
21458          }
21459       }
21460 
21461       /* Check for dialogs needing to be killed */
21462       t = time(NULL);
21463       /* don't scan the dialogs list if it hasn't been a reasonable period
21464          of time since the last time we did it (when MWI is being sent, we can
21465          get back to this point every millisecond or less)
21466       */
21467       ao2_t_callback(dialogs, OBJ_UNLINK | OBJ_NODATA | OBJ_MULTIPLE, dialog_needdestroy, &t, 
21468             "callback to remove dialogs w/needdestroy");
21469 
21470       /* the old methodology would be to restart the search for dialogs to delete with every 
21471          dialog that was found and destroyed, probably because the list contents would change,
21472          so we'd need to restart. This isn't the best thing to do with callbacks. */
21473 
21474       /* XXX TODO The scheduler usage in this module does not have sufficient 
21475        * synchronization being done between running the scheduler and places 
21476        * scheduling tasks.  As it is written, any scheduled item may not run 
21477        * any sooner than about  1 second, regardless of whether a sooner time 
21478        * was asked for. */
21479 
21480       pthread_testcancel();
21481       /* Wait for sched or io */
21482       res = ast_sched_wait(sched);
21483       if ((res < 0) || (res > 1000))
21484          res = 1000;
21485       res = ast_io_wait(io, res);
21486       if (res > 20)
21487          ast_debug(1, "chan_sip: ast_io_wait ran %d all at once\n", res);
21488       ast_mutex_lock(&monlock);
21489       res = ast_sched_runq(sched);
21490       if (res >= 20)
21491          ast_debug(1, "chan_sip: ast_sched_runq ran %d all at once\n", res);
21492       ast_mutex_unlock(&monlock);
21493    }
21494 
21495    /* Never reached */
21496    return NULL;
21497 }
21498 
21499 /*! \brief Start the channel monitor thread */
21500 static int restart_monitor(void)
21501 {
21502    /* If we're supposed to be stopped -- stay stopped */
21503    if (monitor_thread == AST_PTHREADT_STOP)
21504       return 0;
21505    ast_mutex_lock(&monlock);
21506    if (monitor_thread == pthread_self()) {
21507       ast_mutex_unlock(&monlock);
21508       ast_log(LOG_WARNING, "Cannot kill myself\n");
21509       return -1;
21510    }
21511    if (monitor_thread != AST_PTHREADT_NULL) {
21512       /* Wake up the thread */
21513       pthread_kill(monitor_thread, SIGURG);
21514    } else {
21515       /* Start a new monitor */
21516       if (ast_pthread_create_background(&monitor_thread, NULL, do_monitor, NULL) < 0) {
21517          ast_mutex_unlock(&monlock);
21518          ast_log(LOG_ERROR, "Unable to start monitor thread.\n");
21519          return -1;
21520       }
21521    }
21522    ast_mutex_unlock(&monlock);
21523    return 0;
21524 }
21525 
21526 
21527 /*! \brief Session-Timers: Restart session timer */
21528 static void restart_session_timer(struct sip_pvt *p)
21529 {
21530    if (!p->stimer) {
21531       ast_log(LOG_WARNING, "Null stimer in restart_session_timer - %s\n", p->callid);
21532       return;
21533    }
21534 
21535    if (p->stimer->st_active == TRUE) {
21536       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
21537             dialog_unref(p, "Removing session timer ref"));
21538       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
21539       start_session_timer(p);
21540    }
21541 }
21542 
21543 
21544 /*! \brief Session-Timers: Stop session timer */
21545 static void stop_session_timer(struct sip_pvt *p)
21546 {
21547    if (!p->stimer) {
21548       ast_log(LOG_WARNING, "Null stimer in stop_session_timer - %s\n", p->callid);
21549       return;
21550    }
21551 
21552    if (p->stimer->st_active == TRUE) {
21553       p->stimer->st_active = FALSE;
21554       AST_SCHED_DEL_UNREF(sched, p->stimer->st_schedid,
21555             dialog_unref(p, "removing session timer ref"));
21556       ast_debug(2, "Session timer stopped: %d - %s\n", p->stimer->st_schedid, p->callid);
21557    }
21558 }
21559 
21560 
21561 /*! \brief Session-Timers: Start session timer */
21562 static void start_session_timer(struct sip_pvt *p)
21563 {
21564    if (!p->stimer) {
21565       ast_log(LOG_WARNING, "Null stimer in start_session_timer - %s\n", p->callid);
21566       return;
21567    }
21568 
21569    p->stimer->st_schedid  = ast_sched_add(sched, p->stimer->st_interval * 1000 / 2, proc_session_timer, 
21570          dialog_ref(p, "adding session timer ref"));
21571    if (p->stimer->st_schedid < 0) {
21572       dialog_unref(p, "removing session timer ref");
21573       ast_log(LOG_ERROR, "ast_sched_add failed.\n");
21574    }
21575    ast_debug(2, "Session timer started: %d - %s\n", p->stimer->st_schedid, p->callid);
21576 }
21577 
21578 
21579 /*! \brief Session-Timers: Process session refresh timeout event */
21580 static int proc_session_timer(const void *vp)
21581 {
21582    struct sip_pvt *p = (struct sip_pvt *) vp;
21583    int sendreinv = FALSE;
21584    int res = 0;
21585 
21586    if (!p->stimer) {
21587       ast_log(LOG_WARNING, "Null stimer in proc_session_timer - %s\n", p->callid);
21588       goto return_unref;
21589    }
21590 
21591    ast_debug(2, "Session timer expired: %d - %s\n", p->stimer->st_schedid, p->callid);
21592 
21593    if (!p->owner) {
21594       goto return_unref;
21595    }
21596 
21597    if ((p->stimer->st_active != TRUE) || (p->owner->_state != AST_STATE_UP)) {
21598       goto return_unref;
21599    }
21600 
21601    switch (p->stimer->st_ref) {
21602    case SESSION_TIMER_REFRESHER_UAC:
21603       if (p->outgoing_call == TRUE) {
21604          sendreinv = TRUE;
21605       }
21606       break;
21607    case SESSION_TIMER_REFRESHER_UAS:
21608       if (p->outgoing_call != TRUE) {
21609          sendreinv = TRUE;
21610       }
21611       break;
21612    default:
21613       ast_log(LOG_ERROR, "Unknown session refresher %d\n", p->stimer->st_ref);
21614       goto return_unref;
21615    }
21616 
21617    if (sendreinv == TRUE) {
21618       res = 1;
21619       transmit_reinvite_with_sdp(p, FALSE, TRUE);
21620    } else {
21621       p->stimer->st_expirys++;
21622       if (p->stimer->st_expirys >= 2) {
21623          if (p->stimer->quit_flag) {
21624             goto return_unref;
21625          }
21626          ast_log(LOG_WARNING, "Session-Timer expired - %s\n", p->callid);
21627          sip_pvt_lock(p);
21628          while (p->owner && ast_channel_trylock(p->owner)) {
21629             sip_pvt_unlock(p);
21630             usleep(1);
21631             if (p->stimer && p->stimer->quit_flag) {
21632                goto return_unref;
21633             }
21634             sip_pvt_lock(p);
21635          }
21636 
21637          ast_softhangup_nolock(p->owner, AST_SOFTHANGUP_DEV);
21638          ast_channel_unlock(p->owner);
21639          sip_pvt_unlock(p);
21640       }
21641    }
21642 
21643 return_unref:
21644    if (!res) {
21645       /* An error occurred.  Stop session timer processing */
21646       if (p->stimer) {
21647          p->stimer->st_schedid = -1;
21648          stop_session_timer(p);
21649       }
21650 
21651       /* If we are not asking to be rescheduled, then we need to release our
21652        * reference to the dialog. */
21653       dialog_unref(p, "removing session timer ref");
21654    }
21655 
21656    return res;
21657 }
21658 
21659 
21660 /*! \brief Session-Timers: Function for parsing Min-SE header */
21661 int parse_minse (const char *p_hdrval, int *const p_interval)
21662 {
21663    if (ast_strlen_zero(p_hdrval)) {
21664       ast_log(LOG_WARNING, "Null Min-SE header\n");
21665       return -1;
21666    }
21667 
21668    *p_interval = 0;
21669    p_hdrval = ast_skip_blanks(p_hdrval);
21670    if (!sscanf(p_hdrval, "%30d", p_interval)) {
21671       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21672       return -1;
21673    }
21674 
21675    ast_debug(2, "Received Min-SE: %d\n", *p_interval);
21676    return 0;
21677 }
21678 
21679 
21680 /*! \brief Session-Timers: Function for parsing Session-Expires header */
21681 int parse_session_expires(const char *p_hdrval, int *const p_interval, enum st_refresher *const p_ref)
21682 {
21683    char *p_token;
21684    int  ref_idx;
21685    char *p_se_hdr;
21686 
21687    if (ast_strlen_zero(p_hdrval)) {
21688       ast_log(LOG_WARNING, "Null Session-Expires header\n");
21689       return -1;
21690    }
21691 
21692    *p_ref = SESSION_TIMER_REFRESHER_AUTO;
21693    *p_interval = 0;
21694 
21695    p_se_hdr = ast_strdupa(p_hdrval);
21696    p_se_hdr = ast_skip_blanks(p_se_hdr);
21697 
21698    while ((p_token = strsep(&p_se_hdr, ";"))) {
21699       p_token = ast_skip_blanks(p_token);
21700       if (!sscanf(p_token, "%30d", p_interval)) {
21701          ast_log(LOG_WARNING, "Parsing of Session-Expires failed\n");
21702          return -1;
21703       }
21704 
21705       ast_debug(2, "Session-Expires: %d\n", *p_interval);
21706 
21707       if (!p_se_hdr)
21708          continue;
21709 
21710       p_se_hdr = ast_skip_blanks(p_se_hdr);
21711       ref_idx = strlen("refresher=");
21712       if (!strncasecmp(p_se_hdr, "refresher=", ref_idx)) {
21713          p_se_hdr += ref_idx;
21714          p_se_hdr = ast_skip_blanks(p_se_hdr);
21715 
21716          if (!strncasecmp(p_se_hdr, "uac", strlen("uac"))) {
21717             *p_ref = SESSION_TIMER_REFRESHER_UAC;
21718             ast_debug(2, "Refresher: UAC\n");
21719          } else if (!strncasecmp(p_se_hdr, "uas", strlen("uas"))) {
21720             *p_ref = SESSION_TIMER_REFRESHER_UAS;
21721             ast_debug(2, "Refresher: UAS\n");
21722          } else {
21723             ast_log(LOG_WARNING, "Invalid refresher value %s\n", p_se_hdr);
21724             return -1;
21725          }
21726          break;
21727       }
21728    }
21729    return 0;
21730 }
21731 
21732 
21733 /*! \brief Handle 422 response to INVITE with session-timer requested
21734 
21735    Session-Timers:   An INVITE originated by Asterisk that asks for session-timers support
21736    from the UAS can result into a 422 response. This is how a UAS or an intermediary proxy 
21737    server tells Asterisk that the session refresh interval offered by Asterisk is too low 
21738    for them.  The proc_422_rsp() function handles a 422 response.  It extracts the Min-SE 
21739    header that comes back in 422 and sends a new INVITE accordingly. */
21740 static void proc_422_rsp(struct sip_pvt *p, struct sip_request *rsp)
21741 {
21742    int rtn;
21743    const char *p_hdrval;
21744    int minse;
21745 
21746    p_hdrval = get_header(rsp, "Min-SE");
21747    if (ast_strlen_zero(p_hdrval)) {
21748       ast_log(LOG_WARNING, "422 response without a Min-SE header %s\n", p_hdrval);
21749       return;
21750    }
21751    rtn = parse_minse(p_hdrval, &minse);
21752    if (rtn != 0) {
21753       ast_log(LOG_WARNING, "Parsing of Min-SE header failed %s\n", p_hdrval);
21754       return;
21755    }
21756    p->stimer->st_interval = minse;
21757    transmit_invite(p, SIP_INVITE, 1, 2); 
21758 }
21759 
21760 
21761 /*! \brief Get Max or Min SE (session timer expiry)
21762  * \param p pointer to the SIP dialog 
21763  * \param max if true, get max se, otherwise min se
21764 */
21765 int st_get_se(struct sip_pvt *p, int max)
21766 {
21767    if (max == TRUE) {
21768       if (p->stimer->st_cached_max_se) {
21769          return p->stimer->st_cached_max_se;
21770       } else if (p->peername) {
21771          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21772          if (pp) {
21773             p->stimer->st_cached_max_se = pp->stimer.st_max_se;
21774             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se");
21775             return (p->stimer->st_cached_max_se);
21776          }
21777       }
21778       p->stimer->st_cached_max_se = global_max_se;
21779       return (p->stimer->st_cached_max_se);
21780    } else {
21781       if (p->stimer->st_cached_min_se) {
21782          return p->stimer->st_cached_min_se;
21783       } else if (p->peername) {
21784          struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21785          if (pp) {
21786             p->stimer->st_cached_min_se = pp->stimer.st_min_se;
21787             unref_peer(pp, "unref peer pointer from find_peer call in st_get_se (2)");
21788             return (p->stimer->st_cached_min_se);
21789          }
21790       }
21791       p->stimer->st_cached_min_se = global_min_se;
21792       return (p->stimer->st_cached_min_se);
21793    }
21794 }
21795 
21796 
21797 /*! \brief Get the entity (UAC or UAS) that's acting as the session-timer refresher 
21798  * \param p pointer to the SIP dialog 
21799 */
21800 enum st_refresher st_get_refresher(struct sip_pvt *p)
21801 {
21802    if (p->stimer->st_cached_ref != SESSION_TIMER_REFRESHER_AUTO) 
21803       return p->stimer->st_cached_ref;
21804 
21805    if (p->peername) {
21806       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21807       if (pp) {
21808          p->stimer->st_cached_ref = pp->stimer.st_ref;
21809          unref_peer(pp, "unref peer pointer from find_peer call in st_get_refresher");
21810          return pp->stimer.st_ref;
21811       }
21812    }
21813    
21814    p->stimer->st_cached_ref = global_st_refresher;
21815    return global_st_refresher;
21816 }
21817 
21818 
21819 /*! \brief Get the session-timer mode 
21820  * \param p pointer to the SIP dialog 
21821 */
21822 enum st_mode st_get_mode(struct sip_pvt *p)
21823 {
21824    if (!p->stimer) 
21825       sip_st_alloc(p);
21826 
21827    if (p->stimer->st_cached_mode != SESSION_TIMER_MODE_INVALID) 
21828       return p->stimer->st_cached_mode;
21829 
21830    if (p->peername) {
21831       struct sip_peer *pp = find_peer(p->peername, NULL, TRUE, FINDPEERS, FALSE, 0);
21832       if (pp) {
21833          p->stimer->st_cached_mode = pp->stimer.st_mode_oper;
21834          unref_peer(pp, "unref peer pointer from find_peer call in st_get_mode");
21835          return pp->stimer.st_mode_oper;
21836       }
21837    }
21838 
21839    p->stimer->st_cached_mode = global_st_mode;
21840    return global_st_mode;
21841 }
21842 
21843 
21844 /*! \brief React to lack of answer to Qualify poke */
21845 static int sip_poke_noanswer(const void *data)
21846 {
21847    struct sip_peer *peer = (struct sip_peer *)data;
21848    
21849    peer->pokeexpire = -1;
21850 
21851    if (peer->lastms > -1) {
21852       ast_log(LOG_NOTICE, "Peer '%s' is now UNREACHABLE!  Last qualify: %d\n", peer->name, peer->lastms);
21853       if (sip_cfg.peer_rtupdate) {
21854          ast_update_realtime(ast_check_realtime("sipregs") ? "sipregs" : "sippeers", "name", peer->name, "lastms", "-1", SENTINEL);
21855       }
21856       manager_event(EVENT_FLAG_SYSTEM, "PeerStatus", "ChannelType: SIP\r\nPeer: SIP/%s\r\nPeerStatus: Unreachable\r\nTime: %d\r\n", peer->name, -1);
21857       if (global_regextenonqualify) {
21858          register_peer_exten(peer, FALSE);
21859       }
21860    }
21861 
21862    if (peer->call) {
21863       dialog_unlink_all(peer->call, TRUE, TRUE);
21864       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21865       /* peer->call = sip_destroy(peer->call);*/
21866    }
21867    
21868    peer->lastms = -1;
21869    ast_devstate_changed(AST_DEVICE_UNKNOWN, "SIP/%s", peer->name);
21870 
21871    /* Try again quickly */
21872    AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, 
21873          DEFAULT_FREQ_NOTOK, sip_poke_peer_s, peer,
21874          unref_peer(_data, "removing poke peer ref"),
21875          unref_peer(peer, "removing poke peer ref"),
21876          ref_peer(peer, "adding poke peer ref"));
21877 
21878    /* Release the ref held by the running scheduler entry */
21879    unref_peer(peer, "release peer poke noanswer ref");
21880 
21881    return 0;
21882 }
21883 
21884 /*! \brief Check availability of peer, also keep NAT open
21885 \note This is done with 60 seconds between each ping,
21886    unless forced by cli or manager. If peer is unreachable,
21887    we check every 10th second by default. 
21888 */
21889 static int sip_poke_peer(struct sip_peer *peer, int force)
21890 {
21891    struct sip_pvt *p;
21892    int xmitres = 0;
21893    
21894    if ((!peer->maxms && !force) || !peer->addr.sin_addr.s_addr) {
21895       /* IF we have no IP, or this isn't to be monitored, return
21896         immediately after clearing things out */
21897       AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21898             unref_peer(peer, "removing poke peer ref"));
21899       
21900       peer->lastms = 0;
21901       if (peer->call) {
21902          peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21903       }
21904       return 0;
21905    }
21906    if (peer->call) {
21907       if (sipdebug) {
21908          ast_log(LOG_NOTICE, "Still have a QUALIFY dialog active, deleting\n");
21909       }
21910       dialog_unlink_all(peer->call, TRUE, TRUE);
21911       peer->call = dialog_unref(peer->call, "unref dialog peer->call");
21912       /* peer->call = sip_destroy(peer->call); */
21913    }
21914    if (!(p = sip_alloc(NULL, NULL, 0, SIP_OPTIONS, NULL))) {
21915       return -1;
21916    }
21917    peer->call = dialog_ref(p, "copy sip alloc from p to peer->call");
21918    
21919    p->sa = peer->addr;
21920    p->recv = peer->addr;
21921    copy_socket_data(&p->socket, &peer->socket);
21922    ast_copy_flags(&p->flags[0], &peer->flags[0], SIP_FLAGS_TO_COPY);
21923    ast_copy_flags(&p->flags[1], &peer->flags[1], SIP_PAGE2_FLAGS_TO_COPY);
21924 
21925    /* Send OPTIONs to peer's fullcontact */
21926    if (!ast_strlen_zero(peer->fullcontact))
21927       ast_string_field_set(p, fullcontact, peer->fullcontact);
21928 
21929    if (!ast_strlen_zero(peer->tohost))
21930       ast_string_field_set(p, tohost, peer->tohost);
21931    else
21932       ast_string_field_set(p, tohost, ast_inet_ntoa(peer->addr.sin_addr));
21933 
21934    /* Recalculate our side, and recalculate Call ID */
21935    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
21936    build_via(p);
21937    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
21938    build_callid_pvt(p);
21939    ao2_t_link(dialogs, p, "Linking in under new name");
21940 
21941    AST_SCHED_DEL_UNREF(sched, peer->pokeexpire,
21942          unref_peer(peer, "removing poke peer ref"));
21943    
21944    if (p->relatedpeer)
21945       p->relatedpeer = unref_peer(p->relatedpeer,"unsetting the relatedpeer field in the dialog, before it is set to something else.");
21946    p->relatedpeer = ref_peer(peer, "setting the relatedpeer field in the dialog");
21947    ast_set_flag(&p->flags[0], SIP_OUTGOING);
21948 #ifdef VOCAL_DATA_HACK
21949    ast_copy_string(p->username, "__VOCAL_DATA_SHOULD_READ_THE_SIP_SPEC__", sizeof(p->username));
21950    xmitres = transmit_invite(p, SIP_INVITE, 0, 2); /* sinks the p refcount */
21951 #else
21952    xmitres = transmit_invite(p, SIP_OPTIONS, 0, 2); /* sinks the p refcount */
21953 #endif
21954    peer->ps = ast_tvnow();
21955    if (xmitres == XMIT_ERROR) {
21956       sip_poke_noanswer(peer);   /* Immediately unreachable, network problems */
21957    } else if (!force) {
21958       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, peer->maxms * 2, sip_poke_noanswer, peer,
21959             unref_peer(_data, "removing poke peer ref"),
21960             unref_peer(peer, "removing poke peer ref"),
21961             ref_peer(peer, "adding poke peer ref"));
21962    }
21963    dialog_unref(p, "unref dialog at end of sip_poke_peer, obtained from sip_alloc, just before it goes out of scope");
21964    return 0;
21965 }
21966 
21967 /*! \brief Part of PBX channel interface
21968 \note
21969 \par  Return values:---
21970 
21971    If we have qualify on and the device is not reachable, regardless of registration
21972    state we return AST_DEVICE_UNAVAILABLE
21973 
21974    For peers with call limit:
21975       - not registered        AST_DEVICE_UNAVAILABLE
21976       - registered, no call         AST_DEVICE_NOT_INUSE
21977       - registered, active calls    AST_DEVICE_INUSE
21978       - registered, call limit reached AST_DEVICE_BUSY
21979       - registered, onhold       AST_DEVICE_ONHOLD
21980       - registered, ringing         AST_DEVICE_RINGING
21981 
21982    For peers without call limit:
21983       - not registered        AST_DEVICE_UNAVAILABLE
21984       - registered            AST_DEVICE_NOT_INUSE
21985       - fixed IP (!dynamic)         AST_DEVICE_NOT_INUSE
21986    
21987    Peers that does not have a known call and can't be reached by OPTIONS
21988       - unreachable           AST_DEVICE_UNAVAILABLE
21989 
21990    If we return AST_DEVICE_UNKNOWN, the device state engine will try to find
21991    out a state by walking the channel list.
21992 
21993    The queue system (\ref app_queue.c) treats a member as "active"
21994    if devicestate is != AST_DEVICE_UNAVAILBALE && != AST_DEVICE_INVALID
21995 
21996    When placing a call to the queue member, queue system sets a member to busy if
21997    != AST_DEVICE_NOT_INUSE and != AST_DEVICE_UNKNOWN
21998 
21999 */
22000 static int sip_devicestate(void *data)
22001 {
22002    char *host;
22003    char *tmp;
22004    struct sip_peer *p;
22005 
22006    int res = AST_DEVICE_INVALID;
22007 
22008    /* make sure data is not null. Maybe unnecessary, but better be safe */
22009    host = ast_strdupa(data ? data : "");
22010    if ((tmp = strchr(host, '@')))
22011       host = tmp + 1;
22012 
22013    ast_debug(3, "Checking device state for peer %s\n", host);
22014 
22015    /* If find_peer asks for a realtime peer, then this breaks rtautoclear.  This
22016     * is because when a peer tries to autoexpire, the last thing it does is to
22017     * queue up an event telling the system that the devicestate has changed
22018     * (presumably to unavailable).  If we ask for a realtime peer here, this would
22019     * load it BACK into memory, thus defeating the point of trying to clear dead
22020     * hosts out of memory.
22021     */
22022    if ((p = find_peer(host, NULL, FALSE, FINDALLDEVICES, TRUE, 0))) {
22023       if (p->addr.sin_addr.s_addr || p->defaddr.sin_addr.s_addr) {
22024          /* we have an address for the peer */
22025       
22026          /* Check status in this order
22027             - Hold
22028             - Ringing
22029             - Busy (enforced only by call limit)
22030             - Inuse (we have a call)
22031             - Unreachable (qualify)
22032             If we don't find any of these state, report AST_DEVICE_NOT_INUSE
22033             for registered devices */
22034 
22035          if (p->onHold)
22036             /* First check for hold or ring states */
22037             res = AST_DEVICE_ONHOLD;
22038          else if (p->inRinging) {
22039             if (p->inRinging == p->inUse)
22040                res = AST_DEVICE_RINGING;
22041             else
22042                res = AST_DEVICE_RINGINUSE;
22043          } else if (p->call_limit && (p->inUse == p->call_limit))
22044             /* check call limit */
22045             res = AST_DEVICE_BUSY;
22046          else if (p->call_limit && p->busy_level && p->inUse >= p->busy_level)
22047             /* We're forcing busy before we've reached the call limit */
22048             res = AST_DEVICE_BUSY;
22049          else if (p->call_limit && p->inUse)
22050             /* Not busy, but we do have a call */
22051             res = AST_DEVICE_INUSE;
22052          else if (p->maxms && ((p->lastms > p->maxms) || (p->lastms < 0))) 
22053             /* We don't have a call. Are we reachable at all? Requires qualify= */
22054             res = AST_DEVICE_UNAVAILABLE;
22055          else  /* Default reply if we're registered and have no other data */
22056             res = AST_DEVICE_NOT_INUSE;
22057       } else {
22058          /* there is no address, it's unavailable */
22059          res = AST_DEVICE_UNAVAILABLE;
22060       }
22061       unref_peer(p, "unref_peer, from sip_devicestate, release ref from find_peer");
22062    } else {
22063       res = AST_DEVICE_UNKNOWN;
22064    }
22065 
22066    return res;
22067 }
22068 
22069 /*! \brief PBX interface function -build SIP pvt structure 
22070  * SIP calls initiated by the PBX arrive here. 
22071  *
22072  * \verbatim   
22073  *    SIP Dial string syntax
22074  *    SIP/exten@host!dnid
22075  * or SIP/host/exten!dnid
22076  * or SIP/host!dnid
22077  * \endverbatim
22078 */
22079 static struct ast_channel *sip_request_call(const char *type, int format, void *data, int *cause)
22080 {
22081    struct sip_pvt *p;
22082    struct ast_channel *tmpc = NULL;
22083    char *ext = NULL, *host;
22084    char tmp[256];
22085    char *dest = data;
22086    char *dnid;
22087    char *secret = NULL;
22088    char *md5secret = NULL;
22089    char *authname = NULL;
22090    char *trans = NULL;
22091    enum sip_transport transport = 0;
22092    int oldformat = format;
22093 
22094    /* mask request with some set of allowed formats.
22095     * XXX this needs to be fixed.
22096     * The original code uses AST_FORMAT_AUDIO_MASK, but it is
22097     * unclear what to use here. We have global_capabilities, which is
22098     * configured from sip.conf, and sip_tech.capabilities, which is
22099     * hardwired to all audio formats.
22100     */
22101    format &= AST_FORMAT_AUDIO_MASK;
22102    if (!format) {
22103       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));
22104       *cause = AST_CAUSE_BEARERCAPABILITY_NOTAVAIL;   /* Can't find codec to connect to host */
22105       return NULL;
22106    }
22107    ast_debug(1, "Asked to create a SIP channel with formats: %s\n", ast_getformatname_multiple(tmp, sizeof(tmp), oldformat));
22108 
22109    if (!(p = sip_alloc(NULL, NULL, 0, SIP_INVITE, NULL))) {
22110       ast_log(LOG_ERROR, "Unable to build sip pvt data for '%s' (Out of memory or socket error)\n", dest);
22111       *cause = AST_CAUSE_SWITCH_CONGESTION;
22112       return NULL;
22113    }
22114 
22115    p->outgoing_call = TRUE;
22116 
22117    if (!(p->options = ast_calloc(1, sizeof(*p->options)))) {
22118       dialog_unlink_all(p, TRUE, TRUE);
22119       dialog_unref(p, "unref dialog p from mem fail");
22120       /* sip_destroy(p); */
22121       ast_log(LOG_ERROR, "Unable to build option SIP data structure - Out of memory\n");
22122       *cause = AST_CAUSE_SWITCH_CONGESTION;
22123       return NULL;
22124    }
22125 
22126    /* Save the destination, the SIP dial string */
22127    ast_copy_string(tmp, dest, sizeof(tmp));
22128 
22129 
22130    /* Find DNID and take it away */
22131    dnid = strchr(tmp, '!');
22132    if (dnid != NULL) {
22133       *dnid++ = '\0';
22134       ast_string_field_set(p, todnid, dnid);
22135    }
22136 
22137    /* Find at sign - @ */
22138    host = strchr(tmp, '@');
22139    if (host) {
22140       *host++ = '\0';
22141       ext = tmp;
22142       secret = strchr(ext, ':');
22143    }
22144    if (secret) {
22145       *secret++ = '\0';
22146       md5secret = strchr(secret, ':');
22147    }
22148    if (md5secret) {
22149       *md5secret++ = '\0';
22150       authname = strchr(md5secret, ':');
22151    }
22152    if (authname) {
22153       *authname++ = '\0';
22154       trans = strchr(authname, ':');
22155    }
22156    if (trans) {
22157       *trans++ = '\0';
22158       if (!strcasecmp(trans, "tcp"))
22159          transport = SIP_TRANSPORT_TCP;
22160       else if (!strcasecmp(trans, "tls"))
22161          transport = SIP_TRANSPORT_TLS;
22162       else {
22163          if (strcasecmp(trans, "udp"))
22164             ast_log(LOG_WARNING, "'%s' is not a valid transport option to Dial() for SIP calls, using udp by default.\n", trans);
22165          transport = SIP_TRANSPORT_UDP;
22166       }
22167    } else { /* use default */
22168       transport = SIP_TRANSPORT_UDP;
22169    }
22170 
22171    if (!host) {
22172       ext = strchr(tmp, '/');
22173       if (ext) 
22174          *ext++ = '\0';
22175       host = tmp;
22176    }
22177 
22178    set_socket_transport(&p->socket, transport);
22179 
22180    /* We now have 
22181       host = peer name, DNS host name or DNS domain (for SRV) 
22182       ext = extension (user part of URI)
22183       dnid = destination of the call (applies to the To: header)
22184    */
22185    if (create_addr(p, host, NULL, 1)) {
22186       *cause = AST_CAUSE_UNREGISTERED;
22187       ast_debug(3, "Cant create SIP call - target device not registered\n");
22188       dialog_unlink_all(p, TRUE, TRUE);
22189       dialog_unref(p, "unref dialog p UNREGISTERED");
22190       /* sip_destroy(p); */
22191       return NULL;
22192    }
22193    if (ast_strlen_zero(p->peername) && ext)
22194       ast_string_field_set(p, peername, ext);
22195    /* Recalculate our side, and recalculate Call ID */
22196    ast_sip_ouraddrfor(&p->sa.sin_addr, &p->ourip, p);
22197    build_via(p);
22198    ao2_t_unlink(dialogs, p, "About to change the callid -- remove the old name");
22199    build_callid_pvt(p);
22200    ao2_t_link(dialogs, p, "Linking in under new name");
22201    
22202    /* We have an extension to call, don't use the full contact here */
22203    /* This to enable dialing registered peers with extension dialling,
22204       like SIP/peername/extension   
22205       SIP/peername will still use the full contact 
22206     */
22207    if (ext) {
22208       ast_string_field_set(p, username, ext);
22209       ast_string_field_set(p, fullcontact, NULL);
22210    }
22211    if (secret && !ast_strlen_zero(secret))
22212       ast_string_field_set(p, peersecret, secret);
22213 
22214    if (md5secret && !ast_strlen_zero(md5secret))
22215       ast_string_field_set(p, peermd5secret, md5secret);
22216 
22217    if (authname && !ast_strlen_zero(authname))
22218       ast_string_field_set(p, authname, authname);
22219 #if 0
22220    printf("Setting up to call extension '%s' at '%s'\n", ext ? ext : "<none>", host);
22221 #endif
22222    p->prefcodec = oldformat;           /* Format for this call */
22223    p->jointcapability = oldformat;
22224    sip_pvt_lock(p);
22225    tmpc = sip_new(p, AST_STATE_DOWN, host);  /* Place the call */
22226    if (global_callevents)
22227       manager_event(EVENT_FLAG_SYSTEM, "ChannelUpdate",
22228          "Channel: %s\r\nChanneltype: %s\r\nSIPcallid: %s\r\nSIPfullcontact: %s\r\nPeername: %s\r\n",
22229          p->owner? p->owner->name : "", "SIP", p->callid, p->fullcontact, p->peername);
22230    sip_pvt_unlock(p);
22231    if (!tmpc) {
22232       dialog_unlink_all(p, TRUE, TRUE);
22233       /* sip_destroy(p); */
22234    }
22235    dialog_unref(p, "toss pvt ptr at end of sip_request_call");
22236    ast_update_use_count();
22237    restart_monitor();
22238    return tmpc;
22239 }
22240 
22241 /*! \brief Parse insecure= setting in sip.conf and set flags according to setting */
22242 static void set_insecure_flags (struct ast_flags *flags, const char *value, int lineno)
22243 {
22244    if (ast_strlen_zero(value))
22245       return;
22246 
22247    if (!ast_false(value)) {
22248       char buf[64];
22249       char *word, *next;
22250 
22251       ast_copy_string(buf, value, sizeof(buf));
22252       next = buf;
22253       while ((word = strsep(&next, ","))) {
22254          if (!strcasecmp(word, "port"))
22255             ast_set_flag(&flags[0], SIP_INSECURE_PORT);
22256          else if (!strcasecmp(word, "invite"))
22257             ast_set_flag(&flags[0], SIP_INSECURE_INVITE);
22258          else
22259             ast_log(LOG_WARNING, "Unknown insecure mode '%s' on line %d\n", value, lineno);
22260       }
22261    }
22262 }
22263 
22264 /*!
22265   \brief Handle T.38 configuration options common to users and peers
22266   \returns non-zero if any config options were handled, zero otherwise
22267 */
22268 static int handle_t38_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v,
22269                int *maxdatagram)
22270 {
22271    int res = 1;
22272 
22273    if (!strcasecmp(v->name, "t38pt_udptl")) {
22274       char *buf = ast_strdupa(v->value);
22275       char *word, *next = buf;
22276 
22277       ast_set_flag(&mask[1], SIP_PAGE2_T38SUPPORT);
22278 
22279       while ((word = strsep(&next, ","))) {
22280          if (ast_true(word) || !strcasecmp(word, "fec")) {
22281             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22282             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_FEC);
22283          } else if (!strcasecmp(word, "redundancy")) {
22284             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22285             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY);
22286          } else if (!strcasecmp(word, "none")) {
22287             ast_clear_flag(&flags[1], SIP_PAGE2_T38SUPPORT);
22288             ast_set_flag(&flags[1], SIP_PAGE2_T38SUPPORT_UDPTL);
22289          } else if (!strncasecmp(word, "maxdatagram=", 12)) {
22290             if (sscanf(&word[12], "%30u", maxdatagram) != 1) {
22291                ast_log(LOG_WARNING, "Invalid maxdatagram '%s' at line %d of %s\n", v->value, v->lineno, config);
22292                *maxdatagram = global_t38_maxdatagram;
22293             }
22294          }
22295       }
22296    } else if (!strcasecmp(v->name, "t38pt_usertpsource")) {
22297       ast_set_flag(&mask[1], SIP_PAGE2_UDPTL_DESTINATION);
22298       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_UDPTL_DESTINATION);
22299    } else {
22300       res = 0;
22301    }
22302 
22303    return res;
22304 }
22305 
22306 /*!
22307   \brief Handle flag-type options common to configuration of devices - peers
22308   \param flags array of two struct ast_flags
22309   \param mask array of two struct ast_flags
22310   \param v linked list of config variables to process
22311   \returns non-zero if any config options were handled, zero otherwise
22312 */
22313 static int handle_common_options(struct ast_flags *flags, struct ast_flags *mask, struct ast_variable *v)
22314 {
22315    int res = 1;
22316 
22317    if (!strcasecmp(v->name, "trustrpid")) {
22318       ast_set_flag(&mask[0], SIP_TRUSTRPID);
22319       ast_set2_flag(&flags[0], ast_true(v->value), SIP_TRUSTRPID);
22320    } else if (!strcasecmp(v->name, "sendrpid")) {
22321       ast_set_flag(&mask[0], SIP_SENDRPID);
22322       ast_set2_flag(&flags[0], ast_true(v->value), SIP_SENDRPID);
22323    } else if (!strcasecmp(v->name, "g726nonstandard")) {
22324       ast_set_flag(&mask[0], SIP_G726_NONSTANDARD);
22325       ast_set2_flag(&flags[0], ast_true(v->value), SIP_G726_NONSTANDARD);
22326    } else if (!strcasecmp(v->name, "useclientcode")) {
22327       ast_set_flag(&mask[0], SIP_USECLIENTCODE);
22328       ast_set2_flag(&flags[0], ast_true(v->value), SIP_USECLIENTCODE);
22329    } else if (!strcasecmp(v->name, "dtmfmode")) {
22330       ast_set_flag(&mask[0], SIP_DTMF);
22331       ast_clear_flag(&flags[0], SIP_DTMF);
22332       if (!strcasecmp(v->value, "inband"))
22333          ast_set_flag(&flags[0], SIP_DTMF_INBAND);
22334       else if (!strcasecmp(v->value, "rfc2833"))
22335          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
22336       else if (!strcasecmp(v->value, "info"))
22337          ast_set_flag(&flags[0], SIP_DTMF_INFO);
22338       else if (!strcasecmp(v->value, "shortinfo"))
22339          ast_set_flag(&flags[0], SIP_DTMF_SHORTINFO);
22340       else if (!strcasecmp(v->value, "auto"))
22341          ast_set_flag(&flags[0], SIP_DTMF_AUTO);
22342       else {
22343          ast_log(LOG_WARNING, "Unknown dtmf mode '%s' on line %d, using rfc2833\n", v->value, v->lineno);
22344          ast_set_flag(&flags[0], SIP_DTMF_RFC2833);
22345       }
22346    } else if (!strcasecmp(v->name, "nat")) {
22347       ast_set_flag(&mask[0], SIP_NAT);
22348       ast_clear_flag(&flags[0], SIP_NAT);
22349       if (!strcasecmp(v->value, "never"))
22350          ast_set_flag(&flags[0], SIP_NAT_NEVER);
22351       else if (!strcasecmp(v->value, "route"))
22352          ast_set_flag(&flags[0], SIP_NAT_ROUTE);
22353       else if (ast_true(v->value))
22354          ast_set_flag(&flags[0], SIP_NAT_ALWAYS);
22355       else
22356          ast_set_flag(&flags[0], SIP_NAT_RFC3581);
22357    } else if (!strcasecmp(v->name, "canreinvite")) {
22358       ast_set_flag(&mask[0], SIP_REINVITE);
22359       ast_clear_flag(&flags[0], SIP_REINVITE);
22360       if (ast_true(v->value)) {
22361          ast_set_flag(&flags[0], SIP_CAN_REINVITE | SIP_CAN_REINVITE_NAT);
22362       } else if (!ast_false(v->value)) {
22363          char buf[64];
22364          char *word, *next = buf;
22365 
22366          ast_copy_string(buf, v->value, sizeof(buf));
22367          while ((word = strsep(&next, ","))) {
22368             if (!strcasecmp(word, "update")) {
22369                ast_set_flag(&flags[0], SIP_REINVITE_UPDATE | SIP_CAN_REINVITE);
22370             } else if (!strcasecmp(word, "nonat")) {
22371                ast_set_flag(&flags[0], SIP_CAN_REINVITE);
22372                ast_clear_flag(&flags[0], SIP_CAN_REINVITE_NAT);
22373             } else {
22374                ast_log(LOG_WARNING, "Unknown canreinvite mode '%s' on line %d\n", v->value, v->lineno);
22375             }
22376          }
22377       }
22378    } else if (!strcasecmp(v->name, "insecure")) {
22379       ast_set_flag(&mask[0], SIP_INSECURE);
22380       ast_clear_flag(&flags[0], SIP_INSECURE);
22381       set_insecure_flags(&flags[0], v->value, v->lineno);   
22382    } else if (!strcasecmp(v->name, "progressinband")) {
22383       ast_set_flag(&mask[0], SIP_PROG_INBAND);
22384       ast_clear_flag(&flags[0], SIP_PROG_INBAND);
22385       if (ast_true(v->value))
22386          ast_set_flag(&flags[0], SIP_PROG_INBAND_YES);
22387       else if (strcasecmp(v->value, "never"))
22388          ast_set_flag(&flags[0], SIP_PROG_INBAND_NO);
22389    } else if (!strcasecmp(v->name, "promiscredir")) {
22390       ast_set_flag(&mask[0], SIP_PROMISCREDIR);
22391       ast_set2_flag(&flags[0], ast_true(v->value), SIP_PROMISCREDIR);
22392    } else if (!strcasecmp(v->name, "videosupport")) {
22393       if (!strcasecmp(v->value, "always")) {
22394          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22395          ast_set_flag(&flags[1], SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
22396       } else {
22397          ast_set_flag(&mask[1], SIP_PAGE2_VIDEOSUPPORT);
22398          ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_VIDEOSUPPORT);
22399       }
22400    } else if (!strcasecmp(v->name, "textsupport")) {
22401       ast_set_flag(&mask[1], SIP_PAGE2_TEXTSUPPORT);
22402       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_TEXTSUPPORT);
22403       res = 1;
22404    } else if (!strcasecmp(v->name, "allowoverlap")) {
22405       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWOVERLAP);
22406       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWOVERLAP);
22407    } else if (!strcasecmp(v->name, "allowsubscribe")) {
22408       ast_set_flag(&mask[1], SIP_PAGE2_ALLOWSUBSCRIBE);
22409       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_ALLOWSUBSCRIBE);
22410    } else if (!strcasecmp(v->name, "ignoresdpversion")) {
22411       ast_set_flag(&mask[1], SIP_PAGE2_IGNORESDPVERSION);
22412       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_IGNORESDPVERSION);
22413    } else if (!strcasecmp(v->name, "rfc2833compensate")) {
22414       ast_set_flag(&mask[1], SIP_PAGE2_RFC2833_COMPENSATE);
22415       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_RFC2833_COMPENSATE);
22416    } else if (!strcasecmp(v->name, "buggymwi")) {
22417       ast_set_flag(&mask[1], SIP_PAGE2_BUGGY_MWI);
22418       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_BUGGY_MWI);
22419    } else if (!strcasecmp(v->name, "constantssrc")) {
22420       ast_set_flag(&mask[1], SIP_PAGE2_CONSTANT_SSRC);
22421       ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
22422    } else if (!strcasecmp(v->name, "faxdetect")) {
22423                 ast_set_flag(&mask[1], SIP_PAGE2_FAX_DETECT);
22424                 ast_set2_flag(&flags[1], ast_true(v->value), SIP_PAGE2_FAX_DETECT);
22425    } else
22426       res = 0;
22427 
22428    return res;
22429 }
22430 
22431 /*! \brief Add SIP domain to list of domains we are responsible for */
22432 static int add_sip_domain(const char *domain, const enum domain_mode mode, const char *context)
22433 {
22434    struct domain *d;
22435 
22436    if (ast_strlen_zero(domain)) {
22437       ast_log(LOG_WARNING, "Zero length domain.\n");
22438       return 1;
22439    }
22440 
22441    if (!(d = ast_calloc(1, sizeof(*d))))
22442       return 0;
22443 
22444    ast_copy_string(d->domain, domain, sizeof(d->domain));
22445 
22446    if (!ast_strlen_zero(context))
22447       ast_copy_string(d->context, context, sizeof(d->context));
22448 
22449    d->mode = mode;
22450 
22451    AST_LIST_LOCK(&domain_list);
22452    AST_LIST_INSERT_TAIL(&domain_list, d, list);
22453    AST_LIST_UNLOCK(&domain_list);
22454 
22455    if (sipdebug)  
22456       ast_debug(1, "Added local SIP domain '%s'\n", domain);
22457 
22458    return 1;
22459 }
22460 
22461 /*! \brief  check_sip_domain: Check if domain part of uri is local to our server */
22462 static int check_sip_domain(const char *domain, char *context, size_t len)
22463 {
22464    struct domain *d;
22465    int result = 0;
22466 
22467    AST_LIST_LOCK(&domain_list);
22468    AST_LIST_TRAVERSE(&domain_list, d, list) {
22469       if (strcasecmp(d->domain, domain))
22470          continue;
22471 
22472       if (len && !ast_strlen_zero(d->context))
22473          ast_copy_string(context, d->context, len);
22474       
22475       result = 1;
22476       break;
22477    }
22478    AST_LIST_UNLOCK(&domain_list);
22479 
22480    return result;
22481 }
22482 
22483 /*! \brief Clear our domain list (at reload) */
22484 static void clear_sip_domains(void)
22485 {
22486    struct domain *d;
22487 
22488    AST_LIST_LOCK(&domain_list);
22489    while ((d = AST_LIST_REMOVE_HEAD(&domain_list, list)))
22490       ast_free(d);
22491    AST_LIST_UNLOCK(&domain_list);
22492 }
22493 
22494 
22495 /*! \brief Add realm authentication in list */
22496 static struct sip_auth *add_realm_authentication(struct sip_auth *authlist, const char *configuration, int lineno)
22497 {
22498    char authcopy[256];
22499    char *username=NULL, *realm=NULL, *secret=NULL, *md5secret=NULL;
22500    struct sip_auth *a, *b, *auth;
22501 
22502    if (ast_strlen_zero(configuration))
22503       return authlist;
22504 
22505    ast_debug(1, "Auth config ::  %s\n", configuration);
22506 
22507    ast_copy_string(authcopy, configuration, sizeof(authcopy));
22508    username = authcopy;
22509 
22510    /* split user[:secret] and relm */
22511    realm = strrchr(username, '@');
22512    if (realm)
22513       *realm++ = '\0';
22514    if (ast_strlen_zero(username) || ast_strlen_zero(realm)) {
22515       ast_log(LOG_WARNING, "Format for authentication entry is user[:secret]@realm at line %d\n", lineno);
22516       return authlist;
22517    }
22518 
22519    /* parse username at ':' for secret, or '#" for md5secret */
22520    if ((secret = strchr(username, ':'))) {
22521       *secret++ = '\0';
22522    } else if ((md5secret = strchr(username, '#'))) {
22523       *md5secret++ = '\0';
22524    }
22525 
22526    if (!(auth = ast_calloc(1, sizeof(*auth))))
22527       return authlist;
22528 
22529    ast_copy_string(auth->realm, realm, sizeof(auth->realm));
22530    ast_copy_string(auth->username, username, sizeof(auth->username));
22531    if (secret)
22532       ast_copy_string(auth->secret, secret, sizeof(auth->secret));
22533    if (md5secret)
22534       ast_copy_string(auth->md5secret, md5secret, sizeof(auth->md5secret));
22535 
22536    /* find the end of the list */
22537    for (b = NULL, a = authlist; a ; b = a, a = a->next)
22538       ;
22539    if (b)
22540       b->next = auth;   /* Add structure add end of list */
22541    else
22542       authlist = auth;
22543 
22544    ast_verb(3, "Added authentication for realm %s\n", realm);
22545 
22546    return authlist;
22547 
22548 }
22549 
22550 /*! \brief Clear realm authentication list (at reload) */
22551 static int clear_realm_authentication(struct sip_auth *authlist)
22552 {
22553    struct sip_auth *a = authlist;
22554    struct sip_auth *b;
22555 
22556    while (a) {
22557       b = a;
22558       a = a->next;
22559       ast_free(b);
22560    }
22561 
22562    return 1;
22563 }
22564 
22565 /*! \brief Find authentication for a specific realm */
22566 static struct sip_auth *find_realm_authentication(struct sip_auth *authlist, const char *realm)
22567 {
22568    struct sip_auth *a;
22569 
22570    for (a = authlist; a; a = a->next) {
22571       if (!strcasecmp(a->realm, realm))
22572          break;
22573    }
22574 
22575    return a;
22576 }
22577 
22578 /*! \brief
22579  * implement the setvar config line
22580  */
22581 static struct ast_variable *add_var(const char *buf, struct ast_variable *list)
22582 {
22583    struct ast_variable *tmpvar = NULL;
22584    char *varname = ast_strdupa(buf), *varval = NULL;
22585    
22586    if ((varval = strchr(varname, '='))) {
22587       *varval++ = '\0';
22588       if ((tmpvar = ast_variable_new(varname, varval, ""))) {
22589          tmpvar->next = list;
22590          list = tmpvar;
22591       }
22592    }
22593    return list;
22594 }
22595 
22596 /*! \brief Set peer defaults before configuring specific configurations */
22597 static void set_peer_defaults(struct sip_peer *peer)
22598 {
22599    if (peer->expire == 0) {
22600       /* Don't reset expire or port time during reload 
22601          if we have an active registration 
22602       */
22603       peer->expire = -1;
22604       peer->pokeexpire = -1;
22605       peer->addr.sin_port = htons(STANDARD_SIP_PORT);
22606       set_socket_transport(&peer->socket, SIP_TRANSPORT_UDP);
22607    }
22608    peer->type = SIP_TYPE_PEER;
22609    ast_copy_flags(&peer->flags[0], &global_flags[0], SIP_FLAGS_TO_COPY);
22610    ast_copy_flags(&peer->flags[1], &global_flags[1], SIP_PAGE2_FLAGS_TO_COPY);
22611    strcpy(peer->context, default_context);
22612    strcpy(peer->subscribecontext, default_subscribecontext);
22613    strcpy(peer->language, default_language);
22614    strcpy(peer->mohinterpret, default_mohinterpret);
22615    strcpy(peer->mohsuggest, default_mohsuggest);
22616    peer->addr.sin_family = AF_INET;
22617    peer->defaddr.sin_family = AF_INET;
22618    peer->capability = global_capability;
22619    peer->maxcallbitrate = default_maxcallbitrate;
22620    peer->rtptimeout = global_rtptimeout;
22621    peer->rtpholdtimeout = global_rtpholdtimeout;
22622    peer->rtpkeepalive = global_rtpkeepalive;
22623    peer->allowtransfer = global_allowtransfer;
22624    peer->autoframing = global_autoframing;
22625    peer->t38_maxdatagram = global_t38_maxdatagram;
22626    peer->qualifyfreq = global_qualifyfreq;
22627    if (global_callcounter)
22628       peer->call_limit=999;
22629    strcpy(peer->vmexten, default_vmexten);
22630    peer->secret[0] = '\0';
22631    peer->md5secret[0] = '\0';
22632    peer->cid_num[0] = '\0';
22633    peer->cid_name[0] = '\0';
22634    peer->fromdomain[0] = '\0';
22635    peer->fromuser[0] = '\0';
22636    peer->regexten[0] = '\0';
22637    peer->callgroup = 0;
22638    peer->pickupgroup = 0;
22639    peer->maxms = default_qualify;
22640    peer->prefs = default_prefs;
22641    peer->stimer.st_mode_oper = global_st_mode;  /* Session-Timers */
22642    peer->stimer.st_ref = global_st_refresher;
22643    peer->stimer.st_min_se = global_min_se;
22644    peer->stimer.st_max_se = global_max_se;
22645    peer->timer_t1 = global_t1;
22646    peer->timer_b = global_timer_b;
22647    clear_peer_mailboxes(peer);
22648 }
22649 
22650 /*! \brief Create temporary peer (used in autocreatepeer mode) */
22651 static struct sip_peer *temp_peer(const char *name)
22652 {
22653    struct sip_peer *peer;
22654 
22655    if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22656       return NULL;
22657 
22658    ast_atomic_fetchadd_int(&apeerobjs, 1);
22659    set_peer_defaults(peer);
22660 
22661    ast_copy_string(peer->name, name, sizeof(peer->name));
22662 
22663    peer->selfdestruct = TRUE;
22664    peer->host_dynamic = TRUE;
22665    peer->prefs = default_prefs;
22666    reg_source_db(peer);
22667 
22668    return peer;
22669 }
22670 
22671 /*! \todo document this function */
22672 static void add_peer_mailboxes(struct sip_peer *peer, const char *value)
22673 {
22674    char *next, *mbox, *context;
22675 
22676    next = ast_strdupa(value);
22677 
22678    while ((mbox = context = strsep(&next, ","))) {
22679       struct sip_mailbox *mailbox;
22680 
22681       if (!(mailbox = ast_calloc(1, sizeof(*mailbox))))
22682          continue;
22683 
22684       strsep(&context, "@");
22685       if (ast_strlen_zero(mbox)) {
22686          ast_free(mailbox);
22687          continue;
22688       }
22689       mailbox->mailbox = ast_strdup(mbox);
22690       mailbox->context = ast_strdup(context);
22691 
22692       AST_LIST_INSERT_TAIL(&peer->mailboxes, mailbox, entry);
22693    }
22694 }
22695 
22696 /*! \brief Build peer from configuration (file or realtime static/dynamic) */
22697 static struct sip_peer *build_peer(const char *name, struct ast_variable *v, struct ast_variable *alt, int realtime, int devstate_only)
22698 {
22699    struct sip_peer *peer = NULL;
22700    struct ast_ha *oldha = NULL;
22701    int found = 0;
22702    int firstpass = 1;
22703    uint16_t port = 0;
22704    int format = 0;      /* Ama flags */
22705    time_t regseconds = 0;
22706    struct ast_flags peerflags[2] = {{(0)}};
22707    struct ast_flags mask[2] = {{(0)}};
22708    char callback[256] = "";
22709    struct sip_peer tmp_peer;
22710    const char *srvlookup = NULL;
22711    static int deprecation_warning = 1;
22712    int alt_fullcontact = alt ? 1 : 0;
22713    struct ast_str *fullcontact = ast_str_alloca(512);
22714 
22715    if (!realtime || ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22716       /* Note we do NOT use find_peer here, to avoid realtime recursion */
22717       /* We also use a case-sensitive comparison (unlike find_peer) so
22718          that case changes made to the peer name will be properly handled
22719          during reload
22720       */
22721       ast_copy_string(tmp_peer.name, name, sizeof(tmp_peer.name));
22722       peer = ao2_t_find(peers, &tmp_peer, OBJ_POINTER | OBJ_UNLINK, "find and unlink peer from peers table");
22723    }
22724 
22725    if (peer) {
22726       /* Already in the list, remove it and it will be added back (or FREE'd)  */
22727       found++;
22728       if (!(peer->the_mark))
22729          firstpass = 0;
22730    } else {
22731       if (!(peer = ao2_t_alloc(sizeof(*peer), sip_destroy_peer_fn, "allocate a peer struct")))
22732          return NULL;
22733 
22734       if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS)) {
22735          ast_atomic_fetchadd_int(&rpeerobjs, 1);
22736          ast_debug(3, "-REALTIME- peer built. Name: %s. Peer objects: %d\n", name, rpeerobjs);
22737       } else
22738          ast_atomic_fetchadd_int(&speerobjs, 1);
22739    }
22740 
22741    /* Note that our peer HAS had its reference count increased */
22742    if (firstpass) {
22743       peer->lastmsgssent = -1;
22744       oldha = peer->ha;
22745       peer->ha = NULL;
22746       set_peer_defaults(peer);   /* Set peer defaults */
22747       peer->type = 0;
22748    }
22749    if (!found && name)
22750       ast_copy_string(peer->name, name, sizeof(peer->name));
22751 
22752    /* If we have channel variables, remove them (reload) */
22753    if (peer->chanvars) {
22754       ast_variables_destroy(peer->chanvars);
22755       peer->chanvars = NULL;
22756       /* XXX should unregister ? */
22757    }
22758 
22759    if (found)
22760       peer->portinuri = 0;
22761 
22762    /* If we have realm authentication information, remove them (reload) */
22763    clear_realm_authentication(peer->auth);
22764    peer->auth = NULL;
22765    peer->default_outbound_transport = 0;
22766    peer->transports = 0;
22767 
22768    for (; v || ((v = alt) && !(alt=NULL)); v = v->next) {
22769       if (!devstate_only) {
22770          if (handle_common_options(&peerflags[0], &mask[0], v)) {
22771             continue;
22772          }
22773          if (handle_t38_options(&peerflags[0], &mask[0], v, &peer->t38_maxdatagram)) {
22774             continue;
22775          }
22776          if (!strcasecmp(v->name, "transport") && !ast_strlen_zero(v->value)) {
22777             char *val = ast_strdupa(v->value);
22778             char *trans;
22779 
22780             while ((trans = strsep(&val, ","))) {
22781                trans = ast_skip_blanks(trans);
22782 
22783                if (!strncasecmp(trans, "udp", 3)) {
22784                   peer->transports |= SIP_TRANSPORT_UDP;
22785                } else if (!strncasecmp(trans, "tcp", 3)) {
22786                   peer->transports |= SIP_TRANSPORT_TCP;
22787                } else if (!strncasecmp(trans, "tls", 3)) {
22788                   peer->transports |= SIP_TRANSPORT_TLS;
22789                } else {
22790                   ast_log(LOG_NOTICE, "'%s' is not a valid transport type. if no other is specified, udp will be used.\n", trans);
22791                }
22792 
22793                if (!peer->default_outbound_transport) { /*!< The first transport listed should be default outbound */
22794                   peer->default_outbound_transport = peer->transports;
22795                }
22796             }
22797          } else if (realtime && !strcasecmp(v->name, "regseconds")) {
22798             ast_get_time_t(v->value, &regseconds, 0, NULL);
22799          } else if (realtime && !strcasecmp(v->name, "name")) {
22800             ast_copy_string(peer->name, v->value, sizeof(peer->name));
22801          } else if (!strcasecmp(v->name, "type")) {
22802             if (!strcasecmp(v->value, "peer")) {
22803                peer->type |= SIP_TYPE_PEER;
22804             } else if (!strcasecmp(v->value, "user")) {
22805                peer->type |= SIP_TYPE_USER;
22806             } else if (!strcasecmp(v->value, "friend")) {
22807                peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
22808             }
22809          } else if (!strcasecmp(v->name, "secret")) {
22810             ast_copy_string(peer->secret, v->value, sizeof(peer->secret));
22811          } else if (!strcasecmp(v->name, "md5secret")) {
22812             ast_copy_string(peer->md5secret, v->value, sizeof(peer->md5secret));
22813          } else if (!strcasecmp(v->name, "auth")) {
22814             peer->auth = add_realm_authentication(peer->auth, v->value, v->lineno);
22815          } else if (!strcasecmp(v->name, "callerid")) {
22816             ast_callerid_split(v->value, peer->cid_name, sizeof(peer->cid_name), peer->cid_num, sizeof(peer->cid_num));
22817          } else if (!strcasecmp(v->name, "fullname")) {
22818             ast_copy_string(peer->cid_name, v->value, sizeof(peer->cid_name));
22819          } else if (!strcasecmp(v->name, "trunkname")) {
22820             /* This is actually for a trunk, so we don't want to override callerid */
22821             ast_copy_string(peer->cid_name, "", sizeof(peer->cid_name));
22822          } else if (!strcasecmp(v->name, "cid_number")) {
22823             ast_copy_string(peer->cid_num, v->value, sizeof(peer->cid_num));
22824          } else if (!strcasecmp(v->name, "context")) {
22825             ast_copy_string(peer->context, v->value, sizeof(peer->context));
22826          } else if (!strcasecmp(v->name, "subscribecontext")) {
22827             ast_copy_string(peer->subscribecontext, v->value, sizeof(peer->subscribecontext));
22828          } else if (!strcasecmp(v->name, "fromdomain")) {
22829             ast_copy_string(peer->fromdomain, v->value, sizeof(peer->fromdomain));
22830          } else if (!strcasecmp(v->name, "usereqphone")) {
22831             ast_set2_flag(&peer->flags[0], ast_true(v->value), SIP_USEREQPHONE);
22832          } else if (!strcasecmp(v->name, "fromuser")) {
22833             ast_copy_string(peer->fromuser, v->value, sizeof(peer->fromuser));
22834          } else if (!strcasecmp(v->name, "outboundproxy")) {
22835             char *port, *next, *force, *proxyname;
22836             int forceopt = FALSE;
22837             /* Set peer channel variable */
22838             next = proxyname = ast_strdupa(v->value);
22839             if ((port = strchr(proxyname, ':'))) {
22840                *port++ = '\0';
22841                next = port;
22842             }
22843             if ((force = strchr(next, ','))) {
22844                *force++ = '\0';
22845                forceopt = strcmp(force, "force");
22846             }
22847             /* Allocate proxy object */
22848             peer->outboundproxy = proxy_allocate(proxyname, port, forceopt);
22849          } else if (!strcasecmp(v->name, "host")) {
22850             if (!strcasecmp(v->value, "dynamic")) {
22851                /* They'll register with us */
22852                if (!found || !peer->host_dynamic) {
22853                   /* Initialize stuff if this is a new peer, or if it used to
22854                    * not be dynamic before the reload. */
22855                   memset(&peer->addr.sin_addr, 0, 4);
22856                   peer->addr.sin_port = 0;
22857                }
22858                peer->host_dynamic = TRUE;
22859             } else {
22860                /* Non-dynamic.  Make sure we become that way if we're not */
22861                AST_SCHED_DEL_UNREF(sched, peer->expire,
22862                      unref_peer(peer, "removing register expire ref"));
22863                /* the port will either be set to a default value or a config specified value once all option parsing is complete */
22864                peer->addr.sin_port = 0;
22865                peer->host_dynamic = FALSE;
22866                srvlookup = v->value;
22867                if (global_dynamic_exclude_static) {
22868                   int err = 0;
22869                   global_contact_ha = ast_append_ha("deny", (char *)ast_inet_ntoa(peer->addr.sin_addr), global_contact_ha, &err);
22870                   if (err) {
22871                      ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22872                   }
22873                }
22874             }
22875          } else if (!strcasecmp(v->name, "defaultip")) {
22876             if (ast_get_ip(&peer->defaddr, v->value)) {
22877                unref_peer(peer, "unref_peer: from build_peer defaultip");
22878                return NULL;
22879             }
22880          } else if (!strcasecmp(v->name, "permit") || !strcasecmp(v->name, "deny")) {
22881             int ha_error = 0;
22882             peer->ha = ast_append_ha(v->name, v->value, peer->ha, &ha_error);
22883             if (ha_error) {
22884                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22885             }
22886          } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
22887             int ha_error = 0;
22888             peer->contactha = ast_append_ha(v->name + 7, v->value, peer->contactha, &ha_error);
22889             if (ha_error) {
22890                ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
22891             }
22892          } else if (!strcasecmp(v->name, "port")) {
22893             peer->portinuri = 1;
22894             if (!(port = port_str2int(v->value, 0))) {
22895                ast_log(LOG_WARNING, "Invalid peer port configuration at line %d : %s\n", v->lineno, v->value);
22896             }
22897          } else if (!strcasecmp(v->name, "callingpres")) {
22898             peer->callingpres = ast_parse_caller_presentation(v->value);
22899             if (peer->callingpres == -1) {
22900                peer->callingpres = atoi(v->value);
22901             }
22902          } else if (!strcasecmp(v->name, "username") || !strcmp(v->name, "defaultuser")) {   /* "username" is deprecated */
22903             ast_copy_string(peer->username, v->value, sizeof(peer->username));
22904             if (!strcasecmp(v->name, "username")) {
22905                if (deprecation_warning) {
22906                   ast_log(LOG_NOTICE, "The 'username' field for sip peers has been deprecated in favor of the term 'defaultuser'\n");
22907                   deprecation_warning = 0;
22908                }
22909                peer->deprecated_username = 1;
22910             }
22911          } else if (!strcasecmp(v->name, "language")) {
22912             ast_copy_string(peer->language, v->value, sizeof(peer->language));
22913          } else if (!strcasecmp(v->name, "regexten")) {
22914             ast_copy_string(peer->regexten, v->value, sizeof(peer->regexten));
22915          } else if (!strcasecmp(v->name, "callbackextension")) {
22916             ast_copy_string(callback, v->value, sizeof(callback));
22917          } else if (!strcasecmp(v->name, "amaflags")) {
22918             format = ast_cdr_amaflags2int(v->value);
22919             if (format < 0) {
22920                ast_log(LOG_WARNING, "Invalid AMA Flags for peer: %s at line %d\n", v->value, v->lineno);
22921             } else {
22922                peer->amaflags = format;
22923             }
22924          } else if (!strcasecmp(v->name, "accountcode")) {
22925             ast_copy_string(peer->accountcode, v->value, sizeof(peer->accountcode));
22926          } else if (!strcasecmp(v->name, "mohinterpret")) {
22927             ast_copy_string(peer->mohinterpret, v->value, sizeof(peer->mohinterpret));
22928          } else if (!strcasecmp(v->name, "mohsuggest")) {
22929             ast_copy_string(peer->mohsuggest, v->value, sizeof(peer->mohsuggest));
22930          } else if (!strcasecmp(v->name, "parkinglot")) {
22931             ast_copy_string(peer->parkinglot, v->value, sizeof(peer->parkinglot));
22932          } else if (!strcasecmp(v->name, "mailbox")) {
22933             add_peer_mailboxes(peer, v->value);
22934          } else if (!strcasecmp(v->name, "hasvoicemail")) {
22935             /* People expect that if 'hasvoicemail' is set, that the mailbox will
22936              * be also set, even if not explicitly specified. */
22937             if (ast_true(v->value) && AST_LIST_EMPTY(&peer->mailboxes)) {
22938                add_peer_mailboxes(peer, name);
22939             }
22940          } else if (!strcasecmp(v->name, "subscribemwi")) {
22941             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_SUBSCRIBEMWIONLY);
22942          } else if (!strcasecmp(v->name, "vmexten")) {
22943             ast_copy_string(peer->vmexten, v->value, sizeof(peer->vmexten));
22944          } else if (!strcasecmp(v->name, "callgroup")) {
22945             peer->callgroup = ast_get_group(v->value);
22946          } else if (!strcasecmp(v->name, "allowtransfer")) {
22947             peer->allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
22948          } else if (!strcasecmp(v->name, "pickupgroup")) {
22949             peer->pickupgroup = ast_get_group(v->value);
22950          } else if (!strcasecmp(v->name, "allow")) {
22951             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, TRUE);
22952             if (error) {
22953                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22954             }
22955          } else if (!strcasecmp(v->name, "disallow")) {
22956             int error =  ast_parse_allow_disallow(&peer->prefs, &peer->capability, v->value, FALSE);
22957             if (error) {
22958                ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
22959             }
22960          } else if (!strcasecmp(v->name, "registertrying")) {
22961             ast_set2_flag(&peer->flags[1], ast_true(v->value), SIP_PAGE2_REGISTERTRYING);
22962          } else if (!strcasecmp(v->name, "autoframing")) {
22963             peer->autoframing = ast_true(v->value);
22964          } else if (!strcasecmp(v->name, "rtptimeout")) {
22965             if ((sscanf(v->value, "%30d", &peer->rtptimeout) != 1) || (peer->rtptimeout < 0)) {
22966                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22967                peer->rtptimeout = global_rtptimeout;
22968             }
22969          } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
22970             if ((sscanf(v->value, "%30d", &peer->rtpholdtimeout) != 1) || (peer->rtpholdtimeout < 0)) {
22971                ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
22972                peer->rtpholdtimeout = global_rtpholdtimeout;
22973             }
22974          } else if (!strcasecmp(v->name, "rtpkeepalive")) {
22975             if ((sscanf(v->value, "%30d", &peer->rtpkeepalive) != 1) || (peer->rtpkeepalive < 0)) {
22976                ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
22977                peer->rtpkeepalive = global_rtpkeepalive;
22978             }
22979          } else if (!strcasecmp(v->name, "timert1")) {
22980             if ((sscanf(v->value, "%30d", &peer->timer_t1) != 1) || (peer->timer_t1 < 0)) {
22981                ast_log(LOG_WARNING, "'%s' is not a valid T1 time at line %d.  Using default.\n", v->value, v->lineno);
22982                peer->timer_t1 = global_t1;
22983             }
22984             /* Note that Timer B is dependent upon T1 and MUST NOT be lower
22985              * than T1 * 64, according to RFC 3261, Section 17.1.1.2 */
22986             if (peer->timer_b < peer->timer_t1 * 64) {
22987                peer->timer_b = peer->timer_t1 * 64;
22988             }
22989          } else if (!strcasecmp(v->name, "timerb")) {
22990             if ((sscanf(v->value, "%30d", &peer->timer_b) != 1) || (peer->timer_b < 0)) {
22991                ast_log(LOG_WARNING, "'%s' is not a valid Timer B time at line %d.  Using default.\n", v->value, v->lineno);
22992                peer->timer_b = global_timer_b;
22993             }
22994             if (peer->timer_b < peer->timer_t1 * 64) {
22995                static int warning = 0;
22996                if (warning++ % 20 == 0) {
22997                   ast_log(LOG_WARNING, "Timer B has been set lower than recommended. (RFC 3261, 17.1.1.2)\n");
22998                }
22999             }
23000          } else if (!strcasecmp(v->name, "setvar")) {
23001             peer->chanvars = add_var(v->value, peer->chanvars);
23002          } else if (!strcasecmp(v->name, "qualifyfreq")) {
23003             int i;
23004             if (sscanf(v->value, "%30d", &i) == 1) {
23005                peer->qualifyfreq = i * 1000;
23006             } else {
23007                ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23008                peer->qualifyfreq = global_qualifyfreq;
23009             }
23010          } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23011             peer->maxcallbitrate = atoi(v->value);
23012             if (peer->maxcallbitrate < 0) {
23013                peer->maxcallbitrate = default_maxcallbitrate;
23014             }
23015          } else if (!strcasecmp(v->name, "session-timers")) {
23016             int i = (int) str2stmode(v->value);
23017             if (i < 0) {
23018                ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23019                peer->stimer.st_mode_oper = global_st_mode;
23020             } else {
23021                peer->stimer.st_mode_oper = i;
23022             }
23023          } else if (!strcasecmp(v->name, "session-expires")) {
23024             if (sscanf(v->value, "%30d", &peer->stimer.st_max_se) != 1) {
23025                ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23026                peer->stimer.st_max_se = global_max_se;
23027             }
23028          } else if (!strcasecmp(v->name, "session-minse")) {
23029             if (sscanf(v->value, "%30d", &peer->stimer.st_min_se) != 1) {
23030                ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23031                peer->stimer.st_min_se = global_min_se;
23032             }
23033             if (peer->stimer.st_min_se < 90) {
23034                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);
23035                peer->stimer.st_min_se = global_min_se;
23036             }
23037          } else if (!strcasecmp(v->name, "session-refresher")) {
23038             int i = (int) str2strefresher(v->value);
23039             if (i < 0) {
23040                ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23041                peer->stimer.st_ref = global_st_refresher;
23042             } else {
23043                peer->stimer.st_ref = i;
23044             }
23045          }
23046       }
23047 
23048       /* These apply to devstate lookups */
23049       if (realtime && !strcasecmp(v->name, "lastms")) {
23050          sscanf(v->value, "%30d", &peer->lastms);
23051       } else if (realtime && !strcasecmp(v->name, "ipaddr") && !ast_strlen_zero(v->value) ) {
23052          inet_aton(v->value, &(peer->addr.sin_addr));
23053       } else if (realtime && !strcasecmp(v->name, "fullcontact")) {
23054          if (alt_fullcontact && !alt) {
23055             /* Reset, because the alternate also has a fullcontact and we
23056              * do NOT want the field value to be doubled. It might be
23057              * tempting to skip this, but the first table might not have
23058              * fullcontact and since we're here, we know that the alternate
23059              * absolutely does. */
23060             alt_fullcontact = 0;
23061             ast_str_reset(fullcontact);
23062          }
23063          /* Reconstruct field, because realtime separates our value at the ';' */
23064          if (fullcontact->used > 0) {
23065             ast_str_append(&fullcontact, 0, ";%s", v->value);
23066          } else {
23067             ast_str_set(&fullcontact, 0, "%s", v->value);
23068          }
23069       } else if (!strcasecmp(v->name, "qualify")) {
23070          if (!strcasecmp(v->value, "no")) {
23071             peer->maxms = 0;
23072          } else if (!strcasecmp(v->value, "yes")) {
23073             peer->maxms = default_qualify ? default_qualify : DEFAULT_MAXMS;
23074          } else if (sscanf(v->value, "%30d", &peer->maxms) != 1) {
23075             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);
23076             peer->maxms = 0;
23077          }
23078          if (realtime && !ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) && peer->maxms > 0) {
23079             /* This would otherwise cause a network storm, where the
23080              * qualify response refreshes the peer from the database,
23081              * which in turn causes another qualify to be sent, ad
23082              * infinitum. */
23083             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);
23084             peer->maxms = 0;
23085          }
23086       } else if (!strcasecmp(v->name, "callcounter")) {
23087          peer->call_limit = ast_true(v->value) ? INT_MAX : 0;
23088       } else if (!strcasecmp(v->name, "call-limit")) {
23089          peer->call_limit = atoi(v->value);
23090          if (peer->call_limit < 0) {
23091             peer->call_limit = 0;
23092          }
23093       } else if (!strcasecmp(v->name, "busylevel")) {
23094          peer->busy_level = atoi(v->value);
23095          if (peer->busy_level < 0) {
23096             peer->busy_level = 0;
23097          }
23098       }
23099    }
23100 
23101    if (!peer->default_outbound_transport) {
23102       peer->transports = SIP_TRANSPORT_UDP;
23103       peer->default_outbound_transport = SIP_TRANSPORT_UDP;
23104    }
23105 
23106    /* The default transport type set during build_peer should only replace the socket.type when...
23107     * 1. Registration is not present and the socket.type and default transport types are different.
23108     * 2. The socket.type is not an acceptable transport type after rebuilding peer.
23109     * 3. The socket.type is not set yet. */
23110    if (((peer->socket.type != peer->default_outbound_transport) && (peer->expire == -1)) ||
23111       !(peer->socket.type & peer->transports) || !(peer->socket.type)) {
23112 
23113       set_socket_transport(&peer->socket, peer->default_outbound_transport);
23114    }
23115 
23116    if (port && !realtime && peer->host_dynamic) {
23117       peer->defaddr.sin_port = htons(port);
23118    } else if (port) {
23119       peer->addr.sin_port = htons(port);
23120    }
23121 
23122    if (ast_str_strlen(fullcontact)) {
23123       ast_copy_string(peer->fullcontact, fullcontact->str, sizeof(peer->fullcontact));
23124       peer->rt_fromcontact = TRUE;
23125       /* We have a hostname in the fullcontact, but if we don't have an
23126        * address listed on the entry (or if it's 'dynamic'), then we need to
23127        * parse the entry to obtain the IP address, so a dynamic host can be
23128        * contacted immediately after reload (as opposed to waiting for it to
23129        * register once again). But if we have an address for this peer and NAT was
23130        * specified, use that address instead. */
23131       /* XXX May need to revisit the final argument; does the realtime DB store whether
23132        * the original contact was over TLS or not? XXX */
23133       if (!ast_test_flag(&peer->flags[0], SIP_NAT_ROUTE) || !peer->addr.sin_addr.s_addr) {
23134          __set_address_from_contact(fullcontact->str, &peer->addr, 0);
23135       }
23136    }
23137 
23138    if (srvlookup && peer->dnsmgr == NULL) {
23139       char transport[MAXHOSTNAMELEN];
23140       char _srvlookup[MAXHOSTNAMELEN];
23141       char *params;
23142 
23143       ast_copy_string(_srvlookup, srvlookup, sizeof(_srvlookup));
23144       if ((params = strchr(_srvlookup, ';'))) {
23145          *params++ = '\0';
23146       }
23147 
23148       snprintf(transport, sizeof(transport), "_sip._%s", get_transport(peer->socket.type));
23149 
23150       if (ast_dnsmgr_lookup(_srvlookup, &peer->addr, &peer->dnsmgr, global_srvlookup && !peer->portinuri ? transport : NULL)) {
23151          ast_log(LOG_ERROR, "srvlookup failed for host: %s, on peer %s, removing peer\n", _srvlookup, peer->name);
23152          unref_peer(peer, "getting rid of a peer pointer");
23153          return NULL;
23154       }
23155 
23156       ast_copy_string(peer->tohost, srvlookup, sizeof(peer->tohost));
23157    }
23158 
23159    if (!peer->addr.sin_port) {
23160       peer->addr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23161    }
23162    if (!peer->defaddr.sin_port) {
23163       peer->defaddr.sin_port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23164    }
23165    if (!peer->socket.port) {
23166       peer->socket.port = htons(((peer->socket.type & SIP_TRANSPORT_TLS) ? STANDARD_TLS_PORT : STANDARD_SIP_PORT));
23167    }
23168 
23169    if (!sip_cfg.ignore_regexpire && peer->host_dynamic && realtime) {
23170       time_t nowtime = time(NULL);
23171 
23172       if ((nowtime - regseconds) > 0) {
23173          destroy_association(peer);
23174          memset(&peer->addr, 0, sizeof(peer->addr));
23175          peer->lastms = -1;
23176          ast_debug(1, "Bah, we're expired (%d/%d/%d)!\n", (int)(nowtime - regseconds), (int)regseconds, (int)nowtime);
23177       }
23178    }
23179 
23180    /* Startup regular pokes */
23181    if (!devstate_only && realtime && peer->lastms > 0) {
23182       ref_peer(peer, "schedule qualify");
23183       sip_poke_peer(peer, 0);
23184    }
23185 
23186    ast_copy_flags(&peer->flags[0], &peerflags[0], mask[0].flags);
23187    ast_copy_flags(&peer->flags[1], &peerflags[1], mask[1].flags);
23188    if (ast_test_flag(&peer->flags[1], SIP_PAGE2_ALLOWSUBSCRIBE)) {
23189       global_allowsubscribe = TRUE; /* No global ban any more */
23190    }
23191    if (!found && peer->host_dynamic && !peer->is_realtime) {
23192       reg_source_db(peer);
23193    }
23194 
23195    /* If they didn't request that MWI is sent *only* on subscribe, go ahead and
23196     * subscribe to it now. */
23197    if (!devstate_only && !ast_test_flag(&peer->flags[1], SIP_PAGE2_SUBSCRIBEMWIONLY) &&
23198       !AST_LIST_EMPTY(&peer->mailboxes)) {
23199       add_peer_mwi_subs(peer);
23200       /* Send MWI from the event cache only.  This is so we can send initial
23201        * MWI if app_voicemail got loaded before chan_sip.  If it is the other
23202        * way, then we will get events when app_voicemail gets loaded. */
23203       sip_send_mwi_to_peer(peer, NULL, 1);
23204    }
23205 
23206    peer->the_mark = 0;
23207 
23208    ast_free_ha(oldha);
23209    if (!ast_strlen_zero(callback)) { /* build string from peer info */
23210       char *reg_string;
23211 
23212       if (asprintf(&reg_string, "%s?%s:%s@%s/%s", peer->name, peer->username, peer->secret, peer->tohost, callback) < 0) {
23213          ast_log(LOG_WARNING, "asprintf() failed: %s\n", strerror(errno));
23214       } else if (reg_string) {
23215          sip_register(reg_string, 0); /* XXX TODO: count in registry_count */
23216          ast_free(reg_string);
23217       }
23218    }
23219    return peer;
23220 }
23221 
23222 static int peer_markall_func(void *device, void *arg, int flags)
23223 {
23224    struct sip_peer *peer = device;
23225    peer->the_mark = 1;
23226    return 0;
23227 }
23228 
23229 /*! \brief Re-read SIP.conf config file
23230 \note This function reloads all config data, except for
23231    active peers (with registrations). They will only
23232    change configuration data at restart, not at reload.
23233    SIP debug and recordhistory state will not change
23234  */
23235 static int reload_config(enum channelreloadreason reason)
23236 {
23237    struct ast_config *cfg, *ucfg;
23238    struct ast_variable *v;
23239    struct sip_peer *peer;
23240    char *cat, *stringp, *context, *oldregcontext;
23241    char newcontexts[AST_MAX_CONTEXT], oldcontexts[AST_MAX_CONTEXT];
23242    struct ast_flags dummy[2];
23243    struct ast_flags config_flags = { reason == CHANNEL_MODULE_LOAD ? 0 : ast_test_flag(&global_flags[1], SIP_PAGE2_RTCACHEFRIENDS) ? 0 : CONFIG_FLAG_FILEUNCHANGED };
23244    int auto_sip_domains = FALSE;
23245    struct sockaddr_in old_bindaddr = bindaddr;
23246    int registry_count = 0, peer_count = 0;
23247    time_t run_start, run_end;
23248    
23249    run_start = time(0);
23250    ast_unload_realtime("sipregs");     
23251    ast_unload_realtime("sippeers");
23252    cfg = ast_config_load(config, config_flags);
23253 
23254    /* We *must* have a config file otherwise stop immediately */
23255    if (!cfg) {
23256       ast_log(LOG_NOTICE, "Unable to load config %s\n", config);
23257       return -1;
23258    } else if (cfg == CONFIG_STATUS_FILEUNCHANGED) {
23259       ucfg = ast_config_load("users.conf", config_flags);
23260       if (ucfg == CONFIG_STATUS_FILEUNCHANGED)
23261          return 1;
23262       /* Must reread both files, because one changed */
23263       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
23264       cfg = ast_config_load(config, config_flags);
23265    } else {
23266       ast_clear_flag(&config_flags, CONFIG_FLAG_FILEUNCHANGED);
23267       ucfg = ast_config_load("users.conf", config_flags);
23268    }
23269 
23270    /* Initialize tcp sockets */
23271    memset(&sip_tcp_desc.local_address, 0, sizeof(sip_tcp_desc.local_address));
23272    memset(&sip_tls_desc.local_address, 0, sizeof(sip_tls_desc.local_address));
23273 
23274    ast_free_ha(global_contact_ha);
23275    global_contact_ha = NULL;
23276 
23277    default_tls_cfg.enabled = FALSE;    /* Default: Disable TLS */
23278 
23279    sip_tcp_desc.local_address.sin_port = htons(STANDARD_SIP_PORT);
23280    sip_tls_desc.local_address.sin_port = htons(STANDARD_TLS_PORT);
23281 
23282    if (reason != CHANNEL_MODULE_LOAD) {
23283       ast_debug(4, "--------------- SIP reload started\n");
23284 
23285       clear_realm_authentication(authl);
23286       clear_sip_domains();
23287       authl = NULL;
23288 
23289       /* First, destroy all outstanding registry calls */
23290       /* This is needed, since otherwise active registry entries will not be destroyed */
23291       ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {  /* regl is locked */
23292 
23293             ASTOBJ_RDLOCK(iterator); /* now regl is locked, and the object is also locked */
23294             if (iterator->call) {
23295                ast_debug(3, "Destroying active SIP dialog for registry %s@%s\n", iterator->username, iterator->hostname);
23296                /* This will also remove references to the registry */
23297                dialog_unlink_all(iterator->call, TRUE, TRUE);
23298                iterator->call = dialog_unref(iterator->call, "remove iterator->call from registry traversal");
23299             }
23300             if (iterator->expire > -1) {
23301                AST_SCHED_DEL_UNREF(sched, iterator->expire, registry_unref(iterator, "reg ptr unref from reload config"));
23302             }
23303             if (iterator->timeout > -1) {
23304                AST_SCHED_DEL_UNREF(sched, iterator->timeout, registry_unref(iterator, "reg ptr unref from reload config"));
23305             }
23306             ASTOBJ_UNLOCK(iterator);
23307             
23308       } while(0));
23309 
23310       /* Then, actually destroy users and registry */
23311       ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
23312       ast_debug(4, "--------------- Done destroying registry list\n");
23313       ao2_t_callback(peers, OBJ_NODATA, peer_markall_func, 0, "callback to mark all peers");
23314    }
23315    
23316    /* Reset certificate handling for TLS sessions */
23317    if (reason != CHANNEL_MODULE_LOAD) {
23318       ast_free(default_tls_cfg.certfile);
23319       ast_free(default_tls_cfg.cipher);
23320       ast_free(default_tls_cfg.cafile);
23321       ast_free(default_tls_cfg.capath);
23322    }
23323    default_tls_cfg.certfile = ast_strdup(AST_CERTFILE); /*XXX Not sure if this is useful */
23324    default_tls_cfg.cipher = ast_strdup("");
23325    default_tls_cfg.cafile = ast_strdup("");
23326    default_tls_cfg.capath = ast_strdup("");
23327    
23328    /* Initialize copy of current global_regcontext for later use in removing stale contexts */
23329    ast_copy_string(oldcontexts, global_regcontext, sizeof(oldcontexts));
23330    oldregcontext = oldcontexts;
23331 
23332    /* Clear all flags before setting default values */
23333    /* Preserve debugging settings for console */
23334    sipdebug &= sip_debug_console;
23335    ast_clear_flag(&global_flags[0], AST_FLAGS_ALL);
23336    ast_clear_flag(&global_flags[1], AST_FLAGS_ALL);
23337 
23338    /* Reset IP addresses  */
23339    memset(&bindaddr, 0, sizeof(bindaddr));
23340    memset(&stunaddr, 0, sizeof(stunaddr));
23341    memset(&internip, 0, sizeof(internip));
23342 
23343    /* Free memory for local network address mask */
23344    ast_free_ha(localaddr);
23345    memset(&localaddr, 0, sizeof(localaddr));
23346    memset(&externip, 0, sizeof(externip));
23347    memset(&default_prefs, 0 , sizeof(default_prefs));
23348    memset(&global_outboundproxy, 0, sizeof(struct sip_proxy));
23349    global_outboundproxy.ip.sin_port = htons(STANDARD_SIP_PORT);
23350    global_outboundproxy.ip.sin_family = AF_INET;   /*!< Type of address: IPv4 */
23351    global_outboundproxy.force = FALSE;    /*!< Don't force proxy usage, use route: headers */
23352    ourport_tcp = STANDARD_SIP_PORT;
23353    ourport_tls = STANDARD_TLS_PORT;
23354    bindaddr.sin_port = htons(STANDARD_SIP_PORT);
23355    global_srvlookup = DEFAULT_SRVLOOKUP;
23356    global_tos_sip = DEFAULT_TOS_SIP;
23357    global_tos_audio = DEFAULT_TOS_AUDIO;
23358    global_tos_video = DEFAULT_TOS_VIDEO;
23359    global_tos_text = DEFAULT_TOS_TEXT;
23360    global_cos_sip = DEFAULT_COS_SIP;
23361    global_cos_audio = DEFAULT_COS_AUDIO;
23362    global_cos_video = DEFAULT_COS_VIDEO;
23363    global_cos_text = DEFAULT_COS_TEXT;
23364 
23365    externhost[0] = '\0';         /* External host name (for behind NAT DynDNS support) */
23366    externexpire = 0;       /* Expiration for DNS re-issuing */
23367    externrefresh = 10;
23368 
23369    /* Reset channel settings to default before re-configuring */
23370    allow_external_domains = DEFAULT_ALLOW_EXT_DOM;          /* Allow external invites */
23371    global_regcontext[0] = '\0';
23372    global_regextenonqualify = DEFAULT_REGEXTENONQUALIFY;
23373    global_notifyringing = DEFAULT_NOTIFYRINGING;
23374    global_notifyhold = FALSE;    /*!< Keep track of hold status for a peer */
23375    global_directrtpsetup = FALSE;      /* Experimental feature, disabled by default */
23376    global_alwaysauthreject = 0;
23377    global_allowsubscribe = FALSE;
23378    snprintf(global_useragent, sizeof(global_useragent), "%s %s", DEFAULT_USERAGENT, ast_get_version());
23379    snprintf(global_sdpsession, sizeof(global_sdpsession), "%s %s", DEFAULT_SDPSESSION, ast_get_version());
23380    snprintf(global_sdpowner, sizeof(global_sdpowner), "%s", DEFAULT_SDPOWNER);
23381    global_prematuremediafilter = FALSE;
23382    ast_copy_string(default_notifymime, DEFAULT_NOTIFYMIME, sizeof(default_notifymime));
23383    ast_copy_string(global_realm, S_OR(ast_config_AST_SYSTEM_NAME, DEFAULT_REALM), sizeof(global_realm));
23384    ast_copy_string(default_callerid, DEFAULT_CALLERID, sizeof(default_callerid));
23385    compactheaders = DEFAULT_COMPACTHEADERS;
23386    global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
23387    global_regattempts_max = 0;
23388    pedanticsipchecking = DEFAULT_PEDANTIC;
23389    autocreatepeer = DEFAULT_AUTOCREATEPEER;
23390    global_autoframing = 0;
23391    global_allowguest = DEFAULT_ALLOWGUEST;
23392    global_callcounter = DEFAULT_CALLCOUNTER;
23393    global_match_auth_username = FALSE;    /*!< Match auth username if available instead of From: Default off. */
23394    global_rtptimeout = 0;
23395    global_rtpholdtimeout = 0;
23396    global_rtpkeepalive = 0;
23397    global_allowtransfer = TRANSFER_OPENFORALL;  /* Merrily accept all transfers by default */
23398    global_rtautoclear = 120;
23399    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWSUBSCRIBE);   /* Default for all devices: TRUE */
23400    ast_set_flag(&global_flags[1], SIP_PAGE2_ALLOWOVERLAP);     /* Default for all devices: TRUE */
23401    sip_cfg.peer_rtupdate = TRUE;
23402    global_dynamic_exclude_static = 0;  /* Exclude static peers */
23403 
23404    /* Session-Timers */
23405    global_st_mode = SESSION_TIMER_MODE_ACCEPT;    
23406    global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23407    global_min_se  = DEFAULT_MIN_SE;
23408    global_max_se  = DEFAULT_MAX_SE;
23409 
23410    /* Initialize some reasonable defaults at SIP reload (used both for channel and as default for devices */
23411    ast_copy_string(default_context, DEFAULT_CONTEXT, sizeof(default_context));
23412    default_subscribecontext[0] = '\0';
23413    default_language[0] = '\0';
23414    default_fromdomain[0] = '\0';
23415    default_qualify = DEFAULT_QUALIFY;
23416    default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23417    ast_copy_string(default_mohinterpret, DEFAULT_MOHINTERPRET, sizeof(default_mohinterpret));
23418    ast_copy_string(default_mohsuggest, DEFAULT_MOHSUGGEST, sizeof(default_mohsuggest));
23419    ast_copy_string(default_vmexten, DEFAULT_VMEXTEN, sizeof(default_vmexten));
23420    ast_set_flag(&global_flags[0], SIP_DTMF_RFC2833);        /*!< Default DTMF setting: RFC2833 */
23421    ast_set_flag(&global_flags[0], SIP_NAT_RFC3581);         /*!< NAT support if requested by device with rport */
23422    ast_set_flag(&global_flags[0], SIP_CAN_REINVITE);        /*!< Allow re-invites */
23423 
23424    /* Debugging settings, always default to off */
23425    dumphistory = FALSE;
23426    recordhistory = FALSE;
23427    sipdebug &= ~sip_debug_config;
23428 
23429    /* Misc settings for the channel */
23430    global_relaxdtmf = FALSE;
23431    global_callevents = FALSE;
23432    global_authfailureevents = FALSE;
23433    global_t1 = SIP_TIMER_T1;
23434    global_timer_b = 64 * SIP_TIMER_T1;
23435    global_t1min = DEFAULT_T1MIN;
23436    global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23437    global_t38_maxdatagram = -1;
23438    global_shrinkcallerid = 1;
23439 
23440    global_matchexterniplocally = FALSE;
23441 
23442    /* Copy the default jb config over global_jbconf */
23443    memcpy(&global_jbconf, &default_jbconf, sizeof(struct ast_jb_conf));
23444 
23445    ast_clear_flag(&global_flags[1], SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_VIDEOSUPPORT_ALWAYS);
23446    ast_clear_flag(&global_flags[1], SIP_PAGE2_TEXTSUPPORT);
23447    ast_clear_flag(&global_flags[1], SIP_PAGE2_IGNORESDPVERSION);
23448    ast_clear_flag(&global_flags[1], SIP_PAGE2_FAX_DETECT);
23449 
23450 
23451    /* Read the [general] config section of sip.conf (or from realtime config) */
23452    for (v = ast_variable_browse(cfg, "general"); v; v = v->next) {
23453       if (handle_common_options(&global_flags[0], &dummy[0], v))
23454          continue;
23455       if (handle_t38_options(&global_flags[0], &dummy[0], v, &global_t38_maxdatagram)) {
23456          continue;
23457       }
23458       /* handle jb conf */
23459       if (!ast_jb_read_conf(&global_jbconf, v->name, v->value))
23460          continue;
23461 
23462       if (!strcasecmp(v->name, "context")) {
23463          ast_copy_string(default_context, v->value, sizeof(default_context));
23464       } else if (!strcasecmp(v->name, "subscribecontext")) {
23465          ast_copy_string(default_subscribecontext, v->value, sizeof(default_subscribecontext));
23466       } else if (!strcasecmp(v->name, "callcounter")) {
23467          global_callcounter = ast_true(v->value) ? 1 : 0;
23468       } else if (!strcasecmp(v->name, "allowguest")) {
23469          global_allowguest = ast_true(v->value) ? 1 : 0;
23470       } else if (!strcasecmp(v->name, "realm")) {
23471          ast_copy_string(global_realm, v->value, sizeof(global_realm));
23472       } else if (!strcasecmp(v->name, "useragent")) {
23473          ast_copy_string(global_useragent, v->value, sizeof(global_useragent));
23474          ast_debug(1, "Setting SIP channel User-Agent Name to %s\n", global_useragent);
23475       } else if (!strcasecmp(v->name, "sdpsession")) {
23476          ast_copy_string(global_sdpsession, v->value, sizeof(global_sdpsession));
23477       } else if (!strcasecmp(v->name, "sdpowner")) {
23478          /* Field cannot contain spaces */
23479          if (!strstr(v->value, " "))
23480             ast_copy_string(global_sdpowner, v->value, sizeof(global_sdpowner));
23481          else
23482             ast_log(LOG_WARNING, "'%s' must not contain spaces at line %d.  Using default.\n", v->value, v->lineno);
23483       } else if (!strcasecmp(v->name, "allowtransfer")) {
23484          global_allowtransfer = ast_true(v->value) ? TRANSFER_OPENFORALL : TRANSFER_CLOSED;
23485       } else if (!strcasecmp(v->name, "rtcachefriends")) {
23486          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_RTCACHEFRIENDS);   
23487       } else if (!strcasecmp(v->name, "rtsavesysname")) {
23488          sip_cfg.rtsave_sysname = ast_true(v->value);
23489       } else if (!strcasecmp(v->name, "rtupdate")) {
23490          sip_cfg.peer_rtupdate = ast_true(v->value);
23491       } else if (!strcasecmp(v->name, "ignoreregexpire")) {
23492          sip_cfg.ignore_regexpire = ast_true(v->value);
23493       } else if (!strcasecmp(v->name, "timert1")) {
23494          /* Defaults to 500ms, but RFC 3261 states that it is recommended
23495           * for the value to be set higher, though a lower value is only
23496           * allowed on private networks unconnected to the Internet. */
23497          global_t1 = atoi(v->value);
23498          /* Note that timer B is dependent on the value of T1 */
23499          global_timer_b = global_t1 * 64;
23500       } else if (!strcasecmp(v->name, "t1min")) {
23501          global_t1min = atoi(v->value);
23502       } else if (!strcasecmp(v->name, "tcpenable")) {
23503          sip_tcp_desc.local_address.sin_family = ast_false(v->value) ? 0 : AF_INET;
23504          ast_debug(2, "Enabling TCP socket for listening\n");
23505       } else if (!strcasecmp(v->name, "tcpbindaddr")) {
23506          int family = sip_tcp_desc.local_address.sin_family;
23507          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tcp_desc.local_address))
23508             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
23509          sip_tcp_desc.local_address.sin_family = family;
23510          ast_debug(2, "Setting TCP socket address to %s\n", v->value);
23511       } else if (!strcasecmp(v->name, "tlsenable")) {
23512          default_tls_cfg.enabled = ast_true(v->value) ? TRUE : FALSE;
23513          sip_tls_desc.local_address.sin_family = AF_INET;
23514       } else if (!strcasecmp(v->name, "tlscertfile")) {
23515          ast_free(default_tls_cfg.certfile);
23516          default_tls_cfg.certfile = ast_strdup(v->value);
23517       } else if (!strcasecmp(v->name, "tlscipher")) {
23518          ast_free(default_tls_cfg.cipher);
23519          default_tls_cfg.cipher = ast_strdup(v->value);
23520       } else if (!strcasecmp(v->name, "tlscafile")) {
23521          ast_free(default_tls_cfg.cafile);
23522          default_tls_cfg.cafile = ast_strdup(v->value);
23523       } else if (!strcasecmp(v->name, "tlscapath")) {
23524          ast_free(default_tls_cfg.capath);
23525          default_tls_cfg.capath = ast_strdup(v->value);
23526       } else if (!strcasecmp(v->name, "tlsverifyclient")) {
23527          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_VERIFY_CLIENT);   
23528       } else if (!strcasecmp(v->name, "tlsdontverifyserver")) {
23529          ast_set2_flag(&default_tls_cfg.flags, ast_true(v->value), AST_SSL_DONT_VERIFY_SERVER); 
23530       } else if (!strcasecmp(v->name, "tlsbindaddr")) {
23531          if (ast_parse_arg(v->value, PARSE_INADDR, &sip_tls_desc.local_address))
23532             ast_log(LOG_WARNING, "Invalid %s '%s' at line %d of %s\n", v->name, v->value, v->lineno, config);
23533       } else if (!strcasecmp(v->name, "dynamic_exclude_static") || !strcasecmp(v->name, "dynamic_excludes_static")) {
23534          global_dynamic_exclude_static = ast_true(v->value);
23535       } else if (!strcasecmp(v->name, "contactpermit") || !strcasecmp(v->name, "contactdeny")) {
23536          int ha_error = 0;
23537          global_contact_ha = ast_append_ha(v->name + 7, v->value, global_contact_ha, &ha_error);
23538          if (ha_error) {
23539             ast_log(LOG_ERROR, "Bad ACL entry in configuration line %d : %s\n", v->lineno, v->value);
23540          }
23541       } else if (!strcasecmp(v->name, "rtautoclear")) {
23542          int i = atoi(v->value);
23543          if (i > 0)
23544             global_rtautoclear = i;
23545          else
23546             i = 0;
23547          ast_set2_flag(&global_flags[1], i || ast_true(v->value), SIP_PAGE2_RTAUTOCLEAR);
23548       } else if (!strcasecmp(v->name, "usereqphone")) {
23549          ast_set2_flag(&global_flags[0], ast_true(v->value), SIP_USEREQPHONE);   
23550       } else if (!strcasecmp(v->name, "prematuremedia")) {
23551          global_prematuremediafilter = ast_true(v->value);
23552       } else if (!strcasecmp(v->name, "relaxdtmf")) {
23553          global_relaxdtmf = ast_true(v->value);
23554       } else if (!strcasecmp(v->name, "vmexten")) {
23555          ast_copy_string(default_vmexten, v->value, sizeof(default_vmexten));
23556       } else if (!strcasecmp(v->name, "rtptimeout")) {
23557          if ((sscanf(v->value, "%30d", &global_rtptimeout) != 1) || (global_rtptimeout < 0)) {
23558             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
23559             global_rtptimeout = 0;
23560          }
23561       } else if (!strcasecmp(v->name, "rtpholdtimeout")) {
23562          if ((sscanf(v->value, "%30d", &global_rtpholdtimeout) != 1) || (global_rtpholdtimeout < 0)) {
23563             ast_log(LOG_WARNING, "'%s' is not a valid RTP hold time at line %d.  Using default.\n", v->value, v->lineno);
23564             global_rtpholdtimeout = 0;
23565          }
23566       } else if (!strcasecmp(v->name, "rtpkeepalive")) {
23567          if ((sscanf(v->value, "%30d", &global_rtpkeepalive) != 1) || (global_rtpkeepalive < 0)) {
23568             ast_log(LOG_WARNING, "'%s' is not a valid RTP keepalive time at line %d.  Using default.\n", v->value, v->lineno);
23569             global_rtpkeepalive = 0;
23570          }
23571       } else if (!strcasecmp(v->name, "compactheaders")) {
23572          compactheaders = ast_true(v->value);
23573       } else if (!strcasecmp(v->name, "notifymimetype")) {
23574          ast_copy_string(default_notifymime, v->value, sizeof(default_notifymime));
23575       } else if (!strcasecmp(v->name, "directrtpsetup")) {
23576          global_directrtpsetup = ast_true(v->value);
23577       } else if (!strcasecmp(v->name, "notifyringing")) {
23578          global_notifyringing = ast_true(v->value);
23579       } else if (!strcasecmp(v->name, "notifyhold")) {
23580          global_notifyhold = ast_true(v->value);
23581       } else if (!strcasecmp(v->name, "alwaysauthreject")) {
23582          global_alwaysauthreject = ast_true(v->value);
23583       } else if (!strcasecmp(v->name, "mohinterpret")) {
23584          ast_copy_string(default_mohinterpret, v->value, sizeof(default_mohinterpret));
23585       } else if (!strcasecmp(v->name, "mohsuggest")) {
23586          ast_copy_string(default_mohsuggest, v->value, sizeof(default_mohsuggest));
23587       } else if (!strcasecmp(v->name, "language")) {
23588          ast_copy_string(default_language, v->value, sizeof(default_language));
23589       } else if (!strcasecmp(v->name, "regcontext")) {
23590          ast_copy_string(newcontexts, v->value, sizeof(newcontexts));
23591          stringp = newcontexts;
23592          /* Let's remove any contexts that are no longer defined in regcontext */
23593          cleanup_stale_contexts(stringp, oldregcontext);
23594          /* Create contexts if they don't exist already */
23595          while ((context = strsep(&stringp, "&"))) {
23596             ast_copy_string(used_context, context, sizeof(used_context));
23597             ast_context_find_or_create(NULL, NULL, context, "SIP");
23598          }
23599          ast_copy_string(global_regcontext, v->value, sizeof(global_regcontext));
23600       } else if (!strcasecmp(v->name, "regextenonqualify")) {
23601          global_regextenonqualify = ast_true(v->value);
23602       } else if (!strcasecmp(v->name, "callerid")) {
23603          ast_copy_string(default_callerid, v->value, sizeof(default_callerid));
23604       } else if (!strcasecmp(v->name, "fromdomain")) {
23605          ast_copy_string(default_fromdomain, v->value, sizeof(default_fromdomain));
23606       } else if (!strcasecmp(v->name, "outboundproxy")) {
23607          int portnum;
23608          char *tok, *proxyname;
23609 
23610          if (ast_strlen_zero(v->value)) {
23611             ast_log(LOG_WARNING, "no value given for outbound proxy on line %d of sip.conf.", v->lineno);
23612             continue;
23613          }
23614 
23615          tok = ast_skip_blanks(strtok(ast_strdupa(v->value), ","));
23616 
23617          sip_parse_host(tok, v->lineno, &proxyname, &portnum, &global_outboundproxy.transport);
23618 
23619          global_outboundproxy.ip.sin_port = htons(portnum);
23620    
23621          if ((tok = strtok(NULL, ","))) {
23622             global_outboundproxy.force = !strncasecmp(ast_skip_blanks(tok), "force", 5);
23623          } else {
23624             global_outboundproxy.force = FALSE;
23625          }
23626 
23627          if (ast_strlen_zero(proxyname)) {
23628             ast_log(LOG_WARNING, "you must specify a name for the outboundproxy on line %d of sip.conf.", v->lineno);
23629             global_outboundproxy.name[0] = '\0';
23630             continue;
23631          }
23632 
23633          ast_copy_string(global_outboundproxy.name, proxyname, sizeof(global_outboundproxy.name));
23634 
23635          proxy_update(&global_outboundproxy);
23636       } else if (!strcasecmp(v->name, "autocreatepeer")) {
23637          autocreatepeer = ast_true(v->value);
23638       } else if (!strcasecmp(v->name, "match_auth_username")) {
23639          global_match_auth_username = ast_true(v->value);
23640       } else if (!strcasecmp(v->name, "srvlookup")) {
23641          global_srvlookup = ast_true(v->value);
23642       } else if (!strcasecmp(v->name, "pedantic")) {
23643          pedanticsipchecking = ast_true(v->value);
23644       } else if (!strcasecmp(v->name, "maxexpirey") || !strcasecmp(v->name, "maxexpiry")) {
23645          max_expiry = atoi(v->value);
23646          if (max_expiry < 1)
23647             max_expiry = DEFAULT_MAX_EXPIRY;
23648       } else if (!strcasecmp(v->name, "minexpirey") || !strcasecmp(v->name, "minexpiry")) {
23649          min_expiry = atoi(v->value);
23650          if (min_expiry < 1)
23651             min_expiry = DEFAULT_MIN_EXPIRY;
23652       } else if (!strcasecmp(v->name, "defaultexpiry") || !strcasecmp(v->name, "defaultexpirey")) {
23653          default_expiry = atoi(v->value);
23654          if (default_expiry < 1)
23655             default_expiry = DEFAULT_DEFAULT_EXPIRY;
23656       } else if (!strcasecmp(v->name, "sipdebug")) {
23657          if (ast_true(v->value))
23658             sipdebug |= sip_debug_config;
23659       } else if (!strcasecmp(v->name, "dumphistory")) {
23660          dumphistory = ast_true(v->value);
23661       } else if (!strcasecmp(v->name, "recordhistory")) {
23662          recordhistory = ast_true(v->value);
23663       } else if (!strcasecmp(v->name, "registertimeout")) {
23664          global_reg_timeout = atoi(v->value);
23665          if (global_reg_timeout < 1)
23666             global_reg_timeout = DEFAULT_REGISTRATION_TIMEOUT;
23667       } else if (!strcasecmp(v->name, "registerattempts")) {
23668          global_regattempts_max = atoi(v->value);
23669       } else if (!strcasecmp(v->name, "stunaddr")) {
23670          stunaddr.sin_port = htons(3478);
23671          if (ast_parse_arg(v->value, PARSE_INADDR, &stunaddr))
23672             ast_log(LOG_WARNING, "Invalid STUN server address: %s\n", v->value);
23673          externexpire = time(NULL);
23674       } else if (!strcasecmp(v->name, "bindaddr") || !strcasecmp(v->name, "udpbindaddr")) {
23675          if (ast_parse_arg(v->value, PARSE_INADDR, &bindaddr))
23676             ast_log(LOG_WARNING, "Invalid address: %s\n", v->value);
23677       } else if (!strcasecmp(v->name, "localnet")) {
23678          struct ast_ha *na;
23679          int ha_error = 0;
23680 
23681          if (!(na = ast_append_ha("d", v->value, localaddr, &ha_error)))
23682             ast_log(LOG_WARNING, "Invalid localnet value: %s\n", v->value);
23683          else
23684             localaddr = na;
23685          if (ha_error)
23686             ast_log(LOG_ERROR, "Bad localnet configuration value line %d : %s\n", v->lineno, v->value);
23687       } else if (!strcasecmp(v->name, "externip")) {
23688          if (ast_parse_arg(v->value, PARSE_INADDR, &externip))
23689             ast_log(LOG_WARNING, "Invalid address for externip keyword: %s\n", v->value);
23690          externexpire = 0;
23691          /* If no port was specified use the value of bindport */
23692          if (!externip.sin_port)
23693             externip.sin_port = bindaddr.sin_port;
23694       } else if (!strcasecmp(v->name, "externhost")) {
23695          ast_copy_string(externhost, v->value, sizeof(externhost));
23696          if (ast_parse_arg(externhost, PARSE_INADDR, &externip))
23697             ast_log(LOG_WARNING, "Invalid address for externhost keyword: %s\n", externhost);
23698          externexpire = time(NULL);
23699          /* If no port was specified use the value of bindport */
23700          if (!externip.sin_port)
23701             externip.sin_port = bindaddr.sin_port;
23702       } else if (!strcasecmp(v->name, "externrefresh")) {
23703          if (sscanf(v->value, "%30d", &externrefresh) != 1) {
23704             ast_log(LOG_WARNING, "Invalid externrefresh value '%s', must be an integer >0 at line %d\n", v->value, v->lineno);
23705             externrefresh = 10;
23706          }
23707       } else if (!strcasecmp(v->name, "allow")) {
23708          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, TRUE);
23709          if (error)
23710             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23711       } else if (!strcasecmp(v->name, "disallow")) {
23712          int error =  ast_parse_allow_disallow(&default_prefs, &global_capability, v->value, FALSE);
23713          if (error)
23714             ast_log(LOG_WARNING, "Codec configuration errors found in line %d : %s = %s\n", v->lineno, v->name, v->value);
23715       } else if (!strcasecmp(v->name, "autoframing")) {
23716          global_autoframing = ast_true(v->value);
23717       } else if (!strcasecmp(v->name, "allowexternaldomains")) {
23718          allow_external_domains = ast_true(v->value);
23719       } else if (!strcasecmp(v->name, "autodomain")) {
23720          auto_sip_domains = ast_true(v->value);
23721       } else if (!strcasecmp(v->name, "domain")) {
23722          char *domain = ast_strdupa(v->value);
23723          char *cntx = strchr(domain, ',');
23724 
23725          if (cntx)
23726             *cntx++ = '\0';
23727 
23728          if (ast_strlen_zero(cntx))
23729             ast_debug(1, "No context specified at line %d for domain '%s'\n", v->lineno, domain);
23730          if (ast_strlen_zero(domain))
23731             ast_log(LOG_WARNING, "Empty domain specified at line %d\n", v->lineno);
23732          else
23733             add_sip_domain(ast_strip(domain), SIP_DOMAIN_CONFIG, cntx ? ast_strip(cntx) : "");
23734       } else if (!strcasecmp(v->name, "register")) {
23735          if (sip_register(v->value, v->lineno) == 0)
23736             registry_count++;
23737       } else if (!strcasecmp(v->name, "tos_sip")) {
23738          if (ast_str2tos(v->value, &global_tos_sip))
23739             ast_log(LOG_WARNING, "Invalid tos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23740       } else if (!strcasecmp(v->name, "tos_audio")) {
23741          if (ast_str2tos(v->value, &global_tos_audio))
23742             ast_log(LOG_WARNING, "Invalid tos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23743       } else if (!strcasecmp(v->name, "tos_video")) {
23744          if (ast_str2tos(v->value, &global_tos_video))
23745             ast_log(LOG_WARNING, "Invalid tos_video value at line %d, refer to QoS documentation\n", v->lineno);
23746       } else if (!strcasecmp(v->name, "tos_text")) {
23747          if (ast_str2tos(v->value, &global_tos_text))
23748             ast_log(LOG_WARNING, "Invalid tos_text value at line %d, refer to QoS documentation\n", v->lineno);
23749       } else if (!strcasecmp(v->name, "cos_sip")) {
23750          if (ast_str2cos(v->value, &global_cos_sip))
23751             ast_log(LOG_WARNING, "Invalid cos_sip value at line %d, refer to QoS documentation\n", v->lineno);
23752       } else if (!strcasecmp(v->name, "cos_audio")) {
23753          if (ast_str2cos(v->value, &global_cos_audio))
23754             ast_log(LOG_WARNING, "Invalid cos_audio value at line %d, refer to QoS documentation\n", v->lineno);
23755       } else if (!strcasecmp(v->name, "cos_video")) {
23756          if (ast_str2cos(v->value, &global_cos_video))
23757             ast_log(LOG_WARNING, "Invalid cos_video value at line %d, refer to QoS documentation\n", v->lineno);
23758       } else if (!strcasecmp(v->name, "cos_text")) {
23759          if (ast_str2cos(v->value, &global_cos_text))
23760             ast_log(LOG_WARNING, "Invalid cos_text value at line %d, refer to QoS documentation\n", v->lineno);
23761       } else if (!strcasecmp(v->name, "bindport")) {
23762          int i;
23763          if (sscanf(v->value, "%5d", &i) == 1) {
23764             bindaddr.sin_port = htons(i);
23765          } else {
23766             ast_log(LOG_WARNING, "Invalid port number '%s' at line %d of %s\n", v->value, v->lineno, config);
23767          }
23768       } else if (!strcasecmp(v->name, "hash_user")) {
23769          int i;
23770          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23771             hash_user_size = i;
23772          } else {
23773             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);
23774          }
23775       } else if (!strcasecmp(v->name, "hash_peer")) {
23776          int i;
23777          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23778             hash_peer_size = i;
23779          } else {
23780             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);
23781          }
23782       } else if (!strcasecmp(v->name, "hash_dialog")) {
23783          int i;
23784          if (sscanf(v->value, "%30d", &i) == 1 && i > 2) {
23785             hash_dialog_size = i;
23786          } else {
23787             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);
23788          }
23789       } else if (!strcasecmp(v->name, "qualify")) {
23790          if (!strcasecmp(v->value, "no")) {
23791             default_qualify = 0;
23792          } else if (!strcasecmp(v->value, "yes")) {
23793             default_qualify = DEFAULT_MAXMS;
23794          } else if (sscanf(v->value, "%30d", &default_qualify) != 1) {
23795             ast_log(LOG_WARNING, "Qualification default should be 'yes', 'no', or a number of milliseconds at line %d of sip.conf\n", v->lineno);
23796             default_qualify = 0;
23797          }
23798       } else if (!strcasecmp(v->name, "qualifyfreq")) {
23799          int i;
23800          if (sscanf(v->value, "%30d", &i) == 1)
23801             global_qualifyfreq = i * 1000;
23802          else {
23803             ast_log(LOG_WARNING, "Invalid qualifyfreq number '%s' at line %d of %s\n", v->value, v->lineno, config);
23804             global_qualifyfreq = DEFAULT_QUALIFYFREQ;
23805          }
23806       } else if (!strcasecmp(v->name, "callevents")) {
23807          global_callevents = ast_true(v->value);
23808       } else if (!strcasecmp(v->name, "authfailureevents")) {
23809          global_authfailureevents = ast_true(v->value);
23810       } else if (!strcasecmp(v->name, "maxcallbitrate")) {
23811          default_maxcallbitrate = atoi(v->value);
23812          if (default_maxcallbitrate < 0)
23813             default_maxcallbitrate = DEFAULT_MAX_CALL_BITRATE;
23814       } else if (!strcasecmp(v->name, "matchexterniplocally")) {
23815          global_matchexterniplocally = ast_true(v->value);
23816       } else if (!strcasecmp(v->name, "constantssrc")) {
23817          ast_set2_flag(&global_flags[1], ast_true(v->value), SIP_PAGE2_CONSTANT_SSRC);
23818       } else if (!strcasecmp(v->name, "session-timers")) {
23819          int i = (int) str2stmode(v->value); 
23820          if (i < 0) {
23821             ast_log(LOG_WARNING, "Invalid session-timers '%s' at line %d of %s\n", v->value, v->lineno, config);
23822             global_st_mode = SESSION_TIMER_MODE_ACCEPT;
23823          } else {
23824             global_st_mode = i;
23825          }
23826       } else if (!strcasecmp(v->name, "session-expires")) {
23827          if (sscanf(v->value, "%30d", &global_max_se) != 1) {
23828             ast_log(LOG_WARNING, "Invalid session-expires '%s' at line %d of %s\n", v->value, v->lineno, config);
23829             global_max_se = DEFAULT_MAX_SE;
23830          } 
23831       } else if (!strcasecmp(v->name, "session-minse")) {
23832          if (sscanf(v->value, "%30d", &global_min_se) != 1) {
23833             ast_log(LOG_WARNING, "Invalid session-minse '%s' at line %d of %s\n", v->value, v->lineno, config);
23834             global_min_se = DEFAULT_MIN_SE;
23835          } 
23836          if (global_min_se < 90) {
23837             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);
23838             global_min_se = DEFAULT_MIN_SE;
23839          } 
23840       } else if (!strcasecmp(v->name, "session-refresher")) {
23841          int i = (int) str2strefresher(v->value); 
23842          if (i < 0) {
23843             ast_log(LOG_WARNING, "Invalid session-refresher '%s' at line %d of %s\n", v->value, v->lineno, config);
23844             global_st_refresher = SESSION_TIMER_REFRESHER_UAS;
23845          } else {
23846             global_st_refresher = i;
23847          }
23848       } else if (!strcasecmp(v->name, "shrinkcallerid")) {
23849          if (ast_true(v->value)) {
23850             global_shrinkcallerid = 1;
23851          } else if (ast_false(v->value)) {
23852             global_shrinkcallerid = 0;
23853          } else {
23854             ast_log(LOG_WARNING, "shrinkcallerid value %s is not valid at line %d.\n", v->value, v->lineno);
23855          }
23856       }
23857    }
23858 
23859    if (!allow_external_domains && AST_LIST_EMPTY(&domain_list)) {
23860       ast_log(LOG_WARNING, "To disallow external domains, you need to configure local SIP domains.\n");
23861       allow_external_domains = 1;
23862    }
23863    
23864    /* Build list of authentication to various SIP realms, i.e. service providers */
23865    for (v = ast_variable_browse(cfg, "authentication"); v ; v = v->next) {
23866       /* Format for authentication is auth = username:password@realm */
23867       if (!strcasecmp(v->name, "auth"))
23868          authl = add_realm_authentication(authl, v->value, v->lineno);
23869    }
23870    
23871    if (ucfg) {
23872       struct ast_variable *gen;
23873       int genhassip, genregistersip;
23874       const char *hassip, *registersip;
23875       
23876       genhassip = ast_true(ast_variable_retrieve(ucfg, "general", "hassip"));
23877       genregistersip = ast_true(ast_variable_retrieve(ucfg, "general", "registersip"));
23878       gen = ast_variable_browse(ucfg, "general");
23879       cat = ast_category_browse(ucfg, NULL);
23880       while (cat) {
23881          if (strcasecmp(cat, "general")) {
23882             hassip = ast_variable_retrieve(ucfg, cat, "hassip");
23883             registersip = ast_variable_retrieve(ucfg, cat, "registersip");
23884             if (ast_true(hassip) || (!hassip && genhassip)) {
23885                peer = build_peer(cat, gen, ast_variable_browse(ucfg, cat), 0, 0);
23886                if (peer) {
23887                   /* user.conf entries are always of type friend */
23888                   peer->type = SIP_TYPE_USER | SIP_TYPE_PEER;
23889                   ao2_t_link(peers, peer, "link peer into peer table");
23890                   if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23891                      ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23892                   }
23893                   
23894                   unref_peer(peer, "unref_peer: from reload_config");
23895                   peer_count++;
23896                }
23897             }
23898             if (ast_true(registersip) || (!registersip && genregistersip)) {
23899                char tmp[256];
23900                const char *host = ast_variable_retrieve(ucfg, cat, "host");
23901                const char *username = ast_variable_retrieve(ucfg, cat, "username");
23902                const char *secret = ast_variable_retrieve(ucfg, cat, "secret");
23903                const char *contact = ast_variable_retrieve(ucfg, cat, "contact");
23904                const char *authuser = ast_variable_retrieve(ucfg, cat, "authuser");
23905                if (!host)
23906                   host = ast_variable_retrieve(ucfg, "general", "host");
23907                if (!username)
23908                   username = ast_variable_retrieve(ucfg, "general", "username");
23909                if (!secret)
23910                   secret = ast_variable_retrieve(ucfg, "general", "secret");
23911                if (!contact)
23912                   contact = "s";
23913                if (!ast_strlen_zero(username) && !ast_strlen_zero(host)) {
23914                   if (!ast_strlen_zero(secret)) {
23915                      if (!ast_strlen_zero(authuser)) {
23916                         snprintf(tmp, sizeof(tmp), "%s:%s:%s@%s/%s", username, secret, authuser, host, contact);
23917                      } else {
23918                         snprintf(tmp, sizeof(tmp), "%s:%s@%s/%s", username, secret, host, contact);
23919                      }
23920                   } else if (!ast_strlen_zero(authuser)) {
23921                      snprintf(tmp, sizeof(tmp), "%s::%s@%s/%s", username, authuser, host, contact);
23922                   } else {
23923                      snprintf(tmp, sizeof(tmp), "%s@%s/%s", username, host, contact);
23924                   }
23925                   if (sip_register(tmp, 0) == 0)
23926                      registry_count++;
23927                }
23928             }
23929          }
23930          cat = ast_category_browse(ucfg, cat);
23931       }
23932       ast_config_destroy(ucfg);
23933    }
23934    
23935 
23936    /* Load peers, users and friends */
23937    cat = NULL;
23938    while ( (cat = ast_category_browse(cfg, cat)) ) {
23939       const char *utype;
23940       if (!strcasecmp(cat, "general") || !strcasecmp(cat, "authentication"))
23941          continue;
23942       utype = ast_variable_retrieve(cfg, cat, "type");
23943       if (!utype) {
23944          ast_log(LOG_WARNING, "Section '%s' lacks type\n", cat);
23945          continue;
23946       } else {
23947          if (!strcasecmp(utype, "user")) {
23948             ;
23949          } else if (!strcasecmp(utype, "friend")) {
23950             ;
23951          } else if (!strcasecmp(utype, "peer")) {
23952             ;
23953          } else {
23954             ast_log(LOG_WARNING, "Unknown type '%s' for '%s' in %s\n", utype, cat, "sip.conf");
23955             continue;
23956          }
23957          peer = build_peer(cat, ast_variable_browse(cfg, cat), NULL, 0, 0);
23958          if (peer) {
23959             ao2_t_link(peers, peer, "link peer into peers table");
23960             if ((peer->type & SIP_TYPE_PEER) && peer->addr.sin_addr.s_addr) {
23961                ao2_t_link(peers_by_ip, peer, "link peer into peers_by_ip table");
23962             }
23963             unref_peer(peer, "unref the result of the build_peer call. Now, the links from the tables are the only ones left.");
23964             peer_count++;
23965          }
23966       }
23967    }
23968    
23969    /* Set UDP address and open socket */
23970    bindaddr.sin_family = AF_INET;
23971    internip = bindaddr;
23972    if (ast_find_ourip(&internip.sin_addr, bindaddr)) {
23973       ast_log(LOG_WARNING, "Unable to get own IP address, SIP disabled\n");
23974       ast_config_destroy(cfg);
23975       return 0;
23976    }
23977    ast_mutex_lock(&netlock);
23978    if ((sipsock > -1) && (memcmp(&old_bindaddr, &bindaddr, sizeof(struct sockaddr_in)))) {
23979       close(sipsock);
23980       sipsock = -1;
23981    }
23982    if (sipsock < 0) {
23983       sipsock = socket(AF_INET, SOCK_DGRAM, 0);
23984       if (sipsock < 0) {
23985          ast_log(LOG_WARNING, "Unable to create SIP socket: %s\n", strerror(errno));
23986          ast_config_destroy(cfg);
23987          return -1;
23988       } else {
23989          /* Allow SIP clients on the same host to access us: */
23990          const int reuseFlag = 1;
23991 
23992          setsockopt(sipsock, SOL_SOCKET, SO_REUSEADDR,
23993                (const char*)&reuseFlag,
23994                sizeof reuseFlag);
23995 
23996          ast_enable_packet_fragmentation(sipsock);
23997 
23998          if (bind(sipsock, (struct sockaddr *)&bindaddr, sizeof(bindaddr)) < 0) {
23999             ast_log(LOG_WARNING, "Failed to bind to %s:%d: %s\n",
24000             ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port),
24001             strerror(errno));
24002             close(sipsock);
24003             sipsock = -1;
24004          } else {
24005             ast_verb(2, "SIP Listening on %s:%d\n",
24006                   ast_inet_ntoa(bindaddr.sin_addr), ntohs(bindaddr.sin_port));
24007             ast_netsock_set_qos(sipsock, global_tos_sip, global_cos_sip, "SIP");
24008          }
24009       }
24010    }
24011    if (stunaddr.sin_addr.s_addr != 0) {
24012       ast_debug(1, "stun to %s:%d\n",
24013          ast_inet_ntoa(stunaddr.sin_addr) , ntohs(stunaddr.sin_port));
24014       ast_stun_request(sipsock, &stunaddr,
24015          NULL, &externip);
24016       ast_debug(1, "STUN sees us at %s:%d\n", 
24017          ast_inet_ntoa(externip.sin_addr) , ntohs(externip.sin_port));
24018    }
24019    ast_mutex_unlock(&netlock);
24020 
24021    /* Start TCP server */
24022    ast_tcptls_server_start(&sip_tcp_desc);
24023 
24024    /* Start TLS server if needed */
24025    memcpy(sip_tls_desc.tls_cfg, &default_tls_cfg, sizeof(default_tls_cfg));
24026 
24027    if (ast_ssl_setup(sip_tls_desc.tls_cfg))
24028       ast_tcptls_server_start(&sip_tls_desc);
24029    else if (sip_tls_desc.tls_cfg->enabled) {
24030       sip_tls_desc.tls_cfg = NULL;
24031       ast_log(LOG_WARNING, "SIP TLS server did not load because of errors.\n");
24032    }
24033 
24034 
24035    /* Add default domains - host name, IP address and IP:port
24036     * Only do this if user added any sip domain with "localdomains" 
24037     * In order to *not* break backwards compatibility 
24038     *    Some phones address us at IP only, some with additional port number 
24039     */
24040    if (auto_sip_domains) {
24041       char temp[MAXHOSTNAMELEN];
24042 
24043       /* First our default IP address */
24044       if (bindaddr.sin_addr.s_addr) {
24045          add_sip_domain(ast_inet_ntoa(bindaddr.sin_addr), SIP_DOMAIN_AUTO, NULL);
24046       } else if (internip.sin_addr.s_addr) {
24047       /* Our internal IP address, if configured */
24048          add_sip_domain(ast_inet_ntoa(internip.sin_addr), SIP_DOMAIN_AUTO, NULL);
24049       } else {
24050          ast_log(LOG_NOTICE, "Can't add wildcard IP address to domain list, please add IP address to domain manually.\n");
24051       }
24052 
24053       /* If TCP is running on a different IP than UDP, then add it too */
24054       if (sip_tcp_desc.local_address.sin_addr.s_addr && !inaddrcmp(&bindaddr, &sip_tcp_desc.local_address))
24055          add_sip_domain(ast_inet_ntoa(sip_tcp_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
24056 
24057       /* If TLS is running on a differen IP than UDP and TCP, then add that too */
24058       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))
24059          add_sip_domain(ast_inet_ntoa(sip_tls_desc.local_address.sin_addr), SIP_DOMAIN_AUTO, NULL);
24060 
24061       /* Our extern IP address, if configured */
24062       if (externip.sin_addr.s_addr)
24063          add_sip_domain(ast_inet_ntoa(externip.sin_addr), SIP_DOMAIN_AUTO, NULL);
24064 
24065       /* Extern host name (NAT traversal support) */
24066       if (!ast_strlen_zero(externhost))
24067          add_sip_domain(externhost, SIP_DOMAIN_AUTO, NULL);
24068       
24069       /* Our host name */
24070       if (!gethostname(temp, sizeof(temp)))
24071          add_sip_domain(temp, SIP_DOMAIN_AUTO, NULL);
24072    }
24073 
24074    /* Release configuration from memory */
24075    ast_config_destroy(cfg);
24076 
24077    /* Load the list of manual NOTIFY types to support */
24078    if (notify_types)
24079       ast_config_destroy(notify_types);
24080    notify_types = ast_config_load(notify_config, config_flags);
24081 
24082    /* Done, tell the manager */
24083    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);
24084    run_end = time(0);
24085    ast_debug(4, "SIP reload_config done...Runtime= %d sec\n", (int)(run_end-run_start));
24086 
24087    return 0;
24088 }
24089 
24090 static struct ast_udptl *sip_get_udptl_peer(struct ast_channel *chan)
24091 {
24092    struct sip_pvt *p;
24093    struct ast_udptl *udptl = NULL;
24094    
24095    p = chan->tech_pvt;
24096    if (!p)
24097       return NULL;
24098    
24099    sip_pvt_lock(p);
24100    if (p->udptl && ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24101       udptl = p->udptl;
24102    sip_pvt_unlock(p);
24103    return udptl;
24104 }
24105 
24106 static int sip_set_udptl_peer(struct ast_channel *chan, struct ast_udptl *udptl)
24107 {
24108    struct sip_pvt *p;
24109    
24110    p = chan->tech_pvt;
24111    if (!p)
24112       return -1;
24113    sip_pvt_lock(p);
24114    if (udptl)
24115       ast_udptl_get_peer(udptl, &p->udptlredirip);
24116    else
24117       memset(&p->udptlredirip, 0, sizeof(p->udptlredirip));
24118    if (!ast_test_flag(&p->flags[0], SIP_GOTREFER)) {
24119       if (!p->pendinginvite) {
24120          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);
24121          transmit_reinvite_with_sdp(p, TRUE, FALSE);
24122       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
24123          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);
24124          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);
24125       }
24126    }
24127    /* Reset lastrtprx timer */
24128    p->lastrtprx = p->lastrtptx = time(NULL);
24129    sip_pvt_unlock(p);
24130    return 0;
24131 }
24132 
24133 /*! \brief Returns null if we can't reinvite audio (part of RTP interface) */
24134 static enum ast_rtp_get_result sip_get_rtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24135 {
24136    struct sip_pvt *p = NULL;
24137    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24138 
24139    if (!(p = chan->tech_pvt))
24140       return AST_RTP_GET_FAILED;
24141 
24142    sip_pvt_lock(p);
24143    if (!(p->rtp)) {
24144       sip_pvt_unlock(p);
24145       return AST_RTP_GET_FAILED;
24146    }
24147 
24148    *rtp = p->rtp;
24149 
24150    if (ast_rtp_getnat(*rtp) && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT))
24151       res = AST_RTP_TRY_PARTIAL;
24152    else if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24153       res = AST_RTP_TRY_NATIVE;
24154    else if (ast_test_flag(&global_jbconf, AST_JB_FORCED))
24155       res = AST_RTP_GET_FAILED;
24156 
24157    sip_pvt_unlock(p);
24158 
24159    return res;
24160 }
24161 
24162 /*! \brief Returns null if we can't reinvite video (part of RTP interface) */
24163 static enum ast_rtp_get_result sip_get_vrtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24164 {
24165    struct sip_pvt *p = NULL;
24166    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24167    
24168    if (!(p = chan->tech_pvt))
24169       return AST_RTP_GET_FAILED;
24170 
24171    sip_pvt_lock(p);
24172    if (!(p->vrtp)) {
24173       sip_pvt_unlock(p);
24174       return AST_RTP_GET_FAILED;
24175    }
24176 
24177    *rtp = p->vrtp;
24178 
24179    if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24180       res = AST_RTP_TRY_NATIVE;
24181 
24182    sip_pvt_unlock(p);
24183 
24184    return res;
24185 }
24186 
24187 /*! \brief Returns null if we can't reinvite text (part of RTP interface) */
24188 static enum ast_rtp_get_result sip_get_trtp_peer(struct ast_channel *chan, struct ast_rtp **rtp)
24189 {
24190    struct sip_pvt *p = NULL;
24191    enum ast_rtp_get_result res = AST_RTP_TRY_PARTIAL;
24192    
24193    if (!(p = chan->tech_pvt))
24194       return AST_RTP_GET_FAILED;
24195 
24196    sip_pvt_lock(p);
24197    if (!(p->trtp)) {
24198       sip_pvt_unlock(p);
24199       return AST_RTP_GET_FAILED;
24200    }
24201 
24202    *rtp = p->trtp;
24203 
24204    if (ast_test_flag(&p->flags[0], SIP_CAN_REINVITE))
24205       res = AST_RTP_TRY_NATIVE;
24206 
24207    sip_pvt_unlock(p);
24208 
24209    return res;
24210 }
24211 
24212 /*! \brief Set the RTP peer for this call */
24213 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)
24214 {
24215    struct sip_pvt *p;
24216    int changed = 0;
24217 
24218    p = chan->tech_pvt;
24219    if (!p) 
24220       return -1;
24221 
24222    /* Disable early RTP bridge  */
24223    if (!ast_bridged_channel(chan) && !global_directrtpsetup)   /* We are in early state */
24224       return 0;
24225 
24226    sip_pvt_lock(p);
24227    if (p->alreadygone) {
24228       /* If we're destroyed, don't bother */
24229       sip_pvt_unlock(p);
24230       return 0;
24231    }
24232 
24233    /* if this peer cannot handle reinvites of the media stream to devices
24234       that are known to be behind a NAT, then stop the process now
24235    */
24236    if (nat_active && !ast_test_flag(&p->flags[0], SIP_CAN_REINVITE_NAT)) {
24237       sip_pvt_unlock(p);
24238       return 0;
24239    }
24240 
24241    if (rtp) {
24242       changed |= ast_rtp_get_peer(rtp, &p->redirip);
24243    } else if (p->redirip.sin_addr.s_addr || ntohs(p->redirip.sin_port) != 0) {
24244       memset(&p->redirip, 0, sizeof(p->redirip));
24245       changed = 1;
24246    }
24247    if (vrtp) {
24248       changed |= ast_rtp_get_peer(vrtp, &p->vredirip);
24249    } else if (p->vredirip.sin_addr.s_addr || ntohs(p->vredirip.sin_port) != 0) {
24250       memset(&p->vredirip, 0, sizeof(p->vredirip));
24251       changed = 1;
24252    }
24253    if (trtp) {
24254       changed |= ast_rtp_get_peer(trtp, &p->tredirip);
24255    } else if (p->tredirip.sin_addr.s_addr || ntohs(p->tredirip.sin_port) != 0) {
24256       memset(&p->tredirip, 0, sizeof(p->tredirip));
24257       changed = 1;
24258    }
24259    if (codecs && (p->redircodecs != codecs)) {
24260       p->redircodecs = codecs;
24261       changed = 1;
24262    }
24263    if (changed && !ast_test_flag(&p->flags[0], SIP_GOTREFER) && !ast_test_flag(&p->flags[0], SIP_DEFER_BYE_ON_TRANSFER)) {
24264       if (chan->_state != AST_STATE_UP) { /* We are in early state */
24265          if (p->do_history)
24266             append_history(p, "ExtInv", "Initial invite sent with remote bridge proposal.");
24267          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));
24268       } else if (!p->pendinginvite) {     /* We are up, and have no outstanding invite */
24269          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));
24270          transmit_reinvite_with_sdp(p, FALSE, FALSE);
24271       } else if (!ast_test_flag(&p->flags[0], SIP_PENDINGBYE)) {
24272          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));
24273          /* We have a pending Invite. Send re-invite when we're done with the invite */
24274          ast_set_flag(&p->flags[0], SIP_NEEDREINVITE);   
24275       }
24276    }
24277    /* Reset lastrtprx timer */
24278    p->lastrtprx = p->lastrtptx = time(NULL);
24279    sip_pvt_unlock(p);
24280    return 0;
24281 }
24282 
24283 static char *synopsis_dtmfmode = "Change the dtmfmode for a SIP call";
24284 static char *descrip_dtmfmode = "  SIPDtmfMode(inband|info|rfc2833): Changes the dtmfmode for a SIP call\n";
24285 static char *app_dtmfmode = "SIPDtmfMode";
24286 
24287 static char *app_sipaddheader = "SIPAddHeader";
24288 static char *synopsis_sipaddheader = "Add a SIP header to the outbound call";
24289 
24290 static char *descrip_sipaddheader = ""
24291 "  SIPAddHeader(Header: Content):\n"
24292 "Adds a header to a SIP call placed with DIAL.\n"
24293 "Remember to user the X-header if you are adding non-standard SIP\n"
24294 "headers, like \"X-Asterisk-Accountcode:\". Use this with care.\n"
24295 "Adding the wrong headers may jeopardize the SIP dialog.\n"
24296 "Always returns 0\n";
24297 
24298 
24299 /*! \brief Set the DTMFmode for an outbound SIP call (application) */
24300 static int sip_dtmfmode(struct ast_channel *chan, void *data)
24301 {
24302    struct sip_pvt *p;
24303    char *mode = data;
24304 
24305    if (!data) {
24306       ast_log(LOG_WARNING, "This application requires the argument: info, inband, rfc2833\n");
24307       return 0;
24308    }
24309    ast_channel_lock(chan);
24310    if (!IS_SIP_TECH(chan->tech)) {
24311       ast_log(LOG_WARNING, "Call this application only on SIP incoming calls\n");
24312       ast_channel_unlock(chan);
24313       return 0;
24314    }
24315    p = chan->tech_pvt;
24316    if (!p) {
24317       ast_channel_unlock(chan);
24318       return 0;
24319    }
24320    sip_pvt_lock(p);
24321    if (!strcasecmp(mode, "info")) {
24322       ast_clear_flag(&p->flags[0], SIP_DTMF);
24323       ast_set_flag(&p->flags[0], SIP_DTMF_INFO);
24324       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24325    } else if (!strcasecmp(mode, "shortinfo")) {
24326       ast_clear_flag(&p->flags[0], SIP_DTMF);
24327       ast_set_flag(&p->flags[0], SIP_DTMF_SHORTINFO);
24328       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24329    } else if (!strcasecmp(mode, "rfc2833")) {
24330       ast_clear_flag(&p->flags[0], SIP_DTMF);
24331       ast_set_flag(&p->flags[0], SIP_DTMF_RFC2833);
24332       p->jointnoncodeccapability |= AST_RTP_DTMF;
24333    } else if (!strcasecmp(mode, "inband")) { 
24334       ast_clear_flag(&p->flags[0], SIP_DTMF);
24335       ast_set_flag(&p->flags[0], SIP_DTMF_INBAND);
24336       p->jointnoncodeccapability &= ~AST_RTP_DTMF;
24337    } else
24338       ast_log(LOG_WARNING, "I don't know about this dtmf mode: %s\n", mode);
24339    if (p->rtp)
24340       ast_rtp_setdtmf(p->rtp, ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_RFC2833);
24341    if (ast_test_flag(&p->flags[0], SIP_DTMF) == SIP_DTMF_INBAND) {
24342       if (!p->dsp) {
24343          p->dsp = ast_dsp_new();
24344          ast_dsp_set_features(p->dsp, DSP_FEATURE_DIGIT_DETECT);
24345       }
24346    } else {
24347       if (p->dsp) {
24348          ast_dsp_free(p->dsp);
24349          p->dsp = NULL;
24350       }
24351    }
24352    sip_pvt_unlock(p);
24353    ast_channel_unlock(chan);
24354    return 0;
24355 }
24356 
24357 /*! \brief Add a SIP header to an outbound INVITE */
24358 static int sip_addheader(struct ast_channel *chan, void *data)
24359 {
24360    int no = 0;
24361    int ok = FALSE;
24362    char varbuf[30];
24363    char *inbuf = data, *subbuf;
24364    
24365    if (ast_strlen_zero(inbuf)) {
24366       ast_log(LOG_WARNING, "This application requires the argument: Header\n");
24367       return 0;
24368    }
24369    ast_channel_lock(chan);
24370 
24371    /* Check for headers */
24372    while (!ok && no <= 50) {
24373       no++;
24374       snprintf(varbuf, sizeof(varbuf), "__SIPADDHEADER%.2d", no);
24375 
24376       /* Compare without the leading underscores */
24377       if ((pbx_builtin_getvar_helper(chan, (const char *) varbuf + 2) == (const char *) NULL)) {
24378          ok = TRUE;
24379       }
24380    }
24381    if (ok) {
24382       size_t len = strlen(inbuf);
24383       subbuf = alloca(len + 1);
24384       ast_get_encoded_str(inbuf, subbuf, len + 1);
24385       pbx_builtin_setvar_helper(chan, varbuf, subbuf);
24386       if (sipdebug) {
24387          ast_debug(1, "SIP Header added \"%s\" as %s\n", inbuf, varbuf);
24388       }
24389    } else {
24390       ast_log(LOG_WARNING, "Too many SIP headers added, max 50\n");
24391    }
24392    ast_channel_unlock(chan);
24393    return 0;
24394 }
24395 
24396 /*! \brief Transfer call before connect with a 302 redirect
24397 \note Called by the transfer() dialplan application through the sip_transfer()
24398    pbx interface function if the call is in ringing state 
24399 \todo Fix this function so that we wait for reply to the REFER and
24400    react to errors, denials or other issues the other end might have.
24401  */
24402 static int sip_sipredirect(struct sip_pvt *p, const char *dest)
24403 {
24404    char *cdest;
24405    char *extension, *host, *port;
24406    char tmp[80];
24407 
24408    cdest = ast_strdupa(dest);
24409    
24410    extension = strsep(&cdest, "@");
24411    host = strsep(&cdest, ":");
24412    port = strsep(&cdest, ":");
24413    if (ast_strlen_zero(extension)) {
24414       ast_log(LOG_ERROR, "Missing mandatory argument: extension\n");
24415       return 0;
24416    }
24417 
24418    /* we'll issue the redirect message here */
24419    if (!host) {
24420       char *localtmp;
24421 
24422       ast_copy_string(tmp, get_header(&p->initreq, "To"), sizeof(tmp));
24423       if (ast_strlen_zero(tmp)) {
24424          ast_log(LOG_ERROR, "Cannot retrieve the 'To' header from the original SIP request!\n");
24425          return 0;
24426       }
24427       if ( ( (localtmp = strcasestr(tmp, "sip:")) || (localtmp = strcasestr(tmp, "sips:")) ) 
24428          && (localtmp = strchr(localtmp, '@'))) {
24429          char lhost[80], lport[80];
24430 
24431          memset(lhost, 0, sizeof(lhost));
24432          memset(lport, 0, sizeof(lport));
24433          localtmp++;
24434          /* This is okey because lhost and lport are as big as tmp */
24435          sscanf(localtmp, "%80[^<>:; ]:%80[^<>:; ]", lhost, lport);
24436          if (ast_strlen_zero(lhost)) {
24437             ast_log(LOG_ERROR, "Can't find the host address\n");
24438             return 0;
24439          }
24440          host = ast_strdupa(lhost);
24441          if (!ast_strlen_zero(lport)) {
24442             port = ast_strdupa(lport);
24443          }
24444       }
24445    }
24446 
24447    ast_string_field_build(p, our_contact, "Transfer <sip:%s@%s%s%s>", extension, host, port ? ":" : "", port ? port : "");
24448    transmit_response_reliable(p, "302 Moved Temporarily", &p->initreq);
24449 
24450    sip_scheddestroy(p, SIP_TRANS_TIMEOUT);   /* Make sure we stop send this reply. */
24451    sip_alreadygone(p);
24452    /* hangup here */
24453    return 0;
24454 }
24455 
24456 /*! \brief Return SIP UA's codec (part of the RTP interface) */
24457 static int sip_get_codec(struct ast_channel *chan)
24458 {
24459    struct sip_pvt *p = chan->tech_pvt;
24460    return p->jointcapability ? p->jointcapability : p->capability;   
24461 }
24462 
24463 /*! \brief Send a poke to all known peers 
24464    Space them out 100 ms apart
24465    XXX We might have a cool algorithm for this or use random - any suggestions?
24466 */
24467 static void sip_poke_all_peers(void)
24468 {
24469    int ms = 0;
24470    struct ao2_iterator i;
24471    struct sip_peer *peer;
24472 
24473    if (!speerobjs)   /* No peers, just give up */
24474       return;
24475 
24476    i = ao2_iterator_init(peers, 0);
24477    while ((peer = ao2_t_iterator_next(&i, "iterate thru peers table"))) {
24478       ao2_lock(peer);
24479       ms += 100;
24480       AST_SCHED_REPLACE_UNREF(peer->pokeexpire, sched, ms, sip_poke_peer_s, peer,
24481             unref_peer(_data, "removing poke peer ref"),
24482             unref_peer(peer, "removing poke peer ref"),
24483             ref_peer(peer, "adding poke peer ref"));
24484       ao2_unlock(peer);
24485       unref_peer(peer, "toss iterator peer ptr");
24486    }
24487    ao2_iterator_destroy(&i);
24488 }
24489 
24490 /*! \brief Send all known registrations */
24491 static void sip_send_all_registers(void)
24492 {
24493    int ms;
24494    int regspacing;
24495    if (!regobjs)
24496       return;
24497    regspacing = default_expiry * 1000/regobjs;
24498    if (regspacing > 100)
24499       regspacing = 100;
24500    ms = regspacing;
24501    ASTOBJ_CONTAINER_TRAVERSE(&regl, 1, do {
24502       ASTOBJ_WRLOCK(iterator);
24503       ms += regspacing;
24504       AST_SCHED_REPLACE_UNREF(iterator->expire, sched, ms, sip_reregister, iterator, 
24505                         registry_unref(_data, "REPLACE sched del decs the refcount"),
24506                         registry_unref(iterator, "REPLACE sched add failure decs the refcount"),
24507                         registry_addref(iterator, "REPLACE sched add incs the refcount"));
24508       ASTOBJ_UNLOCK(iterator);
24509    } while (0)
24510    );
24511 }
24512 
24513 /*! \brief Reload module */
24514 static int sip_do_reload(enum channelreloadreason reason)
24515 {
24516    time_t start_poke, end_poke;
24517    
24518    reload_config(reason);
24519    ast_sched_dump(sched);
24520 
24521    start_poke = time(0);
24522    /* Prune peers who still are supposed to be deleted */
24523    ao2_t_callback(peers, OBJ_NODATA | OBJ_UNLINK | OBJ_MULTIPLE, peer_is_marked, 0, 
24524          "callback to remove marked peers");
24525    
24526    ast_debug(4, "--------------- Done destroying pruned peers\n");
24527 
24528    /* Send qualify (OPTIONS) to all peers */
24529    sip_poke_all_peers();
24530 
24531    /* Register with all services */
24532    sip_send_all_registers();
24533    end_poke = time(0);
24534    
24535    ast_debug(4, "do_reload finished. peer poke/prune reg contact time = %d sec.\n", (int)(end_poke-start_poke));
24536 
24537    ast_debug(4, "--------------- SIP reload done\n");
24538 
24539    return 0;
24540 }
24541 
24542 /*! \brief Force reload of module from cli */
24543 static char *sip_reload(struct ast_cli_entry *e, int cmd, struct ast_cli_args *a)
24544 {
24545    
24546    switch (cmd) {
24547    case CLI_INIT:
24548       e->command = "sip reload";
24549       e->usage =
24550          "Usage: sip reload\n"
24551          "       Reloads SIP configuration from sip.conf\n";
24552       return NULL;
24553    case CLI_GENERATE:
24554       return NULL;
24555    }
24556 
24557    ast_mutex_lock(&sip_reload_lock);
24558    if (sip_reloading) 
24559       ast_verbose("Previous SIP reload not yet done\n");
24560    else {
24561       sip_reloading = TRUE;
24562       sip_reloadreason = (a && a->fd) ? CHANNEL_CLI_RELOAD : CHANNEL_MODULE_RELOAD;
24563    }
24564    ast_mutex_unlock(&sip_reload_lock);
24565    restart_monitor();
24566 
24567    return CLI_SUCCESS;
24568 }
24569 
24570 /*! \brief  Part of Asterisk module interface */
24571 static int reload(void)
24572 {
24573    if (sip_reload(0, 0, NULL))
24574       return 0;
24575    return 1;
24576 }
24577 
24578 static struct ast_cli_entry cli_sip_do_history_deprecated = AST_CLI_DEFINE(sip_do_history_deprecated, "Enable/Disable SIP history");
24579 /*! \brief SIP Cli commands definition */
24580 static struct ast_cli_entry cli_sip[] = {
24581    AST_CLI_DEFINE(sip_show_channels, "List active SIP channels or subscriptions"),
24582    AST_CLI_DEFINE(sip_show_channelstats, "List statistics for active SIP channels"),
24583    AST_CLI_DEFINE(sip_show_domains, "List our local SIP domains"),
24584    AST_CLI_DEFINE(sip_show_inuse, "List all inuse/limits"),
24585    AST_CLI_DEFINE(sip_show_objects, "List all SIP object allocations"),
24586    AST_CLI_DEFINE(sip_show_peers, "List defined SIP peers"),
24587    AST_CLI_DEFINE(sip_show_registry, "List SIP registration status"),
24588    AST_CLI_DEFINE(sip_unregister, "Unregister (force expiration) a SIP peer from the registry"),
24589    AST_CLI_DEFINE(sip_show_settings, "Show SIP global settings"),
24590    AST_CLI_DEFINE(sip_cli_notify, "Send a notify packet to a SIP peer"),
24591    AST_CLI_DEFINE(sip_show_channel, "Show detailed SIP channel info"),
24592    AST_CLI_DEFINE(sip_show_history, "Show SIP dialog history"),
24593    AST_CLI_DEFINE(sip_show_peer, "Show details on specific SIP peer"),
24594    AST_CLI_DEFINE(sip_show_users, "List defined SIP users"),
24595    AST_CLI_DEFINE(sip_show_user, "Show details on specific SIP user"),
24596    AST_CLI_DEFINE(sip_qualify_peer, "Send an OPTIONS packet to a peer"),
24597    AST_CLI_DEFINE(sip_show_sched, "Present a report on the status of the sched queue"),
24598    AST_CLI_DEFINE(sip_prune_realtime, "Prune cached Realtime users/peers"),
24599    AST_CLI_DEFINE(sip_do_debug, "Enable/Disable SIP debugging"),
24600    AST_CLI_DEFINE(sip_set_history, "Enable/Disable SIP history", .deprecate_cmd = &cli_sip_do_history_deprecated),
24601    AST_CLI_DEFINE(sip_reload, "Reload SIP configuration"),
24602    AST_CLI_DEFINE(sip_show_tcp, "List TCP Connections")
24603 };
24604 
24605 /*! \brief PBX load module - initialization */
24606 static int load_module(void)
24607 {
24608    ast_verbose("SIP channel loading...\n");
24609    /* the fact that ao2_containers can't resize automatically is a major worry! */
24610    /* if the number of objects gets above MAX_XXX_BUCKETS, things will slow down */
24611    peers = ao2_t_container_alloc(hash_peer_size, peer_hash_cb, peer_cmp_cb, "allocate peers");
24612    peers_by_ip = ao2_t_container_alloc(hash_peer_size, peer_iphash_cb, peer_ipcmp_cb, "allocate peers_by_ip");
24613    dialogs = ao2_t_container_alloc(hash_dialog_size, dialog_hash_cb, dialog_cmp_cb, "allocate dialogs");
24614    threadt = ao2_t_container_alloc(hash_dialog_size, threadt_hash_cb, threadt_cmp_cb, "allocate threadt table");
24615    
24616    ASTOBJ_CONTAINER_INIT(&regl); /* Registry object list -- not searched for anything */
24617 
24618    if (!(sched = sched_context_create())) {
24619       ast_log(LOG_ERROR, "Unable to create scheduler context\n");
24620       return AST_MODULE_LOAD_FAILURE;
24621    }
24622 
24623    if (!(io = io_context_create())) {
24624       ast_log(LOG_ERROR, "Unable to create I/O context\n");
24625       sched_context_destroy(sched);
24626       return AST_MODULE_LOAD_FAILURE;
24627    }
24628 
24629    sip_reloadreason = CHANNEL_MODULE_LOAD;
24630 
24631    if(reload_config(sip_reloadreason)) /* Load the configuration from sip.conf */
24632       return AST_MODULE_LOAD_DECLINE;
24633 
24634    /* Prepare the version that does not require DTMF BEGIN frames.
24635     * We need to use tricks such as memcpy and casts because the variable
24636     * has const fields.
24637     */
24638    memcpy(&sip_tech_info, &sip_tech, sizeof(sip_tech));
24639    memset((void *) &sip_tech_info.send_digit_begin, 0, sizeof(sip_tech_info.send_digit_begin));
24640 
24641    /* Make sure we can register our sip channel type */
24642    if (ast_channel_register(&sip_tech)) {
24643       ast_log(LOG_ERROR, "Unable to register channel type 'SIP'\n");
24644       io_context_destroy(io);
24645       sched_context_destroy(sched);
24646       return AST_MODULE_LOAD_FAILURE;
24647    }
24648 
24649    /* Register all CLI functions for SIP */
24650    ast_cli_register_multiple(cli_sip, sizeof(cli_sip)/ sizeof(struct ast_cli_entry));
24651 
24652    /* Tell the RTP subdriver that we're here */
24653    ast_rtp_proto_register(&sip_rtp);
24654 
24655    /* Tell the UDPTL subdriver that we're here */
24656    ast_udptl_proto_register(&sip_udptl);
24657 
24658    /* Register dialplan applications */
24659    ast_register_application(app_dtmfmode, sip_dtmfmode, synopsis_dtmfmode, descrip_dtmfmode);
24660    ast_register_application(app_sipaddheader, sip_addheader, synopsis_sipaddheader, descrip_sipaddheader);
24661 
24662    /* Register dialplan functions */
24663    ast_custom_function_register(&sip_header_function);
24664    ast_custom_function_register(&sippeer_function);
24665    ast_custom_function_register(&sipchaninfo_function);
24666    ast_custom_function_register(&checksipdomain_function);
24667 
24668    /* Register manager commands */
24669    ast_manager_register2("SIPpeers", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peers,
24670          "List SIP peers (text format)", mandescr_show_peers);
24671    ast_manager_register2("SIPshowpeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_show_peer,
24672          "Show SIP peer (text format)", mandescr_show_peer);
24673    ast_manager_register2("SIPqualifypeer", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_sip_qualify_peer,
24674          "Show SIP peer (text format)", mandescr_show_peer);   /*! \todo Fix this XXX This must be all wrong XXXX */
24675    ast_manager_register2("SIPshowregistry", EVENT_FLAG_SYSTEM | EVENT_FLAG_REPORTING, manager_show_registry,
24676          "Show SIP registrations (text format)", mandescr_show_registry);
24677    ast_manager_register2("SIPnotify", EVENT_FLAG_SYSTEM, manager_sipnotify,
24678          "Send a SIP notify", mandescr_sipnotify);
24679    sip_poke_all_peers();   
24680    sip_send_all_registers();
24681    
24682    /* And start the monitor for the first time */
24683    restart_monitor();
24684 
24685    ast_realtime_require_field(ast_check_realtime("sipregs") ? "sipregs" : "sippeers",
24686       "name", RQ_CHAR, 10,
24687       "ipaddr", RQ_CHAR, 15,
24688       "port", RQ_UINTEGER2, 5,
24689       "regseconds", RQ_INTEGER4, 11,
24690       "defaultuser", RQ_CHAR, 10,
24691       "fullcontact", RQ_CHAR, 35,
24692       "regserver", RQ_CHAR, 20,
24693       "useragent", RQ_CHAR, 20,
24694       "lastms", RQ_INTEGER4, 11,
24695       SENTINEL);
24696 
24697    return AST_MODULE_LOAD_SUCCESS;
24698 }
24699 
24700 /*! \brief PBX unload module API */
24701 static int unload_module(void)
24702 {
24703    struct sip_pvt *p;
24704    struct sip_threadinfo *th;
24705    struct ast_context *con;
24706    struct ao2_iterator i;
24707 
24708    ast_sched_dump(sched);
24709    
24710    /* First, take us out of the channel type list */
24711    ast_channel_unregister(&sip_tech);
24712 
24713    /* Unregister dial plan functions */
24714    ast_custom_function_unregister(&sipchaninfo_function);
24715    ast_custom_function_unregister(&sippeer_function);
24716    ast_custom_function_unregister(&sip_header_function);
24717    ast_custom_function_unregister(&checksipdomain_function);
24718 
24719    /* Unregister dial plan applications */
24720    ast_unregister_application(app_dtmfmode);
24721    ast_unregister_application(app_sipaddheader);
24722 
24723    /* Unregister CLI commands */
24724    ast_cli_unregister_multiple(cli_sip, sizeof(cli_sip) / sizeof(struct ast_cli_entry));
24725 
24726    /* Disconnect from the RTP subsystem */
24727    ast_rtp_proto_unregister(&sip_rtp);
24728 
24729    /* Disconnect from UDPTL */
24730    ast_udptl_proto_unregister(&sip_udptl);
24731 
24732    /* Unregister AMI actions */
24733    ast_manager_unregister("SIPpeers");
24734    ast_manager_unregister("SIPshowpeer");
24735    ast_manager_unregister("SIPqualifypeer");
24736    ast_manager_unregister("SIPshowregistry");
24737    ast_manager_unregister("SIPnotify");
24738    
24739    /* Kill TCP/TLS server threads */
24740    if (sip_tcp_desc.master)
24741       ast_tcptls_server_stop(&sip_tcp_desc);
24742    if (sip_tls_desc.master)
24743       ast_tcptls_server_stop(&sip_tls_desc);
24744 
24745    /* Kill all existing TCP/TLS threads */
24746    i = ao2_iterator_init(threadt, 0);
24747    while ((th = ao2_t_iterator_next(&i, "iterate through tcp threads for 'sip show tcp'"))) {
24748       pthread_t thread = th->threadid;
24749       th->stop = 1;
24750       pthread_kill(thread, SIGURG);
24751       pthread_join(thread, NULL);
24752       ao2_t_ref(th, -1, "decrement ref from iterator");
24753    }
24754    ao2_iterator_destroy(&i);
24755 
24756    /* Hangup all dialogs if they have an owner */
24757    i = ao2_iterator_init(dialogs, 0);
24758    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24759       if (p->owner)
24760          ast_softhangup(p->owner, AST_SOFTHANGUP_APPUNLOAD);
24761       ao2_t_ref(p, -1, "toss dialog ptr from iterator_next");
24762    }
24763    ao2_iterator_destroy(&i);
24764 
24765    ast_mutex_lock(&monlock);
24766    if (monitor_thread && (monitor_thread != AST_PTHREADT_STOP) && (monitor_thread != AST_PTHREADT_NULL)) {
24767       pthread_cancel(monitor_thread);
24768       pthread_kill(monitor_thread, SIGURG);
24769       pthread_join(monitor_thread, NULL);
24770    }
24771    monitor_thread = AST_PTHREADT_STOP;
24772    ast_mutex_unlock(&monlock);
24773 
24774    /* Destroy all the dialogs and free their memory */
24775    i = ao2_iterator_init(dialogs, 0);
24776    while ((p = ao2_t_iterator_next(&i, "iterate thru dialogs"))) {
24777       dialog_unlink_all(p, TRUE, TRUE);
24778       ao2_t_ref(p, -1, "throw away iterator result"); 
24779    }
24780    ao2_iterator_destroy(&i);
24781 
24782    /* Free memory for local network address mask */
24783    ast_free_ha(localaddr);
24784 
24785    clear_realm_authentication(authl);
24786 
24787 
24788    if (default_tls_cfg.certfile)
24789       ast_free(default_tls_cfg.certfile);
24790    if (default_tls_cfg.cipher)
24791       ast_free(default_tls_cfg.cipher);
24792    if (default_tls_cfg.cafile)
24793       ast_free(default_tls_cfg.cafile);
24794    if (default_tls_cfg.capath)
24795       ast_free(default_tls_cfg.capath);
24796 
24797    ASTOBJ_CONTAINER_DESTROYALL(&regl, sip_registry_destroy);
24798    ASTOBJ_CONTAINER_DESTROY(&regl);
24799 
24800    ao2_t_ref(peers, -1, "unref the peers table");
24801    ao2_t_ref(peers_by_ip, -1, "unref the peers_by_ip table");
24802    ao2_t_ref(dialogs, -1, "unref the dialogs table");
24803    ao2_t_ref(threadt, -1, "unref the thread table");
24804 
24805    clear_sip_domains();
24806    ast_free_ha(global_contact_ha);
24807    close(sipsock);
24808    sched_context_destroy(sched);
24809    con = ast_context_find(used_context);
24810    if (con)
24811       ast_context_destroy(con, "SIP");
24812    ast_unload_realtime("sipregs");
24813    ast_unload_realtime("sippeers");
24814 
24815    return 0;
24816 }
24817 
24818 AST_MODULE_INFO(ASTERISK_GPL_KEY, AST_MODFLAG_DEFAULT, "Session Initiation Protocol (SIP)",
24819       .load = load_module,
24820       .unload = unload_module,
24821       .reload = reload,
24822           );

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