Skip to content
Snippets Groups Projects
chan_motif.c 101 KiB
Newer Older
  • Learn to ignore specific revisions
  • /*
     * Asterisk -- An open source telephony toolkit.
     *
     * Copyright (C) 2012, Digium, Inc.
     *
     * Joshua Colp <jcolp@digium.com>
     *
     * See http://www.asterisk.org for more information about
     * the Asterisk project. Please do not directly contact
     * any of the maintainers of this project for assistance;
     * the project provides a web site, mailing lists and IRC
     * channels for your use.
     *
     * This program is free software, distributed under the terms of
     * the GNU General Public License Version 2. See the LICENSE file
     * at the top of the source tree.
     */
    
    /*! \file
     *
     * \author Joshua Colp <jcolp@digium.com>
     *
     * \brief Motif Jingle Channel Driver
     *
    
     * Iksemel http://iksemel.jabberstudio.org/
    
    /*! \li \ref chan_motif.c uses the configuration file \ref motif.conf
    
    Andrew Latham's avatar
    Andrew Latham committed
     * \addtogroup configuration_file
     */
    
    /*! \page motif.conf motif.conf
     * \verbinclude motif.conf.sample
     */
    
    
    /*** MODULEINFO
    	<depend>iksemel</depend>
    
    	<use type="external">openssl</use>
    	<support_level>core</support_level>
     ***/
    
    #include "asterisk.h"
    
    
    ASTERISK_REGISTER_FILE()
    
    
    #include <sys/socket.h>
    #include <fcntl.h>
    #include <netdb.h>
    #include <netinet/in.h>
    #include <arpa/inet.h>
    #include <sys/signal.h>
    #include <iksemel.h>
    #include <pthread.h>
    
    #include "asterisk/lock.h"
    #include "asterisk/channel.h"
    #include "asterisk/config_options.h"
    #include "asterisk/module.h"
    #include "asterisk/pbx.h"
    #include "asterisk/sched.h"
    #include "asterisk/io.h"
    #include "asterisk/rtp_engine.h"
    #include "asterisk/acl.h"
    #include "asterisk/callerid.h"
    #include "asterisk/file.h"
    #include "asterisk/cli.h"
    #include "asterisk/app.h"
    #include "asterisk/musiconhold.h"
    #include "asterisk/manager.h"
    #include "asterisk/stringfields.h"
    #include "asterisk/utils.h"
    #include "asterisk/causes.h"
    #include "asterisk/abstract_jb.h"
    #include "asterisk/xmpp.h"
    
    #include "asterisk/stasis_channels.h"
    
    /*** DOCUMENTATION
    	<configInfo name="chan_motif" language="en_US">
    		<synopsis>Jingle Channel Driver</synopsis>
    		<description>
    			<para><emphasis>Transports</emphasis></para>
    			<para>There are three different transports and protocol derivatives
    			supported by <literal>chan_motif</literal>. They are in order of
    			preference: Jingle using ICE-UDP, Google Jingle, and Google-V1.</para>
    			<para>Jingle as defined in XEP-0166 supports the widest range of
    			features. It is referred to as <literal>ice-udp</literal>. This is
    			the specification that Jingle clients implement.</para>
    			<para>Google Jingle follows the Jingle specification for signaling
    			but uses a custom transport for media. It is supported by the
    			Google Talk Plug-in in Gmail and by some other Jingle clients. It
    			is referred to as <literal>google</literal> in this file.</para>
    			<para>Google-V1 is the original Google Talk signaling protocol
    			which uses an initial preliminary version of Jingle. It also uses
    			the same custom transport as Google Jingle for media. It is
    			supported by Google Voice, some other Jingle clients, and the
    			Windows Google Talk client. It is referred to as <literal>google-v1</literal>
    			in this file.</para>
    			<para>Incoming sessions will automatically switch to the correct
    			transport once it has been determined.</para>
    			<para>Outgoing sessions are capable of determining if the target
    			is capable of Jingle or a Google transport if the target is in the
    			roster. Unfortunately it is not possible to differentiate between
    			a Google Jingle or Google-V1 capable resource until a session
    			initiate attempt occurs. If a resource is determined to use a
    			Google transport it will initially use Google Jingle but will fall
    			back to Google-V1 if required.</para>
    			<para>If an outgoing session attempt fails due to failure to
    			support the given transport <literal>chan_motif</literal> will
    			fall back in preference order listed previously until all
    			transports have been exhausted.</para>
    			<para><emphasis>Dialing and Resource Selection Strategy</emphasis></para>
    			<para>Placing a call through an endpoint can be accomplished using the
    			following dial string:</para>
    			<para><literal>Motif/[endpoint name]/[target]</literal></para>
    			<para>When placing an outgoing call through an endpoint the requested
    			target is searched for in the roster list. If present the first Jingle
    			or Google Jingle capable resource is specifically targeted. Since the
    			capabilities of the resource are known the outgoing session initiation
    			will disregard the configured transport and use the determined one.</para>
    			<para>If the target is not found in the roster the target will be used
    			as-is and a session will be initiated using the transport specified
    			in this configuration file. If no transport has been specified the
    			endpoint defaults to <literal>ice-udp</literal>.</para>
    			<para><emphasis>Video Support</emphasis></para>
    			<para>Support for video does not need to be explicitly enabled.
    			Configuring any video codec on your endpoint will automatically enable
    			it.</para>
    			<para><emphasis>DTMF</emphasis></para>
    			<para>The only supported method for DTMF is RFC2833. This is always
    			enabled on audio streams and negotiated if possible.</para>
    			<para><emphasis>Incoming Calls</emphasis></para>
    			<para>Incoming calls will first look for the extension matching the
    			name of the endpoint in the configured context. If no such extension
    			exists the call will automatically fall back to the <literal>s</literal> extension.</para>
    			<para><emphasis>CallerID</emphasis></para>
    			<para>The incoming caller id number is populated with the username of
    			the caller and the name is populated with the full identity of the
    			caller. If you would like to perform authentication or filtering
    			of incoming calls it is recommended that you use these fields to do so.</para>
    			<para>Outgoing caller id can <emphasis>not</emphasis> be set.</para>
    			<warning>
    				<para>Multiple endpoints using the
    				same connection is <emphasis>NOT</emphasis> supported. Doing so
    				may result in broken calls.</para>
    			</warning>
    		</description>
    		<configFile name="motif.conf">
    			<configObject name="endpoint">
    				<synopsis>The configuration for an endpoint.</synopsis>
    				<configOption name="context">
    					<synopsis>Default dialplan context that incoming sessions will be routed to</synopsis>
    				</configOption>
    				<configOption name="callgroup">
    					<synopsis>A callgroup to assign to this endpoint.</synopsis>
    				</configOption>
    				<configOption name="pickupgroup">
    					<synopsis>A pickup group to assign to this endpoint.</synopsis>
    				</configOption>
    				<configOption name="language">
    					<synopsis>The default language for this endpoint.</synopsis>
    				</configOption>
    				<configOption name="musicclass">
    					<synopsis>Default music on hold class for this endpoint.</synopsis>
    				</configOption>
    				<configOption name="parkinglot">
    					<synopsis>Default parking lot for this endpoint.</synopsis>
    				</configOption>
    				<configOption name="accountcode">
    					<synopsis>Accout code for CDR purposes</synopsis>
    				</configOption>
    				<configOption name="allow">
    					<synopsis>Codecs to allow</synopsis>
    				</configOption>
    				<configOption name="disallow">
    					<synopsis>Codecs to disallow</synopsis>
    				</configOption>
    				<configOption name="connection">
    					<synopsis>Connection to accept traffic on and on which to send traffic out</synopsis>
    				</configOption>
    				<configOption name="transport">
    					<synopsis>The transport to use for the endpoint.</synopsis>
    					<description>
    						<para>The default outbound transport for this endpoint. Inbound
    						messages are inferred. Allowed transports are <literal>ice-udp</literal>,
    						<literal>google</literal>, or <literal>google-v1</literal>. Note
    						that <literal>chan_motif</literal> will fall back to transport
    						preference order if the transport value chosen here fails.</para>
    						<enumlist>
    							<enum name="ice-udp">
    								<para>The Jingle protocol, as defined in XEP 0166.</para>
    							</enum>
    							<enum name="google">
    								<para>The Google Jingle protocol, which follows the Jingle
    								specification for signaling but uses a custom transport for
    								media.</para>
    							</enum>
    							<enum name="google-v1">
    								<para>Google-V1 is the original Google Talk signaling
    								protocol which uses an initial preliminary version of Jingle.
    								It also uses the same custom transport as <literal>google</literal> for media.</para>
    							</enum>
    						</enumlist>
    					</description>
    				</configOption>
    				<configOption name="maxicecandidates">
    					<synopsis>Maximum number of ICE candidates to offer</synopsis>
    				</configOption>
    				<configOption name="maxpayloads">
    					<synopsis>Maximum number of pyaloads to offer</synopsis>
    				</configOption>
    			</configObject>
    		</configFile>
    	</configInfo>
    ***/
    
    
    /*! \brief Default maximum number of ICE candidates we will offer */
    #define DEFAULT_MAX_ICE_CANDIDATES "10"
    
    /*! \brief Default maximum number of payloads we will offer */
    #define DEFAULT_MAX_PAYLOADS "30"
    
    /*! \brief Number of buckets for endpoints */
    #define ENDPOINT_BUCKETS 37
    
    /*! \brief Number of buckets for sessions, on a per-endpoint basis */
    #define SESSION_BUCKETS 37
    
    /*! \brief Namespace for Jingle itself */
    #define JINGLE_NS "urn:xmpp:jingle:1"
    
    /*! \brief Namespace for Jingle RTP sessions */
    #define JINGLE_RTP_NS "urn:xmpp:jingle:apps:rtp:1"
    
    /*! \brief Namespace for Jingle RTP info */
    #define JINGLE_RTP_INFO_NS "urn:xmpp:jingle:apps:rtp:info:1"
    
    /*! \brief Namespace for Jingle ICE-UDP */
    #define JINGLE_ICE_UDP_NS "urn:xmpp:jingle:transports:ice-udp:1"
    
    /*! \brief Namespace for Google Talk ICE-UDP */
    #define GOOGLE_TRANSPORT_NS "http://www.google.com/transport/p2p"
    
    /*! \brief Namespace for Google Talk Raw UDP */
    #define GOOGLE_TRANSPORT_RAW_NS "http://www.google.com/transport/raw-udp"
    
    /*! \brief Namespace for Google Session */
    #define GOOGLE_SESSION_NS "http://www.google.com/session"
    
    /*! \brief Namespace for Google Phone description */
    #define GOOGLE_PHONE_NS "http://www.google.com/session/phone"
    
    /*! \brief Namespace for Google Video description */
    #define GOOGLE_VIDEO_NS "http://www.google.com/session/video"
    
    /*! \brief Namespace for XMPP stanzas */
    #define XMPP_STANZAS_NS "urn:ietf:params:xml:ns:xmpp-stanzas"
    
    /*! \brief The various transport methods supported, from highest priority to lowest priority when doing fallback */
    enum jingle_transport {
    	JINGLE_TRANSPORT_ICE_UDP = 3,   /*!< XEP-0176 */
    	JINGLE_TRANSPORT_GOOGLE_V2 = 2, /*!< https://developers.google.com/talk/call_signaling */
    	JINGLE_TRANSPORT_GOOGLE_V1 = 1, /*!< Undocumented initial Google specification */
    	JINGLE_TRANSPORT_NONE = 0,      /*!< No transport specified */
    };
    
    /*! \brief Endpoint state information */
    struct jingle_endpoint_state {
    	struct ao2_container *sessions; /*!< Active sessions to or from the endpoint */
    };
    
    /*! \brief Endpoint which contains configuration information and active sessions */
    struct jingle_endpoint {
    	AST_DECLARE_STRING_FIELDS(
    		AST_STRING_FIELD(name);              /*!< Name of the endpoint */
    		AST_STRING_FIELD(context);           /*!< Context to place incoming calls into */
    		AST_STRING_FIELD(accountcode);       /*!< Account code */
    		AST_STRING_FIELD(language);          /*!< Default language for prompts */
    		AST_STRING_FIELD(musicclass);        /*!< Configured music on hold class */
    		AST_STRING_FIELD(parkinglot);        /*!< Configured parking lot */
    		);
    	struct ast_xmpp_client *connection;     /*!< Connection to use for traffic */
    	iksrule *rule;                          /*!< Active matching rule */
    	unsigned int maxicecandidates;          /*!< Maximum number of ICE candidates we will offer */
    	unsigned int maxpayloads;               /*!< Maximum number of payloads we will offer */
    	struct ast_format_cap *cap;             /*!< Formats to use */
    	ast_group_t callgroup;                  /*!< Call group */
    	ast_group_t pickupgroup;                /*!< Pickup group */
    	enum jingle_transport transport;        /*!< Default transport to use on outgoing sessions */
    	struct jingle_endpoint_state *state;    /*!< Endpoint state information */
    };
    
    /*! \brief Session which contains information about an active session */
    struct jingle_session {
    	AST_DECLARE_STRING_FIELDS(
    		AST_STRING_FIELD(sid);        /*!< Session identifier */
    		AST_STRING_FIELD(audio_name); /*!< Name of the audio content */
    		AST_STRING_FIELD(video_name); /*!< Name of the video content */
    		);
    	struct jingle_endpoint_state *state;  /*!< Endpoint we are associated with */
    	struct ast_xmpp_client *connection;   /*!< Connection to use for traffic */
    	enum jingle_transport transport;      /*!< Transport type to use for this session */
    	unsigned int maxicecandidates;        /*!< Maximum number of ICE candidates we will offer */
    	unsigned int maxpayloads;             /*!< Maximum number of payloads we will offer */
    	char remote_original[XMPP_MAX_JIDLEN];/*!< Identifier of the original remote party (remote may have changed due to redirect) */
    	char remote[XMPP_MAX_JIDLEN];         /*!< Identifier of the remote party */
    	iksrule *rule;                        /*!< Session matching rule */
    	struct ast_channel *owner;            /*!< Master Channel */
    	struct ast_rtp_instance *rtp;         /*!< RTP audio session */
    	struct ast_rtp_instance *vrtp;        /*!< RTP video session */
    	struct ast_format_cap *cap;           /*!< Local codec capabilities */
    	struct ast_format_cap *jointcap;      /*!< Joint codec capabilities */
    	struct ast_format_cap *peercap;       /*!< Peer codec capabilities */
    	unsigned int outgoing:1;              /*!< Whether this is an outgoing leg or not */
    	unsigned int gone:1;                  /*!< In the eyes of Jingle this session is already gone */
    
    	ast_callid callid;                    /*!< Bound session call-id */
    
    };
    
    static const char desc[] = "Motif Jingle Channel";
    static const char channel_type[] = "Motif";
    
    struct jingle_config {
    	struct ao2_container *endpoints; /*!< Configured endpoints */
    };
    
    static AO2_GLOBAL_OBJ_STATIC(globals);
    
    static struct ast_sched_context *sched; /*!< Scheduling context for RTCP */
    
    /* \brief Asterisk core interaction functions */
    
    static struct ast_channel *jingle_request(const char *type, struct ast_format_cap *cap, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *data, int *cause);
    
    static int jingle_sendtext(struct ast_channel *ast, const char *text);
    static int jingle_digit_begin(struct ast_channel *ast, char digit);
    static int jingle_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
    static int jingle_call(struct ast_channel *ast, const char *dest, int timeout);
    static int jingle_hangup(struct ast_channel *ast);
    static int jingle_answer(struct ast_channel *ast);
    static struct ast_frame *jingle_read(struct ast_channel *ast);
    static int jingle_write(struct ast_channel *ast, struct ast_frame *f);
    static int jingle_indicate(struct ast_channel *ast, int condition, const void *data, size_t datalen);
    static int jingle_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
    static struct jingle_session *jingle_alloc(struct jingle_endpoint *endpoint, const char *from, const char *sid);
    
    /*! \brief Action handlers */
    static void jingle_action_session_initiate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    static void jingle_action_transport_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    static void jingle_action_session_accept(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    static void jingle_action_session_info(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    static void jingle_action_session_terminate(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    
    /*! \brief PBX interface structure for channel registration */
    static struct ast_channel_tech jingle_tech = {
    	.type = "Motif",
    	.description = "Motif Jingle Channel Driver",
    	.requester = jingle_request,
    	.send_text = jingle_sendtext,
    	.send_digit_begin = jingle_digit_begin,
    	.send_digit_end = jingle_digit_end,
    	.call = jingle_call,
    	.hangup = jingle_hangup,
    	.answer = jingle_answer,
    	.read = jingle_read,
    	.write = jingle_write,
    	.write_video = jingle_write,
    	.exception = jingle_read,
    	.indicate = jingle_indicate,
    	.fixup = jingle_fixup,
    	.properties = AST_CHAN_TP_WANTSJITTER | AST_CHAN_TP_CREATESJITTER
    };
    
    /*! \brief Defined handlers for different Jingle actions */
    static const struct jingle_action_handler {
    	const char *action;
    	void (*handler)(struct jingle_endpoint *endpoint, struct jingle_session *session, ikspak *pak);
    } jingle_action_handlers[] = {
    	/* Jingle actions */
    	{ "session-initiate", jingle_action_session_initiate, },
    	{ "transport-info", jingle_action_transport_info, },
    	{ "session-accept", jingle_action_session_accept, },
    	{ "session-info", jingle_action_session_info, },
    	{ "session-terminate", jingle_action_session_terminate, },
    	/* Google-V1 actions */
    	{ "initiate", jingle_action_session_initiate, },
    	{ "candidates", jingle_action_transport_info, },
    	{ "accept", jingle_action_session_accept, },
    	{ "terminate", jingle_action_session_terminate, },
    	{ "reject", jingle_action_session_terminate, },
    };
    
    /*! \brief Reason text <-> cause code mapping */
    static const struct jingle_reason_mapping {
    	const char *reason;
    	int cause;
    } jingle_reason_mappings[] = {
    	{ "busy", AST_CAUSE_BUSY, },
    	{ "cancel", AST_CAUSE_CALL_REJECTED, },
    	{ "connectivity-error", AST_CAUSE_INTERWORKING, },
    	{ "decline", AST_CAUSE_CALL_REJECTED, },
    	{ "expired", AST_CAUSE_NO_USER_RESPONSE, },
    	{ "failed-transport", AST_CAUSE_PROTOCOL_ERROR, },
    	{ "failed-application", AST_CAUSE_SWITCH_CONGESTION, },
    	{ "general-error", AST_CAUSE_CONGESTION, },
    	{ "gone", AST_CAUSE_NORMAL_CLEARING, },
    	{ "incompatible-parameters", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
    	{ "media-error", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
    	{ "security-error", AST_CAUSE_PROTOCOL_ERROR, },
    	{ "success", AST_CAUSE_NORMAL_CLEARING, },
    	{ "timeout", AST_CAUSE_RECOVERY_ON_TIMER_EXPIRE, },
    	{ "unsupported-applications", AST_CAUSE_BEARERCAPABILITY_NOTAVAIL, },
    	{ "unsupported-transports", AST_CAUSE_FACILITY_NOT_IMPLEMENTED, },
    };
    
    /*! \brief Hashing function for Jingle sessions */
    static int jingle_session_hash(const void *obj, const int flags)
    {
    	const struct jingle_session *session = obj;
    	const char *sid = obj;
    
    	return ast_str_hash(flags & OBJ_KEY ? sid : session->sid);
    }
    
    /*! \brief Comparator function for Jingle sessions */
    static int jingle_session_cmp(void *obj, void *arg, int flags)
    {
    	struct jingle_session *session1 = obj, *session2 = arg;
    	const char *sid = arg;
    
    	return !strcmp(session1->sid, flags & OBJ_KEY ? sid : session2->sid) ? CMP_MATCH | CMP_STOP : 0;
    }
    
    /*! \brief Destructor for Jingle endpoint state */
    static void jingle_endpoint_state_destructor(void *obj)
    {
    	struct jingle_endpoint_state *state = obj;
    
    	ao2_ref(state->sessions, -1);
    }
    
    /*! \brief Destructor for Jingle endpoints */
    static void jingle_endpoint_destructor(void *obj)
    {
    	struct jingle_endpoint *endpoint = obj;
    
    	if (endpoint->rule) {
    		iks_filter_remove_rule(endpoint->connection->filter, endpoint->rule);
    	}
    
    	if (endpoint->connection) {
    		ast_xmpp_client_unref(endpoint->connection);
    	}
    
    
    	ao2_ref(endpoint->state, -1);
    
    	ast_string_field_free_memory(endpoint);
    }
    
    /*! \brief Find function for Jingle endpoints */
    static void *jingle_endpoint_find(struct ao2_container *tmp_container, const char *category)
    {
    	return ao2_find(tmp_container, category, OBJ_KEY);
    }
    
    /*! \brief Allocator function for Jingle endpoint state */
    static struct jingle_endpoint_state *jingle_endpoint_state_create(void)
    {
    	struct jingle_endpoint_state *state;
    
    	if (!(state = ao2_alloc(sizeof(*state), jingle_endpoint_state_destructor))) {
    		return NULL;
    	}
    
    	if (!(state->sessions = ao2_container_alloc(SESSION_BUCKETS, jingle_session_hash, jingle_session_cmp))) {
    		ao2_ref(state, -1);
    		return NULL;
    	}
    
    	return state;
    }
    
    /*! \brief State find/create function */
    static struct jingle_endpoint_state *jingle_endpoint_state_find_or_create(const char *category)
    {
    	RAII_VAR(struct jingle_config *, cfg, ao2_global_obj_ref(globals), ao2_cleanup);
    	RAII_VAR(struct jingle_endpoint *, endpoint, NULL, ao2_cleanup);
    
    	if (!cfg || !cfg->endpoints || !(endpoint = jingle_endpoint_find(cfg->endpoints, category))) {
    		return jingle_endpoint_state_create();
    	}
    
    	ao2_ref(endpoint->state, +1);
    	return endpoint->state;
    }
    
    /*! \brief Allocator function for Jingle endpoints */
    static void *jingle_endpoint_alloc(const char *cat)
    {
    	struct jingle_endpoint *endpoint;
    
    	if (!(endpoint = ao2_alloc(sizeof(*endpoint), jingle_endpoint_destructor))) {
    		return NULL;
    	}
    
    	if (ast_string_field_init(endpoint, 512)) {
    		ao2_ref(endpoint, -1);
    		return NULL;
    	}
    
    	if (!(endpoint->state = jingle_endpoint_state_find_or_create(cat))) {
    		ao2_ref(endpoint, -1);
    		return NULL;
    	}
    
    	ast_string_field_set(endpoint, name, cat);
    
    
    	endpoint->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
    
    	endpoint->transport = JINGLE_TRANSPORT_ICE_UDP;
    
    	return endpoint;
    }
    
    /*! \brief Hashing function for Jingle endpoints */
    static int jingle_endpoint_hash(const void *obj, const int flags)
    {
    	const struct jingle_endpoint *endpoint = obj;
    	const char *name = obj;
    
    	return ast_str_hash(flags & OBJ_KEY ? name : endpoint->name);
    }
    
    /*! \brief Comparator function for Jingle endpoints */
    static int jingle_endpoint_cmp(void *obj, void *arg, int flags)
    {
    	struct jingle_endpoint *endpoint1 = obj, *endpoint2 = arg;
    	const char *name = arg;
    
    	return !strcmp(endpoint1->name, flags & OBJ_KEY ? name : endpoint2->name) ? CMP_MATCH | CMP_STOP : 0;
    }
    
    static struct aco_type endpoint_option = {
    	.type = ACO_ITEM,
    
    	.name = "endpoint",
    
    	.category_match = ACO_BLACKLIST,
    	.category = "^general$",
    	.item_alloc = jingle_endpoint_alloc,
    	.item_find = jingle_endpoint_find,
    	.item_offset = offsetof(struct jingle_config, endpoints),
    };
    
    struct aco_type *endpoint_options[] = ACO_TYPES(&endpoint_option);
    
    struct aco_file jingle_conf = {
    	.filename = "motif.conf",
    	.types = ACO_TYPES(&endpoint_option),
    };
    
    /*! \brief Destructor for Jingle sessions */
    static void jingle_session_destructor(void *obj)
    {
    	struct jingle_session *session = obj;
    
    	if (session->rule) {
    		iks_filter_remove_rule(session->connection->filter, session->rule);
    	}
    
    	if (session->connection) {
    		ast_xmpp_client_unref(session->connection);
    	}
    
    	if (session->rtp) {
    
    		ast_rtp_instance_stop(session->rtp);
    
    		ast_rtp_instance_destroy(session->rtp);
    	}
    
    	if (session->vrtp) {
    
    		ast_rtp_instance_stop(session->vrtp);
    
    	ao2_cleanup(session->cap);
    	ao2_cleanup(session->jointcap);
    	ao2_cleanup(session->peercap);
    
    
    	ast_string_field_free_memory(session);
    }
    
    /*! \brief Destructor called when module configuration goes away */
    static void jingle_config_destructor(void *obj)
    {
    	struct jingle_config *cfg = obj;
    	ao2_cleanup(cfg->endpoints);
    }
    
    /*! \brief Allocator called when module configuration should appear */
    static void *jingle_config_alloc(void)
    {
    	struct jingle_config *cfg;
    
    	if (!(cfg = ao2_alloc(sizeof(*cfg), jingle_config_destructor))) {
    		return NULL;
    	}
    
    	if (!(cfg->endpoints = ao2_container_alloc(ENDPOINT_BUCKETS, jingle_endpoint_hash, jingle_endpoint_cmp))) {
    		ao2_ref(cfg, -1);
    		return NULL;
    	}
    
    	return cfg;
    }
    
    CONFIG_INFO_STANDARD(cfg_info, globals, jingle_config_alloc,
    		     .files = ACO_FILES(&jingle_conf),
    	);
    
    /*! \brief Function called by RTP engine to get local RTP peer */
    static enum ast_rtp_glue_result jingle_get_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance **instance)
    {
    	struct jingle_session *session = ast_channel_tech_pvt(chan);
    	enum ast_rtp_glue_result res = AST_RTP_GLUE_RESULT_LOCAL;
    
    	if (!session->rtp) {
    		return AST_RTP_GLUE_RESULT_FORBID;
    	}
    
    	ao2_ref(session->rtp, +1);
    	*instance = session->rtp;
    
    	return res;
    }
    
    /*! \brief Function called by RTP engine to get peer capabilities */
    static void jingle_get_codec(struct ast_channel *chan, struct ast_format_cap *result)
    {
    }
    
    /*! \brief Function called by RTP engine to change where the remote party should send media */
    static int jingle_set_rtp_peer(struct ast_channel *chan, struct ast_rtp_instance *rtp, struct ast_rtp_instance *vrtp, struct ast_rtp_instance *tpeer, const struct ast_format_cap *cap, int nat_active)
    {
    	return -1;
    }
    
    /*! \brief Local glue for interacting with the RTP engine core */
    static struct ast_rtp_glue jingle_rtp_glue = {
    	.type = "Motif",
    	.get_rtp_info = jingle_get_rtp_peer,
    	.get_codec = jingle_get_codec,
    	.update_peer = jingle_set_rtp_peer,
    };
    
    
    /*! \brief Set the channel owner on the \ref jingle_session object and related objects */
    static void jingle_set_owner(struct jingle_session *session, struct ast_channel *chan)
    {
    	session->owner = chan;
    	if (session->rtp) {
    		ast_rtp_instance_set_channel_id(session->rtp, session->owner ? ast_channel_uniqueid(session->owner) : "");
    	}
    	if (session->vrtp) {
    		ast_rtp_instance_set_channel_id(session->vrtp, session->owner ? ast_channel_uniqueid(session->owner) : "");
    	}
    }
    
    
    /*! \brief Internal helper function which enables video support on a sesson if possible */
    static void jingle_enable_video(struct jingle_session *session)
    {
    	struct ast_sockaddr tmp;
    	struct ast_rtp_engine_ice *ice;
    
    	/* If video is already present don't do anything */
    	if (session->vrtp) {
    		return;
    	}
    
    	/* If there are no configured video codecs do not turn video support on, it just won't work */
    
    	if (!ast_format_cap_has_type(session->cap, AST_MEDIA_TYPE_VIDEO)) {
    
    		return;
    	}
    
    	ast_sockaddr_parse(&tmp, "0.0.0.0", 0);
    
    	if (!(session->vrtp = ast_rtp_instance_new("asterisk", sched, &tmp, NULL))) {
    		return;
    	}
    
    	ast_rtp_instance_set_prop(session->vrtp, AST_RTP_PROPERTY_RTCP, 1);
    
    	ast_rtp_instance_set_channel_id(session->vrtp, ast_channel_uniqueid(session->owner));
    
    	ast_channel_set_fd(session->owner, 2, ast_rtp_instance_fd(session->vrtp, 0));
    	ast_channel_set_fd(session->owner, 3, ast_rtp_instance_fd(session->vrtp, 1));
    
    	ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(session->vrtp),
    		ast_format_cap_get_framing(session->cap));
    
    	if (session->transport == JINGLE_TRANSPORT_GOOGLE_V2 && (ice = ast_rtp_instance_get_ice(session->vrtp))) {
    		ice->stop(session->vrtp);
    	}
    }
    
    /*! \brief Internal helper function used to allocate Jingle session on an endpoint */
    static struct jingle_session *jingle_alloc(struct jingle_endpoint *endpoint, const char *from, const char *sid)
    {
    	struct jingle_session *session;
    
    	struct ast_sockaddr tmp;
    
    	if (!(session = ao2_alloc(sizeof(*session), jingle_session_destructor))) {
    		return NULL;
    	}
    
    
    	callid = ast_read_threadstorage_callid();
    	session->callid = (callid ? callid : ast_create_callid());
    
    
    	if (ast_string_field_init(session, 512)) {
    		ao2_ref(session, -1);
    		return NULL;
    	}
    
    	if (!ast_strlen_zero(from)) {
    		ast_copy_string(session->remote_original, from, sizeof(session->remote_original));
    		ast_copy_string(session->remote, from, sizeof(session->remote));
    	}
    
    	if (ast_strlen_zero(sid)) {
    
    		ast_string_field_build(session, sid, "%08lx%08lx", (unsigned long)ast_random(), (unsigned long)ast_random());
    
    		session->outgoing = 1;
    		ast_string_field_set(session, audio_name, "audio");
    		ast_string_field_set(session, video_name, "video");
    	} else {
    		ast_string_field_set(session, sid, sid);
    	}
    
    	ao2_ref(endpoint->state, +1);
    	session->state = endpoint->state;
    	ao2_ref(endpoint->connection, +1);
    	session->connection = endpoint->connection;
    	session->transport = endpoint->transport;
    
    
    	if (!(session->cap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
    	    !(session->jointcap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
    	    !(session->peercap = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT)) ||
    
    	    !session->callid) {
    
    	ast_format_cap_append_from_cap(session->cap, endpoint->cap, AST_MEDIA_TYPE_UNKNOWN);
    
    	/* While we rely on res_xmpp for communication we still need a temporary ast_sockaddr to tell the RTP engine
    
    	 * that we want IPv4 */
    	ast_sockaddr_parse(&tmp, "0.0.0.0", 0);
    
    	/* Sessions always carry audio, but video is optional so don't enable it here */
    	if (!(session->rtp = ast_rtp_instance_new("asterisk", sched, &tmp, NULL))) {
    		ao2_ref(session, -1);
    		return NULL;
    	}
    	ast_rtp_instance_set_prop(session->rtp, AST_RTP_PROPERTY_RTCP, 1);
    	ast_rtp_instance_set_prop(session->rtp, AST_RTP_PROPERTY_DTMF, 1);
    
    	session->maxicecandidates = endpoint->maxicecandidates;
    	session->maxpayloads = endpoint->maxpayloads;
    
    	return session;
    }
    
    /*! \brief Function called to create a new Jingle Asterisk channel */
    
    static struct ast_channel *jingle_new(struct jingle_endpoint *endpoint, struct jingle_session *session, int state, const char *title, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, const char *cid_name)
    
    {
    	struct ast_channel *chan;
    	const char *str = S_OR(title, session->remote);
    
    	struct ast_format_cap *caps;
    	struct ast_format *tmpfmt;
    
    	if (!ast_format_cap_count(session->cap)) {
    		return NULL;
    	}
    
    	caps = ast_format_cap_alloc(AST_FORMAT_CAP_FLAG_DEFAULT);
    	if (!caps) {
    
    	if (!(chan = ast_channel_alloc_with_endpoint(1, state, S_OR(title, ""), S_OR(cid_name, ""), "", "", "", assignedids, requestor, 0, endpoint->connection->endpoint, "Motif/%s-%04lx", str, (unsigned long)(ast_random() & 0xffff)))) {
    
    	ast_channel_stage_snapshot(chan);
    
    
    	ast_channel_tech_set(chan, &jingle_tech);
    	ast_channel_tech_pvt_set(chan, session);
    
    	jingle_set_owner(session, chan);
    
    	ast_channel_callid_set(chan, session->callid);
    
    
    	ast_format_cap_append_from_cap(caps, session->cap, AST_MEDIA_TYPE_UNKNOWN);
    	ast_channel_nativeformats_set(chan, caps);
    	ao2_ref(caps, -1);
    
    
    	if (session->rtp) {
    		struct ast_rtp_engine_ice *ice;
    
    		ast_channel_set_fd(chan, 0, ast_rtp_instance_fd(session->rtp, 0));
    		ast_channel_set_fd(chan, 1, ast_rtp_instance_fd(session->rtp, 1));
    
    		ast_rtp_codecs_set_framing(ast_rtp_instance_get_codecs(session->rtp),
    			ast_format_cap_get_framing(session->cap));
    
    
    		if (((session->transport == JINGLE_TRANSPORT_GOOGLE_V2) ||
    		     (session->transport == JINGLE_TRANSPORT_GOOGLE_V1)) &&
    		    (ice = ast_rtp_instance_get_ice(session->rtp))) {
    			/* We stop built in ICE support because we need to fall back to old old old STUN support */
    			ice->stop(session->rtp);
    		}
    	}
    
    	if (state == AST_STATE_RING) {
    		ast_channel_rings_set(chan, 1);
    	}
    
    	ast_channel_adsicpe_set(chan, AST_ADSI_UNAVAILABLE);
    
    
    	tmpfmt = ast_format_cap_get_format(session->cap, 0);
    	ast_channel_set_writeformat(chan, tmpfmt);
    	ast_channel_set_rawwriteformat(chan, tmpfmt);
    	ast_channel_set_readformat(chan, tmpfmt);
    	ast_channel_set_rawreadformat(chan, tmpfmt);
    	ao2_ref(tmpfmt, -1);
    
    
    	ao2_lock(endpoint);
    
    	ast_channel_callgroup_set(chan, endpoint->callgroup);
    	ast_channel_pickupgroup_set(chan, endpoint->pickupgroup);
    
    	if (!ast_strlen_zero(endpoint->accountcode)) {
    		ast_channel_accountcode_set(chan, endpoint->accountcode);
    	}
    
    	if (!ast_strlen_zero(endpoint->language)) {
    		ast_channel_language_set(chan, endpoint->language);
    	}
    
    	if (!ast_strlen_zero(endpoint->musicclass)) {
    		ast_channel_musicclass_set(chan, endpoint->musicclass);
    	}
    
    	ast_channel_context_set(chan, endpoint->context);
    
    	if (ast_exists_extension(NULL, endpoint->context, endpoint->name, 1, NULL)) {
    		ast_channel_exten_set(chan, endpoint->name);
    	} else {
    		ast_channel_exten_set(chan, "s");
    	}
    
    	ast_channel_priority_set(chan, 1);
    
    	ao2_unlock(endpoint);
    
    
    	ast_channel_stage_snapshot_done(chan);
    
    	ast_channel_unlock(chan);
    
    
    	return chan;
    }
    
    /*! \brief Internal helper function which sends a response */
    static void jingle_send_response(struct ast_xmpp_client *connection, ikspak *pak)
    {
    	iks *response;
    
    	if (!(response = iks_new("iq"))) {
    		ast_log(LOG_ERROR, "Unable to allocate an IKS response stanza\n");
    		return;
    	}
    
    	iks_insert_attrib(response, "type", "result");
    	iks_insert_attrib(response, "from", connection->jid->full);
    	iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
    	iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
    
    	ast_xmpp_client_send(connection, response);
    
    	iks_delete(response);
    }
    
    /*! \brief Internal helper function which sends an error response */
    static void jingle_send_error_response(struct ast_xmpp_client *connection, ikspak *pak, const char *type, const char *reasonstr, const char *reasonstr2)
    {
    	iks *response, *error = NULL, *reason = NULL, *reason2 = NULL;
    
    	if (!(response = iks_new("iq")) ||
    	    !(error = iks_new("error")) ||
    	    !(reason = iks_new(reasonstr))) {
    		ast_log(LOG_ERROR, "Unable to allocate IKS error response stanzas\n");
    		goto end;
    	}
    
    	iks_insert_attrib(response, "type", "error");
    	iks_insert_attrib(response, "from", connection->jid->full);
    	iks_insert_attrib(response, "to", iks_find_attrib(pak->x, "from"));
    	iks_insert_attrib(response, "id", iks_find_attrib(pak->x, "id"));
    
    	iks_insert_attrib(error, "type", type);
    	iks_insert_node(error, reason);
    
    	if (!ast_strlen_zero(reasonstr2) && (reason2 = iks_new(reasonstr2))) {
    		iks_insert_node(error, reason2);
    	}
    
    	iks_insert_node(response, error);
    
    	ast_xmpp_client_send(connection, response);
    end:
    	iks_delete(reason2);
    	iks_delete(reason);
    	iks_delete(error);
    	iks_delete(response);
    }
    
    /*! \brief Internal helper function which adds ICE-UDP candidates to a transport node */
    static int jingle_add_ice_udp_candidates_to_transport(struct ast_rtp_instance *rtp, iks *transport, iks **candidates, unsigned int maximum)
    {
    	struct ast_rtp_engine_ice *ice;
    	struct ao2_container *local_candidates;
    	struct ao2_iterator it;
    	struct ast_rtp_engine_ice_candidate *candidate;
    	int i = 0, res = 0;
    
    	if (!(ice = ast_rtp_instance_get_ice(rtp)) || !(local_candidates = ice->get_local_candidates(rtp))) {
    		ast_log(LOG_ERROR, "Unable to add ICE-UDP candidates as ICE support not available or no candidates available\n");
    		return -1;
    	}
    
    	iks_insert_attrib(transport, "xmlns", JINGLE_ICE_UDP_NS);
    	iks_insert_attrib(transport, "pwd", ice->get_password(rtp));
    	iks_insert_attrib(transport, "ufrag", ice->get_ufrag(rtp));
    
    	it = ao2_iterator_init(local_candidates, 0);
    
    	while ((candidate = ao2_iterator_next(&it)) && (i < maximum)) {
    		iks *local_candidate;
    		char tmp[30];
    
    		if (!(local_candidate = iks_new("candidate"))) {
    			res = -1;
    			ast_log(LOG_ERROR, "Unable to allocate IKS candidate stanza for ICE-UDP transport\n");
    			break;
    		}
    
    
    		snprintf(tmp, sizeof(tmp), "%u", candidate->id);
    
    		iks_insert_attrib(local_candidate, "component", tmp);
    		snprintf(tmp, sizeof(tmp), "%d", ast_str_hash(candidate->foundation));
    		iks_insert_attrib(local_candidate, "foundation", tmp);
    		iks_insert_attrib(local_candidate, "generation", "0");
    
    		iks_insert_attrib(local_candidate, "network", "0");
    
    		snprintf(tmp, sizeof(tmp), "%04lx", (unsigned long)(ast_random() & 0xffff));
    
    		iks_insert_attrib(local_candidate, "id", tmp);
    		iks_insert_attrib(local_candidate, "ip", ast_sockaddr_stringify_host(&candidate->address));
    		iks_insert_attrib(local_candidate, "port", ast_sockaddr_stringify_port(&candidate->address));
    		snprintf(tmp, sizeof(tmp), "%d", candidate->priority);
    		iks_insert_attrib(local_candidate, "priority", tmp);
    		iks_insert_attrib(local_candidate, "protocol", "udp");
    
    		if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_HOST) {
    			iks_insert_attrib(local_candidate, "type", "host");
    		} else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_SRFLX) {
    			iks_insert_attrib(local_candidate, "type", "srflx");
    		} else if (candidate->type == AST_RTP_ICE_CANDIDATE_TYPE_RELAYED) {
    			iks_insert_attrib(local_candidate, "type", "relay");
    		}
    
    		iks_insert_node(transport, local_candidate);
    		candidates[i++] = local_candidate;
    	}
    
    	ao2_iterator_destroy(&it);
    	ao2_ref(local_candidates, -1);
    
    	return res;
    }
    
    /*! \brief Internal helper function which adds Google candidates to a transport node */
    static int jingle_add_google_candidates_to_transport(struct ast_rtp_instance *rtp, iks *transport, iks **candidates, unsigned int video, enum jingle_transport transport_type, unsigned int maximum)
    {
    	struct ast_rtp_engine_ice *ice;
    	struct ao2_container *local_candidates;
    	struct ao2_iterator it;
    	struct ast_rtp_engine_ice_candidate *candidate;
    	int i = 0, res = 0;
    
    	if (!(ice = ast_rtp_instance_get_ice(rtp)) || !(local_candidates = ice->get_local_candidates(rtp))) {
    		ast_log(LOG_ERROR, "Unable to add Google ICE candidates as ICE support not available or no candidates available\n");
    		return -1;
    	}
    
    	if (transport_type != JINGLE_TRANSPORT_GOOGLE_V1) {
    		iks_insert_attrib(transport, "xmlns", GOOGLE_TRANSPORT_NS);
    	}
    
    	it = ao2_iterator_init(local_candidates, 0);
    
    	while ((candidate = ao2_iterator_next(&it)) && (i < maximum)) {
    		iks *local_candidate;
    		/* In Google land a username is 16 bytes, explicitly */