Skip to content
Snippets Groups Projects
chan_sip.c 938 KiB
Newer Older
  • Learn to ignore specific revisions
  • 	/* RFC3891: Replaces: header for transfer */
    	{ SIP_OPT_REPLACES,	SUPPORTED,	"replaces" },	
    	/* One version of Polycom firmware has the wrong label */
    	{ SIP_OPT_REPLACES,	SUPPORTED,	"replace" },	
    	/* RFC4412 Resource priorities */
    	{ SIP_OPT_RESPRIORITY,	NOT_SUPPORTED,	"resource-priority" },
    
    	/* RFC3329: Security agreement mechanism */
    	{ SIP_OPT_SEC_AGREE,	NOT_SUPPORTED,	"sec_agree" },
    
    	/* RFC4092: Usage of the SDP ANAT Semantics in the SIP */
    	{ SIP_OPT_SDP_ANAT,	NOT_SUPPORTED,	"sdp-anat" },
    	/* RFC4028: SIP Session-Timers */
    	{ SIP_OPT_TIMER,	SUPPORTED,	"timer" },
    
    	/* RFC4538: Target-dialog */
    
    	{ SIP_OPT_TARGET_DIALOG,NOT_SUPPORTED,	"tdialog" },
    
    /*! \brief Diversion header reasons
     *
     * The core defines a bunch of constants used to define
     * redirecting reasons. This provides a translation table
     * between those and the strings which may be present in
     * a SIP Diversion header
     */
    static const struct sip_reasons {
    	enum AST_REDIRECTING_REASON code;
    	char * const text;
    } sip_reason_table[] = {
    	{ AST_REDIRECTING_REASON_UNKNOWN, "unknown" },
    	{ AST_REDIRECTING_REASON_USER_BUSY, "user-busy" },
    	{ AST_REDIRECTING_REASON_NO_ANSWER, "no-answer" },
    	{ AST_REDIRECTING_REASON_UNAVAILABLE, "unavailable" },
    	{ AST_REDIRECTING_REASON_UNCONDITIONAL, "unconditional" },
    	{ AST_REDIRECTING_REASON_TIME_OF_DAY, "time-of-day" },
    	{ AST_REDIRECTING_REASON_DO_NOT_DISTURB, "do-not-disturb" },
    	{ AST_REDIRECTING_REASON_DEFLECTION, "deflection" },
    	{ AST_REDIRECTING_REASON_FOLLOW_ME, "follow-me" },
    	{ AST_REDIRECTING_REASON_OUT_OF_ORDER, "out-of-service" },
    	{ AST_REDIRECTING_REASON_AWAY, "away" },
    	{ AST_REDIRECTING_REASON_CALL_FWD_DTE, "unknown"}
    };
    
    static enum AST_REDIRECTING_REASON sip_reason_str_to_code(const char *text)
    {
    	enum AST_REDIRECTING_REASON ast = AST_REDIRECTING_REASON_UNKNOWN;
    	int i;
    
    	for (i = 0; i < ARRAY_LEN(sip_reason_table); ++i) {
    		if (!strcasecmp(text, sip_reason_table[i].text)) {
    			ast = sip_reason_table[i].code;
    			break;
    		}
    	}
    
    	return ast;
    }
    
    static const char *sip_reason_code_to_str(enum AST_REDIRECTING_REASON code)
    {
    	if (code >= 0 && code < ARRAY_LEN(sip_reason_table)) {
    		return sip_reason_table[code].text;
    	}
    
    	return "unknown";
    }
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief SIP Methods we support 
    
    	\todo This string should be set dynamically. We only support REFER and SUBSCRIBE if we have
    
    Olle Johansson's avatar
    Olle Johansson committed
    	allowsubscribe and allowrefer on in sip.conf.
    */
    
    #define ALLOWED_METHODS "INVITE, ACK, CANCEL, OPTIONS, BYE, REFER, SUBSCRIBE, NOTIFY, INFO"
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief SIP Extensions we support 
    	\note This should be generated based on the previous array
    		in combination with settings.
    	\todo We should not have "timer" if it's disabled in the configuration file.
    */
    
    #define SUPPORTED_EXTENSIONS "replaces, timer" 
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief Standard SIP unsecure port for UDP and TCP from RFC 3261. DO NOT CHANGE THIS */
    
    #define STANDARD_SIP_PORT	5060
    
    /*! \brief Standard SIP TLS port from RFC 3261. DO NOT CHANGE THIS */
    
    #define STANDARD_TLS_PORT	5061
    
    /*! \note in many SIP headers, absence of a port number implies port 5060,
    
     * and this is why we cannot change the above constant.
     * There is a limited number of places in asterisk where we could,
     * in principle, use a different "default" port number, but
     * we do not support this feature at the moment.
    
     * You can run Asterisk with SIP on a different port with a configuration
     * option. If you change this value, the signalling will be incorrect.
    
    /*! \name DefaultValues Default values, set and reset in reload_config before reading configuration 
    
    Olle Johansson's avatar
    Olle Johansson committed
    
       These are default values in the source. There are other recommended values in the
    
       sip.conf.sample for new installations. These may differ to keep backwards compatibility,
       yet encouraging new behaviour on new installations 
     */
    
    #define DEFAULT_CONTEXT		"default"	/*!< The default context for [general] section as well as devices */
    #define DEFAULT_MOHINTERPRET    "default"	/*!< The default music class */
    
    #define DEFAULT_VMEXTEN 	"asterisk"	/*!< Default voicemail extension */
    #define DEFAULT_CALLERID 	"asterisk"	/*!< Default caller ID */
    
    #define DEFAULT_MWI_FROM ""
    
    #define DEFAULT_NOTIFYMIME 	"application/simple-message-summary"
    #define DEFAULT_ALLOWGUEST	TRUE
    
    #define DEFAULT_RTPKEEPALIVE	0		/*!< Default RTPkeepalive setting */
    
    #define DEFAULT_SRVLOOKUP	TRUE		/*!< Recommended setting is ON */
    
    #define DEFAULT_COMPACTHEADERS	FALSE		/*!< Send compact (one-character) SIP headers. Default off */
    
    #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. */
    #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. */
    #define DEFAULT_TOS_VIDEO       0               /*!< Video packets should be marked as DSCP AF41, but the default is 0 to be compatible with previous versions. */
    
    #define DEFAULT_TOS_TEXT        0               /*!< Text packets should be marked as XXXX XXXX, but the default is 0 to be compatible with previous versions. */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define DEFAULT_COS_SIP         4		/*!< Level 2 class of service for SIP signalling */
    #define DEFAULT_COS_AUDIO       5		/*!< Level 2 class of service for audio media  */
    #define DEFAULT_COS_VIDEO       6		/*!< Level 2 class of service for video media */
    #define DEFAULT_COS_TEXT        5		/*!< Level 2 class of service for text media (T.140) */
    #define DEFAULT_ALLOW_EXT_DOM	TRUE		/*!< Allow external domains */
    #define DEFAULT_REALM		"asterisk"	/*!< Realm for HTTP digest authentication */
    
    #define DEFAULT_DOMAINSASREALM	FALSE		/*!< Use the domain option to guess the realm for registration and invite requests */
    
    #define DEFAULT_NOTIFYRINGING	TRUE		/*!< Notify devicestate system on ringing state */
    
    #define DEFAULT_NOTIFYCID		DISABLED	/*!< Include CID with ringing notifications */
    
    #define DEFAULT_PEDANTIC	FALSE		/*!< Avoid following SIP standards for dialog matching */
    #define DEFAULT_AUTOCREATEPEER	FALSE		/*!< Don't create peers automagically */
    
    #define	DEFAULT_MATCHEXTERNIPLOCALLY FALSE	/*!< Match extern IP locally default setting */
    
    #define DEFAULT_QUALIFY		FALSE		/*!< Don't monitor devices */
    
    #define DEFAULT_CALLEVENTS	FALSE		/*!< Extra manager SIP call events */
    #define DEFAULT_ALWAYSAUTHREJECT	FALSE	/*!< Don't reject authentication requests always */
    
    #define DEFAULT_T1MIN		100		/*!< 100 MS for minimal roundtrip time */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define DEFAULT_MAX_CALL_BITRATE (384)		/*!< Max bitrate for video */
    
    #ifndef DEFAULT_USERAGENT
    #define DEFAULT_USERAGENT "Asterisk PBX"	/*!< Default Useragent: header unless re-defined in sip.conf */
    
    #define DEFAULT_SDPSESSION "Asterisk PBX"	/*!< Default SDP session name, (s=) header unless re-defined in sip.conf */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define DEFAULT_SDPOWNER "root"			/*!< Default SDP username field in (o=) header unless re-defined in sip.conf */
    
    #define DEFAULT_ENGINE "asterisk"               /*!< Default RTP engine to use for sessions */
    
    #endif
    
    /*! \name DefaultSettings
    	Default setttings are used as a channel setting and as a default when
    	configuring devices 
    */
    /*@{*/ 
    
    static char default_language[MAX_LANGUAGE];
    static char default_callerid[AST_MAX_EXTENSION];
    
    static char default_mwi_from[80];
    
    static char default_fromdomain[AST_MAX_EXTENSION];
    static char default_notifymime[AST_MAX_EXTENSION];
    static int default_qualify;		/*!< Default Qualify= setting */
    
    static char default_vmexten[AST_MAX_EXTENSION];
    
    static char default_mohinterpret[MAX_MUSICCLASS];  /*!< Global setting for moh class to use when put on hold */
    static char default_mohsuggest[MAX_MUSICCLASS];	   /*!< Global setting for moh class to suggest when putting 
                                                        *   a bridged channel on hold */
    
    Jeff Peeler's avatar
    Jeff Peeler committed
    static char default_parkinglot[AST_MAX_CONTEXT]; /*!< Parkinglot */
    
    static char default_engine[256];        /*!< Default RTP engine */
    
    Olle Johansson's avatar
    Olle Johansson committed
    static int default_maxcallbitrate;	/*!< Maximum bitrate for call */
    
    static struct ast_codec_pref default_prefs;		/*!< Default codec prefs */
    
    static unsigned int default_transports;			/*!< Default Transports (enum sip_transport) that are acceptable */
    static unsigned int default_primary_transport;		/*!< Default primary Transport (enum sip_transport) for outbound connections to devices */
    
    /*! \name GlobalSettings
    	Global settings apply to the channel (often settings you can change in the general section
    	of sip.conf
    */
    /*@{*/ 
    
    /*! \brief a place to store all global settings for the sip channel driver 
    
    	These are settings that will be possibly to apply on a group level later on.
    
    	\note Do not add settings that only apply to the channel itself and can't
    	      be applied to devices (trunks, services, phones)
    
    */
    struct sip_settings {
    	int peer_rtupdate;		/*!< G: Update database with registration data for peer? */
    	int rtsave_sysname;		/*!< G: Save system name at registration? */
    	int ignore_regexpire;		/*!< G: Ignore expiration of peer  */
    	int rtautoclear;		/*!< Realtime ?? */
    	int directrtpsetup;		/*!< Enable support for Direct RTP setup (no re-invites) */
    	int pedanticsipchecking;	/*!< Extra checking ?  Default off */
    	int autocreatepeer;		/*!< Auto creation of peers at registration? Default off. */
    	int srvlookup;			/*!< SRV Lookup on or off. Default is on */
    	int allowguest;			/*!< allow unauthenticated peers to connect? */
    	int alwaysauthreject;		/*!< Send 401 Unauthorized for all failing requests */
    	int compactheaders;		/*!< send compact sip headers */
    	int allow_external_domains;	/*!< Accept calls to external SIP domains? */
    	int callevents;			/*!< Whether we send manager events or not */
    	int regextenonqualify;  	/*!< Whether to add/remove regexten when qualifying peers */
    	int matchexterniplocally;	/*!< Match externip/externhost setting against localnet setting */
    
    	unsigned int disallowed_methods; /*!< methods that we should never try to use */
    
    	int notifyringing;		/*!< Send notifications on ringing */
    	int notifyhold;			/*!< Send notifications on hold */
    	enum notifycid_setting notifycid; /*!< Send CID with ringing notifications */
    	enum transfermodes allowtransfer;	/*!< SIP Refer restriction scheme */
    	int allowsubscribe;	        /*!< Flag for disabling ALL subscriptions, this is FALSE only if all peers are FALSE 
    					    the global setting is in globals_flags[1] */
    	char realm[MAXHOSTNAMELEN]; 		/*!< Default realm */
    
    	int domainsasrealm;			/*!< Use domains lists as realms */
    
    	struct sip_proxy outboundproxy;	/*!< Outbound proxy */
    	char default_context[AST_MAX_CONTEXT];
    	char default_subscribecontext[AST_MAX_CONTEXT];
    
    static int global_match_auth_username;		/*!< Match auth username if available instead of From: Default off. */
    
    static int global_relaxdtmf;		/*!< Relax DTMF */
    
    static int global_rtptimeout;		/*!< Time out call if no RTP */
    
    static int global_rtpholdtimeout;	/*!< Time out call if no RTP during hold */
    
    static int global_rtpkeepalive;		/*!< Send RTP keepalives */
    static int global_reg_timeout;	
    static int global_regattempts_max;	/*!< Registration attempts before giving up */
    
    static int global_callcounter;		/*!< Enable call counters for all devices. This is currently enabled by setting the peer
    						call-limit to 999. When we remove the call-limit from the code, we can make it
    						with just a boolean flag in the device structure */
    
    static unsigned int global_tos_sip;		/*!< IP type of service for SIP packets */
    static unsigned int global_tos_audio;		/*!< IP type of service for audio RTP packets */
    static unsigned int global_tos_video;		/*!< IP type of service for video RTP packets */
    
    static unsigned int global_tos_text;		/*!< IP type of service for text RTP packets */
    
    static unsigned int global_cos_sip;		/*!< 802.1p class of service for SIP packets */
    static unsigned int global_cos_audio;		/*!< 802.1p class of service for audio RTP packets */
    static unsigned int global_cos_video;		/*!< 802.1p class of service for video RTP packets */
    static unsigned int global_cos_text;		/*!< 802.1p class of service for text RTP packets */
    
    static unsigned int recordhistory;		/*!< Record SIP history. Off by default */
    static unsigned int dumphistory;		/*!< Dump history to verbose before destroying SIP dialog */
    
    static char global_regcontext[AST_MAX_CONTEXT];		/*!< Context for auto-extensions */
    
    static char global_useragent[AST_MAX_EXTENSION];	/*!< Useragent for the SIP channel */
    
    static char global_sdpsession[AST_MAX_EXTENSION];	/*!< SDP session name for the SIP channel */
    static char global_sdpowner[AST_MAX_EXTENSION];	/*!< SDP owner name for the SIP channel */
    
    static int global_authfailureevents;		/*!< Whether we send authentication failure manager events or not. Default no. */
    
    static int global_t1min;		/*!< T1 roundtrip time minimum */
    
    Olle Johansson's avatar
    Olle Johansson committed
    static int global_timer_b;    			/*!< Timer B - RFC 3261 Section 17.1.1.2 */
    
    static unsigned int global_autoframing;        	/*!< Turn autoframing on or off. */
    
    Olle Johansson's avatar
    Olle Johansson committed
    static int global_qualifyfreq;			/*!< Qualify frequency */
    
    static int global_qualify_gap;              /*!< Time between our group of peer pokes */
    static int global_qualify_peers;          /*!< Number of peers to poke at a given time */
    
    /*! \brief Codecs that we support by default: */
    static int global_capability = AST_FORMAT_ULAW | AST_FORMAT_ALAW | AST_FORMAT_GSM | AST_FORMAT_H263;
    
    Olle Johansson's avatar
    Olle Johansson committed
    static enum st_mode global_st_mode;           /*!< Mode of operation for Session-Timers           */
    static enum st_refresher global_st_refresher; /*!< Session-Timer refresher                        */
    static int global_min_se;                     /*!< Lowest threshold for session refresh interval  */
    static int global_max_se;                     /*!< Highest threshold for session refresh interval */
    
    
    /*! \brief Global list of addresses dynamic peers are not allowed to use */
    static struct ast_ha *global_contact_ha = NULL;
    static int global_dynamic_exclude_static = 0;
    
    
    /*! \name Object counters @{
     * \bug These counters are not handled in a thread-safe way ast_atomic_fetchadd_int()
    
     * should be used to modify these values. */
    
    Russell Bryant's avatar
    Russell Bryant committed
    static int speerobjs = 0;                /*!< Static peers */
    
    static int rpeerobjs = 0;                /*!< Realtime peers */
    static int apeerobjs = 0;                /*!< Autocreated peer objects */
    static int regobjs = 0;                  /*!< Registry objects */
    
    static struct ast_flags global_flags[2] = {{0}};        /*!< global SIP_ flags */
    
    Olle Johansson's avatar
    Olle Johansson committed
    static char used_context[AST_MAX_CONTEXT];		/*!< name of automatically created context for unloading */
    
    AST_MUTEX_DEFINE_STATIC(netlock);
    
    
    /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
    
    Mark Spencer's avatar
    Mark Spencer committed
       when it's doing something critical. */
    
    AST_MUTEX_DEFINE_STATIC(monlock);
    
    AST_MUTEX_DEFINE_STATIC(sip_reload_lock);
    
    
    /*! \brief This is the thread for the monitor which checks for input on the channels
    
    Mark Spencer's avatar
    Mark Spencer committed
       which are not currently in use.  */
    
    static pthread_t monitor_thread = AST_PTHREADT_NULL;
    
    static int sip_reloading = FALSE;                       /*!< Flag for avoiding multiple reloads at the same time */
    static enum channelreloadreason sip_reloadreason;       /*!< Reason for last reload/load of configuration */
    
    static struct sched_context *sched;     /*!< The scheduling context */
    static struct io_context *io;           /*!< The IO context */
    
    static int *sipsock_read_id;            /*!< ID of IO entry for sipsock FD */
    
    #define DEC_CALL_LIMIT	0
    #define INC_CALL_LIMIT	1
    
    #define DEC_CALL_RINGING 2
    #define INC_CALL_RINGING 3
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief The SIP socket definition */
    
    struct sip_socket {
    
    Olle Johansson's avatar
    Olle Johansson committed
    	enum sip_transport type;	/*!< UDP, TCP or TLS */
    	int fd;				/*!< Filed descriptor, the actual socket */
    
    	struct ast_tcptls_session_instance *tcptls_session;	/* If tcp or tls, a socket manager */
    
    };
    
    /*! \brief sip_request: The data grabbed from the UDP socket
     *
    
    Jason Parker's avatar
    Jason Parker committed
     * \verbatim
    
     * Incoming messages: we first store the data from the socket in data[],
     * adding a trailing \0 to make string parsing routines happy.
     * Then call parse_request() and req.method = find_sip_method();
     * to initialize the other fields. The \r\n at the end of each line is   
     * replaced by \0, so that data[] is not a conforming SIP message anymore.
     * After this processing, rlPart1 is set to non-NULL to remember
     * that we can run get_header() on this kind of packet.
     *
     * parse_request() splits the first line as follows:
     * Requests have in the first line      method uri SIP/2.0
     *      rlPart1 = method; rlPart2 = uri;
     * Responses have in the first line     SIP/2.0 NNN description
     *      rlPart1 = SIP/2.0; rlPart2 = NNN + description;
     *
     * For outgoing packets, we initialize the fields with init_req() or init_resp()
     * (which fills the first line to "METHOD uri SIP/2.0" or "SIP/2.0 code text"),
     * and then fill the rest with add_header() and add_line().
     * The \r\n at the end of the line are still there, so the get_header()
     * and similar functions don't work on these packets. 
    
    Jason Parker's avatar
    Jason Parker committed
     * \endverbatim
    
    Mark Spencer's avatar
    Mark Spencer committed
    struct sip_request {
    
    	ptrdiff_t rlPart1; 	        /*!< Offset of the SIP Method Name or "SIP/2.0" protocol version */
    	ptrdiff_t rlPart2; 	        /*!< Offset of the Request URI or Response Status */
    
    Jason Parker's avatar
    Jason Parker committed
    	int len;                /*!< bytes used in data[], excluding trailing null terminator. Rarely used. */
    
    	int headers;            /*!< # of SIP Headers */
    	int method;             /*!< Method of this request */
    	int lines;              /*!< Body Content */
    
    	unsigned int sdp_start; /*!< the line number where the SDP begins */
    	unsigned int sdp_end;   /*!< the line number where the SDP ends */
    	char debug;		/*!< print extra debugging if non zero */
    	char has_to_tag;	/*!< non-zero if packet has To: tag */
    	char ignore;		/*!< if non-zero This is a re-transmit, ignore it */
    
    	/* Array of offsets into the request string of each SIP header*/
    	ptrdiff_t header[SIP_MAX_HEADERS];
    	/* Array of offsets into the request string of each SDP line*/
    	ptrdiff_t line[SIP_MAX_LINES];
    
    	/* XXX Do we need to unref socket.ser when the request goes away? */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	struct sip_socket socket;	/*!< The socket used for this request */
    
    	AST_LIST_ENTRY(sip_request) next;
    
    /* \brief given a sip_request and an offset, return the char * that resides there
     *
     * It used to be that rlPart1, rlPart2, and the header and line arrays were character
     * pointers. They are now offsets into the ast_str portion of the sip_request structure.
     * To avoid adding a bunch of redundant pointer arithmetic to the code, this macro is
     * provided to retrieve the string at a particular offset within the request's buffer
     */
    #define REQ_OFFSET_TO_STR(req,offset) (ast_str_buffer((req)->data) + ((req)->offset))
    
    
    /*! \brief structure used in transfers */
    struct sip_dual {
    
    	struct ast_channel *chan1;	/*!< First channel involved */
    	struct ast_channel *chan2;	/*!< Second channel involved */
    	struct sip_request req;		/*!< Request that caused the transfer (REFER) */
    	int seqno;			/*!< Sequence number */
    
    Mark Spencer's avatar
    Mark Spencer committed
    struct sip_pkt;
    
    
    /*! \brief Parameters to the transmit_invite function */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int addsipheaders;		/*!< Add extra SIP headers */
    
    	const char *uri_options;	/*!< URI options to add to the URI */
    	const char *vxml_url;		/*!< VXML url for Cisco phones */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	char *auth;			/*!< Authentication */
    	char *authheader;		/*!< Auth header */
    
    	enum sip_auth_type auth_type;	/*!< Authentication type */
    
    	const char *replaces;		/*!< Replaces header for call transfers */
    	int transfer;			/*!< Flag - is this Invite part of a SIP transfer? (invite/replaces) */
    
    /*! \brief Structure to save routing information for a SIP session */
    
    struct sip_route {
    	struct sip_route *next;
    	char hop[0];
    };
    
    
    /*! \brief Modes for SIP domain handling in the PBX */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	SIP_DOMAIN_AUTO,		/*!< This domain is auto-configured */
    	SIP_DOMAIN_CONFIG,		/*!< This domain is from configuration */
    
    /*! \brief Domain data structure. 
    	\note In the future, we will connect this to a configuration tree specific
    	for this domain
    */
    
    	char domain[MAXHOSTNAMELEN];		/*!< SIP domain we are responsible for */
    	char context[AST_MAX_EXTENSION];	/*!< Incoming context for this domain */
    	enum domain_mode mode;			/*!< How did we find this domain? */
    	AST_LIST_ENTRY(domain) list;		/*!< List mechanics */
    
    static AST_LIST_HEAD_STATIC(domain_list, domain);	/*!< The SIP domain list */
    
    /*! \brief sip_history: Structure for saving transactions within a SIP dialog */
    
    	AST_LIST_ENTRY(sip_history) list;
    	char event[0];	/* actually more, depending on needs */
    
    AST_LIST_HEAD_NOLOCK(sip_history_head, sip_history); /*!< history list, entry in sip_pvt */
    
    
    /*! \brief sip_auth: Credentials for authentication to other SIP services */
    
    struct sip_auth {
    
    	char realm[AST_MAX_EXTENSION];  /*!< Realm in which these credentials are valid */
    
    	char username[256];             /*!< Username */
    	char secret[256];               /*!< Secret */
    	char md5secret[256];            /*!< MD5Secret */
    	struct sip_auth *next;          /*!< Next auth structure in list */
    
    /*! \name SIPflags
    	Various flags for the flags field in the pvt structure 
    
    	Trying to sort these up (one or more of the following):
    	D: Dialog
    	P: Peer/user
    	G: Global flag
    	When flags are used by multiple structures, it is important that
    	they have a common layout so it is easy to copy them.
    
    Olle Johansson's avatar
    Olle Johansson committed
    */
    
    #define SIP_OUTGOING		(1 << 0)	/*!< D: Direction of the last transaction in this dialog */
    #define SIP_RINGING		(1 << 2)	/*!< D: Have sent 180 ringing */
    #define SIP_PROGRESS_SENT	(1 << 3)	/*!< D: Have sent 183 message progress */
    #define SIP_NEEDREINVITE	(1 << 4)	/*!< D: Do we need to send another reinvite? */
    #define SIP_PENDINGBYE		(1 << 5)	/*!< D: Need to send bye after we ack? */
    #define SIP_GOTREFER		(1 << 6)	/*!< D: Got a refer? */
    #define SIP_CALL_LIMIT		(1 << 7)	/*!< D: Call limit enforced for this call */
    #define SIP_INC_COUNT		(1 << 8)	/*!< D: Did this dialog increment the counter of in-use calls? */
    #define SIP_INC_RINGING		(1 << 9)	/*!< D: Did this connection increment the counter of in-use calls? */
    
    #define SIP_DEFER_BYE_ON_TRANSFER	(1 << 10)	/*!< D: Do not hangup at first ast_hangup */
    
    #define SIP_PROMISCREDIR	(1 << 11)	/*!< DP: Promiscuous redirection */
    #define SIP_TRUSTRPID		(1 << 12)	/*!< DP: Trust RPID headers? */
    #define SIP_USEREQPHONE		(1 << 13)	/*!< DP: Add user=phone to numeric URI. Default off */
    #define SIP_USECLIENTCODE	(1 << 14)	/*!< DP: Trust X-ClientCode info message */
    
    
    /* DTMF flags - see str2dtmfmode() and dtmfmode2str() */
    
    #define SIP_DTMF		(7 << 15)	/*!< DP: DTMF Support: five settings, uses three bits */
    #define SIP_DTMF_RFC2833	(0 << 15)	/*!< DP: DTMF Support: RTP DTMF - "rfc2833" */
    #define SIP_DTMF_INBAND		(1 << 15)	/*!< DP: DTMF Support: Inband audio, only for ULAW/ALAW - "inband" */
    #define SIP_DTMF_INFO		(2 << 15)	/*!< DP: DTMF Support: SIP Info messages - "info" */
    #define SIP_DTMF_AUTO		(3 << 15)	/*!< DP: DTMF Support: AUTO switch between rfc2833 and in-band DTMF */
    #define SIP_DTMF_SHORTINFO      (4 << 15)       /*!< DP: DTMF Support: SIP Info messages - "info" - short variant */
    
    /* NAT settings */
    #define SIP_NAT_FORCE_RPORT     (1 << 18)       /*!< DP: Force rport even if not present in the request */
    #define SIP_NAT_RPORT_PRESENT   (1 << 19)       /*!< DP: rport was present in the request */
    
    /* re-INVITE related settings */
    
    #define SIP_REINVITE		(7 << 20)	/*!< DP: four settings, uses three bits */
    #define SIP_REINVITE_NONE	(0 << 20)	/*!< DP: no reinvite allowed */
    
    #define SIP_DIRECT_MEDIA	(1 << 20)	/*!< DP: allow peers to be reinvited to send media directly p2p */
    #define SIP_DIRECT_MEDIA_NAT	(2 << 20)	/*!< DP: allow media reinvite when new peer is behind NAT */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_REINVITE_UPDATE	(4 << 20)	/*!< DP: use UPDATE (RFC3311) when reinviting this peer */
    
    
    /* "insecure" settings - see insecure2str() */
    
    #define SIP_INSECURE		(3 << 23)	/*!< DP: three settings, uses two bits */
    #define SIP_INSECURE_NONE	(0 << 23)	/*!< DP: secure mode */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_INSECURE_PORT	(1 << 23)	/*!< DP: don't require matching port for incoming requests */
    #define SIP_INSECURE_INVITE	(1 << 24)	/*!< DP: don't require authentication for incoming INVITEs */
    
    /* Sending PROGRESS in-band settings */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_PROG_INBAND		(3 << 25)	/*!< DP: three settings, uses two bits */
    
    #define SIP_PROG_INBAND_NEVER	(0 << 25)
    #define SIP_PROG_INBAND_NO	(1 << 25)
    #define SIP_PROG_INBAND_YES	(2 << 25)
    
    #define SIP_SENDRPID		(3 << 29)	/*!< DP: Remote Party-ID Support */
    #define SIP_SENDRPID_NO     (0 << 29)
    #define SIP_SENDRPID_PAI    (1 << 29)   /*!< Use "P-Asserted-Identity" for rpid */
    #define SIP_SENDRPID_RPID   (2 << 29)   /*!< Use "Remote-Party-ID" for rpid */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_G726_NONSTANDARD	(1 << 31)	/*!< DP: Use non-standard packing for G726-32 data */
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief Flags to copy from peer/user to dialog */
    
    #define SIP_FLAGS_TO_COPY \
    	(SIP_PROMISCREDIR | SIP_TRUSTRPID | SIP_SENDRPID | SIP_DTMF | SIP_REINVITE | \
    
    	 SIP_PROG_INBAND | SIP_USECLIENTCODE | SIP_NAT_FORCE_RPORT | SIP_G726_NONSTANDARD | \
    
    	 SIP_USEREQPHONE | SIP_INSECURE)
    
    /*! \name SIPflags2
    	a second page of flags (for flags[1] */
    /*@{*/ 
    
    #define SIP_PAGE2_RTCACHEFRIENDS	(1 << 0)	/*!< GP: Should we keep RT objects in memory for extended time? */
    #define SIP_PAGE2_RTAUTOCLEAR		(1 << 2)	/*!< GP: Should we clean memory from peers after expiry? */
    
    #define SIP_PAGE2_RPID_UPDATE		(1 << 3)
    
    /* Space for addition of other realtime flags in the future */
    
    #define SIP_PAGE2_SYMMETRICRTP          (1 << 8)        /*!< GDP: Whether symmetric RTP is enabled or not */
    
    #define SIP_PAGE2_STATECHANGEQUEUE	(1 << 9)	/*!< D: Unsent state pending change exists */
    
    #define SIP_PAGE2_CONNECTLINEUPDATE_PEND		(1 << 10)
    #define SIP_PAGE2_RPID_IMMEDIATE			(1 << 11)
    
    #define SIP_PAGE2_RPORT_PRESENT         (1 << 12)       /*!< Was rport received in the Via header? */
    
    #define SIP_PAGE2_PREFERRED_CODEC	(1 << 13)	/*!< GDP: Only respond with single most preferred joint codec */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_PAGE2_VIDEOSUPPORT		(1 << 14)	/*!< DP: Video supported if offered? */
    #define SIP_PAGE2_TEXTSUPPORT		(1 << 15)	/*!< GDP: Global text enable */
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_PAGE2_ALLOWSUBSCRIBE	(1 << 16)	/*!< GP: Allow subscriptions from this peer? */
    #define SIP_PAGE2_ALLOWOVERLAP		(1 << 17)	/*!< DP: Allow overlap dialing ? */
    #define SIP_PAGE2_SUBSCRIBEMWIONLY	(1 << 18)	/*!< GP: Only issue MWI notification if subscribed to */
    
    #define SIP_PAGE2_IGNORESDPVERSION	(1 << 19)	/*!< GDP: Ignore the SDP session version number we receive and treat all sessions as new */
    
    #define SIP_PAGE2_T38SUPPORT		        (7 << 20)	/*!< GDP: T.38 Fax Support */
    #define SIP_PAGE2_T38SUPPORT_UDPTL	        (1 << 20)	/*!< GDP: T.38 Fax Support (no error correction) */
    #define SIP_PAGE2_T38SUPPORT_UDPTL_FEC	        (2 << 20)	/*!< GDP: T.38 Fax Support (FEC error correction) */
    #define SIP_PAGE2_T38SUPPORT_UDPTL_REDUNDANCY	(4 << 20)	/*!< GDP: T.38 Fax Support (redundancy error correction) */
    
    
    #define SIP_PAGE2_CALL_ONHOLD		(3 << 23)	/*!< D: Call hold states: */
    #define SIP_PAGE2_CALL_ONHOLD_ACTIVE    (1 << 23)       /*!< D: Active hold */
    #define SIP_PAGE2_CALL_ONHOLD_ONEDIR	(2 << 23)	/*!< D: One directional hold */
    #define SIP_PAGE2_CALL_ONHOLD_INACTIVE	(3 << 23)	/*!< D: Inactive hold */
    
    #define SIP_PAGE2_RFC2833_COMPENSATE    (1 << 25)	/*!< DP: Compensate for buggy RFC2833 implementations */
    #define SIP_PAGE2_BUGGY_MWI		(1 << 26)	/*!< DP: Buggy CISCO MWI fix */
    
    #define SIP_PAGE2_DIALOG_ESTABLISHED    (1 << 27)       /*!< 29: Has a dialog been established? */
    
    #define SIP_PAGE2_FAX_DETECT		(1 << 28)		/*!< DP: Fax Detection support */
    
    Joshua Colp's avatar
    Joshua Colp committed
    #define SIP_PAGE2_REGISTERTRYING        (1 << 29)       /*!< DP: Send 100 Trying on REGISTER attempts */
    
    #define SIP_PAGE2_UDPTL_DESTINATION     (1 << 30)       /*!< DP: Use source IP of RTP as destination if NAT is enabled */
    
    #define SIP_PAGE2_VIDEOSUPPORT_ALWAYS	(1 << 31)       /*!< DP: Always set up video, even if endpoints don't support it */
    
    Olle Johansson's avatar
    Olle Johansson committed
    
    
    Olle Johansson's avatar
    Olle Johansson committed
    #define SIP_PAGE2_FLAGS_TO_COPY \
    
    	(SIP_PAGE2_ALLOWSUBSCRIBE | SIP_PAGE2_ALLOWOVERLAP | SIP_PAGE2_IGNORESDPVERSION | \
    	SIP_PAGE2_VIDEOSUPPORT | SIP_PAGE2_T38SUPPORT | SIP_PAGE2_RFC2833_COMPENSATE | \
    	SIP_PAGE2_BUGGY_MWI | SIP_PAGE2_TEXTSUPPORT | SIP_PAGE2_FAX_DETECT | \
    
    	SIP_PAGE2_UDPTL_DESTINATION | SIP_PAGE2_VIDEOSUPPORT_ALWAYS | SIP_PAGE2_PREFERRED_CODEC | \
    
    	SIP_PAGE2_RPID_IMMEDIATE | SIP_PAGE2_RPID_UPDATE | SIP_PAGE2_SYMMETRICRTP)
    
    /*! \brief debugging state
     * We store separately the debugging requests from the config file
     * and requests from the CLI. Debugging is enabled if either is set
     * (which means that if sipdebug is set in the config file, we can
     * only turn it off by reloading the config).
     */
    enum sip_debug_e {
    	sip_debug_none = 0,
    	sip_debug_config = 1,
    	sip_debug_console = 2,
    };
    
    static enum sip_debug_e sipdebug;
    
    /*! \brief extra debugging for 'text' related events.
    
    Olle Johansson's avatar
    Olle Johansson committed
     * At the moment this is set together with sip_debug_console.
     * \note It should either go away or be implemented properly.
    
    	T38_DISABLED = 0,                /*!< Not enabled */
    	T38_LOCAL_REINVITE,              /*!< Offered from local - REINVITE */
    	T38_PEER_REINVITE,               /*!< Offered from peer - REINVITE */
    	T38_ENABLED                      /*!< Negotiated (enabled) */
    
    };
    
    /*! \brief T.38 channel settings (at some point we need to make this alloc'ed */
    struct t38properties {
    	enum t38state state;		/*!< T.38 state */
    
    	struct ast_control_t38_parameters our_parms;
    	struct ast_control_t38_parameters their_parms;
    
    /*! \brief Parameters to know status of transfer */
    enum referstatus {
    
    	REFER_IDLE,                    /*!< No REFER is in progress */
    	REFER_SENT,                    /*!< Sent REFER to transferee */
    	REFER_RECEIVED,                /*!< Received REFER from transferrer */
    
    	REFER_CONFIRMED,               /*!< Refer confirmed with a 100 TRYING (unused) */
    
    	REFER_ACCEPTED,                /*!< Accepted by transferee */
    	REFER_RINGING,                 /*!< Target Ringing */
    	REFER_200OK,                   /*!< Answered by transfer target */
    	REFER_FAILED,                  /*!< REFER declined - go on */
    	REFER_NOAUTH                   /*!< We had no auth for REFER */
    
    /*! \brief generic struct to map between strings and integers.
     * Fill it with x-s pairs, terminate with an entry with s = NULL;
     * Then you can call map_x_s(...) to map an integer to a string,
     * and map_s_x() for the string -> integer mapping.
     */
    struct _map_x_s {
    	int x;
    	const char *s;
    };              
    
    static const struct _map_x_s referstatusstrings[] = {
    
    	{ REFER_IDLE,		"<none>" },
    	{ REFER_SENT,		"Request sent" },
    	{ REFER_RECEIVED,	"Request received" },
    
    	{ REFER_CONFIRMED,	"Confirmed" },
    
    	{ REFER_ACCEPTED,	"Accepted" },
    	{ REFER_RINGING,	"Target ringing" },
    	{ REFER_200OK,		"Done" },
    	{ REFER_FAILED,		"Failed" },
    
    	{ REFER_NOAUTH,		"Failed - auth failure" },
    	{ -1,			NULL} /* terminator */
    };
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief Structure to handle SIP transfers. Dynamically allocated when needed
    	\note OEJ: Should be moved to string fields */
    
    struct sip_refer {
    	char refer_to[AST_MAX_EXTENSION];		/*!< Place to store REFER-TO extension */
    	char refer_to_domain[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO domain */
    	char refer_to_urioption[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO uri options */
    	char refer_to_context[AST_MAX_EXTENSION];	/*!< Place to store REFER-TO context */
    	char referred_by[AST_MAX_EXTENSION];		/*!< Place to store REFERRED-BY extension */
    	char referred_by_name[AST_MAX_EXTENSION];	/*!< Place to store REFERRED-BY extension */
    	char refer_contact[AST_MAX_EXTENSION];		/*!< Place to store Contact info from a REFER extension */
    
    	char replaces_callid[SIPBUFSIZE];			/*!< Replace info: callid */
    	char replaces_callid_totag[SIPBUFSIZE/2];		/*!< Replace info: to-tag */
    	char replaces_callid_fromtag[SIPBUFSIZE/2];		/*!< Replace info: from-tag */
    
    	struct sip_pvt *refer_call;			/*!< Call we are referring. This is just a reference to a
    							 * dialog owned by someone else, so we should not destroy
    							 * it when the sip_refer object goes.
    							 */
    
    	int attendedtransfer;				/*!< Attended or blind transfer? */
    	int localtransfer;				/*!< Transfer to local domain? */
    	enum referstatus status;			/*!< REFER status */
    };
    
    
    /*! \brief Structure that encapsulates all attributes related to running 
     *   SIP Session-Timers feature on a per dialog basis.
     */
    struct sip_st_dlg {
    	int st_active;                          /*!< Session-Timers on/off */ 
    	int st_interval;                        /*!< Session-Timers negotiated session refresh interval */
    	int st_schedid;                         /*!< Session-Timers ast_sched scheduler id */
    	enum st_refresher st_ref;               /*!< Session-Timers session refresher */
    	int st_expirys;                         /*!< Session-Timers number of expirys */
    	int st_active_peer_ua;                  /*!< Session-Timers on/off in peer UA */
    	int st_cached_min_se;                   /*!< Session-Timers cached Min-SE */
    	int st_cached_max_se;                   /*!< Session-Timers cached Session-Expires */
    	enum st_mode st_cached_mode;            /*!< Session-Timers cached M.O. */
    	enum st_refresher st_cached_ref;        /*!< Session-Timers cached refresher */
    };
    
    
    /*! \brief Structure that encapsulates all attributes related to configuration 
     *   of SIP Session-Timers feature on a per user/peer basis.
     */
    struct sip_st_cfg {
    	enum st_mode st_mode_oper;      /*!< Mode of operation for Session-Timers           */
    	enum st_refresher st_ref;       /*!< Session-Timer refresher                        */
    	int st_min_se;                  /*!< Lowest threshold for session refresh interval  */
    	int st_max_se;                  /*!< Highest threshold for session refresh interval */
    };
    
    
    struct offered_media {
    	int offered;
    	char text[128];
    };
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief Structure used for each SIP dialog, ie. a call, a registration, a subscribe.
    
     * Created and initialized by sip_alloc(), the descriptor goes into the list of
     * descriptors (dialoglist).
     */
    
    Luigi Rizzo's avatar
    Luigi Rizzo committed
    	struct sip_pvt *next;			/*!< Next dialog in chain */
    
    	enum invitestates invitestate;		/*!< Track state of SIP_INVITEs */
    
    	int method;				/*!< SIP method that opened this dialog */
    
    	AST_DECLARE_STRING_FIELDS(
    		AST_STRING_FIELD(callid);	/*!< Global CallID */
    		AST_STRING_FIELD(randdata);	/*!< Random data */
    		AST_STRING_FIELD(accountcode);	/*!< Account code */
    		AST_STRING_FIELD(realm);	/*!< Authorization realm */
    		AST_STRING_FIELD(nonce);	/*!< Authorization nonce */
    		AST_STRING_FIELD(opaque);	/*!< Opaque nonsense */
    		AST_STRING_FIELD(qop);		/*!< Quality of Protection, since SIP wasn't complicated enough yet. */
    		AST_STRING_FIELD(domain);	/*!< Authorization domain */
    		AST_STRING_FIELD(from);		/*!< The From: header */
    		AST_STRING_FIELD(useragent);	/*!< User agent in SIP request */
    		AST_STRING_FIELD(exten);	/*!< Extension where to start */
    		AST_STRING_FIELD(context);	/*!< Context for this call */
    		AST_STRING_FIELD(subscribecontext); /*!< Subscribecontext */
    
    		AST_STRING_FIELD(subscribeuri); /*!< Subscribecontext */
    
    		AST_STRING_FIELD(fromdomain);	/*!< Domain to show in the from field */
    		AST_STRING_FIELD(fromuser);	/*!< User to show in the user field */
    		AST_STRING_FIELD(fromname);	/*!< Name to show in the user field */
    		AST_STRING_FIELD(tohost);	/*!< Host we should put in the "to" field */
    
    		AST_STRING_FIELD(todnid);	/*!< DNID of this call (overrides host) */
    
    		AST_STRING_FIELD(language);	/*!< Default language for this call */
    
    		AST_STRING_FIELD(mohinterpret);	/*!< MOH class to use when put on hold */
    		AST_STRING_FIELD(mohsuggest);	/*!< MOH class to suggest when putting a peer on hold */
    
    		AST_STRING_FIELD(rdnis);	/*!< Referring DNIS */
    
    		AST_STRING_FIELD(redircause);	/*!< Referring cause */
    
    		AST_STRING_FIELD(theirtag);	/*!< Their tag */
    		AST_STRING_FIELD(username);	/*!< [user] name */
    		AST_STRING_FIELD(peername);	/*!< [peer] name, not set if [user] */
    		AST_STRING_FIELD(authname);	/*!< Who we use for authentication */
    		AST_STRING_FIELD(uri);		/*!< Original requested URI */
    		AST_STRING_FIELD(okcontacturi);	/*!< URI from the 200 OK on INVITE */
    		AST_STRING_FIELD(peersecret);	/*!< Password */
    		AST_STRING_FIELD(peermd5secret);
    
    		AST_STRING_FIELD(cid_num);	/*!< Caller*ID number */
    		AST_STRING_FIELD(cid_name);	/*!< Caller*ID name */
    
    		AST_STRING_FIELD(mwi_from); /*!< Name to place in the From header in outgoing NOTIFY requests */
    
    		AST_STRING_FIELD(fullcontact);	/*!< The Contact: that the UA registers with us */
    
    			/* we only store the part in <brackets> in this field. */
    
    		AST_STRING_FIELD(our_contact);	/*!< Our contact header */
    
    		AST_STRING_FIELD(url);		/*!< URL to be sent with next message to peer */
    
    Jeff Peeler's avatar
    Jeff Peeler committed
    		AST_STRING_FIELD(parkinglot);		/*!< Parkinglot */
    
    		AST_STRING_FIELD(engine);       /*!< RTP engine to use */
    
    	char via[128];                          /*!< Via: header */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	struct sip_socket socket;		/*!< The socket used for this dialog */
    
    	unsigned int ocseq;			/*!< Current outgoing seqno */
    	unsigned int icseq;			/*!< Current incoming seqno */
    	ast_group_t callgroup;			/*!< Call group */
    	ast_group_t pickupgroup;		/*!< Pickup group */
    	int lastinvite;				/*!< Last Cseq of invite */
    
    	struct ast_flags flags[2];		/*!< SIP_ flags */
    
    	/* boolean flags that don't belong in flags */
    	unsigned short do_history:1;		/*!< Set if we want to record history */
    	unsigned short alreadygone:1;		/*!< already destroyed by our peer */
    	unsigned short needdestroy:1;		/*!< need to be destroyed by the monitor thread */
    	unsigned short outgoing_call:1;		/*!< this is an outgoing call */
    	unsigned short answered_elsewhere:1;	/*!< This call is cancelled due to answer on another channel */
    	unsigned short novideo:1;		/*!< Didn't get video in invite, don't offer */
    	unsigned short notext:1;		/*!< Text not supported  (?) */
    	unsigned short session_modify:1;	/*!< Session modification request true/false  */
    	unsigned short route_persistent:1;	/*!< Is this the "real" route? */
    	unsigned short autoframing:1;		/*!< Whether to use our local configuration for frame sizes (off)
    						 *   or respect the other endpoint's request for frame sizes (on)
    						 *   for incoming calls
    						 */
    	char tag[11];				/*!< Our tag for this session */
    
    	int timer_t1;				/*!< SIP timer T1, ms rtt */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int timer_b;                            /*!< SIP timer B, ms */
    
    	unsigned int sipoptions;		/*!< Supported SIP options on the other end */
    
    	unsigned int reqsipoptions;		/*!< Required SIP options on the other end */
    
    	struct ast_codec_pref prefs;		/*!< codec prefs */
    
    	int capability;				/*!< Special capability (codec) */
    
    	int jointcapability;			/*!< Supported capability at both ends (codecs) */
    
    	int peercapability;			/*!< Supported peer capability */
    	int prefcodec;				/*!< Preferred codec (outbound only) */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int noncodeccapability;			/*!< DTMF RFC2833 telephony-event */
    
    	int jointnoncodeccapability;            /*!< Joint Non codec capability */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int redircodecs;			/*!< Redirect codecs */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int maxcallbitrate;			/*!< Maximum Call Bitrate for Video Calls */	
    
    	int request_queue_sched_id;		/*!< Scheduler ID of any scheduled action to process queued requests */
    	int authtries;				/*!< Times we've tried to authenticate */
    
    	struct sip_proxy *outboundproxy;	/*!< Outbound proxy for this dialog. Use ref_proxy to set this instead of setting it directly*/
    
    	struct t38properties t38;		/*!< T38 settings */
    	struct sockaddr_in udptlredirip;	/*!< Where our T.38 UDPTL should be going if not to us */
    	struct ast_udptl *udptl;		/*!< T.38 UDPTL session */
    
    	int callingpres;			/*!< Calling presentation */
    	int expiry;				/*!< How long we take to expire */
    
    	int sessionversion;			/*!< SDP Session Version */
    	int sessionid;				/*!< SDP Session ID */
    
    	long branch;				/*!< The branch identifier of this session */
    
    	long invite_branch;			/*!< The branch used when we sent the initial INVITE */
    
    	int64_t sessionversion_remote;		/*!< Remote UA's SDP Session Version */
    
    	struct sockaddr_in sa;			/*!< Our peer */
    	struct sockaddr_in redirip;		/*!< Where our RTP should be going if not to us */
    	struct sockaddr_in vredirip;		/*!< Where our Video RTP should be going if not to us */
    
    	struct sockaddr_in tredirip;		/*!< Where our Text RTP should be going if not to us */
    
    	time_t lastrtprx;			/*!< Last RTP received */
    	time_t lastrtptx;			/*!< Last RTP sent */
    	int rtptimeout;				/*!< RTP timeout time */
    
    	struct sockaddr_in recv;		/*!< Received as */
    
    	struct sockaddr_in ourip;		/*!< Our IP (as seen from the outside) */
    
    	enum transfermodes allowtransfer;	/*!< REFER: restriction scheme */
    
    	struct ast_channel *owner;		/*!< Who owns us (if we have an owner) */
    
    	struct sip_route *route;		/*!< Head of linked list of routing steps (fm Record-Route) */
    
    	struct ast_variable *notify_headers;    /*!< Custom notify type */
    
    	struct sip_auth *peerauth;		/*!< Realm authentication */
    	int noncecount;				/*!< Nonce-count */
    
    	unsigned int stalenonce:1;	/*!< Marks the current nonce as responded too */
    
    	char lastmsg[256];			/*!< Last Message sent/received */
    	int amaflags;				/*!< AMA Flags */
    
    	int pendinginvite;			/*!< Any pending INVITE or state NOTIFY (in subscribe pvt's) ? (seqno of this) */
    
    	int glareinvite;			/*!< A invite received while a pending invite is already present is stored here.  Its seqno is the
    						value. Since this glare invite's seqno is not the same as the pending invite's, it must be 
    						held in order to properly process acknowledgements for our 491 response. */
    
    	struct sip_request initreq;		/*!< Latest request that opened a new transaction
    							within this dialog.
    
    							NOT the request that opened the dialog */
    
    
    	int initid;				/*!< Auto-congest ID if appropriate (scheduler) */
    
    	int waitid;				/*!< Wait ID for scheduler after 491 or other delays */
    
    	int autokillid;				/*!< Auto-kill ID (scheduler) */
    
    	struct sip_refer *refer;		/*!< REFER: SIP transfer data structure */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	enum subscriptiontype subscribed;	/*!< SUBSCRIBE: Is this dialog a subscription?  */
    	int stateid;				/*!< SUBSCRIBE: ID for devicestate subscriptions */
    	int laststate;				/*!< SUBSCRIBE: Last known extension state */
    	int dialogver;				/*!< SUBSCRIBE: Version for subscription dialog-info */
    
    	struct ast_dsp *dsp;			/*!< Inband DTMF Detection dsp */
    
    	struct sip_peer *relatedpeer;		/*!< If this dialog is related to a peer, which one 
    							Used in peerpoke, mwi subscriptions */
    
    	struct sip_registry *registry;		/*!< If this is a REGISTER dialog, to which registry */
    
    	struct ast_rtp_instance *rtp;			/*!< RTP Session */
    	struct ast_rtp_instance *vrtp;			/*!< Video RTP session */
    	struct ast_rtp_instance *trtp;			/*!< Text RTP session */
    
    	struct sip_pkt *packets;		/*!< Packets scheduled for re-transmission */
    
    	struct sip_history_head *history;	/*!< History of this SIP dialog */
    
    	size_t history_entries;			/*!< Number of entires in the history */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	struct ast_variable *chanvars;		/*!< Channel variables to set for inbound call */
    
    	AST_LIST_HEAD_NOLOCK(request_queue, sip_request) request_queue; /*!< Requests that arrived but could not be processed immediately */
    
    	struct sip_invite_param *options;	/*!< Options for INVITE */
    
    	struct sip_st_dlg *stimer;		/*!< SIP Session-Timers */              
    
    Olle Johansson's avatar
    Olle Johansson committed
    	int red; 				/*!< T.140 RTP Redundancy */
    
    	int hangupcause;			/*!< Storage of hangupcause copied from our owner before we disconnect from the AST channel (only used at hangup) */
    
    
    	struct sip_subscription_mwi *mwi;       /*!< If this is a subscription MWI dialog, to which subscription */
    
    	/*! The SIP methods supported by this peer. We get this information from the Allow header of the first
    	 * message we receive from an endpoint during a dialog.
    
    	/*! Some peers are not trustworthy with their Allow headers, and so we need to override their wicked
    	 * ways through configuration. This is a copy of the peer's disallowed_methods, so that we can apply them
    	 * to the sip_pvt at various stages of dialog establishment
    	 */
    	unsigned int disallowed_methods;
    
    	/*! When receiving an SDP offer, it is important to take note of what media types were offered.
    	 * By doing this, even if we don't want to answer a particular media stream with something meaningful, we can
    	 * still put an m= line in our answer with the port set to 0.
    	 *
    	 * The reason for the length being 4 is that in this branch of Asterisk, the only media types supported are 
    	 * image, audio, text, and video. Therefore we need to keep track of which types of media were offered.
    	 *
    	 * Note that if we wanted to be 100% correct, we would keep a list of all media streams offered. That way we could respond
    	 * even to unknown media types, and we could respond to multiple streams of the same type. Such large-scale changes
    	 * are not a good idea for released branches, though, so we're compromising by just making sure that for the common cases:
    	 * audio and video, audio and T.38, and audio and text, we give the appropriate response to both media streams.
    	 *
    	 * The large-scale changes would be a good idea for implementing during an SDP rewrite.
    	 */
    	struct offered_media offered_media[4];
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief
    
     * Here we implement the container for dialogs (sip_pvt), defining
     * generic wrapper functions to ease the transition from the current
     * implementation (a single linked list) to a different container.
     * In addition to a reference to the container, we need functions to lock/unlock
     * the container and individual items, and functions to add/remove
     * references to the individual items.
     */
    
    static struct ao2_container *dialogs;
    
    #define sip_pvt_lock(x) ao2_lock(x)
    #define sip_pvt_trylock(x) ao2_trylock(x)
    #define sip_pvt_unlock(x) ao2_unlock(x)
    
    
    Olle Johansson's avatar
    Olle Johansson committed
    /*! \brief
    
     * when we create or delete references, make sure to use these
     * functions so we keep track of the refcounts.
     * To simplify the code, we allow a NULL to be passed to dialog_unref().
     */
    #ifdef REF_DEBUG
    #define dialog_ref(arg1,arg2) dialog_ref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
    #define dialog_unref(arg1,arg2) dialog_unref_debug((arg1),(arg2), __FILE__, __LINE__, __PRETTY_FUNCTION__)
    
    static struct sip_pvt *dialog_ref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
    
    	if (p)
    		_ao2_ref_debug(p, 1, tag, file, line, func);
    	else
    		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
    	return p;
    
    static struct sip_pvt *dialog_unref_debug(struct sip_pvt *p, char *tag, char *file, int line, const char *func)
    
    	if (p)
    		_ao2_ref_debug(p, -1, tag, file, line, func);
    	return NULL;
    
    static struct sip_pvt *dialog_ref(struct sip_pvt *p, char *tag)
    
    	if (p)
    		ao2_ref(p, 1);
    	else
    		ast_log(LOG_ERROR, "Attempt to Ref a null pointer\n");
    
    static struct sip_pvt *dialog_unref(struct sip_pvt *p, char *tag)
    
    /*! \brief sip packet - raw format for outbound packets that are sent or scheduled for transmission
     * Packets are linked in a list, whose head is in the struct sip_pvt they belong to.
     * Each packet holds a reference to the parent struct sip_pvt.
     * This structure is allocated in __sip_reliable_xmit() and only for packets that
     * require retransmissions.
     */
    
    Mark Spencer's avatar
    Mark Spencer committed
    struct sip_pkt {
    
    	struct sip_pkt *next;			/*!< Next packet in linked list */
    
    	int retrans;				/*!< Retransmission number */
    	int method;				/*!< SIP method for this packet */
    	int seqno;				/*!< Sequence number */
    
    	char is_resp;				/*!< 1 if this is a response packet (e.g. 200 OK), 0 if it is a request */
    	char is_fatal;				/*!< non-zero if there is a fatal error */
    
    	int response_code;		/*!< If this is a response, the response code */
    
    	struct sip_pvt *owner;			/*!< Owner AST call */
    
    	int retransid;				/*!< Retransmission ID */
    	int timer_a;				/*!< SIP timer A, retransmission timer */
    	int timer_t1;				/*!< SIP Timer T1, estimated RTT or 500 ms */
    	int packetlen;				/*!< Length of packet */
    
    Mark Spencer's avatar
    Mark Spencer committed
    };	
    
    /*!
     * \brief A peer's mailbox
     *
     * We could use STRINGFIELDS here, but for only two strings, it seems like
     * too much effort ...
     */
    struct sip_mailbox {
    	char *mailbox;
    	char *context;
    	/*! Associated MWI subscription */
    	struct ast_event_sub *event_sub;
    	AST_LIST_ENTRY(sip_mailbox) entry;
    };
    
    
    enum sip_peer_type {
    	SIP_TYPE_PEER = (1 << 0),
    	SIP_TYPE_USER = (1 << 1),
    };
    
    
    /*! \brief Structure for SIP peer data, we place calls to peers if registered  or fixed IP address (host) 
    */
    
    /* XXX field 'name' must be first otherwise sip_addrcmp() will fail, as will astobj2 hashing of the structure */
    
    Mark Spencer's avatar
    Mark Spencer committed
    struct sip_peer {
    
    	char name[80];					/*!< the unique name of this object */
    	AST_DECLARE_STRING_FIELDS(
    		AST_STRING_FIELD(secret);		/*!< Password for inbound auth */
    		AST_STRING_FIELD(md5secret);		/*!< Password in MD5 */
    		AST_STRING_FIELD(remotesecret);		/*!< Remote secret (trunks, remote devices) */
    		AST_STRING_FIELD(context);		/*!< Default context for incoming calls */
    		AST_STRING_FIELD(subscribecontext);	/*!< Default context for subscriptions */
    		AST_STRING_FIELD(username);		/*!< Temporary username until registration */ 
    		AST_STRING_FIELD(accountcode);		/*!< Account code */
    		AST_STRING_FIELD(tohost);		/*!< If not dynamic, IP address */
    		AST_STRING_FIELD(regexten); 		/*!< Extension to register (if regcontext is used) */
    		AST_STRING_FIELD(fromuser);		/*!< From: user when calling this peer */
    		AST_STRING_FIELD(fromdomain);		/*!< From: domain when calling this peer */
    		AST_STRING_FIELD(fullcontact);		/*!< Contact registered with us (not in sip.conf) */
    		AST_STRING_FIELD(cid_num);		/*!< Caller ID num */
    		AST_STRING_FIELD(cid_name);		/*!< Caller ID name */
    		AST_STRING_FIELD(vmexten); 		/*!< Dialplan extension for MWI notify message*/
    		AST_STRING_FIELD(language);		/*!<  Default language for prompts */
    		AST_STRING_FIELD(mohinterpret);		/*!<  Music on Hold class */
    		AST_STRING_FIELD(mohsuggest);		/*!<  Music on Hold class */
    		AST_STRING_FIELD(parkinglot);		/*!<  Parkinglot */
    		AST_STRING_FIELD(useragent);		/*!<  User agent in SIP request (saved from registration) */
    
    		AST_STRING_FIELD(mwi_from);         /*!< Name to place in From header for outgoing NOTIFY requests */
    
    		AST_STRING_FIELD(engine);               /*!<  RTP Engine to use */
    
    Olle Johansson's avatar
    Olle Johansson committed
    	struct sip_socket socket;	/*!< Socket used for this peer */
    
    	enum sip_transport default_outbound_transport;    /*!< Peer Registration may change the default outbound transport.
    
    							    If register expires, default should be reset. to this value */
    	/* things that don't belong in flags */
    	unsigned short transports:3;	/*!< Transports (enum sip_transport) that are acceptable for this peer */
    	unsigned short is_realtime:1;	/*!< this is a 'realtime' peer */
    	unsigned short rt_fromcontact:1;/*!< copy fromcontact from realtime */
    	unsigned short host_dynamic:1;	/*!< Dynamic Peers register with Asterisk */
    	unsigned short selfdestruct:1;	/*!< Automatic peers need to destruct themselves */
    	unsigned short the_mark:1;	/*!< moved out of ASTOBJ into struct proper; That which bears the_mark should be deleted! */
    	unsigned short autoframing:1;	/*!< Whether to use our local configuration for frame sizes (off)
    					 *   or respect the other endpoint's request for frame sizes (on)
    					 *   for incoming calls
    					 */
    
    	struct sip_auth *auth;		/*!< Realm authentication list */
    	int amaflags;			/*!< AMA Flags (for billing) */
    	int callingpres;		/*!< Calling id presentation */
    	int inUse;			/*!< Number of calls in use */
    
    	int inRinging;			/*!< Number of calls ringing */
    
    	int onHold;                     /*!< Peer has someone on hold */
    
    	int call_limit;			/*!< Limit of concurrent calls */
    
    	int busy_level;			/*!< Level of active channels where we signal busy */
    
    	enum transfermodes allowtransfer;	/*! SIP Refer restriction scheme */
    
    	struct ast_codec_pref prefs;	/*!<  codec prefs */