From 6e732d625ffd4759defdaf818cd4cc2d580d26b5 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 25 Sep 2026 14:15:29 +0000 Subject: [PATCH] M3: tsc-query and tsc-observer (invisible presence, relay chat) - tsc-query: ServerQuery codec (escaping, rows, errors, notifications, command builder/parser), line client for raw TCP and SSH (russh) with events, flood-limit token bucket and keepalive, HTTP WebQuery client. - tsc-model: Presence (snapshot/delta/diff), ChannelInfo, ClientInfo, ChatMessage, relay formatting and message splitting. - tsc-observer: Observer (snapshot, events or polling, resync, reconnect) and RelayPool (one query session per channel, reads channel chat and posts as [Nick] text, unique nicknames, polite quit). - tsctl query/observe/relay; smoke test covers presence and relay on TS3 (raw) and TS6 (SSH). Dev servers enable all query interfaces with a fixed dev password. - docs: query clients are hidden by clients, not the server. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01NJvYyRmTjKcb9i8eyYXK5G --- Cargo.lock | 1106 +++++++++++++++++++++++++-- Cargo.toml | 4 + README.md | 16 +- crates/tsc-model/src/chat.rs | 81 ++ crates/tsc-model/src/lib.rs | 6 + crates/tsc-model/src/presence.rs | 233 ++++++ crates/tsc-observer/Cargo.toml | 22 + crates/tsc-observer/src/convert.rs | 218 ++++++ crates/tsc-observer/src/lib.rs | 17 + crates/tsc-observer/src/observer.rs | 234 ++++++ crates/tsc-observer/src/relay.rs | 190 +++++ crates/tsc-query/Cargo.toml | 24 + crates/tsc-query/src/client.rs | 149 ++++ crates/tsc-query/src/codec.rs | 352 +++++++++ crates/tsc-query/src/http.rs | 93 +++ crates/tsc-query/src/lib.rs | 50 ++ crates/tsc-query/src/line.rs | 314 ++++++++ crates/tsc-query/src/ssh.rs | 59 ++ dev/docker-compose.yml | 14 +- docs/architecture.md | 16 + scripts/it-smoke.sh | 51 ++ tools/tsctl/Cargo.toml | 2 + tools/tsctl/src/main.rs | 11 + tools/tsctl/src/observe.rs | 227 ++++++ tools/tsctl/src/query.rs | 118 +++ 25 files changed, 3555 insertions(+), 52 deletions(-) create mode 100644 crates/tsc-model/src/chat.rs create mode 100644 crates/tsc-model/src/presence.rs create mode 100644 crates/tsc-observer/Cargo.toml create mode 100644 crates/tsc-observer/src/convert.rs create mode 100644 crates/tsc-observer/src/lib.rs create mode 100644 crates/tsc-observer/src/observer.rs create mode 100644 crates/tsc-observer/src/relay.rs create mode 100644 crates/tsc-query/Cargo.toml create mode 100644 crates/tsc-query/src/client.rs create mode 100644 crates/tsc-query/src/codec.rs create mode 100644 crates/tsc-query/src/http.rs create mode 100644 crates/tsc-query/src/lib.rs create mode 100644 crates/tsc-query/src/line.rs create mode 100644 crates/tsc-query/src/ssh.rs create mode 100644 tools/tsctl/src/observe.rs create mode 100644 tools/tsctl/src/query.rs diff --git a/Cargo.lock b/Cargo.lock index a5292ad..e67a73f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aead" version = "0.5.2" @@ -9,7 +15,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" dependencies = [ "crypto-common 0.1.7", - "generic-array", + "generic-array 0.14.7", +] + +[[package]] +name = "aead" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99" +dependencies = [ + "crypto-common 0.2.2", + "inout 0.2.2", ] [[package]] @@ -32,6 +48,22 @@ dependencies = [ "cipher 0.5.2", "cpubits", "cpufeatures 0.3.1", + "zeroize", +] + +[[package]] +name = "aes-gcm" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f2b8006a0c83f52b62ba44a97b58bf76fe2f70a329e588f67f89691d93d498f" +dependencies = [ + "aead 0.6.1", + "aes 0.9.3", + "cipher 0.5.2", + "ctr 0.10.1", + "ctutils", + "ghash", + "zeroize", ] [[package]] @@ -74,6 +106,15 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + [[package]] name = "anes" version = "0.1.6" @@ -147,6 +188,18 @@ dependencies = [ "security-framework", ] +[[package]] +name = "argon2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "134c52ddac6d63c576bef8168db10c83c49c26444ecbc68060fef078925a901c" +dependencies = [ + "base64ct", + "blake2", + "cpufeatures 0.3.1", + "password-hash", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -330,6 +383,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" dependencies = [ "aws-lc-sys", + "untrusted 0.7.1", "zeroize", ] @@ -358,6 +412,12 @@ version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" +[[package]] +name = "base16ct" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6" + [[package]] name = "base64" version = "0.22.1" @@ -376,6 +436,17 @@ version = "1.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" +[[package]] +name = "bcrypt-pbkdf" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "144e573728da132683b9488acd528274c790e07fc06ff81ee29f9d8f8b1041e0" +dependencies = [ + "blowfish", + "pbkdf2", + "sha2 0.11.0", +] + [[package]] name = "bit-vec" version = "0.6.3" @@ -391,13 +462,22 @@ dependencies = [ "serde_core", ] +[[package]] +name = "blake2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f" +dependencies = [ + "digest 0.11.3", +] + [[package]] name = "block-buffer" version = "0.10.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" dependencies = [ - "generic-array", + "generic-array 0.14.7", ] [[package]] @@ -407,6 +487,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" dependencies = [ "hybrid-array", + "zeroize", ] [[package]] @@ -440,6 +521,16 @@ dependencies = [ "piper", ] +[[package]] +name = "blowfish" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62ce3946557b35e71d1bbe07ec385073ce9eda05043f95de134eb578fcf1a298" +dependencies = [ + "byteorder", + "cipher 0.5.2", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -504,8 +595,23 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" dependencies = [ "cfg-if", + "cipher 0.5.2", "cpufeatures 0.3.1", "rand_core 0.10.1", + "zeroize", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", ] [[package]] @@ -551,8 +657,10 @@ version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c" dependencies = [ + "block-buffer 0.12.1", "crypto-common 0.2.2", "inout 0.2.2", + "zeroize", ] [[package]] @@ -758,6 +866,15 @@ dependencies = [ "libc", ] +[[package]] +name = "crc32fast" +version = "1.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01a7799fd6b852db0e61728dde9a204c423b44d689dbd432522543614b490e78" +dependencies = [ + "cfg-if", +] + [[package]] name = "criterion" version = "0.8.2" @@ -845,7 +962,7 @@ version = "0.5.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ - "generic-array", + "generic-array 0.14.7", "rand_core 0.6.4", "subtle", "zeroize", @@ -862,13 +979,30 @@ dependencies = [ "subtle", ] +[[package]] +name = "crypto-bigint" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a52aa3fcda4e6302a9f48734f234d35d4721b96f8fe07d073f07ce9df4f0271" +dependencies = [ + "cpubits", + "ctutils", + "getrandom 0.4.3", + "hybrid-array", + "num-traits", + "rand_core 0.10.1", + "serdect", + "subtle", + "zeroize", +] + [[package]] name = "crypto-common" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" dependencies = [ - "generic-array", + "generic-array 0.14.7", "rand_core 0.6.4", "typenum", ] @@ -879,7 +1013,19 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" dependencies = [ + "getrandom 0.4.3", "hybrid-array", + "rand_core 0.10.1", +] + +[[package]] +name = "crypto-primes" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3633a51a39c69ebbaa4feaa694bd83d241e4093901c84a0963b19d9bb3f0cf8f" +dependencies = [ + "crypto-bigint 0.7.5", + "rand_core 0.10.1", ] [[package]] @@ -912,6 +1058,15 @@ dependencies = [ "cipher 0.4.4", ] +[[package]] +name = "ctr" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaca1c4b237092596f64d571e9db6ce4109c4ef9742e27590f1709594461f21" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "ctutils" version = "0.4.2" @@ -919,6 +1074,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e" dependencies = [ "cmov", + "subtle", ] [[package]] @@ -930,13 +1086,30 @@ dependencies = [ "cfg-if", "cpufeatures 0.2.17", "curve25519-dalek-derive", - "fiat-crypto", + "fiat-crypto 0.2.9", "rand_core 0.6.4", "rustc_version", "subtle", "zeroize", ] +[[package]] +name = "curve25519-dalek" +version = "5.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5eed333089e2e1c1ac8c6c0398e5e2497b4c9926ca6d0365ed1e099afa5bc23" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "curve25519-dalek-derive", + "digest 0.11.3", + "fiat-crypto 0.3.0", + "rand_core 0.10.1", + "rustc_version", + "subtle", + "zeroize", +] + [[package]] name = "curve25519-dalek-derive" version = "0.1.1" @@ -966,7 +1139,18 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bd2735a791158376708f9347fe8faba9667589d82427ef3aed6794a8981de3d9" dependencies = [ - "generic-array", + "generic-array 0.14.7", +] + +[[package]] +name = "delegate" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "780eb241654bf097afb00fc5f054a09b687dad862e485fdcf8399bb056565370" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", ] [[package]] @@ -976,7 +1160,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" dependencies = [ "const-oid 0.9.6", - "pem-rfc7468", + "pem-rfc7468 0.7.0", + "zeroize", +] + +[[package]] +name = "der" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a878c850e9e421b20262e9b41f9c860e4785fa07541c266b62ff9d1ef998a80a" +dependencies = [ + "const-oid 0.10.2", + "pem-rfc7468 1.0.0", "zeroize", ] @@ -989,6 +1184,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "des" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "916a94e407b54f9034d71dd748234cd1e516ced6284009906ae246f177eafe5a" +dependencies = [ + "cipher 0.5.2", +] + [[package]] name = "digest" version = "0.10.7" @@ -1067,10 +1271,10 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9954fabd903b82b9d7a68f65f97dc96dd9ad368e40ccc907a7c19d53e6bfac28" dependencies = [ - "aead", + "aead 0.5.2", "cipher 0.4.4", "cmac", - "ctr", + "ctr 0.9.2", "subtle", ] @@ -1080,12 +1284,53 @@ version = "0.16.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" dependencies = [ - "der", + "der 0.7.10", "digest 0.10.7", - "elliptic-curve", - "rfc6979", - "signature", - "spki", + "elliptic-curve 0.13.8", + "rfc6979 0.4.0", + "signature 2.2.0", + "spki 0.7.3", +] + +[[package]] +name = "ecdsa" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0681a4fc24c767085329728d8dfba959af91228aa4610cca4f8ce317ba46ae0" +dependencies = [ + "der 0.8.2", + "digest 0.11.3", + "elliptic-curve 0.14.1", + "rfc6979 0.6.0", + "signature 3.0.0", + "spki 0.8.0", + "zeroize", +] + +[[package]] +name = "ed25519" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29fcf32e6c73d1079f83ab4d782de2d81620346a5f38c6237a86a22f8368980a" +dependencies = [ + "pkcs8 0.11.0", + "signature 3.0.0", +] + +[[package]] +name = "ed25519-dalek" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ebaa1a2bf1290ab3bfe5a7b771d050ebffab2711c19a81691c683a5144a25de" +dependencies = [ + "curve25519-dalek 5.0.0", + "ed25519", + "rand_core 0.10.1", + "serde", + "sha2 0.11.0", + "signature 3.0.0", + "subtle", + "zeroize", ] [[package]] @@ -1100,17 +1345,39 @@ version = "0.13.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" dependencies = [ - "base16ct", + "base16ct 0.2.0", "crypto-bigint 0.5.5", "digest 0.10.7", - "ff", - "generic-array", - "group", + "ff 0.13.1", + "generic-array 0.14.7", + "group 0.13.0", "hkdf 0.12.4", - "pem-rfc7468", - "pkcs8", + "pem-rfc7468 0.7.0", + "pkcs8 0.10.2", "rand_core 0.6.4", - "sec1", + "sec1 0.7.3", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d65aa39b3a5c1c9c1b745c9a019234bb7a21b77abcb4f4d266d706e2d577d65" +dependencies = [ + "base16ct 1.0.0", + "crypto-bigint 0.7.5", + "crypto-common 0.2.2", + "digest 0.11.3", + "ff 0.14.0", + "group 0.14.0", + "hkdf 0.13.0", + "hybrid-array", + "pem-rfc7468 1.0.0", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sec1 0.8.1", "subtle", "zeroize", ] @@ -1135,6 +1402,18 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" +[[package]] +name = "enum_dispatch" +version = "0.3.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa18ce2bc66555b3218614519ac839ddb759a7d6720732f979ef8d13be147ecd" +dependencies = [ + "once_cell", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "enumflags2" version = "0.7.12" @@ -1240,18 +1519,45 @@ dependencies = [ "subtle", ] +[[package]] +name = "ff" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1f686ab92a9fb0eaf188f6c6c87b89490baa6fdb0db4544ba4dc47f7942489f" +dependencies = [ + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "fiat-crypto" version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" +[[package]] +name = "fiat-crypto" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64cd1e32ddd350061ae6edb1b082d7c54915b5c672c389143b9a63403a109f24" + [[package]] name = "find-msvc-tools" version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "aedcfb3409746eddb02b9e19ebda1c3394f759a152e48ee875a0844d1b955484" +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", + "zlib-rs", +] + [[package]] name = "fnv" version = "1.0.7" @@ -1391,6 +1697,17 @@ dependencies = [ "zeroize", ] +[[package]] +name = "generic-array" +version = "1.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "337d46834ee672ab3e48caca2cb0c78cc174fb12b3a68d0d88f99a0519a5e36e" +dependencies = [ + "generic-array 0.14.7", + "rustversion", + "typenum", +] + [[package]] name = "getrandom" version = "0.2.17" @@ -1418,6 +1735,16 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "ghash" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5" +dependencies = [ + "polyval", + "zeroize", +] + [[package]] name = "git-testament" version = "0.2.6" @@ -1456,11 +1783,22 @@ version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ - "ff", + "ff 0.13.1", "rand_core 0.6.4", "subtle", ] +[[package]] +name = "group" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7fd1a1c7a5206c5b7a3f5a0d7ccd3ff85d0c8f5133d62a02680255b0004af5f4" +dependencies = [ + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", +] + [[package]] name = "h2" version = "0.4.19" @@ -1536,6 +1874,12 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hex-literal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1" + [[package]] name = "hickory-net" version = "0.26.3" @@ -1693,7 +2037,10 @@ version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" dependencies = [ + "ctutils", + "subtle", "typenum", + "zeroize", ] [[package]] @@ -1756,6 +2103,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -1876,7 +2247,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "879f10e63c20629ecabbb64a8010319738c66a5cd0c29b02d63d272b03751d01" dependencies = [ - "generic-array", + "generic-array 0.14.7", ] [[package]] @@ -2020,6 +2391,26 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "keccak" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8f198d1db720e4940b5a493201d199d9f24f568f8f746bd13706243a2f71598" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", +] + +[[package]] +name = "kem" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01737161ba802849cfd486b5bd209d38ba4943494c249a8126005170c7621edd" +dependencies = [ + "crypto-common 0.2.2", + "rand_core 0.10.1", +] + [[package]] name = "keyring" version = "4.2.0" @@ -2138,6 +2529,12 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "md5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebb8d8732c6a6df3d8f032a82911cfc747e00efb95cc46e8d0acd5b5b88570c" + [[package]] name = "memchr" version = "2.8.3" @@ -2165,6 +2562,16 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + [[package]] name = "mio" version = "1.2.3" @@ -2176,6 +2583,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "ml-kem" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e15f3e5b957493873e396a66914e83e616b6afe335cdef7efe5c6e1216aba66" +dependencies = [ + "hybrid-array", + "kem", + "module-lattice", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sha3 0.11.0", +] + +[[package]] +name = "module-lattice" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c61b87c9683ab7cb1c6871d261ad5479b6b10ceb52c4352aaca3b5d35a8febe" +dependencies = [ + "ctutils", + "hybrid-array", + "num-traits", +] + [[package]] name = "moka" version = "0.12.16" @@ -2228,6 +2660,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nom" version = "7.1.3" @@ -2253,7 +2697,7 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35bd024e8b2ff75562e5f34e7f4905839deb4b22955ef5e73d2fea1b9813cb23" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-complex", "num-integer", "num-iter", @@ -2271,6 +2715,18 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-bigint" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0" +dependencies = [ + "num-integer", + "num-traits", + "rand 0.10.3", + "rand_core 0.10.1", +] + [[package]] name = "num-complex" version = "0.4.6" @@ -2322,7 +2778,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-integer", "num-traits", ] @@ -2516,12 +2972,53 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" dependencies = [ - "ecdsa", - "elliptic-curve", - "primeorder", + "ecdsa 0.16.9", + "elliptic-curve 0.13.8", + "primeorder 0.13.6", "sha2 0.10.9", ] +[[package]] +name = "p256" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c9239b2dbc807adbbe147e8cf72ea7450c3a0aabe62cb8e75ff4ec22e1f72a" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.0", +] + +[[package]] +name = "p384" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d17b851e6b3e378ab4ecb07fa2ed23f4d15f075735f8fec9fa1e7bdce5f8301f" +dependencies = [ + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", + "fiat-crypto 0.3.0", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.0", +] + +[[package]] +name = "p521" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ad64cc32c2dc466317c12ee5853e61f159f9eab1fe7efade0395dc2e7b43449" +dependencies = [ + "base16ct 1.0.0", + "ecdsa 0.17.0", + "elliptic-curve 0.14.1", + "primefield", + "primeorder 0.14.0", + "sha2 0.11.0", +] + [[package]] name = "page_size" version = "0.6.0" @@ -2532,6 +3029,26 @@ dependencies = [ "winapi", ] +[[package]] +name = "pageant" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d8eab09a361a4afe0b1668be978cd97e4f052e927a92b0b608cf902965d49ce" +dependencies = [ + "base16ct 1.0.0", + "byteorder", + "bytes", + "delegate", + "futures", + "log", + "rand 0.10.3", + "sha2 0.11.0", + "thiserror 2.0.21", + "tokio", + "windows", + "windows-strings", +] + [[package]] name = "parking" version = "2.2.1" @@ -2561,6 +3078,25 @@ dependencies = [ "windows-link", ] +[[package]] +name = "password-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aab41826031698d6ffcd9cff78ef56ef998e39dc7e5067cdfebe373842d4723b" +dependencies = [ + "phc", +] + +[[package]] +name = "pbkdf2" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112d82ceb8c5bf524d9af484d4e4970c9fd5a0cc15ba14ad93dccd28873b0629" +dependencies = [ + "digest 0.11.3", + "hmac 0.13.0", +] + [[package]] name = "pem-rfc7468" version = "0.7.0" @@ -2570,12 +3106,31 @@ dependencies = [ "base64ct", ] +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" +[[package]] +name = "phc" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44dc769b75f93afdddd8c7fa12d685292ddeff1e66f7f0f3a234cf1818afe892" +dependencies = [ + "base64ct", + "ctutils", +] + [[package]] name = "pin-project-lite" version = "0.2.17" @@ -2599,14 +3154,53 @@ dependencies = [ "futures-io", ] +[[package]] +name = "pkcs1" +version = "0.8.0-rc.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e" +dependencies = [ + "der 0.8.2", + "spki 0.8.0", +] + +[[package]] +name = "pkcs5" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63d440a804ec8d6fafbb6b84471e013286658d373248927692ab3366686220ca" +dependencies = [ + "aes 0.9.3", + "aes-gcm", + "cbc", + "der 0.8.2", + "pbkdf2", + "rand_core 0.10.1", + "scrypt", + "sha2 0.11.0", + "spki 0.8.0", +] + [[package]] name = "pkcs8" version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" dependencies = [ - "der", - "spki", + "der 0.7.10", + "spki 0.7.3", +] + +[[package]] +name = "pkcs8" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "451913da69c775a56034ea8d9003d27ee8948e12443eae7c038ba100a4f21cb7" +dependencies = [ + "der 0.8.2", + "pkcs5", + "rand_core 0.10.1", + "spki 0.8.0", ] [[package]] @@ -2657,6 +3251,29 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "poly1305" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2d0073b297041425c7c3df6eb4792d598a15323fe63346852b092eca02904c" +dependencies = [ + "cpufeatures 0.3.1", + "universal-hash", + "zeroize", +] + +[[package]] +name = "polyval" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd" +dependencies = [ + "cpubits", + "cpufeatures 0.3.1", + "universal-hash", + "zeroize", +] + [[package]] name = "portable-atomic" version = "1.15.0" @@ -2707,13 +3324,40 @@ dependencies = [ "num-integer", ] +[[package]] +name = "primefield" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c555a6e4eb7d4e158fcb028c835c3b8642206ddc279b5c6b202ef9a8bdb592f4" +dependencies = [ + "crypto-bigint 0.7.5", + "crypto-common 0.2.2", + "ff 0.14.0", + "rand_core 0.10.1", + "subtle", + "zeroize", +] + [[package]] name = "primeorder" version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" dependencies = [ - "elliptic-curve", + "elliptic-curve 0.13.8", +] + +[[package]] +name = "primeorder" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c9f42978c78a00e3d68f69fc03e57a234debae69da4020a4fb588fcdcd07b06" +dependencies = [ + "elliptic-curve 0.14.1", + "once_cell", + "primefield", + "serdect", + "wnaf", ] [[package]] @@ -3018,6 +3662,9 @@ dependencies = [ "rustls", "rustls-pki-types", "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", "sync_wrapper", "tokio", "tokio-rustls", @@ -3046,6 +3693,16 @@ dependencies = [ "subtle", ] +[[package]] +name = "rfc6979" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4a459cddafb3fe76b31fd8f1108007566c40301feb64dc7b54656eb7388172b" +dependencies = [ + "crypto-bigint 0.7.5", + "hmac 0.13.0", +] + [[package]] name = "ring" version = "0.17.14" @@ -3056,10 +3713,29 @@ dependencies = [ "cfg-if", "getrandom 0.2.17", "libc", - "untrusted", + "untrusted 0.9.0", "windows-sys 0.52.0", ] +[[package]] +name = "rsa" +version = "0.10.0-rc.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30b2aa4ba0d89f73d1e332df05be0eeab8840351c36ca5654341dfdb57bb3caf" +dependencies = [ + "const-oid 0.10.2", + "crypto-bigint 0.7.5", + "crypto-primes", + "digest 0.11.3", + "pkcs1", + "pkcs8 0.11.0", + "rand_core 0.10.1", + "sha2 0.11.0", + "signature 3.0.0", + "spki 0.8.0", + "zeroize", +] + [[package]] name = "rsqlite-vfs" version = "0.1.1" @@ -3119,6 +3795,101 @@ dependencies = [ "sqlite-wasm-rs", ] +[[package]] +name = "russh" +version = "0.63.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "036204edbd199552a5b3832f63c60dcdf395dc44c7f06b4af1c0e8139cc11bce" +dependencies = [ + "aes 0.9.3", + "aws-lc-rs", + "bitflags", + "block-padding", + "byteorder", + "bytes", + "cbc", + "cipher 0.5.2", + "crypto-bigint 0.7.5", + "ctr 0.10.1", + "curve25519-dalek 5.0.0", + "data-encoding", + "delegate", + "der 0.8.2", + "digest 0.11.3", + "ecdsa 0.17.0", + "ed25519-dalek", + "elliptic-curve 0.14.1", + "enum_dispatch", + "flate2", + "futures", + "generic-array 1.4.5", + "getrandom 0.4.3", + "ghash", + "hex-literal", + "hmac 0.13.0", + "inout 0.2.2", + "keccak", + "log", + "md5", + "ml-kem", + "module-lattice", + "num-bigint 0.5.1", + "p256 0.14.0", + "p384", + "p521", + "pageant", + "pbkdf2", + "pkcs1", + "pkcs5", + "pkcs8 0.11.0", + "polyval", + "rand 0.10.3", + "rand_core 0.10.1", + "rsa", + "russh-cryptovec", + "russh-util", + "salsa20", + "scrypt", + "sec1 0.8.1", + "sha1", + "sha2 0.11.0", + "sha3 0.12.0", + "signature 3.0.0", + "spki 0.8.0", + "ssh-encoding", + "ssh-key", + "subtle", + "thiserror 2.0.21", + "tokio", + "typenum", + "universal-hash", + "zeroize", +] + +[[package]] +name = "russh-cryptovec" +version = "0.62.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3aec6cb630dbe85d72ffd7bcd95f07e1bd69f9f270ee8adfa1afe443a6331438" +dependencies = [ + "log", + "nix", + "ssh-encoding", + "windows-sys 0.61.2", +] + +[[package]] +name = "russh-util" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668424a5dde0bcb45b55ba7de8476b93831b4aa2fa6947e145f3b053e22c60b6" +dependencies = [ + "chrono", + "tokio", + "wasm-bindgen", + "wasm-bindgen-futures", +] + [[package]] name = "rustc-hash" version = "2.1.3" @@ -3233,7 +4004,7 @@ dependencies = [ "aws-lc-rs", "ring", "rustls-pki-types", - "untrusted", + "untrusted 0.9.0", ] [[package]] @@ -3248,6 +4019,16 @@ version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" +[[package]] +name = "salsa20" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f874456e72520ff1375a06c588eaf074b0f01f9e9e1aada45bd9b7954a6e42c" +dependencies = [ + "cfg-if", + "cipher 0.5.2", +] + [[package]] name = "same-file" version = "1.0.6" @@ -3272,16 +4053,42 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "scrypt" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87af57419b594aa23fa95f09f0e06d80d84ba01c26148c43844cad6ff4485f0" +dependencies = [ + "cfg-if", + "pbkdf2", + "salsa20", + "sha2 0.11.0", +] + [[package]] name = "sec1" version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" dependencies = [ - "base16ct", - "der", - "generic-array", - "pkcs8", + "base16ct 0.2.0", + "der 0.7.10", + "generic-array 0.14.7", + "pkcs8 0.10.2", + "subtle", + "zeroize", +] + +[[package]] +name = "sec1" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d" +dependencies = [ + "base16ct 1.0.0", + "ctutils", + "der 0.8.2", + "hybrid-array", "subtle", "zeroize", ] @@ -3403,6 +4210,28 @@ dependencies = [ "serde_core", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serdect" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66cf8fedced2fcf12406bcb34223dffb92eaf34908ede12fed414c82b7f00b3e" +dependencies = [ + "base16ct 1.0.0", + "serde", +] + [[package]] name = "sha-1" version = "0.10.1" @@ -3414,6 +4243,17 @@ dependencies = [ "digest 0.10.7", ] +[[package]] +name = "sha1" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aacc4cc499359472b4abe1bf11d0b12e688af9a805fa5e3016f9a386dc2d0214" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", +] + [[package]] name = "sha2" version = "0.10.9" @@ -3436,6 +4276,27 @@ dependencies = [ "digest 0.11.3", ] +[[package]] +name = "sha3" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be176f1a57ce4e3d31c1a166222d9768de5954f811601fb7ca06fc8203905ce1" +dependencies = [ + "digest 0.11.3", + "keccak", +] + +[[package]] +name = "sha3" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bc9bad02c26382724b2d2692c6f179285e4b54eeecd7968f52a50059c3c11759" +dependencies = [ + "digest 0.11.3", + "keccak", + "sponge-cursor", +] + [[package]] name = "sharded-slab" version = "0.1.7" @@ -3471,6 +4332,22 @@ dependencies = [ "rand_core 0.6.4", ] +[[package]] +name = "signature" +version = "3.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28d567dcbaf0049cb8ac2608a76cd95ff9e4412e1899d389ee400918ca7537f5" +dependencies = [ + "digest 0.11.3", + "rand_core 0.10.1", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + [[package]] name = "simd_cesu8" version = "1.2.0" @@ -3493,7 +4370,7 @@ version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d" dependencies = [ - "num-bigint", + "num-bigint 0.4.8", "num-traits", "thiserror 2.0.21", "time", @@ -3528,9 +4405,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" dependencies = [ "base64ct", - "der", + "der 0.7.10", ] +[[package]] +name = "spki" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d9efca8738c78ee9484207732f728b1ef517bbb1833d6fc0879ca898a522f6f" +dependencies = [ + "base64ct", + "der 0.8.2", +] + +[[package]] +name = "sponge-cursor" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a0219bd7d979d58245a4f41f695e1ac9f8befdffadd7f61f1bae9e39abc6620" + [[package]] name = "sqlite-wasm-rs" version = "0.5.5" @@ -3543,6 +4436,65 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "ssh-cipher" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d801accda99469cde6d73da741422610fdf6508a72d9a69d1b55cb241c720597" +dependencies = [ + "aead 0.6.1", + "aes 0.9.3", + "aes-gcm", + "chacha20", + "cipher 0.5.2", + "ctutils", + "des", + "poly1305", + "ssh-encoding", + "zeroize", +] + +[[package]] +name = "ssh-encoding" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b54d0ed0498daf3f78d82e00e28c8eec9d75a067c4cfbcc7a0f7d0f4077749e" +dependencies = [ + "base64ct", + "bytes", + "crypto-bigint 0.7.5", + "ctutils", + "digest 0.11.3", + "pem-rfc7468 1.0.0", + "zeroize", +] + +[[package]] +name = "ssh-key" +version = "0.7.0-rc.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9a32fae177b74a22aa9c5b01bf7e68b33545be32d9e381e248058d2adc15ce3" +dependencies = [ + "argon2", + "bcrypt-pbkdf", + "ctutils", + "ed25519-dalek", + "hex", + "hmac 0.13.0", + "p256 0.14.0", + "p384", + "p521", + "rand_core 0.10.1", + "rsa", + "sec1 0.8.1", + "sha1", + "sha2 0.11.0", + "signature 3.0.0", + "ssh-cipher", + "ssh-encoding", + "zeroize", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -4046,6 +4998,30 @@ dependencies = [ "serde_json", ] +[[package]] +name = "tsc-observer" +version = "0.1.0" +dependencies = [ + "thiserror 2.0.21", + "tokio", + "tracing", + "tsc-model", + "tsc-query", +] + +[[package]] +name = "tsc-query" +version = "0.1.0" +dependencies = [ + "reqwest", + "russh", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tracing", +] + [[package]] name = "tsc-store" version = "0.1.0" @@ -4107,6 +5083,8 @@ dependencies = [ "tracing-subscriber", "tsc-audio", "tsc-model", + "tsc-observer", + "tsc-query", "tsclientlib", "tsproto-packets", ] @@ -4121,12 +5099,12 @@ dependencies = [ "clap", "criterion", "crypto-bigint 0.6.1", - "curve25519-dalek", + "curve25519-dalek 4.1.3", "eax", "futures", - "generic-array", + "generic-array 0.14.7", "git-testament", - "num-bigint", + "num-bigint 0.4.8", "num-derive", "num-traits", "omnom", @@ -4179,14 +5157,14 @@ version = "0.1.0" dependencies = [ "base64 0.22.1", "bitflags", - "curve25519-dalek", - "elliptic-curve", - "generic-array", + "curve25519-dalek 4.1.3", + "elliptic-curve 0.13.8", + "generic-array 0.14.7", "heck", - "num-bigint", + "num-bigint 0.4.8", "num-derive", "num-traits", - "p256", + "p256 0.13.2", "rand 0.8.8", "ref-cast", "serde", @@ -4221,6 +5199,22 @@ version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" +[[package]] +name = "universal-hash" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96" +dependencies = [ + "crypto-common 0.2.2", + "ctutils", +] + +[[package]] +name = "untrusted" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a" + [[package]] name = "untrusted" version = "0.9.0" @@ -4673,6 +5667,18 @@ dependencies = [ "memchr", ] +[[package]] +name = "wnaf" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "795ca18b3fdb5e62bf982199278341ddcf7ebf7d32e25e212ad05d496e95f6fa" +dependencies = [ + "ff 0.14.0", + "group 0.14.0", + "hybrid-array", + "primefield", +] + [[package]] name = "writeable" version = "0.6.4" @@ -4863,6 +5869,12 @@ dependencies = [ "syn 3.0.6", ] +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index c675077..fa34fa5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,6 +10,8 @@ members = [ "crates/proto/tsclientlib", "crates/tsc-audio", "crates/tsc-model", + "crates/tsc-observer", + "crates/tsc-query", "crates/tsc-store", "tools/tsctl", ] @@ -22,6 +24,8 @@ default-members = [ "crates/proto/tsclientlib", "crates/tsc-audio", "crates/tsc-model", + "crates/tsc-observer", + "crates/tsc-query", "crates/tsc-store", "tools/tsctl", ] diff --git a/README.md b/README.md index 79ed1eb..2a33210 100644 --- a/README.md +++ b/README.md @@ -23,7 +23,7 @@ See [docs/architecture.md](docs/architecture.md) for the design and milestones. ## Status -Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)): +Done so far (milestones M0–M3 of [the plan](docs/architecture.md#milestones)): - `crates/proto/`: vendored tsclientlib, modernised (TS6 fields and stream messages, faster off-thread Init1 puzzle, `curve25519-dalek` 4, fuzzing fixes; @@ -31,9 +31,13 @@ Done so far (milestones M0–M2 of [the plan](docs/architecture.md#milestones)): - `crates/tsc-model`: server flavor detection (TS3 / TS6) and capabilities - `crates/tsc-audio`: Opus voice encoding, framing, resampling, WAV, jitter buffer/mixer, cpal devices - `crates/tsc-store`: SQLite store for identities, bookmarks, settings and chat history; keyring secrets -- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events +- `crates/tsc-query`: ServerQuery client over raw TCP, SSH and HTTP WebQuery (events, rate limiting, keepalive) +- `crates/tsc-observer`: invisible presence (events or polling) and channel-chat relays over ServerQuery +- `tools/tsctl`: headless CLI: channel tree, chat, voice send/record, raw commands, stream events, + `query`, `observe` (invisible presence) and `relay` (channel chat without joining) - `dev/`: TeamSpeak 3.13 and TeamSpeak 6 (6.0.0-beta13.1) servers; `scripts/it-smoke.sh` - checks tree, server chat, channel chat and a voice tone round-trip on both + checks tree, server chat, channel chat, a voice tone round-trip, invisible presence + and relay chat on both - `fuzz/`: cargo-fuzz targets for packets, commands and the license chain No GUI and no screen sharing yet. @@ -50,7 +54,11 @@ cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me repl # interactive chat cargo run -p tsctl -- connect 127.0.0.1:9988 --nick me voice send --tone 440 cargo run -p tsctl -- connect 127.0.0.1:9988 --nick ear voice record out.wav -scripts/it-smoke.sh # tree, chat and voice round-trips on both servers +# ServerQuery (dev password tsc-dev-admin): invisible presence and relay chat +cargo run -p tsctl -- observe ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted +cargo run -p tsctl -- relay ssh 127.0.0.1:10022 --secret tsc-dev-admin --allowlisted --channel 1 + +scripts/it-smoke.sh # all of the above, on both servers ``` Other commands: `tsctl identity new`, `tsctl versions`, `tsctl connect listen|chat|raw`. diff --git a/crates/tsc-model/src/chat.rs b/crates/tsc-model/src/chat.rs new file mode 100644 index 0000000..6380006 --- /dev/null +++ b/crates/tsc-model/src/chat.rs @@ -0,0 +1,81 @@ +//! Chat messages, from any source. + +use serde::{Deserialize, Serialize}; + +use crate::presence::{ChannelId, ClientId}; + +#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(tag = "kind", content = "id", rename_all = "snake_case")] +pub enum ChatTarget { + /// Everyone on the server. + Server, + Channel(ChannelId), + /// Private chat, by the other side's unique id when known. + Private(String), +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChatMessage { + pub target: ChatTarget, + pub author_name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author_uid: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub author_id: Option, + pub text: String, + /// Unix time in milliseconds. + pub ts_ms: i64, + /// Carried by a gateway or query relay rather than our own connection. + #[serde(default)] + pub via_relay: bool, +} + +/// Format of messages a relay posts on behalf of a user. +pub fn relay_text(format: &str, nick: &str, text: &str) -> String { + format.replace("{nick}", nick).replace("{text}", text) +} + +/// Split text so each part fits TeamSpeak's message limit (1024 bytes of +/// text), breaking at character boundaries. +pub fn split_message(text: &str, max_bytes: usize) -> Vec { + let mut parts = Vec::new(); + let mut current = String::new(); + for c in text.chars() { + if current.len() + c.len_utf8() > max_bytes { + parts.push(std::mem::take(&mut current)); + } + current.push(c); + } + if !current.is_empty() || parts.is_empty() { + parts.push(current); + } + parts +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn relay_format() { + assert_eq!(relay_text("[{nick}] {text}", "Alice", "hi"), "[Alice] hi"); + } + + #[test] + fn splits_on_char_boundaries() { + assert_eq!(split_message("abcdef", 4), vec!["abcd", "ef"]); + assert_eq!(split_message("", 4), vec![""]); + let parts = split_message("ääää", 3); + assert!(parts.iter().all(|p| p.len() <= 3)); + assert_eq!(parts.concat(), "ääää"); + } + + #[test] + fn target_json() { + assert_eq!( + serde_json::to_string(&ChatTarget::Channel(5)).unwrap(), + r#"{"kind":"channel","id":5}"# + ); + assert_eq!(serde_json::to_string(&ChatTarget::Server).unwrap(), r#"{"kind":"server"}"#); + } +} diff --git a/crates/tsc-model/src/lib.rs b/crates/tsc-model/src/lib.rs index 350e491..1943a9b 100644 --- a/crates/tsc-model/src/lib.rs +++ b/crates/tsc-model/src/lib.rs @@ -3,6 +3,12 @@ //! Nothing in here does IO; the types describe what a server offers and what //! the user sees. +mod chat; +mod presence; mod server; +pub use chat::{ChatMessage, ChatTarget, relay_text, split_message}; +pub use presence::{ + ChannelId, ChannelInfo, ClientId, ClientInfo, Presence, PresenceDelta, PresenceSnapshot, +}; pub use server::{Capabilities, ServerFlavor, ServerVersion}; diff --git a/crates/tsc-model/src/presence.rs b/crates/tsc-model/src/presence.rs new file mode 100644 index 0000000..ec4c2c0 --- /dev/null +++ b/crates/tsc-model/src/presence.rs @@ -0,0 +1,233 @@ +//! Who is where: channels and the clients in them. +//! +//! The same model is fed from a voice connection, a query session or a +//! gateway. Sources send a [`PresenceSnapshot`] followed by +//! [`PresenceDelta`]s; sources that can only poll use [`Presence::diff`]. + +use std::collections::BTreeMap; + +use serde::{Deserialize, Serialize}; + +pub type ChannelId = u64; +pub type ClientId = u16; + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ChannelInfo { + pub id: ChannelId, + /// `0` for top-level channels. + pub parent: ChannelId, + /// Id of the sibling directly above, `0` for the first. + pub order: ChannelId, + pub name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub topic: Option, + #[serde(default)] + pub has_password: bool, + /// `None` means unlimited. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub max_clients: Option, + #[serde(default)] + pub needed_subscribe_power: i32, + #[serde(default)] + pub needed_talk_power: i32, + #[serde(default)] + pub is_default: bool, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct ClientInfo { + pub id: ClientId, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub uid: Option, + pub nickname: String, + pub channel: ChannelId, + /// ServerQuery clients (bots, our own relays). UIs normally hide them. + #[serde(default)] + pub is_query: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub away: Option, + #[serde(default)] + pub input_muted: bool, + #[serde(default)] + pub output_muted: bool, + /// `None` when the source cannot tell (query sessions see no voice). + #[serde(default, skip_serializing_if = "Option::is_none")] + pub talking: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub streaming: Option, + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub server_groups: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub country: Option, +} + +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PresenceSnapshot { + pub server_name: String, + pub channels: Vec, + pub clients: Vec, +} + +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum PresenceDelta { + ChannelAdded(ChannelInfo), + ChannelChanged(ChannelInfo), + ChannelRemoved { id: ChannelId }, + ClientJoined(ClientInfo), + ClientChanged(ClientInfo), + ClientMoved { id: ClientId, channel: ChannelId }, + ClientLeft { id: ClientId }, + ServerRenamed { name: String }, +} + +/// Current state; apply deltas as they arrive. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Presence { + pub server_name: String, + pub channels: BTreeMap, + pub clients: BTreeMap, +} + +impl Presence { + pub fn from_snapshot(s: PresenceSnapshot) -> Self { + Self { + server_name: s.server_name, + channels: s.channels.into_iter().map(|c| (c.id, c)).collect(), + clients: s.clients.into_iter().map(|c| (c.id, c)).collect(), + } + } + + pub fn snapshot(&self) -> PresenceSnapshot { + PresenceSnapshot { + server_name: self.server_name.clone(), + channels: self.channels.values().cloned().collect(), + clients: self.clients.values().cloned().collect(), + } + } + + /// Apply a delta. Returns `false` if it referred to something unknown + /// (the caller may want to resynchronise). + pub fn apply(&mut self, delta: &PresenceDelta) -> bool { + match delta { + PresenceDelta::ChannelAdded(c) | PresenceDelta::ChannelChanged(c) => { + self.channels.insert(c.id, c.clone()); + true + } + PresenceDelta::ChannelRemoved { id } => self.channels.remove(id).is_some(), + PresenceDelta::ClientJoined(c) | PresenceDelta::ClientChanged(c) => { + self.clients.insert(c.id, c.clone()); + true + } + PresenceDelta::ClientMoved { id, channel } => match self.clients.get_mut(id) { + Some(c) => { + c.channel = *channel; + true + } + None => false, + }, + PresenceDelta::ClientLeft { id } => self.clients.remove(id).is_some(), + PresenceDelta::ServerRenamed { name } => { + self.server_name = name.clone(); + true + } + } + } + + /// Deltas that turn `self` into `new`, for sources that poll. + pub fn diff(&self, new: &Presence) -> Vec { + let mut out = Vec::new(); + if self.server_name != new.server_name { + out.push(PresenceDelta::ServerRenamed { name: new.server_name.clone() }); + } + for (id, c) in &new.channels { + match self.channels.get(id) { + None => out.push(PresenceDelta::ChannelAdded(c.clone())), + Some(old) if old != c => out.push(PresenceDelta::ChannelChanged(c.clone())), + _ => {} + } + } + for (id, c) in &new.clients { + match self.clients.get(id) { + None => out.push(PresenceDelta::ClientJoined(c.clone())), + Some(old) if old == c => {} + Some(old) if ClientInfo { channel: c.channel, ..old.clone() } == *c => { + out.push(PresenceDelta::ClientMoved { id: *id, channel: c.channel }); + } + Some(_) => out.push(PresenceDelta::ClientChanged(c.clone())), + } + } + for id in self.clients.keys().filter(|id| !new.clients.contains_key(id)) { + out.push(PresenceDelta::ClientLeft { id: *id }); + } + // Channels last, so clients leave a removed channel first. + for id in self.channels.keys().filter(|id| !new.channels.contains_key(id)) { + out.push(PresenceDelta::ChannelRemoved { id: *id }); + } + out + } + + /// Clients in a channel, excluding query clients. + pub fn members(&self, channel: ChannelId) -> impl Iterator { + self.clients.values().filter(move |c| c.channel == channel && !c.is_query) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn ch(id: u64, name: &str) -> ChannelInfo { + ChannelInfo { id, name: name.into(), ..Default::default() } + } + + fn cl(id: u16, name: &str, channel: u64) -> ClientInfo { + ClientInfo { id, nickname: name.into(), channel, ..Default::default() } + } + + fn presence(channels: Vec, clients: Vec) -> Presence { + Presence::from_snapshot(PresenceSnapshot { server_name: "s".into(), channels, clients }) + } + + #[test] + fn diff_then_apply_reaches_target() { + let old = presence( + vec![ch(1, "Lobby"), ch(2, "Games")], + vec![cl(1, "Alice", 1), cl(2, "Bob", 1), cl(3, "Carol", 2)], + ); + let mut muted = cl(2, "Bob", 1); + muted.input_muted = true; + let new = presence( + vec![ch(1, "Lobby"), ch(3, "New")], + vec![cl(1, "Alice", 3), muted, cl(4, "Dave", 1)], + ); + let deltas = old.diff(&new); + assert!(deltas.contains(&PresenceDelta::ClientMoved { id: 1, channel: 3 })); + assert!(deltas.contains(&PresenceDelta::ClientLeft { id: 3 })); + assert!(deltas.contains(&PresenceDelta::ChannelRemoved { id: 2 })); + assert!(deltas.iter().any(|d| matches!(d, PresenceDelta::ClientChanged(c) if c.id == 2))); + let mut state = old.clone(); + for d in &deltas { + assert!(state.apply(d)); + } + assert_eq!(state, new); + assert!(new.diff(&new).is_empty()); + } + + #[test] + fn members_skip_query_clients() { + let mut bot = cl(9, "bot", 1); + bot.is_query = true; + let p = presence(vec![ch(1, "Lobby")], vec![cl(1, "Alice", 1), bot]); + assert_eq!(p.members(1).count(), 1); + } + + #[test] + fn delta_json_is_tagged() { + let json = + serde_json::to_string(&PresenceDelta::ClientMoved { id: 1, channel: 3 }).unwrap(); + assert_eq!(json, r#"{"kind":"client_moved","id":1,"channel":3}"#); + let back: PresenceDelta = serde_json::from_str(&json).unwrap(); + assert_eq!(back, PresenceDelta::ClientMoved { id: 1, channel: 3 }); + } +} diff --git a/crates/tsc-observer/Cargo.toml b/crates/tsc-observer/Cargo.toml new file mode 100644 index 0000000..f9a9f62 --- /dev/null +++ b/crates/tsc-observer/Cargo.toml @@ -0,0 +1,22 @@ +[package] +name = "tsc-observer" +version = "0.1.0" +description = "Invisible presence and channel-chat relays over ServerQuery." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +thiserror = "2" +tokio = { version = "1", features = ["macros", "rt", "sync", "time"] } +tracing = "0.1" +tsc-model = { path = "../tsc-model" } +tsc-query = { path = "../tsc-query" } + +[dev-dependencies] +tokio = { version = "1", features = ["macros", "rt-multi-thread", "test-util"] } + +[lints] +workspace = true diff --git a/crates/tsc-observer/src/convert.rs b/crates/tsc-observer/src/convert.rs new file mode 100644 index 0000000..b74e3c6 --- /dev/null +++ b/crates/tsc-observer/src/convert.rs @@ -0,0 +1,218 @@ +//! Query rows and events to model types. + +use tsc_model::{ChannelInfo, ChatMessage, ChatTarget, ClientInfo, PresenceDelta}; +use tsc_query::{Notification, Row}; + +/// From a `channellist -topic -flags -voice -limits` row, or the fields of +/// `notifychannelcreated`. +pub fn channel_from_row(row: &Row) -> Option { + Some(ChannelInfo { + id: row.parse("cid")?, + parent: row.parse("pid").or_else(|| row.parse("cpid")).unwrap_or(0), + order: row.parse("channel_order").unwrap_or(0), + name: row.get("channel_name").unwrap_or_default().to_string(), + topic: row.get("channel_topic").filter(|t| !t.is_empty()).map(str::to_string), + has_password: row.flag("channel_flag_password").unwrap_or(false), + max_clients: row.parse::("channel_maxclients").filter(|m| *m >= 0), + needed_subscribe_power: row.parse("channel_needed_subscribe_power").unwrap_or(0), + needed_talk_power: row.parse("channel_needed_talk_power").unwrap_or(0), + is_default: row.flag("channel_flag_default").unwrap_or(false), + }) +} + +/// Update `channel` with the properties present in `row` (for +/// `notifychanneledited`, which only carries what changed). +pub fn update_channel(channel: &mut ChannelInfo, row: &Row) { + if let Some(name) = row.get("channel_name") { + channel.name = name.to_string(); + } + if let Some(topic) = row.get("channel_topic") { + channel.topic = Some(topic.to_string()).filter(|t| !t.is_empty()); + } + if let Some(order) = row.parse("channel_order") { + channel.order = order; + } + if let Some(p) = row.flag("channel_flag_password") { + channel.has_password = p; + } + if let Some(m) = row.parse::("channel_maxclients") { + channel.max_clients = Some(m).filter(|m| *m >= 0); + } + if let Some(p) = row.parse("channel_needed_subscribe_power") { + channel.needed_subscribe_power = p; + } + if let Some(p) = row.parse("channel_needed_talk_power") { + channel.needed_talk_power = p; + } + if let Some(d) = row.flag("channel_flag_default") { + channel.is_default = d; + } +} + +/// From a `clientlist -uid -away -voice -groups -country` row or a +/// `notifycliententerview` row (which names the channel `ctid`). +pub fn client_from_row(row: &Row) -> Option { + let away = row.flag("client_away").unwrap_or(false); + Some(ClientInfo { + id: row.parse("clid")?, + uid: row.get("client_unique_identifier").map(str::to_string), + nickname: row.get("client_nickname").unwrap_or_default().to_string(), + channel: row.parse("cid").or_else(|| row.parse("ctid"))?, + is_query: row.parse::("client_type") == Some(1), + away: away.then(|| row.get("client_away_message").unwrap_or_default().to_string()), + input_muted: row.flag("client_input_muted").unwrap_or(false), + output_muted: row.flag("client_output_muted").unwrap_or(false), + talking: row.flag("client_flag_talking"), + streaming: row.flag("client_is_streaming"), + server_groups: row + .get("client_servergroups") + .map(|g| g.split(',').filter_map(|g| g.parse().ok()).collect()) + .unwrap_or_default(), + country: row.get("client_country").filter(|c| !c.is_empty()).map(str::to_string), + }) +} + +/// Presence changes carried by a query event. `notifychanneledited` needs the +/// current channel state and is handled by the observer. +pub fn delta_from_notification(n: &Notification) -> Vec { + let rows = n.rows.iter(); + match n.name.as_str() { + "notifycliententerview" => { + rows.filter_map(client_from_row).map(PresenceDelta::ClientJoined).collect() + } + "notifyclientleftview" => rows + .filter_map(|r| r.parse("clid")) + .map(|id| PresenceDelta::ClientLeft { id }) + .collect(), + "notifyclientmoved" => { + // Several clients can move at once; ctid is only in the first row. + let ctid = n.rows.first().and_then(|r| r.parse("ctid")); + rows.filter_map(|r| { + Some(PresenceDelta::ClientMoved { + id: r.parse("clid")?, + channel: r.parse("ctid").or(ctid)?, + }) + }) + .collect() + } + "notifychannelcreated" => { + rows.filter_map(channel_from_row).map(PresenceDelta::ChannelAdded).collect() + } + "notifychanneldeleted" => rows + .filter_map(|r| r.parse("cid")) + .map(|id| PresenceDelta::ChannelRemoved { id }) + .collect(), + "notifyserveredited" => rows + .filter_map(|r| r.get("virtualserver_name")) + .map(|name| PresenceDelta::ServerRenamed { name: name.to_string() }) + .collect(), + _ => Vec::new(), + } +} + +/// A `notifytextmessage` as a chat message. +pub fn is_text_message(n: &Notification, now_ms: i64) -> Option { + if n.name != "notifytextmessage" { + return None; + } + let row = n.rows.first()?; + let target = match row.parse::("targetmode")? { + 3 => ChatTarget::Server, + 2 => ChatTarget::Channel(0), // filled in by the receiver, who knows its channel + 1 => ChatTarget::Private(row.get("invokeruid").unwrap_or_default().to_string()), + _ => return None, + }; + Some(ChatMessage { + target, + author_name: row.get("invokername").unwrap_or_default().to_string(), + author_uid: row.get("invokeruid").map(str::to_string), + author_id: row.parse("invokerid"), + text: row.get("msg").unwrap_or_default().to_string(), + ts_ms: now_ms, + via_relay: true, + }) +} + +#[cfg(test)] +mod tests { + use tsc_query::{Line, parse_line}; + + use super::*; + + fn notify(line: &str) -> Notification { + match parse_line(line) { + Line::Notify(n) => n, + other => panic!("{other:?}"), + } + } + + #[test] + fn clientlist_row() { + // Captured from TeamSpeak 6.0.0-beta13.1 (clientlist -uid -away -voice -groups -country). + let row = &tsc_query::parse_rows( + "clid=7 cid=1 client_database_id=4 client_nickname=sample client_type=0 client_away=0 \ + client_away_message client_flag_talking=0 client_input_muted=1 client_output_muted=0 \ + client_unique_identifier=hSC9DusMo3MJwDuA8MuvZBaHfb\\/h77N9WZtYskAFlG0= \ + client_servergroups=8,9 client_country", + )[0]; + let c = client_from_row(row).unwrap(); + assert_eq!((c.id, c.channel, c.nickname.as_str()), (7, 1, "sample")); + assert!(!c.is_query && c.input_muted && c.away.is_none()); + assert_eq!(c.talking, Some(false)); + assert_eq!(c.server_groups, vec![8, 9]); + assert_eq!(c.uid.as_deref(), Some("hSC9DusMo3MJwDuA8MuvZBaHfb/h77N9WZtYskAFlG0=")); + assert_eq!(c.country, None); + } + + #[test] + fn channellist_row() { + let row = &tsc_query::parse_rows( + "cid=1 pid=0 channel_order=0 channel_name=Default\\sChannel channel_topic=t \ + channel_flag_default=1 channel_flag_password=0 channel_maxclients=-1 \ + channel_needed_subscribe_power=0 channel_needed_talk_power=5", + )[0]; + let c = channel_from_row(row).unwrap(); + assert_eq!(c.name, "Default Channel"); + assert!(c.is_default && !c.has_password); + assert_eq!(c.max_clients, None); + assert_eq!(c.needed_talk_power, 5); + } + + #[test] + fn events_to_deltas() { + let n = notify( + "notifycliententerview cfid=0 ctid=1 reasonid=0 clid=6 \ + client_unique_identifier=abc client_nickname=evtest client_type=0", + ); + match &delta_from_notification(&n)[..] { + [PresenceDelta::ClientJoined(c)] => assert_eq!((c.id, c.channel), (6, 1)), + other => panic!("{other:?}"), + } + let n = notify("notifyclientmoved ctid=5 reasonid=0 clid=6|clid=7"); + assert_eq!( + delta_from_notification(&n), + vec![ + PresenceDelta::ClientMoved { id: 6, channel: 5 }, + PresenceDelta::ClientMoved { id: 7, channel: 5 }, + ] + ); + let n = notify("notifyclientleftview cfid=1 ctid=0 reasonid=8 clid=6"); + assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ClientLeft { id: 6 }]); + let n = notify("notifychanneldeleted cid=3 invokerid=0"); + assert_eq!(delta_from_notification(&n), vec![PresenceDelta::ChannelRemoved { id: 3 }]); + } + + #[test] + fn text_messages() { + let n = notify( + "notifytextmessage targetmode=3 msg=hi\\sall invokerid=5 invokername=Bob invokeruid=u", + ); + let m = is_text_message(&n, 42).unwrap(); + assert_eq!(m.target, ChatTarget::Server); + assert_eq!( + (m.text.as_str(), m.author_name.as_str(), m.author_id), + ("hi all", "Bob", Some(5)) + ); + assert!(is_text_message(¬ify("notifyclientleftview clid=1"), 0).is_none()); + } +} diff --git a/crates/tsc-observer/src/lib.rs b/crates/tsc-observer/src/lib.rs new file mode 100644 index 0000000..2cb1510 --- /dev/null +++ b/crates/tsc-observer/src/lib.rs @@ -0,0 +1,17 @@ +//! Invisible presence and channel-chat relays over ServerQuery. +//! +//! Query clients do not show up in normal clients' channel trees. The +//! [`Observer`] keeps a live [`Presence`](tsc_model::Presence) of a server +//! from one query session. A [`RelayPool`] puts one query session into each +//! channel whose chat someone wants to read or write without joining it. +//! +//! Used by the gateway (`tsgw`) for all of its users and by the client for +//! users who have their own query credentials. + +mod convert; +mod observer; +mod relay; + +pub use convert::{channel_from_row, client_from_row, delta_from_notification, is_text_message}; +pub use observer::{Observer, ObserverConfig, ObserverEvent}; +pub use relay::{RelayConfig, RelayEvent, RelayPool}; diff --git a/crates/tsc-observer/src/observer.rs b/crates/tsc-observer/src/observer.rs new file mode 100644 index 0000000..5b6f589 --- /dev/null +++ b/crates/tsc-observer/src/observer.rs @@ -0,0 +1,234 @@ +//! Keep a server's presence up to date from one query session. + +use std::sync::{Arc, RwLock}; +use std::time::Duration; + +use tokio::sync::{broadcast, watch}; +use tokio::time::{Instant, sleep, sleep_until}; +use tracing::{debug, info, warn}; +use tsc_model::{ChatMessage, Presence, PresenceDelta, PresenceSnapshot}; +use tsc_query::{Command, Connect, Notification, QueryClient}; + +use crate::convert::{ + channel_from_row, client_from_row, delta_from_notification, is_text_message, update_channel, +}; + +#[derive(Clone, Debug)] +pub struct ObserverConfig { + pub connect: Connect, + /// Full resync interval. Query sessions receive no `notifyclientupdated`, + /// so mute/away changes are only noticed by re-reading the client list. + pub poll_interval: Duration, + /// Also deliver server chat (`event=textserver`). + pub server_chat: bool, + /// Wait between reconnect attempts. + pub reconnect_delay: Duration, +} + +impl ObserverConfig { + pub fn new(connect: Connect) -> Self { + Self { + connect, + poll_interval: Duration::from_secs(10), + server_chat: true, + reconnect_delay: Duration::from_secs(5), + } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum ObserverEvent { + /// Full state; sent after every (re)connect. + Snapshot(PresenceSnapshot), + Delta(PresenceDelta), + Chat(ChatMessage), + /// Lost the query connection; presence may be stale until the next snapshot. + Disconnected(String), +} + +/// Handle to a running observer. Dropping it stops the task. +pub struct Observer { + presence: Arc>, + events: broadcast::Sender, + _stop: watch::Sender<()>, +} + +impl Observer { + pub fn spawn(config: ObserverConfig) -> Self { + let presence = Arc::new(RwLock::new(Presence::default())); + let (events, _) = broadcast::channel(1024); + let (stop, stopped) = watch::channel(()); + tokio::spawn(run(config, presence.clone(), events.clone(), stopped)); + Self { presence, events, _stop: stop } + } + + /// Receive events. Call [`Observer::snapshot`] after subscribing to get + /// the state the events apply to. + pub fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } + + pub fn snapshot(&self) -> PresenceSnapshot { + self.presence.read().unwrap().snapshot() + } + + pub fn presence(&self) -> Arc> { + self.presence.clone() + } +} + +async fn run( + config: ObserverConfig, + presence: Arc>, + events: broadcast::Sender, + mut stopped: watch::Receiver<()>, +) { + loop { + let result = tokio::select! { + r = session(&config, &presence, &events) => r, + _ = stopped.changed() => return, + }; + let reason = match result { + Ok(()) => "connection closed".to_string(), + Err(e) => e.to_string(), + }; + warn!(%reason, addr = %config.connect.addr, "observer disconnected"); + let _ = events.send(ObserverEvent::Disconnected(reason)); + tokio::select! { + _ = sleep(config.reconnect_delay) => {} + _ = stopped.changed() => return, + } + } +} + +/// Read the full state. +async fn load(client: &QueryClient) -> tsc_query::Result { + let info = client.send(&Command::new("serverinfo")).await?; + let channels = client + .send(&Command::new("channellist").flag("topic").flag("flags").flag("voice").flag("limits")) + .await?; + let clients = client + .send( + &Command::new("clientlist") + .flag("uid") + .flag("away") + .flag("voice") + .flag("groups") + .flag("country"), + ) + .await?; + Ok(Presence::from_snapshot(PresenceSnapshot { + server_name: info + .first() + .and_then(|r| r.get("virtualserver_name")) + .unwrap_or_default() + .to_string(), + channels: channels.iter().filter_map(channel_from_row).collect(), + clients: clients.iter().filter_map(client_from_row).collect(), + })) +} + +fn now_ms() -> i64 { + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default() +} + +async fn session( + config: &ObserverConfig, + presence: &RwLock, + events: &broadcast::Sender, +) -> tsc_query::Result<()> { + let (client, mut notifications) = QueryClient::connect(&config.connect).await?; + if notifications.is_some() { + for event in ["server", "channel"] { + let mut cmd = Command::new("servernotifyregister").arg("event", event); + if event == "channel" { + cmd = cmd.arg("id", 0); + } + client.send(&cmd).await?; + } + if config.server_chat { + client.send(&Command::new("servernotifyregister").arg("event", "textserver")).await?; + } + } + let state = load(&client).await?; + info!( + server = %state.server_name, + channels = state.channels.len(), + clients = state.clients.len(), + events = notifications.is_some(), + "observer connected" + ); + *presence.write().unwrap() = state.clone(); + let _ = events.send(ObserverEvent::Snapshot(state.snapshot())); + + let mut next_poll = Instant::now() + config.poll_interval; + loop { + let notification: Option = tokio::select! { + n = async { + match &mut notifications { + Some(rx) => rx.recv().await, + None => std::future::pending().await, + } + } => match n { + Some(n) => Some(n), + None => return Ok(()), + }, + _ = sleep_until(next_poll) => None, + }; + + match notification { + Some(n) => handle_notification(&n, presence, events), + None => { + // Resync and publish only what changed. + let fresh = load(&client).await?; + let deltas = presence.read().unwrap().diff(&fresh); + if !deltas.is_empty() { + debug!(changes = deltas.len(), "observer resync"); + } + *presence.write().unwrap() = fresh; + for d in deltas { + let _ = events.send(ObserverEvent::Delta(d)); + } + next_poll = Instant::now() + config.poll_interval; + } + } + } +} + +fn handle_notification( + n: &Notification, + presence: &RwLock, + events: &broadcast::Sender, +) { + if let Some(msg) = is_text_message(n, now_ms()) { + let _ = events.send(ObserverEvent::Chat(msg)); + return; + } + let deltas = if n.name == "notifychanneledited" || n.name == "notifychannelmoved" { + let state = presence.read().unwrap(); + n.rows + .iter() + .filter_map(|row| { + let mut channel = state.channels.get(&row.parse("cid")?)?.clone(); + update_channel(&mut channel, row); + if let Some(parent) = row.parse("cpid") { + channel.parent = parent; + } + if let Some(order) = row.parse("order") { + channel.order = order; + } + Some(PresenceDelta::ChannelChanged(channel)) + }) + .collect() + } else { + delta_from_notification(n) + }; + let mut state = presence.write().unwrap(); + for d in deltas { + state.apply(&d); + let _ = events.send(ObserverEvent::Delta(d)); + } +} diff --git a/crates/tsc-observer/src/relay.rs b/crates/tsc-observer/src/relay.rs new file mode 100644 index 0000000..edf23cc --- /dev/null +++ b/crates/tsc-observer/src/relay.rs @@ -0,0 +1,190 @@ +//! Channel-chat relays: one query session sitting in each relayed channel. +//! +//! TeamSpeak only delivers channel chat to clients in that channel, and a +//! client can only post to its own channel. A relay session is an invisible +//! query client moved into the channel; it forwards what is said there and +//! posts messages on behalf of users as `[Nick] text`. + +use std::collections::HashMap; +use std::sync::Arc; + +use tokio::sync::{Mutex, broadcast, mpsc}; +use tokio::task::JoinHandle; +use tracing::{debug, info, warn}; +use tsc_model::{ChannelId, ChatMessage, ChatTarget, relay_text, split_message}; +use tsc_query::{Command, Connect, Notification, QueryClient}; + +use crate::convert::is_text_message; + +/// `clientupdate client_nickname=` with a name someone else has. +const ERR_NICKNAME_IN_USE: u32 = 513; +/// `clientmove` into the channel the client is already in. +const ERR_ALREADY_MEMBER: u32 = 770; + +/// TeamSpeak's limit for one text message. +const MAX_MESSAGE_BYTES: usize = 1024; + +#[derive(Clone, Debug)] +pub struct RelayConfig { + pub connect: Connect, + /// Base nickname; the channel id is appended because nicknames are unique. + pub nickname: String, + /// How posts appear, with `{nick}` and `{text}` placeholders. + pub format: String, +} + +impl RelayConfig { + pub fn new(connect: Connect) -> Self { + Self { connect, nickname: "Chat Relay".into(), format: "[{nick}] {text}".into() } + } +} + +#[derive(Clone, Debug, PartialEq)] +pub enum RelayEvent { + /// Someone wrote in a relayed channel (our own posts are not echoed). + Message(ChatMessage), + /// A relay stopped (connection lost or closed). + Closed { channel: ChannelId, reason: String }, +} + +struct Session { + client: QueryClient, + task: JoinHandle<()>, +} + +impl Drop for Session { + fn drop(&mut self) { + self.task.abort(); + } +} + +/// Manages relay sessions, at most one per channel. +#[derive(Clone)] +pub struct RelayPool { + config: Arc, + sessions: Arc>>, + events: broadcast::Sender, +} + +impl RelayPool { + pub fn new(config: RelayConfig) -> Self { + let (events, _) = broadcast::channel(1024); + Self { config: Arc::new(config), sessions: Default::default(), events } + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.events.subscribe() + } + + /// Channels with an open relay. + pub async fn channels(&self) -> Vec { + self.sessions.lock().await.keys().copied().collect() + } + + /// Start relaying a channel (no-op if already open). + pub async fn open(&self, channel: ChannelId) -> tsc_query::Result<()> { + let mut sessions = self.sessions.lock().await; + if sessions.get(&channel).is_some_and(|s| !s.task.is_finished()) { + return Ok(()); + } + let (client, notifications) = QueryClient::connect(&self.config.connect).await?; + let Some(notifications) = notifications else { + return Err(tsc_query::Error::Unsupported("relays need a transport with events")); + }; + let own_id = client.own_client_id().await?; + set_nickname(&client, &format!("{} {channel}", self.config.nickname)).await; + match client.send(&Command::new("clientmove").arg("clid", own_id).arg("cid", channel)).await + { + // Query clients start in the default channel. + Err(tsc_query::Error::Query(e)) if e.id == ERR_ALREADY_MEMBER => {} + other => { + other?; + } + } + client.send(&Command::new("servernotifyregister").arg("event", "textchannel")).await?; + info!(channel, own_id, "relay opened"); + let task = tokio::spawn(forward(channel, own_id, notifications, self.events.clone())); + sessions.insert(channel, Session { client, task }); + Ok(()) + } + + /// Stop relaying a channel. + pub async fn close(&self, channel: ChannelId) { + let session = self.sessions.lock().await.remove(&channel); + if let Some(session) = session { + session.client.quit().await; + info!(channel, "relay closed"); + } + } + + /// Stop all relays. + pub async fn close_all(&self) { + let sessions: Vec<_> = self.sessions.lock().await.drain().collect(); + for (channel, session) in sessions { + session.client.quit().await; + info!(channel, "relay closed"); + } + } + + /// Post `text` in `channel` on behalf of `nick`, opening a relay if needed. + pub async fn send(&self, channel: ChannelId, nick: &str, text: &str) -> tsc_query::Result<()> { + self.open(channel).await?; + let client = match self.sessions.lock().await.get(&channel) { + Some(s) => s.client.clone(), + None => return Err(tsc_query::Error::Closed), + }; + let full = relay_text(&self.config.format, nick, text); + for part in split_message(&full, MAX_MESSAGE_BYTES) { + client + .send( + &Command::new("sendtextmessage") + .arg("targetmode", 2) + .arg("target", channel) + .arg("msg", part), + ) + .await?; + } + Ok(()) + } +} + +/// Nicknames are unique per server; try a few numbered variants. The name is +/// cosmetic, so failing keeps the server-assigned one. +async fn set_nickname(client: &QueryClient, base: &str) { + for attempt in 1..=5 { + let nickname = if attempt == 1 { base.to_string() } else { format!("{base} ({attempt})") }; + match client.send(&Command::new("clientupdate").arg("client_nickname", &nickname)).await { + Ok(_) => return, + Err(tsc_query::Error::Query(e)) if e.id == ERR_NICKNAME_IN_USE => continue, + Err(e) => { + warn!(%e, %nickname, "could not set relay nickname"); + return; + } + } + } + warn!(base, "all relay nicknames in use"); +} + +async fn forward( + channel: ChannelId, + own_id: u16, + mut notifications: mpsc::UnboundedReceiver, + events: broadcast::Sender, +) { + while let Some(n) = notifications.recv().await { + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .map(|d| d.as_millis() as i64) + .unwrap_or_default(); + let Some(mut msg) = is_text_message(&n, now) else { continue }; + if msg.author_id == Some(own_id) { + continue; + } + if msg.target == ChatTarget::Channel(0) { + msg.target = ChatTarget::Channel(channel); + } + debug!(channel, author = %msg.author_name, "relayed message"); + let _ = events.send(RelayEvent::Message(msg)); + } + let _ = events.send(RelayEvent::Closed { channel, reason: "connection closed".into() }); +} diff --git a/crates/tsc-query/Cargo.toml b/crates/tsc-query/Cargo.toml new file mode 100644 index 0000000..37dcdb3 --- /dev/null +++ b/crates/tsc-query/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "tsc-query" +version = "0.1.0" +description = "TeamSpeak ServerQuery client: raw TCP, SSH and HTTP WebQuery transports." +edition.workspace = true +rust-version.workspace = true +license.workspace = true +repository.workspace = true +publish.workspace = true + +[dependencies] +reqwest = { version = "0.13.5", default-features = false, features = ["json", "query", "rustls"] } +russh = "0.63.3" +serde = { version = "1.0.229", features = ["derive"] } +serde_json = "1.0.151" +thiserror = "2.0.21" +tokio = { version = "1.53.1", features = ["net", "io-util", "sync", "time", "rt", "macros"] } +tracing = "0.1.44" + +[lints] +workspace = true + +[dev-dependencies] +tokio = { version = "1.53.1", features = ["rt-multi-thread", "macros", "test-util"] } diff --git a/crates/tsc-query/src/client.rs b/crates/tsc-query/src/client.rs new file mode 100644 index 0000000..c006dc9 --- /dev/null +++ b/crates/tsc-query/src/client.rs @@ -0,0 +1,149 @@ +//! Transport-independent query client. + +use tokio::io::split; +use tokio::net::TcpStream; +use tokio::sync::mpsc; + +use crate::codec::{Command, Notification, Row}; +use crate::http::HttpClient; +use crate::line::{LineClient, LineOptions}; +use crate::{Error, Result}; + +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Transport { + Raw, + Ssh, + Http, +} + +/// Everything needed to open a query connection. +#[derive(Clone, Debug)] +pub struct Connect { + pub transport: Transport, + /// host:port of the query interface. + pub addr: String, + /// Login name (raw/SSH). Ignored for HTTP. + pub user: String, + /// Password (raw/SSH) or API key (HTTP, optional for guest access). + pub secret: Option, + /// Select the virtual server by voice port (`use port=`)... + pub server_port: Option, + /// ...or by id (defaults to 1). + pub server_id: Option, + pub line: LineOptions, +} + +/// A logged-in query connection with a selected virtual server. +#[derive(Clone)] +pub enum QueryClient { + Line(LineClient), + Http(HttpClient), +} + +impl QueryClient { + /// Connect, log in and select the virtual server. The event receiver is + /// `None` for HTTP, which has no events. + pub async fn connect( + cfg: &Connect, + ) -> Result<(Self, Option>)> { + match cfg.transport { + Transport::Raw => { + let stream = TcpStream::connect(&cfg.addr).await?; + stream.set_nodelay(true)?; + let (r, w) = stream.into_split(); + let (client, events) = LineClient::spawn(r, w, cfg.line.clone()); + let client = Self::Line(client); + client.login_and_use(cfg).await?; + Ok((client, Some(events))) + } + Transport::Ssh => { + let password = cfg.secret.as_deref().unwrap_or_default(); + let shell = crate::ssh::connect(&cfg.addr, &cfg.user, password).await?; + tracing::debug!(fingerprint = ?shell.fingerprint, addr = %cfg.addr, "ssh query connected"); + let (r, w) = split(shell.stream); + let (client, events) = + LineClient::spawn_with_guard(r, w, cfg.line.clone(), shell.session); + let client = Self::Line(client); + // SSH already authenticated; only select the server. + client.use_server(cfg).await?; + Ok((client, Some(events))) + } + Transport::Http => { + let base = if cfg.addr.contains("://") { + cfg.addr.clone() + } else { + format!("http://{}", cfg.addr) + }; + let mut client = + HttpClient::new(&base, cfg.secret.clone(), cfg.server_id.unwrap_or(1))?; + if let Some(port) = cfg.server_port { + // Resolve the port to a server id once. + let servers = client.send(&Command::new("serverlist")).await?; + let sid = servers + .iter() + .find(|r| r.parse::("virtualserver_port") == Some(port)) + .and_then(|r| r.parse("virtualserver_id")) + .ok_or_else(|| { + Error::Protocol(format!("no virtual server on port {port}")) + })?; + client.set_sid(sid); + } + Ok((Self::Http(client), None)) + } + } + } + + async fn login_and_use(&self, cfg: &Connect) -> Result<()> { + if let Some(password) = &cfg.secret { + self.send( + &Command::new("login") + .arg("client_login_name", &cfg.user) + .arg("client_login_password", password), + ) + .await?; + } + self.use_server(cfg).await + } + + async fn use_server(&self, cfg: &Connect) -> Result<()> { + let cmd = match (cfg.server_port, cfg.server_id) { + (Some(port), _) => Command::new("use").arg("port", port), + (None, sid) => Command::new("use").arg("sid", sid.unwrap_or(1)), + }; + self.send(&cmd).await.map(|_| ()) + } + + pub async fn send(&self, cmd: &Command) -> Result> { + match self { + QueryClient::Line(c) => c.send(cmd).await, + QueryClient::Http(c) => c.send(cmd).await, + } + } + + /// End the session politely (servers otherwise keep SSH query clients + /// around until they time out). HTTP has no session to end. + pub async fn quit(&self) { + if let QueryClient::Line(c) = self { + // The server closes the connection instead of answering. + let _ = tokio::time::timeout( + std::time::Duration::from_secs(2), + c.send(&Command::new("quit")), + ) + .await; + } + } + + /// Whether the transport delivers `notify*` events. + pub fn has_events(&self) -> bool { + matches!(self, QueryClient::Line(_)) + } + + /// Our own client id (`whoami`). + pub async fn own_client_id(&self) -> Result { + let rows = self.send(&Command::new("whoami")).await?; + rows.first() + .and_then(|r| r.parse("client_id")) + .ok_or_else(|| Error::Protocol("whoami without client_id".into())) + } +} diff --git a/crates/tsc-query/src/codec.rs b/crates/tsc-query/src/codec.rs new file mode 100644 index 0000000..ee25ba6 --- /dev/null +++ b/crates/tsc-query/src/codec.rs @@ -0,0 +1,352 @@ +//! ServerQuery text format: escaping, commands, responses and events. +//! +//! A response is zero or more data lines followed by `error id=0 msg=ok`. +//! Data is a list of rows separated by `|`, each row a space-separated list of +//! `key=value` pairs. Events are lines starting with `notify`. + +use std::fmt; + +/// Escape a value for the query protocol. +pub fn escape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for c in s.chars() { + match c { + '\\' => out.push_str("\\\\"), + '/' => out.push_str("\\/"), + ' ' => out.push_str("\\s"), + '|' => out.push_str("\\p"), + '\x07' => out.push_str("\\a"), + '\x08' => out.push_str("\\b"), + '\x0c' => out.push_str("\\f"), + '\n' => out.push_str("\\n"), + '\r' => out.push_str("\\r"), + '\t' => out.push_str("\\t"), + '\x0b' => out.push_str("\\v"), + c => out.push(c), + } + } + out +} + +/// Reverse [`escape`]. Unknown escapes are kept as they are. +pub fn unescape(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + let mut chars = s.chars(); + while let Some(c) = chars.next() { + if c != '\\' { + out.push(c); + continue; + } + match chars.next() { + Some('\\') => out.push('\\'), + Some('/') => out.push('/'), + Some('s') => out.push(' '), + Some('p') => out.push('|'), + Some('a') => out.push('\x07'), + Some('b') => out.push('\x08'), + Some('f') => out.push('\x0c'), + Some('n') => out.push('\n'), + Some('r') => out.push('\r'), + Some('t') => out.push('\t'), + Some('v') => out.push('\x0b'), + Some(other) => { + out.push('\\'); + out.push(other); + } + None => out.push('\\'), + } + } + out +} + +/// One `key=value ...` group of a response or event. Keys keep their order; +/// a key without `=` has an empty value. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Row(pub Vec<(String, String)>); + +impl Row { + pub fn get(&self, key: &str) -> Option<&str> { + self.0.iter().find(|(k, _)| k == key).map(|(_, v)| v.as_str()) + } + + pub fn parse(&self, key: &str) -> Option { + self.get(key)?.parse().ok() + } + + /// `1` / `0` flags. + pub fn flag(&self, key: &str) -> Option { + self.get(key).map(|v| v == "1" || v.eq_ignore_ascii_case("true")) + } + + pub fn insert(&mut self, key: impl Into, value: impl Into) { + let key = key.into(); + let value = value.into(); + match self.0.iter_mut().find(|(k, _)| *k == key) { + Some(entry) => entry.1 = value, + None => self.0.push((key, value)), + } + } +} + +/// Parse `a=1 b=2|a=3` into rows. Keys shared by the first row are not +/// repeated by the server in later rows for some commands; callers that need +/// that should use [`Row::get`] on the first row as a fallback. +pub fn parse_rows(line: &str) -> Vec { + line.split('|') + .map(|part| { + Row(part + .split(' ') + .filter(|kv| !kv.is_empty()) + .map(|kv| match kv.split_once('=') { + Some((k, v)) => (k.to_string(), unescape(v)), + None => (kv.to_string(), String::new()), + }) + .collect()) + }) + .filter(|row| !row.0.is_empty()) + .collect() +} + +/// The `error` line that ends every response. +#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)] +pub struct QueryError { + pub id: u32, + pub msg: String, + pub extra_msg: Option, + pub failed_permid: Option, +} + +impl fmt::Display for QueryError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{} ({})", self.id, self.msg)?; + if let Some(extra) = &self.extra_msg { + write!(f, ": {extra}")?; + } + if let Some(perm) = self.failed_permid { + write!(f, " [failed permission {perm}]")?; + } + Ok(()) + } +} + +impl QueryError { + pub fn is_ok(&self) -> bool { + self.id == 0 + } + + /// The server has no data for a list command (`database empty result set`). + pub fn is_empty_result(&self) -> bool { + self.id == 1281 + } + + pub(crate) fn from_row(row: &Row) -> Self { + QueryError { + id: row.parse("id").unwrap_or(u32::MAX), + msg: row.get("msg").unwrap_or_default().to_string(), + extra_msg: row.get("extra_msg").map(str::to_string), + failed_permid: row.parse("failed_permid"), + } + } +} + +/// An event, e.g. `notifycliententerview`. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Notification { + /// Name including the `notify` prefix. + pub name: String, + pub rows: Vec, +} + +/// A classified line from a line-based transport. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Line { + Error(QueryError), + Notify(Notification), + Data(Vec), + Empty, +} + +pub fn parse_line(line: &str) -> Line { + let line = line.trim_matches(|c| c == '\r' || c == '\n'); + if line.is_empty() { + return Line::Empty; + } + if let Some(rest) = line.strip_prefix("error ") { + let row = parse_rows(rest).into_iter().next().unwrap_or_default(); + return Line::Error(QueryError::from_row(&row)); + } + if line.starts_with("notify") { + let (name, rest) = line.split_once(' ').unwrap_or((line, "")); + return Line::Notify(Notification { name: name.to_string(), rows: parse_rows(rest) }); + } + Line::Data(parse_rows(line)) +} + +/// A command to send, built with escaping applied. +/// +/// ``` +/// use tsc_query::Command; +/// let cmd = Command::new("sendtextmessage").arg("targetmode", 3).arg("msg", "hi there"); +/// assert_eq!(cmd.to_line(), "sendtextmessage targetmode=3 msg=hi\\sthere"); +/// ``` +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Command { + pub name: String, + /// Rows; the first row also carries the command-wide arguments. + pub rows: Vec>, + pub flags: Vec, +} + +impl Command { + pub fn new(name: impl Into) -> Self { + Self { name: name.into(), rows: vec![Vec::new()], flags: Vec::new() } + } + + /// Add an argument to the current row. + pub fn arg(mut self, key: impl Into, value: impl fmt::Display) -> Self { + self.rows.last_mut().unwrap().push((key.into(), value.to_string())); + self + } + + /// Start a new `|`-separated row. + pub fn row(mut self) -> Self { + self.rows.push(Vec::new()); + self + } + + /// Add an option like `-uid`. + pub fn flag(mut self, flag: impl Into) -> Self { + let flag = flag.into(); + self.flags.push(if flag.starts_with('-') { flag } else { format!("-{flag}") }); + self + } + + /// Parse an escaped command line such as `clientlist -uid` or + /// `clientmove clid=5 cid=2|clid=6`. + pub fn parse(line: &str) -> Option { + let line = line.trim(); + let (name, rest) = line.split_once(' ').unwrap_or((line, "")); + if name.is_empty() { + return None; + } + let mut cmd = Command::new(name); + for (i, part) in rest.split('|').enumerate() { + if i > 0 { + cmd = cmd.row(); + } + for token in part.split(' ').filter(|t| !t.is_empty()) { + if token.starts_with('-') && !token.contains('=') { + cmd.flags.push(token.to_string()); + } else { + let (k, v) = token.split_once('=').unwrap_or((token, "")); + cmd = cmd.arg(k, unescape(v)); + } + } + } + Some(cmd) + } + + /// Render for line-based transports (no trailing newline). + pub fn to_line(&self) -> String { + let mut out = self.name.clone(); + for (i, row) in self.rows.iter().enumerate() { + if i > 0 { + out.push('|'); + } else if !row.is_empty() { + out.push(' '); + } + let parts: Vec = + row.iter().map(|(k, v)| format!("{k}={}", escape(v))).collect(); + out.push_str(&parts.join(" ")); + } + for flag in &self.flags { + out.push(' '); + out.push_str(flag); + } + out + } +} + +impl fmt::Display for Command { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.to_line()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn escape_roundtrip() { + let s = "a b|c\\d/e\nf\tg"; + assert_eq!(escape(s), "a\\sb\\pc\\\\d\\/e\\nf\\tg"); + assert_eq!(unescape(&escape(s)), s); + assert_eq!(unescape("trailing\\"), "trailing\\"); + assert_eq!(unescape("\\x"), "\\x"); + } + + #[test] + fn parses_lines() { + assert_eq!(parse_line("\n\r"), Line::Empty); + match parse_line("error id=1281 msg=database\\sempty\\sresult\\sset\n\r") { + Line::Error(e) => { + assert!(e.is_empty_result()); + assert_eq!(e.msg, "database empty result set"); + } + other => panic!("{other:?}"), + } + match parse_line("notifytextmessage targetmode=3 msg=hi\\sall invokerid=5 invokername=Bob") + { + Line::Notify(n) => { + assert_eq!(n.name, "notifytextmessage"); + assert_eq!(n.rows[0].get("msg"), Some("hi all")); + assert_eq!(n.rows[0].parse::("invokerid"), Some(5)); + } + other => panic!("{other:?}"), + } + match parse_line("clid=1 cid=1 client_nickname=A|clid=2 cid=3 client_nickname=B\\sC") { + Line::Data(rows) => { + assert_eq!(rows.len(), 2); + assert_eq!(rows[1].get("client_nickname"), Some("B C")); + } + other => panic!("{other:?}"), + } + } + + #[test] + fn builds_commands() { + let cmd = Command::new("clientlist").flag("uid").flag("-away"); + assert_eq!(cmd.to_line(), "clientlist -uid -away"); + let cmd = Command::new("clientkick").arg("clid", 1).row().arg("clid", 2).arg("reasonid", 5); + assert_eq!(cmd.to_line(), "clientkick clid=1|clid=2 reasonid=5"); + let cmd = Command::new("login") + .arg("client_login_name", "a b") + .arg("client_login_password", "p|w"); + assert_eq!(cmd.to_line(), "login client_login_name=a\\sb client_login_password=p\\pw"); + } + + #[test] + fn parses_command_lines() { + let line = r"clientmove clid=5 cid=2 cpw=a\sb|clid=6 -continueonerror"; + let cmd = Command::parse(line).unwrap(); + assert_eq!(cmd.name, "clientmove"); + assert_eq!(cmd.rows.len(), 2); + assert_eq!(cmd.rows[0][2], ("cpw".to_string(), "a b".to_string())); + assert_eq!(cmd.flags, vec!["-continueonerror"]); + assert_eq!(cmd.to_line(), line); + assert!(Command::parse(" ").is_none()); + } + + #[test] + fn row_helpers() { + let mut row = parse_rows("a=1 b=0 c").remove(0); + assert_eq!(row.flag("a"), Some(true)); + assert_eq!(row.flag("b"), Some(false)); + assert_eq!(row.get("c"), Some("")); + row.insert("b", "7"); + row.insert("d", "x"); + assert_eq!(row.parse::("b"), Some(7)); + assert_eq!(row.get("d"), Some("x")); + } +} diff --git a/crates/tsc-query/src/http.rs b/crates/tsc-query/src/http.rs new file mode 100644 index 0000000..595b11f --- /dev/null +++ b/crates/tsc-query/src/http.rs @@ -0,0 +1,93 @@ +//! HTTP WebQuery: `GET //?key=value` with an `x-api-key` header, +//! answered with JSON `{"body": [...], "status": {"code": 0, "message": "ok"}}`. + +use serde::Deserialize; + +use crate::codec::{Command, QueryError, Row}; +use crate::{Error, Result}; + +#[derive(Clone)] +pub struct HttpClient { + http: reqwest::Client, + base: String, + api_key: Option, + sid: u32, +} + +#[derive(Deserialize)] +struct Status { + code: u32, + message: String, + #[serde(default)] + extra_message: Option, + #[serde(default)] + failed_permission: Option, +} + +#[derive(Deserialize)] +struct Reply { + #[serde(default)] + body: Vec>, + status: Status, +} + +impl HttpClient { + /// `base` is e.g. `http://host:10080`. Without an API key requests run + /// with the server's guest query permissions. + pub fn new(base: &str, api_key: Option, sid: u32) -> Result { + let http = reqwest::Client::builder().build()?; + Ok(Self { http, base: base.trim_end_matches('/').to_string(), api_key, sid }) + } + + pub fn set_sid(&mut self, sid: u32) { + self.sid = sid; + } + + pub async fn send(&self, cmd: &Command) -> Result> { + // Multi-row commands are not expressible as query parameters. + if cmd.rows.len() > 1 { + return Err(Error::Unsupported("multi-row commands over HTTP")); + } + // Instance-level commands have no server id in the path. + let url = if matches!(cmd.name.as_str(), "serverlist" | "version" | "hostinfo") { + format!("{}/{}", self.base, cmd.name) + } else { + format!("{}/{}/{}", self.base, self.sid, cmd.name) + }; + let mut params: Vec<(String, String)> = cmd.rows[0].clone(); + params.extend(cmd.flags.iter().map(|f| (f.clone(), String::new()))); + let mut req = self.http.get(url).query(¶ms); + if let Some(key) = &self.api_key { + req = req.header("x-api-key", key); + } + let reply: Reply = req.send().await?.json().await?; + if reply.status.code != 0 && reply.status.code != 1281 { + return Err(QueryError { + id: reply.status.code, + msg: reply.status.message, + extra_msg: reply.status.extra_message.or_else(|| { + reply.status.failed_permission.map(|p| format!("missing permission {p}")) + }), + failed_permid: None, + } + .into()); + } + Ok(reply + .body + .into_iter() + .map(|obj| { + Row(obj + .into_iter() + .map(|(k, v)| { + let v = match v { + serde_json::Value::String(s) => s, + serde_json::Value::Null => String::new(), + other => other.to_string(), + }; + (k, v) + }) + .collect()) + }) + .collect()) + } +} diff --git a/crates/tsc-query/src/lib.rs b/crates/tsc-query/src/lib.rs new file mode 100644 index 0000000..255bc47 --- /dev/null +++ b/crates/tsc-query/src/lib.rs @@ -0,0 +1,50 @@ +//! TeamSpeak ServerQuery client. +//! +//! ServerQuery is the admin/bot interface of TeamSpeak servers. Query clients +//! are invisible to normal users, which is what makes invisible presence and +//! channel-chat relays possible. +//! +//! Transports: +//! - raw TCP (TeamSpeak 3, port 10011) and SSH (both, port 10022): line based, +//! with asynchronous `notify*` events ([`LineClient`]) +//! - HTTP WebQuery (TeamSpeak 6 and 3.12+, port 10080): request/response only, +//! authenticated with an API key ([`HttpClient`]) +//! +//! [`QueryClient`] hides the difference for code that only sends commands. + +mod client; +mod codec; +mod http; +mod line; +mod ssh; + +pub use client::{Connect, QueryClient, Transport}; +pub use codec::{ + Command, Line, Notification, QueryError, Row, escape, parse_line, parse_rows, unescape, +}; +pub use http::HttpClient; +pub use line::{LineClient, LineOptions}; + +#[derive(Debug, thiserror::Error)] +pub enum Error { + #[error("io: {0}")] + Io(#[from] std::io::Error), + #[error("ssh: {0}")] + Ssh(#[from] russh::Error), + #[error("ssh authentication failed")] + SshAuth, + #[error("http: {0}")] + Http(#[from] reqwest::Error), + #[error("server error {0}")] + Query(#[from] QueryError), + #[error("protocol: {0}")] + Protocol(String), + #[error("connection closed")] + Closed, + #[error("timed out")] + Timeout, + #[error("not supported by this transport: {0}")] + Unsupported(&'static str), +} + +pub type Result = std::result::Result; diff --git a/crates/tsc-query/src/line.rs b/crates/tsc-query/src/line.rs new file mode 100644 index 0000000..230bdf0 --- /dev/null +++ b/crates/tsc-query/src/line.rs @@ -0,0 +1,314 @@ +//! Client for the line-based transports (raw TCP and SSH). +//! +//! A background task owns the connection. Commands are sent one at a time +//! (the protocol has no request ids); `notify*` lines are forwarded to an +//! event channel whenever they arrive. + +use std::collections::VecDeque; +use std::time::Duration; + +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader}; +use tokio::sync::{mpsc, oneshot}; +use tokio::time::{Instant, sleep_until}; +use tracing::{debug, trace}; + +use crate::codec::{Command, Line, Notification, Row, parse_line}; +use crate::{Error, Result}; + +#[derive(Clone, Debug)] +pub struct LineOptions { + /// Send `whoami` after this long without traffic (servers drop idle + /// query connections after 300 s by default). + pub keepalive: Duration, + /// Flood protection: at most `rate_commands` per `rate_window`. `None` + /// when the client IP is on the server's query allowlist. + pub rate_limit: Option<(u32, Duration)>, + /// Give up on a command after this long. + pub timeout: Duration, +} + +impl Default for LineOptions { + fn default() -> Self { + Self { + keepalive: Duration::from_secs(180), + // TeamSpeak's default: 10 commands per 3 seconds. + rate_limit: Some((10, Duration::from_secs(3))), + timeout: Duration::from_secs(15), + } + } +} + +type Reply = oneshot::Sender>>; + +struct Request { + line: String, + reply: Reply, +} + +/// Handle to a line-based query connection. Cheap to clone. +#[derive(Clone)] +pub struct LineClient { + requests: mpsc::Sender, + timeout: Duration, +} + +impl LineClient { + /// Start the connection task. Returns the client and the event stream. + pub fn spawn( + reader: R, + writer: W, + options: LineOptions, + ) -> (Self, mpsc::UnboundedReceiver) + where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, + { + Self::spawn_with_guard(reader, writer, options, ()) + } + + /// Like [`LineClient::spawn`], keeping `guard` alive as long as the + /// connection task runs (e.g. an SSH session handle). + pub fn spawn_with_guard( + reader: R, + writer: W, + options: LineOptions, + guard: G, + ) -> (Self, mpsc::UnboundedReceiver) + where + R: AsyncRead + Unpin + Send + 'static, + W: AsyncWrite + Unpin + Send + 'static, + G: Send + 'static, + { + let (requests, rx) = mpsc::channel(64); + let (events_tx, events) = mpsc::unbounded_channel(); + let timeout = options.timeout; + tokio::spawn(async move { + run(BufReader::new(reader), writer, rx, events_tx, options).await; + drop(guard); + }); + (Self { requests, timeout }, events) + } + + /// Send a command and collect its data rows. + pub async fn send(&self, cmd: &Command) -> Result> { + self.send_line(cmd.to_line()).await + } + + /// Send an already formatted command line. + pub async fn send_line(&self, line: String) -> Result> { + let (reply, rx) = oneshot::channel(); + self.requests.send(Request { line, reply }).await.map_err(|_| Error::Closed)?; + match tokio::time::timeout(self.timeout, rx).await { + Ok(Ok(result)) => result, + Ok(Err(_)) => Err(Error::Closed), + Err(_) => Err(Error::Timeout), + } + } + + pub fn is_closed(&self) -> bool { + self.requests.is_closed() + } +} + +/// Token bucket for the query flood protection. +struct RateLimiter { + limit: Option<(u32, Duration)>, + sent: VecDeque, +} + +impl RateLimiter { + /// When the next command may be sent. + fn next_slot(&mut self, now: Instant) -> Instant { + let Some((count, window)) = self.limit else { return now }; + while self.sent.front().is_some_and(|t| now.duration_since(*t) >= window) { + self.sent.pop_front(); + } + if self.sent.len() < count as usize { + now + } else { + // Leave a little margin: the server's clock is not ours. + self.sent[0] + window + Duration::from_millis(50) + } + } + + fn record(&mut self, t: Instant) { + if self.limit.is_some() { + self.sent.push_back(t); + } + } +} + +async fn run( + mut reader: BufReader, + mut writer: W, + mut requests: mpsc::Receiver, + events: mpsc::UnboundedSender, + options: LineOptions, +) where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, +{ + let mut limiter = RateLimiter { limit: options.rate_limit, sent: VecDeque::new() }; + // The request being answered and the rows collected for it so far. + let mut pending: Option<(Reply, Vec)> = None; + let mut keepalive_pending = false; + let mut last_activity = Instant::now(); + let mut buf = Vec::new(); + + loop { + let can_send = pending.is_none() && !keepalive_pending; + let keepalive_at = last_activity + options.keepalive; + tokio::select! { + read = reader.read_until(b'\n', &mut buf) => { + match read { + Ok(0) | Err(_) => { + debug!("query connection closed"); + break; + } + Ok(_) => {} + } + let text = String::from_utf8_lossy(&buf).into_owned(); + buf.clear(); + trace!(line = %text.trim(), "query <"); + match parse_line(&text) { + Line::Empty => {} + Line::Notify(n) => { + let _ = events.send(n); + } + // Response data always has key=value pairs; lines without + // any `=` are the welcome banner, which may arrive after the + // first command was sent. + Line::Data(rows) if text.contains('=') => { + if let Some((_, collected)) = &mut pending { + collected.extend(rows); + } + } + Line::Data(_) => {} + Line::Error(e) => { + if keepalive_pending && pending.is_none() { + keepalive_pending = false; + } else if let Some((reply, rows)) = pending.take() { + let result = if e.is_ok() || e.is_empty_result() { + Ok(rows) + } else { + Err(e.into()) + }; + let _ = reply.send(result); + } + } + } + } + req = requests.recv(), if can_send => { + let Some(req) = req else { break }; + let slot = limiter.next_slot(Instant::now()); + if slot > Instant::now() { + sleep_until(slot).await; + } + limiter.record(Instant::now()); + trace!(line = %req.line, "query >"); + if let Err(e) = write_line(&mut writer, &req.line).await { + let _ = req.reply.send(Err(e.into())); + break; + } + last_activity = Instant::now(); + pending = Some((req.reply, Vec::new())); + } + _ = sleep_until(keepalive_at), if can_send => { + limiter.record(Instant::now()); + if write_line(&mut writer, "whoami").await.is_err() { + break; + } + last_activity = Instant::now(); + keepalive_pending = true; + } + } + } + if let Some((reply, _)) = pending { + let _ = reply.send(Err(Error::Closed)); + } + debug!("query connection task ended"); +} + +async fn write_line(writer: &mut W, line: &str) -> std::io::Result<()> { + writer.write_all(line.as_bytes()).await?; + writer.write_all(b"\n").await?; + writer.flush().await +} + +#[cfg(test)] +mod tests { + use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, duplex}; + + use super::*; + + /// A scripted fake server: answers each command from `script` in order. + async fn fake_server( + stream: tokio::io::DuplexStream, + script: Vec<(&'static str, &'static str)>, + ) { + let (r, mut w) = tokio::io::split(stream); + let mut r = BufReader::new(r); + w.write_all(b"TS3\n\rWelcome to the TeamSpeak 3 ServerQuery interface.\n\r").await.unwrap(); + for (expect, answer) in script { + let mut line = String::new(); + r.read_line(&mut line).await.unwrap(); + assert_eq!(line.trim_end(), expect); + w.write_all(answer.as_bytes()).await.unwrap(); + } + } + + #[tokio::test] + async fn request_response_and_events() { + let (client_io, server_io) = duplex(4096); + let server = tokio::spawn(fake_server( + server_io, + vec![ + ( + "login client_login_name=serveradmin client_login_password=pw", + "error id=0 msg=ok\n\r", + ), + ( + "clientlist -uid", + "clid=1 client_nickname=A|clid=2 client_nickname=B\\sC\n\r\ + notifycliententerview clid=3 client_nickname=D\n\r\ + error id=0 msg=ok\n\r", + ), + ("use sid=9", "error id=1024 msg=invalid\\sserverID\n\r"), + ("channellist", "error id=1281 msg=database\\sempty\\sresult\\sset\n\r"), + ], + )); + let (r, w) = tokio::io::split(client_io); + let (client, mut events) = + LineClient::spawn(r, w, LineOptions { rate_limit: None, ..Default::default() }); + + let login = Command::new("login") + .arg("client_login_name", "serveradmin") + .arg("client_login_password", "pw"); + assert!(client.send(&login).await.unwrap().is_empty()); + let rows = client.send(&Command::new("clientlist").flag("uid")).await.unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[1].get("client_nickname"), Some("B C")); + let event = events.recv().await.unwrap(); + assert_eq!(event.name, "notifycliententerview"); + match client.send(&Command::new("use").arg("sid", 9)).await { + Err(Error::Query(e)) => assert_eq!(e.id, 1024), + other => panic!("{other:?}"), + } + // "empty result set" is an empty list, not an error. + assert!(client.send(&Command::new("channellist")).await.unwrap().is_empty()); + server.await.unwrap(); + } + + #[tokio::test(start_paused = true)] + async fn rate_limiter_spaces_commands() { + let mut limiter = + RateLimiter { limit: Some((2, Duration::from_secs(3))), sent: VecDeque::new() }; + let t0 = Instant::now(); + assert_eq!(limiter.next_slot(t0), t0); + limiter.record(t0); + limiter.record(t0); + assert!(limiter.next_slot(t0) >= t0 + Duration::from_secs(3)); + let later = t0 + Duration::from_secs(4); + assert_eq!(limiter.next_slot(later), later); + } +} diff --git a/crates/tsc-query/src/ssh.rs b/crates/tsc-query/src/ssh.rs new file mode 100644 index 0000000..6982138 --- /dev/null +++ b/crates/tsc-query/src/ssh.rs @@ -0,0 +1,59 @@ +//! SSH transport: password login, then the query runs in the shell channel. + +use std::sync::Arc; +use std::time::Duration; + +use russh::client; +use russh::keys::PublicKeyOrCertificate; + +use crate::{Error, Result}; + +/// Accepts any host key. ServerQuery hosts generate their key on first start +/// and there is no out-of-band way to learn it; callers that care can pin the +/// fingerprint returned by [`connect`]. +pub(crate) struct AcceptAny { + fingerprint: Arc>>, +} + +impl client::Handler for AcceptAny { + type Error = russh::Error; + + async fn check_server_key( + &mut self, + key: &PublicKeyOrCertificate, + ) -> std::result::Result { + if let PublicKeyOrCertificate::PublicKey { key, .. } = key { + *self.fingerprint.lock().unwrap() = + Some(key.fingerprint(russh::keys::HashAlg::Sha256).to_string()); + } + Ok(true) + } +} + +/// An open SSH shell channel. The session handle is kept with it because the +/// connection closes when the handle is dropped. +pub(crate) struct Shell { + pub stream: russh::ChannelStream, + pub session: client::Handle, + pub fingerprint: Option, +} + +/// Open an SSH session and start the query shell. +pub(crate) async fn connect(addr: &str, user: &str, password: &str) -> Result { + let config = Arc::new(client::Config { + inactivity_timeout: None, + keepalive_interval: Some(Duration::from_secs(60)), + ..Default::default() + }); + let fingerprint = Arc::new(std::sync::Mutex::new(None)); + let handler = AcceptAny { fingerprint: fingerprint.clone() }; + let mut session = client::connect(config, addr, handler).await?; + let auth = session.authenticate_password(user, password).await?; + if !auth.success() { + return Err(Error::SshAuth); + } + let channel = session.channel_open_session().await?; + channel.request_shell(true).await?; + let fingerprint = fingerprint.lock().unwrap().clone(); + Ok(Shell { stream: channel.into_stream(), session, fingerprint }) +} diff --git a/dev/docker-compose.yml b/dev/docker-compose.yml index b8aeed0..40554cf 100644 --- a/dev/docker-compose.yml +++ b/dev/docker-compose.yml @@ -6,6 +6,10 @@ # Each server prints a one-time ServerAdmin privilege key to its log on first # start; the smoke test reads it from there. `down -v` resets the servers. # +# ServerQuery: every interface is enabled with the fixed development password +# `tsc-dev-admin` for the `serveradmin` login (TS3: raw 10011, SSH 10023, +# HTTP 10081; TS6: SSH 10022, HTTP 10080). Never use these settings in production. +# # query_ip_allowlist.txt allowlists private ranges: clients reach the servers # through the Docker bridge, and allowlisted IPs skip the anti-flood bans that # rapid test connections would otherwise trigger. Development use only. @@ -21,9 +25,13 @@ services: environment: TS3SERVER_LICENSE: accept TS3SERVER_IP_ALLOWLIST: /etc/ts3server/query_ip_allowlist.txt + TS3SERVER_SERVERADMIN_PASSWORD: tsc-dev-admin + TS3SERVER_QUERY_PROTOCOLS: raw,ssh,http ports: - "9987:9987/udp" # voice - "10011:10011" # raw ServerQuery + - "10023:10022" # SSH ServerQuery + - "10081:10080" # HTTP WebQuery - "30033:30033" # file transfer volumes: - ts3-data:/var/ts3server @@ -34,6 +42,10 @@ services: image: ${REGISTRY:-docker.io}/teamspeaksystems/teamspeak6-server@sha256:d845f803aecf842c2df034c959c23ff2462357bacafb3807500885c5ec170fa1 environment: TSSERVER_LICENSE_ACCEPTED: accept + TSSERVER_QUERY_ADMIN_PASSWORD: tsc-dev-admin + TSSERVER_QUERY_SSH_ENABLED: 1 + TSSERVER_QUERY_HTTP_ENABLED: 1 + TSSERVER_QUERY_ALLOW_LIST: /etc/tsserver/query_ip_allowlist.txt ports: - "9988:9987/udp" # voice (mapped to 9988 so both servers can run) - "10022:10022" # SSH ServerQuery @@ -41,7 +53,7 @@ services: - "30034:30033" # file transfer volumes: - ts6-data:/var/tsserver - - ./query_ip_allowlist.txt:/var/tsserver/query_ip_allowlist.txt:ro + - ./query_ip_allowlist.txt:/etc/tsserver/query_ip_allowlist.txt:ro volumes: ts3-data: diff --git a/docs/architecture.md b/docs/architecture.md index cfcccea..cde34e1 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -20,6 +20,22 @@ facts constrain it, how the code is organised, and the milestone order. - TeamSpeak 6 servers still accept the TeamSpeak 3 client protocol; verified with `tsctl` against 6.0.0-beta13.1. +### What "invisible" means for query clients (verified on 3.13.8 and 6.0.0-beta13.1) + +The server does not hide ServerQuery clients: every client subscribed to a +channel receives `notifycliententerview` for query clients in it too +(`client_type=1`). Official clients hide a query client when its +`client_needed_serverquery_view_power` (100 for `serveradmin` by default) is +higher than the viewer's `i_client_serverquery_view_power` (only Server Admins +have it by default). So observers and relays are invisible to normal users of +official clients, visible to admins, and visible to third-party clients that +ignore the rule. This client applies the same rule. + +TeamSpeak 6 ships with SSH and HTTP query disabled +(`TSSERVER_QUERY_SSH_ENABLED`, `TSSERVER_QUERY_HTTP_ENABLED`). HTTP guest +access (`query-http-allow-guest`, on by default) lacks list permissions unless +the admin grants them to the guest query group. + ## How each feature is delivered | Feature | Mechanism | diff --git a/scripts/it-smoke.sh b/scripts/it-smoke.sh index 0f284e3..529c98e 100755 --- a/scripts/it-smoke.sh +++ b/scripts/it-smoke.sh @@ -7,6 +7,8 @@ # 2. server chat between two clients # 3. channel chat between two clients # 4. voice: a 1 kHz tone sent by one client is recorded by another +# 5. invisible presence: a ServerQuery observer sees a voice client join +# 6. relay chat: a query relay reads channel chat and posts into the channel # # Usage: scripts/it-smoke.sh [ts3|ts6]... (default: both) # Env: TSCTL=path/to/tsctl (default: builds target/debug/tsctl) @@ -28,6 +30,9 @@ if [[ -z "${TSCTL:-}" ]]; then fi declare -A PORTS=([ts3]=9987 [ts6]=9988) +# ServerQuery transport and address per server (dev/docker-compose.yml). +declare -A QUERY=([ts3]="raw 127.0.0.1:10011" [ts6]="ssh 127.0.0.1:10022") +QUERY_SECRET=tsc-dev-admin SERVERS=("$@") [[ ${#SERVERS[@]} -eq 0 ]] && SERVERS=(ts3 ts6) @@ -99,6 +104,50 @@ voice_roundtrip() { grep "tone ratio" "$out" } +# An observer over ServerQuery must see a voice client join. +presence_check() { + local addr=$1 query=$2 out="$STATE_DIR/observe.log" + # shellcheck disable=SC2086 + "$TSCTL" observe $query --secret "$QUERY_SECRET" --allowlisted --poll 2 \ + --seconds 20 --expect-client presence-probe >"$out" 2>&1 & + local observer=$! + sleep 2 + "$TSCTL" connect "$addr" --nick presence-probe listen --timeout 4 >/dev/null 2>&1 || true + if ! wait "$observer"; then + cat "$out" + fail "observer did not see the voice client" + fi + grep "presence-probe" "$out" +} + +# A relay reads a voice client's channel message and posts one back. +relay_check() { + local addr=$1 query=$2 out="$STATE_DIR/relay.log" heard="$STATE_DIR/relay-heard.log" + local token="relay-$RANDOM$RANDOM" + # shellcheck disable=SC2086 + "$TSCTL" relay $query --secret "$QUERY_SECRET" --allowlisted --channel 1 \ + --expect "to-relay-$token" --seconds 20 >"$out" 2>&1 & + local relay=$! + "$TSCTL" connect "$addr" --nick relay-listener listen --expect "from-relay-$token" \ + --timeout 20 >"$heard" 2>&1 & + local listener=$! + sleep 4 + "$TSCTL" connect "$addr" --nick relay-talker chat channel "to-relay-$token" + # shellcheck disable=SC2086 + "$TSCTL" relay $query --secret "$QUERY_SECRET" --allowlisted --channel 1 --nick Alice \ + --send "from-relay-$token" --seconds 1 >/dev/null + if ! wait "$relay"; then + cat "$out" + fail "relay did not receive the channel message" + fi + if ! wait "$listener"; then + cat "$heard" + fail "voice client did not receive the relayed post" + fi + grep "to-relay-$token" "$out" + grep "from-relay-$token" "$heard" +} + for svc in "${SERVERS[@]}"; do port=${PORTS[$svc]:?unknown server $svc} addr="127.0.0.1:$port" @@ -114,6 +163,8 @@ for svc in "${SERVERS[@]}"; do chat_roundtrip "$addr" server "$admin" chat_roundtrip "$addr" channel "" voice_roundtrip "$addr" + presence_check "$addr" "${QUERY[$svc]}" + relay_check "$addr" "${QUERY[$svc]}" done log "all smoke tests passed" diff --git a/tools/tsctl/Cargo.toml b/tools/tsctl/Cargo.toml index e4f2fbb..ee1c2c8 100644 --- a/tools/tsctl/Cargo.toml +++ b/tools/tsctl/Cargo.toml @@ -21,6 +21,8 @@ tracing-subscriber = { version = "0.3", features = ["env-filter"] } tsclientlib = { path = "../../crates/proto/tsclientlib" } tsproto-packets = { path = "../../crates/proto/tsproto-packets" } tsc-model = { path = "../../crates/tsc-model" } +tsc-query = { path = "../../crates/tsc-query" } +tsc-observer = { path = "../../crates/tsc-observer" } tsc-audio = { path = "../../crates/tsc-audio", default-features = false } [lints] diff --git a/tools/tsctl/src/main.rs b/tools/tsctl/src/main.rs index d40919c..081e841 100644 --- a/tools/tsctl/src/main.rs +++ b/tools/tsctl/src/main.rs @@ -1,6 +1,8 @@ //! `tsctl`: headless TeamSpeak 3/6 client for development and integration tests. mod identity; +mod observe; +mod query; mod session; mod tree; mod versions; @@ -34,6 +36,12 @@ enum Command { }, /// Connect to a server and run an action. Connect(ConnectArgs), + /// Run ServerQuery commands (raw TCP, SSH or HTTP WebQuery). + Query(query::QueryArgs), + /// Watch who is in which channel through ServerQuery, without appearing on the server. + Observe(observe::ObserveArgs), + /// Read and write a channel's chat through an invisible query relay. + Relay(observe::RelayArgs), } #[derive(Subcommand, Debug)] @@ -190,6 +198,9 @@ fn main() -> Result<()> { let rt = tokio::runtime::Runtime::new()?; rt.block_on(session::run(args)) } + Command::Query(args) => tokio::runtime::Runtime::new()?.block_on(query::run(args)), + Command::Observe(args) => tokio::runtime::Runtime::new()?.block_on(observe::observe(args)), + Command::Relay(args) => tokio::runtime::Runtime::new()?.block_on(observe::relay(args)), } } diff --git a/tools/tsctl/src/observe.rs b/tools/tsctl/src/observe.rs new file mode 100644 index 0000000..22e407f --- /dev/null +++ b/tools/tsctl/src/observe.rs @@ -0,0 +1,227 @@ +//! `tsctl observe` and `tsctl relay`: invisible presence and channel chat. + +use std::time::Duration; + +use anyhow::{Result, bail}; +use clap::Args; +use tokio::sync::broadcast::error::RecvError; +use tokio::time::{Instant, timeout_at}; +use tsc_model::{ChatMessage, ChatTarget, Presence, PresenceDelta}; +use tsc_observer::{Observer, ObserverConfig, ObserverEvent, RelayConfig, RelayEvent, RelayPool}; + +use crate::query::QueryConnArgs; + +#[derive(Args, Debug, Clone)] +pub struct ObserveArgs { + #[command(flatten)] + pub conn: QueryConnArgs, + /// Stop after this many seconds (default: until Ctrl-C). + #[arg(long)] + pub seconds: Option, + /// Print events as JSON lines. + #[arg(long)] + pub json: bool, + /// Resync interval in seconds. + #[arg(long, default_value_t = 10)] + pub poll: u64, + /// Exit successfully once a client with this nickname is seen (for tests). + #[arg(long)] + pub expect_client: Option, +} + +#[derive(Args, Debug, Clone)] +pub struct RelayArgs { + #[command(flatten)] + pub conn: QueryConnArgs, + /// Channel id to relay. + #[arg(long)] + pub channel: u64, + /// Post this message after opening the relay. + #[arg(long)] + pub send: Option, + /// Name shown in relayed posts. + #[arg(long, default_value = "tsctl")] + pub nick: String, + /// Stop after this many seconds (default: until Ctrl-C). + #[arg(long)] + pub seconds: Option, + /// Exit successfully once a message containing this text arrives. + #[arg(long)] + pub expect: Option, +} + +fn print_chat(msg: &ChatMessage) { + let target = match &msg.target { + ChatTarget::Server => "server".to_string(), + ChatTarget::Channel(cid) => format!("channel {cid}"), + ChatTarget::Private(_) => "private".to_string(), + }; + println!("[{target}] {}: {}", msg.author_name, msg.text); +} + +fn print_tree(p: &Presence) { + let channels: Vec<_> = p + .channels + .values() + .map(|c| crate::tree::ChannelNode { + id: tsclientlib::ChannelId(c.id), + parent: tsclientlib::ChannelId(c.parent), + order: tsclientlib::ChannelId(c.order), + name: c.name.clone(), + }) + .collect(); + let clients: Vec<_> = p + .clients + .values() + .map(|c| crate::tree::ClientNode { + channel: tsclientlib::ChannelId(c.channel), + name: c.nickname.clone(), + talk_power: 0, + is_query: c.is_query, + input_muted: c.input_muted, + output_muted: c.output_muted, + away: c.away.is_some(), + streaming: c.streaming == Some(true), + }) + .collect(); + print!( + "{}", + crate::tree::render( + &format!("{} (via query, invisible)", p.server_name), + &channels, + &clients + ) + ); +} + +fn describe(p: &Presence, d: &PresenceDelta) -> String { + let name = |id: &u16| { + p.clients.get(id).map(|c| c.nickname.clone()).unwrap_or_else(|| format!("clid {id}")) + }; + let channel = |id: &u64| { + p.channels.get(id).map(|c| c.name.clone()).unwrap_or_else(|| format!("cid {id}")) + }; + match d { + PresenceDelta::ClientJoined(c) => format!("+ {} in #{}", c.nickname, channel(&c.channel)), + PresenceDelta::ClientLeft { id } => format!("- {} left", name(id)), + PresenceDelta::ClientMoved { id, channel: to } => { + format!("> {} moved to #{}", name(id), channel(to)) + } + PresenceDelta::ClientChanged(c) => format!( + "~ {} changed (muted: {}, away: {})", + c.nickname, + c.input_muted, + c.away.is_some() + ), + PresenceDelta::ChannelAdded(c) => format!("+ channel #{}", c.name), + PresenceDelta::ChannelChanged(c) => format!("~ channel #{}", c.name), + PresenceDelta::ChannelRemoved { id } => format!("- channel {}", channel(id)), + PresenceDelta::ServerRenamed { name } => format!("~ server renamed to {name}"), + } +} + +pub async fn observe(args: ObserveArgs) -> Result<()> { + let mut config = ObserverConfig::new(args.conn.connect_config()); + config.poll_interval = Duration::from_secs(args.poll); + let observer = Observer::spawn(config); + let mut events = observer.subscribe(); + let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s)); + loop { + let next = async { + match deadline { + Some(d) => timeout_at(d, events.recv()).await.ok(), + None => Some(events.recv().await), + } + }; + let event = tokio::select! { + e = next => e, + _ = tokio::signal::ctrl_c() => return Ok(()), + }; + let event = match event { + None => break, + Some(Ok(e)) => e, + Some(Err(RecvError::Lagged(n))) => { + eprintln!("(missed {n} events)"); + continue; + } + Some(Err(RecvError::Closed)) => bail!("observer stopped"), + }; + let presence = observer.presence(); + let presence = presence.read().unwrap().clone(); + if args.json { + match &event { + ObserverEvent::Snapshot(s) => println!("{}", serde_json::to_string(s)?), + ObserverEvent::Delta(d) => println!("{}", serde_json::to_string(d)?), + ObserverEvent::Chat(m) => println!("{}", serde_json::to_string(m)?), + ObserverEvent::Disconnected(r) => { + println!("{}", serde_json::json!({"disconnected": r})) + } + } + } else { + match &event { + ObserverEvent::Snapshot(_) => print_tree(&presence), + ObserverEvent::Delta(d) => println!("{}", describe(&presence, d)), + ObserverEvent::Chat(m) => print_chat(m), + ObserverEvent::Disconnected(r) => println!("! disconnected: {r}"), + } + } + if let Some(nick) = &args.expect_client + && presence.clients.values().any(|c| &c.nickname == nick) + { + return Ok(()); + } + } + if let Some(nick) = &args.expect_client { + bail!("client {nick:?} not seen"); + } + Ok(()) +} + +pub async fn relay(args: RelayArgs) -> Result<()> { + let pool = RelayPool::new(RelayConfig::new(args.conn.connect_config())); + let mut events = pool.subscribe(); + pool.open(args.channel).await?; + println!("relaying channel {}", args.channel); + if let Some(text) = &args.send { + pool.send(args.channel, &args.nick, text).await?; + println!("sent"); + } + let result = relay_loop(&args, &mut events).await; + pool.close_all().await; + result +} + +async fn relay_loop( + args: &RelayArgs, + events: &mut tokio::sync::broadcast::Receiver, +) -> Result<()> { + let deadline = args.seconds.map(|s| Instant::now() + Duration::from_secs(s)); + loop { + let next = async { + match deadline { + Some(d) => timeout_at(d, events.recv()).await.ok(), + None => Some(events.recv().await), + } + }; + let event = tokio::select! { + e = next => e, + _ = tokio::signal::ctrl_c() => return Ok(()), + }; + match event { + None => break, + Some(Ok(RelayEvent::Message(m))) => { + print_chat(&m); + if args.expect.as_ref().is_some_and(|e| m.text.contains(e.as_str())) { + return Ok(()); + } + } + Some(Ok(RelayEvent::Closed { reason, .. })) => bail!("relay closed: {reason}"), + Some(Err(RecvError::Lagged(_))) => {} + Some(Err(RecvError::Closed)) => break, + } + } + if let Some(expect) = &args.expect { + bail!("no message containing {expect:?}"); + } + Ok(()) +} diff --git a/tools/tsctl/src/query.rs b/tools/tsctl/src/query.rs new file mode 100644 index 0000000..d5c5516 --- /dev/null +++ b/tools/tsctl/src/query.rs @@ -0,0 +1,118 @@ +//! `tsctl query`: ServerQuery commands and events. + +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use clap::Args; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tsc_query::{Command, Connect, LineOptions, QueryClient, Row, Transport}; + +/// How to reach and log into a ServerQuery interface. +#[derive(Args, Debug, Clone)] +pub struct QueryConnArgs { + /// Transport: raw (TS3 only), ssh or http. + #[arg(value_enum)] + pub transport: TransportArg, + /// host:port of the query interface (e.g. 127.0.0.1:10022). + pub addr: String, + /// Login name (raw/SSH). + #[arg(long, default_value = "serveradmin")] + pub user: String, + /// Password (raw/SSH) or API key (HTTP). Without it, HTTP runs as guest. + #[arg(long, env = "TSCTL_QUERY_SECRET", hide_env_values = true)] + pub secret: Option, + /// Select the virtual server by its voice port instead of id 1. + #[arg(long)] + pub server_port: Option, + /// Our IP is on the server's query allowlist: skip client-side rate limiting. + #[arg(long)] + pub allowlisted: bool, +} + +#[derive(Args, Debug, Clone)] +pub struct QueryArgs { + #[command(flatten)] + pub conn: QueryConnArgs, + /// After the commands, print events for this many seconds. + #[arg(long)] + pub events: Option, + /// Command line to run, e.g. `clientlist -uid`. Without one, commands are read from stdin. + #[arg(trailing_var_arg = true, allow_hyphen_values = true)] + pub command: Vec, +} + +#[derive(clap::ValueEnum, Clone, Copy, Debug)] +pub enum TransportArg { + Raw, + Ssh, + Http, +} + +impl QueryConnArgs { + pub fn connect_config(&self) -> Connect { + Connect { + transport: match self.transport { + TransportArg::Raw => Transport::Raw, + TransportArg::Ssh => Transport::Ssh, + TransportArg::Http => Transport::Http, + }, + addr: self.addr.clone(), + user: self.user.clone(), + secret: self.secret.clone(), + server_port: self.server_port, + server_id: None, + line: LineOptions { + rate_limit: if self.allowlisted { None } else { LineOptions::default().rate_limit }, + ..Default::default() + }, + } + } +} + +pub fn print_rows(rows: &[Row]) { + for row in rows { + let fields: Vec = row.0.iter().map(|(k, v)| format!("{k}={v}")).collect(); + println!("{}", fields.join(" ")); + } +} + +pub async fn run(args: QueryArgs) -> Result<()> { + let (client, events) = QueryClient::connect(&args.conn.connect_config()) + .await + .context("query connection failed")?; + + if args.command.is_empty() { + let mut lines = BufReader::new(tokio::io::stdin()).lines(); + while let Some(line) = lines.next_line().await? { + if line.trim().is_empty() { + continue; + } + run_line(&client, &line).await; + } + } else { + let line = args.command.join(" "); + let Some(cmd) = Command::parse(&line) else { bail!("empty command") }; + print_rows(&client.send(&cmd).await?); + } + + if let Some(secs) = args.events { + let Some(mut events) = events else { bail!("this transport has no events") }; + let deadline = tokio::time::Instant::now() + Duration::from_secs(secs); + while let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.recv()).await { + print!("{}: ", event.name); + print_rows(&event.rows); + } + } + Ok(()) +} + +async fn run_line(client: &QueryClient, line: &str) { + let Some(cmd) = Command::parse(line) else { return }; + match client.send(&cmd).await { + Ok(rows) => { + print_rows(&rows); + println!("ok"); + } + Err(error) => println!("error: {error}"), + } +}