aboutsummaryrefslogtreecommitdiff
path: root/xmpp-vala/src
diff options
context:
space:
mode:
Diffstat (limited to 'xmpp-vala/src')
-rw-r--r--xmpp-vala/src/core/xmpp_log.vala4
-rw-r--r--xmpp-vala/src/module/bind.vala4
-rw-r--r--xmpp-vala/src/module/iq/module.vala7
-rw-r--r--xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala17
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle.vala1061
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/component.vala62
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/content.vala239
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/content_description.vala27
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/content_node.vala112
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/content_security.vala18
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/content_transport.vala29
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/jingle_flag.vala38
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/jingle_module.vala235
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/jingle_structs.vala73
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/reason_element.vala30
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/session.vala561
-rw-r--r--xmpp-vala/src/module/xep/0166_jingle/session_info.vala12
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/content_parameters.vala231
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/content_type.vala23
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/jingle_rtp_module.vala290
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/payload_type.vala99
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/session_info_type.vala67
-rw-r--r--xmpp-vala/src/module/xep/0167_jingle_rtp/stream.vala76
-rw-r--r--xmpp-vala/src/module/xep/0176_jingle_ice_udp/candidate.vala93
-rw-r--r--xmpp-vala/src/module/xep/0176_jingle_ice_udp/jingle_ice_udp_module.vala39
-rw-r--r--xmpp-vala/src/module/xep/0176_jingle_ice_udp/transport_parameters.vala167
-rw-r--r--xmpp-vala/src/module/xep/0199_ping.vala2
-rw-r--r--xmpp-vala/src/module/xep/0215_external_service_discovery.vala49
-rw-r--r--xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala168
-rw-r--r--xmpp-vala/src/module/xep/0260_jingle_socks5_bytestreams.vala413
-rw-r--r--xmpp-vala/src/module/xep/0261_jingle_in_band_bytestreams.vala52
-rw-r--r--xmpp-vala/src/module/xep/0353_jingle_message_initiation.vala104
-rw-r--r--xmpp-vala/src/module/xep/0384_omemo/omemo_decryptor.vala62
-rw-r--r--xmpp-vala/src/module/xep/0384_omemo/omemo_encryptor.vala116
34 files changed, 3362 insertions, 1218 deletions
diff --git a/xmpp-vala/src/core/xmpp_log.vala b/xmpp-vala/src/core/xmpp_log.vala
index 4790a8ab..3d5693ef 100644
--- a/xmpp-vala/src/core/xmpp_log.vala
+++ b/xmpp-vala/src/core/xmpp_log.vala
@@ -110,13 +110,13 @@ public class XmppLog {
public void node(string what, StanzaNode node, XmppStream stream) {
if (should_log_node(node)) {
- stderr.printf("%sXMPP %s [%s %p %s]%s\n%s\n", use_ansi ? ANSI_COLOR_WHITE : "", what, ident, stream, new DateTime.now_local().to_string(), use_ansi ? ANSI_COLOR_END : "", use_ansi ? node.to_ansi_string(hide_ns) : node.to_string());
+ stderr.printf("%sXMPP %s [%s stream:%p thread:%p %s]%s\n%s\n", use_ansi ? ANSI_COLOR_WHITE : "", what, ident, stream, Thread.self<Thread>(), new DateTime.now_local().to_string(), use_ansi ? ANSI_COLOR_END : "", use_ansi ? node.to_ansi_string(hide_ns) : node.to_string());
}
}
public void str(string what, string str, XmppStream stream) {
if (should_log_str(str)) {
- stderr.printf("%sXMPP %s [%s %p %s]%s\n%s\n", use_ansi ? ANSI_COLOR_WHITE : "", what, ident, stream, new DateTime.now_local().to_string(), use_ansi ? ANSI_COLOR_END : "", str);
+ stderr.printf("%sXMPP %s [%s stream:%p thread:%p %s]%s\n%s\n", use_ansi ? ANSI_COLOR_WHITE : "", what, ident, stream, Thread.self<Thread>(), new DateTime.now_local().to_string(), use_ansi ? ANSI_COLOR_END : "", str);
}
}
diff --git a/xmpp-vala/src/module/bind.vala b/xmpp-vala/src/module/bind.vala
index 89398bfb..4df8881a 100644
--- a/xmpp-vala/src/module/bind.vala
+++ b/xmpp-vala/src/module/bind.vala
@@ -69,6 +69,10 @@ namespace Xmpp.Bind {
public Jid? my_jid;
public bool finished = false;
+ public static Jid? get_my_jid(XmppStream stream) {
+ return stream.get_flag(IDENTITY).my_jid;
+ }
+
public override string get_ns() { return NS_URI; }
public override string get_id() { return IDENTITY.id; }
}
diff --git a/xmpp-vala/src/module/iq/module.vala b/xmpp-vala/src/module/iq/module.vala
index 9deb0422..17cd3f0d 100644
--- a/xmpp-vala/src/module/iq/module.vala
+++ b/xmpp-vala/src/module/iq/module.vala
@@ -6,10 +6,15 @@ namespace Xmpp.Iq {
public class Module : XmppStreamNegotiationModule {
public static ModuleIdentity<Module> IDENTITY = new ModuleIdentity<Module>(NS_URI, "iq_module");
+ public signal void preprocess_incoming_iq_set_get(XmppStream stream, Stanza iq_stanza);
+ public signal void preprocess_outgoing_iq_set_get(XmppStream stream, Stanza iq_stanza);
+
private HashMap<string, ResponseListener> responseListeners = new HashMap<string, ResponseListener>();
private HashMap<string, ArrayList<Handler>> namespaceRegistrants = new HashMap<string, ArrayList<Handler>>();
public async Iq.Stanza send_iq_async(XmppStream stream, Iq.Stanza iq) {
+ assert(iq.type_ == Iq.Stanza.TYPE_GET || iq.type_ == Iq.Stanza.TYPE_SET);
+
Iq.Stanza? return_stanza = null;
send_iq(stream, iq, (_, result_iq) => {
return_stanza = result_iq;
@@ -21,6 +26,7 @@ namespace Xmpp.Iq {
public delegate void OnResult(XmppStream stream, Iq.Stanza iq);
public void send_iq(XmppStream stream, Iq.Stanza iq, owned OnResult? listener = null) {
+ preprocess_outgoing_iq_set_get(stream, iq);
stream.write(iq.stanza);
if (listener != null) {
responseListeners[iq.id] = new ResponseListener((owned) listener);
@@ -68,6 +74,7 @@ namespace Xmpp.Iq {
} else {
Gee.List<StanzaNode> children = node.get_all_subnodes();
if (children.size == 1 && namespaceRegistrants.has_key(children[0].ns_uri)) {
+ preprocess_incoming_iq_set_get(stream, iq);
Gee.List<Handler> handlers = namespaceRegistrants[children[0].ns_uri];
foreach (Handler handler in handlers) {
if (iq.type_ == Iq.Stanza.TYPE_GET) {
diff --git a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala
index fdee2411..c184877c 100644
--- a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala
+++ b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala
@@ -18,21 +18,34 @@ public class Proxy : Object {
}
}
+public delegate Gee.List<string> GetLocalIpAddresses();
+
public class Module : XmppStreamModule, Iq.Handler {
public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0065_socks5_bytestreams");
+ private GetLocalIpAddresses? get_local_ip_addresses_impl = null;
+
public override void attach(XmppStream stream) {
stream.add_flag(new Flag());
query_availability.begin(stream);
}
public override void detach(XmppStream stream) { }
- public async void on_iq_set(XmppStream stream, Iq.Stanza iq) { }
-
public Gee.List<Proxy> get_proxies(XmppStream stream) {
return stream.get_flag(Flag.IDENTITY).proxies;
}
+ public void set_local_ip_address_handler(owned GetLocalIpAddresses get_local_ip_addresses) {
+ get_local_ip_addresses_impl = (owned)get_local_ip_addresses;
+ }
+
+ public Gee.List<string> get_local_ip_addresses() {
+ if (get_local_ip_addresses_impl == null) {
+ return Gee.List.empty();
+ }
+ return get_local_ip_addresses_impl();
+ }
+
private async void query_availability(XmppStream stream) {
ServiceDiscovery.ItemsResult? items_result = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).request_items(stream, stream.remote_name);
if (items_result == null) return;
diff --git a/xmpp-vala/src/module/xep/0166_jingle.vala b/xmpp-vala/src/module/xep/0166_jingle.vala
deleted file mode 100644
index 3a634222..00000000
--- a/xmpp-vala/src/module/xep/0166_jingle.vala
+++ /dev/null
@@ -1,1061 +0,0 @@
-using Gee;
-using Xmpp.Xep;
-using Xmpp;
-
-namespace Xmpp.Xep.Jingle {
-
-private const string NS_URI = "urn:xmpp:jingle:1";
-private const string ERROR_NS_URI = "urn:xmpp:jingle:errors:1";
-
-public errordomain IqError {
- BAD_REQUEST,
- NOT_ACCEPTABLE,
- NOT_IMPLEMENTED,
- UNSUPPORTED_INFO,
- OUT_OF_ORDER,
- RESOURCE_CONSTRAINT,
-}
-
-void send_iq_error(IqError iq_error, XmppStream stream, Iq.Stanza iq) {
- ErrorStanza error;
- if (iq_error is IqError.BAD_REQUEST) {
- error = new ErrorStanza.bad_request(iq_error.message);
- } else if (iq_error is IqError.NOT_ACCEPTABLE) {
- error = new ErrorStanza.not_acceptable(iq_error.message);
- } else if (iq_error is IqError.NOT_IMPLEMENTED) {
- error = new ErrorStanza.feature_not_implemented(iq_error.message);
- } else if (iq_error is IqError.UNSUPPORTED_INFO) {
- StanzaNode unsupported_info = new StanzaNode.build("unsupported-info", ERROR_NS_URI).add_self_xmlns();
- error = new ErrorStanza.build(ErrorStanza.TYPE_CANCEL, ErrorStanza.CONDITION_FEATURE_NOT_IMPLEMENTED, iq_error.message, unsupported_info);
- } else if (iq_error is IqError.OUT_OF_ORDER) {
- StanzaNode out_of_order = new StanzaNode.build("out-of-order", ERROR_NS_URI).add_self_xmlns();
- error = new ErrorStanza.build(ErrorStanza.TYPE_MODIFY, ErrorStanza.CONDITION_UNEXPECTED_REQUEST, iq_error.message, out_of_order);
- } else if (iq_error is IqError.RESOURCE_CONSTRAINT) {
- error = new ErrorStanza.resource_constraint(iq_error.message);
- } else {
- assert_not_reached();
- }
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, error) { to=iq.from });
-}
-
-public errordomain Error {
- GENERAL,
- BAD_REQUEST,
- INVALID_PARAMETERS,
- UNSUPPORTED_TRANSPORT,
- UNSUPPORTED_SECURITY,
- NO_SHARED_PROTOCOLS,
- TRANSPORT_ERROR,
-}
-
-StanzaNode? get_single_node_anyns(StanzaNode parent, string? node_name = null) throws IqError {
- StanzaNode? result = null;
- foreach (StanzaNode child in parent.get_all_subnodes()) {
- if (node_name == null || child.name == node_name) {
- if (result != null) {
- if (node_name != null) {
- throw new IqError.BAD_REQUEST(@"multiple $(node_name) nodes");
- } else {
- throw new IqError.BAD_REQUEST(@"expected single subnode");
- }
- }
- result = child;
- }
- }
- return result;
-}
-
-class ContentNode {
- public Role creator;
- public string name;
- public StanzaNode? description;
- public StanzaNode? transport;
- public StanzaNode? security;
-}
-
-ContentNode get_single_content_node(StanzaNode jingle) throws IqError {
- Gee.List<StanzaNode> contents = jingle.get_subnodes("content");
- if (contents.size == 0) {
- throw new IqError.BAD_REQUEST("missing content node");
- }
- if (contents.size > 1) {
- throw new IqError.NOT_IMPLEMENTED("can't process multiple content nodes");
- }
- StanzaNode content = contents[0];
- string? creator_str = content.get_attribute("creator");
- // Vala can't typecheck the ternary operator here.
- Role? creator = null;
- if (creator_str != null) {
- creator = Role.parse(creator_str);
- } else {
- // TODO(hrxi): now, is the creator attribute optional or not (XEP-0166
- // Jingle)?
- creator = Role.INITIATOR;
- }
-
- string? name = content.get_attribute("name");
- StanzaNode? description = get_single_node_anyns(content, "description");
- StanzaNode? transport = get_single_node_anyns(content, "transport");
- StanzaNode? security = get_single_node_anyns(content, "security");
- if (name == null || creator == null) {
- throw new IqError.BAD_REQUEST("missing name or creator");
- }
-
- return new ContentNode() {
- creator=creator,
- name=name,
- description=description,
- transport=transport,
- security=security
- };
-}
-
-// This module can only be attached to one stream at a time.
-public class Module : XmppStreamModule, Iq.Handler {
- public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0166_jingle");
-
- private HashMap<string, ContentType> content_types = new HashMap<string, ContentType>();
- private HashMap<string, Transport> transports = new HashMap<string, Transport>();
- private HashMap<string, SecurityPrecondition> security_preconditions = new HashMap<string, SecurityPrecondition>();
-
- private XmppStream? current_stream = null;
-
- public override void attach(XmppStream stream) {
- stream.add_flag(new Flag());
- stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
- stream.get_module(Iq.Module.IDENTITY).register_for_namespace(NS_URI, this);
- current_stream = stream;
- }
- public override void detach(XmppStream stream) {
- stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
- stream.get_module(Iq.Module.IDENTITY).unregister_from_namespace(NS_URI, this);
- }
-
- public void register_content_type(ContentType content_type) {
- content_types[content_type.content_type_ns_uri()] = content_type;
- }
- public ContentType? get_content_type(string ns_uri) {
- if (!content_types.has_key(ns_uri)) {
- return null;
- }
- return content_types[ns_uri];
- }
- public void register_transport(Transport transport) {
- transports[transport.transport_ns_uri()] = transport;
- }
- public Transport? get_transport(string ns_uri) {
- if (!transports.has_key(ns_uri)) {
- return null;
- }
- return transports[ns_uri];
- }
- public async Transport? select_transport(XmppStream stream, TransportType type, Jid receiver_full_jid, Set<string> blacklist) {
- Transport? result = null;
- foreach (Transport transport in transports.values) {
- if (transport.transport_type() != type) {
- continue;
- }
- if (transport.transport_ns_uri() in blacklist) {
- continue;
- }
- if (yield transport.is_transport_available(stream, receiver_full_jid)) {
- if (result != null) {
- if (result.transport_priority() >= transport.transport_priority()) {
- continue;
- }
- }
- result = transport;
- }
- }
- return result;
- }
- public void register_security_precondition(SecurityPrecondition precondition) {
- security_preconditions[precondition.security_ns_uri()] = precondition;
- }
- public SecurityPrecondition? get_security_precondition(string? ns_uri) {
- if (ns_uri == null) return null;
- if (!security_preconditions.has_key(ns_uri)) {
- return null;
- }
- return security_preconditions[ns_uri];
- }
-
- private async bool is_jingle_available(XmppStream stream, Jid full_jid) {
- bool? has_jingle = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
- return has_jingle != null && has_jingle;
- }
-
- public async bool is_available(XmppStream stream, TransportType type, Jid full_jid) {
- return (yield is_jingle_available(stream, full_jid)) && (yield select_transport(stream, type, full_jid, Set.empty())) != null;
- }
-
- public async Session create_session(XmppStream stream, TransportType type, Jid receiver_full_jid, Senders senders, string content_name, StanzaNode description, string? precondition_name = null, Object? precondation_options = null) throws Error {
- if (!yield is_jingle_available(stream, receiver_full_jid)) {
- throw new Error.NO_SHARED_PROTOCOLS("No Jingle support");
- }
- Transport? transport = yield select_transport(stream, type, receiver_full_jid, Set.empty());
- if (transport == null) {
- throw new Error.NO_SHARED_PROTOCOLS("No suitable transports");
- }
- SecurityPrecondition? precondition = get_security_precondition(precondition_name);
- if (precondition_name != null && precondition == null) {
- throw new Error.UNSUPPORTED_SECURITY("No suitable security precondiiton found");
- }
- Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
- if (my_jid == null) {
- throw new Error.GENERAL("Couldn't determine own JID");
- }
- TransportParameters transport_params = transport.create_transport_parameters(stream, my_jid, receiver_full_jid);
- SecurityParameters? security_params = precondition != null ? precondition.create_security_parameters(stream, my_jid, receiver_full_jid, precondation_options) : null;
- Session session = new Session.initiate_sent(random_uuid(), type, transport_params, security_params, my_jid, receiver_full_jid, content_name, send_terminate_and_remove_session);
- StanzaNode content = new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_attribute("senders", senders.to_string())
- .put_node(description)
- .put_node(transport_params.to_transport_stanza_node());
- if (security_params != null) {
- content.put_node(security_params.to_security_stanza_node(stream, my_jid, receiver_full_jid));
- }
- StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "session-initiate")
- .put_attribute("initiator", my_jid.to_string())
- .put_attribute("sid", session.sid)
- .put_node(content);
- Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=receiver_full_jid };
-
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => {
- // TODO(hrxi): handle errors
- stream.get_flag(Flag.IDENTITY).add_session(session);
- });
-
- return session;
- }
-
- public void handle_session_initiate(XmppStream stream, string sid, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- ContentNode content = get_single_content_node(jingle);
- if (content.description == null || content.transport == null) {
- throw new IqError.BAD_REQUEST("missing description or transport node");
- }
- Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
- if (my_jid == null) {
- throw new IqError.RESOURCE_CONSTRAINT("Couldn't determine own JID");
- }
- Transport? transport = get_transport(content.transport.ns_uri);
- TransportParameters? transport_params = null;
- if (transport != null) {
- transport_params = transport.parse_transport_parameters(stream, my_jid, iq.from, content.transport);
- } else {
- // terminate the session below
- }
-
- ContentType? content_type = get_content_type(content.description.ns_uri);
- if (content_type == null) {
- // TODO(hrxi): how do we signal an unknown content type?
- throw new IqError.NOT_IMPLEMENTED("unknown content type");
- }
- ContentParameters content_params = content_type.parse_content_parameters(content.description);
-
- SecurityPrecondition? precondition = content.security != null ? get_security_precondition(content.security.ns_uri) : null;
- SecurityParameters? security_params = null;
- if (precondition != null) {
- debug("Using precondition %s", precondition.security_ns_uri());
- security_params = precondition.parse_security_parameters(stream, my_jid, iq.from, content.security);
- } else if (content.security != null) {
- throw new IqError.NOT_IMPLEMENTED("unknown security precondition");
- }
-
- TransportType type = content_type.content_type_transport_type();
- Session session = new Session.initiate_received(sid, type, transport_params, security_params, my_jid, iq.from, content.name, send_terminate_and_remove_session);
- stream.get_flag(Flag.IDENTITY).add_session(session);
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
-
- if (transport == null || transport.transport_type() != type) {
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("unsupported-transports", NS_URI));
- session.terminate(reason, "unsupported transports");
- return;
- }
-
- content_params.on_session_initiate(stream, session);
- }
-
- private void send_terminate_and_remove_session(Jid to, string sid, StanzaNode reason) {
- StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "session-terminate")
- .put_attribute("sid", sid)
- .put_node(reason);
- Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=to };
- current_stream.get_module(Iq.Module.IDENTITY).send_iq(current_stream, iq);
-
- // Immediately remove the session from the open sessions as per the
- // XEP, don't wait for confirmation.
- current_stream.get_flag(Flag.IDENTITY).remove_session(sid);
- }
-
- public async void on_iq_set(XmppStream stream, Iq.Stanza iq) {
- try {
- handle_iq_set(stream, iq);
- } catch (IqError e) {
- send_iq_error(e, stream, iq);
- }
- }
-
- public void handle_iq_set(XmppStream stream, Iq.Stanza iq) throws IqError {
- StanzaNode? jingle = iq.stanza.get_subnode("jingle", NS_URI);
- string? sid = jingle != null ? jingle.get_attribute("sid") : null;
- string? action = jingle != null ? jingle.get_attribute("action") : null;
- if (jingle == null || sid == null || action == null) {
- throw new IqError.BAD_REQUEST("missing jingle node, sid or action");
- }
- Session? session = stream.get_flag(Flag.IDENTITY).get_session(sid);
- if (action == "session-initiate") {
- if (session != null) {
- // TODO(hrxi): Info leak if other clients use predictable session IDs?
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.build(ErrorStanza.TYPE_MODIFY, ErrorStanza.CONDITION_CONFLICT, "session ID already in use", null)) { to=iq.from });
- return;
- }
- handle_session_initiate(stream, sid, jingle, iq);
- return;
- }
- if (session == null) {
- StanzaNode unknown_session = new StanzaNode.build("unknown-session", ERROR_NS_URI).add_self_xmlns();
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.item_not_found(unknown_session)) { to=iq.from });
- return;
- }
- session.handle_iq_set(stream, action, jingle, iq);
- }
-
- public override string get_ns() { return NS_URI; }
- public override string get_id() { return IDENTITY.id; }
-}
-
-public enum TransportType {
- DATAGRAM,
- STREAMING,
-}
-
-public enum Senders {
- BOTH,
- INITIATOR,
- NONE,
- RESPONDER;
-
- public string to_string() {
- switch (this) {
- case BOTH: return "both";
- case INITIATOR: return "initiator";
- case NONE: return "none";
- case RESPONDER: return "responder";
- }
- assert_not_reached();
- }
-}
-
-public delegate void SessionTerminate(Jid to, string sid, StanzaNode reason);
-
-public interface Transport : Object {
- public abstract string transport_ns_uri();
- public async abstract bool is_transport_available(XmppStream stream, Jid full_jid);
- public abstract TransportType transport_type();
- public abstract int transport_priority();
- public abstract TransportParameters create_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid) throws Error;
- public abstract TransportParameters parse_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws IqError;
-}
-
-
-// Gets a null `stream` if connection setup was unsuccessful and another
-// transport method should be tried.
-public interface TransportParameters : Object {
- public abstract string transport_ns_uri();
- public abstract StanzaNode to_transport_stanza_node();
- public abstract void on_transport_accept(StanzaNode transport) throws IqError;
- public abstract void on_transport_info(StanzaNode transport) throws IqError;
- public abstract void create_transport_connection(XmppStream stream, Session session);
-}
-
-public enum Role {
- INITIATOR,
- RESPONDER;
-
- public string to_string() {
- switch (this) {
- case INITIATOR: return "initiator";
- case RESPONDER: return "responder";
- }
- assert_not_reached();
- }
-
- public static Role parse(string role) throws IqError {
- switch (role) {
- case "initiator": return INITIATOR;
- case "responder": return RESPONDER;
- }
- throw new IqError.BAD_REQUEST(@"invalid role $(role)");
- }
-}
-
-public interface ContentType : Object {
- public abstract string content_type_ns_uri();
- public abstract TransportType content_type_transport_type();
- public abstract ContentParameters parse_content_parameters(StanzaNode description) throws IqError;
- public abstract void handle_content_session_info(XmppStream stream, Session session, StanzaNode info, Iq.Stanza iq) throws IqError;
-}
-
-public interface ContentParameters : Object {
- public abstract void on_session_initiate(XmppStream stream, Session session);
-}
-
-public interface SecurityPrecondition : Object {
- public abstract string security_ns_uri();
- public abstract SecurityParameters? create_security_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, Object options) throws Jingle.Error;
- public abstract SecurityParameters? parse_security_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode security) throws IqError;
-}
-
-public interface SecurityParameters : Object {
- public abstract string security_ns_uri();
- public abstract StanzaNode to_security_stanza_node(XmppStream stream, Jid local_full_jid, Jid peer_full_jid);
- public abstract IOStream wrap_stream(IOStream stream);
-}
-
-public class Session {
- // INITIATE_SENT -> CONNECTING -> [REPLACING_TRANSPORT -> CONNECTING ->]... ACTIVE -> ENDED
- // INITIATE_RECEIVED -> CONNECTING -> [WAITING_FOR_TRANSPORT_REPLACE -> CONNECTING ->].. ACTIVE -> ENDED
- public enum State {
- INITIATE_SENT,
- REPLACING_TRANSPORT,
- INITIATE_RECEIVED,
- WAITING_FOR_TRANSPORT_REPLACE,
- CONNECTING,
- ACTIVE,
- ENDED,
- }
-
- public State state { get; private set; }
-
- public Role role { get; private set; }
- public string sid { get; private set; }
- public TransportType type_ { get; private set; }
- public Jid local_full_jid { get; private set; }
- public Jid peer_full_jid { get; private set; }
- public Role content_creator { get; private set; }
- public string content_name { get; private set; }
- public SecurityParameters? security { get; private set; }
-
- private Connection connection;
- public IOStream conn { get { return connection; } }
-
- public bool terminate_on_connection_close { get; set; }
-
- // INITIATE_SENT | INITIATE_RECEIVED | CONNECTING
- Set<string> tried_transport_methods = new HashSet<string>();
- TransportParameters? transport = null;
-
- SessionTerminate session_terminate_handler;
-
- public Session.initiate_sent(string sid, TransportType type, TransportParameters transport, SecurityParameters? security, Jid local_full_jid, Jid peer_full_jid, string content_name, owned SessionTerminate session_terminate_handler) {
- this.state = State.INITIATE_SENT;
- this.role = Role.INITIATOR;
- this.sid = sid;
- this.type_ = type;
- this.local_full_jid = local_full_jid;
- this.peer_full_jid = peer_full_jid;
- this.content_creator = Role.INITIATOR;
- this.content_name = content_name;
- this.tried_transport_methods = new HashSet<string>();
- this.tried_transport_methods.add(transport.transport_ns_uri());
- this.transport = transport;
- this.security = security;
- this.connection = new Connection(this);
- this.session_terminate_handler = (owned)session_terminate_handler;
- this.terminate_on_connection_close = true;
- }
-
- public Session.initiate_received(string sid, TransportType type, TransportParameters? transport, SecurityParameters? security, Jid local_full_jid, Jid peer_full_jid, string content_name, owned SessionTerminate session_terminate_handler) {
- this.state = State.INITIATE_RECEIVED;
- this.role = Role.RESPONDER;
- this.sid = sid;
- this.type_ = type;
- this.local_full_jid = local_full_jid;
- this.peer_full_jid = peer_full_jid;
- this.content_creator = Role.INITIATOR;
- this.content_name = content_name;
- this.transport = transport;
- this.security = security;
- this.tried_transport_methods = new HashSet<string>();
- if (transport != null) {
- this.tried_transport_methods.add(transport.transport_ns_uri());
- }
- this.connection = new Connection(this);
- this.session_terminate_handler = (owned)session_terminate_handler;
- this.terminate_on_connection_close = true;
- }
-
- public void handle_iq_set(XmppStream stream, string action, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- // Validate action.
- switch (action) {
- case "session-accept":
- case "session-info":
- case "session-terminate":
- case "transport-accept":
- case "transport-info":
- case "transport-reject":
- case "transport-replace":
- break;
- case "content-accept":
- case "content-add":
- case "content-modify":
- case "content-reject":
- case "content-remove":
- case "description-info":
- case "security-info":
- throw new IqError.NOT_IMPLEMENTED(@"$(action) is not implemented");
- default:
- throw new IqError.BAD_REQUEST("invalid action");
- }
- ContentNode? content = null;
- StanzaNode? transport = null;
- // Do some pre-processing.
- if (action != "session-info" && action != "session-terminate") {
- content = get_single_content_node(jingle);
- verify_content(content);
- switch (action) {
- case "transport-accept":
- case "transport-reject":
- case "transport-replace":
- case "transport-info":
- switch (state) {
- case State.INITIATE_SENT:
- case State.REPLACING_TRANSPORT:
- case State.INITIATE_RECEIVED:
- case State.WAITING_FOR_TRANSPORT_REPLACE:
- case State.CONNECTING:
- break;
- default:
- throw new IqError.OUT_OF_ORDER("transport-* unsupported after connection setup");
- }
- // TODO(hrxi): What to do with description nodes?
- if (content.transport == null) {
- throw new IqError.BAD_REQUEST("missing transport node");
- }
- transport = content.transport;
- break;
- }
- }
- switch (action) {
- case "session-accept":
- if (state != State.INITIATE_SENT) {
- throw new IqError.OUT_OF_ORDER("got session-accept while not waiting for one");
- }
- handle_session_accept(stream, content, jingle, iq);
- break;
- case "session-info":
- handle_session_info(stream, jingle, iq);
- break;
- case "session-terminate":
- handle_session_terminate(stream, jingle, iq);
- break;
- case "transport-accept":
- handle_transport_accept(stream, transport, jingle, iq);
- break;
- case "transport-reject":
- handle_transport_reject(stream, jingle, iq);
- break;
- case "transport-replace":
- handle_transport_replace(stream, transport, jingle, iq);
- break;
- case "transport-info":
- handle_transport_info(stream, transport, jingle, iq);
- break;
- }
- }
- void handle_session_accept(XmppStream stream, ContentNode content, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- string? responder_str = jingle.get_attribute("responder");
- Jid responder = iq.from;
- if (responder_str != null) {
- try {
- responder = new Jid(responder_str);
- } catch (InvalidJidError e) {
- warning("Received invalid session accept: %s", e.message);
- }
- }
- // TODO(hrxi): more sanity checking, perhaps replace who we're talking to
- if (!responder.is_full()) {
- throw new IqError.BAD_REQUEST("invalid responder JID");
- }
- if (content.description == null || content.transport == null) {
- throw new IqError.BAD_REQUEST("missing description or transport node");
- }
- if (content.transport.ns_uri != transport.transport_ns_uri()) {
- throw new IqError.BAD_REQUEST("session-accept with unnegotiated transport method");
- }
- transport.on_transport_accept(content.transport);
- // TODO(hrxi): handle content.description :)
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
-
- state = State.CONNECTING;
- transport.create_transport_connection(stream, this);
- }
- void connection_created(XmppStream stream, IOStream? conn) {
- if (state != State.CONNECTING) {
- return;
- }
- if (conn != null) {
- state = State.ACTIVE;
- tried_transport_methods.clear();
- if (security != null) {
- connection.set_inner(security.wrap_stream(conn));
- } else {
- connection.set_inner(conn);
- }
- transport = null;
- } else {
- if (role == Role.INITIATOR) {
- select_new_transport.begin(stream);
- } else {
- state = State.WAITING_FOR_TRANSPORT_REPLACE;
- }
- }
- }
- void handle_session_terminate(XmppStream stream, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- connection.on_terminated_by_jingle("remote terminated jingle session");
- state = State.ENDED;
- stream.get_flag(Flag.IDENTITY).remove_session(sid);
-
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- // TODO(hrxi): also handle presence type=unavailable
- }
- void handle_session_info(XmppStream stream, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- StanzaNode? info = get_single_node_anyns(jingle);
- if (info == null) {
- // Jingle session ping
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- return;
- }
- ContentType? content_type = stream.get_module(Module.IDENTITY).get_content_type(info.ns_uri);
- if (content_type == null) {
- throw new IqError.UNSUPPORTED_INFO("unknown session-info namespace");
- }
- content_type.handle_content_session_info(stream, this, info, iq);
- }
- async void select_new_transport(XmppStream stream) {
- Transport? new_transport = yield stream.get_module(Module.IDENTITY).select_transport(stream, type_, peer_full_jid, tried_transport_methods);
- if (new_transport == null) {
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("failed-transport", NS_URI));
- terminate(reason, "failed transport");
- return;
- }
- tried_transport_methods.add(new_transport.transport_ns_uri());
- transport = new_transport.create_transport_parameters(stream, local_full_jid, peer_full_jid);
- StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "transport-replace")
- .put_attribute("sid", sid)
- .put_node(new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_node(transport.to_transport_stanza_node())
- );
- Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
- state = State.REPLACING_TRANSPORT;
- }
- void handle_transport_accept(XmppStream stream, StanzaNode transport_node, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- if (state != State.REPLACING_TRANSPORT) {
- throw new IqError.OUT_OF_ORDER("no outstanding transport-replace request");
- }
- if (transport_node.ns_uri != transport.transport_ns_uri()) {
- throw new IqError.BAD_REQUEST("transport-accept with unnegotiated transport method");
- }
- transport.on_transport_accept(transport_node);
- state = State.CONNECTING;
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- transport.create_transport_connection(stream, this);
- }
- void handle_transport_reject(XmppStream stream, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- if (state != State.REPLACING_TRANSPORT) {
- throw new IqError.OUT_OF_ORDER("no outstanding transport-replace request");
- }
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- select_new_transport.begin(stream);
- }
- void handle_transport_replace(XmppStream stream, StanzaNode transport_node, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- Transport? transport = stream.get_module(Module.IDENTITY).get_transport(transport_node.ns_uri);
- TransportParameters? parameters = null;
- if (transport != null) {
- // Just parse the transport info for the errors.
- parameters = transport.parse_transport_parameters(stream, local_full_jid, peer_full_jid, transport_node);
- }
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- if (state != State.WAITING_FOR_TRANSPORT_REPLACE || transport == null) {
- StanzaNode jingle_response = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "transport-reject")
- .put_attribute("sid", sid)
- .put_node(new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_node(transport_node)
- );
- Iq.Stanza iq_response = new Iq.Stanza.set(jingle_response) { to=peer_full_jid };
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq_response);
- return;
- }
- this.transport = parameters;
- StanzaNode jingle_response = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "transport-accept")
- .put_attribute("sid", sid)
- .put_node(new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_node(this.transport.to_transport_stanza_node())
- );
- Iq.Stanza iq_response = new Iq.Stanza.set(jingle_response) { to=peer_full_jid };
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq_response);
-
- state = State.CONNECTING;
- this.transport.create_transport_connection(stream, this);
- }
- void handle_transport_info(XmppStream stream, StanzaNode transport, StanzaNode jingle, Iq.Stanza iq) throws IqError {
- this.transport.on_transport_info(transport);
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- }
- void verify_content(ContentNode content) throws IqError {
- if (content.name != content_name || content.creator != content_creator) {
- throw new IqError.BAD_REQUEST("unknown content");
- }
- }
- public void set_transport_connection(XmppStream stream, IOStream? conn) {
- if (state != State.CONNECTING) {
- return;
- }
- connection_created(stream, conn);
- }
- public void send_transport_info(XmppStream stream, StanzaNode transport) {
- if (state != State.CONNECTING) {
- return;
- }
- StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "transport-info")
- .put_attribute("sid", sid)
- .put_node(new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_node(transport)
- );
- Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
- }
- public void accept(XmppStream stream, StanzaNode description) {
- if (state != State.INITIATE_RECEIVED) {
- return; // TODO(hrxi): what to do?
- }
- StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
- .add_self_xmlns()
- .put_attribute("action", "session-accept")
- .put_attribute("sid", sid)
- .put_node(new StanzaNode.build("content", NS_URI)
- .put_attribute("creator", "initiator")
- .put_attribute("name", content_name)
- .put_node(description)
- .put_node(transport.to_transport_stanza_node())
- );
- Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
-
- state = State.CONNECTING;
- transport.create_transport_connection(stream, this);
- }
-
- public void reject(XmppStream stream) {
- if (state != State.INITIATE_RECEIVED) {
- return; // TODO(hrxi): what to do?
- }
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("decline", NS_URI));
- terminate(reason, "declined");
- }
-
- public void set_application_error(XmppStream stream, StanzaNode? application_reason = null) {
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("failed-application", NS_URI));
- if (application_reason != null) {
- reason.put_node(application_reason);
- }
- terminate(reason, "application error");
- }
-
- public void on_connection_error(IOError error) {
- // TODO(hrxi): where can we get an XmppStream from?
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("failed-transport", NS_URI))
- .put_node(new StanzaNode.build("text", NS_URI)
- .put_node(new StanzaNode.text(error.message))
- );
- terminate(reason, @"transport error: $(error.message)");
- }
- public void on_connection_close() {
- if (terminate_on_connection_close) {
- StanzaNode reason = new StanzaNode.build("reason", NS_URI)
- .put_node(new StanzaNode.build("success", NS_URI));
- terminate(reason, "success");
- }
- }
-
- public void terminate(StanzaNode reason, string? local_reason) {
- if (state == State.ENDED) {
- return;
- }
- if (state == State.ACTIVE) {
- if (local_reason != null) {
- connection.on_terminated_by_jingle(@"local session-terminate: $(local_reason)");
- } else {
- connection.on_terminated_by_jingle("local session-terminate");
- }
- }
-
- session_terminate_handler(peer_full_jid, sid, reason);
- state = State.ENDED;
- }
-}
-
-public class Connection : IOStream {
- public class Input : InputStream {
- private weak Connection connection;
- public Input(Connection connection) {
- this.connection = connection;
- }
- public override ssize_t read(uint8[] buffer, Cancellable? cancellable = null) throws IOError {
- throw new IOError.NOT_SUPPORTED("can't do non-async reads on jingle connections");
- }
- public override async ssize_t read_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- return yield connection.read_async(buffer, io_priority, cancellable);
- }
- public override bool close(Cancellable? cancellable = null) throws IOError {
- return connection.close_read(cancellable);
- }
- public override async bool close_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- return yield connection.close_read_async(io_priority, cancellable);
- }
- }
- public class Output : OutputStream {
- private weak Connection connection;
- public Output(Connection connection) {
- this.connection = connection;
- }
- public override ssize_t write(uint8[] buffer, Cancellable? cancellable = null) throws IOError {
- throw new IOError.NOT_SUPPORTED("can't do non-async writes on jingle connections");
- }
- public override async ssize_t write_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- return yield connection.write_async(buffer, io_priority, cancellable);
- }
- public override bool close(Cancellable? cancellable = null) throws IOError {
- return connection.close_write(cancellable);
- }
- public override async bool close_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- return yield connection.close_write_async(io_priority, cancellable);
- }
- }
-
- private Input input;
- private Output output;
- public override InputStream input_stream { get { return input; } }
- public override OutputStream output_stream { get { return output; } }
-
- private weak Session session;
- private IOStream? inner = null;
- private string? error = null;
-
- private bool read_closed = false;
- private bool write_closed = false;
-
- private class OnSetInnerCallback {
- public SourceFunc callback;
- public int io_priority;
- }
-
- Gee.List<OnSetInnerCallback> callbacks = new ArrayList<OnSetInnerCallback>();
-
- public Connection(Session session) {
- this.input = new Input(this);
- this.output = new Output(this);
- this.session = session;
- }
-
- public void set_inner(IOStream inner) {
- assert(this.inner == null);
- this.inner = inner;
- foreach (OnSetInnerCallback c in callbacks) {
- Idle.add((owned) c.callback, c.io_priority);
- }
- callbacks = null;
- }
-
- public void on_terminated_by_jingle(string reason) {
- if (error == null) {
- close_async.begin();
- error = reason;
- }
- }
-
- private void check_for_errors() throws IOError {
- if (error != null) {
- throw new IOError.CLOSED(error);
- }
- }
- private async void wait_and_check_for_errors(int io_priority, Cancellable? cancellable = null) throws IOError {
- while (true) {
- check_for_errors();
- if (inner != null) {
- return;
- }
- SourceFunc callback = wait_and_check_for_errors.callback;
- ulong id = 0;
- if (cancellable != null) {
- id = cancellable.connect(() => callback());
- }
- callbacks.add(new OnSetInnerCallback() { callback=(owned)callback, io_priority=io_priority});
- yield;
- if (cancellable != null) {
- cancellable.disconnect(id);
- }
- }
- }
- private void handle_connection_error(IOError error) {
- Session? strong = session;
- if (strong != null) {
- strong.on_connection_error(error);
- }
- }
- private void handle_connection_close() {
- Session? strong = session;
- if (strong != null) {
- strong.on_connection_close();
- }
- }
-
- public async ssize_t read_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- yield wait_and_check_for_errors(io_priority, cancellable);
- try {
- return yield inner.input_stream.read_async(buffer, io_priority, cancellable);
- } catch (IOError e) {
- handle_connection_error(e);
- throw e;
- }
- }
- public async ssize_t write_async(uint8[]? buffer, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- yield wait_and_check_for_errors(io_priority, cancellable);
- try {
- return yield inner.output_stream.write_async(buffer, io_priority, cancellable);
- } catch (IOError e) {
- handle_connection_error(e);
- throw e;
- }
- }
- public bool close_read(Cancellable? cancellable = null) throws IOError {
- check_for_errors();
- if (read_closed) {
- return true;
- }
- close_read_async.begin(GLib.Priority.DEFAULT, cancellable);
- return true;
- }
- public async bool close_read_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- debug("Closing Jingle input stream");
- yield wait_and_check_for_errors(io_priority, cancellable);
- if (read_closed) {
- return true;
- }
- read_closed = true;
- IOError error = null;
- bool result = true;
- try {
- result = yield inner.input_stream.close_async(io_priority, cancellable);
- } catch (IOError e) {
- if (error == null) {
- error = e;
- }
- }
- try {
- result = (yield close_if_both_closed(io_priority, cancellable)) && result;
- } catch (IOError e) {
- if (error == null) {
- error = e;
- }
- }
- if (error != null) {
- handle_connection_error(error);
- throw error;
- }
- return result;
- }
- public bool close_write(Cancellable? cancellable = null) throws IOError {
- check_for_errors();
- if (write_closed) {
- return true;
- }
- close_write_async.begin(GLib.Priority.DEFAULT, cancellable);
- return true;
- }
- public async bool close_write_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
- yield wait_and_check_for_errors(io_priority, cancellable);
- if (write_closed) {
- return true;
- }
- write_closed = true;
- IOError error = null;
- bool result = true;
- try {
- result = yield inner.output_stream.close_async(io_priority, cancellable);
- } catch (IOError e) {
- if (error == null) {
- error = e;
- }
- }
- try {
- result = (yield close_if_both_closed(io_priority, cancellable)) && result;
- } catch (IOError e) {
- if (error == null) {
- error = e;
- }
- }
- if (error != null) {
- handle_connection_error(error);
- throw error;
- }
- return result;
- }
- private async bool close_if_both_closed(int io_priority, Cancellable? cancellable = null) throws IOError {
- if (read_closed && write_closed) {
- handle_connection_close();
- //return yield inner.close_async(io_priority, cancellable);
- }
- return true;
- }
-}
-
-public class Flag : XmppStreamFlag {
- public static FlagIdentity<Flag> IDENTITY = new FlagIdentity<Flag>(NS_URI, "jingle");
-
- private HashMap<string, Session> sessions = new HashMap<string, Session>();
-
- public void add_session(Session session) {
- sessions[session.sid] = session;
- }
- public Session? get_session(string sid) {
- return sessions.has_key(sid) ? sessions[sid] : null;
- }
- public void remove_session(string sid) {
- sessions.unset(sid);
- }
-
- public override string get_ns() { return NS_URI; }
- public override string get_id() { return IDENTITY.id; }
-}
-
-}
diff --git a/xmpp-vala/src/module/xep/0166_jingle/component.vala b/xmpp-vala/src/module/xep/0166_jingle/component.vala
new file mode 100644
index 00000000..5d573522
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/component.vala
@@ -0,0 +1,62 @@
+namespace Xmpp.Xep.Jingle {
+
+ public abstract class ComponentConnection : Object {
+ public uint8 component_id { get; set; default = 0; }
+ public abstract async void terminate(bool we_terminated, string? reason_name = null, string? reason_text = null);
+ public signal void connection_closed();
+ public signal void connection_error(IOError e);
+ }
+
+ public abstract class DatagramConnection : ComponentConnection {
+ public bool ready { get; set; default = false; }
+ private string? terminate_reason_name = null;
+ private string? terminate_reason_text = null;
+ private bool terminated = false;
+
+ public override async void terminate(bool we_terminated, string? reason_string = null, string? reason_text = null) {
+ if (!terminated) {
+ terminated = true;
+ terminate_reason_name = reason_string;
+ terminate_reason_text = reason_text;
+ connection_closed();
+ }
+ }
+
+ public signal void datagram_received(Bytes datagram);
+ public abstract void send_datagram(Bytes datagram);
+ }
+
+ public class StreamingConnection : ComponentConnection {
+ public Gee.Future<IOStream> stream { get { return promise.future; } }
+ protected Gee.Promise<IOStream> promise = new Gee.Promise<IOStream>();
+ private string? terminated = null;
+
+ public async void set_stream(IOStream? stream) {
+ if (stream == null) {
+ promise.set_exception(new IOError.FAILED("Jingle connection failed"));
+ return;
+ }
+ assert(!this.stream.ready);
+ promise.set_value(stream);
+ if (terminated != null) {
+ yield stream.close_async();
+ }
+ }
+
+ public void set_error(GLib.Error? e) {
+ promise.set_exception(e);
+ }
+
+ public override async void terminate(bool we_terminated, string? reason_name = null, string? reason_text = null) {
+ if (terminated == null) {
+ terminated = (reason_name ?? "") + " - " + (reason_text ?? "") + @"we terminated? $we_terminated";
+ if (stream.ready) {
+ yield stream.value.close_async();
+ } else {
+ promise.set_exception(new IOError.FAILED("Jingle connection failed"));
+ }
+ }
+ }
+ }
+}
+
diff --git a/xmpp-vala/src/module/xep/0166_jingle/content.vala b/xmpp-vala/src/module/xep/0166_jingle/content.vala
new file mode 100644
index 00000000..41310aeb
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/content.vala
@@ -0,0 +1,239 @@
+using Gee;
+using Xmpp;
+
+public class Xmpp.Xep.Jingle.Content : Object {
+
+ public signal void senders_modify_incoming(Senders proposed_senders);
+
+ // INITIATE_SENT -> CONNECTING -> [REPLACING_TRANSPORT -> CONNECTING ->]... ACTIVE -> ENDED
+ // INITIATE_RECEIVED -> CONNECTING -> [WAITING_FOR_TRANSPORT_REPLACE -> CONNECTING ->].. ACTIVE -> ENDED
+ public enum State {
+ PENDING,
+ WANTS_TO_BE_ACCEPTED,
+ ACCEPTED,
+ REPLACING_TRANSPORT,
+ WAITING_FOR_TRANSPORT_REPLACE
+ }
+
+ public State state { get; set; }
+
+ public Role role { get; private set; }
+ public Jid local_full_jid { get; private set; }
+ public Jid peer_full_jid { get; private set; }
+ public Role content_creator { get; private set; }
+ public string content_name { get; private set; }
+ public Senders senders { get; private set; }
+
+ public ContentType content_type;
+ public ContentParameters content_params;
+ public Transport transport;
+ public TransportParameters? transport_params;
+ public SecurityPrecondition security_precondition;
+ public SecurityParameters? security_params;
+
+ public weak Session session;
+ public Map<uint8, ComponentConnection> component_connections = new HashMap<uint8, ComponentConnection>(); // TODO private
+
+ public HashMap<string, ContentEncryption> encryptions = new HashMap<string, ContentEncryption>();
+
+ private Set<string> tried_transport_methods = new HashSet<string>();
+
+
+ public Content.initiate_sent(string content_name, Senders senders,
+ ContentType content_type, ContentParameters content_params,
+ Transport transport, TransportParameters? transport_params,
+ SecurityPrecondition? security_precondition, SecurityParameters? security_params,
+ Jid local_full_jid, Jid peer_full_jid) {
+ this.content_name = content_name;
+ this.senders = senders;
+ this.role = Role.INITIATOR;
+ this.local_full_jid = local_full_jid;
+ this.peer_full_jid = peer_full_jid;
+ this.content_creator = Role.INITIATOR;
+
+ this.content_type = content_type;
+ this.content_params = content_params;
+ this.transport = transport;
+ this.transport_params = transport_params;
+ this.security_precondition = security_precondition;
+ this.security_params = security_params;
+
+ this.tried_transport_methods.add(transport.ns_uri);
+
+ state = State.PENDING;
+ }
+
+ public Content.initiate_received(string content_name, Senders senders,
+ ContentType content_type, ContentParameters content_params,
+ Transport transport, TransportParameters? transport_params,
+ SecurityPrecondition? security_precondition, SecurityParameters? security_params,
+ Jid local_full_jid, Jid peer_full_jid) throws Error {
+ this.content_name = content_name;
+ this.senders = senders;
+ this.role = Role.RESPONDER;
+ this.local_full_jid = local_full_jid;
+ this.peer_full_jid = peer_full_jid;
+ this.content_creator = Role.INITIATOR;
+
+ this.content_type = content_type;
+ this.content_params = content_params;
+ this.transport = transport;
+ this.transport_params = transport_params;
+ this.security_precondition = security_precondition;
+ this.security_params = security_params;
+
+ if (transport != null) {
+ this.tried_transport_methods.add(transport.ns_uri);
+ }
+
+ state = State.PENDING;
+ }
+
+ public void set_session(Session session) {
+ this.session = session;
+ this.transport_params.set_content(this);
+ }
+
+ public void accept() {
+ state = State.WANTS_TO_BE_ACCEPTED;
+
+ session.accept_content(this);
+ }
+
+ public void reject() {
+ session.reject_content(this);
+ }
+
+ public void terminate(bool we_terminated, string? reason_name, string? reason_text) {
+ content_params.terminate(we_terminated, reason_name, reason_text);
+ transport_params.dispose();
+
+ foreach (ComponentConnection connection in component_connections.values) {
+ connection.terminate.begin(we_terminated, reason_name, reason_text);
+ }
+ }
+
+ public void modify(Senders new_sender) {
+ session.send_content_modify(this, new_sender);
+ this.senders = new_sender;
+ }
+
+ public void accept_content_modify(Senders senders) {
+ this.senders = senders;
+ }
+
+ internal void handle_content_modify(XmppStream stream, Senders proposed_senders) {
+ senders_modify_incoming(proposed_senders);
+ }
+
+ internal void on_accept(XmppStream stream) {
+ this.transport_params.create_transport_connection(stream, this);
+ this.content_params.accept(stream, session, this);
+ }
+
+ internal void handle_accept(XmppStream stream, ContentNode content_node) {
+ this.transport_params.handle_transport_accept(content_node.transport);
+ this.transport_params.create_transport_connection(stream, this);
+ this.content_params.handle_accept(stream, this.session, this, content_node.description);
+ }
+
+ private async void select_new_transport() {
+ XmppStream stream = session.stream;
+ Transport? new_transport = yield stream.get_module(Module.IDENTITY).select_transport(stream, transport.type_, transport_params.components, peer_full_jid, tried_transport_methods);
+ if (new_transport == null) {
+ session.terminate(ReasonElement.FAILED_TRANSPORT, null, "failed transport");
+ // TODO should we only terminate this content or really the whole session?
+ return;
+ }
+ tried_transport_methods.add(new_transport.ns_uri);
+ transport_params = new_transport.create_transport_parameters(stream, transport_params.components, local_full_jid, peer_full_jid);
+ set_transport_params(transport_params);
+ session.send_transport_replace(this, transport_params);
+ state = State.REPLACING_TRANSPORT;
+ }
+
+ public void handle_transport_accept(XmppStream stream, StanzaNode transport_node, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ if (state != State.REPLACING_TRANSPORT) {
+ throw new IqError.OUT_OF_ORDER("no outstanding transport-replace request");
+ }
+ if (transport_node.ns_uri != transport.ns_uri) {
+ throw new IqError.BAD_REQUEST("transport-accept with unnegotiated transport method");
+ }
+ transport_params.handle_transport_accept(transport_node);
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ transport_params.create_transport_connection(stream, this);
+ }
+
+ public void handle_transport_reject(XmppStream stream, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ if (state != State.REPLACING_TRANSPORT) {
+ throw new IqError.OUT_OF_ORDER("no outstanding transport-replace request");
+ }
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ select_new_transport.begin();
+ }
+
+ public void handle_transport_replace(XmppStream stream, StanzaNode transport_node, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ Transport? transport = stream.get_module(Module.IDENTITY).get_transport(transport_node.ns_uri);
+ TransportParameters? parameters = null;
+ if (transport != null) {
+ // Just parse the transport info for the errors.
+ parameters = transport.parse_transport_parameters(stream, content_type.required_components, local_full_jid, peer_full_jid, transport_node);
+ }
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ if (state != State.WAITING_FOR_TRANSPORT_REPLACE || transport == null) {
+ session.send_transport_reject(this, transport_node);
+ return;
+ }
+ set_transport_params(parameters);
+ session.send_transport_accept(this, parameters);
+
+ this.transport_params.create_transport_connection(stream, this);
+ }
+
+ public void handle_transport_info(XmppStream stream, StanzaNode transport, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ this.transport_params.handle_transport_info(transport);
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ }
+
+ public void on_description_info(XmppStream stream, StanzaNode description, StanzaNode jinglq, Iq.Stanza iq) throws IqError {
+ // TODO: do something.
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ }
+
+ public void set_transport_connection(ComponentConnection? conn, uint8 component = 1) {
+ debug(@"set_transport_connection: %s, %s, %i, %s, overwrites: %s", this.content_name, this.state.to_string(), component, (conn != null).to_string(), component_connections.has_key(component).to_string());
+
+ if (conn != null) {
+ component_connections[component] = conn;
+ if (transport_params.components == component) {
+ state = State.ACCEPTED;
+ tried_transport_methods.clear();
+ }
+ } else {
+ if (role == Role.INITIATOR) {
+ select_new_transport.begin();
+ } else {
+ state = State.WAITING_FOR_TRANSPORT_REPLACE;
+ }
+ }
+ }
+
+ private void set_transport_params(TransportParameters transport_params) {
+ this.transport_params = transport_params;
+ }
+
+ public ComponentConnection? get_transport_connection(uint8 component = 1) {
+ return component_connections[component];
+ }
+
+ public void send_transport_info(StanzaNode transport) {
+ session.send_transport_info(this, transport);
+ }
+}
+
+public class Xmpp.Xep.Jingle.ContentEncryption : Object {
+ public string encryption_ns { get; set; }
+ public string encryption_name { get; set; }
+ public uint8[] our_key { get; set; }
+ public uint8[] peer_key { get; set; }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/content_description.vala b/xmpp-vala/src/module/xep/0166_jingle/content_description.vala
new file mode 100644
index 00000000..1a24e52e
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/content_description.vala
@@ -0,0 +1,27 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ public interface ContentType : Object {
+ public abstract string ns_uri { get; }
+ public abstract TransportType required_transport_type { get; }
+ public abstract uint8 required_components { get; }
+ public abstract ContentParameters parse_content_parameters(StanzaNode description) throws IqError;
+ }
+
+ public interface ContentParameters : Object {
+ /** Called when the counterpart proposes the content */
+ public abstract async void handle_proposed_content(XmppStream stream, Jingle.Session session, Content content);
+
+ /** Called when we accept the content that was proposed by the counterpart */
+ public abstract void accept(XmppStream stream, Jingle.Session session, Jingle.Content content);
+ /** Called when the counterpart accepts the content that was proposed by us*/
+ public abstract void handle_accept(XmppStream stream, Jingle.Session session, Jingle.Content content, StanzaNode description_node);
+
+ public abstract void terminate(bool we_terminated, string? reason_name, string? reason_text);
+
+ public abstract StanzaNode get_description_node();
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/content_node.vala b/xmpp-vala/src/module/xep/0166_jingle/content_node.vala
new file mode 100644
index 00000000..7d8d56c8
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/content_node.vala
@@ -0,0 +1,112 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ class ContentNode {
+ public Role creator;
+ public string name;
+ public Senders senders;
+ public StanzaNode? description;
+ public StanzaNode? transport;
+ public StanzaNode? security;
+ }
+
+ [Version(deprecated = true)]
+ ContentNode get_single_content_node(StanzaNode jingle) throws IqError {
+ Gee.List<StanzaNode> contents = jingle.get_subnodes("content");
+ if (contents.size == 0) {
+ throw new IqError.BAD_REQUEST("missing content node");
+ }
+ if (contents.size > 1) {
+ throw new IqError.NOT_IMPLEMENTED("can't process multiple content nodes");
+ }
+ StanzaNode content = contents[0];
+ string? creator_str = content.get_attribute("creator");
+ // Vala can't typecheck the ternary operator here.
+ Role? creator = null;
+ if (creator_str != null) {
+ creator = Role.parse(creator_str);
+ } else {
+ // TODO(hrxi): now, is the creator attribute optional or not (XEP-0166
+ // Jingle)?
+ creator = Role.INITIATOR;
+ }
+
+ string? name = content.get_attribute("name");
+
+ Senders senders = Senders.parse(content.get_attribute("senders"));
+
+ StanzaNode? description = get_single_node_anyns(content, "description");
+ StanzaNode? transport = get_single_node_anyns(content, "transport");
+ StanzaNode? security = get_single_node_anyns(content, "security");
+ if (name == null || creator == null) {
+ throw new IqError.BAD_REQUEST("missing name or creator");
+ }
+
+ return new ContentNode() {
+ creator=creator,
+ name=name,
+ senders=senders,
+ description=description,
+ transport=transport,
+ security=security
+ };
+ }
+
+ Gee.List<ContentNode> get_content_nodes(StanzaNode jingle) throws IqError {
+ Gee.List<StanzaNode> contents = jingle.get_subnodes("content");
+ if (contents.size == 0) {
+ throw new IqError.BAD_REQUEST("missing content node");
+ }
+ Gee.List<ContentNode> list = new ArrayList<ContentNode>();
+ foreach (StanzaNode content in contents) {
+ string? creator_str = content.get_attribute("creator");
+ // Vala can't typecheck the ternary operator here.
+ Role? creator = null;
+ if (creator_str != null) {
+ creator = Role.parse(creator_str);
+ } else {
+ // TODO(hrxi): now, is the creator attribute optional or not (XEP-0166
+ // Jingle)?
+ creator = Role.INITIATOR;
+ }
+
+ string? name = content.get_attribute("name");
+ Senders senders = Senders.parse(content.get_attribute("senders"));
+ StanzaNode? description = get_single_node_anyns(content, "description");
+ StanzaNode? transport = get_single_node_anyns(content, "transport");
+ StanzaNode? security = get_single_node_anyns(content, "security");
+ if (name == null || creator == null) {
+ throw new IqError.BAD_REQUEST("missing name or creator");
+ }
+ list.add(new ContentNode() {
+ creator=creator,
+ name=name,
+ senders=senders,
+ description=description,
+ transport=transport,
+ security=security
+ });
+ }
+ return list;
+ }
+
+ StanzaNode? get_single_node_anyns(StanzaNode parent, string? node_name = null) throws IqError {
+ StanzaNode? result = null;
+ foreach (StanzaNode child in parent.get_all_subnodes()) {
+ if (node_name == null || child.name == node_name) {
+ if (result != null) {
+ if (node_name != null) {
+ throw new IqError.BAD_REQUEST(@"multiple $(node_name) nodes");
+ } else {
+ throw new IqError.BAD_REQUEST(@"expected single subnode");
+ }
+ }
+ result = child;
+ }
+ }
+ return result;
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/content_security.vala b/xmpp-vala/src/module/xep/0166_jingle/content_security.vala
new file mode 100644
index 00000000..0e10311d
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/content_security.vala
@@ -0,0 +1,18 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ public interface SecurityPrecondition : Object {
+ public abstract string security_ns_uri();
+ public abstract SecurityParameters? create_security_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, Object options) throws Jingle.Error;
+ public abstract SecurityParameters? parse_security_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode security) throws IqError;
+ }
+
+ public interface SecurityParameters : Object {
+ public abstract string security_ns_uri();
+ public abstract StanzaNode to_security_stanza_node(XmppStream stream, Jid local_full_jid, Jid peer_full_jid);
+ public abstract IOStream wrap_stream(IOStream stream);
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/content_transport.vala b/xmpp-vala/src/module/xep/0166_jingle/content_transport.vala
new file mode 100644
index 00000000..2697a01c
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/content_transport.vala
@@ -0,0 +1,29 @@
+namespace Xmpp.Xep.Jingle {
+
+ public interface Transport : Object {
+ public abstract string ns_uri { get; }
+ public async abstract bool is_transport_available(XmppStream stream, uint8 components, Jid full_jid);
+ public abstract TransportType type_ { get; }
+ public abstract int priority { get; }
+ public abstract TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) throws Error;
+ public abstract TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws IqError;
+ }
+
+ public enum TransportType {
+ DATAGRAM,
+ STREAMING,
+ }
+
+ // Gets a null `stream` if connection setup was unsuccessful and another
+ // transport method should be tried.
+ public interface TransportParameters : Object {
+ public abstract string ns_uri { get; }
+ public abstract uint8 components { get; }
+
+ public abstract void set_content(Content content);
+ public abstract StanzaNode to_transport_stanza_node(string action_type);
+ public abstract void handle_transport_accept(StanzaNode transport) throws IqError;
+ public abstract void handle_transport_info(StanzaNode transport) throws IqError;
+ public abstract void create_transport_connection(XmppStream stream, Content content);
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/jingle_flag.vala b/xmpp-vala/src/module/xep/0166_jingle/jingle_flag.vala
new file mode 100644
index 00000000..9f0acd27
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/jingle_flag.vala
@@ -0,0 +1,38 @@
+using Gee;
+using Xmpp;
+
+public class Xmpp.Xep.Jingle.Flag : XmppStreamFlag {
+ public static FlagIdentity<Flag> IDENTITY = new FlagIdentity<Flag>(NS_URI, "jingle");
+
+ public HashMap<string, Session> sessions = new HashMap<string, Session>();
+ public HashMap<string, Promise<Session?>> promises = new HashMap<string, Promise<Session?>>();
+
+ // We might get transport-infos about a session before we finished fully creating the session. (e.g. telepathy outgoing calls)
+ // Thus, we "pre add" the session as soon as possible and can then await it.
+ public void pre_add_session(string sid) {
+ var promise = new Promise<Session?>();
+ promises[sid] = promise;
+ }
+
+ public void add_session(Session session) {
+ if (promises.has_key(session.sid)) {
+ promises[session.sid].set_value(session);
+ promises.unset(session.sid);
+ }
+ sessions[session.sid] = session;
+ }
+
+ public async Session? get_session(string sid) {
+ if (promises.has_key(sid)) {
+ return yield promises[sid].future.wait_async();
+ }
+ return sessions[sid];
+ }
+
+ public void remove_session(string sid) {
+ sessions.unset(sid);
+ }
+
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/jingle_module.vala b/xmpp-vala/src/module/xep/0166_jingle/jingle_module.vala
new file mode 100644
index 00000000..186848f6
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/jingle_module.vala
@@ -0,0 +1,235 @@
+using Gee;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ public const string NS_URI = "urn:xmpp:jingle:1";
+ private const string ERROR_NS_URI = "urn:xmpp:jingle:errors:1";
+
+ // This module can only be attached to one stream at a time.
+ public class Module : XmppStreamModule, Iq.Handler {
+ public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0166_jingle");
+
+ public signal void session_initiate_received(XmppStream stream, Session session);
+
+ private HashMap<string, ContentType> content_types = new HashMap<string, ContentType>();
+ private HashMap<string, SessionInfoNs> session_info_types = new HashMap<string, SessionInfoNs>();
+ private HashMap<string, Transport> transports = new HashMap<string, Transport>();
+ private HashMap<string, SecurityPrecondition> security_preconditions = new HashMap<string, SecurityPrecondition>();
+
+ public override void attach(XmppStream stream) {
+ stream.add_flag(new Flag());
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
+ stream.get_module(Iq.Module.IDENTITY).register_for_namespace(NS_URI, this);
+
+ // TODO update stream in all sessions
+ }
+
+ public override void detach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
+ stream.get_module(Iq.Module.IDENTITY).unregister_from_namespace(NS_URI, this);
+ }
+
+ public void register_content_type(ContentType content_type) {
+ content_types[content_type.ns_uri] = content_type;
+ }
+
+ public void register_session_info_type(SessionInfoNs info_ns) {
+ session_info_types[info_ns.ns_uri] = info_ns;
+ }
+
+ public ContentType? get_content_type(string ns_uri) {
+ if (!content_types.has_key(ns_uri)) {
+ return null;
+ }
+ return content_types[ns_uri];
+ }
+
+ public SessionInfoNs? get_session_info_type(string ns_uri) {
+ return session_info_types[ns_uri];
+ }
+
+ public void register_transport(Transport transport) {
+ transports[transport.ns_uri] = transport;
+ }
+
+ public Transport? get_transport(string ns_uri) {
+ if (!transports.has_key(ns_uri)) {
+ return null;
+ }
+ return transports[ns_uri];
+ }
+
+ public async Transport? select_transport(XmppStream stream, TransportType type, uint8 components, Jid receiver_full_jid, Set<string> blacklist) {
+ Transport? result = null;
+ foreach (Transport transport in transports.values) {
+ if (transport.type_ != type) {
+ continue;
+ }
+ if (transport.ns_uri in blacklist) {
+ continue;
+ }
+ if (yield transport.is_transport_available(stream, components, receiver_full_jid)) {
+ if (result != null) {
+ if (result.priority >= transport.priority) {
+ continue;
+ }
+ }
+ result = transport;
+ }
+ }
+ return result;
+ }
+
+ public void register_security_precondition(SecurityPrecondition precondition) {
+ security_preconditions[precondition.security_ns_uri()] = precondition;
+ }
+
+ public SecurityPrecondition? get_security_precondition(string? ns_uri) {
+ if (ns_uri == null) return null;
+ if (!security_preconditions.has_key(ns_uri)) {
+ return null;
+ }
+ return security_preconditions[ns_uri];
+ }
+
+ private async bool is_jingle_available(XmppStream stream, Jid full_jid) {
+ bool? has_jingle = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
+ return has_jingle != null && has_jingle;
+ }
+
+ public async bool is_available(XmppStream stream, TransportType type, uint8 components, Jid full_jid) {
+ return (yield is_jingle_available(stream, full_jid)) && (yield select_transport(stream, type, components, full_jid, Set.empty())) != null;
+ }
+
+ public async Session create_session(XmppStream stream, Gee.List<Content> contents, Jid receiver_full_jid, string? sid = null) throws Error {
+ if (!yield is_jingle_available(stream, receiver_full_jid)) {
+ throw new Error.NO_SHARED_PROTOCOLS("No Jingle support");
+ }
+ Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
+ if (my_jid == null) {
+ throw new Error.GENERAL("Couldn't determine own JID");
+ }
+
+ Session session = new Session.initiate_sent(stream, sid ?? random_uuid(), my_jid, receiver_full_jid);
+ session.terminated.connect((session, stream, _1, _2, _3) => { stream.get_flag(Flag.IDENTITY).remove_session(session.sid); });
+
+ foreach (Content content in contents) {
+ session.insert_content(content);
+ }
+
+ // Build & send session-initiate iq stanza
+ StanzaNode initiate_jingle_iq = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "session-initiate")
+ .put_attribute("initiator", my_jid.to_string())
+ .put_attribute("sid", session.sid);
+
+ foreach (Content content in contents) {
+ StanzaNode content_node = new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_attribute("senders", content.senders.to_string())
+ .put_node(content.content_params.get_description_node())
+ .put_node(content.transport_params.to_transport_stanza_node("session-initiate"));
+ if (content.security_params != null) {
+ content_node.put_node(content.security_params.to_security_stanza_node(stream, my_jid, receiver_full_jid));
+ }
+ initiate_jingle_iq.put_node(content_node);
+ }
+
+ Iq.Stanza iq = new Iq.Stanza.set(initiate_jingle_iq) { to=receiver_full_jid };
+
+ stream.get_flag(Flag.IDENTITY).add_session(session);
+ // We might get a follow-up before the ack => add_session before send_iq returns
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq, (stream, iq) => {
+ if (iq.is_error()) warning("Jingle session-initiate got error: %s", iq.stanza.to_string());
+ });
+
+ return session;
+ }
+
+ public async void handle_session_initiate(XmppStream stream, string sid, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
+ if (my_jid == null) {
+ throw new IqError.RESOURCE_CONSTRAINT("Couldn't determine own JID");
+ }
+
+ Session session = new Session.initiate_received(stream, sid, my_jid, iq.from);
+ session.terminated.connect((stream) => { stream.get_flag(Flag.IDENTITY).remove_session(sid); });
+
+ stream.get_flag(Flag.IDENTITY).pre_add_session(session.sid);
+
+ foreach (ContentNode content_node in get_content_nodes(jingle)) {
+ yield session.insert_content_node(content_node, iq.from);
+ }
+
+ stream.get_flag(Flag.IDENTITY).add_session(session);
+
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+
+ session_initiate_received(stream, session);
+ }
+
+ public async void on_iq_set(XmppStream stream, Iq.Stanza iq) {
+ try {
+ yield handle_iq_set(stream, iq);
+ } catch (IqError e) {
+ send_iq_error(e, stream, iq);
+ }
+ }
+
+ public async void handle_iq_set(XmppStream stream, Iq.Stanza iq) throws IqError {
+ StanzaNode? jingle_node = iq.stanza.get_subnode("jingle", NS_URI);
+ if (jingle_node == null) {
+ throw new IqError.BAD_REQUEST("missing jingle node");
+ }
+ string? sid = jingle_node.get_attribute("sid");
+ string? action = jingle_node.get_attribute("action");
+ if (sid == null || action == null) {
+ throw new IqError.BAD_REQUEST("missing jingle node, sid or action");
+ }
+
+ Session? session = yield stream.get_flag(Flag.IDENTITY).get_session(sid);
+ if (action == "session-initiate") {
+ if (session != null) {
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.build(ErrorStanza.TYPE_MODIFY, ErrorStanza.CONDITION_CONFLICT, "session ID already in use", null)) { to=iq.from });
+ return;
+ }
+ yield handle_session_initiate(stream, sid, jingle_node, iq);
+ return;
+ }
+ if (session == null) {
+ StanzaNode unknown_session = new StanzaNode.build("unknown-session", ERROR_NS_URI).add_self_xmlns();
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, new ErrorStanza.item_not_found(unknown_session)) { to=iq.from });
+ return;
+ }
+ session.handle_iq_set(action, jingle_node, iq);
+ }
+
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+ }
+
+ void send_iq_error(IqError iq_error, XmppStream stream, Iq.Stanza iq) {
+ ErrorStanza error;
+ if (iq_error is IqError.BAD_REQUEST) {
+ error = new ErrorStanza.bad_request(iq_error.message);
+ } else if (iq_error is IqError.NOT_ACCEPTABLE) {
+ error = new ErrorStanza.not_acceptable(iq_error.message);
+ } else if (iq_error is IqError.NOT_IMPLEMENTED) {
+ error = new ErrorStanza.feature_not_implemented(iq_error.message);
+ } else if (iq_error is IqError.UNSUPPORTED_INFO) {
+ StanzaNode unsupported_info = new StanzaNode.build("unsupported-info", ERROR_NS_URI).add_self_xmlns();
+ error = new ErrorStanza.build(ErrorStanza.TYPE_CANCEL, ErrorStanza.CONDITION_FEATURE_NOT_IMPLEMENTED, iq_error.message, unsupported_info);
+ } else if (iq_error is IqError.OUT_OF_ORDER) {
+ StanzaNode out_of_order = new StanzaNode.build("out-of-order", ERROR_NS_URI).add_self_xmlns();
+ error = new ErrorStanza.build(ErrorStanza.TYPE_MODIFY, ErrorStanza.CONDITION_UNEXPECTED_REQUEST, iq_error.message, out_of_order);
+ } else if (iq_error is IqError.RESOURCE_CONSTRAINT) {
+ error = new ErrorStanza.resource_constraint(iq_error.message);
+ } else {
+ assert_not_reached();
+ }
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.error(iq, error) { to=iq.from });
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/jingle_structs.vala b/xmpp-vala/src/module/xep/0166_jingle/jingle_structs.vala
new file mode 100644
index 00000000..0f283e0e
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/jingle_structs.vala
@@ -0,0 +1,73 @@
+using Gee;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ public errordomain IqError {
+ BAD_REQUEST,
+ NOT_ACCEPTABLE,
+ NOT_IMPLEMENTED,
+ UNSUPPORTED_INFO,
+ OUT_OF_ORDER,
+ RESOURCE_CONSTRAINT,
+ }
+
+ public errordomain Error {
+ GENERAL,
+ BAD_REQUEST,
+ INVALID_PARAMETERS,
+ UNSUPPORTED_TRANSPORT,
+ UNSUPPORTED_SECURITY,
+ NO_SHARED_PROTOCOLS,
+ TRANSPORT_ERROR,
+ }
+
+ public enum Senders {
+ BOTH,
+ INITIATOR,
+ NONE,
+ RESPONDER;
+
+ public string to_string() {
+ switch (this) {
+ case BOTH: return "both";
+ case INITIATOR: return "initiator";
+ case NONE: return "none";
+ case RESPONDER: return "responder";
+ }
+ assert_not_reached();
+ }
+
+ public static Senders parse(string? senders) throws IqError {
+ if (senders == null) return Senders.BOTH;
+ switch (senders) {
+ case "initiator": return Senders.INITIATOR;
+ case "responder": return Senders.RESPONDER;
+ case "both": return Senders.BOTH;
+ }
+ throw new IqError.BAD_REQUEST(@"invalid role $(senders)");
+ }
+ }
+
+ public enum Role {
+ INITIATOR,
+ RESPONDER;
+
+ public string to_string() {
+ switch (this) {
+ case INITIATOR: return "initiator";
+ case RESPONDER: return "responder";
+ }
+ assert_not_reached();
+ }
+
+ public static Role parse(string role) throws IqError {
+ switch (role) {
+ case "initiator": return INITIATOR;
+ case "responder": return RESPONDER;
+ }
+ throw new IqError.BAD_REQUEST(@"invalid role $(role)");
+ }
+ }
+
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/reason_element.vala b/xmpp-vala/src/module/xep/0166_jingle/reason_element.vala
new file mode 100644
index 00000000..4d47d4cd
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/reason_element.vala
@@ -0,0 +1,30 @@
+using Gee;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle.ReasonElement {
+ public const string ALTERNATIVE_SESSION = "alternative-session";
+ public const string BUSY = "busy";
+ public const string CANCEL = "cancel";
+ public const string CONNECTIVITY_ERROR = "connectivity-error";
+ public const string DECLINE = "decline";
+ public const string EXPIRED = "expired";
+ public const string FAILED_APPLICATION = "failed_application";
+ public const string FAILED_TRANSPORT = "failed_transport";
+ public const string GENERAL_ERROR = "general-error";
+ public const string GONE = "gone";
+ public const string INCOMPATIBLE_PARAMETERS = "incompatible-parameters";
+ public const string MEDIA_ERROR = "media-error";
+ public const string SECURITY_ERROR = "security-error";
+ public const string SUCCESS = "success";
+ public const string TIMEOUT = "timeout";
+ public const string UNSUPPORTED_APPLICATIONS = "unsupported-applications";
+ public const string UNSUPPORTED_TRANSPORTS = "unsupported-transports";
+
+ public const string[] NORMAL_TERMINATE_REASONS = {
+ BUSY,
+ CANCEL,
+ DECLINE,
+ GONE,
+ SUCCESS
+ };
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/session.vala b/xmpp-vala/src/module/xep/0166_jingle/session.vala
new file mode 100644
index 00000000..4d04c8d5
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/session.vala
@@ -0,0 +1,561 @@
+using Gee;
+using Xmpp;
+
+
+public delegate void Xmpp.Xep.Jingle.SessionTerminate(Jid to, string sid, StanzaNode reason);
+
+public class Xmpp.Xep.Jingle.Session : Object {
+
+ public signal void terminated(XmppStream stream, bool we_terminated, string? reason_name, string? reason_text);
+ public signal void additional_content_add_incoming(XmppStream stream, Content content);
+
+ // INITIATE_SENT/INITIATE_RECEIVED -> CONNECTING -> PENDING -> ACTIVE -> ENDED
+ public enum State {
+ INITIATE_SENT,
+ INITIATE_RECEIVED,
+ ACTIVE,
+ ENDED,
+ }
+
+ public XmppStream stream { get; set; }
+ public State state { get; set; }
+ public string sid { get; private set; }
+ public Jid local_full_jid { get; private set; }
+ public Jid peer_full_jid { get; private set; }
+ public bool we_initiated { get; private set; }
+
+ public HashMap<string, Content> contents_map = new HashMap<string, Content>();
+ public Gee.List<Content> contents = new ArrayList<Content>(); // Keep the order contents
+
+ public SecurityParameters? security { get { return contents.to_array()[0].security_params; } }
+
+ public Session.initiate_sent(XmppStream stream, string sid, Jid local_full_jid, Jid peer_full_jid) {
+ this.stream = stream;
+ this.sid = sid;
+ this.local_full_jid = local_full_jid;
+ this.peer_full_jid = peer_full_jid;
+ this.state = State.INITIATE_SENT;
+ this.we_initiated = true;
+ }
+
+ public Session.initiate_received(XmppStream stream, string sid, Jid local_full_jid, Jid peer_full_jid) {
+ this.stream = stream;
+ this.sid = sid;
+ this.local_full_jid = local_full_jid;
+ this.peer_full_jid = peer_full_jid;
+ this.state = State.INITIATE_RECEIVED;
+ this.we_initiated = false;
+ }
+
+ public void handle_iq_set(string action, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+
+ if (action.has_prefix("session-")) {
+ switch (action) {
+ case "session-accept":
+ Gee.List<ContentNode> content_nodes = get_content_nodes(jingle);
+
+ if (state != State.INITIATE_SENT) {
+ throw new IqError.OUT_OF_ORDER("got session-accept while not waiting for one");
+ }
+ handle_session_accept(content_nodes, jingle, iq);
+ break;
+ case "session-info":
+ handle_session_info.begin(jingle, iq);
+ break;
+ case "session-terminate":
+ handle_session_terminate(jingle, iq);
+ break;
+ default:
+ throw new IqError.BAD_REQUEST("invalid action");
+ }
+
+
+ } else if (action.has_prefix("content-")) {
+ switch (action) {
+ case "content-accept":
+ ContentNode content_node = get_single_content_node(jingle);
+ handle_content_accept(content_node);
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ break;
+ case "content-add":
+ ContentNode content_node = get_single_content_node(jingle);
+ insert_content_node.begin(content_node, peer_full_jid);
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ break;
+ case "content-modify":
+ handle_content_modify(stream, jingle, iq);
+ break;
+ case "content-reject":
+ case "content-remove":
+ throw new IqError.NOT_IMPLEMENTED(@"$(action) is not implemented");
+ default:
+ throw new IqError.BAD_REQUEST("invalid action");
+ }
+
+
+ } else if (action.has_prefix("transport-")) {
+ ContentNode content_node = get_single_content_node(jingle);
+ if (!contents_map.has_key(content_node.name)) {
+ throw new IqError.BAD_REQUEST("unknown content");
+ }
+
+ if (content_node.transport == null) {
+ throw new IqError.BAD_REQUEST("missing transport node");
+ }
+
+ Content content = contents_map[content_node.name];
+
+ if (content_node.creator != content.content_creator) {
+ throw new IqError.BAD_REQUEST("unknown content; creator");
+ }
+
+ switch (action) {
+ case "transport-accept":
+ content.handle_transport_accept(stream, content_node.transport, jingle, iq);
+ break;
+ case "transport-info":
+ content.handle_transport_info(stream, content_node.transport, jingle, iq);
+ break;
+ case "transport-reject":
+ content.handle_transport_reject(stream, jingle, iq);
+ break;
+ case "transport-replace":
+ content.handle_transport_replace(stream, content_node.transport, jingle, iq);
+ break;
+ default:
+ throw new IqError.BAD_REQUEST("invalid action");
+ }
+
+
+ } else if (action == "description-info") {
+ ContentNode content_node = get_single_content_node(jingle);
+ if (!contents_map.has_key(content_node.name)) {
+ throw new IqError.BAD_REQUEST("unknown content");
+ }
+
+ Content content = contents_map[content_node.name];
+
+ if (content_node.creator != content.content_creator) {
+ throw new IqError.BAD_REQUEST("unknown content; creator");
+ }
+
+ content.on_description_info(stream, content_node.description, jingle, iq);
+ } else if (action == "security-info") {
+ throw new IqError.NOT_IMPLEMENTED(@"$(action) is not implemented");
+
+
+ } else {
+ throw new IqError.BAD_REQUEST("invalid action");
+ }
+ }
+
+ internal void insert_content(Content content) {
+ this.contents_map[content.content_name] = content;
+ this.contents.add(content);
+ content.set_session(this);
+ }
+
+ internal async void insert_content_node(ContentNode content_node, Jid peer_full_jid) throws IqError {
+ if (content_node.description == null || content_node.transport == null) {
+ throw new IqError.BAD_REQUEST("missing description or transport node");
+ }
+
+ Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
+
+ Transport? transport = stream.get_module(Jingle.Module.IDENTITY).get_transport(content_node.transport.ns_uri);
+ ContentType? content_type = stream.get_module(Jingle.Module.IDENTITY).get_content_type(content_node.description.ns_uri);
+
+ if (content_type == null) {
+ // TODO(hrxi): how do we signal an unknown content type?
+ throw new IqError.NOT_IMPLEMENTED("unknown content type");
+ }
+
+ TransportParameters? transport_params = null;
+ if (transport != null) {
+ transport_params = transport.parse_transport_parameters(stream, content_type.required_components, my_jid, peer_full_jid, content_node.transport);
+ } else {
+ // terminate the session below
+ }
+
+ ContentParameters content_params = content_type.parse_content_parameters(content_node.description);
+
+ SecurityPrecondition? precondition = content_node.security != null ? stream.get_module(Jingle.Module.IDENTITY).get_security_precondition(content_node.security.ns_uri) : null;
+ SecurityParameters? security_params = null;
+ if (precondition != null) {
+ debug("Using precondition %s", precondition.security_ns_uri());
+ security_params = precondition.parse_security_parameters(stream, my_jid, peer_full_jid, content_node.security);
+ } else if (content_node.security != null) {
+ throw new IqError.NOT_IMPLEMENTED("unknown security precondition");
+ }
+
+ TransportType type = content_type.required_transport_type;
+
+ if (transport == null || transport.type_ != type) {
+ terminate(ReasonElement.UNSUPPORTED_TRANSPORTS, null, "unsupported transports");
+ throw new IqError.NOT_IMPLEMENTED("unsupported transports");
+ }
+
+ Content content = new Content.initiate_received(content_node.name, content_node.senders,
+ content_type, content_params,
+ transport, transport_params,
+ precondition, security_params,
+ my_jid, peer_full_jid);
+ insert_content(content);
+
+ yield content_params.handle_proposed_content(stream, this, content);
+
+ if (this.state == State.ACTIVE) {
+ additional_content_add_incoming(stream, content);
+ }
+ }
+
+ public async void add_content(Content content) {
+ insert_content(content);
+
+ StanzaNode content_add_node = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "content-add")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_attribute("senders", content.senders.to_string())
+ .put_node(content.content_params.get_description_node())
+ .put_node(content.transport_params.to_transport_stanza_node("content-add")));
+
+ Iq.Stanza iq = new Iq.Stanza.set(content_add_node) { to=peer_full_jid };
+ yield stream.get_module(Iq.Module.IDENTITY).send_iq_async(stream, iq);
+ }
+
+ private void handle_content_accept(ContentNode content_node) throws IqError {
+ if (content_node.description == null || content_node.transport == null) throw new IqError.BAD_REQUEST("missing description or transport node");
+ if (!contents_map.has_key(content_node.name)) throw new IqError.BAD_REQUEST("unknown content");
+
+ Content content = contents_map[content_node.name];
+
+ if (content_node.creator != content.content_creator) warning("Counterpart accepts content with an unexpected `creator`");
+ if (content_node.senders != content.senders) warning("Counterpart accepts content with an unexpected `senders`");
+ if (content_node.transport.ns_uri != content.transport_params.ns_uri) throw new IqError.BAD_REQUEST("session-accept with unnegotiated transport method");
+
+ content.handle_accept(stream, content_node);
+ }
+
+ private void handle_content_modify(XmppStream stream, StanzaNode jingle_node, Iq.Stanza iq) throws IqError {
+ ContentNode content_node = get_single_content_node(jingle_node);
+
+ Content? content = contents_map[content_node.name];
+
+ if (content == null) throw new IqError.BAD_REQUEST("no such content");
+ if (content_node.creator != content.content_creator) throw new IqError.BAD_REQUEST("mismatching creator");
+
+ Iq.Stanza result_iq = new Iq.Stanza.result(iq) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, result_iq);
+
+ content.handle_content_modify(stream, content_node.senders);
+ }
+
+ private void handle_session_accept(Gee.List<ContentNode> content_nodes, StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ string? responder_str = jingle.get_attribute("responder");
+ Jid responder = iq.from;
+ if (responder_str != null) {
+ try {
+ responder = new Jid(responder_str);
+ } catch (InvalidJidError e) {
+ warning("Received invalid session accept: %s", e.message);
+ }
+ }
+ // TODO(hrxi): more sanity checking, perhaps replace who we're talking to
+ if (!responder.is_full()) {
+ throw new IqError.BAD_REQUEST("invalid responder JID");
+ }
+ foreach (ContentNode content_node in content_nodes) {
+ handle_content_accept(content_node);
+ }
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+
+ state = State.ACTIVE;
+ }
+
+ private void handle_session_terminate(StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ string? reason_text = null;
+ string? reason_name = null;
+ StanzaNode? reason_node = iq.stanza.get_deep_subnode(NS_URI + ":jingle", NS_URI + ":reason");
+ if (reason_node != null) {
+ if (reason_node.sub_nodes.size > 2) warning("Jingle session-terminate reason node w/ >2 subnodes: %s", iq.stanza.to_string());
+
+ StanzaNode? specific_reason_node = null;
+ StanzaNode? text_node = null;
+ foreach (StanzaNode node in reason_node.sub_nodes) {
+ if (node.name == "text") {
+ text_node = node;
+ } else if (node.ns_uri == NS_URI) {
+ specific_reason_node = node;
+ }
+ }
+ reason_name = specific_reason_node != null ? specific_reason_node.name : null;
+ reason_text = text_node != null ? text_node.get_string_content() : null;
+
+ if (reason_name != null && !(specific_reason_node.name in ReasonElement.NORMAL_TERMINATE_REASONS)) {
+ warning("Jingle session terminated: %s : %s", reason_name ?? "", reason_text ?? "");
+ } else {
+ debug("Jingle session terminated: %s : %s", reason_name ?? "", reason_text ?? "");
+ }
+ }
+
+ foreach (Content content in contents) {
+ content.terminate(false, reason_name, reason_text);
+ }
+
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ // TODO(hrxi): also handle presence type=unavailable
+
+ state = State.ENDED;
+ terminated(stream, false, reason_name, reason_text);
+ }
+
+ private async void handle_session_info(StanzaNode jingle, Iq.Stanza iq) throws IqError {
+ StanzaNode? info = get_single_node_anyns(jingle);
+ if (info == null) {
+ // Jingle session ping
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
+ return;
+ }
+ SessionInfoNs? info_ns = stream.get_module(Module.IDENTITY).get_session_info_type(info.ns_uri);
+ if (info_ns == null) {
+ throw new IqError.UNSUPPORTED_INFO("unknown session-info namespace");
+ }
+ info_ns.handle_content_session_info(stream, this, info, iq);
+
+ Iq.Stanza result_iq = new Iq.Stanza.result(iq) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, result_iq);
+ }
+
+ private void accept() {
+ if (state != State.INITIATE_RECEIVED) critical("Accepting a stream, but we're the initiator");
+
+ StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "session-accept")
+ .put_attribute("sid", sid);
+ foreach (Content content in contents) {
+ StanzaNode content_node = new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_attribute("senders", content.senders.to_string())
+ .put_node(content.content_params.get_description_node())
+ .put_node(content.transport_params.to_transport_stanza_node("session-accept"));
+ jingle.put_node(content_node);
+ }
+
+ Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+
+
+ foreach (Content content2 in contents) {
+ content2.on_accept(stream);
+ }
+
+ state = State.ACTIVE;
+ }
+
+ internal void accept_content(Content content) {
+ if (state == State.INITIATE_RECEIVED) {
+ bool all_accepted = true;
+ foreach (Content c in contents) {
+ if (c.state != Content.State.WANTS_TO_BE_ACCEPTED) {
+ all_accepted = false;
+ }
+ }
+ if (all_accepted) {
+ accept();
+ }
+ } else if (state == State.ACTIVE) {
+ StanzaNode content_accept_node = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "content-accept")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_attribute("senders", content.senders.to_string())
+ .put_node(content.content_params.get_description_node())
+ .put_node(content.transport_params.to_transport_stanza_node("content-accept")));
+
+ Iq.Stanza iq = new Iq.Stanza.set(content_accept_node) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+
+ content.on_accept(stream);
+ }
+ }
+
+ private void reject() {
+ if (state != State.INITIATE_RECEIVED) critical("Accepting a stream, but we're the initiator");
+ terminate(ReasonElement.DECLINE, null, "declined");
+ }
+
+ internal void reject_content(Content content) {
+ if (state == State.INITIATE_RECEIVED) {
+ reject();
+ } else {
+ warning("not really handeling content rejects");
+ }
+ }
+
+ public void set_application_error(StanzaNode? application_reason = null) {
+ terminate(ReasonElement.FAILED_APPLICATION, null, "application error");
+ }
+
+ public void terminate(string? reason_name, string? reason_text, string? local_reason) {
+ if (state == State.ENDED) return;
+
+ if (state == State.ACTIVE) {
+ string reason_str;
+ if (local_reason != null) {
+ reason_str = @"local session-terminate: $(local_reason)";
+ } else {
+ reason_str = "local session-terminate";
+ }
+ foreach (Content content in contents) {
+ content.terminate(true, reason_name, reason_text);
+ }
+ }
+
+ StanzaNode terminate_iq = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "session-terminate")
+ .put_attribute("sid", sid);
+ if (reason_name != null || reason_text != null) {
+ StanzaNode reason_node = new StanzaNode.build("reason", NS_URI);
+ if (reason_name != null) {
+ reason_node.put_node(new StanzaNode.build(reason_name, NS_URI));
+ }
+ if (reason_text != null) {
+ reason_node.put_node(new StanzaNode.text(reason_text));
+ }
+ terminate_iq.put_node(reason_node);
+ }
+ Iq.Stanza iq = new Iq.Stanza.set(terminate_iq) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+
+ state = State.ENDED;
+ terminated(stream, true, reason_name, reason_text);
+ }
+
+ internal void send_session_info(StanzaNode child_node) {
+ if (state == State.ENDED) return;
+
+ StanzaNode node = new StanzaNode.build("jingle", NS_URI).add_self_xmlns()
+ .put_attribute("action", "session-info")
+ .put_attribute("sid", sid)
+ // TODO put `initiator`?
+ .put_node(child_node);
+ Iq.Stanza iq = new Iq.Stanza.set(node) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+ }
+
+ internal void send_content_modify(Content content, Senders senders) {
+ if (state == State.ENDED) return;
+
+ StanzaNode node = new StanzaNode.build("jingle", NS_URI).add_self_xmlns()
+ .put_attribute("action", "content-modify")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", content.content_creator.to_string())
+ .put_attribute("name", content.content_name)
+ .put_attribute("senders", senders.to_string()));
+ Iq.Stanza iq = new Iq.Stanza.set(node) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+ }
+
+ internal void send_transport_accept(Content content, TransportParameters transport_params) {
+ if (state == State.ENDED) return;
+
+ StanzaNode jingle_response = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "transport-accept")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_node(transport_params.to_transport_stanza_node("transport-accept"))
+ );
+ Iq.Stanza iq_response = new Iq.Stanza.set(jingle_response) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq_response);
+ }
+
+ internal void send_transport_replace(Content content, TransportParameters transport_params) {
+ if (state == State.ENDED) return;
+
+ StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "transport-replace")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_node(transport_params.to_transport_stanza_node("transport-replace"))
+ );
+ Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+ }
+
+ internal void send_transport_reject(Content content, StanzaNode transport_node) {
+ if (state == State.ENDED) return;
+
+ StanzaNode jingle_response = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "transport-reject")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_node(transport_node)
+ );
+ Iq.Stanza iq_response = new Iq.Stanza.set(jingle_response) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq_response);
+ }
+
+ internal void send_transport_info(Content content, StanzaNode transport) {
+ if (state == State.ENDED) return;
+
+ StanzaNode jingle = new StanzaNode.build("jingle", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("action", "transport-info")
+ .put_attribute("sid", sid)
+ .put_node(new StanzaNode.build("content", NS_URI)
+ .put_attribute("creator", "initiator")
+ .put_attribute("name", content.content_name)
+ .put_node(transport)
+ );
+ Iq.Stanza iq = new Iq.Stanza.set(jingle) { to=peer_full_jid };
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, iq);
+ }
+
+ public bool senders_include_us(Senders senders) {
+ switch (senders) {
+ case Senders.BOTH:
+ return true;
+ case Senders.NONE:
+ return false;
+ case Senders.INITIATOR:
+ return we_initiated;
+ case Senders.RESPONDER:
+ return !we_initiated;
+ }
+ assert_not_reached();
+ }
+
+ public bool senders_include_counterpart(Senders senders) {
+ switch (senders) {
+ case Senders.BOTH:
+ return true;
+ case Senders.NONE:
+ return false;
+ case Senders.INITIATOR:
+ return !we_initiated;
+ case Senders.RESPONDER:
+ return we_initiated;
+ }
+ assert_not_reached();
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0166_jingle/session_info.vala b/xmpp-vala/src/module/xep/0166_jingle/session_info.vala
new file mode 100644
index 00000000..fcf7584f
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0166_jingle/session_info.vala
@@ -0,0 +1,12 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Jingle {
+
+ public interface SessionInfoNs : Object {
+ public abstract string ns_uri { get; }
+
+ public abstract void handle_content_session_info(XmppStream stream, Session session, StanzaNode info, Iq.Stanza iq) throws IqError;
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/content_parameters.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/content_parameters.vala
new file mode 100644
index 00000000..344fe8b8
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/content_parameters.vala
@@ -0,0 +1,231 @@
+using Gee;
+using Xmpp;
+using Xmpp.Xep;
+
+public class Xmpp.Xep.JingleRtp.Parameters : Jingle.ContentParameters, Object {
+
+ public signal void stream_created(Stream stream);
+ public signal void connection_ready();
+
+ public string media { get; private set; }
+ public string? ssrc { get; private set; }
+ public bool rtcp_mux { get; private set; }
+
+ public string? bandwidth { get; private set; }
+ public string? bandwidth_type { get; private set; }
+
+ public bool encryption_required { get; private set; default = false; }
+ public PayloadType? agreed_payload_type { get; private set; }
+ public Gee.List<PayloadType> payload_types = new ArrayList<PayloadType>(PayloadType.equals_func);
+ public Gee.List<HeaderExtension> header_extensions = new ArrayList<HeaderExtension>();
+ public Gee.List<Crypto> remote_cryptos = new ArrayList<Crypto>();
+ public Crypto? local_crypto = null;
+ public Crypto? remote_crypto = null;
+
+ public weak Stream? stream { get; private set; }
+
+ private Module parent;
+
+ public Parameters(Module parent,
+ string media, Gee.List<PayloadType> payload_types,
+ string? ssrc = null, bool rtcp_mux = false,
+ string? bandwidth = null, string? bandwidth_type = null,
+ bool encryption_required = false, Crypto? local_crypto = null
+ ) {
+ this.parent = parent;
+ this.media = media;
+ this.ssrc = ssrc;
+ this.rtcp_mux = true;
+ this.bandwidth = bandwidth;
+ this.bandwidth_type = bandwidth_type;
+ this.encryption_required = encryption_required;
+ this.payload_types = payload_types;
+ this.local_crypto = local_crypto;
+ }
+
+ public Parameters.from_node(Module parent, StanzaNode node) throws Jingle.IqError {
+ this.parent = parent;
+ this.media = node.get_attribute("media");
+ this.ssrc = node.get_attribute("ssrc");
+ this.rtcp_mux = node.get_subnode("rtcp-mux") != null;
+ StanzaNode? encryption = node.get_subnode("encryption");
+ if (encryption != null) {
+ this.encryption_required = encryption.get_attribute_bool("required", this.encryption_required);
+ foreach (StanzaNode crypto in encryption.get_subnodes("crypto")) {
+ this.remote_cryptos.add(Crypto.parse(crypto));
+ }
+ }
+ foreach (StanzaNode payloadType in node.get_subnodes(PayloadType.NAME)) {
+ this.payload_types.add(PayloadType.parse(payloadType));
+ }
+ foreach (StanzaNode subnode in node.get_subnodes(HeaderExtension.NAME, HeaderExtension.NS_URI)) {
+ this.header_extensions.add(HeaderExtension.parse(subnode));
+ }
+ }
+
+ public async void handle_proposed_content(XmppStream stream, Jingle.Session session, Jingle.Content content) {
+ agreed_payload_type = yield parent.pick_payload_type(media, payload_types);
+ if (agreed_payload_type == null) {
+ debug("no usable payload type");
+ content.reject();
+ return;
+ }
+ // Drop unsupported header extensions
+ var iter = header_extensions.iterator();
+ while(iter.next()) {
+ if (!parent.is_header_extension_supported(media, iter.@get())) iter.remove();
+ }
+ remote_crypto = parent.pick_remote_crypto(remote_cryptos);
+ if (local_crypto == null && remote_crypto != null) {
+ local_crypto = parent.pick_local_crypto(remote_crypto);
+ }
+ if ((local_crypto == null || remote_crypto == null) && encryption_required) {
+ debug("no usable encryption, but encryption required");
+ content.reject();
+ return;
+ }
+ }
+
+ public void accept(XmppStream stream, Jingle.Session session, Jingle.Content content) {
+ debug("[%p] Jingle RTP on_accept", stream);
+
+ Jingle.DatagramConnection rtp_datagram = (Jingle.DatagramConnection) content.get_transport_connection(1);
+ Jingle.DatagramConnection rtcp_datagram = (Jingle.DatagramConnection) content.get_transport_connection(2);
+
+ ulong rtcp_ready_handler_id = 0;
+ rtcp_ready_handler_id = rtcp_datagram.notify["ready"].connect((rtcp_datagram, _) => {
+ this.stream.on_rtcp_ready();
+
+ ((Jingle.DatagramConnection)rtcp_datagram).disconnect(rtcp_ready_handler_id);
+ rtcp_ready_handler_id = 0;
+ });
+
+ ulong rtp_ready_handler_id = 0;
+ rtp_ready_handler_id = rtp_datagram.notify["ready"].connect((rtp_datagram, _) => {
+ this.stream.on_rtp_ready();
+ if (rtcp_mux) {
+ this.stream.on_rtcp_ready();
+ }
+ connection_ready();
+
+ ((Jingle.DatagramConnection)rtp_datagram).disconnect(rtp_ready_handler_id);
+ rtp_ready_handler_id = 0;
+ });
+
+ ulong session_state_handler_id = 0;
+ session_state_handler_id = session.notify["state"].connect((obj, _) => {
+ Jingle.Session session2 = (Jingle.Session) obj;
+ if (session2.state == Jingle.Session.State.ENDED) {
+ if (rtcp_ready_handler_id != 0) rtcp_datagram.disconnect(rtcp_ready_handler_id);
+ if (rtp_ready_handler_id != 0) rtp_datagram.disconnect(rtp_ready_handler_id);
+ if (session_state_handler_id != 0) {
+ session2.disconnect(session_state_handler_id);
+ }
+ }
+ });
+
+ if (remote_crypto == null || local_crypto == null) {
+ if (encryption_required) {
+ warning("Encryption required but not provided in both directions");
+ return;
+ }
+ remote_crypto = null;
+ local_crypto = null;
+ }
+ if (remote_crypto != null && local_crypto != null) {
+ var content_encryption = new Xmpp.Xep.Jingle.ContentEncryption() { encryption_ns = "", encryption_name = "SRTP", our_key=local_crypto.key, peer_key=remote_crypto.key };
+ content.encryptions[content_encryption.encryption_name] = content_encryption;
+ }
+
+ this.stream = parent.create_stream(content);
+ rtp_datagram.datagram_received.connect(this.stream.on_recv_rtp_data);
+ rtcp_datagram.datagram_received.connect(this.stream.on_recv_rtcp_data);
+ this.stream.on_send_rtp_data.connect(rtp_datagram.send_datagram);
+ this.stream.on_send_rtcp_data.connect(rtcp_datagram.send_datagram);
+ this.stream_created(this.stream);
+ this.stream.create();
+ }
+
+ public void handle_accept(XmppStream stream, Jingle.Session session, Jingle.Content content, StanzaNode description_node) {
+ rtcp_mux = description_node.get_subnode("rtcp-mux") != null;
+ Gee.List<StanzaNode> payload_type_nodes = description_node.get_subnodes("payload-type");
+ if (payload_type_nodes.size == 0) {
+ warning("Counterpart didn't include any payload types");
+ return;
+ }
+ PayloadType preferred_payload_type = PayloadType.parse(payload_type_nodes[0]);
+ if (!payload_types.contains(preferred_payload_type)) {
+ warning("Counterpart's preferred content type doesn't match any of our sent ones");
+ }
+ agreed_payload_type = preferred_payload_type;
+
+ Gee.List<StanzaNode> crypto_nodes = description_node.get_deep_subnodes("encryption", "crypto");
+ if (crypto_nodes.size == 0) {
+ debug("Counterpart didn't include any cryptos");
+ if (encryption_required) {
+ return;
+ }
+ } else {
+ Crypto preferred_crypto = Crypto.parse(crypto_nodes[0]);
+ if (local_crypto.crypto_suite != preferred_crypto.crypto_suite) {
+ warning("Counterpart's crypto suite doesn't match any of our sent ones");
+ }
+ remote_crypto = preferred_crypto;
+ }
+
+ accept(stream, session, content);
+ }
+
+ public void terminate(bool we_terminated, string? reason_name, string? reason_text) {
+ if (stream != null) parent.close_stream(stream);
+ }
+
+ public StanzaNode get_description_node() {
+ StanzaNode ret = new StanzaNode.build("description", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("media", media);
+
+ if (agreed_payload_type != null) {
+ ret.put_node(agreed_payload_type.to_xml());
+ } else {
+ foreach (PayloadType payload_type in payload_types) {
+ ret.put_node(payload_type.to_xml());
+ }
+ }
+ foreach (HeaderExtension ext in header_extensions) {
+ ret.put_node(ext.to_xml());
+ }
+ if (local_crypto != null) {
+ ret.put_node(new StanzaNode.build("encryption", NS_URI)
+ .put_node(local_crypto.to_xml()));
+ }
+ if (rtcp_mux) {
+ ret.put_node(new StanzaNode.build("rtcp-mux", NS_URI));
+ }
+ return ret;
+ }
+}
+
+public class Xmpp.Xep.JingleRtp.HeaderExtension {
+ public const string NS_URI = "urn:xmpp:jingle:apps:rtp:rtp-hdrext:0";
+ public const string NAME = "rtp-hdrext";
+
+ public uint8 id { get; private set; }
+ public string uri { get; private set; }
+
+ public HeaderExtension(uint8 id, string uri) {
+ this.id = id;
+ this.uri = uri;
+ }
+
+ public static HeaderExtension parse(StanzaNode node) {
+ return new HeaderExtension((uint8) node.get_attribute_int("id"), node.get_attribute("uri"));
+ }
+
+ public StanzaNode to_xml() {
+ return new StanzaNode.build(NAME, NS_URI)
+ .add_self_xmlns()
+ .put_attribute("id", id.to_string())
+ .put_attribute("uri", uri);
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/content_type.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/content_type.vala
new file mode 100644
index 00000000..5a8ed1b6
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/content_type.vala
@@ -0,0 +1,23 @@
+using Gee;
+using Xmpp;
+using Xmpp.Xep;
+
+public class Xmpp.Xep.JingleRtp.ContentType : Jingle.ContentType, Object {
+ public string ns_uri { get { return NS_URI; } }
+ public Jingle.TransportType required_transport_type { get { return Jingle.TransportType.DATAGRAM; } }
+ public uint8 required_components { get { return 2; /* RTP + RTCP */ } }
+
+ private Module module;
+
+ public ContentType(Module module) {
+ this.module = module;
+ }
+
+ public Jingle.ContentParameters parse_content_parameters(StanzaNode description) throws Jingle.IqError {
+ return new Parameters.from_node(module, description);
+ }
+
+ public Jingle.ContentParameters create_content_parameters(Object object) throws Jingle.IqError {
+ assert_not_reached();
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/jingle_rtp_module.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/jingle_rtp_module.vala
new file mode 100644
index 00000000..6b55cbe6
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/jingle_rtp_module.vala
@@ -0,0 +1,290 @@
+using Gee;
+using Xmpp;
+using Xmpp.Xep;
+
+namespace Xmpp.Xep.JingleRtp {
+
+public const string NS_URI = "urn:xmpp:jingle:apps:rtp:1";
+public const string NS_URI_AUDIO = "urn:xmpp:jingle:apps:rtp:audio";
+public const string NS_URI_VIDEO = "urn:xmpp:jingle:apps:rtp:video";
+
+public abstract class Module : XmppStreamModule {
+ public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0167_jingle_rtp");
+
+ private ContentType content_type;
+ public SessionInfoType session_info_type = new SessionInfoType();
+
+ protected Module() {
+ content_type = new ContentType(this);
+ }
+
+ public abstract async Gee.List<PayloadType> get_supported_payloads(string media);
+ public abstract async PayloadType? pick_payload_type(string media, Gee.List<PayloadType> payloads);
+ public abstract Crypto? generate_local_crypto();
+ public abstract Crypto? pick_remote_crypto(Gee.List<Crypto> cryptos);
+ public abstract Crypto? pick_local_crypto(Crypto? remote);
+ public abstract Stream create_stream(Jingle.Content content);
+ public abstract bool is_header_extension_supported(string media, HeaderExtension ext);
+ public abstract Gee.List<HeaderExtension> get_suggested_header_extensions(string media);
+ public abstract void close_stream(Stream stream);
+
+ public async Jingle.Session start_call(XmppStream stream, Jid receiver_full_jid, bool video, string? sid = null) throws Jingle.Error {
+
+ Jingle.Module jingle_module = stream.get_module(Jingle.Module.IDENTITY);
+
+ Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
+ if (my_jid == null) {
+ throw new Jingle.Error.GENERAL("Couldn't determine own JID");
+ }
+
+ ArrayList<Jingle.Content> contents = new ArrayList<Jingle.Content>();
+
+ // Create audio content
+ Parameters audio_content_parameters = new Parameters(this, "audio", yield get_supported_payloads("audio"));
+ audio_content_parameters.local_crypto = generate_local_crypto();
+ audio_content_parameters.header_extensions.add_all(get_suggested_header_extensions("audio"));
+ Jingle.Transport? audio_transport = yield jingle_module.select_transport(stream, content_type.required_transport_type, content_type.required_components, receiver_full_jid, Set.empty());
+ if (audio_transport == null) {
+ throw new Jingle.Error.NO_SHARED_PROTOCOLS("No suitable audio transports");
+ }
+ Jingle.TransportParameters audio_transport_params = audio_transport.create_transport_parameters(stream, content_type.required_components, my_jid, receiver_full_jid);
+ Jingle.Content audio_content = new Jingle.Content.initiate_sent("voice", Jingle.Senders.BOTH,
+ content_type, audio_content_parameters,
+ audio_transport, audio_transport_params,
+ null, null,
+ my_jid, receiver_full_jid);
+ contents.add(audio_content);
+
+ Jingle.Content? video_content = null;
+ if (video) {
+ // Create video content
+ Parameters video_content_parameters = new Parameters(this, "video", yield get_supported_payloads("video"));
+ video_content_parameters.local_crypto = generate_local_crypto();
+ video_content_parameters.header_extensions.add_all(get_suggested_header_extensions("video"));
+ Jingle.Transport? video_transport = yield stream.get_module(Jingle.Module.IDENTITY).select_transport(stream, content_type.required_transport_type, content_type.required_components, receiver_full_jid, Set.empty());
+ if (video_transport == null) {
+ throw new Jingle.Error.NO_SHARED_PROTOCOLS("No suitable video transports");
+ }
+ Jingle.TransportParameters video_transport_params = video_transport.create_transport_parameters(stream, content_type.required_components, my_jid, receiver_full_jid);
+ video_content = new Jingle.Content.initiate_sent("webcam", Jingle.Senders.BOTH,
+ content_type, video_content_parameters,
+ video_transport, video_transport_params,
+ null, null,
+ my_jid, receiver_full_jid);
+ contents.add(video_content);
+ }
+
+ // Create session
+ try {
+ Jingle.Session session = yield jingle_module.create_session(stream, contents, receiver_full_jid, sid);
+ return session;
+ } catch (Jingle.Error e) {
+ throw new Jingle.Error.GENERAL(@"Couldn't create Jingle session: $(e.message)");
+ }
+ }
+
+ public async Jingle.Content add_outgoing_video_content(XmppStream stream, Jingle.Session session) throws Jingle.Error {
+ Jid my_jid = session.local_full_jid;
+ Jid receiver_full_jid = session.peer_full_jid;
+
+ Jingle.Content? content = null;
+ foreach (Jingle.Content c in session.contents) {
+ Parameters? parameters = c.content_params as Parameters;
+ if (parameters == null) continue;
+
+ if (parameters.media == "video") {
+ content = c;
+ break;
+ }
+ }
+
+ if (content == null) {
+ // Content for video does not yet exist -> create it
+ Parameters video_content_parameters = new Parameters(this, "video", yield get_supported_payloads("video"));
+ video_content_parameters.local_crypto = generate_local_crypto();
+ video_content_parameters.header_extensions.add_all(get_suggested_header_extensions("video"));
+ Jingle.Transport? video_transport = yield stream.get_module(Jingle.Module.IDENTITY).select_transport(stream, content_type.required_transport_type, content_type.required_components, receiver_full_jid, Set.empty());
+ if (video_transport == null) {
+ throw new Jingle.Error.NO_SHARED_PROTOCOLS("No suitable video transports");
+ }
+ Jingle.TransportParameters video_transport_params = video_transport.create_transport_parameters(stream, content_type.required_components, my_jid, receiver_full_jid);
+ content = new Jingle.Content.initiate_sent("webcam",
+ session.we_initiated ? Jingle.Senders.INITIATOR : Jingle.Senders.RESPONDER,
+ content_type, video_content_parameters,
+ video_transport, video_transport_params,
+ null, null,
+ my_jid, receiver_full_jid);
+
+ session.add_content.begin(content);
+ } else {
+ // Content for video already exists -> modify senders
+ bool we_initiated = session.we_initiated;
+ Jingle.Senders want_sender = we_initiated ? Jingle.Senders.INITIATOR : Jingle.Senders.RESPONDER;
+ if (content.senders == Jingle.Senders.BOTH || content.senders == want_sender) {
+ warning("want to add video but senders is already both/target");
+ } else if (content.senders == Jingle.Senders.NONE) {
+ content.modify(want_sender);
+ } else {
+ content.modify(Jingle.Senders.BOTH);
+ }
+ }
+
+ return content;
+ }
+
+ public override void attach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI_AUDIO);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI_VIDEO);
+ stream.get_module(Jingle.Module.IDENTITY).register_content_type(content_type);
+ stream.get_module(Jingle.Module.IDENTITY).register_session_info_type(session_info_type);
+ }
+
+ public override void detach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI_AUDIO);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI_VIDEO);
+ }
+
+ public async bool is_available(XmppStream stream, Jid full_jid) {
+ bool? has_feature = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
+ if (has_feature == null || !(!)has_feature) {
+ return false;
+ }
+ return yield stream.get_module(Jingle.Module.IDENTITY).is_available(stream, content_type.required_transport_type, content_type.required_components, full_jid);
+ }
+
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+}
+
+public class Crypto {
+ public const string AES_CM_128_HMAC_SHA1_80 = "AES_CM_128_HMAC_SHA1_80";
+ public const string AES_CM_128_HMAC_SHA1_32 = "AES_CM_128_HMAC_SHA1_32";
+ public const string F8_128_HMAC_SHA1_80 = "F8_128_HMAC_SHA1_80";
+
+ public string crypto_suite { get; private set; }
+ public string key_params { get; private set; }
+ public string? session_params { get; private set; }
+ public string tag { get; private set; }
+
+ public uint8[]? key_and_salt { owned get {
+ if (!key_params.has_prefix("inline:")) return null;
+ int endIndex = key_params.index_of("|");
+ if (endIndex < 0) endIndex = key_params.length;
+ string sub = key_params.substring(7, endIndex - 7);
+ return Base64.decode(sub);
+ }}
+
+ public string? lifetime { owned get {
+ if (!key_params.has_prefix("inline:")) return null;
+ int firstIndex = key_params.index_of("|");
+ if (firstIndex < 0) return null;
+ int endIndex = key_params.index_of("|", firstIndex + 1);
+ if (endIndex < 0) {
+ if (key_params.index_of(":", firstIndex) > 0) return null; // Is MKI
+ endIndex = key_params.length;
+ }
+ return key_params.substring(firstIndex + 1, endIndex);
+ }}
+
+ public int mki { get {
+ if (!key_params.has_prefix("inline:")) return -1;
+ int firstIndex = key_params.index_of("|");
+ if (firstIndex < 0) return -1;
+ int splitIndex = key_params.index_of(":", firstIndex);
+ if (splitIndex < 0) return -1;
+ int secondIndex = key_params.index_of("|", firstIndex + 1);
+ if (secondIndex < 0) {
+ return int.parse(key_params.substring(firstIndex + 1, splitIndex));
+ } else if (splitIndex > secondIndex) {
+ return int.parse(key_params.substring(secondIndex + 1, splitIndex));
+ }
+ return -1;
+ }}
+
+ public int mki_length { get {
+ if (!key_params.has_prefix("inline:")) return -1;
+ int firstIndex = key_params.index_of("|");
+ if (firstIndex < 0) return -1;
+ int splitIndex = key_params.index_of(":", firstIndex);
+ if (splitIndex < 0) return -1;
+ int secondIndex = key_params.index_of("|", firstIndex + 1);
+ if (secondIndex < 0 || splitIndex > secondIndex) {
+ return int.parse(key_params.substring(splitIndex + 1, key_params.length));
+ }
+ return -1;
+ }}
+
+ public bool is_valid { get {
+ switch(crypto_suite) {
+ case AES_CM_128_HMAC_SHA1_80:
+ case AES_CM_128_HMAC_SHA1_32:
+ case F8_128_HMAC_SHA1_80:
+ return key_and_salt != null && key_and_salt.length == 30;
+ }
+ return false;
+ }}
+
+ public uint8[]? key { owned get {
+ uint8[]? key_and_salt = key_and_salt;
+ switch(crypto_suite) {
+ case AES_CM_128_HMAC_SHA1_80:
+ case AES_CM_128_HMAC_SHA1_32:
+ case F8_128_HMAC_SHA1_80:
+ if (key_and_salt != null && key_and_salt.length >= 16) return key_and_salt[0:16];
+ break;
+ }
+ return null;
+ }}
+
+ public uint8[]? salt { owned get {
+ uint8[]? key_and_salt = key_and_salt;
+ switch(crypto_suite) {
+ case AES_CM_128_HMAC_SHA1_80:
+ case AES_CM_128_HMAC_SHA1_32:
+ case F8_128_HMAC_SHA1_80:
+ if (key_and_salt != null && key_and_salt.length >= 30) return key_and_salt[16:30];
+ break;
+ }
+ return null;
+ }}
+
+ public static Crypto create(string crypto_suite, uint8[] key_and_salt, string? session_params = null, string tag = "1") {
+ Crypto crypto = new Crypto();
+ crypto.crypto_suite = crypto_suite;
+ crypto.key_params = "inline:" + Base64.encode(key_and_salt);
+ crypto.session_params = session_params;
+ crypto.tag = tag;
+ return crypto;
+ }
+
+ public Crypto rekey(uint8[] key_and_salt) {
+ Crypto crypto = new Crypto();
+ crypto.crypto_suite = crypto_suite;
+ crypto.key_params = "inline:" + Base64.encode(key_and_salt);
+ crypto.session_params = session_params;
+ crypto.tag = tag;
+ return crypto;
+ }
+
+ public static Crypto parse(StanzaNode node) {
+ Crypto crypto = new Crypto();
+ crypto.crypto_suite = node.get_attribute("crypto-suite");
+ crypto.key_params = node.get_attribute("key-params");
+ crypto.session_params = node.get_attribute("session-params");
+ crypto.tag = node.get_attribute("tag");
+ return crypto;
+ }
+
+ public StanzaNode to_xml() {
+ StanzaNode node = new StanzaNode.build("crypto", NS_URI)
+ .put_attribute("crypto-suite", crypto_suite)
+ .put_attribute("key-params", key_params)
+ .put_attribute("tag", tag);
+ if (session_params != null) node.put_attribute("session-params", session_params);
+ return node;
+ }
+}
+
+}
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/payload_type.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/payload_type.vala
new file mode 100644
index 00000000..faba38c9
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/payload_type.vala
@@ -0,0 +1,99 @@
+using Gee;
+using Xmpp;
+using Xmpp.Xep;
+
+public class Xmpp.Xep.JingleRtp.PayloadType {
+ public const string NAME = "payload-type";
+
+ public uint8 id { get; set; }
+ public string? name { get; set; }
+ public uint8 channels { get; set; default = 1; }
+ public uint32 clockrate { get; set; }
+ public uint32 maxptime { get; set; }
+ public uint32 ptime { get; set; }
+ public Map<string, string> parameters = new HashMap<string, string>();
+ public Gee.List<RtcpFeedback> rtcp_fbs = new ArrayList<RtcpFeedback>();
+
+ public static PayloadType parse(StanzaNode node) {
+ PayloadType payloadType = new PayloadType();
+ payloadType.channels = (uint8) node.get_attribute_uint("channels", payloadType.channels);
+ payloadType.clockrate = node.get_attribute_uint("clockrate");
+ payloadType.id = (uint8) node.get_attribute_uint("id");
+ payloadType.maxptime = node.get_attribute_uint("maxptime");
+ payloadType.name = node.get_attribute("name");
+ payloadType.ptime = node.get_attribute_uint("ptime");
+ foreach (StanzaNode parameter in node.get_subnodes("parameter")) {
+ payloadType.parameters[parameter.get_attribute("name")] = parameter.get_attribute("value");
+ }
+ foreach (StanzaNode subnode in node.get_subnodes(RtcpFeedback.NAME, RtcpFeedback.NS_URI)) {
+ payloadType.rtcp_fbs.add(RtcpFeedback.parse(subnode));
+ }
+ return payloadType;
+ }
+
+ public StanzaNode to_xml() {
+ StanzaNode node = new StanzaNode.build(NAME, NS_URI)
+ .put_attribute("id", id.to_string());
+ if (channels != 1) node.put_attribute("channels", channels.to_string());
+ if (clockrate != 0) node.put_attribute("clockrate", clockrate.to_string());
+ if (maxptime != 0) node.put_attribute("maxptime", maxptime.to_string());
+ if (name != null) node.put_attribute("name", name);
+ if (ptime != 0) node.put_attribute("ptime", ptime.to_string());
+ foreach (string parameter in parameters.keys) {
+ node.put_node(new StanzaNode.build("parameter", NS_URI)
+ .put_attribute("name", parameter)
+ .put_attribute("value", parameters[parameter]));
+ }
+ foreach (RtcpFeedback rtcp_fb in rtcp_fbs) {
+ node.put_node(rtcp_fb.to_xml());
+ }
+ return node;
+ }
+
+ public PayloadType clone() {
+ PayloadType clone = new PayloadType();
+ clone.id = id;
+ clone.name = name;
+ clone.channels = channels;
+ clone.clockrate = clockrate;
+ clone.maxptime = maxptime;
+ clone.ptime = ptime;
+ clone.parameters.set_all(parameters);
+ clone.rtcp_fbs.add_all(rtcp_fbs);
+ return clone;
+ }
+
+ public static bool equals_func(PayloadType a, PayloadType b) {
+ return a.id == b.id &&
+ a.name == b.name &&
+ a.channels == b.channels &&
+ a.clockrate == b.clockrate &&
+ a.maxptime == b.maxptime &&
+ a.ptime == b.ptime;
+ }
+}
+
+public class Xmpp.Xep.JingleRtp.RtcpFeedback {
+ public const string NS_URI = "urn:xmpp:jingle:apps:rtp:rtcp-fb:0";
+ public const string NAME = "rtcp-fb";
+
+ public string type_ { get; private set; }
+ public string? subtype { get; private set; }
+
+ public RtcpFeedback(string type, string? subtype = null) {
+ this.type_ = type;
+ this.subtype = subtype;
+ }
+
+ public static RtcpFeedback parse(StanzaNode node) {
+ return new RtcpFeedback(node.get_attribute("type"), node.get_attribute("subtype"));
+ }
+
+ public StanzaNode to_xml() {
+ StanzaNode node = new StanzaNode.build(NAME, NS_URI)
+ .add_self_xmlns()
+ .put_attribute("type", type_);
+ if (subtype != null) node.put_attribute("subtype", subtype);
+ return node;
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/session_info_type.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/session_info_type.vala
new file mode 100644
index 00000000..32cd9016
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/session_info_type.vala
@@ -0,0 +1,67 @@
+using Gee;
+using Xmpp;
+using Xmpp.Xep;
+
+namespace Xmpp.Xep.JingleRtp {
+
+ public enum CallSessionInfo {
+ ACTIVE,
+ HOLD,
+ UNHOLD,
+ MUTE,
+ UNMUTE,
+ RINGING
+ }
+
+ public class SessionInfoType : Jingle.SessionInfoNs, Object {
+ public const string NS_URI = "urn:xmpp:jingle:apps:rtp:info:1";
+ public string ns_uri { get { return NS_URI; } }
+
+ public signal void info_received(Jingle.Session session, CallSessionInfo info);
+ public signal void mute_update_received(Jingle.Session session, bool mute, string name);
+
+ public void handle_content_session_info(XmppStream stream, Jingle.Session session, StanzaNode info, Iq.Stanza iq) throws Jingle.IqError {
+ switch (info.name) {
+ case "active":
+ info_received(session, CallSessionInfo.ACTIVE);
+ break;
+ case "hold":
+ info_received(session, CallSessionInfo.HOLD);
+ break;
+ case "unhold":
+ info_received(session, CallSessionInfo.UNHOLD);
+ break;
+ case "mute":
+ string? name = info.get_attribute("name");
+ mute_update_received(session, true, name);
+ info_received(session, CallSessionInfo.MUTE);
+ break;
+ case "unmute":
+ string? name = info.get_attribute("name");
+ mute_update_received(session, false, name);
+ info_received(session, CallSessionInfo.UNMUTE);
+ break;
+ case "ringing":
+ info_received(session, CallSessionInfo.RINGING);
+ break;
+ }
+ }
+
+ public void send_mute(Jingle.Session session, bool mute, string media) {
+ string node_name = mute ? "mute" : "unmute";
+
+ foreach (Jingle.Content content in session.contents) {
+ Parameters? parameters = content.content_params as Parameters;
+ if (parameters != null && parameters.media == media) {
+ StanzaNode session_info_content = new StanzaNode.build(node_name, NS_URI).add_self_xmlns().put_attribute("name", content.content_name);
+ session.send_session_info(session_info_content);
+ }
+ }
+ }
+
+ public void send_ringing(Jingle.Session session) {
+ StanzaNode session_info_content = new StanzaNode.build("ringing", NS_URI).add_self_xmlns();
+ session.send_session_info(session_info_content);
+ }
+ }
+}
diff --git a/xmpp-vala/src/module/xep/0167_jingle_rtp/stream.vala b/xmpp-vala/src/module/xep/0167_jingle_rtp/stream.vala
new file mode 100644
index 00000000..65be8a0a
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0167_jingle_rtp/stream.vala
@@ -0,0 +1,76 @@
+public abstract class Xmpp.Xep.JingleRtp.Stream : Object {
+
+ public Jingle.Content content { get; protected set; }
+
+ public string name { get {
+ return content.content_name;
+ }}
+ public string? media { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).media;
+ }
+ return null;
+ }}
+ public JingleRtp.PayloadType? payload_type { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).agreed_payload_type;
+ }
+ return null;
+ }}
+ public JingleRtp.Crypto? local_crypto { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).local_crypto;
+ }
+ return null;
+ }}
+ public JingleRtp.Crypto? remote_crypto { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).remote_crypto;
+ }
+ return null;
+ }}
+ public Gee.List<JingleRtp.HeaderExtension>? header_extensions { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).header_extensions;
+ }
+ return null;
+ }}
+ public bool sending { get {
+ return content.session.senders_include_us(content.senders);
+ }}
+ public bool receiving { get {
+ return content.session.senders_include_counterpart(content.senders);
+ }}
+ public bool rtcp_mux { get {
+ var content_params = content.content_params;
+ if (content_params is Parameters) {
+ return ((Parameters)content_params).rtcp_mux;
+ }
+ return false;
+ }}
+
+ protected Stream(Jingle.Content content) {
+ this.content = content;
+ }
+
+ public signal void on_send_rtp_data(Bytes bytes);
+ public signal void on_send_rtcp_data(Bytes bytes);
+
+ public abstract void on_recv_rtp_data(Bytes bytes);
+ public abstract void on_recv_rtcp_data(Bytes bytes);
+
+ public abstract void on_rtp_ready();
+ public abstract void on_rtcp_ready();
+
+ public abstract void create();
+ public abstract void destroy();
+
+ public string to_string() {
+ return @"$name/$media stream in $(content.session.sid)";
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0176_jingle_ice_udp/candidate.vala b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/candidate.vala
new file mode 100644
index 00000000..bcb3aa80
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/candidate.vala
@@ -0,0 +1,93 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+public class Xmpp.Xep.JingleIceUdp.Candidate {
+ public uint8 component;
+ public string foundation;
+ public uint8 generation;
+ public string id;
+ public string ip;
+ public uint8 network;
+ public uint16 port;
+ public uint32 priority;
+ public string protocol;
+ public string? rel_addr;
+ public uint16 rel_port;
+ public Type type_;
+
+ public static Candidate parse(StanzaNode node) throws Jingle.IqError {
+ Candidate candidate = new Candidate();
+ candidate.component = (uint8) node.get_attribute_uint("component");
+ candidate.foundation = (string) node.get_attribute("foundation");
+ candidate.generation = (uint8) node.get_attribute_uint("generation");
+ candidate.id = node.get_attribute("id");
+ candidate.ip = node.get_attribute("ip");
+ candidate.network = (uint8) node.get_attribute_uint("network");
+ candidate.port = (uint16) node.get_attribute_uint("port");
+ candidate.priority = (uint32) node.get_attribute_uint("priority");
+ candidate.protocol = node.get_attribute("protocol");
+ candidate.rel_addr = node.get_attribute("rel-addr");
+ candidate.rel_port = (uint16) node.get_attribute_uint("rel-port");
+ candidate.type_ = Type.parse(node.get_attribute("type"));
+ return candidate;
+ }
+
+ public enum Type {
+ HOST, PRFLX, RELAY, SRFLX;
+ public static Type parse(string str) throws Jingle.IqError {
+ switch (str) {
+ case "host": return HOST;
+ case "prflx": return PRFLX;
+ case "relay": return RELAY;
+ case "srflx": return SRFLX;
+ default: throw new Jingle.IqError.BAD_REQUEST("Illegal ICE-UDP candidate type");
+ }
+ }
+ public string to_string() {
+ switch (this) {
+ case HOST: return "host";
+ case PRFLX: return "prflx";
+ case RELAY: return "relay";
+ case SRFLX: return "srflx";
+ default: assert_not_reached();
+ }
+ }
+ }
+
+ public StanzaNode to_xml() {
+ StanzaNode node = new StanzaNode.build("candidate", NS_URI)
+ .put_attribute("component", component.to_string())
+ .put_attribute("foundation", foundation.to_string())
+ .put_attribute("generation", generation.to_string())
+ .put_attribute("id", id)
+ .put_attribute("ip", ip)
+ .put_attribute("network", network.to_string())
+ .put_attribute("port", port.to_string())
+ .put_attribute("priority", priority.to_string())
+ .put_attribute("protocol", protocol)
+ .put_attribute("type", type_.to_string());
+ if (rel_addr != null) node.put_attribute("rel-addr", rel_addr);
+ if (rel_port != 0) node.put_attribute("rel-port", rel_port.to_string());
+ return node;
+ }
+
+ public bool equals(Candidate c) {
+ return equals_func(this, c);
+ }
+
+ public static bool equals_func(Candidate c1, Candidate c2) {
+ return c1.component == c2.component &&
+ c1.foundation == c2.foundation &&
+ c1.generation == c2.generation &&
+ c1.id == c2.id &&
+ c1.ip == c2.ip &&
+ c1.network == c2.network &&
+ c1.port == c2.port &&
+ c1.priority == c2.priority &&
+ c1.protocol == c2.protocol &&
+ c1.rel_addr == c2.rel_addr &&
+ c1.rel_port == c2.rel_port &&
+ c1.type_ == c2.type_;
+ }
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0176_jingle_ice_udp/jingle_ice_udp_module.vala b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/jingle_ice_udp_module.vala
new file mode 100644
index 00000000..87c010dd
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/jingle_ice_udp_module.vala
@@ -0,0 +1,39 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.JingleIceUdp {
+
+public const string NS_URI = "urn:xmpp:jingle:transports:ice-udp:1";
+public const string DTLS_NS_URI = "urn:xmpp:jingle:apps:dtls:0";
+
+public abstract class Module : XmppStreamModule, Jingle.Transport {
+ public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0176_jingle_ice_udp");
+
+ public override void attach(XmppStream stream) {
+ stream.get_module(Jingle.Module.IDENTITY).register_transport(this);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, DTLS_NS_URI);
+ }
+ public override void detach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, DTLS_NS_URI);
+ }
+
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+
+ public async bool is_transport_available(XmppStream stream, uint8 components, Jid full_jid) {
+ return yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
+ }
+
+ public string ns_uri{ get { return NS_URI; } }
+ public Jingle.TransportType type_{ get { return Jingle.TransportType.DATAGRAM; } }
+ public int priority { get { return 1; } }
+
+ public abstract Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid);
+
+ public abstract Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError;
+}
+
+} \ No newline at end of file
diff --git a/xmpp-vala/src/module/xep/0176_jingle_ice_udp/transport_parameters.vala b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/transport_parameters.vala
new file mode 100644
index 00000000..07b599ee
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0176_jingle_ice_udp/transport_parameters.vala
@@ -0,0 +1,167 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+public abstract class Xmpp.Xep.JingleIceUdp.IceUdpTransportParameters : Jingle.TransportParameters, Object {
+ public string ns_uri { get { return NS_URI; } }
+ public string remote_pwd { get; private set; }
+ public string remote_ufrag { get; private set; }
+ public string local_pwd { get; private set; }
+ public string local_ufrag { get; private set; }
+
+ public ConcurrentList<Candidate> local_candidates = new ConcurrentList<Candidate>(Candidate.equals_func);
+ public ConcurrentList<Candidate> unsent_local_candidates = new ConcurrentList<Candidate>(Candidate.equals_func);
+ public Gee.List<Candidate> remote_candidates = new ArrayList<Candidate>(Candidate.equals_func);
+
+ public uint8[]? own_fingerprint = null;
+ public string? own_setup = null;
+ public uint8[]? peer_fingerprint = null;
+ public string? peer_fp_algo = null;
+ public string? peer_setup = null;
+
+ public Jid local_full_jid { get; private set; }
+ public Jid peer_full_jid { get; private set; }
+ private uint8 components_;
+ public uint8 components { get { return components_; } }
+
+ public bool incoming { get; private set; default = false; }
+ private bool connection_created = false;
+
+ protected weak Jingle.Content? content = null;
+
+ protected IceUdpTransportParameters(uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode? node = null) {
+ this.components_ = components;
+ this.local_full_jid = local_full_jid;
+ this.peer_full_jid = peer_full_jid;
+ if (node != null) {
+ incoming = true;
+ remote_pwd = node.get_attribute("pwd");
+ remote_ufrag = node.get_attribute("ufrag");
+ foreach (StanzaNode candidateNode in node.get_subnodes("candidate")) {
+ remote_candidates.add(Candidate.parse(candidateNode));
+ }
+
+ StanzaNode? fingerprint_node = node.get_subnode("fingerprint", DTLS_NS_URI);
+ if (fingerprint_node != null) {
+ peer_fingerprint = fingerprint_to_bytes(fingerprint_node.get_string_content());
+ peer_fp_algo = fingerprint_node.get_attribute("hash");
+ peer_setup = fingerprint_node.get_attribute("setup");
+ }
+ }
+ }
+
+ public void init(string ufrag, string pwd) {
+ this.local_ufrag = ufrag;
+ this.local_pwd = pwd;
+ debug("Initialized for %s", pwd);
+ }
+
+ public void set_content(Jingle.Content content) {
+ this.content = content;
+ this.content.weak_ref(unset_content);
+ }
+
+ public void unset_content() {
+ this.content = null;
+ }
+
+ public StanzaNode to_transport_stanza_node(string action_type) {
+ var node = new StanzaNode.build("transport", NS_URI)
+ .add_self_xmlns()
+ .put_attribute("ufrag", local_ufrag)
+ .put_attribute("pwd", local_pwd);
+
+ if (own_fingerprint != null && action_type != "transport-info") {
+ var fingerprint_node = new StanzaNode.build("fingerprint", DTLS_NS_URI)
+ .add_self_xmlns()
+ .put_attribute("hash", "sha-256")
+ .put_node(new StanzaNode.text(format_fingerprint(own_fingerprint)));
+ fingerprint_node.put_attribute("setup", own_setup);
+ node.put_node(fingerprint_node);
+ }
+
+ foreach (Candidate candidate in unsent_local_candidates) {
+ node.put_node(candidate.to_xml());
+ }
+ unsent_local_candidates.clear();
+ return node;
+ }
+
+ public virtual void handle_transport_accept(StanzaNode node) throws Jingle.IqError {
+ string? pwd = node.get_attribute("pwd");
+ string? ufrag = node.get_attribute("ufrag");
+ if (pwd != null) remote_pwd = pwd;
+ if (ufrag != null) remote_ufrag = ufrag;
+ foreach (StanzaNode candidateNode in node.get_subnodes("candidate")) {
+ remote_candidates.add(Candidate.parse(candidateNode));
+ }
+
+ StanzaNode? fingerprint_node = node.get_subnode("fingerprint", DTLS_NS_URI);
+ if (fingerprint_node != null) {
+ peer_fingerprint = fingerprint_to_bytes(fingerprint_node.get_string_content());
+ peer_fp_algo = fingerprint_node.get_attribute("hash");
+ peer_setup = fingerprint_node.get_attribute("setup");
+ }
+ }
+
+ public virtual void handle_transport_info(StanzaNode node) throws Jingle.IqError {
+ string? pwd = node.get_attribute("pwd");
+ string? ufrag = node.get_attribute("ufrag");
+ if (pwd != null) remote_pwd = pwd;
+ if (ufrag != null) remote_ufrag = ufrag;
+ foreach (StanzaNode candidateNode in node.get_subnodes("candidate")) {
+ remote_candidates.add(Candidate.parse(candidateNode));
+ }
+ }
+
+ public virtual void create_transport_connection(XmppStream stream, Jingle.Content content) {
+ connection_created = true;
+
+ check_send_transport_info();
+ }
+
+ public void add_local_candidate_threadsafe(Candidate candidate) {
+ if (local_candidates.contains(candidate)) return;
+
+ debug("New local candidate %u %s %s:%u", candidate.component, candidate.type_.to_string(), candidate.ip, candidate.port);
+ unsent_local_candidates.add(candidate);
+ local_candidates.add(candidate);
+
+ if (this.content != null && (this.connection_created || !this.incoming)) {
+ Timeout.add(50, () => {
+ check_send_transport_info();
+ return false;
+ });
+ }
+ }
+
+ private void check_send_transport_info() {
+ if (this.content != null && unsent_local_candidates.size > 0) {
+ content.send_transport_info(to_transport_stanza_node("transport-info"));
+ }
+ }
+
+ private string format_fingerprint(uint8[] fingerprint) {
+ var sb = new StringBuilder();
+ for (int i = 0; i < fingerprint.length; i++) {
+ sb.append("%02x".printf(fingerprint[i]));
+ if (i < fingerprint.length - 1) {
+ sb.append(":");
+ }
+ }
+ return sb.str;
+ }
+
+ private uint8[]? fingerprint_to_bytes(string? fingerprint_) {
+ if (fingerprint_ == null) return null;
+
+ string fingerprint = fingerprint_.replace(":", "").up();
+
+ uint8[] bin = new uint8[fingerprint.length / 2];
+ const string HEX = "0123456789ABCDEF";
+ for (int i = 0; i < fingerprint.length / 2; i++) {
+ bin[i] = (uint8) (HEX.index_of_char(fingerprint[i*2]) << 4) | HEX.index_of_char(fingerprint[i*2+1]);
+ }
+ return bin;
+ }
+}
diff --git a/xmpp-vala/src/module/xep/0199_ping.vala b/xmpp-vala/src/module/xep/0199_ping.vala
index f3e68660..0b31011f 100644
--- a/xmpp-vala/src/module/xep/0199_ping.vala
+++ b/xmpp-vala/src/module/xep/0199_ping.vala
@@ -23,7 +23,7 @@ namespace Xmpp.Xep.Ping {
}
public async void on_iq_get(XmppStream stream, Iq.Stanza iq) {
- yield stream.get_module(Iq.Module.IDENTITY).send_iq_async(stream, new Iq.Stanza.result(iq));
+ stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
}
public override string get_ns() { return NS_URI; }
diff --git a/xmpp-vala/src/module/xep/0215_external_service_discovery.vala b/xmpp-vala/src/module/xep/0215_external_service_discovery.vala
new file mode 100644
index 00000000..07c3f71c
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0215_external_service_discovery.vala
@@ -0,0 +1,49 @@
+using Gee;
+
+namespace Xmpp.Xep.ExternalServiceDiscovery {
+
+ private const string NS_URI = "urn:xmpp:extdisco:2";
+
+ public static async Gee.List<Service> request_services(XmppStream stream) {
+ Iq.Stanza request_iq = new Iq.Stanza.get((new StanzaNode.build("services", NS_URI)).add_self_xmlns()) { to=stream.remote_name };
+ Iq.Stanza response_iq = yield stream.get_module(Iq.Module.IDENTITY).send_iq_async(stream, request_iq);
+
+ ArrayList<Service> ret = new ArrayList<Service>();
+ if (response_iq.is_error()) return ret;
+ StanzaNode? services_node = response_iq.stanza.get_subnode("services", NS_URI);
+ if (services_node == null) return ret;
+
+ Gee.List<StanzaNode> service_nodes = services_node.get_subnodes("service", NS_URI);
+ foreach (StanzaNode service_node in service_nodes) {
+ Service service = new Service();
+ service.host = service_node.get_attribute("host", NS_URI);
+ string? port_str = service_node.get_attribute("port", NS_URI);
+ if (port_str != null) service.port = int.parse(port_str);
+ service.ty = service_node.get_attribute("type", NS_URI);
+
+ if (service.host == null || service.ty == null || port_str == null) continue;
+
+ service.username = service_node.get_attribute("username", NS_URI);
+ service.password = service_node.get_attribute("password", NS_URI);
+ service.transport = service_node.get_attribute("transport", NS_URI);
+ service.name = service_node.get_attribute("name", NS_URI);
+ string? restricted_str = service_node.get_attribute("restricted", NS_URI);
+ if (restricted_str != null) service.restricted = bool.parse(restricted_str);
+ ret.add(service);
+ }
+ return ret;
+ }
+
+ public class Service {
+ public string host { get; set; }
+ public uint port { get; set; }
+ public string ty { get; set; }
+
+ public string username { get; set; }
+ public string password { get; set; }
+
+ public string transport { get; set; }
+ public string name { get; set; }
+ public bool restricted { get; set; }
+ }
+}
diff --git a/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala b/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala
index 1c0323be..4581019f 100644
--- a/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala
+++ b/xmpp-vala/src/module/xep/0234_jingle_file_transfer.vala
@@ -7,50 +7,42 @@ namespace Xmpp.Xep.JingleFileTransfer {
private const string NS_URI = "urn:xmpp:jingle:apps:file-transfer:5";
public class Module : Jingle.ContentType, XmppStreamModule {
+
+ public signal void file_incoming(XmppStream stream, FileTransfer file_transfer);
+
public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0234_jingle_file_transfer");
+ public SessionInfoType session_info_type = new SessionInfoType();
public override void attach(XmppStream stream) {
stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
stream.get_module(Jingle.Module.IDENTITY).register_content_type(this);
+ stream.get_module(Jingle.Module.IDENTITY).register_session_info_type(session_info_type);
}
public override void detach(XmppStream stream) {
stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
}
- public string content_type_ns_uri() {
- return NS_URI;
- }
- public Jingle.TransportType content_type_transport_type() {
- return Jingle.TransportType.STREAMING;
- }
+ public string ns_uri { get { return NS_URI; } }
+ public Jingle.TransportType required_transport_type { get { return Jingle.TransportType.STREAMING; } }
+ public uint8 required_components { get { return 1; } }
+
public Jingle.ContentParameters parse_content_parameters(StanzaNode description) throws Jingle.IqError {
return Parameters.parse(this, description);
}
- public void handle_content_session_info(XmppStream stream, Jingle.Session session, StanzaNode info, Iq.Stanza iq) throws Jingle.IqError {
- switch (info.name) {
- case "received":
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- break;
- case "checksum":
- // TODO(hrxi): handle hash
- stream.get_module(Iq.Module.IDENTITY).send_iq(stream, new Iq.Stanza.result(iq));
- break;
- default:
- throw new Jingle.IqError.UNSUPPORTED_INFO(@"unsupported file transfer info $(info.name)");
- }
- }
- public signal void file_incoming(XmppStream stream, FileTransfer file_transfer);
+ public Jingle.ContentParameters create_content_parameters(Object object) throws Jingle.IqError {
+ assert_not_reached();
+ }
public async bool is_available(XmppStream stream, Jid full_jid) {
bool? has_feature = yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
if (has_feature == null || !(!)has_feature) {
return false;
}
- return yield stream.get_module(Jingle.Module.IDENTITY).is_available(stream, Jingle.TransportType.STREAMING, full_jid);
+ return yield stream.get_module(Jingle.Module.IDENTITY).is_available(stream, required_transport_type, required_components, full_jid);
}
- public async void offer_file_stream(XmppStream stream, Jid receiver_full_jid, InputStream input_stream, string basename, int64 size, string? precondition_name = null, Object? precondition_options = null) throws IOError {
+ public async void offer_file_stream(XmppStream stream, Jid receiver_full_jid, InputStream input_stream, string basename, int64 size, string? precondition_name = null, Object? precondition_options = null) throws Jingle.Error {
StanzaNode file_node;
StanzaNode description = new StanzaNode.build("description", NS_URI)
.add_self_xmlns()
@@ -64,25 +56,83 @@ public class Module : Jingle.ContentType, XmppStreamModule {
warning("Sending file %s without size, likely going to cause problems down the road...", basename);
}
- Jingle.Session session;
- try {
- session = yield stream.get_module(Jingle.Module.IDENTITY)
- .create_session(stream, Jingle.TransportType.STREAMING, receiver_full_jid, Jingle.Senders.INITIATOR, "a-file-offer", description, precondition_name, precondition_options); // TODO(hrxi): Why "a-file-offer"?
- } catch (Jingle.Error e) {
- throw new IOError.FAILED(@"couldn't create Jingle session: $(e.message)");
+ Parameters parameters = Parameters.parse(this, description);
+
+ Jingle.Module jingle_module = stream.get_module(Jingle.Module.IDENTITY);
+
+ Jingle.Transport? transport = yield jingle_module.select_transport(stream, required_transport_type, required_components, receiver_full_jid, Set.empty());
+ if (transport == null) {
+ throw new Jingle.Error.NO_SHARED_PROTOCOLS("No suitable transports");
+ }
+ Jingle.SecurityPrecondition? precondition = jingle_module.get_security_precondition(precondition_name);
+ if (precondition_name != null && precondition == null) {
+ throw new Jingle.Error.UNSUPPORTED_SECURITY("No suitable security precondiiton found");
+ }
+ Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
+ if (my_jid == null) {
+ throw new Jingle.Error.GENERAL("Couldn't determine own JID");
}
- session.terminate_on_connection_close = false;
+ Jingle.TransportParameters transport_params = transport.create_transport_parameters(stream, required_components, my_jid, receiver_full_jid);
+ Jingle.SecurityParameters? security_params = precondition != null ? precondition.create_security_parameters(stream, my_jid, receiver_full_jid, precondition_options) : null;
- yield session.conn.input_stream.close_async();
+ Jingle.Content content = new Jingle.Content.initiate_sent("a-file-offer", Jingle.Senders.INITIATOR,
+ this, parameters,
+ transport, transport_params,
+ precondition, security_params,
+ my_jid, receiver_full_jid);
- // TODO(hrxi): catch errors
- yield session.conn.output_stream.splice_async(input_stream, OutputStreamSpliceFlags.CLOSE_SOURCE|OutputStreamSpliceFlags.CLOSE_TARGET);
+ ArrayList<Jingle.Content> contents = new ArrayList<Jingle.Content>();
+ contents.add(content);
+
+
+ Jingle.Session? session = null;
+ try {
+ session = yield jingle_module.create_session(stream, contents, receiver_full_jid);
+
+ // Wait for the counterpart to accept our offer
+ ulong content_notify_id = 0;
+ content_notify_id = content.notify["state"].connect(() => {
+ if (content.state == Jingle.Content.State.ACCEPTED) {
+ Idle.add(offer_file_stream.callback);
+ content.disconnect(content_notify_id);
+ }
+ });
+ yield;
+
+ // Send the file data
+ Jingle.StreamingConnection connection = content.component_connections.values.to_array()[0] as Jingle.StreamingConnection;
+ IOStream io_stream = yield connection.stream.wait_async();
+ yield io_stream.input_stream.close_async();
+ yield io_stream.output_stream.splice_async(input_stream, OutputStreamSpliceFlags.CLOSE_SOURCE|OutputStreamSpliceFlags.CLOSE_TARGET);
+ yield connection.terminate(true);
+ } catch (Jingle.Error e) {
+ session.terminate(Jingle.ReasonElement.FAILED_TRANSPORT, e.message, e.message);
+ throw new Jingle.Error.GENERAL(@"couldn't create Jingle session: $(e.message)");
+ }
}
public override string get_ns() { return NS_URI; }
public override string get_id() { return IDENTITY.id; }
}
+public class SessionInfoType : Jingle.SessionInfoNs, Object {
+
+ public string ns_uri { get { return NS_URI; } }
+
+ public void handle_content_session_info(XmppStream stream, Jingle.Session session, StanzaNode info, Iq.Stanza iq) throws Jingle.IqError {
+ switch (info.name) {
+ case "received":
+ break;
+ case "checksum":
+ // TODO(hrxi): handle hash
+ break;
+ default:
+ throw new Jingle.IqError.UNSUPPORTED_INFO(@"unsupported file transfer info $(info.name)");
+ }
+ }
+
+}
+
public class Parameters : Jingle.ContentParameters, Object {
Module parent;
@@ -127,24 +177,42 @@ public class Parameters : Jingle.ContentParameters, Object {
return new Parameters(parent, description, media_type, name, size);
}
- public void on_session_initiate(XmppStream stream, Jingle.Session session) {
- parent.file_incoming(stream, new FileTransfer(session, this));
+ public StanzaNode get_description_node() {
+ return original_description;
+ }
+
+ public async void handle_proposed_content(XmppStream stream, Jingle.Session session, Jingle.Content content) {
+ parent.file_incoming(stream, new FileTransfer(session, content, this));
}
+
+ public void modify(XmppStream stream, Jingle.Session session, Jingle.Content content, Jingle.Senders senders) { }
+
+ public void accept(XmppStream stream, Jingle.Session session, Jingle.Content content) { }
+
+ public void handle_accept(XmppStream stream, Jingle.Session session, Jingle.Content content, StanzaNode description_node) { }
+
+ public void terminate(bool we_terminated, string? reason_name, string? reason_text) { }
}
// Does nothing except wrapping an input stream to signal EOF after reading
// `max_size` bytes.
private class FileTransferInputStream : InputStream {
+
+ public signal void closed();
+
InputStream inner;
int64 remaining_size;
+
public FileTransferInputStream(InputStream inner, int64 max_size) {
this.inner = inner;
this.remaining_size = max_size;
}
+
private ssize_t update_remaining(ssize_t read) {
this.remaining_size -= read;
return read;
}
+
public override ssize_t read(uint8[] buffer_, Cancellable? cancellable = null) throws IOError {
unowned uint8[] buffer = buffer_;
if (remaining_size <= 0) {
@@ -155,6 +223,7 @@ private class FileTransferInputStream : InputStream {
}
return update_remaining(inner.read(buffer, cancellable));
}
+
public override async ssize_t read_async(uint8[]? buffer_, int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
unowned uint8[] buffer = buffer_;
if (remaining_size <= 0) {
@@ -165,16 +234,21 @@ private class FileTransferInputStream : InputStream {
}
return update_remaining(yield inner.read_async(buffer, io_priority, cancellable));
}
+
public override bool close(Cancellable? cancellable = null) throws IOError {
+ closed();
return inner.close(cancellable);
}
+
public override async bool close_async(int io_priority = GLib.Priority.DEFAULT, Cancellable? cancellable = null) throws IOError {
+ closed();
return yield inner.close_async(io_priority, cancellable);
}
}
public class FileTransfer : Object {
Jingle.Session session;
+ Jingle.Content content;
Parameters parameters;
public Jid peer { get { return session.peer_full_jid; } }
@@ -184,19 +258,33 @@ public class FileTransfer : Object {
public InputStream? stream { get; private set; }
- public FileTransfer(Jingle.Session session, Parameters parameters) {
+ public FileTransfer(Jingle.Session session, Jingle.Content content, Parameters parameters) {
this.session = session;
+ this.content = content;
this.parameters = parameters;
- this.stream = new FileTransferInputStream(session.conn.input_stream, size);
}
- public void accept(XmppStream stream) throws IOError {
- session.accept(stream, parameters.original_description);
- session.conn.output_stream.close();
+ public async void accept(XmppStream stream) throws IOError {
+ content.accept();
+
+ Jingle.StreamingConnection connection = content.component_connections.values.to_array()[0] as Jingle.StreamingConnection;
+ try {
+ IOStream io_stream = yield connection.stream.wait_async();
+ FileTransferInputStream ft_stream = new FileTransferInputStream(io_stream.input_stream, size);
+ io_stream.output_stream.close();
+ ft_stream.closed.connect(() => {
+ session.terminate(Jingle.ReasonElement.SUCCESS, null, null);
+ });
+ this.stream = ft_stream;
+ } catch (FutureError.EXCEPTION e) {
+ warning("Error accepting Jingle file-transfer: %s", connection.stream.exception.message);
+ } catch (FutureError e) {
+ warning("FutureError accepting Jingle file-transfer: %s", e.message);
+ }
}
public void reject(XmppStream stream) {
- session.reject(stream);
+ content.reject();
}
}
diff --git a/xmpp-vala/src/module/xep/0260_jingle_socks5_bytestreams.vala b/xmpp-vala/src/module/xep/0260_jingle_socks5_bytestreams.vala
index ea7ef375..47c243e8 100644
--- a/xmpp-vala/src/module/xep/0260_jingle_socks5_bytestreams.vala
+++ b/xmpp-vala/src/module/xep/0260_jingle_socks5_bytestreams.vala
@@ -5,6 +5,7 @@ using Xmpp.Xep;
namespace Xmpp.Xep.JingleSocks5Bytestreams {
private const string NS_URI = "urn:xmpp:jingle:transports:s5b:1";
+private const int NEGOTIATION_TIMEOUT = 3;
public class Module : Jingle.Transport, XmppStreamModule {
public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0260_jingle_socks5_bytestreams");
@@ -20,20 +21,15 @@ public class Module : Jingle.Transport, XmppStreamModule {
public override string get_ns() { return NS_URI; }
public override string get_id() { return IDENTITY.id; }
- public async bool is_transport_available(XmppStream stream, Jid full_jid) {
- return yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
+ public async bool is_transport_available(XmppStream stream, uint8 components, Jid full_jid) {
+ return components == 1 && yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
}
- public string transport_ns_uri() {
- return NS_URI;
- }
- public Jingle.TransportType transport_type() {
- return Jingle.TransportType.STREAMING;
- }
- public int transport_priority() {
- return 1;
- }
- private Gee.List<Candidate> get_local_candidates(XmppStream stream) {
+ public string ns_uri { get { return NS_URI; } }
+ public Jingle.TransportType type_ { get { return Jingle.TransportType.STREAMING; } }
+ public int priority { get { return 1; } }
+
+ private Gee.List<Candidate> get_proxies(XmppStream stream) {
Gee.List<Candidate> result = new ArrayList<Candidate>();
int i = 1 << 15;
foreach (Socks5Bytestreams.Proxy proxy in stream.get_module(Socks5Bytestreams.Module.IDENTITY).get_proxies(stream)) {
@@ -42,18 +38,64 @@ public class Module : Jingle.Transport, XmppStreamModule {
}
return result;
}
- public Jingle.TransportParameters create_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid) {
+
+ private Gee.List<Candidate> start_local_listeners(XmppStream stream, Jid local_full_jid, string dstaddr, out LocalListener? local_listener) {
+ Gee.List<Candidate> result = new ArrayList<Candidate>();
+ SocketListener listener = new SocketListener();
+ int i = 1 << 15;
+ foreach (string ip_address in stream.get_module(Socks5Bytestreams.Module.IDENTITY).get_local_ip_addresses()) {
+ InetSocketAddress addr = new InetSocketAddress.from_string(ip_address, 0);
+ SocketAddress effective_any;
+ string cid = random_uuid();
+ try {
+ listener.add_address(addr, SocketType.STREAM, SocketProtocol.DEFAULT, new StringWrapper(cid), out effective_any);
+ } catch (Error e) {
+ continue;
+ }
+ InetSocketAddress effective = (InetSocketAddress)effective_any;
+ result.add(new Candidate.build(cid, ip_address, local_full_jid, (int)effective.port, i, CandidateType.DIRECT));
+ i -= 1;
+ }
+ if (!result.is_empty) {
+ local_listener = new LocalListener(listener, dstaddr);
+ local_listener.start();
+ } else {
+ local_listener = new LocalListener.empty();
+ }
+ return result;
+ }
+
+ private void select_candidates(XmppStream stream, Jid local_full_jid, string dstaddr, Parameters result) {
+ result.local_candidates.add_all(get_proxies(stream));
+ result.local_candidates.add_all(start_local_listeners(stream, local_full_jid, dstaddr, out result.listener));
+ result.local_candidates.sort((c1, c2) => {
+ if (c1.priority < c2.priority) { return 1; }
+ if (c1.priority > c2.priority) { return -1; }
+ return 0;
+ });
+ }
+
+ public Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) {
+ assert(components == 1);
Parameters result = new Parameters.create(local_full_jid, peer_full_jid, random_uuid());
- result.local_candidates.add_all(get_local_candidates(stream));
+ string dstaddr = calculate_dstaddr(result.sid, local_full_jid, peer_full_jid);
+ select_candidates(stream, local_full_jid, dstaddr, result);
return result;
}
- public Jingle.TransportParameters parse_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
+
+ public Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
Parameters result = Parameters.parse(local_full_jid, peer_full_jid, transport);
- result.local_candidates.add_all(get_local_candidates(stream));
+ string dstaddr = calculate_dstaddr(result.sid, local_full_jid, peer_full_jid);
+ select_candidates(stream, local_full_jid, dstaddr, result);
return result;
}
}
+private string calculate_dstaddr(string sid, Jid first_jid, Jid second_jid) {
+ string hashed = sid + first_jid.to_string() + second_jid.to_string();
+ return Checksum.compute_for_string(ChecksumType.SHA1, hashed);
+}
+
public enum CandidateType {
ASSISTED,
DIRECT,
@@ -109,6 +151,7 @@ public class Candidate : Socks5Bytestreams.Proxy {
public Candidate.build(string cid, string host, Jid jid, int port, int local_priority, CandidateType type) {
this(cid, host, jid, port, type.type_preference() + local_priority, type);
}
+
public Candidate.proxy(string cid, Socks5Bytestreams.Proxy proxy, int local_priority) {
this.build(cid, proxy.host, proxy.jid, proxy.port, local_priority, CandidateType.PROXY);
}
@@ -133,6 +176,7 @@ public class Candidate : Socks5Bytestreams.Proxy {
return new Candidate(cid, host, jid, port, priority, type);
}
+
public StanzaNode to_xml() {
return new StanzaNode.build("candidate", NS_URI)
.put_attribute("cid", cid)
@@ -156,13 +200,154 @@ bool bytes_equal(uint8[] a, uint8[] b) {
return true;
}
+class StringWrapper : GLib.Object {
+ public string str { get; set; }
+
+ public StringWrapper(string str) {
+ this.str = str;
+ }
+}
+
+class LocalListener {
+ SocketListener? inner;
+ string dstaddr;
+ HashMap<string, SocketConnection> connections = new HashMap<string, SocketConnection>();
+
+ public LocalListener(SocketListener inner, string dstaddr) {
+ this.inner = inner;
+ this.dstaddr = dstaddr;
+ }
+
+ public LocalListener.empty() {
+ this.inner = null;
+ this.dstaddr = "";
+ }
+
+ public void start() {
+ if (inner == null) {
+ return;
+ }
+ run.begin();
+ }
+ async void run() {
+ while (true) {
+ Object cid;
+ SocketConnection conn;
+ try {
+ conn = yield inner.accept_async(null, out cid);
+ } catch (Error e) {
+ break;
+ }
+ handle_conn.begin(((StringWrapper)cid).str, conn);
+ }
+ }
+
+ async void handle_conn(string cid, SocketConnection conn) {
+ conn.socket.timeout = NEGOTIATION_TIMEOUT;
+ size_t read;
+ size_t written;
+ uint8[] read_buffer = new uint8[1024];
+ ByteArray write_buffer = new ByteArray();
+
+ try {
+ // 05 SOCKS version 5
+ // ?? number of authentication methods
+ yield conn.input_stream.read_all_async(read_buffer[0:2], GLib.Priority.DEFAULT, null, out read);
+ if (read != 2) {
+ throw new IOError.PROXY_FAILED("wanted client hello message consisting of 2 bytes, only got %d bytes".printf((int)read));
+ }
+ if (read_buffer[0] != 0x05 || read_buffer[1] == 0) {
+ throw new IOError.PROXY_FAILED("wanted 05 xx, got %02x %02x".printf(read_buffer[0], read_buffer[1]));
+ }
+ int num_auth_methods = read_buffer[1];
+ // ?? authentication method (num_auth_methods times)
+ yield conn.input_stream.read_all_async(read_buffer[0:num_auth_methods], GLib.Priority.DEFAULT, null, out read);
+ bool found_null_auth = false;
+ for (int i = 0; i < read; i++) {
+ if (read_buffer[i] == 0x00) {
+ found_null_auth = true;
+ break;
+ }
+ }
+ if (read != num_auth_methods || !found_null_auth) {
+ throw new IOError.PROXY_FAILED("peer didn't offer null auth");
+ }
+ // 05 SOCKS version 5
+ // 00 nop authentication
+ yield conn.output_stream.write_all_async({0x05, 0x00}, GLib.Priority.DEFAULT, null, out written);
+
+ // 05 SOCKS version 5
+ // 01 connect
+ // 00 reserved
+ // 03 address type: domain name
+ // ?? length of the domain
+ // .. domain
+ // 00 port 0 (upper half)
+ // 00 port 0 (lower half)
+ yield conn.input_stream.read_all_async(read_buffer[0:4], GLib.Priority.DEFAULT, null, out read);
+ if (read != 4) {
+ throw new IOError.PROXY_FAILED("wanted connect message consisting of 4 bytes, only got %d bytes".printf((int)read));
+ }
+ if (read_buffer[0] != 0x05 || read_buffer[1] != 0x01 || read_buffer[3] != 0x03) {
+ throw new IOError.PROXY_FAILED("wanted 05 00 ?? 03, got %02x %02x %02x %02x".printf(read_buffer[0], read_buffer[1], read_buffer[2], read_buffer[3]));
+ }
+ yield conn.input_stream.read_all_async(read_buffer[0:1], GLib.Priority.DEFAULT, null, out read);
+ if (read != 1) {
+ throw new IOError.PROXY_FAILED("wanted length of dstaddr consisting of 1 byte, only got %d bytes".printf((int)read));
+ }
+ int dstaddr_len = read_buffer[0];
+ yield conn.input_stream.read_all_async(read_buffer[0:dstaddr_len+2], GLib.Priority.DEFAULT, null, out read);
+ if (read != dstaddr_len + 2) {
+ throw new IOError.PROXY_FAILED("wanted dstaddr and port consisting of %d bytes, got %d bytes".printf(dstaddr_len + 2, (int)read));
+ }
+ if (!bytes_equal(read_buffer[0:dstaddr_len], dstaddr.data)) {
+ string repr = ((string)read_buffer[0:dstaddr.length]).make_valid().escape();
+ throw new IOError.PROXY_FAILED(@"wanted dstaddr $(dstaddr), got $(repr)");
+ }
+ if (read_buffer[dstaddr_len] != 0x00 || read_buffer[dstaddr_len + 1] != 0x00) {
+ throw new IOError.PROXY_FAILED("wanted 00 00, got %02x %02x".printf(read_buffer[dstaddr_len], read_buffer[dstaddr_len + 1]));
+ }
+
+ // 05 SOCKS version 5
+ // 00 success
+ // 00 reserved
+ // 03 address type: domain name
+ // ?? length of the domain
+ // .. domain
+ // 00 port 0 (upper half)
+ // 00 port 0 (lower half)
+ write_buffer.append({0x05, 0x00, 0x00, 0x03});
+ write_buffer.append({(uint8)dstaddr.length});
+ write_buffer.append(dstaddr.data);
+ write_buffer.append({0x00, 0x00});
+ yield conn.output_stream.write_all_async(write_buffer.data, GLib.Priority.DEFAULT, null, out written);
+
+ conn.socket.timeout = 0;
+ if (!connections.has_key(cid)) {
+ connections[cid] = conn;
+ }
+ } catch (Error e) {
+ }
+ }
+
+ public SocketConnection? get_connection(string cid) {
+ if (!connections.has_key(cid)) {
+ return null;
+ }
+ return connections[cid];
+ }
+}
+
class Parameters : Jingle.TransportParameters, Object {
+ public string ns_uri { get { return NS_URI; } }
+ public uint8 components { get { return 1; } }
public Jingle.Role role { get; private set; }
public string sid { get; private set; }
public string remote_dstaddr { get; private set; }
public string local_dstaddr { get; private set; }
public Gee.List<Candidate> local_candidates = new ArrayList<Candidate>();
public Gee.List<Candidate> remote_candidates = new ArrayList<Candidate>();
+ public LocalListener? listener = null;
Jid local_full_jid;
Jid peer_full_jid;
@@ -173,16 +358,13 @@ class Parameters : Jingle.TransportParameters, Object {
Candidate? local_selected_candidate = null;
SocketConnection? local_selected_candidate_conn = null;
weak Jingle.Session? session = null;
+ weak Jingle.Content? content = null;
XmppStream? hack = null;
string? waiting_for_activation_cid = null;
SourceFunc waiting_for_activation_callback;
bool waiting_for_activation_error = false;
- private static string calculate_dstaddr(string sid, Jid first_jid, Jid second_jid) {
- string hashed = sid + first_jid.to_string() + second_jid.to_string();
- return Checksum.compute_for_string(ChecksumType.SHA1, hashed);
- }
private Parameters(Jingle.Role role, string sid, Jid local_full_jid, Jid peer_full_jid, string? remote_dstaddr) {
this.role = role;
this.sid = sid;
@@ -192,9 +374,11 @@ class Parameters : Jingle.TransportParameters, Object {
this.local_full_jid = local_full_jid;
this.peer_full_jid = peer_full_jid;
}
+
public Parameters.create(Jid local_full_jid, Jid peer_full_jid, string sid) {
this(Jingle.Role.INITIATOR, sid, local_full_jid, peer_full_jid, null);
}
+
public static Parameters parse(Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
string? dstaddr = transport.get_attribute("dstaddr");
string? mode = transport.get_attribute("mode");
@@ -211,10 +395,12 @@ class Parameters : Jingle.TransportParameters, Object {
}
return result;
}
- public string transport_ns_uri() {
- return NS_URI;
+
+ public void set_content(Jingle.Content content) {
+
}
- public StanzaNode to_transport_stanza_node() {
+
+ public StanzaNode to_transport_stanza_node(string action_type) {
StanzaNode transport = new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("dstaddr", local_dstaddr);
@@ -230,7 +416,8 @@ class Parameters : Jingle.TransportParameters, Object {
}
return transport;
}
- public void on_transport_accept(StanzaNode transport) throws Jingle.IqError {
+
+ public void handle_transport_accept(StanzaNode transport) throws Jingle.IqError {
Parameters other = Parameters.parse(local_full_jid, peer_full_jid, transport);
if (other.sid != sid) {
throw new Jingle.IqError.BAD_REQUEST("invalid sid");
@@ -238,42 +425,44 @@ class Parameters : Jingle.TransportParameters, Object {
remote_candidates = other.remote_candidates;
remote_dstaddr = other.remote_dstaddr;
}
- public void on_transport_info(StanzaNode transport) throws Jingle.IqError {
- StanzaNode? candidate_error = transport.get_subnode("candidate-error", NS_URI);
- StanzaNode? candidate_used = transport.get_subnode("candidate-used", NS_URI);
- StanzaNode? activated = transport.get_subnode("activated", NS_URI);
- StanzaNode? proxy_error = transport.get_subnode("proxy-error", NS_URI);
- int num_children = 0;
- if (candidate_error != null) { num_children += 1; }
- if (candidate_used != null) { num_children += 1; }
- if (activated != null) { num_children += 1; }
- if (proxy_error != null) { num_children += 1; }
- if (num_children == 0) {
- throw new Jingle.IqError.UNSUPPORTED_INFO("unknown transport-info");
- } else if (num_children > 1) {
- throw new Jingle.IqError.BAD_REQUEST("transport-info with more than one child");
- }
- if (candidate_error != null) {
- handle_remote_candidate(null);
- }
- if (candidate_used != null) {
- string? cid = candidate_used.get_attribute("cid");
- if (cid == null) {
- throw new Jingle.IqError.BAD_REQUEST("missing cid");
- }
- handle_remote_candidate(cid);
- }
- if (activated != null) {
- string? cid = activated.get_attribute("cid");
- if (cid == null) {
- throw new Jingle.IqError.BAD_REQUEST("missing cid");
- }
- handle_activated(cid);
+
+ public void handle_transport_info(StanzaNode transport) throws Jingle.IqError {
+ ArrayList<StanzaNode> socks5_nodes = new ArrayList<StanzaNode>();
+ foreach (StanzaNode node in transport.sub_nodes) {
+ if (node.ns_uri == NS_URI) socks5_nodes.add(node);
}
- if (proxy_error != null) {
- handle_proxy_error();
+ if (socks5_nodes.is_empty) { warning("No socks5 subnodes in transport node"); return; }
+ if (socks5_nodes.size > 1) { warning("Too many socks5 subnodes in transport node"); return; }
+
+ StanzaNode node = socks5_nodes[0];
+
+ switch (node.name) {
+ case "activated":
+ string? cid = node.get_attribute("cid");
+ if (cid == null) {
+ throw new Jingle.IqError.BAD_REQUEST("missing cid");
+ }
+ handle_activated(cid);
+ break;
+ case "candidate-used":
+ string? cid = node.get_attribute("cid");
+ if (cid == null) {
+ throw new Jingle.IqError.BAD_REQUEST("missing cid");
+ }
+ handle_remote_candidate(cid);
+ break;
+ case "candidate-error":
+ handle_remote_candidate(null);
+ break;
+ case "proxy-error":
+ handle_proxy_error();
+ break;
+ default:
+ warning("Unknown transport-info: %s", transport.to_string());
+ break;
}
}
+
private void handle_remote_candidate(string? cid) throws Jingle.IqError {
if (remote_sent_selected_candidate) {
throw new Jingle.IqError.BAD_REQUEST("remote candidate already specified");
@@ -295,6 +484,7 @@ class Parameters : Jingle.TransportParameters, Object {
debug("Remote selected candidate %s", candidate != null ? candidate.cid : "(null)");
try_completing_negotiation();
}
+
private void handle_activated(string cid) throws Jingle.IqError {
if (waiting_for_activation_cid == null || cid != waiting_for_activation_cid) {
throw new Jingle.IqError.BAD_REQUEST("unexpected proxy activation message");
@@ -302,6 +492,7 @@ class Parameters : Jingle.TransportParameters, Object {
Idle.add((owned)waiting_for_activation_callback);
waiting_for_activation_cid = null;
}
+
private void handle_proxy_error() throws Jingle.IqError {
if (waiting_for_activation_cid == null) {
throw new Jingle.IqError.BAD_REQUEST("unexpected proxy error message");
@@ -311,37 +502,28 @@ class Parameters : Jingle.TransportParameters, Object {
waiting_for_activation_error = true;
}
+
private void try_completing_negotiation() {
if (!remote_sent_selected_candidate || !local_determined_selected_candidate) {
return;
}
- Candidate? remote = remote_selected_candidate;
- Candidate? local = local_selected_candidate;
-
- int num_candidates = 0;
- if (remote != null) { num_candidates += 1; }
- if (local != null) { num_candidates += 1; }
-
- if (num_candidates == 0) {
- // Notify Jingle of the failed transport.
- session.set_transport_connection(hack, null);
+ if (remote_selected_candidate == null && local_selected_candidate == null) {
+ content_set_transport_connection_error(new IOError.FAILED("No candidates"));
return;
}
bool remote_wins;
- if (num_candidates == 1) {
- remote_wins = remote != null;
- } else {
- if (local.priority < remote.priority) {
- remote_wins = true;
- } else if (local.priority > remote.priority) {
- remote_wins = false;
- } else {
+ if (remote_selected_candidate != null && local_selected_candidate != null) {
+ if (local_selected_candidate.priority == remote_selected_candidate.priority) {
// equal priority -> XEP-0260 says that the candidate offered
// by the initiator wins, so the one that the remote chose
remote_wins = role == Jingle.Role.INITIATOR;
+ } else {
+ remote_wins = local_selected_candidate.priority < remote_selected_candidate.priority;
}
+ } else {
+ remote_wins = remote_selected_candidate != null;
}
if (!remote_wins) {
@@ -350,14 +532,28 @@ class Parameters : Jingle.TransportParameters, Object {
if (strong == null) {
return;
}
- strong.set_transport_connection(hack, local_selected_candidate_conn);
+ content_set_transport_connection(local_selected_candidate_conn);
} else {
wait_for_remote_activation.begin(local_selected_candidate, local_selected_candidate_conn);
}
} else {
- connect_to_local_candidate.begin(remote_selected_candidate);
+ if (remote_selected_candidate.type_ == CandidateType.DIRECT) {
+ Jingle.Session? strong = session;
+ if (strong == null) {
+ return;
+ }
+ SocketConnection? conn = listener.get_connection(remote_selected_candidate.cid);
+ if (conn == null) {
+ content_set_transport_connection_error(new IOError.FAILED("Remote hasn't actually connected to us?!"));
+ return;
+ }
+ content_set_transport_connection(conn);
+ } else {
+ connect_to_local_candidate.begin(remote_selected_candidate);
+ }
}
}
+
public async void wait_for_remote_activation(Candidate candidate, SocketConnection conn) {
debug("Waiting for remote activation of %s", candidate.cid);
waiting_for_activation_cid = candidate.cid;
@@ -369,11 +565,12 @@ class Parameters : Jingle.TransportParameters, Object {
return;
}
if (!waiting_for_activation_error) {
- strong.set_transport_connection(hack, conn);
+ content_set_transport_connection(conn);
} else {
- strong.set_transport_connection(hack, null);
+ content_set_transport_connection_error(new IOError.FAILED("waiting_for_activation_error"));
}
}
+
public async void connect_to_local_candidate(Candidate candidate) {
debug("Connecting to candidate %s", candidate.cid);
try {
@@ -398,11 +595,11 @@ class Parameters : Jingle.TransportParameters, Object {
throw new IOError.PROXY_FAILED("activation iq error");
}
- Jingle.Session? strong = session;
- if (strong == null) {
+ Jingle.Content? strong_content = content;
+ if (strong_content == null) {
return;
}
- strong.send_transport_info(hack, new StanzaNode.build("transport", NS_URI)
+ strong_content.send_transport_info(new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("sid", sid)
.put_node(new StanzaNode.build("activated", NS_URI)
@@ -410,22 +607,23 @@ class Parameters : Jingle.TransportParameters, Object {
)
);
- strong.set_transport_connection(hack, conn);
+ content_set_transport_connection(conn);
} catch (Error e) {
- Jingle.Session? strong = session;
- if (strong == null) {
+ Jingle.Content? strong_content = content;
+ if (strong_content == null) {
return;
}
- strong.send_transport_info(hack, new StanzaNode.build("transport", NS_URI)
+ strong_content.send_transport_info(new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("sid", sid)
.put_node(new StanzaNode.build("proxy-error", NS_URI))
);
- strong.set_transport_connection(hack, null);
+ content_set_transport_connection_error(new IOError.FAILED("Connect to local candidate error: %s", e.message));
}
}
+
public async SocketConnection connect_to_socks5(Candidate candidate, string dstaddr) throws Error {
- SocketClient socket_client = new SocketClient() { timeout=3 };
+ SocketClient socket_client = new SocketClient() { timeout=NEGOTIATION_TIMEOUT };
string address = @"[$(candidate.host)]:$(candidate.port)";
debug("Connecting to SOCKS5 server at %s", address);
@@ -444,7 +642,10 @@ class Parameters : Jingle.TransportParameters, Object {
yield conn.input_stream.read_all_async(read_buffer[0:2], GLib.Priority.DEFAULT, null, out read);
// 05 SOCKS version 5
- // 01 success
+ // 00 nop authentication
+ if (read != 2) {
+ throw new IOError.PROXY_FAILED("wanted 05 00, only got %d bytes".printf((int)read));
+ }
if (read_buffer[0] != 0x05 || read_buffer[1] != 0x00) {
throw new IOError.PROXY_FAILED("wanted 05 00, got %02x %02x".printf(read_buffer[0], read_buffer[1]));
}
@@ -472,6 +673,9 @@ class Parameters : Jingle.TransportParameters, Object {
// .. domain
// 00 port 0 (upper half)
// 00 port 0 (lower half)
+ if (read != write_buffer.len) {
+ throw new IOError.PROXY_FAILED("wanted server success response consisting of %d bytes, only got %d bytes".printf((int)write_buffer.len, (int)read));
+ }
if (read_buffer[0] != 0x05 || read_buffer[1] != 0x00 || read_buffer[3] != 0x03) {
throw new IOError.PROXY_FAILED("wanted 05 00 ?? 03, got %02x %02x %02x %02x".printf(read_buffer[0], read_buffer[1], read_buffer[2], read_buffer[3]));
}
@@ -486,10 +690,11 @@ class Parameters : Jingle.TransportParameters, Object {
throw new IOError.PROXY_FAILED("wanted port 00 00, got %02x %02x".printf(read_buffer[5+dstaddr.length], read_buffer[5+dstaddr.length+1]));
}
- conn.get_socket().set_timeout(0);
+ conn.socket.timeout = 0;
return conn;
}
+
public async void try_connecting_to_candidates(XmppStream stream, Jingle.Session session) throws Error {
remote_candidates.sort((c1, c2) => {
// sort from priorities from high to low
@@ -510,7 +715,7 @@ class Parameters : Jingle.TransportParameters, Object {
local_selected_candidate = candidate;
local_selected_candidate_conn = conn;
debug("Selected candidate %s", candidate.cid);
- session.send_transport_info(stream, new StanzaNode.build("transport", NS_URI)
+ content.send_transport_info(new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("sid", sid)
.put_node(new StanzaNode.build("candidate-used", NS_URI)
@@ -527,7 +732,7 @@ class Parameters : Jingle.TransportParameters, Object {
}
local_determined_selected_candidate = true;
local_selected_candidate = null;
- session.send_transport_info(stream, new StanzaNode.build("transport", NS_URI)
+ content.send_transport_info(new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("sid", sid)
.put_node(new StanzaNode.build("candidate-error", NS_URI))
@@ -535,10 +740,30 @@ class Parameters : Jingle.TransportParameters, Object {
// Try remote candidates
try_completing_negotiation();
}
- public void create_transport_connection(XmppStream stream, Jingle.Session session) {
- this.session = session;
+
+ private Jingle.StreamingConnection connection = new Jingle.StreamingConnection();
+
+ private void content_set_transport_connection(IOStream ios) {
+ IOStream iostream = ios;
+ Jingle.Content? strong_content = content;
+ if (strong_content == null) return;
+
+ if (strong_content.security_params != null) {
+ iostream = strong_content.security_params.wrap_stream(iostream);
+ }
+ connection.set_stream.begin(iostream);
+ }
+
+ private void content_set_transport_connection_error(Error e) {
+ connection.set_error(e);
+ }
+
+ public void create_transport_connection(XmppStream stream, Jingle.Content content) {
+ this.session = content.session;
+ this.content = content;
this.hack = stream;
try_connecting_to_candidates.begin(stream, session);
+ this.content.set_transport_connection(connection, 1);
}
}
diff --git a/xmpp-vala/src/module/xep/0261_jingle_in_band_bytestreams.vala b/xmpp-vala/src/module/xep/0261_jingle_in_band_bytestreams.vala
index e26d63b7..09eaf711 100644
--- a/xmpp-vala/src/module/xep/0261_jingle_in_band_bytestreams.vala
+++ b/xmpp-vala/src/module/xep/0261_jingle_in_band_bytestreams.vala
@@ -21,41 +21,41 @@ public class Module : Jingle.Transport, XmppStreamModule {
public override string get_ns() { return NS_URI; }
public override string get_id() { return IDENTITY.id; }
- public async bool is_transport_available(XmppStream stream, Jid full_jid) {
- return yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
+ public async bool is_transport_available(XmppStream stream, uint8 components, Jid full_jid) {
+ return components == 1 && yield stream.get_module(ServiceDiscovery.Module.IDENTITY).has_entity_feature(stream, full_jid, NS_URI);
}
- public string transport_ns_uri() {
- return NS_URI;
- }
- public Jingle.TransportType transport_type() {
- return Jingle.TransportType.STREAMING;
- }
- public int transport_priority() {
- return 0;
- }
- public Jingle.TransportParameters create_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid) {
+ public string ns_uri { get { return NS_URI; } }
+ public Jingle.TransportType type_ { get { return Jingle.TransportType.STREAMING; } }
+ public int priority { get { return 0; } }
+ public Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) {
+ assert(components == 1);
return new Parameters.create(peer_full_jid, random_uuid());
}
- public Jingle.TransportParameters parse_transport_parameters(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
+ public Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
return Parameters.parse(peer_full_jid, transport);
}
}
class Parameters : Jingle.TransportParameters, Object {
+ public string ns_uri { get { return NS_URI; } }
+ public uint8 components { get { return 1; } }
public Jingle.Role role { get; private set; }
public Jid peer_full_jid { get; private set; }
public string sid { get; private set; }
public int block_size { get; private set; }
+
private Parameters(Jingle.Role role, Jid peer_full_jid, string sid, int block_size) {
this.role = role;
this.peer_full_jid = peer_full_jid;
this.sid = sid;
this.block_size = block_size;
}
+
public Parameters.create(Jid peer_full_jid, string sid) {
this(Jingle.Role.INITIATOR, peer_full_jid, sid, DEFAULT_BLOCKSIZE);
}
+
public static Parameters parse(Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError {
string? sid = transport.get_attribute("sid");
int block_size = transport.get_attribute_int("block-size");
@@ -64,27 +64,43 @@ class Parameters : Jingle.TransportParameters, Object {
}
return new Parameters(Jingle.Role.RESPONDER, peer_full_jid, sid, block_size);
}
+
public string transport_ns_uri() {
return NS_URI;
}
- public StanzaNode to_transport_stanza_node() {
+
+ public void set_content(Jingle.Content content) {
+
+ }
+
+ public StanzaNode to_transport_stanza_node(string action_type) {
return new StanzaNode.build("transport", NS_URI)
.add_self_xmlns()
.put_attribute("block-size", block_size.to_string())
.put_attribute("sid", sid);
}
- public void on_transport_accept(StanzaNode transport) throws Jingle.IqError {
+
+ public void handle_transport_accept(StanzaNode transport) throws Jingle.IqError {
Parameters other = Parameters.parse(peer_full_jid, transport);
if (other.sid != sid || other.block_size > block_size) {
throw new Jingle.IqError.NOT_ACCEPTABLE("invalid IBB sid or block_size");
}
block_size = other.block_size;
}
- public void on_transport_info(StanzaNode transport) throws Jingle.IqError {
+
+ public void handle_transport_info(StanzaNode transport) throws Jingle.IqError {
throw new Jingle.IqError.UNSUPPORTED_INFO("transport-info not supported for IBBs");
}
- public void create_transport_connection(XmppStream stream, Jingle.Session session) {
- session.set_transport_connection(stream, InBandBytestreams.Connection.create(stream, peer_full_jid, sid, block_size, role == Jingle.Role.INITIATOR));
+
+ public void create_transport_connection(XmppStream stream, Jingle.Content content) {
+ IOStream iostream = InBandBytestreams.Connection.create(stream, peer_full_jid, sid, block_size, role == Jingle.Role.INITIATOR);
+ Jingle.StreamingConnection connection = new Jingle.StreamingConnection();
+ if (content.security_params != null) {
+ iostream = content.security_params.wrap_stream(iostream);
+ }
+ connection.set_stream.begin(iostream);
+ debug("set transport conn ibb");
+ content.set_transport_connection(connection, 1);
}
}
diff --git a/xmpp-vala/src/module/xep/0353_jingle_message_initiation.vala b/xmpp-vala/src/module/xep/0353_jingle_message_initiation.vala
new file mode 100644
index 00000000..71e16a95
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0353_jingle_message_initiation.vala
@@ -0,0 +1,104 @@
+using Gee;
+
+namespace Xmpp.Xep.JingleMessageInitiation {
+ public const string NS_URI = "urn:xmpp:jingle-message:0";
+
+ public class Module : XmppStreamModule {
+ public static ModuleIdentity<Module> IDENTITY = new ModuleIdentity<Module>(NS_URI, "0353_jingle_message_initiation");
+
+ public signal void session_proposed(Jid from, Jid to, string sid, Gee.List<StanzaNode> descriptions);
+ public signal void session_retracted(Jid from, Jid to, string sid);
+ public signal void session_accepted(Jid from, string sid);
+ public signal void session_rejected(Jid from, Jid to, string sid);
+
+ public void send_session_propose_to_peer(XmppStream stream, Jid to, string sid, Gee.List<StanzaNode> descriptions) {
+ StanzaNode propose_node = new StanzaNode.build("propose", NS_URI).add_self_xmlns().put_attribute("id", sid, NS_URI);
+ foreach (StanzaNode desc_node in descriptions) {
+ propose_node.put_node(desc_node);
+ }
+
+ MessageStanza accepted_message = new MessageStanza() { to=to, type_=MessageStanza.TYPE_CHAT };
+ accepted_message.stanza.put_node(propose_node);
+ stream.get_module(MessageModule.IDENTITY).send_message.begin(stream, accepted_message);
+ }
+
+ public void send_session_retract_to_peer(XmppStream stream, Jid to, string sid) {
+ send_jmi_message(stream, "retract", to, sid);
+ }
+
+ public void send_session_accept_to_self(XmppStream stream, string sid) {
+ send_jmi_message(stream, "accept", Bind.Flag.get_my_jid(stream).bare_jid, sid);
+ }
+
+ public void send_session_reject_to_self(XmppStream stream, string sid) {
+ send_jmi_message(stream, "reject", Bind.Flag.get_my_jid(stream).bare_jid, sid);
+ }
+
+ public void send_session_proceed_to_peer(XmppStream stream, Jid to, string sid) {
+ send_jmi_message(stream, "proceed", to, sid);
+ }
+
+ public void send_session_reject_to_peer(XmppStream stream, Jid to, string sid) {
+ send_jmi_message(stream, "reject", to, sid);
+ }
+
+ private void send_jmi_message(XmppStream stream, string name, Jid to, string sid) {
+ MessageStanza accepted_message = new MessageStanza() { to=to, type_=MessageStanza.TYPE_CHAT };
+ accepted_message.stanza.put_node(
+ new StanzaNode.build(name, NS_URI).add_self_xmlns()
+ .put_attribute("id", sid, NS_URI));
+ stream.get_module(MessageModule.IDENTITY).send_message.begin(stream, accepted_message);
+ }
+
+ private void on_received_message(XmppStream stream, MessageStanza message) {
+ Xep.MessageArchiveManagement.MessageFlag? mam_flag = Xep.MessageArchiveManagement.MessageFlag.get_flag(message);
+ if (mam_flag != null) return;
+
+ StanzaNode? mi_node = null;
+ foreach (StanzaNode node in message.stanza.sub_nodes) {
+ if (node.ns_uri == NS_URI) {
+ mi_node = node;
+ }
+ }
+ if (mi_node == null) return;
+
+ switch (mi_node.name) {
+ case "accept":
+ case "proceed":
+ session_accepted(message.from, mi_node.get_attribute("id"));
+ break;
+ case "propose":
+ ArrayList<StanzaNode> descriptions = new ArrayList<StanzaNode>();
+
+ foreach (StanzaNode node in mi_node.sub_nodes) {
+ if (node.name != "description") continue;
+ descriptions.add(node);
+ }
+
+ if (descriptions.size > 0) {
+ session_proposed(message.from, message.to, mi_node.get_attribute("id"), descriptions);
+ }
+ break;
+ case "retract":
+ session_retracted(message.from, message.to, mi_node.get_attribute("id"));
+ break;
+ case "reject":
+ session_rejected(message.from, message.to, mi_node.get_attribute("id"));
+ break;
+ }
+ }
+
+ public override void attach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
+ stream.get_module(MessageModule.IDENTITY).received_message.connect(on_received_message);
+ }
+
+ public override void detach(XmppStream stream) {
+ stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
+ stream.get_module(MessageModule.IDENTITY).received_message.disconnect(on_received_message);
+ }
+
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+ }
+}
diff --git a/xmpp-vala/src/module/xep/0384_omemo/omemo_decryptor.vala b/xmpp-vala/src/module/xep/0384_omemo/omemo_decryptor.vala
new file mode 100644
index 00000000..8e3213ae
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0384_omemo/omemo_decryptor.vala
@@ -0,0 +1,62 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Omemo {
+
+ public abstract class OmemoDecryptor : XmppStreamModule {
+
+ public static Xmpp.ModuleIdentity<OmemoDecryptor> IDENTITY = new Xmpp.ModuleIdentity<OmemoDecryptor>(NS_URI, "0384_omemo_decryptor");
+
+ public abstract uint32 own_device_id { get; }
+
+ public abstract string decrypt(uint8[] ciphertext, uint8[] key, uint8[] iv) throws GLib.Error;
+
+ public abstract uint8[] decrypt_key(ParsedData data, Jid from_jid) throws GLib.Error;
+
+ public ParsedData? parse_node(StanzaNode encrypted_node) {
+ ParsedData ret = new ParsedData();
+
+ StanzaNode? header_node = encrypted_node.get_subnode("header");
+ if (header_node == null) return null;
+
+ ret.sid = header_node.get_attribute_int("sid", -1);
+ if (ret.sid == -1) return null;
+
+ string? payload_str = encrypted_node.get_deep_string_content("payload");
+ if (payload_str != null) ret.ciphertext = Base64.decode(payload_str);
+
+ string? iv_str = header_node.get_deep_string_content("iv");
+ if (iv_str == null) return null;
+ ret.iv = Base64.decode(iv_str);
+
+ foreach (StanzaNode key_node in header_node.get_subnodes("key")) {
+ debug("Is ours? %d =? %u", key_node.get_attribute_int("rid"), own_device_id);
+ if (key_node.get_attribute_int("rid") == own_device_id) {
+ string? key_node_content = key_node.get_string_content();
+ if (key_node_content == null) continue;
+ uchar[] encrypted_key = Base64.decode(key_node_content);
+ ret.our_potential_encrypted_keys[new Bytes.take(encrypted_key)] = key_node.get_attribute_bool("prekey");
+ }
+ }
+
+ return ret;
+ }
+
+ public override void attach(XmppStream stream) { }
+ public override void detach(XmppStream stream) { }
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+ }
+
+ public class ParsedData {
+ public int sid;
+ public uint8[] ciphertext;
+ public uint8[] iv;
+ public uchar[] encrypted_key;
+ public bool is_prekey;
+
+ public HashMap<Bytes, bool> our_potential_encrypted_keys = new HashMap<Bytes, bool>();
+ }
+}
+
diff --git a/xmpp-vala/src/module/xep/0384_omemo/omemo_encryptor.vala b/xmpp-vala/src/module/xep/0384_omemo/omemo_encryptor.vala
new file mode 100644
index 00000000..6509bfe3
--- /dev/null
+++ b/xmpp-vala/src/module/xep/0384_omemo/omemo_encryptor.vala
@@ -0,0 +1,116 @@
+using Gee;
+using Xmpp.Xep;
+using Xmpp;
+
+namespace Xmpp.Xep.Omemo {
+
+ public const string NS_URI = "eu.siacs.conversations.axolotl";
+ public const string NODE_DEVICELIST = NS_URI + ".devicelist";
+ public const string NODE_BUNDLES = NS_URI + ".bundles";
+ public const string NODE_VERIFICATION = NS_URI + ".verification";
+
+ public abstract class OmemoEncryptor : XmppStreamModule {
+
+ public static Xmpp.ModuleIdentity<OmemoEncryptor> IDENTITY = new Xmpp.ModuleIdentity<OmemoEncryptor>(NS_URI, "0384_omemo_encryptor");
+
+ public abstract uint32 own_device_id { get; }
+
+ public abstract EncryptionData encrypt_plaintext(string plaintext) throws GLib.Error;
+
+ public abstract void encrypt_key(Xep.Omemo.EncryptionData encryption_data, Jid jid, int32 device_id) throws GLib.Error;
+
+ public abstract EncryptionResult encrypt_key_to_recipient(XmppStream stream, Xep.Omemo.EncryptionData enc_data, Jid recipient) throws GLib.Error;
+
+ public override void attach(XmppStream stream) { }
+ public override void detach(XmppStream stream) { }
+ public override string get_ns() { return NS_URI; }
+ public override string get_id() { return IDENTITY.id; }
+ }
+
+ public class EncryptionData {
+ public uint32 own_device_id;
+ public uint8[] ciphertext;
+ public uint8[] keytag;
+ public uint8[] iv;
+
+ public Gee.List<StanzaNode> key_nodes = new ArrayList<StanzaNode>();
+
+ public EncryptionData(uint32 own_device_id) {
+ this.own_device_id = own_device_id;
+ }
+
+ public void add_device_key(int device_id, uint8[] device_key, bool prekey) {
+ StanzaNode key_node = new StanzaNode.build("key", NS_URI)
+ .put_attribute("rid", device_id.to_string())
+ .put_node(new StanzaNode.text(Base64.encode(device_key)));
+ if (prekey) {
+ key_node.put_attribute("prekey", "true");
+ }
+ key_nodes.add(key_node);
+ }
+
+ public StanzaNode get_encrypted_node() {
+ StanzaNode encrypted_node = new StanzaNode.build("encrypted", NS_URI).add_self_xmlns();
+
+ StanzaNode header_node = new StanzaNode.build("header", NS_URI)
+ .put_attribute("sid", own_device_id.to_string())
+ .put_node(new StanzaNode.build("iv", NS_URI).put_node(new StanzaNode.text(Base64.encode(iv))));
+ encrypted_node.put_node(header_node);
+
+ if (ciphertext != null) {
+ StanzaNode payload_node = new StanzaNode.build("payload", NS_URI)
+ .put_node(new StanzaNode.text(Base64.encode(ciphertext)));
+ encrypted_node.put_node(payload_node);
+ }
+
+ foreach (StanzaNode key_node in key_nodes) {
+ header_node.put_node(key_node);
+ }
+
+ return encrypted_node;
+ }
+ }
+
+ public class EncryptionResult {
+ public int lost { get; internal set; }
+ public int success { get; internal set; }
+ public int unknown { get; internal set; }
+ public int failure { get; internal set; }
+ }
+
+ public class EncryptState {
+ public bool encrypted { get; internal set; }
+ public int other_devices { get; internal set; }
+ public int other_success { get; internal set; }
+ public int other_lost { get; internal set; }
+ public int other_unknown { get; internal set; }
+ public int other_failure { get; internal set; }
+ public int other_waiting_lists { get; internal set; }
+
+ public int own_devices { get; internal set; }
+ public int own_success { get; internal set; }
+ public int own_lost { get; internal set; }
+ public int own_unknown { get; internal set; }
+ public int own_failure { get; internal set; }
+ public bool own_list { get; internal set; }
+
+ public void add_result(EncryptionResult enc_res, bool own) {
+ if (own) {
+ own_lost += enc_res.lost;
+ own_success += enc_res.success;
+ own_unknown += enc_res.unknown;
+ own_failure += enc_res.failure;
+ } else {
+ other_lost += enc_res.lost;
+ other_success += enc_res.success;
+ other_unknown += enc_res.unknown;
+ other_failure += enc_res.failure;
+ }
+ }
+
+ public string to_string() {
+ return @"EncryptState (encrypted=$encrypted, other=(devices=$other_devices, success=$other_success, lost=$other_lost, unknown=$other_unknown, failure=$other_failure, waiting_lists=$other_waiting_lists, own=(devices=$own_devices, success=$own_success, lost=$own_lost, unknown=$own_unknown, failure=$own_failure, list=$own_list))";
+ }
+ }
+}
+