commit 268b986bb98e22a3b2257649356f55a3f3b45e18 Author: Michael Date: Wed Sep 30 06:35:24 2026 -0400 Rust port of OmniVox, wire-compatible with the C++ original Byte-exact cereal binary layout, RFC 8439 ChaCha20-Poly1305, RFC 7914 scrypt defaults; tokio transport preserving the original's observable behavior (contract B1-B3, B5 quirks included). Parity evidence: golden C++ vectors in tests/vectors.rs and loopback behavior tests; both cross-directions verified against the unmodified C++ binaries. Source: https://git.0xfeedc0de.com/michael/OmniVox diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..171222e --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +/target +**/*.rs.bk +/opencode diff --git a/.opencode/MEMORY.md b/.opencode/MEMORY.md new file mode 100644 index 0000000..a0f3327 --- /dev/null +++ b/.opencode/MEMORY.md @@ -0,0 +1 @@ +2026-09-30 Repo split out of ~/gits/rust-skill (which still holds the C++ original in omnivox/ and build-ref/). PARITY-CONTRACT.md normative; quirks B1/B2/B3/B5 preserved on purpose. Golden vectors: C++ oracles in tests/vectors.txt (regenerate via reference/README.md). Gotchas: tokio 1.53 uses Owned{Read,Write}Half via into_split (no IO through Arc); disconnect must actively shutdown the writer Option (Arc kept alive by read task). No unsafe. Not yet pushed to a remote. diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..94bdc0f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,639 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "rand_core", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "inout" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" +dependencies = [ + "generic-array", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.189" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "mio" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b18443e9c262bfe8fa82f51666e2642c53393f7e5c27b3e1aeab922cff5b9d8" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "omnivox" +version = "0.13.0" +dependencies = [ + "chacha20poly1305", + "getrandom 0.3.4", + "scrypt", + "thiserror", + "tokio", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "opaque-debug" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "password-hash" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "346f04948ba92c43e8469c1ee6736c7563d71012b17d40745260fe106aac2166" +dependencies = [ + "base64ct", + "rand_core", + "subtle", +] + +[[package]] +name = "pbkdf2" +version = "0.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" +dependencies = [ + "digest", + "hmac", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "salsa20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97a22f5af31f73a954c10289c93e8a50cc23d971e80ee446f1f6f7137a088213" +dependencies = [ + "cipher", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "scrypt" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0516a385866c09368f0b5bcd1caff3366aace790fcd46e2bb032697bb172fd1f" +dependencies = [ + "password-hash", + "pbkdf2", + "salsa20", + "sha2", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "smallvec" +version = "1.16.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9395f0f0eee849a9b707b2f06bb92a6a422090e2123bb2ef8e87a0e61892a8e" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8593e8e72159ed2257d083c7a454a85cbf854f37a0966d8d483aff8c8a3ebcee" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tokio" +version = "1.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.6", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "nu-ansi-term", + "sharded-slab", + "smallvec", + "thread_local", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "zeroize" +version = "1.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a7f6320 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "omnivox" +version = "0.13.0" +edition = "2024" +license = "GPL-3.0-or-later" +description = "Encrypted async TCP client-server messaging (ChaCha20-Poly1305), Rust port of the OmniVox C++ library" + +[dependencies] +chacha20poly1305 = "0.10" +getrandom = "0.3" +scrypt = "0.11" +thiserror = "2" +tokio = { version = "1", features = ["rt-multi-thread", "net", "io-util", "time", "sync", "macros"] } +tracing = "0.1" + +[dev-dependencies] +tracing-subscriber = { version = "0.3", features = ["fmt"] } +tokio = { version = "1", features = ["full"] } \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program 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 General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/PARITY-CONTRACT.md b/PARITY-CONTRACT.md new file mode 100644 index 0000000..c225760 --- /dev/null +++ b/PARITY-CONTRACT.md @@ -0,0 +1,84 @@ +# OmniVox Port — Parity Contract + +Source: `omnivox/` (C++17/20, asio + cereal + CryptoPP + fmt) +Target: `omnivox-rs/` (Rust, tokio + RustCrypto) +End state: **A — replacement.** Rust crate + example binaries ship; C++ deleted at cut-over. +Seam: **the TCP network boundary.** C++ and Rust must interoperate byte-for-byte at any mix. + +## Unit of parity + +The byte stream on the wire at the TCP boundary, and the callbacks the library +delivers to the application (connect / data / disconnect with their context). + +## Wire format (recovered — this is normative) + +All integers little-endian (x86 native memcpy/cereal, never htonl'd anywhere). + +- Framing: `u32` payload-length prefix, then that many bytes. Read in two + async steps (header, then body) with separate timeouts. +- `AeadPacket` (cereal binary archive = raw fields, no magic/header): + `nonce[12] || tag[16] || u64 len || ciphertext[len]` +- `DatagramPayload`: `u16 id || u64 qword || u64 len || bytes[len]` +- AEAD: ChaCha20-Poly1305 per RFC 8439 (CryptoPP impl is RFC-conformant). + No AAD. Random 12-byte nonce per message (`AutoSeededRandomPool`). +- Key: scrypt per RFC 7914, `N=2^17, r=8, p=1, dkLen=32`, passphrase = raw + password bytes, salt = raw salt bytes. Both peers must set the identical key. + +## Not acceptable (any difference = regression) + +- Any wire byte: framing, field layout, key derivation, AEAD construction. +- Tamper behavior: `DecryptAndVerify` failure → message dropped, error logged, + **connection stays open** (exception caught in processMessage). +- Limits: `MAX_MESSAGE_SIZE = 5 MiB`; header `0` or `> 5 MiB` → log + disconnect. +- Timeouts: per-message header-wait = `timeoutMs` (server, per client arg); + body stall = 5000 ms fixed. Server per-client stall timers; **client side has + no timers** (ctx.id == serverContext.id path). +- Client IDs: server assigns from 1, monotonic (`nextClientId`), visible in + `ConnectionContext.id`. +- Callback order on accept: allow → client registered & reading before the + connect log; deny → socket closed, disconnect callback fires. +- `sendToServer` returns false unless socket open **and** status Connected; + `sendToClient` returns false if id unknown. +- Malformed/undecryptable message: logged, skipped, connection survives. + +## Acceptable (do not chase) + +- Log text, wording, timestamps; steady-clock `creationTime` values. +- Thread structure (pool + io_context → tokio tasks); task scheduling. +- **Message processing order**: C++ server processes on a worker pool and can + reorder concurrent messages; Rust may differ in interleaving. Per-connection + stream order must still be preserved. +- Exact race outcomes under B1/B3 below (timing-dependent in C++ itself). +- TCP_NODELAY: C++ leaves Nagle ON (`NODELAY_OPT` never defined); Rust matches + default. Never observable in payload bytes. + +## Bug/quirk inventory — preserved, NOT fixed (fixes = separate commits after parity) + +| # | Source | Behaviour | Port decision | +|---|--------|-----------|---------------| +| B1 | OmniVox.h:914 | Bad header size logs + `handleDisconnect` **without returning** — proceeds to read a body of that size (0-byte read succeeds and processes an empty packet → decrypt error logged) | Preserve: disconnect + best-effort body read; races allowed | +| B2 | OmniVox.h:990 | Decrypt/parse errors are swallowed (log only), connection kept | Preserve | +| B3 | OmniVox.h:630 | `sendToClient` does a **blocking** `asio::write` while holding the clients lock | Rust holds the connection write lock across the full write; log as follow-up improvement | +| B4 | OmniVox.h:960 | Processing on thread pool → concurrent reordering | Acceptable-difference above | +| B5 | OmniVox.h:869 | Client mode never arms stall timers | Preserve | +| B6 | OmniVox.h:782 | `timeoutCheckerThread`/`timeoutCheckerRunning` — dead code, never started | **Not ported** (dead) | +| B7 | OmniVox.h:99 | `inline std::optional` global — shadowed by member, dead | **Not ported** (dead) | +| B8 | client.cpp:101 | Client sleeps 15 s then stops; server sleeps `UINT32_MAX` hours | Examples mirror this | + +## Deliberately not ported + +B6/B7 dead code; the cereal/cryptopp/asio vendored trees; `PackedValue64` union +(only `.qword` is ever serialized → port as `u64` field on `DatagramPayload`); +`ThreadPool_` as a class (tokio replaces it; do not transliterate). + +## Verification (how parity is proven) + +1. **Vector tests**: golden `scrypt` + cereal-layout + AEAD vectors generated + by C++ (`cppgen` helper in `omnivox-ref/`) checked into `tests/vectors/`. +2. **Differential cross-tests over loopback**: C++ server ↔ Rust client, + Rust server ↔ C++ client — echo handshake must round-trip. +3. **Tamper test**: flip a ciphertext byte mid-stream → receiver logs and + survives. +4. Differential harness reports inputs-compared and differences-found. + +`cargo test --all-features && cargo clippy --all-targets --all-features && cargo fmt --check` \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..8e6e6a8 --- /dev/null +++ b/README.md @@ -0,0 +1,57 @@ +# omnivox-rs + +Rust port of [OmniVox](https://git.0xfeedc0de.com/michael/OmniVox), a +templated encrypted TCP client-server library — **wire-compatible +byte-for-byte** with the original C++ implementation. A Rust client talks +to a C++ server and vice versa. + +- Async TCP built on tokio +- ChaCha20-Poly1305 authenticated encryption (RFC 8439) +- scrypt key derivation (RFC 7914, `N = 2^17, r = 8, p = 1`) +- Byte-exact cereal `BinaryOutputArchive` field layout +- Zero `unsafe` + +## Wire format + +Framing is a `u32` little-endian length prefix. Each message is a +`AeadPacket`: `nonce[12] || tag[16] || u64 len || ciphertext`. Payloads +implement the `Cereal` trait, which reproduces cereal's raw-LE field +encoding (see `PARITY-CONTRACT.md` for the normative spec). + +## Usage + +```rust +use omnivox::{OmniVox, Cereal, CodecError, Decision, derive_encrypt_key}; +``` + +Create an `OmniVox` where `T: Cereal`, set the key (both peers must +agree), then use `start_server` / `connect_to_server` / `send_to_client` +/ `send_to_server`. Runnable ports of the original demo apps live in +`examples/`. + +## Parity + +`PARITY-CONTRACT.md` is the definition of done: it names the unit of +parity, the accepted differences, and the original's quirks this port +deliberately preserves (B1–B3, B5) rather than silently fixing. Parity +evidence: + +- `tests/vectors.rs` — golden vectors generated by the C++ CryptoPP + + cereal stack (`reference/cppgen.cpp`); keys, serialization bytes, and + AEAD ciphertext/tags must match exactly. +- `tests/loopback.rs` — runtime behavior clauses of the contract. +- Differential cross-tests: this crate's binaries were verified talking + to the unmodified C++ binaries in both directions over loopback. + +## Build & test + +```bash +cargo test # note: the scrypt vectors use N=2^17 (~1 s, 128 MiB per derivation) +cargo clippy --all-targets +cargo run --example omnivox-server # terminal 1 +cargo run --example omnivox-client # terminal 2 +``` + +## License + +GPL-3.0-or-later, matching the original OmniVox. \ No newline at end of file diff --git a/examples/common/mod.rs b/examples/common/mod.rs new file mode 100644 index 0000000..9e657c3 --- /dev/null +++ b/examples/common/mod.rs @@ -0,0 +1,37 @@ +//! Port of the C++ `common.h`: shared payload type and demo constants. + +use omnivox::{Cereal, CodecError, Reader, write_byte_vec}; + +/// Wire-identical to the C++ `DatagramPayload` (cereal field order: +/// `id`, `v1.qword`, `payload`; the `PackedValue64` union only ever +/// serialized its `qword`, so it ports as a plain `u64`). +#[derive(Debug, Default)] +pub struct DatagramPayload { + pub id: u16, + pub v1: u64, + pub payload: Vec, +} + +impl Cereal for DatagramPayload { + fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&self.id.to_le_bytes()); + out.extend_from_slice(&self.v1.to_le_bytes()); + write_byte_vec(out, &self.payload); + } + + fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + Ok(Self { + id: r.u16()?, + v1: r.u64()?, + payload: r.byte_vec()?, + }) + } +} + +pub const PASSWORD: &str = "SecurePassword123"; +pub const SALT: &[u8] = &[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08]; +pub const SERVER_PORT: u16 = 8080; +/// Only used by the client example. +#[allow(dead_code)] +pub const SERVER_ADDR: &str = "127.0.0.1"; diff --git a/examples/omnivox-client.rs b/examples/omnivox-client.rs new file mode 100644 index 0000000..d7ddc1f --- /dev/null +++ b/examples/omnivox-client.rs @@ -0,0 +1,71 @@ +//! Port of OmniVox-client.cpp: connects, sends "Hello", prints what the +//! server echoes, then stops after 15 seconds like the C++ example. + +#[path = "common/mod.rs"] +mod common; + +use common::{DatagramPayload, PASSWORD, SALT, SERVER_ADDR, SERVER_PORT}; +use omnivox::{ConnectionContext, ConnectionStatus, OmniVox, derive_encrypt_key}; +use std::sync::Arc; + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt() + .with_target(false) + .without_time() + .init(); + + tracing::info!("Connecting to server at {SERVER_ADDR}:{SERVER_PORT}"); + + let client = Arc::new(OmniVox::::new()); + let key = derive_encrypt_key(PASSWORD.as_bytes(), SALT, 17, 8, 1)?; + client.set_encrypt_key(key); + + let data_cb = Arc::new(|_data: &DatagramPayload, ctx: &ConnectionContext| { + tracing::info!("Server ID: {}, sent data!", ctx.id); + }); + + let connector = Arc::clone(&client); + let connection_cb = Arc::new(move |ctx: &ConnectionContext| match ctx.connected { + ConnectionStatus::Connected => { + tracing::info!( + "[onConnect] Successfully connected to: {}:{}", + ctx.ip, + ctx.port + ); + let client = Arc::clone(&connector); + tokio::spawn(async move { + let payload = DatagramPayload { + id: 1, + v1: 0, + payload: b"Hello".to_vec(), + }; + if client.send_to_server(&payload).await { + tracing::info!("Sent initial data to server"); + } + }); + } + ConnectionStatus::ConnectionFailed => { + tracing::info!( + "[onConnect] Connection failed or timed out to: {}:{}", + ctx.ip, + ctx.port + ); + } + _ => { + tracing::info!( + "[onConnect] Unexpected connection status to: {}:{}", + ctx.ip, + ctx.port + ); + } + }); + + client + .connect_to_server(SERVER_ADDR, SERVER_PORT, Some(data_cb), connection_cb) + .await?; + + tokio::time::sleep(std::time::Duration::from_secs(15)).await; + client.stop().await; + Ok(()) +} diff --git a/examples/omnivox-server.rs b/examples/omnivox-server.rs new file mode 100644 index 0000000..9ace2f4 --- /dev/null +++ b/examples/omnivox-server.rs @@ -0,0 +1,89 @@ +//! Port of OmniVox-server.cpp: echoes each client payload back with the +//! client id, refusing no client that holds the key. + +#[path = "common/mod.rs"] +mod common; + +use common::{DatagramPayload, PASSWORD, SALT, SERVER_PORT}; +use omnivox::{ConnectionContext, Decision, OmniVox, derive_encrypt_key}; +use std::{ + collections::HashMap, + sync::{Arc, Mutex}, +}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + tracing_subscriber::fmt() + .with_target(false) + .without_time() + .init(); + + tracing::info!("Starting server on port {SERVER_PORT} with 2 threads"); + + let server = Arc::new(OmniVox::::new()); + let key = derive_encrypt_key(PASSWORD.as_bytes(), SALT, 17, 8, 1)?; + server.set_encrypt_key(key); + + // The C++ example's g_clientHalt map, kept for behavioral parity. + let client_halt: Arc>> = Arc::new(Mutex::new(HashMap::new())); + + let responder = Arc::clone(&server); + let received = Arc::new(move |data: &DatagramPayload, ctx: &ConnectionContext| { + tracing::info!( + "Received data from client {}: Payload size={}", + ctx.id, + data.payload.len() + ); + if !data.payload.is_empty() { + tracing::info!( + "Payload content: {}", + String::from_utf8_lossy(&data.payload) + ); + } + let response = DatagramPayload { + id: ctx.id as u16, + v1: 0, + payload: data.payload.clone(), + }; + let server = Arc::clone(&responder); + let id = ctx.id; + // C++ echoed synchronously inside the callback; the Rust callback is + // sync, so the echo rides a task — per-connection socket order is + // still serialized by the client's write lock (contract B3). + tokio::spawn(async move { + if server.send_to_client(&response, id).await { + tracing::info!("Sent response to client {id}"); + } else { + tracing::info!("Error sending data to client {id}"); + } + }); + }); + + let halt = Arc::clone(&client_halt); + let disconnect = Arc::new(move |ctx: &ConnectionContext| { + tracing::info!( + "Client {} {}:{} is disconnecting from the server cleaning up objects.", + ctx.id, + ctx.ip, + ctx.port + ); + *halt.lock().unwrap().entry(ctx.id).or_default() = true; + }); + + let halt = Arc::clone(&client_halt); + let connect = Arc::new(move |ctx: &ConnectionContext| { + *halt.lock().unwrap().entry(ctx.id).or_default() = false; + tracing::info!("New client has connected - {}:{}", ctx.ip, ctx.port); + Decision::Allow + }); + + server + .start_server(SERVER_PORT, 2, 15000, received, disconnect, connect) + .await?; + + tracing::info!("Server started successfully"); + + // C++ slept u32::MAX hours; we serve until killed, like the reference. + std::future::pending::<()>().await; + Ok(()) +} diff --git a/reference/README.md b/reference/README.md new file mode 100644 index 0000000..64a2002 --- /dev/null +++ b/reference/README.md @@ -0,0 +1,11 @@ +Provenance of the golden vectors in tests/vectors.txt. + +Generate with (from a checkout of the original C++ OmniVox tree, which provides common.h, include/, cereal/, asio/, cryptopp/; requires libcryptopp.a and system fmt): + + g++ -std=c++20 -O1 -DDEBUG -I -I/include \ + -I/cereal/include -I/asio/include -I/cryptopp \ + $(pkg-config --cflags fmt) reference/cppgen.cpp \ + /cryptopp/libcryptopp.a $(pkg-config --libs fmt) -lpthread + +The scrypt derivations take ~1 s and 128 MiB each. Any change to these +bytes means the Rust port has regressed against the original. diff --git a/reference/cppgen.cpp b/reference/cppgen.cpp new file mode 100644 index 0000000..baf4e7a --- /dev/null +++ b/reference/cppgen.cpp @@ -0,0 +1,73 @@ +// Golden-vector generator for the Rust port. Output is normative. +#include "common.h" +#include +#include + +static std::string hex(const uint8_t* p, size_t n) { + std::ostringstream os; os << std::hex << std::setfill('0'); + for (size_t i = 0; i < n; i++) os << std::setw(2) << (int)p[i]; + return os.str(); +} +static std::string hexv(const std::vector& v) { return hex(v.data(), v.size()); } + +int main() { + // 1. scrypt key derivation (default params N=2^17 r=8 p=1) + OmniVox vox; + std::vector pw(g_sPassword.begin(), g_sPassword.end()); + auto key = vox.deriveEncryptKey(pw, g_vecSalt); + std::cout << "scrypt_key=" << hex(key.data(), key.size()) << "\n"; + + // extra scrypt vector: known short inputs + std::vector pw2{'p','a','s','s'}, salt2{'s','a','l','t'}; + auto key2 = vox.deriveEncryptKey(pw2, salt2); + std::cout << "scrypt_key2=" << hex(key2.data(), key2.size()) << "\n"; + + vox.setEncryptKey(key); + + // 2. cereal byte layouts + DatagramPayload dp; + dp.id = 0x1234; dp.v1.qword = 0x1122334455667788ULL; + dp.payload = {'H','e','l','l','o'}; + std::cout << "cereal_datagram=" << hexv(serializeObject(dp)) << "\n"; + DatagramPayload dp0; // all defaults + std::cout << "cereal_datagram_default=" << hexv(serializeObject(dp0)) << "\n"; + + AeadPacket ap{}; + for (int i = 0; i < 12; i++) ap.nonce[i] = (uint8_t)i; + for (int i = 0; i < 16; i++) ap.tag[i] = (uint8_t)(0xA0 + i); + ap.payload = {0xDE, 0xAD, 0xBE, 0xEF}; + std::cout << "cereal_aead=" << hexv(serializeObject(ap)) << "\n"; + AeadPacket ap0{}; + std::cout << "cereal_aead_empty=" << hexv(serializeObject(ap0)) << "\n"; + + // 3. AEAD vectors: fixed nonce, CryptoPP as the oracle + auto vec = [](std::string s){ return std::vector(s.begin(), s.end()); }; + { + auto pkt = vox.encrypt(vec("Hello")); // random nonce: structure check only + std::cout << "aead_random_payloadlen=" << pkt.payload.size() << "\n"; + } + // deterministic: set key, encrypt with forced nonce by round-tripping through + // a fresh object whose rng we can't seed... instead use Crypto++ directly. + { + CryptoPP::ChaCha20Poly1305::Encryption enc; + uint8_t nonce[12] = {0,1,2,3,4,5,6,7,8,9,10,11}; + enc.SetKeyWithIV(key.data(), key.size(), nonce, 12); + std::string pt = "Hello"; + std::vector ct(pt.size()), tag(16); + enc.EncryptAndAuthenticate(ct.data(), tag.data(), 16, nonce, 12, + nullptr, 0, + (const unsigned char*)pt.data(), pt.size()); + std::cout << "aead_ct=" << hexv(ct) << "\n"; + std::cout << "aead_tag=" << hex(tag.data(), 16) << "\n"; + } + { + CryptoPP::ChaCha20Poly1305::Encryption enc; + uint8_t nonce[12] = {0,1,2,3,4,5,6,7,8,9,10,11}; + enc.SetKeyWithIV(key.data(), key.size(), nonce, 12); + std::vector ct(0), tag(16); + enc.EncryptAndAuthenticate(ct.data(), tag.data(), 16, nonce, 12, + nullptr, 0, (const unsigned char*)"", 0); + std::cout << "aead_empty_tag=" << hex(tag.data(), 16) << "\n"; + } + return 0; +} \ No newline at end of file diff --git a/reference/vectors.txt b/reference/vectors.txt new file mode 100644 index 0000000..0b288ef --- /dev/null +++ b/reference/vectors.txt @@ -0,0 +1,10 @@ +scrypt_key=f64f4c05eb28676be5e4dd760c7f9409327a47e11abb66adc593b2bd039a0650 +scrypt_key2=f21278eee02abf1ad982428b5ab5d1ffccb62f6f1163dc616bfe30686e143ea0 +cereal_datagram=34128877665544332211050000000000000048656c6c6f +cereal_datagram_default=000000000000000000000000000000000000 +cereal_aead=000102030405060708090a0ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf0400000000000000deadbeef +cereal_aead_empty=000000000000000000000000000000000000000000000000000000000000000000000000 +aead_random_payloadlen=5 +aead_ct=3e3c330d3b +aead_tag=89c6b5d2dbc9d3f7c82c12825f992c49 +aead_empty_tag=791eac80a87ddffcf45d6bad2769ea04 diff --git a/src/codec.rs b/src/codec.rs new file mode 100644 index 0000000..73638d3 --- /dev/null +++ b/src/codec.rs @@ -0,0 +1,147 @@ +//! Byte-exact codec for the cereal `BinaryOutputArchive` wire format. +//! +//! cereal writes raw little-endian fields with no header or magic: +//! PODs as native LE bytes, fixed arrays as raw bytes, and +//! `std::vector`/`std::string` as a `size_t` (u64) length followed by the +//! bytes. Trailing bytes after the last field are ignored on read, exactly +//! as cereal's stream reads ignore them. + +use thiserror::Error; + +/// Errors produced while decoding cereal-encoded bytes. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum CodecError { + /// Input ended before all fields were read. + #[error("unexpected end of input at byte {offset} of {len}")] + UnexpectedEof { offset: usize, len: usize }, + /// A vector length prefix exceeded the remaining input. + #[error("vector length {declared} exceeds remaining input {available}")] + LengthOverflow { declared: u64, available: usize }, +} + +/// A type with a byte-exact cereal binary representation. +/// +/// Implementations must write exactly the same bytes cereal's +/// `BinaryOutputArchive` would write for the equivalent C++ `serialize` +/// function, in field order. +pub trait Cereal { + /// Appends this value's cereal encoding to `out`. + fn encode(&self, out: &mut Vec); + + /// Decodes a value, ignoring any trailing bytes. + fn decode(bytes: &[u8]) -> Result + where + Self: Sized; +} + +/// Streaming reader over a byte slice, little-endian. +pub struct Reader<'a> { + bytes: &'a [u8], + pos: usize, +} + +impl<'a> Reader<'a> { + pub fn new(bytes: &'a [u8]) -> Self { + Self { bytes, pos: 0 } + } + + pub fn take(&mut self) -> Result<[u8; N], CodecError> { + let end = self.pos + N; + if end > self.bytes.len() { + return Err(CodecError::UnexpectedEof { + offset: self.pos, + len: self.bytes.len(), + }); + } + let mut out = [0u8; N]; + out.copy_from_slice(&self.bytes[self.pos..end]); + self.pos = end; + Ok(out) + } + + pub fn u16(&mut self) -> Result { + Ok(u16::from_le_bytes(self.take()?)) + } + + pub fn u32(&mut self) -> Result { + Ok(u32::from_le_bytes(self.take()?)) + } + + pub fn u64(&mut self) -> Result { + Ok(u64::from_le_bytes(self.take()?)) + } + + /// Reads a cereal `std::vector`: u64 length, then bytes. + pub fn byte_vec(&mut self) -> Result, CodecError> { + let declared = self.u64()?; + let available = self.bytes.len() - self.pos; + let len = usize::try_from(declared).map_err(|_| CodecError::LengthOverflow { + declared, + available, + })?; + if len > available { + return Err(CodecError::LengthOverflow { + declared, + available, + }); + } + let out = self.bytes[self.pos..self.pos + len].to_vec(); + self.pos += len; + Ok(out) + } +} + +/// Pushes a cereal `std::vector`: u64 LE length, then bytes. +pub fn write_byte_vec(out: &mut Vec, bytes: &[u8]) { + out.extend_from_slice(&(bytes.len() as u64).to_le_bytes()); + out.extend_from_slice(bytes); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reader_matches_cereal_field_layout() { + // 3412 8877665544332211 0500000000000000 48656c6c6f + // (golden: cereal_datagram from tests/vectors.txt) + let bytes = [ + 0x34, 0x12, 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11, 0x05, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x48, 0x65, 0x6c, 0x6c, 0x6f, + ]; + let mut r = Reader::new(&bytes); + assert_eq!(r.u16().unwrap(), 0x1234); + assert_eq!(r.u64().unwrap(), 0x1122334455667788); + assert_eq!(r.byte_vec().unwrap(), b"Hello"); + } + + #[test] + fn trailing_bytes_are_ignored() { + let mut bytes = vec![0x01, 0x00]; + bytes.extend_from_slice(b"junk"); + let mut r = Reader::new(&bytes); + assert_eq!(r.u16().unwrap(), 1); + } + + #[test] + fn truncated_input_errors() { + let mut r = Reader::new(&[0x01]); + assert!(matches!( + r.u16(), + Err(CodecError::UnexpectedEof { offset: 0, len: 1 }) + )); + } + + #[test] + fn lying_length_prefix_errors_instead_of_allocating() { + let mut bytes = Vec::new(); + write_byte_vec(&mut bytes, b"hi"); + let declared = u64::MAX; + bytes[..8].copy_from_slice(&declared.to_le_bytes()); + let mut r = Reader::new(&bytes); + assert!(matches!( + r.byte_vec(), + Err(CodecError::LengthOverflow { .. }) + )); + } +} diff --git a/src/crypto.rs b/src/crypto.rs new file mode 100644 index 0000000..b5ade1e --- /dev/null +++ b/src/crypto.rs @@ -0,0 +1,138 @@ +//! Authenticated encryption recovered from the C++ CryptoPP usage: +//! scrypt key derivation (RFC 7914) and ChaCha20-Poly1305 (RFC 8439), +//! byte-compatible with CryptoPP's `Scrypt` and `ChaCha20Poly1305`. + +use chacha20poly1305::{ + AeadInPlace, ChaCha20Poly1305, Key, KeyInit, aead::generic_array::GenericArray, +}; +use thiserror::Error; + +use crate::codec::{Cereal, CodecError, Reader, write_byte_vec}; + +/// 256-bit ChaCha20-Poly1305 key. +pub const KEY_LEN: usize = 32; +/// 96-bit IETF nonce. +pub const NONCE_LEN: usize = 12; +/// 128-bit Poly1305 tag. +pub const TAG_LEN: usize = 16; + +/// scrypt cost parameter used by the C++ default (N = 2^17). +pub const SCRYPT_LOG_N: u8 = 17; +/// scrypt block size used by the C++ default. +pub const SCRYPT_R: u32 = 8; +/// scrypt parallelism used by the C++ default. +pub const SCRYPT_P: u32 = 1; + +/// Errors from key derivation or AEAD operations. +#[derive(Debug, Error, PartialEq, Eq)] +pub enum CryptoError { + /// C++ threw `std::invalid_argument`; carried as an error instead. + #[error("Passphrase and salt must be non-empty")] + EmptyInput, + /// The C++ port of `DecryptAndVerify` returning false. + #[error("Authentication failed: message has been tampered with")] + AuthenticationFailed, + #[error("scrypt parameters rejected: {0}")] + ScryptParams(String), +} + +/// Derives a ChaCha20 key from a passphrase and salt with scrypt. +/// +/// Matches CryptoPP `Scrypt::DeriveKey(key, 32, passphrase, salt, N, r, p)` +/// with the C++ defaults `N = 2^17, r = 8, p = 1`. +/// +/// # Errors +/// +/// [`CryptoError::EmptyInput`] if either input is empty, or +/// [`CryptoError::ScryptParams`] if the parameters are rejected. +pub fn derive_encrypt_key( + passphrase: &[u8], + salt: &[u8], + log_n: u8, + r: u32, + p: u32, +) -> Result<[u8; KEY_LEN], CryptoError> { + if passphrase.is_empty() || salt.is_empty() { + return Err(CryptoError::EmptyInput); + } + let params = scrypt::Params::new(log_n, r, p, KEY_LEN) + .map_err(|e| CryptoError::ScryptParams(e.to_string()))?; + let mut key = [0u8; KEY_LEN]; + scrypt::scrypt(passphrase, salt, ¶ms, &mut key) + .map_err(|e| CryptoError::ScryptParams(e.to_string()))?; + Ok(key) +} + +/// An encrypted message on the wire: nonce, detached tag, ciphertext. +/// +/// Serializes in cereal byte order: `nonce[12] || tag[16] || u64 len || payload`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AeadPacket { + pub nonce: [u8; NONCE_LEN], + pub tag: [u8; TAG_LEN], + pub payload: Vec, +} + +impl Cereal for AeadPacket { + fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&self.nonce); + out.extend_from_slice(&self.tag); + write_byte_vec(out, &self.payload); + } + + fn decode(bytes: &[u8]) -> Result { + let mut r = Reader::new(bytes); + Ok(Self { + nonce: r.take()?, + tag: r.take()?, + payload: r.byte_vec()?, + }) + } +} + +/// Encrypts `plaintext` with a fresh random 96-bit nonce and no AAD, +/// matching the C++ `encrypt` (CryptoPP `EncryptAndAuthenticate`). +pub fn encrypt(key: &[u8; KEY_LEN], plaintext: &[u8]) -> AeadPacket { + let mut nonce = [0u8; NONCE_LEN]; + getrandom::fill(&mut nonce).expect("OS RNG failure"); + encrypt_with_nonce(key, &nonce, plaintext) +} + +/// Deterministic variant for tests; production traffic uses [`encrypt`]. +pub fn encrypt_with_nonce( + key: &[u8; KEY_LEN], + nonce: &[u8; NONCE_LEN], + plaintext: &[u8], +) -> AeadPacket { + let cipher = ChaCha20Poly1305::new(Key::from_slice(key)); + let mut payload = plaintext.to_vec(); + let tag = cipher + .encrypt_in_place_detached(GenericArray::from_slice(nonce), b"", &mut payload) + .expect("ChaCha20Poly1305 detached encryption is infallible"); + let mut packet_tag = [0u8; TAG_LEN]; + packet_tag.copy_from_slice(tag.as_slice()); + AeadPacket { + nonce: *nonce, + tag: packet_tag, + payload, + } +} + +/// Decrypts and verifies a packet. +/// +/// # Errors +/// +/// [`CryptoError::AuthenticationFailed`] if the tag does not verify. +pub fn decrypt(key: &[u8; KEY_LEN], packet: &AeadPacket) -> Result, CryptoError> { + let cipher = ChaCha20Poly1305::new(Key::from_slice(key)); + let mut payload = packet.payload.clone(); + cipher + .decrypt_in_place_detached( + GenericArray::from_slice(&packet.nonce), + b"", + &mut payload, + GenericArray::from_slice(&packet.tag), + ) + .map_err(|_| CryptoError::AuthenticationFailed)?; + Ok(payload) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..b6fc16c --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,618 @@ +//! OmniVox — encrypted async TCP client/server messaging. +//! +//! Rust port of the OmniVox C++ library, wire-compatible byte-for-byte with +//! the original (framing, cereal field layout, scrypt + ChaCha20-Poly1305). +//! See `PARITY-CONTRACT.md` at the workspace root for the normative spec, +//! including the quirks this port deliberately preserves (B1, B2, B5). +//! +//! # Example +//! +//! ```no_run +//! use omnivox::{Cereal, CodecError, ConnectionContext, Decision, OmniVox, OmniVoxError}; +//! use std::sync::Arc; +//! +//! #[derive(Default)] +//! struct Ping; +//! +//! impl Cereal for Ping { +//! fn encode(&self, out: &mut Vec) { out.push(1); } +//! fn decode(_: &[u8]) -> Result { Ok(Ping) } +//! } +//! +//! # async fn run() -> Result<(), OmniVoxError> { +//! let server = Arc::new(OmniVox::::new()); +//! server.set_encrypt_key([7u8; 32]); +//! server +//! .start_server( +//! 8080, +//! 2, +//! 15000, +//! Arc::new(|_data: &Ping, _ctx: &ConnectionContext| {}), +//! Arc::new(|_ctx| {}), +//! Arc::new(|_ctx| Decision::Allow), +//! ) +//! .await?; +//! # Ok(()) } +//! ``` + +mod codec; +mod crypto; + +pub use codec::{Cereal, CodecError, Reader, write_byte_vec}; +pub use crypto::{ + AeadPacket, CryptoError, KEY_LEN, NONCE_LEN, SCRYPT_LOG_N, SCRYPT_P, SCRYPT_R, TAG_LEN, + decrypt, derive_encrypt_key, encrypt, encrypt_with_nonce, +}; + +use std::{ + collections::HashMap, + net::SocketAddr, + sync::{ + Arc, Mutex, OnceLock, + atomic::{AtomicBool, AtomicU32, Ordering}, + }, + time::{SystemTime, UNIX_EPOCH}, +}; + +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::{ + TcpListener, TcpStream, + tcp::{OwnedReadHalf, OwnedWriteHalf}, + }, + sync::Mutex as AsyncMutex, + task::JoinHandle, + time::{Duration, timeout}, +}; +use tracing::{error, info}; + +/// 5 MiB per-message allocation cap, matching `MAX_MESSAGE_SIZE`. +pub const MAX_MESSAGE_SIZE: u32 = 1024 * 1024 * 5; +/// Fixed body-read stall cap, matching `MAX_TIMEOUT_STALL_MS`. +pub const MAX_TIMEOUT_STALL_MS: u64 = 5000; + +/// State of a connection, matching the C++ `ConnectionStatus`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ConnectionStatus { + NotConnected, + Connected, + ConnectionFailed, + Rejected, +} + +/// Per-connection metadata handed to every callback. +/// +/// `total_sent` mirrors the C++ `iTotalSent`, which the original never +/// increments; it is preserved as always-zero for parity. +#[derive(Debug, Clone)] +pub struct ConnectionContext { + pub connected: ConnectionStatus, + pub id: u32, + pub total_sent: usize, + pub creation_time: u64, + pub ip: String, + pub port: u16, +} + +impl ConnectionContext { + fn unknown(host: &str, port: u16) -> Self { + Self { + connected: ConnectionStatus::ConnectionFailed, + id: 0, + total_sent: 0, + creation_time: 0, + ip: host.to_owned(), + port, + } + } +} + +/// Server-side accept decision, matching `ConnectionDecision`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Decision { + Allow, + Deny, +} + +pub type DataHandler = Arc; +pub type ConnHandler = Arc; +pub type DecisionHandler = Arc Decision + Send + Sync + 'static>; + +/// Library errors surfaced from setup calls. Runtime message failures are +/// logged and swallowed, matching the C++ exception swallowing (contract B2). +#[derive(Debug, thiserror::Error)] +pub enum OmniVoxError { + #[error(transparent)] + Io(#[from] std::io::Error), + #[error(transparent)] + Crypto(#[from] CryptoError), + #[error("already started")] + AlreadyStarted, +} + +fn now_micros() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_micros() as u64) + .unwrap_or(0) +} + +struct ClientHandle { + /// Held across the full frame write, mirroring the C++ clients-mutex + /// hold across the blocking `asio::write` (contract B3). `Option` so a + /// disconnect can close the socket even while the read task still holds + /// the handle, matching the C++ `handleDisconnect` socket close. + writer: AsyncMutex>, + context: ConnectionContext, +} + +struct Inner { + key: Mutex>, + clients: Mutex>>, + next_id: AtomicU32, + stopping: AtomicBool, + /// Client-mode connection state; id 0 means "never connected", so the + /// C++ `ctx.id != serverContext.id` timer-gating reproduces exactly. + server_ctx: Mutex>, + server_writer: AsyncMutex>, + received: OnceLock>, + disconnected: OnceLock, + connect_decision: OnceLock, + server_connected: OnceLock, + tasks: Mutex>>, +} + +/// Encrypted TCP endpoint usable in either client or server role. +/// +/// Cheap to hand out: state is shared behind an `Arc`; clone or borrow the +/// same instance from callbacks. +pub struct OmniVox { + inner: Arc>, +} + +impl Default for OmniVox { + fn default() -> Self { + Self::new() + } +} + +impl OmniVox { + /// Creates an endpoint with no key set (traffic then uses the all-zero + /// key, reproducing the C++ default-constructed `SecByteBlock`). + pub fn new() -> Self { + Self { + inner: Arc::new(Inner { + key: Mutex::new(None), + clients: Mutex::new(HashMap::new()), + next_id: AtomicU32::new(1), + stopping: AtomicBool::new(false), + server_ctx: Mutex::new(None), + server_writer: AsyncMutex::const_new(None), + received: OnceLock::new(), + disconnected: OnceLock::new(), + connect_decision: OnceLock::new(), + server_connected: OnceLock::new(), + tasks: Mutex::new(Vec::new()), + }), + } + } + + /// Sets the ChaCha20-Poly1305 key. Until set, traffic uses the all-zero + /// key, which is what the C++ default-constructed `SecByteBlock` did. + pub fn set_encrypt_key(&self, key: [u8; KEY_LEN]) { + *self.inner.key.lock().unwrap() = Some(key); + } + + fn key_bytes(&self) -> [u8; KEY_LEN] { + self.inner.key.lock().unwrap().unwrap_or([0u8; KEY_LEN]) + } + + /// Starts the server on `0.0.0.0:port`. + /// + /// `num_threads` is accepted for API parity with the C++ signature; the + /// tokio runtime's worker pool already provides the parallelism the C++ + /// `ThreadPool_` existed to add, so it configures nothing (contract: + /// thread structure is an accepted difference). + /// + /// `timeout_ms` is the per-client idle cap for waiting on a message + /// header. Errors only if already started; runtime failures are logged. + pub async fn start_server( + &self, + port: u16, + num_threads: usize, + timeout_ms: u64, + data: DataHandler, + disconnect: ConnHandler, + connect: DecisionHandler, + ) -> Result<(), OmniVoxError> { + let _ = num_threads; + let _ = self.inner.received.set(data); + let _ = self.inner.disconnected.set(disconnect); + let _ = self.inner.connect_decision.set(connect); + + let listener = TcpListener::bind(("0.0.0.0", port)).await?; + let accept_inner = Arc::clone(&self.inner); + let accept_task = tokio::spawn(async move { + loop { + let (stream, peer) = match listener.accept().await { + Ok(v) => v, + Err(_) if accept_inner.stopping.load(Ordering::Relaxed) => break, + Err(e) => { + error!("[OMNIVOX] accept error: {e}"); + continue; + } + }; + let conn_inner = Arc::clone(&accept_inner); + let task = tokio::spawn(async move { + Self::serve_connection(conn_inner, stream, peer, timeout_ms).await; + }); + accept_inner.tasks.lock().unwrap().push(task); + } + }); + self.inner.tasks.lock().unwrap().push(accept_task); + + info!( + "[OMNIVOX] Server started on port {port} with {num_threads} threads and {timeout_ms} ms timeout" + ); + Ok(()) + } + + async fn serve_connection( + inner: Arc>, + mut stream: TcpStream, + peer: SocketAddr, + timeout_ms: u64, + ) { + let id = inner.next_id.fetch_add(1, Ordering::Relaxed); + let mut ctx = ConnectionContext { + connected: ConnectionStatus::Connected, + id, + total_sent: 0, + creation_time: now_micros(), + ip: peer.ip().to_string(), + port: peer.port(), + }; + + let decision = inner + .connect_decision + .get() + .map(|f| f(&ctx)) + .unwrap_or(Decision::Allow); + + if decision == Decision::Deny { + let _ = stream.shutdown().await; + ctx.connected = ConnectionStatus::Rejected; + if let Some(f) = inner.disconnected.get() { + f(&ctx); + } + info!( + "[OMNIVOX] Client connection from {}:{} rejected", + ctx.ip, ctx.port + ); + return; + } + + let (mut reader, writer) = stream.into_split(); + let handle = Arc::new(ClientHandle { + writer: AsyncMutex::new(Some(writer)), + context: ctx.clone(), + }); + inner + .clients + .lock() + .unwrap() + .insert(id, Arc::clone(&handle)); + info!( + "[OMNIVOX] Client {id} connected from {}:{}", + ctx.ip, ctx.port + ); + + Self::read_loop(inner, handle, &mut reader, timeout_ms).await; + } + + async fn read_loop( + inner: Arc>, + handle: Arc, + reader: &mut OwnedReadHalf, + timeout_ms: u64, + ) { + let ctx = &handle.context; + loop { + // Header: u32 LE message length, bounded by the client timeout. + let mut header = [0u8; 4]; + match timeout( + Duration::from_millis(timeout_ms), + reader.read_exact(&mut header), + ) + .await + { + Err(_elapsed) => { + info!( + "[OMNIVOX] Client {} {}:{} Timed out", + ctx.id, ctx.ip, ctx.port + ); + Self::handle_client_disconnect(&inner, ctx).await; + return; + } + Ok(Err(_)) => { + Self::handle_client_disconnect(&inner, ctx).await; + return; + } + Ok(Ok(_)) => {} + } + + let size = u32::from_le_bytes(header); + // Contract B1, preserved: on an unreasonable size the C++ code + // disconnects but does NOT return — it still attempts the body + // read (a 0-byte read succeeds and its empty packet then fails + // to decrypt, which is logged, not fatal). + if size == 0 || size > MAX_MESSAGE_SIZE { + info!( + "[OMNIVOX] Client {} {}:{} has an unreasonable header size!", + ctx.id, ctx.ip, ctx.port + ); + Self::handle_client_disconnect(&inner, ctx).await; + } + + // Body: fixed 5 s stall cap against slow-body attacks. + let mut body = vec![0u8; size as usize]; + match timeout( + Duration::from_millis(MAX_TIMEOUT_STALL_MS), + reader.read_exact(&mut body), + ) + .await + { + Err(_elapsed) => { + info!( + "[OMNIVOX] Client {} {}:{} had a stall during body read!", + ctx.id, ctx.ip, ctx.port + ); + Self::handle_client_disconnect(&inner, ctx).await; + return; + } + Ok(Err(_)) => { + Self::handle_client_disconnect(&inner, ctx).await; + return; + } + Ok(Ok(_)) => {} + } + + // Contract B2, preserved: bad packets are logged and skipped; + // the connection stays open. + if let Err(e) = Self::process_message(&inner, &body, ctx) { + error!("[OMNIVOX] Error processing message: {e}"); + } + } + } + + fn process_message( + inner: &Inner, + body: &[u8], + ctx: &ConnectionContext, + ) -> Result<(), ProcessError> { + let packet = AeadPacket::decode(body)?; + let plaintext = decrypt(&inner_key(inner), &packet)?; + let payload = T::decode(&plaintext)?; + if let Some(f) = inner.received.get() { + f(&payload, ctx); + } + Ok(()) + } + + async fn handle_client_disconnect(inner: &Inner, ctx: &ConnectionContext) { + let removed = { + let mut clients = inner.clients.lock().unwrap(); + clients.remove(&ctx.id) + }; + if let Some(handle) = removed { + if let Some(mut writer) = handle.writer.lock().await.take() { + let _ = writer.shutdown().await; + } + if let Some(f) = inner.disconnected.get() { + f(ctx); + } + info!("[OMNIVOX] Client {} disconnected", ctx.id); + } + } + + /// Connects to `host:port`, registering callbacks. The read loop runs + /// only when `data` is provided — the C++ gate on `receivedCallback`, + /// including contract B5 (client mode never arms stall timers). + /// + /// The `connection` callback fires exactly once with the outcome; data + /// arriving later reaches `data` on a background task. + pub async fn connect_to_server( + &self, + host: &str, + port: u16, + data: Option>, + connection: ConnHandler, + ) -> Result<(), OmniVoxError> { + if let Some(d) = data { + let _ = self.inner.received.set(d); + } + let _ = self.inner.server_connected.set(connection); + + let ctx = match Self::dial(host, port).await { + Err(_) => ConnectionContext::unknown(host, port), + Ok(stream) => { + let ctx = ConnectionContext { + connected: ConnectionStatus::Connected, + id: self.inner.next_id.fetch_add(1, Ordering::Relaxed), + total_sent: 0, + creation_time: now_micros(), + ip: host.to_owned(), + port, + }; + *self.inner.server_ctx.lock().unwrap() = Some(ctx.clone()); + let (reader, writer) = stream.into_split(); + *self.inner.server_writer.lock().await = Some(writer); + if self.inner.received.get().is_some() { + let inner = Arc::clone(&self.inner); + let read_ctx = ctx.clone(); + self.inner + .tasks + .lock() + .unwrap() + .push(tokio::spawn(async move { + Self::client_read_loop(inner, reader, read_ctx).await; + })); + } + ctx + } + }; + + if let Some(f) = self.inner.server_connected.get() { + f(&ctx); + } + Ok(()) + } + + async fn dial(host: &str, port: u16) -> Result { + // asio::async_connect tries the resolved list in order and stops at + // the first success. + let addrs = tokio::net::lookup_host((host, port)).await?; + let mut last = Err(std::io::Error::other("no addresses resolved")); + for addr in addrs { + match TcpStream::connect(addr).await { + Ok(s) => return Ok(s), + Err(e) => last = Err(e), + } + } + last + } + + async fn client_read_loop( + inner: Arc>, + mut reader: OwnedReadHalf, + ctx: ConnectionContext, + ) { + loop { + let mut header = [0u8; 4]; + if reader.read_exact(&mut header).await.is_err() { + break; + } + let size = u32::from_le_bytes(header); + if size == 0 || size > MAX_MESSAGE_SIZE { + info!( + "[OMNIVOX] Client {} {}:{} has an unreasonable header size!", + ctx.id, ctx.ip, ctx.port + ); + } + let mut body = vec![0u8; size as usize]; + if reader.read_exact(&mut body).await.is_err() { + break; + } + if let Err(e) = Self::process_message(&inner, &body, &ctx) { + error!("[OMNIVOX] Error processing message: {e}"); + } + } + *inner.server_writer.lock().await = None; + if let Some(mut sc) = inner.server_ctx.lock().unwrap().take() { + sc.connected = ConnectionStatus::NotConnected; + if let Some(f) = inner.server_connected.get() { + f(&sc); + } + } + } + + /// Sends to the connected server. `false` if not connected — the C++ + /// checks `is_open() && status == Connected` and returns, not throws. + pub async fn send_to_server(&self, data: &T) -> bool { + let connected = self + .inner + .server_ctx + .lock() + .unwrap() + .as_ref() + .is_some_and(|c| c.connected == ConnectionStatus::Connected); + if !connected { + return false; + } + let frame = match Self::sealed_frame(&self.key_bytes(), data) { + Ok(f) => f, + Err(()) => return false, + }; + let mut guard = self.inner.server_writer.lock().await; + match guard.as_mut() { + Some(writer) => writer.write_all(&frame).await.is_ok(), + None => false, + } + } + + /// Sends to client `id`. `false` if unknown — contract B3 preserved: the + /// write lock is held across the full frame write, as the C++ held the + /// clients mutex across the blocking `asio::write`. + pub async fn send_to_client(&self, data: &T, id: u32) -> bool { + let client = self.inner.clients.lock().unwrap().get(&id).cloned(); + let Some(client) = client else { return false }; + let Ok(frame) = Self::sealed_frame(&self.key_bytes(), data) else { + return false; + }; + let mut guard = client.writer.lock().await; + match guard.as_mut() { + Some(writer) => writer.write_all(&frame).await.is_ok(), + None => false, + } + } + + fn sealed_frame(key: &[u8; KEY_LEN], data: &T) -> Result, ()> { + let mut serialized = Vec::new(); + data.encode(&mut serialized); + let packet = encrypt(key, &serialized); + let mut packet_bytes = Vec::new(); + packet.encode(&mut packet_bytes); + let mut frame = Vec::with_capacity(4 + packet_bytes.len()); + // C++ memcpy'd a size_t into a u32 slot — truncation kept. + frame.extend_from_slice(&(packet_bytes.len() as u32).to_le_bytes()); + frame.extend_from_slice(&packet_bytes); + Ok(frame) + } + + /// Stops everything: accept loop, read loops, all sockets. Idempotent. + pub async fn stop(&self) { + self.inner.stopping.store(true, Ordering::Relaxed); + let tasks: Vec<_> = self.inner.tasks.lock().unwrap().drain(..).collect(); + for t in tasks { + t.abort(); + } + let clients: Vec<_> = self + .inner + .clients + .lock() + .unwrap() + .drain() + .map(|(_, c)| c) + .collect(); + drop(clients); + let server = self.inner.server_writer.lock().await.take(); + drop(server); + info!("[OMNIVOX] OmniVox stopped"); + } + + /// Server-side view of a client, for callbacks that want metadata. + pub fn client_context(&self, id: u32) -> Option { + self.inner + .clients + .lock() + .unwrap() + .get(&id) + .map(|c| c.context.clone()) + } + + pub fn server_context(&self) -> Option { + self.inner.server_ctx.lock().unwrap().clone() + } +} + +fn inner_key(inner: &Inner) -> [u8; KEY_LEN] { + inner.key.lock().unwrap().unwrap_or([0u8; KEY_LEN]) +} + +#[derive(Debug, thiserror::Error)] +enum ProcessError { + #[error(transparent)] + Codec(#[from] CodecError), + #[error(transparent)] + Crypto(#[from] CryptoError), +} diff --git a/tests/loopback.rs b/tests/loopback.rs new file mode 100644 index 0000000..43412e9 --- /dev/null +++ b/tests/loopback.rs @@ -0,0 +1,213 @@ +//! Loopback behavior tests mirroring the contract's runtime clauses +//! (B1 unreasonable header, B2 tampered packet survives, framing). +//! Raw keys via `set_encrypt_key` keep these fast (no scrypt). + +use omnivox::{ + AeadPacket, Cereal, ConnectionContext, Decision, MAX_MESSAGE_SIZE, OmniVox, encrypt, +}; +use std::{ + sync::{ + Arc, + atomic::{AtomicU32, Ordering}, + }, + time::Duration, +}; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, +}; + +#[derive(Debug, Default)] +struct Msg(Vec); + +impl Cereal for Msg { + fn encode(&self, out: &mut Vec) { + omnivox::write_byte_vec(out, &self.0); + } + fn decode(bytes: &[u8]) -> Result { + Ok(Self(omnivox::Reader::new(bytes).byte_vec()?)) + } +} + +fn frame(key: &[u8; 32], msg: &[u8]) -> Vec { + let mut plain = Vec::new(); + Msg(msg.to_vec()).encode(&mut plain); + let packet = encrypt(key, &plain); + let mut bytes = Vec::new(); + packet.encode(&mut bytes); + let mut out = Vec::new(); + out.extend_from_slice(&(bytes.len() as u32).to_le_bytes()); + out.extend_from_slice(&bytes); + out +} + +async fn start_server(port: u16, rx: Arc) -> Arc> { + let server = Arc::new(OmniVox::::new()); + server.set_encrypt_key([42u8; 32]); + let data = Arc::new(move |msg: &Msg, _ctx: &ConnectionContext| { + if msg.0.starts_with(b"ok") { + rx.fetch_add(1, Ordering::SeqCst); + } + }); + server + .start_server( + port, + 1, + 2000, + data, + Arc::new(|_ctx| {}), + Arc::new(|_ctx| Decision::Allow), + ) + .await + .unwrap(); + server +} + +fn free_port(hint: u16) -> u16 { + // bind-and-drop probe; tests run sequentially per port + hint +} + +#[tokio::test] +async fn tampered_message_is_dropped_but_connection_survives() { + let port = free_port(18101); + let rx = Arc::new(AtomicU32::new(0)); + let server = start_server(port, Arc::clone(&rx)).await; + + let client = OmniVox::::new(); + client.set_encrypt_key([42u8; 32]); + let got = Arc::new(AtomicU32::new(0)); + let g = Arc::clone(&got); + client + .connect_to_server( + "127.0.0.1", + port, + Some(Arc::new(move |_d, _c| { + g.fetch_add(1, Ordering::SeqCst); + })), + Arc::new(|_c| {}), + ) + .await + .unwrap(); + + // Valid through the API. + assert!(client.send_to_server(&Msg(b"ok1".to_vec())).await); + // Tampered raw frame: flip a ciphertext byte. + let mut bad = frame(&[42u8; 32], b"ok2"); + let last = bad.len() - 1; + bad[last] ^= 0x01; + let mut raw = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + raw.write_all(&bad).await.unwrap(); + // Valid again on the tampered connection's server slot (new conn). + assert!(client.send_to_server(&Msg(b"ok3".to_vec())).await); + + tokio::time::sleep(Duration::from_millis(300)).await; + assert_eq!( + rx.load(Ordering::SeqCst), + 2, + "tampered frame must not decode" + ); + // Contract B2: the tampering connection is NOT dropped — server keeps + // its header wait armed (rx-timeout is 2 s, so a 500 ms read must time + // out without EOF). + let r = tokio::time::timeout(Duration::from_millis(500), raw.read(&mut [0u8; 1])).await; + assert!(r.is_err(), "tampering connection must stay open (B2)"); + assert_eq!( + got.load(Ordering::SeqCst), + 0, + "server does not echo in this test" + ); + server.stop().await; + client.stop().await; +} + +#[tokio::test] +async fn zero_size_header_disconnects_like_cpp_b1() { + let port = free_port(18102); + let rx = Arc::new(AtomicU32::new(0)); + let server = start_server(port, Arc::clone(&rx)).await; + + let mut raw = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + raw.write_all(&0u32.to_le_bytes()).await.unwrap(); + // C++ B1: server logs, disconnects, then the 0-byte read "succeeds" and + // the empty packet fails to decode (logged). The socket must close. + let mut buf = [0u8; 1]; + let n = tokio::time::timeout(Duration::from_secs(2), raw.read(&mut buf)) + .await + .expect("server must close, not hang") + .unwrap(); + assert_eq!(n, 0, "EOF after unreasonable header"); + server.stop().await; +} + +#[tokio::test] +async fn oversized_header_disconnects() { + let port = free_port(18103); + let rx = Arc::new(AtomicU32::new(0)); + let server = start_server(port, Arc::clone(&rx)).await; + + let mut raw = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + raw.write_all(&(MAX_MESSAGE_SIZE + 1).to_le_bytes()) + .await + .unwrap(); + let mut buf = [0u8; 1]; + let n = tokio::time::timeout(Duration::from_secs(2), raw.read(&mut buf)) + .await + .expect("server must close, not hang") + .unwrap(); + assert_eq!(n, 0); + server.stop().await; +} + +#[tokio::test] +async fn header_stall_times_out_server_side() { + let port = free_port(18104); + let rx = Arc::new(AtomicU32::new(0)); + // start_server timeout_ms = 300 for this one + let server = Arc::new(OmniVox::::new()); + server.set_encrypt_key([42u8; 32]); + server + .start_server( + port, + 1, + 300, + Arc::new(move |_: &Msg, _: &ConnectionContext| { + rx.fetch_add(1, Ordering::SeqCst); + }), + Arc::new(|_c| {}), + Arc::new(|_c| Decision::Allow), + ) + .await + .unwrap(); + + let mut raw = TcpStream::connect(("127.0.0.1", port)).await.unwrap(); + raw.write_all(&[0x10, 0x00]).await.unwrap(); // partial header, then silence + let mut buf = [0u8; 1]; + let n = tokio::time::timeout(Duration::from_secs(3), raw.read(&mut buf)) + .await + .expect("stall timeout must fire") + .unwrap(); + assert_eq!(n, 0); + server.stop().await; +} + +#[tokio::test] +async fn send_to_unknown_client_is_false_like_cpp() { + let server = OmniVox::::new(); + server.set_encrypt_key([0u8; 32]); + assert!(!server.send_to_client(&Msg(b"x".to_vec()), 999).await); + assert!(!server.send_to_server(&Msg(b"x".to_vec())).await); +} + +#[test] +fn aead_packet_roundtrip_matches_wire_shape() { + let pkt = AeadPacket { + nonce: [9; 12], + tag: [8; 16], + payload: vec![7; 3], + }; + let mut b = Vec::new(); + pkt.encode(&mut b); + assert_eq!(b.len(), 12 + 16 + 8 + 3); + assert_eq!(AeadPacket::decode(&b).unwrap(), pkt); +} diff --git a/tests/vectors.rs b/tests/vectors.rs new file mode 100644 index 0000000..a873438 --- /dev/null +++ b/tests/vectors.rs @@ -0,0 +1,149 @@ +//! Golden vectors produced by the C++ implementation (CryptoPP + cereal) +//! in `omnivox-ref/cppgen.cpp`. The Rust leaves must reproduce these bytes. + +use omnivox::{AeadPacket, Cereal, decrypt, derive_encrypt_key, encrypt_with_nonce}; + +fn vectors() -> Vec<(String, String)> { + include_str!("vectors.txt") + .lines() + .filter_map(|l| l.split_once('=')) + .map(|(k, v)| (k.to_owned(), v.to_owned())) + .collect() +} + +fn get<'a>(vs: &'a [(String, String)], key: &str) -> &'a str { + vs.iter() + .find(|(k, _)| k == key) + .unwrap_or_else(|| panic!("missing vector {key}")) + .1 + .as_str() +} + +fn unhex(s: &str) -> Vec { + (0..s.len()) + .step_by(2) + .map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()) + .collect() +} + +#[test] +fn scrypt_key_matches_cpp_default_params() { + let vs = vectors(); + let pw = b"SecurePassword123"; + let salt: Vec = (1u8..=8).collect(); + let key = derive_encrypt_key(pw, &salt, 17, 8, 1).expect("scrypt"); + assert_eq!(hex(key), get(&vs, "scrypt_key")); +} + +#[test] +fn scrypt_key_matches_cpp_short_inputs() { + let vs = vectors(); + let key = derive_encrypt_key(b"pass", b"salt", 17, 8, 1).expect("scrypt"); + assert_eq!(hex(key), get(&vs, "scrypt_key2")); +} + +#[test] +fn empty_inputs_rejected_like_cpp_invalid_argument() { + assert!(derive_encrypt_key(b"", b"salt", 17, 8, 1).is_err()); + assert!(derive_encrypt_key(b"pw", b"", 17, 8, 1).is_err()); +} + +#[test] +fn datagram_payload_layout_matches_cereal() { + struct DatagramPayload { + id: u16, + v1: u64, + payload: Vec, + } + impl Cereal for DatagramPayload { + fn encode(&self, out: &mut Vec) { + out.extend_from_slice(&self.id.to_le_bytes()); + out.extend_from_slice(&self.v1.to_le_bytes()); + omnivox::write_byte_vec(out, &self.payload); + } + fn decode(bytes: &[u8]) -> Result { + let mut r = omnivox::Reader::new(bytes); + Ok(Self { + id: r.u16()?, + v1: r.u64()?, + payload: r.byte_vec()?, + }) + } + } + + let vs = vectors(); + let dp = DatagramPayload { + id: 0x1234, + v1: 0x1122334455667788, + payload: b"Hello".to_vec(), + }; + let mut out = Vec::new(); + dp.encode(&mut out); + assert_eq!(hex(&out), get(&vs, "cereal_datagram")); + let back = DatagramPayload::decode(&out).unwrap(); + assert_eq!( + (back.id, back.v1, back.payload), + (0x1234, 0x1122334455667788, b"Hello".to_vec()) + ); + + let mut zeroed = Vec::new(); + DatagramPayload { + id: 0, + v1: 0, + payload: vec![], + } + .encode(&mut zeroed); + assert_eq!(hex(zeroed), get(&vs, "cereal_datagram_default")); +} + +#[test] +fn aead_packet_layout_matches_cereal() { + let vs = vectors(); + let pkt = AeadPacket { + nonce: std::array::from_fn(|i| i as u8), + tag: std::array::from_fn(|i| 0xA0 + i as u8), + payload: vec![0xDE, 0xAD, 0xBE, 0xEF], + }; + let mut out = Vec::new(); + pkt.encode(&mut out); + assert_eq!(hex(&out), get(&vs, "cereal_aead")); + assert_eq!(AeadPacket::decode(&out).unwrap(), pkt); + + let empty = AeadPacket { + nonce: [0; 12], + tag: [0; 16], + payload: vec![], + }; + let mut out = Vec::new(); + empty.encode(&mut out); + assert_eq!(hex(out), get(&vs, "cereal_aead_empty")); +} + +#[test] +fn aead_matches_cryptopp_output() { + let vs = vectors(); + let key: [u8; 32] = unhex(get(&vs, "scrypt_key")).try_into().unwrap(); + let nonce: [u8; 12] = std::array::from_fn(|i| i as u8); + + let pkt = encrypt_with_nonce(&key, &nonce, b"Hello"); + assert_eq!(hex(&pkt.payload), get(&vs, "aead_ct")); + assert_eq!(hex(pkt.tag), get(&vs, "aead_tag")); + assert_eq!(decrypt(&key, &pkt).unwrap(), b"Hello"); + + let empty = encrypt_with_nonce(&key, &nonce, b""); + assert_eq!(hex(empty.tag), get(&vs, "aead_empty_tag")); + assert_eq!(decrypt(&key, &empty).unwrap(), b""); +} + +#[test] +fn tampered_packet_fails_authentication() { + let key = [3u8; 32]; + let mut pkt = omnivox::encrypt(&key, b"important"); + pkt.payload[0] ^= 0x01; + let err = decrypt(&key, &pkt).unwrap_err(); + assert!(err.to_string().contains("tampered")); +} + +fn hex(bytes: impl AsRef<[u8]>) -> String { + bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect() +} diff --git a/tests/vectors.txt b/tests/vectors.txt new file mode 100644 index 0000000..0b288ef --- /dev/null +++ b/tests/vectors.txt @@ -0,0 +1,10 @@ +scrypt_key=f64f4c05eb28676be5e4dd760c7f9409327a47e11abb66adc593b2bd039a0650 +scrypt_key2=f21278eee02abf1ad982428b5ab5d1ffccb62f6f1163dc616bfe30686e143ea0 +cereal_datagram=34128877665544332211050000000000000048656c6c6f +cereal_datagram_default=000000000000000000000000000000000000 +cereal_aead=000102030405060708090a0ba0a1a2a3a4a5a6a7a8a9aaabacadaeaf0400000000000000deadbeef +cereal_aead_empty=000000000000000000000000000000000000000000000000000000000000000000000000 +aead_random_payloadlen=5 +aead_ct=3e3c330d3b +aead_tag=89c6b5d2dbc9d3f7c82c12825f992c49 +aead_empty_tag=791eac80a87ddffcf45d6bad2769ea04