From b013d28182ce582f229185c23b6011f566f1f8cc Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sat, 22 Aug 2026 18:53:02 +0200 Subject: meson: Strip unneeded C compiler warnings when processing vala code These warnings arecompiler annoyances where the vala compiler creates C code that is usually unexpected in proper C code and thus triggers warnings. --- plugins/ice/meson.build | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'plugins/ice') diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 48db71f5..1cec8b38 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -18,7 +18,7 @@ sources = files( 'src/util.vala', 'src/register_plugin.vala', ) -c_args = [ +c_args = vala_c_args + [ '-DG_LOG_DOMAIN="ice"', ] vala_args = [ -- cgit v1.3 From 76a91fca2fc7dd5975e8ff0e6695f27c98539dba Mon Sep 17 00:00:00 2001 From: hrxi Date: Fri, 24 Nov 2023 20:53:50 +0100 Subject: Add support for OpenSSL Uses work by @hrxi in https://github.com/dino/dino/pull/1515 Co-Authored-By: hrxi --- crypto-vala/meson.build | 15 +- crypto-vala/src/cipher.vala | 159 +--------- crypto-vala/src/cipher_converter.vala | 50 ++-- crypto-vala/src/cipher_gcrypt.vala | 137 +++++++++ crypto-vala/src/cipher_openssl.vala | 156 ++++++++++ crypto-vala/src/error.vala | 6 +- crypto-vala/src/gcrypt.vala | 21 ++ crypto-vala/src/openssl.vala | 19 ++ crypto-vala/src/random.vala | 5 - crypto-vala/vapi/openssl.vapi | 322 +++++++++++++++++++++ meson.build | 25 +- meson_options.txt | 1 + plugins/ice/meson.build | 15 +- plugins/ice/src/dtls_srtp.vala | 297 +++---------------- plugins/ice/src/dtls_srtp_gnutls.vala | 245 ++++++++++++++++ plugins/ice/src/dtls_srtp_openssl.vala | 202 +++++++++++++ plugins/ice/src/module.vala | 2 +- plugins/ice/src/openssl_utils.c | 49 ++++ plugins/ice/src/openssl_utils.h | 8 + plugins/ice/vapi/openssl.vapi | 218 ++++++++++++++ plugins/omemo/meson.build | 8 +- .../omemo/src/file_transfer/file_decryptor.vala | 2 +- .../omemo/src/file_transfer/file_encryptor.vala | 6 +- plugins/omemo/src/jingle/jet_omemo.vala | 8 +- plugins/omemo/src/logic/encrypt.vala | 6 +- plugins/omemo/src/native/context.vala | 6 +- plugins/omemo/src/native/helper.c | 265 ----------------- plugins/omemo/src/native/helper.h | 1 - plugins/omemo/src/native/helper_gcrypt.c | 257 ++++++++++++++++ plugins/omemo/src/native/helper_openssl.c | 313 ++++++++++++++++++++ plugins/omemo/src/native/store.vala | 2 +- plugins/omemo/vapi/libomemo-c.vapi | 2 - plugins/omemo/vapi/openssl.vapi | 0 33 files changed, 2099 insertions(+), 729 deletions(-) create mode 100644 crypto-vala/src/cipher_gcrypt.vala create mode 100644 crypto-vala/src/cipher_openssl.vala create mode 100644 crypto-vala/src/gcrypt.vala create mode 100644 crypto-vala/src/openssl.vala delete mode 100644 crypto-vala/src/random.vala create mode 100644 crypto-vala/vapi/openssl.vapi create mode 100644 plugins/ice/src/dtls_srtp_gnutls.vala create mode 100644 plugins/ice/src/dtls_srtp_openssl.vala create mode 100644 plugins/ice/src/openssl_utils.c create mode 100644 plugins/ice/src/openssl_utils.h create mode 100644 plugins/ice/vapi/openssl.vapi create mode 100644 plugins/omemo/src/native/helper_gcrypt.c create mode 100644 plugins/omemo/src/native/helper_openssl.c create mode 100644 plugins/omemo/vapi/openssl.vapi (limited to 'plugins/ice') diff --git a/crypto-vala/meson.build b/crypto-vala/meson.build index fdd08f87..bc66fbf9 100644 --- a/crypto-vala/meson.build +++ b/crypto-vala/meson.build @@ -1,14 +1,12 @@ dependencies = [ dep_gio, dep_glib, - dep_libgcrypt, dep_libsrtp2, ] sources = files( 'src/cipher.vala', 'src/cipher_converter.vala', 'src/error.vala', - 'src/random.vala', 'src/srtp.vala', ) c_args = vala_c_args + [ @@ -17,6 +15,19 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] +if crypto_backend == 'gnutls' + dependencies += [ dep_libgcrypt ] + sources += files( + 'src/gcrypt.vala', + 'src/cipher_gcrypt.vala', + ) +else # openssl + dependencies += [ dep_openssl ] + sources += files( + 'src/openssl.vala', + 'src/cipher_openssl.vala', + ) +endif lib_crypto_vala = library('crypto-vala', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, version: '0.0', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) dep_crypto_vala = declare_dependency(link_with: lib_crypto_vala, include_directories: include_directories('.')) diff --git a/crypto-vala/src/cipher.vala b/crypto-vala/src/cipher.vala index 306dafa8..f7aee100 100644 --- a/crypto-vala/src/cipher.vala +++ b/crypto-vala/src/cipher.vala @@ -1,152 +1,19 @@ namespace Crypto { -public class SymmetricCipher { - private GCrypt.Cipher.Cipher cipher; - public static bool supports(string algo_name) { - GCrypt.Cipher.Algorithm algo; - GCrypt.Cipher.Mode mode; - GCrypt.Cipher.Flag flags; - return parse(algo_name, out algo, out mode, out flags); - } - - private static unowned string mode_to_string(GCrypt.Cipher.Mode mode) { - switch (mode) { - case GCrypt.Cipher.Mode.ECB: return "ECB"; - case GCrypt.Cipher.Mode.CFB: return "CFB"; - case GCrypt.Cipher.Mode.CBC: return "CBC"; - case GCrypt.Cipher.Mode.STREAM: return "STREAM"; - case GCrypt.Cipher.Mode.OFB: return "OFB"; - case GCrypt.Cipher.Mode.CTR: return "CTR"; - case GCrypt.Cipher.Mode.AESWRAP: return "AESWRAP"; - case GCrypt.Cipher.Mode.GCM: return "GCM"; - case GCrypt.Cipher.Mode.POLY1305: return "POLY1305"; - case GCrypt.Cipher.Mode.OCB: return "OCB"; - case GCrypt.Cipher.Mode.CFB8: return "CFB8"; - // case GCrypt.Cipher.Mode.XTS: return "XTS"; // Not supported in gcrypt < 1.8 - } - return "NONE"; - } - - private static GCrypt.Cipher.Mode mode_from_string(string name) { - switch (name) { - case "ECB": return GCrypt.Cipher.Mode.ECB; - case "CFB": return GCrypt.Cipher.Mode.CFB; - case "CBC": return GCrypt.Cipher.Mode.CBC; - case "STREAM": return GCrypt.Cipher.Mode.STREAM; - case "OFB": return GCrypt.Cipher.Mode.OFB; - case "CTR": return GCrypt.Cipher.Mode.CTR; - case "AESWRAP": return GCrypt.Cipher.Mode.AESWRAP; - case "GCM": return GCrypt.Cipher.Mode.GCM; - case "POLY1305": return GCrypt.Cipher.Mode.POLY1305; - case "OCB": return GCrypt.Cipher.Mode.OCB; - case "CFB8": return GCrypt.Cipher.Mode.CFB8; - // case "XTS": return GCrypt.Cipher.Mode.XTS; // Not supported in gcrypt < 1.8 - } - return GCrypt.Cipher.Mode.NONE; - } - - private static string flags_to_string(GCrypt.Cipher.Flag flags) { - string? s = null; - if ((GCrypt.Cipher.Flag.CBC_MAC & flags) != 0) s = (s == null ? "" : @"$s-") + "MAC"; - if ((GCrypt.Cipher.Flag.CBC_CTS & flags) != 0) s = (s == null ? "" : @"$s-") + "CTS"; - if ((GCrypt.Cipher.Flag.ENABLE_SYNC & flags) != 0) s = (s == null ? "" : @"$s-") + "SYNC"; - if ((GCrypt.Cipher.Flag.SECURE & flags) != 0) s = (s == null ? "" : @"$s-") + "SECURE"; - return s ?? "NONE"; - } - - private static GCrypt.Cipher.Flag flag_from_string(string flag_name) { - if (flag_name == "SECURE") return GCrypt.Cipher.Flag.SECURE; - if (flag_name == "SYNC") return GCrypt.Cipher.Flag.ENABLE_SYNC; - if (flag_name == "CTS") return GCrypt.Cipher.Flag.CBC_CTS; - if (flag_name == "MAC") return GCrypt.Cipher.Flag.CBC_MAC; - return 0; - } - - private static GCrypt.Cipher.Flag flags_from_string(string flag_names) { - GCrypt.Cipher.Flag flags = 0; - foreach(string flag in flag_names.split("-")) { - flags |= flag_from_string(flag); - } - return flags; - } - - private static bool parse(string algo_name, out GCrypt.Cipher.Algorithm algo, out GCrypt.Cipher.Mode mode, out GCrypt.Cipher.Flag flags) { - algo = GCrypt.Cipher.Algorithm.NONE; - mode = GCrypt.Cipher.Mode.NONE; - flags = 0; - string[] algo_parts = algo_name.split("-", 3); - - algo = GCrypt.Cipher.Algorithm.from_string(algo_parts[0]); - if (algo_parts.length >= 2) { - mode = mode_from_string(algo_parts[1]); - } - if (algo_parts.length == 3) { - flags |= flags_from_string(algo_parts[2]); - } - return to_algo_name(algo, mode, flags) == algo_name; - } - - private static string to_algo_name(GCrypt.Cipher.Algorithm algo = GCrypt.Cipher.Algorithm.NONE, GCrypt.Cipher.Mode mode = GCrypt.Cipher.Mode.NONE, GCrypt.Cipher.Flag flags = 0) { - if (flags != 0) { - return @"$algo-$(mode_to_string(mode))-$(flags_to_string(flags))"; - } else if (mode != GCrypt.Cipher.Mode.NONE) { - return @"$algo-$(mode_to_string(mode))"; - } else { - return algo.to_string(); - } - } - - public SymmetricCipher(string algo_name) throws Error { - GCrypt.Cipher.Algorithm algo; - GCrypt.Cipher.Mode mode; - GCrypt.Cipher.Flag flags; - if (parse(algo_name, out algo, out mode, out flags)) { - this.gcrypt(algo, mode, flags); - } else { - throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); - } - } - - private SymmetricCipher.gcrypt(GCrypt.Cipher.Algorithm algo, GCrypt.Cipher.Mode mode, GCrypt.Cipher.Flag flags) throws Error { - may_throw_gcrypt_error(GCrypt.Cipher.Cipher.open(out this.cipher, algo, mode, flags)); - } - - public void set_key(uint8[] key) throws Error { - may_throw_gcrypt_error(cipher.set_key(key)); - } - - public void set_iv(uint8[] iv) throws Error { - may_throw_gcrypt_error(cipher.set_iv(iv)); - } - - public void set_counter_vector(uint8[] ctr) throws Error { - may_throw_gcrypt_error(cipher.set_counter_vector(ctr)); - } - - public void reset() throws Error { - may_throw_gcrypt_error(cipher.reset()); - } - - public uint8[] get_tag(size_t taglen) throws Error { - uint8[] tag = new uint8[taglen]; - may_throw_gcrypt_error(cipher.get_tag(tag)); - return tag; - } - - public void check_tag(uint8[] tag) throws Error { - may_throw_gcrypt_error(cipher.check_tag(tag)); - } - - public void encrypt(uint8[] output, uint8[] input) throws Error { - may_throw_gcrypt_error(cipher.encrypt(output, input)); - } +public interface SymmetricCipher { + public abstract void set_key(uint8[] key) throws Error; + public abstract void set_iv(uint8[] iv) throws Error; + public abstract void reset() throws Error; +} - public void decrypt(uint8[] output, uint8[] input) throws Error { - may_throw_gcrypt_error(cipher.decrypt(output, input)); - } +public interface SymmetricCipherEncryption : SymmetricCipher, Object { + public abstract int encrypt(uint8[] output, uint8[] input) throws Error; + public abstract uint8[] get_tag(size_t taglen) throws Error; +} - public void sync() throws Error { - may_throw_gcrypt_error(cipher.sync()); - } +public interface SymmetricCipherDecryption : SymmetricCipher, Object { + public abstract int decrypt(uint8[] output, uint8[] input) throws Error; + public abstract void check_tag(uint8[] tag) throws Error; } + } diff --git a/crypto-vala/src/cipher_converter.vala b/crypto-vala/src/cipher_converter.vala index 5fb1f548..49e7af71 100644 --- a/crypto-vala/src/cipher_converter.vala +++ b/crypto-vala/src/cipher_converter.vala @@ -1,18 +1,14 @@ using GLib; namespace Crypto { -public abstract class SymmetricCipherConverter : Converter, Object { - internal SymmetricCipher cipher; - internal size_t attached_taglen; - public abstract ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError; +public class SymmetricCipherEncrypter : Converter, Object { + private SymmetricCipherEncryption cipher; + private size_t attached_taglen; - public uint8[] get_tag(size_t taglen) throws Error { - return cipher.get_tag(taglen); - } - - public void check_tag(uint8[] tag) throws Error { - cipher.check_tag(tag); + public SymmetricCipherEncrypter(owned SymmetricCipherEncryption cipher, size_t attached_taglen = 0) { + this.cipher = (owned) cipher; + this.attached_taglen = attached_taglen; } public void reset() { @@ -22,15 +18,12 @@ public abstract class SymmetricCipherConverter : Converter, Object { warning(@"$(e.domain) error while resetting cipher: $(e.message)"); } } -} -public class SymmetricCipherEncrypter : SymmetricCipherConverter { - public SymmetricCipherEncrypter(owned SymmetricCipher cipher, size_t attached_taglen = 0) { - this.cipher = (owned) cipher; - this.attached_taglen = attached_taglen; + public uint8[] get_tag(size_t taglen) throws Error { + return ((SymmetricCipherEncryption)cipher).get_tag(taglen); } - public override ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { + public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { if (inbuf.length > outbuf.length) { throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); } @@ -39,7 +32,7 @@ public class SymmetricCipherEncrypter : SymmetricCipherConverter { } try { if (inbuf.length > 0) { - cipher.encrypt(outbuf, inbuf); + ((SymmetricCipherEncryption)cipher).encrypt(outbuf, inbuf); } bytes_read = inbuf.length; bytes_written = inbuf.length; @@ -60,13 +53,28 @@ public class SymmetricCipherEncrypter : SymmetricCipherConverter { } } -public class SymmetricCipherDecrypter : SymmetricCipherConverter { - public SymmetricCipherDecrypter(owned SymmetricCipher cipher, size_t attached_taglen = 0) { +public class SymmetricCipherDecrypter : Converter, Object { + private SymmetricCipherDecryption cipher; + private size_t attached_taglen; + + public SymmetricCipherDecrypter(owned SymmetricCipherDecryption cipher, size_t attached_taglen = 0) { this.cipher = (owned) cipher; this.attached_taglen = attached_taglen; } - public override ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { + public void reset() { + try { + cipher.reset(); + } catch (Crypto.Error e) { + warning(@"$(e.domain) error while resetting cipher: $(e.message)"); + } + } + + public void check_tag(uint8[] tag) throws Error { + ((SymmetricCipherDecryption)cipher).check_tag(tag); + } + + public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { if (inbuf.length > outbuf.length + attached_taglen) { throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); } @@ -78,7 +86,7 @@ public class SymmetricCipherDecrypter : SymmetricCipherConverter { try { inbuf.length -= (int) attached_taglen; if (inbuf.length > 0) { - cipher.decrypt(outbuf, inbuf); + ((SymmetricCipherDecryption)cipher).decrypt(outbuf, inbuf); } bytes_read = inbuf.length; bytes_written = inbuf.length; diff --git a/crypto-vala/src/cipher_gcrypt.vala b/crypto-vala/src/cipher_gcrypt.vala new file mode 100644 index 00000000..3e811d29 --- /dev/null +++ b/crypto-vala/src/cipher_gcrypt.vala @@ -0,0 +1,137 @@ +namespace Crypto { + +internal class SymmetricCipherGcrypt : SymmetricCipher, SymmetricCipherEncryption, SymmetricCipherDecryption, Object { + private GCrypt.Cipher.Cipher cipher; + + private static unowned string mode_to_string(GCrypt.Cipher.Mode mode) { + switch (mode) { + case GCrypt.Cipher.Mode.ECB: return "ECB"; + case GCrypt.Cipher.Mode.CFB: return "CFB"; + case GCrypt.Cipher.Mode.CBC: return "CBC"; + case GCrypt.Cipher.Mode.STREAM: return "STREAM"; + case GCrypt.Cipher.Mode.OFB: return "OFB"; + case GCrypt.Cipher.Mode.CTR: return "CTR"; + case GCrypt.Cipher.Mode.AESWRAP: return "AESWRAP"; + case GCrypt.Cipher.Mode.GCM: return "GCM"; + case GCrypt.Cipher.Mode.POLY1305: return "POLY1305"; + case GCrypt.Cipher.Mode.OCB: return "OCB"; + case GCrypt.Cipher.Mode.CFB8: return "CFB8"; + // case GCrypt.Cipher.Mode.XTS: return "XTS"; // Not supported in gcrypt < 1.8 + } + return "NONE"; + } + + private static GCrypt.Cipher.Mode mode_from_string(string name) { + switch (name) { + case "ECB": return GCrypt.Cipher.Mode.ECB; + case "CFB": return GCrypt.Cipher.Mode.CFB; + case "CBC": return GCrypt.Cipher.Mode.CBC; + case "STREAM": return GCrypt.Cipher.Mode.STREAM; + case "OFB": return GCrypt.Cipher.Mode.OFB; + case "CTR": return GCrypt.Cipher.Mode.CTR; + case "AESWRAP": return GCrypt.Cipher.Mode.AESWRAP; + case "GCM": return GCrypt.Cipher.Mode.GCM; + case "POLY1305": return GCrypt.Cipher.Mode.POLY1305; + case "OCB": return GCrypt.Cipher.Mode.OCB; + case "CFB8": return GCrypt.Cipher.Mode.CFB8; + // case "XTS": return GCrypt.Cipher.Mode.XTS; // Not supported in gcrypt < 1.8 + } + return GCrypt.Cipher.Mode.NONE; + } + + private static string flags_to_string(GCrypt.Cipher.Flag flags) { + string? s = null; + if ((GCrypt.Cipher.Flag.CBC_MAC & flags) != 0) s = (s == null ? "" : @"$s-") + "MAC"; + if ((GCrypt.Cipher.Flag.CBC_CTS & flags) != 0) s = (s == null ? "" : @"$s-") + "CTS"; + if ((GCrypt.Cipher.Flag.ENABLE_SYNC & flags) != 0) s = (s == null ? "" : @"$s-") + "SYNC"; + if ((GCrypt.Cipher.Flag.SECURE & flags) != 0) s = (s == null ? "" : @"$s-") + "SECURE"; + return s ?? "NONE"; + } + + private static GCrypt.Cipher.Flag flag_from_string(string flag_name) { + if (flag_name == "SECURE") return GCrypt.Cipher.Flag.SECURE; + if (flag_name == "SYNC") return GCrypt.Cipher.Flag.ENABLE_SYNC; + if (flag_name == "CTS") return GCrypt.Cipher.Flag.CBC_CTS; + if (flag_name == "MAC") return GCrypt.Cipher.Flag.CBC_MAC; + return 0; + } + + private static GCrypt.Cipher.Flag flags_from_string(string flag_names) { + GCrypt.Cipher.Flag flags = 0; + foreach(string flag in flag_names.split("-")) { + flags |= flag_from_string(flag); + } + return flags; + } + + private static bool parse(string algo_name, out GCrypt.Cipher.Algorithm algo, out GCrypt.Cipher.Mode mode, out GCrypt.Cipher.Flag flags) { + algo = GCrypt.Cipher.Algorithm.NONE; + mode = GCrypt.Cipher.Mode.NONE; + flags = 0; + string[] algo_parts = algo_name.split("-", 3); + + algo = GCrypt.Cipher.Algorithm.from_string(algo_parts[0]); + if (algo_parts.length >= 2) { + mode = mode_from_string(algo_parts[1]); + } + if (algo_parts.length == 3) { + flags |= flags_from_string(algo_parts[2]); + } + return to_algo_name(algo, mode, flags) == algo_name; + } + + private static string to_algo_name(GCrypt.Cipher.Algorithm algo = GCrypt.Cipher.Algorithm.NONE, GCrypt.Cipher.Mode mode = GCrypt.Cipher.Mode.NONE, GCrypt.Cipher.Flag flags = 0) { + if (flags != 0) { + return @"$algo-$(mode_to_string(mode))-$(flags_to_string(flags))"; + } else if (mode != GCrypt.Cipher.Mode.NONE) { + return @"$algo-$(mode_to_string(mode))"; + } else { + return algo.to_string(); + } + } + + public SymmetricCipherGcrypt(string algo_name) throws Error { + GCrypt.Cipher.Algorithm algo; + GCrypt.Cipher.Mode mode; + GCrypt.Cipher.Flag flags; + if (parse(algo_name, out algo, out mode, out flags)) { + may_throw_gcrypt_error(GCrypt.Cipher.Cipher.open(out this.cipher, algo, mode, flags)); + } else { + throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + } + } + + public void set_key(uint8[] key) throws Error { + may_throw_gcrypt_error(cipher.set_key(key)); + } + + public void set_iv(uint8[] iv) throws Error { + may_throw_gcrypt_error(cipher.set_iv(iv)); + } + + public void reset() throws Error { + may_throw_gcrypt_error(cipher.reset()); + } + + public uint8[] get_tag(size_t taglen) throws Error { + uint8[] tag = new uint8[taglen]; + may_throw_gcrypt_error(cipher.get_tag(tag)); + return tag; + } + + public void check_tag(uint8[] tag) throws Error { + may_throw_gcrypt_error(cipher.check_tag(tag)); + } + + public int encrypt(uint8[] output, uint8[] input) throws Error { + may_throw_gcrypt_error(cipher.encrypt(output, input)); + return input.length; + } + + public int decrypt(uint8[] output, uint8[] input) throws Error { + may_throw_gcrypt_error(cipher.decrypt(output, input)); + return input.length; + } +} + +} diff --git a/crypto-vala/src/cipher_openssl.vala b/crypto-vala/src/cipher_openssl.vala new file mode 100644 index 00000000..75a0ef9a --- /dev/null +++ b/crypto-vala/src/cipher_openssl.vala @@ -0,0 +1,156 @@ +namespace Crypto { + +internal class SymmetricCipherEncryptionOpenssl : SymmetricCipher, SymmetricCipherEncryption, Object { + private OpenSSL.EVP.CipherContext? cipher; + private bool is_finalized = false; + + public SymmetricCipherEncryptionOpenssl(string algo_name) throws Error { + if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + cipher = new OpenSSL.EVP.CipherContext(); + } + + public void set_key(uint8[] key) throws Error { + unowned OpenSSL.EVP.Cipher algo; + if (key.length == 16) { + algo = OpenSSL.EVP.aes_128_gcm(); + } else if (key.length == 32) { + algo = OpenSSL.EVP.aes_256_gcm(); + } else { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); + } + try { + cipher.encrypt_init(algo, null, null); + cipher.encrypt_init(null, key, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_iv(uint8[] iv) throws Error { + if (iv.length != 12) { + cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); + } + try { + cipher.encrypt_init(null, null, iv); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void reset() throws Error { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); + } + + public uint8[] get_tag(size_t taglen) throws Error { + uint8[] tag = new uint8[taglen]; + if (!is_finalized) { + uint8[] empty = new uint8[0]; + int empty_len = 0; + try { + cipher.encrypt_final(empty, out empty_len); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + if (empty_len != 0) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("get_tag called on a stream with remaining data"); + } + } + if (cipher.ctrl(OpenSSL.EVP.Control.GCM_GET_TAG, (int)taglen, tag) != 1) { + openssl_error(); + } + return tag; + } + + public int encrypt(uint8[] output, uint8[] input) throws Error { + int output_length = output.length; + if (is_finalized) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("encrypt called after get_tag"); + } + try { + cipher.encrypt_update(output, out output_length, input); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + return output_length; + } +} + +internal class SymmetricCipherDecryptionOpenssl : SymmetricCipher, SymmetricCipherDecryption, Object { + private OpenSSL.EVP.CipherContext? cipher; + private bool is_finalized = false; + + public SymmetricCipherDecryptionOpenssl(string algo_name) throws Error { + if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + cipher = new OpenSSL.EVP.CipherContext(); + try { + cipher.decrypt_init(OpenSSL.EVP.aes_128_gcm(), null, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_key(uint8[] key) throws Error { + unowned OpenSSL.EVP.Cipher algo; + if (key.length == 16) { + algo = OpenSSL.EVP.aes_128_gcm(); + } else if (key.length == 32) { + algo = OpenSSL.EVP.aes_256_gcm(); + } else { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); + } + try { + cipher.decrypt_init(algo, null, null); + cipher.decrypt_init(null, key, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_iv(uint8[] iv) throws Error { + if (iv.length != 12) { + cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); + } + try { + cipher.decrypt_init(null, null, iv); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void reset() throws Error { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); + } + + public void check_tag(uint8[] tag) throws Error { + if (cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_TAG, tag.length, tag) != 1) { + openssl_error(); + } + if (!is_finalized) { + uint8[] empty = new uint8[0]; + int empty_len = 0; + try { + cipher.decrypt_final(empty, out empty_len); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + if (empty_len != 0) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("check_tag called on a stream with remaining data"); + } + } + } + + public int decrypt(uint8[] output, uint8[] input) throws Error { + if (is_finalized) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("decrypt called after check_tag"); + } + int output_length = output.length; + try { + cipher.decrypt_update(output, out output_length, input); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + return output_length; + } +} + +} diff --git a/crypto-vala/src/error.vala b/crypto-vala/src/error.vala index 5007d725..a26f39c3 100644 --- a/crypto-vala/src/error.vala +++ b/crypto-vala/src/error.vala @@ -3,13 +3,9 @@ namespace Crypto { public errordomain Error { ILLEGAL_ARGUMENTS, GCRYPT, + OPENSSL, AUTHENTICATION_FAILED, UNKNOWN } -internal void may_throw_gcrypt_error(GCrypt.Error e) throws Error { - if (((int)e) != 0) { - throw new Crypto.Error.GCRYPT(e.to_string()); - } } -} \ No newline at end of file diff --git a/crypto-vala/src/gcrypt.vala b/crypto-vala/src/gcrypt.vala new file mode 100644 index 00000000..1997a5e1 --- /dev/null +++ b/crypto-vala/src/gcrypt.vala @@ -0,0 +1,21 @@ +namespace Crypto { + +public static void randomize(uint8[] buffer) { + GCrypt.Random.randomize(buffer); +} + +internal void may_throw_gcrypt_error(GCrypt.Error e) throws Error { + if (((int)e) != 0) { + throw new Crypto.Error.GCRYPT(e.to_string()); + } +} + +public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { + return new SymmetricCipherGcrypt(algo_name); +} + +public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { + return new SymmetricCipherGcrypt(algo_name); +} + +} diff --git a/crypto-vala/src/openssl.vala b/crypto-vala/src/openssl.vala new file mode 100644 index 00000000..4a288467 --- /dev/null +++ b/crypto-vala/src/openssl.vala @@ -0,0 +1,19 @@ +namespace Crypto { + +public static void randomize(uint8[] buffer) { + OpenSSL.RAND.bytes(buffer); +} + +internal void openssl_error() throws Error { + throw new Crypto.Error.OPENSSL(OpenSSL.ERR.reason_error_string(OpenSSL.ERR.get_error())); +} + +public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { + return new SymmetricCipherEncryptionOpenssl(algo_name); +} + +public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { + return new SymmetricCipherDecryptionOpenssl(algo_name); +} + +} diff --git a/crypto-vala/src/random.vala b/crypto-vala/src/random.vala deleted file mode 100644 index 3f5d3ba9..00000000 --- a/crypto-vala/src/random.vala +++ /dev/null @@ -1,5 +0,0 @@ -namespace Crypto { -public static void randomize(uint8[] buffer) { - GCrypt.Random.randomize(buffer); -} -} \ No newline at end of file diff --git a/crypto-vala/vapi/openssl.vapi b/crypto-vala/vapi/openssl.vapi new file mode 100644 index 00000000..87693d37 --- /dev/null +++ b/crypto-vala/vapi/openssl.vapi @@ -0,0 +1,322 @@ +[CCode (cprefix = "")] +namespace OpenSSL { + [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")] + namespace ASN1 { + [Compact] + [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")] + public class Integer { + public bool @set (long v); + } + + [Compact] + [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")] + public class Time { + public bool @set (time_t t); + } + } + [Compact] + [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)] + public class BIO { + [Compact] + [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)] + public class Method { + public Method (Type type, string name); + [CCode (has_target = false)] + public delegate int WriteFunc (BIO bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf); + [CCode (has_target = false)] + public delegate int ReadFunc (BIO bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf); + [CCode (has_target = false, simple_generics = true)] + public delegate long CtrlFunc (BIO bio, ControlCommand cmd, long num, void* ptr); + public WriteFunc write { get; set; } + public ReadFunc read { get; set; } + public CtrlFunc ctrl { get; set; } + } + + [Flags] + [CCode (cname = "int")] + public enum Type { + SOURCE_SINK, + DGRAM, + } + + [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)] + public enum ControlCommand { + RESET, + EOF, + SET, + GET, + PUSH, + POP, + GET_CLOSE, + SET_CLOSE, + PENDING, + FLUSH, + DUP, + WPENDING, + + DGRAM_QUERY_MTU, + DGRAM_GET_MTU, + DGRAM_SET_MTU, + DGRAM_SET_PEER, + DGRAM_SET_NEXT_TIMEOUT, + DGRAM_GET_PEER, + DGRAM_GET_FALLBACK_MTU, + DGRAM_SET_DONT_FRAG, + DGRAM_GET_MTU_OVERHEAD, + } + + public BIO (Method type); + public T data { get; set; } + + public void clear_retry_flags (); + public void set_retry_read (); + public bool should_read (); + } + + [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")] + namespace ERR { + public ulong get_error (); + public unowned string lib_error_string (ulong error); + public unowned string reason_error_string (ulong error); + } + + [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")] + namespace EVP { + [Compact] + [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] + public class Key { + public Key (); + [CCode (cheader_filename = "openssl_utils.h")] + public Key.generate_ecdsa (string curve); + } + [Compact] + [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")] + public class MessageDigest { + } + + [Compact] + [CCode (cname = "EVP_CIPHER", lower_case_cprefix = "EVP_CIPHER_", cprefix = "EVP_CIPHER_", ref_function = "EVP_CIPHER_up_ref", ref_function_void = true, unref_function = "EVP_CIPHER_free")] + public class Cipher { + + } + + [Compact] + [CCode (cname = "EVP_CIPHER_CTX", lower_case_cprefix = "EVP_CIPHER_CTX_", cprefix = "EVP_CIPHER_CTX_", free_function = "EVP_CIPHER_CTX_free")] + public class CipherContext { + public CipherContext (); + + [CCode (simple_generics = true)] + public int ctrl(Control cmd, int p1, T? p2); + + [CCode (cname = "EVP_EncryptInit")] + private int encrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); + public void encrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { + throw_if_error (encrypt_init_ (cipher, key, iv)); + } + [CCode (cname = "EVP_EncryptUpdate")] + private int encrypt_update_ ([CCode (array_length = false)] uint8[] out, out int out_len, uint8[] in); + public void encrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { + throw_if_error (encrypt_update_ (@out, out out_len, in)); + } + [CCode (cname = "EVP_EncryptFinal")] + private int encrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); + public void encrypt_final (uint8[] out, out int out_len) throws GLib.Error { + throw_if_error (encrypt_final_ (@out, out out_len)); + } + + [CCode (cname = "EVP_DecryptInit")] + private int decrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); + public void decrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { + throw_if_error (decrypt_init_ (cipher, key, iv)); + } + [CCode (cname = "EVP_DecryptUpdate")] + private int decrypt_update_ ([CCode (array_length = false)] uchar[] out, out int out_len, uint8[] in); + public void decrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { + throw_if_error (decrypt_update_ (@out, out out_len, in)); + } + [CCode (cname = "EVP_DecryptFinal")] + private int decrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); + public void decrypt_final (uint8[] out, out int out_len) throws GLib.Error { + throw_if_error (decrypt_final_ (@out, out out_len)); + } + + public int reset(); + public int set_key_length (int keylen); + public int set_padding (int pad); + } + + [CCode (cname = "int", cprefix = "EVP_CTRL_", has_type_id = false)] + public enum Control { + INIT, + SET_KEY_LENGTH, + GET_RC2_KEY_BITS, + SET_RC2_KEY_BITS, + GET_RC5_ROUNDS, + SET_RC5_ROUNDS, + RAND_KEY, + PBE_PRF_NID, + COPY, + AEAD_SET_IVLEN, + AEAD_GET_TAG, + AEAD_SET_TAG, + AEAD_SET_IV_FIXED, + GCM_SET_IVLEN, + GCM_GET_TAG, + GCM_SET_TAG, + GCM_SET_IV_FIXED, + GCM_IV_GEN, + CCM_SET_IVLEN, + CCM_GET_TAG, + CCM_SET_TAG, + CCM_SET_IV_FIXED, + CCM_SET_L, + CCM_SET_MSGLEN, + AEAD_TLS1_AAD, + AEAD_SET_MAC_KEY, + GCM_SET_IV_INV, + TLS1_1_MULTIBLOCK_AAD, + TLS1_1_MULTIBLOCK_ENCRYPT, + TLS1_1_MULTIBLOCK_DECRYPT, + TLS1_1_MULTIBLOCK_MAX_BUFSIZE, + SSL3_MASTER_SECRET, + SET_SBOX, + SBOX_USED, + KEY_MESH, + BLOCK_PADDING_MODE, + SET_PIPELINE_OUTPUT_BUFS, + SET_PIPELINE_INPUT_BUFS, + SET_PIPELINE_INPUT_LENS, + GET_IVLEN, + } + + public static unowned Cipher? aes_128_gcm (); + public static unowned Cipher? aes_256_gcm (); + + public static unowned MessageDigest sha256 (); + } + + [CCode (lower_case_cprefix = "RAND_", cprefix = "RAND_", cheader_filename = "openssl/rand.h")] + namespace RAND { + public static int bytes (uint8[] buf); + public static int priv_bytes (uint8[] buf); + } + + [Compact] + [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")] + class SSL { + [Compact] + [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")] + public class Context { + public Context (Method method); + public int set_tlsext_use_srtp (string profiles); + public int use_certificate (X509.Certificate certificate); + [CCode (cname = "SSL_CTX_use_PrivateKey")] + public int use_private_key (EVP.Key private_key); + } + + [CCode (cname = "const SSL_METHOD*")] + public enum Method { + [CCode (cname = "DTLS_client_method()")] + DTLS_CLIENT, + [CCode (cname = "DTLS_server_method()")] + DTLS_SERVER, + } + + [CCode (cname = "int", has_type_id = false)] + public enum Error { + NONE, + ZERO_RETURN, + WANT_READ, + WANT_WRITE, + WANT_CONNECT, + WANT_ACCEPT, + WANT_X509_LOOKUP, + WANT_ASYNC, + WANT_ASYNC_JOB, + WANT_CLIENT_HELLO_CB, + SYSCALL, + SSL + } + + public SSL (Context context); + public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; } + public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; } + + [CCode (cname = "SSL_do_handshake")] + private int do_handshake_ (); + [CCode (cname = "SSL_do_handshake_")] + public Error do_handshake () throws GLib.Error { + int ret = throw_if_error (do_handshake_ ()); + return get_error (ret); + } + [CCode (cname = "SSL_export_keying_material")] + private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context); + [CCode (cname = "SSL_export_keying_material_")] + public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error { + throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null)); + } + public Error get_error (int ret); + public void set_accept_state (); + public void set_connect_state (); + public int want (); + } + + [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")] + namespace X509 { + [Compact] + [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")] + public class Certificate { + public Certificate (); + public ASN1.Time not_before { + [CCode (cname = "X509_get_notBefore")] + get; + [CCode (cname = "X509_set_notBefore")] + set; + } + public ASN1.Time not_after { + [CCode (cname = "X509_get_notAfter")] + get; + [CCode (cname = "X509_set_notAfter")] + set; + } + public ASN1.Integer serial_number { + [CCode (cname = "X509_get_serialNumber")] + get; + [CCode (cname = "X509_set_serialNumber")] + set; + } + [CCode (cname = "X509_digest")] + private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len); + [CCode (cname = "X509_digest_")] + public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error { + uint8[] buf = new uint8[buf_len]; + uint buf_out_size = (uint) buf_len; + throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size)); + + uint8[] ret = new uint8[buf_out_size]; + for (int i = 0; i < buf_out_size; i++) { + ret[i] = buf[i]; + } + return ret; + } + [CCode (cname = "X509_set_pubkey")] + public int set_public_key (EVP.Key public_key); + public int set_version (long version); + [CCode (cname = "X509_sign")] + private int sign_ (EVP.Key private_key, EVP.MessageDigest md); + [CCode (cname = "X509_sign_")] + public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error { + throw_if_error (sign_ (private_key, md)); + } + } + } + + public int throw_if_error(int res) throws GLib.Error { + if (res <= 0) { + ulong error = ERR.get_error (); + if (error == 0) return res; + throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error)); + } + return res; + } +} \ No newline at end of file diff --git a/meson.build b/meson.build index df5a2b80..84597fd4 100644 --- a/meson.build +++ b/meson.build @@ -47,9 +47,6 @@ vala_c_args = cc.get_supported_arguments([ '-Wno-unused-variable', ]) -# plugin_crypto is enabled if any of the crypto plugins is enabled, auto if -# none of them are explicitly enabled but at least one is set to auto, or -# disabled if all of them are disabled. plugin_crypto = get_option('plugin-ice') foreach plugin : ['plugin-ice', 'plugin-omemo', 'plugin-rtp'] if get_option(plugin).enabled() and not plugin_crypto.enabled() @@ -59,11 +56,30 @@ foreach plugin : ['plugin-ice', 'plugin-omemo', 'plugin-rtp'] endif endforeach +if get_option('crypto-backend') == 'auto' + # Prefer libgcrypt/gnutls over openssl because glib-networking is usually + # built with gnutls anyway. + dep_libgcrypt = dependency('libgcrypt', required: false) + dep_gnutls = dependency('gnutls', required: false) + if dep_libgcrypt.found() and dep_gnutls.found() + crypto_backend = 'gnutls' + else + dep_openssl = dependency('openssl', disabler: true, required: plugin_crypto) + crypto_backend = 'openssl' + endif +elif get_option('crypto-backend') == 'openssl' + dep_openssl = dependency('openssl', disabler: true, required: plugin_crypto) + crypto_backend = 'openssl' +elif get_option('crypto-backend') == 'gnutls' + dep_libgcrypt = dependency('libgcrypt', disabler: true, required: plugin_crypto) + dep_gnutls = dependency('gnutls', disabler: true, required: get_option('plugin-ice')) + crypto_backend = 'gnutls' +endif + dep_gdk_pixbuf = dependency('gdk-pixbuf-2.0') dep_gee = dependency('gee-0.8') dep_gio = dependency('gio-2.0') dep_glib = dependency('glib-2.0') -dep_gnutls = dependency('gnutls', disabler: true, required: get_option('plugin-ice')) dep_gmodule = dependency('gmodule-2.0') dep_gpgme = dependency('gpgme', disabler: true, required: get_option('plugin-openpgp')) dep_gstreamer = dependency('gstreamer-1.0', disabler: true, required: get_option('plugin-rtp')) @@ -75,7 +91,6 @@ dep_gtk4 = dependency('gtk4') dep_icu_uc = dependency('icu-uc') dep_libadwaita = dependency('libadwaita-1', version: '>=1.5') dep_libcanberra = dependency('libcanberra', disabler: true, required: get_option('plugin-notification-sound')) -dep_libgcrypt = dependency('libgcrypt', disabler: true, required: plugin_crypto) dep_libqrencode = dependency('libqrencode', disabler: true, required: get_option('plugin-omemo')) dep_libsrtp2 = dependency('libsrtp2', disabler: true, required: plugin_crypto) dep_libomemo_c = dependency('libomemo-c', disabler: true, required: get_option('plugin-omemo')) diff --git a/meson_options.txt b/meson_options.txt index 93c1f12a..bbf7a046 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -1,6 +1,7 @@ option('plugindir', type: 'string', value: 'dino/plugins', description: 'Dino plugin directory, relative to libdir') option('set-install-rpath', type: 'boolean', value: false, description: 'Set rpath of installed binaries to the configured libdir') +option('crypto-backend', type: 'combo', choices: ['auto', 'openssl', 'gnutls'], value: 'auto', description: 'Preferred crypto backend') option('plugin-ice', type: 'feature', value: 'enabled', description: 'Peer-to-peer communication') option('plugin-omemo', type: 'feature', value: 'enabled', description: 'End-to-end encryption using OMEMO') diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 1cec8b38..5ed807bf 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -5,7 +5,6 @@ dependencies = [ dep_gio, dep_glib, dep_gmodule, - dep_gnutls, dep_nice, dep_qlite, dep_xmpp_vala, @@ -24,6 +23,18 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) +if crypto_backend == 'gnutls' + dependencies += [ dep_gnutls ] + sources += files( + 'src/dtls_srtp_gnutls.vala' + ) +else # openssl + dependencies += [ dep_openssl ] + sources += files( + 'src/dtls_srtp_openssl.vala', + 'src/openssl_utils.c', + ) +endif +lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) dep_ice = declare_dependency(link_with: lib_ice, include_directories: include_directories('.')) summary('Peer-to-peer communication (ice)', dep_ice.found(), bool_yn: true, section: 'Plugins') diff --git a/plugins/ice/src/dtls_srtp.vala b/plugins/ice/src/dtls_srtp.vala index c9813b7e..41918359 100644 --- a/plugins/ice/src/dtls_srtp.vala +++ b/plugins/ice/src/dtls_srtp.vala @@ -1,14 +1,10 @@ -using GnuTLS; - namespace Dino.Plugins.Ice.DtlsSrtp { -public class CredentialsCapsule { +public abstract class CredentialsCapsule : Object { public uint8[] own_fingerprint; - public X509.Certificate[] own_cert; - public X509.PrivateKey private_key; } -public class Handler { +public abstract class AbstractHandler { public signal void send_data(uint8[] data); @@ -21,18 +17,18 @@ public class Handler { public uint8[] peer_fingerprint { get; set; } public string peer_fp_algo { get; set; } - private CredentialsCapsule credentials; - private Cond buffer_cond = Cond(); - private Mutex buffer_mutex = Mutex(); - private Gee.LinkedList buffer_queue = new Gee.LinkedList(); + protected CredentialsCapsule credentials; + protected Cond buffer_cond = Cond(); + protected Mutex buffer_mutex = Mutex(); + protected Gee.LinkedList buffer_queue = new Gee.LinkedList(); - private bool running = false; - private bool stop = false; - private bool restart = false; + protected bool running = false; + protected bool stop = false; + protected bool restart = false; - private Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session(); + protected Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session(); - public Handler.with_cert(CredentialsCapsule creds) { + protected AbstractHandler.with_cert(CredentialsCapsule creds) { this.credentials = creds; this.own_fingerprint = creds.own_fingerprint; } @@ -79,38 +75,6 @@ public class Handler { buffer_mutex.unlock(); } - internal static CredentialsCapsule generate_credentials() throws GLib.Error { - int err = 0; - - X509.PrivateKey private_key = X509.PrivateKey.create(); - err = private_key.generate(PKAlgorithm.ECDSA, 256); - throw_if_error(err); - - var start_time = new DateTime.now_local().add_days(-1); - var end_time = start_time.add_days(2); - - X509.Certificate cert = X509.Certificate.create(); - cert.set_key(private_key); - cert.set_version(1); - cert.set_activation_time ((time_t) start_time.to_unix ()); - cert.set_expiration_time ((time_t) end_time.to_unix ()); - - uint32 serial = 1; - cert.set_serial(&serial, sizeof(uint32)); - - cert.sign(cert, private_key); - - uint8[] own_fingerprint = get_fingerprint(cert, DigestAlgorithm.SHA256); - X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert }; - - var creds = new CredentialsCapsule(); - creds.own_fingerprint = own_fingerprint; - creds.own_cert = (owned) own_cert; - creds.private_key = (owned) private_key; - - return creds; - } - public void stop_dtls_connection() { buffer_mutex.lock(); stop = true; @@ -118,228 +82,49 @@ public class Handler { buffer_mutex.unlock(); } - public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() { - MainContext context = MainContext.current_source().get_context(); - var thread = new Thread("dtls-connection", () => { - var res = setup_dtls_connection_thread(); - Source source = new IdleSource(); - source.set_callback(setup_dtls_connection.callback); - source.attach(context); - return res; - }); - yield; - return thread.join(); - } - - private Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() { + protected Bytes get_buffer_if_present () { buffer_mutex.lock(); - if (stop) { - restart = true; + if (buffer_queue.size == 0) { buffer_mutex.unlock(); return null; } - if (running || ready) { - buffer_mutex.unlock(); - return null; - } - running = true; - restart = false; - buffer_mutex.unlock(); - - InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT; - debug("Setting up DTLS connection. We're %s", mode.to_string()); - - CertificateCredentials cert_cred = CertificateCredentials.create(); - int err = cert_cred.set_x509_key(credentials.own_cert, credentials.private_key); - throw_if_error(err); - - Session? session = Session.create(server_or_client | InitFlags.DATAGRAM); - session.enable_heartbeat(1); - session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80"); - session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred); - session.server_set_request(CertificateRequest.REQUEST); - session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509"); - - session.set_transport_pointer(this); - session.set_pull_function(pull_function); - session.set_pull_timeout_function(pull_timeout_function); - session.set_push_function(push_function); - session.set_verify_function(verify_function); - - DateTime maximum_time = new DateTime.now_utc().add_seconds(20); - do { - err = session.handshake(); - - DateTime current_time = new DateTime.now_utc(); - if (maximum_time.compare(current_time) < 0) { - warning("DTLS handshake timeouted"); - err = ErrorCode.APPLICATION_ERROR_MIN + 1; - break; - } - if (stop) { - debug("DTLS handshake stopped"); - err = ErrorCode.APPLICATION_ERROR_MIN + 2; - break; - } - } while (err < 0 && !((ErrorCode)err).is_fatal()); - - buffer_mutex.lock(); - if (stop) { - stop = false; - running = false; - bool restart = restart; - buffer_mutex.unlock(); - if (restart) { - debug("Restarting DTLS handshake"); - return setup_dtls_connection_thread(); - } - return null; - } + Bytes res = buffer_queue.remove_at(0); buffer_mutex.unlock(); - if (err != ErrorCode.SUCCESS) { - warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string()); - return null; - } - - uint8[] km = new uint8[150]; - Datum? client_key, client_salt, server_key, server_salt; - session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt); - if (client_key == null || client_salt == null || server_key == null || server_salt == null) { - warning("SRTP client/server key/salt null"); - } - - debug("Finished DTLS connection. We're %s", mode.to_string()); - if (mode == Mode.SERVER) { - srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); - srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); - } else { - srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); - srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); - } - return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); + return res; } - private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) { - Handler self = transport_ptr as Handler; - - self.buffer_mutex.lock(); - while (self.buffer_queue.size == 0) { - self.buffer_cond.wait(self.buffer_mutex); - if (self.stop) { - self.buffer_mutex.unlock(); - debug("DTLS handshake pull_function stopped"); - return -1; - } - } - Bytes data = self.buffer_queue.remove_at(0); - self.buffer_mutex.unlock(); - - uint8[] data_uint8 = Bytes.unref_to_data((owned) data); - Memory.copy(buffer, data_uint8, data_uint8.length); - - // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error. - return (ssize_t)data_uint8.length; - } - - private static int pull_timeout_function(void* transport_ptr, uint ms) { - Handler self = transport_ptr as Handler; - - int64 end_time = get_monotonic_time() + ms * 1000; - - self.buffer_mutex.lock(); - while (self.buffer_queue.size == 0) { - self.buffer_cond.wait_until(self.buffer_mutex, end_time); - if (self.stop) { - self.buffer_mutex.unlock(); - debug("DTLS handshake pull_timeout_function stopped"); - return -1; - } - - if (get_monotonic_time() > end_time) { - self.buffer_mutex.unlock(); - return 0; + public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() { + MainContext context = MainContext.current_source().get_context(); + var thread = new Thread("dtls-connection", () => { + // Check we can start working on the thread + buffer_mutex.lock(); + if (stop) { + restart = true; + buffer_mutex.unlock(); + return null; } - } - self.buffer_mutex.unlock(); - - // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. - return 1; - } - - private static ssize_t push_function(void* transport_ptr, uint8[] buffer) { - Handler self = transport_ptr as Handler; - self.send_data(buffer); - - // The callback should return a positive number indicating the bytes sent, and -1 on error. - return (ssize_t)buffer.length; - } - - private static int verify_function(Session session) { - Handler self = session.get_transport_pointer() as Handler; - try { - bool valid = self.verify_peer_cert(session); - if (!valid) { - warning("DTLS certificate invalid. Aborting handshake."); - return 1; + if (running || ready) { + buffer_mutex.unlock(); + return null; } - } catch (Error e) { - warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message); - return 1; - } - - // The callback function should return 0 for the handshake to continue or non-zero to terminate. - return 0; - } - - private bool verify_peer_cert(Session session) throws GLib.Error { - unowned Datum[] cert_datums = session.get_peer_certificates(); - if (cert_datums.length == 0) { - warning("No peer certs"); - return false; - } - if (cert_datums.length > 1) warning("More than one peer cert"); - - X509.Certificate peer_cert = X509.Certificate.create(); - peer_cert.import(ref cert_datums[0], CertificateFormat.DER); - - DigestAlgorithm algo; - switch (peer_fp_algo) { - case "sha-256": - algo = DigestAlgorithm.SHA256; - break; - default: - warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo); - return false; - } - - uint8[] real_peer_fp = get_fingerprint(peer_cert, algo); - - if (real_peer_fp.length != this.peer_fingerprint.length) { - warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length); - return false; - } + running = true; + restart = false; + buffer_mutex.unlock(); - for (int i = 0; i < real_peer_fp.length; i++) { - if (real_peer_fp[i] != this.peer_fingerprint[i]) { - warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint)); - return false; - } - } + // Actual work + var res = setup_dtls_connection_thread(); - return true; + // Callback + Source source = new IdleSource(); + source.set_callback(setup_dtls_connection.callback); + source.attach(context); + return res; + }); + yield; + return thread.join(); } -} - -private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) { - uint8[] buf = new uint8[512]; - size_t buf_out_size = 512; - certificate.get_fingerprint(digest_algo, buf, ref buf_out_size); - uint8[] ret = new uint8[buf_out_size]; - for (int i = 0; i < buf_out_size; i++) { - ret[i] = buf[i]; - } - return ret; + protected abstract Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread(); } private string format_fingerprint(uint8[] fingerprint) { diff --git a/plugins/ice/src/dtls_srtp_gnutls.vala b/plugins/ice/src/dtls_srtp_gnutls.vala new file mode 100644 index 00000000..91a7cfb2 --- /dev/null +++ b/plugins/ice/src/dtls_srtp_gnutls.vala @@ -0,0 +1,245 @@ +using GnuTLS; + +namespace Dino.Plugins.Ice.DtlsSrtp { + +public class CredentialsCapsuleGnuTLS : CredentialsCapsule { + public X509.Certificate[] own_cert; + public X509.PrivateKey private_key; +} + +private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) { + uint8[] buf = new uint8[512]; + size_t buf_out_size = 512; + certificate.get_fingerprint(digest_algo, buf, ref buf_out_size); + + uint8[] ret = new uint8[buf_out_size]; + for (int i = 0; i < buf_out_size; i++) { + ret[i] = buf[i]; + } + return ret; +} + +internal CredentialsCapsule generate_credentials () throws GLib.Error { + int err = 0; + + X509.PrivateKey private_key = X509.PrivateKey.create (); + err = private_key.generate (PKAlgorithm.ECDSA, 256); + throw_if_error (err); + + var start_time = new DateTime.now_local().add_days(-1); + var end_time = start_time.add_days (2); + + X509.Certificate cert = X509.Certificate.create (); + cert.set_key (private_key); + cert.set_version (1); + cert.set_activation_time ((time_t) start_time.to_unix ()); + cert.set_expiration_time ((time_t) end_time.to_unix ()); + + uint32 serial = 1; + cert.set_serial (&serial, sizeof(uint32)); + + cert.sign (cert, private_key); + + uint8[] own_fingerprint = get_fingerprint (cert, DigestAlgorithm.SHA256); + X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert }; + + var creds = new CredentialsCapsuleGnuTLS(); + creds.own_fingerprint = own_fingerprint; + creds.own_cert = (owned) own_cert; + creds.private_key = (owned) private_key; + + return creds; +} + +public class Handler : AbstractHandler { + + public Handler.with_cert(CredentialsCapsule creds) { + base.with_cert(creds); + } + + protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() { + InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT; + debug("Setting up DTLS connection using GnuTLS. We're %s", mode.to_string()); + + CertificateCredentials cert_cred = CertificateCredentials.create(); + int err = cert_cred.set_x509_key(((CredentialsCapsuleGnuTLS)credentials).own_cert, ((CredentialsCapsuleGnuTLS)credentials).private_key); + throw_if_error(err); + + Session? session = Session.create(server_or_client | InitFlags.DATAGRAM); + session.enable_heartbeat(1); + session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80"); + session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred); + session.server_set_request(CertificateRequest.REQUEST); + session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509"); + + session.set_transport_pointer(this); + session.set_pull_function(pull_function); + session.set_pull_timeout_function(pull_timeout_function); + session.set_push_function(push_function); + session.set_verify_function(verify_function); + + DateTime maximum_time = new DateTime.now_utc().add_seconds(20); + do { + err = session.handshake(); + + DateTime current_time = new DateTime.now_utc(); + if (maximum_time.compare(current_time) < 0) { + warning("DTLS handshake timeouted"); + err = ErrorCode.APPLICATION_ERROR_MIN + 1; + break; + } + if (stop) { + debug("DTLS handshake stopped"); + err = ErrorCode.APPLICATION_ERROR_MIN + 2; + break; + } + } while (err < 0 && !((ErrorCode)err).is_fatal()); + + buffer_mutex.lock(); + if (stop) { + stop = false; + running = false; + bool restart = restart; + buffer_mutex.unlock(); + if (restart) { + debug("Restarting DTLS handshake"); + return setup_dtls_connection_thread(); + } + return null; + } + buffer_mutex.unlock(); + if (err != ErrorCode.SUCCESS) { + warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string()); + return null; + } + + uint8[] km = new uint8[150]; + Datum? client_key, client_salt, server_key, server_salt; + session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt); + if (client_key == null || client_salt == null || server_key == null || server_salt == null) { + warning("SRTP client/server key/salt null"); + } + + debug("Finished DTLS connection. We're %s", mode.to_string()); + if (mode == Mode.SERVER) { + srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); + srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); + } else { + srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); + srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); + } + return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); + } + + private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) { + Handler self = transport_ptr as Handler; + + self.buffer_mutex.lock(); + while (self.buffer_queue.size == 0) { + self.buffer_cond.wait(self.buffer_mutex); + if (self.stop) { + self.buffer_mutex.unlock(); + debug("DTLS handshake pull_function stopped"); + return -1; + } + } + Bytes data = self.buffer_queue.remove_at(0); + self.buffer_mutex.unlock(); + + uint8[] data_uint8 = Bytes.unref_to_data((owned) data); + Memory.copy(buffer, data_uint8, data_uint8.length); + + // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error. + return (ssize_t)data_uint8.length; + } + + private static int pull_timeout_function(void* transport_ptr, uint ms) { + Handler self = transport_ptr as Handler; + + int64 end_time = get_monotonic_time() + ms * 1000; + + self.buffer_mutex.lock(); + while (self.buffer_queue.size == 0) { + self.buffer_cond.wait_until(self.buffer_mutex, end_time); + if (self.stop) { + self.buffer_mutex.unlock(); + debug("DTLS handshake pull_timeout_function stopped"); + return -1; + } + + if (get_monotonic_time() > end_time) { + self.buffer_mutex.unlock(); + return 0; + } + } + self.buffer_mutex.unlock(); + + // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. + return 1; + } + + private static ssize_t push_function(void* transport_ptr, uint8[] buffer) { + Handler self = transport_ptr as Handler; + self.send_data(buffer); + + // The callback should return a positive number indicating the bytes sent, and -1 on error. + return (ssize_t)buffer.length; + } + + private static int verify_function(Session session) { + Handler self = session.get_transport_pointer() as Handler; + try { + bool valid = self.verify_peer_cert(session); + if (!valid) { + warning("DTLS certificate invalid. Aborting handshake."); + return 1; + } + } catch (Error e) { + warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message); + return 1; + } + + // The callback function should return 0 for the handshake to continue or non-zero to terminate. + return 0; + } + + private bool verify_peer_cert(Session session) throws GLib.Error { + unowned Datum[] cert_datums = session.get_peer_certificates(); + if (cert_datums.length == 0) { + warning("No peer certs"); + return false; + } + if (cert_datums.length > 1) warning("More than one peer cert"); + + X509.Certificate peer_cert = X509.Certificate.create(); + peer_cert.import(ref cert_datums[0], CertificateFormat.DER); + + DigestAlgorithm algo; + switch (peer_fp_algo) { + case "sha-256": + algo = DigestAlgorithm.SHA256; + break; + default: + warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo); + return false; + } + + uint8[] real_peer_fp = get_fingerprint(peer_cert, algo); + + if (real_peer_fp.length != this.peer_fingerprint.length) { + warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length); + return false; + } + + for (int i = 0; i < real_peer_fp.length; i++) { + if (real_peer_fp[i] != this.peer_fingerprint[i]) { + warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint)); + return false; + } + } + + return true; + } +} + +} \ No newline at end of file diff --git a/plugins/ice/src/dtls_srtp_openssl.vala b/plugins/ice/src/dtls_srtp_openssl.vala new file mode 100644 index 00000000..86f080e5 --- /dev/null +++ b/plugins/ice/src/dtls_srtp_openssl.vala @@ -0,0 +1,202 @@ +using OpenSSL; + +namespace Dino.Plugins.Ice.DtlsSrtp { + +public class CredentialsCapsuleOpenSSL : CredentialsCapsule { + public X509.Certificate own_cert; + public EVP.Key private_key; +} + +internal CredentialsCapsule generate_credentials () throws GLib.Error { + EVP.Key key = new EVP.Key.generate_ecdsa ("prime256v1"); + + var start_time = new DateTime.now_local().add_days(-1); + var end_time = start_time.add_days (2); + + X509.Certificate cert = new X509.Certificate (); + cert.set_public_key (key); + cert.set_version (1); + cert.not_before.set ((time_t) start_time.to_unix ()); + cert.not_after.set ((time_t) end_time.to_unix ()); + cert.serial_number.set (1); + + cert.sign (key, EVP.sha256 ()); + + CredentialsCapsuleOpenSSL credentials = new CredentialsCapsuleOpenSSL (); + credentials.own_fingerprint = cert.digest (EVP.sha256 ()); + credentials.own_cert = (owned) cert; + credentials.private_key = (owned) key; + return credentials; +} + +public class Handler : AbstractHandler { + + public Handler.with_cert (CredentialsCapsule creds) { + base.with_cert (creds); + } + + protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread () { + debug("Setting up DTLS connection using OpenSSL. We're %s", mode.to_string()); + SSL.Context context = new SSL.Context (mode == Mode.SERVER ? SSL.Method.DTLS_SERVER : SSL.Method.DTLS_CLIENT); + context.set_tlsext_use_srtp ("SRTP_AES128_CM_SHA1_80"); + context.use_certificate (((CredentialsCapsuleOpenSSL) credentials).own_cert); + context.use_private_key (((CredentialsCapsuleOpenSSL) credentials).private_key); + SSL session = new SSL (context); + BIO bio = new BIO(get_handler_based_bio_method()); + bio.data = this; + session.rbio = bio; + session.wbio = bio; + + DateTime maximum_time = new DateTime.now_utc().add_seconds(20); + int err = 0; + if (mode == Mode.SERVER) { + session.set_accept_state (); + } else { + session.set_connect_state (); + } + do { + try { + SSL.Error ret = session.do_handshake(); + switch (ret) { + case SSL.Error.NONE: + err = 1; + break; + case SSL.Error.WANT_READ: + debug ("DTLS wants to read, but nothing in queue, wait for buffer"); + buffer_mutex.lock(); + if (buffer_queue.size == 0) { + buffer_cond.wait_until(buffer_mutex, get_monotonic_time() + maximum_time.difference(new DateTime.now_utc())); + } + buffer_mutex.unlock(); + err = -1; + break; + default: + warning ("DTLS Error: %s", @"$ret"); + err = 4; + break; + } + } catch (Error e) { + warning ("DTLS Error: %s", e.message); + err = e.code; + } + + DateTime current_time = new DateTime.now_utc(); + if (maximum_time.compare(current_time) < 0) { + debug ("DTLS handshake timeouted"); + err = 2; + break; + } + if (stop) { + debug ("DTLS handshake stopped"); + err = 3; + break; + } + } while (err < 0); + + buffer_mutex.lock(); + if (stop) { + stop = false; + running = false; + bool restart = restart; + buffer_mutex.unlock(); + if (restart) { + debug ("Restarting DTLS handshake"); + return setup_dtls_connection_thread(); + } + return null; + } + buffer_mutex.unlock(); + if (err != 1) { + debug ("DTLS handshake failed"); + return null; + } + + // TODO: Check peer certificate + + uint8[] km = new uint8[60]; + session.export_keying_material (km, "EXTRACTOR-dtls_srtp"); + uint8[] client_key = km[0:16]; + uint8[] server_key = km[16:32]; + uint8[] client_salt = km[32:46]; + uint8[] server_salt = km[46:60]; + + debug ("Finished DTLS connection. We're %s", mode.to_string()); + if (mode == Mode.SERVER) { + srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); + srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); + } else { + srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); + srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); + } + return new Xmpp.Xep.Jingle.ContentEncryption (Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); + } + + private int read_impl (BIO bio, uint8[] out_buf) { + Bytes data = get_buffer_if_present (); + if (data == null) { + if (!stop) { + debug ("No pending buffer in queue, but end not reached yet, set_retry_read"); + bio.set_retry_read (); + } + return -1; + } + if (data.length > out_buf.length) { + warning ("Buffer in queue does not fit in out_buf"); + return -1; + } + debug ("Read %d bytes from queue", data.length); + + uint8[] data_uint8 = Bytes.unref_to_data((owned) data); + Memory.copy (out_buf, data_uint8, data_uint8.length); + bio.clear_retry_flags (); + return data_uint8.length; + } + + private int write_impl (BIO bio, uint8[] buf) { + debug ("Write %d bytes to network", buf.length); + send_data (buf); + return buf.length; + } + + private long ctrl_impl (BIO bio, BIO.ControlCommand cmd, long num, void* ptr) { + switch (cmd) { + case BIO.ControlCommand.FLUSH: + // Datagrams are sent out immediately + return 1; + case BIO.ControlCommand.DGRAM_SET_NEXT_TIMEOUT: + // Datagrams are sent out immediately + return 1; + case BIO.ControlCommand.DGRAM_GET_MTU_OVERHEAD: + // Just some safe estimate + return 70; + case BIO.ControlCommand.DGRAM_QUERY_MTU: + // Just some safe estimate + return 1200; + case BIO.ControlCommand.WPENDING: + // Datagrams are sent out immediately + return 0; + case BIO.ControlCommand.POP: + case BIO.ControlCommand.PUSH: + // Ignored + return 0; + default: + warning (@"Unimplemented ctrl cmd:$cmd, num:$num"); + return 0; + } + } + + private static BIO.Method _handler_based_bio_method_instance = null; + + private static unowned BIO.Method get_handler_based_bio_method () { + if (_handler_based_bio_method_instance != null) return _handler_based_bio_method_instance; + _handler_based_bio_method_instance = new BIO.Method (BIO.Type.SOURCE_SINK | BIO.Type.DGRAM, "Dino DTLS Handler BIO"); + _handler_based_bio_method_instance.read = (bio, out_buf) => bio.data.read_impl (bio, out_buf); + _handler_based_bio_method_instance.write = (bio, buf) => bio.data.write_impl (bio, buf); + _handler_based_bio_method_instance.ctrl = (bio, cmd, num, ptr) => bio.data.ctrl_impl (bio, cmd, num, ptr); + return _handler_based_bio_method_instance; + } +} + + + +} \ No newline at end of file diff --git a/plugins/ice/src/module.vala b/plugins/ice/src/module.vala index 2645d7dc..ace62108 100644 --- a/plugins/ice/src/module.vala +++ b/plugins/ice/src/module.vala @@ -42,7 +42,7 @@ public class Dino.Plugins.Ice.Module : JingleIceUdp.Module { private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) { string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); try { - if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.Handler.generate_credentials(); + if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); } catch (Error e) { warning("Error creating dtls credentials: %s", e.message); } diff --git a/plugins/ice/src/openssl_utils.c b/plugins/ice/src/openssl_utils.c new file mode 100644 index 00000000..7f4bf331 --- /dev/null +++ b/plugins/ice/src/openssl_utils.c @@ -0,0 +1,49 @@ +#include "openssl_utils.h" +#include +#include + +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x30000000L +// This is for OpenSSL 3.0.0 and newer + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { + // Generate EVP_PKEY directly + EVP_PKEY *pkey = EVP_EC_gen (curve); + return pkey; +} + +#else +// This is for OpenSSL before 3.0.0 and forks of earlier OpenSSL versions like LibreSSL + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { + // Get NID from curve name + int nid = OBJ_sn2nid (curve); + if (nid == NID_undef) return NULL; + + // Create EC_KEY + EC_KEY *ec_key = EC_KEY_new_by_curve_name (nid); + if (!ec_key) return NULL; + + // Generate key + if (!EC_KEY_generate_key (ec_key)) { + EC_KEY_free (ec_key); + return NULL; + } + + // Create EVP_PKEY + EVP_PKEY *pkey = EVP_PKEY_new (); + if (!pkey) { + EC_KEY_free (ec_key); + return NULL; + } + + // Assign EC_KEY to EVP_PKEY + if (!EVP_PKEY_assign_EC_KEY (pkey, ec_key)) { + EC_KEY_free (ec_key); + return NULL; + } + + // EVP_PKEY_assign_EC_KEY takes ownership of ec_key, no need to free it explicitly + return pkey; +} + +#endif diff --git a/plugins/ice/src/openssl_utils.h b/plugins/ice/src/openssl_utils.h new file mode 100644 index 00000000..bcc6f53a --- /dev/null +++ b/plugins/ice/src/openssl_utils.h @@ -0,0 +1,8 @@ +#ifndef DINO_OPENSSL_UTILS_H +#define DINO_OPENSSL_UTILS_H + +#include + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve); + +#endif //DINO_OPENSSL_UTILS_H \ No newline at end of file diff --git a/plugins/ice/vapi/openssl.vapi b/plugins/ice/vapi/openssl.vapi new file mode 100644 index 00000000..e0654869 --- /dev/null +++ b/plugins/ice/vapi/openssl.vapi @@ -0,0 +1,218 @@ +[CCode (cprefix = "")] +namespace OpenSSL { + [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")] + namespace ASN1 { + [Compact] + [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")] + public class Integer { + public bool @set (long v); + } + + [Compact] + [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")] + public class Time { + public bool @set (time_t t); + } + } + [Compact] + [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)] + public class BIO { + [Compact] + [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)] + public class Method { + public Method (Type type, string name); + [CCode (has_target = false)] + public delegate int WriteFunc (BIO bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf); + [CCode (has_target = false)] + public delegate int ReadFunc (BIO bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf); + [CCode (has_target = false, simple_generics = true)] + public delegate long CtrlFunc (BIO bio, ControlCommand cmd, long num, void* ptr); + public WriteFunc write { get; set; } + public ReadFunc read { get; set; } + public CtrlFunc ctrl { get; set; } + } + + [Flags] + [CCode (cname = "int")] + public enum Type { + SOURCE_SINK, + DGRAM, + } + + [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)] + public enum ControlCommand { + RESET, + EOF, + SET, + GET, + PUSH, + POP, + GET_CLOSE, + SET_CLOSE, + PENDING, + FLUSH, + DUP, + WPENDING, + + DGRAM_QUERY_MTU, + DGRAM_GET_MTU, + DGRAM_SET_MTU, + DGRAM_SET_PEER, + DGRAM_SET_NEXT_TIMEOUT, + DGRAM_GET_PEER, + DGRAM_GET_FALLBACK_MTU, + DGRAM_SET_DONT_FRAG, + DGRAM_GET_MTU_OVERHEAD, + } + + public BIO (Method type); + public T data { get; set; } + + public void clear_retry_flags (); + public void set_retry_read (); + public bool should_read (); + } + + [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")] + namespace ERR { + public ulong get_error (); + public unowned string lib_error_string (ulong error); + public unowned string reason_error_string (ulong error); + } + + [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")] + namespace EVP { + [Compact] + [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] + public class Key { + public Key (); + [CCode (cheader_filename = "openssl_utils.h")] + public Key.generate_ecdsa (string curve); + } + [Compact] + [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")] + public class MessageDigest { + } + + public static unowned MessageDigest sha256 (); + } + + [Compact] + [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")] + class SSL { + [Compact] + [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")] + public class Context { + public Context (Method method); + public int set_tlsext_use_srtp (string profiles); + public int use_certificate (X509.Certificate certificate); + [CCode (cname = "SSL_CTX_use_PrivateKey")] + public int use_private_key (EVP.Key private_key); + } + + [CCode (cname = "const SSL_METHOD*")] + public enum Method { + [CCode (cname = "DTLS_client_method()")] + DTLS_CLIENT, + [CCode (cname = "DTLS_server_method()")] + DTLS_SERVER, + } + + [CCode (cname = "int", has_type_id = false)] + public enum Error { + NONE, + ZERO_RETURN, + WANT_READ, + WANT_WRITE, + WANT_CONNECT, + WANT_ACCEPT, + WANT_X509_LOOKUP, + WANT_ASYNC, + WANT_ASYNC_JOB, + WANT_CLIENT_HELLO_CB, + SYSCALL, + SSL + } + + public SSL (Context context); + public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; } + public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; } + + [CCode (cname = "SSL_do_handshake")] + private int do_handshake_ (); + [CCode (cname = "SSL_do_handshake_")] + public Error do_handshake () throws GLib.Error { + int ret = throw_if_error (do_handshake_ ()); + return get_error (ret); + } + [CCode (cname = "SSL_export_keying_material")] + private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context); + [CCode (cname = "SSL_export_keying_material_")] + public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error { + throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null)); + } + public Error get_error (int ret); + public void set_accept_state (); + public void set_connect_state (); + public int want (); + } + + [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")] + namespace X509 { + [Compact] + [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")] + public class Certificate { + public Certificate (); + public ASN1.Time not_before { + [CCode (cname = "X509_get_notBefore")] + get; + [CCode (cname = "X509_set_notBefore")] + set; + } + public ASN1.Time not_after { + [CCode (cname = "X509_get_notAfter")] + get; + [CCode (cname = "X509_set_notAfter")] + set; + } + public ASN1.Integer serial_number { + [CCode (cname = "X509_get_serialNumber")] + get; + [CCode (cname = "X509_set_serialNumber")] + set; + } + [CCode (cname = "X509_digest")] + private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len); + [CCode (cname = "X509_digest_")] + public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error { + uint8[] buf = new uint8[buf_len]; + uint buf_out_size = (uint) buf_len; + throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size)); + + uint8[] ret = new uint8[buf_out_size]; + for (int i = 0; i < buf_out_size; i++) { + ret[i] = buf[i]; + } + return ret; + } + [CCode (cname = "X509_set_pubkey")] + public int set_public_key (EVP.Key public_key); + public int set_version (long version); + [CCode (cname = "X509_sign")] + private int sign_ (EVP.Key private_key, EVP.MessageDigest md); + [CCode (cname = "X509_sign_")] + public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error { + throw_if_error (sign_ (private_key, md)); + } + } + } + + public int throw_if_error(int res) throws GLib.Error { + if (res <= 0) { + ulong error = ERR.get_error (); + if (error == 0) return res; + throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error)); + } + return res; + } +} \ No newline at end of file diff --git a/plugins/omemo/meson.build b/plugins/omemo/meson.build index 8a00fb1a..d195525e 100644 --- a/plugins/omemo/meson.build +++ b/plugins/omemo/meson.build @@ -7,7 +7,6 @@ dependencies = [ dep_glib, dep_gmodule, dep_gtk4, - dep_libgcrypt, dep_libqrencode, dep_libomemo_c, dep_m, @@ -62,6 +61,13 @@ c_args = vala_c_args + [ '-DGETTEXT_PACKAGE="dino-omemo"', '-DLOCALE_INSTALL_DIR="@0@"'.format(get_option('prefix') / get_option('localedir')), ] +if crypto_backend == 'gnutls' + dependencies += [ dep_libgcrypt ] + sources += files('src/native/helper_gcrypt.c') +else + dependencies += [ dep_openssl ] + sources += files('src/native/helper_openssl.c') +endif vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', # This is to build internal vapi for tests diff --git a/plugins/omemo/src/file_transfer/file_decryptor.vala b/plugins/omemo/src/file_transfer/file_decryptor.vala index 80303789..ff96b4a3 100644 --- a/plugins/omemo/src/file_transfer/file_decryptor.vala +++ b/plugins/omemo/src/file_transfer/file_decryptor.vala @@ -59,7 +59,7 @@ public class OmemoFileDecryptor : FileDecryptor, Object { 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"); + SymmetricCipherDecryption cipher = create_symmetric_cipher_decryption("AES-GCM"); cipher.set_key(key); cipher.set_iv(iv); return new ConverterInputStream(encrypted_stream, new SymmetricCipherDecrypter((owned) cipher, 16)); diff --git a/plugins/omemo/src/file_transfer/file_encryptor.vala b/plugins/omemo/src/file_transfer/file_encryptor.vala index 58be7ef1..1aed752f 100644 --- a/plugins/omemo/src/file_transfer/file_encryptor.vala +++ b/plugins/omemo/src/file_transfer/file_encryptor.vala @@ -27,11 +27,11 @@ public class OmemoFileEncryptor : Dino.FileEncryptor, Object { try { //Create a key and use it to encrypt the file uint8[] iv = new uint8[IV_SIZE]; - Plugin.get_context().randomize(iv); + Crypto.randomize(iv); uint8[] key = new uint8[KEY_SIZE]; - Plugin.get_context().randomize(key); + Crypto.randomize(key); - SymmetricCipher cipher = new SymmetricCipher("AES-GCM"); + SymmetricCipherEncryption cipher = create_symmetric_cipher_encryption("AES-GCM"); cipher.set_key(key); cipher.set_iv(iv); diff --git a/plugins/omemo/src/jingle/jet_omemo.vala b/plugins/omemo/src/jingle/jet_omemo.vala index 2c364625..b1a27e15 100644 --- a/plugins/omemo/src/jingle/jet_omemo.vala +++ b/plugins/omemo/src/jingle/jet_omemo.vala @@ -93,19 +93,19 @@ public class AesGcmCipher : Jet.Cipher, Object { } public Jet.TransportSecret generate_random_secret() { uint8[] iv = new uint8[default_iv_size]; - Omemo.Plugin.get_context().randomize(iv); + Crypto.randomize(iv); uint8[] key = new uint8[key_size]; - Omemo.Plugin.get_context().randomize(key); + Crypto.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"); + SymmetricCipherDecryption cipher = create_symmetric_cipher_decryption("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"); + SymmetricCipherEncryption cipher = create_symmetric_cipher_encryption("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/logic/encrypt.vala b/plugins/omemo/src/logic/encrypt.vala index e5d11c69..94203ac9 100644 --- a/plugins/omemo/src/logic/encrypt.vala +++ b/plugins/omemo/src/logic/encrypt.vala @@ -26,9 +26,9 @@ namespace Dino.Plugins.Omemo { //Create a key and use it to encrypt the message uint8[] key = new uint8[KEY_SIZE]; - Plugin.get_context().randomize(key); + Crypto.randomize(key); uint8[] iv = new uint8[IV_SIZE]; - Plugin.get_context().randomize(iv); + Crypto.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]; @@ -128,4 +128,4 @@ namespace Dino.Plugins.Omemo { 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/native/context.vala b/plugins/omemo/src/native/context.vala index b1f5945b..29a96bc1 100644 --- a/plugins/omemo/src/native/context.vala +++ b/plugins/omemo/src/native/context.vala @@ -1,7 +1,7 @@ namespace Omemo { public class Context { - internal NativeContext native_context; + public NativeContext native_context; private RecMutex mutex = RecMutex(); static void locking_function_lock(void* user_data) { @@ -29,10 +29,6 @@ public class Context { 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; diff --git a/plugins/omemo/src/native/helper.c b/plugins/omemo/src/native/helper.c index 2d808cde..020e39d0 100644 --- a/plugins/omemo/src/native/helper.c +++ b/plugins/omemo/src/native/helper.c @@ -1,7 +1,5 @@ #include "helper.h" -#include - signal_type_base* signal_type_ref_vapi(void* instance) { g_return_val_if_fail(instance != NULL, NULL); signal_type_ref(instance); @@ -64,266 +62,3 @@ void signal_protocol_address_set_device_id(signal_protocol_address* self, int32_ 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 index 3cc21d8a..cbbe220f 100644 --- a/plugins/omemo/src/native/helper.h +++ b/plugins/omemo/src/native/helper.h @@ -17,7 +17,6 @@ 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); diff --git a/plugins/omemo/src/native/helper_gcrypt.c b/plugins/omemo/src/native/helper_gcrypt.c new file mode 100644 index 00000000..a6921bca --- /dev/null +++ b/plugins/omemo/src/native/helper_gcrypt.c @@ -0,0 +1,257 @@ +#include "helper.h" +#include + +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); + } +} + +static 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, + .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_openssl.c b/plugins/omemo/src/native/helper_openssl.c new file mode 100644 index 00000000..a0020971 --- /dev/null +++ b/plugins/omemo/src/native/helper_openssl.c @@ -0,0 +1,313 @@ +#include "helper.h" +#include +#include + +int signal_vala_random_generator(uint8_t *data, size_t len, void *user_data) { + return RAND_bytes(data, len) == 1 ? SG_SUCCESS : SG_ERR_UNKNOWN; +} + +struct SIGNAL_VALA_HMAC_CTX { + EVP_PKEY *pkey; + EVP_MD_CTX *ctx; +}; + +int signal_vala_hmac_sha256_init(void **hmac_context, const uint8_t *key, size_t key_len, void *user_data) { + EVP_PKEY *pkey = EVP_PKEY_new_raw_private_key(EVP_PKEY_HMAC, NULL, key, key_len); + if (!pkey) { + return SG_ERR_NOMEM; + } + EVP_MD_CTX *ctx = EVP_MD_CTX_new(); + if (!ctx) { + EVP_PKEY_free(pkey); + return SG_ERR_NOMEM; + } + if (EVP_DigestSignInit(ctx, NULL, EVP_sha256(), NULL, pkey) != 1) { + EVP_MD_CTX_free(ctx); + EVP_PKEY_free(pkey); + return SG_ERR_UNKNOWN; + } + + struct SIGNAL_VALA_HMAC_CTX *hmac_ctx = malloc(sizeof(*hmac_ctx)); + hmac_ctx->pkey = pkey; + hmac_ctx->ctx = ctx; + *hmac_context = hmac_ctx; + + return SG_SUCCESS; +} + +int signal_vala_hmac_sha256_update(void *hmac_context, const uint8_t *data, size_t data_len, void *user_data) { + struct SIGNAL_VALA_HMAC_CTX *hmac_ctx = hmac_context; + if (EVP_DigestSignUpdate(hmac_ctx->ctx, data, data_len) != 1) { + 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; + struct SIGNAL_VALA_HMAC_CTX *hmac_ctx = hmac_context; + if (EVP_DigestSignFinal(hmac_ctx->ctx, NULL, &len) != 1) { + return SG_ERR_UNKNOWN; + } + signal_buffer *output_buffer = signal_buffer_alloc(len); + if (!output_buffer) { + return SG_ERR_NOMEM; + } + size_t another_len = len; + if (EVP_DigestSignFinal(hmac_ctx->ctx, signal_buffer_data(output_buffer), &another_len) != 1) { + signal_buffer_free(output_buffer); + return SG_ERR_UNKNOWN; + } + if (another_len != len) { + signal_buffer_free(output_buffer); + return SG_ERR_UNKNOWN; + } + *output = output_buffer; + return SG_SUCCESS; +} + +void signal_vala_hmac_sha256_cleanup(void *hmac_context, void *user_data) { + struct SIGNAL_VALA_HMAC_CTX *hmac_ctx = hmac_context; + if (hmac_ctx) { + EVP_MD_CTX_free(hmac_ctx->ctx); + EVP_PKEY_free(hmac_ctx->pkey); + free(hmac_ctx); + } +} + +static const EVP_CIPHER *aes_cipher(int cipher, size_t key_len) { + switch (cipher) { + case SG_CIPHER_AES_CBC_PKCS5: + switch (key_len) { + case 16: return EVP_aes_128_cbc(); + case 24: return EVP_aes_192_cbc(); + case 32: return EVP_aes_256_cbc(); + } + break; + case SG_CIPHER_AES_CTR_NOPADDING: + switch (key_len) { + case 16: return EVP_aes_128_ctr(); + case 24: return EVP_aes_192_ctr(); + case 32: return EVP_aes_256_ctr(); + } + break; + case SG_CIPHER_AES_GCM_NOPADDING: + switch (key_len) { + case 16: return EVP_aes_128_gcm(); + case 24: return EVP_aes_192_gcm(); + case 32: return EVP_aes_256_gcm(); + } + break; + + } + return NULL; +} + +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 result = 0; + uint8_t *out_buf = NULL; + const EVP_CIPHER *evp_cipher = aes_cipher(cipher, key_len); + if (!evp_cipher) { + // fprintf(stderr, "invalid AES mode or key size: %zu\n", key_len); + return SG_ERR_INVAL; + } + if (plaintext_len > INT_MAX - EVP_CIPHER_block_size(evp_cipher)) { + // fprintf(stderr, "invalid plaintext length: %zu\n", plaintext_len); + return SG_ERR_UNKNOWN; + } + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + int buf_extra = 0; + + if (cipher == SG_CIPHER_AES_GCM_NOPADDING) { + // In GCM mode we use the last 16 bytes as auth tag + buf_extra += 16; + + if (EVP_EncryptInit_ex(ctx, evp_cipher, NULL, NULL, NULL) != 1) { + // fprintf(stderr, "cannot initialize cipher\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL) != 1) { + // fprintf(stderr, "cannot set iv size\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (EVP_EncryptInit_ex(ctx, NULL, NULL, key, iv) != 1) { + // fprintf(stderr, "cannot set key/iv\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } else { + // TODO: set ivlen? + if (EVP_EncryptInit_ex(ctx, evp_cipher, 0, key, iv) != 1) { + // fprintf(stderr, "cannot initialize cipher\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + if (cipher == SG_CIPHER_AES_CTR_NOPADDING || cipher == SG_CIPHER_AES_GCM_NOPADDING) { + if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { + // fprintf(stderr, "cannot set padding\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + out_buf = malloc(plaintext_len + EVP_CIPHER_block_size(evp_cipher) + buf_extra); + if (!out_buf) { + // fprintf(stderr, "cannot allocate output buffer\n"); + result = SG_ERR_NOMEM; + goto complete; + } + + int out_len = 0; + if (EVP_EncryptUpdate(ctx, out_buf, &out_len, plaintext, plaintext_len) != 1) { + // fprintf(stderr, "cannot encrypt plaintext\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + int final_len = 0; + if (EVP_EncryptFinal_ex(ctx, out_buf + out_len, &final_len) != 1) { + // fprintf(stderr, "cannot finish encrypting plaintext\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (cipher == SG_CIPHER_AES_GCM_NOPADDING) { + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_GET_TAG, 16, out_buf + out_len + final_len) != 1) { + // fprintf(stderr, "cannot get tag\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + *output = signal_buffer_create(out_buf, out_len + final_len + buf_extra); + +complete: + EVP_CIPHER_CTX_free(ctx); + if (out_buf) { + free(out_buf); + } + return result; +} + +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 result = 0; + uint8_t *out_buf = NULL; + const EVP_CIPHER *evp_cipher = aes_cipher(cipher, key_len); + if (!evp_cipher) { + // fprintf(stderr, "invalid AES mode or key size: %zu\n", key_len); + return SG_ERR_INVAL; + } + if (ciphertext_len > INT_MAX - EVP_CIPHER_block_size(evp_cipher)) { + // fprintf(stderr, "invalid ciphertext length: %zu\n", ciphertext_len); + return SG_ERR_UNKNOWN; + } + + EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new(); + + if (cipher == SG_CIPHER_AES_GCM_NOPADDING) { + // In GCM mode we use the last 16 bytes as auth tag + ciphertext_len -= 16; + + if (EVP_DecryptInit_ex(ctx, evp_cipher, NULL, NULL, NULL) != 1) { + // fprintf(stderr, "cannot initialize cipher\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_IVLEN, iv_len, NULL) != 1) { + // fprintf(stderr, "cannot set iv size\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (EVP_DecryptInit_ex(ctx, NULL, NULL, key, iv) != 1) { + // fprintf(stderr, "cannot set key/iv\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } else { + // TODO: set ivlen? + if (EVP_DecryptInit_ex(ctx, evp_cipher, 0, key, iv) != 1) { + // fprintf(stderr, "cannot initialize cipher\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + if (cipher == SG_CIPHER_AES_CTR_NOPADDING || cipher == SG_CIPHER_AES_GCM_NOPADDING) { + if (EVP_CIPHER_CTX_set_padding(ctx, 0) != 1) { + // fprintf(stderr, "cannot set padding\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + out_buf = malloc(ciphertext_len + EVP_CIPHER_block_size(evp_cipher)); + if (!out_buf) { + // fprintf(stderr, "cannot allocate output buffer\n"); + result = SG_ERR_NOMEM; + goto complete; + } + + int out_len = 0; + if (EVP_DecryptUpdate(ctx, out_buf, &out_len, ciphertext, ciphertext_len) != 1) { + // fprintf(stderr, "cannot decrypt ciphertext\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + if (cipher == SG_CIPHER_AES_GCM_NOPADDING) { + if (EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_GCM_SET_TAG, 16, (void *)(ciphertext + ciphertext_len)) != 1) { + // fprintf(stderr, "cannot set tag\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + } + + int final_len = 0; + if (EVP_DecryptFinal_ex(ctx, out_buf + out_len, &final_len) != 1) { + // fprintf(stderr, "cannot finish decrypting ciphertexts\n"); + result = SG_ERR_UNKNOWN; + goto complete; + } + + *output = signal_buffer_create(out_buf, out_len + final_len); + +complete: + EVP_CIPHER_CTX_free(ctx); + if (out_buf) { + free(out_buf); + } + return result; +} + +void setup_signal_vala_crypto_provider(signal_context *context) { + 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, + .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/store.vala b/plugins/omemo/src/native/store.vala index b1861d93..12f22f83 100644 --- a/plugins/omemo/src/native/store.vala +++ b/plugins/omemo/src/native/store.vala @@ -107,7 +107,7 @@ public class Store : Object { 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_; }} + public 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) { diff --git a/plugins/omemo/vapi/libomemo-c.vapi b/plugins/omemo/vapi/libomemo-c.vapi index 34bb0202..8c7a2fca 100644 --- a/plugins/omemo/vapi/libomemo-c.vapi +++ b/plugins/omemo/vapi/libomemo-c.vapi @@ -689,6 +689,4 @@ namespace Omemo { [CCode (cname = "setup_signal_vala_crypto_provider", cheader_filename = "native/helper.h")] public static void setup_crypto_provider(NativeContext context); - [CCode (cname = "signal_vala_randomize", cheader_filename = "native/helper.h")] - public static int native_random(uint8[] data); } diff --git a/plugins/omemo/vapi/openssl.vapi b/plugins/omemo/vapi/openssl.vapi new file mode 100644 index 00000000..e69de29b -- cgit v1.3 From b0456e13ed35e6ebf684b3a7f4d1cb4b6ec352cc Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sat, 22 Aug 2026 19:03:26 +0200 Subject: Move crypto-vala inside libdino --- crypto-vala/crypto-vala.deps | 2 - crypto-vala/meson.build | 34 - crypto-vala/src/cipher.vala | 19 - crypto-vala/src/cipher_converter.vala | 110 --- crypto-vala/src/cipher_gcrypt.vala | 137 ---- crypto-vala/src/cipher_openssl.vala | 156 ---- crypto-vala/src/error.vala | 11 - crypto-vala/src/gcrypt.vala | 21 - crypto-vala/src/openssl.vala | 19 - crypto-vala/src/srtp.vala | 122 --- crypto-vala/vapi/libgcrypt.vapi | 872 --------------------- crypto-vala/vapi/libsrtp2.vapi | 146 ---- crypto-vala/vapi/openssl.vapi | 322 -------- libdino/dino.deps | 1 + libdino/meson.build | 25 +- libdino/src/crypto/cipher.vala | 19 + libdino/src/crypto/cipher_converter.vala | 110 +++ libdino/src/crypto/error.vala | 11 + libdino/src/crypto/gnu/cipher.vala | 137 ++++ libdino/src/crypto/gnu/utils.vala | 21 + libdino/src/crypto/openssl/cipher.vala | 156 ++++ libdino/src/crypto/openssl/utils.vala | 19 + libdino/src/crypto/srtp.vala | 122 +++ libdino/vapi/libgcrypt.vapi | 872 +++++++++++++++++++++ libdino/vapi/libsrtp2.vapi | 146 ++++ libdino/vapi/openssl.vapi | 322 ++++++++ meson.build | 32 +- meson_options.txt | 2 +- plugins/ice/meson.build | 5 +- plugins/omemo/meson.build | 5 +- .../omemo/src/file_transfer/file_decryptor.vala | 2 +- .../omemo/src/file_transfer/file_encryptor.vala | 2 +- plugins/omemo/src/jingle/jet_omemo.vala | 2 +- plugins/rtp/meson.build | 1 - 34 files changed, 1981 insertions(+), 2002 deletions(-) delete mode 100644 crypto-vala/crypto-vala.deps delete mode 100644 crypto-vala/meson.build delete mode 100644 crypto-vala/src/cipher.vala delete mode 100644 crypto-vala/src/cipher_converter.vala delete mode 100644 crypto-vala/src/cipher_gcrypt.vala delete mode 100644 crypto-vala/src/cipher_openssl.vala delete mode 100644 crypto-vala/src/error.vala delete mode 100644 crypto-vala/src/gcrypt.vala delete mode 100644 crypto-vala/src/openssl.vala delete mode 100644 crypto-vala/src/srtp.vala delete mode 100644 crypto-vala/vapi/libgcrypt.vapi delete mode 100644 crypto-vala/vapi/libsrtp2.vapi delete mode 100644 crypto-vala/vapi/openssl.vapi create mode 100644 libdino/src/crypto/cipher.vala create mode 100644 libdino/src/crypto/cipher_converter.vala create mode 100644 libdino/src/crypto/error.vala create mode 100644 libdino/src/crypto/gnu/cipher.vala create mode 100644 libdino/src/crypto/gnu/utils.vala create mode 100644 libdino/src/crypto/openssl/cipher.vala create mode 100644 libdino/src/crypto/openssl/utils.vala create mode 100644 libdino/src/crypto/srtp.vala create mode 100644 libdino/vapi/libgcrypt.vapi create mode 100644 libdino/vapi/libsrtp2.vapi create mode 100644 libdino/vapi/openssl.vapi (limited to 'plugins/ice') diff --git a/crypto-vala/crypto-vala.deps b/crypto-vala/crypto-vala.deps deleted file mode 100644 index c029e7af..00000000 --- a/crypto-vala/crypto-vala.deps +++ /dev/null @@ -1,2 +0,0 @@ -gio-2.0 -glib-2.0 diff --git a/crypto-vala/meson.build b/crypto-vala/meson.build deleted file mode 100644 index bc66fbf9..00000000 --- a/crypto-vala/meson.build +++ /dev/null @@ -1,34 +0,0 @@ -dependencies = [ - dep_gio, - dep_glib, - dep_libsrtp2, -] -sources = files( - 'src/cipher.vala', - 'src/cipher_converter.vala', - 'src/error.vala', - 'src/srtp.vala', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="crypto-vala"', -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] -if crypto_backend == 'gnutls' - dependencies += [ dep_libgcrypt ] - sources += files( - 'src/gcrypt.vala', - 'src/cipher_gcrypt.vala', - ) -else # openssl - dependencies += [ dep_openssl ] - sources += files( - 'src/openssl.vala', - 'src/cipher_openssl.vala', - ) -endif -lib_crypto_vala = library('crypto-vala', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, version: '0.0', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) -dep_crypto_vala = declare_dependency(link_with: lib_crypto_vala, include_directories: include_directories('.')) - -install_data('crypto-vala.deps', install_dir: get_option('datadir') / 'vala/vapi', install_tag: 'devel') # TODO: workaround for https://github.com/mesonbuild/meson/issues/9756 diff --git a/crypto-vala/src/cipher.vala b/crypto-vala/src/cipher.vala deleted file mode 100644 index f7aee100..00000000 --- a/crypto-vala/src/cipher.vala +++ /dev/null @@ -1,19 +0,0 @@ -namespace Crypto { - -public interface SymmetricCipher { - public abstract void set_key(uint8[] key) throws Error; - public abstract void set_iv(uint8[] iv) throws Error; - public abstract void reset() throws Error; -} - -public interface SymmetricCipherEncryption : SymmetricCipher, Object { - public abstract int encrypt(uint8[] output, uint8[] input) throws Error; - public abstract uint8[] get_tag(size_t taglen) throws Error; -} - -public interface SymmetricCipherDecryption : SymmetricCipher, Object { - public abstract int decrypt(uint8[] output, uint8[] input) throws Error; - public abstract void check_tag(uint8[] tag) throws Error; -} - -} diff --git a/crypto-vala/src/cipher_converter.vala b/crypto-vala/src/cipher_converter.vala deleted file mode 100644 index 49e7af71..00000000 --- a/crypto-vala/src/cipher_converter.vala +++ /dev/null @@ -1,110 +0,0 @@ -using GLib; - -namespace Crypto { - -public class SymmetricCipherEncrypter : Converter, Object { - private SymmetricCipherEncryption cipher; - private size_t attached_taglen; - - public SymmetricCipherEncrypter(owned SymmetricCipherEncryption cipher, size_t attached_taglen = 0) { - this.cipher = (owned) cipher; - this.attached_taglen = attached_taglen; - } - - public void reset() { - try { - cipher.reset(); - } catch (Crypto.Error e) { - warning(@"$(e.domain) error while resetting cipher: $(e.message)"); - } - } - - public uint8[] get_tag(size_t taglen) throws Error { - return ((SymmetricCipherEncryption)cipher).get_tag(taglen); - } - - public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { - if (inbuf.length > outbuf.length) { - throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); - } - if ((flags & ConverterFlags.INPUT_AT_END) != 0 && inbuf.length + attached_taglen > outbuf.length) { - throw new IOError.NO_SPACE("CipherConverter needs additional output space to attach tag"); - } - try { - if (inbuf.length > 0) { - ((SymmetricCipherEncryption)cipher).encrypt(outbuf, inbuf); - } - bytes_read = inbuf.length; - bytes_written = inbuf.length; - if ((flags & ConverterFlags.INPUT_AT_END) != 0) { - if (attached_taglen > 0) { - Memory.copy((uint8*)outbuf + inbuf.length, get_tag(attached_taglen), attached_taglen); - bytes_written = inbuf.length + attached_taglen; - } - return ConverterResult.FINISHED; - } - if ((flags & ConverterFlags.FLUSH) != 0) { - return ConverterResult.FLUSHED; - } - return ConverterResult.CONVERTED; - } catch (Crypto.Error e) { - throw new IOError.FAILED(@"$(e.domain) error while encrypting: $(e.message)"); - } - } -} - -public class SymmetricCipherDecrypter : Converter, Object { - private SymmetricCipherDecryption cipher; - private size_t attached_taglen; - - public SymmetricCipherDecrypter(owned SymmetricCipherDecryption cipher, size_t attached_taglen = 0) { - this.cipher = (owned) cipher; - this.attached_taglen = attached_taglen; - } - - public void reset() { - try { - cipher.reset(); - } catch (Crypto.Error e) { - warning(@"$(e.domain) error while resetting cipher: $(e.message)"); - } - } - - public void check_tag(uint8[] tag) throws Error { - ((SymmetricCipherDecryption)cipher).check_tag(tag); - } - - public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { - if (inbuf.length > outbuf.length + attached_taglen) { - throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); - } - if ((flags & ConverterFlags.INPUT_AT_END) != 0 && inbuf.length < attached_taglen) { - throw new IOError.PARTIAL_INPUT("CipherConverter needs additional input to read tag"); - } else if ((flags & ConverterFlags.INPUT_AT_END) == 0 && inbuf.length < attached_taglen + 1) { - throw new IOError.PARTIAL_INPUT("CipherConverter needs additional input to make sure to not accidentally read tag"); - } - try { - inbuf.length -= (int) attached_taglen; - if (inbuf.length > 0) { - ((SymmetricCipherDecryption)cipher).decrypt(outbuf, inbuf); - } - bytes_read = inbuf.length; - bytes_written = inbuf.length; - inbuf.length += (int) attached_taglen; - if ((flags & ConverterFlags.INPUT_AT_END) != 0) { - if (attached_taglen > 0) { - check_tag(inbuf[(inbuf.length - attached_taglen):inbuf.length]); - bytes_read = inbuf.length; - } - return ConverterResult.FINISHED; - } - if ((flags & ConverterFlags.FLUSH) != 0) { - return ConverterResult.FLUSHED; - } - return ConverterResult.CONVERTED; - } catch (Crypto.Error e) { - throw new IOError.FAILED(@"$(e.domain) error while decrypting: $(e.message)"); - } - } -} -} diff --git a/crypto-vala/src/cipher_gcrypt.vala b/crypto-vala/src/cipher_gcrypt.vala deleted file mode 100644 index 3e811d29..00000000 --- a/crypto-vala/src/cipher_gcrypt.vala +++ /dev/null @@ -1,137 +0,0 @@ -namespace Crypto { - -internal class SymmetricCipherGcrypt : SymmetricCipher, SymmetricCipherEncryption, SymmetricCipherDecryption, Object { - private GCrypt.Cipher.Cipher cipher; - - private static unowned string mode_to_string(GCrypt.Cipher.Mode mode) { - switch (mode) { - case GCrypt.Cipher.Mode.ECB: return "ECB"; - case GCrypt.Cipher.Mode.CFB: return "CFB"; - case GCrypt.Cipher.Mode.CBC: return "CBC"; - case GCrypt.Cipher.Mode.STREAM: return "STREAM"; - case GCrypt.Cipher.Mode.OFB: return "OFB"; - case GCrypt.Cipher.Mode.CTR: return "CTR"; - case GCrypt.Cipher.Mode.AESWRAP: return "AESWRAP"; - case GCrypt.Cipher.Mode.GCM: return "GCM"; - case GCrypt.Cipher.Mode.POLY1305: return "POLY1305"; - case GCrypt.Cipher.Mode.OCB: return "OCB"; - case GCrypt.Cipher.Mode.CFB8: return "CFB8"; - // case GCrypt.Cipher.Mode.XTS: return "XTS"; // Not supported in gcrypt < 1.8 - } - return "NONE"; - } - - private static GCrypt.Cipher.Mode mode_from_string(string name) { - switch (name) { - case "ECB": return GCrypt.Cipher.Mode.ECB; - case "CFB": return GCrypt.Cipher.Mode.CFB; - case "CBC": return GCrypt.Cipher.Mode.CBC; - case "STREAM": return GCrypt.Cipher.Mode.STREAM; - case "OFB": return GCrypt.Cipher.Mode.OFB; - case "CTR": return GCrypt.Cipher.Mode.CTR; - case "AESWRAP": return GCrypt.Cipher.Mode.AESWRAP; - case "GCM": return GCrypt.Cipher.Mode.GCM; - case "POLY1305": return GCrypt.Cipher.Mode.POLY1305; - case "OCB": return GCrypt.Cipher.Mode.OCB; - case "CFB8": return GCrypt.Cipher.Mode.CFB8; - // case "XTS": return GCrypt.Cipher.Mode.XTS; // Not supported in gcrypt < 1.8 - } - return GCrypt.Cipher.Mode.NONE; - } - - private static string flags_to_string(GCrypt.Cipher.Flag flags) { - string? s = null; - if ((GCrypt.Cipher.Flag.CBC_MAC & flags) != 0) s = (s == null ? "" : @"$s-") + "MAC"; - if ((GCrypt.Cipher.Flag.CBC_CTS & flags) != 0) s = (s == null ? "" : @"$s-") + "CTS"; - if ((GCrypt.Cipher.Flag.ENABLE_SYNC & flags) != 0) s = (s == null ? "" : @"$s-") + "SYNC"; - if ((GCrypt.Cipher.Flag.SECURE & flags) != 0) s = (s == null ? "" : @"$s-") + "SECURE"; - return s ?? "NONE"; - } - - private static GCrypt.Cipher.Flag flag_from_string(string flag_name) { - if (flag_name == "SECURE") return GCrypt.Cipher.Flag.SECURE; - if (flag_name == "SYNC") return GCrypt.Cipher.Flag.ENABLE_SYNC; - if (flag_name == "CTS") return GCrypt.Cipher.Flag.CBC_CTS; - if (flag_name == "MAC") return GCrypt.Cipher.Flag.CBC_MAC; - return 0; - } - - private static GCrypt.Cipher.Flag flags_from_string(string flag_names) { - GCrypt.Cipher.Flag flags = 0; - foreach(string flag in flag_names.split("-")) { - flags |= flag_from_string(flag); - } - return flags; - } - - private static bool parse(string algo_name, out GCrypt.Cipher.Algorithm algo, out GCrypt.Cipher.Mode mode, out GCrypt.Cipher.Flag flags) { - algo = GCrypt.Cipher.Algorithm.NONE; - mode = GCrypt.Cipher.Mode.NONE; - flags = 0; - string[] algo_parts = algo_name.split("-", 3); - - algo = GCrypt.Cipher.Algorithm.from_string(algo_parts[0]); - if (algo_parts.length >= 2) { - mode = mode_from_string(algo_parts[1]); - } - if (algo_parts.length == 3) { - flags |= flags_from_string(algo_parts[2]); - } - return to_algo_name(algo, mode, flags) == algo_name; - } - - private static string to_algo_name(GCrypt.Cipher.Algorithm algo = GCrypt.Cipher.Algorithm.NONE, GCrypt.Cipher.Mode mode = GCrypt.Cipher.Mode.NONE, GCrypt.Cipher.Flag flags = 0) { - if (flags != 0) { - return @"$algo-$(mode_to_string(mode))-$(flags_to_string(flags))"; - } else if (mode != GCrypt.Cipher.Mode.NONE) { - return @"$algo-$(mode_to_string(mode))"; - } else { - return algo.to_string(); - } - } - - public SymmetricCipherGcrypt(string algo_name) throws Error { - GCrypt.Cipher.Algorithm algo; - GCrypt.Cipher.Mode mode; - GCrypt.Cipher.Flag flags; - if (parse(algo_name, out algo, out mode, out flags)) { - may_throw_gcrypt_error(GCrypt.Cipher.Cipher.open(out this.cipher, algo, mode, flags)); - } else { - throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); - } - } - - public void set_key(uint8[] key) throws Error { - may_throw_gcrypt_error(cipher.set_key(key)); - } - - public void set_iv(uint8[] iv) throws Error { - may_throw_gcrypt_error(cipher.set_iv(iv)); - } - - public void reset() throws Error { - may_throw_gcrypt_error(cipher.reset()); - } - - public uint8[] get_tag(size_t taglen) throws Error { - uint8[] tag = new uint8[taglen]; - may_throw_gcrypt_error(cipher.get_tag(tag)); - return tag; - } - - public void check_tag(uint8[] tag) throws Error { - may_throw_gcrypt_error(cipher.check_tag(tag)); - } - - public int encrypt(uint8[] output, uint8[] input) throws Error { - may_throw_gcrypt_error(cipher.encrypt(output, input)); - return input.length; - } - - public int decrypt(uint8[] output, uint8[] input) throws Error { - may_throw_gcrypt_error(cipher.decrypt(output, input)); - return input.length; - } -} - -} diff --git a/crypto-vala/src/cipher_openssl.vala b/crypto-vala/src/cipher_openssl.vala deleted file mode 100644 index 75a0ef9a..00000000 --- a/crypto-vala/src/cipher_openssl.vala +++ /dev/null @@ -1,156 +0,0 @@ -namespace Crypto { - -internal class SymmetricCipherEncryptionOpenssl : SymmetricCipher, SymmetricCipherEncryption, Object { - private OpenSSL.EVP.CipherContext? cipher; - private bool is_finalized = false; - - public SymmetricCipherEncryptionOpenssl(string algo_name) throws Error { - if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); - cipher = new OpenSSL.EVP.CipherContext(); - } - - public void set_key(uint8[] key) throws Error { - unowned OpenSSL.EVP.Cipher algo; - if (key.length == 16) { - algo = OpenSSL.EVP.aes_128_gcm(); - } else if (key.length == 32) { - algo = OpenSSL.EVP.aes_256_gcm(); - } else { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); - } - try { - cipher.encrypt_init(algo, null, null); - cipher.encrypt_init(null, key, null); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - } - - public void set_iv(uint8[] iv) throws Error { - if (iv.length != 12) { - cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); - } - try { - cipher.encrypt_init(null, null, iv); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - } - - public void reset() throws Error { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); - } - - public uint8[] get_tag(size_t taglen) throws Error { - uint8[] tag = new uint8[taglen]; - if (!is_finalized) { - uint8[] empty = new uint8[0]; - int empty_len = 0; - try { - cipher.encrypt_final(empty, out empty_len); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - if (empty_len != 0) { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("get_tag called on a stream with remaining data"); - } - } - if (cipher.ctrl(OpenSSL.EVP.Control.GCM_GET_TAG, (int)taglen, tag) != 1) { - openssl_error(); - } - return tag; - } - - public int encrypt(uint8[] output, uint8[] input) throws Error { - int output_length = output.length; - if (is_finalized) { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("encrypt called after get_tag"); - } - try { - cipher.encrypt_update(output, out output_length, input); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - return output_length; - } -} - -internal class SymmetricCipherDecryptionOpenssl : SymmetricCipher, SymmetricCipherDecryption, Object { - private OpenSSL.EVP.CipherContext? cipher; - private bool is_finalized = false; - - public SymmetricCipherDecryptionOpenssl(string algo_name) throws Error { - if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); - cipher = new OpenSSL.EVP.CipherContext(); - try { - cipher.decrypt_init(OpenSSL.EVP.aes_128_gcm(), null, null); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - } - - public void set_key(uint8[] key) throws Error { - unowned OpenSSL.EVP.Cipher algo; - if (key.length == 16) { - algo = OpenSSL.EVP.aes_128_gcm(); - } else if (key.length == 32) { - algo = OpenSSL.EVP.aes_256_gcm(); - } else { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); - } - try { - cipher.decrypt_init(algo, null, null); - cipher.decrypt_init(null, key, null); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - } - - public void set_iv(uint8[] iv) throws Error { - if (iv.length != 12) { - cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); - } - try { - cipher.decrypt_init(null, null, iv); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - } - - public void reset() throws Error { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); - } - - public void check_tag(uint8[] tag) throws Error { - if (cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_TAG, tag.length, tag) != 1) { - openssl_error(); - } - if (!is_finalized) { - uint8[] empty = new uint8[0]; - int empty_len = 0; - try { - cipher.decrypt_final(empty, out empty_len); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - if (empty_len != 0) { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("check_tag called on a stream with remaining data"); - } - } - } - - public int decrypt(uint8[] output, uint8[] input) throws Error { - if (is_finalized) { - throw new Crypto.Error.ILLEGAL_ARGUMENTS("decrypt called after check_tag"); - } - int output_length = output.length; - try { - cipher.decrypt_update(output, out output_length, input); - } catch (GLib.Error e) { - throw new Crypto.Error.OPENSSL(e.message); - } - return output_length; - } -} - -} diff --git a/crypto-vala/src/error.vala b/crypto-vala/src/error.vala deleted file mode 100644 index a26f39c3..00000000 --- a/crypto-vala/src/error.vala +++ /dev/null @@ -1,11 +0,0 @@ -namespace Crypto { - -public errordomain Error { - ILLEGAL_ARGUMENTS, - GCRYPT, - OPENSSL, - AUTHENTICATION_FAILED, - UNKNOWN -} - -} diff --git a/crypto-vala/src/gcrypt.vala b/crypto-vala/src/gcrypt.vala deleted file mode 100644 index 1997a5e1..00000000 --- a/crypto-vala/src/gcrypt.vala +++ /dev/null @@ -1,21 +0,0 @@ -namespace Crypto { - -public static void randomize(uint8[] buffer) { - GCrypt.Random.randomize(buffer); -} - -internal void may_throw_gcrypt_error(GCrypt.Error e) throws Error { - if (((int)e) != 0) { - throw new Crypto.Error.GCRYPT(e.to_string()); - } -} - -public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { - return new SymmetricCipherGcrypt(algo_name); -} - -public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { - return new SymmetricCipherGcrypt(algo_name); -} - -} diff --git a/crypto-vala/src/openssl.vala b/crypto-vala/src/openssl.vala deleted file mode 100644 index 4a288467..00000000 --- a/crypto-vala/src/openssl.vala +++ /dev/null @@ -1,19 +0,0 @@ -namespace Crypto { - -public static void randomize(uint8[] buffer) { - OpenSSL.RAND.bytes(buffer); -} - -internal void openssl_error() throws Error { - throw new Crypto.Error.OPENSSL(OpenSSL.ERR.reason_error_string(OpenSSL.ERR.get_error())); -} - -public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { - return new SymmetricCipherEncryptionOpenssl(algo_name); -} - -public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { - return new SymmetricCipherDecryptionOpenssl(algo_name); -} - -} diff --git a/crypto-vala/src/srtp.vala b/crypto-vala/src/srtp.vala deleted file mode 100644 index 22210e37..00000000 --- a/crypto-vala/src/srtp.vala +++ /dev/null @@ -1,122 +0,0 @@ -using Srtp; - -namespace Crypto.Srtp { -public const string AES_CM_128_HMAC_SHA1_80 = "AES_CM_128_HMAC_SHA1_80"; -public const string AES_CM_128_HMAC_SHA1_32 = "AES_CM_128_HMAC_SHA1_32"; -public const string F8_128_HMAC_SHA1_80 = "F8_128_HMAC_SHA1_80"; - -public class Session { - public bool has_encrypt { get; private set; default = false; } - public bool has_decrypt { get; private set; default = false; } - - private Context encrypt_context; - private Context decrypt_context; - - static construct { - init(); - install_log_handler(log); - } - - private static void log(LogLevel level, string msg) { - print(@"SRTP[$level]: $msg\n"); - } - - public Session() { - Context.create(out encrypt_context, null); - Context.create(out decrypt_context, null); - } - - public uint8[] encrypt_rtp(uint8[] data) throws Error { - uint8[] buf = new uint8[data.length + MAX_TRAILER_LEN]; - Memory.copy(buf, data, data.length); - int buf_use = data.length; - ErrorStatus res = encrypt_context.protect(buf, ref buf_use); - if (res != ErrorStatus.ok) { - throw new Error.UNKNOWN(@"SRTP encrypt failed: $res"); - } - buf.length = buf_use; - return buf; - } - - public uint8[] decrypt_rtp(uint8[] data) throws Error { - uint8[] buf = new uint8[data.length]; - Memory.copy(buf, data, data.length); - int buf_use = data.length; - ErrorStatus res = decrypt_context.unprotect(buf, ref buf_use); - switch (res) { - case ErrorStatus.auth_fail: - throw new Error.AUTHENTICATION_FAILED("SRTP packet failed the message authentication check"); - case ErrorStatus.ok: - break; - default: - throw new Error.UNKNOWN(@"SRTP decrypt failed: $res"); - } - uint8[] ret = new uint8[buf_use]; - GLib.Memory.copy(ret, buf, buf_use); - return ret; - } - - public uint8[] encrypt_rtcp(uint8[] data) throws Error { - uint8[] buf = new uint8[data.length + MAX_TRAILER_LEN + 4]; - Memory.copy(buf, data, data.length); - int buf_use = data.length; - ErrorStatus res = encrypt_context.protect_rtcp(buf, ref buf_use); - if (res != ErrorStatus.ok) { - throw new Error.UNKNOWN(@"SRTCP encrypt failed: $res"); - } - buf.length = buf_use; - return buf; - } - - public uint8[] decrypt_rtcp(uint8[] data) throws Error { - uint8[] buf = new uint8[data.length]; - Memory.copy(buf, data, data.length); - int buf_use = data.length; - ErrorStatus res = decrypt_context.unprotect_rtcp(buf, ref buf_use); - switch (res) { - case ErrorStatus.auth_fail: - throw new Error.AUTHENTICATION_FAILED("SRTCP packet failed the message authentication check"); - case ErrorStatus.ok: - break; - default: - throw new Error.UNKNOWN(@"SRTCP decrypt failed: $res"); - } - uint8[] ret = new uint8[buf_use]; - GLib.Memory.copy(ret, buf, buf_use); - return ret; - } - - private Policy create_policy(string profile) { - Policy policy = Policy(); - switch (profile) { - case AES_CM_128_HMAC_SHA1_80: - policy.rtp.set_aes_cm_128_hmac_sha1_80(); - policy.rtcp.set_aes_cm_128_hmac_sha1_80(); - break; - } - return policy; - } - - public void set_encryption_key(string profile, uint8[] key, uint8[] salt) { - Policy policy = create_policy(profile); - policy.ssrc.type = SsrcType.any_outbound; - policy.key = new uint8[key.length + salt.length]; - Memory.copy(policy.key, key, key.length); - Memory.copy(((uint8*)policy.key) + key.length, salt, salt.length); - policy.next = null; - encrypt_context.add_stream(ref policy); - has_encrypt = true; - } - - public void set_decryption_key(string profile, uint8[] key, uint8[] salt) { - Policy policy = create_policy(profile); - policy.ssrc.type = SsrcType.any_inbound; - policy.key = new uint8[key.length + salt.length]; - Memory.copy(policy.key, key, key.length); - Memory.copy(((uint8*)policy.key) + key.length, salt, salt.length); - policy.next = null; - decrypt_context.add_stream(ref policy); - has_decrypt = true; - } -} -} \ No newline at end of file diff --git a/crypto-vala/vapi/libgcrypt.vapi b/crypto-vala/vapi/libgcrypt.vapi deleted file mode 100644 index 0fa69a02..00000000 --- a/crypto-vala/vapi/libgcrypt.vapi +++ /dev/null @@ -1,872 +0,0 @@ -/* gcrypt.vapi - * - * Copyright: - * 2008 Jiqing Qiang - * 2008, 2010, 2012-2013 Evan Nemerson - * - * This library is free software; you can redistribute it and/or - * modify it under the terms of the GNU Lesser General Public - * License as published by the Free Software Foundation; either - * version 2.1 of the License, or (at your option) any later version. - - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU - * Lesser General Public License for more details. - - * You should have received a copy of the GNU Lesser General Public - * License along with this library; if not, write to the Free Software - * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - * - * Author: - * Jiqing Qiang - * Evan Nemerson - */ - - -[CCode (cheader_filename = "gcrypt.h", lower_case_cprefix = "gcry_")] -namespace GCrypt { - [CCode (cname = "gpg_err_source_t", cprefix = "GPG_ERR_SOURCE_")] - public enum ErrorSource { - UNKNOWN, - GCRYPT, - GPG, - GPGSM, - GPGAGENT, - PINENTRY, - SCD, - GPGME, - KEYBOX, - KSBA, - DIRMNGR, - GSTI, - ANY, - USER_1, - USER_2, - USER_3, - USER_4, - - /* This is one more than the largest allowed entry. */ - DIM - } - - [CCode (cname = "gpg_err_code_t", cprefix = "GPG_ERR_")] - public enum ErrorCode { - NO_ERROR, - GENERAL, - UNKNOWN_PACKET, - UNKNOWN_VERSION, - PUBKEY_ALGO, - DIGEST_ALGO, - BAD_PUBKEY, - BAD_SECKEY, - BAD_SIGNATURE, - NO_PUBKEY, - CHECKSUM, - BAD_PASSPHRASE, - CIPHER_ALGO, - KEYRING_OPEN, - INV_PACKET, - INV_ARMOR, - NO_USER_ID, - NO_SECKEY, - WRONG_SECKEY, - BAD_KEY, - COMPR_ALGO, - NO_PRIME, - NO_ENCODING_METHOD, - NO_ENCRYPTION_SCHEME, - NO_SIGNATURE_SCHEME, - INV_ATTR, - NO_VALUE, - NOT_FOUND, - VALUE_NOT_FOUND, - SYNTAX, - BAD_MPI, - INV_PASSPHRASE, - SIG_CLASS, - RESOURCE_LIMIT, - INV_KEYRING, - TRUSTDB, - BAD_CERT, - INV_USER_ID, - UNEXPECTED, - TIME_CONFLICT, - KEYSERVER, - WRONG_PUBKEY_ALGO, - TRIBUTE_TO_D_A, - WEAK_KEY, - INV_KEYLEN, - INV_ARG, - BAD_URI, - INV_URI, - NETWORK, - UNKNOWN_HOST, - SELFTEST_FAILED, - NOT_ENCRYPTED, - NOT_PROCESSED, - UNUSABLE_PUBKEY, - UNUSABLE_SECKEY, - INV_VALUE, - BAD_CERT_CHAIN, - MISSING_CERT, - NO_DATA, - BUG, - NOT_SUPPORTED, - INV_OP, - TIMEOUT, - INTERNAL, - EOF_GCRYPT, - INV_OBJ, - TOO_SHORT, - TOO_LARGE, - NO_OBJ, - NOT_IMPLEMENTED, - CONFLICT, - INV_CIPHER_MODE, - INV_FLAG, - INV_HANDLE, - TRUNCATED, - INCOMPLETE_LINE, - INV_RESPONSE, - NO_AGENT, - AGENT, - INV_DATA, - ASSUAN_SERVER_FAULT, - ASSUAN, - INV_SESSION_KEY, - INV_SEXP, - UNSUPPORTED_ALGORITHM, - NO_PIN_ENTRY, - PIN_ENTRY, - BAD_PIN, - INV_NAME, - BAD_DATA, - INV_PARAMETER, - WRONG_CARD, - NO_DIRMNGR, - DIRMNGR, - CERT_REVOKED, - NO_CRL_KNOWN, - CRL_TOO_OLD, - LINE_TOO_LONG, - NOT_TRUSTED, - CANCELED, - BAD_CA_CERT, - CERT_EXPIRED, - CERT_TOO_YOUNG, - UNSUPPORTED_CERT, - UNKNOWN_SEXP, - UNSUPPORTED_PROTECTION, - CORRUPTED_PROTECTION, - AMBIGUOUS_NAME, - CARD, - CARD_RESET, - CARD_REMOVED, - INV_CARD, - CARD_NOT_PRESENT, - NO_PKCS15_APP, - NOT_CONFIRMED, - CONFIGURATION, - NO_POLICY_MATCH, - INV_INDEX, - INV_ID, - NO_SCDAEMON, - SCDAEMON, - UNSUPPORTED_PROTOCOL, - BAD_PIN_METHOD, - CARD_NOT_INITIALIZED, - UNSUPPORTED_OPERATION, - WRONG_KEY_USAGE, - NOTHING_FOUND, - WRONG_BLOB_TYPE, - MISSING_VALUE, - HARDWARE, - PIN_BLOCKED, - USE_CONDITIONS, - PIN_NOT_SYNCED, - INV_CRL, - BAD_BER, - INV_BER, - ELEMENT_NOT_FOUND, - IDENTIFIER_NOT_FOUND, - INV_TAG, - INV_LENGTH, - INV_KEYINFO, - UNEXPECTED_TAG, - NOT_DER_ENCODED, - NO_CMS_OBJ, - INV_CMS_OBJ, - UNKNOWN_CMS_OBJ, - UNSUPPORTED_CMS_OBJ, - UNSUPPORTED_ENCODING, - UNSUPPORTED_CMS_VERSION, - UNKNOWN_ALGORITHM, - INV_ENGINE, - PUBKEY_NOT_TRUSTED, - DECRYPT_FAILED, - KEY_EXPIRED, - SIG_EXPIRED, - ENCODING_PROBLEM, - INV_STATE, - DUP_VALUE, - MISSING_ACTION, - MODULE_NOT_FOUND, - INV_OID_STRING, - INV_TIME, - INV_CRL_OBJ, - UNSUPPORTED_CRL_VERSION, - INV_CERT_OBJ, - UNKNOWN_NAME, - LOCALE_PROBLEM, - NOT_LOCKED, - PROTOCOL_VIOLATION, - INV_MAC, - INV_REQUEST, - UNKNOWN_EXTN, - UNKNOWN_CRIT_EXTN, - LOCKED, - UNKNOWN_OPTION, - UNKNOWN_COMMAND, - BUFFER_TOO_SHORT, - SEXP_INV_LEN_SPEC, - SEXP_STRING_TOO_LONG, - SEXP_UNMATCHED_PAREN, - SEXP_NOT_CANONICAL, - SEXP_BAD_CHARACTER, - SEXP_BAD_QUOTATION, - SEXP_ZERO_PREFIX, - SEXP_NESTED_DH, - SEXP_UNMATCHED_DH, - SEXP_UNEXPECTED_PUNC, - SEXP_BAD_HEX_CHAR, - SEXP_ODD_HEX_NUMBERS, - SEXP_BAD_OCT_CHAR, - ASS_GENERAL, - ASS_ACCEPT_FAILED, - ASS_CONNECT_FAILED, - ASS_INV_RESPONSE, - ASS_INV_VALUE, - ASS_INCOMPLETE_LINE, - ASS_LINE_TOO_LONG, - ASS_NESTED_COMMANDS, - ASS_NO_DATA_CB, - ASS_NO_INQUIRE_CB, - ASS_NOT_A_SERVER, - ASS_NOT_A_CLIENT, - ASS_SERVER_START, - ASS_READ_ERROR, - ASS_WRITE_ERROR, - ASS_TOO_MUCH_DATA, - ASS_UNEXPECTED_CMD, - ASS_UNKNOWN_CMD, - ASS_SYNTAX, - ASS_CANCELED, - ASS_NO_INPUT, - ASS_NO_OUTPUT, - ASS_PARAMETER, - ASS_UNKNOWN_INQUIRE, - USER_1, - USER_2, - USER_3, - USER_4, - USER_5, - USER_6, - USER_7, - USER_8, - USER_9, - USER_10, - USER_11, - USER_12, - USER_13, - USER_14, - USER_15, - USER_16, - MISSING_ERRNO, - UNKNOWN_ERRNO, - EOF, - - E2BIG, - EACCES, - EADDRINUSE, - EADDRNOTAVAIL, - EADV, - EAFNOSUPPORT, - EAGAIN, - EALREADY, - EAUTH, - EBACKGROUND, - EBADE, - EBADF, - EBADFD, - EBADMSG, - EBADR, - EBADRPC, - EBADRQC, - EBADSLT, - EBFONT, - EBUSY, - ECANCELED, - ECHILD, - ECHRNG, - ECOMM, - ECONNABORTED, - ECONNREFUSED, - ECONNRESET, - ED, - EDEADLK, - EDEADLOCK, - EDESTADDRREQ, - EDIED, - EDOM, - EDOTDOT, - EDQUOT, - EEXIST, - EFAULT, - EFBIG, - EFTYPE, - EGRATUITOUS, - EGREGIOUS, - EHOSTDOWN, - EHOSTUNREACH, - EIDRM, - EIEIO, - EILSEQ, - EINPROGRESS, - EINTR, - EINVAL, - EIO, - EISCONN, - EISDIR, - EISNAM, - EL2HLT, - EL2NSYNC, - EL3HLT, - EL3RST, - ELIBACC, - ELIBBAD, - ELIBEXEC, - ELIBMAX, - ELIBSCN, - ELNRNG, - ELOOP, - EMEDIUMTYPE, - EMFILE, - EMLINK, - EMSGSIZE, - EMULTIHOP, - ENAMETOOLONG, - ENAVAIL, - ENEEDAUTH, - ENETDOWN, - ENETRESET, - ENETUNREACH, - ENFILE, - ENOANO, - ENOBUFS, - ENOCSI, - ENODATA, - ENODEV, - ENOENT, - ENOEXEC, - ENOLCK, - ENOLINK, - ENOMEDIUM, - ENOMEM, - ENOMSG, - ENONET, - ENOPKG, - ENOPROTOOPT, - ENOSPC, - ENOSR, - ENOSTR, - ENOSYS, - ENOTBLK, - ENOTCONN, - ENOTDIR, - ENOTEMPTY, - ENOTNAM, - ENOTSOCK, - ENOTSUP, - ENOTTY, - ENOTUNIQ, - ENXIO, - EOPNOTSUPP, - EOVERFLOW, - EPERM, - EPFNOSUPPORT, - EPIPE, - EPROCLIM, - EPROCUNAVAIL, - EPROGMISMATCH, - EPROGUNAVAIL, - EPROTO, - EPROTONOSUPPORT, - EPROTOTYPE, - ERANGE, - EREMCHG, - EREMOTE, - EREMOTEIO, - ERESTART, - EROFS, - ERPCMISMATCH, - ESHUTDOWN, - ESOCKTNOSUPPORT, - ESPIPE, - ESRCH, - ESRMNT, - ESTALE, - ESTRPIPE, - ETIME, - ETIMEDOUT, - ETOOMANYREFS, - ETXTBSY, - EUCLEAN, - EUNATCH, - EUSERS, - EWOULDBLOCK, - EXDEV, - EXFULL, - - /* This is one more than the largest allowed entry. */ - CODE_DIM - } - - [CCode (cname = "gcry_error_t", cprefix = "gpg_err_")] - public struct Error : uint { - [CCode (cname = "gcry_err_make")] - public Error (ErrorSource source, ErrorCode code); - [CCode (cname = "gcry_err_make_from_errno")] - public Error.from_errno (ErrorSource source, int err); - public ErrorCode code (); - public ErrorSource source (); - - [CCode (cname = "gcry_strerror")] - public unowned string to_string (); - - [CCode (cname = "gcry_strsource")] - public unowned string source_to_string (); - } - - [CCode (cname = "enum gcry_ctl_cmds", cprefix = "GCRYCTL_")] - public enum ControlCommand { - SET_KEY, - SET_IV, - CFB_SYNC, - RESET, - FINALIZE, - GET_KEYLEN, - GET_BLKLEN, - TEST_ALGO, - IS_SECURE, - GET_ASNOID, - ENABLE_ALGO, - DISABLE_ALGO, - DUMP_RANDOM_STATS, - DUMP_SECMEM_STATS, - GET_ALGO_NPKEY, - GET_ALGO_NSKEY, - GET_ALGO_NSIGN, - GET_ALGO_NENCR, - SET_VERBOSITY, - SET_DEBUG_FLAGS, - CLEAR_DEBUG_FLAGS, - USE_SECURE_RNDPOOL, - DUMP_MEMORY_STATS, - INIT_SECMEM, - TERM_SECMEM, - DISABLE_SECMEM_WARN, - SUSPEND_SECMEM_WARN, - RESUME_SECMEM_WARN, - DROP_PRIVS, - ENABLE_M_GUARD, - START_DUMP, - STOP_DUMP, - GET_ALGO_USAGE, - IS_ALGO_ENABLED, - DISABLE_INTERNAL_LOCKING, - DISABLE_SECMEM, - INITIALIZATION_FINISHED, - INITIALIZATION_FINISHED_P, - ANY_INITIALIZATION_P, - SET_CBC_CTS, - SET_CBC_MAC, - SET_CTR, - ENABLE_QUICK_RANDOM, - SET_RANDOM_SEED_FILE, - UPDATE_RANDOM_SEED_FILE, - SET_THREAD_CBS, - FAST_POLL - } - public Error control (ControlCommand cmd, ...); - - [CCode (lower_case_cname = "cipher_")] - namespace Cipher { - [CCode (cname = "enum gcry_cipher_algos", cprefix = "GCRY_CIPHER_")] - public enum Algorithm { - NONE, - IDEA, - 3DES, - CAST5, - BLOWFISH, - SAFER_SK128, - DES_SK, - AES, - AES128, - RIJNDAEL, - RIJNDAEL128, - AES192, - RIJNDAEL192, - AES256, - RIJNDAEL256, - TWOFISH, - TWOFISH128, - ARCFOUR, - DES, - SERPENT128, - SERPENT192, - SERPENT256, - RFC2268_40, - RFC2268_128, - SEED, - CAMELLIA128, - CAMELLIA192, - CAMELLIA256, - SALSA20, - SALSA20R12, - GOST28147, - CHACHA20; - - [CCode (cname = "gcry_cipher_algo_info")] - public Error info (ControlCommand what, ref uchar[] buffer); - [CCode (cname = "gcry_cipher_algo_name")] - public unowned string to_string (); - [CCode (cname = "gcry_cipher_map_name")] - public static Algorithm from_string (string name); - [CCode (cname = "gcry_cipher_map_oid")] - public static Algorithm from_oid (string oid); - } - - [CCode (cname = "enum gcry_cipher_modes", cprefix = "GCRY_CIPHER_MODE_")] - public enum Mode { - NONE, /* No mode specified */ - ECB, /* Electronic Codebook */ - CFB, /* Cipher Feedback */ - CBC, /* Cipher Block Chaining */ - STREAM, /* Used with stream ciphers */ - OFB, /* Output Feedback */ - CTR, /* Counter */ - AESWRAP, /* AES-WRAP algorithm */ - CCM, /* Counter with CBC-MAC */ - GCM, /* Galois/Counter Mode */ - POLY1305, /* Poly1305 based AEAD mode */ - OCB, /* OCB3 mode */ - CFB8, /* Cipher Feedback /* Poly1305 based AEAD mode. */ - XTS; /* XTS mode */ - - public unowned string to_string () { - switch (this) { - case ECB: return "ECB"; - case CFB: return "CFB"; - case CBC: return "CBC"; - case STREAM: return "STREAM"; - case OFB: return "OFB"; - case CTR: return "CTR"; - case AESWRAP: return "AESWRAP"; - case GCM: return "GCM"; - case POLY1305: return "POLY1305"; - case OCB: return "OCB"; - case CFB8: return "CFB8"; - case XTS: return "XTS"; - } - return "NONE"; - } - - public static Mode from_string (string name) { - switch (name) { - case "ECB": return ECB; - case "CFB": return CFB; - case "CBC": return CBC; - case "STREAM": return STREAM; - case "OFB": return OFB; - case "CTR": return CTR; - case "AESWRAP": return AESWRAP; - case "GCM": return GCM; - case "POLY1305": return POLY1305; - case "OCB": return OCB; - case "CFB8": return CFB8; - case "XTS": return XTS; - } - return NONE; - } - } - - [CCode (cname = "enum gcry_cipher_flags", cprefix = "GCRY_CIPHER_")] - public enum Flag { - SECURE, /* Allocate in secure memory. */ - ENABLE_SYNC, /* Enable CFB sync mode. */ - CBC_CTS, /* Enable CBC cipher text stealing (CTS). */ - CBC_MAC /* Enable CBC message auth. code (MAC). */ - } - [CCode (cname = "gcry_cipher_hd_t", lower_case_cprefix = "gcry_cipher_", free_function = "gcry_cipher_close")] - [SimpleType] - public struct Cipher { - public static Error open (out Cipher cipher, Algorithm algo, Mode mode, Flag flags); - public void close (); - [CCode (cname = "gcry_cipher_ctl")] - public Error control (ControlCommand cmd, uchar[] buffer); - public Error info (ControlCommand what, ref uchar[] buffer); - - public Error encrypt (uchar[] out_buffer, uchar[] in_buffer); - public Error decrypt (uchar[] out_buffer, uchar[] in_buffer); - - [CCode (cname = "gcry_cipher_setkey")] - public Error set_key (uchar[] key_data); - [CCode (cname = "gcry_cipher_setiv")] - public Error set_iv (uchar[] iv_data); - [CCode (cname = "gcry_cipher_setctr")] - public Error set_counter_vector (uchar[] counter_vector); - - [CCode (cname = "gcry_cipher_gettag")] - public Error get_tag(uchar[] out_buffer); - [CCode (cname = "gcry_cipher_checktag")] - public Error check_tag(uchar[] in_buffer); - - public Error reset (); - public Error sync (); - } - } - - [Compact, CCode (cname = "struct gcry_md_handle", cprefix = "gcry_md_", free_function = "gcry_md_close")] - public class Hash { - [CCode (cname = "enum gcry_md_algos", cprefix = "GCRY_MD_")] - public enum Algorithm { - NONE, - SHA1, - RMD160, - MD5, - MD4, - MD2, - TIGER, - TIGER1, - TIGER2, - HAVAL, - SHA224, - SHA256, - SHA384, - SHA512, - SHA3_224, - SHA3_256, - SHA3_384, - SHA3_512, - SHAKE128, - SHAKE256, - CRC32, - CRC32_RFC1510, - CRC24_RFC2440, - WHIRLPOOL, - GOSTR3411_94, - STRIBOG256, - STRIBOG512; - - [CCode (cname = "gcry_md_get_algo_dlen")] - public size_t get_digest_length (); - [CCode (cname = "gcry_md_algo_info")] - public Error info (ControlCommand what, ref uchar[] buffer); - [CCode (cname = "gcry_md_algo_name")] - public unowned string to_string (); - [CCode (cname = "gcry_md_map_name")] - public static Algorithm from_string (string name); - [CCode (cname = "gcry_md_test_algo")] - public Error is_available (); - [CCode (cname = "gcry_md_get_asnoid")] - public Error get_oid (uchar[] buffer); - } - - [CCode (cname = "enum gcry_md_flags", cprefix = "GCRY_MD_FLAG_")] - public enum Flag { - SECURE, - HMAC, - BUGEMU1 - } - - public static Error open (out Hash hash, Algorithm algo, Flag flag); - public void close (); - public Error enable (Algorithm algo); - [CCode (instance_pos = -1)] - public Error copy (out Hash dst); - public void reset (); - [CCode (cname = "enum gcry_md_ctl")] - public Error control (ControlCommand cmd, uchar[] buffer); - public void write (uchar[] buffer); - [CCode (array_length = false)] - public unowned uchar[] read (Algorithm algo); - public static void hash_buffer (Algorithm algo, [CCode (array_length = false)] uchar[] digest, uchar[] buffer); - public Algorithm get_algo (); - public bool is_enabled (Algorithm algo); - public bool is_secure (); - public Error info (ControlCommand what, uchar[] buffer); - [CCode (cname = "gcry_md_setkey")] - public Error set_key (uchar[] key_data); - public void putc (char c); - public void final (); - public static Error list (ref Algorithm[] algos); - } - - namespace Random { - [CCode (cname = "gcry_random_level_t")] - public enum Level { - [CCode (cname = "GCRY_WEAK_RANDOM")] - WEAK, - [CCode (cname = "GCRY_STRONG_RANDOM")] - STRONG, - [CCode (cname = "GCRY_VERY_STRONG_RANDOM")] - VERY_STRONG - } - - [CCode (cname = "gcry_randomize")] - public static void randomize (uchar[] buffer, Level level = Level.VERY_STRONG); - [CCode (cname = "gcry_fast_random_poll")] - public static Error poll (); - [CCode (cname = "gcry_random_bytes", array_length = false)] - public static uchar[] random_bytes (size_t nbytes, Level level = Level.VERY_STRONG); - [CCode (cname = "gcry_random_bytes_secure")] - public static uchar[] random_bytes_secure (size_t nbytes, Level level = Level.VERY_STRONG); - [CCode (cname = "gcry_create_nonce")] - public static void nonce (uchar[] buffer); - } - - [Compact, CCode (cname = "struct gcry_mpi", cprefix = "gcry_mpi_", free_function = "gcry_mpi_release")] - public class MPI { - [CCode (cname = "enum gcry_mpi_format", cprefix = "GCRYMPI_FMT_")] - public enum Format { - NONE, - STD, - PGP, - SSH, - HEX, - USG - } - - [CCode (cname = "enum gcry_mpi_flag", cprefix = "GCRYMPI_FLAG_")] - public enum Flag { - SECURE, - OPAQUE - } - - public MPI (uint nbits); - [CCode (cname = "gcry_mpi_snew")] - public MPI.secure (uint nbits); - public MPI copy (); - public void set (MPI u); - public void set_ui (ulong u); - public void swap (); - public int cmp (MPI v); - public int cmp_ui (ulong v); - - public static Error scan (out MPI ret, MPI.Format format, [CCode (array_length = false)] uchar[] buffer, size_t buflen, out size_t nscanned); - [CCode (instance_pos = -1)] - public Error print (MPI.Format format, [CCode (array_length = false)] uchar[] buffer, size_t buflen, out size_t nwritter); - [CCode (instance_pos = -1)] - public Error aprint (MPI.Format format, out uchar[] buffer); - - public void add (MPI u, MPI v); - public void add_ui (MPI u, ulong v); - public void addm (MPI u, MPI v, MPI m); - public void sub (MPI u, MPI v); - public void sub_ui (MPI u, MPI v); - public void subm (MPI u, MPI v, MPI m); - public void mul (MPI u, MPI v); - public void mul_ui (MPI u, ulong v); - public void mulm (MPI u, MPI v, MPI m); - public void mul_2exp (MPI u, ulong cnt); - public void div (MPI q, MPI r, MPI dividend, MPI divisor, int round); - public void mod (MPI dividend, MPI divisor); - public void powm (MPI b, MPI e, MPI m); - public int gcd (MPI a, MPI b); - public int invm (MPI a, MPI m); - - public uint get_nbits (); - public int test_bit (uint n); - public void set_bit (uint n); - public void clear_bit (uint n); - public void set_highbit (uint n); - public void clear_highbit (uint n); - public void rshift (MPI a, uint n); - public void lshift (MPI a, uint n); - - public void set_flag (MPI.Flag flag); - public void clear_flag (MPI.Flag flag); - public int get_flag (MPI.Flag flag); - } - - [Compact, CCode (cname = "struct gcry_sexp", free_function = "gcry_sexp_release")] - public class SExp { - [CCode (cprefix = "GCRYSEXP_FMT_")] - public enum Format { - DEFAULT, - CANON, - BASE64, - ADVANCED - } - - public static Error @new (out SExp retsexp, void * buffer, size_t length, int autodetect); - public static Error create (out SExp retsexp, void * buffer, size_t length, int autodetect, GLib.DestroyNotify free_function); - public static Error sscan (out SExp retsexp, out size_t erroff, char[] buffer); - public static Error build (out SExp retsexp, out size_t erroff, string format, ...); - public size_t sprint (Format mode, char[] buffer); - public static size_t canon_len (uchar[] buffer, out size_t erroff, out int errcode); - public SExp find_token (string token, size_t token_length = 0); - public int length (); - public SExp? nth (int number); - public SExp? car (); - public SExp? cdr (); - public unowned char[] nth_data (int number); - public gcry_string nth_string (int number); - public MPI nth_mpi (int number, MPI.Format mpifmt); - } - - [CCode (cname = "char", free_function = "gcry_free")] - public class gcry_string : string { } - - [CCode (lower_case_cprefix = "gcry_pk_")] - namespace PublicKey { - [CCode (cname = "enum gcry_pk_algos")] - public enum Algorithm { - RSA, - ELG_E, - DSA, - ELG, - ECDSA; - - [CCode (cname = "gcry_pk_algo_name")] - public unowned string to_string (); - [CCode (cname = "gcry_pk_map_name")] - public static Algorithm map_name (string name); - } - - public static Error encrypt (out SExp ciphertext, SExp data, SExp pkey); - public static Error decrypt (out SExp plaintext, SExp data, SExp skey); - public static Error sign (out SExp signature, SExp data, SExp skey); - public static Error verify (SExp signature, SExp data, SExp pkey); - public static Error testkey (SExp key); - public static Error genkey (out SExp r_key, SExp s_params); - public static uint get_nbits (SExp key); - } - - [CCode (lower_case_cprefix = "gcry_kdf_")] - namespace KeyDerivation { - [CCode (cname = "gcry_kdf_algos", cprefix = "GCRY_KDF_", has_type_id = false)] - public enum Algorithm { - NONE, - SIMPLE_S2K, - SALTED_S2K, - ITERSALTED_S2K, - PBKDF1, - PBKDF2, - SCRYPT - } - - public GCrypt.Error derive ([CCode (type = "const void*", array_length_type = "size_t")] uint8[] passphrasse, GCrypt.KeyDerivation.Algorithm algo, GCrypt.Hash.Algorithm subalgo, [CCode (type = "const void*", array_length_type = "size_t")] uint8[] salt, ulong iterations, [CCode (type = "void*", array_length_type = "size_t", array_length_pos = 5.5)] uint8[] keybuffer); - } -} diff --git a/crypto-vala/vapi/libsrtp2.vapi b/crypto-vala/vapi/libsrtp2.vapi deleted file mode 100644 index f8f2d297..00000000 --- a/crypto-vala/vapi/libsrtp2.vapi +++ /dev/null @@ -1,146 +0,0 @@ -[CCode (cheader_filename = "srtp2/srtp.h")] -namespace Srtp { -public const uint MAX_TRAILER_LEN; - -public static ErrorStatus init(); -public static ErrorStatus shutdown(); - -[Compact] -[CCode (cname = "srtp_ctx_t", cprefix = "srtp_", free_function = "srtp_dealloc")] -public class Context { - public static ErrorStatus create(out Context session, Policy? policy); - - public ErrorStatus protect([CCode (type = "void*", array_length = false)] uint8[] rtp, ref int len); - public ErrorStatus unprotect([CCode (type = "void*", array_length = false)] uint8[] rtp, ref int len); - - public ErrorStatus protect_rtcp([CCode (type = "void*", array_length = false)] uint8[] rtcp, ref int len); - public ErrorStatus unprotect_rtcp([CCode (type = "void*", array_length = false)] uint8[] rtcp, ref int len); - - public ErrorStatus add_stream(ref Policy policy); - public ErrorStatus update_stream(ref Policy policy); - public ErrorStatus remove_stream(uint ssrc); - public ErrorStatus update(ref Policy policy); -} - -[CCode (cname = "srtp_ssrc_t")] -public struct Ssrc { - public SsrcType type; - public uint value; -} - -[CCode (cname = "srtp_ssrc_type_t", cprefix = "ssrc_")] -public enum SsrcType { - undefined, specific, any_inbound, any_outbound -} - -[CCode (cname = "srtp_policy_t", destroy_function = "")] -public struct Policy { - public Ssrc ssrc; - public CryptoPolicy rtp; - public CryptoPolicy rtcp; - [CCode (array_length = false)] - public uint8[] key; - public ulong num_master_keys; - public ulong window_size; - [CCode (ctype = "int")] - public bool allow_repeat_tx; - [CCode (array_length_cname = "enc_xtn_hdr_count")] - public int[] enc_xtn_hdr; - public Policy* next; -} - -[CCode (cname = "srtp_crypto_policy_t")] -public struct CryptoPolicy { - public CipherType cipher_type; - public int cipher_key_len; - public AuthType auth_type; - public int auth_key_len; - public int auth_tag_len; - public SecurityServices sec_serv; - - public void set_aes_cm_128_hmac_sha1_80(); - public void set_aes_cm_128_hmac_sha1_32(); - public void set_aes_cm_128_null_auth(); - public void set_aes_cm_192_hmac_sha1_32(); - public void set_aes_cm_192_hmac_sha1_80(); - public void set_aes_cm_192_null_auth(); - public void set_aes_cm_256_hmac_sha1_32(); - public void set_aes_cm_256_hmac_sha1_80(); - public void set_aes_cm_256_null_auth(); - public void set_aes_gcm_128_16_auth(); - public void set_aes_gcm_128_8_auth(); - public void set_aes_gcm_128_8_only_auth(); - public void set_aes_gcm_256_16_auth(); - public void set_aes_gcm_256_8_auth(); - public void set_aes_gcm_256_8_only_auth(); - public void set_null_cipher_hmac_null(); - public void set_null_cipher_hmac_sha1_80(); - - public void set_rtp_default(); - public void set_rtcp_default(); - - public void set_from_profile_for_rtp(Profile profile); - public void set_from_profile_for_rtcp(Profile profile); -} - -[CCode (cname = "srtp_profile_t", cprefix = "srtp_profile_")] -public enum Profile { - reserved, aes128_cm_sha1_80, aes128_cm_sha1_32, null_sha1_80, null_sha1_32, aead_aes_128_gcm, aead_aes_256_gcm -} - -[CCode (cname = "srtp_cipher_type_id_t")] -public struct CipherType : uint32 {} - -[CCode (cname = "srtp_auth_type_id_t")] -public struct AuthType : uint32 {} - -[CCode (cname = "srtp_sec_serv_t", cprefix = "sec_serv_")] -public enum SecurityServices { - none, conf, auth, conf_and_auth; -} - -[CCode (cname = "srtp_err_status_t", cprefix = "srtp_err_status_", has_type_id = false)] -public enum ErrorStatus { - ok, - fail, - bad_param, - alloc_fail, - dealloc_fail, - init_fail, - terminus, - auth_fail, - cipher_fail, - replay_fail, - replay_old, - - algo_fail, - no_such_op, - no_ctx, - cant_check, - key_expired, - socket_err, - signal_err, - nonce_bad, - read_fail, - write_fail, - - parse_err, - encode_err, - semaphore_err, - pfkey_err, - bad_mki, - pkt_idx_old, - pkt_idx_adv -} - -[CCode (cname = "srtp_log_level_t", cprefix = "srtp_log_level_", has_type_id = false)] -public enum LogLevel { - error, warning, info, debug -} - -[CCode (cname = "srtp_log_handler_func_t")] -public delegate void LogHandler(LogLevel level, string msg); - -public static ErrorStatus install_log_handler(LogHandler func); - -} \ No newline at end of file diff --git a/crypto-vala/vapi/openssl.vapi b/crypto-vala/vapi/openssl.vapi deleted file mode 100644 index 87693d37..00000000 --- a/crypto-vala/vapi/openssl.vapi +++ /dev/null @@ -1,322 +0,0 @@ -[CCode (cprefix = "")] -namespace OpenSSL { - [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")] - namespace ASN1 { - [Compact] - [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")] - public class Integer { - public bool @set (long v); - } - - [Compact] - [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")] - public class Time { - public bool @set (time_t t); - } - } - [Compact] - [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)] - public class BIO { - [Compact] - [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)] - public class Method { - public Method (Type type, string name); - [CCode (has_target = false)] - public delegate int WriteFunc (BIO bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf); - [CCode (has_target = false)] - public delegate int ReadFunc (BIO bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf); - [CCode (has_target = false, simple_generics = true)] - public delegate long CtrlFunc (BIO bio, ControlCommand cmd, long num, void* ptr); - public WriteFunc write { get; set; } - public ReadFunc read { get; set; } - public CtrlFunc ctrl { get; set; } - } - - [Flags] - [CCode (cname = "int")] - public enum Type { - SOURCE_SINK, - DGRAM, - } - - [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)] - public enum ControlCommand { - RESET, - EOF, - SET, - GET, - PUSH, - POP, - GET_CLOSE, - SET_CLOSE, - PENDING, - FLUSH, - DUP, - WPENDING, - - DGRAM_QUERY_MTU, - DGRAM_GET_MTU, - DGRAM_SET_MTU, - DGRAM_SET_PEER, - DGRAM_SET_NEXT_TIMEOUT, - DGRAM_GET_PEER, - DGRAM_GET_FALLBACK_MTU, - DGRAM_SET_DONT_FRAG, - DGRAM_GET_MTU_OVERHEAD, - } - - public BIO (Method type); - public T data { get; set; } - - public void clear_retry_flags (); - public void set_retry_read (); - public bool should_read (); - } - - [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")] - namespace ERR { - public ulong get_error (); - public unowned string lib_error_string (ulong error); - public unowned string reason_error_string (ulong error); - } - - [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")] - namespace EVP { - [Compact] - [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] - public class Key { - public Key (); - [CCode (cheader_filename = "openssl_utils.h")] - public Key.generate_ecdsa (string curve); - } - [Compact] - [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")] - public class MessageDigest { - } - - [Compact] - [CCode (cname = "EVP_CIPHER", lower_case_cprefix = "EVP_CIPHER_", cprefix = "EVP_CIPHER_", ref_function = "EVP_CIPHER_up_ref", ref_function_void = true, unref_function = "EVP_CIPHER_free")] - public class Cipher { - - } - - [Compact] - [CCode (cname = "EVP_CIPHER_CTX", lower_case_cprefix = "EVP_CIPHER_CTX_", cprefix = "EVP_CIPHER_CTX_", free_function = "EVP_CIPHER_CTX_free")] - public class CipherContext { - public CipherContext (); - - [CCode (simple_generics = true)] - public int ctrl(Control cmd, int p1, T? p2); - - [CCode (cname = "EVP_EncryptInit")] - private int encrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); - public void encrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { - throw_if_error (encrypt_init_ (cipher, key, iv)); - } - [CCode (cname = "EVP_EncryptUpdate")] - private int encrypt_update_ ([CCode (array_length = false)] uint8[] out, out int out_len, uint8[] in); - public void encrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { - throw_if_error (encrypt_update_ (@out, out out_len, in)); - } - [CCode (cname = "EVP_EncryptFinal")] - private int encrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); - public void encrypt_final (uint8[] out, out int out_len) throws GLib.Error { - throw_if_error (encrypt_final_ (@out, out out_len)); - } - - [CCode (cname = "EVP_DecryptInit")] - private int decrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); - public void decrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { - throw_if_error (decrypt_init_ (cipher, key, iv)); - } - [CCode (cname = "EVP_DecryptUpdate")] - private int decrypt_update_ ([CCode (array_length = false)] uchar[] out, out int out_len, uint8[] in); - public void decrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { - throw_if_error (decrypt_update_ (@out, out out_len, in)); - } - [CCode (cname = "EVP_DecryptFinal")] - private int decrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); - public void decrypt_final (uint8[] out, out int out_len) throws GLib.Error { - throw_if_error (decrypt_final_ (@out, out out_len)); - } - - public int reset(); - public int set_key_length (int keylen); - public int set_padding (int pad); - } - - [CCode (cname = "int", cprefix = "EVP_CTRL_", has_type_id = false)] - public enum Control { - INIT, - SET_KEY_LENGTH, - GET_RC2_KEY_BITS, - SET_RC2_KEY_BITS, - GET_RC5_ROUNDS, - SET_RC5_ROUNDS, - RAND_KEY, - PBE_PRF_NID, - COPY, - AEAD_SET_IVLEN, - AEAD_GET_TAG, - AEAD_SET_TAG, - AEAD_SET_IV_FIXED, - GCM_SET_IVLEN, - GCM_GET_TAG, - GCM_SET_TAG, - GCM_SET_IV_FIXED, - GCM_IV_GEN, - CCM_SET_IVLEN, - CCM_GET_TAG, - CCM_SET_TAG, - CCM_SET_IV_FIXED, - CCM_SET_L, - CCM_SET_MSGLEN, - AEAD_TLS1_AAD, - AEAD_SET_MAC_KEY, - GCM_SET_IV_INV, - TLS1_1_MULTIBLOCK_AAD, - TLS1_1_MULTIBLOCK_ENCRYPT, - TLS1_1_MULTIBLOCK_DECRYPT, - TLS1_1_MULTIBLOCK_MAX_BUFSIZE, - SSL3_MASTER_SECRET, - SET_SBOX, - SBOX_USED, - KEY_MESH, - BLOCK_PADDING_MODE, - SET_PIPELINE_OUTPUT_BUFS, - SET_PIPELINE_INPUT_BUFS, - SET_PIPELINE_INPUT_LENS, - GET_IVLEN, - } - - public static unowned Cipher? aes_128_gcm (); - public static unowned Cipher? aes_256_gcm (); - - public static unowned MessageDigest sha256 (); - } - - [CCode (lower_case_cprefix = "RAND_", cprefix = "RAND_", cheader_filename = "openssl/rand.h")] - namespace RAND { - public static int bytes (uint8[] buf); - public static int priv_bytes (uint8[] buf); - } - - [Compact] - [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")] - class SSL { - [Compact] - [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")] - public class Context { - public Context (Method method); - public int set_tlsext_use_srtp (string profiles); - public int use_certificate (X509.Certificate certificate); - [CCode (cname = "SSL_CTX_use_PrivateKey")] - public int use_private_key (EVP.Key private_key); - } - - [CCode (cname = "const SSL_METHOD*")] - public enum Method { - [CCode (cname = "DTLS_client_method()")] - DTLS_CLIENT, - [CCode (cname = "DTLS_server_method()")] - DTLS_SERVER, - } - - [CCode (cname = "int", has_type_id = false)] - public enum Error { - NONE, - ZERO_RETURN, - WANT_READ, - WANT_WRITE, - WANT_CONNECT, - WANT_ACCEPT, - WANT_X509_LOOKUP, - WANT_ASYNC, - WANT_ASYNC_JOB, - WANT_CLIENT_HELLO_CB, - SYSCALL, - SSL - } - - public SSL (Context context); - public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; } - public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; } - - [CCode (cname = "SSL_do_handshake")] - private int do_handshake_ (); - [CCode (cname = "SSL_do_handshake_")] - public Error do_handshake () throws GLib.Error { - int ret = throw_if_error (do_handshake_ ()); - return get_error (ret); - } - [CCode (cname = "SSL_export_keying_material")] - private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context); - [CCode (cname = "SSL_export_keying_material_")] - public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error { - throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null)); - } - public Error get_error (int ret); - public void set_accept_state (); - public void set_connect_state (); - public int want (); - } - - [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")] - namespace X509 { - [Compact] - [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")] - public class Certificate { - public Certificate (); - public ASN1.Time not_before { - [CCode (cname = "X509_get_notBefore")] - get; - [CCode (cname = "X509_set_notBefore")] - set; - } - public ASN1.Time not_after { - [CCode (cname = "X509_get_notAfter")] - get; - [CCode (cname = "X509_set_notAfter")] - set; - } - public ASN1.Integer serial_number { - [CCode (cname = "X509_get_serialNumber")] - get; - [CCode (cname = "X509_set_serialNumber")] - set; - } - [CCode (cname = "X509_digest")] - private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len); - [CCode (cname = "X509_digest_")] - public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error { - uint8[] buf = new uint8[buf_len]; - uint buf_out_size = (uint) buf_len; - throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size)); - - uint8[] ret = new uint8[buf_out_size]; - for (int i = 0; i < buf_out_size; i++) { - ret[i] = buf[i]; - } - return ret; - } - [CCode (cname = "X509_set_pubkey")] - public int set_public_key (EVP.Key public_key); - public int set_version (long version); - [CCode (cname = "X509_sign")] - private int sign_ (EVP.Key private_key, EVP.MessageDigest md); - [CCode (cname = "X509_sign_")] - public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error { - throw_if_error (sign_ (private_key, md)); - } - } - } - - public int throw_if_error(int res) throws GLib.Error { - if (res <= 0) { - ulong error = ERR.get_error (); - if (error == 0) return res; - throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error)); - } - return res; - } -} \ No newline at end of file diff --git a/libdino/dino.deps b/libdino/dino.deps index 372dc9bf..bef3fb2a 100644 --- a/libdino/dino.deps +++ b/libdino/dino.deps @@ -1,4 +1,5 @@ gee-0.8 +gio-2.0 glib-2.0 gmodule-2.0 qlite diff --git a/libdino/meson.build b/libdino/meson.build index 6124931d..dbaddf56 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -8,6 +8,7 @@ dependencies = [ dep_glib, dep_gmodule, dep_libsoup, + dep_libsrtp2, dep_qlite, dep_xmpp_vala ] @@ -16,6 +17,10 @@ sources = files( 'src/dbus/login1.vala', 'src/dbus/notifications.vala', 'src/dbus/upower.vala', + 'src/crypto/cipher.vala', + 'src/crypto/cipher_converter.vala', + 'src/crypto/error.vala', + 'src/crypto/srtp.vala', 'src/entity/account.vala', 'src/entity/call.vala', 'src/entity/conversation.vala', @@ -73,13 +78,31 @@ sources = files( 'src/util/util.vala', 'src/util/weak_timeout.vala', ) + sources += [version_c] + +if crypto_backend == 'gnu' + dependencies += [ dep_libgcrypt ] + sources += files( + 'src/crypto/gnu/cipher.vala', + 'src/crypto/gnu/utils.vala', + ) +elif crypto_backend == 'openssl' + dependencies += [ dep_openssl ] + sources += files( + 'src/crypto/openssl/cipher.vala', + 'src/crypto/openssl/utils.vala', + ) +endif + c_args = vala_c_args + [ '-DDINO_SYSTEM_LIBDIR_NAME="@0@"'.format(get_option('prefix') / get_option('libdir')), '-DDINO_SYSTEM_PLUGIN_DIR="@0@"'.format(get_option('prefix') / get_option('libdir') / get_option('plugindir')), '-DG_LOG_DOMAIN="libdino"', ] -vala_args = [] +vala_args = [ + '--vapidir', meson.current_source_dir() / 'vapi', +] if meson.get_compiler('vala').version().version_compare('=0.56.11') vala_args += ['-D', 'VALA_0_56_11'] endif diff --git a/libdino/src/crypto/cipher.vala b/libdino/src/crypto/cipher.vala new file mode 100644 index 00000000..89282144 --- /dev/null +++ b/libdino/src/crypto/cipher.vala @@ -0,0 +1,19 @@ +namespace Dino.Crypto { + +public interface SymmetricCipher { + public abstract void set_key(uint8[] key) throws Error; + public abstract void set_iv(uint8[] iv) throws Error; + public abstract void reset() throws Error; +} + +public interface SymmetricCipherEncryption : SymmetricCipher, Object { + public abstract int encrypt(uint8[] output, uint8[] input) throws Error; + public abstract uint8[] get_tag(size_t taglen) throws Error; +} + +public interface SymmetricCipherDecryption : SymmetricCipher, Object { + public abstract int decrypt(uint8[] output, uint8[] input) throws Error; + public abstract void check_tag(uint8[] tag) throws Error; +} + +} diff --git a/libdino/src/crypto/cipher_converter.vala b/libdino/src/crypto/cipher_converter.vala new file mode 100644 index 00000000..c2404c6d --- /dev/null +++ b/libdino/src/crypto/cipher_converter.vala @@ -0,0 +1,110 @@ +using GLib; + +namespace Dino.Crypto { + +public class SymmetricCipherEncrypter : Converter, Object { + private SymmetricCipherEncryption cipher; + private size_t attached_taglen; + + public SymmetricCipherEncrypter(owned SymmetricCipherEncryption cipher, size_t attached_taglen = 0) { + this.cipher = (owned) cipher; + this.attached_taglen = attached_taglen; + } + + public void reset() { + try { + cipher.reset(); + } catch (Crypto.Error e) { + warning(@"$(e.domain) error while resetting cipher: $(e.message)"); + } + } + + public uint8[] get_tag(size_t taglen) throws Error { + return ((SymmetricCipherEncryption)cipher).get_tag(taglen); + } + + public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { + if (inbuf.length > outbuf.length) { + throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); + } + if ((flags & ConverterFlags.INPUT_AT_END) != 0 && inbuf.length + attached_taglen > outbuf.length) { + throw new IOError.NO_SPACE("CipherConverter needs additional output space to attach tag"); + } + try { + if (inbuf.length > 0) { + ((SymmetricCipherEncryption)cipher).encrypt(outbuf, inbuf); + } + bytes_read = inbuf.length; + bytes_written = inbuf.length; + if ((flags & ConverterFlags.INPUT_AT_END) != 0) { + if (attached_taglen > 0) { + Memory.copy((uint8*)outbuf + inbuf.length, get_tag(attached_taglen), attached_taglen); + bytes_written = inbuf.length + attached_taglen; + } + return ConverterResult.FINISHED; + } + if ((flags & ConverterFlags.FLUSH) != 0) { + return ConverterResult.FLUSHED; + } + return ConverterResult.CONVERTED; + } catch (Crypto.Error e) { + throw new IOError.FAILED(@"$(e.domain) error while encrypting: $(e.message)"); + } + } +} + +public class SymmetricCipherDecrypter : Converter, Object { + private SymmetricCipherDecryption cipher; + private size_t attached_taglen; + + public SymmetricCipherDecrypter(owned SymmetricCipherDecryption cipher, size_t attached_taglen = 0) { + this.cipher = (owned) cipher; + this.attached_taglen = attached_taglen; + } + + public void reset() { + try { + cipher.reset(); + } catch (Crypto.Error e) { + warning(@"$(e.domain) error while resetting cipher: $(e.message)"); + } + } + + public void check_tag(uint8[] tag) throws Error { + ((SymmetricCipherDecryption)cipher).check_tag(tag); + } + + public ConverterResult convert(uint8[] inbuf, uint8[] outbuf, ConverterFlags flags, out size_t bytes_read, out size_t bytes_written) throws IOError { + if (inbuf.length > outbuf.length + attached_taglen) { + throw new IOError.NO_SPACE("CipherConverter needs at least the size of input as output space"); + } + if ((flags & ConverterFlags.INPUT_AT_END) != 0 && inbuf.length < attached_taglen) { + throw new IOError.PARTIAL_INPUT("CipherConverter needs additional input to read tag"); + } else if ((flags & ConverterFlags.INPUT_AT_END) == 0 && inbuf.length < attached_taglen + 1) { + throw new IOError.PARTIAL_INPUT("CipherConverter needs additional input to make sure to not accidentally read tag"); + } + try { + inbuf.length -= (int) attached_taglen; + if (inbuf.length > 0) { + ((SymmetricCipherDecryption)cipher).decrypt(outbuf, inbuf); + } + bytes_read = inbuf.length; + bytes_written = inbuf.length; + inbuf.length += (int) attached_taglen; + if ((flags & ConverterFlags.INPUT_AT_END) != 0) { + if (attached_taglen > 0) { + check_tag(inbuf[(inbuf.length - attached_taglen):inbuf.length]); + bytes_read = inbuf.length; + } + return ConverterResult.FINISHED; + } + if ((flags & ConverterFlags.FLUSH) != 0) { + return ConverterResult.FLUSHED; + } + return ConverterResult.CONVERTED; + } catch (Crypto.Error e) { + throw new IOError.FAILED(@"$(e.domain) error while decrypting: $(e.message)"); + } + } +} +} diff --git a/libdino/src/crypto/error.vala b/libdino/src/crypto/error.vala new file mode 100644 index 00000000..2458ae4a --- /dev/null +++ b/libdino/src/crypto/error.vala @@ -0,0 +1,11 @@ +namespace Dino.Crypto { + +public errordomain Error { + ILLEGAL_ARGUMENTS, + GCRYPT, + OPENSSL, + AUTHENTICATION_FAILED, + UNKNOWN +} + +} diff --git a/libdino/src/crypto/gnu/cipher.vala b/libdino/src/crypto/gnu/cipher.vala new file mode 100644 index 00000000..41f15837 --- /dev/null +++ b/libdino/src/crypto/gnu/cipher.vala @@ -0,0 +1,137 @@ +namespace Dino.Crypto { + +internal class SymmetricCipherGcrypt : SymmetricCipher, SymmetricCipherEncryption, SymmetricCipherDecryption, Object { + private GCrypt.Cipher.Cipher cipher; + + private static unowned string mode_to_string(GCrypt.Cipher.Mode mode) { + switch (mode) { + case GCrypt.Cipher.Mode.ECB: return "ECB"; + case GCrypt.Cipher.Mode.CFB: return "CFB"; + case GCrypt.Cipher.Mode.CBC: return "CBC"; + case GCrypt.Cipher.Mode.STREAM: return "STREAM"; + case GCrypt.Cipher.Mode.OFB: return "OFB"; + case GCrypt.Cipher.Mode.CTR: return "CTR"; + case GCrypt.Cipher.Mode.AESWRAP: return "AESWRAP"; + case GCrypt.Cipher.Mode.GCM: return "GCM"; + case GCrypt.Cipher.Mode.POLY1305: return "POLY1305"; + case GCrypt.Cipher.Mode.OCB: return "OCB"; + case GCrypt.Cipher.Mode.CFB8: return "CFB8"; + // case GCrypt.Cipher.Mode.XTS: return "XTS"; // Not supported in gcrypt < 1.8 + } + return "NONE"; + } + + private static GCrypt.Cipher.Mode mode_from_string(string name) { + switch (name) { + case "ECB": return GCrypt.Cipher.Mode.ECB; + case "CFB": return GCrypt.Cipher.Mode.CFB; + case "CBC": return GCrypt.Cipher.Mode.CBC; + case "STREAM": return GCrypt.Cipher.Mode.STREAM; + case "OFB": return GCrypt.Cipher.Mode.OFB; + case "CTR": return GCrypt.Cipher.Mode.CTR; + case "AESWRAP": return GCrypt.Cipher.Mode.AESWRAP; + case "GCM": return GCrypt.Cipher.Mode.GCM; + case "POLY1305": return GCrypt.Cipher.Mode.POLY1305; + case "OCB": return GCrypt.Cipher.Mode.OCB; + case "CFB8": return GCrypt.Cipher.Mode.CFB8; + // case "XTS": return GCrypt.Cipher.Mode.XTS; // Not supported in gcrypt < 1.8 + } + return GCrypt.Cipher.Mode.NONE; + } + + private static string flags_to_string(GCrypt.Cipher.Flag flags) { + string? s = null; + if ((GCrypt.Cipher.Flag.CBC_MAC & flags) != 0) s = (s == null ? "" : @"$s-") + "MAC"; + if ((GCrypt.Cipher.Flag.CBC_CTS & flags) != 0) s = (s == null ? "" : @"$s-") + "CTS"; + if ((GCrypt.Cipher.Flag.ENABLE_SYNC & flags) != 0) s = (s == null ? "" : @"$s-") + "SYNC"; + if ((GCrypt.Cipher.Flag.SECURE & flags) != 0) s = (s == null ? "" : @"$s-") + "SECURE"; + return s ?? "NONE"; + } + + private static GCrypt.Cipher.Flag flag_from_string(string flag_name) { + if (flag_name == "SECURE") return GCrypt.Cipher.Flag.SECURE; + if (flag_name == "SYNC") return GCrypt.Cipher.Flag.ENABLE_SYNC; + if (flag_name == "CTS") return GCrypt.Cipher.Flag.CBC_CTS; + if (flag_name == "MAC") return GCrypt.Cipher.Flag.CBC_MAC; + return 0; + } + + private static GCrypt.Cipher.Flag flags_from_string(string flag_names) { + GCrypt.Cipher.Flag flags = 0; + foreach(string flag in flag_names.split("-")) { + flags |= flag_from_string(flag); + } + return flags; + } + + private static bool parse(string algo_name, out GCrypt.Cipher.Algorithm algo, out GCrypt.Cipher.Mode mode, out GCrypt.Cipher.Flag flags) { + algo = GCrypt.Cipher.Algorithm.NONE; + mode = GCrypt.Cipher.Mode.NONE; + flags = 0; + string[] algo_parts = algo_name.split("-", 3); + + algo = GCrypt.Cipher.Algorithm.from_string(algo_parts[0]); + if (algo_parts.length >= 2) { + mode = mode_from_string(algo_parts[1]); + } + if (algo_parts.length == 3) { + flags |= flags_from_string(algo_parts[2]); + } + return to_algo_name(algo, mode, flags) == algo_name; + } + + private static string to_algo_name(GCrypt.Cipher.Algorithm algo = GCrypt.Cipher.Algorithm.NONE, GCrypt.Cipher.Mode mode = GCrypt.Cipher.Mode.NONE, GCrypt.Cipher.Flag flags = 0) { + if (flags != 0) { + return @"$algo-$(mode_to_string(mode))-$(flags_to_string(flags))"; + } else if (mode != GCrypt.Cipher.Mode.NONE) { + return @"$algo-$(mode_to_string(mode))"; + } else { + return algo.to_string(); + } + } + + public SymmetricCipherGcrypt(string algo_name) throws Error { + GCrypt.Cipher.Algorithm algo; + GCrypt.Cipher.Mode mode; + GCrypt.Cipher.Flag flags; + if (parse(algo_name, out algo, out mode, out flags)) { + may_throw_gcrypt_error(GCrypt.Cipher.Cipher.open(out this.cipher, algo, mode, flags)); + } else { + throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + } + } + + public void set_key(uint8[] key) throws Error { + may_throw_gcrypt_error(cipher.set_key(key)); + } + + public void set_iv(uint8[] iv) throws Error { + may_throw_gcrypt_error(cipher.set_iv(iv)); + } + + public void reset() throws Error { + may_throw_gcrypt_error(cipher.reset()); + } + + public uint8[] get_tag(size_t taglen) throws Error { + uint8[] tag = new uint8[taglen]; + may_throw_gcrypt_error(cipher.get_tag(tag)); + return tag; + } + + public void check_tag(uint8[] tag) throws Error { + may_throw_gcrypt_error(cipher.check_tag(tag)); + } + + public int encrypt(uint8[] output, uint8[] input) throws Error { + may_throw_gcrypt_error(cipher.encrypt(output, input)); + return input.length; + } + + public int decrypt(uint8[] output, uint8[] input) throws Error { + may_throw_gcrypt_error(cipher.decrypt(output, input)); + return input.length; + } +} + +} diff --git a/libdino/src/crypto/gnu/utils.vala b/libdino/src/crypto/gnu/utils.vala new file mode 100644 index 00000000..8a25ab27 --- /dev/null +++ b/libdino/src/crypto/gnu/utils.vala @@ -0,0 +1,21 @@ +namespace Dino.Crypto { + +public static void randomize(uint8[] buffer) { + GCrypt.Random.randomize(buffer); +} + +internal void may_throw_gcrypt_error(GCrypt.Error e) throws Error { + if (((int)e) != 0) { + throw new Crypto.Error.GCRYPT(e.to_string()); + } +} + +public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { + return new SymmetricCipherGcrypt(algo_name); +} + +public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { + return new SymmetricCipherGcrypt(algo_name); +} + +} diff --git a/libdino/src/crypto/openssl/cipher.vala b/libdino/src/crypto/openssl/cipher.vala new file mode 100644 index 00000000..02064770 --- /dev/null +++ b/libdino/src/crypto/openssl/cipher.vala @@ -0,0 +1,156 @@ +namespace Dino.Crypto { + +internal class SymmetricCipherEncryptionOpenssl : SymmetricCipher, SymmetricCipherEncryption, Object { + private OpenSSL.EVP.CipherContext? cipher; + private bool is_finalized = false; + + public SymmetricCipherEncryptionOpenssl(string algo_name) throws Error { + if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + cipher = new OpenSSL.EVP.CipherContext(); + } + + public void set_key(uint8[] key) throws Error { + unowned OpenSSL.EVP.Cipher algo; + if (key.length == 16) { + algo = OpenSSL.EVP.aes_128_gcm(); + } else if (key.length == 32) { + algo = OpenSSL.EVP.aes_256_gcm(); + } else { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); + } + try { + cipher.encrypt_init(algo, null, null); + cipher.encrypt_init(null, key, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_iv(uint8[] iv) throws Error { + if (iv.length != 12) { + cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); + } + try { + cipher.encrypt_init(null, null, iv); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void reset() throws Error { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); + } + + public uint8[] get_tag(size_t taglen) throws Error { + uint8[] tag = new uint8[taglen]; + if (!is_finalized) { + uint8[] empty = new uint8[0]; + int empty_len = 0; + try { + cipher.encrypt_final(empty, out empty_len); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + if (empty_len != 0) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("get_tag called on a stream with remaining data"); + } + } + if (cipher.ctrl(OpenSSL.EVP.Control.GCM_GET_TAG, (int)taglen, tag) != 1) { + openssl_error(); + } + return tag; + } + + public int encrypt(uint8[] output, uint8[] input) throws Error { + int output_length = output.length; + if (is_finalized) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("encrypt called after get_tag"); + } + try { + cipher.encrypt_update(output, out output_length, input); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + return output_length; + } +} + +internal class SymmetricCipherDecryptionOpenssl : SymmetricCipher, SymmetricCipherDecryption, Object { + private OpenSSL.EVP.CipherContext? cipher; + private bool is_finalized = false; + + public SymmetricCipherDecryptionOpenssl(string algo_name) throws Error { + if (algo_name != "AES-GCM") throw new Error.ILLEGAL_ARGUMENTS(@"The algorithm $algo_name is not supported"); + cipher = new OpenSSL.EVP.CipherContext(); + try { + cipher.decrypt_init(OpenSSL.EVP.aes_128_gcm(), null, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_key(uint8[] key) throws Error { + unowned OpenSSL.EVP.Cipher algo; + if (key.length == 16) { + algo = OpenSSL.EVP.aes_128_gcm(); + } else if (key.length == 32) { + algo = OpenSSL.EVP.aes_256_gcm(); + } else { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("key length must be 16 or 32 for AES-GCM"); + } + try { + cipher.decrypt_init(algo, null, null); + cipher.decrypt_init(null, key, null); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void set_iv(uint8[] iv) throws Error { + if (iv.length != 12) { + cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_IVLEN, iv.length, null); + } + try { + cipher.decrypt_init(null, null, iv); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + } + + public void reset() throws Error { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("can't reset OpenSSL cipher context"); + } + + public void check_tag(uint8[] tag) throws Error { + if (cipher.ctrl(OpenSSL.EVP.Control.GCM_SET_TAG, tag.length, tag) != 1) { + openssl_error(); + } + if (!is_finalized) { + uint8[] empty = new uint8[0]; + int empty_len = 0; + try { + cipher.decrypt_final(empty, out empty_len); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + if (empty_len != 0) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("check_tag called on a stream with remaining data"); + } + } + } + + public int decrypt(uint8[] output, uint8[] input) throws Error { + if (is_finalized) { + throw new Crypto.Error.ILLEGAL_ARGUMENTS("decrypt called after check_tag"); + } + int output_length = output.length; + try { + cipher.decrypt_update(output, out output_length, input); + } catch (GLib.Error e) { + throw new Crypto.Error.OPENSSL(e.message); + } + return output_length; + } +} + +} diff --git a/libdino/src/crypto/openssl/utils.vala b/libdino/src/crypto/openssl/utils.vala new file mode 100644 index 00000000..7a9ed9b6 --- /dev/null +++ b/libdino/src/crypto/openssl/utils.vala @@ -0,0 +1,19 @@ +namespace Dino.Crypto { + +public static void randomize(uint8[] buffer) { + OpenSSL.RAND.bytes(buffer); +} + +internal void openssl_error() throws Error { + throw new Crypto.Error.OPENSSL(OpenSSL.ERR.reason_error_string(OpenSSL.ERR.get_error())); +} + +public SymmetricCipherEncryption create_symmetric_cipher_encryption(string algo_name) throws Error { + return new SymmetricCipherEncryptionOpenssl(algo_name); +} + +public SymmetricCipherDecryption create_symmetric_cipher_decryption(string algo_name) throws Error { + return new SymmetricCipherDecryptionOpenssl(algo_name); +} + +} diff --git a/libdino/src/crypto/srtp.vala b/libdino/src/crypto/srtp.vala new file mode 100644 index 00000000..852dccdc --- /dev/null +++ b/libdino/src/crypto/srtp.vala @@ -0,0 +1,122 @@ +using Srtp; + +namespace Dino.Crypto.Srtp { +public const string AES_CM_128_HMAC_SHA1_80 = "AES_CM_128_HMAC_SHA1_80"; +public const string AES_CM_128_HMAC_SHA1_32 = "AES_CM_128_HMAC_SHA1_32"; +public const string F8_128_HMAC_SHA1_80 = "F8_128_HMAC_SHA1_80"; + +public class Session { + public bool has_encrypt { get; private set; default = false; } + public bool has_decrypt { get; private set; default = false; } + + private Context encrypt_context; + private Context decrypt_context; + + static construct { + init(); + install_log_handler(log); + } + + private static void log(LogLevel level, string msg) { + print(@"SRTP[$level]: $msg\n"); + } + + public Session() { + Context.create(out encrypt_context, null); + Context.create(out decrypt_context, null); + } + + public uint8[] encrypt_rtp(uint8[] data) throws Error { + uint8[] buf = new uint8[data.length + MAX_TRAILER_LEN]; + Memory.copy(buf, data, data.length); + int buf_use = data.length; + ErrorStatus res = encrypt_context.protect(buf, ref buf_use); + if (res != ErrorStatus.ok) { + throw new Error.UNKNOWN(@"SRTP encrypt failed: $res"); + } + buf.length = buf_use; + return buf; + } + + public uint8[] decrypt_rtp(uint8[] data) throws Error { + uint8[] buf = new uint8[data.length]; + Memory.copy(buf, data, data.length); + int buf_use = data.length; + ErrorStatus res = decrypt_context.unprotect(buf, ref buf_use); + switch (res) { + case ErrorStatus.auth_fail: + throw new Error.AUTHENTICATION_FAILED("SRTP packet failed the message authentication check"); + case ErrorStatus.ok: + break; + default: + throw new Error.UNKNOWN(@"SRTP decrypt failed: $res"); + } + uint8[] ret = new uint8[buf_use]; + GLib.Memory.copy(ret, buf, buf_use); + return ret; + } + + public uint8[] encrypt_rtcp(uint8[] data) throws Error { + uint8[] buf = new uint8[data.length + MAX_TRAILER_LEN + 4]; + Memory.copy(buf, data, data.length); + int buf_use = data.length; + ErrorStatus res = encrypt_context.protect_rtcp(buf, ref buf_use); + if (res != ErrorStatus.ok) { + throw new Error.UNKNOWN(@"SRTCP encrypt failed: $res"); + } + buf.length = buf_use; + return buf; + } + + public uint8[] decrypt_rtcp(uint8[] data) throws Error { + uint8[] buf = new uint8[data.length]; + Memory.copy(buf, data, data.length); + int buf_use = data.length; + ErrorStatus res = decrypt_context.unprotect_rtcp(buf, ref buf_use); + switch (res) { + case ErrorStatus.auth_fail: + throw new Error.AUTHENTICATION_FAILED("SRTCP packet failed the message authentication check"); + case ErrorStatus.ok: + break; + default: + throw new Error.UNKNOWN(@"SRTCP decrypt failed: $res"); + } + uint8[] ret = new uint8[buf_use]; + GLib.Memory.copy(ret, buf, buf_use); + return ret; + } + + private Policy create_policy(string profile) { + Policy policy = Policy(); + switch (profile) { + case AES_CM_128_HMAC_SHA1_80: + policy.rtp.set_aes_cm_128_hmac_sha1_80(); + policy.rtcp.set_aes_cm_128_hmac_sha1_80(); + break; + } + return policy; + } + + public void set_encryption_key(string profile, uint8[] key, uint8[] salt) { + Policy policy = create_policy(profile); + policy.ssrc.type = SsrcType.any_outbound; + policy.key = new uint8[key.length + salt.length]; + Memory.copy(policy.key, key, key.length); + Memory.copy(((uint8*)policy.key) + key.length, salt, salt.length); + policy.next = null; + encrypt_context.add_stream(ref policy); + has_encrypt = true; + } + + public void set_decryption_key(string profile, uint8[] key, uint8[] salt) { + Policy policy = create_policy(profile); + policy.ssrc.type = SsrcType.any_inbound; + policy.key = new uint8[key.length + salt.length]; + Memory.copy(policy.key, key, key.length); + Memory.copy(((uint8*)policy.key) + key.length, salt, salt.length); + policy.next = null; + decrypt_context.add_stream(ref policy); + has_decrypt = true; + } +} +} \ No newline at end of file diff --git a/libdino/vapi/libgcrypt.vapi b/libdino/vapi/libgcrypt.vapi new file mode 100644 index 00000000..0fa69a02 --- /dev/null +++ b/libdino/vapi/libgcrypt.vapi @@ -0,0 +1,872 @@ +/* gcrypt.vapi + * + * Copyright: + * 2008 Jiqing Qiang + * 2008, 2010, 2012-2013 Evan Nemerson + * + * This library is free software; you can redistribute it and/or + * modify it under the terms of the GNU Lesser General Public + * License as published by the Free Software Foundation; either + * version 2.1 of the License, or (at your option) any later version. + + * This library is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + * Lesser General Public License for more details. + + * You should have received a copy of the GNU Lesser General Public + * License along with this library; if not, write to the Free Software + * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + * + * Author: + * Jiqing Qiang + * Evan Nemerson + */ + + +[CCode (cheader_filename = "gcrypt.h", lower_case_cprefix = "gcry_")] +namespace GCrypt { + [CCode (cname = "gpg_err_source_t", cprefix = "GPG_ERR_SOURCE_")] + public enum ErrorSource { + UNKNOWN, + GCRYPT, + GPG, + GPGSM, + GPGAGENT, + PINENTRY, + SCD, + GPGME, + KEYBOX, + KSBA, + DIRMNGR, + GSTI, + ANY, + USER_1, + USER_2, + USER_3, + USER_4, + + /* This is one more than the largest allowed entry. */ + DIM + } + + [CCode (cname = "gpg_err_code_t", cprefix = "GPG_ERR_")] + public enum ErrorCode { + NO_ERROR, + GENERAL, + UNKNOWN_PACKET, + UNKNOWN_VERSION, + PUBKEY_ALGO, + DIGEST_ALGO, + BAD_PUBKEY, + BAD_SECKEY, + BAD_SIGNATURE, + NO_PUBKEY, + CHECKSUM, + BAD_PASSPHRASE, + CIPHER_ALGO, + KEYRING_OPEN, + INV_PACKET, + INV_ARMOR, + NO_USER_ID, + NO_SECKEY, + WRONG_SECKEY, + BAD_KEY, + COMPR_ALGO, + NO_PRIME, + NO_ENCODING_METHOD, + NO_ENCRYPTION_SCHEME, + NO_SIGNATURE_SCHEME, + INV_ATTR, + NO_VALUE, + NOT_FOUND, + VALUE_NOT_FOUND, + SYNTAX, + BAD_MPI, + INV_PASSPHRASE, + SIG_CLASS, + RESOURCE_LIMIT, + INV_KEYRING, + TRUSTDB, + BAD_CERT, + INV_USER_ID, + UNEXPECTED, + TIME_CONFLICT, + KEYSERVER, + WRONG_PUBKEY_ALGO, + TRIBUTE_TO_D_A, + WEAK_KEY, + INV_KEYLEN, + INV_ARG, + BAD_URI, + INV_URI, + NETWORK, + UNKNOWN_HOST, + SELFTEST_FAILED, + NOT_ENCRYPTED, + NOT_PROCESSED, + UNUSABLE_PUBKEY, + UNUSABLE_SECKEY, + INV_VALUE, + BAD_CERT_CHAIN, + MISSING_CERT, + NO_DATA, + BUG, + NOT_SUPPORTED, + INV_OP, + TIMEOUT, + INTERNAL, + EOF_GCRYPT, + INV_OBJ, + TOO_SHORT, + TOO_LARGE, + NO_OBJ, + NOT_IMPLEMENTED, + CONFLICT, + INV_CIPHER_MODE, + INV_FLAG, + INV_HANDLE, + TRUNCATED, + INCOMPLETE_LINE, + INV_RESPONSE, + NO_AGENT, + AGENT, + INV_DATA, + ASSUAN_SERVER_FAULT, + ASSUAN, + INV_SESSION_KEY, + INV_SEXP, + UNSUPPORTED_ALGORITHM, + NO_PIN_ENTRY, + PIN_ENTRY, + BAD_PIN, + INV_NAME, + BAD_DATA, + INV_PARAMETER, + WRONG_CARD, + NO_DIRMNGR, + DIRMNGR, + CERT_REVOKED, + NO_CRL_KNOWN, + CRL_TOO_OLD, + LINE_TOO_LONG, + NOT_TRUSTED, + CANCELED, + BAD_CA_CERT, + CERT_EXPIRED, + CERT_TOO_YOUNG, + UNSUPPORTED_CERT, + UNKNOWN_SEXP, + UNSUPPORTED_PROTECTION, + CORRUPTED_PROTECTION, + AMBIGUOUS_NAME, + CARD, + CARD_RESET, + CARD_REMOVED, + INV_CARD, + CARD_NOT_PRESENT, + NO_PKCS15_APP, + NOT_CONFIRMED, + CONFIGURATION, + NO_POLICY_MATCH, + INV_INDEX, + INV_ID, + NO_SCDAEMON, + SCDAEMON, + UNSUPPORTED_PROTOCOL, + BAD_PIN_METHOD, + CARD_NOT_INITIALIZED, + UNSUPPORTED_OPERATION, + WRONG_KEY_USAGE, + NOTHING_FOUND, + WRONG_BLOB_TYPE, + MISSING_VALUE, + HARDWARE, + PIN_BLOCKED, + USE_CONDITIONS, + PIN_NOT_SYNCED, + INV_CRL, + BAD_BER, + INV_BER, + ELEMENT_NOT_FOUND, + IDENTIFIER_NOT_FOUND, + INV_TAG, + INV_LENGTH, + INV_KEYINFO, + UNEXPECTED_TAG, + NOT_DER_ENCODED, + NO_CMS_OBJ, + INV_CMS_OBJ, + UNKNOWN_CMS_OBJ, + UNSUPPORTED_CMS_OBJ, + UNSUPPORTED_ENCODING, + UNSUPPORTED_CMS_VERSION, + UNKNOWN_ALGORITHM, + INV_ENGINE, + PUBKEY_NOT_TRUSTED, + DECRYPT_FAILED, + KEY_EXPIRED, + SIG_EXPIRED, + ENCODING_PROBLEM, + INV_STATE, + DUP_VALUE, + MISSING_ACTION, + MODULE_NOT_FOUND, + INV_OID_STRING, + INV_TIME, + INV_CRL_OBJ, + UNSUPPORTED_CRL_VERSION, + INV_CERT_OBJ, + UNKNOWN_NAME, + LOCALE_PROBLEM, + NOT_LOCKED, + PROTOCOL_VIOLATION, + INV_MAC, + INV_REQUEST, + UNKNOWN_EXTN, + UNKNOWN_CRIT_EXTN, + LOCKED, + UNKNOWN_OPTION, + UNKNOWN_COMMAND, + BUFFER_TOO_SHORT, + SEXP_INV_LEN_SPEC, + SEXP_STRING_TOO_LONG, + SEXP_UNMATCHED_PAREN, + SEXP_NOT_CANONICAL, + SEXP_BAD_CHARACTER, + SEXP_BAD_QUOTATION, + SEXP_ZERO_PREFIX, + SEXP_NESTED_DH, + SEXP_UNMATCHED_DH, + SEXP_UNEXPECTED_PUNC, + SEXP_BAD_HEX_CHAR, + SEXP_ODD_HEX_NUMBERS, + SEXP_BAD_OCT_CHAR, + ASS_GENERAL, + ASS_ACCEPT_FAILED, + ASS_CONNECT_FAILED, + ASS_INV_RESPONSE, + ASS_INV_VALUE, + ASS_INCOMPLETE_LINE, + ASS_LINE_TOO_LONG, + ASS_NESTED_COMMANDS, + ASS_NO_DATA_CB, + ASS_NO_INQUIRE_CB, + ASS_NOT_A_SERVER, + ASS_NOT_A_CLIENT, + ASS_SERVER_START, + ASS_READ_ERROR, + ASS_WRITE_ERROR, + ASS_TOO_MUCH_DATA, + ASS_UNEXPECTED_CMD, + ASS_UNKNOWN_CMD, + ASS_SYNTAX, + ASS_CANCELED, + ASS_NO_INPUT, + ASS_NO_OUTPUT, + ASS_PARAMETER, + ASS_UNKNOWN_INQUIRE, + USER_1, + USER_2, + USER_3, + USER_4, + USER_5, + USER_6, + USER_7, + USER_8, + USER_9, + USER_10, + USER_11, + USER_12, + USER_13, + USER_14, + USER_15, + USER_16, + MISSING_ERRNO, + UNKNOWN_ERRNO, + EOF, + + E2BIG, + EACCES, + EADDRINUSE, + EADDRNOTAVAIL, + EADV, + EAFNOSUPPORT, + EAGAIN, + EALREADY, + EAUTH, + EBACKGROUND, + EBADE, + EBADF, + EBADFD, + EBADMSG, + EBADR, + EBADRPC, + EBADRQC, + EBADSLT, + EBFONT, + EBUSY, + ECANCELED, + ECHILD, + ECHRNG, + ECOMM, + ECONNABORTED, + ECONNREFUSED, + ECONNRESET, + ED, + EDEADLK, + EDEADLOCK, + EDESTADDRREQ, + EDIED, + EDOM, + EDOTDOT, + EDQUOT, + EEXIST, + EFAULT, + EFBIG, + EFTYPE, + EGRATUITOUS, + EGREGIOUS, + EHOSTDOWN, + EHOSTUNREACH, + EIDRM, + EIEIO, + EILSEQ, + EINPROGRESS, + EINTR, + EINVAL, + EIO, + EISCONN, + EISDIR, + EISNAM, + EL2HLT, + EL2NSYNC, + EL3HLT, + EL3RST, + ELIBACC, + ELIBBAD, + ELIBEXEC, + ELIBMAX, + ELIBSCN, + ELNRNG, + ELOOP, + EMEDIUMTYPE, + EMFILE, + EMLINK, + EMSGSIZE, + EMULTIHOP, + ENAMETOOLONG, + ENAVAIL, + ENEEDAUTH, + ENETDOWN, + ENETRESET, + ENETUNREACH, + ENFILE, + ENOANO, + ENOBUFS, + ENOCSI, + ENODATA, + ENODEV, + ENOENT, + ENOEXEC, + ENOLCK, + ENOLINK, + ENOMEDIUM, + ENOMEM, + ENOMSG, + ENONET, + ENOPKG, + ENOPROTOOPT, + ENOSPC, + ENOSR, + ENOSTR, + ENOSYS, + ENOTBLK, + ENOTCONN, + ENOTDIR, + ENOTEMPTY, + ENOTNAM, + ENOTSOCK, + ENOTSUP, + ENOTTY, + ENOTUNIQ, + ENXIO, + EOPNOTSUPP, + EOVERFLOW, + EPERM, + EPFNOSUPPORT, + EPIPE, + EPROCLIM, + EPROCUNAVAIL, + EPROGMISMATCH, + EPROGUNAVAIL, + EPROTO, + EPROTONOSUPPORT, + EPROTOTYPE, + ERANGE, + EREMCHG, + EREMOTE, + EREMOTEIO, + ERESTART, + EROFS, + ERPCMISMATCH, + ESHUTDOWN, + ESOCKTNOSUPPORT, + ESPIPE, + ESRCH, + ESRMNT, + ESTALE, + ESTRPIPE, + ETIME, + ETIMEDOUT, + ETOOMANYREFS, + ETXTBSY, + EUCLEAN, + EUNATCH, + EUSERS, + EWOULDBLOCK, + EXDEV, + EXFULL, + + /* This is one more than the largest allowed entry. */ + CODE_DIM + } + + [CCode (cname = "gcry_error_t", cprefix = "gpg_err_")] + public struct Error : uint { + [CCode (cname = "gcry_err_make")] + public Error (ErrorSource source, ErrorCode code); + [CCode (cname = "gcry_err_make_from_errno")] + public Error.from_errno (ErrorSource source, int err); + public ErrorCode code (); + public ErrorSource source (); + + [CCode (cname = "gcry_strerror")] + public unowned string to_string (); + + [CCode (cname = "gcry_strsource")] + public unowned string source_to_string (); + } + + [CCode (cname = "enum gcry_ctl_cmds", cprefix = "GCRYCTL_")] + public enum ControlCommand { + SET_KEY, + SET_IV, + CFB_SYNC, + RESET, + FINALIZE, + GET_KEYLEN, + GET_BLKLEN, + TEST_ALGO, + IS_SECURE, + GET_ASNOID, + ENABLE_ALGO, + DISABLE_ALGO, + DUMP_RANDOM_STATS, + DUMP_SECMEM_STATS, + GET_ALGO_NPKEY, + GET_ALGO_NSKEY, + GET_ALGO_NSIGN, + GET_ALGO_NENCR, + SET_VERBOSITY, + SET_DEBUG_FLAGS, + CLEAR_DEBUG_FLAGS, + USE_SECURE_RNDPOOL, + DUMP_MEMORY_STATS, + INIT_SECMEM, + TERM_SECMEM, + DISABLE_SECMEM_WARN, + SUSPEND_SECMEM_WARN, + RESUME_SECMEM_WARN, + DROP_PRIVS, + ENABLE_M_GUARD, + START_DUMP, + STOP_DUMP, + GET_ALGO_USAGE, + IS_ALGO_ENABLED, + DISABLE_INTERNAL_LOCKING, + DISABLE_SECMEM, + INITIALIZATION_FINISHED, + INITIALIZATION_FINISHED_P, + ANY_INITIALIZATION_P, + SET_CBC_CTS, + SET_CBC_MAC, + SET_CTR, + ENABLE_QUICK_RANDOM, + SET_RANDOM_SEED_FILE, + UPDATE_RANDOM_SEED_FILE, + SET_THREAD_CBS, + FAST_POLL + } + public Error control (ControlCommand cmd, ...); + + [CCode (lower_case_cname = "cipher_")] + namespace Cipher { + [CCode (cname = "enum gcry_cipher_algos", cprefix = "GCRY_CIPHER_")] + public enum Algorithm { + NONE, + IDEA, + 3DES, + CAST5, + BLOWFISH, + SAFER_SK128, + DES_SK, + AES, + AES128, + RIJNDAEL, + RIJNDAEL128, + AES192, + RIJNDAEL192, + AES256, + RIJNDAEL256, + TWOFISH, + TWOFISH128, + ARCFOUR, + DES, + SERPENT128, + SERPENT192, + SERPENT256, + RFC2268_40, + RFC2268_128, + SEED, + CAMELLIA128, + CAMELLIA192, + CAMELLIA256, + SALSA20, + SALSA20R12, + GOST28147, + CHACHA20; + + [CCode (cname = "gcry_cipher_algo_info")] + public Error info (ControlCommand what, ref uchar[] buffer); + [CCode (cname = "gcry_cipher_algo_name")] + public unowned string to_string (); + [CCode (cname = "gcry_cipher_map_name")] + public static Algorithm from_string (string name); + [CCode (cname = "gcry_cipher_map_oid")] + public static Algorithm from_oid (string oid); + } + + [CCode (cname = "enum gcry_cipher_modes", cprefix = "GCRY_CIPHER_MODE_")] + public enum Mode { + NONE, /* No mode specified */ + ECB, /* Electronic Codebook */ + CFB, /* Cipher Feedback */ + CBC, /* Cipher Block Chaining */ + STREAM, /* Used with stream ciphers */ + OFB, /* Output Feedback */ + CTR, /* Counter */ + AESWRAP, /* AES-WRAP algorithm */ + CCM, /* Counter with CBC-MAC */ + GCM, /* Galois/Counter Mode */ + POLY1305, /* Poly1305 based AEAD mode */ + OCB, /* OCB3 mode */ + CFB8, /* Cipher Feedback /* Poly1305 based AEAD mode. */ + XTS; /* XTS mode */ + + public unowned string to_string () { + switch (this) { + case ECB: return "ECB"; + case CFB: return "CFB"; + case CBC: return "CBC"; + case STREAM: return "STREAM"; + case OFB: return "OFB"; + case CTR: return "CTR"; + case AESWRAP: return "AESWRAP"; + case GCM: return "GCM"; + case POLY1305: return "POLY1305"; + case OCB: return "OCB"; + case CFB8: return "CFB8"; + case XTS: return "XTS"; + } + return "NONE"; + } + + public static Mode from_string (string name) { + switch (name) { + case "ECB": return ECB; + case "CFB": return CFB; + case "CBC": return CBC; + case "STREAM": return STREAM; + case "OFB": return OFB; + case "CTR": return CTR; + case "AESWRAP": return AESWRAP; + case "GCM": return GCM; + case "POLY1305": return POLY1305; + case "OCB": return OCB; + case "CFB8": return CFB8; + case "XTS": return XTS; + } + return NONE; + } + } + + [CCode (cname = "enum gcry_cipher_flags", cprefix = "GCRY_CIPHER_")] + public enum Flag { + SECURE, /* Allocate in secure memory. */ + ENABLE_SYNC, /* Enable CFB sync mode. */ + CBC_CTS, /* Enable CBC cipher text stealing (CTS). */ + CBC_MAC /* Enable CBC message auth. code (MAC). */ + } + [CCode (cname = "gcry_cipher_hd_t", lower_case_cprefix = "gcry_cipher_", free_function = "gcry_cipher_close")] + [SimpleType] + public struct Cipher { + public static Error open (out Cipher cipher, Algorithm algo, Mode mode, Flag flags); + public void close (); + [CCode (cname = "gcry_cipher_ctl")] + public Error control (ControlCommand cmd, uchar[] buffer); + public Error info (ControlCommand what, ref uchar[] buffer); + + public Error encrypt (uchar[] out_buffer, uchar[] in_buffer); + public Error decrypt (uchar[] out_buffer, uchar[] in_buffer); + + [CCode (cname = "gcry_cipher_setkey")] + public Error set_key (uchar[] key_data); + [CCode (cname = "gcry_cipher_setiv")] + public Error set_iv (uchar[] iv_data); + [CCode (cname = "gcry_cipher_setctr")] + public Error set_counter_vector (uchar[] counter_vector); + + [CCode (cname = "gcry_cipher_gettag")] + public Error get_tag(uchar[] out_buffer); + [CCode (cname = "gcry_cipher_checktag")] + public Error check_tag(uchar[] in_buffer); + + public Error reset (); + public Error sync (); + } + } + + [Compact, CCode (cname = "struct gcry_md_handle", cprefix = "gcry_md_", free_function = "gcry_md_close")] + public class Hash { + [CCode (cname = "enum gcry_md_algos", cprefix = "GCRY_MD_")] + public enum Algorithm { + NONE, + SHA1, + RMD160, + MD5, + MD4, + MD2, + TIGER, + TIGER1, + TIGER2, + HAVAL, + SHA224, + SHA256, + SHA384, + SHA512, + SHA3_224, + SHA3_256, + SHA3_384, + SHA3_512, + SHAKE128, + SHAKE256, + CRC32, + CRC32_RFC1510, + CRC24_RFC2440, + WHIRLPOOL, + GOSTR3411_94, + STRIBOG256, + STRIBOG512; + + [CCode (cname = "gcry_md_get_algo_dlen")] + public size_t get_digest_length (); + [CCode (cname = "gcry_md_algo_info")] + public Error info (ControlCommand what, ref uchar[] buffer); + [CCode (cname = "gcry_md_algo_name")] + public unowned string to_string (); + [CCode (cname = "gcry_md_map_name")] + public static Algorithm from_string (string name); + [CCode (cname = "gcry_md_test_algo")] + public Error is_available (); + [CCode (cname = "gcry_md_get_asnoid")] + public Error get_oid (uchar[] buffer); + } + + [CCode (cname = "enum gcry_md_flags", cprefix = "GCRY_MD_FLAG_")] + public enum Flag { + SECURE, + HMAC, + BUGEMU1 + } + + public static Error open (out Hash hash, Algorithm algo, Flag flag); + public void close (); + public Error enable (Algorithm algo); + [CCode (instance_pos = -1)] + public Error copy (out Hash dst); + public void reset (); + [CCode (cname = "enum gcry_md_ctl")] + public Error control (ControlCommand cmd, uchar[] buffer); + public void write (uchar[] buffer); + [CCode (array_length = false)] + public unowned uchar[] read (Algorithm algo); + public static void hash_buffer (Algorithm algo, [CCode (array_length = false)] uchar[] digest, uchar[] buffer); + public Algorithm get_algo (); + public bool is_enabled (Algorithm algo); + public bool is_secure (); + public Error info (ControlCommand what, uchar[] buffer); + [CCode (cname = "gcry_md_setkey")] + public Error set_key (uchar[] key_data); + public void putc (char c); + public void final (); + public static Error list (ref Algorithm[] algos); + } + + namespace Random { + [CCode (cname = "gcry_random_level_t")] + public enum Level { + [CCode (cname = "GCRY_WEAK_RANDOM")] + WEAK, + [CCode (cname = "GCRY_STRONG_RANDOM")] + STRONG, + [CCode (cname = "GCRY_VERY_STRONG_RANDOM")] + VERY_STRONG + } + + [CCode (cname = "gcry_randomize")] + public static void randomize (uchar[] buffer, Level level = Level.VERY_STRONG); + [CCode (cname = "gcry_fast_random_poll")] + public static Error poll (); + [CCode (cname = "gcry_random_bytes", array_length = false)] + public static uchar[] random_bytes (size_t nbytes, Level level = Level.VERY_STRONG); + [CCode (cname = "gcry_random_bytes_secure")] + public static uchar[] random_bytes_secure (size_t nbytes, Level level = Level.VERY_STRONG); + [CCode (cname = "gcry_create_nonce")] + public static void nonce (uchar[] buffer); + } + + [Compact, CCode (cname = "struct gcry_mpi", cprefix = "gcry_mpi_", free_function = "gcry_mpi_release")] + public class MPI { + [CCode (cname = "enum gcry_mpi_format", cprefix = "GCRYMPI_FMT_")] + public enum Format { + NONE, + STD, + PGP, + SSH, + HEX, + USG + } + + [CCode (cname = "enum gcry_mpi_flag", cprefix = "GCRYMPI_FLAG_")] + public enum Flag { + SECURE, + OPAQUE + } + + public MPI (uint nbits); + [CCode (cname = "gcry_mpi_snew")] + public MPI.secure (uint nbits); + public MPI copy (); + public void set (MPI u); + public void set_ui (ulong u); + public void swap (); + public int cmp (MPI v); + public int cmp_ui (ulong v); + + public static Error scan (out MPI ret, MPI.Format format, [CCode (array_length = false)] uchar[] buffer, size_t buflen, out size_t nscanned); + [CCode (instance_pos = -1)] + public Error print (MPI.Format format, [CCode (array_length = false)] uchar[] buffer, size_t buflen, out size_t nwritter); + [CCode (instance_pos = -1)] + public Error aprint (MPI.Format format, out uchar[] buffer); + + public void add (MPI u, MPI v); + public void add_ui (MPI u, ulong v); + public void addm (MPI u, MPI v, MPI m); + public void sub (MPI u, MPI v); + public void sub_ui (MPI u, MPI v); + public void subm (MPI u, MPI v, MPI m); + public void mul (MPI u, MPI v); + public void mul_ui (MPI u, ulong v); + public void mulm (MPI u, MPI v, MPI m); + public void mul_2exp (MPI u, ulong cnt); + public void div (MPI q, MPI r, MPI dividend, MPI divisor, int round); + public void mod (MPI dividend, MPI divisor); + public void powm (MPI b, MPI e, MPI m); + public int gcd (MPI a, MPI b); + public int invm (MPI a, MPI m); + + public uint get_nbits (); + public int test_bit (uint n); + public void set_bit (uint n); + public void clear_bit (uint n); + public void set_highbit (uint n); + public void clear_highbit (uint n); + public void rshift (MPI a, uint n); + public void lshift (MPI a, uint n); + + public void set_flag (MPI.Flag flag); + public void clear_flag (MPI.Flag flag); + public int get_flag (MPI.Flag flag); + } + + [Compact, CCode (cname = "struct gcry_sexp", free_function = "gcry_sexp_release")] + public class SExp { + [CCode (cprefix = "GCRYSEXP_FMT_")] + public enum Format { + DEFAULT, + CANON, + BASE64, + ADVANCED + } + + public static Error @new (out SExp retsexp, void * buffer, size_t length, int autodetect); + public static Error create (out SExp retsexp, void * buffer, size_t length, int autodetect, GLib.DestroyNotify free_function); + public static Error sscan (out SExp retsexp, out size_t erroff, char[] buffer); + public static Error build (out SExp retsexp, out size_t erroff, string format, ...); + public size_t sprint (Format mode, char[] buffer); + public static size_t canon_len (uchar[] buffer, out size_t erroff, out int errcode); + public SExp find_token (string token, size_t token_length = 0); + public int length (); + public SExp? nth (int number); + public SExp? car (); + public SExp? cdr (); + public unowned char[] nth_data (int number); + public gcry_string nth_string (int number); + public MPI nth_mpi (int number, MPI.Format mpifmt); + } + + [CCode (cname = "char", free_function = "gcry_free")] + public class gcry_string : string { } + + [CCode (lower_case_cprefix = "gcry_pk_")] + namespace PublicKey { + [CCode (cname = "enum gcry_pk_algos")] + public enum Algorithm { + RSA, + ELG_E, + DSA, + ELG, + ECDSA; + + [CCode (cname = "gcry_pk_algo_name")] + public unowned string to_string (); + [CCode (cname = "gcry_pk_map_name")] + public static Algorithm map_name (string name); + } + + public static Error encrypt (out SExp ciphertext, SExp data, SExp pkey); + public static Error decrypt (out SExp plaintext, SExp data, SExp skey); + public static Error sign (out SExp signature, SExp data, SExp skey); + public static Error verify (SExp signature, SExp data, SExp pkey); + public static Error testkey (SExp key); + public static Error genkey (out SExp r_key, SExp s_params); + public static uint get_nbits (SExp key); + } + + [CCode (lower_case_cprefix = "gcry_kdf_")] + namespace KeyDerivation { + [CCode (cname = "gcry_kdf_algos", cprefix = "GCRY_KDF_", has_type_id = false)] + public enum Algorithm { + NONE, + SIMPLE_S2K, + SALTED_S2K, + ITERSALTED_S2K, + PBKDF1, + PBKDF2, + SCRYPT + } + + public GCrypt.Error derive ([CCode (type = "const void*", array_length_type = "size_t")] uint8[] passphrasse, GCrypt.KeyDerivation.Algorithm algo, GCrypt.Hash.Algorithm subalgo, [CCode (type = "const void*", array_length_type = "size_t")] uint8[] salt, ulong iterations, [CCode (type = "void*", array_length_type = "size_t", array_length_pos = 5.5)] uint8[] keybuffer); + } +} diff --git a/libdino/vapi/libsrtp2.vapi b/libdino/vapi/libsrtp2.vapi new file mode 100644 index 00000000..f8f2d297 --- /dev/null +++ b/libdino/vapi/libsrtp2.vapi @@ -0,0 +1,146 @@ +[CCode (cheader_filename = "srtp2/srtp.h")] +namespace Srtp { +public const uint MAX_TRAILER_LEN; + +public static ErrorStatus init(); +public static ErrorStatus shutdown(); + +[Compact] +[CCode (cname = "srtp_ctx_t", cprefix = "srtp_", free_function = "srtp_dealloc")] +public class Context { + public static ErrorStatus create(out Context session, Policy? policy); + + public ErrorStatus protect([CCode (type = "void*", array_length = false)] uint8[] rtp, ref int len); + public ErrorStatus unprotect([CCode (type = "void*", array_length = false)] uint8[] rtp, ref int len); + + public ErrorStatus protect_rtcp([CCode (type = "void*", array_length = false)] uint8[] rtcp, ref int len); + public ErrorStatus unprotect_rtcp([CCode (type = "void*", array_length = false)] uint8[] rtcp, ref int len); + + public ErrorStatus add_stream(ref Policy policy); + public ErrorStatus update_stream(ref Policy policy); + public ErrorStatus remove_stream(uint ssrc); + public ErrorStatus update(ref Policy policy); +} + +[CCode (cname = "srtp_ssrc_t")] +public struct Ssrc { + public SsrcType type; + public uint value; +} + +[CCode (cname = "srtp_ssrc_type_t", cprefix = "ssrc_")] +public enum SsrcType { + undefined, specific, any_inbound, any_outbound +} + +[CCode (cname = "srtp_policy_t", destroy_function = "")] +public struct Policy { + public Ssrc ssrc; + public CryptoPolicy rtp; + public CryptoPolicy rtcp; + [CCode (array_length = false)] + public uint8[] key; + public ulong num_master_keys; + public ulong window_size; + [CCode (ctype = "int")] + public bool allow_repeat_tx; + [CCode (array_length_cname = "enc_xtn_hdr_count")] + public int[] enc_xtn_hdr; + public Policy* next; +} + +[CCode (cname = "srtp_crypto_policy_t")] +public struct CryptoPolicy { + public CipherType cipher_type; + public int cipher_key_len; + public AuthType auth_type; + public int auth_key_len; + public int auth_tag_len; + public SecurityServices sec_serv; + + public void set_aes_cm_128_hmac_sha1_80(); + public void set_aes_cm_128_hmac_sha1_32(); + public void set_aes_cm_128_null_auth(); + public void set_aes_cm_192_hmac_sha1_32(); + public void set_aes_cm_192_hmac_sha1_80(); + public void set_aes_cm_192_null_auth(); + public void set_aes_cm_256_hmac_sha1_32(); + public void set_aes_cm_256_hmac_sha1_80(); + public void set_aes_cm_256_null_auth(); + public void set_aes_gcm_128_16_auth(); + public void set_aes_gcm_128_8_auth(); + public void set_aes_gcm_128_8_only_auth(); + public void set_aes_gcm_256_16_auth(); + public void set_aes_gcm_256_8_auth(); + public void set_aes_gcm_256_8_only_auth(); + public void set_null_cipher_hmac_null(); + public void set_null_cipher_hmac_sha1_80(); + + public void set_rtp_default(); + public void set_rtcp_default(); + + public void set_from_profile_for_rtp(Profile profile); + public void set_from_profile_for_rtcp(Profile profile); +} + +[CCode (cname = "srtp_profile_t", cprefix = "srtp_profile_")] +public enum Profile { + reserved, aes128_cm_sha1_80, aes128_cm_sha1_32, null_sha1_80, null_sha1_32, aead_aes_128_gcm, aead_aes_256_gcm +} + +[CCode (cname = "srtp_cipher_type_id_t")] +public struct CipherType : uint32 {} + +[CCode (cname = "srtp_auth_type_id_t")] +public struct AuthType : uint32 {} + +[CCode (cname = "srtp_sec_serv_t", cprefix = "sec_serv_")] +public enum SecurityServices { + none, conf, auth, conf_and_auth; +} + +[CCode (cname = "srtp_err_status_t", cprefix = "srtp_err_status_", has_type_id = false)] +public enum ErrorStatus { + ok, + fail, + bad_param, + alloc_fail, + dealloc_fail, + init_fail, + terminus, + auth_fail, + cipher_fail, + replay_fail, + replay_old, + + algo_fail, + no_such_op, + no_ctx, + cant_check, + key_expired, + socket_err, + signal_err, + nonce_bad, + read_fail, + write_fail, + + parse_err, + encode_err, + semaphore_err, + pfkey_err, + bad_mki, + pkt_idx_old, + pkt_idx_adv +} + +[CCode (cname = "srtp_log_level_t", cprefix = "srtp_log_level_", has_type_id = false)] +public enum LogLevel { + error, warning, info, debug +} + +[CCode (cname = "srtp_log_handler_func_t")] +public delegate void LogHandler(LogLevel level, string msg); + +public static ErrorStatus install_log_handler(LogHandler func); + +} \ No newline at end of file diff --git a/libdino/vapi/openssl.vapi b/libdino/vapi/openssl.vapi new file mode 100644 index 00000000..87693d37 --- /dev/null +++ b/libdino/vapi/openssl.vapi @@ -0,0 +1,322 @@ +[CCode (cprefix = "")] +namespace OpenSSL { + [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")] + namespace ASN1 { + [Compact] + [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")] + public class Integer { + public bool @set (long v); + } + + [Compact] + [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")] + public class Time { + public bool @set (time_t t); + } + } + [Compact] + [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)] + public class BIO { + [Compact] + [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)] + public class Method { + public Method (Type type, string name); + [CCode (has_target = false)] + public delegate int WriteFunc (BIO bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf); + [CCode (has_target = false)] + public delegate int ReadFunc (BIO bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf); + [CCode (has_target = false, simple_generics = true)] + public delegate long CtrlFunc (BIO bio, ControlCommand cmd, long num, void* ptr); + public WriteFunc write { get; set; } + public ReadFunc read { get; set; } + public CtrlFunc ctrl { get; set; } + } + + [Flags] + [CCode (cname = "int")] + public enum Type { + SOURCE_SINK, + DGRAM, + } + + [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)] + public enum ControlCommand { + RESET, + EOF, + SET, + GET, + PUSH, + POP, + GET_CLOSE, + SET_CLOSE, + PENDING, + FLUSH, + DUP, + WPENDING, + + DGRAM_QUERY_MTU, + DGRAM_GET_MTU, + DGRAM_SET_MTU, + DGRAM_SET_PEER, + DGRAM_SET_NEXT_TIMEOUT, + DGRAM_GET_PEER, + DGRAM_GET_FALLBACK_MTU, + DGRAM_SET_DONT_FRAG, + DGRAM_GET_MTU_OVERHEAD, + } + + public BIO (Method type); + public T data { get; set; } + + public void clear_retry_flags (); + public void set_retry_read (); + public bool should_read (); + } + + [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")] + namespace ERR { + public ulong get_error (); + public unowned string lib_error_string (ulong error); + public unowned string reason_error_string (ulong error); + } + + [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")] + namespace EVP { + [Compact] + [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] + public class Key { + public Key (); + [CCode (cheader_filename = "openssl_utils.h")] + public Key.generate_ecdsa (string curve); + } + [Compact] + [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")] + public class MessageDigest { + } + + [Compact] + [CCode (cname = "EVP_CIPHER", lower_case_cprefix = "EVP_CIPHER_", cprefix = "EVP_CIPHER_", ref_function = "EVP_CIPHER_up_ref", ref_function_void = true, unref_function = "EVP_CIPHER_free")] + public class Cipher { + + } + + [Compact] + [CCode (cname = "EVP_CIPHER_CTX", lower_case_cprefix = "EVP_CIPHER_CTX_", cprefix = "EVP_CIPHER_CTX_", free_function = "EVP_CIPHER_CTX_free")] + public class CipherContext { + public CipherContext (); + + [CCode (simple_generics = true)] + public int ctrl(Control cmd, int p1, T? p2); + + [CCode (cname = "EVP_EncryptInit")] + private int encrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); + public void encrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { + throw_if_error (encrypt_init_ (cipher, key, iv)); + } + [CCode (cname = "EVP_EncryptUpdate")] + private int encrypt_update_ ([CCode (array_length = false)] uint8[] out, out int out_len, uint8[] in); + public void encrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { + throw_if_error (encrypt_update_ (@out, out out_len, in)); + } + [CCode (cname = "EVP_EncryptFinal")] + private int encrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); + public void encrypt_final (uint8[] out, out int out_len) throws GLib.Error { + throw_if_error (encrypt_final_ (@out, out out_len)); + } + + [CCode (cname = "EVP_DecryptInit")] + private int decrypt_init_ (Cipher? cipher, [CCode (array_length = false)] uint8[]? key, [CCode (array_length = false)] uint8[]? iv); + public void decrypt_init (Cipher? cipher, uint8[]? key, uint8[]? iv) throws GLib.Error { + throw_if_error (decrypt_init_ (cipher, key, iv)); + } + [CCode (cname = "EVP_DecryptUpdate")] + private int decrypt_update_ ([CCode (array_length = false)] uchar[] out, out int out_len, uint8[] in); + public void decrypt_update (uint8[] out, out int out_len, uint8[] in) throws GLib.Error { + throw_if_error (decrypt_update_ (@out, out out_len, in)); + } + [CCode (cname = "EVP_DecryptFinal")] + private int decrypt_final_ ([CCode (array_length = false)] uchar[] out, out int out_len); + public void decrypt_final (uint8[] out, out int out_len) throws GLib.Error { + throw_if_error (decrypt_final_ (@out, out out_len)); + } + + public int reset(); + public int set_key_length (int keylen); + public int set_padding (int pad); + } + + [CCode (cname = "int", cprefix = "EVP_CTRL_", has_type_id = false)] + public enum Control { + INIT, + SET_KEY_LENGTH, + GET_RC2_KEY_BITS, + SET_RC2_KEY_BITS, + GET_RC5_ROUNDS, + SET_RC5_ROUNDS, + RAND_KEY, + PBE_PRF_NID, + COPY, + AEAD_SET_IVLEN, + AEAD_GET_TAG, + AEAD_SET_TAG, + AEAD_SET_IV_FIXED, + GCM_SET_IVLEN, + GCM_GET_TAG, + GCM_SET_TAG, + GCM_SET_IV_FIXED, + GCM_IV_GEN, + CCM_SET_IVLEN, + CCM_GET_TAG, + CCM_SET_TAG, + CCM_SET_IV_FIXED, + CCM_SET_L, + CCM_SET_MSGLEN, + AEAD_TLS1_AAD, + AEAD_SET_MAC_KEY, + GCM_SET_IV_INV, + TLS1_1_MULTIBLOCK_AAD, + TLS1_1_MULTIBLOCK_ENCRYPT, + TLS1_1_MULTIBLOCK_DECRYPT, + TLS1_1_MULTIBLOCK_MAX_BUFSIZE, + SSL3_MASTER_SECRET, + SET_SBOX, + SBOX_USED, + KEY_MESH, + BLOCK_PADDING_MODE, + SET_PIPELINE_OUTPUT_BUFS, + SET_PIPELINE_INPUT_BUFS, + SET_PIPELINE_INPUT_LENS, + GET_IVLEN, + } + + public static unowned Cipher? aes_128_gcm (); + public static unowned Cipher? aes_256_gcm (); + + public static unowned MessageDigest sha256 (); + } + + [CCode (lower_case_cprefix = "RAND_", cprefix = "RAND_", cheader_filename = "openssl/rand.h")] + namespace RAND { + public static int bytes (uint8[] buf); + public static int priv_bytes (uint8[] buf); + } + + [Compact] + [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")] + class SSL { + [Compact] + [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")] + public class Context { + public Context (Method method); + public int set_tlsext_use_srtp (string profiles); + public int use_certificate (X509.Certificate certificate); + [CCode (cname = "SSL_CTX_use_PrivateKey")] + public int use_private_key (EVP.Key private_key); + } + + [CCode (cname = "const SSL_METHOD*")] + public enum Method { + [CCode (cname = "DTLS_client_method()")] + DTLS_CLIENT, + [CCode (cname = "DTLS_server_method()")] + DTLS_SERVER, + } + + [CCode (cname = "int", has_type_id = false)] + public enum Error { + NONE, + ZERO_RETURN, + WANT_READ, + WANT_WRITE, + WANT_CONNECT, + WANT_ACCEPT, + WANT_X509_LOOKUP, + WANT_ASYNC, + WANT_ASYNC_JOB, + WANT_CLIENT_HELLO_CB, + SYSCALL, + SSL + } + + public SSL (Context context); + public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; } + public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; } + + [CCode (cname = "SSL_do_handshake")] + private int do_handshake_ (); + [CCode (cname = "SSL_do_handshake_")] + public Error do_handshake () throws GLib.Error { + int ret = throw_if_error (do_handshake_ ()); + return get_error (ret); + } + [CCode (cname = "SSL_export_keying_material")] + private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context); + [CCode (cname = "SSL_export_keying_material_")] + public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error { + throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null)); + } + public Error get_error (int ret); + public void set_accept_state (); + public void set_connect_state (); + public int want (); + } + + [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")] + namespace X509 { + [Compact] + [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")] + public class Certificate { + public Certificate (); + public ASN1.Time not_before { + [CCode (cname = "X509_get_notBefore")] + get; + [CCode (cname = "X509_set_notBefore")] + set; + } + public ASN1.Time not_after { + [CCode (cname = "X509_get_notAfter")] + get; + [CCode (cname = "X509_set_notAfter")] + set; + } + public ASN1.Integer serial_number { + [CCode (cname = "X509_get_serialNumber")] + get; + [CCode (cname = "X509_set_serialNumber")] + set; + } + [CCode (cname = "X509_digest")] + private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len); + [CCode (cname = "X509_digest_")] + public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error { + uint8[] buf = new uint8[buf_len]; + uint buf_out_size = (uint) buf_len; + throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size)); + + uint8[] ret = new uint8[buf_out_size]; + for (int i = 0; i < buf_out_size; i++) { + ret[i] = buf[i]; + } + return ret; + } + [CCode (cname = "X509_set_pubkey")] + public int set_public_key (EVP.Key public_key); + public int set_version (long version); + [CCode (cname = "X509_sign")] + private int sign_ (EVP.Key private_key, EVP.MessageDigest md); + [CCode (cname = "X509_sign_")] + public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error { + throw_if_error (sign_ (private_key, md)); + } + } + } + + public int throw_if_error(int res) throws GLib.Error { + if (res <= 0) { + ulong error = ERR.get_error (); + if (error == 0) return res; + throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error)); + } + return res; + } +} \ No newline at end of file diff --git a/meson.build b/meson.build index 84597fd4..b9df102b 100644 --- a/meson.build +++ b/meson.build @@ -47,33 +47,28 @@ vala_c_args = cc.get_supported_arguments([ '-Wno-unused-variable', ]) -plugin_crypto = get_option('plugin-ice') -foreach plugin : ['plugin-ice', 'plugin-omemo', 'plugin-rtp'] - if get_option(plugin).enabled() and not plugin_crypto.enabled() - plugin_crypto = get_option(plugin) - elif get_option(plugin).allowed() and not plugin_crypto.allowed() - plugin_crypto = get_option(plugin) - endif -endforeach - if get_option('crypto-backend') == 'auto' # Prefer libgcrypt/gnutls over openssl because glib-networking is usually # built with gnutls anyway. dep_libgcrypt = dependency('libgcrypt', required: false) dep_gnutls = dependency('gnutls', required: false) if dep_libgcrypt.found() and dep_gnutls.found() - crypto_backend = 'gnutls' + crypto_backend = 'gnu' else - dep_openssl = dependency('openssl', disabler: true, required: plugin_crypto) - crypto_backend = 'openssl' + dep_openssl = dependency('openssl', required: false) + if dep_openssl.found() + crypto_backend = 'openssl' + else + error('Could not find crypto backend automatically. Specify explicitly via crypto-backend option.') + endif endif elif get_option('crypto-backend') == 'openssl' - dep_openssl = dependency('openssl', disabler: true, required: plugin_crypto) + dep_openssl = dependency('openssl', required: true) crypto_backend = 'openssl' -elif get_option('crypto-backend') == 'gnutls' - dep_libgcrypt = dependency('libgcrypt', disabler: true, required: plugin_crypto) - dep_gnutls = dependency('gnutls', disabler: true, required: get_option('plugin-ice')) - crypto_backend = 'gnutls' +elif get_option('crypto-backend') == 'gnu' + dep_libgcrypt = dependency('libgcrypt', required: true) + dep_gnutls = dependency('gnutls', required: get_option('plugin-ice')) + crypto_backend = 'gnu' endif dep_gdk_pixbuf = dependency('gdk-pixbuf-2.0') @@ -92,7 +87,7 @@ dep_icu_uc = dependency('icu-uc') dep_libadwaita = dependency('libadwaita-1', version: '>=1.5') dep_libcanberra = dependency('libcanberra', disabler: true, required: get_option('plugin-notification-sound')) dep_libqrencode = dependency('libqrencode', disabler: true, required: get_option('plugin-omemo')) -dep_libsrtp2 = dependency('libsrtp2', disabler: true, required: plugin_crypto) +dep_libsrtp2 = dependency('libsrtp2', disabler: true, required: true) dep_libomemo_c = dependency('libomemo-c', disabler: true, required: get_option('plugin-omemo')) dep_libsoup = dependency('libsoup-3.0') dep_nice = dependency('nice', version: '>=0.1.15', disabler: true, required: get_option('plugin-ice')) @@ -119,5 +114,4 @@ subdir('qlite') subdir('xmpp-vala') subdir('libdino') subdir('main') -subdir('crypto-vala') subdir('plugins') diff --git a/meson_options.txt b/meson_options.txt index bbf7a046..4700ef74 100644 --- a/meson_options.txt +++ b/meson_options.txt @@ -1,7 +1,7 @@ option('plugindir', type: 'string', value: 'dino/plugins', description: 'Dino plugin directory, relative to libdir') option('set-install-rpath', type: 'boolean', value: false, description: 'Set rpath of installed binaries to the configured libdir') -option('crypto-backend', type: 'combo', choices: ['auto', 'openssl', 'gnutls'], value: 'auto', description: 'Preferred crypto backend') +option('crypto-backend', type: 'combo', choices: ['auto', 'openssl', 'gnu'], value: 'auto', description: 'Preferred crypto backend') option('plugin-ice', type: 'feature', value: 'enabled', description: 'Peer-to-peer communication') option('plugin-omemo', type: 'feature', value: 'enabled', description: 'End-to-end encryption using OMEMO') diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 5ed807bf..5161b123 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -1,5 +1,4 @@ dependencies = [ - dep_crypto_vala, dep_dino, dep_gee, dep_gio, @@ -23,12 +22,12 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if crypto_backend == 'gnutls' +if crypto_backend == 'gnu' dependencies += [ dep_gnutls ] sources += files( 'src/dtls_srtp_gnutls.vala' ) -else # openssl +elif crypto_backend == 'openssl' dependencies += [ dep_openssl ] sources += files( 'src/dtls_srtp_openssl.vala', diff --git a/plugins/omemo/meson.build b/plugins/omemo/meson.build index d195525e..978fb9a6 100644 --- a/plugins/omemo/meson.build +++ b/plugins/omemo/meson.build @@ -1,7 +1,6 @@ subdir('po') dependencies = [ dep_libadwaita, - dep_crypto_vala, dep_dino, dep_gee, dep_glib, @@ -61,10 +60,10 @@ c_args = vala_c_args + [ '-DGETTEXT_PACKAGE="dino-omemo"', '-DLOCALE_INSTALL_DIR="@0@"'.format(get_option('prefix') / get_option('localedir')), ] -if crypto_backend == 'gnutls' +if crypto_backend == 'gnu' dependencies += [ dep_libgcrypt ] sources += files('src/native/helper_gcrypt.c') -else +elif crypto_backend == 'openssl' dependencies += [ dep_openssl ] sources += files('src/native/helper_openssl.c') endif diff --git a/plugins/omemo/src/file_transfer/file_decryptor.vala b/plugins/omemo/src/file_transfer/file_decryptor.vala index ff96b4a3..8ae0b96b 100644 --- a/plugins/omemo/src/file_transfer/file_decryptor.vala +++ b/plugins/omemo/src/file_transfer/file_decryptor.vala @@ -1,6 +1,6 @@ using Dino.Entities; -using Crypto; +using Dino.Crypto; using Omemo; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/file_transfer/file_encryptor.vala b/plugins/omemo/src/file_transfer/file_encryptor.vala index 1aed752f..5f1d6e69 100644 --- a/plugins/omemo/src/file_transfer/file_encryptor.vala +++ b/plugins/omemo/src/file_transfer/file_encryptor.vala @@ -1,7 +1,7 @@ using Gee; using Gtk; -using Crypto; +using Dino.Crypto; using Dino.Entities; using Xmpp; using Omemo; diff --git a/plugins/omemo/src/jingle/jet_omemo.vala b/plugins/omemo/src/jingle/jet_omemo.vala index b1a27e15..8a84d3d2 100644 --- a/plugins/omemo/src/jingle/jet_omemo.vala +++ b/plugins/omemo/src/jingle/jet_omemo.vala @@ -1,4 +1,4 @@ -using Crypto; +using Dino.Crypto; using Dino; using Dino.Entities; using Gee; diff --git a/plugins/rtp/meson.build b/plugins/rtp/meson.build index fadce062..b4ba5cf6 100644 --- a/plugins/rtp/meson.build +++ b/plugins/rtp/meson.build @@ -1,5 +1,4 @@ dependencies = [ - dep_crypto_vala, dep_dino, dep_gee, dep_glib, -- cgit v1.3 From 98ef191bfb3cc5694b9d1001e46a9b00abbd7195 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sun, 23 Aug 2026 19:32:25 +0200 Subject: Move qlite into libdino --- libdino/dino.deps | 2 +- libdino/meson.build | 12 +- libdino/src/qlite/column.vala | 190 ++++++++++++++++ libdino/src/qlite/database.vala | 163 ++++++++++++++ libdino/src/qlite/delete_builder.vala | 62 ++++++ libdino/src/qlite/insert_builder.vala | 84 ++++++++ libdino/src/qlite/query_builder.vala | 238 +++++++++++++++++++++ libdino/src/qlite/row.vala | 147 +++++++++++++ libdino/src/qlite/statement_builder.vala | 58 +++++ libdino/src/qlite/table.vala | 218 +++++++++++++++++++ libdino/src/qlite/update_builder.vala | 103 +++++++++ libdino/src/qlite/upsert_builder.vala | 93 ++++++++ libdino/src/service/avatar_manager.vala | 4 +- libdino/src/service/call_store.vala | 2 +- libdino/src/service/contact_model.vala | 1 - libdino/src/service/content_item_store.vala | 2 +- libdino/src/service/database.vala | 2 +- libdino/src/service/entity_info.vala | 2 +- libdino/src/service/fallback_body.vala | 1 - libdino/src/service/file_transfer_storage.vala | 2 +- libdino/src/service/history_sync.vala | 2 +- libdino/src/service/message_correction.vala | 2 +- libdino/src/service/message_deletion.vala | 1 - libdino/src/service/message_processor.vala | 2 +- libdino/src/service/message_storage.vala | 2 +- libdino/src/service/occupant_id_store.vala | 2 +- libdino/src/service/reactions.vala | 4 +- libdino/src/service/replies.vala | 2 +- libdino/src/service/search_processor.vala | 4 +- libdino/src/service/util.vala | 1 - main/meson.build | 1 - meson.build | 1 - plugins/ice/meson.build | 1 - plugins/notification-sound/meson.build | 1 - plugins/omemo/meson.build | 1 - plugins/omemo/src/logic/database.vala | 2 +- plugins/omemo/src/logic/decrypt.vala | 5 +- plugins/omemo/src/logic/manager.vala | 5 +- plugins/omemo/src/logic/pre_key_store.vala | 2 +- plugins/omemo/src/logic/session_store.vala | 2 +- plugins/omemo/src/logic/signed_pre_key_store.vala | 2 +- plugins/omemo/src/logic/trust_manager.vala | 7 +- plugins/omemo/src/ui/bad_messages_populator.vala | 2 +- plugins/omemo/src/ui/call_encryption_entry.vala | 5 +- plugins/omemo/src/ui/contact_details_provider.vala | 1 - plugins/omemo/src/ui/encryption_list_entry.vala | 5 +- .../omemo/src/ui/encryption_preferences_entry.vala | 9 +- plugins/omemo/src/ui/manage_key_dialog.vala | 3 +- plugins/openpgp/meson.build | 1 - plugins/openpgp/src/database.vala | 3 +- plugins/rtp/meson.build | 1 - qlite/meson.build | 27 --- qlite/qlite.deps | 3 - qlite/src/column.vala | 190 ---------------- qlite/src/database.vala | 163 -------------- qlite/src/delete_builder.vala | 62 ------ qlite/src/insert_builder.vala | 84 -------- qlite/src/query_builder.vala | 238 --------------------- qlite/src/row.vala | 147 ------------- qlite/src/statement_builder.vala | 58 ----- qlite/src/table.vala | 218 ------------------- qlite/src/update_builder.vala | 103 --------- qlite/src/upsert_builder.vala | 93 -------- 63 files changed, 1414 insertions(+), 1440 deletions(-) create mode 100644 libdino/src/qlite/column.vala create mode 100644 libdino/src/qlite/database.vala create mode 100644 libdino/src/qlite/delete_builder.vala create mode 100644 libdino/src/qlite/insert_builder.vala create mode 100644 libdino/src/qlite/query_builder.vala create mode 100644 libdino/src/qlite/row.vala create mode 100644 libdino/src/qlite/statement_builder.vala create mode 100644 libdino/src/qlite/table.vala create mode 100644 libdino/src/qlite/update_builder.vala create mode 100644 libdino/src/qlite/upsert_builder.vala delete mode 100644 qlite/meson.build delete mode 100644 qlite/qlite.deps delete mode 100644 qlite/src/column.vala delete mode 100644 qlite/src/database.vala delete mode 100644 qlite/src/delete_builder.vala delete mode 100644 qlite/src/insert_builder.vala delete mode 100644 qlite/src/query_builder.vala delete mode 100644 qlite/src/row.vala delete mode 100644 qlite/src/statement_builder.vala delete mode 100644 qlite/src/table.vala delete mode 100644 qlite/src/update_builder.vala delete mode 100644 qlite/src/upsert_builder.vala (limited to 'plugins/ice') diff --git a/libdino/dino.deps b/libdino/dino.deps index bef3fb2a..b14c7d54 100644 --- a/libdino/dino.deps +++ b/libdino/dino.deps @@ -2,5 +2,5 @@ gee-0.8 gio-2.0 glib-2.0 gmodule-2.0 -qlite +sqlite3 xmpp-vala diff --git a/libdino/meson.build b/libdino/meson.build index dbaddf56..5c7c20c4 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -9,7 +9,7 @@ dependencies = [ dep_gmodule, dep_libsoup, dep_libsrtp2, - dep_qlite, + dep_sqlite3, dep_xmpp_vala ] sources = files( @@ -34,6 +34,16 @@ sources = files( 'src/plugin/interfaces.vala', 'src/plugin/loader.vala', 'src/plugin/registry.vala', + 'src/qlite/column.vala', + 'src/qlite/database.vala', + 'src/qlite/delete_builder.vala', + 'src/qlite/insert_builder.vala', + 'src/qlite/query_builder.vala', + 'src/qlite/row.vala', + 'src/qlite/statement_builder.vala', + 'src/qlite/table.vala', + 'src/qlite/update_builder.vala', + 'src/qlite/upsert_builder.vala', 'src/service/avatar_manager.vala', 'src/service/blocking_manager.vala', 'src/service/call_store.vala', diff --git a/libdino/src/qlite/column.vala b/libdino/src/qlite/column.vala new file mode 100644 index 00000000..8f45307f --- /dev/null +++ b/libdino/src/qlite/column.vala @@ -0,0 +1,190 @@ +using Sqlite; + +namespace Dino.Qlite { + +public abstract class Column { + public const string DEFAULT_TABLE_NAME = ""; + + public string name { get; private set; } + public string? default { get; set; } + public int sqlite_type { get; private set; } + public bool primary_key { get; set; } + public bool auto_increment { get; set; } + public bool unique { get; set; } + public virtual bool not_null { get; set; } + public long min_version { get; set; default = -1; } + public long max_version { get; set; default = long.MAX; } + internal Table table { get; set; } + + public abstract T get(Row row, string? table_name = DEFAULT_TABLE_NAME); + + public virtual bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return false; + } + + internal abstract void bind(Statement stmt, int index, T value); + + public string to_string() { + return table == null ? name : (table.name + "." + name); + } + + public string to_column_definition() { + string res = name; + switch (sqlite_type) { + case INTEGER: + res += " INTEGER"; + break; + case FLOAT: + res += " REAL"; + break; + case TEXT: + res += " TEXT"; + break; + default: + res += " UNKNOWN"; + break; + } + if (primary_key) { + res += " PRIMARY KEY"; + if (auto_increment) res += " AUTOINCREMENT"; + } + if (not_null) res += " NOT NULL"; + if (unique) res += " UNIQUE"; + if (default != null) res += @" DEFAULT $((!) default)"; + + return res; + } + + Column(string name, int type) { + this.name = name; + this.sqlite_type = type; + } + + public class Integer : Column { + public Integer(string name) { + base(name, INTEGER); + } + + public override int get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (int) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, int value) { + stmt.bind_int(index, value); + } + } + + public class Long : Column { + public Long(string name) { + base(name, INTEGER); + } + + public override long get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (long) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, long value) { + stmt.bind_int64(index, value); + } + } + + public class NullableReal : Column { + public NullableReal(string name) { + base(name, FLOAT); + } + + public override bool not_null { get { return false; } set {} } + + public override double? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return !row.has_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + internal override void bind(Statement stmt, int index, double? value) { + stmt.bind_double(index, value); + } + } + + public class Text : Column { + public Text(string name) { + base(name, TEXT); + } + + public override string? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return get(row, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == null; + } + + internal override void bind(Statement stmt, int index, string? value) { + if (value != null) { + stmt.bind_text(index, (!) value); + } else { + stmt.bind_null(index); + } + } + } + + public class NonNullText : Column { + public NonNullText(string name) { + base(name, TEXT); + } + + public override bool not_null { get { return true; } set {} } + + public override string get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return (!)row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); + } + + public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return false; + } + + internal override void bind(Statement stmt, int index, string value) { + stmt.bind_text(index, (!) value); + } + } + + public class BoolText : Column { + public BoolText(string name) { + base(name, TEXT); + } + + public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == "1"; + } + + internal override void bind(Statement stmt, int index, bool value) { + stmt.bind_text(index, value ? "1" : "0"); + } + } + + public class BoolInt : Column { + public BoolInt(string name) { + base(name, INTEGER); + } + + public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { + return row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == 1; + } + + internal override void bind(Statement stmt, int index, bool value) { + stmt.bind_int(index, value ? 1 : 0); + } + } +} + +} diff --git a/libdino/src/qlite/database.vala b/libdino/src/qlite/database.vala new file mode 100644 index 00000000..e55d5b59 --- /dev/null +++ b/libdino/src/qlite/database.vala @@ -0,0 +1,163 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class Database { + private string file_name; + private Sqlite.Database db; + private long expected_version; + private Table[]? tables; + + private Column meta_name = new Column.Text("name") { primary_key = true }; + private Column meta_int_val = new Column.Long("int_val"); + private Column meta_text_val = new Column.Text("text_val"); + private Table meta_table; + + public bool debug = false; + + public Database(string file_name, long expected_version) { + this.file_name = file_name; + this.expected_version = expected_version; + meta_table = new Table(this, "_meta"); + meta_table.init({meta_name, meta_int_val, meta_text_val}); + } + + public void init(Table[] tables) { + Sqlite.config(Config.SERIALIZED); + int ec = Sqlite.Database.open_v2(file_name, out db, OPEN_READWRITE | OPEN_CREATE | 0x00010000); + if (ec != Sqlite.OK) { + error(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + this.tables = tables; + if (debug) db.trace((message) => print(@"Qlite trace: $message\n")); + start_migration(); + } + + public void ensure_init() { + if (tables == null) error(@"Database $file_name was not initialized, call init()"); + } + + private void start_migration() { + try { + exec("BEGIN TRANSACTION"); + } catch (Error e) { + error("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + meta_table.create_table_at_version(expected_version); + long old_version = 0; + old_version = meta_table.row_with(meta_name, "version")[meta_int_val, -1]; + if (old_version == -1) { + foreach (Table t in tables) { + t.create_table_at_version(expected_version); + } + meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); + } else if (expected_version != old_version) { + foreach (Table t in tables) { + t.create_table_at_version(old_version); + } + foreach (Table t in tables) { + t.add_columns_for_version(old_version, expected_version); + } + migrate(old_version); + foreach (Table t in tables) { + t.delete_columns_for_version(old_version, expected_version); + } + if (old_version == -1) { + meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); + } else { + meta_table.update().with(meta_name, "=", "version").set(meta_int_val, expected_version).perform(); + } + } + foreach (Table t in tables) { + t.post(); + } + try { + exec("END TRANSACTION"); + } catch (Error e) { + error("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + + internal int errcode() { + return db.errcode(); + } + + internal string errmsg() { + return db.errmsg(); + } + + internal int64 last_insert_rowid() { + return db.last_insert_rowid(); + } + + // To be implemented by actual implementation if required + // new table columns are added, outdated columns are still present and will be removed afterwards + public virtual void migrate(long old_version) { + } + + public QueryBuilder select(Column[]? columns = null) { + ensure_init(); + return new QueryBuilder(this).select(columns); + } + + internal MatchQueryBuilder match_query(Table table) { + ensure_init(); + return new MatchQueryBuilder(this, table); + } + + public InsertBuilder insert() { + ensure_init(); + return new InsertBuilder(this); + } + + public UpdateBuilder update(Table table) { + ensure_init(); + return new UpdateBuilder(this, table); + } + + public UpsertBuilder upsert(Table table) { + ensure_init(); + return new UpsertBuilder(this, table); + } + + public UpdateBuilder update_named(string table) { + ensure_init(); + return new UpdateBuilder.for_name(this, table); + } + + public DeleteBuilder delete() { + ensure_init(); + return new DeleteBuilder(this); + } + + public RowIterator query_sql(string sql, string[]? args = null) { + ensure_init(); + return new RowIterator(this, sql, args); + } + + internal Statement prepare(string sql) { + ensure_init(); + Sqlite.Statement statement; + if (db.prepare_v2(sql, sql.length, out statement) != OK) { + error("SQLite error: %d - %s: %s", db.errcode(), db.errmsg(), sql); + } + return statement; + } + + public void exec(string sql) throws Error { + ensure_init(); + if (db.exec(sql) != OK) { + throw new Error(-1, 0, "SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + + public bool is_known_column(string table, string field) { + ensure_init(); + foreach (Table t in tables) { + if (t.is_known_column(field)) return true; + } + return false; + } +} + +} diff --git a/libdino/src/qlite/delete_builder.vala b/libdino/src/qlite/delete_builder.vala new file mode 100644 index 00000000..df63bba6 --- /dev/null +++ b/libdino/src/qlite/delete_builder.vala @@ -0,0 +1,62 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class DeleteBuilder : StatementBuilder { + + // DELETE FROM [...] + private Table? table; + private string table_name; + + // WHERE [...] + private string selection = "1"; + private StatementBuilder.AbstractField[] selection_args = {}; + + internal DeleteBuilder(Database db) { + base(db); + } + + public DeleteBuilder from(Table table) { + if (this.table != null) error("Qlite Error: ILLEGAL QUERY: cannot use from() multiple times."); + this.table = table; + this.table_name = table.name; + return this; + } + + public DeleteBuilder from_name(string table) { + this.table_name = table; + return this; + } + + public DeleteBuilder where(string selection, string[]? selection_args = null) { + if (this.selection != "1") error("selection was already done, but where() was called."); + this.selection = selection; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public DeleteBuilder with(Column column, string comp, T value) { + selection_args += new Field(column, value); + selection = @"($selection) AND $(column.name) $comp ?"; + return this; + } + + internal override Statement prepare() { + Statement stmt = db.prepare(@"DELETE FROM $table_name WHERE $selection"); + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i+1); + } + return stmt; + } + + public void perform() { + if (prepare().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + +} + +} diff --git a/libdino/src/qlite/insert_builder.vala b/libdino/src/qlite/insert_builder.vala new file mode 100644 index 00000000..3383f0e2 --- /dev/null +++ b/libdino/src/qlite/insert_builder.vala @@ -0,0 +1,84 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class InsertBuilder : StatementBuilder { + + // INSERT [OR ...] + private bool replace_val; + private string? or_val; + + // INTO [...] + private Table table; + private string table_name; + + // VALUES [...] + private StatementBuilder.AbstractField[] fields = {}; + + internal InsertBuilder(Database db) { + base(db); + } + + public InsertBuilder replace() { + this.replace_val = true; + return this; + } + + public InsertBuilder or(string or) { + this.or_val = or; + return this; + } + + public InsertBuilder into(Table table) { + this.table = table; + this.table_name = table.name; + return this; + } + + public InsertBuilder into_name(string table) { + this.table_name = table; + return this; + } + + public InsertBuilder value(Column column, T value) { + fields += new Field(column, value); + return this; + } + + public InsertBuilder value_null(Column column) { + if (column.not_null) error("Qlite Error: ILLEGAL QUERY: Can't set non-null column %s to null", column.name); + fields += new NullField(column); + return this; + } + + internal override Statement prepare() { + string fields_text = ""; + string value_qs = ""; + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + value_qs += ", "; + fields_text += ", "; + } + fields_text += ((!)fields[i].column).name; + value_qs += "?"; + } + string sql = replace_val ? "REPLACE" : "INSERT"; + if (!replace_val && or_val != null) sql += @" OR $((!)or_val)"; + sql += @" INTO $table_name ( $fields_text ) VALUES ($value_qs)"; + Statement stmt = db.prepare(sql); + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i+1); + } + return stmt; + } + + public int64 perform() { + if (prepare().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + return db.last_insert_rowid(); + } + +} + +} diff --git a/libdino/src/qlite/query_builder.vala b/libdino/src/qlite/query_builder.vala new file mode 100644 index 00000000..40514fd5 --- /dev/null +++ b/libdino/src/qlite/query_builder.vala @@ -0,0 +1,238 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class QueryBuilder : StatementBuilder { + private bool single_result; + + // SELECT [...] + private string column_selector = "*"; + private Column[] columns = {}; + + // FROM [...] + protected Table? table; + protected string? table_name; + + // JOIN [...] + private string joins = ""; + + // WHERE [...] + protected string selection = "1"; + internal StatementBuilder.AbstractField[] selection_args = {}; + + // ORDER BY [...] + private OrderingTerm[]? order_by_terms = {}; + + // GROUP BY [...] + private string? group_by_term; + + // LIMIT [...] OFFSET [...] + private int limit_val; + private int offset_val; + + internal QueryBuilder(Database db) { + base(db); + } + + public QueryBuilder select(Column[] columns = {}) { + this.columns = columns; + if (columns.length != 0) { + for (int i = 0; i < columns.length; i++) { + if (column_selector == "*") { + column_selector = columns[i].to_string(); + } else { + column_selector += ", " + columns[i].to_string(); + } + } + } else { + column_selector = "*"; + } + return this; + } + + public QueryBuilder select_string(string column_selector) { + this.columns = {}; + this.column_selector = column_selector; + return this; + } + + public virtual QueryBuilder from(Table table) { + if (this.table_name != null) error("cannot use from() multiple times."); + this.table = table; + this.table_name = table.name; + return this; + } + + public virtual QueryBuilder from_name(string table) { + this.table_name = table; + return this; + } + + public QueryBuilder outer_join_with(Table table, Column lhs, Column rhs, string? as = null) { + return outer_join_on(table, @"$lhs = $rhs", as); + } + + public QueryBuilder outer_join_on(Table table, string on, string? as = null) { + if (as == null) as = table.name; + joins += @" LEFT OUTER JOIN $(table.name) AS $as ON $on"; + return this; + } + + public QueryBuilder join_with(Table table, Column lhs, Column rhs, string? as = null) { + return join_on(table, @"$lhs = $rhs", as); + } + + public QueryBuilder join_on(Table table, string on, string? as = null) { + if (as == null) as = table.name; + joins += @" JOIN $(table.name) AS $as ON $on"; + return this; + } + + internal QueryBuilder join_name(string table_name, string on) { + joins += @" JOIN $table_name ON $on"; + return this; + } + + public QueryBuilder where(string selection, string[] selection_args = {}) { + this.selection = @"($(this.selection)) AND ($selection)"; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public QueryBuilder with(Column column, string comp, T value) { + if ((column.unique || column.primary_key) && comp == "=") single_result = true; + selection_args += new Field(column, value); + selection = @"($selection) AND $column $comp ?"; + return this; + } + + public QueryBuilder with_null(Column column) { + selection = @"($selection) AND $column ISNULL"; + return this; + } + + public QueryBuilder without_null(Column column) { + selection = @"($selection) AND $column NOT NULL"; + return this; + } + + public QueryBuilder order_by(Column column, string dir = "ASC") { + order_by_terms += new OrderingTerm(column, dir); + return this; + } + + public QueryBuilder order_by_name(string name, string dir) { + order_by_terms += new OrderingTerm.by_name(name, dir); + return this; + } + + public QueryBuilder group_by(Column[] columns) { + foreach(Column col in columns) { + if (group_by_term == null) { + group_by_term = col.to_string(); + } else { + group_by_term += @", $col"; + } + } + return this; + } + + public QueryBuilder limit(int limit) { + if (this.limit_val != 0 && limit > this.limit_val) error("tried to increase an existing limit"); + this.limit_val = limit; + return this; + } + + public QueryBuilder offset(int offset) { + if (this.limit_val == 0) error("limit required before offset"); + this.offset_val = offset; + return this; + } + + public QueryBuilder single() { + this.single_result = true; + return limit(1); + } + + public int64 count() { + this.column_selector = @"COUNT($column_selector) AS count"; + this.single_result = true; + return row().get_integer("count"); + } + + private Row? row_() { + if (!single_result) error("query is not suited to return a single row, but row() was called."); + return iterator().get_next(); + } + + public RowOption row() { + return new RowOption(row_()); + } + + public T get(Column field, T def = null) { + return row().get(field, def); + } + + internal override Statement prepare() { + Statement stmt = db.prepare(@"SELECT $column_selector $(table_name == null ? "" : @"FROM $((!) table_name)") $joins WHERE $selection $(group_by_term == null ? "" : @"GROUP BY $group_by_term") $(OrderingTerm.all_to_string(order_by_terms)) $(limit_val > 0 ? @" LIMIT $limit_val OFFSET $offset_val" : "")"); + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i+1); + } + return stmt; + } + + public RowIterator iterator() { + return new RowIterator.from_query_builder(db, this); + } + + class OrderingTerm { + Column? column; + string column_name; + string dir; + + public OrderingTerm(Column column, string dir) { + this.column = column; + this.column_name = column.to_string(); + this.dir = dir; + } + + public OrderingTerm.by_name(string column_name, string dir) { + this.column_name = column_name; + this.dir = dir; + } + + public string to_string() { + return @"$column_name $dir"; + } + + public static string all_to_string(OrderingTerm[]? terms) { + if (terms == null || terms.length == 0) return ""; + string res = "ORDER BY "+terms[0].to_string(); + for (int i = 1; i < terms.length; i++) { + res += @", $(terms[i])"; + } + return res; + } + } +} + +public class MatchQueryBuilder : QueryBuilder { + internal MatchQueryBuilder(Database db, Table table) { + base(db); + if (table.fts_columns == null) error("MATCH query on non FTS table"); + from(table); + join_name(@"_fts_$table_name", @"_fts_$table_name.docid = $table_name.rowid"); + } + + public MatchQueryBuilder match(Column column, string match) { + if (table == null) error("MATCH must occur after FROM statement"); + if (!(column in table.fts_columns)) error("MATCH selection on non FTS column"); + selection_args += new StatementBuilder.StringField(match); + selection = @"($selection) AND _fts_$table_name.$(column.name) MATCH ?"; + return this; + } +} + +} diff --git a/libdino/src/qlite/row.vala b/libdino/src/qlite/row.vala new file mode 100644 index 00000000..65c80f02 --- /dev/null +++ b/libdino/src/qlite/row.vala @@ -0,0 +1,147 @@ +using Gee; +using Sqlite; + +namespace Dino.Qlite { + +public class Row { + private Map text_map = new HashMap(); + private Map int_map = new HashMap(); + private Map real_map = new HashMap(); + + internal Row(Statement stmt) { + for (int i = 0; i < stmt.column_count(); i++) { + string column_name; + if (stmt.column_origin_name(i) != null) { + column_name = @"$(stmt.column_table_name(i)).$(stmt.column_origin_name(i))"; + } else { + column_name = stmt.column_name(i); + } + switch(stmt.column_type(i)) { + case TEXT: + text_map[column_name] = stmt.column_text(i); + break; + case INTEGER: + int_map[column_name] = (long) stmt.column_int64(i); + break; + case FLOAT: + real_map[column_name] = stmt.column_double(i); + break; + } + } + } + + public T get(Column field) { + return field[this]; + } + + private string field_name(string field, string? table) { + if (table != null) { + return @"$table.$field"; + } else { + return field; + } + } + + public string? get_text(string field, string? table = null) { + if (text_map.has_key(field_name(field, table))) { + return text_map[field_name(field, table)]; + } + return null; + } + + public long get_integer(string field, string? table = null) { + return int_map[field_name(field, table)]; + } + + public bool has_integer(string field, string? table = null) { + return int_map.has_key(field_name(field, table)); + } + + public double get_real(string field, string? table = null, double def = 0) { + return real_map[field_name(field, table)] ?? def; + } + + public bool has_real(string field, string? table = null) { + return real_map.has_key(field_name(field, table)) && real_map[field_name(field, table)] != null; + } + + public string to_string() { + string ret = "{"; + + foreach (string key in text_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: \"$(text_map[key])\""; + } + foreach (string key in int_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: $(int_map[key])"; + } + foreach (string key in real_map.keys) { + if (ret.length > 1) ret += ", "; + ret = @"$ret$key: $(real_map[key])"; + } + + return ret + "}"; + } +} + +public class RowIterator { + private Database db; + private Statement stmt; + + public RowIterator.from_query_builder(Database db, QueryBuilder query) { + this.db = db; + this.stmt = query.prepare(); + } + + public RowIterator(Database db, string sql, string[]? args = null) { + this.db = db; + this.stmt = db.prepare(sql); + if (args != null) { + for (int i = 0; i < args.length; i++) { + stmt.bind_text(i, sql, sql.length); + } + } + } + + public bool next() { + int r = stmt.step(); + if (r == Sqlite.ROW) return true; + if (r == Sqlite.DONE) return false; + warning(@"SQLite error: $(db.errcode()) - $(db.errmsg())"); + return false; + } + + public Row get() { + return new Row(stmt); + } + + public Row? get_next() { + if (next()) return get(); + return null; + } +} + +public class RowOption { + public Row? inner { get; private set; } + + public RowOption(Row? row) { + this.inner = row; + } + + public bool is_present() { + return inner != null; + } + + public T get(Column field, T def = null) { + if (inner == null || field.is_null((!)inner)) return def; + return field[(!)inner]; + } + + internal long get_integer(string field, long def = 0) { + if (inner == null || !((!)inner).has_integer(field)) return def; + return ((!)inner).get_integer(field); + } +} + +} diff --git a/libdino/src/qlite/statement_builder.vala b/libdino/src/qlite/statement_builder.vala new file mode 100644 index 00000000..5c756ab3 --- /dev/null +++ b/libdino/src/qlite/statement_builder.vala @@ -0,0 +1,58 @@ +using Sqlite; + +namespace Dino.Qlite { + +public abstract class StatementBuilder { + protected Database db; + + internal StatementBuilder(Database db) { + this.db = db; + } + + internal abstract Statement prepare(); + + internal abstract class AbstractField { + public T value; + public Column? column; + + AbstractField(T value) { + this.value = value; + } + + internal abstract void bind(Statement stmt, int index); + } + + internal class Field : AbstractField { + public Field(Column column, T value) { + base(value); + this.column = column; + } + + internal override void bind(Statement stmt, int index) { + ((!)column).bind(stmt, index, value); + } + } + + internal class NullField : AbstractField { + public NullField(Column column) { + base(null); + this.column = column; + } + + internal override void bind(Statement stmt, int index) { + stmt.bind_null(index); + } + } + + internal class StringField : AbstractField { + public StringField(string value) { + base(value); + } + + internal override void bind(Statement stmt, int index) { + stmt.bind_text(index, value); + } + } +} + +} diff --git a/libdino/src/qlite/table.vala b/libdino/src/qlite/table.vala new file mode 100644 index 00000000..3b75e22e --- /dev/null +++ b/libdino/src/qlite/table.vala @@ -0,0 +1,218 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class Table { + protected Database db; + public string name { get; private set; } + protected Column[]? columns; + private string constraints = ""; + private string[] post_statements = {}; + private string[] create_statements = {}; + internal Column[]? fts_columns; + + public Table(Database db, string name) { + this.db = db; + this.name = name; + } + + public void init(Column[] columns, string constraints = "") { + this.columns = columns; + this.constraints = constraints; + + foreach(Column c in columns) { + c.table = this; + } + } + + public void fts(Column[] columns) { + if (fts_columns != null) error("Only one FTS index may be used per table."); + fts_columns = columns; + string cs = ""; + string cnames = ""; + string cnews = ""; + foreach (Column c in columns) { + cs += @", $(c.to_column_definition())"; + cnames += @", $(c.name)"; + cnews += @", new.$(c.name)"; + } + add_create_statement(@"CREATE VIRTUAL TABLE IF NOT EXISTS _fts_$name USING fts4(tokenize=unicode61, content=\"$name\"$cs)"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bu_$(name) BEFORE UPDATE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bd_$(name) BEFORE DELETE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_au_$(name) AFTER UPDATE ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); + add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_ai_$(name) AFTER INSERT ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); + } + + public void fts_rebuild() { + if (fts_columns == null) error("FTS not available on this table."); + try { + db.exec(@"INSERT INTO _fts_$name(_fts_$name) VALUES('rebuild');"); + } catch (Error e) { + critical(@"Qlite Error: Rebuilding FTS index: $(e.message)"); + } + } + + public void unique(Column[] columns, string? on_conflict = null) { + constraints += ", UNIQUE ("; + bool first = true; + foreach (Column c in columns) { + if (!first) constraints += ", "; + constraints += c.name; + first = false; + } + constraints += ")"; + if (on_conflict != null) { + constraints += " ON CONFLICT " + (!)on_conflict; + } + } + + public void add_post_statement(string stmt) { + post_statements += stmt; + } + + public void add_create_statement(string stmt) { + create_statements += stmt; + } + + public void index(string index_name, Column[] columns, bool unique = false) { + string stmt = @"CREATE $(unique ? "UNIQUE" : "") INDEX IF NOT EXISTS $index_name ON $name ("; + bool first = true; + foreach (Column c in columns) { + if (!first) stmt += ", "; + stmt += c.name; + first = false; + } + stmt += ")"; + add_post_statement(stmt); + } + + private void ensure_init() { + if (columns == null) error("Table %s was not initialized, call init()", name); + } + + public QueryBuilder select(Column[]? columns = null) { + ensure_init(); + return db.select(columns).from(this); + } + + private MatchQueryBuilder match_query() { + ensure_init(); + return db.match_query(this); + } + + public MatchQueryBuilder match(Column column, string query) { + return match_query().match(column, query); + } + + public InsertBuilder insert() { + ensure_init(); + return db.insert().into(this); + } + + public UpdateBuilder update() { + ensure_init(); + return db.update(this); + } + + public UpsertBuilder upsert() { + ensure_init(); + return db.upsert(this); + } + + public DeleteBuilder delete() { + ensure_init(); + return db.delete().from(this); + } + + public RowOption row_with(Column column, T value) { + ensure_init(); + if (!column.unique && !column.primary_key) error("%s is not suited to identify a row, but used with row_with()", column.name); + return select().with(column, "=", value).row(); + } + + public bool is_known_column(string column) { + ensure_init(); + foreach (Column c in columns) { + if (c.name == column) return true; + } + return false; + } + + public void create_table_at_version(long version) { + ensure_init(); + string sql = @"CREATE TABLE IF NOT EXISTS $name ("; + bool first = true; + for (int i = 0; i < columns.length; i++) { + Column c = columns[i]; + if (c.min_version <= version && c.max_version >= version) { + sql += @"$(!first ? "," : "") $(c.to_column_definition())"; + first = false; + } + } + sql += @"$constraints)"; + try { + db.exec(sql); + } catch (Error e) { + error(@"Qlite Error: Create table at version: $(e.message)"); + } + foreach (string stmt in create_statements) { + try { + db.exec(stmt); + } catch (Error e) { + error(@"Qlite Error: Create table at version: $(e.message)"); + } + } + } + + public void add_columns_for_version(long old_version, long new_version) { + ensure_init(); + foreach (Column c in columns) { + if (c.min_version <= new_version && c.max_version >= new_version && c.min_version > old_version) { + try { + db.exec(@"ALTER TABLE $name ADD COLUMN $(c.to_column_definition())"); + } catch (Error e) { + critical(@"Qlite Error: Add columns for version: $(e.message)"); + } + } + } + } + + public void delete_columns_for_version(long old_version, long new_version) { + bool column_deletion_required = false; + string column_list = ""; + foreach (Column c in columns) { + if (c.min_version <= new_version && c.max_version >= new_version) { + if (column_list == "") { + column_list = c.name; + } else { + column_list += ", " + c.name; + } + } + if (!(c.min_version <= new_version && c.max_version >= new_version) && c.min_version <= old_version && c.max_version >= old_version) { + column_deletion_required = true; + } + } + if (column_deletion_required) { + try { + db.exec(@"ALTER TABLE $name RENAME TO _$(name)_$old_version"); + create_table_at_version(new_version); + db.exec(@"INSERT INTO $name ($column_list) SELECT $column_list FROM _$(name)_$old_version"); + db.exec(@"DROP TABLE _$(name)_$old_version"); + } catch (Error e) { + error(@"Qlite Error: Delete columns for version change: $(e.message)"); + } + } + } + + internal void post() { + foreach (string stmt in post_statements) { + try { + db.exec(stmt); + } catch (Error e) { + error(@"Qlite Error: Post: $(e.message)"); + } + } + } +} + +} diff --git a/libdino/src/qlite/update_builder.vala b/libdino/src/qlite/update_builder.vala new file mode 100644 index 00000000..d371a93a --- /dev/null +++ b/libdino/src/qlite/update_builder.vala @@ -0,0 +1,103 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class UpdateBuilder : StatementBuilder { + + // UPDATE [OR ...] + private string? or_val; + + // [...] + private Table? table; + private string table_name; + + // SET [...] + private StatementBuilder.AbstractField[] fields = {}; + + // WHERE [...] + private string selection = "1"; + private StatementBuilder.AbstractField[] selection_args = {}; + + internal UpdateBuilder(Database db, Table table) { + base(db); + this.table = table; + this.table_name = table.name; + } + + internal UpdateBuilder.for_name(Database db, string table) { + base(db); + this.table_name = table; + } + + public UpdateBuilder or(string or) { + this.or_val = or; + return this; + } + + public UpdateBuilder set(Column column, T value) { + fields += new Field(column, value); + return this; + } + + public UpdateBuilder set_null(Column column) { + if (column.not_null) error("Can't set non-null column %s to null", column.name); + fields += new NullField(column); + return this; + } + + public UpdateBuilder where(string selection, string[] selection_args = {}) { + if (this.selection != "1") error("selection was already done, but where() was called."); + this.selection = selection; + foreach (string arg in selection_args) { + this.selection_args += new StatementBuilder.StringField(arg); + } + return this; + } + + public UpdateBuilder with(Column column, string comp, T value) { + selection_args += new Field(column, value); + selection = @"($selection) AND $(column.name) $comp ?"; + return this; + } + + public UpdateBuilder with_null(Column column) { + selection = @"($selection) AND $(column.name) ISNULL"; + return this; + } + + public UpdateBuilder without_null(Column column) { + selection = @"($selection) AND $(column.name) NOT NULL"; + return this; + } + + internal override Statement prepare() { + string sql = "UPDATE"; + if (or_val != null) sql += @" OR $((!)or_val)"; + sql += @" $table_name SET "; + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + sql += ", "; + } + sql += @"$(((!)fields[i].column).name) = ?"; + } + sql += @" WHERE $selection"; + Statement stmt = db.prepare(sql); + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i+1); + } + for (int i = 0; i < selection_args.length; i++) { + selection_args[i].bind(stmt, i + fields.length + 1); + } + return stmt; + } + + public void perform() { + if (fields.length == 0) return; + if (prepare().step() != DONE) { + critical("SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + } + +} + +} diff --git a/libdino/src/qlite/upsert_builder.vala b/libdino/src/qlite/upsert_builder.vala new file mode 100644 index 00000000..e9a73e4f --- /dev/null +++ b/libdino/src/qlite/upsert_builder.vala @@ -0,0 +1,93 @@ +using Sqlite; + +namespace Dino.Qlite { + +public class UpsertBuilder : StatementBuilder { + // INTO [...] + private Table table; + private string table_name; + + // VALUES [...] + private StatementBuilder.AbstractField[] keys = {}; + private StatementBuilder.AbstractField[] fields = {}; + + internal UpsertBuilder(Database db, Table table) { + base(db); + this.table = table; + this.table_name = table.name; + } + + public UpsertBuilder value(Column column, T value, bool key = false) { + if (key) { + keys += new Field(column, value); + } else { + fields += new Field(column, value); + } + return this; + } + + public UpsertBuilder value_null(Column column, bool key = false) { + if (column.not_null) error("Can't set non-null column %s to null", column.name); + if (key) { + keys += new NullField(column); + } else { + fields += new NullField(column); + } + return this; + } + + internal override Statement prepare() { + error("prepare() not available for upsert."); + } + + internal Statement prepare_upsert() { + var unique_fields = new StringBuilder(); + var unique_values = new StringBuilder(); + var update_fields = new StringBuilder(); + var update_values = new StringBuilder(); + var update_fields_vals = new StringBuilder(); + + for (int i = 0; i < keys.length; i++) { + if (i != 0) { + unique_fields.append(", "); + unique_values.append(", "); + } + unique_fields.append(keys[i].column.name); + unique_values.append("?"); + } + + for (int i = 0; i < fields.length; i++) { + if (i != 0) { + update_fields.append(", "); + update_values.append(", "); + update_fields_vals.append(", "); + } + update_fields.append(fields[i].column.name); + update_values.append("?"); + update_fields_vals.append(fields[i].column.name).append("=excluded.").append(fields[i].column.name); + } + + string sql = @"INSERT INTO $table_name ($(unique_fields.str), $(update_fields.str)) VALUES ($(unique_values.str), $(update_values.str)) " + + @"ON CONFLICT ($(unique_fields.str)) DO UPDATE SET $(update_fields_vals.str)"; + + Statement stmt = db.prepare(sql); + for (int i = 0; i < keys.length; i++) { + keys[i].bind(stmt, i + 1); + } + for (int i = 0; i < fields.length; i++) { + fields[i].bind(stmt, i + keys.length + 1); + } + + return stmt; + } + + public int64 perform() { + if (prepare_upsert().step() != DONE) { + critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); + } + return db.last_insert_rowid(); + } + +} + +} diff --git a/libdino/src/service/avatar_manager.vala b/libdino/src/service/avatar_manager.vala index 0c98a8f3..ac4971ef 100644 --- a/libdino/src/service/avatar_manager.vala +++ b/libdino/src/service/avatar_manager.vala @@ -1,9 +1,9 @@ using Gdk; using Gee; -using Qlite; -using Xmpp; using Dino.Entities; +using Dino.Qlite; +using Xmpp; namespace Dino { diff --git a/libdino/src/service/call_store.vala b/libdino/src/service/call_store.vala index bfc8255f..9e32517f 100644 --- a/libdino/src/service/call_store.vala +++ b/libdino/src/service/call_store.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/contact_model.vala b/libdino/src/service/contact_model.vala index 33f6126b..3e52e040 100644 --- a/libdino/src/service/contact_model.vala +++ b/libdino/src/service/contact_model.vala @@ -1,6 +1,5 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; diff --git a/libdino/src/service/content_item_store.vala b/libdino/src/service/content_item_store.vala index cf4c6975..5e440c76 100644 --- a/libdino/src/service/content_item_store.vala +++ b/libdino/src/service/content_item_store.vala @@ -1,7 +1,7 @@ using Gee; using Dino.Entities; -using Qlite; +using Dino.Qlite; using Xmpp; namespace Dino { diff --git a/libdino/src/service/database.vala b/libdino/src/service/database.vala index 8432ff40..4319e027 100644 --- a/libdino/src/service/database.vala +++ b/libdino/src/service/database.vala @@ -1,8 +1,8 @@ using Gee; -using Qlite; using Xmpp; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/entity_info.vala b/libdino/src/service/entity_info.vala index 03828d1d..e9a20df1 100644 --- a/libdino/src/service/entity_info.vala +++ b/libdino/src/service/entity_info.vala @@ -1,6 +1,6 @@ using Gee; using Dino.Entities; -using Qlite; +using Dino.Qlite; using Xmpp; using Xmpp.Xep; using Xmpp.Xep.ServiceDiscovery; diff --git a/libdino/src/service/fallback_body.vala b/libdino/src/service/fallback_body.vala index 0ce89ade..09aa839a 100644 --- a/libdino/src/service/fallback_body.vala +++ b/libdino/src/service/fallback_body.vala @@ -1,5 +1,4 @@ using Gee; -using Qlite; using Xmpp; using Xmpp.Xep; diff --git a/libdino/src/service/file_transfer_storage.vala b/libdino/src/service/file_transfer_storage.vala index b4a4db3e..33ebcbce 100644 --- a/libdino/src/service/file_transfer_storage.vala +++ b/libdino/src/service/file_transfer_storage.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/history_sync.vala b/libdino/src/service/history_sync.vala index 9bd3f54f..a7a99d2d 100644 --- a/libdino/src/service/history_sync.vala +++ b/libdino/src/service/history_sync.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; public class Dino.HistorySync { diff --git a/libdino/src/service/message_correction.vala b/libdino/src/service/message_correction.vala index 164106e0..02151ac8 100644 --- a/libdino/src/service/message_correction.vala +++ b/libdino/src/service/message_correction.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/message_deletion.vala b/libdino/src/service/message_deletion.vala index 4467311e..0060a7e2 100644 --- a/libdino/src/service/message_deletion.vala +++ b/libdino/src/service/message_deletion.vala @@ -3,7 +3,6 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; namespace Dino { diff --git a/libdino/src/service/message_processor.vala b/libdino/src/service/message_processor.vala index 9190cd9d..7997af67 100644 --- a/libdino/src/service/message_processor.vala +++ b/libdino/src/service/message_processor.vala @@ -3,7 +3,7 @@ using Gee; using Xmpp; using Xmpp.Xep; using Dino.Entities; -using Qlite; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/message_storage.vala b/libdino/src/service/message_storage.vala index d6b8d6e3..2567738c 100644 --- a/libdino/src/service/message_storage.vala +++ b/libdino/src/service/message_storage.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/occupant_id_store.vala b/libdino/src/service/occupant_id_store.vala index 662b9cbb..d2849652 100644 --- a/libdino/src/service/occupant_id_store.vala +++ b/libdino/src/service/occupant_id_store.vala @@ -1,8 +1,8 @@ using Xmpp; using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino { diff --git a/libdino/src/service/reactions.vala b/libdino/src/service/reactions.vala index 16849c68..8f3aa4fa 100644 --- a/libdino/src/service/reactions.vala +++ b/libdino/src/service/reactions.vala @@ -1,9 +1,9 @@ using Gee; -using Qlite; +using Dino.Entities; +using Dino.Qlite; using Xmpp; using Xmpp.Xep; -using Dino.Entities; public class Dino.Reactions : StreamInteractionModule, Object { public static ModuleIdentity IDENTITY = new ModuleIdentity("reactions"); diff --git a/libdino/src/service/replies.vala b/libdino/src/service/replies.vala index ea10cf88..95c28ef1 100644 --- a/libdino/src/service/replies.vala +++ b/libdino/src/service/replies.vala @@ -1,9 +1,9 @@ using Gee; -using Qlite; using Xmpp; using Xmpp.Xep; using Dino.Entities; +using Dino.Qlite; public class Dino.Replies : StreamInteractionModule, Object { public static ModuleIdentity IDENTITY = new ModuleIdentity("reply"); diff --git a/libdino/src/service/search_processor.vala b/libdino/src/service/search_processor.vala index 2b5ebe49..aaec990a 100644 --- a/libdino/src/service/search_processor.vala +++ b/libdino/src/service/search_processor.vala @@ -1,8 +1,8 @@ using Gee; -using Xmpp; -using Qlite; using Dino.Entities; +using Dino.Qlite; +using Xmpp; namespace Dino { diff --git a/libdino/src/service/util.vala b/libdino/src/service/util.vala index e85e2005..ac596cad 100644 --- a/libdino/src/service/util.vala +++ b/libdino/src/service/util.vala @@ -1,5 +1,4 @@ using Dino.Entities; -using Qlite; namespace Dino { diff --git a/main/meson.build b/main/meson.build index 8b9404c9..3c15db32 100644 --- a/main/meson.build +++ b/main/meson.build @@ -8,7 +8,6 @@ dependencies = [ dep_icu_uc, dep_libadwaita, dep_m, - dep_qlite, dep_xmpp_vala, meson.get_compiler('vala').find_library('posix'), ] diff --git a/meson.build b/meson.build index b9df102b..ad0f7e4e 100644 --- a/meson.build +++ b/meson.build @@ -110,7 +110,6 @@ if get_option('set-install-rpath') default_install_rpath = get_option('prefix') / get_option('libdir') endif -subdir('qlite') subdir('xmpp-vala') subdir('libdino') subdir('main') diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 5161b123..99f8e6a1 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -5,7 +5,6 @@ dependencies = [ dep_glib, dep_gmodule, dep_nice, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/notification-sound/meson.build b/plugins/notification-sound/meson.build index d6eebe18..80a1d062 100644 --- a/plugins/notification-sound/meson.build +++ b/plugins/notification-sound/meson.build @@ -4,7 +4,6 @@ dependencies = [ dep_glib, dep_gmodule, dep_libcanberra, - dep_qlite, dep_xmpp_vala, dep_gio, ] diff --git a/plugins/omemo/meson.build b/plugins/omemo/meson.build index 978fb9a6..7838a8d6 100644 --- a/plugins/omemo/meson.build +++ b/plugins/omemo/meson.build @@ -9,7 +9,6 @@ dependencies = [ dep_libqrencode, dep_libomemo_c, dep_m, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/omemo/src/logic/database.vala b/plugins/omemo/src/logic/database.vala index ec5a0924..f2a92259 100644 --- a/plugins/omemo/src/logic/database.vala +++ b/plugins/omemo/src/logic/database.vala @@ -1,7 +1,7 @@ using Gee; -using Qlite; using Dino.Entities; +using Dino.Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/decrypt.vala b/plugins/omemo/src/logic/decrypt.vala index 2861b42f..698d3f76 100644 --- a/plugins/omemo/src/logic/decrypt.vala +++ b/plugins/omemo/src/logic/decrypt.vala @@ -1,6 +1,7 @@ -using Dino.Entities; -using Qlite; using Gee; + +using Dino.Entities; +using Dino.Qlite; using Omemo; using Xmpp; diff --git a/plugins/omemo/src/logic/manager.vala b/plugins/omemo/src/logic/manager.vala index 71f17aae..f171a1c0 100644 --- a/plugins/omemo/src/logic/manager.vala +++ b/plugins/omemo/src/logic/manager.vala @@ -1,8 +1,9 @@ +using Gee; + using Dino.Entities; +using Dino.Qlite; using Omemo; -using Qlite; using Xmpp; -using Gee; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/pre_key_store.vala b/plugins/omemo/src/logic/pre_key_store.vala index c15acc84..beb2d87a 100644 --- a/plugins/omemo/src/logic/pre_key_store.vala +++ b/plugins/omemo/src/logic/pre_key_store.vala @@ -1,5 +1,5 @@ +using Dino.Qlite; using Omemo; -using Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/session_store.vala b/plugins/omemo/src/logic/session_store.vala index ea5738fd..bb9ca83f 100644 --- a/plugins/omemo/src/logic/session_store.vala +++ b/plugins/omemo/src/logic/session_store.vala @@ -1,5 +1,5 @@ +using Dino.Qlite; using Omemo; -using Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/signed_pre_key_store.vala b/plugins/omemo/src/logic/signed_pre_key_store.vala index d73cbe71..68f3092c 100644 --- a/plugins/omemo/src/logic/signed_pre_key_store.vala +++ b/plugins/omemo/src/logic/signed_pre_key_store.vala @@ -1,4 +1,4 @@ -using Qlite; +using Dino.Qlite; using Omemo; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/logic/trust_manager.vala b/plugins/omemo/src/logic/trust_manager.vala index 8cf1ddeb..f17ade99 100644 --- a/plugins/omemo/src/logic/trust_manager.vala +++ b/plugins/omemo/src/logic/trust_manager.vala @@ -1,8 +1,9 @@ -using Dino.Entities; using Gee; -using Xmpp; + +using Dino.Entities; +using Dino.Qlite; using Omemo; -using Qlite; +using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/bad_messages_populator.vala b/plugins/omemo/src/ui/bad_messages_populator.vala index 9dacba95..c291a422 100644 --- a/plugins/omemo/src/ui/bad_messages_populator.vala +++ b/plugins/omemo/src/ui/bad_messages_populator.vala @@ -1,8 +1,8 @@ using Gee; using Gtk; -using Qlite; using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/call_encryption_entry.vala b/plugins/omemo/src/ui/call_encryption_entry.vala index 69b7b686..04f0443c 100644 --- a/plugins/omemo/src/ui/call_encryption_entry.vala +++ b/plugins/omemo/src/ui/call_encryption_entry.vala @@ -1,6 +1,7 @@ -using Dino.Entities; using Gtk; -using Qlite; + +using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/contact_details_provider.vala b/plugins/omemo/src/ui/contact_details_provider.vala index 7c733cd7..1b61f31d 100644 --- a/plugins/omemo/src/ui/contact_details_provider.vala +++ b/plugins/omemo/src/ui/contact_details_provider.vala @@ -1,6 +1,5 @@ using Gtk; using Gee; -using Qlite; using Dino.Entities; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/encryption_list_entry.vala b/plugins/omemo/src/ui/encryption_list_entry.vala index 3bb76c52..dfec813a 100644 --- a/plugins/omemo/src/ui/encryption_list_entry.vala +++ b/plugins/omemo/src/ui/encryption_list_entry.vala @@ -1,6 +1,7 @@ -using Dino.Entities; using Gtk; -using Qlite; + +using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/encryption_preferences_entry.vala b/plugins/omemo/src/ui/encryption_preferences_entry.vala index f0aedb6a..cea856bb 100644 --- a/plugins/omemo/src/ui/encryption_preferences_entry.vala +++ b/plugins/omemo/src/ui/encryption_preferences_entry.vala @@ -1,10 +1,11 @@ -using Qlite; -using Qrencode; using Gee; -using Xmpp; -using Dino.Entities; using Gtk; +using Qrencode; + +using Dino.Entities; +using Dino.Qlite; using Omemo; +using Xmpp; namespace Dino.Plugins.Omemo { diff --git a/plugins/omemo/src/ui/manage_key_dialog.vala b/plugins/omemo/src/ui/manage_key_dialog.vala index ac8896a5..117149b6 100644 --- a/plugins/omemo/src/ui/manage_key_dialog.vala +++ b/plugins/omemo/src/ui/manage_key_dialog.vala @@ -1,5 +1,6 @@ using Gtk; -using Qlite; + +using Dino.Qlite; namespace Dino.Plugins.Omemo { diff --git a/plugins/openpgp/meson.build b/plugins/openpgp/meson.build index 23588fca..56bc9d0c 100644 --- a/plugins/openpgp/meson.build +++ b/plugins/openpgp/meson.build @@ -7,7 +7,6 @@ dependencies = [ dep_gmodule, dep_gpgme, dep_gtk4, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/plugins/openpgp/src/database.vala b/plugins/openpgp/src/database.vala index fb575a3b..4c05571e 100644 --- a/plugins/openpgp/src/database.vala +++ b/plugins/openpgp/src/database.vala @@ -1,6 +1,5 @@ -using Qlite; - using Dino.Entities; +using Dino.Qlite; using Xmpp; namespace Dino.Plugins.OpenPgp { diff --git a/plugins/rtp/meson.build b/plugins/rtp/meson.build index b4ba5cf6..2772ad88 100644 --- a/plugins/rtp/meson.build +++ b/plugins/rtp/meson.build @@ -10,7 +10,6 @@ dependencies = [ dep_gstreamer_video, dep_gtk4, dep_m, - dep_qlite, dep_xmpp_vala, ] sources = files( diff --git a/qlite/meson.build b/qlite/meson.build deleted file mode 100644 index 162d6aa8..00000000 --- a/qlite/meson.build +++ /dev/null @@ -1,27 +0,0 @@ -dependencies = [ - dep_gee, - dep_glib, - dep_sqlite3, -] -sources = files( - 'src/column.vala', - 'src/database.vala', - 'src/delete_builder.vala', - 'src/insert_builder.vala', - 'src/query_builder.vala', - 'src/row.vala', - 'src/statement_builder.vala', - 'src/table.vala', - 'src/update_builder.vala', - 'src/upsert_builder.vala', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="qlite"', -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] -lib_qlite = library('qlite', sources, c_args: c_args, vala_args: vala_args, dependencies: dependencies, version: '0.1', install: true, install_dir: [true, true, true], install_rpath: default_install_rpath) -dep_qlite = declare_dependency(link_with: lib_qlite, include_directories: include_directories('.')) - -install_data('qlite.deps', install_dir: get_option('datadir') / 'vala/vapi', install_tag: 'devel') # TODO: workaround for https://github.com/mesonbuild/meson/issues/9756 diff --git a/qlite/qlite.deps b/qlite/qlite.deps deleted file mode 100644 index d9b15e78..00000000 --- a/qlite/qlite.deps +++ /dev/null @@ -1,3 +0,0 @@ -gee-0.8 -glib-2.0 -sqlite3 diff --git a/qlite/src/column.vala b/qlite/src/column.vala deleted file mode 100644 index 36c8fcff..00000000 --- a/qlite/src/column.vala +++ /dev/null @@ -1,190 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public abstract class Column { - public const string DEFAULT_TABLE_NAME = ""; - - public string name { get; private set; } - public string? default { get; set; } - public int sqlite_type { get; private set; } - public bool primary_key { get; set; } - public bool auto_increment { get; set; } - public bool unique { get; set; } - public virtual bool not_null { get; set; } - public long min_version { get; set; default = -1; } - public long max_version { get; set; default = long.MAX; } - internal Table table { get; set; } - - public abstract T get(Row row, string? table_name = DEFAULT_TABLE_NAME); - - public virtual bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return false; - } - - internal abstract void bind(Statement stmt, int index, T value); - - public string to_string() { - return table == null ? name : (table.name + "." + name); - } - - public string to_column_definition() { - string res = name; - switch (sqlite_type) { - case INTEGER: - res += " INTEGER"; - break; - case FLOAT: - res += " REAL"; - break; - case TEXT: - res += " TEXT"; - break; - default: - res += " UNKNOWN"; - break; - } - if (primary_key) { - res += " PRIMARY KEY"; - if (auto_increment) res += " AUTOINCREMENT"; - } - if (not_null) res += " NOT NULL"; - if (unique) res += " UNIQUE"; - if (default != null) res += @" DEFAULT $((!) default)"; - - return res; - } - - Column(string name, int type) { - this.name = name; - this.sqlite_type = type; - } - - public class Integer : Column { - public Integer(string name) { - base(name, INTEGER); - } - - public override int get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (int) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, int value) { - stmt.bind_int(index, value); - } - } - - public class Long : Column { - public Long(string name) { - base(name, INTEGER); - } - - public override long get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (long) row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, long value) { - stmt.bind_int64(index, value); - } - } - - public class NullableReal : Column { - public NullableReal(string name) { - base(name, FLOAT); - } - - public override bool not_null { get { return false; } set {} } - - public override double? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return !row.has_real(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - internal override void bind(Statement stmt, int index, double? value) { - stmt.bind_double(index, value); - } - } - - public class Text : Column { - public Text(string name) { - base(name, TEXT); - } - - public override string? get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return get(row, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == null; - } - - internal override void bind(Statement stmt, int index, string? value) { - if (value != null) { - stmt.bind_text(index, (!) value); - } else { - stmt.bind_null(index); - } - } - } - - public class NonNullText : Column { - public NonNullText(string name) { - base(name, TEXT); - } - - public override bool not_null { get { return true; } set {} } - - public override string get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return (!)row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name); - } - - public override bool is_null(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return false; - } - - internal override void bind(Statement stmt, int index, string value) { - stmt.bind_text(index, (!) value); - } - } - - public class BoolText : Column { - public BoolText(string name) { - base(name, TEXT); - } - - public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_text(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == "1"; - } - - internal override void bind(Statement stmt, int index, bool value) { - stmt.bind_text(index, value ? "1" : "0"); - } - } - - public class BoolInt : Column { - public BoolInt(string name) { - base(name, INTEGER); - } - - public override bool get(Row row, string? table_name = DEFAULT_TABLE_NAME) { - return row.get_integer(name, table_name == DEFAULT_TABLE_NAME ? table.name : table_name) == 1; - } - - internal override void bind(Statement stmt, int index, bool value) { - stmt.bind_int(index, value ? 1 : 0); - } - } -} - -} diff --git a/qlite/src/database.vala b/qlite/src/database.vala deleted file mode 100644 index 8b2f447d..00000000 --- a/qlite/src/database.vala +++ /dev/null @@ -1,163 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class Database { - private string file_name; - private Sqlite.Database db; - private long expected_version; - private Table[]? tables; - - private Column meta_name = new Column.Text("name") { primary_key = true }; - private Column meta_int_val = new Column.Long("int_val"); - private Column meta_text_val = new Column.Text("text_val"); - private Table meta_table; - - public bool debug = false; - - public Database(string file_name, long expected_version) { - this.file_name = file_name; - this.expected_version = expected_version; - meta_table = new Table(this, "_meta"); - meta_table.init({meta_name, meta_int_val, meta_text_val}); - } - - public void init(Table[] tables) { - Sqlite.config(Config.SERIALIZED); - int ec = Sqlite.Database.open_v2(file_name, out db, OPEN_READWRITE | OPEN_CREATE | 0x00010000); - if (ec != Sqlite.OK) { - error(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - this.tables = tables; - if (debug) db.trace((message) => print(@"Qlite trace: $message\n")); - start_migration(); - } - - public void ensure_init() { - if (tables == null) error(@"Database $file_name was not initialized, call init()"); - } - - private void start_migration() { - try { - exec("BEGIN TRANSACTION"); - } catch (Error e) { - error("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - meta_table.create_table_at_version(expected_version); - long old_version = 0; - old_version = meta_table.row_with(meta_name, "version")[meta_int_val, -1]; - if (old_version == -1) { - foreach (Table t in tables) { - t.create_table_at_version(expected_version); - } - meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); - } else if (expected_version != old_version) { - foreach (Table t in tables) { - t.create_table_at_version(old_version); - } - foreach (Table t in tables) { - t.add_columns_for_version(old_version, expected_version); - } - migrate(old_version); - foreach (Table t in tables) { - t.delete_columns_for_version(old_version, expected_version); - } - if (old_version == -1) { - meta_table.insert().value(meta_name, "version").value(meta_int_val, expected_version).perform(); - } else { - meta_table.update().with(meta_name, "=", "version").set(meta_int_val, expected_version).perform(); - } - } - foreach (Table t in tables) { - t.post(); - } - try { - exec("END TRANSACTION"); - } catch (Error e) { - error("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - - internal int errcode() { - return db.errcode(); - } - - internal string errmsg() { - return db.errmsg(); - } - - internal int64 last_insert_rowid() { - return db.last_insert_rowid(); - } - - // To be implemented by actual implementation if required - // new table columns are added, outdated columns are still present and will be removed afterwards - public virtual void migrate(long old_version) { - } - - public QueryBuilder select(Column[]? columns = null) { - ensure_init(); - return new QueryBuilder(this).select(columns); - } - - internal MatchQueryBuilder match_query(Table table) { - ensure_init(); - return new MatchQueryBuilder(this, table); - } - - public InsertBuilder insert() { - ensure_init(); - return new InsertBuilder(this); - } - - public UpdateBuilder update(Table table) { - ensure_init(); - return new UpdateBuilder(this, table); - } - - public UpsertBuilder upsert(Table table) { - ensure_init(); - return new UpsertBuilder(this, table); - } - - public UpdateBuilder update_named(string table) { - ensure_init(); - return new UpdateBuilder.for_name(this, table); - } - - public DeleteBuilder delete() { - ensure_init(); - return new DeleteBuilder(this); - } - - public RowIterator query_sql(string sql, string[]? args = null) { - ensure_init(); - return new RowIterator(this, sql, args); - } - - internal Statement prepare(string sql) { - ensure_init(); - Sqlite.Statement statement; - if (db.prepare_v2(sql, sql.length, out statement) != OK) { - error("SQLite error: %d - %s: %s", db.errcode(), db.errmsg(), sql); - } - return statement; - } - - public void exec(string sql) throws Error { - ensure_init(); - if (db.exec(sql) != OK) { - throw new Error(-1, 0, "SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - - public bool is_known_column(string table, string field) { - ensure_init(); - foreach (Table t in tables) { - if (t.is_known_column(field)) return true; - } - return false; - } -} - -} diff --git a/qlite/src/delete_builder.vala b/qlite/src/delete_builder.vala deleted file mode 100644 index 45e09dc7..00000000 --- a/qlite/src/delete_builder.vala +++ /dev/null @@ -1,62 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class DeleteBuilder : StatementBuilder { - - // DELETE FROM [...] - private Table? table; - private string table_name; - - // WHERE [...] - private string selection = "1"; - private StatementBuilder.AbstractField[] selection_args = {}; - - internal DeleteBuilder(Database db) { - base(db); - } - - public DeleteBuilder from(Table table) { - if (this.table != null) error("Qlite Error: ILLEGAL QUERY: cannot use from() multiple times."); - this.table = table; - this.table_name = table.name; - return this; - } - - public DeleteBuilder from_name(string table) { - this.table_name = table; - return this; - } - - public DeleteBuilder where(string selection, string[]? selection_args = null) { - if (this.selection != "1") error("selection was already done, but where() was called."); - this.selection = selection; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public DeleteBuilder with(Column column, string comp, T value) { - selection_args += new Field(column, value); - selection = @"($selection) AND $(column.name) $comp ?"; - return this; - } - - internal override Statement prepare() { - Statement stmt = db.prepare(@"DELETE FROM $table_name WHERE $selection"); - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i+1); - } - return stmt; - } - - public void perform() { - if (prepare().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - -} - -} diff --git a/qlite/src/insert_builder.vala b/qlite/src/insert_builder.vala deleted file mode 100644 index 8b14b33f..00000000 --- a/qlite/src/insert_builder.vala +++ /dev/null @@ -1,84 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class InsertBuilder : StatementBuilder { - - // INSERT [OR ...] - private bool replace_val; - private string? or_val; - - // INTO [...] - private Table table; - private string table_name; - - // VALUES [...] - private StatementBuilder.AbstractField[] fields = {}; - - internal InsertBuilder(Database db) { - base(db); - } - - public InsertBuilder replace() { - this.replace_val = true; - return this; - } - - public InsertBuilder or(string or) { - this.or_val = or; - return this; - } - - public InsertBuilder into(Table table) { - this.table = table; - this.table_name = table.name; - return this; - } - - public InsertBuilder into_name(string table) { - this.table_name = table; - return this; - } - - public InsertBuilder value(Column column, T value) { - fields += new Field(column, value); - return this; - } - - public InsertBuilder value_null(Column column) { - if (column.not_null) error("Qlite Error: ILLEGAL QUERY: Can't set non-null column %s to null", column.name); - fields += new NullField(column); - return this; - } - - internal override Statement prepare() { - string fields_text = ""; - string value_qs = ""; - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - value_qs += ", "; - fields_text += ", "; - } - fields_text += ((!)fields[i].column).name; - value_qs += "?"; - } - string sql = replace_val ? "REPLACE" : "INSERT"; - if (!replace_val && or_val != null) sql += @" OR $((!)or_val)"; - sql += @" INTO $table_name ( $fields_text ) VALUES ($value_qs)"; - Statement stmt = db.prepare(sql); - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i+1); - } - return stmt; - } - - public int64 perform() { - if (prepare().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - return db.last_insert_rowid(); - } - -} - -} diff --git a/qlite/src/query_builder.vala b/qlite/src/query_builder.vala deleted file mode 100644 index 88f05e04..00000000 --- a/qlite/src/query_builder.vala +++ /dev/null @@ -1,238 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class QueryBuilder : StatementBuilder { - private bool single_result; - - // SELECT [...] - private string column_selector = "*"; - private Column[] columns = {}; - - // FROM [...] - protected Table? table; - protected string? table_name; - - // JOIN [...] - private string joins = ""; - - // WHERE [...] - protected string selection = "1"; - internal StatementBuilder.AbstractField[] selection_args = {}; - - // ORDER BY [...] - private OrderingTerm[]? order_by_terms = {}; - - // GROUP BY [...] - private string? group_by_term; - - // LIMIT [...] OFFSET [...] - private int limit_val; - private int offset_val; - - internal QueryBuilder(Database db) { - base(db); - } - - public QueryBuilder select(Column[] columns = {}) { - this.columns = columns; - if (columns.length != 0) { - for (int i = 0; i < columns.length; i++) { - if (column_selector == "*") { - column_selector = columns[i].to_string(); - } else { - column_selector += ", " + columns[i].to_string(); - } - } - } else { - column_selector = "*"; - } - return this; - } - - public QueryBuilder select_string(string column_selector) { - this.columns = {}; - this.column_selector = column_selector; - return this; - } - - public virtual QueryBuilder from(Table table) { - if (this.table_name != null) error("cannot use from() multiple times."); - this.table = table; - this.table_name = table.name; - return this; - } - - public virtual QueryBuilder from_name(string table) { - this.table_name = table; - return this; - } - - public QueryBuilder outer_join_with(Table table, Column lhs, Column rhs, string? as = null) { - return outer_join_on(table, @"$lhs = $rhs", as); - } - - public QueryBuilder outer_join_on(Table table, string on, string? as = null) { - if (as == null) as = table.name; - joins += @" LEFT OUTER JOIN $(table.name) AS $as ON $on"; - return this; - } - - public QueryBuilder join_with(Table table, Column lhs, Column rhs, string? as = null) { - return join_on(table, @"$lhs = $rhs", as); - } - - public QueryBuilder join_on(Table table, string on, string? as = null) { - if (as == null) as = table.name; - joins += @" JOIN $(table.name) AS $as ON $on"; - return this; - } - - internal QueryBuilder join_name(string table_name, string on) { - joins += @" JOIN $table_name ON $on"; - return this; - } - - public QueryBuilder where(string selection, string[] selection_args = {}) { - this.selection = @"($(this.selection)) AND ($selection)"; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public QueryBuilder with(Column column, string comp, T value) { - if ((column.unique || column.primary_key) && comp == "=") single_result = true; - selection_args += new Field(column, value); - selection = @"($selection) AND $column $comp ?"; - return this; - } - - public QueryBuilder with_null(Column column) { - selection = @"($selection) AND $column ISNULL"; - return this; - } - - public QueryBuilder without_null(Column column) { - selection = @"($selection) AND $column NOT NULL"; - return this; - } - - public QueryBuilder order_by(Column column, string dir = "ASC") { - order_by_terms += new OrderingTerm(column, dir); - return this; - } - - public QueryBuilder order_by_name(string name, string dir) { - order_by_terms += new OrderingTerm.by_name(name, dir); - return this; - } - - public QueryBuilder group_by(Column[] columns) { - foreach(Column col in columns) { - if (group_by_term == null) { - group_by_term = col.to_string(); - } else { - group_by_term += @", $col"; - } - } - return this; - } - - public QueryBuilder limit(int limit) { - if (this.limit_val != 0 && limit > this.limit_val) error("tried to increase an existing limit"); - this.limit_val = limit; - return this; - } - - public QueryBuilder offset(int offset) { - if (this.limit_val == 0) error("limit required before offset"); - this.offset_val = offset; - return this; - } - - public QueryBuilder single() { - this.single_result = true; - return limit(1); - } - - public int64 count() { - this.column_selector = @"COUNT($column_selector) AS count"; - this.single_result = true; - return row().get_integer("count"); - } - - private Row? row_() { - if (!single_result) error("query is not suited to return a single row, but row() was called."); - return iterator().get_next(); - } - - public RowOption row() { - return new RowOption(row_()); - } - - public T get(Column field, T def = null) { - return row().get(field, def); - } - - internal override Statement prepare() { - Statement stmt = db.prepare(@"SELECT $column_selector $(table_name == null ? "" : @"FROM $((!) table_name)") $joins WHERE $selection $(group_by_term == null ? "" : @"GROUP BY $group_by_term") $(OrderingTerm.all_to_string(order_by_terms)) $(limit_val > 0 ? @" LIMIT $limit_val OFFSET $offset_val" : "")"); - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i+1); - } - return stmt; - } - - public RowIterator iterator() { - return new RowIterator.from_query_builder(db, this); - } - - class OrderingTerm { - Column? column; - string column_name; - string dir; - - public OrderingTerm(Column column, string dir) { - this.column = column; - this.column_name = column.to_string(); - this.dir = dir; - } - - public OrderingTerm.by_name(string column_name, string dir) { - this.column_name = column_name; - this.dir = dir; - } - - public string to_string() { - return @"$column_name $dir"; - } - - public static string all_to_string(OrderingTerm[]? terms) { - if (terms == null || terms.length == 0) return ""; - string res = "ORDER BY "+terms[0].to_string(); - for (int i = 1; i < terms.length; i++) { - res += @", $(terms[i])"; - } - return res; - } - } -} - -public class MatchQueryBuilder : QueryBuilder { - internal MatchQueryBuilder(Database db, Table table) { - base(db); - if (table.fts_columns == null) error("MATCH query on non FTS table"); - from(table); - join_name(@"_fts_$table_name", @"_fts_$table_name.docid = $table_name.rowid"); - } - - public MatchQueryBuilder match(Column column, string match) { - if (table == null) error("MATCH must occur after FROM statement"); - if (!(column in table.fts_columns)) error("MATCH selection on non FTS column"); - selection_args += new StatementBuilder.StringField(match); - selection = @"($selection) AND _fts_$table_name.$(column.name) MATCH ?"; - return this; - } -} - -} diff --git a/qlite/src/row.vala b/qlite/src/row.vala deleted file mode 100644 index 4671db20..00000000 --- a/qlite/src/row.vala +++ /dev/null @@ -1,147 +0,0 @@ -using Gee; -using Sqlite; - -namespace Qlite { - -public class Row { - private Map text_map = new HashMap(); - private Map int_map = new HashMap(); - private Map real_map = new HashMap(); - - internal Row(Statement stmt) { - for (int i = 0; i < stmt.column_count(); i++) { - string column_name; - if (stmt.column_origin_name(i) != null) { - column_name = @"$(stmt.column_table_name(i)).$(stmt.column_origin_name(i))"; - } else { - column_name = stmt.column_name(i); - } - switch(stmt.column_type(i)) { - case TEXT: - text_map[column_name] = stmt.column_text(i); - break; - case INTEGER: - int_map[column_name] = (long) stmt.column_int64(i); - break; - case FLOAT: - real_map[column_name] = stmt.column_double(i); - break; - } - } - } - - public T get(Column field) { - return field[this]; - } - - private string field_name(string field, string? table) { - if (table != null) { - return @"$table.$field"; - } else { - return field; - } - } - - public string? get_text(string field, string? table = null) { - if (text_map.has_key(field_name(field, table))) { - return text_map[field_name(field, table)]; - } - return null; - } - - public long get_integer(string field, string? table = null) { - return int_map[field_name(field, table)]; - } - - public bool has_integer(string field, string? table = null) { - return int_map.has_key(field_name(field, table)); - } - - public double get_real(string field, string? table = null, double def = 0) { - return real_map[field_name(field, table)] ?? def; - } - - public bool has_real(string field, string? table = null) { - return real_map.has_key(field_name(field, table)) && real_map[field_name(field, table)] != null; - } - - public string to_string() { - string ret = "{"; - - foreach (string key in text_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: \"$(text_map[key])\""; - } - foreach (string key in int_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: $(int_map[key])"; - } - foreach (string key in real_map.keys) { - if (ret.length > 1) ret += ", "; - ret = @"$ret$key: $(real_map[key])"; - } - - return ret + "}"; - } -} - -public class RowIterator { - private Database db; - private Statement stmt; - - public RowIterator.from_query_builder(Database db, QueryBuilder query) { - this.db = db; - this.stmt = query.prepare(); - } - - public RowIterator(Database db, string sql, string[]? args = null) { - this.db = db; - this.stmt = db.prepare(sql); - if (args != null) { - for (int i = 0; i < args.length; i++) { - stmt.bind_text(i, sql, sql.length); - } - } - } - - public bool next() { - int r = stmt.step(); - if (r == Sqlite.ROW) return true; - if (r == Sqlite.DONE) return false; - warning(@"SQLite error: $(db.errcode()) - $(db.errmsg())"); - return false; - } - - public Row get() { - return new Row(stmt); - } - - public Row? get_next() { - if (next()) return get(); - return null; - } -} - -public class RowOption { - public Row? inner { get; private set; } - - public RowOption(Row? row) { - this.inner = row; - } - - public bool is_present() { - return inner != null; - } - - public T get(Column field, T def = null) { - if (inner == null || field.is_null((!)inner)) return def; - return field[(!)inner]; - } - - internal long get_integer(string field, long def = 0) { - if (inner == null || !((!)inner).has_integer(field)) return def; - return ((!)inner).get_integer(field); - } -} - -} diff --git a/qlite/src/statement_builder.vala b/qlite/src/statement_builder.vala deleted file mode 100644 index dca6983e..00000000 --- a/qlite/src/statement_builder.vala +++ /dev/null @@ -1,58 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public abstract class StatementBuilder { - protected Database db; - - internal StatementBuilder(Database db) { - this.db = db; - } - - internal abstract Statement prepare(); - - internal abstract class AbstractField { - public T value; - public Column? column; - - AbstractField(T value) { - this.value = value; - } - - internal abstract void bind(Statement stmt, int index); - } - - internal class Field : AbstractField { - public Field(Column column, T value) { - base(value); - this.column = column; - } - - internal override void bind(Statement stmt, int index) { - ((!)column).bind(stmt, index, value); - } - } - - internal class NullField : AbstractField { - public NullField(Column column) { - base(null); - this.column = column; - } - - internal override void bind(Statement stmt, int index) { - stmt.bind_null(index); - } - } - - internal class StringField : AbstractField { - public StringField(string value) { - base(value); - } - - internal override void bind(Statement stmt, int index) { - stmt.bind_text(index, value); - } - } -} - -} diff --git a/qlite/src/table.vala b/qlite/src/table.vala deleted file mode 100644 index a5a57c49..00000000 --- a/qlite/src/table.vala +++ /dev/null @@ -1,218 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class Table { - protected Database db; - public string name { get; private set; } - protected Column[]? columns; - private string constraints = ""; - private string[] post_statements = {}; - private string[] create_statements = {}; - internal Column[]? fts_columns; - - public Table(Database db, string name) { - this.db = db; - this.name = name; - } - - public void init(Column[] columns, string constraints = "") { - this.columns = columns; - this.constraints = constraints; - - foreach(Column c in columns) { - c.table = this; - } - } - - public void fts(Column[] columns) { - if (fts_columns != null) error("Only one FTS index may be used per table."); - fts_columns = columns; - string cs = ""; - string cnames = ""; - string cnews = ""; - foreach (Column c in columns) { - cs += @", $(c.to_column_definition())"; - cnames += @", $(c.name)"; - cnews += @", new.$(c.name)"; - } - add_create_statement(@"CREATE VIRTUAL TABLE IF NOT EXISTS _fts_$name USING fts4(tokenize=unicode61, content=\"$name\"$cs)"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bu_$(name) BEFORE UPDATE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_bd_$(name) BEFORE DELETE ON $name BEGIN DELETE FROM _fts_$name WHERE docid=old.rowid; END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_au_$(name) AFTER UPDATE ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); - add_post_statement(@"CREATE TRIGGER IF NOT EXISTS _fts_ai_$(name) AFTER INSERT ON $name BEGIN INSERT INTO _fts_$name(docid$cnames) VALUES(new.rowid$cnews); END"); - } - - public void fts_rebuild() { - if (fts_columns == null) error("FTS not available on this table."); - try { - db.exec(@"INSERT INTO _fts_$name(_fts_$name) VALUES('rebuild');"); - } catch (Error e) { - critical(@"Qlite Error: Rebuilding FTS index: $(e.message)"); - } - } - - public void unique(Column[] columns, string? on_conflict = null) { - constraints += ", UNIQUE ("; - bool first = true; - foreach (Column c in columns) { - if (!first) constraints += ", "; - constraints += c.name; - first = false; - } - constraints += ")"; - if (on_conflict != null) { - constraints += " ON CONFLICT " + (!)on_conflict; - } - } - - public void add_post_statement(string stmt) { - post_statements += stmt; - } - - public void add_create_statement(string stmt) { - create_statements += stmt; - } - - public void index(string index_name, Column[] columns, bool unique = false) { - string stmt = @"CREATE $(unique ? "UNIQUE" : "") INDEX IF NOT EXISTS $index_name ON $name ("; - bool first = true; - foreach (Column c in columns) { - if (!first) stmt += ", "; - stmt += c.name; - first = false; - } - stmt += ")"; - add_post_statement(stmt); - } - - private void ensure_init() { - if (columns == null) error("Table %s was not initialized, call init()", name); - } - - public QueryBuilder select(Column[]? columns = null) { - ensure_init(); - return db.select(columns).from(this); - } - - private MatchQueryBuilder match_query() { - ensure_init(); - return db.match_query(this); - } - - public MatchQueryBuilder match(Column column, string query) { - return match_query().match(column, query); - } - - public InsertBuilder insert() { - ensure_init(); - return db.insert().into(this); - } - - public UpdateBuilder update() { - ensure_init(); - return db.update(this); - } - - public UpsertBuilder upsert() { - ensure_init(); - return db.upsert(this); - } - - public DeleteBuilder delete() { - ensure_init(); - return db.delete().from(this); - } - - public RowOption row_with(Column column, T value) { - ensure_init(); - if (!column.unique && !column.primary_key) error("%s is not suited to identify a row, but used with row_with()", column.name); - return select().with(column, "=", value).row(); - } - - public bool is_known_column(string column) { - ensure_init(); - foreach (Column c in columns) { - if (c.name == column) return true; - } - return false; - } - - public void create_table_at_version(long version) { - ensure_init(); - string sql = @"CREATE TABLE IF NOT EXISTS $name ("; - bool first = true; - for (int i = 0; i < columns.length; i++) { - Column c = columns[i]; - if (c.min_version <= version && c.max_version >= version) { - sql += @"$(!first ? "," : "") $(c.to_column_definition())"; - first = false; - } - } - sql += @"$constraints)"; - try { - db.exec(sql); - } catch (Error e) { - error(@"Qlite Error: Create table at version: $(e.message)"); - } - foreach (string stmt in create_statements) { - try { - db.exec(stmt); - } catch (Error e) { - error(@"Qlite Error: Create table at version: $(e.message)"); - } - } - } - - public void add_columns_for_version(long old_version, long new_version) { - ensure_init(); - foreach (Column c in columns) { - if (c.min_version <= new_version && c.max_version >= new_version && c.min_version > old_version) { - try { - db.exec(@"ALTER TABLE $name ADD COLUMN $(c.to_column_definition())"); - } catch (Error e) { - critical(@"Qlite Error: Add columns for version: $(e.message)"); - } - } - } - } - - public void delete_columns_for_version(long old_version, long new_version) { - bool column_deletion_required = false; - string column_list = ""; - foreach (Column c in columns) { - if (c.min_version <= new_version && c.max_version >= new_version) { - if (column_list == "") { - column_list = c.name; - } else { - column_list += ", " + c.name; - } - } - if (!(c.min_version <= new_version && c.max_version >= new_version) && c.min_version <= old_version && c.max_version >= old_version) { - column_deletion_required = true; - } - } - if (column_deletion_required) { - try { - db.exec(@"ALTER TABLE $name RENAME TO _$(name)_$old_version"); - create_table_at_version(new_version); - db.exec(@"INSERT INTO $name ($column_list) SELECT $column_list FROM _$(name)_$old_version"); - db.exec(@"DROP TABLE _$(name)_$old_version"); - } catch (Error e) { - error(@"Qlite Error: Delete columns for version change: $(e.message)"); - } - } - } - - internal void post() { - foreach (string stmt in post_statements) { - try { - db.exec(stmt); - } catch (Error e) { - error(@"Qlite Error: Post: $(e.message)"); - } - } - } -} - -} diff --git a/qlite/src/update_builder.vala b/qlite/src/update_builder.vala deleted file mode 100644 index 0bf83aee..00000000 --- a/qlite/src/update_builder.vala +++ /dev/null @@ -1,103 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class UpdateBuilder : StatementBuilder { - - // UPDATE [OR ...] - private string? or_val; - - // [...] - private Table? table; - private string table_name; - - // SET [...] - private StatementBuilder.AbstractField[] fields = {}; - - // WHERE [...] - private string selection = "1"; - private StatementBuilder.AbstractField[] selection_args = {}; - - internal UpdateBuilder(Database db, Table table) { - base(db); - this.table = table; - this.table_name = table.name; - } - - internal UpdateBuilder.for_name(Database db, string table) { - base(db); - this.table_name = table; - } - - public UpdateBuilder or(string or) { - this.or_val = or; - return this; - } - - public UpdateBuilder set(Column column, T value) { - fields += new Field(column, value); - return this; - } - - public UpdateBuilder set_null(Column column) { - if (column.not_null) error("Can't set non-null column %s to null", column.name); - fields += new NullField(column); - return this; - } - - public UpdateBuilder where(string selection, string[] selection_args = {}) { - if (this.selection != "1") error("selection was already done, but where() was called."); - this.selection = selection; - foreach (string arg in selection_args) { - this.selection_args += new StatementBuilder.StringField(arg); - } - return this; - } - - public UpdateBuilder with(Column column, string comp, T value) { - selection_args += new Field(column, value); - selection = @"($selection) AND $(column.name) $comp ?"; - return this; - } - - public UpdateBuilder with_null(Column column) { - selection = @"($selection) AND $(column.name) ISNULL"; - return this; - } - - public UpdateBuilder without_null(Column column) { - selection = @"($selection) AND $(column.name) NOT NULL"; - return this; - } - - internal override Statement prepare() { - string sql = "UPDATE"; - if (or_val != null) sql += @" OR $((!)or_val)"; - sql += @" $table_name SET "; - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - sql += ", "; - } - sql += @"$(((!)fields[i].column).name) = ?"; - } - sql += @" WHERE $selection"; - Statement stmt = db.prepare(sql); - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i+1); - } - for (int i = 0; i < selection_args.length; i++) { - selection_args[i].bind(stmt, i + fields.length + 1); - } - return stmt; - } - - public void perform() { - if (fields.length == 0) return; - if (prepare().step() != DONE) { - critical("SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - } - -} - -} diff --git a/qlite/src/upsert_builder.vala b/qlite/src/upsert_builder.vala deleted file mode 100644 index 79104972..00000000 --- a/qlite/src/upsert_builder.vala +++ /dev/null @@ -1,93 +0,0 @@ -using Sqlite; - -namespace Qlite { - -public class UpsertBuilder : StatementBuilder { - // INTO [...] - private Table table; - private string table_name; - - // VALUES [...] - private StatementBuilder.AbstractField[] keys = {}; - private StatementBuilder.AbstractField[] fields = {}; - - internal UpsertBuilder(Database db, Table table) { - base(db); - this.table = table; - this.table_name = table.name; - } - - public UpsertBuilder value(Column column, T value, bool key = false) { - if (key) { - keys += new Field(column, value); - } else { - fields += new Field(column, value); - } - return this; - } - - public UpsertBuilder value_null(Column column, bool key = false) { - if (column.not_null) error("Can't set non-null column %s to null", column.name); - if (key) { - keys += new NullField(column); - } else { - fields += new NullField(column); - } - return this; - } - - internal override Statement prepare() { - error("prepare() not available for upsert."); - } - - internal Statement prepare_upsert() { - var unique_fields = new StringBuilder(); - var unique_values = new StringBuilder(); - var update_fields = new StringBuilder(); - var update_values = new StringBuilder(); - var update_fields_vals = new StringBuilder(); - - for (int i = 0; i < keys.length; i++) { - if (i != 0) { - unique_fields.append(", "); - unique_values.append(", "); - } - unique_fields.append(keys[i].column.name); - unique_values.append("?"); - } - - for (int i = 0; i < fields.length; i++) { - if (i != 0) { - update_fields.append(", "); - update_values.append(", "); - update_fields_vals.append(", "); - } - update_fields.append(fields[i].column.name); - update_values.append("?"); - update_fields_vals.append(fields[i].column.name).append("=excluded.").append(fields[i].column.name); - } - - string sql = @"INSERT INTO $table_name ($(unique_fields.str), $(update_fields.str)) VALUES ($(unique_values.str), $(update_values.str)) " + - @"ON CONFLICT ($(unique_fields.str)) DO UPDATE SET $(update_fields_vals.str)"; - - Statement stmt = db.prepare(sql); - for (int i = 0; i < keys.length; i++) { - keys[i].bind(stmt, i + 1); - } - for (int i = 0; i < fields.length; i++) { - fields[i].bind(stmt, i + keys.length + 1); - } - - return stmt; - } - - public int64 perform() { - if (prepare_upsert().step() != DONE) { - critical(@"SQLite error: %d - %s", db.errcode(), db.errmsg()); - } - return db.last_insert_rowid(); - } - -} - -} -- cgit v1.3 From 49f4ae03b742e73b6efdf9edf50dee92ebae1448 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Mon, 24 Aug 2026 11:48:22 +0200 Subject: Move DLTS-SRTP into libdino --- libdino/meson.build | 6 +- libdino/src/crypto/dtls_srtp.vala | 146 +++++++++++ libdino/src/crypto/gnu/dtls_srtp.vala | 245 +++++++++++++++++ libdino/src/crypto/openssl/dtls_srtp.vala | 202 ++++++++++++++ libdino/src/crypto/openssl/utils.c | 49 ++++ libdino/src/crypto/openssl/utils.h | 8 + libdino/vapi/gnutls.vapi | 420 ++++++++++++++++++++++++++++++ libdino/vapi/openssl.vapi | 2 +- plugins/ice/meson.build | 13 - plugins/ice/src/dtls_srtp.vala | 146 ----------- plugins/ice/src/dtls_srtp_gnutls.vala | 245 ----------------- plugins/ice/src/dtls_srtp_openssl.vala | 202 -------------- plugins/ice/src/module.vala | 4 +- plugins/ice/src/openssl_utils.c | 49 ---- plugins/ice/src/openssl_utils.h | 8 - plugins/ice/src/transport_parameters.vala | 2 + plugins/ice/vapi/gnutls.vapi | 420 ------------------------------ plugins/ice/vapi/openssl.vapi | 218 ---------------- 18 files changed, 1081 insertions(+), 1304 deletions(-) create mode 100644 libdino/src/crypto/dtls_srtp.vala create mode 100644 libdino/src/crypto/gnu/dtls_srtp.vala create mode 100644 libdino/src/crypto/openssl/dtls_srtp.vala create mode 100644 libdino/src/crypto/openssl/utils.c create mode 100644 libdino/src/crypto/openssl/utils.h create mode 100644 libdino/vapi/gnutls.vapi delete mode 100644 plugins/ice/src/dtls_srtp.vala delete mode 100644 plugins/ice/src/dtls_srtp_gnutls.vala delete mode 100644 plugins/ice/src/dtls_srtp_openssl.vala delete mode 100644 plugins/ice/src/openssl_utils.c delete mode 100644 plugins/ice/src/openssl_utils.h delete mode 100644 plugins/ice/vapi/gnutls.vapi delete mode 100644 plugins/ice/vapi/openssl.vapi (limited to 'plugins/ice') diff --git a/libdino/meson.build b/libdino/meson.build index 5c7c20c4..67ac6a83 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -19,6 +19,7 @@ sources = files( 'src/dbus/upower.vala', 'src/crypto/cipher.vala', 'src/crypto/cipher_converter.vala', + 'src/crypto/dtls_srtp.vala', 'src/crypto/error.vala', 'src/crypto/srtp.vala', 'src/entity/account.vala', @@ -92,15 +93,18 @@ sources = files( sources += [version_c] if crypto_backend == 'gnu' - dependencies += [ dep_libgcrypt ] + dependencies += [ dep_libgcrypt, dep_gnutls ] sources += files( 'src/crypto/gnu/cipher.vala', + 'src/crypto/gnu/dtls_srtp.vala', 'src/crypto/gnu/utils.vala', ) elif crypto_backend == 'openssl' dependencies += [ dep_openssl ] sources += files( 'src/crypto/openssl/cipher.vala', + 'src/crypto/openssl/dtls_srtp.vala', + 'src/crypto/openssl/utils.c', 'src/crypto/openssl/utils.vala', ) endif diff --git a/libdino/src/crypto/dtls_srtp.vala b/libdino/src/crypto/dtls_srtp.vala new file mode 100644 index 00000000..884f1a43 --- /dev/null +++ b/libdino/src/crypto/dtls_srtp.vala @@ -0,0 +1,146 @@ +namespace Dino.Crypto.DtlsSrtp { + +public abstract class CredentialsCapsule : Object { + public uint8[] own_fingerprint; +} + +public abstract class AbstractHandler { + + public signal void send_data(uint8[] data); + + public bool ready { get { + return srtp_session.has_encrypt && srtp_session.has_decrypt; + }} + + public Mode mode { get; set; default = Mode.CLIENT; } + public uint8[] own_fingerprint { get; private set; } + public uint8[] peer_fingerprint { get; set; } + public string peer_fp_algo { get; set; } + + protected CredentialsCapsule credentials; + protected Cond buffer_cond = Cond(); + protected Mutex buffer_mutex = Mutex(); + protected Gee.LinkedList buffer_queue = new Gee.LinkedList(); + + protected bool running = false; + protected bool stop = false; + protected bool restart = false; + + protected Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session(); + + protected AbstractHandler.with_cert(CredentialsCapsule creds) { + this.credentials = creds; + this.own_fingerprint = creds.own_fingerprint; + } + + public uint8[]? process_incoming_data(uint component_id, uint8[] data) throws Crypto.Error { + if (data[0] >= 128) { + if (!srtp_session.has_decrypt) { + debug("Received data before SRTP session is ready, dropping."); + return null; + } + if (component_id == 1) { + if (data.length >= 2 && data[1] >= 192 && data[1] < 224) { + return srtp_session.decrypt_rtcp(data); + } + return srtp_session.decrypt_rtp(data); + } + if (component_id == 2) return srtp_session.decrypt_rtcp(data); + } + if (component_id == 1 && data.length >= 1 && (data[0] >= 20 && data[0] < 64)) { + on_data_rec(data); + return null; + } + debug("Dropping unknown data from component %u", component_id); + return null; + } + + public uint8[]? process_outgoing_data(uint component_id, uint8[] data) throws Crypto.Error { + if (srtp_session.has_encrypt) { + if (component_id == 1) { + if (data.length >= 2 && data[1] >= 192 && data[1] < 224) { + return srtp_session.encrypt_rtcp(data); + } + return srtp_session.encrypt_rtp(data); + } + if (component_id == 2) return srtp_session.encrypt_rtcp(data); + } + return null; + } + + public void on_data_rec(owned uint8[] data) { + buffer_mutex.lock(); + buffer_queue.add(new Bytes.take(data)); + buffer_cond.signal(); + buffer_mutex.unlock(); + } + + public void stop_dtls_connection() { + buffer_mutex.lock(); + stop = true; + buffer_cond.signal(); + buffer_mutex.unlock(); + } + + protected Bytes get_buffer_if_present () { + buffer_mutex.lock(); + if (buffer_queue.size == 0) { + buffer_mutex.unlock(); + return null; + } + Bytes res = buffer_queue.remove_at(0); + buffer_mutex.unlock(); + return res; + } + + public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() { + MainContext context = MainContext.current_source().get_context(); + var thread = new Thread("dtls-connection", () => { + // Check we can start working on the thread + buffer_mutex.lock(); + if (stop) { + restart = true; + buffer_mutex.unlock(); + return null; + } + if (running || ready) { + buffer_mutex.unlock(); + return null; + } + running = true; + restart = false; + buffer_mutex.unlock(); + + // Actual work + var res = setup_dtls_connection_thread(); + + // Callback + Source source = new IdleSource(); + source.set_callback(setup_dtls_connection.callback); + source.attach(context); + return res; + }); + yield; + return thread.join(); + } + + protected abstract Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread(); +} + +private string format_fingerprint(uint8[] fingerprint) { + var sb = new StringBuilder(); + for (int i = 0; i < fingerprint.length; i++) { + sb.append("%02X".printf(fingerprint[i])); + if (i < fingerprint.length - 1) { + sb.append(":"); + } + } + return sb.str; +} + + +public enum Mode { + CLIENT, SERVER +} + +} diff --git a/libdino/src/crypto/gnu/dtls_srtp.vala b/libdino/src/crypto/gnu/dtls_srtp.vala new file mode 100644 index 00000000..f6f0a24e --- /dev/null +++ b/libdino/src/crypto/gnu/dtls_srtp.vala @@ -0,0 +1,245 @@ +using GnuTLS; + +namespace Dino.Crypto.DtlsSrtp { + +public class CredentialsCapsuleGnuTLS : CredentialsCapsule { + internal X509.Certificate[] own_cert; + internal X509.PrivateKey private_key; +} + +private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) { + uint8[] buf = new uint8[512]; + size_t buf_out_size = 512; + certificate.get_fingerprint(digest_algo, buf, ref buf_out_size); + + uint8[] ret = new uint8[buf_out_size]; + for (int i = 0; i < buf_out_size; i++) { + ret[i] = buf[i]; + } + return ret; +} + +public CredentialsCapsule generate_credentials () throws GLib.Error { + int err = 0; + + X509.PrivateKey private_key = X509.PrivateKey.create (); + err = private_key.generate (PKAlgorithm.ECDSA, 256); + throw_if_error (err); + + var start_time = new DateTime.now_local().add_days(-1); + var end_time = start_time.add_days (2); + + X509.Certificate cert = X509.Certificate.create (); + cert.set_key (private_key); + cert.set_version (1); + cert.set_activation_time ((time_t) start_time.to_unix ()); + cert.set_expiration_time ((time_t) end_time.to_unix ()); + + uint32 serial = 1; + cert.set_serial (&serial, sizeof(uint32)); + + cert.sign (cert, private_key); + + uint8[] own_fingerprint = get_fingerprint (cert, DigestAlgorithm.SHA256); + X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert }; + + var creds = new CredentialsCapsuleGnuTLS(); + creds.own_fingerprint = own_fingerprint; + creds.own_cert = (owned) own_cert; + creds.private_key = (owned) private_key; + + return creds; +} + +public class Handler : AbstractHandler { + + public Handler.with_cert(CredentialsCapsule creds) { + base.with_cert(creds); + } + + protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() { + InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT; + debug("Setting up DTLS connection using GnuTLS. We're %s", mode.to_string()); + + CertificateCredentials cert_cred = CertificateCredentials.create(); + int err = cert_cred.set_x509_key(((CredentialsCapsuleGnuTLS)credentials).own_cert, ((CredentialsCapsuleGnuTLS)credentials).private_key); + throw_if_error(err); + + Session? session = Session.create(server_or_client | InitFlags.DATAGRAM); + session.enable_heartbeat(1); + session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80"); + session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred); + session.server_set_request(CertificateRequest.REQUEST); + session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509"); + + session.set_transport_pointer(this); + session.set_pull_function(pull_function); + session.set_pull_timeout_function(pull_timeout_function); + session.set_push_function(push_function); + session.set_verify_function(verify_function); + + DateTime maximum_time = new DateTime.now_utc().add_seconds(20); + do { + err = session.handshake(); + + DateTime current_time = new DateTime.now_utc(); + if (maximum_time.compare(current_time) < 0) { + warning("DTLS handshake timeouted"); + err = ErrorCode.APPLICATION_ERROR_MIN + 1; + break; + } + if (stop) { + debug("DTLS handshake stopped"); + err = ErrorCode.APPLICATION_ERROR_MIN + 2; + break; + } + } while (err < 0 && !((ErrorCode)err).is_fatal()); + + buffer_mutex.lock(); + if (stop) { + stop = false; + running = false; + bool restart = restart; + buffer_mutex.unlock(); + if (restart) { + debug("Restarting DTLS handshake"); + return setup_dtls_connection_thread(); + } + return null; + } + buffer_mutex.unlock(); + if (err != ErrorCode.SUCCESS) { + warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string()); + return null; + } + + uint8[] km = new uint8[150]; + Datum? client_key, client_salt, server_key, server_salt; + session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt); + if (client_key == null || client_salt == null || server_key == null || server_salt == null) { + warning("SRTP client/server key/salt null"); + } + + debug("Finished DTLS connection. We're %s", mode.to_string()); + if (mode == Mode.SERVER) { + srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); + srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); + } else { + srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); + srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); + } + return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); + } + + private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) { + Handler self = transport_ptr as Handler; + + self.buffer_mutex.lock(); + while (self.buffer_queue.size == 0) { + self.buffer_cond.wait(self.buffer_mutex); + if (self.stop) { + self.buffer_mutex.unlock(); + debug("DTLS handshake pull_function stopped"); + return -1; + } + } + Bytes data = self.buffer_queue.remove_at(0); + self.buffer_mutex.unlock(); + + uint8[] data_uint8 = Bytes.unref_to_data((owned) data); + Memory.copy(buffer, data_uint8, data_uint8.length); + + // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error. + return (ssize_t)data_uint8.length; + } + + private static int pull_timeout_function(void* transport_ptr, uint ms) { + Handler self = transport_ptr as Handler; + + int64 end_time = get_monotonic_time() + ms * 1000; + + self.buffer_mutex.lock(); + while (self.buffer_queue.size == 0) { + self.buffer_cond.wait_until(self.buffer_mutex, end_time); + if (self.stop) { + self.buffer_mutex.unlock(); + debug("DTLS handshake pull_timeout_function stopped"); + return -1; + } + + if (get_monotonic_time() > end_time) { + self.buffer_mutex.unlock(); + return 0; + } + } + self.buffer_mutex.unlock(); + + // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. + return 1; + } + + private static ssize_t push_function(void* transport_ptr, uint8[] buffer) { + Handler self = transport_ptr as Handler; + self.send_data(buffer); + + // The callback should return a positive number indicating the bytes sent, and -1 on error. + return (ssize_t)buffer.length; + } + + private static int verify_function(Session session) { + Handler self = session.get_transport_pointer() as Handler; + try { + bool valid = self.verify_peer_cert(session); + if (!valid) { + warning("DTLS certificate invalid. Aborting handshake."); + return 1; + } + } catch (Error e) { + warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message); + return 1; + } + + // The callback function should return 0 for the handshake to continue or non-zero to terminate. + return 0; + } + + private bool verify_peer_cert(Session session) throws GLib.Error { + unowned Datum[] cert_datums = session.get_peer_certificates(); + if (cert_datums.length == 0) { + warning("No peer certs"); + return false; + } + if (cert_datums.length > 1) warning("More than one peer cert"); + + X509.Certificate peer_cert = X509.Certificate.create(); + peer_cert.import(ref cert_datums[0], CertificateFormat.DER); + + DigestAlgorithm algo; + switch (peer_fp_algo) { + case "sha-256": + algo = DigestAlgorithm.SHA256; + break; + default: + warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo); + return false; + } + + uint8[] real_peer_fp = get_fingerprint(peer_cert, algo); + + if (real_peer_fp.length != this.peer_fingerprint.length) { + warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length); + return false; + } + + for (int i = 0; i < real_peer_fp.length; i++) { + if (real_peer_fp[i] != this.peer_fingerprint[i]) { + warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint)); + return false; + } + } + + return true; + } +} + +} \ No newline at end of file diff --git a/libdino/src/crypto/openssl/dtls_srtp.vala b/libdino/src/crypto/openssl/dtls_srtp.vala new file mode 100644 index 00000000..192f0da2 --- /dev/null +++ b/libdino/src/crypto/openssl/dtls_srtp.vala @@ -0,0 +1,202 @@ +using OpenSSL; + +namespace Dino.Crypto.DtlsSrtp { + +public class CredentialsCapsuleOpenSSL : CredentialsCapsule { + internal X509.Certificate own_cert; + internal EVP.Key private_key; +} + +public CredentialsCapsule generate_credentials () throws GLib.Error { + EVP.Key key = new EVP.Key.generate_ecdsa ("prime256v1"); + + var start_time = new DateTime.now_local().add_days(-1); + var end_time = start_time.add_days (2); + + X509.Certificate cert = new X509.Certificate (); + cert.set_public_key (key); + cert.set_version (1); + cert.not_before.set ((time_t) start_time.to_unix ()); + cert.not_after.set ((time_t) end_time.to_unix ()); + cert.serial_number.set (1); + + cert.sign (key, EVP.sha256 ()); + + CredentialsCapsuleOpenSSL credentials = new CredentialsCapsuleOpenSSL (); + credentials.own_fingerprint = cert.digest (EVP.sha256 ()); + credentials.own_cert = (owned) cert; + credentials.private_key = (owned) key; + return credentials; +} + +public class Handler : AbstractHandler { + + public Handler.with_cert (CredentialsCapsule creds) { + base.with_cert (creds); + } + + protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread () { + debug("Setting up DTLS connection using OpenSSL. We're %s", mode.to_string()); + SSL.Context context = new SSL.Context (mode == Mode.SERVER ? SSL.Method.DTLS_SERVER : SSL.Method.DTLS_CLIENT); + context.set_tlsext_use_srtp ("SRTP_AES128_CM_SHA1_80"); + context.use_certificate (((CredentialsCapsuleOpenSSL) credentials).own_cert); + context.use_private_key (((CredentialsCapsuleOpenSSL) credentials).private_key); + SSL session = new SSL (context); + BIO bio = new BIO(get_handler_based_bio_method()); + bio.data = this; + session.rbio = bio; + session.wbio = bio; + + DateTime maximum_time = new DateTime.now_utc().add_seconds(20); + int err = 0; + if (mode == Mode.SERVER) { + session.set_accept_state (); + } else { + session.set_connect_state (); + } + do { + try { + SSL.Error ret = session.do_handshake(); + switch (ret) { + case SSL.Error.NONE: + err = 1; + break; + case SSL.Error.WANT_READ: + debug ("DTLS wants to read, but nothing in queue, wait for buffer"); + buffer_mutex.lock(); + if (buffer_queue.size == 0) { + buffer_cond.wait_until(buffer_mutex, get_monotonic_time() + maximum_time.difference(new DateTime.now_utc())); + } + buffer_mutex.unlock(); + err = -1; + break; + default: + warning ("DTLS Error: %s", @"$ret"); + err = 4; + break; + } + } catch (Error e) { + warning ("DTLS Error: %s", e.message); + err = e.code; + } + + DateTime current_time = new DateTime.now_utc(); + if (maximum_time.compare(current_time) < 0) { + debug ("DTLS handshake timeouted"); + err = 2; + break; + } + if (stop) { + debug ("DTLS handshake stopped"); + err = 3; + break; + } + } while (err < 0); + + buffer_mutex.lock(); + if (stop) { + stop = false; + running = false; + bool restart = restart; + buffer_mutex.unlock(); + if (restart) { + debug ("Restarting DTLS handshake"); + return setup_dtls_connection_thread(); + } + return null; + } + buffer_mutex.unlock(); + if (err != 1) { + debug ("DTLS handshake failed"); + return null; + } + + // TODO: Check peer certificate + + uint8[] km = new uint8[60]; + session.export_keying_material (km, "EXTRACTOR-dtls_srtp"); + uint8[] client_key = km[0:16]; + uint8[] server_key = km[16:32]; + uint8[] client_salt = km[32:46]; + uint8[] server_salt = km[46:60]; + + debug ("Finished DTLS connection. We're %s", mode.to_string()); + if (mode == Mode.SERVER) { + srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); + srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); + } else { + srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); + srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); + } + return new Xmpp.Xep.Jingle.ContentEncryption (Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); + } + + private int read_impl (BIO bio, uint8[] out_buf) { + Bytes data = get_buffer_if_present (); + if (data == null) { + if (!stop) { + debug ("No pending buffer in queue, but end not reached yet, set_retry_read"); + bio.set_retry_read (); + } + return -1; + } + if (data.length > out_buf.length) { + warning ("Buffer in queue does not fit in out_buf"); + return -1; + } + debug ("Read %d bytes from queue", data.length); + + uint8[] data_uint8 = Bytes.unref_to_data((owned) data); + Memory.copy (out_buf, data_uint8, data_uint8.length); + bio.clear_retry_flags (); + return data_uint8.length; + } + + private int write_impl (BIO bio, uint8[] buf) { + debug ("Write %d bytes to network", buf.length); + send_data (buf); + return buf.length; + } + + private long ctrl_impl (BIO bio, BIO.ControlCommand cmd, long num, void* ptr) { + switch (cmd) { + case BIO.ControlCommand.FLUSH: + // Datagrams are sent out immediately + return 1; + case BIO.ControlCommand.DGRAM_SET_NEXT_TIMEOUT: + // Datagrams are sent out immediately + return 1; + case BIO.ControlCommand.DGRAM_GET_MTU_OVERHEAD: + // Just some safe estimate + return 70; + case BIO.ControlCommand.DGRAM_QUERY_MTU: + // Just some safe estimate + return 1200; + case BIO.ControlCommand.WPENDING: + // Datagrams are sent out immediately + return 0; + case BIO.ControlCommand.POP: + case BIO.ControlCommand.PUSH: + // Ignored + return 0; + default: + warning (@"Unimplemented ctrl cmd:$cmd, num:$num"); + return 0; + } + } + + private static BIO.Method _handler_based_bio_method_instance = null; + + private static unowned BIO.Method get_handler_based_bio_method () { + if (_handler_based_bio_method_instance != null) return _handler_based_bio_method_instance; + _handler_based_bio_method_instance = new BIO.Method (BIO.Type.SOURCE_SINK | BIO.Type.DGRAM, "Dino DTLS Handler BIO"); + _handler_based_bio_method_instance.read = (bio, out_buf) => bio.data.read_impl (bio, out_buf); + _handler_based_bio_method_instance.write = (bio, buf) => bio.data.write_impl (bio, buf); + _handler_based_bio_method_instance.ctrl = (bio, cmd, num, ptr) => bio.data.ctrl_impl (bio, cmd, num, ptr); + return _handler_based_bio_method_instance; + } +} + + + +} \ No newline at end of file diff --git a/libdino/src/crypto/openssl/utils.c b/libdino/src/crypto/openssl/utils.c new file mode 100644 index 00000000..1a84f642 --- /dev/null +++ b/libdino/src/crypto/openssl/utils.c @@ -0,0 +1,49 @@ +#include "utils.h" +#include +#include + +#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x30000000L +// This is for OpenSSL 3.0.0 and newer + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { + // Generate EVP_PKEY directly + EVP_PKEY *pkey = EVP_EC_gen (curve); + return pkey; +} + +#else +// This is for OpenSSL before 3.0.0 and forks of earlier OpenSSL versions like LibreSSL + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { + // Get NID from curve name + int nid = OBJ_sn2nid (curve); + if (nid == NID_undef) return NULL; + + // Create EC_KEY + EC_KEY *ec_key = EC_KEY_new_by_curve_name (nid); + if (!ec_key) return NULL; + + // Generate key + if (!EC_KEY_generate_key (ec_key)) { + EC_KEY_free (ec_key); + return NULL; + } + + // Create EVP_PKEY + EVP_PKEY *pkey = EVP_PKEY_new (); + if (!pkey) { + EC_KEY_free (ec_key); + return NULL; + } + + // Assign EC_KEY to EVP_PKEY + if (!EVP_PKEY_assign_EC_KEY (pkey, ec_key)) { + EC_KEY_free (ec_key); + return NULL; + } + + // EVP_PKEY_assign_EC_KEY takes ownership of ec_key, no need to free it explicitly + return pkey; +} + +#endif diff --git a/libdino/src/crypto/openssl/utils.h b/libdino/src/crypto/openssl/utils.h new file mode 100644 index 00000000..bcc6f53a --- /dev/null +++ b/libdino/src/crypto/openssl/utils.h @@ -0,0 +1,8 @@ +#ifndef DINO_OPENSSL_UTILS_H +#define DINO_OPENSSL_UTILS_H + +#include + +EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve); + +#endif //DINO_OPENSSL_UTILS_H \ No newline at end of file diff --git a/libdino/vapi/gnutls.vapi b/libdino/vapi/gnutls.vapi new file mode 100644 index 00000000..86a8c401 --- /dev/null +++ b/libdino/vapi/gnutls.vapi @@ -0,0 +1,420 @@ +[CCode (cprefix = "gnutls_", lower_case_cprefix = "gnutls_", cheader_filename = "gnutls/gnutls.h")] +namespace GnuTLS { + + public int global_init(); + + [CCode (cname = "gnutls_pull_func", has_target = false)] + public delegate ssize_t PullFunc(void* transport_ptr, [CCode (ctype = "void*", array_length_type="size_t")] uint8[] array); + + [CCode (cname = "gnutls_pull_timeout_func", has_target = false)] + public delegate int PullTimeoutFunc(void* transport_ptr, uint ms); + + [CCode (cname = "gnutls_push_func", has_target = false)] + public delegate ssize_t PushFunc(void* transport_ptr, [CCode (ctype = "void*", array_length_type="size_t")] uint8[] array); + + [CCode (cname = "gnutls_certificate_verify_function", has_target = false)] + public delegate int VerifyFunc(Session session); + + [Compact] + [CCode (cname = "struct gnutls_session_int", free_function = "gnutls_deinit")] + public class Session { + + public static Session? create(int con_end) throws GLib.Error { + Session result; + var ret = init(out result, con_end); + throw_if_error(ret); + return result; + } + + [CCode (cname = "gnutls_init")] + private static int init(out Session session, int con_end); + + [CCode (cname = "gnutls_transport_set_push_function")] + public void set_push_function(PushFunc func); + + [CCode (cname = "gnutls_transport_set_pull_function")] + public void set_pull_function(PullFunc func); + + [CCode (cname = "gnutls_transport_set_pull_timeout_function")] + public void set_pull_timeout_function(PullTimeoutFunc func); + + [CCode (cname = "gnutls_transport_set_ptr")] + public void set_transport_pointer(void* ptr); + + [CCode (cname = "gnutls_transport_get_ptr")] + public void* get_transport_pointer(); + + [CCode (cname = "gnutls_heartbeat_enable")] + public int enable_heartbeat(uint type); + + [CCode (cname = "gnutls_certificate_server_set_request")] + public void server_set_request(CertificateRequest req); + + [CCode (cname = "gnutls_credentials_set")] + public int set_credentials_(CredentialsType type, void* cred); + [CCode (cname = "gnutls_credentials_set_")] + public void set_credentials(CredentialsType type, void* cred) throws GLib.Error { + int err = set_credentials_(type, cred); + throw_if_error(err); + } + + [CCode (cname = "gnutls_priority_set_direct")] + public int set_priority_from_string_(string priority, out unowned string err_pos = null); + [CCode (cname = "gnutls_priority_set_direct_")] + public void set_priority_from_string(string priority, out unowned string err_pos = null) throws GLib.Error { + int err = set_priority_from_string_(priority, out err_pos); + throw_if_error(err); + } + + [CCode (cname = "gnutls_srtp_set_profile_direct")] + public int set_srtp_profile_direct_(string profiles, out unowned string err_pos = null); + [CCode (cname = "gnutls_srtp_set_profile_direct_")] + public void set_srtp_profile_direct(string profiles, out unowned string err_pos = null) throws GLib.Error { + int err = set_srtp_profile_direct_(profiles, out err_pos); + throw_if_error(err); + } + + [CCode (cname = "gnutls_transport_set_int")] + public void transport_set_int(int fd); + + [CCode (cname = "gnutls_handshake")] + public int handshake(); + + [CCode (cname = "gnutls_srtp_get_keys")] + public int get_srtp_keys_(void *key_material, uint32 key_material_size, out Datum client_key, out Datum client_salt, out Datum server_key, out Datum server_salt); + [CCode (cname = "gnutls_srtp_get_keys_")] + public void get_srtp_keys(void *key_material, uint32 key_material_size, out Datum client_key, out Datum client_salt, out Datum server_key, out Datum server_salt) throws GLib.Error { + get_srtp_keys_(key_material, key_material_size, out client_key, out client_salt, out server_key, out server_salt); + } + + [CCode (cname = "gnutls_certificate_get_peers", array_length_type = "unsigned int")] + public unowned Datum[]? get_peer_certificates(); + + [CCode (cname = "gnutls_session_set_verify_function")] + public void set_verify_function(VerifyFunc func); + } + + [Compact] + [CCode (cname = "struct gnutls_certificate_credentials_st", free_function = "gnutls_certificate_free_credentials", cprefix = "gnutls_certificate_")] + public class CertificateCredentials { + + [CCode (cname = "gnutls_certificate_allocate_credentials")] + private static int allocate(out CertificateCredentials credentials); + + public static CertificateCredentials create() throws GLib.Error { + CertificateCredentials result; + var ret = allocate (out result); + throw_if_error(ret); + return result; + } + + public void get_x509_crt(uint index, [CCode (array_length_type = "unsigned int")] out unowned X509.Certificate[] x509_ca_list); + + public int set_x509_key(X509.Certificate[] cert_list, X509.PrivateKey key); + } + + [CCode (cheader_filename = "gnutls/x509.h", cprefix = "GNUTLS_")] + namespace X509 { + + [Compact] + [CCode (cname = "struct gnutls_x509_crt_int", cprefix = "gnutls_x509_crt_", free_function = "gnutls_x509_crt_deinit")] + public class Certificate { + + [CCode (cname = "gnutls_x509_crt_init")] + private static int init (out Certificate cert); + public static Certificate create() throws GLib.Error { + Certificate result; + var ret = init (out result); + throw_if_error(ret); + return result; + } + + [CCode (cname = "gnutls_x509_crt_import")] + public int import_(ref Datum data, CertificateFormat format); + [CCode (cname = "gnutls_x509_crt_import_")] + public void import(ref Datum data, CertificateFormat format) throws GLib.Error { + int err = import_(ref data, format); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_set_version")] + public int set_version_(uint version); + [CCode (cname = "gnutls_x509_crt_set_version_")] + public void set_version(uint version) throws GLib.Error { + int err = set_version_(version); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_set_key")] + public int set_key_(PrivateKey key); + [CCode (cname = "gnutls_x509_crt_set_key_")] + public void set_key(PrivateKey key) throws GLib.Error { + int err = set_key_(key); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_set_activation_time")] + public int set_activation_time_(time_t act_time); + [CCode (cname = "gnutls_x509_crt_set_activation_time_")] + public void set_activation_time(time_t act_time) throws GLib.Error { + int err = set_activation_time_(act_time); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_set_expiration_time")] + public int set_expiration_time_(time_t exp_time); + [CCode (cname = "gnutls_x509_crt_set_expiration_time_")] + public void set_expiration_time(time_t exp_time) throws GLib.Error { + int err = set_expiration_time_(exp_time); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_set_serial")] + public int set_serial_(void* serial, size_t serial_size); + [CCode (cname = "gnutls_x509_crt_set_serial_")] + public void set_serial(void* serial, size_t serial_size) throws GLib.Error { + int err = set_serial_(serial, serial_size); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_sign")] + public int sign_(Certificate issuer, PrivateKey issuer_key); + [CCode (cname = "gnutls_x509_crt_sign_")] + public void sign(Certificate issuer, PrivateKey issuer_key) throws GLib.Error { + int err = sign_(issuer, issuer_key); + throw_if_error(err); + } + + [CCode (cname = "gnutls_x509_crt_get_fingerprint")] + public int get_fingerprint_(DigestAlgorithm algo, void* buf, ref size_t buf_size); + [CCode (cname = "gnutls_x509_crt_get_fingerprint_")] + public void get_fingerprint(DigestAlgorithm algo, void* buf, ref size_t buf_size) throws GLib.Error { + int err = get_fingerprint_(algo, buf, ref buf_size); + throw_if_error(err); + } + } + + [Compact] + [CCode (cname = "struct gnutls_x509_privkey_int", cprefix = "gnutls_x509_privkey_", free_function = "gnutls_x509_privkey_deinit")] + public class PrivateKey { + private static int init (out PrivateKey key); + public static PrivateKey create () throws GLib.Error { + PrivateKey result; + var ret = init (out result); + throw_if_error(ret); + return result; + } + + public int generate(PKAlgorithm algo, uint bits, uint flags = 0); + } + + } + + [CCode (cname = "gnutls_certificate_request_t", cprefix = "GNUTLS_CERT_", has_type_id = false)] + public enum CertificateRequest { + IGNORE, + REQUEST, + REQUIRE + } + + [CCode (cname = "gnutls_pk_algorithm_t", cprefix = "GNUTLS_PK_", has_type_id = false)] + public enum PKAlgorithm { + UNKNOWN, + RSA, + DSA, + ECDSA; + } + + [CCode (cname = "gnutls_digest_algorithm_t", cprefix = "GNUTLS_DIG_", has_type_id = false)] + public enum DigestAlgorithm { + NULL, + MD5, + SHA1, + RMD160, + MD2, + SHA224, + SHA256, + SHA384, + SHA512; + } + + [Flags] + [CCode (cname = "gnutls_init_flags_t", cprefix = "GNUTLS_", has_type_id = false)] + public enum InitFlags { + SERVER, + CLIENT, + DATAGRAM + } + + [CCode (cname = "gnutls_credentials_type_t", cprefix = "GNUTLS_CRD_", has_type_id = false)] + public enum CredentialsType { + CERTIFICATE, + ANON, + SRP, + PSK, + IA + } + + [CCode (cname = "gnutls_x509_crt_fmt_t", cprefix = "GNUTLS_X509_FMT_", has_type_id = false)] + public enum CertificateFormat { + DER, + PEM + } + + [Flags] + [CCode (cname = "gnutls_certificate_status_t", cprefix = "GNUTLS_CERT_", has_type_id = false)] + public enum CertificateStatus { + INVALID, // will be set if the certificate was not verified. + REVOKED, // in X.509 this will be set only if CRLs are checked + SIGNER_NOT_FOUND, + SIGNER_NOT_CA, + INSECURE_ALGORITHM + } + + [SimpleType] + [CCode (cname = "gnutls_datum_t", has_type_id = false)] + public struct Datum { + public uint8* data; + public uint size; + + public uint8[] extract() { + uint8[] ret = new uint8[size]; + for (int i = 0; i < size; i++) { + ret[i] = data[i]; + } + return ret; + } + } + + // Gnutls error codes. The mapping to a TLS alert is also shown in comments. + [CCode (cname = "int", cprefix = "GNUTLS_E_", lower_case_cprefix = "gnutls_error_", has_type_id = false)] + public enum ErrorCode { + SUCCESS, + UNKNOWN_COMPRESSION_ALGORITHM, + UNKNOWN_CIPHER_TYPE, + LARGE_PACKET, + UNSUPPORTED_VERSION_PACKET, // GNUTLS_A_PROTOCOL_VERSION + UNEXPECTED_PACKET_LENGTH, // GNUTLS_A_RECORD_OVERFLOW + INVALID_SESSION, + FATAL_ALERT_RECEIVED, + UNEXPECTED_PACKET, // GNUTLS_A_UNEXPECTED_MESSAGE + WARNING_ALERT_RECEIVED, + ERROR_IN_FINISHED_PACKET, + UNEXPECTED_HANDSHAKE_PACKET, + UNKNOWN_CIPHER_SUITE, // GNUTLS_A_HANDSHAKE_FAILURE + UNWANTED_ALGORITHM, + MPI_SCAN_FAILED, + DECRYPTION_FAILED, // GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_BAD_RECORD_MAC + MEMORY_ERROR, + DECOMPRESSION_FAILED, // GNUTLS_A_DECOMPRESSION_FAILURE + COMPRESSION_FAILED, + AGAIN, + EXPIRED, + DB_ERROR, + SRP_PWD_ERROR, + INSUFFICIENT_CREDENTIALS, + HASH_FAILED, + BASE64_DECODING_ERROR, + MPI_PRINT_FAILED, + REHANDSHAKE, // GNUTLS_A_NO_RENEGOTIATION + GOT_APPLICATION_DATA, + RECORD_LIMIT_REACHED, + ENCRYPTION_FAILED, + PK_ENCRYPTION_FAILED, + PK_DECRYPTION_FAILED, + PK_SIGN_FAILED, + X509_UNSUPPORTED_CRITICAL_EXTENSION, + KEY_USAGE_VIOLATION, + NO_CERTIFICATE_FOUND, // GNUTLS_A_BAD_CERTIFICATE + INVALID_REQUEST, + SHORT_MEMORY_BUFFER, + INTERRUPTED, + PUSH_ERROR, + PULL_ERROR, + RECEIVED_ILLEGAL_PARAMETER, // GNUTLS_A_ILLEGAL_PARAMETER + REQUESTED_DATA_NOT_AVAILABLE, + PKCS1_WRONG_PAD, + RECEIVED_ILLEGAL_EXTENSION, + INTERNAL_ERROR, + DH_PRIME_UNACCEPTABLE, + FILE_ERROR, + TOO_MANY_EMPTY_PACKETS, + UNKNOWN_PK_ALGORITHM, + // returned if libextra functionality was requested but + // gnutls_global_init_extra() was not called. + + INIT_LIBEXTRA, + LIBRARY_VERSION_MISMATCH, + // returned if you need to generate temporary RSA + // parameters. These are needed for export cipher suites. + + NO_TEMPORARY_RSA_PARAMS, + LZO_INIT_FAILED, + NO_COMPRESSION_ALGORITHMS, + NO_CIPHER_SUITES, + OPENPGP_GETKEY_FAILED, + PK_SIG_VERIFY_FAILED, + ILLEGAL_SRP_USERNAME, + SRP_PWD_PARSING_ERROR, + NO_TEMPORARY_DH_PARAMS, + // For certificate and key stuff + + ASN1_ELEMENT_NOT_FOUND, + ASN1_IDENTIFIER_NOT_FOUND, + ASN1_DER_ERROR, + ASN1_VALUE_NOT_FOUND, + ASN1_GENERIC_ERROR, + ASN1_VALUE_NOT_VALID, + ASN1_TAG_ERROR, + ASN1_TAG_IMPLICIT, + ASN1_TYPE_ANY_ERROR, + ASN1_SYNTAX_ERROR, + ASN1_DER_OVERFLOW, + OPENPGP_UID_REVOKED, + CERTIFICATE_ERROR, + CERTIFICATE_KEY_MISMATCH, + UNSUPPORTED_CERTIFICATE_TYPE, // GNUTLS_A_UNSUPPORTED_CERTIFICATE + X509_UNKNOWN_SAN, + OPENPGP_FINGERPRINT_UNSUPPORTED, + X509_UNSUPPORTED_ATTRIBUTE, + UNKNOWN_HASH_ALGORITHM, + UNKNOWN_PKCS_CONTENT_TYPE, + UNKNOWN_PKCS_BAG_TYPE, + INVALID_PASSWORD, + MAC_VERIFY_FAILED, // for PKCS #12 MAC + CONSTRAINT_ERROR, + WARNING_IA_IPHF_RECEIVED, + WARNING_IA_FPHF_RECEIVED, + IA_VERIFY_FAILED, + UNKNOWN_ALGORITHM, + BASE64_ENCODING_ERROR, + INCOMPATIBLE_CRYPTO_LIBRARY, + INCOMPATIBLE_LIBTASN1_LIBRARY, + OPENPGP_KEYRING_ERROR, + X509_UNSUPPORTED_OID, + RANDOM_FAILED, + BASE64_UNEXPECTED_HEADER_ERROR, + OPENPGP_SUBKEY_ERROR, + CRYPTO_ALREADY_REGISTERED, + HANDSHAKE_TOO_LARGE, + UNIMPLEMENTED_FEATURE, + APPLICATION_ERROR_MAX, // -65000 + APPLICATION_ERROR_MIN; // -65500 + + [CCode (cname = "gnutls_error_is_fatal")] + public bool is_fatal(); + + [CCode (cname = "gnutls_perror")] + public void print(); + + [CCode (cname = "gnutls_strerror")] + public unowned string to_string(); + } + + public void throw_if_error(int err_int) throws GLib.Error { + ErrorCode error = (ErrorCode)err_int; + if (error != ErrorCode.SUCCESS) { + throw new GLib.Error(-1, error, "%s%s", error.to_string(), error.is_fatal() ? " fatal" : ""); + } + } +} \ No newline at end of file diff --git a/libdino/vapi/openssl.vapi b/libdino/vapi/openssl.vapi index 87693d37..57e4022c 100644 --- a/libdino/vapi/openssl.vapi +++ b/libdino/vapi/openssl.vapi @@ -86,7 +86,7 @@ namespace OpenSSL { [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] public class Key { public Key (); - [CCode (cheader_filename = "openssl_utils.h")] + [CCode (cheader_filename = "crypto/openssl/utils.h")] public Key.generate_ecdsa (string curve); } [Compact] diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build index 99f8e6a1..19030259 100644 --- a/plugins/ice/meson.build +++ b/plugins/ice/meson.build @@ -8,7 +8,6 @@ dependencies = [ dep_xmpp_vala, ] sources = files( - 'src/dtls_srtp.vala', 'src/module.vala', 'src/plugin.vala', 'src/transport_parameters.vala', @@ -21,18 +20,6 @@ c_args = vala_c_args + [ vala_args = [ '--vapidir', meson.current_source_dir() / 'vapi', ] -if crypto_backend == 'gnu' - dependencies += [ dep_gnutls ] - sources += files( - 'src/dtls_srtp_gnutls.vala' - ) -elif crypto_backend == 'openssl' - dependencies += [ dep_openssl ] - sources += files( - 'src/dtls_srtp_openssl.vala', - 'src/openssl_utils.c', - ) -endif lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) dep_ice = declare_dependency(link_with: lib_ice, include_directories: include_directories('.')) summary('Peer-to-peer communication (ice)', dep_ice.found(), bool_yn: true, section: 'Plugins') diff --git a/plugins/ice/src/dtls_srtp.vala b/plugins/ice/src/dtls_srtp.vala deleted file mode 100644 index 41918359..00000000 --- a/plugins/ice/src/dtls_srtp.vala +++ /dev/null @@ -1,146 +0,0 @@ -namespace Dino.Plugins.Ice.DtlsSrtp { - -public abstract class CredentialsCapsule : Object { - public uint8[] own_fingerprint; -} - -public abstract class AbstractHandler { - - public signal void send_data(uint8[] data); - - public bool ready { get { - return srtp_session.has_encrypt && srtp_session.has_decrypt; - }} - - public Mode mode { get; set; default = Mode.CLIENT; } - public uint8[] own_fingerprint { get; private set; } - public uint8[] peer_fingerprint { get; set; } - public string peer_fp_algo { get; set; } - - protected CredentialsCapsule credentials; - protected Cond buffer_cond = Cond(); - protected Mutex buffer_mutex = Mutex(); - protected Gee.LinkedList buffer_queue = new Gee.LinkedList(); - - protected bool running = false; - protected bool stop = false; - protected bool restart = false; - - protected Crypto.Srtp.Session srtp_session = new Crypto.Srtp.Session(); - - protected AbstractHandler.with_cert(CredentialsCapsule creds) { - this.credentials = creds; - this.own_fingerprint = creds.own_fingerprint; - } - - public uint8[]? process_incoming_data(uint component_id, uint8[] data) throws Crypto.Error { - if (data[0] >= 128) { - if (!srtp_session.has_decrypt) { - debug("Received data before SRTP session is ready, dropping."); - return null; - } - if (component_id == 1) { - if (data.length >= 2 && data[1] >= 192 && data[1] < 224) { - return srtp_session.decrypt_rtcp(data); - } - return srtp_session.decrypt_rtp(data); - } - if (component_id == 2) return srtp_session.decrypt_rtcp(data); - } - if (component_id == 1 && data.length >= 1 && (data[0] >= 20 && data[0] < 64)) { - on_data_rec(data); - return null; - } - debug("Dropping unknown data from component %u", component_id); - return null; - } - - public uint8[]? process_outgoing_data(uint component_id, uint8[] data) throws Crypto.Error { - if (srtp_session.has_encrypt) { - if (component_id == 1) { - if (data.length >= 2 && data[1] >= 192 && data[1] < 224) { - return srtp_session.encrypt_rtcp(data); - } - return srtp_session.encrypt_rtp(data); - } - if (component_id == 2) return srtp_session.encrypt_rtcp(data); - } - return null; - } - - public void on_data_rec(owned uint8[] data) { - buffer_mutex.lock(); - buffer_queue.add(new Bytes.take(data)); - buffer_cond.signal(); - buffer_mutex.unlock(); - } - - public void stop_dtls_connection() { - buffer_mutex.lock(); - stop = true; - buffer_cond.signal(); - buffer_mutex.unlock(); - } - - protected Bytes get_buffer_if_present () { - buffer_mutex.lock(); - if (buffer_queue.size == 0) { - buffer_mutex.unlock(); - return null; - } - Bytes res = buffer_queue.remove_at(0); - buffer_mutex.unlock(); - return res; - } - - public async Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection() { - MainContext context = MainContext.current_source().get_context(); - var thread = new Thread("dtls-connection", () => { - // Check we can start working on the thread - buffer_mutex.lock(); - if (stop) { - restart = true; - buffer_mutex.unlock(); - return null; - } - if (running || ready) { - buffer_mutex.unlock(); - return null; - } - running = true; - restart = false; - buffer_mutex.unlock(); - - // Actual work - var res = setup_dtls_connection_thread(); - - // Callback - Source source = new IdleSource(); - source.set_callback(setup_dtls_connection.callback); - source.attach(context); - return res; - }); - yield; - return thread.join(); - } - - protected abstract Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread(); -} - -private string format_fingerprint(uint8[] fingerprint) { - var sb = new StringBuilder(); - for (int i = 0; i < fingerprint.length; i++) { - sb.append("%02X".printf(fingerprint[i])); - if (i < fingerprint.length - 1) { - sb.append(":"); - } - } - return sb.str; -} - - -public enum Mode { - CLIENT, SERVER -} - -} diff --git a/plugins/ice/src/dtls_srtp_gnutls.vala b/plugins/ice/src/dtls_srtp_gnutls.vala deleted file mode 100644 index 91a7cfb2..00000000 --- a/plugins/ice/src/dtls_srtp_gnutls.vala +++ /dev/null @@ -1,245 +0,0 @@ -using GnuTLS; - -namespace Dino.Plugins.Ice.DtlsSrtp { - -public class CredentialsCapsuleGnuTLS : CredentialsCapsule { - public X509.Certificate[] own_cert; - public X509.PrivateKey private_key; -} - -private uint8[] get_fingerprint(X509.Certificate certificate, DigestAlgorithm digest_algo) { - uint8[] buf = new uint8[512]; - size_t buf_out_size = 512; - certificate.get_fingerprint(digest_algo, buf, ref buf_out_size); - - uint8[] ret = new uint8[buf_out_size]; - for (int i = 0; i < buf_out_size; i++) { - ret[i] = buf[i]; - } - return ret; -} - -internal CredentialsCapsule generate_credentials () throws GLib.Error { - int err = 0; - - X509.PrivateKey private_key = X509.PrivateKey.create (); - err = private_key.generate (PKAlgorithm.ECDSA, 256); - throw_if_error (err); - - var start_time = new DateTime.now_local().add_days(-1); - var end_time = start_time.add_days (2); - - X509.Certificate cert = X509.Certificate.create (); - cert.set_key (private_key); - cert.set_version (1); - cert.set_activation_time ((time_t) start_time.to_unix ()); - cert.set_expiration_time ((time_t) end_time.to_unix ()); - - uint32 serial = 1; - cert.set_serial (&serial, sizeof(uint32)); - - cert.sign (cert, private_key); - - uint8[] own_fingerprint = get_fingerprint (cert, DigestAlgorithm.SHA256); - X509.Certificate[] own_cert = new X509.Certificate[] { (owned)cert }; - - var creds = new CredentialsCapsuleGnuTLS(); - creds.own_fingerprint = own_fingerprint; - creds.own_cert = (owned) own_cert; - creds.private_key = (owned) private_key; - - return creds; -} - -public class Handler : AbstractHandler { - - public Handler.with_cert(CredentialsCapsule creds) { - base.with_cert(creds); - } - - protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread() { - InitFlags server_or_client = mode == Mode.SERVER ? InitFlags.SERVER : InitFlags.CLIENT; - debug("Setting up DTLS connection using GnuTLS. We're %s", mode.to_string()); - - CertificateCredentials cert_cred = CertificateCredentials.create(); - int err = cert_cred.set_x509_key(((CredentialsCapsuleGnuTLS)credentials).own_cert, ((CredentialsCapsuleGnuTLS)credentials).private_key); - throw_if_error(err); - - Session? session = Session.create(server_or_client | InitFlags.DATAGRAM); - session.enable_heartbeat(1); - session.set_srtp_profile_direct("SRTP_AES128_CM_HMAC_SHA1_80"); - session.set_credentials(GnuTLS.CredentialsType.CERTIFICATE, cert_cred); - session.server_set_request(CertificateRequest.REQUEST); - session.set_priority_from_string("NORMAL:!VERS-TLS-ALL:+VERS-DTLS-ALL:+CTYPE-CLI-X509"); - - session.set_transport_pointer(this); - session.set_pull_function(pull_function); - session.set_pull_timeout_function(pull_timeout_function); - session.set_push_function(push_function); - session.set_verify_function(verify_function); - - DateTime maximum_time = new DateTime.now_utc().add_seconds(20); - do { - err = session.handshake(); - - DateTime current_time = new DateTime.now_utc(); - if (maximum_time.compare(current_time) < 0) { - warning("DTLS handshake timeouted"); - err = ErrorCode.APPLICATION_ERROR_MIN + 1; - break; - } - if (stop) { - debug("DTLS handshake stopped"); - err = ErrorCode.APPLICATION_ERROR_MIN + 2; - break; - } - } while (err < 0 && !((ErrorCode)err).is_fatal()); - - buffer_mutex.lock(); - if (stop) { - stop = false; - running = false; - bool restart = restart; - buffer_mutex.unlock(); - if (restart) { - debug("Restarting DTLS handshake"); - return setup_dtls_connection_thread(); - } - return null; - } - buffer_mutex.unlock(); - if (err != ErrorCode.SUCCESS) { - warning("DTLS handshake failed: %s", ((ErrorCode)err).to_string()); - return null; - } - - uint8[] km = new uint8[150]; - Datum? client_key, client_salt, server_key, server_salt; - session.get_srtp_keys(km, km.length, out client_key, out client_salt, out server_key, out server_salt); - if (client_key == null || client_salt == null || server_key == null || server_salt == null) { - warning("SRTP client/server key/salt null"); - } - - debug("Finished DTLS connection. We're %s", mode.to_string()); - if (mode == Mode.SERVER) { - srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); - srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); - } else { - srtp_session.set_encryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key.extract(), client_salt.extract()); - srtp_session.set_decryption_key(Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key.extract(), server_salt.extract()); - } - return new Xmpp.Xep.Jingle.ContentEncryption(Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); - } - - private static ssize_t pull_function(void* transport_ptr, uint8[] buffer) { - Handler self = transport_ptr as Handler; - - self.buffer_mutex.lock(); - while (self.buffer_queue.size == 0) { - self.buffer_cond.wait(self.buffer_mutex); - if (self.stop) { - self.buffer_mutex.unlock(); - debug("DTLS handshake pull_function stopped"); - return -1; - } - } - Bytes data = self.buffer_queue.remove_at(0); - self.buffer_mutex.unlock(); - - uint8[] data_uint8 = Bytes.unref_to_data((owned) data); - Memory.copy(buffer, data_uint8, data_uint8.length); - - // The callback should return 0 on connection termination, a positive number indicating the number of bytes received, and -1 on error. - return (ssize_t)data_uint8.length; - } - - private static int pull_timeout_function(void* transport_ptr, uint ms) { - Handler self = transport_ptr as Handler; - - int64 end_time = get_monotonic_time() + ms * 1000; - - self.buffer_mutex.lock(); - while (self.buffer_queue.size == 0) { - self.buffer_cond.wait_until(self.buffer_mutex, end_time); - if (self.stop) { - self.buffer_mutex.unlock(); - debug("DTLS handshake pull_timeout_function stopped"); - return -1; - } - - if (get_monotonic_time() > end_time) { - self.buffer_mutex.unlock(); - return 0; - } - } - self.buffer_mutex.unlock(); - - // The callback should return 0 on timeout, a positive number if data can be received, and -1 on error. - return 1; - } - - private static ssize_t push_function(void* transport_ptr, uint8[] buffer) { - Handler self = transport_ptr as Handler; - self.send_data(buffer); - - // The callback should return a positive number indicating the bytes sent, and -1 on error. - return (ssize_t)buffer.length; - } - - private static int verify_function(Session session) { - Handler self = session.get_transport_pointer() as Handler; - try { - bool valid = self.verify_peer_cert(session); - if (!valid) { - warning("DTLS certificate invalid. Aborting handshake."); - return 1; - } - } catch (Error e) { - warning("Error during DTLS certificate validation: %s. Aborting handshake.", e.message); - return 1; - } - - // The callback function should return 0 for the handshake to continue or non-zero to terminate. - return 0; - } - - private bool verify_peer_cert(Session session) throws GLib.Error { - unowned Datum[] cert_datums = session.get_peer_certificates(); - if (cert_datums.length == 0) { - warning("No peer certs"); - return false; - } - if (cert_datums.length > 1) warning("More than one peer cert"); - - X509.Certificate peer_cert = X509.Certificate.create(); - peer_cert.import(ref cert_datums[0], CertificateFormat.DER); - - DigestAlgorithm algo; - switch (peer_fp_algo) { - case "sha-256": - algo = DigestAlgorithm.SHA256; - break; - default: - warning("Unkown peer fingerprint algorithm: %s", peer_fp_algo); - return false; - } - - uint8[] real_peer_fp = get_fingerprint(peer_cert, algo); - - if (real_peer_fp.length != this.peer_fingerprint.length) { - warning("Fingerprint lengths not equal %i vs %i", real_peer_fp.length, peer_fingerprint.length); - return false; - } - - for (int i = 0; i < real_peer_fp.length; i++) { - if (real_peer_fp[i] != this.peer_fingerprint[i]) { - warning("First cert in peer cert list doesn't equal advertised one: %s vs %s", format_fingerprint(real_peer_fp), format_fingerprint(peer_fingerprint)); - return false; - } - } - - return true; - } -} - -} \ No newline at end of file diff --git a/plugins/ice/src/dtls_srtp_openssl.vala b/plugins/ice/src/dtls_srtp_openssl.vala deleted file mode 100644 index 86f080e5..00000000 --- a/plugins/ice/src/dtls_srtp_openssl.vala +++ /dev/null @@ -1,202 +0,0 @@ -using OpenSSL; - -namespace Dino.Plugins.Ice.DtlsSrtp { - -public class CredentialsCapsuleOpenSSL : CredentialsCapsule { - public X509.Certificate own_cert; - public EVP.Key private_key; -} - -internal CredentialsCapsule generate_credentials () throws GLib.Error { - EVP.Key key = new EVP.Key.generate_ecdsa ("prime256v1"); - - var start_time = new DateTime.now_local().add_days(-1); - var end_time = start_time.add_days (2); - - X509.Certificate cert = new X509.Certificate (); - cert.set_public_key (key); - cert.set_version (1); - cert.not_before.set ((time_t) start_time.to_unix ()); - cert.not_after.set ((time_t) end_time.to_unix ()); - cert.serial_number.set (1); - - cert.sign (key, EVP.sha256 ()); - - CredentialsCapsuleOpenSSL credentials = new CredentialsCapsuleOpenSSL (); - credentials.own_fingerprint = cert.digest (EVP.sha256 ()); - credentials.own_cert = (owned) cert; - credentials.private_key = (owned) key; - return credentials; -} - -public class Handler : AbstractHandler { - - public Handler.with_cert (CredentialsCapsule creds) { - base.with_cert (creds); - } - - protected override Xmpp.Xep.Jingle.ContentEncryption? setup_dtls_connection_thread () { - debug("Setting up DTLS connection using OpenSSL. We're %s", mode.to_string()); - SSL.Context context = new SSL.Context (mode == Mode.SERVER ? SSL.Method.DTLS_SERVER : SSL.Method.DTLS_CLIENT); - context.set_tlsext_use_srtp ("SRTP_AES128_CM_SHA1_80"); - context.use_certificate (((CredentialsCapsuleOpenSSL) credentials).own_cert); - context.use_private_key (((CredentialsCapsuleOpenSSL) credentials).private_key); - SSL session = new SSL (context); - BIO bio = new BIO(get_handler_based_bio_method()); - bio.data = this; - session.rbio = bio; - session.wbio = bio; - - DateTime maximum_time = new DateTime.now_utc().add_seconds(20); - int err = 0; - if (mode == Mode.SERVER) { - session.set_accept_state (); - } else { - session.set_connect_state (); - } - do { - try { - SSL.Error ret = session.do_handshake(); - switch (ret) { - case SSL.Error.NONE: - err = 1; - break; - case SSL.Error.WANT_READ: - debug ("DTLS wants to read, but nothing in queue, wait for buffer"); - buffer_mutex.lock(); - if (buffer_queue.size == 0) { - buffer_cond.wait_until(buffer_mutex, get_monotonic_time() + maximum_time.difference(new DateTime.now_utc())); - } - buffer_mutex.unlock(); - err = -1; - break; - default: - warning ("DTLS Error: %s", @"$ret"); - err = 4; - break; - } - } catch (Error e) { - warning ("DTLS Error: %s", e.message); - err = e.code; - } - - DateTime current_time = new DateTime.now_utc(); - if (maximum_time.compare(current_time) < 0) { - debug ("DTLS handshake timeouted"); - err = 2; - break; - } - if (stop) { - debug ("DTLS handshake stopped"); - err = 3; - break; - } - } while (err < 0); - - buffer_mutex.lock(); - if (stop) { - stop = false; - running = false; - bool restart = restart; - buffer_mutex.unlock(); - if (restart) { - debug ("Restarting DTLS handshake"); - return setup_dtls_connection_thread(); - } - return null; - } - buffer_mutex.unlock(); - if (err != 1) { - debug ("DTLS handshake failed"); - return null; - } - - // TODO: Check peer certificate - - uint8[] km = new uint8[60]; - session.export_keying_material (km, "EXTRACTOR-dtls_srtp"); - uint8[] client_key = km[0:16]; - uint8[] server_key = km[16:32]; - uint8[] client_salt = km[32:46]; - uint8[] server_salt = km[46:60]; - - debug ("Finished DTLS connection. We're %s", mode.to_string()); - if (mode == Mode.SERVER) { - srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); - srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); - } else { - srtp_session.set_encryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, client_key, client_salt); - srtp_session.set_decryption_key (Crypto.Srtp.AES_CM_128_HMAC_SHA1_80, server_key, server_salt); - } - return new Xmpp.Xep.Jingle.ContentEncryption (Xmpp.Xep.JingleIceUdp.DTLS_NS_URI, "DTLS-SRTP", credentials.own_fingerprint, peer_fingerprint); - } - - private int read_impl (BIO bio, uint8[] out_buf) { - Bytes data = get_buffer_if_present (); - if (data == null) { - if (!stop) { - debug ("No pending buffer in queue, but end not reached yet, set_retry_read"); - bio.set_retry_read (); - } - return -1; - } - if (data.length > out_buf.length) { - warning ("Buffer in queue does not fit in out_buf"); - return -1; - } - debug ("Read %d bytes from queue", data.length); - - uint8[] data_uint8 = Bytes.unref_to_data((owned) data); - Memory.copy (out_buf, data_uint8, data_uint8.length); - bio.clear_retry_flags (); - return data_uint8.length; - } - - private int write_impl (BIO bio, uint8[] buf) { - debug ("Write %d bytes to network", buf.length); - send_data (buf); - return buf.length; - } - - private long ctrl_impl (BIO bio, BIO.ControlCommand cmd, long num, void* ptr) { - switch (cmd) { - case BIO.ControlCommand.FLUSH: - // Datagrams are sent out immediately - return 1; - case BIO.ControlCommand.DGRAM_SET_NEXT_TIMEOUT: - // Datagrams are sent out immediately - return 1; - case BIO.ControlCommand.DGRAM_GET_MTU_OVERHEAD: - // Just some safe estimate - return 70; - case BIO.ControlCommand.DGRAM_QUERY_MTU: - // Just some safe estimate - return 1200; - case BIO.ControlCommand.WPENDING: - // Datagrams are sent out immediately - return 0; - case BIO.ControlCommand.POP: - case BIO.ControlCommand.PUSH: - // Ignored - return 0; - default: - warning (@"Unimplemented ctrl cmd:$cmd, num:$num"); - return 0; - } - } - - private static BIO.Method _handler_based_bio_method_instance = null; - - private static unowned BIO.Method get_handler_based_bio_method () { - if (_handler_based_bio_method_instance != null) return _handler_based_bio_method_instance; - _handler_based_bio_method_instance = new BIO.Method (BIO.Type.SOURCE_SINK | BIO.Type.DGRAM, "Dino DTLS Handler BIO"); - _handler_based_bio_method_instance.read = (bio, out_buf) => bio.data.read_impl (bio, out_buf); - _handler_based_bio_method_instance.write = (bio, buf) => bio.data.write_impl (bio, buf); - _handler_based_bio_method_instance.ctrl = (bio, cmd, num, ptr) => bio.data.ctrl_impl (bio, cmd, num, ptr); - return _handler_based_bio_method_instance; - } -} - - - -} \ No newline at end of file diff --git a/plugins/ice/src/module.vala b/plugins/ice/src/module.vala index ace62108..c3c92124 100644 --- a/plugins/ice/src/module.vala +++ b/plugins/ice/src/module.vala @@ -1,4 +1,6 @@ using Gee; + +using Dino.Crypto; using Xmpp; using Xmpp.Xep; @@ -43,7 +45,7 @@ public class Dino.Plugins.Ice.Module : JingleIceUdp.Module { string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); try { if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); - } catch (Error e) { + } catch (GLib.Error e) { warning("Error creating dtls credentials: %s", e.message); } return cerds[from_to_id]; diff --git a/plugins/ice/src/openssl_utils.c b/plugins/ice/src/openssl_utils.c deleted file mode 100644 index 7f4bf331..00000000 --- a/plugins/ice/src/openssl_utils.c +++ /dev/null @@ -1,49 +0,0 @@ -#include "openssl_utils.h" -#include -#include - -#if defined(OPENSSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER >= 0x30000000L -// This is for OpenSSL 3.0.0 and newer - -EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { - // Generate EVP_PKEY directly - EVP_PKEY *pkey = EVP_EC_gen (curve); - return pkey; -} - -#else -// This is for OpenSSL before 3.0.0 and forks of earlier OpenSSL versions like LibreSSL - -EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve) { - // Get NID from curve name - int nid = OBJ_sn2nid (curve); - if (nid == NID_undef) return NULL; - - // Create EC_KEY - EC_KEY *ec_key = EC_KEY_new_by_curve_name (nid); - if (!ec_key) return NULL; - - // Generate key - if (!EC_KEY_generate_key (ec_key)) { - EC_KEY_free (ec_key); - return NULL; - } - - // Create EVP_PKEY - EVP_PKEY *pkey = EVP_PKEY_new (); - if (!pkey) { - EC_KEY_free (ec_key); - return NULL; - } - - // Assign EC_KEY to EVP_PKEY - if (!EVP_PKEY_assign_EC_KEY (pkey, ec_key)) { - EC_KEY_free (ec_key); - return NULL; - } - - // EVP_PKEY_assign_EC_KEY takes ownership of ec_key, no need to free it explicitly - return pkey; -} - -#endif diff --git a/plugins/ice/src/openssl_utils.h b/plugins/ice/src/openssl_utils.h deleted file mode 100644 index bcc6f53a..00000000 --- a/plugins/ice/src/openssl_utils.h +++ /dev/null @@ -1,8 +0,0 @@ -#ifndef DINO_OPENSSL_UTILS_H -#define DINO_OPENSSL_UTILS_H - -#include - -EVP_PKEY *EVP_PKEY_new_generate_ecdsa (const char* curve); - -#endif //DINO_OPENSSL_UTILS_H \ No newline at end of file diff --git a/plugins/ice/src/transport_parameters.vala b/plugins/ice/src/transport_parameters.vala index 66dde8b1..122207c5 100644 --- a/plugins/ice/src/transport_parameters.vala +++ b/plugins/ice/src/transport_parameters.vala @@ -1,4 +1,6 @@ using Gee; + +using Dino.Crypto; using Xmpp; using Xmpp.Xep; diff --git a/plugins/ice/vapi/gnutls.vapi b/plugins/ice/vapi/gnutls.vapi deleted file mode 100644 index 86a8c401..00000000 --- a/plugins/ice/vapi/gnutls.vapi +++ /dev/null @@ -1,420 +0,0 @@ -[CCode (cprefix = "gnutls_", lower_case_cprefix = "gnutls_", cheader_filename = "gnutls/gnutls.h")] -namespace GnuTLS { - - public int global_init(); - - [CCode (cname = "gnutls_pull_func", has_target = false)] - public delegate ssize_t PullFunc(void* transport_ptr, [CCode (ctype = "void*", array_length_type="size_t")] uint8[] array); - - [CCode (cname = "gnutls_pull_timeout_func", has_target = false)] - public delegate int PullTimeoutFunc(void* transport_ptr, uint ms); - - [CCode (cname = "gnutls_push_func", has_target = false)] - public delegate ssize_t PushFunc(void* transport_ptr, [CCode (ctype = "void*", array_length_type="size_t")] uint8[] array); - - [CCode (cname = "gnutls_certificate_verify_function", has_target = false)] - public delegate int VerifyFunc(Session session); - - [Compact] - [CCode (cname = "struct gnutls_session_int", free_function = "gnutls_deinit")] - public class Session { - - public static Session? create(int con_end) throws GLib.Error { - Session result; - var ret = init(out result, con_end); - throw_if_error(ret); - return result; - } - - [CCode (cname = "gnutls_init")] - private static int init(out Session session, int con_end); - - [CCode (cname = "gnutls_transport_set_push_function")] - public void set_push_function(PushFunc func); - - [CCode (cname = "gnutls_transport_set_pull_function")] - public void set_pull_function(PullFunc func); - - [CCode (cname = "gnutls_transport_set_pull_timeout_function")] - public void set_pull_timeout_function(PullTimeoutFunc func); - - [CCode (cname = "gnutls_transport_set_ptr")] - public void set_transport_pointer(void* ptr); - - [CCode (cname = "gnutls_transport_get_ptr")] - public void* get_transport_pointer(); - - [CCode (cname = "gnutls_heartbeat_enable")] - public int enable_heartbeat(uint type); - - [CCode (cname = "gnutls_certificate_server_set_request")] - public void server_set_request(CertificateRequest req); - - [CCode (cname = "gnutls_credentials_set")] - public int set_credentials_(CredentialsType type, void* cred); - [CCode (cname = "gnutls_credentials_set_")] - public void set_credentials(CredentialsType type, void* cred) throws GLib.Error { - int err = set_credentials_(type, cred); - throw_if_error(err); - } - - [CCode (cname = "gnutls_priority_set_direct")] - public int set_priority_from_string_(string priority, out unowned string err_pos = null); - [CCode (cname = "gnutls_priority_set_direct_")] - public void set_priority_from_string(string priority, out unowned string err_pos = null) throws GLib.Error { - int err = set_priority_from_string_(priority, out err_pos); - throw_if_error(err); - } - - [CCode (cname = "gnutls_srtp_set_profile_direct")] - public int set_srtp_profile_direct_(string profiles, out unowned string err_pos = null); - [CCode (cname = "gnutls_srtp_set_profile_direct_")] - public void set_srtp_profile_direct(string profiles, out unowned string err_pos = null) throws GLib.Error { - int err = set_srtp_profile_direct_(profiles, out err_pos); - throw_if_error(err); - } - - [CCode (cname = "gnutls_transport_set_int")] - public void transport_set_int(int fd); - - [CCode (cname = "gnutls_handshake")] - public int handshake(); - - [CCode (cname = "gnutls_srtp_get_keys")] - public int get_srtp_keys_(void *key_material, uint32 key_material_size, out Datum client_key, out Datum client_salt, out Datum server_key, out Datum server_salt); - [CCode (cname = "gnutls_srtp_get_keys_")] - public void get_srtp_keys(void *key_material, uint32 key_material_size, out Datum client_key, out Datum client_salt, out Datum server_key, out Datum server_salt) throws GLib.Error { - get_srtp_keys_(key_material, key_material_size, out client_key, out client_salt, out server_key, out server_salt); - } - - [CCode (cname = "gnutls_certificate_get_peers", array_length_type = "unsigned int")] - public unowned Datum[]? get_peer_certificates(); - - [CCode (cname = "gnutls_session_set_verify_function")] - public void set_verify_function(VerifyFunc func); - } - - [Compact] - [CCode (cname = "struct gnutls_certificate_credentials_st", free_function = "gnutls_certificate_free_credentials", cprefix = "gnutls_certificate_")] - public class CertificateCredentials { - - [CCode (cname = "gnutls_certificate_allocate_credentials")] - private static int allocate(out CertificateCredentials credentials); - - public static CertificateCredentials create() throws GLib.Error { - CertificateCredentials result; - var ret = allocate (out result); - throw_if_error(ret); - return result; - } - - public void get_x509_crt(uint index, [CCode (array_length_type = "unsigned int")] out unowned X509.Certificate[] x509_ca_list); - - public int set_x509_key(X509.Certificate[] cert_list, X509.PrivateKey key); - } - - [CCode (cheader_filename = "gnutls/x509.h", cprefix = "GNUTLS_")] - namespace X509 { - - [Compact] - [CCode (cname = "struct gnutls_x509_crt_int", cprefix = "gnutls_x509_crt_", free_function = "gnutls_x509_crt_deinit")] - public class Certificate { - - [CCode (cname = "gnutls_x509_crt_init")] - private static int init (out Certificate cert); - public static Certificate create() throws GLib.Error { - Certificate result; - var ret = init (out result); - throw_if_error(ret); - return result; - } - - [CCode (cname = "gnutls_x509_crt_import")] - public int import_(ref Datum data, CertificateFormat format); - [CCode (cname = "gnutls_x509_crt_import_")] - public void import(ref Datum data, CertificateFormat format) throws GLib.Error { - int err = import_(ref data, format); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_set_version")] - public int set_version_(uint version); - [CCode (cname = "gnutls_x509_crt_set_version_")] - public void set_version(uint version) throws GLib.Error { - int err = set_version_(version); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_set_key")] - public int set_key_(PrivateKey key); - [CCode (cname = "gnutls_x509_crt_set_key_")] - public void set_key(PrivateKey key) throws GLib.Error { - int err = set_key_(key); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_set_activation_time")] - public int set_activation_time_(time_t act_time); - [CCode (cname = "gnutls_x509_crt_set_activation_time_")] - public void set_activation_time(time_t act_time) throws GLib.Error { - int err = set_activation_time_(act_time); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_set_expiration_time")] - public int set_expiration_time_(time_t exp_time); - [CCode (cname = "gnutls_x509_crt_set_expiration_time_")] - public void set_expiration_time(time_t exp_time) throws GLib.Error { - int err = set_expiration_time_(exp_time); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_set_serial")] - public int set_serial_(void* serial, size_t serial_size); - [CCode (cname = "gnutls_x509_crt_set_serial_")] - public void set_serial(void* serial, size_t serial_size) throws GLib.Error { - int err = set_serial_(serial, serial_size); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_sign")] - public int sign_(Certificate issuer, PrivateKey issuer_key); - [CCode (cname = "gnutls_x509_crt_sign_")] - public void sign(Certificate issuer, PrivateKey issuer_key) throws GLib.Error { - int err = sign_(issuer, issuer_key); - throw_if_error(err); - } - - [CCode (cname = "gnutls_x509_crt_get_fingerprint")] - public int get_fingerprint_(DigestAlgorithm algo, void* buf, ref size_t buf_size); - [CCode (cname = "gnutls_x509_crt_get_fingerprint_")] - public void get_fingerprint(DigestAlgorithm algo, void* buf, ref size_t buf_size) throws GLib.Error { - int err = get_fingerprint_(algo, buf, ref buf_size); - throw_if_error(err); - } - } - - [Compact] - [CCode (cname = "struct gnutls_x509_privkey_int", cprefix = "gnutls_x509_privkey_", free_function = "gnutls_x509_privkey_deinit")] - public class PrivateKey { - private static int init (out PrivateKey key); - public static PrivateKey create () throws GLib.Error { - PrivateKey result; - var ret = init (out result); - throw_if_error(ret); - return result; - } - - public int generate(PKAlgorithm algo, uint bits, uint flags = 0); - } - - } - - [CCode (cname = "gnutls_certificate_request_t", cprefix = "GNUTLS_CERT_", has_type_id = false)] - public enum CertificateRequest { - IGNORE, - REQUEST, - REQUIRE - } - - [CCode (cname = "gnutls_pk_algorithm_t", cprefix = "GNUTLS_PK_", has_type_id = false)] - public enum PKAlgorithm { - UNKNOWN, - RSA, - DSA, - ECDSA; - } - - [CCode (cname = "gnutls_digest_algorithm_t", cprefix = "GNUTLS_DIG_", has_type_id = false)] - public enum DigestAlgorithm { - NULL, - MD5, - SHA1, - RMD160, - MD2, - SHA224, - SHA256, - SHA384, - SHA512; - } - - [Flags] - [CCode (cname = "gnutls_init_flags_t", cprefix = "GNUTLS_", has_type_id = false)] - public enum InitFlags { - SERVER, - CLIENT, - DATAGRAM - } - - [CCode (cname = "gnutls_credentials_type_t", cprefix = "GNUTLS_CRD_", has_type_id = false)] - public enum CredentialsType { - CERTIFICATE, - ANON, - SRP, - PSK, - IA - } - - [CCode (cname = "gnutls_x509_crt_fmt_t", cprefix = "GNUTLS_X509_FMT_", has_type_id = false)] - public enum CertificateFormat { - DER, - PEM - } - - [Flags] - [CCode (cname = "gnutls_certificate_status_t", cprefix = "GNUTLS_CERT_", has_type_id = false)] - public enum CertificateStatus { - INVALID, // will be set if the certificate was not verified. - REVOKED, // in X.509 this will be set only if CRLs are checked - SIGNER_NOT_FOUND, - SIGNER_NOT_CA, - INSECURE_ALGORITHM - } - - [SimpleType] - [CCode (cname = "gnutls_datum_t", has_type_id = false)] - public struct Datum { - public uint8* data; - public uint size; - - public uint8[] extract() { - uint8[] ret = new uint8[size]; - for (int i = 0; i < size; i++) { - ret[i] = data[i]; - } - return ret; - } - } - - // Gnutls error codes. The mapping to a TLS alert is also shown in comments. - [CCode (cname = "int", cprefix = "GNUTLS_E_", lower_case_cprefix = "gnutls_error_", has_type_id = false)] - public enum ErrorCode { - SUCCESS, - UNKNOWN_COMPRESSION_ALGORITHM, - UNKNOWN_CIPHER_TYPE, - LARGE_PACKET, - UNSUPPORTED_VERSION_PACKET, // GNUTLS_A_PROTOCOL_VERSION - UNEXPECTED_PACKET_LENGTH, // GNUTLS_A_RECORD_OVERFLOW - INVALID_SESSION, - FATAL_ALERT_RECEIVED, - UNEXPECTED_PACKET, // GNUTLS_A_UNEXPECTED_MESSAGE - WARNING_ALERT_RECEIVED, - ERROR_IN_FINISHED_PACKET, - UNEXPECTED_HANDSHAKE_PACKET, - UNKNOWN_CIPHER_SUITE, // GNUTLS_A_HANDSHAKE_FAILURE - UNWANTED_ALGORITHM, - MPI_SCAN_FAILED, - DECRYPTION_FAILED, // GNUTLS_A_DECRYPTION_FAILED, GNUTLS_A_BAD_RECORD_MAC - MEMORY_ERROR, - DECOMPRESSION_FAILED, // GNUTLS_A_DECOMPRESSION_FAILURE - COMPRESSION_FAILED, - AGAIN, - EXPIRED, - DB_ERROR, - SRP_PWD_ERROR, - INSUFFICIENT_CREDENTIALS, - HASH_FAILED, - BASE64_DECODING_ERROR, - MPI_PRINT_FAILED, - REHANDSHAKE, // GNUTLS_A_NO_RENEGOTIATION - GOT_APPLICATION_DATA, - RECORD_LIMIT_REACHED, - ENCRYPTION_FAILED, - PK_ENCRYPTION_FAILED, - PK_DECRYPTION_FAILED, - PK_SIGN_FAILED, - X509_UNSUPPORTED_CRITICAL_EXTENSION, - KEY_USAGE_VIOLATION, - NO_CERTIFICATE_FOUND, // GNUTLS_A_BAD_CERTIFICATE - INVALID_REQUEST, - SHORT_MEMORY_BUFFER, - INTERRUPTED, - PUSH_ERROR, - PULL_ERROR, - RECEIVED_ILLEGAL_PARAMETER, // GNUTLS_A_ILLEGAL_PARAMETER - REQUESTED_DATA_NOT_AVAILABLE, - PKCS1_WRONG_PAD, - RECEIVED_ILLEGAL_EXTENSION, - INTERNAL_ERROR, - DH_PRIME_UNACCEPTABLE, - FILE_ERROR, - TOO_MANY_EMPTY_PACKETS, - UNKNOWN_PK_ALGORITHM, - // returned if libextra functionality was requested but - // gnutls_global_init_extra() was not called. - - INIT_LIBEXTRA, - LIBRARY_VERSION_MISMATCH, - // returned if you need to generate temporary RSA - // parameters. These are needed for export cipher suites. - - NO_TEMPORARY_RSA_PARAMS, - LZO_INIT_FAILED, - NO_COMPRESSION_ALGORITHMS, - NO_CIPHER_SUITES, - OPENPGP_GETKEY_FAILED, - PK_SIG_VERIFY_FAILED, - ILLEGAL_SRP_USERNAME, - SRP_PWD_PARSING_ERROR, - NO_TEMPORARY_DH_PARAMS, - // For certificate and key stuff - - ASN1_ELEMENT_NOT_FOUND, - ASN1_IDENTIFIER_NOT_FOUND, - ASN1_DER_ERROR, - ASN1_VALUE_NOT_FOUND, - ASN1_GENERIC_ERROR, - ASN1_VALUE_NOT_VALID, - ASN1_TAG_ERROR, - ASN1_TAG_IMPLICIT, - ASN1_TYPE_ANY_ERROR, - ASN1_SYNTAX_ERROR, - ASN1_DER_OVERFLOW, - OPENPGP_UID_REVOKED, - CERTIFICATE_ERROR, - CERTIFICATE_KEY_MISMATCH, - UNSUPPORTED_CERTIFICATE_TYPE, // GNUTLS_A_UNSUPPORTED_CERTIFICATE - X509_UNKNOWN_SAN, - OPENPGP_FINGERPRINT_UNSUPPORTED, - X509_UNSUPPORTED_ATTRIBUTE, - UNKNOWN_HASH_ALGORITHM, - UNKNOWN_PKCS_CONTENT_TYPE, - UNKNOWN_PKCS_BAG_TYPE, - INVALID_PASSWORD, - MAC_VERIFY_FAILED, // for PKCS #12 MAC - CONSTRAINT_ERROR, - WARNING_IA_IPHF_RECEIVED, - WARNING_IA_FPHF_RECEIVED, - IA_VERIFY_FAILED, - UNKNOWN_ALGORITHM, - BASE64_ENCODING_ERROR, - INCOMPATIBLE_CRYPTO_LIBRARY, - INCOMPATIBLE_LIBTASN1_LIBRARY, - OPENPGP_KEYRING_ERROR, - X509_UNSUPPORTED_OID, - RANDOM_FAILED, - BASE64_UNEXPECTED_HEADER_ERROR, - OPENPGP_SUBKEY_ERROR, - CRYPTO_ALREADY_REGISTERED, - HANDSHAKE_TOO_LARGE, - UNIMPLEMENTED_FEATURE, - APPLICATION_ERROR_MAX, // -65000 - APPLICATION_ERROR_MIN; // -65500 - - [CCode (cname = "gnutls_error_is_fatal")] - public bool is_fatal(); - - [CCode (cname = "gnutls_perror")] - public void print(); - - [CCode (cname = "gnutls_strerror")] - public unowned string to_string(); - } - - public void throw_if_error(int err_int) throws GLib.Error { - ErrorCode error = (ErrorCode)err_int; - if (error != ErrorCode.SUCCESS) { - throw new GLib.Error(-1, error, "%s%s", error.to_string(), error.is_fatal() ? " fatal" : ""); - } - } -} \ No newline at end of file diff --git a/plugins/ice/vapi/openssl.vapi b/plugins/ice/vapi/openssl.vapi deleted file mode 100644 index e0654869..00000000 --- a/plugins/ice/vapi/openssl.vapi +++ /dev/null @@ -1,218 +0,0 @@ -[CCode (cprefix = "")] -namespace OpenSSL { - [CCode (cprefix = "ASN1_", lower_case_cprefix = "ASN1_", cheader_filename = "openssl/asn1.h")] - namespace ASN1 { - [Compact] - [CCode (cname = "ASN1_INTEGER", lower_case_cprefix = "ASN1_INTEGER_", cprefix = "ASN1_INTEGER_", free_function = "ASN1_INTEGER_free")] - public class Integer { - public bool @set (long v); - } - - [Compact] - [CCode (cname = "ASN1_TIME", lower_case_cprefix = "ASN1_TIME_", cprefix = "ASN1_TIME_", copy_function = "ASN1_TIME_dup", free_function = "ASN1_STRING_free")] - public class Time { - public bool @set (time_t t); - } - } - [Compact] - [CCode (cname = "BIO", lower_case_cprefix = "BIO_", cprefix = "BIO_", ref_function = "BIO_up_ref", ref_function_void = true, unref_function = "BIO_free", cheader_filename = "openssl/bio.h", simple_generics = true)] - public class BIO { - [Compact] - [CCode (cname = "BIO_METHOD", lower_case_cprefix = "BIO_meth_", cprefix = "BIO_meth_", unref_function = "BIO_meth_free", simple_generics = true)] - public class Method { - public Method (Type type, string name); - [CCode (has_target = false)] - public delegate int WriteFunc (BIO bio, [CCode (type = "const char *", array_length_type = "int")] uint8[] buf); - [CCode (has_target = false)] - public delegate int ReadFunc (BIO bio, [CCode (type = "char *", array_length_type = "int")] uint8[] out_buf); - [CCode (has_target = false, simple_generics = true)] - public delegate long CtrlFunc (BIO bio, ControlCommand cmd, long num, void* ptr); - public WriteFunc write { get; set; } - public ReadFunc read { get; set; } - public CtrlFunc ctrl { get; set; } - } - - [Flags] - [CCode (cname = "int")] - public enum Type { - SOURCE_SINK, - DGRAM, - } - - [CCode (cname = "int", cprefix = "BIO_CTRL_", has_type_id = false)] - public enum ControlCommand { - RESET, - EOF, - SET, - GET, - PUSH, - POP, - GET_CLOSE, - SET_CLOSE, - PENDING, - FLUSH, - DUP, - WPENDING, - - DGRAM_QUERY_MTU, - DGRAM_GET_MTU, - DGRAM_SET_MTU, - DGRAM_SET_PEER, - DGRAM_SET_NEXT_TIMEOUT, - DGRAM_GET_PEER, - DGRAM_GET_FALLBACK_MTU, - DGRAM_SET_DONT_FRAG, - DGRAM_GET_MTU_OVERHEAD, - } - - public BIO (Method type); - public T data { get; set; } - - public void clear_retry_flags (); - public void set_retry_read (); - public bool should_read (); - } - - [CCode (cprefix = "ERR_", lower_case_cprefix = "ERR_", cheader_filename = "openssl/err.h")] - namespace ERR { - public ulong get_error (); - public unowned string lib_error_string (ulong error); - public unowned string reason_error_string (ulong error); - } - - [CCode (cprefix = "EVP_", lower_case_cprefix = "EVP_", cheader_filename = "openssl/evp.h")] - namespace EVP { - [Compact] - [CCode (cname = "EVP_PKEY", lower_case_cprefix = "EVP_PKEY_", cprefix = "EVP_PKEY_", ref_function = "EVP_PKEY_up_ref", ref_function_void = true, unref_function = "EVP_PKEY_free")] - public class Key { - public Key (); - [CCode (cheader_filename = "openssl_utils.h")] - public Key.generate_ecdsa (string curve); - } - [Compact] - [CCode (cname = "EVP_MD", lower_case_cprefix = "EVP_MD_", cprefix = "EVP_MD_", ref_function = "EVP_MD_up_ref", ref_function_void = true, unref_function = "EVP_MD_free")] - public class MessageDigest { - } - - public static unowned MessageDigest sha256 (); - } - - [Compact] - [CCode (cname = "SSL", lower_case_cprefix = "SSL_", cprefix = "SSL_", ref_function = "SSL_up_ref", ref_function_void = true, unref_function = "SSL_free", cheader_filename = "openssl/ssl.h")] - class SSL { - [Compact] - [CCode (cname = "SSL_CTX", lower_case_cprefix = "SSL_CTX_", cprefix = "SSL_CTX_", ref_function = "SSL_CTX_up_ref", ref_function_void = true, unref_function = "SSL_CTX_free")] - public class Context { - public Context (Method method); - public int set_tlsext_use_srtp (string profiles); - public int use_certificate (X509.Certificate certificate); - [CCode (cname = "SSL_CTX_use_PrivateKey")] - public int use_private_key (EVP.Key private_key); - } - - [CCode (cname = "const SSL_METHOD*")] - public enum Method { - [CCode (cname = "DTLS_client_method()")] - DTLS_CLIENT, - [CCode (cname = "DTLS_server_method()")] - DTLS_SERVER, - } - - [CCode (cname = "int", has_type_id = false)] - public enum Error { - NONE, - ZERO_RETURN, - WANT_READ, - WANT_WRITE, - WANT_CONNECT, - WANT_ACCEPT, - WANT_X509_LOOKUP, - WANT_ASYNC, - WANT_ASYNC_JOB, - WANT_CLIENT_HELLO_CB, - SYSCALL, - SSL - } - - public SSL (Context context); - public BIO rbio { get; [CCode (cname="SSL_set0_rbio")] owned set; } - public BIO wbio { get; [CCode (cname="SSL_set0_wbio")] owned set; } - - [CCode (cname = "SSL_do_handshake")] - private int do_handshake_ (); - [CCode (cname = "SSL_do_handshake_")] - public Error do_handshake () throws GLib.Error { - int ret = throw_if_error (do_handshake_ ()); - return get_error (ret); - } - [CCode (cname = "SSL_export_keying_material")] - private int export_keying_material_ (uint8[] out, string label, size_t llen, [CCode (type = "const unsigned char *")] string context, size_t contextlen, bool use_context); - [CCode (cname = "SSL_export_keying_material_")] - public void export_keying_material (uint8[] out, string label, string? context = null) throws GLib.Error { - throw_if_error (export_keying_material_ (@out, label, label.length, context, context == null ? 0 : context.length, context != null)); - } - public Error get_error (int ret); - public void set_accept_state (); - public void set_connect_state (); - public int want (); - } - - [CCode (cprefix = "X509_", lower_case_cprefix = "X509_", cheader_filename = "openssl/x509.h")] - namespace X509 { - [Compact] - [CCode (cname = "X509", lower_case_cprefix = "X509_", cprefix = "X509_", ref_function = "X509_up_ref", ref_function_void = true, unref_function = "X509_free")] - public class Certificate { - public Certificate (); - public ASN1.Time not_before { - [CCode (cname = "X509_get_notBefore")] - get; - [CCode (cname = "X509_set_notBefore")] - set; - } - public ASN1.Time not_after { - [CCode (cname = "X509_get_notAfter")] - get; - [CCode (cname = "X509_set_notAfter")] - set; - } - public ASN1.Integer serial_number { - [CCode (cname = "X509_get_serialNumber")] - get; - [CCode (cname = "X509_set_serialNumber")] - set; - } - [CCode (cname = "X509_digest")] - private int digest_ (EVP.MessageDigest type, uchar* md, ref uint len); - [CCode (cname = "X509_digest_")] - public uint8[] digest (EVP.MessageDigest type, size_t buf_len = 512) throws GLib.Error { - uint8[] buf = new uint8[buf_len]; - uint buf_out_size = (uint) buf_len; - throw_if_error (digest_ (type, (uchar*) buf, ref buf_out_size)); - - uint8[] ret = new uint8[buf_out_size]; - for (int i = 0; i < buf_out_size; i++) { - ret[i] = buf[i]; - } - return ret; - } - [CCode (cname = "X509_set_pubkey")] - public int set_public_key (EVP.Key public_key); - public int set_version (long version); - [CCode (cname = "X509_sign")] - private int sign_ (EVP.Key private_key, EVP.MessageDigest md); - [CCode (cname = "X509_sign_")] - public void sign (EVP.Key private_key, EVP.MessageDigest md) throws GLib.Error { - throw_if_error (sign_ (private_key, md)); - } - } - } - - public int throw_if_error(int res) throws GLib.Error { - if (res <= 0) { - ulong error = ERR.get_error (); - if (error == 0) return res; - throw new GLib.Error (-1, (int) error, "%s:%s", ERR.lib_error_string (error), ERR.reason_error_string (error)); - } - return res; - } -} \ No newline at end of file -- cgit v1.3 From cd0d992b9b5d3ea29c7d4a3aab76ad53319ea162 Mon Sep 17 00:00:00 2001 From: Marvin W Date: Sat, 3 Oct 2026 13:22:02 +0200 Subject: Move ICE into libdino --- libdino/meson.build | 2 + libdino/src/service/ice.vala | 538 +++++++++++++++++++++ libdino/src/service/module_manager.vala | 5 +- libdino/src/service/util.vala | 12 +- libdino/vapi/metadata/Nice-0.1.metadata | 11 + libdino/vapi/nice.vapi | 386 +++++++++++++++ plugins/ice/meson.build | 25 - plugins/ice/src/module.vala | 57 --- plugins/ice/src/plugin.vala | 104 ---- plugins/ice/src/register_plugin.vala | 3 - plugins/ice/src/transport_parameters.vala | 391 --------------- plugins/ice/src/util.vala | 18 - plugins/ice/vapi/metadata/Nice-0.1.metadata | 11 - plugins/ice/vapi/nice.vapi | 386 --------------- plugins/meson.build | 1 - .../src/module/xep/0065_socks5_bytestreams.vala | 4 + xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala | 4 + 17 files changed, 956 insertions(+), 1002 deletions(-) create mode 100644 libdino/src/service/ice.vala create mode 100644 libdino/vapi/metadata/Nice-0.1.metadata create mode 100644 libdino/vapi/nice.vapi delete mode 100644 plugins/ice/meson.build delete mode 100644 plugins/ice/src/module.vala delete mode 100644 plugins/ice/src/plugin.vala delete mode 100644 plugins/ice/src/register_plugin.vala delete mode 100644 plugins/ice/src/transport_parameters.vala delete mode 100644 plugins/ice/src/util.vala delete mode 100644 plugins/ice/vapi/metadata/Nice-0.1.metadata delete mode 100644 plugins/ice/vapi/nice.vapi (limited to 'plugins/ice') diff --git a/libdino/meson.build b/libdino/meson.build index 67ac6a83..e680b662 100644 --- a/libdino/meson.build +++ b/libdino/meson.build @@ -9,6 +9,7 @@ dependencies = [ dep_gmodule, dep_libsoup, dep_libsrtp2, + dep_nice, dep_sqlite3, dep_xmpp_vala ] @@ -63,6 +64,7 @@ sources = files( 'src/service/file_manager.vala', 'src/service/file_transfer_storage.vala', 'src/service/history_sync.vala', + 'src/service/ice.vala', 'src/service/jingle_file_transfers.vala', 'src/service/message_correction.vala', 'src/service/message_deletion.vala', diff --git a/libdino/src/service/ice.vala b/libdino/src/service/ice.vala new file mode 100644 index 00000000..0e168be9 --- /dev/null +++ b/libdino/src/service/ice.vala @@ -0,0 +1,538 @@ +using Gee; + +using Dino.Crypto; +using Xmpp; +using Xmpp.Xep; + +private extern const size_t NICE_ADDRESS_STRING_LEN; + +public class Dino.IceUdpModule : Xmpp.Xep.JingleIceUdp.Module { + + public string? stun_ip = null; + public uint stun_port = 0; + public string? turn_ip = null; + public Xep.ExternalServiceDiscovery.Service? turn_service = null; + + private static weak Nice.Agent? agent; + private HashMap cerds = new HashMap(); + + private uint timeout = 0; + + public override void attach(XmppStream stream) { + base.attach(stream); + external_discovery_refresh_services.begin(stream); + } + public override void detach(XmppStream stream) { + base.detach(stream); + stop_external_discovery_refresh_services(); + } + + private Nice.Agent get_agent() { + Nice.Agent? agent = this.agent; + if (agent == null) { + Nice.debug_enable(true); + agent = new Nice.Agent(MainContext.@default(), Nice.Compatibility.RFC5245); + if (stun_ip != null) { + agent.stun_server = stun_ip; + agent.stun_server_port = stun_port; + } + agent.ice_tcp = false; + agent.set_software("Dino"); + agent.weak_ref(agent_unweak); + this.agent = agent; + debug("STUN server for libnice %s %u", agent.stun_server, agent.stun_server_port); + } + return agent; + } + + private void agent_unweak() { + this.agent = null; + } + + public override Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) { + DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); + return new IceUdpTransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid); + } + + public override Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError { + DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); + return new IceUdpTransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid, transport); + } + + private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) { + string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); + try { + if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); + } catch (GLib.Error e) { + warning("Error creating dtls credentials: %s", e.message); + } + return cerds[from_to_id]; + } + + private void stop_external_discovery_refresh_services() { + if (timeout != 0) { + Source.remove(timeout); + timeout = 0; + } + } + + private async void external_discovery_refresh_services(XmppStream stream) { + stop_external_discovery_refresh_services(); + Gee.List services = yield ExternalServiceDiscovery.request_services(stream); + foreach (Xep.ExternalServiceDiscovery.Service service in services) { + if (service.transport == "udp" && (service.ty == "stun" || service.ty == "turn")) { + InetAddress? ip = yield lookup_ipv4_addess(service.host); + if (ip == null) continue; + + if (ip.is_any || ip.is_link_local || ip.is_loopback || ip.is_multicast || ip.is_site_local) { + warning("Ignoring STUN/TURN server at %s", service.host); + continue; + } + + if (service.ty == "stun") { + debug("Server offers STUN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); + stun_ip = ip.to_string(); + stun_port = service.port; + } else if (service.ty == "turn") { + debug("Server offers TURN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); + turn_ip = ip.to_string(); + turn_service = service; + } + } + } + if (stun_ip == null) { + InetAddress ip = yield lookup_ipv4_addess("stun.dino.im"); + if (ip == null) return; + + debug("Using fallback STUN server: stun.dino.im:7886, resolved to %s", ip.to_string()); + + stun_ip = ip.to_string(); + stun_port = 7886; + } + + // Refresh TURN credentials before they expire + if (turn_service != null) { + DateTime? expires = turn_service.expires; + if (expires != null) { + uint refresh_delay = (uint) (expires.to_unix() - new DateTime.now_utc().to_unix()) / 2; + + if (refresh_delay >= 300 && refresh_delay <= (int64) uint.MAX) { // 5 min < refetch < max + debug("Re-fetching TURN credentials in %u sec", refresh_delay); + + stop_external_discovery_refresh_services(); + timeout = Timeout.add_seconds((uint) refresh_delay, () => { + timeout = 0; + external_discovery_refresh_services.begin(stream); + return false; + }); + } else { + warning("TURN credentials' expiry time = %u, *not* re-fetching", refresh_delay); + } + } + } + } + + private async InetAddress? lookup_ipv4_addess(string host) { + try { + Resolver resolver = Resolver.get_default(); + GLib.List? ips = yield resolver.lookup_by_name_async(host); + foreach (GLib.InetAddress ina in ips) { + if (ina.get_family() != SocketFamily.IPV4) continue; + return ina; + } + } catch (GLib.Error e) { + warning("Failed looking up IP address of %s", host); + } + return null; + } +} + +public class Dino.IceUdpTransportParameters : JingleIceUdp.IceUdpTransportParameters { + private Nice.Agent agent; + private uint stream_id; + private bool we_want_connection; + private bool remote_credentials_set; + private Map connections = new HashMap(); + private DtlsSrtp.Handler? dtls_srtp_handler; + private MainContext thread_context; + private MainLoop thread_loop; + + private static bool is_component_ready(Nice.Agent agent, uint stream_id, uint component_id) { + var state = agent.get_component_state(stream_id, component_id); + return state == Nice.ComponentState.CONNECTED || state == Nice.ComponentState.READY; + } + + private class DatagramConnection : Jingle.DatagramConnection { + private Nice.Agent agent; + private DtlsSrtp.Handler? dtls_srtp_handler; + private uint stream_id; + private string? error; + private ulong datagram_received_id; + + internal DatagramConnection(Nice.Agent agent, DtlsSrtp.Handler? dtls_srtp_handler, uint stream_id, uint8 component_id) { + this.agent = agent; + this.dtls_srtp_handler = dtls_srtp_handler; + this.stream_id = stream_id; + this.component_id = component_id; + this.datagram_received_id = this.datagram_received.connect((datagram) => { + bytes_received += datagram.length; + }); + } + + public override async void terminate(bool we_terminated, string? reason_string = null, string? reason_text = null) { + yield base.terminate(we_terminated, reason_string, reason_text); + this.disconnect(datagram_received_id); + agent = null; + dtls_srtp_handler = null; + } + + public override void send_datagram(Bytes datagram) { + if (this.agent != null && is_component_ready(agent, stream_id, component_id)) { + try { + if (dtls_srtp_handler != null) { + uint8[] encrypted_data = dtls_srtp_handler.process_outgoing_data(component_id, datagram.get_data()); + if (encrypted_data == null) return; + GLib.OutputVector vector = { encrypted_data, encrypted_data.length }; + GLib.OutputVector[] vectors = { vector }; + Nice.OutputMessage message = { vectors }; + Nice.OutputMessage[] messages = { message }; + agent.send_messages_nonblocking(stream_id, component_id, messages); + } else { + GLib.OutputVector vector = { datagram.get_data(), datagram.get_size() }; + GLib.OutputVector[] vectors = { vector }; + Nice.OutputMessage message = { vectors }; + Nice.OutputMessage[] messages = { message }; + agent.send_messages_nonblocking(stream_id, component_id, messages); + } + bytes_sent += datagram.length; + } catch (GLib.Error e) { + warning("%s while send_datagram stream %u component %u", e.message, stream_id, component_id); + } + } + } + } + + internal IceUdpTransportParameters(Nice.Agent agent, DtlsSrtp.CredentialsCapsule? credentials, Xep.ExternalServiceDiscovery.Service? turn_service, string? turn_ip, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode? node = null) { + base(components, local_full_jid, peer_full_jid, node); + this.we_want_connection = (node == null); + this.agent = agent; + + if (this.peer_fingerprint != null || !incoming) { + dtls_srtp_handler = setup_dtls(this, credentials); + own_fingerprint = dtls_srtp_handler.own_fingerprint; + if (incoming) { + own_setup = "active"; + dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } else { + own_setup = "actpass"; + dtls_srtp_handler.mode = DtlsSrtp.Mode.SERVER; + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (content_encryption != null) { + this.content.encryptions[content_encryption.encryption_ns] = content_encryption; + } + }); + } + } + + agent.candidate_gathering_done.connect(on_candidate_gathering_done); + agent.initial_binding_request_received.connect(on_initial_binding_request_received); + agent.component_state_changed.connect(on_component_state_changed); + agent.new_selected_pair_full.connect(on_new_selected_pair_full); + agent.new_candidate_full.connect(on_new_candidate); + + agent.controlling_mode = !incoming; + stream_id = agent.add_stream(components); + thread_context = new MainContext(); + new Thread(@"ice-thread-$stream_id", () => { + thread_context.push_thread_default(); + thread_loop = new MainLoop(thread_context, false); + thread_loop.run(); + thread_context.pop_thread_default(); + return null; + }); + + if (turn_ip != null) { + for (uint8 component_id = 1; component_id <= components; component_id++) { + agent.set_relay_info(stream_id, component_id, turn_ip, turn_service.port, turn_service.username, turn_service.password, Nice.RelayType.UDP); + debug("TURN info (component %i) %s:%u", component_id, turn_ip, turn_service.port); + } + } + string ufrag; + string pwd; + agent.get_local_credentials(stream_id, out ufrag, out pwd); + init(ufrag, pwd); + + for (uint8 component_id = 1; component_id <= components; component_id++) { + // We don't properly get local candidates before this call + agent.attach_recv(stream_id, component_id, thread_context, on_recv); + } + + agent.gather_candidates(stream_id); + } + + private static DtlsSrtp.Handler setup_dtls(IceUdpTransportParameters tp, DtlsSrtp.CredentialsCapsule credentials) { + var weak_self = WeakRef(tp); + DtlsSrtp.Handler dtls_srtp = new DtlsSrtp.Handler.with_cert(credentials); + dtls_srtp.send_data.connect((data) => { + IceUdpTransportParameters self = (IceUdpTransportParameters) weak_self.get(); + if (self != null) self.agent.send(self.stream_id, 1, data); + }); + return dtls_srtp; + } + + private void on_candidate_gathering_done(uint stream_id) { + if (stream_id != this.stream_id) return; + debug("on_candidate_gathering_done in %u", stream_id); + + for (uint8 i = 1; i <= components; i++) { + foreach (unowned Nice.Candidate nc in agent.get_local_candidates(stream_id, i)) { + if (nc.transport == Nice.CandidateTransport.UDP) { + JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); + if (candidate == null) continue; + debug("Local candidate summary: %s", agent.generate_local_candidate_sdp(nc)); + } + } + } + } + + private void on_new_candidate(Nice.Candidate nc) { + if (nc.stream_id != stream_id) return; + JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); + if (candidate == null) return; + + if (nc.transport == Nice.CandidateTransport.UDP) { + // Execution was in the agent thread before + add_local_candidate_threadsafe(candidate); + } + } + + private bool bytes_equal(uint8[] a1, uint8[] a2) { + return a1.length == a2.length && Memory.cmp(a1, a2, a1.length) == 0; + } + + public override void handle_transport_accept(StanzaNode transport) throws Jingle.IqError { + debug("on_transport_accept from %s", peer_full_jid.to_string()); + base.handle_transport_accept(transport); + + if (dtls_srtp_handler != null && peer_fingerprint != null) { + if (dtls_srtp_handler.peer_fingerprint != null) { + if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { + warning("Tried to replace certificate fingerprint mid use. We don't allow that."); + peer_fingerprint = dtls_srtp_handler.peer_fingerprint; + peer_fp_algo = dtls_srtp_handler.peer_fp_algo; + } + } else { + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } + if (peer_setup == "passive") { + dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; + dtls_srtp_handler.stop_dtls_connection(); + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (content_encryption != null) { + this.content.encryptions[content_encryption.encryption_ns] = content_encryption; + } + }); + } + } else { + dtls_srtp_handler = null; + } + } + + public override void handle_transport_info(StanzaNode transport) throws Jingle.IqError { + debug("on_transport_info from %s", peer_full_jid.to_string()); + base.handle_transport_info(transport); + + if (dtls_srtp_handler != null && peer_fingerprint != null) { + if (dtls_srtp_handler.peer_fingerprint != null) { + if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { + warning("Tried to replace certificate fingerprint mid use. We don't allow that."); + peer_fingerprint = dtls_srtp_handler.peer_fingerprint; + peer_fp_algo = dtls_srtp_handler.peer_fp_algo; + } + } else { + dtls_srtp_handler.peer_fingerprint = peer_fingerprint; + dtls_srtp_handler.peer_fp_algo = peer_fp_algo; + } + } + + if (!we_want_connection) return; + + if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { + agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); + remote_credentials_set = true; + } + for (uint8 i = 1; i <= components; i++) { + SList candidates = new SList(); + foreach (JingleIceUdp.Candidate candidate in remote_candidates) { + if (candidate.component == i) { + candidates.append(candidate_to_nice(candidate)); + } + } + int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); + debug("Updated to %i remote candidates for candidate %u via transport info", new_candidates, i); + } + } + + public override void create_transport_connection(XmppStream stream, Jingle.Content content) { + debug("create_transport_connection: %s", content.session.sid); + debug("local_credentials: %s %s", local_ufrag, local_pwd); + debug("remote_credentials: %s %s", remote_ufrag, remote_pwd); + debug("expected incoming credentials: %s %s", local_ufrag + ":" + remote_ufrag, local_pwd); + debug("expected outgoing credentials: %s %s", remote_ufrag + ":" + local_ufrag, remote_pwd); + + we_want_connection = true; + + if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { + agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); + remote_credentials_set = true; + } + for (uint8 i = 1; i <= components; i++) { + SList candidates = new SList(); + foreach (JingleIceUdp.Candidate candidate in remote_candidates) { + if (candidate.ip.has_prefix("fe80::")) continue; + if (candidate.component == i) { + candidates.append(candidate_to_nice(candidate)); + debug("remote candidate: %s", agent.generate_local_candidate_sdp(candidate_to_nice(candidate))); + } + } + int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); + debug("Initiated component %u with %i remote candidates", i, new_candidates); + + connections[i] = new DatagramConnection(agent, dtls_srtp_handler, stream_id, i); + content.set_transport_connection(connections[i], i); + } + + base.create_transport_connection(stream, content); + } + + private void on_component_state_changed(uint stream_id, uint component_id, uint state) { + if (stream_id != this.stream_id) return; + debug("stream %u component %u state changed to %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); + may_consider_ready(stream_id, component_id); + if (incoming && dtls_srtp_handler != null && !dtls_srtp_handler.ready && is_component_ready(agent, stream_id, component_id) && dtls_srtp_handler.mode == DtlsSrtp.Mode.CLIENT) { + dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { + Jingle.ContentEncryption? encryption = dtls_srtp_handler.setup_dtls_connection.end(res); + if (encryption != null) { + this.content.encryptions[encryption.encryption_ns] = encryption; + } + }); + } + } + + private void may_consider_ready(uint stream_id, uint component_id) { + if (stream_id != this.stream_id) return; + if (connections.has_key((uint8) component_id) && !connections[(uint8)component_id].ready && is_component_ready(agent, stream_id, component_id) && (dtls_srtp_handler == null || dtls_srtp_handler.ready)) { + connections[(uint8)component_id].ready = true; + } + } + + private void on_initial_binding_request_received(uint stream_id) { + if (stream_id != this.stream_id) return; + debug("initial_binding_request_received"); + } + + private void on_new_selected_pair_full(uint stream_id, uint component_id, Nice.Candidate p1, Nice.Candidate p2) { + if (stream_id != this.stream_id) return; + debug("new_selected_pair_full %u [%s, %s]", component_id, agent.generate_local_candidate_sdp(p1), agent.generate_local_candidate_sdp(p2)); + } + + private void on_recv(Nice.Agent agent, uint stream_id, uint component_id, uint8[] data) { + if (stream_id != this.stream_id) return; + uint8[] decrypt_data = null; + if (dtls_srtp_handler != null) { + try { + decrypt_data = dtls_srtp_handler.process_incoming_data(component_id, data); + if (decrypt_data == null) return; + } catch (Crypto.Error e) { + warning("%s while on_recv stream %u component %u", e.message, stream_id, component_id); + return; + } + } + may_consider_ready(stream_id, component_id); + if (connections.has_key((uint8) component_id)) { + if (!connections[(uint8) component_id].ready) { + debug("on_recv stream %u component %u when state %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); + } + connections[(uint8) component_id].datagram_received(new Bytes(decrypt_data ?? data)); + } else { + debug("on_recv stream %u component %u length %u", stream_id, component_id, data.length); + } + } + + private static Nice.Candidate candidate_to_nice(JingleIceUdp.Candidate c) { + Nice.CandidateType type; + switch (c.type_) { + case JingleIceUdp.Candidate.Type.HOST: type = Nice.CandidateType.HOST; break; + case JingleIceUdp.Candidate.Type.PRFLX: type = Nice.CandidateType.PEER_REFLEXIVE; break; + case JingleIceUdp.Candidate.Type.RELAY: type = Nice.CandidateType.RELAYED; break; + case JingleIceUdp.Candidate.Type.SRFLX: type = Nice.CandidateType.SERVER_REFLEXIVE; break; + default: assert_not_reached(); + } + + Nice.Candidate candidate = new Nice.Candidate(type); + candidate.component_id = c.component; + char[] foundation = new char[Nice.CANDIDATE_MAX_FOUNDATION]; + Memory.copy(foundation, c.foundation.data, size_t.min(c.foundation.length, Nice.CANDIDATE_MAX_FOUNDATION - 1)); + candidate.foundation = foundation; + candidate.addr = Nice.Address(); + candidate.addr.init(); + candidate.addr.set_from_string(c.ip); + candidate.addr.set_port(c.port); + candidate.priority = c.priority; + if (c.rel_addr != null) { + candidate.base_addr = Nice.Address(); + candidate.base_addr.init(); + candidate.base_addr.set_from_string(c.rel_addr); + candidate.base_addr.set_port(c.rel_port); + } + candidate.transport = Nice.CandidateTransport.UDP; + return candidate; + } + + private static JingleIceUdp.Candidate? candidate_to_jingle(Nice.Candidate nc) { + JingleIceUdp.Candidate candidate = new JingleIceUdp.Candidate(); + switch (nc.type) { + case Nice.CandidateType.HOST: candidate.type_ = JingleIceUdp.Candidate.Type.HOST; break; + case Nice.CandidateType.PEER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.PRFLX; break; + case Nice.CandidateType.RELAYED: candidate.type_ = JingleIceUdp.Candidate.Type.RELAY; break; + case Nice.CandidateType.SERVER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.SRFLX; break; + default: assert_not_reached(); + } + candidate.component = (uint8) nc.component_id; + candidate.foundation = ((string)nc.foundation).dup(); + candidate.generation = 0; + candidate.id = Random.next_int().to_string("%08x"); // TODO + + char[] res = new char[NICE_ADDRESS_STRING_LEN]; + nc.addr.to_string(res); + candidate.ip = (string) res; + candidate.network = 0; // TODO + candidate.port = (uint16) nc.addr.get_port(); + candidate.priority = nc.priority; + candidate.protocol = "udp"; + if (nc.base_addr.is_valid() && !nc.base_addr.equal(nc.addr)) { + res = new char[NICE_ADDRESS_STRING_LEN]; + nc.base_addr.to_string(res); + candidate.rel_addr = (string) res; + candidate.rel_port = (uint16) nc.base_addr.get_port(); + } + if (candidate.ip.has_prefix("fe80::")) return null; + + return candidate; + } + + public override void dispose() { + base.dispose(); + agent = null; + dtls_srtp_handler = null; + connections.clear(); + if (thread_loop != null) { + thread_loop.quit(); + } + } +} diff --git a/libdino/src/service/module_manager.vala b/libdino/src/service/module_manager.vala index f7cad0fe..a6efe629 100644 --- a/libdino/src/service/module_manager.vala +++ b/libdino/src/service/module_manager.vala @@ -85,7 +85,7 @@ public class ModuleManager { module_map[account].add(new Xep.InBandRegistration.Module()); module_map[account].add(new Xep.HttpFileUpload.Module()); module_map[account].add(new Xep.Reactions.Module()); - module_map[account].add(new Xep.Socks5Bytestreams.Module()); + module_map[account].add(new Xep.Socks5Bytestreams.Module.with_local_ip_address_handler(Util.get_local_ip_addresses)); module_map[account].add(new Xep.InBandBytestreams.Module()); module_map[account].add(new Xep.Jingle.Module()); module_map[account].add(new Xep.JingleSocks5Bytestreams.Module()); @@ -97,11 +97,12 @@ public class ModuleManager { module_map[account].add(new Xep.JingleMessageInitiation.Module()); module_map[account].add(new Xep.OccupantIds.Module()); module_map[account].add(new Xep.MessageRetraction.Module()); - module_map[account].add(new Xep.JingleRawUdp.Module()); + module_map[account].add(new Xep.JingleRawUdp.Module.with_local_ip_address_handler(Util.get_local_ip_addresses)); module_map[account].add(new Xep.Muji.Module()); module_map[account].add(new Xep.CallInvites.Module()); module_map[account].add(new Xep.Coin.Module()); module_map[account].add(new Xep.MessageDisplayedSynchronization.Module()); + module_map[account].add(new IceUdpModule()); initialize_account_modules(account, module_map[account]); } } diff --git a/libdino/src/service/util.vala b/libdino/src/service/util.vala index ac596cad..577bc6cc 100644 --- a/libdino/src/service/util.vala +++ b/libdino/src/service/util.vala @@ -1,8 +1,6 @@ using Dino.Entities; -namespace Dino { - -public class Util { +namespace Dino.Util { public static Message.Type get_message_type_for_conversation(Conversation conversation) { switch (conversation.type_) { case Conversation.Type.CHAT: @@ -41,6 +39,12 @@ public class Util { } return false; } -} + public static Gee.List get_local_ip_addresses() { + Gee.List result = new Gee.ArrayList(); + foreach (string ip_address in Nice.interfaces_get_local_ips(false)) { + result.add(ip_address); + } + return result; + } } diff --git a/libdino/vapi/metadata/Nice-0.1.metadata b/libdino/vapi/metadata/Nice-0.1.metadata new file mode 100644 index 00000000..7fcf046a --- /dev/null +++ b/libdino/vapi/metadata/Nice-0.1.metadata @@ -0,0 +1,11 @@ +Nice cheader_filename="nice.h" +Address.to_string.dst type="char[]" +Agent.new_reliable#constructor name="create_reliable" +Agent.attach_recv skip=false +Agent.send.buf type="uint8[]" array_length_idx=2 +AgentRecvFunc.buf type="uint8[]" array_length_idx=3 +PseudoTcpCallbacks#record skip +PseudoTcpSocket#class skip + +# Not yet supported by vapigen +# Candidate copy_function="nice_candidate_copy" free_function="nice_candidate_free" type_id="" diff --git a/libdino/vapi/nice.vapi b/libdino/vapi/nice.vapi new file mode 100644 index 00000000..540e2b4e --- /dev/null +++ b/libdino/vapi/nice.vapi @@ -0,0 +1,386 @@ +/* nice.vapi generated by vapigen, do not modify. */ + +[CCode (cprefix = "Nice", gir_namespace = "Nice", gir_version = "0.1", lower_case_cprefix = "nice_")] +namespace Nice { + [CCode (cheader_filename = "nice.h", type_id = "nice_agent_get_type ()")] + public class Agent : GLib.Object { + [CCode (has_construct_function = false)] + public Agent (GLib.MainContext ctx, Nice.Compatibility compat); + public bool add_local_address (Nice.Address addr); + public uint add_stream (uint n_components); + public bool attach_recv (uint stream_id, uint component_id, GLib.MainContext ctx, Nice.AgentRecvFunc func); + [Version (since = "0.1.16")] + public async void close_async (); + [CCode (cname = "nice_agent_new_reliable", has_construct_function = false)] + [Version (since = "0.0.11")] + public Agent.create_reliable (GLib.MainContext ctx, Nice.Compatibility compat); + [Version (since = "0.1.6")] + public bool forget_relays (uint stream_id, uint component_id); + [CCode (has_construct_function = false)] + [Version (since = "0.1.15")] + public Agent.full (GLib.MainContext ctx, Nice.Compatibility compat, Nice.AgentOption flags); + public bool gather_candidates (uint stream_id); + [Version (since = "0.1.4")] + public string generate_local_candidate_sdp (Nice.Candidate candidate); + [Version (since = "0.1.4")] + public string generate_local_sdp (); + [Version (since = "0.1.4")] + public string generate_local_stream_sdp (uint stream_id, bool include_non_ice); + [Version (since = "0.1.8")] + public Nice.ComponentState get_component_state (uint stream_id, uint component_id); + public Nice.Candidate get_default_local_candidate (uint stream_id, uint component_id); + [Version (since = "0.1.5")] + public GLib.IOStream get_io_stream (uint stream_id, uint component_id); + public GLib.SList get_local_candidates (uint stream_id, uint component_id); + public bool get_local_credentials (uint stream_id, out string ufrag, out string pwd); + public GLib.SList get_remote_candidates (uint stream_id, uint component_id); + public bool get_selected_pair (uint stream_id, uint component_id, Nice.Candidate local, Nice.Candidate remote); + [Version (since = "0.1.5")] + public GLib.Socket? get_selected_socket (uint stream_id, uint component_id); + [Version (since = "0.1.4")] + public unowned string get_stream_name (uint stream_id); + [Version (since = "0.1.4")] + public Nice.Candidate parse_remote_candidate_sdp (uint stream_id, string sdp); + [Version (since = "0.1.4")] + public int parse_remote_sdp (string sdp); + [Version (since = "0.1.4")] + public GLib.SList parse_remote_stream_sdp (uint stream_id, string sdp, string ufrag, string pwd); + [Version (since = "0.1.16")] + public bool peer_candidate_gathering_done (uint stream_id); + [Version (since = "0.1.5")] + public ssize_t recv (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public int recv_messages (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public int recv_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + [Version (since = "0.1.5")] + public ssize_t recv_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; + public void remove_stream (uint stream_id); + public bool restart (); + [Version (since = "0.1.6")] + public bool restart_stream (uint stream_id); + public int send (uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 2.5, array_length_type = "guint", type = "const gchar*")] uint8[] buf); + [Version (since = "0.1.5")] + public int send_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] Nice.OutputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; + public bool set_local_credentials (uint stream_id, string ufrag, string pwd); + public void set_port_range (uint stream_id, uint component_id, uint min_port, uint max_port); + public bool set_relay_info (uint stream_id, uint component_id, string server_ip, uint server_port, string username, string password, Nice.RelayType type); + public int set_remote_candidates (uint stream_id, uint component_id, GLib.SList candidates); + public bool set_remote_credentials (uint stream_id, string ufrag, string pwd); + public bool set_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); + public bool set_selected_remote_candidate (uint stream_id, uint component_id, Nice.Candidate candidate); + [Version (since = "0.0.10")] + public void set_software (string software); + [Version (since = "0.1.4")] + public bool set_stream_name (uint stream_id, string name); + [Version (since = "0.0.9")] + public void set_stream_tos (uint stream_id, int tos); + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool bytestream_tcp { get; } + [NoAccessorMethod] + public uint compatibility { get; construct; } + [NoAccessorMethod] + public bool controlling_mode { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.14")] + public bool force_relay { get; set; } + [NoAccessorMethod] + public bool full_mode { get; construct; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool ice_tcp { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.16")] + public bool ice_trickle { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool ice_udp { get; set; } + [NoAccessorMethod] + [Version (since = "0.1.8")] + public bool keepalive_conncheck { get; set; } + [NoAccessorMethod] + public void* main_context { get; construct; } + [NoAccessorMethod] + public uint max_connectivity_checks { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_ip { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_password { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public uint proxy_port { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public uint proxy_type { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.4")] + public string proxy_username { owned get; set; } + [NoAccessorMethod] + [Version (since = "0.0.11")] + public bool reliable { get; construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_initial_timeout { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_max_retransmissions { get; set construct; } + [NoAccessorMethod] + public uint stun_pacing_timer { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.1.15")] + public uint stun_reliable_timeout { get; set construct; } + [NoAccessorMethod] + public string stun_server { owned get; set; } + [NoAccessorMethod] + public uint stun_server_port { get; set; } + [NoAccessorMethod] + public bool support_renomination { get; set; } + [NoAccessorMethod] + [Version (since = "0.0.7")] + public bool upnp { get; set construct; } + [NoAccessorMethod] + [Version (since = "0.0.7")] + public uint upnp_timeout { get; set construct; } + public signal void candidate_gathering_done (uint stream_id); + public signal void component_state_changed (uint stream_id, uint component_id, uint state); + public signal void initial_binding_request_received (uint stream_id); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_candidate (uint stream_id, uint component_id, string foundation); + [Version (since = "0.1.8")] + public signal void new_candidate_full (Nice.Candidate candidate); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_remote_candidate (uint stream_id, uint component_id, string foundation); + [Version (since = "0.1.8")] + public signal void new_remote_candidate_full (Nice.Candidate candidate); + [Version (deprecated = true, deprecated_since = "0.1.8")] + public signal void new_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); + [Version (since = "0.1.8")] + public signal void new_selected_pair_full (uint stream_id, uint component_id, Nice.Candidate lcandidate, Nice.Candidate rcandidate); + [Version (since = "0.0.11")] + public signal void reliable_transport_writable (uint stream_id, uint component_id); + [Version (since = "0.1.5")] + public signal void streams_removed ([CCode (array_length = false, array_null_terminated = true)] uint[] stream_ids); + } + [CCode (cheader_filename = "nice.h", copy_function = "nice_candidate_copy", free_function = "nice_candidate_free")] + [Compact] + public class Candidate { + public Nice.Address addr; + public Nice.Address base_addr; + public uint component_id; + [CCode (array_length = false)] + public weak char foundation[33]; + public weak string password; + public uint32 priority; + public void* sockptr; + public uint stream_id; + public Nice.CandidateTransport transport; + public Nice.TurnServer turn; + public Nice.CandidateType type; + public weak string username; + [CCode (has_construct_function = false)] + public Candidate (Nice.CandidateType type); + public Nice.Candidate copy (); + [Version (since = "0.1.15")] + public bool equal_target (Nice.Candidate candidate2); + public void free (); + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + public struct Address { + [CCode (cname = "s.addr")] + public void* s_addr; + [CCode (cname = "s.ip4")] + public void* s_ip4; + [CCode (cname = "s.ip6")] + public void* s_ip6; + public void copy_to_sockaddr (void* sin); + public bool equal (Nice.Address b); + [Version (since = "0.1.8")] + public bool equal_no_port (Nice.Address b); + public void free (); + public uint get_port (); + public void init (); + public int ip_version (); + public bool is_private (); + public bool is_valid (); + public void set_from_sockaddr (void* sin); + public bool set_from_string (string str); + public void set_ipv4 (uint32 addr_ipv4); + public void set_ipv6 (uint8 addr_ipv6); + public void set_port (uint port); + public void to_string ([CCode (array_length = false, type = "gchar*")] char[] dst); + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + [Version (since = "0.1.5")] + public struct InputMessage { + [CCode (array_length_cname = "n_buffers")] + public weak GLib.InputVector[] buffers; + public int n_buffers; + public Nice.Address from; + public size_t length; + } + [CCode (cheader_filename = "nice.h", has_type_id = false)] + [Version (since = "0.1.5")] + public struct OutputMessage { + [CCode (array_length_cname = "n_buffers")] + public weak GLib.OutputVector[] buffers; + public int n_buffers; + } + [CCode (cheader_filename = "nice.h", cname = "TurnServer", has_type_id = false)] + public struct TurnServer { + public int ref_count; + public Nice.Address server; + public weak string username; + public weak string password; + public Nice.RelayType type; + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_AGENT_OPTION_", has_type_id = false)] + [Flags] + [Version (since = "0.1.15")] + public enum AgentOption { + REGULAR_NOMINATION, + RELIABLE, + LITE_MODE, + ICE_TRICKLE, + SUPPORT_RENOMINATION + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TRANSPORT_", has_type_id = false)] + public enum CandidateTransport { + UDP, + TCP_ACTIVE, + TCP_PASSIVE, + TCP_SO + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TYPE_", has_type_id = false)] + public enum CandidateType { + HOST, + SERVER_REFLEXIVE, + PEER_REFLEXIVE, + RELAYED + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPATIBILITY_", has_type_id = false)] + public enum Compatibility { + RFC5245, + DRAFT19, + GOOGLE, + MSN, + WLM2009, + OC2007, + OC2007R2, + LAST + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_STATE_", has_type_id = false)] + public enum ComponentState { + DISCONNECTED, + GATHERING, + CONNECTING, + CONNECTED, + READY, + FAILED, + LAST; + [Version (since = "0.1.6")] + public unowned string to_string (); + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_TYPE_", has_type_id = false)] + public enum ComponentType { + RTP, + RTCP + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_NOMINATION_MODE_", has_type_id = false)] + [Version (since = "0.1.15")] + public enum NominationMode { + REGULAR, + AGGRESSIVE + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_PROXY_TYPE_", has_type_id = false)] + [Version (since = "0.0.4")] + public enum ProxyType { + NONE, + SOCKS5, + HTTP, + LAST + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpDebugLevel", cprefix = "PSEUDO_TCP_DEBUG_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpDebugLevel { + NONE, + NORMAL, + VERBOSE + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpShutdown", cprefix = "PSEUDO_TCP_SHUTDOWN_", has_type_id = false)] + [Version (since = "0.1.8")] + public enum PseudoTcpShutdown { + RD, + WR, + RDWR + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpState", cprefix = "PSEUDO_TCP_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpState { + LISTEN, + SYN_SENT, + SYN_RECEIVED, + ESTABLISHED, + CLOSED, + FIN_WAIT_1, + FIN_WAIT_2, + CLOSING, + TIME_WAIT, + CLOSE_WAIT, + LAST_ACK + } + [CCode (cheader_filename = "nice.h", cname = "PseudoTcpWriteResult", cprefix = "WR_", has_type_id = false)] + [Version (since = "0.0.11")] + public enum PseudoTcpWriteResult { + SUCCESS, + TOO_LARGE, + FAIL + } + [CCode (cheader_filename = "nice.h", cprefix = "NICE_RELAY_TYPE_TURN_", has_type_id = false)] + public enum RelayType { + UDP, + TCP, + TLS + } + [CCode (cheader_filename = "nice.h", instance_pos = 4.9)] + public delegate void AgentRecvFunc (Nice.Agent agent, uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 3.5, array_length_type = "guint", type = "gchar*")] uint8[] buf); + [CCode (cheader_filename = "nice.h", cname = "NICE_AGENT_MAX_REMOTE_CANDIDATES")] + public const int AGENT_MAX_REMOTE_CANDIDATES; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_ACTIVE")] + public const int CANDIDATE_DIRECTION_MS_PREF_ACTIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_PASSIVE")] + public const int CANDIDATE_DIRECTION_MS_PREF_PASSIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_MAX_FOUNDATION")] + public const int CANDIDATE_MAX_FOUNDATION; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_TCP")] + public const int CANDIDATE_TRANSPORT_MS_PREF_TCP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_UDP")] + public const int CANDIDATE_TRANSPORT_MS_PREF_UDP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_HOST")] + public const int CANDIDATE_TYPE_PREF_HOST; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_NAT_ASSISTED")] + public const int CANDIDATE_TYPE_PREF_NAT_ASSISTED; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_PEER_REFLEXIVE")] + public const int CANDIDATE_TYPE_PREF_PEER_REFLEXIVE; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED")] + public const int CANDIDATE_TYPE_PREF_RELAYED; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED_UDP")] + public const int CANDIDATE_TYPE_PREF_RELAYED_UDP; + [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE")] + public const int CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE; + [CCode (cheader_filename = "nice.h")] + public static void debug_disable (bool with_stun); + [CCode (cheader_filename = "nice.h")] + public static void debug_enable (bool with_stun); + [CCode (cheader_filename = "nice.h")] + public static string? interfaces_get_ip_for_interface (string interface_name); + [CCode (cheader_filename = "nice.h")] + public static GLib.List interfaces_get_local_interfaces (); + [CCode (cheader_filename = "nice.h")] + public static GLib.List interfaces_get_local_ips (bool include_loopback); + [CCode (cheader_filename = "nice.h", cname = "pseudo_tcp_set_debug_level")] + [Version (since = "0.0.11")] + public static void pseudo_tcp_set_debug_level (Nice.PseudoTcpDebugLevel level); +} diff --git a/plugins/ice/meson.build b/plugins/ice/meson.build deleted file mode 100644 index 19030259..00000000 --- a/plugins/ice/meson.build +++ /dev/null @@ -1,25 +0,0 @@ -dependencies = [ - dep_dino, - dep_gee, - dep_gio, - dep_glib, - dep_gmodule, - dep_nice, - dep_xmpp_vala, -] -sources = files( - 'src/module.vala', - 'src/plugin.vala', - 'src/transport_parameters.vala', - 'src/util.vala', - 'src/register_plugin.vala', -) -c_args = vala_c_args + [ - '-DG_LOG_DOMAIN="ice"', -] -vala_args = [ - '--vapidir', meson.current_source_dir() / 'vapi', -] -lib_ice = shared_library('ice', sources, name_prefix: '', c_args: c_args, vala_args: vala_args, include_directories: include_directories('src'), dependencies: dependencies, install: true, install_dir: get_option('libdir') / get_option('plugindir'), install_rpath: default_install_rpath) -dep_ice = declare_dependency(link_with: lib_ice, include_directories: include_directories('.')) -summary('Peer-to-peer communication (ice)', dep_ice.found(), bool_yn: true, section: 'Plugins') diff --git a/plugins/ice/src/module.vala b/plugins/ice/src/module.vala deleted file mode 100644 index c3c92124..00000000 --- a/plugins/ice/src/module.vala +++ /dev/null @@ -1,57 +0,0 @@ -using Gee; - -using Dino.Crypto; -using Xmpp; -using Xmpp.Xep; - -public class Dino.Plugins.Ice.Module : JingleIceUdp.Module { - - public string? stun_ip = null; - public uint stun_port = 0; - public string? turn_ip = null; - public Xep.ExternalServiceDiscovery.Service? turn_service = null; - - private weak Nice.Agent? agent; - private HashMap cerds = new HashMap(); - - private Nice.Agent get_agent() { - Nice.Agent? agent = this.agent; - if (agent == null) { - agent = new Nice.Agent(MainContext.@default(), Nice.Compatibility.RFC5245); - if (stun_ip != null) { - agent.stun_server = stun_ip; - agent.stun_server_port = stun_port; - } - agent.ice_tcp = false; - agent.set_software("Dino"); - agent.weak_ref(agent_unweak); - this.agent = agent; - debug("STUN server for libnice %s %u", agent.stun_server, agent.stun_server_port); - } - return agent; - } - - public override Jingle.TransportParameters create_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid) { - DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); - return new TransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid); - } - - public override Jingle.TransportParameters parse_transport_parameters(XmppStream stream, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode transport) throws Jingle.IqError { - DtlsSrtp.CredentialsCapsule? cred = get_create_credentials(local_full_jid, peer_full_jid); - return new TransportParameters(get_agent(), cred, turn_service, turn_ip, components, local_full_jid, peer_full_jid, transport); - } - - private DtlsSrtp.CredentialsCapsule? get_create_credentials(Jid local_full_jid, Jid peer_full_jid) { - string from_to_id = local_full_jid.to_string() + peer_full_jid.to_string(); - try { - if (!cerds.has_key(from_to_id)) cerds[from_to_id] = DtlsSrtp.generate_credentials(); - } catch (GLib.Error e) { - warning("Error creating dtls credentials: %s", e.message); - } - return cerds[from_to_id]; - } - - private void agent_unweak() { - this.agent = null; - } -} \ No newline at end of file diff --git a/plugins/ice/src/plugin.vala b/plugins/ice/src/plugin.vala deleted file mode 100644 index d1655a74..00000000 --- a/plugins/ice/src/plugin.vala +++ /dev/null @@ -1,104 +0,0 @@ -using Gee; -using Dino.Entities; -using Xmpp; -using Xmpp.Xep; - -private extern const size_t NICE_ADDRESS_STRING_LEN; - -public class Dino.Plugins.Ice.Plugin : RootInterface, Object { - private HashMap timeouts = new HashMap(Account.hash_func, Account.equals_func); - - public Dino.Application app; - - public void registered(Dino.Application app) { - Nice.debug_enable(true); - this.app = app; - app.stream_interactor.module_manager.initialize_account_modules.connect((account, list) => { - list.add(new Module()); - }); - app.stream_interactor.stream_attached_modules.connect((account, stream) => { - if (stream.get_module(Socks5Bytestreams.Module.IDENTITY) != null) { - stream.get_module(Socks5Bytestreams.Module.IDENTITY).set_local_ip_address_handler(get_local_ip_addresses); - } - if (stream.get_module(JingleRawUdp.Module.IDENTITY) != null) { - stream.get_module(JingleRawUdp.Module.IDENTITY).set_local_ip_address_handler(get_local_ip_addresses); - } - }); - app.stream_interactor.stream_negotiated.connect(external_discovery_refresh_services); - } - - private async void external_discovery_refresh_services(Account account, XmppStream stream) { - Module? ice_udp_module = stream.get_module(JingleIceUdp.Module.IDENTITY) as Module; - if (ice_udp_module == null) return; - - Gee.List services = yield ExternalServiceDiscovery.request_services(stream); - foreach (Xep.ExternalServiceDiscovery.Service service in services) { - if (service.transport == "udp" && (service.ty == "stun" || service.ty == "turn")) { - InetAddress? ip = yield lookup_ipv4_addess(service.host); - if (ip == null) continue; - - if (ip.is_any || ip.is_link_local || ip.is_loopback || ip.is_multicast || ip.is_site_local) { - warning("Ignoring STUN/TURN server at %s", service.host); - continue; - } - - if (service.ty == "stun") { - debug("Server offers STUN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); - ice_udp_module.stun_ip = ip.to_string(); - ice_udp_module.stun_port = service.port; - } else if (service.ty == "turn") { - debug("Server offers TURN server: %s:%u, resolved to %s", service.host, service.port, ip.to_string()); - ice_udp_module.turn_ip = ip.to_string(); - ice_udp_module.turn_service = service; - } - } - } - if (ice_udp_module.stun_ip == null) { - InetAddress ip = yield lookup_ipv4_addess("stun.dino.im"); - if (ip == null) return; - - debug("Using fallback STUN server: stun.dino.im:7886, resolved to %s", ip.to_string()); - - ice_udp_module.stun_ip = ip.to_string(); - ice_udp_module.stun_port = 7886; - } - - // Refresh TURN credentials before they expire - if (ice_udp_module.turn_service != null) { - DateTime? expires = ice_udp_module.turn_service.expires; - if (expires != null) { - uint refresh_delay = (uint) (expires.to_unix() - new DateTime.now_utc().to_unix()) / 2; - - if (refresh_delay >= 300 && refresh_delay <= (int64) uint.MAX) { // 5 min < refetch < max - debug("Re-fetching TURN credentials in %u sec", refresh_delay); - - timeouts.unset(account); - timeouts[account] = Timeout.add_seconds((uint) refresh_delay, () => { - external_discovery_refresh_services.begin(account, stream); - return false; - }); - } else { - warning("TURN credentials' expiry time = %u, *not* re-fetching", refresh_delay); - } - } - } - } - - public void shutdown() { - // Nothing to do - } - - private async InetAddress? lookup_ipv4_addess(string host) { - try { - Resolver resolver = Resolver.get_default(); - GLib.List? ips = yield resolver.lookup_by_name_async(host); - foreach (GLib.InetAddress ina in ips) { - if (ina.get_family() != SocketFamily.IPV4) continue; - return ina; - } - } catch (Error e) { - warning("Failed looking up IP address of %s", host); - } - return null; - } -} \ No newline at end of file diff --git a/plugins/ice/src/register_plugin.vala b/plugins/ice/src/register_plugin.vala deleted file mode 100644 index b2ed56c1..00000000 --- a/plugins/ice/src/register_plugin.vala +++ /dev/null @@ -1,3 +0,0 @@ -public Type register_plugin(Module module) { - return typeof (Dino.Plugins.Ice.Plugin); -} diff --git a/plugins/ice/src/transport_parameters.vala b/plugins/ice/src/transport_parameters.vala deleted file mode 100644 index 122207c5..00000000 --- a/plugins/ice/src/transport_parameters.vala +++ /dev/null @@ -1,391 +0,0 @@ -using Gee; - -using Dino.Crypto; -using Xmpp; -using Xmpp.Xep; - - -public class Dino.Plugins.Ice.TransportParameters : JingleIceUdp.IceUdpTransportParameters { - private Nice.Agent agent; - private uint stream_id; - private bool we_want_connection; - private bool remote_credentials_set; - private Map connections = new HashMap(); - private DtlsSrtp.Handler? dtls_srtp_handler; - private MainContext thread_context; - private MainLoop thread_loop; - - private class DatagramConnection : Jingle.DatagramConnection { - private Nice.Agent agent; - private DtlsSrtp.Handler? dtls_srtp_handler; - private uint stream_id; - private string? error; - private ulong datagram_received_id; - - public DatagramConnection(Nice.Agent agent, DtlsSrtp.Handler? dtls_srtp_handler, uint stream_id, uint8 component_id) { - this.agent = agent; - this.dtls_srtp_handler = dtls_srtp_handler; - this.stream_id = stream_id; - this.component_id = component_id; - this.datagram_received_id = this.datagram_received.connect((datagram) => { - bytes_received += datagram.length; - }); - } - - public override async void terminate(bool we_terminated, string? reason_string = null, string? reason_text = null) { - yield base.terminate(we_terminated, reason_string, reason_text); - this.disconnect(datagram_received_id); - agent = null; - dtls_srtp_handler = null; - } - - public override void send_datagram(Bytes datagram) { - if (this.agent != null && is_component_ready(agent, stream_id, component_id)) { - try { - if (dtls_srtp_handler != null) { - uint8[] encrypted_data = dtls_srtp_handler.process_outgoing_data(component_id, datagram.get_data()); - if (encrypted_data == null) return; - GLib.OutputVector vector = { encrypted_data, encrypted_data.length }; - GLib.OutputVector[] vectors = { vector }; - Nice.OutputMessage message = { vectors }; - Nice.OutputMessage[] messages = { message }; - agent.send_messages_nonblocking(stream_id, component_id, messages); - } else { - GLib.OutputVector vector = { datagram.get_data(), datagram.get_size() }; - GLib.OutputVector[] vectors = { vector }; - Nice.OutputMessage message = { vectors }; - Nice.OutputMessage[] messages = { message }; - agent.send_messages_nonblocking(stream_id, component_id, messages); - } - bytes_sent += datagram.length; - } catch (GLib.Error e) { - warning("%s while send_datagram stream %u component %u", e.message, stream_id, component_id); - } - } - } - } - - public TransportParameters(Nice.Agent agent, DtlsSrtp.CredentialsCapsule? credentials, Xep.ExternalServiceDiscovery.Service? turn_service, string? turn_ip, uint8 components, Jid local_full_jid, Jid peer_full_jid, StanzaNode? node = null) { - base(components, local_full_jid, peer_full_jid, node); - this.we_want_connection = (node == null); - this.agent = agent; - - if (this.peer_fingerprint != null || !incoming) { - dtls_srtp_handler = setup_dtls(this, credentials); - own_fingerprint = dtls_srtp_handler.own_fingerprint; - if (incoming) { - own_setup = "active"; - dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } else { - own_setup = "actpass"; - dtls_srtp_handler.mode = DtlsSrtp.Mode.SERVER; - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (content_encryption != null) { - this.content.encryptions[content_encryption.encryption_ns] = content_encryption; - } - }); - } - } - - agent.candidate_gathering_done.connect(on_candidate_gathering_done); - agent.initial_binding_request_received.connect(on_initial_binding_request_received); - agent.component_state_changed.connect(on_component_state_changed); - agent.new_selected_pair_full.connect(on_new_selected_pair_full); - agent.new_candidate_full.connect(on_new_candidate); - - agent.controlling_mode = !incoming; - stream_id = agent.add_stream(components); - thread_context = new MainContext(); - new Thread(@"ice-thread-$stream_id", () => { - thread_context.push_thread_default(); - thread_loop = new MainLoop(thread_context, false); - thread_loop.run(); - thread_context.pop_thread_default(); - return null; - }); - - if (turn_ip != null) { - for (uint8 component_id = 1; component_id <= components; component_id++) { - agent.set_relay_info(stream_id, component_id, turn_ip, turn_service.port, turn_service.username, turn_service.password, Nice.RelayType.UDP); - debug("TURN info (component %i) %s:%u", component_id, turn_ip, turn_service.port); - } - } - string ufrag; - string pwd; - agent.get_local_credentials(stream_id, out ufrag, out pwd); - init(ufrag, pwd); - - for (uint8 component_id = 1; component_id <= components; component_id++) { - // We don't properly get local candidates before this call - agent.attach_recv(stream_id, component_id, thread_context, on_recv); - } - - agent.gather_candidates(stream_id); - } - - private static DtlsSrtp.Handler setup_dtls(TransportParameters tp, DtlsSrtp.CredentialsCapsule credentials) { - var weak_self = WeakRef(tp); - DtlsSrtp.Handler dtls_srtp = new DtlsSrtp.Handler.with_cert(credentials); - dtls_srtp.send_data.connect((data) => { - TransportParameters self = (TransportParameters) weak_self.get(); - if (self != null) self.agent.send(self.stream_id, 1, data); - }); - return dtls_srtp; - } - - private void on_candidate_gathering_done(uint stream_id) { - if (stream_id != this.stream_id) return; - debug("on_candidate_gathering_done in %u", stream_id); - - for (uint8 i = 1; i <= components; i++) { - foreach (unowned Nice.Candidate nc in agent.get_local_candidates(stream_id, i)) { - if (nc.transport == Nice.CandidateTransport.UDP) { - JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); - if (candidate == null) continue; - debug("Local candidate summary: %s", agent.generate_local_candidate_sdp(nc)); - } - } - } - } - - private void on_new_candidate(Nice.Candidate nc) { - if (nc.stream_id != stream_id) return; - JingleIceUdp.Candidate? candidate = candidate_to_jingle(nc); - if (candidate == null) return; - - if (nc.transport == Nice.CandidateTransport.UDP) { - // Execution was in the agent thread before - add_local_candidate_threadsafe(candidate); - } - } - - private bool bytes_equal(uint8[] a1, uint8[] a2) { - return a1.length == a2.length && Memory.cmp(a1, a2, a1.length) == 0; - } - - public override void handle_transport_accept(StanzaNode transport) throws Jingle.IqError { - debug("on_transport_accept from %s", peer_full_jid.to_string()); - base.handle_transport_accept(transport); - - if (dtls_srtp_handler != null && peer_fingerprint != null) { - if (dtls_srtp_handler.peer_fingerprint != null) { - if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { - warning("Tried to replace certificate fingerprint mid use. We don't allow that."); - peer_fingerprint = dtls_srtp_handler.peer_fingerprint; - peer_fp_algo = dtls_srtp_handler.peer_fp_algo; - } - } else { - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } - if (peer_setup == "passive") { - dtls_srtp_handler.mode = DtlsSrtp.Mode.CLIENT; - dtls_srtp_handler.stop_dtls_connection(); - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - var content_encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (content_encryption != null) { - this.content.encryptions[content_encryption.encryption_ns] = content_encryption; - } - }); - } - } else { - dtls_srtp_handler = null; - } - } - - public override void handle_transport_info(StanzaNode transport) throws Jingle.IqError { - debug("on_transport_info from %s", peer_full_jid.to_string()); - base.handle_transport_info(transport); - - if (dtls_srtp_handler != null && peer_fingerprint != null) { - if (dtls_srtp_handler.peer_fingerprint != null) { - if (!bytes_equal(dtls_srtp_handler.peer_fingerprint, peer_fingerprint)) { - warning("Tried to replace certificate fingerprint mid use. We don't allow that."); - peer_fingerprint = dtls_srtp_handler.peer_fingerprint; - peer_fp_algo = dtls_srtp_handler.peer_fp_algo; - } - } else { - dtls_srtp_handler.peer_fingerprint = peer_fingerprint; - dtls_srtp_handler.peer_fp_algo = peer_fp_algo; - } - } - - if (!we_want_connection) return; - - if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { - agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); - remote_credentials_set = true; - } - for (uint8 i = 1; i <= components; i++) { - SList candidates = new SList(); - foreach (JingleIceUdp.Candidate candidate in remote_candidates) { - if (candidate.component == i) { - candidates.append(candidate_to_nice(candidate)); - } - } - int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); - debug("Updated to %i remote candidates for candidate %u via transport info", new_candidates, i); - } - } - - public override void create_transport_connection(XmppStream stream, Jingle.Content content) { - debug("create_transport_connection: %s", content.session.sid); - debug("local_credentials: %s %s", local_ufrag, local_pwd); - debug("remote_credentials: %s %s", remote_ufrag, remote_pwd); - debug("expected incoming credentials: %s %s", local_ufrag + ":" + remote_ufrag, local_pwd); - debug("expected outgoing credentials: %s %s", remote_ufrag + ":" + local_ufrag, remote_pwd); - - we_want_connection = true; - - if (remote_ufrag != null && remote_pwd != null && !remote_credentials_set) { - agent.set_remote_credentials(stream_id, remote_ufrag, remote_pwd); - remote_credentials_set = true; - } - for (uint8 i = 1; i <= components; i++) { - SList candidates = new SList(); - foreach (JingleIceUdp.Candidate candidate in remote_candidates) { - if (candidate.ip.has_prefix("fe80::")) continue; - if (candidate.component == i) { - candidates.append(candidate_to_nice(candidate)); - debug("remote candidate: %s", agent.generate_local_candidate_sdp(candidate_to_nice(candidate))); - } - } - int new_candidates = agent.set_remote_candidates(stream_id, i, candidates); - debug("Initiated component %u with %i remote candidates", i, new_candidates); - - connections[i] = new DatagramConnection(agent, dtls_srtp_handler, stream_id, i); - content.set_transport_connection(connections[i], i); - } - - base.create_transport_connection(stream, content); - } - - private void on_component_state_changed(uint stream_id, uint component_id, uint state) { - if (stream_id != this.stream_id) return; - debug("stream %u component %u state changed to %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); - may_consider_ready(stream_id, component_id); - if (incoming && dtls_srtp_handler != null && !dtls_srtp_handler.ready && is_component_ready(agent, stream_id, component_id) && dtls_srtp_handler.mode == DtlsSrtp.Mode.CLIENT) { - dtls_srtp_handler.setup_dtls_connection.begin((_, res) => { - Jingle.ContentEncryption? encryption = dtls_srtp_handler.setup_dtls_connection.end(res); - if (encryption != null) { - this.content.encryptions[encryption.encryption_ns] = encryption; - } - }); - } - } - - private void may_consider_ready(uint stream_id, uint component_id) { - if (stream_id != this.stream_id) return; - if (connections.has_key((uint8) component_id) && !connections[(uint8)component_id].ready && is_component_ready(agent, stream_id, component_id) && (dtls_srtp_handler == null || dtls_srtp_handler.ready)) { - connections[(uint8)component_id].ready = true; - } - } - - private void on_initial_binding_request_received(uint stream_id) { - if (stream_id != this.stream_id) return; - debug("initial_binding_request_received"); - } - - private void on_new_selected_pair_full(uint stream_id, uint component_id, Nice.Candidate p1, Nice.Candidate p2) { - if (stream_id != this.stream_id) return; - debug("new_selected_pair_full %u [%s, %s]", component_id, agent.generate_local_candidate_sdp(p1), agent.generate_local_candidate_sdp(p2)); - } - - private void on_recv(Nice.Agent agent, uint stream_id, uint component_id, uint8[] data) { - if (stream_id != this.stream_id) return; - uint8[] decrypt_data = null; - if (dtls_srtp_handler != null) { - try { - decrypt_data = dtls_srtp_handler.process_incoming_data(component_id, data); - if (decrypt_data == null) return; - } catch (Crypto.Error e) { - warning("%s while on_recv stream %u component %u", e.message, stream_id, component_id); - return; - } - } - may_consider_ready(stream_id, component_id); - if (connections.has_key((uint8) component_id)) { - if (!connections[(uint8) component_id].ready) { - debug("on_recv stream %u component %u when state %s", stream_id, component_id, agent.get_component_state(stream_id, component_id).to_string()); - } - connections[(uint8) component_id].datagram_received(new Bytes(decrypt_data ?? data)); - } else { - debug("on_recv stream %u component %u length %u", stream_id, component_id, data.length); - } - } - - private static Nice.Candidate candidate_to_nice(JingleIceUdp.Candidate c) { - Nice.CandidateType type; - switch (c.type_) { - case JingleIceUdp.Candidate.Type.HOST: type = Nice.CandidateType.HOST; break; - case JingleIceUdp.Candidate.Type.PRFLX: type = Nice.CandidateType.PEER_REFLEXIVE; break; - case JingleIceUdp.Candidate.Type.RELAY: type = Nice.CandidateType.RELAYED; break; - case JingleIceUdp.Candidate.Type.SRFLX: type = Nice.CandidateType.SERVER_REFLEXIVE; break; - default: assert_not_reached(); - } - - Nice.Candidate candidate = new Nice.Candidate(type); - candidate.component_id = c.component; - char[] foundation = new char[Nice.CANDIDATE_MAX_FOUNDATION]; - Memory.copy(foundation, c.foundation.data, size_t.min(c.foundation.length, Nice.CANDIDATE_MAX_FOUNDATION - 1)); - candidate.foundation = foundation; - candidate.addr = Nice.Address(); - candidate.addr.init(); - candidate.addr.set_from_string(c.ip); - candidate.addr.set_port(c.port); - candidate.priority = c.priority; - if (c.rel_addr != null) { - candidate.base_addr = Nice.Address(); - candidate.base_addr.init(); - candidate.base_addr.set_from_string(c.rel_addr); - candidate.base_addr.set_port(c.rel_port); - } - candidate.transport = Nice.CandidateTransport.UDP; - return candidate; - } - - private static JingleIceUdp.Candidate? candidate_to_jingle(Nice.Candidate nc) { - JingleIceUdp.Candidate candidate = new JingleIceUdp.Candidate(); - switch (nc.type) { - case Nice.CandidateType.HOST: candidate.type_ = JingleIceUdp.Candidate.Type.HOST; break; - case Nice.CandidateType.PEER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.PRFLX; break; - case Nice.CandidateType.RELAYED: candidate.type_ = JingleIceUdp.Candidate.Type.RELAY; break; - case Nice.CandidateType.SERVER_REFLEXIVE: candidate.type_ = JingleIceUdp.Candidate.Type.SRFLX; break; - default: assert_not_reached(); - } - candidate.component = (uint8) nc.component_id; - candidate.foundation = ((string)nc.foundation).dup(); - candidate.generation = 0; - candidate.id = Random.next_int().to_string("%08x"); // TODO - - char[] res = new char[NICE_ADDRESS_STRING_LEN]; - nc.addr.to_string(res); - candidate.ip = (string) res; - candidate.network = 0; // TODO - candidate.port = (uint16) nc.addr.get_port(); - candidate.priority = nc.priority; - candidate.protocol = "udp"; - if (nc.base_addr.is_valid() && !nc.base_addr.equal(nc.addr)) { - res = new char[NICE_ADDRESS_STRING_LEN]; - nc.base_addr.to_string(res); - candidate.rel_addr = (string) res; - candidate.rel_port = (uint16) nc.base_addr.get_port(); - } - if (candidate.ip.has_prefix("fe80::")) return null; - - return candidate; - } - - public override void dispose() { - base.dispose(); - agent = null; - dtls_srtp_handler = null; - connections.clear(); - if (thread_loop != null) { - thread_loop.quit(); - } - } -} diff --git a/plugins/ice/src/util.vala b/plugins/ice/src/util.vala deleted file mode 100644 index dd89d2f4..00000000 --- a/plugins/ice/src/util.vala +++ /dev/null @@ -1,18 +0,0 @@ -using Gee; - -namespace Dino.Plugins.Ice { - -internal static bool is_component_ready(Nice.Agent agent, uint stream_id, uint component_id) { - var state = agent.get_component_state(stream_id, component_id); - return state == Nice.ComponentState.CONNECTED || state == Nice.ComponentState.READY; -} - -internal Gee.List get_local_ip_addresses() { - Gee.List result = new ArrayList(); - foreach (string ip_address in Nice.interfaces_get_local_ips(false)) { - result.add(ip_address); - } - return result; -} - -} \ No newline at end of file diff --git a/plugins/ice/vapi/metadata/Nice-0.1.metadata b/plugins/ice/vapi/metadata/Nice-0.1.metadata deleted file mode 100644 index 7fcf046a..00000000 --- a/plugins/ice/vapi/metadata/Nice-0.1.metadata +++ /dev/null @@ -1,11 +0,0 @@ -Nice cheader_filename="nice.h" -Address.to_string.dst type="char[]" -Agent.new_reliable#constructor name="create_reliable" -Agent.attach_recv skip=false -Agent.send.buf type="uint8[]" array_length_idx=2 -AgentRecvFunc.buf type="uint8[]" array_length_idx=3 -PseudoTcpCallbacks#record skip -PseudoTcpSocket#class skip - -# Not yet supported by vapigen -# Candidate copy_function="nice_candidate_copy" free_function="nice_candidate_free" type_id="" diff --git a/plugins/ice/vapi/nice.vapi b/plugins/ice/vapi/nice.vapi deleted file mode 100644 index 540e2b4e..00000000 --- a/plugins/ice/vapi/nice.vapi +++ /dev/null @@ -1,386 +0,0 @@ -/* nice.vapi generated by vapigen, do not modify. */ - -[CCode (cprefix = "Nice", gir_namespace = "Nice", gir_version = "0.1", lower_case_cprefix = "nice_")] -namespace Nice { - [CCode (cheader_filename = "nice.h", type_id = "nice_agent_get_type ()")] - public class Agent : GLib.Object { - [CCode (has_construct_function = false)] - public Agent (GLib.MainContext ctx, Nice.Compatibility compat); - public bool add_local_address (Nice.Address addr); - public uint add_stream (uint n_components); - public bool attach_recv (uint stream_id, uint component_id, GLib.MainContext ctx, Nice.AgentRecvFunc func); - [Version (since = "0.1.16")] - public async void close_async (); - [CCode (cname = "nice_agent_new_reliable", has_construct_function = false)] - [Version (since = "0.0.11")] - public Agent.create_reliable (GLib.MainContext ctx, Nice.Compatibility compat); - [Version (since = "0.1.6")] - public bool forget_relays (uint stream_id, uint component_id); - [CCode (has_construct_function = false)] - [Version (since = "0.1.15")] - public Agent.full (GLib.MainContext ctx, Nice.Compatibility compat, Nice.AgentOption flags); - public bool gather_candidates (uint stream_id); - [Version (since = "0.1.4")] - public string generate_local_candidate_sdp (Nice.Candidate candidate); - [Version (since = "0.1.4")] - public string generate_local_sdp (); - [Version (since = "0.1.4")] - public string generate_local_stream_sdp (uint stream_id, bool include_non_ice); - [Version (since = "0.1.8")] - public Nice.ComponentState get_component_state (uint stream_id, uint component_id); - public Nice.Candidate get_default_local_candidate (uint stream_id, uint component_id); - [Version (since = "0.1.5")] - public GLib.IOStream get_io_stream (uint stream_id, uint component_id); - public GLib.SList get_local_candidates (uint stream_id, uint component_id); - public bool get_local_credentials (uint stream_id, out string ufrag, out string pwd); - public GLib.SList get_remote_candidates (uint stream_id, uint component_id); - public bool get_selected_pair (uint stream_id, uint component_id, Nice.Candidate local, Nice.Candidate remote); - [Version (since = "0.1.5")] - public GLib.Socket? get_selected_socket (uint stream_id, uint component_id); - [Version (since = "0.1.4")] - public unowned string get_stream_name (uint stream_id); - [Version (since = "0.1.4")] - public Nice.Candidate parse_remote_candidate_sdp (uint stream_id, string sdp); - [Version (since = "0.1.4")] - public int parse_remote_sdp (string sdp); - [Version (since = "0.1.4")] - public GLib.SList parse_remote_stream_sdp (uint stream_id, string sdp, string ufrag, string pwd); - [Version (since = "0.1.16")] - public bool peer_candidate_gathering_done (uint stream_id); - [Version (since = "0.1.5")] - public ssize_t recv (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public int recv_messages (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public int recv_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] out unowned Nice.InputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - [Version (since = "0.1.5")] - public ssize_t recv_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "buf_len", array_length_pos = 3.5, array_length_type = "gsize")] out unowned uint8[] buf, GLib.Cancellable? cancellable = null) throws GLib.Error; - public void remove_stream (uint stream_id); - public bool restart (); - [Version (since = "0.1.6")] - public bool restart_stream (uint stream_id); - public int send (uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 2.5, array_length_type = "guint", type = "const gchar*")] uint8[] buf); - [Version (since = "0.1.5")] - public int send_messages_nonblocking (uint stream_id, uint component_id, [CCode (array_length_cname = "n_messages", array_length_pos = 3.5, array_length_type = "guint")] Nice.OutputMessage[] messages, GLib.Cancellable? cancellable = null) throws GLib.Error; - public bool set_local_credentials (uint stream_id, string ufrag, string pwd); - public void set_port_range (uint stream_id, uint component_id, uint min_port, uint max_port); - public bool set_relay_info (uint stream_id, uint component_id, string server_ip, uint server_port, string username, string password, Nice.RelayType type); - public int set_remote_candidates (uint stream_id, uint component_id, GLib.SList candidates); - public bool set_remote_credentials (uint stream_id, string ufrag, string pwd); - public bool set_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); - public bool set_selected_remote_candidate (uint stream_id, uint component_id, Nice.Candidate candidate); - [Version (since = "0.0.10")] - public void set_software (string software); - [Version (since = "0.1.4")] - public bool set_stream_name (uint stream_id, string name); - [Version (since = "0.0.9")] - public void set_stream_tos (uint stream_id, int tos); - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool bytestream_tcp { get; } - [NoAccessorMethod] - public uint compatibility { get; construct; } - [NoAccessorMethod] - public bool controlling_mode { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.14")] - public bool force_relay { get; set; } - [NoAccessorMethod] - public bool full_mode { get; construct; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool ice_tcp { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.16")] - public bool ice_trickle { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool ice_udp { get; set; } - [NoAccessorMethod] - [Version (since = "0.1.8")] - public bool keepalive_conncheck { get; set; } - [NoAccessorMethod] - public void* main_context { get; construct; } - [NoAccessorMethod] - public uint max_connectivity_checks { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_ip { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_password { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public uint proxy_port { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public uint proxy_type { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.4")] - public string proxy_username { owned get; set; } - [NoAccessorMethod] - [Version (since = "0.0.11")] - public bool reliable { get; construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_initial_timeout { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_max_retransmissions { get; set construct; } - [NoAccessorMethod] - public uint stun_pacing_timer { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.1.15")] - public uint stun_reliable_timeout { get; set construct; } - [NoAccessorMethod] - public string stun_server { owned get; set; } - [NoAccessorMethod] - public uint stun_server_port { get; set; } - [NoAccessorMethod] - public bool support_renomination { get; set; } - [NoAccessorMethod] - [Version (since = "0.0.7")] - public bool upnp { get; set construct; } - [NoAccessorMethod] - [Version (since = "0.0.7")] - public uint upnp_timeout { get; set construct; } - public signal void candidate_gathering_done (uint stream_id); - public signal void component_state_changed (uint stream_id, uint component_id, uint state); - public signal void initial_binding_request_received (uint stream_id); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_candidate (uint stream_id, uint component_id, string foundation); - [Version (since = "0.1.8")] - public signal void new_candidate_full (Nice.Candidate candidate); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_remote_candidate (uint stream_id, uint component_id, string foundation); - [Version (since = "0.1.8")] - public signal void new_remote_candidate_full (Nice.Candidate candidate); - [Version (deprecated = true, deprecated_since = "0.1.8")] - public signal void new_selected_pair (uint stream_id, uint component_id, string lfoundation, string rfoundation); - [Version (since = "0.1.8")] - public signal void new_selected_pair_full (uint stream_id, uint component_id, Nice.Candidate lcandidate, Nice.Candidate rcandidate); - [Version (since = "0.0.11")] - public signal void reliable_transport_writable (uint stream_id, uint component_id); - [Version (since = "0.1.5")] - public signal void streams_removed ([CCode (array_length = false, array_null_terminated = true)] uint[] stream_ids); - } - [CCode (cheader_filename = "nice.h", copy_function = "nice_candidate_copy", free_function = "nice_candidate_free")] - [Compact] - public class Candidate { - public Nice.Address addr; - public Nice.Address base_addr; - public uint component_id; - [CCode (array_length = false)] - public weak char foundation[33]; - public weak string password; - public uint32 priority; - public void* sockptr; - public uint stream_id; - public Nice.CandidateTransport transport; - public Nice.TurnServer turn; - public Nice.CandidateType type; - public weak string username; - [CCode (has_construct_function = false)] - public Candidate (Nice.CandidateType type); - public Nice.Candidate copy (); - [Version (since = "0.1.15")] - public bool equal_target (Nice.Candidate candidate2); - public void free (); - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - public struct Address { - [CCode (cname = "s.addr")] - public void* s_addr; - [CCode (cname = "s.ip4")] - public void* s_ip4; - [CCode (cname = "s.ip6")] - public void* s_ip6; - public void copy_to_sockaddr (void* sin); - public bool equal (Nice.Address b); - [Version (since = "0.1.8")] - public bool equal_no_port (Nice.Address b); - public void free (); - public uint get_port (); - public void init (); - public int ip_version (); - public bool is_private (); - public bool is_valid (); - public void set_from_sockaddr (void* sin); - public bool set_from_string (string str); - public void set_ipv4 (uint32 addr_ipv4); - public void set_ipv6 (uint8 addr_ipv6); - public void set_port (uint port); - public void to_string ([CCode (array_length = false, type = "gchar*")] char[] dst); - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - [Version (since = "0.1.5")] - public struct InputMessage { - [CCode (array_length_cname = "n_buffers")] - public weak GLib.InputVector[] buffers; - public int n_buffers; - public Nice.Address from; - public size_t length; - } - [CCode (cheader_filename = "nice.h", has_type_id = false)] - [Version (since = "0.1.5")] - public struct OutputMessage { - [CCode (array_length_cname = "n_buffers")] - public weak GLib.OutputVector[] buffers; - public int n_buffers; - } - [CCode (cheader_filename = "nice.h", cname = "TurnServer", has_type_id = false)] - public struct TurnServer { - public int ref_count; - public Nice.Address server; - public weak string username; - public weak string password; - public Nice.RelayType type; - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_AGENT_OPTION_", has_type_id = false)] - [Flags] - [Version (since = "0.1.15")] - public enum AgentOption { - REGULAR_NOMINATION, - RELIABLE, - LITE_MODE, - ICE_TRICKLE, - SUPPORT_RENOMINATION - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TRANSPORT_", has_type_id = false)] - public enum CandidateTransport { - UDP, - TCP_ACTIVE, - TCP_PASSIVE, - TCP_SO - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_CANDIDATE_TYPE_", has_type_id = false)] - public enum CandidateType { - HOST, - SERVER_REFLEXIVE, - PEER_REFLEXIVE, - RELAYED - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPATIBILITY_", has_type_id = false)] - public enum Compatibility { - RFC5245, - DRAFT19, - GOOGLE, - MSN, - WLM2009, - OC2007, - OC2007R2, - LAST - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_STATE_", has_type_id = false)] - public enum ComponentState { - DISCONNECTED, - GATHERING, - CONNECTING, - CONNECTED, - READY, - FAILED, - LAST; - [Version (since = "0.1.6")] - public unowned string to_string (); - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_COMPONENT_TYPE_", has_type_id = false)] - public enum ComponentType { - RTP, - RTCP - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_NOMINATION_MODE_", has_type_id = false)] - [Version (since = "0.1.15")] - public enum NominationMode { - REGULAR, - AGGRESSIVE - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_PROXY_TYPE_", has_type_id = false)] - [Version (since = "0.0.4")] - public enum ProxyType { - NONE, - SOCKS5, - HTTP, - LAST - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpDebugLevel", cprefix = "PSEUDO_TCP_DEBUG_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpDebugLevel { - NONE, - NORMAL, - VERBOSE - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpShutdown", cprefix = "PSEUDO_TCP_SHUTDOWN_", has_type_id = false)] - [Version (since = "0.1.8")] - public enum PseudoTcpShutdown { - RD, - WR, - RDWR - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpState", cprefix = "PSEUDO_TCP_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpState { - LISTEN, - SYN_SENT, - SYN_RECEIVED, - ESTABLISHED, - CLOSED, - FIN_WAIT_1, - FIN_WAIT_2, - CLOSING, - TIME_WAIT, - CLOSE_WAIT, - LAST_ACK - } - [CCode (cheader_filename = "nice.h", cname = "PseudoTcpWriteResult", cprefix = "WR_", has_type_id = false)] - [Version (since = "0.0.11")] - public enum PseudoTcpWriteResult { - SUCCESS, - TOO_LARGE, - FAIL - } - [CCode (cheader_filename = "nice.h", cprefix = "NICE_RELAY_TYPE_TURN_", has_type_id = false)] - public enum RelayType { - UDP, - TCP, - TLS - } - [CCode (cheader_filename = "nice.h", instance_pos = 4.9)] - public delegate void AgentRecvFunc (Nice.Agent agent, uint stream_id, uint component_id, [CCode (array_length_cname = "len", array_length_pos = 3.5, array_length_type = "guint", type = "gchar*")] uint8[] buf); - [CCode (cheader_filename = "nice.h", cname = "NICE_AGENT_MAX_REMOTE_CANDIDATES")] - public const int AGENT_MAX_REMOTE_CANDIDATES; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_ACTIVE")] - public const int CANDIDATE_DIRECTION_MS_PREF_ACTIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_DIRECTION_MS_PREF_PASSIVE")] - public const int CANDIDATE_DIRECTION_MS_PREF_PASSIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_MAX_FOUNDATION")] - public const int CANDIDATE_MAX_FOUNDATION; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_TCP")] - public const int CANDIDATE_TRANSPORT_MS_PREF_TCP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TRANSPORT_MS_PREF_UDP")] - public const int CANDIDATE_TRANSPORT_MS_PREF_UDP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_HOST")] - public const int CANDIDATE_TYPE_PREF_HOST; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_NAT_ASSISTED")] - public const int CANDIDATE_TYPE_PREF_NAT_ASSISTED; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_PEER_REFLEXIVE")] - public const int CANDIDATE_TYPE_PREF_PEER_REFLEXIVE; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED")] - public const int CANDIDATE_TYPE_PREF_RELAYED; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_RELAYED_UDP")] - public const int CANDIDATE_TYPE_PREF_RELAYED_UDP; - [CCode (cheader_filename = "nice.h", cname = "NICE_CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE")] - public const int CANDIDATE_TYPE_PREF_SERVER_REFLEXIVE; - [CCode (cheader_filename = "nice.h")] - public static void debug_disable (bool with_stun); - [CCode (cheader_filename = "nice.h")] - public static void debug_enable (bool with_stun); - [CCode (cheader_filename = "nice.h")] - public static string? interfaces_get_ip_for_interface (string interface_name); - [CCode (cheader_filename = "nice.h")] - public static GLib.List interfaces_get_local_interfaces (); - [CCode (cheader_filename = "nice.h")] - public static GLib.List interfaces_get_local_ips (bool include_loopback); - [CCode (cheader_filename = "nice.h", cname = "pseudo_tcp_set_debug_level")] - [Version (since = "0.0.11")] - public static void pseudo_tcp_set_debug_level (Nice.PseudoTcpDebugLevel level); -} diff --git a/plugins/meson.build b/plugins/meson.build index 8aa05215..3f804fcb 100644 --- a/plugins/meson.build +++ b/plugins/meson.build @@ -1,4 +1,3 @@ -subdir('ice') subdir('notification-sound') subdir('omemo') subdir('openpgp') diff --git a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala index 97674f3f..9cfb4afc 100644 --- a/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala +++ b/xmpp-vala/src/module/xep/0065_socks5_bytestreams.vala @@ -25,6 +25,10 @@ public class Module : XmppStreamModule, Iq.Handler { private GetLocalIpAddresses? get_local_ip_addresses_impl = null; + public Module.with_local_ip_address_handler(owned GetLocalIpAddresses get_local_ip_addresses) { + set_local_ip_address_handler((owned) get_local_ip_addresses); + } + public override void attach(XmppStream stream) { stream.add_flag(new Flag()); query_availability.begin(stream); diff --git a/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala b/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala index 200cdfa9..b59c1b06 100644 --- a/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala +++ b/xmpp-vala/src/module/xep/0177_jingle_raw_udp.vala @@ -13,6 +13,10 @@ namespace Xmpp.Xep.JingleRawUdp { private GetLocalIpAddresses? get_local_ip_addresses_impl = null; + public Module.with_local_ip_address_handler(owned GetLocalIpAddresses get_local_ip_addresses) { + set_local_ip_address_handler((owned) get_local_ip_addresses); + } + public override void attach(XmppStream stream) { stream.get_module(Jingle.Module.IDENTITY).register_transport(this); stream.get_module(ServiceDiscovery.Module.IDENTITY).add_feature(stream, NS_URI); -- cgit v1.3