aboutsummaryrefslogtreecommitdiff
path: root/plugins/omemo/src
diff options
context:
space:
mode:
Diffstat (limited to 'plugins/omemo/src')
-rw-r--r--plugins/omemo/src/dtls_srtp_verification_draft.vala268
-rw-r--r--plugins/omemo/src/file_transfer/file_decryptor.vala90
-rw-r--r--plugins/omemo/src/file_transfer/file_encryptor.vala76
-rw-r--r--plugins/omemo/src/jingle/jet_omemo.vala114
-rw-r--r--plugins/omemo/src/jingle/jingle_helper.vala53
-rw-r--r--plugins/omemo/src/logic/database.vala284
-rw-r--r--plugins/omemo/src/logic/decrypt.vala210
-rw-r--r--plugins/omemo/src/logic/encrypt.vala131
-rw-r--r--plugins/omemo/src/logic/manager.vala429
-rw-r--r--plugins/omemo/src/logic/pre_key_store.vala45
-rw-r--r--plugins/omemo/src/logic/session_store.vala49
-rw-r--r--plugins/omemo/src/logic/signed_pre_key_store.vala45
-rw-r--r--plugins/omemo/src/logic/trust_manager.vala141
-rw-r--r--plugins/omemo/src/native/context.vala115
-rw-r--r--plugins/omemo/src/native/helper.c329
-rw-r--r--plugins/omemo/src/native/helper.h41
-rw-r--r--plugins/omemo/src/native/simple_iks.vala40
-rw-r--r--plugins/omemo/src/native/simple_pks.vala33
-rw-r--r--plugins/omemo/src/native/simple_spks.vala33
-rw-r--r--plugins/omemo/src/native/simple_ss.vala75
-rw-r--r--plugins/omemo/src/native/store.vala415
-rw-r--r--plugins/omemo/src/native/util.vala45
-rw-r--r--plugins/omemo/src/plugin.vala97
-rw-r--r--plugins/omemo/src/protocol/bundle.vala88
-rw-r--r--plugins/omemo/src/protocol/message_flag.vala23
-rw-r--r--plugins/omemo/src/protocol/stream_module.vala331
-rw-r--r--plugins/omemo/src/register_plugin.vala3
-rw-r--r--plugins/omemo/src/trust_level.vala15
-rw-r--r--plugins/omemo/src/ui/bad_messages_populator.vala198
-rw-r--r--plugins/omemo/src/ui/call_encryption_entry.vala57
-rw-r--r--plugins/omemo/src/ui/contact_details_provider.vala29
-rw-r--r--plugins/omemo/src/ui/device_notification_populator.vala90
-rw-r--r--plugins/omemo/src/ui/encryption_list_entry.vala77
-rw-r--r--plugins/omemo/src/ui/encryption_preferences_entry.vala323
-rw-r--r--plugins/omemo/src/ui/manage_key_dialog.vala177
-rw-r--r--plugins/omemo/src/ui/own_notifications.vala35
-rw-r--r--plugins/omemo/src/ui/util.vala40
37 files changed, 0 insertions, 4644 deletions
diff --git a/plugins/omemo/src/dtls_srtp_verification_draft.vala b/plugins/omemo/src/dtls_srtp_verification_draft.vala
deleted file mode 100644
index 09617a2a..00000000
--- a/plugins/omemo/src/dtls_srtp_verification_draft.vala
+++ /dev/null
@@ -1,268 +0,0 @@
-using Omemo;
-using Gee;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo.DtlsSrtpVerificationDraft {
- public const string NS_URI = "http://gultsch.de/xmpp/drafts/omemo/dlts-srtp-verification";
-
- public class StreamModule : XmppStreamModule {
-
- public static Xmpp.ModuleIdentity<StreamModule> IDENTITY = new Xmpp.ModuleIdentity<StreamModule>(NS_URI, "dtls_srtp_omemo_verification_draft");
-
- private VerificationSendListener send_listener = new VerificationSendListener();
- private HashMap<string, int> device_id_by_jingle_sid = new HashMap<string, int>();
- private HashMap<string, int> device_id_by_muji_member = new HashMap<string, int>();
- private HashMap<string, Gee.List<string>> content_names_by_jingle_sid = new HashMap<string, Gee.List<string>>();
-
- private void on_preprocess_incoming_iq_set_get(XmppStream stream, Xmpp.Iq.Stanza iq) {
- if (iq.type_ != Iq.Stanza.TYPE_SET) return;
-
- Gee.List<StanzaNode> content_nodes = iq.stanza.get_deep_subnodes(Xep.Jingle.NS_URI + ":jingle", Xep.Jingle.NS_URI + ":content");
- if (content_nodes.size == 0) return;
-
- string? jingle_sid = iq.stanza.get_deep_attribute(Xep.Jingle.NS_URI + ":jingle", "sid");
- if (jingle_sid == null) return;
-
- Xep.Omemo.OmemoDecryptor decryptor = stream.get_module(Xep.Omemo.OmemoDecryptor.IDENTITY);
-
- foreach (StanzaNode content_node in content_nodes) {
- string? content_name = content_node.get_attribute("name");
- if (content_name == null) continue;
- StanzaNode? transport_node = content_node.get_subnode("transport", Xep.JingleIceUdp.NS_URI);
- if (transport_node == null) continue;
- StanzaNode? fingerprint_node = transport_node.get_subnode("fingerprint", NS_URI);
- if (fingerprint_node == null) continue;
- StanzaNode? encrypted_node = fingerprint_node.get_subnode("encrypted", Omemo.NS_URI);
- if (encrypted_node == null) continue;
-
- Xep.Omemo.ParsedData? parsed_data = decryptor.parse_node(encrypted_node);
- if (parsed_data == null || parsed_data.ciphertext == null) continue;
-
- if (device_id_by_jingle_sid.has_key(jingle_sid) && device_id_by_jingle_sid[jingle_sid] != parsed_data.sid) {
- warning("Expected DTLS fingerprint to be OMEMO encrypted from %s %d, but it was from %d", iq.from.to_string(), device_id_by_jingle_sid[jingle_sid], parsed_data.sid);
- }
-
- foreach (Bytes encr_key in parsed_data.our_potential_encrypted_keys.keys) {
- parsed_data.is_prekey = parsed_data.our_potential_encrypted_keys[encr_key];
- parsed_data.encrypted_key = encr_key.get_data();
-
- try {
- uint8[] key = decryptor.decrypt_key(parsed_data, iq.from.bare_jid);
- string cleartext = decryptor.decrypt(parsed_data.ciphertext, key, parsed_data.iv);
-
- StanzaNode new_fingerprint_node = new StanzaNode.build("fingerprint", Xep.JingleIceUdp.DTLS_NS_URI).add_self_xmlns()
- .put_node(new StanzaNode.text(cleartext));
- string? hash_attr = fingerprint_node.get_attribute("hash", NS_URI);
- string? setup_attr = fingerprint_node.get_attribute("setup", NS_URI);
- if (hash_attr != null) new_fingerprint_node.put_attribute("hash", hash_attr);
- if (setup_attr != null) new_fingerprint_node.put_attribute("setup", setup_attr);
- transport_node.put_node(new_fingerprint_node);
-
- device_id_by_jingle_sid[jingle_sid] = parsed_data.sid;
- if (!content_names_by_jingle_sid.has_key(content_name)) {
- content_names_by_jingle_sid[content_name] = new ArrayList<string>();
- }
- content_names_by_jingle_sid[content_name].add(content_name);
-
- stream.get_flag(Xep.Jingle.Flag.IDENTITY).get_session.begin(jingle_sid, (_, res) => {
- Xep.Jingle.Session? session = stream.get_flag(Xep.Jingle.Flag.IDENTITY).get_session.end(res);
- if (session == null || !session.contents_map.has_key(content_name)) return;
- var encryption = new OmemoContentEncryption(NS_URI, "OMEMO", iq.from.bare_jid, device_id_by_jingle_sid[jingle_sid]);
- session.contents_map[content_name].encryptions[NS_URI] = encryption;
-
- if (iq.stanza.get_deep_attribute(Xep.Jingle.NS_URI + ":jingle", "action") == "session-accept") {
- session.additional_content_add_incoming.connect(on_content_add_received);
- }
- });
-
- break;
- } catch (Error e) {
- debug("Decrypting message from %s/%d failed: %s", iq.from.bare_jid.to_string(), parsed_data.sid, e.message);
- }
- }
- }
- }
-
- private void on_preprocess_outgoing_iq_set_get(XmppStream stream, Xmpp.Iq.Stanza iq) {
- if (iq.type_ != Iq.Stanza.TYPE_SET) return;
-
- StanzaNode? jingle_node = iq.stanza.get_subnode("jingle", Xep.Jingle.NS_URI);
- if (jingle_node == null) return;
-
- int device_id = -1;
- string? sid = jingle_node.get_attribute("sid", Xep.Jingle.NS_URI);
- if (sid != null && device_id_by_jingle_sid.has_key(sid)) {
- device_id = device_id_by_jingle_sid[sid];
- }
-
- StanzaNode? muji_node = jingle_node.get_subnode("muji", Xep.Muji.NS_URI);
- if (muji_node != null) {
- string muji_room = muji_node.get_attribute("room");
- try {
- Jid muji_jid = Jid.from_string(muji_room);
- if (device_id_by_muji_member.has_key(@"$(muji_jid.bare_jid)/$(iq.to)")) {
- device_id = device_id_by_muji_member[@"$(muji_jid.bare_jid)/$(iq.to)"];
- }
- } catch (InvalidJidError e) {
- // Ignore
- }
- }
-
- if (device_id == -1) return;
-
- Gee.List<StanzaNode> content_nodes = jingle_node.get_subnodes("content", Xep.Jingle.NS_URI);
- if (content_nodes.size == 0) return;
-
- foreach (StanzaNode content_node in content_nodes) {
- StanzaNode? transport_node = content_node.get_subnode("transport", Xep.JingleIceUdp.NS_URI);
- if (transport_node == null) continue;
- StanzaNode? fingerprint_node = transport_node.get_subnode("fingerprint", Xep.JingleIceUdp.DTLS_NS_URI);
- if (fingerprint_node == null) continue;
- string fingerprint = fingerprint_node.get_deep_string_content();
-
- StanzaNode? encrypted_node = null;
- try {
- Xep.Omemo.OmemoEncryptor encryptor = stream.get_module(Xep.Omemo.OmemoEncryptor.IDENTITY);
- Xep.Omemo.EncryptionData enc_data = encryptor.encrypt_plaintext(fingerprint);
- encryptor.encrypt_key(enc_data, iq.to.bare_jid, device_id);
- encrypted_node = enc_data.get_encrypted_node();
- } catch (Error e) {
- warning("Error while OMEMO-encrypting call keys: %s", e.message);
- return;
- }
-
- StanzaNode new_fingerprint_node = new StanzaNode.build("fingerprint", NS_URI).add_self_xmlns().put_node(encrypted_node);
- string? hash_attr = fingerprint_node.get_attribute("hash", Xep.JingleIceUdp.DTLS_NS_URI);
- string? setup_attr = fingerprint_node.get_attribute("setup", Xep.JingleIceUdp.DTLS_NS_URI);
- if (hash_attr != null) new_fingerprint_node.put_attribute("hash", hash_attr);
- if (setup_attr != null) new_fingerprint_node.put_attribute("setup", setup_attr);
- transport_node.put_node(new_fingerprint_node);
-
- transport_node.sub_nodes.remove(fingerprint_node);
- }
- }
-
- private void on_message_received(XmppStream stream, Xmpp.MessageStanza message) {
- StanzaNode? proceed_node = message.stanza.get_subnode("proceed", Xep.JingleMessageInitiation.NS_URI);
- if (proceed_node == null) return;
-
- string? jingle_sid = proceed_node.get_attribute("id");
- if (jingle_sid == null) return;
-
- StanzaNode? device_node = proceed_node.get_subnode("device", NS_URI);
- if (device_node == null) return;
-
- int device_id = device_node.get_attribute_int("id", -1);
- if (device_id == -1) return;
-
- device_id_by_jingle_sid[jingle_sid] = device_id;
- }
-
- private void on_session_initiate_received(XmppStream stream, Xep.Jingle.Session session) {
- if (device_id_by_jingle_sid.has_key(session.sid)) {
- foreach (Xep.Jingle.Content content in session.contents) {
- on_content_add_received(stream, content);
- }
- }
- session.additional_content_add_incoming.connect(on_content_add_received);
- }
-
- private void on_content_add_received(XmppStream stream, Xep.Jingle.Content content) {
- if (!content_names_by_jingle_sid.has_key(content.session.sid) || content_names_by_jingle_sid[content.session.sid].contains(content.content_name)) {
- var encryption = new OmemoContentEncryption(NS_URI, "OMEMO", content.peer_full_jid.bare_jid, device_id_by_jingle_sid[content.session.sid]);
- content.encryptions[encryption.encryption_ns] = encryption;
- }
- }
-
- private void on_pre_send_presence_stanza(XmppStream stream, Presence.Stanza presence) {
- StanzaNode? muji_node = presence.stanza.get_subnode("muji", Xep.Muji.NS_URI);
- if (muji_node == null) return;
-
- StanzaNode device_node = new StanzaNode.build("device", NS_URI).add_self_xmlns()
- .put_attribute("id", stream.get_module(Omemo.StreamModule.IDENTITY).store.local_registration_id.to_string());
- muji_node.put_node(device_node);
- }
-
- private void on_received_available(XmppStream stream, Presence.Stanza presence) {
- StanzaNode? muji_node = presence.stanza.get_subnode("muji", Xep.Muji.NS_URI);
- if (muji_node == null) return;
-
- StanzaNode? device_node = muji_node.get_subnode("device", NS_URI);
- if (device_node == null) return;
-
- int device_id = device_node.get_attribute_int("id", -1);
- if (device_id == -1) return;
-
- StanzaNode? muc_x_node = presence.stanza.get_subnode("x", "http://jabber.org/protocol/muc#user");
- if (muc_x_node == null) return;
-
- StanzaNode? item_node = muc_x_node.get_subnode("item");
- if (item_node == null) return;
-
- Jid? real_jid = null;
- try {
- string jid_attribute = item_node.get_attribute("jid");
- if (jid_attribute == null) return;
- real_jid = Jid.from_string(jid_attribute);
- } catch (InvalidJidError e) {
- // Ignore
- return;
- }
-
- device_id_by_muji_member[@"$(presence.from.bare_jid)/$(real_jid)"] = device_id;
- }
-
- public override void attach(XmppStream stream) {
- stream.get_module(Xmpp.MessageModule.IDENTITY).received_message.connect(on_message_received);
- stream.get_module(Xmpp.MessageModule.IDENTITY).send_pipeline.connect(send_listener);
- stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_incoming_iq_set_get.connect(on_preprocess_incoming_iq_set_get);
- stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_outgoing_iq_set_get.connect(on_preprocess_outgoing_iq_set_get);
- stream.get_module(Xep.Jingle.Module.IDENTITY).session_initiate_received.connect(on_session_initiate_received);
- stream.get_module(Xmpp.Presence.Module.IDENTITY).pre_send_presence_stanza.connect(on_pre_send_presence_stanza);
- stream.get_module(Xmpp.Presence.Module.IDENTITY).received_available.connect(on_received_available);
- }
-
- public override void detach(XmppStream stream) {
- stream.get_module(Xmpp.MessageModule.IDENTITY).received_message.disconnect(on_message_received);
- stream.get_module(Xmpp.MessageModule.IDENTITY).send_pipeline.disconnect(send_listener);
- stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_incoming_iq_set_get.disconnect(on_preprocess_incoming_iq_set_get);
- stream.get_module(Xmpp.Iq.Module.IDENTITY).preprocess_outgoing_iq_set_get.disconnect(on_preprocess_outgoing_iq_set_get);
- stream.get_module(Xep.Jingle.Module.IDENTITY).session_initiate_received.disconnect(on_session_initiate_received);
- stream.get_module(Xmpp.Presence.Module.IDENTITY).received_available.disconnect(on_received_available);
- }
-
- public override string get_ns() { return NS_URI; }
-
- public override string get_id() { return IDENTITY.id; }
- }
-
- public class VerificationSendListener : StanzaListener<MessageStanza> {
-
- private string[] after_actions_const = {};
-
- public override string action_group { get { return "REWRITE_NODES"; } }
- public override string[] after_actions { get { return after_actions_const; } }
-
- public override async bool run(XmppStream stream, MessageStanza message) {
- StanzaNode? proceed_node = message.stanza.get_subnode("proceed", Xep.JingleMessageInitiation.NS_URI);
- if (proceed_node == null) return false;
-
- StanzaNode device_node = new StanzaNode.build("device", NS_URI).add_self_xmlns()
- .put_attribute("id", stream.get_module(Omemo.StreamModule.IDENTITY).store.local_registration_id.to_string());
- proceed_node.put_node(device_node);
- return false;
- }
- }
-
- public class OmemoContentEncryption : Xep.Jingle.ContentEncryption {
- public Jid jid { get; set; }
- public int sid { get; set; }
-
- public OmemoContentEncryption(string encryption_ns, string encryption_name, Jid jid, int sid) {
- base(encryption_ns, encryption_name);
- this.jid = jid;
- this.sid = sid;
- }
- }
-}
-
diff --git a/plugins/omemo/src/file_transfer/file_decryptor.vala b/plugins/omemo/src/file_transfer/file_decryptor.vala
deleted file mode 100644
index 80303789..00000000
--- a/plugins/omemo/src/file_transfer/file_decryptor.vala
+++ /dev/null
@@ -1,90 +0,0 @@
-using Dino.Entities;
-
-using Crypto;
-using Omemo;
-
-namespace Dino.Plugins.Omemo {
-
-public class OmemoHttpFileReceiveData : HttpFileReceiveData {
- public string original_url;
-}
-
-public class OmemoFileDecryptor : FileDecryptor, Object {
-
- private Regex url_regex = /^aesgcm:\/\/(.*)#(([A-Fa-f0-9]{2}){48}|([A-Fa-f0-9]{2}){44})$/;
-
- public Encryption get_encryption() {
- return Encryption.OMEMO;
- }
-
- public FileReceiveData prepare_get_meta_info(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) {
- HttpFileReceiveData? http_receive_data = receive_data as HttpFileReceiveData;
- if (http_receive_data == null) assert(false);
- if ((receive_data as OmemoHttpFileReceiveData) != null) return receive_data;
-
- var omemo_http_receive_data = new OmemoHttpFileReceiveData();
- omemo_http_receive_data.url = aesgcm_to_https_link(http_receive_data.url);
- omemo_http_receive_data.original_url = http_receive_data.url;
-
- return omemo_http_receive_data;
- }
-
- public FileMeta prepare_download_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data, FileMeta file_meta) {
- if (file_meta.file_name != null) {
- file_meta.file_name = file_meta.file_name.split("#")[0];
- }
- return file_meta;
- }
-
- public bool can_decrypt_file(Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) {
- HttpFileReceiveData? http_file_receive = receive_data as HttpFileReceiveData;
- if (http_file_receive == null) return false;
-
- return this.url_regex.match(http_file_receive.url) || (receive_data as OmemoHttpFileReceiveData) != null;
- }
-
- public async InputStream decrypt_file(InputStream encrypted_stream, Conversation conversation, FileTransfer file_transfer, FileReceiveData receive_data) throws FileReceiveError {
- const uint KEY_SIZE = 32;
- try {
- OmemoHttpFileReceiveData? omemo_http_receive_data = receive_data as OmemoHttpFileReceiveData;
- if (omemo_http_receive_data == null) assert(false);
-
- // Decode IV and key
- MatchInfo match_info;
- this.url_regex.match(omemo_http_receive_data.original_url, 0, out match_info);
- uint8[] iv_and_key = hex_to_bin(match_info.fetch(2).up());
- uint8[] iv = iv_and_key[0:iv_and_key.length-KEY_SIZE];
- uint8[] key = iv_and_key[iv_and_key.length-KEY_SIZE:iv_and_key.length];
-
- file_transfer.encryption = Encryption.OMEMO;
- debug("Decrypting file %s from %s", file_transfer.file_name, file_transfer.server_file_name);
-
- SymmetricCipher cipher = new SymmetricCipher("AES-GCM");
- cipher.set_key(key);
- cipher.set_iv(iv);
- return new ConverterInputStream(encrypted_stream, new SymmetricCipherDecrypter((owned) cipher, 16));
-
- } catch (Crypto.Error e) {
- throw new FileReceiveError.DECRYPTION_FAILED("OMEMO file decryption error: %s".printf(e.message));
- } catch (GLib.Error e) {
- throw new FileReceiveError.DECRYPTION_FAILED("OMEMO file decryption error: %s".printf(e.message));
- }
- }
-
- private uint8[] hex_to_bin(string hex) {
- uint8[] bin = new uint8[hex.length / 2];
- const string HEX = "0123456789ABCDEF";
- for (int i = 0; i < hex.length / 2; i++) {
- bin[i] = (uint8) (HEX.index_of_char(hex[i*2]) << 4) | HEX.index_of_char(hex[i*2+1]);
- }
- return bin;
- }
-
- private string aesgcm_to_https_link(string aesgcm_link) {
- MatchInfo match_info;
- this.url_regex.match(aesgcm_link, 0, out match_info);
- return "https://" + match_info.fetch(1);
- }
-}
-
-}
diff --git a/plugins/omemo/src/file_transfer/file_encryptor.vala b/plugins/omemo/src/file_transfer/file_encryptor.vala
deleted file mode 100644
index 58be7ef1..00000000
--- a/plugins/omemo/src/file_transfer/file_encryptor.vala
+++ /dev/null
@@ -1,76 +0,0 @@
-using Gee;
-using Gtk;
-
-using Crypto;
-using Dino.Entities;
-using Xmpp;
-using Omemo;
-
-namespace Dino.Plugins.Omemo {
-
-public class OmemoHttpFileMeta : HttpFileMeta {
- public uint8[] iv;
- public uint8[] key;
-}
-
-public class OmemoFileEncryptor : Dino.FileEncryptor, Object {
-
- public bool can_encrypt_file(Conversation conversation, FileTransfer file_transfer) {
- return file_transfer.encryption == Encryption.OMEMO;
- }
-
- public FileMeta encrypt_file(Conversation conversation, FileTransfer file_transfer) throws FileSendError {
- const uint KEY_SIZE = 32;
- const uint IV_SIZE = 12;
- var omemo_http_file_meta = new OmemoHttpFileMeta();
-
- try {
- //Create a key and use it to encrypt the file
- uint8[] iv = new uint8[IV_SIZE];
- Plugin.get_context().randomize(iv);
- uint8[] key = new uint8[KEY_SIZE];
- Plugin.get_context().randomize(key);
-
- SymmetricCipher cipher = new SymmetricCipher("AES-GCM");
- cipher.set_key(key);
- cipher.set_iv(iv);
-
- omemo_http_file_meta.iv = iv;
- omemo_http_file_meta.key = key;
- omemo_http_file_meta.size = file_transfer.size + 16;
- omemo_http_file_meta.content_type = new FileContentType.from_mime_type("application/octet-stream");
- file_transfer.input_stream = new ConverterInputStream(file_transfer.input_stream, new SymmetricCipherEncrypter((owned) cipher, 16));
- } catch (Crypto.Error error) {
- throw new FileSendError.ENCRYPTION_FAILED("OMEMO file encryption error: %s".printf(error.message));
- } catch (GLib.Error error) {
- throw new FileSendError.ENCRYPTION_FAILED("OMEMO file encryption error: %s".printf(error.message));
- }
-
- debug("Encrypting file %s as %s", file_transfer.file_name, file_transfer.server_file_name);
-
- return omemo_http_file_meta;
- }
-
- public FileSendData? preprocess_send_file(Conversation conversation, FileTransfer file_transfer, FileSendData file_send_data, FileMeta file_meta) {
- HttpFileSendData? send_data = file_send_data as HttpFileSendData;
- if (send_data == null) return null;
-
- OmemoHttpFileMeta? omemo_http_file_meta = file_meta as OmemoHttpFileMeta;
- if (omemo_http_file_meta == null) return null;
-
- // Convert iv and key to hex
- string iv_and_key = "";
- foreach (uint8 byte in omemo_http_file_meta.iv) iv_and_key += byte.to_string("%02x");
- foreach (uint8 byte in omemo_http_file_meta.key) iv_and_key += byte.to_string("%02x");
-
- string aesgcm_link = send_data.url_down + "#" + iv_and_key;
- aesgcm_link = "aesgcm://" + aesgcm_link.substring(8); // replace https:// by aesgcm://
-
- send_data.url_down = aesgcm_link;
- send_data.encrypt_message = true;
-
- return file_send_data;
- }
-}
-
-}
diff --git a/plugins/omemo/src/jingle/jet_omemo.vala b/plugins/omemo/src/jingle/jet_omemo.vala
deleted file mode 100644
index 2c364625..00000000
--- a/plugins/omemo/src/jingle/jet_omemo.vala
+++ /dev/null
@@ -1,114 +0,0 @@
-using Crypto;
-using Dino;
-using Dino.Entities;
-using Gee;
-using Omemo;
-using Xmpp;
-using Xmpp.Xep;
-
-namespace Dino.Plugins.JetOmemo {
-
-private const string NS_URI = "urn:xmpp:jingle:jet-omemo:0";
-private const string AES_128_GCM_URI = "urn:xmpp:ciphers:aes-128-gcm-nopadding";
-
-public class Module : XmppStreamModule, Jet.EnvelopEncoding {
- public static Xmpp.ModuleIdentity<Module> IDENTITY = new Xmpp.ModuleIdentity<Module>(NS_URI, "0396_jet_omemo");
- const uint KEY_SIZE = 16;
- const uint IV_SIZE = 12;
-
- public override void attach(XmppStream stream) {
- if (stream.get_module(Jet.Module.IDENTITY) != null) {
- stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI);
- stream.get_module(Jet.Module.IDENTITY).register_envelop_encoding(this);
- stream.get_module(Jet.Module.IDENTITY).register_cipher(new AesGcmCipher(KEY_SIZE, IV_SIZE, AES_128_GCM_URI));
- }
- }
-
- public override void detach(XmppStream stream) {
- stream.get_module(ServiceDiscovery.Module.IDENTITY).remove_feature(stream, NS_URI);
- }
-
- 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(Xep.Jet.Module.IDENTITY).is_available(stream, full_jid);
- }
-
- public string get_type_uri() {
- return Omemo.NS_URI;
- }
-
- public Jet.TransportSecret decode_envolop(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, StanzaNode security) throws Jingle.IqError {
- StanzaNode? encrypted = security.get_subnode("encrypted", Omemo.NS_URI);
- if (encrypted == null) throw new Jingle.IqError.BAD_REQUEST("Invalid JET-OMEMO envelop: missing encrypted element");
-
- Xep.Omemo.OmemoDecryptor decryptor = stream.get_module(Xep.Omemo.OmemoDecryptor.IDENTITY);
-
- Xmpp.Xep.Omemo.ParsedData? data = decryptor.parse_node(encrypted);
- if (data == null) throw new Jingle.IqError.BAD_REQUEST("Invalid JET-OMEMO envelop: bad encrypted element");
-
- foreach (Bytes encr_key in data.our_potential_encrypted_keys.keys) {
- data.is_prekey = data.our_potential_encrypted_keys[encr_key];
- data.encrypted_key = encr_key.get_data();
-
- try {
- uint8[] key = decryptor.decrypt_key(data, peer_full_jid.bare_jid);
- return new Jet.TransportSecret(key, data.iv);
- } catch (GLib.Error e) {
- debug("Decrypting JET key from %s/%d failed: %s", peer_full_jid.bare_jid.to_string(), data.sid, e.message);
- }
- }
- throw new Jingle.IqError.NOT_ACCEPTABLE("Not encrypted for targeted device");
- }
-
- public void encode_envelop(XmppStream stream, Jid local_full_jid, Jid peer_full_jid, Jet.SecurityParameters security_params, StanzaNode security) {
- Store store = stream.get_module(Omemo.StreamModule.IDENTITY).store;
-
- var encryption_data = new Xep.Omemo.EncryptionData(store.local_registration_id);
- encryption_data.iv = security_params.secret.initialization_vector;
- encryption_data.keytag = security_params.secret.transport_key;
- Xep.Omemo.OmemoEncryptor encryptor = stream.get_module(Xep.Omemo.OmemoEncryptor.IDENTITY);
- encryptor.encrypt_key_to_recipient(stream, encryption_data, peer_full_jid.bare_jid);
-
- security.put_node(encryption_data.get_encrypted_node());
- }
-
- public override string get_ns() { return NS_URI; }
- public override string get_id() { return IDENTITY.id; }
-}
-
-public class AesGcmCipher : Jet.Cipher, Object {
- private uint key_size;
- private uint default_iv_size;
- private string uri;
- public AesGcmCipher(uint key_size, uint default_iv_size, string uri) {
- this.key_size = key_size;
- this.default_iv_size = default_iv_size;
- this.uri = uri;
- }
- public string get_cipher_uri() {
- return uri;
- }
- public Jet.TransportSecret generate_random_secret() {
- uint8[] iv = new uint8[default_iv_size];
- Omemo.Plugin.get_context().randomize(iv);
- uint8[] key = new uint8[key_size];
- Omemo.Plugin.get_context().randomize(key);
- return new Jet.TransportSecret(key, iv);
- }
- public InputStream wrap_input_stream(InputStream input, Jet.TransportSecret secret) requires (secret.transport_key.length == key_size) {
- SymmetricCipher cipher = new SymmetricCipher("AES-GCM");
- cipher.set_key(secret.transport_key);
- cipher.set_iv(secret.initialization_vector);
- return new ConverterInputStream(input, new SymmetricCipherDecrypter((owned) cipher, 16));
- }
- public OutputStream wrap_output_stream(OutputStream output, Jet.TransportSecret secret) requires (secret.transport_key.length == key_size) {
- Crypto.SymmetricCipher cipher = new SymmetricCipher("AES-GCM");
- cipher.set_key(secret.transport_key);
- cipher.set_iv(secret.initialization_vector);
- return new ConverterOutputStream(output, new SymmetricCipherEncrypter((owned) cipher, 16));
- }
-}
-}
diff --git a/plugins/omemo/src/jingle/jingle_helper.vala b/plugins/omemo/src/jingle/jingle_helper.vala
deleted file mode 100644
index ec6c0eca..00000000
--- a/plugins/omemo/src/jingle/jingle_helper.vala
+++ /dev/null
@@ -1,53 +0,0 @@
-using Dino.Entities;
-using Xmpp;
-
-namespace Dino.Plugins.JetOmemo {
-public class EncryptionHelper : JingleFileEncryptionHelper, Object {
- private StreamInteractor stream_interactor;
-
- public EncryptionHelper(StreamInteractor stream_interactor) {
- this.stream_interactor = stream_interactor;
- }
-
- public bool can_transfer(Conversation conversation) {
- return true;
- }
-
- public async bool can_encrypt(Conversation conversation, FileTransfer file_transfer, Jid? full_jid) {
- XmppStream? stream = stream_interactor.get_stream(conversation.account);
- if (stream == null) return false;
-
- Gee.List<Jid>? resources = stream.get_flag(Presence.Flag.IDENTITY).get_resources(conversation.counterpart);
- if (resources == null) return false;
-
- if (full_jid == null) {
- foreach (Jid test_jid in resources) {
- if (yield stream.get_module(Module.IDENTITY).is_available(stream, test_jid)) {
- return true;
- }
- }
- } else {
- if (yield stream.get_module(Module.IDENTITY).is_available(stream, full_jid)) {
- return true;
- }
- }
- return false;
- }
-
- public string? get_precondition_name(Conversation conversation, FileTransfer file_transfer) {
- return Xep.Jet.NS_URI;
- }
-
- public Object? get_precondition_options(Conversation conversation, FileTransfer file_transfer) {
- return new Xep.Jet.Options(Omemo.NS_URI, AES_128_GCM_URI);
- }
-
- public Encryption get_encryption(Xmpp.Xep.JingleFileTransfer.FileTransfer jingle_transfer) {
- Xep.Jet.SecurityParameters? security = jingle_transfer.security as Xep.Jet.SecurityParameters;
- if (security != null && security.encoding.get_type_uri() == Omemo.NS_URI) {
- return Encryption.OMEMO;
- }
- return Encryption.NONE;
- }
-}
-}
diff --git a/plugins/omemo/src/logic/database.vala b/plugins/omemo/src/logic/database.vala
deleted file mode 100644
index ec5a0924..00000000
--- a/plugins/omemo/src/logic/database.vala
+++ /dev/null
@@ -1,284 +0,0 @@
-using Gee;
-using Qlite;
-
-using Dino.Entities;
-
-namespace Dino.Plugins.Omemo {
-
-public class Database : Qlite.Database {
- private const int VERSION = 5;
-
- public class IdentityMetaTable : Table {
- //Default to provide backwards compatability
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true, min_version = 2, default = "-1" };
- public Column<string> address_name = new Column.Text("address_name") { not_null = true };
- public Column<int> device_id = new Column.Integer("device_id") { not_null = true };
- public Column<string?> identity_key_public_base64 = new Column.Text("identity_key_public_base64");
- public Column<bool> trusted_identity = new Column.BoolInt("trusted_identity") { default = "0", max_version = 1 };
- public Column<int> trust_level = new Column.Integer("trust_level") { default = TrustLevel.UNKNOWN.to_string(), min_version = 2 };
- public Column<bool> now_active = new Column.BoolInt("now_active") { default = "1" };
- public Column<long> last_active = new Column.Long("last_active");
- public Column<long> last_message_untrusted = new Column.Long("last_message_untrusted") { min_version = 5 };
- public Column<long> last_message_undecryptable = new Column.Long("last_message_undecryptable") { min_version = 5 };
-
- internal IdentityMetaTable(Database db) {
- base(db, "identity_meta");
- init({identity_id, address_name, device_id, identity_key_public_base64, trusted_identity, trust_level, now_active, last_active, last_message_untrusted, last_message_undecryptable});
- index("identity_meta_idx", {identity_id, address_name, device_id}, true);
- index("identity_meta_list_idx", {identity_id, address_name});
- }
-
- public QueryBuilder with_address(int identity_id, string address_name) {
- return select().with(this.identity_id, "=", identity_id).with(this.address_name, "=", address_name);
- }
-
- public QueryBuilder get_with_device_id(int identity_id, int device_id) {
- return select().with(this.identity_id, "=", identity_id).with(this.device_id, "=", device_id);
- }
-
- public void insert_device_list(int32 identity_id, string address_name, ArrayList<int32> devices) {
- update().with(this.identity_id, "=", identity_id).with(this.address_name, "=", address_name).set(now_active, false).perform();
- foreach (int32 device_id in devices) {
- upsert()
- .value(this.identity_id, identity_id, true)
- .value(this.address_name, address_name, true)
- .value(this.device_id, device_id, true)
- .value(this.now_active, true)
- .value(this.last_active, (long) new DateTime.now_utc().to_unix())
- .perform();
- }
- }
-
- public int64 insert_device_bundle(int32 identity_id, string address_name, int device_id, Bundle bundle, TrustLevel trust) {
- if (bundle == null || bundle.identity_key == null) return -1;
- // Do not replace identity_key if it was known before, it should never change!
- string identity_key = Base64.encode(bundle.identity_key.serialize());
- RowOption row = with_address(identity_id, address_name).with(this.device_id, "=", device_id).single().row();
- if (row.is_present() && row[identity_key_public_base64] != null && row[identity_key_public_base64] != identity_key) {
- critical("Tried to change the identity key for a known device id. Likely an attack.");
- return -1;
- }
- return upsert()
- .value(this.identity_id, identity_id, true)
- .value(this.address_name, address_name, true)
- .value(this.device_id, device_id, true)
- .value(this.identity_key_public_base64, identity_key)
- .value(this.trust_level, trust).perform();
- }
-
- public int64 insert_device_session(int32 identity_id, string address_name, int device_id, string identity_key, TrustLevel trust) {
- RowOption row = with_address(identity_id, address_name).with(this.device_id, "=", device_id).single().row();
- if (row.is_present() && row[identity_key_public_base64] != null && row[identity_key_public_base64] != identity_key) {
- critical("Tried to change the identity key for a known device id. Likely an attack.");
- return -1;
- }
- return upsert()
- .value(this.identity_id, identity_id, true)
- .value(this.address_name, address_name, true)
- .value(this.device_id, device_id, true)
- .value(this.identity_key_public_base64, identity_key)
- .value(this.trust_level, trust).perform();
- }
-
- public void update_last_message_untrusted(int identity_id, int device_id, DateTime? time) {
- var stmt = update()
- .with(this.identity_id, "=", identity_id)
- .with(this.device_id, "=", device_id);
- if (time != null) {
- stmt.set(last_message_untrusted, (long)time.to_unix());
- } else {
- stmt.set_null(last_message_untrusted);
- }
- stmt.perform();
- }
-
- public void update_last_message_undecryptable(int identity_id, int device_id, DateTime? time) {
- var stmt = update()
- .with(this.identity_id, "=", identity_id)
- .with(this.device_id, "=", device_id);
- if (time != null) {
- stmt.set(last_message_undecryptable, (long)time.to_unix());
- } else {
- stmt.set_null(last_message_undecryptable);
- }
- stmt.perform();
- }
-
- public QueryBuilder get_trusted_devices(int identity_id, string address_name) {
- return this.with_address(identity_id, address_name)
- .with(this.trust_level, "!=", TrustLevel.UNTRUSTED)
- .with(this.now_active, "=", true);
- }
-
- public QueryBuilder get_known_devices(int identity_id, string address_name) {
- return this.with_address(identity_id, address_name)
- .with(this.trust_level, "!=", TrustLevel.UNKNOWN)
- .without_null(this.identity_key_public_base64);
- }
-
- public QueryBuilder get_unknown_devices(int identity_id, string address_name) {
- return this.with_address(identity_id, address_name)
- .with_null(this.identity_key_public_base64);
- }
-
- public QueryBuilder get_new_devices(int identity_id, string address_name) {
- return this.with_address(identity_id, address_name)
- .with(this.trust_level, "=", TrustLevel.UNKNOWN)
- .without_null(this.identity_key_public_base64);
- }
-
- public Row? get_device(int identity_id, string address_name, int device_id) {
- return this.with_address(identity_id, address_name)
- .with(this.device_id, "=", device_id).single().row().inner;
- }
- }
-
-
- public class TrustTable : Table {
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true };
- public Column<string> address_name = new Column.Text("address_name");
- public Column<bool> blind_trust = new Column.BoolInt("blind_trust") { default = "1" } ;
-
- internal TrustTable(Database db) {
- base(db, "trust");
- init({identity_id, address_name, blind_trust});
- index("trust_idx", {identity_id, address_name}, true);
- }
-
- public bool get_blind_trust(int32 identity_id, string address_name, bool def = false) {
- RowOption row = this.select().with(this.identity_id, "=", identity_id)
- .with(this.address_name, "=", address_name).single().row();
- if (row.is_present()) return row[blind_trust];
- return def;
- }
- }
-
- public class IdentityTable : Table {
- public Column<int> id = new Column.Integer("id") { primary_key = true, auto_increment = true };
- public Column<int> account_id = new Column.Integer("account_id") { unique = true, not_null = true };
- public Column<int> device_id = new Column.Integer("device_id") { not_null = true };
- public Column<string> identity_key_private_base64 = new Column.NonNullText("identity_key_private_base64");
- public Column<string> identity_key_public_base64 = new Column.NonNullText("identity_key_public_base64");
-
- internal IdentityTable(Database db) {
- base(db, "identity");
- init({id, account_id, device_id, identity_key_private_base64, identity_key_public_base64});
- }
-
- public int get_id(int account_id) {
- int id = -1;
- Row? row = this.row_with(this.account_id, account_id).inner;
- if (row != null) id = ((!)row)[this.id];
- return id;
- }
- }
-
- public class SignedPreKeyTable : Table {
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true };
- public Column<int> signed_pre_key_id = new Column.Integer("signed_pre_key_id") { not_null = true };
- public Column<string> record_base64 = new Column.NonNullText("record_base64");
-
- internal SignedPreKeyTable(Database db) {
- base(db, "signed_pre_key");
- init({identity_id, signed_pre_key_id, record_base64});
- unique({identity_id, signed_pre_key_id});
- index("signed_pre_key_idx", {identity_id, signed_pre_key_id}, true);
- }
- }
-
- public class PreKeyTable : Table {
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true };
- public Column<int> pre_key_id = new Column.Integer("pre_key_id") { not_null = true };
- public Column<string> record_base64 = new Column.NonNullText("record_base64");
-
- internal PreKeyTable(Database db) {
- base(db, "pre_key");
- init({identity_id, pre_key_id, record_base64});
- unique({identity_id, pre_key_id});
- index("pre_key_idx", {identity_id, pre_key_id}, true);
- }
- }
-
- public class SessionTable : Table {
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true };
- public Column<string> address_name = new Column.NonNullText("name");
- public Column<int> device_id = new Column.Integer("device_id") { not_null = true };
- public Column<string> record_base64 = new Column.NonNullText("record_base64");
-
- internal SessionTable(Database db) {
- base(db, "session");
- init({identity_id, address_name, device_id, record_base64});
- unique({identity_id, address_name, device_id});
- index("session_idx", {identity_id, address_name, device_id}, true);
- }
- }
-
- public class ContentItemMetaTable : Table {
- public Column<int> content_item_id = new Column.Integer("message_id") { primary_key = true };
- public Column<int> identity_id = new Column.Integer("identity_id") { not_null = true };
- public Column<string> address_name = new Column.Text("address_name") { not_null = true };
- public Column<int> device_id = new Column.Integer("device_id") { not_null = true };
- public Column<bool> trusted_when_received = new Column.BoolInt("trusted_when_received") { not_null = true, default = "1" };
-
- internal ContentItemMetaTable(Database db) {
- base(db, "content_item_meta");
- init({content_item_id, identity_id, address_name, device_id, trusted_when_received});
- index("content_item_meta_device_idx", {identity_id, device_id, address_name});
- }
-
- public RowOption with_content_item(ContentItem item) {
- return row_with(content_item_id, item.id);
- }
-
- public QueryBuilder with_device(int identity_id, string address_name, int device_id) {
- return select()
- .with(this.identity_id, "=", identity_id)
- .with(this.address_name, "=", address_name)
- .with(this.device_id, "=", device_id);
- }
- }
-
- public IdentityMetaTable identity_meta { get; private set; }
- public TrustTable trust { get; private set; }
- public IdentityTable identity { get; private set; }
- public SignedPreKeyTable signed_pre_key { get; private set; }
- public PreKeyTable pre_key { get; private set; }
- public SessionTable session { get; private set; }
- public ContentItemMetaTable content_item_meta { get; private set; }
-
- public Database(string fileName) {
- base(fileName, VERSION);
- identity_meta = new IdentityMetaTable(this);
- trust = new TrustTable(this);
- identity = new IdentityTable(this);
- signed_pre_key = new SignedPreKeyTable(this);
- pre_key = new PreKeyTable(this);
- session = new SessionTable(this);
- content_item_meta = new ContentItemMetaTable(this);
- init({identity_meta, trust, identity, signed_pre_key, pre_key, session, content_item_meta});
-
- try {
- exec("PRAGMA journal_mode = WAL");
- exec("PRAGMA synchronous = NORMAL");
- exec("PRAGMA secure_delete = ON");
- } catch (Error e) {
- error("Failed to set OMEMO database properties: %s", e.message);
- }
- }
-
- public override void migrate(long oldVersion) {
- if(oldVersion == 1) {
- try {
- exec("DROP INDEX identity_meta_idx");
- exec("DROP INDEX identity_meta_list_idx");
- exec("CREATE UNIQUE INDEX identity_meta_idx ON identity_meta (identity_id, address_name, device_id)");
- exec("CREATE INDEX identity_meta_list_idx ON identity_meta (identity_id, address_name)");
- } catch (Error e) {
- stderr.printf("Failed to migrate OMEMO database\n");
- Process.exit(-1);
- }
- }
- }
-}
-
-}
diff --git a/plugins/omemo/src/logic/decrypt.vala b/plugins/omemo/src/logic/decrypt.vala
deleted file mode 100644
index 2861b42f..00000000
--- a/plugins/omemo/src/logic/decrypt.vala
+++ /dev/null
@@ -1,210 +0,0 @@
-using Dino.Entities;
-using Qlite;
-using Gee;
-using Omemo;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
- public class OmemoDecryptor : Xep.Omemo.OmemoDecryptor {
-
- private Account account;
- private Store store;
- private Database db;
- private StreamInteractor stream_interactor;
- private TrustManager trust_manager;
-
- public override uint32 own_device_id { get { return store.local_registration_id; }}
-
- public OmemoDecryptor(Account account, StreamInteractor stream_interactor, TrustManager trust_manager, Database db, Store store) {
- this.account = account;
- this.stream_interactor = stream_interactor;
- this.trust_manager = trust_manager;
- this.db = db;
- this.store = store;
- }
-
- public bool decrypt_message(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) {
- StanzaNode? encrypted_node = stanza.stanza.get_subnode("encrypted", NS_URI);
- if (encrypted_node == null || MessageFlag.get_flag(stanza) != null || stanza.from == null) return false;
-
- if (!Plugin.ensure_context()) return false;
- int identity_id = db.identity.get_id(conversation.account.id);
-
- MessageFlag flag = new MessageFlag();
- stanza.add_flag(flag);
-
- Xep.Omemo.ParsedData? data = parse_node(encrypted_node);
- if (data == null) return false;
-
-
- foreach (Bytes encr_key in data.our_potential_encrypted_keys.keys) {
- data.is_prekey = data.our_potential_encrypted_keys[encr_key];
- data.encrypted_key = encr_key.get_data();
- Gee.List<Jid> possible_jids = get_potential_message_jids(message, data, identity_id);
- if (possible_jids.size == 0) {
- debug("Received message from unknown entity with device id %d", data.sid);
- }
-
- foreach (Jid possible_jid in possible_jids) {
- try {
- uint8[] key = decrypt_key(data, possible_jid);
- if (data.ciphertext != null) {
- string cleartext = arr_to_str(aes_decrypt(Cipher.AES_GCM_NOPADDING, key, data.iv, data.ciphertext));
- message.body = cleartext;
- }
-
- // If we figured out which real jid a message comes from due to decryption working, save it
- if (conversation.type_ == Conversation.Type.GROUPCHAT && message.real_jid == null) {
- message.real_jid = possible_jid;
- }
-
- message.encryption = Encryption.OMEMO;
-
- trust_manager.message_device_id_map[message] = data.sid;
- return true;
- } catch (Error e) {
- debug("Decrypting message from %s/%d failed: %s", possible_jid.to_string(), data.sid, e.message);
- }
- }
- }
-
- if (
- data.ciphertext != null && // Ratchet forwarding doesn't contain payload and might not include us, which is ok
- data.our_potential_encrypted_keys.size == 0 && // The message was not encrypted to us
- stream_interactor.module_manager.get_module(message.account, StreamModule.IDENTITY).store.local_registration_id != data.sid // Message from this device. Never encrypted to itself.
- ) {
- db.identity_meta.update_last_message_undecryptable(identity_id, data.sid, message.time);
- trust_manager.bad_message_state_updated(conversation.account, message.from, data.sid);
- }
-
- debug("Received OMEMO encryped message that could not be decrypted.");
- return false;
- }
-
- public Gee.List<Jid> get_potential_message_jids(Entities.Message message, Xmpp.Xep.Omemo.ParsedData data, int identity_id) {
- Gee.List<Jid> possible_jids = new ArrayList<Jid>();
- if (message.type_ == Message.Type.CHAT) {
- possible_jids.add(message.from.bare_jid);
- } else {
- if (message.real_jid != null) {
- possible_jids.add(message.real_jid.bare_jid);
- } else if (data.is_prekey) {
- // pre key messages do store the identity key, so we can use that to find the real jid
- PreKeyOmemoMessage msg = Plugin.get_context().deserialize_signal_pre_key_message(data.encrypted_key);
- string identity_key = Base64.encode(msg.identity_key.serialize());
- foreach (Row row in db.identity_meta.get_with_device_id(identity_id, data.sid).with(db.identity_meta.identity_key_public_base64, "=", identity_key)) {
- try {
- possible_jids.add(Jid.from_string(row[db.identity_meta.address_name]));
- } catch (InvalidJidError e) {
- warning("Ignoring invalid jid from database: %s", e.message);
- }
- }
- } else {
- // If we don't know the device name (MUC history w/o MAM), test decryption with all keys with fitting device id
- foreach (Row row in db.identity_meta.get_with_device_id(identity_id, data.sid)) {
- try {
- possible_jids.add(Jid.from_string(row[db.identity_meta.address_name]));
- } catch (InvalidJidError e) {
- warning("Ignoring invalid jid from database: %s", e.message);
- }
- }
- }
- }
- return possible_jids;
- }
-
- public override uint8[] decrypt_key(Xmpp.Xep.Omemo.ParsedData data, Jid from_jid) throws GLib.Error {
- int sid = data.sid;
- uint8[] ciphertext = data.ciphertext;
- uint8[] encrypted_key = data.encrypted_key;
-
- Address address = new Address(from_jid.to_string(), sid);
- uint8[] key;
-
- if (data.is_prekey) {
- int identity_id = db.identity.get_id(account.id);
- PreKeyOmemoMessage msg = Plugin.get_context().deserialize_signal_pre_key_message(encrypted_key);
- string identity_key = Base64.encode(msg.identity_key.serialize());
-
- bool ok = update_db_for_prekey(identity_id, identity_key, from_jid, sid);
- if (!ok) throw new GLib.Error(-1, 0, "Failed updating db for prekey");
-
- debug("Starting new session for decryption with device from %s/%d", from_jid.to_string(), sid);
- SessionCipher cipher = store.create_session_cipher(address);
- key = cipher.decrypt_pre_key_message(msg);
- // TODO: Finish session
- } else {
- debug("Continuing session for decryption with device from %s/%d", from_jid.to_string(), sid);
- OmemoMessage msg = Plugin.get_context().deserialize_signal_message(encrypted_key);
- SessionCipher cipher = store.create_session_cipher(address);
- key = cipher.decrypt_message(msg);
- }
-
- if (key.length >= 32) {
- int authtaglength = key.length - 16;
- uint8[] new_ciphertext = new uint8[ciphertext.length + authtaglength];
- uint8[] new_key = new uint8[16];
- Memory.copy(new_ciphertext, ciphertext, ciphertext.length);
- Memory.copy((uint8*)new_ciphertext + ciphertext.length, (uint8*)key + 16, authtaglength);
- Memory.copy(new_key, key, 16);
- data.ciphertext = new_ciphertext;
- key = new_key;
- }
-
- return key;
- }
-
- public override string decrypt(uint8[] ciphertext, uint8[] key, uint8[] iv) throws GLib.Error {
- return arr_to_str(aes_decrypt(Cipher.AES_GCM_NOPADDING, key, iv, ciphertext));
- }
-
- private bool update_db_for_prekey(int identity_id, string identity_key, Jid from_jid, int sid) {
- Row? device = db.identity_meta.get_device(identity_id, from_jid.to_string(), sid);
- if (device != null && device[db.identity_meta.identity_key_public_base64] != null) {
- if (device[db.identity_meta.identity_key_public_base64] != identity_key) {
- critical("Tried to use a different identity key for a known device id.");
- return false;
- }
- } else {
- debug("Learn new device from incoming message from %s/%d", from_jid.to_string(), sid);
- bool blind_trust = db.trust.get_blind_trust(identity_id, from_jid.to_string(), true);
- if (db.identity_meta.insert_device_session(identity_id, from_jid.to_string(), sid, identity_key, blind_trust ? TrustLevel.TRUSTED : TrustLevel.UNKNOWN) < 0) {
- critical("Failed learning a device.");
- return false;
- }
-
- XmppStream? stream = stream_interactor.get_stream(account);
- if (device == null && stream != null) {
- stream.get_module(StreamModule.IDENTITY).request_user_devicelist.begin(stream, from_jid);
- }
- }
- return true;
- }
-
- private string arr_to_str(uint8[] arr) {
- // null-terminate the array
- uint8[] rarr = new uint8[arr.length+1];
- Memory.copy(rarr, arr, arr.length);
- return (string)rarr;
- }
- }
-
- public class DecryptMessageListener : MessageListener {
- public string[] after_actions_const = new string[]{ };
- public override string action_group { get { return "DECRYPT"; } }
- public override string[] after_actions { get { return after_actions_const; } }
-
- private HashMap<Account, OmemoDecryptor> decryptors;
-
- public DecryptMessageListener(HashMap<Account, OmemoDecryptor> decryptors) {
- this.decryptors = decryptors;
- }
-
- public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) {
- decryptors[message.account].decrypt_message(message, stanza, conversation);
- return false;
- }
- }
-}
-
diff --git a/plugins/omemo/src/logic/encrypt.vala b/plugins/omemo/src/logic/encrypt.vala
deleted file mode 100644
index e5d11c69..00000000
--- a/plugins/omemo/src/logic/encrypt.vala
+++ /dev/null
@@ -1,131 +0,0 @@
-using Gee;
-using Omemo;
-using Dino.Entities;
-using Xmpp;
-using Xmpp.Xep.Omemo;
-
-namespace Dino.Plugins.Omemo {
-
- public class OmemoEncryptor : Xep.Omemo.OmemoEncryptor {
-
- private Account account;
- private Store store;
- private TrustManager trust_manager;
-
- public override uint32 own_device_id { get { return store.local_registration_id; }}
-
- public OmemoEncryptor(Account account, TrustManager trust_manager, Store store) {
- this.account = account;
- this.trust_manager = trust_manager;
- this.store = store;
- }
-
- public override Xep.Omemo.EncryptionData encrypt_plaintext(string plaintext) throws GLib.Error {
- const uint KEY_SIZE = 16;
- const uint IV_SIZE = 12;
-
- //Create a key and use it to encrypt the message
- uint8[] key = new uint8[KEY_SIZE];
- Plugin.get_context().randomize(key);
- uint8[] iv = new uint8[IV_SIZE];
- Plugin.get_context().randomize(iv);
-
- uint8[] aes_encrypt_result = aes_encrypt(Cipher.AES_GCM_NOPADDING, key, iv, plaintext.data);
- uint8[] ciphertext = aes_encrypt_result[0:aes_encrypt_result.length - 16];
- uint8[] tag = aes_encrypt_result[aes_encrypt_result.length - 16:aes_encrypt_result.length];
- uint8[] keytag = new uint8[key.length + tag.length];
- Memory.copy(keytag, key, key.length);
- Memory.copy((uint8*)keytag + key.length, tag, tag.length);
-
- var ret = new Xep.Omemo.EncryptionData(own_device_id);
- ret.ciphertext = ciphertext;
- ret.keytag = keytag;
- ret.iv = iv;
- return ret;
- }
-
- public EncryptState encrypt(MessageStanza message, Jid self_jid, Gee.List<Jid> recipients, XmppStream stream) {
-
- EncryptState status = new EncryptState();
- if (!Plugin.ensure_context()) return status;
- if (message.to == null) return status;
-
- try {
- EncryptionData enc_data = encrypt_plaintext(message.body);
- status = encrypt_key_to_recipients(enc_data, self_jid, recipients, stream);
-
- message.stanza.put_node(enc_data.get_encrypted_node());
- Xep.ExplicitEncryption.add_encryption_tag_to_message(message, NS_URI, "OMEMO");
- message.body = "[This message is OMEMO encrypted]";
- status.encrypted = true;
- } catch (Error e) {
- warning(@"error while encrypting message: $(e.message)\n");
- message.body = "[OMEMO encryption failed]";
- status.encrypted = false;
- }
- return status;
- }
-
- internal EncryptState encrypt_key_to_recipients(EncryptionData enc_data, Jid self_jid, Gee.List<Jid> recipients, XmppStream stream) throws Error {
- EncryptState status = new EncryptState();
-
- //Check we have the bundles and device lists needed to send the message
- if (!trust_manager.is_known_address(account, self_jid)) return status;
- status.own_list = true;
- status.own_devices = trust_manager.get_trusted_devices(account, self_jid).size;
- status.other_waiting_lists = 0;
- status.other_devices = 0;
- foreach (Jid recipient in recipients) {
- if (!trust_manager.is_known_address(account, recipient)) {
- status.other_waiting_lists++;
- }
- if (status.other_waiting_lists > 0) return status;
- status.other_devices += trust_manager.get_trusted_devices(account, recipient).size;
- }
- if (status.own_devices == 0 || status.other_devices == 0) return status;
-
-
- //Encrypt the key for each recipient's device individually
- foreach (Jid recipient in recipients) {
- EncryptionResult enc_res = encrypt_key_to_recipient(stream, enc_data, recipient);
- status.add_result(enc_res, false);
- }
-
- // Encrypt the key for each own device
- EncryptionResult enc_res = encrypt_key_to_recipient(stream, enc_data, self_jid);
- status.add_result(enc_res, true);
-
- return status;
- }
-
- public override EncryptionResult encrypt_key_to_recipient(XmppStream stream, Xep.Omemo.EncryptionData enc_data, Jid recipient) throws GLib.Error {
- var result = new EncryptionResult();
- StreamModule module = stream.get_module(StreamModule.IDENTITY);
-
- foreach(int32 device_id in trust_manager.get_trusted_devices(account, recipient)) {
- if (module.is_ignored_device(recipient, device_id)) {
- result.lost++;
- continue;
- }
- try {
- encrypt_key(enc_data, recipient, device_id);
- result.success++;
- } catch (Error e) {
- if (e.code == ErrorCode.UNKNOWN) result.unknown++;
- else result.failure++;
- }
- }
- return result;
- }
-
- public override void encrypt_key(Xep.Omemo.EncryptionData encryption_data, Jid jid, int32 device_id) throws GLib.Error {
- Address address = new Address(jid.to_string(), device_id);
- SessionCipher cipher = store.create_session_cipher(address);
- CiphertextMessage device_key = cipher.encrypt(encryption_data.keytag);
- address.device_id = 0;
- debug("Created encrypted key for %s/%d", jid.to_string(), device_id);
-
- encryption_data.add_device_key(device_id, device_key.serialized, device_key.type == CiphertextType.PREKEY);
- }
- }
-} \ No newline at end of file
diff --git a/plugins/omemo/src/logic/manager.vala b/plugins/omemo/src/logic/manager.vala
deleted file mode 100644
index 71f17aae..00000000
--- a/plugins/omemo/src/logic/manager.vala
+++ /dev/null
@@ -1,429 +0,0 @@
-using Dino.Entities;
-using Omemo;
-using Qlite;
-using Xmpp;
-using Gee;
-
-namespace Dino.Plugins.Omemo {
-
-public class Manager : StreamInteractionModule, Object {
- public static ModuleIdentity<Manager> IDENTITY = new ModuleIdentity<Manager>("omemo_manager");
- public string id { get { return IDENTITY.id; } }
-
- private StreamInteractor stream_interactor;
- private Database db;
- private TrustManager trust_manager;
- private HashMap<Account, OmemoEncryptor> encryptors;
- private Map<Entities.Message, MessageState> message_states = new HashMap<Entities.Message, MessageState>(Entities.Message.hash_func, Entities.Message.equals_func);
-
- private class MessageState {
- public Entities.Message msg { get; private set; }
- public Xep.Omemo.EncryptState last_try { get; private set; }
- public int waiting_other_sessions { get; set; }
- public int waiting_own_sessions { get; set; }
- public bool waiting_own_devicelist { get; set; }
- public int waiting_other_devicelists { get; set; }
- public bool force_next_attempt { get; set; }
- public bool will_send_now { get; private set; }
- public bool active_send_attempt { get; set; }
-
- public MessageState(Entities.Message msg, Xep.Omemo.EncryptState last_try) {
- update_from_encrypt_status(msg, last_try);
- }
-
- public void update_from_encrypt_status(Entities.Message msg, Xep.Omemo.EncryptState new_try) {
- this.msg = msg;
- this.last_try = new_try;
- this.waiting_other_sessions = new_try.other_unknown;
- this.waiting_own_sessions = new_try.own_unknown;
- this.waiting_own_devicelist = !new_try.own_list;
- this.waiting_other_devicelists = new_try.other_waiting_lists;
- this.active_send_attempt = false;
- will_send_now = false;
- if (new_try.other_failure > 0 || (new_try.other_lost == new_try.other_devices && new_try.other_devices > 0)) {
- msg.marked = Entities.Message.Marked.WONTSEND;
- } else if (new_try.other_unknown > 0 || new_try.own_unknown > 0 || new_try.other_waiting_lists > 0 || !new_try.own_list || new_try.own_devices == 0) {
- msg.marked = Entities.Message.Marked.UNSENT;
- } else if (!new_try.encrypted) {
- msg.marked = Entities.Message.Marked.WONTSEND;
- } else {
- will_send_now = true;
- }
- }
-
- public bool should_retry_now() {
- return !waiting_own_devicelist && waiting_other_devicelists <= 0 && waiting_other_sessions <= 0 && waiting_own_sessions <= 0 && !active_send_attempt;
- }
-
- public string to_string() {
- return @"MessageState (msg=$(msg.stanza_id), send=$will_send_now, $last_try)";
- }
- }
-
- private Manager(StreamInteractor stream_interactor, Database db, TrustManager trust_manager, HashMap<Account, OmemoEncryptor> encryptors) {
- this.stream_interactor = stream_interactor;
- this.db = db;
- this.trust_manager = trust_manager;
- this.encryptors = encryptors;
-
- stream_interactor.account_added.connect(on_account_added);
- stream_interactor.stream_negotiated.connect(on_stream_negotiated);
- stream_interactor.get_module(MessageProcessor.IDENTITY).pre_message_send.connect(on_pre_message_send);
- stream_interactor.get_module(RosterManager.IDENTITY).mutual_subscription.connect(on_mutual_subscription);
- }
-
- public void clear_device_list(Account account) {
- XmppStream? stream = stream_interactor.get_stream(account);
- if (stream == null) return;
-
- stream.get_module(StreamModule.IDENTITY).clear_device_list(stream);
- }
-
- private Gee.List<Jid> get_occupants(Jid jid, Account account){
- Gee.List<Jid> occupants = new ArrayList<Jid>(Jid.equals_bare_func);
- if(!stream_interactor.get_module(MucManager.IDENTITY).is_groupchat(jid, account)){
- occupants.add(jid);
- }
- Gee.List<Jid>? occupant_jids = stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(jid, account);
- if(occupant_jids == null) {
- return occupants;
- }
- foreach (Jid occupant in occupant_jids) {
- if(!occupant.equals(account.bare_jid)){
- occupants.add(occupant.bare_jid);
- }
- }
- return occupants;
- }
-
- private void on_pre_message_send(Entities.Message message, Xmpp.MessageStanza message_stanza, Conversation conversation) {
- if (message.encryption == Encryption.OMEMO) {
- if (message.type_ == Message.Type.GROUPCHAT_PM) {
- message.marked = Message.Marked.WONTSEND;
- return;
- }
- XmppStream? stream = stream_interactor.get_stream(conversation.account);
- if (stream == null) {
- message.marked = Entities.Message.Marked.UNSENT;
- return;
- }
- StreamModule? module_ = ((!)stream).get_module(StreamModule.IDENTITY);
- if (module_ == null) {
- message.marked = Entities.Message.Marked.UNSENT;
- return;
- }
- StreamModule module = (!)module_;
-
- //Get a list of everyone for whom the message should be encrypted
- Gee.List<Jid> recipients;
- if (message_stanza.type_ == MessageStanza.TYPE_GROUPCHAT) {
- recipients = get_occupants((!)message.to.bare_jid, conversation.account);
- if (recipients.size == 0) {
- message.marked = Entities.Message.Marked.WONTSEND;
- return;
- }
- } else {
- recipients = new ArrayList<Jid>(Jid.equals_bare_func);
- recipients.add(message_stanza.to);
- }
-
- //Attempt to encrypt the message
- Xep.Omemo.EncryptState enc_state = encryptors[conversation.account].encrypt(message_stanza, conversation.account.bare_jid, recipients, stream);
- MessageState state;
- lock (message_states) {
- if (message_states.has_key(message)) {
- state = message_states.get(message);
- state.update_from_encrypt_status(message, enc_state);
- if (state.will_send_now) {
- debug("sending message delayed: %s", state.to_string());
- }
- } else {
- state = new MessageState(message, enc_state);
- message_states[message] = state;
- }
- if (state.will_send_now) {
- message_states.unset(message);
- }
- }
-
- //Encryption failed - need to fetch more information
- if (!state.will_send_now) {
- if (message.marked == Entities.Message.Marked.WONTSEND) {
- debug("retracting message %s", state.to_string());
- message_states.unset(message);
- } else {
- debug("delaying message %s", state.to_string());
-
- if (state.waiting_own_sessions > 0) {
- module.fetch_bundles((!)stream, conversation.account.bare_jid, trust_manager.get_trusted_devices(conversation.account, conversation.account.bare_jid));
- }
- if (state.waiting_other_sessions > 0 && message.counterpart != null) {
- foreach(Jid jid in get_occupants(((!)message.counterpart).bare_jid, conversation.account)) {
- module.fetch_bundles((!)stream, jid, trust_manager.get_trusted_devices(conversation.account, jid));
- }
- }
- if (state.waiting_other_devicelists > 0 && message.counterpart != null) {
- foreach(Jid jid in get_occupants(((!)message.counterpart).bare_jid, conversation.account)) {
- module.request_user_devicelist.begin((!)stream, jid);
- }
- }
- }
- }
- }
- }
-
- private void on_mutual_subscription(Account account, Jid jid) {
- XmppStream? stream = stream_interactor.get_stream(account);
- if(stream == null) return;
-
- stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).request_user_devicelist.begin((!)stream, jid);
- }
-
- private void on_stream_negotiated(Account account, XmppStream stream) {
- StreamModule module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY);
- if (module != null) {
- module.request_user_devicelist.begin(stream, account.bare_jid);
- }
- }
-
- private void on_account_added(Account account) {
- StreamModule module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY);
- if (module != null) {
- module.device_list_loaded.connect((jid, devices) => on_device_list_loaded(account, jid, devices));
- module.bundle_fetched.connect((jid, device_id, bundle) => on_bundle_fetched(account, jid, device_id, bundle));
- module.bundle_fetch_failed.connect((jid) => continue_message_sending(account, jid));
- }
- initialize_store.begin(account);
- }
-
- private void on_device_list_loaded(Account account, Jid jid, ArrayList<int32> device_list) {
- debug("received device list for %s from %s", account.bare_jid.to_string(), jid.to_string());
-
- XmppStream? stream = stream_interactor.get_stream(account);
- if (stream == null) {
- return;
- }
- StreamModule? module = ((!)stream).get_module(StreamModule.IDENTITY);
- if (module == null) {
- return;
- }
-
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return;
-
- //Update meta database
- db.identity_meta.insert_device_list(identity_id, jid.bare_jid.to_string(), device_list);
-
- //Fetch the bundle for each new device
- int inc = 0;
- foreach (Row row in db.identity_meta.get_unknown_devices(identity_id, jid.bare_jid.to_string())) {
- try {
- module.fetch_bundle(stream, Jid.from_string(row[db.identity_meta.address_name]), row[db.identity_meta.device_id], false);
- inc++;
- } catch (InvalidJidError e) {
- warning("Ignoring device with invalid Jid: %s", e.message);
- }
- }
- if (inc > 0) {
- debug("new bundles %i/%i for %s", inc, device_list.size, jid.to_string());
- }
-
- //Create an entry for the jid in the account table if one does not exist already
- if (db.trust.select().with(db.trust.identity_id, "=", identity_id).with(db.trust.address_name, "=", jid.bare_jid.to_string()).count() == 0) {
- db.trust.insert().value(db.trust.identity_id, identity_id).value(db.trust.address_name, jid.bare_jid.to_string()).value(db.trust.blind_trust, true).perform();
- }
-
- //Get all messages that needed the devicelist and determine if we can now send them
- HashSet<Entities.Message> send_now = new HashSet<Entities.Message>();
- lock (message_states) {
- foreach (Entities.Message msg in message_states.keys) {
- if (!msg.account.equals(account)) continue;
- Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account);
- MessageState state = message_states[msg];
- if (account.bare_jid.equals(jid)) {
- state.waiting_own_devicelist = false;
- } else if (msg.counterpart != null && occupants.contains(jid)) {
- state.waiting_other_devicelists--;
- }
- if (state.should_retry_now()) {
- send_now.add(msg);
- state.active_send_attempt = true;
- }
- }
- }
- foreach (Entities.Message msg in send_now) {
- if (msg.counterpart == null) continue;
- Entities.Conversation? conv = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation(((!)msg.counterpart), account);
- if (conv == null) continue;
- stream_interactor.get_module(MessageProcessor.IDENTITY).send_xmpp_message(msg, (!)conv, true);
- }
-
- }
-
- private void on_bundle_fetched(Account account, Jid jid, int32 device_id, Bundle bundle) {
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return;
-
- bool blind_trust = db.trust.get_blind_trust(identity_id, jid.bare_jid.to_string(), true);
-
- //If we don't blindly trust new devices and we haven't seen this key before then don't trust it
- bool untrust = !(blind_trust || db.identity_meta.with_address(identity_id, jid.bare_jid.to_string())
- .with(db.identity_meta.device_id, "=", device_id)
- .with(db.identity_meta.identity_key_public_base64, "=", Base64.encode(bundle.identity_key.serialize()))
- .single().row().is_present());
-
- //Get trust information from the database if the device id is known
- Row device = db.identity_meta.get_device(identity_id, jid.bare_jid.to_string(), device_id);
- TrustLevel trusted = TrustLevel.UNKNOWN;
- if (device != null) {
- trusted = (TrustLevel) device[db.identity_meta.trust_level];
- }
-
- if(untrust) {
- trusted = TrustLevel.UNKNOWN;
- } else if (blind_trust && trusted == TrustLevel.UNKNOWN) {
- trusted = TrustLevel.TRUSTED;
- }
-
- //Update the database with the appropriate trust information
- db.identity_meta.insert_device_bundle(identity_id, jid.bare_jid.to_string(), device_id, bundle, trusted);
-
- if (should_start_session(account, jid)) {
- XmppStream? stream = stream_interactor.get_stream(account);
- if (stream != null) {
- StreamModule? module = ((!)stream).get_module(StreamModule.IDENTITY);
- if (module != null) {
- module.start_session(stream, jid, device_id, bundle);
- }
- }
- }
- continue_message_sending(account, jid);
- }
-
- private bool should_start_session(Account account, Jid jid) {
- lock (message_states) {
- foreach (Entities.Message msg in message_states.keys) {
- if (!msg.account.equals(account)) continue;
- Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account);
- if (account.bare_jid.equals(jid) || (msg.counterpart != null && (msg.counterpart.equals_bare(jid) || occupants.contains(jid)))) {
- return true;
- }
- }
- }
- return false;
- }
-
- private void continue_message_sending(Account account, Jid jid) {
- //Get all messages waiting and determine if they can now be sent
- HashSet<Entities.Message> send_now = new HashSet<Entities.Message>();
- lock (message_states) {
- foreach (Entities.Message msg in message_states.keys) {
- if (!msg.account.equals(account)) continue;
- Gee.List<Jid> occupants = get_occupants(msg.counterpart.bare_jid, account);
-
- MessageState state = message_states[msg];
-
- if (account.bare_jid.equals(jid)) {
- state.waiting_own_sessions--;
- } else if (msg.counterpart != null && (msg.counterpart.equals_bare(jid) || occupants.contains(jid))) {
- state.waiting_other_sessions--;
- }
- if (state.should_retry_now()){
- send_now.add(msg);
- state.active_send_attempt = true;
- }
- }
- }
- foreach (Entities.Message msg in send_now) {
- if (msg.counterpart == null) continue;
- Entities.Conversation? conv = stream_interactor.get_module(ConversationManager.IDENTITY).get_conversation((!)msg.counterpart, account);
- if (conv == null) continue;
- stream_interactor.get_module(MessageProcessor.IDENTITY).send_xmpp_message(msg, (!)conv, true);
- }
- }
-
- private async void initialize_store(Account account) {
- // If the account is not yet persisted, wait for that and then continue - without identity.account_id the entry isn't worth much.
- if (account.id == -1) {
- account.notify["id"].connect(() => initialize_store.callback());
- yield;
- }
- StreamModule? module = stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY);
- if (module == null) return;
- Store store = module.store;
- Qlite.Row? row = db.identity.row_with(db.identity.account_id, account.id).inner;
- int identity_id = -1;
- bool publish_identity = false;
-
- if (row == null) {
- // OMEMO not yet initialized, starting with empty base
- publish_identity = true;
- try {
- store.identity_key_store.local_registration_id = Random.int_range(1, int32.MAX);
-
- ECKeyPair key_pair = Plugin.get_context().generate_key_pair();
- store.identity_key_store.identity_key_private = new Bytes(key_pair.private.serialize());
- store.identity_key_store.identity_key_public = new Bytes(key_pair.public.serialize());
-
- identity_id = (int) db.identity.upsert()
- .value(db.identity.account_id, account.id, true)
- .value(db.identity.device_id, (int) store.local_registration_id)
- .value(db.identity.identity_key_private_base64, Base64.encode(store.identity_key_store.identity_key_private.get_data()))
- .value(db.identity.identity_key_public_base64, Base64.encode(store.identity_key_store.identity_key_public.get_data()))
- .perform();
- } catch (Error e) {
- // Ignore error
- }
- } else {
- store.identity_key_store.local_registration_id = ((!)row)[db.identity.device_id];
- store.identity_key_store.identity_key_private = new Bytes(Base64.decode(((!)row)[db.identity.identity_key_private_base64]));
- store.identity_key_store.identity_key_public = new Bytes(Base64.decode(((!)row)[db.identity.identity_key_public_base64]));
- identity_id = ((!)row)[db.identity.id];
- }
-
- if (identity_id >= 0) {
- store.signed_pre_key_store = new BackedSignedPreKeyStore(db, identity_id);
- store.pre_key_store = new BackedPreKeyStore(db, identity_id);
- store.session_store = new BackedSessionStore(db, identity_id);
- } else {
- warning("store for %s is not persisted!", account.bare_jid.to_string());
- }
-
- // Generated new device ID, ensure this gets added to the devicelist
- XmppStream? stream = stream_interactor.get_stream(account);
- if (stream != null) {
- module.request_user_devicelist.begin((!)stream, account.bare_jid);
- }
- }
-
- public async bool ensure_get_keys_for_conversation(Conversation conversation) {
- if (stream_interactor.get_module(MucManager.IDENTITY).is_private_room(conversation.account, conversation.counterpart)) {
- foreach (Jid offline_member in stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(conversation.counterpart, conversation.account)) {
- bool ok = yield ensure_get_keys_for_jid(conversation.account, offline_member);
- if (!ok) {
- return false;
- }
- }
- return true;
- }
-
- return yield ensure_get_keys_for_jid(conversation.account, conversation.counterpart.bare_jid);
- }
-
- public async bool ensure_get_keys_for_jid(Account account, Jid jid) {
- if (trust_manager.is_known_address(account, jid)) return true;
- XmppStream? stream = stream_interactor.get_stream(account);
- if (stream != null) {
- var device_list = yield stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).request_user_devicelist(stream, jid);
- return device_list.size > 0;
- }
- return true; // TODO wait for stream?
- }
-
- public static void start(StreamInteractor stream_interactor, Database db, TrustManager trust_manager, HashMap<Account, OmemoEncryptor> encryptors) {
- Manager m = new Manager(stream_interactor, db, trust_manager, encryptors);
- stream_interactor.add_module(m);
- }
-}
-
-}
diff --git a/plugins/omemo/src/logic/pre_key_store.vala b/plugins/omemo/src/logic/pre_key_store.vala
deleted file mode 100644
index c15acc84..00000000
--- a/plugins/omemo/src/logic/pre_key_store.vala
+++ /dev/null
@@ -1,45 +0,0 @@
-using Omemo;
-using Qlite;
-
-namespace Dino.Plugins.Omemo {
-
-private class BackedPreKeyStore : SimplePreKeyStore {
- private Database db;
- private int identity_id;
-
- public BackedPreKeyStore(Database db, int identity_id) {
- this.db = db;
- this.identity_id = identity_id;
- init();
- }
-
- private void init() {
- try {
- foreach (Row row in db.pre_key.select().with(db.pre_key.identity_id, "=", identity_id)) {
- store_pre_key(row[db.pre_key.pre_key_id], Base64.decode(row[db.pre_key.record_base64]));
- }
- } catch (Error e) {
- warning("Error while initializing pre key store: %s", e.message);
- }
-
- pre_key_stored.connect(on_pre_key_stored);
- pre_key_deleted.connect(on_pre_key_deleted);
- }
-
- public void on_pre_key_stored(PreKeyStore.Key key) {
- db.pre_key.upsert()
- .value(db.pre_key.identity_id, identity_id, true)
- .value(db.pre_key.pre_key_id, (int) key.key_id, true)
- .value(db.pre_key.record_base64, Base64.encode(key.record))
- .perform();
- }
-
- public void on_pre_key_deleted(PreKeyStore.Key key) {
- db.pre_key.delete()
- .with(db.pre_key.identity_id, "=", identity_id)
- .with(db.pre_key.pre_key_id, "=", (int) key.key_id)
- .perform();
- }
-}
-
-}
diff --git a/plugins/omemo/src/logic/session_store.vala b/plugins/omemo/src/logic/session_store.vala
deleted file mode 100644
index ea5738fd..00000000
--- a/plugins/omemo/src/logic/session_store.vala
+++ /dev/null
@@ -1,49 +0,0 @@
-using Omemo;
-using Qlite;
-
-namespace Dino.Plugins.Omemo {
-
-private class BackedSessionStore : SimpleSessionStore {
- private Database db;
- private int identity_id;
-
- public BackedSessionStore(Database db, int identity_id) {
- this.db = db;
- this.identity_id = identity_id;
- init();
- }
-
- private void init() {
- try {
- foreach (Row row in db.session.select().with(db.session.identity_id, "=", identity_id)) {
- Address addr = new Address(row[db.session.address_name], row[db.session.device_id]);
- store_session(addr, Base64.decode(row[db.session.record_base64]));
- addr.device_id = 0;
- }
- } catch (Error e) {
- print("Error while initializing session store: %s", e.message);
- }
-
- session_stored.connect(on_session_stored);
- session_removed.connect(on_session_deleted);
- }
-
- public void on_session_stored(SessionStore.Session session) {
- db.session.upsert()
- .value(db.session.identity_id, identity_id, true)
- .value(db.session.address_name, session.name, true)
- .value(db.session.device_id, session.device_id, true)
- .value(db.session.record_base64, Base64.encode(session.record))
- .perform();
- }
-
- public void on_session_deleted(SessionStore.Session session) {
- db.session.delete()
- .with(db.session.identity_id, "=", identity_id)
- .with(db.session.address_name, "=", session.name)
- .with(db.session.device_id, "=", session.device_id)
- .perform();
- }
-}
-
-}
diff --git a/plugins/omemo/src/logic/signed_pre_key_store.vala b/plugins/omemo/src/logic/signed_pre_key_store.vala
deleted file mode 100644
index d73cbe71..00000000
--- a/plugins/omemo/src/logic/signed_pre_key_store.vala
+++ /dev/null
@@ -1,45 +0,0 @@
-using Qlite;
-using Omemo;
-
-namespace Dino.Plugins.Omemo {
-
-private class BackedSignedPreKeyStore : SimpleSignedPreKeyStore {
- private Database db;
- private int identity_id;
-
- public BackedSignedPreKeyStore(Database db, int identity_id) {
- this.db = db;
- this.identity_id = identity_id;
- init();
- }
-
- private void init() {
- try {
- foreach (Row row in db.signed_pre_key.select().with(db.signed_pre_key.identity_id, "=", identity_id)) {
- store_signed_pre_key(row[db.signed_pre_key.signed_pre_key_id], Base64.decode(row[db.signed_pre_key.record_base64]));
- }
- } catch (Error e) {
- print("Error while initializing signed pre key store: %s", e.message);
- }
-
- signed_pre_key_stored.connect(on_signed_pre_key_stored);
- signed_pre_key_deleted.connect(on_signed_pre_key_deleted);
- }
-
- public void on_signed_pre_key_stored(SignedPreKeyStore.Key key) {
- db.signed_pre_key.upsert()
- .value(db.signed_pre_key.identity_id, identity_id, true)
- .value(db.signed_pre_key.signed_pre_key_id, (int) key.key_id, true)
- .value(db.signed_pre_key.record_base64, Base64.encode(key.record))
- .perform();
- }
-
- public void on_signed_pre_key_deleted(SignedPreKeyStore.Key key) {
- db.signed_pre_key.delete()
- .with(db.signed_pre_key.identity_id, "=", identity_id)
- .with(db.signed_pre_key.signed_pre_key_id, "=", (int) key.key_id)
- .perform();
- }
-}
-
-}
diff --git a/plugins/omemo/src/logic/trust_manager.vala b/plugins/omemo/src/logic/trust_manager.vala
deleted file mode 100644
index 8cf1ddeb..00000000
--- a/plugins/omemo/src/logic/trust_manager.vala
+++ /dev/null
@@ -1,141 +0,0 @@
-using Dino.Entities;
-using Gee;
-using Xmpp;
-using Omemo;
-using Qlite;
-
-namespace Dino.Plugins.Omemo {
-
-public class TrustManager {
-
- public signal void bad_message_state_updated(Account account, Jid jid, int device_id);
-
- private StreamInteractor stream_interactor;
- private Database db;
- private TagMessageListener tag_message_listener;
-
- public HashMap<Message, int> message_device_id_map = new HashMap<Message, int>(Message.hash_func, Message.equals_func);
-
- public TrustManager(StreamInteractor stream_interactor, Database db) {
- this.stream_interactor = stream_interactor;
- this.db = db;
-
- tag_message_listener = new TagMessageListener(stream_interactor, this, db, message_device_id_map);
- stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(tag_message_listener);
- }
-
- public void set_blind_trust(Account account, Jid jid, bool blind_trust) {
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return;
- db.trust.update()
- .with(db.trust.identity_id, "=", identity_id)
- .with(db.trust.address_name, "=", jid.bare_jid.to_string())
- .set(db.trust.blind_trust, blind_trust).perform();
- }
-
- public void set_device_trust(Account account, Jid jid, int device_id, TrustLevel trust_level) {
- int identity_id = db.identity.get_id(account.id);
- db.identity_meta.update()
- .with(db.identity_meta.identity_id, "=", identity_id)
- .with(db.identity_meta.address_name, "=", jid.bare_jid.to_string())
- .with(db.identity_meta.device_id, "=", device_id)
- .set(db.identity_meta.trust_level, trust_level).perform();
-
- // Hide messages from untrusted or unknown devices
- string selection = null;
- string[] selection_args = {};
- var app_db = Application.get_default().db;
- foreach (Row row in db.content_item_meta.with_device(identity_id, jid.bare_jid.to_string(), device_id).with(db.content_item_meta.trusted_when_received, "=", false)) {
- if (selection == null) {
- selection = @"$(app_db.content_item.id) = ?";
- } else {
- selection += @" OR $(app_db.content_item.id) = ?";
- }
- selection_args += row[db.content_item_meta.content_item_id].to_string();
- }
- if (selection != null) {
- app_db.content_item.update()
- .set(app_db.content_item.hide, trust_level == TrustLevel.UNTRUSTED || trust_level == TrustLevel.UNKNOWN)
- .where(selection, selection_args)
- .perform();
- }
-
- if (trust_level == TrustLevel.TRUSTED) {
- db.identity_meta.update_last_message_untrusted(identity_id, device_id, null);
- bad_message_state_updated(account, jid, device_id);
- }
- }
-
- public bool is_known_address(Account account, Jid jid) {
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return false;
- return db.identity_meta.with_address(identity_id, jid.to_string()).with(db.identity_meta.last_active, ">", 0).count() > 0;
- }
-
- public Gee.List<int32> get_trusted_devices(Account account, Jid jid) {
- Gee.List<int32> devices = new ArrayList<int32>();
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return devices;
- foreach (Row device in db.identity_meta.get_trusted_devices(identity_id, jid.bare_jid.to_string())) {
- if(device[db.identity_meta.trust_level] != TrustLevel.UNKNOWN || device[db.identity_meta.identity_key_public_base64] == null)
- devices.add(device[db.identity_meta.device_id]);
- }
- return devices;
- }
-
- private class TagMessageListener : MessageListener {
- public string[] after_actions_const = new string[]{ "STORE" };
- public override string action_group { get { return "DECRYPT_TAG"; } }
- public override string[] after_actions { get { return after_actions_const; } }
-
- private StreamInteractor stream_interactor;
- private TrustManager trust_manager;
- private Database db;
- private HashMap<Message, int> message_device_id_map;
-
- public TagMessageListener(StreamInteractor stream_interactor, TrustManager trust_manager, Database db, HashMap<Message, int> message_device_id_map) {
- this.stream_interactor = stream_interactor;
- this.trust_manager = trust_manager;
- this.db = db;
- this.message_device_id_map = message_device_id_map;
- }
-
- public override async bool run(Entities.Message message, Xmpp.MessageStanza stanza, Conversation conversation) {
- int device_id = 0;
- if (message_device_id_map.has_key(message)) {
- device_id = message_device_id_map[message];
- message_device_id_map.unset(message);
- }
-
- // TODO: Handling of files
-
- ContentItem? content_item = stream_interactor.get_module(ContentItemStore.IDENTITY).get_item_by_foreign(conversation, 1, message.id);
-
- if (content_item != null && device_id != 0) {
- Jid jid = content_item.jid;
- if (conversation.type_ == Conversation.Type.GROUPCHAT) {
- jid = message.real_jid;
- }
-
- int identity_id = db.identity.get_id(conversation.account.id);
- TrustLevel trust_level = (TrustLevel) db.identity_meta.get_device(identity_id, jid.bare_jid.to_string(), device_id)[db.identity_meta.trust_level];
- if (trust_level == TrustLevel.UNTRUSTED || trust_level == TrustLevel.UNKNOWN) {
- stream_interactor.get_module(ContentItemStore.IDENTITY).set_item_hide(content_item, true);
- db.identity_meta.update_last_message_untrusted(identity_id, device_id, message.time);
- trust_manager.bad_message_state_updated(conversation.account, jid, device_id);
- }
-
- db.content_item_meta.insert()
- .value(db.content_item_meta.content_item_id, content_item.id)
- .value(db.content_item_meta.identity_id, identity_id)
- .value(db.content_item_meta.address_name, jid.bare_jid.to_string())
- .value(db.content_item_meta.device_id, device_id)
- .value(db.content_item_meta.trusted_when_received, trust_level != TrustLevel.UNTRUSTED)
- .perform();
- }
- return false;
- }
- }
-}
-
-}
diff --git a/plugins/omemo/src/native/context.vala b/plugins/omemo/src/native/context.vala
deleted file mode 100644
index b1f5945b..00000000
--- a/plugins/omemo/src/native/context.vala
+++ /dev/null
@@ -1,115 +0,0 @@
-namespace Omemo {
-
-public class Context {
- internal NativeContext native_context;
- private RecMutex mutex = RecMutex();
-
- static void locking_function_lock(void* user_data) {
- Context ctx = (Context) user_data;
- ctx.mutex.lock();
- }
-
- static void locking_function_unlock(void* user_data) {
- Context ctx = (Context) user_data;
- ctx.mutex.unlock();
- }
-
- static void stderr_log(LogLevel level, string message, size_t len, void* user_data) {
- printerr(@"$level: $message\n");
- }
-
- public Context(bool log = false) throws Error {
- throw_by_code(NativeContext.create(out native_context, this), "Error initializing native context");
- throw_by_code(native_context.set_locking_functions(locking_function_lock, locking_function_unlock), "Error initializing native locking functions");
- if (log) native_context.set_log_function(stderr_log);
- setup_crypto_provider(native_context);
- }
-
- public Store create_store() {
- return new Store(this);
- }
-
- public void randomize(uint8[] data) throws Error {
- throw_by_code(native_random(data));
- }
-
- public SignedPreKeyRecord generate_signed_pre_key(IdentityKeyPair identity_key_pair, int32 id, uint64 timestamp = 0) throws Error {
- if (timestamp == 0) timestamp = new DateTime.now_utc().to_unix();
- SignedPreKeyRecord res;
- throw_by_code(Protocol.KeyHelper.generate_signed_pre_key(out res, identity_key_pair, id, timestamp, native_context));
- return res;
- }
-
- public Gee.Set<PreKeyRecord> generate_pre_keys(uint start, uint count) throws Error {
- Gee.Set<PreKeyRecord> res = new Gee.HashSet<PreKeyRecord>();
- for(uint i = start; i < start+count; i++) {
- ECKeyPair pair = generate_key_pair();
- PreKeyRecord record;
- throw_by_code(PreKeyRecord.create(out record, i, pair));
- res.add(record);
- }
- return res;
- }
-
- public ECPublicKey decode_public_key(uint8[] bytes) throws Error {
- ECPublicKey public_key;
- throw_by_code(curve_decode_point(out public_key, bytes, native_context), "Error decoding public key");
- return public_key;
- }
-
- public ECPrivateKey decode_private_key(uint8[] bytes) throws Error {
- ECPrivateKey private_key;
- throw_by_code(curve_decode_private_point(out private_key, bytes, native_context), "Error decoding private key");
- return private_key;
- }
-
- public ECKeyPair generate_key_pair() throws Error {
- ECKeyPair key_pair;
- throw_by_code(curve_generate_key_pair(native_context, out key_pair), "Error generating key pair");
- return key_pair;
- }
-
- public uint8[] calculate_signature(ECPrivateKey signing_key, uint8[] message) throws Error {
- Buffer signature;
- throw_by_code(Curve.calculate_signature(native_context, out signature, signing_key, message), "Error calculating signature");
- return signature.data;
- }
-
- public OmemoMessage deserialize_signal_message(uint8[] data) throws Error {
- OmemoMessage res;
- throw_by_code(message_deserialize(out res, data, native_context));
- return res;
- }
-
- public OmemoMessage deserialize_omemo_message(uint8[] data) throws Error {
- OmemoMessage res;
- throw_by_code(message_deserialize_omemo(out res, data, native_context));
- return res;
- }
-
- public OmemoMessage copy_message(CiphertextMessage original) throws Error {
- OmemoMessage res;
- throw_by_code(message_copy(out res, (OmemoMessage) original, native_context));
- return res;
- }
-
- public PreKeyOmemoMessage deserialize_signal_pre_key_message(uint8[] data) throws Error {
- PreKeyOmemoMessage res;
- throw_by_code(pre_key_message_deserialize(out res, data, native_context));
- return res;
- }
-
- public PreKeyOmemoMessage deserialize_omemo_pre_key_message(uint8[] data, uint32 remote_registration_id) throws Error {
- PreKeyOmemoMessage res;
- throw_by_code(pre_key_message_deserialize_omemo(out res, data, remote_registration_id, native_context));
- return res;
- }
-
- public PreKeyOmemoMessage copy_pre_key_message(CiphertextMessage original) throws Error {
- PreKeyOmemoMessage res;
- throw_by_code(pre_key_message_copy(out res, (PreKeyOmemoMessage) original, native_context));
- return res;
- }
-}
-
-}
diff --git a/plugins/omemo/src/native/helper.c b/plugins/omemo/src/native/helper.c
deleted file mode 100644
index 2d808cde..00000000
--- a/plugins/omemo/src/native/helper.c
+++ /dev/null
@@ -1,329 +0,0 @@
-#include "helper.h"
-
-#include <gcrypt.h>
-
-signal_type_base* signal_type_ref_vapi(void* instance) {
- g_return_val_if_fail(instance != NULL, NULL);
- signal_type_ref(instance);
- return instance;
-}
-
-signal_type_base* signal_type_unref_vapi(void* instance) {
- g_return_val_if_fail(instance != NULL, NULL);
- signal_type_unref(instance);
- return NULL;
-}
-
-signal_protocol_address* signal_protocol_address_new(const gchar* name, int32_t device_id) {
- g_return_val_if_fail(name != NULL, NULL);
- signal_protocol_address* address = malloc(sizeof(signal_protocol_address));
- address->device_id = -1;
- address->name = NULL;
- signal_protocol_address_set_name(address, name);
- signal_protocol_address_set_device_id(address, device_id);
- return address;
-}
-
-void signal_protocol_address_free(signal_protocol_address* ptr) {
- g_return_if_fail(ptr != NULL);
- if (ptr->name) {
- g_free((void*)ptr->name);
- }
- return free(ptr);
-}
-
-void signal_protocol_address_set_name(signal_protocol_address* self, const gchar* name) {
- g_return_if_fail(self != NULL);
- g_return_if_fail(name != NULL);
- gchar* n = g_malloc(strlen(name)+1);
- memcpy(n, name, strlen(name));
- n[strlen(name)] = 0;
- if (self->name) {
- g_free((void*)self->name);
- }
- self->name = n;
- self->name_len = strlen(n);
-}
-
-gchar* signal_protocol_address_get_name(signal_protocol_address* self) {
- g_return_val_if_fail(self != NULL, NULL);
- g_return_val_if_fail(self->name != NULL, 0);
- gchar* res = g_malloc(sizeof(char) * (self->name_len + 1));
- memcpy(res, self->name, self->name_len);
- res[self->name_len] = 0;
- return res;
-}
-
-int32_t signal_protocol_address_get_device_id(signal_protocol_address* self) {
- g_return_val_if_fail(self != NULL, -1);
- return self->device_id;
-}
-
-void signal_protocol_address_set_device_id(signal_protocol_address* self, int32_t device_id) {
- g_return_if_fail(self != NULL);
- self->device_id = device_id;
-}
-
-int signal_vala_randomize(uint8_t *data, size_t len) {
- gcry_randomize(data, len, GCRY_STRONG_RANDOM);
- return SG_SUCCESS;
-}
-
-int signal_vala_random_generator(uint8_t *data, size_t len, void *user_data) {
- gcry_randomize(data, len, GCRY_STRONG_RANDOM);
- return SG_SUCCESS;
-}
-
-int signal_vala_hmac_sha256_init(void **hmac_context, const uint8_t *key, size_t key_len, void *user_data) {
- gcry_mac_hd_t* ctx = malloc(sizeof(gcry_mac_hd_t));
- if (!ctx) return SG_ERR_NOMEM;
-
- if (gcry_mac_open(ctx, GCRY_MAC_HMAC_SHA256, 0, 0)) {
- free(ctx);
- return SG_ERR_UNKNOWN;
- }
-
- if (gcry_mac_setkey(*ctx, key, key_len)) {
- free(ctx);
- return SG_ERR_UNKNOWN;
- }
-
- *hmac_context = ctx;
-
- return SG_SUCCESS;
-}
-
-int signal_vala_hmac_sha256_update(void *hmac_context, const uint8_t *data, size_t data_len, void *user_data) {
- gcry_mac_hd_t* ctx = hmac_context;
-
- if (gcry_mac_write(*ctx, data, data_len)) return SG_ERR_UNKNOWN;
-
- return SG_SUCCESS;
-}
-
-int signal_vala_hmac_sha256_final(void *hmac_context, signal_buffer **output, void *user_data) {
- size_t len = gcry_mac_get_algo_maclen(GCRY_MAC_HMAC_SHA256);
- uint8_t md[len];
- gcry_mac_hd_t* ctx = hmac_context;
-
- if (gcry_mac_read(*ctx, md, &len)) return SG_ERR_UNKNOWN;
-
- signal_buffer *output_buffer = signal_buffer_create(md, len);
- if (!output_buffer) return SG_ERR_NOMEM;
-
- *output = output_buffer;
-
- return SG_SUCCESS;
-}
-
-void signal_vala_hmac_sha256_cleanup(void *hmac_context, void *user_data) {
- gcry_mac_hd_t* ctx = hmac_context;
- if (ctx) {
- gcry_mac_close(*ctx);
- free(ctx);
- }
-}
-
-const int aes_cipher(int cipher, size_t key_len, int* algo, int* mode) {
- switch (key_len) {
- case 16:
- *algo = GCRY_CIPHER_AES128;
- break;
- case 24:
- *algo = GCRY_CIPHER_AES192;
- break;
- case 32:
- *algo = GCRY_CIPHER_AES256;
- break;
- default:
- return SG_ERR_UNKNOWN;
- }
- switch (cipher) {
- case SG_CIPHER_AES_CBC_PKCS5:
- *mode = GCRY_CIPHER_MODE_CBC;
- break;
- case SG_CIPHER_AES_CTR_NOPADDING:
- *mode = GCRY_CIPHER_MODE_CTR;
- break;
- case SG_CIPHER_AES_GCM_NOPADDING:
- *mode = GCRY_CIPHER_MODE_GCM;
- break;
- default:
- return SG_ERR_UNKNOWN;
- }
- return SG_SUCCESS;
-}
-
-int signal_vala_encrypt(signal_buffer **output,
- int cipher,
- const uint8_t *key, size_t key_len,
- const uint8_t *iv, size_t iv_len,
- const uint8_t *plaintext, size_t plaintext_len,
- void *user_data) {
- int algo, mode, error_code = SG_ERR_UNKNOWN;
- if (aes_cipher(cipher, key_len, &algo, &mode)) return SG_ERR_INVAL;
-
- gcry_cipher_hd_t ctx = {0};
-
- if (gcry_cipher_open(&ctx, algo, mode, 0)) return SG_ERR_NOMEM;
-
- signal_buffer* padded = 0;
- signal_buffer* out_buf = 0;
- goto no_error;
-error:
- gcry_cipher_close(ctx);
- if (padded != 0) {
- signal_buffer_bzero_free(padded);
- }
- if (out_buf != 0) {
- signal_buffer_free(out_buf);
- }
- return error_code;
-no_error:
-
- if (gcry_cipher_setkey(ctx, key, key_len)) goto error;
-
- uint8_t tag_len = 0, pad_len = 0;
- switch (cipher) {
- case SG_CIPHER_AES_CBC_PKCS5:
- if (gcry_cipher_setiv(ctx, iv, iv_len)) goto error;
- pad_len = 16 - (plaintext_len % 16);
- if (pad_len == 0) pad_len = 16;
- break;
- case SG_CIPHER_AES_CTR_NOPADDING:
- if (gcry_cipher_setctr(ctx, iv, iv_len)) goto error;
- break;
- case SG_CIPHER_AES_GCM_NOPADDING:
- if (gcry_cipher_setiv(ctx, iv, iv_len)) goto error;
- tag_len = 16;
- break;
- default:
- return SG_ERR_UNKNOWN;
- }
-
- size_t padded_len = plaintext_len + pad_len;
- padded = signal_buffer_alloc(padded_len);
- if (padded == 0) {
- error_code = SG_ERR_NOMEM;
- goto error;
- }
-
- memset(signal_buffer_data(padded) + plaintext_len, pad_len, pad_len);
- memcpy(signal_buffer_data(padded), plaintext, plaintext_len);
-
- out_buf = signal_buffer_alloc(padded_len + tag_len);
- if (out_buf == 0) {
- error_code = SG_ERR_NOMEM;
- goto error;
- }
-
- if (gcry_cipher_encrypt(ctx, signal_buffer_data(out_buf), padded_len, signal_buffer_data(padded), padded_len)) goto error;
-
- if (tag_len > 0) {
- if (gcry_cipher_gettag(ctx, signal_buffer_data(out_buf) + padded_len, tag_len)) goto error;
- }
-
- *output = out_buf;
- out_buf = 0;
-
- signal_buffer_bzero_free(padded);
- padded = 0;
-
- gcry_cipher_close(ctx);
- return SG_SUCCESS;
-}
-
-int signal_vala_decrypt(signal_buffer **output,
- int cipher,
- const uint8_t *key, size_t key_len,
- const uint8_t *iv, size_t iv_len,
- const uint8_t *ciphertext, size_t ciphertext_len,
- void *user_data) {
- int algo, mode, error_code = SG_ERR_UNKNOWN;
- *output = 0;
- if (aes_cipher(cipher, key_len, &algo, &mode)) return SG_ERR_INVAL;
- if (ciphertext_len == 0) return SG_ERR_INVAL;
-
- gcry_cipher_hd_t ctx = {0};
-
- if (gcry_cipher_open(&ctx, algo, mode, 0)) return SG_ERR_NOMEM;
-
- signal_buffer* out_buf = 0;
- goto no_error;
-error:
- gcry_cipher_close(ctx);
- if (out_buf != 0) {
- signal_buffer_bzero_free(out_buf);
- }
- return error_code;
-no_error:
-
- if (gcry_cipher_setkey(ctx, key, key_len)) goto error;
-
- uint8_t tag_len = 0, pkcs_pad = FALSE;
- switch (cipher) {
- case SG_CIPHER_AES_CBC_PKCS5:
- if (gcry_cipher_setiv(ctx, iv, iv_len)) goto error;
- pkcs_pad = TRUE;
- break;
- case SG_CIPHER_AES_CTR_NOPADDING:
- if (gcry_cipher_setctr(ctx, iv, iv_len)) goto error;
- break;
- case SG_CIPHER_AES_GCM_NOPADDING:
- if (gcry_cipher_setiv(ctx, iv, iv_len)) goto error;
- if (ciphertext_len < 16) goto error;
- tag_len = 16;
- break;
- default:
- goto error;
- }
-
- size_t padded_len = ciphertext_len - tag_len;
- out_buf = signal_buffer_alloc(padded_len);
- if (out_buf == 0) {
- error_code = SG_ERR_NOMEM;
- goto error;
- }
-
- if (gcry_cipher_decrypt(ctx, signal_buffer_data(out_buf), signal_buffer_len(out_buf), ciphertext, padded_len)) goto error;
-
- if (tag_len > 0) {
- if (gcry_cipher_checktag(ctx, ciphertext + padded_len, tag_len)) goto error;
- }
-
- if (pkcs_pad) {
- uint8_t pad_len = signal_buffer_data(out_buf)[padded_len - 1];
- if (pad_len > 16 || pad_len > padded_len) goto error;
- *output = signal_buffer_create(signal_buffer_data(out_buf), padded_len - pad_len);
- signal_buffer_bzero_free(out_buf);
- out_buf = 0;
- } else {
- *output = out_buf;
- out_buf = 0;
- }
-
- gcry_cipher_close(ctx);
- return SG_SUCCESS;
-}
-
-void setup_signal_vala_crypto_provider(signal_context *context)
-{
- gcry_check_version(NULL);
-
- signal_crypto_provider provider = {
- .random_func = signal_vala_random_generator,
- .hmac_sha256_init_func = signal_vala_hmac_sha256_init,
- .hmac_sha256_update_func = signal_vala_hmac_sha256_update,
- .hmac_sha256_final_func = signal_vala_hmac_sha256_final,
- .hmac_sha256_cleanup_func = signal_vala_hmac_sha256_cleanup,
- .sha512_digest_init_func = NULL,
- .sha512_digest_update_func = NULL,
- .sha512_digest_final_func = NULL,
- .sha512_digest_cleanup_func = NULL,
- .encrypt_func = signal_vala_encrypt,
- .decrypt_func = signal_vala_decrypt,
- .user_data = 0
- };
-
- signal_context_set_crypto_provider(context, &provider);
-}
diff --git a/plugins/omemo/src/native/helper.h b/plugins/omemo/src/native/helper.h
deleted file mode 100644
index 3cc21d8a..00000000
--- a/plugins/omemo/src/native/helper.h
+++ /dev/null
@@ -1,41 +0,0 @@
-#ifndef SIGNAL_PROTOCOL_VALA_HELPER
-#define SIGNAL_PROTOCOL_VALA_HELPER 1
-
-#include <omemo/signal_protocol.h>
-#include <string.h>
-#include <glib.h>
-
-#define SG_CIPHER_AES_GCM_NOPADDING 1000
-
-signal_type_base* signal_type_ref_vapi(void* what);
-signal_type_base* signal_type_unref_vapi(void* what);
-
-signal_protocol_address* signal_protocol_address_new(const gchar* name, int32_t device_id);
-void signal_protocol_address_free(signal_protocol_address* ptr);
-void signal_protocol_address_set_name(signal_protocol_address* self, const gchar* name);
-gchar* signal_protocol_address_get_name(signal_protocol_address* self);
-void signal_protocol_address_set_device_id(signal_protocol_address* self, int32_t device_id);
-int32_t signal_protocol_address_get_device_id(signal_protocol_address* self);
-
-int signal_vala_randomize(uint8_t *data, size_t len);
-int signal_vala_random_generator(uint8_t *data, size_t len, void *user_data);
-int signal_vala_hmac_sha256_init(void **hmac_context, const uint8_t *key, size_t key_len, void *user_data);
-int signal_vala_hmac_sha256_update(void *hmac_context, const uint8_t *data, size_t data_len, void *user_data);
-int signal_vala_hmac_sha256_final(void *hmac_context, signal_buffer **output, void *user_data);
-void signal_vala_hmac_sha256_cleanup(void *hmac_context, void *user_data);
-
-int signal_vala_encrypt(signal_buffer **output,
- int cipher,
- const uint8_t *key, size_t key_len,
- const uint8_t *iv, size_t iv_len,
- const uint8_t *plaintext, size_t plaintext_len,
- void *user_data);
-int signal_vala_decrypt(signal_buffer **output,
- int cipher,
- const uint8_t *key, size_t key_len,
- const uint8_t *iv, size_t iv_len,
- const uint8_t *ciphertext, size_t ciphertext_len,
- void *user_data);
-void setup_signal_vala_crypto_provider(signal_context *context);
-
-#endif
diff --git a/plugins/omemo/src/native/simple_iks.vala b/plugins/omemo/src/native/simple_iks.vala
deleted file mode 100644
index 6f752d33..00000000
--- a/plugins/omemo/src/native/simple_iks.vala
+++ /dev/null
@@ -1,40 +0,0 @@
-using Gee;
-
-namespace Omemo {
-
-public class SimpleIdentityKeyStore : IdentityKeyStore {
- public override Bytes identity_key_private { get; set; }
- public override Bytes identity_key_public { get; set; }
- public override uint32 local_registration_id { get; set; }
- private Map<string, Map<int, IdentityKeyStore.TrustedIdentity>> trusted_identities = new HashMap<string, Map<int, IdentityKeyStore.TrustedIdentity>>();
-
- public override void save_identity(Address address, uint8[] key) throws Error {
- string name = address.name;
- if (trusted_identities.has_key(name)) {
- if (trusted_identities[name].has_key(address.device_id)) {
- trusted_identities[name][address.device_id].key = key;
- trusted_identity_updated(trusted_identities[name][address.device_id]);
- } else {
- trusted_identities[name][address.device_id] = new TrustedIdentity.by_address(address, key);
- trusted_identity_added(trusted_identities[name][address.device_id]);
- }
- } else {
- trusted_identities[name] = new HashMap<int, IdentityKeyStore.TrustedIdentity>();
- trusted_identities[name][address.device_id] = new TrustedIdentity.by_address(address, key);
- trusted_identity_added(trusted_identities[name][address.device_id]);
- }
- }
-
- public override bool is_trusted_identity(Address address, uint8[] key) throws Error {
- if (!trusted_identities.has_key(address.name)) return true;
- if (!trusted_identities[address.name].has_key(address.device_id)) return true;
- uint8[] other_key = trusted_identities[address.name][address.device_id].key;
- if (other_key.length != key.length) return false;
- for (int i = 0; i < key.length; i++) {
- if (other_key[i] != key[i]) return false;
- }
- return true;
- }
-}
-
-}
diff --git a/plugins/omemo/src/native/simple_pks.vala b/plugins/omemo/src/native/simple_pks.vala
deleted file mode 100644
index 900985ea..00000000
--- a/plugins/omemo/src/native/simple_pks.vala
+++ /dev/null
@@ -1,33 +0,0 @@
-using Gee;
-
-namespace Omemo {
-
-public class SimplePreKeyStore : PreKeyStore {
- private Map<uint32, PreKeyStore.Key> pre_key_map = new HashMap<uint32, PreKeyStore.Key>();
-
- public override uint8[]? load_pre_key(uint32 pre_key_id) throws Error {
- if (contains_pre_key(pre_key_id)) {
- return pre_key_map[pre_key_id].record;
- }
- return null;
- }
-
- public override void store_pre_key(uint32 pre_key_id, uint8[] record) throws Error {
- PreKeyStore.Key key = new Key(pre_key_id, record);
- pre_key_map[pre_key_id] = key;
- pre_key_stored(key);
- }
-
- public override bool contains_pre_key(uint32 pre_key_id) throws Error {
- return pre_key_map.has_key(pre_key_id);
- }
-
- public override void delete_pre_key(uint32 pre_key_id) throws Error {
- PreKeyStore.Key key;
- if (pre_key_map.unset(pre_key_id, out key)) {
- pre_key_deleted(key);
- }
- }
-}
-
-} \ No newline at end of file
diff --git a/plugins/omemo/src/native/simple_spks.vala b/plugins/omemo/src/native/simple_spks.vala
deleted file mode 100644
index 772a7322..00000000
--- a/plugins/omemo/src/native/simple_spks.vala
+++ /dev/null
@@ -1,33 +0,0 @@
-using Gee;
-
-namespace Omemo {
-
-public class SimpleSignedPreKeyStore : SignedPreKeyStore {
- private Map<uint32, SignedPreKeyStore.Key> pre_key_map = new HashMap<uint32, SignedPreKeyStore.Key>();
-
- public override uint8[]? load_signed_pre_key(uint32 pre_key_id) throws Error {
- if (contains_signed_pre_key(pre_key_id)) {
- return pre_key_map[pre_key_id].record;
- }
- return null;
- }
-
- public override void store_signed_pre_key(uint32 pre_key_id, uint8[] record) throws Error {
- SignedPreKeyStore.Key key = new Key(pre_key_id, record);
- pre_key_map[pre_key_id] = key;
- signed_pre_key_stored(key);
- }
-
- public override bool contains_signed_pre_key(uint32 pre_key_id) throws Error {
- return pre_key_map.has_key(pre_key_id);
- }
-
- public override void delete_signed_pre_key(uint32 pre_key_id) throws Error {
- SignedPreKeyStore.Key key;
- if (pre_key_map.unset(pre_key_id, out key)) {
- signed_pre_key_deleted(key);
- }
- }
-}
-
-} \ No newline at end of file
diff --git a/plugins/omemo/src/native/simple_ss.vala b/plugins/omemo/src/native/simple_ss.vala
deleted file mode 100644
index 26bc8e56..00000000
--- a/plugins/omemo/src/native/simple_ss.vala
+++ /dev/null
@@ -1,75 +0,0 @@
-using Gee;
-
-namespace Omemo {
-
-public class SimpleSessionStore : SessionStore {
-
- private Map<string, ArrayList<SessionStore.Session>> session_map = new HashMap<string, ArrayList<SessionStore.Session>>();
-
- public override uint8[]? load_session(Address address) throws Error {
- if (session_map.has_key(address.name)) {
- foreach (SessionStore.Session session in session_map[address.name]) {
- if (session.device_id == address.device_id) return session.record;
- }
- }
- return null;
- }
-
- public override IntList get_sub_device_sessions(string name) throws Error {
- IntList res = new IntList();
- if (session_map.has_key(name)) {
- foreach (SessionStore.Session session in session_map[name]) {
- res.add(session.device_id);
- }
- }
- return res;
- }
-
- public override void store_session(Address address, uint8[] record) throws Error {
- if (contains_session(address)) {
- delete_session(address);
- }
- if (!session_map.has_key(address.name)) {
- session_map[address.name] = new ArrayList<SessionStore.Session>();
- }
- SessionStore.Session session = new Session() { name = address.name, device_id = address.device_id, record = record };
- session_map[address.name].add(session);
- session_stored(session);
- }
-
- public override bool contains_session(Address address) throws Error {
- if (!session_map.has_key(address.name)) return false;
- foreach (SessionStore.Session session in session_map[address.name]) {
- if (session.device_id == address.device_id) return true;
- }
- return false;
- }
-
- public override void delete_session(Address address) throws Error {
- if (!session_map.has_key(address.name)) throw_by_code(ErrorCode.UNKNOWN, "No session found");
- foreach (SessionStore.Session session in session_map[address.name]) {
- if (session.device_id == address.device_id) {
- session_map[address.name].remove(session);
- if (session_map[address.name].size == 0) {
- session_map.unset(address.name);
- }
- session_removed(session);
- return;
- }
- }
- }
-
- public override void delete_all_sessions(string name) throws Error {
- if (session_map.has_key(name)) {
- foreach (SessionStore.Session session in session_map[name]) {
- session_map[name].remove(session);
- if (session_map[name].size == 0) {
- session_map.unset(name);
- }
- session_removed(session);
- }
- }
- }
-}
-
-} \ No newline at end of file
diff --git a/plugins/omemo/src/native/store.vala b/plugins/omemo/src/native/store.vala
deleted file mode 100644
index b1861d93..00000000
--- a/plugins/omemo/src/native/store.vala
+++ /dev/null
@@ -1,415 +0,0 @@
-namespace Omemo {
-
-public abstract class IdentityKeyStore : Object {
- public abstract Bytes identity_key_private { get; set; }
- public abstract Bytes identity_key_public { get; set; }
- public abstract uint32 local_registration_id { get; set; }
-
- public signal void trusted_identity_added(TrustedIdentity id);
- public signal void trusted_identity_updated(TrustedIdentity id);
-
- public abstract void save_identity(Address address, uint8[] key) throws Error ;
-
- public abstract bool is_trusted_identity(Address address, uint8[] key) throws Error ;
-
- public class TrustedIdentity {
- public uint8[] key { get; set; }
- public string name { get; private set; }
- public int device_id { get; private set; }
-
- public TrustedIdentity(string name, int device_id, uint8[] key) {
- this.key = key;
- this.name = name;
- this.device_id = device_id;
- }
-
- public TrustedIdentity.by_address(Address address, uint8[] key) {
- this(address.name, address.device_id, key);
- }
- }
-}
-
-public abstract class SessionStore : Object {
-
- public signal void session_stored(Session session);
- public signal void session_removed(Session session);
- public abstract uint8[]? load_session(Address address) throws Error ;
-
- public abstract IntList get_sub_device_sessions(string name) throws Error ;
-
- public abstract void store_session(Address address, uint8[] record) throws Error ;
-
- public abstract bool contains_session(Address address) throws Error ;
-
- public abstract void delete_session(Address address) throws Error ;
-
- public abstract void delete_all_sessions(string name) throws Error ;
-
- public class Session {
- public string name;
- public int device_id;
- public uint8[] record;
- }
-}
-
-public abstract class PreKeyStore : Object {
-
- public signal void pre_key_stored(Key key);
- public signal void pre_key_deleted(Key key);
-
- public abstract uint8[]? load_pre_key(uint32 pre_key_id) throws Error ;
-
- public abstract void store_pre_key(uint32 pre_key_id, uint8[] record) throws Error ;
-
- public abstract bool contains_pre_key(uint32 pre_key_id) throws Error ;
-
- public abstract void delete_pre_key(uint32 pre_key_id) throws Error ;
-
- public class Key {
- public uint32 key_id { get; private set; }
- public uint8[] record { get; private set; }
-
- public Key(uint32 key_id, uint8[] record) {
- this.key_id = key_id;
- this.record = record;
- }
- }
-}
-
-public abstract class SignedPreKeyStore : Object {
-
- public signal void signed_pre_key_stored(Key key);
- public signal void signed_pre_key_deleted(Key key);
-
- public abstract uint8[]? load_signed_pre_key(uint32 pre_key_id) throws Error ;
-
- public abstract void store_signed_pre_key(uint32 pre_key_id, uint8[] record) throws Error ;
-
- public abstract bool contains_signed_pre_key(uint32 pre_key_id) throws Error ;
-
- public abstract void delete_signed_pre_key(uint32 pre_key_id) throws Error ;
-
- public class Key {
- public uint32 key_id { get; private set; }
- public uint8[] record { get; private set; }
-
- public Key(uint32 key_id, uint8[] record) {
- this.key_id = key_id;
- this.record = record;
- }
- }
-}
-
-public class Store : Object {
- public Context context { get; private set; }
- public IdentityKeyStore identity_key_store { get; set; default = new SimpleIdentityKeyStore(); }
- public SessionStore session_store { get; set; default = new SimpleSessionStore(); }
- public PreKeyStore pre_key_store { get; set; default = new SimplePreKeyStore(); }
- public SignedPreKeyStore signed_pre_key_store { get; set; default = new SimpleSignedPreKeyStore(); }
- public uint32 local_registration_id { get { return identity_key_store.local_registration_id; } }
- internal NativeStoreContext native_context {get { return native_store_context_; }}
- private NativeStoreContext native_store_context_;
-
- static int iks_get_identity_key_pair(out Buffer public_data, out Buffer private_data, void* user_data) {
- Store store = (Store) user_data;
- public_data = new Buffer.from(store.identity_key_store.identity_key_public.get_data());
- private_data = new Buffer.from(store.identity_key_store.identity_key_private.get_data());
- return 0;
- }
-
- static int iks_get_local_registration_id(void* user_data, out uint32 registration_id) {
- Store store = (Store) user_data;
- registration_id = store.identity_key_store.local_registration_id;
- return 0;
- }
-
- static int iks_save_identity(Address address, uint8[] key, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.identity_key_store.save_identity(address, key);
- return 0;
- });
- }
-
- static int iks_is_trusted_identity(Address address, uint8[] key, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- return store.identity_key_store.is_trusted_identity(address, key) ? 1 : 0;
- });
- }
-
- static void iks_destroy_func(void* user_data) {
- }
-
- static int ss_load_session_func(out Buffer? record, out Buffer? user_record, Address address, void* user_data) {
- Store store = (Store) user_data;
- user_record = null; // No support for user_record
- uint8[]? res = null;
- try {
- res = store.session_store.load_session(address);
- } catch (Error e) {
- record = null;
- return e.code;
- }
- if (res == null) {
- record = null;
- return 0;
- }
- record = new Buffer.from((!)res);
- if (record == null) return ErrorCode.NOMEM;
- return 1;
- }
-
- static int ss_get_sub_device_sessions_func(out IntList? sessions, char[] name, void* user_data) {
- Store store = (Store) user_data;
- try {
- sessions = store.session_store.get_sub_device_sessions(carr_to_string(name));
- } catch (Error e) {
- sessions = null;
- return e.code;
- }
- return 0;
- }
-
- static int ss_store_session_func(Address address, uint8[] record, uint8[] user_record, void* user_data) {
- // Ignoring user_record
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.session_store.store_session(address, record);
- return 0;
- });
- }
-
- static int ss_contains_session_func(Address address, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- return store.session_store.contains_session(address) ? 1 : 0;
- });
- }
-
- static int ss_delete_session_func(Address address, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.session_store.delete_session(address);
- return 0;
- });
- }
-
- static int ss_delete_all_sessions_func(char[] name, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.session_store.delete_all_sessions(carr_to_string(name));
- return 0;
- });
- }
-
- static void ss_destroy_func(void* user_data) {
- }
-
- static int pks_load_pre_key(out Buffer? record, uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- uint8[]? res = null;
- try {
- res = store.pre_key_store.load_pre_key(pre_key_id);
- } catch (Error e) {
- record = null;
- return e.code;
- }
- if (res == null) {
- record = new Buffer(0);
- return 0;
- }
- record = new Buffer.from((!)res);
- if (record == null) return ErrorCode.NOMEM;
- return 1;
- }
-
- static int pks_store_pre_key(uint32 pre_key_id, uint8[] record, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.pre_key_store.store_pre_key(pre_key_id, record);
- return 0;
- });
- }
-
- static int pks_contains_pre_key(uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- return store.pre_key_store.contains_pre_key(pre_key_id) ? 1 : 0;
- });
- }
-
- static int pks_remove_pre_key(uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.pre_key_store.delete_pre_key(pre_key_id);
- return 0;
- });
- }
-
- static void pks_destroy_func(void* user_data) {
- }
-
- static int spks_load_signed_pre_key(out Buffer? record, uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- uint8[]? res = null;
- try {
- res = store.signed_pre_key_store.load_signed_pre_key(pre_key_id);
- } catch (Error e) {
- record = null;
- return e.code;
- }
- if (res == null) {
- record = new Buffer(0);
- return 0;
- }
- record = new Buffer.from((!)res);
- if (record == null) return ErrorCode.NOMEM;
- return 1;
- }
-
- static int spks_store_signed_pre_key(uint32 pre_key_id, uint8[] record, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.signed_pre_key_store.store_signed_pre_key(pre_key_id, record);
- return 0;
- });
- }
-
- static int spks_contains_signed_pre_key(uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- return store.signed_pre_key_store.contains_signed_pre_key(pre_key_id) ? 1 : 0;
- });
- }
-
- static int spks_remove_signed_pre_key(uint32 pre_key_id, void* user_data) {
- Store store = (Store) user_data;
- return catch_to_code(() => {
- store.signed_pre_key_store.delete_signed_pre_key(pre_key_id);
- return 0;
- });
- }
-
- static void spks_destroy_func(void* user_data) {
- }
-
- internal Store(Context context) {
- this.context = context;
- NativeStoreContext.create(out native_store_context_, context.native_context);
-
- NativeIdentityKeyStore iks = NativeIdentityKeyStore() {
- get_identity_key_pair = iks_get_identity_key_pair,
- get_local_registration_id = iks_get_local_registration_id,
- save_identity = iks_save_identity,
- is_trusted_identity = iks_is_trusted_identity,
- destroy_func = iks_destroy_func,
- user_data = this
- };
- native_context.set_identity_key_store(iks);
-
- NativeSessionStore ss = NativeSessionStore() {
- load_session_func = ss_load_session_func,
- get_sub_device_sessions_func = ss_get_sub_device_sessions_func,
- store_session_func = ss_store_session_func,
- contains_session_func = ss_contains_session_func,
- delete_session_func = ss_delete_session_func,
- delete_all_sessions_func = ss_delete_all_sessions_func,
- destroy_func = ss_destroy_func,
- user_data = this
- };
- native_context.set_session_store(ss);
-
- NativePreKeyStore pks = NativePreKeyStore() {
- load_pre_key = pks_load_pre_key,
- store_pre_key = pks_store_pre_key,
- contains_pre_key = pks_contains_pre_key,
- remove_pre_key = pks_remove_pre_key,
- destroy_func = pks_destroy_func,
- user_data = this
- };
- native_context.set_pre_key_store(pks);
-
- NativeSignedPreKeyStore spks = NativeSignedPreKeyStore() {
- load_signed_pre_key = spks_load_signed_pre_key,
- store_signed_pre_key = spks_store_signed_pre_key,
- contains_signed_pre_key = spks_contains_signed_pre_key,
- remove_signed_pre_key = spks_remove_signed_pre_key,
- destroy_func = spks_destroy_func,
- user_data = this
- };
- native_context.set_signed_pre_key_store(spks);
- }
-
- public SessionBuilder create_session_builder(Address other) throws Error {
- SessionBuilder builder;
- throw_by_code(session_builder_create(out builder, native_context, other, context.native_context), "Error creating session builder");
- return builder;
- }
-
- public SessionCipher create_session_cipher(Address other) throws Error {
- SessionCipher cipher;
- throw_by_code(session_cipher_create(out cipher, native_context, other, context.native_context));
- return cipher;
- }
-
- public IdentityKeyPair identity_key_pair {
- owned get {
- IdentityKeyPair pair;
- Protocol.Identity.get_key_pair(native_context, out pair);
- return pair;
- }
- }
-
- public bool is_trusted_identity(Address address, ECPublicKey key) throws Error {
- return throw_by_code(Protocol.Identity.is_trusted_identity(native_context, address, key)) == 1;
- }
-
- public void save_identity(Address address, ECPublicKey key) throws Error {
- throw_by_code(Protocol.Identity.save_identity(native_context, address, key));
- }
-
- public bool contains_session(Address other) throws Error {
- return throw_by_code(Protocol.Session.contains_session(native_context, other)) == 1;
- }
-
- public void delete_session(Address address) throws Error {
- throw_by_code(Protocol.Session.delete_session(native_context, address));
- }
-
- public SessionRecord load_session(Address other) throws Error {
- SessionRecord record;
- throw_by_code(Protocol.Session.load_session(native_context, out record, other));
- return record;
- }
-
- public bool contains_pre_key(uint32 pre_key_id) throws Error {
- return throw_by_code(Protocol.PreKey.contains_key(native_context, pre_key_id)) == 1;
- }
-
- public void store_pre_key(PreKeyRecord record) throws Error {
- throw_by_code(Protocol.PreKey.store_key(native_context, record));
- }
-
- public PreKeyRecord load_pre_key(uint32 pre_key_id) throws Error {
- PreKeyRecord res;
- throw_by_code(Protocol.PreKey.load_key(native_context, out res, pre_key_id));
- return res;
- }
-
- public bool contains_signed_pre_key(uint32 pre_key_id) throws Error {
- return throw_by_code(Protocol.SignedPreKey.contains_key(native_context, pre_key_id)) == 1;
- }
-
- public void store_signed_pre_key(SignedPreKeyRecord record) throws Error {
- throw_by_code(Protocol.SignedPreKey.store_key(native_context, record));
- }
-
- public SignedPreKeyRecord load_signed_pre_key(uint32 pre_key_id) throws Error {
- SignedPreKeyRecord res;
- throw_by_code(Protocol.SignedPreKey.load_key(native_context, out res, pre_key_id));
- return res;
- }
-}
-
-}
diff --git a/plugins/omemo/src/native/util.vala b/plugins/omemo/src/native/util.vala
deleted file mode 100644
index be43668d..00000000
--- a/plugins/omemo/src/native/util.vala
+++ /dev/null
@@ -1,45 +0,0 @@
-namespace Omemo {
-
-public ECPublicKey generate_public_key(ECPrivateKey private_key) throws Error {
- ECPublicKey public_key;
- throw_by_code(ECPublicKey.generate(out public_key, private_key), "Error generating public key");
-
- return public_key;
-}
-
-public uint8[] calculate_agreement(ECPublicKey public_key, ECPrivateKey private_key) throws Error {
- uint8[] res;
- int len = Curve.calculate_agreement(out res, public_key, private_key);
- throw_by_code(len, "Error calculating agreement");
- res.length = len;
- return res;
-}
-
-public bool verify_signature(ECPublicKey signing_key, uint8[] message, uint8[] signature) throws Error {
- return throw_by_code(Curve.verify_signature(signing_key, message, signature)) == 1;
-}
-
-public PreKeyBundle create_pre_key_bundle(uint32 registration_id, int device_id, uint32 pre_key_id, ECPublicKey? pre_key_public,
- uint32 signed_pre_key_id, ECPublicKey? signed_pre_key_public, uint8[]? signed_pre_key_signature, ECPublicKey? identity_key) throws Error {
- PreKeyBundle res;
- throw_by_code(PreKeyBundle.create(out res, registration_id, device_id, pre_key_id, pre_key_public, signed_pre_key_id, signed_pre_key_public, signed_pre_key_signature, identity_key), "Error creating PreKeyBundle");
- return res;
-}
-
-internal string carr_to_string(char[] carr) {
- char[] nu = new char[carr.length + 1];
- Memory.copy(nu, carr, carr.length);
- return (string) nu;
-}
-
-internal delegate int CodeErroringFunc() throws Error;
-
-internal int catch_to_code(CodeErroringFunc func) {
- try {
- return func();
- } catch (Error e) {
- return e.code;
- }
-}
-
-} \ No newline at end of file
diff --git a/plugins/omemo/src/plugin.vala b/plugins/omemo/src/plugin.vala
deleted file mode 100644
index 7b7034c8..00000000
--- a/plugins/omemo/src/plugin.vala
+++ /dev/null
@@ -1,97 +0,0 @@
-using Gee;
-using Dino.Entities;
-using Omemo;
-
-extern const string GETTEXT_PACKAGE;
-extern const string LOCALE_INSTALL_DIR;
-
-namespace Dino.Plugins.Omemo {
-
-public class Plugin : RootInterface, Object {
- public const bool DEBUG = false;
- private static Context? _context;
- public static Context get_context() {
- assert(_context != null);
- return (!)_context;
- }
- public static bool ensure_context() {
- lock(_context) {
- try {
- if (_context == null) {
- _context = new Context(DEBUG);
- }
- return true;
- } catch (Error e) {
- warning("Error initializing libomemo-c Context %s", e.message);
- return false;
- }
- }
- }
-
- public Dino.Application app;
- public Database db;
- public EncryptionListEntry list_entry;
- public ContactDetailsProvider contact_details_provider;
- public DeviceNotificationPopulator device_notification_populator;
- public OwnNotifications own_notifications;
- public TrustManager trust_manager;
- public HashMap<Account, OmemoDecryptor> decryptors = new HashMap<Account, OmemoDecryptor>(Account.hash_func, Account.equals_func);
- public HashMap<Account, OmemoEncryptor> encryptors = new HashMap<Account, OmemoEncryptor>(Account.hash_func, Account.equals_func);
-
- public void registered(Dino.Application app) {
- ensure_context();
- this.app = app;
- this.db = new Database(Path.build_filename(Application.get_storage_dir(), "omemo.db"));
- this.list_entry = new EncryptionListEntry(this);
- this.contact_details_provider = new ContactDetailsProvider(this);
- this.device_notification_populator = new DeviceNotificationPopulator(this, this.app.stream_interactor);
- this.trust_manager = new TrustManager(this.app.stream_interactor, this.db);
-
- this.app.plugin_registry.register_encryption_list_entry(list_entry);
- this.app.plugin_registry.register_encryption_preferences_entry(new OmemoPreferencesEntry(this));
- this.app.plugin_registry.register_contact_details_entry(contact_details_provider);
- this.app.plugin_registry.register_notification_populator(device_notification_populator);
- this.app.plugin_registry.register_conversation_addition_populator(new BadMessagesPopulator(this.app.stream_interactor, this));
- this.app.plugin_registry.register_call_entryption_entry(DtlsSrtpVerificationDraft.NS_URI, new CallEncryptionEntry(db));
-
- this.app.stream_interactor.module_manager.initialize_account_modules.connect((account, list) => {
- Store store = Plugin.get_context().create_store();
- list.add(new StreamModule(store));
- decryptors[account] = new OmemoDecryptor(account, app.stream_interactor, trust_manager, db, store);
- list.add(decryptors[account]);
- encryptors[account] = new OmemoEncryptor(account, trust_manager, store);
- list.add(encryptors[account]);
- list.add(new JetOmemo.Module());
- list.add(new DtlsSrtpVerificationDraft.StreamModule());
- this.own_notifications = new OwnNotifications(this, this.app.stream_interactor, account);
- });
-
- app.stream_interactor.get_module(MessageProcessor.IDENTITY).received_pipeline.connect(new DecryptMessageListener(decryptors));
- app.stream_interactor.get_module(FileManager.IDENTITY).add_file_decryptor(new OmemoFileDecryptor());
- app.stream_interactor.get_module(FileManager.IDENTITY).add_file_encryptor(new OmemoFileEncryptor());
- JingleFileHelperRegistry.instance.add_encryption_helper(Encryption.OMEMO, new JetOmemo.EncryptionHelper(app.stream_interactor));
-
- Manager.start(this.app.stream_interactor, db, trust_manager, encryptors);
-
- string locales_dir;
- if (app.search_path_generator != null) {
- locales_dir = ((!)app.search_path_generator).get_locale_path(GETTEXT_PACKAGE, LOCALE_INSTALL_DIR);
- } else {
- locales_dir = LOCALE_INSTALL_DIR;
- }
- internationalize(GETTEXT_PACKAGE, locales_dir);
- }
-
- public void shutdown() {
- // Nothing to do
- }
-
- public bool has_new_devices(Account account, Xmpp.Jid jid) {
- int identity_id = db.identity.get_id(account.id);
- if (identity_id < 0) return false;
-
- return db.identity_meta.get_new_devices(identity_id, jid.bare_jid.to_string()).count() > 0;
- }
-}
-
-}
diff --git a/plugins/omemo/src/protocol/bundle.vala b/plugins/omemo/src/protocol/bundle.vala
deleted file mode 100644
index b7e2b9cf..00000000
--- a/plugins/omemo/src/protocol/bundle.vala
+++ /dev/null
@@ -1,88 +0,0 @@
-using Gee;
-using Omemo;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
-public class Bundle {
- public StanzaNode? node;
-
- public Bundle(StanzaNode? node) {
- this.node = node;
- assert(Plugin.ensure_context());
- }
-
- public int32 signed_pre_key_id { get {
- if (node == null) return -1;
- string? id = ((!)node).get_deep_attribute("signedPreKeyPublic", "signedPreKeyId");
- if (id == null) return -1;
- return int.parse((!)id);
- }}
-
- public ECPublicKey? signed_pre_key { owned get {
- if (node == null) return null;
- string? key = ((!)node).get_deep_string_content("signedPreKeyPublic");
- if (key == null) return null;
- try {
- return Plugin.get_context().decode_public_key(Base64.decode((!)key));
- } catch (Error e) {
- return null;
- }
- }}
-
- public uint8[]? signed_pre_key_signature { owned get {
- if (node == null) return null;
- string? sig = ((!)node).get_deep_string_content("signedPreKeySignature");
- if (sig == null) return null;
- return Base64.decode((!)sig);
- }}
-
- public ECPublicKey? identity_key { owned get {
- if (node == null) return null;
- string? key = ((!)node).get_deep_string_content("identityKey");
- if (key == null) return null;
- try {
- return Plugin.get_context().decode_public_key(Base64.decode((!)key));
- } catch (Error e) {
- return null;
- }
- }}
-
- public ArrayList<PreKey> pre_keys { owned get {
- ArrayList<PreKey> list = new ArrayList<PreKey>();
- if (node == null || ((!)node).get_subnode("prekeys") == null) return list;
- ((!)node).get_deep_subnodes("prekeys", "preKeyPublic")
- .filter((node) => ((!)node).get_attribute("preKeyId") != null)
- .map<PreKey>(PreKey.create)
- .foreach((key) => list.add(key));
- return list;
- }}
-
- public class PreKey {
- private StanzaNode node;
-
- public static PreKey create(owned StanzaNode node) {
- return new PreKey(node);
- }
-
- public PreKey(StanzaNode node) {
- this.node = node;
- }
-
- public int32 key_id { get {
- return int.parse(node.get_attribute("preKeyId") ?? "-1");
- }}
-
- public ECPublicKey? key { owned get {
- string? key = node.get_string_content();
- if (key == null) return null;
- try {
- return Plugin.get_context().decode_public_key(Base64.decode((!)key));
- } catch (Error e) {
- return null;
- }
- }}
- }
-}
-
-}
diff --git a/plugins/omemo/src/protocol/message_flag.vala b/plugins/omemo/src/protocol/message_flag.vala
deleted file mode 100644
index ba9ea16e..00000000
--- a/plugins/omemo/src/protocol/message_flag.vala
+++ /dev/null
@@ -1,23 +0,0 @@
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
-public class MessageFlag : Xmpp.MessageFlag {
- public const string id = "omemo";
-
- public bool decrypted = false;
-
- public static MessageFlag? get_flag(MessageStanza message) {
- return (MessageFlag) message.get_flag(NS_URI, id);
- }
-
- public override string get_ns() {
- return NS_URI;
- }
-
- public override string get_id() {
- return id;
- }
-}
-
-} \ No newline at end of file
diff --git a/plugins/omemo/src/protocol/stream_module.vala b/plugins/omemo/src/protocol/stream_module.vala
deleted file mode 100644
index cb68d4b4..00000000
--- a/plugins/omemo/src/protocol/stream_module.vala
+++ /dev/null
@@ -1,331 +0,0 @@
-using Gee;
-using Xmpp;
-using Xmpp.Xep;
-using Omemo;
-
-namespace Dino.Plugins.Omemo {
-
-internal const string NS_URI = "eu.siacs.conversations.axolotl";
-private const string NODE_DEVICELIST = NS_URI + ".devicelist";
-private const string NODE_BUNDLES = NS_URI + ".bundles";
-private const string NODE_VERIFICATION = NS_URI + ".verification";
-
-private const int NUM_KEYS_TO_PUBLISH = 100;
-
-public class StreamModule : XmppStreamModule {
- public static Xmpp.ModuleIdentity<StreamModule> IDENTITY = new Xmpp.ModuleIdentity<StreamModule>(NS_URI, "omemo_module");
- private static TimeSpan IGNORE_TIME = TimeSpan.MINUTE;
-
- public Store store { public get; private set; }
- private ConcurrentSet<string> active_bundle_requests = new ConcurrentSet<string>();
- private HashMap<Jid, Future<ArrayList<int32>>> active_devicelist_requests = new HashMap<Jid, Future<ArrayList<int32>>>(Jid.hash_func, Jid.equals_func);
- private Map<string, DateTime> device_ignore_time = new HashMap<string, DateTime>();
-
- public signal void device_list_loaded(Jid jid, ArrayList<int32> devices);
- public signal void bundle_fetched(Jid jid, int device_id, Bundle bundle);
- public signal void bundle_fetch_failed(Jid jid, int device_id);
-
- public StreamModule(Store store) {
- this.store = store;
- }
-
- public override void attach(XmppStream stream) {
- stream.get_module(Pubsub.Module.IDENTITY).add_filtered_notification(stream, NODE_DEVICELIST,
- (stream, jid, id, node) => parse_device_list(stream, jid, id, node), null, null);
- }
-
- public override void detach(XmppStream stream) {
- stream.get_module(Pubsub.Module.IDENTITY).remove_filtered_notification(stream, NODE_DEVICELIST);
- }
-
- public async ArrayList<int32> request_user_devicelist(XmppStream stream, Jid jid) {
- var future = active_devicelist_requests[jid];
- if (future == null) {
- var promise = new Promise<ArrayList<int32>?>();
- future = promise.future;
- active_devicelist_requests[jid] = future;
-
- stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid, NODE_DEVICELIST, (stream, jid, id, node) => {
- ArrayList<int32> device_list = parse_device_list(stream, jid, id, node);
- promise.set_value(device_list);
- active_devicelist_requests.unset(jid);
- });
- }
-
- try {
- ArrayList<int32> device_list = yield future.wait_async();
- return device_list;
- } catch (FutureError error) {
- warning("Future error when waiting for device list: %s", error.message);
- return new ArrayList<int32>();
- }
- }
-
- public ArrayList<int32> parse_device_list(XmppStream stream, Jid jid, string? id, StanzaNode? node_) {
- ArrayList<int32> device_list = new ArrayList<int32>();
-
- StanzaNode node = node_ ?? new StanzaNode.build("list", NS_URI).add_self_xmlns();
- Jid? my_jid = stream.get_flag(Bind.Flag.IDENTITY).my_jid;
- if (my_jid == null) return device_list;
- if (jid.equals_bare(my_jid) && store.local_registration_id != 0) {
- bool am_on_devicelist = false;
- foreach (StanzaNode device_node in node.get_subnodes("device")) {
- int device_id = device_node.get_attribute_int("id");
- if (store.local_registration_id == device_id) {
- am_on_devicelist = true;
- }
- }
- if (!am_on_devicelist) {
- debug("Not on device list, adding id");
- node.put_node(new StanzaNode.build("device", NS_URI).put_attribute("id", store.local_registration_id.to_string()));
- stream.get_module(Pubsub.Module.IDENTITY).publish.begin(stream, jid, NODE_DEVICELIST, id, node, null, true, () => {
- try_make_node_public.begin(stream, NODE_DEVICELIST);
- });
- }
- publish_bundles_if_needed(stream, jid);
- }
-
- foreach (StanzaNode device_node in node.get_subnodes("device")) {
- device_list.add(device_node.get_attribute_int("id"));
- }
- device_list_loaded(jid, device_list);
-
- return device_list;
- }
-
- public void fetch_bundles(XmppStream stream, Jid jid, Gee.List<int32> devices) {
- Address address = new Address(jid.bare_jid.to_string(), 0);
- foreach(int32 device_id in devices) {
- if (!is_ignored_device(jid, device_id)) {
- address.device_id = device_id;
- try {
- if (!store.contains_session(address)) {
- fetch_bundle(stream, jid, device_id);
- }
- } catch (Error e) {
- // Ignore
- }
- }
- }
- address.device_id = 0; // TODO: Hack to have address obj live longer
- }
-
- public void fetch_bundle(XmppStream stream, Jid jid, int device_id, bool ignore_if_non_present = true) {
- if (active_bundle_requests.add(jid.bare_jid.to_string() + @":$device_id")) {
- debug("Asking for bundle for %s/%d", jid.bare_jid.to_string(), device_id);
- stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid.bare_jid, @"$NODE_BUNDLES:$device_id", (stream, jid, id, node) => {
- on_other_bundle_result(stream, jid, device_id, id, node, ignore_if_non_present);
- });
- }
- }
-
- public void ignore_device(Jid jid, int32 device_id) {
- if (device_id <= 0) return;
- lock (device_ignore_time) {
- device_ignore_time[jid.bare_jid.to_string() + @":$device_id"] = new DateTime.now_utc();
- }
- }
-
- public void unignore_device(Jid jid, int32 device_id) {
- if (device_id <= 0) return;
- lock (device_ignore_time) {
- device_ignore_time.unset(jid.bare_jid.to_string() + @":$device_id");
- }
- }
-
- public bool is_ignored_device(Jid jid, int32 device_id) {
- if (device_id <= 0) return true;
- lock (device_ignore_time) {
- string id = jid.bare_jid.to_string() + @":$device_id";
- if (device_ignore_time.has_key(id)) {
- return new DateTime.now_utc().difference(device_ignore_time[id]) < IGNORE_TIME;
- }
- }
- return false;
- }
-
- public void clear_device_list(XmppStream stream) {
- stream.get_module(Pubsub.Module.IDENTITY).delete_node(stream, null, NODE_DEVICELIST);
- }
-
- private void on_other_bundle_result(XmppStream stream, Jid jid, int device_id, string? id, StanzaNode? node, bool ignore_if_non_present) {
- if (node == null) {
- // Device not registered, shouldn't exist
- if (ignore_if_non_present) {
- debug("Ignoring device %s/%d: No bundle", jid.bare_jid.to_string(), device_id);
- stream.get_module(IDENTITY).ignore_device(jid, device_id);
- }
- bundle_fetch_failed(jid, device_id);
- } else {
- Bundle bundle = new Bundle(node);
- stream.get_module(IDENTITY).unignore_device(jid, device_id);
- debug("Received bundle for %s/%d: %s", jid.bare_jid.to_string(), device_id, Base64.encode(bundle.identity_key.serialize()));
- bundle_fetched(jid, device_id, bundle);
- }
- stream.get_module(IDENTITY).active_bundle_requests.remove(jid.bare_jid.to_string() + @":$device_id");
- }
-
- public bool start_session(XmppStream stream, Jid jid, int32 device_id, Bundle bundle) {
- bool fail = false;
- int32 signed_pre_key_id = bundle.signed_pre_key_id;
- ECPublicKey? signed_pre_key = bundle.signed_pre_key;
- uint8[] signed_pre_key_signature = bundle.signed_pre_key_signature;
- ECPublicKey? identity_key = bundle.identity_key;
-
- ArrayList<Bundle.PreKey> pre_keys = bundle.pre_keys;
- if (signed_pre_key_id < 0 || signed_pre_key == null || identity_key == null || pre_keys.size == 0) {
- fail = true;
- } else {
- int pre_key_idx = Random.int_range(0, pre_keys.size);
- int32 pre_key_id = pre_keys[pre_key_idx].key_id;
- ECPublicKey? pre_key = pre_keys[pre_key_idx].key;
- if (pre_key_id < 0 || pre_key == null) {
- fail = true;
- } else {
- Address address = new Address(jid.bare_jid.to_string(), device_id);
- try {
- if (store.contains_session(address)) {
- return false;
- }
- debug("Starting new session for encryption with %s/%d", jid.bare_jid.to_string(), device_id);
- SessionBuilder builder = store.create_session_builder(address);
- builder.process_pre_key_bundle(create_pre_key_bundle(device_id, device_id, pre_key_id, pre_key, signed_pre_key_id, signed_pre_key, signed_pre_key_signature, identity_key));
- } catch (Error e) {
- debug("Can't create session with %s/%d: %s", jid.bare_jid.to_string(), device_id, e.message);
- fail = true;
- }
- address.device_id = 0; // TODO: Hack to have address obj live longer
- }
- }
- if (fail) {
- debug("Ignoring device %s/%d: Bad bundle: %s", jid.bare_jid.to_string(), device_id, bundle.node.to_string());
- stream.get_module(IDENTITY).ignore_device(jid, device_id);
- }
- return true;
- }
-
- public void publish_bundles_if_needed(XmppStream stream, Jid jid) {
- if (active_bundle_requests.add(jid.bare_jid.to_string() + @":$(store.local_registration_id)")) {
- stream.get_module(Pubsub.Module.IDENTITY).request(stream, jid, @"$NODE_BUNDLES:$(store.local_registration_id)", on_self_bundle_result);
- }
- }
-
- private void on_self_bundle_result(XmppStream stream, Jid jid, string? id, StanzaNode? node) {
- if (!Plugin.ensure_context()) return;
- Map<int, ECPublicKey> keys = new HashMap<int, ECPublicKey>();
- ECPublicKey? identity_key = null;
- int32 signed_pre_key_id = -1;
- ECPublicKey? signed_pre_key = null;
- SignedPreKeyRecord? signed_pre_key_record = null;
- bool changed = false;
- if (node == null) {
- identity_key = store.identity_key_pair.public;
- changed = true;
- } else {
- Bundle bundle = new Bundle(node);
- foreach (Bundle.PreKey prekey in bundle.pre_keys) {
- ECPublicKey? key = prekey.key;
- if (key != null) {
- keys[prekey.key_id] = (!)key;
- }
- }
- identity_key = bundle.identity_key;
- signed_pre_key_id = bundle.signed_pre_key_id;
- signed_pre_key = bundle.signed_pre_key;
- }
-
- try {
- // Validate IdentityKey
- if (identity_key == null || store.identity_key_pair.public.compare((!)identity_key) != 0) {
- changed = true;
- }
- IdentityKeyPair identity_key_pair = store.identity_key_pair;
-
- // Validate signedPreKeyRecord + ID
- if (signed_pre_key == null || signed_pre_key_id == -1 || !store.contains_signed_pre_key(signed_pre_key_id) || store.load_signed_pre_key(signed_pre_key_id).key_pair.public.compare((!)signed_pre_key) != 0) {
- signed_pre_key_id = Random.int_range(1, int32.MAX); // TODO: No random, use ordered number
- signed_pre_key_record = Plugin.get_context().generate_signed_pre_key(identity_key_pair, signed_pre_key_id);
- store.store_signed_pre_key((!)signed_pre_key_record);
- changed = true;
- } else {
- signed_pre_key_record = store.load_signed_pre_key(signed_pre_key_id);
- }
-
- // Validate PreKeys
- Set<PreKeyRecord> pre_key_records = new HashSet<PreKeyRecord>();
- foreach (var entry in keys.entries) {
- if (store.contains_pre_key(entry.key)) {
- PreKeyRecord record = store.load_pre_key(entry.key);
- if (record.key_pair.public.compare(entry.value) == 0) {
- pre_key_records.add(record);
- }
- }
- }
- int new_keys = NUM_KEYS_TO_PUBLISH - pre_key_records.size;
- if (new_keys > 0) {
- int32 next_id = Random.int_range(1, int32.MAX); // TODO: No random, use ordered number
- Set<PreKeyRecord> new_records = Plugin.get_context().generate_pre_keys((uint)next_id, (uint)new_keys);
- pre_key_records.add_all(new_records);
- foreach (PreKeyRecord record in new_records) {
- store.store_pre_key(record);
- }
- changed = true;
- }
-
- if (changed) {
- publish_bundles.begin(stream, (!)signed_pre_key_record, identity_key_pair, pre_key_records, (int32) store.local_registration_id);
- }
- } catch (Error e) {
- warning(@"Unexpected error while publishing bundle: $(e.message)\n");
- }
- stream.get_module(IDENTITY).active_bundle_requests.remove(jid.bare_jid.to_string() + @":$(store.local_registration_id)");
- }
-
- public async void publish_bundles(XmppStream stream, SignedPreKeyRecord signed_pre_key_record, IdentityKeyPair identity_key_pair, Set<PreKeyRecord> pre_key_records, int32 device_id) throws Error {
- ECKeyPair tmp;
- StanzaNode bundle = new StanzaNode.build("bundle", NS_URI)
- .add_self_xmlns()
- .put_node(new StanzaNode.build("signedPreKeyPublic", NS_URI)
- .put_attribute("signedPreKeyId", signed_pre_key_record.id.to_string())
- .put_node(new StanzaNode.text(Base64.encode((tmp = signed_pre_key_record.key_pair).public.serialize()))))
- .put_node(new StanzaNode.build("signedPreKeySignature", NS_URI)
- .put_node(new StanzaNode.text(Base64.encode(signed_pre_key_record.signature))))
- .put_node(new StanzaNode.build("identityKey", NS_URI)
- .put_node(new StanzaNode.text(Base64.encode(identity_key_pair.public.serialize()))));
- StanzaNode prekeys = new StanzaNode.build("prekeys", NS_URI);
- foreach (PreKeyRecord pre_key_record in pre_key_records) {
- prekeys.put_node(new StanzaNode.build("preKeyPublic", NS_URI)
- .put_attribute("preKeyId", pre_key_record.id.to_string())
- .put_node(new StanzaNode.text(Base64.encode(pre_key_record.key_pair.public.serialize()))));
- }
- bundle.put_node(prekeys);
-
- string node_id = @"$NODE_BUNDLES:$device_id";
- yield stream.get_module(Pubsub.Module.IDENTITY).publish(stream, null, node_id, "1", bundle);
- yield try_make_node_public(stream, node_id);
-
- }
-
- private async void try_make_node_public(XmppStream stream, string node_id) {
- DataForms.DataForm? data_form = yield stream.get_module(Pubsub.Module.IDENTITY).request_node_config(stream, null, node_id);
- if (data_form == null) return;
-
- foreach (DataForms.DataForm.Field field in data_form.fields) {
- if (field.var == "pubsub#access_model" && field.get_value_string() != Pubsub.ACCESS_MODEL_OPEN) {
- field.set_value_string(Pubsub.ACCESS_MODEL_OPEN);
- yield stream.get_module(Pubsub.Module.IDENTITY).submit_node_config(stream, data_form, node_id);
- break;
- }
- }
- }
-
- public override string get_ns() {
- return NS_URI;
- }
-
- public override string get_id() {
- return IDENTITY.id;
- }
-}
-
-}
diff --git a/plugins/omemo/src/register_plugin.vala b/plugins/omemo/src/register_plugin.vala
deleted file mode 100644
index 0d0e1c3e..00000000
--- a/plugins/omemo/src/register_plugin.vala
+++ /dev/null
@@ -1,3 +0,0 @@
-public Type register_plugin(Module module) {
- return typeof (Dino.Plugins.Omemo.Plugin);
-}
diff --git a/plugins/omemo/src/trust_level.vala b/plugins/omemo/src/trust_level.vala
deleted file mode 100644
index afcfb0fb..00000000
--- a/plugins/omemo/src/trust_level.vala
+++ /dev/null
@@ -1,15 +0,0 @@
-namespace Dino.Plugins.Omemo {
-
-public enum TrustLevel {
- VERIFIED,
- TRUSTED,
- UNTRUSTED,
- UNKNOWN;
-
- public string to_string() {
- int val = this;
- return val.to_string();
- }
-}
-
-}
diff --git a/plugins/omemo/src/ui/bad_messages_populator.vala b/plugins/omemo/src/ui/bad_messages_populator.vala
deleted file mode 100644
index 9dacba95..00000000
--- a/plugins/omemo/src/ui/bad_messages_populator.vala
+++ /dev/null
@@ -1,198 +0,0 @@
-using Gee;
-using Gtk;
-using Qlite;
-
-using Dino.Entities;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
-public enum BadnessType {
- UNTRUSTED,
- UNDECRYPTABLE
-}
-
-public class BadMessagesPopulator : Plugins.ConversationItemPopulator, Plugins.ConversationAdditionPopulator, Object {
-
- public string id { get { return "bad_omemo_messages"; } }
-
- private StreamInteractor stream_interactor;
- private Plugin plugin;
- private Database db;
-
- private Conversation? current_conversation;
- private Plugins.ConversationItemCollection? item_collection;
-
- private Gee.List<BadMessageItem> bad_items = new ArrayList<BadMessageItem>();
-
- public BadMessagesPopulator(StreamInteractor stream_interactor, Plugin plugin) {
- this.stream_interactor = stream_interactor;
- this.plugin = plugin;
- this.db = plugin.db;
-
- plugin.trust_manager.bad_message_state_updated.connect((account, jid, device_id) => {
- clear_state();
- init_state();
- });
- }
-
- private void init_state() {
- if (current_conversation == null) return;
- if (current_conversation.type_ == Conversation.Type.GROUPCHAT_PM) return;
-
- var qry = db.identity_meta.select()
- .join_with(db.identity, db.identity.id, db.identity_meta.identity_id)
- .with(db.identity.account_id, "=", current_conversation.account.id)
- .where("last_message_untrusted is not NULL OR last_message_undecryptable is not NULL");
-
- switch (current_conversation.type_) {
- case Conversation.Type.CHAT:
- qry.with(db.identity_meta.address_name, "=", current_conversation.counterpart.to_string());
- break;
- case Conversation.Type.GROUPCHAT:
- bool is_private = stream_interactor.get_module(MucManager.IDENTITY).is_private_room(current_conversation.account, current_conversation.counterpart);
- if (!is_private) return;
-
- var list = stream_interactor.get_module(MucManager.IDENTITY).get_offline_members(current_conversation.counterpart, current_conversation.account);
- if (list == null || list.is_empty) return;
-
- var selection = new StringBuilder();
- string[] selection_args = {};
- foreach (Jid jid in list) {
- if (selection.len == 0) {
- selection.append(@" ($(db.identity_meta.address_name) = ?");
- } else {
- selection.append(@" OR $(db.identity_meta.address_name) = ?");
- }
- selection_args += jid.to_string();
- }
- selection.append(")");
- qry.where(selection.str, selection_args);
- break;
- case Conversation.Type.GROUPCHAT_PM:
- break;
- }
-
- foreach (Row row in qry) {
- Jid jid = Jid.from_string(row[db.identity_meta.address_name]);
- if (!db.identity_meta.last_message_untrusted.is_null(row)) {
- DateTime time = new DateTime.from_unix_utc(row[db.identity_meta.last_message_untrusted]);
- var item = new BadMessageItem(plugin, current_conversation, jid, time, BadnessType.UNTRUSTED);
- bad_items.add(item);
- item_collection.insert_item(item);
- }
- if (!db.identity_meta.last_message_undecryptable.is_null(row)) {
- DateTime time = new DateTime.from_unix_utc(row[db.identity_meta.last_message_undecryptable]);
- var item = new BadMessageItem(plugin, current_conversation, jid, time, BadnessType.UNDECRYPTABLE);
- bad_items.add(item);
- item_collection.insert_item(item);
- }
- }
- }
-
- private void clear_state() {
- foreach (BadMessageItem bad_item in bad_items) {
- item_collection.remove_item(bad_item);
- }
- bad_items.clear();
- }
-
- public void init(Conversation conversation, Plugins.ConversationItemCollection item_collection, Plugins.WidgetType type) {
- current_conversation = conversation;
- this.item_collection = item_collection;
-
- init_state();
- }
-
- public void close(Conversation conversation) {
- clear_state();
- }
-
- public void populate_timespan(Conversation conversation, DateTime after, DateTime before) { }
-}
-
-public class BadMessageItem : Plugins.MetaConversationItem {
-
- private Plugin plugin;
- private Conversation conversation;
- private Jid problem_jid;
- private BadnessType badness_type;
-
- public BadMessageItem(Plugin plugin, Conversation conversation, Jid jid, DateTime date, BadnessType badness_type) {
- this.plugin = plugin;
- this.conversation = conversation;
- this.problem_jid = jid;
- this.time = date;
- this.badness_type = badness_type;
- }
-
- public override Object? get_widget(Plugins.ConversationItemWidgetInterface outer, Plugins.WidgetType widget_type) {
- return new BadMessagesWidget(plugin, conversation, problem_jid, badness_type);
- }
-
- public override Gee.List<Plugins.MessageAction>? get_item_actions(Plugins.WidgetType type) { return null; }
-}
-
-public class BadMessagesWidget : Box {
- private Plugin plugin;
- private Conversation conversation;
- private Jid jid;
- private Label label;
-
- public BadMessagesWidget(Plugin plugin, Conversation conversation, Jid jid, BadnessType badness_type) {
- Object(orientation:Orientation.HORIZONTAL, spacing:5);
-
- this.plugin = plugin;
- this.conversation = conversation;
- this.jid = jid;
- this.halign = Align.CENTER;
- this.visible = true;
-
- string who = "";
- if (conversation.type_ == Conversation.Type.CHAT) {
- who = Dino.get_participant_display_name(plugin.app.stream_interactor, conversation, jid);
- } else if (conversation.type_ == Conversation.Type.GROUPCHAT) {
- who = jid.to_string();
- // `jid` is a real JID. In MUCs, try to show nicks instead (given that the JID is currently online)
- var occupants = plugin.app.stream_interactor.get_module(MucManager.IDENTITY).get_occupants(conversation.counterpart, conversation.account);
- if (occupants == null) return;
- foreach (Jid occupant in occupants) {
- if (jid.equals_bare(plugin.app.stream_interactor.get_module(MucManager.IDENTITY).get_real_jid(occupant, conversation.account))) {
- who = occupant.resourcepart;
- }
- }
- }
-
- string warning_text = "";
- if (badness_type == BadnessType.UNTRUSTED) {
- warning_text = _("%s has been using an untrusted device. You won't see messages from devices that you do not trust.").printf(who) +
- " <a href=\"\">%s</a>".printf(_("Manage devices"));
- } else {
- warning_text += _("%s does not trust this device. That means, you might be missing messages.").printf(who);
- }
- label = new Label(warning_text) { margin_start=70, margin_end=70, justify=Justification.CENTER, use_markup=true, selectable=true, wrap=true, wrap_mode=Pango.WrapMode.WORD_CHAR, hexpand=true };
- label.add_css_class("dim-label");
- this.append(label);
-
- if (badness_type == BadnessType.UNTRUSTED) {
- label.activate_link.connect(on_label_activate_link);
- }
- }
-
- private bool on_label_activate_link() {
- var variant = new Variant.tuple(new Variant[] {new Variant.int32(conversation.id), new Variant.string("encryption")});
- GLib.Application.get_default().activate_action("open-conversation-details", variant);
- return false;
- }
-
- public override void dispose() {
- if (label != null) {
- label.unparent();
- label.dispose();
- label = null;
- }
- base.dispose();
- }
-}
-
-}
diff --git a/plugins/omemo/src/ui/call_encryption_entry.vala b/plugins/omemo/src/ui/call_encryption_entry.vala
deleted file mode 100644
index 69b7b686..00000000
--- a/plugins/omemo/src/ui/call_encryption_entry.vala
+++ /dev/null
@@ -1,57 +0,0 @@
-using Dino.Entities;
-using Gtk;
-using Qlite;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
- public class CallEncryptionEntry : Plugins.CallEncryptionEntry, Object {
- private Database db;
-
- public CallEncryptionEntry(Database db) {
- this.db = db;
- }
-
- public Plugins.CallEncryptionWidget? get_widget(Account account, Xmpp.Xep.Jingle.ContentEncryption encryption) {
- DtlsSrtpVerificationDraft.OmemoContentEncryption? omemo_encryption = encryption as DtlsSrtpVerificationDraft.OmemoContentEncryption;
- if (omemo_encryption == null) return null;
-
- int identity_id = db.identity.get_id(account.id);
- Row? device = db.identity_meta.get_device(identity_id, omemo_encryption.jid.to_string(), omemo_encryption.sid);
- if (device == null) return null;
- TrustLevel trust = (TrustLevel) device[db.identity_meta.trust_level];
-
- return new CallEncryptionWidget(trust);
- }
- }
-
- public class CallEncryptionWidget : Plugins.CallEncryptionWidget, Object {
-
- string? title = null;
- string? icon = null;
- bool should_show_keys = false;
-
- public CallEncryptionWidget(TrustLevel trust) {
- if (trust == TrustLevel.VERIFIED) {
- title = "This call is <b>encrypted and verified</b> with OMEMO.";
- icon = "dino-security-high-symbolic";
- should_show_keys = false;
- } else {
- title = "This call is encrypted with OMEMO.";
- should_show_keys = true;
- }
- }
-
- public string? get_title() {
- return title;
- }
-
- public string? get_icon_name() {
- return icon;
- }
-
- public bool show_keys() {
- return should_show_keys;
- }
- }
-}
diff --git a/plugins/omemo/src/ui/contact_details_provider.vala b/plugins/omemo/src/ui/contact_details_provider.vala
deleted file mode 100644
index 7c733cd7..00000000
--- a/plugins/omemo/src/ui/contact_details_provider.vala
+++ /dev/null
@@ -1,29 +0,0 @@
-using Gtk;
-using Gee;
-using Qlite;
-using Dino.Entities;
-
-namespace Dino.Plugins.Omemo {
-
-public class ContactDetailsProvider : Plugins.ContactDetailsProvider, Object {
- public string id { get { return "omemo_info"; } }
- public string tab { get { return "encryption"; } }
-
- private Plugin plugin;
-
- public ContactDetailsProvider(Plugin plugin) {
- this.plugin = plugin;
- }
-
- public void populate(Conversation conversation, Plugins.ContactDetails contact_details, WidgetType type) { }
-
- public Object? get_widget(Conversation conversation) {
- if (conversation.type_ != Conversation.Type.CHAT) return null;
-
- var widget = new OmemoPreferencesWidget(plugin);
- widget.set_jid(conversation.account, conversation.counterpart);
- return widget;
- }
-}
-
-}
diff --git a/plugins/omemo/src/ui/device_notification_populator.vala b/plugins/omemo/src/ui/device_notification_populator.vala
deleted file mode 100644
index 7829d89c..00000000
--- a/plugins/omemo/src/ui/device_notification_populator.vala
+++ /dev/null
@@ -1,90 +0,0 @@
-using Dino.Entities;
-using Xmpp;
-using Gtk;
-
-namespace Dino.Plugins.Omemo {
-
-public class DeviceNotificationPopulator : NotificationPopulator, Object {
-
- public string id { get { return "device_notification"; } }
-
- private StreamInteractor? stream_interactor;
- private Plugin plugin;
- private Conversation? current_conversation;
- private NotificationCollection? notification_collection;
- private ConversationNotification notification;
-
- public DeviceNotificationPopulator(Plugin plugin, StreamInteractor stream_interactor) {
- this.stream_interactor = stream_interactor;
- this.plugin = plugin;
-
- stream_interactor.account_added.connect(on_account_added);
- }
-
- public void init(Conversation conversation, NotificationCollection notification_collection, Plugins.WidgetType type) {
- current_conversation = conversation;
- this.notification_collection = notification_collection;
- if (plugin.has_new_devices(conversation.account, conversation.counterpart) && conversation.type_ == Conversation.Type.CHAT) {
- display_notification();
- }
- }
-
- public void close(Conversation conversation) {
- notification = null;
- }
-
- private void display_notification() {
- if (notification == null) {
- notification = new ConversationNotification(plugin, current_conversation);
- notification.should_hide.connect(should_hide);
- notification_collection.add_meta_notification(notification);
- }
- }
-
- public void should_hide() {
- if (!plugin.has_new_devices(current_conversation.account, current_conversation.counterpart) && notification != null){
- notification_collection.remove_meta_notification(notification);
- notification = null;
- }
- }
-
- private void on_account_added(Account account) {
- stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).bundle_fetched.connect_after((jid, device_id, bundle) => {
- if (current_conversation != null && jid.equals(current_conversation.counterpart) && plugin.has_new_devices(current_conversation.account, current_conversation.counterpart)) {
- display_notification();
- }
- });
- }
-}
-
-private class ConversationNotification : MetaConversationNotification {
- private Widget widget;
- private Plugin plugin;
- private Jid jid;
- private Account account;
- public signal void should_hide();
-
- public ConversationNotification(Plugin plugin, Conversation conversation) {
- this.plugin = plugin;
- this.jid = jid;
- this.account = account;
-
- Box box = new Box(Orientation.HORIZONTAL, 5);
- Button manage_button = new Button.with_label(_("Manage"));
- manage_button.clicked.connect(() => {
- manage_button.activate();
-
- var variant = new Variant.tuple(new Variant[] {new Variant.int32(conversation.id), new Variant.string("encryption")});
- GLib.Application.get_default().activate_action("open-conversation-details", variant);
- });
- box.append(new Label(_("This contact has new devices")) { margin_end=10 });
- box.append(manage_button);
- widget = box;
- }
-
- public override Object? get_widget(WidgetType type) {
- return widget;
- }
-}
-
-}
diff --git a/plugins/omemo/src/ui/encryption_list_entry.vala b/plugins/omemo/src/ui/encryption_list_entry.vala
deleted file mode 100644
index 3bb76c52..00000000
--- a/plugins/omemo/src/ui/encryption_list_entry.vala
+++ /dev/null
@@ -1,77 +0,0 @@
-using Dino.Entities;
-using Gtk;
-using Qlite;
-using Xmpp;
-
-namespace Dino.Plugins.Omemo {
-
-public class EncryptionListEntry : Plugins.EncryptionListEntry, Object {
- private Plugin plugin;
- private Database db;
-
- public EncryptionListEntry(Plugin plugin) {
- this.plugin = plugin;
- this.db = plugin.db;
- }
-
- public Entities.Encryption encryption { get {
- return Entities.Encryption.OMEMO;
- }}
-
- public string name { get {
- return "OMEMO";
- }}
-
- public Object? get_encryption_icon(Entities.Conversation conversation, ContentItem content_item) {
- return null;
- }
-
- public string? get_encryption_icon_name(Entities.Conversation conversation, ContentItem content_item) {
- if (content_item.encryption != encryption) return null;
-
- RowOption row = db.content_item_meta.select( { db.identity_meta.trust_level } ).with(db.content_item_meta.content_item_id, "=", content_item.id)
- .join_on(db.identity_meta, @"$(db.identity_meta.address_name)=$(db.content_item_meta.address_name) AND $(db.identity_meta.device_id)=$(db.content_item_meta.device_id)")
- .single().row();
-
-
- if (row.is_present() && (TrustLevel) row[db.identity_meta.trust_level] == TrustLevel.VERIFIED) {
- return "dino-security-high-symbolic";
- }
- return null;
- }
-
- public void encryption_activated(Entities.Conversation conversation, Plugins.SetInputFieldStatus input_status_callback) {
- encryption_activated_async.begin(conversation, input_status_callback);
- }
-
- public async void encryption_activated_async(Entities.Conversation conversation, Plugins.SetInputFieldStatus input_status_callback) {
- if (conversation.type_ == Conversation.Type.GROUPCHAT_PM) {
- input_status_callback(new Plugins.InputFieldStatus("Can't use encryption in a groupchat private message.", Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND));
- return;
- }
- MucManager muc_manager = plugin.app.stream_interactor.get_module(MucManager.IDENTITY);
- Manager omemo_manager = plugin.app.stream_interactor.get_module(Manager.IDENTITY);
-
- if (muc_manager.is_private_room(conversation.account, conversation.counterpart)) {
- var offline_members = muc_manager.get_offline_members(conversation.counterpart, conversation.account);
- if (offline_members == null) {
- // We don't store offline members yet, and it'll be null if we're offline
- return;
- }
- foreach (Jid offline_member in offline_members) {
- bool ok = yield omemo_manager.ensure_get_keys_for_jid(conversation.account, offline_member);
- if (!ok) {
- input_status_callback(new Plugins.InputFieldStatus("A member does not support OMEMO: %s".printf(offline_member.to_string()), Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND));
- return;
- }
- }
- return;
- }
-
- if (!(yield omemo_manager.ensure_get_keys_for_jid(conversation.account, conversation.counterpart.bare_jid))) {
- input_status_callback(new Plugins.InputFieldStatus("This contact does not support %s encryption".printf("OMEMO"), Plugins.InputFieldStatus.MessageType.ERROR, Plugins.InputFieldStatus.InputState.NO_SEND));
- }
- }
-
-}
-}
diff --git a/plugins/omemo/src/ui/encryption_preferences_entry.vala b/plugins/omemo/src/ui/encryption_preferences_entry.vala
deleted file mode 100644
index f0aedb6a..00000000
--- a/plugins/omemo/src/ui/encryption_preferences_entry.vala
+++ /dev/null
@@ -1,323 +0,0 @@
-using Qlite;
-using Qrencode;
-using Gee;
-using Xmpp;
-using Dino.Entities;
-using Gtk;
-using Omemo;
-
-namespace Dino.Plugins.Omemo {
-
-public class OmemoPreferencesEntry : Plugins.EncryptionPreferencesEntry {
-
- OmemoPreferencesWidget widget;
- Plugin plugin;
-
- public OmemoPreferencesEntry(Plugin plugin) {
- this.plugin = plugin;
- }
-
- public override Object? get_widget(Account account, WidgetType type) {
- if (type != WidgetType.GTK4) return null;
- var widget = new OmemoPreferencesWidget(plugin);
- widget.set_jid(account, account.bare_jid);
- return widget;
- }
-
- public override string id { get { return "omemo_preferences_entryption"; }}
-}
-
-[GtkTemplate (ui = "/im/dino/Dino/omemo/encryption_preferences_entry.ui")]
-public class OmemoPreferencesWidget : Adw.PreferencesGroup {
- private Plugin plugin;
- private Account account;
- private Jid jid;
- private int identity_id = 0;
- private Store store;
- private Set<uint32> displayed_ids = new HashSet<uint32>();
-
- [GtkChild] private unowned Adw.SwitchRow automatically_accept_new_row;
- [GtkChild] private unowned Adw.SwitchRow encrypt_by_default_row;
- [GtkChild] private unowned Label new_keys_label;
-
- [GtkChild] private unowned Adw.PreferencesGroup keys_preferences_group;
- [GtkChild] private unowned ListBox new_keys_listbox;
- [GtkChild] private unowned Picture qrcode_picture;
- [GtkChild] private unowned Popover qrcode_popover;
-
- private ArrayList<Widget> keys_preferences_group_children = new ArrayList<Widget>();
-
- construct {
- // If we set the strings in the .ui file, they don't get translated
- encrypt_by_default_row.title = _("OMEMO by default");
- encrypt_by_default_row.subtitle = _("Enable OMEMO encryption for new conversations");
- automatically_accept_new_row.title = _("Encrypt to new devices");
- automatically_accept_new_row.subtitle = _("Automatically encrypt to new devices from this contact.");
- new_keys_label.label = _("New keys");
- }
-
- public OmemoPreferencesWidget(Plugin plugin) {
- this.plugin = plugin;
- }
-
- public void set_jid(Account account, Jid jid) {
- this.account = account;
- this.jid = jid;
- this.identity_id = plugin.db.identity.get_id(account.id);
- if (identity_id <= 0) {
- warning("OmemoPreferencesWidget missing identity_id");
- return;
- }
-
- automatically_accept_new_row.active = plugin.db.trust.get_blind_trust(identity_id, jid.bare_jid.to_string(), true);
- automatically_accept_new_row.notify["active"].connect((obj, _) => { on_auto_accept_toggled(((Adw.SwitchRow) obj).active); });
-
- encrypt_by_default_row.visible = account.bare_jid.equals_bare(jid);
- encrypt_by_default_row.active = plugin.app.settings.get_default_encryption(account) != Encryption.NONE;
- encrypt_by_default_row.notify["active"].connect((obj, _) => { on_omemo_by_default_toggled(((Adw.SwitchRow) obj).active); });
-
- Dino.Application? app = Application.get_default() as Dino.Application;
- if (app != null) {
- store = app.stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).store;
- }
-
- redraw_key_list();
-
- // Check for unknown devices
- fetch_unknown_bundles();
- }
-
- private void redraw_key_list() {
- // Remove current widgets
- foreach (var widget in keys_preferences_group_children) {
- keys_preferences_group.remove(widget);
- }
- keys_preferences_group_children.clear();
-
- // Dialog opened from the account settings menu
- // Show the fingerprint for this device separately with buttons for a qrcode and to copy
- if(jid.equals(account.bare_jid)) {
- automatically_accept_new_row.subtitle = _("New encryption keys from your other devices will be accepted automatically.");
- add_own_fingerprint();
- }
-
- //Show the normal devicelist
- var own_id = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.device_id];
- foreach (Row device in plugin.db.identity_meta.get_known_devices(identity_id, jid.to_string())) {
- if(jid.equals(account.bare_jid) && device[plugin.db.identity_meta.device_id] == own_id) {
- // If this is our own account, don't show this device twice (did it separately already)
- continue;
- }
- add_fingerprint(device, (TrustLevel) device[plugin.db.identity_meta.trust_level]);
- }
-
- //Show any new devices for which the user must decide whether to accept or reject
- foreach (Row device in plugin.db.identity_meta.get_new_devices(identity_id, jid.to_string())) {
- add_new_fingerprint(device);
- }
- }
-
- private static string escape_for_iri_path_segment(string s) {
- // from RFC 3986, 2.2. Reserved Characters:
- string SUB_DELIMS = "!$&'()*+,;=";
- // from RFC 3986, 3.3. Path (pchar without unreserved and pct-encoded):
- string ALLOWED_RESERVED_CHARS = SUB_DELIMS + ":@";
- return GLib.Uri.escape_string(s, ALLOWED_RESERVED_CHARS, true);
- }
-
- private void fetch_unknown_bundles() {
- Dino.Application app = Application.get_default() as Dino.Application;
- XmppStream? stream = app.stream_interactor.get_stream(account);
- if (stream == null) return;
- StreamModule? module = stream.get_module(StreamModule.IDENTITY);
- if (module == null) return;
- module.bundle_fetched.connect_after((bundle_jid, device_id, bundle) => {
- if (bundle_jid.equals(jid) && !displayed_ids.contains(device_id)) {
- redraw_key_list();
- }
- });
- foreach (Row device in plugin.db.identity_meta.get_unknown_devices(identity_id, jid.to_string())) {
- try {
- module.fetch_bundle(stream, Jid.from_string(device[plugin.db.identity_meta.address_name]), device[plugin.db.identity_meta.device_id], false);
- } catch (InvalidJidError e) {
- warning("Ignoring device with invalid Jid: %s", e.message);
- }
- }
- }
-
- private void add_own_fingerprint() {
- string own_b64 = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.identity_key_public_base64];
- string fingerprint = fingerprint_from_base64(own_b64);
-
- var own_action_box = new Box(Orientation.HORIZONTAL, 6);
- var show_qrcode_button = new MenuButton() { icon_name="dino-qr-code-symbolic", valign=Align.CENTER };
- own_action_box.append(show_qrcode_button);
- var copy_button = new Button() { icon_name="dino-edit-copy-symbolic", valign=Align.CENTER };
- copy_button.clicked.connect(() => { copy_button.get_clipboard().set_text(fingerprint); });
- own_action_box.append(copy_button);
-
- Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true };
- action_row.title = _("This device");
- action_row.subtitle = fingerprint_markup(fingerprint_from_base64(own_b64));
- action_row.add_suffix(own_action_box);
- add_key_row(action_row);
-
- // Create and set QR code popover
- int sid = plugin.db.identity.row_with(plugin.db.identity.account_id, account.id)[plugin.db.identity.device_id];
- var iri_query = @"omemo-sid-$(sid)=$(fingerprint)";
-#if GLIB_2_66 && VALA_0_50
- string iri = GLib.Uri.join(UriFlags.NONE, "xmpp", null, null, 0, jid.to_string(), iri_query, null);
-#else
- var iri_path_seg = escape_for_iri_path_segment(jid.to_string());
- var iri = @"xmpp:$(iri_path_seg)?$(iri_query)";
-#endif
-
- const int QUIET_ZONE_MODULES = 4; // MUST be at least 4
- const int MODULE_SIZE_PX = 4; // arbitrary
- var qr_paintable = new QRcode(iri, 2)
- .to_paintable(MODULE_SIZE_PX * qrcode_picture.scale_factor);
- qrcode_picture.paintable = qr_paintable;
- qrcode_picture.margin_top = qrcode_picture.margin_end =
- qrcode_picture.margin_bottom = qrcode_picture.margin_start = QUIET_ZONE_MODULES * MODULE_SIZE_PX;
- qrcode_popover.add_css_class("qrcode-container");
-
- show_qrcode_button.popover = qrcode_popover;
- }
-
- private void add_fingerprint(Row device, TrustLevel trust) {
- string key_base64 = device[plugin.db.identity_meta.identity_key_public_base64];
- bool key_active = device[plugin.db.identity_meta.now_active];
- if (store != null) {
- try {
- Address address = new Address(jid.to_string(), device[plugin.db.identity_meta.device_id]);
- SessionRecord? session = null;
- if (store.contains_session(address)) {
- session = store.load_session(address);
- string session_key_base64 = Base64.encode(session.state.remote_identity_key.serialize());
- if (key_base64 != session_key_base64) {
- critical("Session and database identity key mismatch!");
- key_base64 = session_key_base64;
- }
- }
- } catch (Error e) {
- print("Error while reading session store: %s", e.message);
- }
- }
-
- if (device[plugin.db.identity_meta.now_active]) {
- Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true };
- action_row.activated.connect(() => {
- Row updated_device = plugin.db.identity_meta.get_device(device[plugin.db.identity_meta.identity_id], device[plugin.db.identity_meta.address_name], device[plugin.db.identity_meta.device_id]);
- ManageKeyDialog manage_dialog = new ManageKeyDialog(updated_device, plugin.db);
- manage_dialog.set_transient_for((Gtk.Window) get_root());
- manage_dialog.present();
- manage_dialog.response.connect((response) => {
- update_stored_trust(response, updated_device);
- redraw_key_list();
- });
- });
- action_row.activatable = true;
- action_row.title = account.bare_jid.equals_bare(jid) ? _("Other device") : _("Device");
- action_row.subtitle = fingerprint_markup(fingerprint_from_base64(key_base64));
- string trust_str = _("Accepted");
- switch(trust) {
- case TrustLevel.UNTRUSTED:
- trust_str = _("Rejected");
- break;
- case TrustLevel.VERIFIED:
- trust_str = _("Verified");
- break;
- }
-
- action_row.add_suffix(new Label(trust_str));
- add_key_row(action_row);
- }
- displayed_ids.add(device[plugin.db.identity_meta.device_id]);
- }
-
- private bool on_auto_accept_toggled(bool active) {
- plugin.trust_manager.set_blind_trust(account, jid, active);
-
- if (active) {
- int identity_id = plugin.db.identity.get_id(account.id);
- if (identity_id < 0) return false;
-
- foreach (Row device in plugin.db.identity_meta.get_new_devices(identity_id, jid.to_string())) {
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED);
- add_fingerprint(device, TrustLevel.TRUSTED);
- }
- }
- return false;
- }
-
- private bool on_omemo_by_default_toggled(bool active) {
- var encryption_value = active ? Encryption.OMEMO : Encryption.NONE;
- plugin.app.settings.set_default_encryption(account, encryption_value);
- return false;
- }
-
- private void update_stored_trust(int response, Row device) {
- switch (response) {
- case TrustLevel.TRUSTED:
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED);
- break;
- case TrustLevel.UNTRUSTED:
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.UNTRUSTED);
- break;
- case TrustLevel.VERIFIED:
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.VERIFIED);
- plugin.trust_manager.set_blind_trust(account, jid, false);
- automatically_accept_new_row.active = false;
- break;
- }
- }
-
- private void add_new_fingerprint(Row device) {
- Adw.ActionRow action_row = new Adw.ActionRow() { use_markup = true };
- action_row.title = _("New device");
- action_row.subtitle = fingerprint_markup(fingerprint_from_base64(device[plugin.db.identity_meta.identity_key_public_base64]));
-
- Button accept_button = new Button() { visible = true, valign = Align.CENTER, hexpand = true };
- accept_button.set_icon_name("dino-check-plain-symbolic"); // using .image = sets .image-button. Together with .suggested/destructive action that breaks the button Adwaita
- accept_button.add_css_class("suggested-action");
- accept_button.tooltip_text = _("Accept key");
-
- Button reject_button = new Button() { visible = true, valign = Align.CENTER, hexpand = true };
- reject_button.set_icon_name("action-unavailable-symbolic");
- reject_button.add_css_class("destructive-action");
- reject_button.tooltip_text = _("Reject key");
-
- accept_button.clicked.connect(() => {
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.TRUSTED);
- add_fingerprint(device, TrustLevel.TRUSTED);
- remove_key_row(action_row);
- });
-
- reject_button.clicked.connect(() => {
- plugin.trust_manager.set_device_trust(account, jid, device[plugin.db.identity_meta.device_id], TrustLevel.UNTRUSTED);
- add_fingerprint(device, TrustLevel.UNTRUSTED);
- remove_key_row(action_row);
- });
-
- Box control_box = new Box(Gtk.Orientation.HORIZONTAL, 0) { visible = true, hexpand = true };
- control_box.append(accept_button);
- control_box.append(reject_button);
- control_box.add_css_class("linked"); // .linked: Visually link the accept / reject buttons
-
- action_row.add_suffix(control_box);
-
- add_key_row(action_row);
- displayed_ids.add(device[plugin.db.identity_meta.device_id]);
- }
-
- private void add_key_row(Adw.PreferencesRow widget) {
- keys_preferences_group.add(widget);
- keys_preferences_group_children.add(widget);
- }
-
- private void remove_key_row(Adw.PreferencesRow widget) {
- keys_preferences_group.remove(widget);
- keys_preferences_group_children.remove(widget);
- }
-}
-} \ No newline at end of file
diff --git a/plugins/omemo/src/ui/manage_key_dialog.vala b/plugins/omemo/src/ui/manage_key_dialog.vala
deleted file mode 100644
index ac8896a5..00000000
--- a/plugins/omemo/src/ui/manage_key_dialog.vala
+++ /dev/null
@@ -1,177 +0,0 @@
-using Gtk;
-using Qlite;
-
-namespace Dino.Plugins.Omemo {
-
-[GtkTemplate (ui = "/im/dino/Dino/omemo/manage_key_dialog.ui")]
-public class ManageKeyDialog : Gtk.Dialog {
-
- [GtkChild] private unowned Stack manage_stack;
-
- [GtkChild] private unowned Button cancel_button;
- [GtkChild] private unowned Button ok_button;
-
- [GtkChild] private unowned Label main_desc_label;
- [GtkChild] private unowned ListBox main_action_list;
-
- [GtkChild] private unowned Image confirm_image;
- [GtkChild] private unowned Label confirm_title_label;
- [GtkChild] private unowned Label confirm_desc_label;
-
- [GtkChild] private unowned Label verify_label;
- [GtkChild] private unowned Label compare_fingerprint_label;
- [GtkChild] private unowned Button verify_yes_button;
- [GtkChild] private unowned Button verify_no_button;
-
- private Row device;
- private Database db;
-
- private bool return_to_main;
- private int current_response;
-
- construct {
- // If we set the strings in the .ui file, they don't get translated
- this.title = _("Manage Key");
- compare_fingerprint_label.label = _("Compare the fingerprint, character by character, with the one shown on your contact's device.");
- verify_no_button.label = _("Fingerprints differ");
- verify_yes_button.label = _("Fingerprints match");
- cancel_button.label = _("Cancel");
- ok_button.label = _("Confirm");
- }
-
- public ManageKeyDialog(Row device, Database db) {
- Object(use_header_bar : 1);
-
- this.device = device;
- this.db = db;
-
- setup_main_screen();
- setup_verify_screen();
-
- cancel_button.clicked.connect(handle_cancel);
- ok_button.clicked.connect(() => {
- response(current_response);
- close();
- });
-
- verify_yes_button.clicked.connect(() => {
- confirm_image.set_from_icon_name("security-high-symbolic");
- confirm_title_label.label = _("Verify key");
- confirm_desc_label.set_markup(_("Future messages sent by %s from the device that uses this key will be highlighted accordingly in the chat window.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- manage_stack.set_visible_child_name("confirm");
- ok_button.sensitive = true;
- return_to_main = false;
- current_response = TrustLevel.VERIFIED;
- });
-
- verify_no_button.clicked.connect(() => {
- return_to_main = false;
- confirm_image.set_from_icon_name("dino-dialog-warning-symbolic");
- confirm_title_label.label = _("Fingerprints do not match");
- confirm_desc_label.set_markup(_("Please verify that you are comparing the correct fingerprint. If fingerprints do not match, %s's account may be compromised and you should consider rejecting this key.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- manage_stack.set_visible_child_name("confirm");
- });
- }
-
- private void handle_cancel() {
- if (manage_stack.get_visible_child_name() == "main") close();
-
- if (manage_stack.get_visible_child_name() == "verify") {
- manage_stack.set_visible_child_name("main");
- cancel_button.label = _("Cancel");
- }
-
- if (manage_stack.get_visible_child_name() == "confirm") {
- if (return_to_main) {
- manage_stack.set_visible_child_name("main");
- cancel_button.label = _("Cancel");
- } else {
- manage_stack.set_visible_child_name("verify");
- }
- }
-
- ok_button.sensitive = false;
- }
-
- private Box make_action_box(string title, string desc){
- Box box = new Box(Orientation.VERTICAL, 0) { visible = true, margin_start = 20, margin_end = 20, margin_top = 14, margin_bottom = 14 };
- Label lbl_title = new Label(title) { visible = true, halign = Align.START };
- Label lbl_desc = new Label(desc) { visible = true, xalign = 0, wrap = true, max_width_chars = 40 };
-
- Pango.AttrList title_attrs = new Pango.AttrList();
- title_attrs.insert(Pango.attr_scale_new(1.1));
- lbl_title.attributes = title_attrs;
- Pango.AttrList desc_attrs = new Pango.AttrList();
- desc_attrs.insert(Pango.attr_scale_new(0.8));
- lbl_desc.attributes = desc_attrs;
- lbl_desc.add_css_class("dim-label");
-
- box.append(lbl_title);
- box.append(lbl_desc);
-
- return box;
- }
-
- private void setup_main_screen() {
- main_action_list.set_header_func((row, before_row) => {
- if (row.get_header() == null && before_row != null) {
- row.set_header(new Separator(Orientation.HORIZONTAL));
- }
- });
-
- ListBoxRow verify_row = new ListBoxRow() { visible = true };
- verify_row.set_child(make_action_box(_("Verify key fingerprint"), _("Compare this key's fingerprint with the fingerprint displayed on the contact's device.")));
- ListBoxRow reject_row = new ListBoxRow() { visible = true };
- reject_row.set_child(make_action_box(_("Reject key"), _("Block encrypted communication with the contact's device that uses this key.")));
- ListBoxRow accept_row = new ListBoxRow() {visible = true };
- accept_row.set_child(make_action_box(_("Accept key"), _("Allow encrypted communication with the contact's device that uses this key.")));
-
- switch((TrustLevel) device[db.identity_meta.trust_level]) {
- case TrustLevel.TRUSTED:
- main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#1A63D9'>"+_("accepted")+"</span>")+" "+_("This means it can be used by %s to receive and send encrypted messages.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- main_action_list.append(verify_row);
- main_action_list.append(reject_row);
- break;
- case TrustLevel.VERIFIED:
- main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#1A63D9'>"+_("verified")+"</span>")+" "+_("This means it can be used by %s to receive and send encrypted messages.").printf(@"<b>$(device[db.identity_meta.address_name])</b>") + " " + _("Additionally it has been verified to match the key on the contact's device."));
- main_action_list.append(reject_row);
- break;
- case TrustLevel.UNTRUSTED:
- main_desc_label.set_markup(_("This key is currently %s.").printf("<span color='#D91900'>"+_("rejected")+"</span>")+" "+_("This means it cannot be used by %s to decipher your messages, and you won't see messages encrypted with it.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- main_action_list.append(accept_row);
- break;
- }
-
- //Row clicked - go to appropriate screen
- main_action_list.row_activated.connect((row) => {
- if(row == verify_row) {
- manage_stack.set_visible_child_name("verify");
- } else if (row == reject_row) {
- confirm_image.set_from_icon_name("action-unavailable-symbolic");
- confirm_title_label.label = _("Reject key");
- confirm_desc_label.set_markup(_("You won't see encrypted messages from the device of %s that uses this key. Conversely, that device won't be able to decipher your messages anymore.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- manage_stack.set_visible_child_name("confirm");
- ok_button.sensitive = true;
- return_to_main = true;
- current_response = TrustLevel.UNTRUSTED;
- } else if (row == accept_row) {
- confirm_image.set_from_icon_name("dino-check-plain-symbolic");
- confirm_title_label.label = _("Accept key");
- confirm_desc_label.set_markup(_("You will be able to exchange encrypted messages with the device of %s that uses this key.").printf(@"<b>$(device[db.identity_meta.address_name])</b>"));
- manage_stack.set_visible_child_name("confirm");
- ok_button.sensitive = true;
- return_to_main = true;
- current_response = TrustLevel.TRUSTED;
- }
- cancel_button.label = _("Back");
- });
-
- manage_stack.set_visible_child_name("main");
- }
-
- private void setup_verify_screen() {
- verify_label.set_markup(fingerprint_markup(fingerprint_from_base64(device[db.identity_meta.identity_key_public_base64])));
- }
-}
-
-}
diff --git a/plugins/omemo/src/ui/own_notifications.vala b/plugins/omemo/src/ui/own_notifications.vala
deleted file mode 100644
index 7ff10e30..00000000
--- a/plugins/omemo/src/ui/own_notifications.vala
+++ /dev/null
@@ -1,35 +0,0 @@
-using Dino.Entities;
-using Xmpp;
-using Gtk;
-
-namespace Dino.Plugins.Omemo {
-
-public class OwnNotifications {
-
- private StreamInteractor stream_interactor;
- private Plugin plugin;
- private Account account;
-
- public OwnNotifications (Plugin plugin, StreamInteractor stream_interactor, Account account) {
- this.stream_interactor = (!)stream_interactor;
- this.plugin = plugin;
- this.account = account;
- stream_interactor.module_manager.get_module(account, StreamModule.IDENTITY).bundle_fetched.connect_after((jid, device_id, bundle) => {
- if (jid.equals(account.bare_jid) && plugin.has_new_devices(account, account.bare_jid)) {
- display_notification();
- }
- });
-
- if (plugin.has_new_devices(account, account.bare_jid)) {
- display_notification();
- }
- }
-
- private void display_notification() {
- Notification notification = new Notification(_("OMEMO trust decision required"));
- notification.set_default_action_and_target_value("app.own-keys", new Variant.int32(account.id));
- notification.set_body(_("Did you add a new device for account %s?").printf(@"$(account.bare_jid.to_string())"));
- plugin.app.send_notification(account.id.to_string()+"-new-device", notification);
- }
-}
-}
diff --git a/plugins/omemo/src/ui/util.vala b/plugins/omemo/src/ui/util.vala
deleted file mode 100644
index e250ff4d..00000000
--- a/plugins/omemo/src/ui/util.vala
+++ /dev/null
@@ -1,40 +0,0 @@
-using Xmpp.Util;
-
-namespace Dino.Plugins.Omemo {
-
-public static string fingerprint_from_base64(string b64) {
- uint8[] arr = Base64.decode(b64);
-
- arr = arr[1:arr.length];
- string s = "";
- foreach (uint8 i in arr) {
- string tmp = i.to_string("%x");
- if (tmp.length == 1) tmp = "0" + tmp;
- s = s + tmp;
- }
-
- return s;
-}
-
-public static string fingerprint_markup(string s) {
- return "<span font_family='monospace' font='9'>" + format_fingerprint(s) + "</span>";
-}
-
-public static string format_fingerprint(string s) {
- string markup = "";
- for (int i = 0; i < s.length; i += 4) {
- string four_chars = s.substring(i, 4).down();
-
- if (i % 32 == 0 && i != 0) markup += "\n";
- markup += four_chars;
- if (i % 16 == 12 && i % 32 != 28) {
- markup += " ";
- }
- if (i % 8 == 4 && i % 16 != 12) {
- markup += "\u00a0"; // Non-breaking space
- }
- }
- return markup;
-}
-
-}