From cc532cf60d933a17e88a7f65c43e9cd448517de6 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sat, 24 Oct 2026 21:57:30 -0300 Subject: [PATCH 01/14] Add a QUIC Wi-Fi link with PIN pairing to ezd-link Add a QUIC transport (quinn with rustls/ring, TLS 1.3) where both peers use self-signed certificates pinned by SHA-256 fingerprint. Control and video run on separate streams through a split mux, so video loss never delays input or cursor updates. Pairing uses SPAKE2 with a PIN, followed by HMAC key confirmation bound to the TLS exporter and both certificate fingerprints. A pairing window allows 5 attempts within 5 minutes and is guarded by a generation check. A QR URI carries the pairing data. The host limits what unauthenticated peers can do. Protocol minor version is bumped to 0.5. The `quic` feature is off in the workspace dependency so the Windows MSVC cross-check builds without ring. CI gives ring the NDK clang for the Android check. --- .github/workflows/ci.yml | 7 +- Cargo.lock | 482 ++++++++++++++++++- Cargo.toml | 8 +- crates/ezd-link/Cargo.toml | 13 + crates/ezd-link/src/identity.rs | 274 +++++++++++ crates/ezd-link/src/lib.rs | 7 + crates/ezd-link/src/link.rs | 38 +- crates/ezd-link/src/mux.rs | 583 +++++++++++++++++++++-- crates/ezd-link/src/pair.rs | 794 ++++++++++++++++++++++++++++++++ crates/ezd-link/src/quic.rs | 668 +++++++++++++++++++++++++++ crates/ezd-proto/src/lib.rs | 5 + crates/ezd-proto/src/pair.rs | 153 ++++++ 12 files changed, 2969 insertions(+), 63 deletions(-) create mode 100644 crates/ezd-link/src/identity.rs create mode 100644 crates/ezd-link/src/pair.rs create mode 100644 crates/ezd-link/src/quic.rs create mode 100644 crates/ezd-proto/src/pair.rs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 37dc6ef..3a91445 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -219,6 +219,11 @@ jobs: targets: aarch64-linux-android, x86_64-pc-windows-msvc - uses: Swatinem/rust-cache@v2 - name: Protocol and link crates build for Android - run: cargo check --target aarch64-linux-android -p ezd-proto -p ezd-link + # ring (QUIC/TLS) compiles C code, so it needs the NDK's clang. + run: | + bin="$ANDROID_NDK_LATEST_HOME/toolchains/llvm/prebuilt/linux-x86_64/bin" + export CC_aarch64_linux_android="$bin/aarch64-linux-android26-clang" + export AR_aarch64_linux_android="$bin/llvm-ar" + cargo check --target aarch64-linux-android -p ezd-proto -p ezd-link - name: Platform-independent crates build for Windows run: cargo check --target x86_64-pc-windows-msvc -p ezd-proto -p ezd-link -p ezd-host-core -p ezd-host-windows -p ezd-host-service -p ezd-host -p ezd-tray --no-default-features diff --git a/Cargo.lock b/Cargo.lock index d74a63f..8e1ed5b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -326,6 +326,45 @@ dependencies = [ "zbus", ] +[[package]] +name = "asn1-rs" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f43a50ac4fdca5df8e885c21b835997f0a1cdee65494a6847694a98652d9d8" +dependencies = [ + "asn1-rs-derive", + "asn1-rs-impl", + "displaydoc", + "nom 7.1.3", + "num-traits", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + +[[package]] +name = "asn1-rs-derive" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3109e49b1e4909e9db6515a30c633684d68cdeaa252f215214cb4fa1a5bfee2c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "synstructure", +] + +[[package]] +name = "asn1-rs-impl" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "async-broadcast" version = "0.7.2" @@ -604,6 +643,15 @@ dependencies = [ "wyz", ] +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + [[package]] name = "block-buffer" version = "0.12.1" @@ -760,6 +808,17 @@ dependencies = [ "libc", ] +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + [[package]] name = "clang-sys" version = "1.9.1" @@ -936,6 +995,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + [[package]] name = "cpufeatures" version = "0.3.1" @@ -1003,6 +1071,16 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + [[package]] name = "crypto-common" version = "0.2.2" @@ -1018,6 +1096,52 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "curve25519-dalek-derive", + "fiat-crypto", + "rand_core 0.6.4", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "der-parser" +version = "10.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07da5016415d5a3c4dd39b11ed26f915f52fc4e0dc197d87908bc916e51bc1a6" +dependencies = [ + "asn1-rs", + "displaydoc", + "nom 7.1.3", + "num-bigint", + "num-traits", + "rusticata-macros", +] + [[package]] name = "deranged" version = "0.5.9" @@ -1040,15 +1164,26 @@ dependencies = [ "rayon", ] +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer 0.10.4", + "crypto-common 0.1.7", + "subtle", +] + [[package]] name = "digest" version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" dependencies = [ - "block-buffer", + "block-buffer 0.12.1", "const-oid", - "crypto-common", + "crypto-common 0.2.2", ] [[package]] @@ -1603,7 +1738,13 @@ name = "ezd-link" version = "0.1.0-alpha.1" dependencies = [ "ezd-proto", + "quinn", + "rcgen", + "ring", + "rustls", + "serde", "socket2", + "spake2", "thiserror 2.0.21", "tokio", "tracing", @@ -1693,6 +1834,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + [[package]] name = "find-crate" version = "0.6.3" @@ -1890,6 +2037,16 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + [[package]] name = "gethostname" version = "1.1.0" @@ -1909,6 +2066,19 @@ dependencies = [ "unicode-width", ] +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -1928,8 +2098,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" dependencies = [ "cfg-if", + "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", ] [[package]] @@ -2137,6 +2310,24 @@ version = "0.4.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest 0.10.7", +] + [[package]] name = "hybrid-array" version = "0.4.15" @@ -2572,6 +2763,12 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "matchers" version = "0.2.0" @@ -2812,12 +3009,31 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3268,6 +3484,15 @@ dependencies = [ "objc2-foundation 0.3.2", ] +[[package]] +name = "oid-registry" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12f40cff3dde1b6087cc5d5f5d4d65712f34016a03ed60e9c08dcc392736b5b7" +dependencies = [ + "asn1-rs", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -3690,6 +3915,62 @@ dependencies = [ "memchr", ] +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand", + "rand_pcg", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -3717,6 +3998,41 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +[[package]] +name = "rand" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c9fb96cbc91e3478eaae79a69fcd3f1ae4ad052e471fe6732fff548984b4af" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "range-alloc" version = "0.1.5" @@ -3761,6 +4077,19 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "rcgen" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10b99e0098aa4082912d4c649628623db6aba77335e4f4569ff5083a6448b32e" +dependencies = [ + "ring", + "rustls-pki-types", + "time", + "x509-parser", + "yasna", +] + [[package]] name = "read-fonts" version = "0.41.0" @@ -3850,6 +4179,20 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "roxmltree" version = "0.21.1" @@ -3890,7 +4233,7 @@ version = "8.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0d84e8ba78bd384263e5922f084cbe1b081c3b7e69add59c8fb097b879ba968a" dependencies = [ - "sha2", + "sha2 0.11.0", "walkdir", ] @@ -3915,6 +4258,15 @@ dependencies = [ "semver", ] +[[package]] +name = "rusticata-macros" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faf0c4a6ece9950b9abdb62b1cfcf2a68b3b67a10ba445b3bb85be2a293d0632" +dependencies = [ + "nom 7.1.3", +] + [[package]] name = "rustix" version = "0.38.44" @@ -3941,6 +4293,41 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.23" @@ -4061,6 +4448,17 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + [[package]] name = "sha2" version = "0.11.0" @@ -4068,8 +4466,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -4218,6 +4616,18 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "spake2" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5482afe85a0b6ce956c945401598dbc527593c77ba51d0a87a586938b1b893a" +dependencies = [ + "curve25519-dalek", + "hkdf", + "rand_core 0.6.4", + "sha2 0.10.9", +] + [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" @@ -4239,6 +4649,12 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + [[package]] name = "symlink" version = "0.1.0" @@ -4267,6 +4683,17 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "sys-locale" version = "0.3.2" @@ -4437,6 +4864,12 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokio" version = "1.54.1" @@ -4735,6 +5168,12 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "utf8parse" version = "0.2.2" @@ -5573,6 +6012,24 @@ version = "0.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" +[[package]] +name = "x509-parser" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43b0f71ce057da06bc0851b23ee24f3f86190b07203dd8f567d0b706a185202" +dependencies = [ + "asn1-rs", + "data-encoding", + "der-parser", + "lazy_static", + "nom 7.1.3", + "oid-registry", + "ring", + "rusticata-macros", + "thiserror 2.0.21", + "time", +] + [[package]] name = "xcursor" version = "0.3.11" @@ -5604,6 +6061,15 @@ version = "0.8.29" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" +[[package]] +name = "yasna" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17bb3549cc1321ae1296b9cdc2698e2b6cb1992adfa19a8c72e5b7a738f44cd" +dependencies = [ + "time", +] + [[package]] name = "zbus" version = "5.13.2" @@ -5727,6 +6193,12 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + [[package]] name = "zerovec" version = "0.11.9" diff --git a/Cargo.toml b/Cargo.toml index 65506d3..476ece6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,9 @@ rust-version = "1.85" [workspace.dependencies] ezd-proto = { path = "crates/ezd-proto" } ezd-input = { path = "crates/ezd-input" } -ezd-link = { path = "crates/ezd-link" } +# Without default features: members that need Wi-Fi links enable `quic` themselves, so the Windows +# cross-check can build the rest without a C toolchain for ring. +ezd-link = { path = "crates/ezd-link", default-features = false } ezd-host-core = { path = "crates/ezd-host-core" } # Without default features: members enable `ffmpeg` themselves (see their `ffmpeg` feature), so the # Windows cross-check can build them without FFmpeg headers. @@ -24,6 +26,10 @@ ezd-host-windows = { path = "crates/ezd-host-windows", default-features = false ezd-fake-client = { path = "crates/ezd-fake-client" } anyhow = "1" +dirs = "6" +gethostname = "1" +mdns-sd = "0.21" +qrcode = { version = "0.14", default-features = false } clap = { version = "4", features = ["derive", "string"] } i18n-embed = { version = "0.16", features = ["fluent-system", "desktop-requester"] } i18n-embed-fl = "0.10" diff --git a/crates/ezd-link/Cargo.toml b/crates/ezd-link/Cargo.toml index d73b88a..3f10696 100644 --- a/crates/ezd-link/Cargo.toml +++ b/crates/ezd-link/Cargo.toml @@ -13,6 +13,19 @@ ezd-proto.workspace = true thiserror.workspace = true tokio.workspace = true tracing.workspace = true +# Wi-Fi links (`quic` feature). ring is the only crypto backend: it builds with the NDK clang and +# needs no cmake. Its C code needs the target's C toolchain, so the Windows cross-check from Linux +# builds without this feature. +quinn = { version = "0.11", default-features = false, features = ["runtime-tokio", "rustls-ring"], optional = true } +rustls = { version = "0.23", default-features = false, features = ["ring", "std"], optional = true } +rcgen = { version = "0.14", default-features = false, features = ["ring"], optional = true } +ring = { version = "0.17", optional = true } +spake2 = { version = "0.4", optional = true } +serde = { workspace = true, optional = true } + +[features] +default = ["quic"] +quic = ["dep:quinn", "dep:rustls", "dep:rcgen", "dep:ring", "dep:spake2", "dep:serde"] [target.'cfg(any(target_os = "linux", target_os = "android"))'.dependencies] socket2 = { version = "0.6", features = ["all"] } diff --git a/crates/ezd-link/src/identity.rs b/crates/ezd-link/src/identity.rs new file mode 100644 index 0000000..b35dad9 --- /dev/null +++ b/crates/ezd-link/src/identity.rs @@ -0,0 +1,274 @@ +//! Device identity for Wi-Fi links: a self-signed certificate and its private key. +//! +//! Peers do not use a CA. Each side keeps one long-lived certificate and pins the other's +//! [`Fingerprint`] (SHA-256 of the certificate DER) when they pair. + +use ezd_proto::pair::Fingerprint; +use std::fmt::Write as _; +use std::io; +use std::path::Path; + +/// Certificate file name inside an identity directory. +pub const CERT_FILE: &str = "identity.crt"; +/// Private key file name inside an identity directory. +pub const KEY_FILE: &str = "identity.key"; + +/// A certificate (DER) and its PKCS#8 private key (DER). +#[derive(Clone)] +pub struct Identity { + cert_der: Vec, + key_der: Vec, +} + +impl std::fmt::Debug for Identity { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("Identity") + .field("fingerprint", &fingerprint_hex(&self.fingerprint())) + .finish_non_exhaustive() + } +} + +impl Identity { + /// Generates a new ECDSA P-256 identity. + pub fn generate() -> io::Result { + let key = rcgen::KeyPair::generate().map_err(io::Error::other)?; + let params = rcgen::CertificateParams::new(vec!["ezdisplay".to_string()]) + .map_err(io::Error::other)?; + let cert = params.self_signed(&key).map_err(io::Error::other)?; + Ok(Identity { + cert_der: cert.der().to_vec(), + key_der: key.serialize_der(), + }) + } + + /// Loads the identity stored in `dir`, or creates and stores a new one when neither file + /// exists. Only one of the two files is an error rather than a silent new identity, which + /// would drop every pairing. On Unix the directory is created owner-only and both files are + /// readable by the owner only. + pub fn load_or_create(dir: &Path) -> io::Result { + let (cert, key) = (dir.join(CERT_FILE), dir.join(KEY_FILE)); + match (std::fs::read(&cert), std::fs::read(&key)) { + (Ok(cert_der), Ok(key_der)) => { + let id = Identity { cert_der, key_der }; + // Fails early on a damaged file instead of at the first handshake. + id.key_pair()?; + return Ok(id); + } + (Err(c), Err(k)) + if c.kind() == io::ErrorKind::NotFound && k.kind() == io::ErrorKind::NotFound => {} + (Err(e), _) | (_, Err(e)) if e.kind() != io::ErrorKind::NotFound => return Err(e), + _ => { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + format!( + "incomplete identity in {}: one of {CERT_FILE} and {KEY_FILE} is missing", + dir.display() + ), + )); + } + } + create_private_dir(dir)?; + let id = Identity::generate()?; + // Key first: a crash in between leaves only the key, which the next start reports. + write_private(&key, &id.key_der)?; + write_private(&cert, &id.cert_der)?; + Ok(id) + } + + /// Certificate DER. + pub fn cert_der(&self) -> &[u8] { + &self.cert_der + } + + /// PKCS#8 private key DER. + pub fn key_der(&self) -> &[u8] { + &self.key_der + } + + /// SHA-256 of the certificate. + pub fn fingerprint(&self) -> Fingerprint { + fingerprint_of(&self.cert_der) + } + + fn key_pair(&self) -> io::Result { + rcgen::KeyPair::try_from(self.key_der.as_slice()).map_err(io::Error::other) + } +} + +/// SHA-256 of a certificate DER. +pub fn fingerprint_of(cert_der: &[u8]) -> Fingerprint { + let d = ring::digest::digest(&ring::digest::SHA256, cert_der); + let mut out = [0u8; 32]; + out.copy_from_slice(d.as_ref()); + out +} + +/// Lower-case hex of a fingerprint (64 characters). +pub fn fingerprint_hex(fp: &Fingerprint) -> String { + let mut s = String::with_capacity(64); + for b in fp { + let _ = write!(s, "{b:02x}"); + } + s +} + +/// Parses [`fingerprint_hex`] output (either case). +pub fn parse_fingerprint(hex: &str) -> Option { + let hex = hex.as_bytes(); + if hex.len() != 64 { + return None; + } + let mut out = [0u8; 32]; + for (o, pair) in out.iter_mut().zip(hex.chunks(2)) { + let s = std::str::from_utf8(pair).ok()?; + *o = u8::from_str_radix(s, 16).ok()?; + } + Some(out) +} + +/// Short form for people to compare: the first 8 bytes as 4 dash-separated groups, +/// e.g. `3f2a-91c0-77de-0b14`. +pub fn fingerprint_short(fp: &Fingerprint) -> String { + let hex = fingerprint_hex(fp); + [&hex[0..4], &hex[4..8], &hex[8..12], &hex[12..16]].join("-") +} + +/// Writes `data` to `path` through a new temporary file, `fsync` and a rename, so readers see +/// the old or the new contents and never a partial file. The file is readable by the owner +/// only (Unix). +pub fn write_atomic(path: &Path, data: &[u8]) -> io::Result<()> { + write_private(path, data) +} + +/// Unique temporary name next to `path` (`...tmp`). +fn temp_path(path: &Path) -> std::path::PathBuf { + static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0); + let n = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(format!(".{}.{n}.tmp", std::process::id())); + path.with_file_name(name) +} + +fn write_private(path: &Path, data: &[u8]) -> io::Result<()> { + use std::io::Write as _; + let tmp = temp_path(path); + let mut opts = std::fs::OpenOptions::new(); + // `create_new` never reuses a leftover or planted file (or follows a symlink). + opts.write(true).create_new(true); + #[cfg(unix)] + std::os::unix::fs::OpenOptionsExt::mode(&mut opts, 0o600); + // %APPDATA% is already private to the user on Windows. + let result = (|| { + let mut f = opts.open(&tmp)?; + f.write_all(data)?; + f.sync_all()?; + drop(f); + std::fs::rename(&tmp, path)?; + sync_dir(path) + })(); + if result.is_err() { + let _ = std::fs::remove_file(&tmp); + } + result +} + +/// Makes the rename durable (Unix; a no-op elsewhere). +fn sync_dir(path: &Path) -> io::Result<()> { + #[cfg(unix)] + if let Some(dir) = path.parent() { + let dir = if dir.as_os_str().is_empty() { + Path::new(".") + } else { + dir + }; + std::fs::File::open(dir)?.sync_all()?; + } + #[cfg(not(unix))] + let _ = path; + Ok(()) +} + +fn create_private_dir(dir: &Path) -> io::Result<()> { + let mut b = std::fs::DirBuilder::new(); + b.recursive(true); + #[cfg(unix)] + std::os::unix::fs::DirBuilderExt::mode(&mut b, 0o700); + b.create(dir) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn temp_dir(name: &str) -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("ezd-identity-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + d + } + + #[test] + fn load_or_create_is_stable() { + let d = temp_dir("stable"); + let a = Identity::load_or_create(&d).unwrap(); + let b = Identity::load_or_create(&d).unwrap(); + assert_eq!(a.fingerprint(), b.fingerprint()); + assert_ne!(a.fingerprint(), Identity::generate().unwrap().fingerprint()); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt as _; + let mode = std::fs::metadata(d.join(KEY_FILE)) + .unwrap() + .permissions() + .mode(); + assert_eq!(mode & 0o777, 0o600); + let mode = std::fs::metadata(&d).unwrap().permissions().mode(); + assert_eq!(mode & 0o777, 0o700); + } + std::fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn missing_half_is_an_error() { + let d = temp_dir("half"); + Identity::load_or_create(&d).unwrap(); + std::fs::remove_file(d.join(CERT_FILE)).unwrap(); + assert!(Identity::load_or_create(&d).is_err()); + assert!(!d.join(CERT_FILE).exists()); + std::fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn atomic_write_ignores_leftover_temp_files() { + let d = temp_dir("atomic"); + std::fs::create_dir_all(&d).unwrap(); + let p = d.join("data.json"); + write_atomic(&p, b"one").unwrap(); + write_atomic(&p, b"two").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"two"); + let names: Vec<_> = std::fs::read_dir(&d) + .unwrap() + .map(|e| e.unwrap().file_name()) + .collect(); + assert_eq!(names, ["data.json"]); + std::fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn damaged_key_is_an_error() { + let d = temp_dir("damaged"); + Identity::load_or_create(&d).unwrap(); + std::fs::write(d.join(KEY_FILE), b"garbage").unwrap(); + assert!(Identity::load_or_create(&d).is_err()); + std::fs::remove_dir_all(&d).unwrap(); + } + + #[test] + fn fingerprint_text_forms() { + let fp: Fingerprint = core::array::from_fn(|i| i as u8 * 7); + let hex = fingerprint_hex(&fp); + assert_eq!(parse_fingerprint(&hex), Some(fp)); + assert_eq!(parse_fingerprint(&hex.to_uppercase()), Some(fp)); + assert_eq!(parse_fingerprint(&hex[..62]), None); + assert_eq!(fingerprint_short(&fp), "0007-0e15-1c23-2a31"); + } +} diff --git a/crates/ezd-link/src/lib.rs b/crates/ezd-link/src/lib.rs index 451ef30..aa185d6 100644 --- a/crates/ezd-link/src/lib.rs +++ b/crates/ezd-link/src/lib.rs @@ -3,11 +3,18 @@ //! * [`Link`]: a reliable ordered byte stream (TCP, in-memory duplex, later AOA). //! * [`mux`]: [`MuxSender`] / [`MuxReceiver`], the prioritized message mux on top of a link. //! * [`adb`] (not on Android): locate `adb`, list devices, manage `adb reverse`. +//! * [`quic`], [`pair`], [`identity`] (`quic` feature): Wi-Fi links over QUIC with PIN pairing. #[cfg(not(target_os = "android"))] pub mod adb; +#[cfg(feature = "quic")] +pub mod identity; pub mod link; pub mod mux; +#[cfg(feature = "quic")] +pub mod pair; +#[cfg(feature = "quic")] +pub mod quic; pub use link::{BoxRead, BoxWrite, Link}; pub use mux::{ diff --git a/crates/ezd-link/src/link.rs b/crates/ezd-link/src/link.rs index 91543e7..e0d2558 100644 --- a/crates/ezd-link/src/link.rs +++ b/crates/ezd-link/src/link.rs @@ -1,6 +1,6 @@ //! [`Link`]: a reliable ordered byte stream. -use crate::mux::{MuxOptions, MuxReceiver, MuxSender, MuxTask, spawn_mux}; +use crate::mux::{MuxOptions, MuxReceiver, MuxSender, MuxTask, spawn_mux, spawn_mux_split}; use std::io; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpStream, ToSocketAddrs}; @@ -12,8 +12,10 @@ pub type BoxWrite = Box; /// A connected, reliable, ordered byte stream split into halves. /// -/// Transports (TCP now; AOA bulk endpoints later) only have to produce a -/// `Link`; everything above it is transport-agnostic. +/// Transports (TCP and QUIC now; AOA bulk endpoints later) only have to produce a +/// `Link`; everything above it is transport-agnostic. A link may carry a second +/// stream for video (see [`Link::with_video`]), which the mux then uses so video +/// cannot delay control, input or cursor traffic. pub struct Link { /// Read half. pub reader: BoxRead, @@ -21,6 +23,8 @@ pub struct Link { pub writer: BoxWrite, /// Human readable description of the peer, for logs. pub peer: String, + /// Separate video stream (read, write), if the transport has one. + video: Option<(BoxRead, BoxWrite)>, } impl std::fmt::Debug for Link { @@ -38,9 +42,22 @@ impl Link { reader, writer, peer: peer.into(), + video: None, } } + /// Adds a separate video stream. A side that only receives video passes + /// `tokio::io::sink()` as the write half; one that only sends passes `tokio::io::empty()`. + pub fn with_video(mut self, reader: BoxRead, writer: BoxWrite) -> Self { + self.video = Some((reader, writer)); + self + } + + /// True when the link has a separate video stream. + pub fn has_video_stream(&self) -> bool { + self.video.is_some() + } + /// Wraps a connected TCP stream and enables `TCP_NODELAY`. pub fn from_tcp(stream: TcpStream) -> io::Result { stream.set_nodelay(true)?; @@ -80,9 +97,18 @@ impl Link { /// Starts the mux with explicit [`MuxOptions`]. pub fn into_mux_with(self, opts: MuxOptions) -> (MuxSender, MuxReceiver, MuxTask) { - let rx = MuxReceiver::new(self.reader); - let (tx, task) = spawn_mux(self.writer, opts); - (tx, rx, task) + match self.video { + None => { + let rx = MuxReceiver::new(self.reader); + let (tx, task) = spawn_mux(self.writer, opts); + (tx, rx, task) + } + Some((video_r, video_w)) => { + let rx = MuxReceiver::new_split(self.reader, video_r); + let (tx, task) = spawn_mux_split(self.writer, video_w, opts); + (tx, rx, task) + } + } } } diff --git a/crates/ezd-link/src/mux.rs b/crates/ezd-link/src/mux.rs index a3ab484..04d9711 100644 --- a/crates/ezd-link/src/mux.rs +++ b/crates/ezd-link/src/mux.rs @@ -24,6 +24,11 @@ //! would corrupt the reference chain); producers coalesce *before* capture by //! pulling the newest frame only when a slot is free. //! +//! [`spawn_mux_split`] serves the same queues onto two byte streams: control, +//! input and cursor traffic on one, video on the other, so a stalled or +//! retransmitting video stream cannot delay them (head-of-line blocking on a +//! QUIC-like transport). [`MuxReceiver::new_split`] is its counterpart. +//! //! Reassembly on the receiving side ([`MuxReceiver`]) is keyed by //! `(channel, kind)`, so complete frames interleaved between video fragments are fine. @@ -209,6 +214,9 @@ struct SlotState { struct Shared { q: Mutex, wake: Notify, + /// Wakes the video writer in split mode (`wake` serves control/input/cursor then). + wake_video: Notify, + split: bool, slot: watch::Sender, coalesced: AtomicU64, states_sent: AtomicU64, @@ -243,6 +251,16 @@ impl Shared { fn close(&self) { self.lock().closing = true; self.wake.notify_one(); + self.wake_video.notify_one(); + } + + /// Wakes the writer that serves video (`video`) or everything else. + fn wake_writer(&self, video: bool) { + if video && self.split { + self.wake_video.notify_one(); + } else { + self.wake.notify_one(); + } } } @@ -328,7 +346,8 @@ impl MuxSender { _ => q.control.push_back(enc), } } - self.shared.wake.notify_one(); + self.shared + .wake_writer(matches!(msg, Message::VideoFrame(_))); Ok(()) } @@ -407,12 +426,12 @@ impl MuxSender { } } -/// Handle to the writer task. +/// Handle to the writer task (in split mode, to the task running both writers). #[derive(Debug)] pub struct MuxTask(tokio::task::JoinHandle>); impl MuxTask { - /// Waits for the writer to finish (after [`MuxSender::close`], all senders + /// Waits for the writer(s) to finish (after [`MuxSender::close`], all senders /// dropped, or a transport error). pub async fn join(self) -> io::Result<()> { match self.0.await { @@ -427,15 +446,16 @@ impl MuxTask { } } -/// Spawns the writer task on the current tokio runtime. -pub fn spawn_mux(writer: BoxWrite, opts: MuxOptions) -> (MuxSender, MuxTask) { +fn new_shared(opts: MuxOptions, split: bool) -> Arc { let (slot, _) = watch::channel(SlotState { busy: false, closed: false, }); - let shared = Arc::new(Shared { + Arc::new(Shared { q: Mutex::new(Queues::default()), wake: Notify::new(), + wake_video: Notify::new(), + split, slot, coalesced: AtomicU64::new(0), states_sent: AtomicU64::new(0), @@ -445,14 +465,44 @@ pub fn spawn_mux(writer: BoxWrite, opts: MuxOptions) -> (MuxSender, MuxTask) { frames_written: AtomicU64::new(0), ack_timeouts: AtomicU64::new(0), credit: opts.credit, - }); - let chunk_len = opts.chunk_len.clamp(1, ezd_proto::MAX_FRAME_LEN as usize); - let task = tokio::spawn(writer_task(shared.clone(), writer, chunk_len)); - let sender = MuxSender { + }) +} + +fn sender_for(shared: Arc) -> MuxSender { + MuxSender { shared: shared.clone(), _guard: Arc::new(CloseOnDrop(shared)), - }; - (sender, MuxTask(task)) + } +} + +fn clamp_chunk(opts: MuxOptions) -> usize { + opts.chunk_len.clamp(1, ezd_proto::MAX_FRAME_LEN as usize) +} + +/// Spawns the writer task on the current tokio runtime. +pub fn spawn_mux(writer: BoxWrite, opts: MuxOptions) -> (MuxSender, MuxTask) { + let shared = new_shared(opts, false); + let task = tokio::spawn(writer_task(shared.clone(), writer, clamp_chunk(opts))); + (sender_for(shared), MuxTask(task)) +} + +/// Like [`spawn_mux`] but with two streams: control, input and cursor traffic +/// go to `control`, video to `video`. Both writers run in one task; if either +/// fails the mux closes and the other stops too. On a graceful close each +/// drains its queues and shuts down its own half. +pub fn spawn_mux_split( + control: BoxWrite, + video: BoxWrite, + opts: MuxOptions, +) -> (MuxSender, MuxTask) { + let shared = new_shared(opts, true); + let task = tokio::spawn(split_task( + shared.clone(), + control, + video, + clamp_chunk(opts), + )); + (sender_for(shared), MuxTask(task)) } enum Next { @@ -512,32 +562,9 @@ async fn writer_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io: } Next::Done => return Ok(()), Next::Whole(m, is_state) => { - for (flags, chunk) in fragments(&m.payload, chunk_len) { - buf.clear(); - put_frame(&mut buf, m.channel, m.kind, flags, chunk); - w.write_all(&buf).await?; - shared.frames_written.fetch_add(1, Ordering::Relaxed); - } - w.flush().await?; - if is_state { - shared.states_sent.fetch_add(1, Ordering::Relaxed); - } - } - Next::Input(batch) => { - // One contiguous buffer, one write, one flush. - buf.clear(); - let mut n = 0u64; - for m in &batch { - for (flags, chunk) in fragments(&m.payload, chunk_len) { - put_frame(&mut buf, m.channel, m.kind, flags, chunk); - shared.frames_written.fetch_add(1, Ordering::Relaxed); - } - n += 1; - } - w.write_all(&buf).await?; - w.flush().await?; - shared.inputs_sent.fetch_add(n, Ordering::Relaxed); + write_whole(shared, w, &mut buf, &m, is_state, chunk_len).await?; } + Next::Input(batch) => write_input(shared, w, &mut buf, &batch, chunk_len).await?, Next::VideoChunk => { let Some((enc, off)) = in_flight.as_mut() else { continue; @@ -563,19 +590,167 @@ async fn writer_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io: if finished { w.flush().await?; let ack_id = in_flight.take().and_then(|(e, _)| e.ack_id); - shared.videos_sent.fetch_add(1, Ordering::Relaxed); - let mut q = shared.lock(); - q.writing = false; - let early = q.early_ack.take(); - if let (Some(id), VideoCredit::OnAck { .. }) = (ack_id, shared.credit) - && early.is_none_or(|a| a < id) - { - q.unacked.push_back((id, Instant::now())); - } - shared.update_slot(&q); + finish_video(shared, ack_id); + } + } + } + } +} + +/// Writes one message (all its fragments) and flushes. +async fn write_whole( + shared: &Shared, + w: &mut BoxWrite, + buf: &mut Vec, + m: &Encoded, + is_state: bool, + chunk_len: usize, +) -> io::Result<()> { + for (flags, chunk) in fragments(&m.payload, chunk_len) { + buf.clear(); + put_frame(buf, m.channel, m.kind, flags, chunk); + w.write_all(buf).await?; + shared.frames_written.fetch_add(1, Ordering::Relaxed); + } + w.flush().await?; + if is_state { + shared.states_sent.fetch_add(1, Ordering::Relaxed); + } + Ok(()) +} + +/// Writes an input batch: one contiguous buffer, one write, one flush. +async fn write_input( + shared: &Shared, + w: &mut BoxWrite, + buf: &mut Vec, + batch: &[Encoded], + chunk_len: usize, +) -> io::Result<()> { + buf.clear(); + let mut n = 0u64; + for m in batch { + for (flags, chunk) in fragments(&m.payload, chunk_len) { + put_frame(buf, m.channel, m.kind, flags, chunk); + shared.frames_written.fetch_add(1, Ordering::Relaxed); + } + n += 1; + } + w.write_all(buf).await?; + w.flush().await?; + shared.inputs_sent.fetch_add(n, Ordering::Relaxed); + Ok(()) +} + +/// Bookkeeping after the last chunk of a video frame was written and flushed. +fn finish_video(shared: &Shared, ack_id: Option) { + shared.videos_sent.fetch_add(1, Ordering::Relaxed); + let mut q = shared.lock(); + q.writing = false; + let early = q.early_ack.take(); + if let (Some(id), VideoCredit::OnAck { .. }) = (ack_id, shared.credit) + && early.is_none_or(|a| a < id) + { + q.unacked.push_back((id, Instant::now())); + } + shared.update_slot(&q); +} + +/// Runs both split writers; the first error stops the other one. +async fn split_task( + shared: Arc, + mut control: BoxWrite, + mut video: BoxWrite, + chunk_len: usize, +) -> io::Result<()> { + let res = { + let c = control_loop(&shared, &mut control, chunk_len); + let v = video_loop(&shared, &mut video, chunk_len); + tokio::pin!(c, v); + tokio::select! { + r = &mut c => match r { + Ok(()) => v.await, + Err(e) => Err(e), + }, + r = &mut v => match r { + Ok(()) => c.await, + Err(e) => Err(e), + }, + } + }; + shared.lock().closing = true; + shared.slot.send_modify(|s| s.closed = true); + let _ = tokio::join!(control.shutdown(), video.shutdown()); + if let Err(e) = &res { + tracing::debug!("mux writer stopped: {e}"); + } + res +} + +/// Split-mode writer for control > input > cursor shapes > cursor state. +async fn control_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { + let mut buf: Vec = Vec::with_capacity(chunk_len + 16); + loop { + let next = { + let mut q = shared.lock(); + if let Some(m) = q.control.pop_front() { + Next::Whole(m, false) + } else if !q.input.is_empty() { + Next::Input(q.input.drain(..).map(|i| i.enc).collect()) + } else if let Some(m) = q.cursor_shapes.pop_front() { + Next::Whole(m, false) + } else if let Some(m) = q.cursor_state.take() { + Next::Whole(m, true) + } else if q.closing { + Next::Done + } else { + Next::Idle(None) + } + }; + match next { + Next::Done => return Ok(()), + Next::Whole(m, is_state) => { + write_whole(shared, w, &mut buf, &m, is_state, chunk_len).await?; + } + Next::Input(batch) => write_input(shared, w, &mut buf, &batch, chunk_len).await?, + _ => shared.wake.notified().await, + } + } +} + +/// Split-mode writer for video; also expires ack deadlines while idle. +async fn video_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { + let mut buf: Vec = Vec::with_capacity(chunk_len + 16); + loop { + let (frame, deadline, closing) = { + let mut q = shared.lock(); + let deadline = expire_acks(shared, &mut q); + let frame = q.video.pop_front(); + if frame.is_some() { + q.writing = true; + } + (frame, deadline, q.closing) + }; + let Some(enc) = frame else { + if closing { + return Ok(()); + } + match deadline { + None => shared.wake_video.notified().await, + Some(at) => { + let _ = tokio::time::timeout_at(at.into(), shared.wake_video.notified()).await; } } + continue; + }; + for (flags, chunk) in fragments(&enc.payload, chunk_len) { + buf.clear(); + put_frame(&mut buf, enc.channel, enc.kind, flags, chunk); + w.write_all(&buf).await?; + shared.frames_written.fetch_add(1, Ordering::Relaxed); } + w.flush().await?; + finish_video(shared, enc.ack_id); } } @@ -605,12 +780,25 @@ fn expire_acks(shared: &Shared, q: &mut Queues) -> Option { q.unacked.front().map(|&(_, at)| at + timeout) } -/// Reads and decodes messages from a link's read half. +/// Reads and decodes messages from a link's read half (or from the two halves +/// of a split link). pub struct MuxReceiver { reader: BoxRead, decoder: FrameDecoder, buf: Vec, unknown: u64, + /// Video stream of a split receiver; `None` for a single-stream one. + video: Option, + /// The primary reader ended cleanly (split mode only). + ended: bool, +} + +/// Reader, decoder and read buffer of the second stream of a split receiver. +struct Side { + reader: BoxRead, + decoder: FrameDecoder, + buf: Vec, + ended: bool, } impl std::fmt::Debug for MuxReceiver { @@ -621,6 +809,39 @@ impl std::fmt::Debug for MuxReceiver { } } +/// Pops the next known message from `decoder`, counting skipped unknown kinds. +fn pop_known(decoder: &mut FrameDecoder, unknown: &mut u64) -> Result, MuxError> { + loop { + match decoder.pop()? { + Some(Incoming::Message(m)) => return Ok(Some(m)), + Some(Incoming::Unknown { channel, kind, len }) => { + *unknown += 1; + tracing::debug!(channel, kind, len, "skipping unknown message"); + } + None => return Ok(None), + } + } +} + +/// Handles the result of a read: feeds the decoder, or marks a clean EOF. +fn feed( + decoder: &mut FrameDecoder, + buf: &[u8], + n: io::Result, + ended: &mut bool, +) -> Result<(), MuxError> { + let n = n?; + if n == 0 { + if decoder.buffered() != 0 { + return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into()); + } + *ended = true; + } else { + decoder.push(&buf[..n]); + } + Ok(()) +} + impl MuxReceiver { /// Wraps a read half. pub fn new(reader: BoxRead) -> Self { @@ -629,6 +850,22 @@ impl MuxReceiver { decoder: FrameDecoder::new(), buf: vec![0; 64 * 1024], unknown: 0, + video: None, + ended: false, + } + } + + /// Wraps the two read halves of a split link (see [`spawn_mux_split`]). + /// Each stream has its own decoder; control is preferred when both have data. + pub fn new_split(control: BoxRead, video: BoxRead) -> Self { + MuxReceiver { + video: Some(Side { + reader: video, + decoder: FrameDecoder::new(), + buf: vec![0; 64 * 1024], + ended: false, + }), + ..Self::new(control) } } @@ -637,9 +874,13 @@ impl MuxReceiver { self.unknown } - /// Receives the next known message; `Ok(None)` on a clean EOF between messages. - /// Unknown message kinds are skipped transparently. Cancel-safe. + /// Receives the next known message; `Ok(None)` on a clean EOF between messages + /// (for a split receiver: once both streams ended). Unknown message kinds are + /// skipped transparently. Cancel-safe. pub async fn recv(&mut self) -> Result, MuxError> { + if self.video.is_some() { + return self.recv_split().await; + } loop { match self.decoder.pop()? { Some(Incoming::Message(m)) => return Ok(Some(m)), @@ -661,6 +902,33 @@ impl MuxReceiver { self.decoder.push(&self.buf[..n]); } } + + async fn recv_split(&mut self) -> Result, MuxError> { + let Some(video) = self.video.as_mut() else { + return Ok(None); + }; + loop { + if let Some(m) = pop_known(&mut self.decoder, &mut self.unknown)? { + return Ok(Some(m)); + } + if let Some(m) = pop_known(&mut video.decoder, &mut self.unknown)? { + return Ok(Some(m)); + } + if self.ended && video.ended { + return Ok(None); + } + // Reads are cancel-safe: the losing branch of the select drops no data. + tokio::select! { + biased; + n = self.reader.read(&mut self.buf), if !self.ended => { + feed(&mut self.decoder, &self.buf, n, &mut self.ended)?; + } + n = video.reader.read(&mut video.buf), if !video.ended => { + feed(&mut video.decoder, &video.buf, n, &mut video.ended)?; + } + } + } + } } /// Priority rank of a channel (lower is more urgent); documents the writer @@ -1276,4 +1544,219 @@ mod tests { tx.ack_video(2); assert!(tx.video_slot_free()); } + + /// Split mux over two duplex streams; returns the sender, its task and a split receiver. + fn split_pair( + ctl_cap: usize, + vid_cap: usize, + opts: MuxOptions, + ) -> (MuxSender, MuxTask, MuxReceiver) { + let (cw, cr) = tokio::io::duplex(ctl_cap); + let (vw, vr) = tokio::io::duplex(vid_cap); + let (tx, task) = spawn_mux_split(Box::new(cw), Box::new(vw), opts); + (tx, task, MuxReceiver::new_split(Box::new(cr), Box::new(vr))) + } + + /// Writer that fails every write. + struct FailWriter; + impl tokio::io::AsyncWrite for FailWriter { + fn poll_write( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + _: &[u8], + ) -> std::task::Poll> { + std::task::Poll::Ready(Err(io::Error::from(io::ErrorKind::BrokenPipe))) + } + fn poll_flush( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + fn poll_shutdown( + self: std::pin::Pin<&mut Self>, + _: &mut std::task::Context<'_>, + ) -> std::task::Poll> { + std::task::Poll::Ready(Ok(())) + } + } + + #[tokio::test] + async fn split_stalled_video_does_not_delay_control_traffic() { + let (cw, cr) = tokio::io::duplex(64 * 1024); + let (vw, _vr_never_read) = tokio::io::duplex(1024); + let (tx, _task) = spawn_mux_split(Box::new(cw), Box::new(vw), onwrite(4096)); + let mut rx = MuxReceiver::new(Box::new(cr)); + tx.send_video(vf(1, 1024 * 1024)).unwrap(); + sleep(Duration::from_millis(50)).await; // video writer is blocked on a full stream + tx.send_control(Message::Ping(Ping { seq: 1, t0_us: 0 })) + .unwrap(); + tx.send(&pen(7, PenSample::IN_RANGE)).unwrap(); + tx.send(&Message::CursorShape(CursorShape { + shape_id: 4, + width: 1, + height: 1, + hot_x: 0, + hot_y: 0, + rgba: vec![0; 4], + })) + .unwrap(); + tx.send_cursor_state(cs(5)).unwrap(); + assert!(matches!(recv(&mut rx).await, Message::Ping(_))); + assert!(matches!(recv(&mut rx).await, Message::Pen(p) if p.t_us == 7)); + assert!(matches!(recv(&mut rx).await, Message::CursorShape(s) if s.shape_id == 4)); + assert!(matches!(recv(&mut rx).await, Message::CursorState(s) if s.x == 5)); + assert!(!tx.video_slot_free()); + } + + #[tokio::test] + async fn split_delivers_both_streams_in_per_channel_order() { + let (tx, _task, mut rx) = split_pair(4096, 4096, onwrite(1024)); + let sender = { + let tx = tx.clone(); + tokio::spawn(async move { + for i in 0..10u64 { + tx.send_video(vf(i, 20_000)).unwrap(); + tx.send(&pen(i, PenSample::IN_RANGE)).unwrap(); + tx.send_control(Message::Ping(Ping { + seq: i as u32, + t0_us: 0, + })) + .unwrap(); + tx.wait_video_slot().await.unwrap(); + } + }) + }; + let (mut videos, mut pens, mut pings) = (vec![], vec![], vec![]); + while videos.len() < 10 || pens.len() < 10 || pings.len() < 10 { + match recv(&mut rx).await { + Message::VideoFrame(v) => { + assert_eq!(v.data, vf(v.frame_id, 20_000).data); + videos.push(v.frame_id); + } + Message::Pen(p) => pens.push(p.t_us), + Message::Ping(p) => pings.push(p.seq), + m => panic!("{m:?}"), + } + } + sender.await.unwrap(); + let want: Vec = (0..10).collect(); + assert_eq!( + (videos, pens, pings), + ( + want.clone(), + want.clone(), + want.iter().map(|&i| i as u32).collect::>() + ) + ); + } + + #[tokio::test] + async fn split_credit_is_held_until_ack_and_early_ack_works() { + let (tx, _task, mut rx) = split_pair(1 << 20, 1 << 20, acked(1, 5000)); + tx.send_video(vf(7, 100)).unwrap(); + assert!(matches!(recv(&mut rx).await, Message::VideoFrame(_))); + sleep(Duration::from_millis(50)).await; + assert!(!tx.video_slot_free(), "written but not acked"); + assert_eq!(tx.ack_video(7), 1); + timeout(Duration::from_secs(1), tx.wait_video_slot()) + .await + .unwrap() + .unwrap(); + // The ack for 8 arrives before the writer records the frame: consumed, not stuck. + assert_eq!(tx.ack_video(8), 0); + tx.send_video(vf(8, 100)).unwrap(); + recv(&mut rx).await; + timeout(Duration::from_secs(1), tx.wait_video_slot()) + .await + .expect("an early ack must not wait for the ack timeout") + .unwrap(); + assert_eq!(tx.stats().ack_timeouts, 0); + } + + #[tokio::test] + async fn split_ack_timeout_frees_slot_while_idle() { + let (tx, _task, mut rx) = split_pair(1 << 20, 1 << 20, acked(1, 100)); + tx.send_video(vf(1, 100)).unwrap(); + recv(&mut rx).await; + timeout(Duration::from_secs(2), tx.wait_video_slot()) + .await + .expect("the idle writer must wake at the ack deadline") + .unwrap(); + assert_eq!(tx.stats().ack_timeouts, 1); + } + + #[tokio::test] + async fn split_close_flushes_both_streams_then_ends() { + let (tx, task, mut rx) = split_pair(64 * 1024, 64 * 1024, onwrite(1024)); + tx.send_video(vf(1, 10_000)).unwrap(); + tx.send_cursor_state(cs(3)).unwrap(); + tx.send_control(Message::Bye(Bye { + reason: "done".into(), + })) + .unwrap(); + tx.close(); + assert!(tx.send_control(Message::ConfigAck).is_err()); + let mut got = vec![]; + while let Some(m) = timeout(Duration::from_secs(10), rx.recv()) + .await + .unwrap() + .unwrap() + { + got.push(m); + } + assert_eq!(got.len(), 3); + assert!(got.iter().any(|m| matches!(m, Message::Bye(_)))); + assert!(got.iter().any(|m| matches!(m, Message::CursorState(_)))); + assert!( + got.iter() + .any(|m| matches!(m, Message::VideoFrame(v) if v.data.len() == 10_000)) + ); + task.join().await.unwrap(); + } + + #[tokio::test] + async fn split_receiver_survives_one_stream_eof() { + let (mut cw, cr) = tokio::io::duplex(4096); + let (mut vw, vr) = tokio::io::duplex(4096); + let mut rx = MuxReceiver::new_split(Box::new(cr), Box::new(vr)); + let mut buf = Vec::new(); + let (ch, kind, payload) = encode_message(&Message::ConfigAck).unwrap(); + put_frame(&mut buf, ch as u8, kind, 0, &payload); + cw.write_all(&buf).await.unwrap(); + cw.shutdown().await.unwrap(); // control ends first + assert!(matches!(recv(&mut rx).await, Message::ConfigAck)); + assert!( + timeout(Duration::from_millis(100), rx.recv()) + .await + .is_err(), + "video is still open" + ); + let (ch, kind, payload) = encode_message(&Message::VideoFrame(vf(1, 10))).unwrap(); + buf.clear(); + put_frame(&mut buf, ch as u8, kind, 0, &payload); + vw.write_all(&buf).await.unwrap(); + assert!(matches!(recv(&mut rx).await, Message::VideoFrame(_))); + // Mid-message EOF on video is an error. + vw.write_all(&buf[..5]).await.unwrap(); + vw.shutdown().await.unwrap(); + assert!(matches!(rx.recv().await, Err(MuxError::Io(_)))); + } + + #[tokio::test] + async fn split_video_write_error_closes_the_mux() { + let (cw, _cr) = tokio::io::duplex(4096); + let (tx, task) = spawn_mux_split(Box::new(cw), Box::new(FailWriter), onwrite(1024)); + tx.send_video(vf(1, 100)).unwrap(); + let err = timeout(Duration::from_secs(5), task.join()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::BrokenPipe); + assert!(matches!( + tx.send_control(Message::ConfigAck), + Err(MuxError::Closed(_)) + )); + assert!(tx.wait_video_slot().await.is_err()); + } } diff --git a/crates/ezd-link/src/pair.rs b/crates/ezd-link/src/pair.rs new file mode 100644 index 0000000..2a3b4da --- /dev/null +++ b/crates/ezd-link/src/pair.rs @@ -0,0 +1,794 @@ +//! PIN pairing over a Wi-Fi link. +//! +//! The host shows a one-time 6-digit PIN (and a QR code with its address and certificate +//! fingerprint). Over a fresh QUIC connection both sides run SPAKE2 with the PIN as the +//! password, then exchange key confirmations: HMACs over a transcript that holds both +//! certificate fingerprints and TLS keying material of this connection. Confirmations only +//! match when both used the same PIN *and* see the same TLS session, so a man in the middle +//! (who must run two TLS sessions) fails, and each attempt tests a single PIN guess. After +//! [`MAX_ATTEMPTS`] attempts the window closes. +//! +//! On success each side pins the other's fingerprint; later connections use +//! [`crate::quic::connect`] with the pinned host fingerprint and skip pairing. + +use crate::identity::{fingerprint_hex, parse_fingerprint}; +use crate::quic::{Opened, QuicConn, QuicError, finish_and_close, read_msg, write_msg}; +use ezd_proto::pair::{ + Fingerprint, LinkOpen, LinkReply, PIN_DIGITS, PairConfirm, PairOutcome, Refusal, is_valid_pin, +}; +use ring::hmac; +use spake2::{Ed25519Group, Identity as SpakeId, Password, Spake2}; +use std::net::SocketAddr; +use std::sync::Mutex; +use std::time::{Duration, Instant}; + +/// Pairing attempts allowed per window (each tests one PIN guess). +pub const MAX_ATTEMPTS: u32 = 5; +/// Default lifetime of a pairing window. +pub const DEFAULT_WINDOW: Duration = Duration::from_secs(5 * 60); +/// Longest device or host name kept from a peer. +pub const MAX_NAME_CHARS: usize = 64; + +const SPAKE_ID_CLIENT: &[u8] = b"ezdisplay client"; +const SPAKE_ID_HOST: &[u8] = b"ezdisplay host"; +const TRANSCRIPT_TAG: &[u8] = b"ezd-pair-v1"; +const EXPORTER_LABEL: &[u8] = b"EXPORTER-ezd-pair-v1"; +const CONFIRM_HOST: &[u8] = b"host confirm"; +const CONFIRM_CLIENT: &[u8] = b"client confirm"; + +/// A host the client paired with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairedHost { + /// Host certificate fingerprint to pin. + pub fingerprint: Fingerprint, + /// Host name, as announced by the host. + pub name: String, +} + +/// A client the host paired with. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairedClient { + /// Client certificate fingerprint to pin. + pub fingerprint: Fingerprint, + /// Device name, as announced by the client. + pub name: String, +} + +/// Why a host-side pairing attempt ended without pairing. +#[derive(Debug, thiserror::Error)] +pub enum HostPairError { + /// The attempt was refused (closed window, too many attempts, wrong PIN). + #[error("pairing refused: {0:?}")] + Refused(Refusal), + /// The connection failed or the client sent something unexpected. + #[error(transparent)] + Link(#[from] QuicError), + /// Storing the client failed; the client was told the pairing was refused. + #[error("cannot store the paired device: {0}")] + Store(std::io::Error), +} + +/// Generates a uniformly random PIN of [`PIN_DIGITS`] digits. +pub fn generate_pin() -> String { + use ring::rand::{SecureRandom, SystemRandom}; + let rng = SystemRandom::new(); + // Rejection sampling keeps the digits uniform. + const LIMIT: u32 = u32::MAX - u32::MAX % 1_000_000; + loop { + let mut b = [0u8; 4]; + rng.fill(&mut b).expect("system random source"); + let v = u32::from_le_bytes(b); + if v < LIMIT { + return format!("{:0width$}", v % 1_000_000, width = PIN_DIGITS); + } + } +} + +/// State of a [`PairingWindow`]. Its `Debug` output hides the PIN. +#[derive(Clone, PartialEq, Eq)] +pub enum WindowState { + /// Accepting attempts with this PIN until `expires`. + Open { + /// The PIN. + pin: String, + /// When the window closes by itself. + expires: Instant, + /// Attempts already started. + attempts: u32, + }, + /// Not accepting attempts. + Closed(CloseReason), +} + +impl std::fmt::Debug for WindowState { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + WindowState::Open { + expires, attempts, .. + } => f + .debug_struct("Open") + .field("pin", &"") + .field("expires", expires) + .field("attempts", attempts) + .finish(), + WindowState::Closed(why) => f.debug_tuple("Closed").field(why).finish(), + } + } +} + +/// Why a pairing window is closed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CloseReason { + /// Never opened, or closed on request. + NotOpen, + /// A device paired. + Paired, + /// [`MAX_ATTEMPTS`] attempts were used. + TooManyAttempts, + /// It expired. + Expired, +} + +/// The host's pairing window: at most one PIN at a time, [`MAX_ATTEMPTS`] attempts, a +/// deadline. Shared between the accept loop and whoever shows the PIN. +/// +/// Every open or close starts a new generation. An attempt only pairs if the window it began +/// in is still current when it finishes, so closing or reopening the window (or its expiry) +/// cancels attempts in flight, and one window pairs at most one device. +#[derive(Debug)] +pub struct PairingWindow { + state: Mutex, +} + +#[derive(Debug)] +struct Generation { + state: WindowState, + id: u64, +} + +impl Default for PairingWindow { + fn default() -> Self { + PairingWindow { + state: Mutex::new(Generation { + state: WindowState::Closed(CloseReason::NotOpen), + id: 0, + }), + } + } +} + +impl PairingWindow { + /// Opens (or reopens) the window with a new random PIN; returns the PIN. + pub fn open(&self, ttl: Duration) -> String { + let pin = generate_pin(); + self.open_with(pin.clone(), ttl); + pin + } + + /// Opens the window with a given PIN (tests). + pub fn open_with(&self, pin: String, ttl: Duration) { + let mut g = self.lock(); + g.id += 1; + g.state = WindowState::Open { + pin, + expires: Instant::now() + ttl, + attempts: 0, + }; + } + + /// Closes the window and cancels attempts in flight. + pub fn close(&self) { + let mut g = self.lock(); + g.id += 1; + g.state = WindowState::Closed(CloseReason::NotOpen); + } + + /// Current state (an expired window reads as closed). + pub fn state(&self) -> WindowState { + let mut g = self.lock(); + Self::expire(&mut g.state); + g.state.clone() + } + + /// True while attempts are accepted. + pub fn is_open(&self) -> bool { + matches!(self.state(), WindowState::Open { .. }) + } + + /// Starts an attempt: returns the PIN and the window generation, or why no attempt is + /// possible. Every started attempt counts, even one the client abandons. + fn begin(&self) -> Result<(String, u64), Refusal> { + let mut g = self.lock(); + let id = g.id; + Self::expire(&mut g.state); + match &mut g.state { + WindowState::Open { pin, attempts, .. } => { + *attempts += 1; + let pin = pin.clone(); + if *attempts >= MAX_ATTEMPTS { + // This is the last one; a success turns it into `Paired`. + g.state = WindowState::Closed(CloseReason::TooManyAttempts); + } + Ok((pin, id)) + } + WindowState::Closed(CloseReason::TooManyAttempts) => Err(Refusal::TooManyAttempts), + WindowState::Closed(_) => Err(Refusal::PairingClosed), + } + } + + /// Finishes a successful attempt of generation `id`: if that window is still current and + /// has not paired or expired, runs `store` and closes the window as paired, all under the + /// lock (`store` must not use the window). `Ok(false)` when the window moved on. + fn commit( + &self, + id: u64, + store: impl FnOnce() -> std::io::Result<()>, + ) -> std::io::Result { + let mut g = self.lock(); + Self::expire(&mut g.state); + let live = g.id == id + && matches!( + g.state, + WindowState::Open { .. } | WindowState::Closed(CloseReason::TooManyAttempts) + ); + if !live { + return Ok(false); + } + store()?; + g.state = WindowState::Closed(CloseReason::Paired); + Ok(true) + } + + fn expire(s: &mut WindowState) { + if let WindowState::Open { expires, .. } = s + && Instant::now() >= *expires + { + *s = WindowState::Closed(CloseReason::Expired); + } + } + + fn lock(&self) -> std::sync::MutexGuard<'_, Generation> { + self.state.lock().unwrap_or_else(|e| e.into_inner()) + } +} + +/// Transcript both confirmations cover. +fn transcript( + conn: &QuicConn, + host_fp: &Fingerprint, + client_fp: &Fingerprint, +) -> Result, QuicError> { + let exported = conn.export(EXPORTER_LABEL)?; + let mut t = Vec::with_capacity(TRANSCRIPT_TAG.len() + 96); + t.extend_from_slice(TRANSCRIPT_TAG); + t.extend_from_slice(&exported); + t.extend_from_slice(host_fp); + t.extend_from_slice(client_fp); + Ok(t) +} + +/// Confirmation key for one side, derived from the SPAKE2 key. +fn confirm_key(spake_key: &[u8], side: &[u8]) -> hmac::Key { + let k = hmac::sign(&hmac::Key::new(hmac::HMAC_SHA256, spake_key), side); + hmac::Key::new(hmac::HMAC_SHA256, k.as_ref()) +} + +fn confirm_tag(spake_key: &[u8], side: &[u8], transcript: &[u8]) -> [u8; 32] { + let tag = hmac::sign(&confirm_key(spake_key, side), transcript); + let mut out = [0u8; 32]; + out.copy_from_slice(tag.as_ref()); + out +} + +fn confirm_ok(spake_key: &[u8], side: &[u8], transcript: &[u8], tag: &[u8; 32]) -> bool { + // Constant time. + hmac::verify(&confirm_key(spake_key, side), transcript, tag).is_ok() +} + +/// Keeps printable characters and at most [`MAX_NAME_CHARS`] of them. Bidirectional +/// overrides and invisible format characters are dropped so a name cannot disguise itself. +pub fn clean_name(name: &str) -> String { + name.chars() + .filter(|&c| !c.is_control() && !is_format_char(c)) + .take(MAX_NAME_CHARS) + .collect::() + .trim() + .to_string() +} + +/// Invisible or direction-changing format characters (Unicode `Cf` ranges that matter for +/// display spoofing). +fn is_format_char(c: char) -> bool { + matches!(c, + '\u{00AD}' | '\u{061C}' | '\u{180E}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' + | '\u{2060}'..='\u{206F}' | '\u{FEFF}' | '\u{FFF9}'..='\u{FFFB}') +} + +/// Client: pairs over `conn` (from [`crate::quic::connect`]) with the PIN shown by the host. +/// On success the caller pins [`PairedHost::fingerprint`] and opens sessions on new +/// connections. +pub async fn pair(conn: QuicConn, pin: &str, device_name: &str) -> Result { + if !is_valid_pin(pin) { + return Err(QuicError::InvalidPin); + } + let host_fp = conn + .peer_fingerprint() + .ok_or(QuicError::Unexpected("no host certificate"))?; + let (state, msg_a) = Spake2::::start_a( + &Password::new(pin.as_bytes()), + &SpakeId::new(SPAKE_ID_CLIENT), + &SpakeId::new(SPAKE_ID_HOST), + ); + let (mut send, mut recv) = conn.open_bi().await?; + write_msg( + &mut send, + &LinkOpen::Pair { + device_name: clean_name(device_name), + spake: msg_a, + }, + ) + .await?; + let (host_name, msg_b, host_confirm) = match read_msg::(&mut recv).await? { + LinkReply::PairChallenge { + host_name, + spake, + confirm, + } => (host_name, spake, confirm), + LinkReply::Refused(r) => return Err(QuicError::Refused(r)), + LinkReply::Accepted => return Err(QuicError::Unexpected("session reply to pairing")), + }; + let t = transcript(&conn, &host_fp, &conn.local_fingerprint())?; + let key = state.finish(&msg_b); + let Some(key) = key + .ok() + .filter(|k| confirm_ok(k, CONFIRM_HOST, &t, &host_confirm)) + else { + // Wrong PIN, or someone in the middle. Tell the host nothing it could test offline. + conn.close("pairing failed"); + return Err(QuicError::Refused(Refusal::WrongPin)); + }; + write_msg( + &mut send, + &PairConfirm { + confirm: confirm_tag(&key, CONFIRM_CLIENT, &t), + }, + ) + .await?; + let outcome = read_msg::(&mut recv).await?; + finish_and_close(&mut send, &conn, "paired").await; + match outcome { + PairOutcome::Paired => Ok(PairedHost { + fingerprint: host_fp, + name: clean_name(&host_name), + }), + PairOutcome::Refused(r) => Err(QuicError::Refused(r)), + } +} + +/// Host: runs a pairing attempt for a client whose [`LinkOpen::Pair`] was read. `store` is +/// called with the new client before the client is told it is paired; if it fails the client +/// is refused. +pub async fn host_pair( + opened: Opened, + window: &PairingWindow, + host_name: &str, + store: impl FnOnce(&PairedClient) -> std::io::Result<()>, +) -> Result { + let LinkOpen::Pair { + device_name, + spake: msg_a, + } = opened.open.clone() + else { + return Err(QuicError::Unexpected("not a pairing request").into()); + }; + let Some(client_fp) = opened.peer_fingerprint() else { + return Err(QuicError::Unexpected("no client certificate").into()); + }; + let (pin, generation) = match window.begin() { + Ok(begun) => begun, + Err(why) => { + opened.refuse(why).await; + return Err(HostPairError::Refused(why)); + } + }; + let Opened { + conn, + mut send, + mut recv, + .. + } = opened; + let (state, msg_b) = Spake2::::start_b( + &Password::new(pin.as_bytes()), + &SpakeId::new(SPAKE_ID_CLIENT), + &SpakeId::new(SPAKE_ID_HOST), + ); + let Ok(key) = state.finish(&msg_a) else { + let _ = write_msg(&mut send, &LinkReply::Refused(Refusal::WrongPin)).await; + finish_and_close(&mut send, &conn, "pairing failed").await; + return Err(HostPairError::Refused(Refusal::WrongPin)); + }; + let t = transcript(&conn, &conn.local_fingerprint(), &client_fp)?; + write_msg( + &mut send, + &LinkReply::PairChallenge { + host_name: clean_name(host_name), + spake: msg_b, + confirm: confirm_tag(&key, CONFIRM_HOST, &t), + }, + ) + .await?; + // A client with the wrong PIN closes the connection here. + let confirm = read_msg::(&mut recv).await?; + if !confirm_ok(&key, CONFIRM_CLIENT, &t, &confirm.confirm) { + let _ = write_msg(&mut send, &PairOutcome::Refused(Refusal::WrongPin)).await; + finish_and_close(&mut send, &conn, "pairing failed").await; + return Err(HostPairError::Refused(Refusal::WrongPin)); + } + let client = PairedClient { + fingerprint: client_fp, + name: clean_name(&device_name), + }; + let refusal = match window.commit(generation, || store(&client)) { + Ok(true) => None, + // Closed, reopened or expired while this attempt ran, or another device paired. + Ok(false) => Some(HostPairError::Refused(Refusal::PairingClosed)), + Err(e) => Some(HostPairError::Store(e)), + }; + if let Some(err) = refusal { + let _ = write_msg(&mut send, &PairOutcome::Refused(Refusal::PairingClosed)).await; + finish_and_close(&mut send, &conn, "pairing failed").await; + return Err(err); + } + write_msg(&mut send, &PairOutcome::Paired).await?; + finish_and_close(&mut send, &conn, "paired").await; + Ok(client) +} + +/// Contents of the host's pairing QR code: +/// `ezd://pair?a=&fp=&pin=&n=`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairUri { + /// Host address. + pub addr: SocketAddr, + /// Host certificate fingerprint; the client requires it in the TLS handshake. + pub fingerprint: Fingerprint, + /// The current PIN. + pub pin: String, + /// Host name. + pub name: String, +} + +const URI_PREFIX: &str = "ezd://pair?"; + +impl PairUri { + /// Formats the URI. + pub fn to_uri(&self) -> String { + format!( + "{URI_PREFIX}a={}&fp={}&pin={}&n={}", + self.addr, + fingerprint_hex(&self.fingerprint), + self.pin, + percent_encode(&self.name) + ) + } + + /// Parses a URI; unknown parameters are ignored. + pub fn parse(uri: &str) -> Option { + let query = uri.trim().strip_prefix(URI_PREFIX)?; + let (mut addr, mut fp, mut pin, mut name) = (None, None, None, String::new()); + for kv in query.split('&') { + let (k, v) = kv.split_once('=')?; + match k { + "a" => addr = v.parse().ok(), + "fp" => fp = parse_fingerprint(v), + "pin" if is_valid_pin(v) => pin = Some(v.to_string()), + "n" => name = clean_name(&percent_decode(v)?), + _ => {} + } + } + Some(PairUri { + addr: addr?, + fingerprint: fp?, + pin: pin?, + name, + }) + } +} + +fn percent_encode(s: &str) -> String { + let mut out = String::with_capacity(s.len()); + for b in s.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +fn percent_decode(s: &str) -> Option { + let mut out = Vec::with_capacity(s.len()); + let mut bytes = s.bytes(); + while let Some(b) = bytes.next() { + if b == b'%' { + let hi = (bytes.next()? as char).to_digit(16)?; + let lo = (bytes.next()? as char).to_digit(16)?; + out.push((hi * 16 + lo) as u8); + } else { + out.push(b); + } + } + String::from_utf8(out).ok() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::identity::Identity; + use crate::quic::{Congestion, QuicServer, connect}; + use std::sync::Arc; + + #[test] + fn pins_are_six_digits() { + for _ in 0..100 { + assert!(is_valid_pin(&generate_pin())); + } + } + + #[test] + fn uri_round_trip() { + let u = PairUri { + addr: "192.168.0.5:27183".parse().unwrap(), + fingerprint: [0xab; 32], + pin: "004213".into(), + name: "Estación & PC".into(), + }; + let s = u.to_uri(); + assert!(s.starts_with("ezd://pair?a=192.168.0.5:27183&fp=abab")); + assert_eq!(PairUri::parse(&s), Some(u)); + assert_eq!(PairUri::parse("https://example.com"), None); + assert_eq!(PairUri::parse(&s.replace("pin=004213", "pin=42")), None); + } + + #[test] + fn window_counts_attempts_and_expires() { + let w = PairingWindow::default(); + assert_eq!(w.begin(), Err(Refusal::PairingClosed)); + w.open_with("111111".into(), Duration::from_secs(60)); + for _ in 0..MAX_ATTEMPTS { + assert_eq!(w.begin().map(|(pin, _)| pin).as_deref(), Ok("111111")); + } + assert_eq!(w.begin(), Err(Refusal::TooManyAttempts)); + w.open_with("222222".into(), Duration::ZERO); + assert_eq!(w.state(), WindowState::Closed(CloseReason::Expired)); + assert_eq!(w.begin(), Err(Refusal::PairingClosed)); + } + + #[test] + fn last_attempt_can_still_pair() { + let w = PairingWindow::default(); + w.open_with("111111".into(), Duration::from_secs(60)); + let ids: Vec = (0..MAX_ATTEMPTS).map(|_| w.begin().unwrap().1).collect(); + assert!(w.commit(ids[4], || Ok(())).unwrap()); + assert_eq!(w.state(), WindowState::Closed(CloseReason::Paired)); + // One window pairs one device. + assert!(!w.commit(ids[3], || panic!("stored twice")).unwrap()); + } + + #[test] + fn closing_or_reopening_cancels_attempts_in_flight() { + let w = PairingWindow::default(); + w.open_with("111111".into(), Duration::from_secs(60)); + let (_, old) = w.begin().unwrap(); + w.close(); + assert!(!w.commit(old, || panic!("stored after close")).unwrap()); + + w.open_with("222222".into(), Duration::from_secs(60)); + let (_, old) = w.begin().unwrap(); + w.open_with("333333".into(), Duration::from_secs(60)); + assert!(!w.commit(old, || panic!("stored after reopen")).unwrap()); + assert!(w.is_open(), "a stale attempt must not close the new window"); + + w.open_with("444444".into(), Duration::from_millis(1)); + let (_, old) = w.begin().unwrap(); + std::thread::sleep(Duration::from_millis(5)); + assert!(!w.commit(old, || panic!("stored after expiry")).unwrap()); + } + + #[test] + fn failed_store_keeps_the_window_open() { + let w = PairingWindow::default(); + w.open_with("111111".into(), Duration::from_secs(60)); + let (_, id) = w.begin().unwrap(); + assert!( + w.commit(id, || Err(std::io::Error::other("disk full"))) + .is_err() + ); + assert!(w.is_open()); + } + + #[test] + fn debug_hides_the_pin() { + let w = PairingWindow::default(); + w.open_with("987654".into(), Duration::from_secs(60)); + assert!(!format!("{w:?} {:?}", w.state()).contains("987654")); + } + + #[test] + fn names_lose_invisible_and_bidi_characters() { + assert_eq!(clean_name(" tab\u{202E}let\u{200B}\u{7} "), "tablet"); + assert_eq!(clean_name(&"é".repeat(100)).chars().count(), MAX_NAME_CHARS); + } + + struct Fixture { + server: Arc, + addr: SocketAddr, + host: Identity, + client: Identity, + window: Arc, + } + + fn fixture() -> Fixture { + let host = Identity::generate().unwrap(); + let server = + QuicServer::bind("127.0.0.1:0".parse().unwrap(), &host, Congestion::default()).unwrap(); + let addr = server.local_addr().unwrap(); + Fixture { + server: Arc::new(server), + addr, + host, + client: Identity::generate().unwrap(), + window: Arc::new(PairingWindow::default()), + } + } + + /// Host side of one connection: pairs, or accepts a session if the client is `paired`. + async fn host_once( + f: &Fixture, + paired: Option, + ) -> Result, HostPairError> { + let conn = f.server.accept().await.unwrap()?; + let opened = conn.accept_open().await?; + match opened.open { + LinkOpen::Session => { + if opened.peer_fingerprint() == paired && paired.is_some() { + let link = opened.accept_session().await?; + let (tx, mut rx, _t) = link.into_mux(1024); + tx.send(&ezd_proto::Message::Ping(ezd_proto::Ping { + seq: 1, + t0_us: 7, + })) + .unwrap(); + // Waits for the client's Bye so the connection outlives the exchange. + let _ = rx.recv().await; + } else { + opened.refuse(Refusal::NotPaired).await; + } + Ok(None) + } + LinkOpen::Pair { .. } => host_pair(opened, &f.window, "test host", |_| Ok(())) + .await + .map(Some), + } + } + + /// Client side of one pairing connection. + async fn client_pair(f: &Fixture, pin: &str) -> Result { + let conn = connect(f.addr, &f.client, None, Congestion::default()).await?; + pair(conn, pin, "tablet").await + } + + #[tokio::test] + async fn pairing_then_session_without_pin() { + let f = fixture(); + f.window.open_with("123456".into(), Duration::from_secs(60)); + let (host, client) = tokio::join!(host_once(&f, None), client_pair(&f, "123456")); + let host = host.unwrap().unwrap(); + let client = client.unwrap(); + assert_eq!(host.fingerprint, f.client.fingerprint()); + assert_eq!(host.name, "tablet"); + assert_eq!(client.fingerprint, f.host.fingerprint()); + assert_eq!(client.name, "test host"); + assert_eq!(f.window.state(), WindowState::Closed(CloseReason::Paired)); + + // Reconnect with the pinned host certificate: no PIN needed. + let session = async { + let conn = connect(f.addr, &f.client, Some(client.fingerprint), Congestion::Bbr) + .await + .unwrap(); + let link = conn.open_session().await.unwrap(); + assert!(link.has_video_stream()); + let (tx, mut rx, _t) = link.into_mux(1024); + let m = rx.recv().await.unwrap().unwrap(); + tx.send(&ezd_proto::Message::Bye(ezd_proto::Bye { + reason: "done".into(), + })) + .unwrap(); + m + }; + let (h, m) = tokio::join!(host_once(&f, Some(host.fingerprint)), session); + h.unwrap(); + assert_eq!( + m, + ezd_proto::Message::Ping(ezd_proto::Ping { seq: 1, t0_us: 7 }) + ); + } + + #[tokio::test] + async fn wrong_pin_is_refused_and_attempts_run_out() { + let f = fixture(); + f.window.open_with("123456".into(), Duration::from_secs(60)); + for i in 0..MAX_ATTEMPTS { + let (host, client) = tokio::join!(host_once(&f, None), client_pair(&f, "654321")); + assert!( + matches!(client, Err(QuicError::Refused(Refusal::WrongPin))), + "attempt {i}: {client:?}" + ); + assert!(host.is_err()); + } + // Even the right PIN is refused now. + let (_, client) = tokio::join!(host_once(&f, None), client_pair(&f, "123456")); + assert!(matches!( + client, + Err(QuicError::Refused(Refusal::TooManyAttempts)) + )); + } + + #[tokio::test] + async fn closed_window_refuses_pairing() { + let f = fixture(); + let (_, client) = tokio::join!(host_once(&f, None), client_pair(&f, "123456")); + assert!(matches!( + client, + Err(QuicError::Refused(Refusal::PairingClosed)) + )); + } + + #[tokio::test] + async fn unpaired_session_is_refused() { + let f = fixture(); + let session = async { + connect( + f.addr, + &f.client, + Some(f.host.fingerprint()), + Congestion::default(), + ) + .await? + .open_session() + .await + }; + let (_, client) = tokio::join!(host_once(&f, None), session); + assert!(matches!( + client, + Err(QuicError::Refused(Refusal::NotPaired)) + )); + } + + #[tokio::test] + async fn unpinned_connection_cannot_open_a_session() { + let f = fixture(); + let server = f.server.clone(); + tokio::spawn(async move { while server.accept().await.is_some() {} }); + let err = connect(f.addr, &f.client, None, Congestion::default()) + .await + .unwrap() + .open_session() + .await + .unwrap_err(); + assert!(matches!(err, QuicError::Unexpected(_)), "{err:?}"); + } + + #[tokio::test] + async fn pinned_fingerprint_mismatch_fails_the_handshake() { + let f = fixture(); + let server = f.server.clone(); + // The host handshake fails too; just drain it. + tokio::spawn(async move { while server.accept().await.is_some() {} }); + let err = connect(f.addr, &f.client, Some([0; 32]), Congestion::default()) + .await + .unwrap_err(); + assert!(matches!(err, QuicError::FingerprintMismatch), "{err:?}"); + } +} diff --git a/crates/ezd-link/src/quic.rs b/crates/ezd-link/src/quic.rs new file mode 100644 index 0000000..0630903 --- /dev/null +++ b/crates/ezd-link/src/quic.rs @@ -0,0 +1,668 @@ +//! Wi-Fi links over QUIC. +//! +//! Each session (or pairing attempt) is one QUIC connection with mutual TLS 1.3. Both sides use +//! a self-signed [`Identity`]; there is no CA. The client checks the host certificate against +//! the pinned fingerprint (or accepts any during PIN-only pairing, which SPAKE2 then +//! authenticates); the host accepts any client certificate in the handshake and decides by its +//! fingerprint afterwards. TLS still verifies that each peer holds its certificate's key. +//! +//! Streams (see `docs/protocol.md`): +//! * control, bidirectional, opened by the client: [`LinkOpen`] / [`LinkReply`], then the framed +//! control, input and cursor traffic; +//! * video, unidirectional, opened by the host after [`LinkReply::Accepted`]: one +//! [`VIDEO_STREAM_TAG`] byte, then framed video. +//! +//! The control stream has the higher send priority, and since the streams are independent a +//! lost video packet never delays cursor or input traffic. + +use crate::identity::{Identity, fingerprint_of}; +use crate::link::Link; +use ezd_proto::ProtoError; +use ezd_proto::pair::{ + self, ALPN, Fingerprint, LinkOpen, LinkReply, MAX_PREAMBLE_LEN, Refusal, VIDEO_STREAM_TAG, +}; +use quinn::{Connection, Endpoint, RecvStream, SendStream, VarInt}; +use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; +use rustls::crypto::CryptoProvider; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName, UnixTime}; +use rustls::server::danger::{ClientCertVerified, ClientCertVerifier}; +use rustls::{DigitallySignedStruct, DistinguishedName, SignatureScheme}; +use serde::Serialize; +use serde::de::DeserializeOwned; +use std::io; +use std::net::SocketAddr; +use std::pin::Pin; +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::task::{Context, Poll}; +use std::time::Duration; +use tokio::io::{AsyncRead, ReadBuf}; + +/// TLS server name. Certificates are checked by fingerprint, so it is only a placeholder. +const SERVER_NAME: &str = "ezdisplay"; +/// Time allowed for each preamble step (open, reply, video stream). +pub const PREAMBLE_TIMEOUT: Duration = Duration::from_secs(10); +/// Application close code for a normal end or a refusal. +const CLOSE_OK: u32 = 0; +/// Send priority of the control stream (higher is served first); video uses 0. +const CONTROL_PRIORITY: i32 = 1; + +/// Congestion controller of a Wi-Fi link. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub enum Congestion { + /// CUBIC (quinn's default). + #[default] + Cubic, + /// BBR (experimental in quinn); can keep queues shorter on a busy Wi-Fi channel. + Bbr, +} + +/// Errors of a Wi-Fi link. +#[derive(Debug, thiserror::Error)] +pub enum QuicError { + /// The connection could not be started (bad address, endpoint stopped). + #[error("cannot connect: {0}")] + Connect(#[from] quinn::ConnectError), + /// The connection failed or was closed. + #[error("connection failed: {0}")] + Connection(#[from] quinn::ConnectionError), + /// The host certificate is not the expected (paired or scanned) one. + #[error("the host certificate does not match the paired one")] + FingerprintMismatch, + /// The host refused the session or the pairing attempt. + #[error("refused by the host: {0:?}")] + Refused(Refusal), + /// The PIN is not 6 digits. + #[error("the PIN must be 6 digits")] + InvalidPin, + /// A preamble message was not the expected one. + #[error("unexpected message from the peer: {0}")] + Unexpected(&'static str), + /// A preamble step took longer than [`PREAMBLE_TIMEOUT`]. + #[error("timed out")] + Timeout, + /// TLS or endpoint configuration failed. + #[error("TLS setup failed: {0}")] + Tls(String), + /// Stream I/O failure. + #[error("io error: {0}")] + Io(#[from] io::Error), + /// Malformed preamble. + #[error("protocol error: {0}")] + Proto(#[from] ProtoError), +} + +impl From for QuicError { + fn from(e: quinn::WriteError) -> Self { + QuicError::Io(e.into()) + } +} + +impl From for QuicError { + fn from(e: quinn::ReadExactError) -> Self { + QuicError::Io(match e { + quinn::ReadExactError::FinishedEarly(_) => io::ErrorKind::UnexpectedEof.into(), + quinn::ReadExactError::ReadError(e) => e.into(), + }) + } +} + +fn tls_err(e: impl std::fmt::Display) -> QuicError { + QuicError::Tls(e.to_string()) +} + +fn provider() -> Arc { + Arc::new(rustls::crypto::ring::default_provider()) +} + +fn cert_and_key(id: &Identity) -> (Vec>, PrivateKeyDer<'static>) { + ( + vec![CertificateDer::from(id.cert_der().to_vec())], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(id.key_der().to_vec())), + ) +} + +/// Most QUIC connections the host keeps at once, handshakes included (see +/// [`QuicServer::open_connections`]). +pub const MAX_HOST_CONNECTIONS: usize = 8; + +/// Which side a transport configuration is for. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Side { + Host, + Client, +} + +/// Transport settings for a low-latency LAN link. +/// +/// Only the host receives from peers it has not authenticated yet (it accepts any client +/// certificate), so its receive windows are small: it only reads the preamble and input, never +/// video. The client receives video and needs room for a large keyframe in flight. Each side +/// allows exactly the streams the other opens: one bidirectional stream from the client, one +/// unidirectional stream from the host. +fn transport(cc: Congestion, side: Side) -> quinn::TransportConfig { + let mut t = quinn::TransportConfig::default(); + t.keep_alive_interval(Some(Duration::from_secs(1))) + .max_idle_timeout(quinn::IdleTimeout::try_from(Duration::from_secs(5)).ok()) + // A LAN round trip is a few ms; quinn's 333 ms default slows the first loss recovery. + .initial_rtt(Duration::from_millis(10)) + .send_window(16 << 20) + .datagram_receive_buffer_size(None); + match side { + Side::Host => t + .stream_receive_window(VarInt::from_u32(256 << 10)) + .receive_window(VarInt::from_u32(256 << 10)) + .max_concurrent_bidi_streams(VarInt::from_u32(1)) + .max_concurrent_uni_streams(VarInt::from_u32(0)), + Side::Client => t + .stream_receive_window(VarInt::from_u32(8 << 20)) + .receive_window(VarInt::from_u32(16 << 20)) + .max_concurrent_bidi_streams(VarInt::from_u32(0)) + .max_concurrent_uni_streams(VarInt::from_u32(1)), + }; + if cc == Congestion::Bbr { + t.congestion_controller_factory(Arc::new(quinn::congestion::BbrConfig::default())); + } + t +} + +/// Accepts the host certificate if it matches `expected` (any when `None`). +#[derive(Debug)] +struct ServerCheck { + expected: Option, + mismatch: Arc, + provider: Arc, +} + +impl ServerCertVerifier for ServerCheck { + fn verify_server_cert( + &self, + end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _server_name: &ServerName<'_>, + _ocsp_response: &[u8], + _now: UnixTime, + ) -> Result { + if let Some(fp) = self.expected + && fingerprint_of(end_entity) != fp + { + self.mismatch.store(true, Ordering::Relaxed); + return Err(rustls::Error::InvalidCertificate( + rustls::CertificateError::ApplicationVerificationFailure, + )); + } + Ok(ServerCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn supported_verify_schemes(&self) -> Vec { + self.provider + .signature_verification_algorithms + .supported_schemes() + } +} + +/// Requires a client certificate but accepts any; the host checks its fingerprint after the +/// handshake ([`Opened::peer_fingerprint`]). +#[derive(Debug)] +struct AnyClient { + provider: Arc, +} + +impl ClientCertVerifier for AnyClient { + fn root_hint_subjects(&self) -> &[DistinguishedName] { + &[] + } + + fn verify_client_cert( + &self, + _end_entity: &CertificateDer<'_>, + _intermediates: &[CertificateDer<'_>], + _now: UnixTime, + ) -> Result { + Ok(ClientCertVerified::assertion()) + } + + fn verify_tls12_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls12_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn verify_tls13_signature( + &self, + message: &[u8], + cert: &CertificateDer<'_>, + dss: &DigitallySignedStruct, + ) -> Result { + rustls::crypto::verify_tls13_signature( + message, + cert, + dss, + &self.provider.signature_verification_algorithms, + ) + } + + fn supported_verify_schemes(&self) -> Vec { + self.provider + .signature_verification_algorithms + .supported_schemes() + } +} + +/// An established QUIC connection plus what is needed to keep it alive. +#[derive(Debug, Clone)] +pub struct QuicConn { + conn: Connection, + /// The client's own endpoint; the host's lives in [`QuicServer`]. + _endpoint: Option, + local_fp: Fingerprint, + /// Client: the host certificate was checked against a pinned fingerprint. + pinned: bool, +} + +impl QuicConn { + /// Fingerprint of the peer certificate. + pub fn peer_fingerprint(&self) -> Option { + let certs = self + .conn + .peer_identity()? + .downcast::>>() + .ok()?; + certs.first().map(|c| fingerprint_of(c)) + } + + /// Fingerprint of our own certificate. + pub fn local_fingerprint(&self) -> Fingerprint { + self.local_fp + } + + /// Address of the peer. + pub fn remote_address(&self) -> SocketAddr { + self.conn.remote_address() + } + + /// Closes the connection at once. + pub fn close(&self, reason: &str) { + self.conn.close(CLOSE_OK.into(), reason.as_bytes()); + } + + /// 32 bytes of TLS keying material for `label` (RFC 5705), unique to this connection. + pub(crate) fn export(&self, label: &[u8]) -> Result<[u8; 32], QuicError> { + let mut out = [0u8; 32]; + self.conn + .export_keying_material(&mut out, label, b"") + .map_err(|_| QuicError::Tls("keying material export failed".into()))?; + Ok(out) + } + + pub(crate) async fn open_bi(&self) -> Result<(SendStream, RecvStream), QuicError> { + let (send, recv) = self.conn.open_bi().await?; + let _ = send.set_priority(CONTROL_PRIORITY); + Ok((send, recv)) + } + + /// Client: asks for a session on a paired host and returns the two-stream link. + /// The connection must come from [`connect`] with a pinned fingerprint: an unpinned one + /// is only authenticated by [`crate::pair::pair`]. + pub async fn open_session(self) -> Result { + if !self.pinned { + return Err(QuicError::Unexpected( + "session on a connection without a pinned host", + )); + } + let (mut send, mut recv) = self.open_bi().await?; + write_msg(&mut send, &LinkOpen::Session).await?; + match read_msg::(&mut recv).await? { + LinkReply::Accepted => {} + LinkReply::Refused(r) => return Err(QuicError::Refused(r)), + LinkReply::PairChallenge { .. } => { + return Err(QuicError::Unexpected("pairing reply to a session request")); + } + } + let mut video = tokio::time::timeout(PREAMBLE_TIMEOUT, self.conn.accept_uni()) + .await + .map_err(|_| QuicError::Timeout)??; + let mut tag = [0u8; 1]; + tokio::time::timeout(PREAMBLE_TIMEOUT, video.read_exact(&mut tag)) + .await + .map_err(|_| QuicError::Timeout)??; + if tag[0] != VIDEO_STREAM_TAG { + return Err(QuicError::Unexpected("video stream tag")); + } + let peer = format!("quic:{}", self.conn.remote_address()); + let keep = Arc::new(Lingering(self)); + Ok( + Link::new(Box::new(Keep::new(recv, &keep)), Box::new(send), peer).with_video( + Box::new(Keep::new(video, &keep)), + Box::new(tokio::io::sink()), + ), + ) + } + + /// Host: reads the client's [`LinkOpen`] on the control stream. + pub async fn accept_open(self) -> Result { + let (send, mut recv) = tokio::time::timeout(PREAMBLE_TIMEOUT, self.conn.accept_bi()) + .await + .map_err(|_| QuicError::Timeout)??; + let _ = send.set_priority(CONTROL_PRIORITY); + let open = read_msg::(&mut recv).await?; + Ok(Opened { + conn: self, + open, + send, + recv, + }) + } +} + +/// Host side of a connection whose [`LinkOpen`] was read. +#[derive(Debug)] +pub struct Opened { + pub(crate) conn: QuicConn, + /// What the client asked for. + pub open: LinkOpen, + pub(crate) send: SendStream, + pub(crate) recv: RecvStream, +} + +impl Opened { + /// Fingerprint of the client certificate. + pub fn peer_fingerprint(&self) -> Option { + self.conn.peer_fingerprint() + } + + /// Address of the client. + pub fn remote_address(&self) -> SocketAddr { + self.conn.remote_address() + } + + /// Accepts a session: answers [`LinkReply::Accepted`], opens the video stream and returns + /// the two-stream link. + pub async fn accept_session(mut self) -> Result { + write_msg(&mut self.send, &LinkReply::Accepted).await?; + let mut video = tokio::time::timeout(PREAMBLE_TIMEOUT, self.conn.conn.open_uni()) + .await + .map_err(|_| QuicError::Timeout)??; + let _ = video.set_priority(0); + video.write_all(&[VIDEO_STREAM_TAG]).await?; + let peer = format!("quic:{}", self.conn.remote_address()); + let keep = Arc::new(Lingering(self.conn)); + Ok(Link::new( + Box::new(Keep::new(self.recv, &keep)), + Box::new(self.send), + peer, + ) + .with_video(Box::new(tokio::io::empty()), Box::new(video))) + } + + /// Refuses the request and closes the connection once the answer is delivered (or after + /// a short wait). + pub async fn refuse(mut self, why: Refusal) { + let _ = write_msg(&mut self.send, &LinkReply::Refused(why)).await; + finish_and_close(&mut self.send, &self.conn, "refused").await; + } +} + +/// Finishes `send`, waits briefly for the peer to read it, then closes the connection. +pub(crate) async fn finish_and_close(send: &mut SendStream, conn: &QuicConn, reason: &str) { + let _ = send.finish(); + let _ = tokio::time::timeout(Duration::from_secs(1), send.stopped()).await; + conn.close(reason); +} + +/// Host endpoint listening for Wi-Fi clients. +#[derive(Debug)] +pub struct QuicServer { + endpoint: Endpoint, + local_fp: Fingerprint, +} + +impl QuicServer { + /// Binds a UDP socket on `addr` with the host `identity`. + pub fn bind(addr: SocketAddr, identity: &Identity, cc: Congestion) -> Result { + let p = provider(); + let (certs, key) = cert_and_key(identity); + let mut tls = rustls::ServerConfig::builder_with_provider(p.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(tls_err)? + .with_client_cert_verifier(Arc::new(AnyClient { provider: p })) + .with_single_cert(certs, key) + .map_err(tls_err)?; + tls.alpn_protocols = vec![ALPN.to_vec()]; + let crypto = quinn::crypto::rustls::QuicServerConfig::try_from(tls).map_err(tls_err)?; + let mut cfg = quinn::ServerConfig::with_crypto(Arc::new(crypto)); + cfg.transport_config(Arc::new(transport(cc, Side::Host))); + Ok(QuicServer { + endpoint: Endpoint::server(cfg, addr)?, + local_fp: identity.fingerprint(), + }) + } + + /// The bound address. + pub fn local_addr(&self) -> io::Result { + self.endpoint.local_addr() + } + + /// Waits for the next incoming connection without completing its handshake, so a slow + /// client never delays the next one: complete it with [`QuicIncoming::handshake`] in its + /// own task. `None` once the endpoint is closed. + pub async fn accept_incoming(&self) -> Option { + let incoming = self.endpoint.accept().await?; + Some(QuicIncoming { + incoming, + local_fp: self.local_fp, + }) + } + + /// Waits for the next client handshake; `None` once the endpoint is closed. A failed + /// handshake is returned as an error and the server keeps accepting. + pub async fn accept(&self) -> Option> { + Some(self.accept_incoming().await?.handshake().await) + } + + /// Connections currently open on the endpoint, handshakes included. Refuse new ones + /// ([`QuicIncoming::refuse`]) above [`MAX_HOST_CONNECTIONS`]. + pub fn open_connections(&self) -> usize { + self.endpoint.open_connections() + } + + /// Waits up to `limit` for every connection to finish (sessions that just ended deliver + /// their last messages), for a clean shutdown before [`close`](Self::close). + pub async fn wait_idle(&self, limit: Duration) { + let _ = tokio::time::timeout(limit, self.endpoint.wait_idle()).await; + } + + /// Stops accepting and closes every connection. + pub fn close(&self) { + self.endpoint.close(CLOSE_OK.into(), b"host stopped"); + } +} + +/// A connection attempt that reached the host and has not finished its handshake. +/// Dropping it refuses the attempt. +#[derive(Debug)] +pub struct QuicIncoming { + incoming: quinn::Incoming, + local_fp: Fingerprint, +} + +impl QuicIncoming { + /// Address of the peer (not yet validated). + pub fn remote_address(&self) -> SocketAddr { + self.incoming.remote_address() + } + + /// Completes the handshake within [`PREAMBLE_TIMEOUT`]. + pub async fn handshake(self) -> Result { + let conn = tokio::time::timeout(PREAMBLE_TIMEOUT, self.incoming) + .await + .map_err(|_| QuicError::Timeout)??; + Ok(QuicConn { + conn, + _endpoint: None, + local_fp: self.local_fp, + pinned: false, + }) + } + + /// Refuses the attempt (host busy or over its connection limit). + pub fn refuse(self) { + self.incoming.refuse(); + } +} + +/// Client: connects to a host. With `expected` the host certificate must have that +/// fingerprint ([`QuicError::FingerprintMismatch`] otherwise); without it any certificate is +/// accepted, which is only safe for [`crate::pair::pair`]; [`QuicConn::open_session`] refuses +/// such a connection. +pub async fn connect( + addr: SocketAddr, + identity: &Identity, + expected: Option, + cc: Congestion, +) -> Result { + let p = provider(); + let mismatch = Arc::new(AtomicBool::new(false)); + let (certs, key) = cert_and_key(identity); + let mut tls = rustls::ClientConfig::builder_with_provider(p.clone()) + .with_protocol_versions(&[&rustls::version::TLS13]) + .map_err(tls_err)? + .dangerous() + .with_custom_certificate_verifier(Arc::new(ServerCheck { + expected, + mismatch: mismatch.clone(), + provider: p, + })) + .with_client_auth_cert(certs, key) + .map_err(tls_err)?; + tls.alpn_protocols = vec![ALPN.to_vec()]; + let crypto = quinn::crypto::rustls::QuicClientConfig::try_from(tls).map_err(tls_err)?; + let mut cfg = quinn::ClientConfig::new(Arc::new(crypto)); + cfg.transport_config(Arc::new(transport(cc, Side::Client))); + let bind: SocketAddr = if addr.is_ipv6() { + (std::net::Ipv6Addr::UNSPECIFIED, 0).into() + } else { + (std::net::Ipv4Addr::UNSPECIFIED, 0).into() + }; + let endpoint = Endpoint::client(bind)?; + let conn = match endpoint.connect_with(cfg, addr, SERVER_NAME)?.await { + Ok(c) => c, + Err(_) if mismatch.load(Ordering::Relaxed) => return Err(QuicError::FingerprintMismatch), + Err(e) => return Err(e.into()), + }; + Ok(QuicConn { + conn, + _endpoint: Some(endpoint), + local_fp: identity.fingerprint(), + pinned: expected.is_some(), + }) +} + +/// Writes one length-prefixed preamble message. +pub(crate) async fn write_msg(w: &mut SendStream, msg: &T) -> Result<(), QuicError> { + w.write_all(&pair::encode_preamble(msg)?).await?; + Ok(()) +} + +/// Reads one length-prefixed preamble message within [`PREAMBLE_TIMEOUT`]. +pub(crate) async fn read_msg(r: &mut RecvStream) -> Result { + let read = async { + let mut len = [0u8; 2]; + r.read_exact(&mut len).await?; + let len = u16::from_le_bytes(len) as usize; + if len > MAX_PREAMBLE_LEN { + return Err(ProtoError::MessageTooLarge.into()); + } + let mut body = vec![0; len]; + r.read_exact(&mut body).await?; + Ok(pair::decode_preamble(&body)?) + }; + tokio::time::timeout(PREAMBLE_TIMEOUT, read) + .await + .map_err(|_| QuicError::Timeout)? +} + +/// Most time a finished session's connection stays open to deliver what is still in flight. +const LINGER: Duration = Duration::from_secs(1); + +/// Owner of a session's connection. Quinn closes a connection as soon as its last handle is +/// dropped and discards unsent stream data, such as a final `Bye`. When the session drops this, +/// a task keeps the connection (and the client endpoint) open until the peer closes it or +/// [`LINGER`] passes. +struct Lingering(QuicConn); + +impl Drop for Lingering { + fn drop(&mut self) { + let conn = self.0.clone(); + match tokio::runtime::Handle::try_current() { + Ok(rt) => { + rt.spawn(async move { + let _ = tokio::time::timeout(LINGER, conn.conn.closed()).await; + conn.close("session ended"); + }); + } + Err(_) => conn.close("session ended"), + } + } +} + +/// A read half that keeps the connection (and the client endpoint) alive while in use. +struct Keep { + inner: R, + _conn: Arc, +} + +impl Keep { + fn new(inner: R, conn: &Arc) -> Self { + Keep { + inner, + _conn: conn.clone(), + } + } +} + +impl AsyncRead for Keep { + fn poll_read( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + buf: &mut ReadBuf<'_>, + ) -> Poll> { + Pin::new(&mut self.inner).poll_read(cx, buf) + } +} diff --git a/crates/ezd-proto/src/lib.rs b/crates/ezd-proto/src/lib.rs index 0a838d2..1f13ffd 100644 --- a/crates/ezd-proto/src/lib.rs +++ b/crates/ezd-proto/src/lib.rs @@ -11,11 +11,13 @@ //! * [`negotiate`]: [`negotiate()`] turns client + host capabilities into a //! [`StreamConfig`]. //! * [`clock`]: NTP-style [`ClockSync`]. +//! * [`pair`]: Wi-Fi link preamble and PIN pairing messages. pub mod clock; pub mod frame; pub mod msg; pub mod negotiate; +pub mod pair; pub use clock::{ClockSync, Sample}; pub use frame::{ @@ -68,6 +70,9 @@ pub enum ProtoError { /// The peer's major version. peer: u16, }, + /// A Wi-Fi link preamble message could not be decoded. + #[error("malformed link preamble: {0}")] + Preamble(postcard::Error), /// No codec is supported by both the client decoders and the host encoders. #[error("no codec supported by both client decoders and host encoders")] NoCommonCodec, diff --git a/crates/ezd-proto/src/pair.rs b/crates/ezd-proto/src/pair.rs new file mode 100644 index 0000000..bdf2faa --- /dev/null +++ b/crates/ezd-proto/src/pair.rs @@ -0,0 +1,153 @@ +//! Wi-Fi link preamble and PIN pairing messages. +//! +//! A Wi-Fi link is a QUIC connection with mutual TLS (self-signed certificates, pinned by +//! fingerprint after pairing). The client opens the control stream (bidirectional) and sends a +//! [`LinkOpen`]; the host answers with a [`LinkReply`]. For a session the host then opens the +//! video stream (unidirectional), starting with [`VIDEO_STREAM_TAG`], and both sides run the +//! normal framed protocol. Pairing is a SPAKE2 exchange keyed by a 6-digit PIN, see +//! `docs/protocol.md`. +//! +//! Preamble messages are postcard encoded with a little-endian `u16` length prefix +//! ([`encode_preamble`] / [`decode_preamble`]); they never exceed [`MAX_PREAMBLE_LEN`]. + +use serde::{Deserialize, Serialize, de::DeserializeOwned}; + +/// ALPN protocol id of a Wi-Fi link. +pub const ALPN: &[u8] = b"ezd/0"; +/// First byte of the host's video stream. +pub const VIDEO_STREAM_TAG: u8 = b'V'; +/// Largest preamble message payload. +pub const MAX_PREAMBLE_LEN: usize = 1024; +/// Number of digits in a pairing PIN. +pub const PIN_DIGITS: usize = 6; + +/// SHA-256 of a peer's certificate (DER). +pub type Fingerprint = [u8; 32]; + +/// First message of the client on the control stream. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum LinkOpen { + /// Start a session; the client certificate must already be paired. + Session, + /// Pair this client using the host's current PIN. + Pair { + /// Human readable client name. + device_name: String, + /// SPAKE2 message of the client (side A). + #[serde(with = "serde_bytes")] + spake: Vec, + }, +} + +/// Why the host refused a [`LinkOpen`] or a pairing attempt. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum Refusal { + /// The client certificate is not paired with this host. + NotPaired, + /// No pairing window is open on the host. + PairingClosed, + /// The pairing window closed after too many failed attempts. + TooManyAttempts, + /// The PIN did not match. + WrongPin, + /// Another client is streaming. + Busy, +} + +/// Host answer to a [`LinkOpen`]. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub enum LinkReply { + /// Session accepted; the video stream follows. + Accepted, + /// Refused; the host closes the connection. + Refused(Refusal), + /// Pairing answer of the host. + PairChallenge { + /// Human readable host name. + host_name: String, + /// SPAKE2 message of the host (side B). + #[serde(with = "serde_bytes")] + spake: Vec, + /// Host key confirmation (HMAC over the transcript). + confirm: [u8; 32], + }, +} + +/// Client key confirmation, sent after checking the host's. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PairConfirm { + /// Client key confirmation (HMAC over the transcript). + pub confirm: [u8; 32], +} + +/// Final host message of a pairing exchange. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum PairOutcome { + /// Both sides pinned each other's certificate. + Paired, + /// Refused; nothing was stored. + Refused(Refusal), +} + +/// Encodes a preamble message with its length prefix. +pub fn encode_preamble(msg: &T) -> crate::Result> { + let body = postcard::to_allocvec(msg).map_err(crate::ProtoError::Encode)?; + if body.len() > MAX_PREAMBLE_LEN { + return Err(crate::ProtoError::MessageTooLarge); + } + let mut out = Vec::with_capacity(2 + body.len()); + out.extend_from_slice(&(body.len() as u16).to_le_bytes()); + out.extend_from_slice(&body); + Ok(out) +} + +/// Decodes a preamble payload (without its length prefix). +pub fn decode_preamble(body: &[u8]) -> crate::Result { + postcard::from_bytes(body).map_err(crate::ProtoError::Preamble) +} + +/// True for a well-formed PIN: exactly [`PIN_DIGITS`] ASCII digits. +pub fn is_valid_pin(pin: &str) -> bool { + pin.len() == PIN_DIGITS && pin.bytes().all(|b| b.is_ascii_digit()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn preamble_round_trip() { + let msgs = [ + LinkReply::Accepted, + LinkReply::Refused(Refusal::Busy), + LinkReply::PairChallenge { + host_name: "pc".into(), + spake: vec![7; 33], + confirm: [9; 32], + }, + ]; + for m in msgs { + let enc = encode_preamble(&m).unwrap(); + let len = u16::from_le_bytes([enc[0], enc[1]]) as usize; + assert_eq!(len, enc.len() - 2); + assert_eq!(decode_preamble::(&enc[2..]).unwrap(), m); + } + } + + #[test] + fn oversized_preamble_is_rejected() { + let m = LinkOpen::Pair { + device_name: "x".repeat(MAX_PREAMBLE_LEN), + spake: vec![], + }; + assert!(encode_preamble(&m).is_err()); + } + + #[test] + fn pin_format() { + assert!(is_valid_pin("012345")); + assert!(!is_valid_pin("12345")); + assert!(!is_valid_pin("1234567")); + assert!(!is_valid_pin("12a456")); + } +} From 079e2ad003f7db241db4e7001ea53aea4cd73b45 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sat, 24 Oct 2026 21:57:34 -0300 Subject: [PATCH 02/14] Serve paired tablets over Wi-Fi in the host and fake client Add `ezd-host run --wifi [ADDR]` to accept tablets over the QUIC link, and `--pair` to open a pairing window. Pairing shows a QR code and a PIN in the terminal. `ezd-host paired list` and `ezd-host paired forget` manage the paired tablets, which are stored in the config directory. The host advertises itself over mDNS as `_ezdisplay._udp`. Only one session runs at a time across USB and Wi-Fi. Pairing events are reported through the live status. The fake client gains `--wifi`, `--pin`, `--uri` and `--state-dir` for testing the Wi-Fi path. Its strings are added in all six locales. The `wifi` feature is on by default. --- crates/ezd-fake-client/Cargo.toml | 8 + .../i18n/de/ezd-fake-client.ftl | 18 + .../i18n/en/ezd-fake-client.ftl | 18 + .../i18n/es/ezd-fake-client.ftl | 18 + .../i18n/fr/ezd-fake-client.ftl | 18 + .../i18n/it/ezd-fake-client.ftl | 18 + .../i18n/pt/ezd-fake-client.ftl | 18 + crates/ezd-fake-client/src/lib.rs | 2 + crates/ezd-fake-client/src/main.rs | 104 ++- crates/ezd-fake-client/src/wifi.rs | 184 +++++ crates/ezd-fake-client/tests/wifi.rs | 219 +++++ crates/ezd-host-service/Cargo.toml | 8 +- crates/ezd-host-service/src/config.rs | 78 ++ crates/ezd-host-service/src/error.rs | 3 + crates/ezd-host-service/src/lib.rs | 15 +- crates/ezd-host-service/src/mdns.rs | 95 +++ crates/ezd-host-service/src/service.rs | 197 ++++- crates/ezd-host-service/src/status.rs | 85 ++ crates/ezd-host-service/src/store.rs | 346 ++++++++ crates/ezd-host-service/src/wifi.rs | 763 ++++++++++++++++++ crates/ezd-host/Cargo.toml | 5 +- crates/ezd-host/i18n/de/ezd-host.ftl | 30 + crates/ezd-host/i18n/en/ezd-host.ftl | 30 + crates/ezd-host/i18n/es/ezd-host.ftl | 30 + crates/ezd-host/i18n/fr/ezd-host.ftl | 30 + crates/ezd-host/i18n/it/ezd-host.ftl | 30 + crates/ezd-host/i18n/pt/ezd-host.ftl | 30 + crates/ezd-host/src/main.rs | 13 + crates/ezd-host/src/run.rs | 102 ++- crates/ezd-host/src/wifi.rs | 295 +++++++ 30 files changed, 2748 insertions(+), 62 deletions(-) create mode 100644 crates/ezd-fake-client/src/wifi.rs create mode 100644 crates/ezd-fake-client/tests/wifi.rs create mode 100644 crates/ezd-host-service/src/mdns.rs create mode 100644 crates/ezd-host-service/src/store.rs create mode 100644 crates/ezd-host-service/src/wifi.rs create mode 100644 crates/ezd-host/src/wifi.rs diff --git a/crates/ezd-fake-client/Cargo.toml b/crates/ezd-fake-client/Cargo.toml index 10b73a8..be43437 100644 --- a/crates/ezd-fake-client/Cargo.toml +++ b/crates/ezd-fake-client/Cargo.toml @@ -15,7 +15,13 @@ name = "ezd_fake_client" name = "ezd-fake-client" path = "src/main.rs" +[features] +default = ["wifi"] +# Wi-Fi (QUIC) transport: `--wifi`, `--pin`, `--uri`. +wifi = ["ezd-link/quic", "dep:dirs", "dep:serde", "dep:serde_json"] + [dependencies] +dirs = { workspace = true, optional = true } anyhow.workspace = true clap.workspace = true ezd-client-core = { path = "../ezd-client-core" } @@ -26,6 +32,8 @@ ezd-proto.workspace = true i18n-embed.workspace = true i18n-embed-fl.workspace = true rust-embed.workspace = true +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } thiserror.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/crates/ezd-fake-client/i18n/de/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/de/ezd-fake-client.ftl index 8eb9440..cd9118d 100644 --- a/crates/ezd-fake-client/i18n/de/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/de/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = Uhr: Versatz { $offset } us, RTT { $rtt } us summary-decode = Dekodierung: p50 { $p50 } us, p95 { $p95 } us summary-e2e = Ende-zu-Ende (Host-Aufnahme -> dekodiert): p50 { $p50 } us, p95 { $p95 } us summary-input = Eingabe: Status { $status }, Optionen { $options }, gesendet { $sent } + +arg-wifi = Verbindet sich per WLAN (QUIC) mit dem Host unter ADDR statt per TCP. Ein bereits gekoppelter Host braucht nichts weiter; beim ersten Mal gib `--pin` an (oder nutze `--uri`). +arg-pin = Koppelt zuerst mit dem Host über die 6-stellige PIN, die er anzeigt. +arg-uri = Kopplungs-URI aus dem QR-Code des Hosts (`ezd://pair?...`): liefert die Adresse, legt den Fingerabdruck des Hosts fest und enthält die PIN. +arg-state-dir = Ordner für die Identität dieses Clients und den gekoppelten Host (Standard: `ezdisplay-fake-client` im Konfigurationsordner). +paired-with = Mit { $host } gekoppelt ({ $fingerprint }) +err-pin-needs-wifi = --pin erfordert --wifi ADDR oder --uri +err-uri-invalid = die Kopplungs-URI ist ungültig +err-no-state-dir = kein Ordner für den Client-Zustand gefunden; gib --state-dir an +err-wifi-no-address = Hostadresse fehlt: gib --wifi ADDR oder --uri an +err-wifi-not-paired = noch kein Host gekoppelt: gib --pin PIN (oder --uri) zum Koppeln an +err-refused-not-paired = der Host kennt diesen Client nicht: koppele erneut mit --pin +err-refused-closed = der Host nimmt keine neuen Kopplungen an: öffne zuerst sein Kopplungsfenster +err-refused-attempts = der Host hat die Kopplung nach zu vielen falschen PINs geschlossen +err-refused-wrong-pin = falsche PIN +err-refused-busy = der Host ist mit einem anderen Client beschäftigt +err-wifi-fingerprint = das Zertifikat des Hosts passt nicht zum gekoppelten +err-wifi = WLAN: { $reason } diff --git a/crates/ezd-fake-client/i18n/en/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/en/ezd-fake-client.ftl index f83de47..b79ba16 100644 --- a/crates/ezd-fake-client/i18n/en/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/en/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = clock: offset { $offset } us, rtt { $rtt } us summary-decode = decode: p50 { $p50 } us, p95 { $p95 } us summary-e2e = e2e (host capture -> decoded): p50 { $p50 } us, p95 { $p95 } us summary-input = input: status { $status }, options { $options }, sent { $sent } + +arg-wifi = Connect to the host over Wi-Fi (QUIC) at ADDR instead of TCP. A paired host needs nothing else; the first time add `--pin` (or use `--uri`). +arg-pin = Pair with the host first, using the 6-digit PIN it shows. +arg-uri = Pairing URI from the host's QR code (`ezd://pair?...`): gives the address, pins the host fingerprint and carries the PIN. +arg-state-dir = Folder for this client's identity and the paired host (default: `ezdisplay-fake-client` in the config folder). +paired-with = Paired with { $host } ({ $fingerprint }) +err-pin-needs-wifi = --pin needs --wifi ADDR or --uri +err-uri-invalid = the pairing URI is not valid +err-no-state-dir = cannot find a folder for the client state; pass --state-dir +err-wifi-no-address = no host address: pass --wifi ADDR or --uri +err-wifi-not-paired = not paired with a host yet: pass --pin PIN (or --uri) to pair +err-refused-not-paired = the host does not know this client: pair again with --pin +err-refused-closed = the host is not accepting new pairings: open its pairing window first +err-refused-attempts = the host closed pairing after too many wrong PINs +err-refused-wrong-pin = wrong PIN +err-refused-busy = the host is busy with another client +err-wifi-fingerprint = the host certificate does not match the paired one +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-fake-client/i18n/es/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/es/ezd-fake-client.ftl index 4638a7d..01fc992 100644 --- a/crates/ezd-fake-client/i18n/es/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/es/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = reloj: desfase { $offset } us, rtt { $rtt } us summary-decode = decodificación: p50 { $p50 } us, p95 { $p95 } us summary-e2e = extremo a extremo (captura del host -> decodificado): p50 { $p50 } us, p95 { $p95 } us summary-input = entrada: estado { $status }, opciones { $options }, enviados { $sent } + +arg-wifi = Se conecta al host por Wi-Fi (QUIC) en ADDR en lugar de TCP. Un host ya vinculado no necesita nada más; la primera vez agregá `--pin` (o usá `--uri`). +arg-pin = Se vincula primero con el host usando el PIN de 6 dígitos que muestra. +arg-uri = URI de vinculación del código QR del host (`ezd://pair?...`): da la dirección, fija la huella del host y trae el PIN. +arg-state-dir = Carpeta para la identidad de este cliente y el host vinculado (por defecto: `ezdisplay-fake-client` en la carpeta de configuración). +paired-with = Vinculado con { $host } ({ $fingerprint }) +err-pin-needs-wifi = --pin requiere --wifi ADDR o --uri +err-uri-invalid = la URI de vinculación no es válida +err-no-state-dir = no se encontró una carpeta para el estado del cliente; indicá --state-dir +err-wifi-no-address = falta la dirección del host: indicá --wifi ADDR o --uri +err-wifi-not-paired = todavía no hay un host vinculado: indicá --pin PIN (o --uri) para vincular +err-refused-not-paired = el host no conoce a este cliente: vinculá de nuevo con --pin +err-refused-closed = el host no acepta vinculaciones nuevas: abrí primero su ventana de vinculación +err-refused-attempts = el host cerró la vinculación por demasiados PIN incorrectos +err-refused-wrong-pin = PIN incorrecto +err-refused-busy = el host está ocupado con otro cliente +err-wifi-fingerprint = el certificado del host no coincide con el vinculado +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-fake-client/i18n/fr/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/fr/ezd-fake-client.ftl index 69d17fb..52aee3a 100644 --- a/crates/ezd-fake-client/i18n/fr/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/fr/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = horloge : décalage { $offset } us, rtt { $rtt } us summary-decode = décodage : p50 { $p50 } us, p95 { $p95 } us summary-e2e = de bout en bout (capture hôte -> décodé) : p50 { $p50 } us, p95 { $p95 } us summary-input = entrée : état { $status }, options { $options }, envoyés { $sent } + +arg-wifi = Se connecte à l'hôte en Wi-Fi (QUIC) à ADDR au lieu de TCP. Un hôte déjà appairé n'a besoin de rien d'autre ; la première fois, ajoutez `--pin` (ou utilisez `--uri`). +arg-pin = Appaire d'abord avec l'hôte grâce au code PIN à 6 chiffres qu'il affiche. +arg-uri = URI d'appairage du QR code de l'hôte (`ezd://pair?...`) : fournit l'adresse, épingle l'empreinte de l'hôte et contient le PIN. +arg-state-dir = Dossier de l'identité de ce client et de l'hôte appairé (par défaut : `ezdisplay-fake-client` dans le dossier de configuration). +paired-with = Appairé avec { $host } ({ $fingerprint }) +err-pin-needs-wifi = --pin nécessite --wifi ADDR ou --uri +err-uri-invalid = l'URI d'appairage n'est pas valide +err-no-state-dir = impossible de trouver un dossier pour l'état du client ; indiquez --state-dir +err-wifi-no-address = adresse de l'hôte manquante : indiquez --wifi ADDR ou --uri +err-wifi-not-paired = aucun hôte appairé pour l'instant : indiquez --pin PIN (ou --uri) pour appairer +err-refused-not-paired = l'hôte ne connaît pas ce client : appairez à nouveau avec --pin +err-refused-closed = l'hôte n'accepte pas de nouvel appairage : ouvrez d'abord sa fenêtre d'appairage +err-refused-attempts = l'hôte a fermé l'appairage après trop de PIN incorrects +err-refused-wrong-pin = PIN incorrect +err-refused-busy = l'hôte est occupé avec un autre client +err-wifi-fingerprint = le certificat de l'hôte ne correspond pas à celui de l'appairage +err-wifi = Wi-Fi : { $reason } diff --git a/crates/ezd-fake-client/i18n/it/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/it/ezd-fake-client.ftl index e7cb379..b34d8f5 100644 --- a/crates/ezd-fake-client/i18n/it/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/it/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = orologio: scarto { $offset } us, rtt { $rtt } us summary-decode = decodifica: p50 { $p50 } us, p95 { $p95 } us summary-e2e = end-to-end (cattura host -> decodificato): p50 { $p50 } us, p95 { $p95 } us summary-input = input: stato { $status }, opzioni { $options }, inviati { $sent } + +arg-wifi = Si connette all'host via Wi-Fi (QUIC) a ADDR invece che con TCP. Un host già associato non richiede altro; la prima volta aggiungi `--pin` (o usa `--uri`). +arg-pin = Si associa prima all'host usando il PIN a 6 cifre che mostra. +arg-uri = URI di associazione dal codice QR dell'host (`ezd://pair?...`): fornisce l'indirizzo, fissa l'impronta dell'host e contiene il PIN. +arg-state-dir = Cartella dell'identità di questo client e dell'host associato (predefinita: `ezdisplay-fake-client` nella cartella di configurazione). +paired-with = Associato a { $host } ({ $fingerprint }) +err-pin-needs-wifi = --pin richiede --wifi ADDR o --uri +err-uri-invalid = l'URI di associazione non è valido +err-no-state-dir = impossibile trovare una cartella per lo stato del client; indica --state-dir +err-wifi-no-address = manca l'indirizzo dell'host: indica --wifi ADDR o --uri +err-wifi-not-paired = nessun host ancora associato: indica --pin PIN (o --uri) per associare +err-refused-not-paired = l'host non conosce questo client: associa di nuovo con --pin +err-refused-closed = l'host non accetta nuove associazioni: apri prima la sua finestra di associazione +err-refused-attempts = l'host ha chiuso l'associazione dopo troppi PIN errati +err-refused-wrong-pin = PIN errato +err-refused-busy = l'host è occupato con un altro client +err-wifi-fingerprint = il certificato dell'host non corrisponde a quello associato +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-fake-client/i18n/pt/ezd-fake-client.ftl b/crates/ezd-fake-client/i18n/pt/ezd-fake-client.ftl index ae23067..590c698 100644 --- a/crates/ezd-fake-client/i18n/pt/ezd-fake-client.ftl +++ b/crates/ezd-fake-client/i18n/pt/ezd-fake-client.ftl @@ -28,3 +28,21 @@ summary-clock = relógio: deslocamento { $offset } us, rtt { $rtt } us summary-decode = decodificação: p50 { $p50 } us, p95 { $p95 } us summary-e2e = ponta a ponta (captura do host -> decodificado): p50 { $p50 } us, p95 { $p95 } us summary-input = entrada: estado { $status }, opções { $options }, enviados { $sent } + +arg-wifi = Conecta ao host por Wi-Fi (QUIC) em ADDR em vez de TCP. Um host já pareado não precisa de mais nada; na primeira vez, adicione `--pin` (ou use `--uri`). +arg-pin = Pareia primeiro com o host usando o PIN de 6 dígitos que ele mostra. +arg-uri = URI de pareamento do QR code do host (`ezd://pair?...`): fornece o endereço, fixa a impressão digital do host e traz o PIN. +arg-state-dir = Pasta da identidade deste cliente e do host pareado (padrão: `ezdisplay-fake-client` na pasta de configuração). +paired-with = Pareado com { $host } ({ $fingerprint }) +err-pin-needs-wifi = --pin requer --wifi ADDR ou --uri +err-uri-invalid = a URI de pareamento não é válida +err-no-state-dir = não foi possível encontrar uma pasta para o estado do cliente; informe --state-dir +err-wifi-no-address = falta o endereço do host: informe --wifi ADDR ou --uri +err-wifi-not-paired = ainda não há host pareado: informe --pin PIN (ou --uri) para parear +err-refused-not-paired = o host não conhece este cliente: pareie de novo com --pin +err-refused-closed = o host não aceita novos pareamentos: abra antes a janela de pareamento dele +err-refused-attempts = o host encerrou o pareamento após PINs incorretos demais +err-refused-wrong-pin = PIN incorreto +err-refused-busy = o host está ocupado com outro cliente +err-wifi-fingerprint = o certificado do host não corresponde ao pareado +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-fake-client/src/lib.rs b/crates/ezd-fake-client/src/lib.rs index 55f64ce..1c3327f 100644 --- a/crates/ezd-fake-client/src/lib.rs +++ b/crates/ezd-fake-client/src/lib.rs @@ -8,6 +8,8 @@ #[macro_use] pub mod i18n; mod script; +#[cfg(feature = "wifi")] +pub mod wifi; use ezd_client_core::{ ClientConfig, ClientError as CoreError, ClientHandle, ClientHandler, Flow, HandlerResult, diff --git a/crates/ezd-fake-client/src/main.rs b/crates/ezd-fake-client/src/main.rs index 3126659..3e02f44 100644 --- a/crates/ezd-fake-client/src/main.rs +++ b/crates/ezd-fake-client/src/main.rs @@ -40,6 +40,18 @@ struct Args { exit_after_script: bool, #[arg(long, hide = true)] proto_minor: Option, + #[cfg(feature = "wifi")] + #[arg(long, value_name = "ADDR", conflicts_with = "connect")] + wifi: Option, + #[cfg(feature = "wifi")] + #[arg(long, value_name = "PIN", conflicts_with = "uri")] + pin: Option, + #[cfg(feature = "wifi")] + #[arg(long, value_name = "URI", conflicts_with = "connect")] + uri: Option, + #[cfg(feature = "wifi")] + #[arg(long, value_name = "DIR")] + state_dir: Option, } #[derive(Debug, Clone, Copy, ValueEnum)] @@ -74,6 +86,12 @@ fn command(l: &FluentLanguageLoader) -> Command { .mut_arg("exit_after_script", |a| { a.help(fl!(l, "arg-exit-after-script")) }); + #[cfg(feature = "wifi")] + let cmd = cmd + .mut_arg("wifi", |a| a.help(fl!(l, "arg-wifi"))) + .mut_arg("pin", |a| a.help(fl!(l, "arg-pin"))) + .mut_arg("uri", |a| a.help(fl!(l, "arg-uri"))) + .mut_arg("state_dir", |a| a.help(fl!(l, "arg-state-dir"))); i18n::localize_version(i18n::localize_chrome(cmd, l), l) } @@ -90,6 +108,8 @@ async fn main() -> Result<()> { ) .init(); let a = parse(&command(&i18n::LANGUAGE_LOADER).get_matches()); + #[cfg(feature = "wifi")] + let wifi = wifi_options(&a)?; let dump_frame = match a.dump_frame { Some(v) => { let n: u64 = v[0].parse().with_context(|| fl!("err-dump-frame"))?; @@ -98,7 +118,7 @@ async fn main() -> Result<()> { None => None, }; let cfg = FakeClientConfig { - device_name: a.name, + device_name: a.name.clone(), width: a.width, height: a.height, refresh_rates_mhz: a.refresh_rates_mhz, @@ -119,6 +139,27 @@ async fn main() -> Result<()> { ..Default::default() }; + #[cfg(feature = "wifi")] + if let Some(opts) = wifi { + let (link, outcome) = ezd_fake_client::wifi::connect_wifi(&opts) + .await + .map_err(|e| wifi_error(&e))?; + if let Some(host) = outcome.paired_with { + println!( + "{}", + fl!( + "paired-with", + host = host.name.as_str(), + fingerprint = host.fingerprint.as_str() + ) + ); + } + tracing::info!("connected over Wi-Fi"); + let report = run_fake_client(link, cfg).await?; + println!("{}", report.summary()); + return Ok(()); + } + let start = Instant::now(); let link = loop { match Link::connect_tcp(&a.connect).await { @@ -138,6 +179,67 @@ async fn main() -> Result<()> { Ok(()) } +/// The Wi-Fi options the command line describes, if any. +#[cfg(feature = "wifi")] +fn wifi_options(a: &Args) -> Result> { + use std::net::ToSocketAddrs; + if a.wifi.is_none() && a.uri.is_none() { + if a.pin.is_some() { + anyhow::bail!(fl!("err-pin-needs-wifi")); + } + return Ok(None); + } + let uri = match &a.uri { + Some(u) => Some(ezd_link::pair::PairUri::parse(u).with_context(|| fl!("err-uri-invalid"))?), + None => None, + }; + let addr = match &a.wifi { + Some(addr) => Some( + addr.to_socket_addrs() + .ok() + .and_then(|mut x| x.next()) + .with_context(|| fl!("err-connecting", addr = addr.as_str()))?, + ), + None => None, + }; + let state_dir = a + .state_dir + .clone() + .or_else(ezd_fake_client::wifi::default_state_dir) + .with_context(|| fl!("err-no-state-dir"))?; + Ok(Some(ezd_fake_client::wifi::WifiOptions { + addr, + pin: a.pin.clone(), + uri, + state_dir, + device_name: a.name.clone(), + connect_timeout: Duration::from_secs(a.connect_timeout), + })) +} + +/// User-facing text of a Wi-Fi failure. +#[cfg(feature = "wifi")] +fn wifi_error(e: &ezd_fake_client::wifi::WifiError) -> anyhow::Error { + use ezd_fake_client::wifi::WifiError; + use ezd_link::quic::QuicError; + use ezd_proto::pair::Refusal; + match e { + WifiError::NoAddress => anyhow::anyhow!(fl!("err-wifi-no-address")), + WifiError::NotPaired => anyhow::anyhow!(fl!("err-wifi-not-paired")), + WifiError::Quic(QuicError::Refused(r)) => anyhow::anyhow!(match r { + Refusal::NotPaired => fl!("err-refused-not-paired"), + Refusal::PairingClosed => fl!("err-refused-closed"), + Refusal::TooManyAttempts => fl!("err-refused-attempts"), + Refusal::WrongPin => fl!("err-refused-wrong-pin"), + Refusal::Busy => fl!("err-refused-busy"), + }), + WifiError::Quic(QuicError::FingerprintMismatch) => { + anyhow::anyhow!(fl!("err-wifi-fingerprint")) + } + other => anyhow::anyhow!(fl!("err-wifi", reason = other.to_string())), + } +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ezd-fake-client/src/wifi.rs b/crates/ezd-fake-client/src/wifi.rs new file mode 100644 index 0000000..1a62e0b --- /dev/null +++ b/crates/ezd-fake-client/src/wifi.rs @@ -0,0 +1,184 @@ +//! Wi-Fi (QUIC) connection of the fake client: pairing with a PIN, remembering the host, and +//! opening sessions on the paired host. +//! +//! The client keeps its identity (`identity.crt`/`identity.key`) and the paired host +//! (`host.json`) in a state directory. + +use ezd_link::Link; +use ezd_link::identity::{Identity, fingerprint_hex, parse_fingerprint, write_atomic}; +use ezd_link::pair::{PairUri, pair}; +use ezd_link::quic::{Congestion, QuicError, connect}; +use ezd_proto::pair::{Fingerprint, Refusal}; +use serde::{Deserialize, Serialize}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +const HOST_FILE: &str = "host.json"; + +/// The default state directory: `ezdisplay-fake-client` inside the user's config directory. +pub fn default_state_dir() -> Option { + dirs::config_dir().map(|d| d.join("ezdisplay-fake-client")) +} + +/// The host this client paired with. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredHost { + /// Host name, as announced when pairing. + pub name: String, + /// Host certificate fingerprint, lower-case hex. + pub fingerprint: String, +} + +/// What to connect to and how. +#[derive(Debug, Clone)] +pub struct WifiOptions { + /// Host address; taken from `uri` when `None`. + pub addr: Option, + /// Pair first with this PIN. + pub pin: Option, + /// Pairing URI (pins the host fingerprint and carries a PIN). + pub uri: Option, + /// Identity and paired host live here. + pub state_dir: PathBuf, + /// Name announced when pairing. + pub device_name: String, + /// Keep retrying the session connection this long. + pub connect_timeout: Duration, +} + +/// Why the Wi-Fi connection failed. +#[derive(Debug, thiserror::Error)] +pub enum WifiError { + /// No address was given. + #[error("no host address: pass an address or a pairing URI")] + NoAddress, + /// No paired host and no PIN to pair with. + #[error("not paired with this host: pass --pin or --uri")] + NotPaired, + /// The connection, the handshake or the pairing failed. + #[error("{0}")] + Quic(#[from] QuicError), + /// State directory problem. + #[error("{}: {source}", path.display())] + State { + /// The file or directory. + path: PathBuf, + /// The OS error. + source: std::io::Error, + }, + /// `host.json` does not parse; it was left untouched. + #[error("{} is corrupt: {reason}", path.display())] + Corrupt { + /// The file. + path: PathBuf, + /// What is wrong with it. + reason: String, + }, +} + +/// What happened besides the connection, for the caller to tell the user. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WifiOutcome { + /// Set when this call paired with a host. + pub paired_with: Option, +} + +/// Loads the stored host; a missing file is `None`, a corrupt one an error. +pub fn load_host(dir: &Path) -> Result, WifiError> { + let path = dir.join(HOST_FILE); + let data = match std::fs::read(&path) { + Ok(d) => d, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), + Err(source) => return Err(WifiError::State { path, source }), + }; + let host: StoredHost = serde_json::from_slice(&data).map_err(|e| WifiError::Corrupt { + path: path.clone(), + reason: e.to_string(), + })?; + if parse_fingerprint(&host.fingerprint).is_none() { + return Err(WifiError::Corrupt { + path, + reason: "invalid fingerprint".into(), + }); + } + Ok(Some(host)) +} + +fn save_host(dir: &Path, host: &StoredHost) -> Result<(), WifiError> { + let path = dir.join(HOST_FILE); + let json = serde_json::to_vec_pretty(host).expect("host serializes"); + write_atomic(&path, &json).map_err(|source| WifiError::State { path, source }) +} + +/// Worth another session attempt: the host is not up yet, or still finishing the previous +/// session (`Busy`). +fn retryable(e: &QuicError) -> bool { + matches!( + e, + QuicError::Connect(_) + | QuicError::Connection(_) + | QuicError::Timeout + | QuicError::Io(_) + | QuicError::Refused(Refusal::Busy) + ) +} + +/// Pairs if asked to, then opens a session. The result is the link to hand to +/// [`run_fake_client`](crate::run_fake_client). +pub async fn connect_wifi(opts: &WifiOptions) -> Result<(Link, WifiOutcome), WifiError> { + let addr = opts + .addr + .or(opts.uri.as_ref().map(|u| u.addr)) + .ok_or(WifiError::NoAddress)?; + std::fs::create_dir_all(&opts.state_dir).map_err(|source| WifiError::State { + path: opts.state_dir.clone(), + source, + })?; + let id = Identity::load_or_create(&opts.state_dir).map_err(|source| WifiError::State { + path: opts.state_dir.clone(), + source, + })?; + let cc = Congestion::default(); + + let pin = opts + .pin + .clone() + .or(opts.uri.as_ref().map(|u| u.pin.clone())); + let mut paired_with = None; + let host_fp: Fingerprint = if let Some(pin) = pin { + // The URI pins the host certificate; a bare PIN is authenticated by the pairing itself. + let pinned = opts.uri.as_ref().map(|u| u.fingerprint); + let conn = connect(addr, &id, pinned, cc).await?; + let host = pair(conn, &pin, &opts.device_name).await?; + let stored = StoredHost { + name: host.name, + fingerprint: fingerprint_hex(&host.fingerprint), + }; + save_host(&opts.state_dir, &stored)?; + paired_with = Some(stored); + host.fingerprint + } else { + let host = load_host(&opts.state_dir)?.ok_or(WifiError::NotPaired)?; + parse_fingerprint(&host.fingerprint).expect("checked by load_host") + }; + + let start = Instant::now(); + let link = loop { + let attempt = async { + connect(addr, &id, Some(host_fp), cc) + .await? + .open_session() + .await + }; + match attempt.await { + Ok(l) => break l, + Err(e) if retryable(&e) && start.elapsed() < opts.connect_timeout => { + tracing::debug!("connect failed ({e}), retrying"); + tokio::time::sleep(Duration::from_millis(200)).await; + } + Err(e) => return Err(e.into()), + } + }; + Ok((link, WifiOutcome { paired_with })) +} diff --git a/crates/ezd-fake-client/tests/wifi.rs b/crates/ezd-fake-client/tests/wifi.rs new file mode 100644 index 0000000..7c8f31c --- /dev/null +++ b/crates/ezd-fake-client/tests/wifi.rs @@ -0,0 +1,219 @@ +//! Host session <-> fake client over a real QUIC loopback: pairing with a PIN, then reconnecting +//! with the stored pairing and no PIN. +#![cfg(feature = "wifi")] + +use ezd_fake_client::wifi::{WifiError, WifiOptions, connect_wifi, load_host}; +use ezd_fake_client::{ClientEnd, FakeClientConfig, run_fake_client}; +use ezd_ffmpeg::{SwVideoSource, encoder_available}; +use ezd_host_core::run_host_session; +use ezd_link::identity::Identity; +use ezd_link::pair::{PairUri, PairingWindow, host_pair}; +use ezd_link::quic::{Congestion, QuicError, QuicServer}; +use ezd_proto::Prefs; +use ezd_proto::pair::{Fingerprint, LinkOpen, Refusal}; +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Duration; +use tokio::time::timeout; + +struct TempDir(PathBuf); + +impl TempDir { + fn new(tag: &str) -> TempDir { + let dir = + std::env::temp_dir().join(format!("ezd-fake-client-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + TempDir(dir) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A host that pairs while its window is open and streams to paired clients. +fn spawn_host( + server: QuicServer, + window: Arc, + paired: Arc>>, +) -> tokio::task::JoinHandle<()> { + tokio::spawn(async move { + // A failed handshake is an `Err` and the server keeps accepting. + while let Some(accepted) = server.accept().await { + let Ok(conn) = accepted else { continue }; + let (window, paired) = (window.clone(), paired.clone()); + tokio::spawn(async move { + let Ok(opened) = conn.accept_open().await else { + return; + }; + match opened.open.clone() { + LinkOpen::Pair { .. } => { + let _ = host_pair(opened, &window, "test host", |c| { + paired.lock().unwrap().push(c.fingerprint); + Ok(()) + }) + .await; + } + LinkOpen::Session => { + let known = opened + .peer_fingerprint() + .is_some_and(|fp| paired.lock().unwrap().contains(&fp)); + if !known { + return opened.refuse(Refusal::NotPaired).await; + } + let link = opened.accept_session().await.unwrap(); + let _ = run_host_session( + link, + Box::new(SwVideoSource::new()), + Prefs::default(), + ) + .await; + } + } + }); + } + }) +} + +fn options(addr: SocketAddr, dir: &TempDir, pin: Option<&str>) -> WifiOptions { + WifiOptions { + addr: Some(addr), + pin: pin.map(Into::into), + uri: None, + state_dir: dir.0.clone(), + device_name: "fake tablet".into(), + connect_timeout: Duration::from_secs(2), + } +} + +fn client_cfg() -> FakeClientConfig { + FakeClientConfig { + width: 1280, + height: 720, + refresh_rates_mhz: vec![60_000], + frames: Some(30), + ..Default::default() + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn pairs_with_a_pin_then_reconnects_without_one() { + if !encoder_available("libx264") && !encoder_available("libopenh264") { + eprintln!("no software H.264 encoder, skipping"); + return; + } + let host_id = Identity::generate().unwrap(); + let server = + QuicServer::bind("127.0.0.1:0".parse().unwrap(), &host_id, Congestion::Cubic).unwrap(); + let addr = server.local_addr().unwrap(); + let window = Arc::new(PairingWindow::default()); + window.open_with("123456".into(), Duration::from_secs(60)); + let paired = Arc::new(Mutex::new(Vec::new())); + let host = spawn_host(server, window.clone(), paired.clone()); + let dir = TempDir::new("pair"); + + // No pairing yet and no PIN. + let err = connect_wifi(&options(addr, &dir, None)) + .await + .err() + .unwrap(); + assert!(matches!(err, WifiError::NotPaired), "{err:?}"); + + // Pair, then stream. + let (link, outcome) = connect_wifi(&options(addr, &dir, Some("123456"))) + .await + .unwrap(); + assert_eq!(outcome.paired_with.unwrap().name, "test host"); + let report = timeout(Duration::from_secs(60), run_fake_client(link, client_cfg())) + .await + .unwrap() + .unwrap(); + assert_eq!(report.end, ClientEnd::FramesReached); + assert!(report.frames_decoded >= 30); + assert_eq!( + load_host(&dir.0).unwrap().unwrap().fingerprint, + ezd_link::identity::fingerprint_hex(&host_id.fingerprint()) + ); + + // Later: the address alone is enough, and the window is closed. + assert!(!window.is_open()); + let (link, outcome) = connect_wifi(&options(addr, &dir, None)).await.unwrap(); + assert!(outcome.paired_with.is_none()); + let report = timeout(Duration::from_secs(60), run_fake_client(link, client_cfg())) + .await + .unwrap() + .unwrap(); + assert!(report.frames_decoded >= 30); + host.abort(); +} + +#[tokio::test] +async fn a_wrong_pin_is_refused_and_nothing_is_stored() { + let host_id = Identity::generate().unwrap(); + let server = + QuicServer::bind("127.0.0.1:0".parse().unwrap(), &host_id, Congestion::Cubic).unwrap(); + let addr = server.local_addr().unwrap(); + let window = Arc::new(PairingWindow::default()); + window.open_with("123456".into(), Duration::from_secs(60)); + let host = spawn_host(server, window, Arc::default()); + let dir = TempDir::new("wrong-pin"); + let err = connect_wifi(&options(addr, &dir, Some("654321"))) + .await + .err() + .unwrap(); + assert!( + matches!(err, WifiError::Quic(QuicError::Refused(_))), + "{err:?}" + ); + assert!(load_host(&dir.0).unwrap().is_none()); + host.abort(); +} + +#[tokio::test] +async fn a_uri_pins_the_host_and_supplies_address_and_pin() { + let host_id = Identity::generate().unwrap(); + let server = + QuicServer::bind("127.0.0.1:0".parse().unwrap(), &host_id, Congestion::Cubic).unwrap(); + let addr = server.local_addr().unwrap(); + let window = Arc::new(PairingWindow::default()); + window.open_with("123456".into(), Duration::from_secs(60)); + let host = spawn_host(server, window, Arc::default()); + let uri = |fingerprint| PairUri { + addr, + fingerprint, + pin: "123456".into(), + name: "test host".into(), + }; + let dir = TempDir::new("uri"); + + // A URI for another certificate fails the handshake; nothing is stored. + let opts = |u: PairUri| WifiOptions { + addr: None, + pin: None, + uri: Some(u), + ..options(addr, &dir, None) + }; + let err = connect_wifi(&opts(uri([7; 32]))).await.err().unwrap(); + assert!( + matches!(err, WifiError::Quic(QuicError::FingerprintMismatch)), + "{err:?}" + ); + assert!(load_host(&dir.0).unwrap().is_none()); + + let (_link, outcome) = connect_wifi(&opts(uri(host_id.fingerprint()))) + .await + .unwrap(); + assert!(outcome.paired_with.is_some()); + host.abort(); +} + +#[test] +fn a_corrupt_host_file_is_an_error() { + let dir = TempDir::new("corrupt"); + std::fs::create_dir_all(&dir.0).unwrap(); + std::fs::write(dir.0.join("host.json"), "nope").unwrap(); + assert!(matches!(load_host(&dir.0), Err(WifiError::Corrupt { .. }))); +} diff --git a/crates/ezd-host-service/Cargo.toml b/crates/ezd-host-service/Cargo.toml index 0e3765d..bc4f6f2 100644 --- a/crates/ezd-host-service/Cargo.toml +++ b/crates/ezd-host-service/Cargo.toml @@ -9,13 +9,19 @@ repository.workspace = true rust-version.workspace = true [features] -default = ["ffmpeg"] +default = ["ffmpeg", "wifi"] # The software (synthetic) source and the Windows hardware encode go through FFmpeg, which needs # its headers/libs at build time. `--no-default-features` builds on a machine without them (the # Windows cross-check in CI); the synthetic source then reports "built without ffmpeg". ffmpeg = ["dep:ezd-ffmpeg", "ezd-host-windows/ffmpeg"] +# Wi-Fi (QUIC) transport with PIN pairing and mDNS discovery. ring (QUIC's crypto) has C code that +# the Windows cross-check from Linux cannot build, hence the feature, like `ffmpeg`. +wifi = ["ezd-link/quic", "dep:mdns-sd", "dep:dirs", "dep:gethostname"] [dependencies] +dirs = { workspace = true, optional = true } +gethostname = { workspace = true, optional = true } +mdns-sd = { workspace = true, optional = true } ezd-ffmpeg = { workspace = true, optional = true } ezd-host-core.workspace = true ezd-link.workspace = true diff --git a/crates/ezd-host-service/src/config.rs b/crates/ezd-host-service/src/config.rs index 38ae67a..a517d01 100644 --- a/crates/ezd-host-service/src/config.rs +++ b/crates/ezd-host-service/src/config.rs @@ -82,6 +82,57 @@ impl From for HdrMode { } } +/// Congestion controller of the Wi-Fi link. +#[cfg(feature = "wifi")] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum CongestionChoice { + /// CUBIC. + #[default] + Cubic, + /// BBR (experimental). + Bbr, +} + +#[cfg(feature = "wifi")] +impl From for ezd_link::quic::Congestion { + fn from(c: CongestionChoice) -> Self { + match c { + CongestionChoice::Cubic => Self::Cubic, + CongestionChoice::Bbr => Self::Bbr, + } + } +} + +/// The Wi-Fi (QUIC) listener. It is read when the service starts; changing it later needs a +/// restart of the service. +#[cfg(feature = "wifi")] +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(default)] +pub struct WifiConfig { + /// UDP address the tablets connect to. + pub listen: SocketAddr, + /// Open the pairing window at start even if a device is already paired. + pub pair_on_start: bool, + /// Congestion controller. + pub congestion: CongestionChoice, + /// Where the identity and the paired devices live; `None` is the `ezdisplay` folder in the + /// user's config directory. + pub config_dir: Option, +} + +#[cfg(feature = "wifi")] +impl Default for WifiConfig { + fn default() -> Self { + WifiConfig { + listen: SocketAddr::from(([0, 0, 0, 0], ezd_proto::DEFAULT_PORT)), + pair_on_start: false, + congestion: CongestionChoice::default(), + config_dir: None, + } + } +} + /// Everything the service needs to run; loads from a file with missing or unknown keys. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(default)] @@ -120,6 +171,10 @@ pub struct ServiceConfig { pub open_app_on_connect: bool, /// HDR10 streaming policy (`hdr = "auto" | "off"`). pub hdr: HdrChoice, + /// Wi-Fi listener; `None` leaves Wi-Fi off. Sessions on it always use the network link kind, + /// whatever `link` says. + #[cfg(feature = "wifi")] + pub wifi: Option, } impl Default for ServiceConfig { @@ -142,6 +197,8 @@ impl Default for ServiceConfig { pen_mode: PenChoice::default(), open_app_on_connect: true, hdr: HdrChoice::default(), + #[cfg(feature = "wifi")] + wifi: None, } } } @@ -163,6 +220,14 @@ impl ServiceConfig { } } + /// Preferences of a Wi-Fi session: the network link kind, the rest as [`prefs`](Self::prefs). + pub fn wifi_prefs(&self) -> Prefs { + Prefs { + link: LinkKind::Network, + ..self.prefs() + } + } + /// Options of the virtual-display backend. pub fn platform_options(&self) -> PlatformOptions { PlatformOptions { @@ -242,6 +307,19 @@ mod tests { ); } + #[test] + fn wifi_sessions_use_the_network_link_kind() { + let c = ServiceConfig::default(); + assert_eq!(c.prefs().link, LinkKind::Usb); + assert_eq!( + c.wifi_prefs(), + Prefs { + link: LinkKind::Network, + ..c.prefs() + } + ); + } + #[test] fn platform_options_follow_the_fields() { let c = ServiceConfig { diff --git a/crates/ezd-host-service/src/error.rs b/crates/ezd-host-service/src/error.rs index 911c19a..9eb8267 100644 --- a/crates/ezd-host-service/src/error.rs +++ b/crates/ezd-host-service/src/error.rs @@ -27,6 +27,9 @@ pub enum ServiceError { /// There is no virtual display backend for this platform. #[error("no virtual display backend for this platform")] UnsupportedPlatform, + /// The Wi-Fi transport cannot start (identity or paired-devices file unusable, ...). + #[error("Wi-Fi: {0}")] + Wifi(String), /// The video source could not be created. #[error("cannot create the video source: {0}")] Source(String), diff --git a/crates/ezd-host-service/src/lib.rs b/crates/ezd-host-service/src/lib.rs index ef1c10e..641bdb4 100644 --- a/crates/ezd-host-service/src/lib.rs +++ b/crates/ezd-host-service/src/lib.rs @@ -4,6 +4,8 @@ //! * [`HostService::start`] binds the listener and spawns the accept loop and the adb watcher. //! * [`HostService::status`] is a `watch` channel with the current [`HostStatus`]; one-off //! notifications (a session ended, ...) come from [`HostService::events`]. +//! * With the `wifi` feature, [`ServiceConfig::wifi`] adds a QUIC listener for paired tablets +//! next to the plaintext TCP one; only one session streams at a time across both. //! * [`HostService::apply`] changes the [`ServiceConfig`] while running; [`HostService::stop`] //! ends the session cleanly and removes the adb reverses. //! @@ -13,12 +15,23 @@ pub mod adb; pub mod config; pub mod error; +#[cfg(feature = "wifi")] +mod mdns; pub mod platform; mod service; pub mod status; +#[cfg(feature = "wifi")] +pub mod store; +#[cfg(feature = "wifi")] +mod wifi; pub use adb::{AdbClient, AdbLocator, is_network_serial}; pub use config::{AdbMode, HdrChoice, LinkChoice, PenChoice, ServiceConfig, SourceKind}; +#[cfg(feature = "wifi")] +pub use config::{CongestionChoice, WifiConfig}; pub use error::ServiceError; pub use service::{HostService, ServiceHooks, SourceFactory}; -pub use status::{DeviceInfo, DeviceState, HostEvent, HostStatus, LiveSession}; +pub use status::{ + DeviceInfo, DeviceState, HostEvent, HostStatus, LiveSession, PairingCloseReason, RefusedWhy, + Transport, WifiInfo, +}; diff --git a/crates/ezd-host-service/src/mdns.rs b/crates/ezd-host-service/src/mdns.rs new file mode 100644 index 0000000..ebad634 --- /dev/null +++ b/crates/ezd-host-service/src/mdns.rs @@ -0,0 +1,95 @@ +//! mDNS advertisement: `_ezdisplay._udp.local.` on the Wi-Fi port, so tablets can find the +//! host without typing an address. + +use mdns_sd::{ServiceDaemon, ServiceInfo}; + +/// DNS-SD service type of the host. +pub const SERVICE_TYPE: &str = "_ezdisplay._udp.local."; + +/// A registered advertisement; dropping it unregisters the service and stops the daemon. +pub struct Advertiser { + daemon: ServiceDaemon, + fullname: String, +} + +/// The TXT record: `fp` is the short fingerprint, `name` the host name, `pv` the protocol major. +pub fn txt_records(fingerprint_short: &str, host_name: &str) -> Vec<(String, String)> { + vec![ + ("fp".into(), fingerprint_short.into()), + ("name".into(), host_name.into()), + ("pv".into(), ezd_proto::PROTOCOL_MAJOR.to_string()), + ] +} + +impl Advertiser { + /// Starts advertising on `port`. The instance name is the host name; addresses follow the + /// network interfaces automatically. + pub fn start( + port: u16, + fingerprint_short: &str, + host_name: &str, + ) -> Result { + let daemon = ServiceDaemon::new()?; + let dns_host = format!("{}.local.", dns_label(host_name)); + let info = ServiceInfo::new( + SERVICE_TYPE, + host_name, + &dns_host, + "", + port, + &txt_records(fingerprint_short, host_name)[..], + )? + .enable_addr_auto(); + let fullname = info.get_fullname().to_string(); + if let Err(e) = daemon.register(info) { + let _ = daemon.shutdown(); + return Err(e); + } + Ok(Advertiser { daemon, fullname }) + } +} + +impl Drop for Advertiser { + fn drop(&mut self) { + if let Ok(rx) = self.daemon.unregister(&self.fullname) { + // The goodbye packet goes out before the daemon stops. + let _ = rx.recv_timeout(std::time::Duration::from_millis(500)); + } + let _ = self.daemon.shutdown(); + } +} + +/// A host name as one DNS label: letters, digits and hyphens. +fn dns_label(name: &str) -> String { + let label: String = name + .chars() + .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }) + .collect(); + let label = label.trim_matches('-'); + if label.is_empty() { + "ezdisplay".into() + } else { + label.chars().take(63).collect() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn dns_labels_are_sanitized() { + assert_eq!(dns_label("My PC (work)"), "My-PC--work"); + assert_eq!(dns_label("---"), "ezdisplay"); + assert_eq!(dns_label(&"a".repeat(100)).len(), 63); + } + + #[test] + fn txt_carries_fingerprint_name_and_protocol() { + let t = txt_records("3f2a-91c0-77de-0b14", "desk"); + assert_eq!(t[0], ("fp".into(), "3f2a-91c0-77de-0b14".into())); + assert_eq!(t[1], ("name".into(), "desk".into())); + assert_eq!(t[2].0, "pv"); + assert_eq!(t[2].1, ezd_proto::PROTOCOL_MAJOR.to_string()); + } +} diff --git a/crates/ezd-host-service/src/service.rs b/crates/ezd-host-service/src/service.rs index 6680a31..c5ce3d9 100644 --- a/crates/ezd-host-service/src/service.rs +++ b/crates/ezd-host-service/src/service.rs @@ -3,19 +3,26 @@ use crate::adb::{AdbClient, AdbLocator, Watcher, locate_system_adb}; use crate::config::{AdbMode, ServiceConfig, SourceKind}; use crate::error::ServiceError; -use crate::status::{DeviceInfo, HostEvent, HostStatus, LiveSession}; +use crate::status::{DeviceInfo, HostEvent, HostStatus, LiveSession, Transport, WifiInfo}; use ezd_host_core::{SessionEvent, VideoSource, run_host_session_with}; use ezd_link::Link; +use ezd_proto::Prefs; use std::net::SocketAddr; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Duration; use tokio::net::TcpListener; -use tokio::sync::{broadcast, mpsc, watch}; +use tokio::sync::{Semaphore, broadcast, mpsc, watch}; use tokio::task::JoinHandle; /// How often the adb watcher lists the devices. pub const ADB_POLL_INTERVAL: Duration = Duration::from_secs(2); +/// Default lifetime of a pairing window. +#[cfg(feature = "wifi")] +const DEFAULT_PAIRING_TTL: Duration = ezd_link::pair::DEFAULT_WINDOW; +#[cfg(not(feature = "wifi"))] +const DEFAULT_PAIRING_TTL: Duration = Duration::from_secs(5 * 60); + /// Creates the video source for one client connection. pub type SourceFactory = Arc Result, ServiceError> + Send + Sync>; @@ -29,6 +36,8 @@ pub struct ServiceHooks { pub locate_adb: AdbLocator, /// Builds the source of a session. pub create_source: SourceFactory, + /// How long a pairing window stays open. + pub pairing_ttl: Duration, } impl Default for ServiceHooks { @@ -37,6 +46,7 @@ impl Default for ServiceHooks { adb_poll_interval: ADB_POLL_INTERVAL, locate_adb: Arc::new(locate_system_adb), create_source: Arc::new(create_source), + pairing_ttl: DEFAULT_PAIRING_TTL, } } } @@ -63,15 +73,15 @@ fn synthetic_source() -> Result, ServiceError> { // One live session at a time, so the size of the variant does not matter. #[allow(clippy::large_enum_variant)] -enum Phase { +pub(crate) enum Phase { Waiting, Streaming(LiveSession), Error(ServiceError), Stopped, } -struct State { - phase: Phase, +pub(crate) struct State { + pub(crate) phase: Phase, devices: Vec, /// adb problem (not found, reverse failing); shown while no session is running. adb_error: Option, @@ -96,8 +106,8 @@ impl State { } } -struct Inner { - cfg: watch::Sender, +pub(crate) struct Inner { + pub(crate) cfg: watch::Sender, status: watch::Sender, events: broadcast::Sender, state: Mutex, @@ -106,16 +116,22 @@ struct Inner { /// Ends the running session when it holds `true`. session_stop: Mutex>>>, /// Set by `stop`. - stop: watch::Sender, - hooks: ServiceHooks, + pub(crate) stop: watch::Sender, + pub(crate) hooks: ServiceHooks, + /// One permit: held for as long as a session streams, whichever transport it came from. + pub(crate) slot: Arc, + /// The Wi-Fi listener, when on. + pub(crate) wifi_info: watch::Sender>, + #[cfg(feature = "wifi")] + pub(crate) wifi: Option>, } -fn lock(m: &Mutex) -> MutexGuard<'_, T> { +pub(crate) fn lock(m: &Mutex) -> MutexGuard<'_, T> { m.lock().unwrap_or_else(|e| e.into_inner()) } impl Inner { - fn update(&self, f: impl FnOnce(&mut State)) { + pub(crate) fn update(&self, f: impl FnOnce(&mut State)) { let mut st = lock(&self.state); f(&mut st); let new = st.status(); @@ -128,11 +144,11 @@ impl Inner { }); } - fn emit(&self, ev: HostEvent) { + pub(crate) fn emit(&self, ev: HostEvent) { let _ = self.events.send(ev); } - fn on_session_event(&self, ev: SessionEvent) { + fn on_session_event(&self, ev: SessionEvent, transport: Transport) { self.update(|st| match ev { SessionEvent::Configured { client_hello, @@ -147,6 +163,7 @@ impl Inner { devices: Vec::new(), stats: None, input: None, + transport, }); } SessionEvent::Stats(s) => { @@ -177,6 +194,8 @@ pub struct HostService { inner: Arc, serve: Option>, watch: Option>, + /// Wi-Fi tasks (accept loop, pairing watcher). + wifi_tasks: Vec>, } impl HostService { @@ -206,6 +225,11 @@ impl HostService { }; let local = listener.local_addr().map_err(bind_err)?; + #[cfg(feature = "wifi")] + let wifi = match &cfg.wifi { + Some(w) => Some(crate::wifi::Wifi::setup(handle, w, hooks.pairing_ttl)?), + None => None, + }; let requested = cfg.listen; let status = HostStatus::Waiting { devices: Vec::new(), @@ -223,17 +247,59 @@ impl HostService { session_stop: Mutex::new(None), stop: watch::channel(false).0, hooks, + slot: Arc::new(Semaphore::new(1)), + wifi_info: watch::channel(None).0, + #[cfg(feature = "wifi")] + wifi, }); inner.set_addr(Some(local)); + #[allow(unused_mut)] + let mut wifi_tasks = Vec::new(); + #[cfg(feature = "wifi")] + if let Some(w) = &inner.wifi { + inner.wifi_info.send_replace(Some(w.info())); + wifi_tasks.push(handle.spawn(crate::wifi::serve(inner.clone(), w.clone()))); + wifi_tasks.push(handle.spawn(crate::wifi::watch_pairing(inner.clone(), w.clone()))); + } let serve = handle.spawn(serve(inner.clone(), listener, requested)); let watch = handle.spawn(watch_adb(inner.clone())); Ok(HostService { inner, serve: Some(serve), watch: Some(watch), + wifi_tasks, }) } + /// The Wi-Fi listener; `None` while Wi-Fi is off. + pub fn wifi(&self) -> watch::Receiver> { + self.inner.wifi_info.subscribe() + } + + /// Opens the pairing window with a new PIN (the PIN and QR URI arrive as + /// [`HostEvent::PairingOpen`]). Returns the PIN, or `None` when Wi-Fi is off. + #[cfg(feature = "wifi")] + pub fn open_pairing(&self) -> Option { + Some(self.inner.wifi.as_ref()?.open_pairing()) + } + + /// Emits [`HostEvent::PairingOpen`] again if a window is open: for a frontend that + /// subscribed to [`events`](Self::events) after the service started with the window open. + #[cfg(feature = "wifi")] + pub fn refresh_pairing(&self) { + if let Some(w) = &self.inner.wifi { + w.refresh_pairing(); + } + } + + /// Closes the pairing window. + #[cfg(feature = "wifi")] + pub fn close_pairing(&self) { + if let Some(w) = &self.inner.wifi { + w.close_pairing(); + } + } + /// Current state; changes are pushed to the receiver. pub fn status(&self) -> watch::Receiver { self.inner.status.subscribe() @@ -264,12 +330,17 @@ impl HostService { /// tearing a hardware encoder down while the process exits can deadlock in the driver. pub async fn stop(mut self) { self.inner.stop.send_replace(true); - for task in [self.serve.take(), self.watch.take()].into_iter().flatten() { + let tasks = [self.serve.take(), self.watch.take()] + .into_iter() + .flatten() + .chain(std::mem::take(&mut self.wifi_tasks)); + for task in tasks { if let Err(e) = task.await { tracing::error!("service task failed: {e}"); } } self.inner.addr.send_replace(None); + self.inner.wifi_info.send_replace(None); self.inner.update(|st| st.phase = Phase::Stopped); } } @@ -342,31 +413,62 @@ async fn serve(inner: Arc, first: TcpListener, requested: SocketAddr) { continue; } }; - let source = match (inner.hooks.create_source)(&cfg) { - Ok(s) => s, - Err(e) => { - tracing::warn!("cannot create virtual source: {e}"); - inner.emit(HostEvent::SourceFailed(e.clone())); - inner.update(|st| st.phase = Phase::Error(e)); - continue; - } + // One session at a time across transports: while a Wi-Fi session streams, this client + // waits for it (like a second client in the listen backlog did before). + let permit = tokio::select! { + p = inner.slot.clone().acquire_owned() => p.expect("the slot is never closed"), + _ = stop_rx.changed() => break, }; - let result = run_session(&inner, &cfg, link, source, &mut stop_rx).await; - inner.update(|st| st.phase = Phase::Waiting); - match &result { - Ok(s) => tracing::debug!(end = ?s.end, "session returned"), - Err(e) => tracing::debug!("session failed: {e}"), - } - inner.emit(HostEvent::SessionEnded(result.map_err(|e| e.to_string()))); + stream_session(&inner, &cfg, link, Transport::Tcp, &mut stop_rx).await; + drop(permit); } // Close the listener before reporting that serving stopped. drop(listener); } +/// Creates the source and runs one session on `link`; the caller holds the session slot. +async fn stream_session( + inner: &Inner, + cfg: &ServiceConfig, + link: Link, + transport: Transport, + stop_rx: &mut watch::Receiver, +) { + let source = match (inner.hooks.create_source)(cfg) { + Ok(s) => s, + Err(e) => { + tracing::warn!("cannot create virtual source: {e}"); + inner.emit(HostEvent::SourceFailed(e.clone())); + inner.update(|st| st.phase = Phase::Error(e)); + return; + } + }; + finish_session(inner, cfg, link, transport, source, stop_rx).await; +} + +/// Runs a session with an existing source and reports its end. +pub(crate) async fn finish_session( + inner: &Inner, + cfg: &ServiceConfig, + link: Link, + transport: Transport, + source: Box, + stop_rx: &mut watch::Receiver, +) { + let result = run_session(inner, cfg, link, transport, source, stop_rx).await; + inner.update(|st| st.phase = Phase::Waiting); + match &result { + Ok(s) => tracing::debug!(end = ?s.end, "session returned"), + Err(e) => tracing::debug!("session failed: {e}"), + } + inner.emit(HostEvent::SessionEnded(result.map_err(|e| e.to_string()))); +} + async fn run_session( inner: &Inner, cfg: &ServiceConfig, link: Link, + transport: Transport, source: Box, stop_rx: &mut watch::Receiver, ) -> Result { @@ -374,10 +476,15 @@ async fn run_session( let end_tx = Arc::new(end_tx); *lock(&inner.session_stop) = Some(end_tx.clone()); let (ev_tx, mut ev_rx) = mpsc::unbounded_channel(); + // A Wi-Fi session is always a network link, whatever `cfg.link` says. + let prefs: Prefs = match transport { + Transport::Tcp => cfg.prefs(), + Transport::Wifi => cfg.wifi_prefs(), + }; let session = run_host_session_with( link, source, - cfg.prefs(), + prefs, cfg.session_options(end_rx, Some(ev_tx)), ); tokio::pin!(session); @@ -385,7 +492,7 @@ async fn run_session( let result = loop { tokio::select! { r = &mut session => break r, - Some(ev) = ev_rx.recv() => inner.on_session_event(ev), + Some(ev) = ev_rx.recv() => inner.on_session_event(ev, transport), _ = stop_rx.changed(), if !stop_forwarded => { // The session stops the source before it returns. tracing::info!("stopping, ending the session"); @@ -472,7 +579,7 @@ async fn release_all(watcher: &Arc>, adb: &Arc) { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; use crate::adb::fake::{FakeAdb, device}; use ezd_host_core::testing::ScriptedSource; @@ -484,9 +591,9 @@ mod tests { }; use tokio::time::timeout; - const WAIT: Duration = Duration::from_secs(10); + pub(crate) const WAIT: Duration = Duration::from_secs(10); - fn cfg() -> ServiceConfig { + pub(crate) fn cfg() -> ServiceConfig { ServiceConfig { listen: "127.0.0.1:0".parse().unwrap(), adb: AdbMode::Off, @@ -495,17 +602,18 @@ mod tests { } } - fn hooks() -> ServiceHooks { + pub(crate) fn hooks() -> ServiceHooks { ServiceHooks { adb_poll_interval: Duration::from_millis(20), locate_adb: Arc::new(|| None), create_source: Arc::new(|_| { Ok(Box::new(ScriptedSource::new(Duration::from_millis(5), 200))) }), + pairing_ttl: Duration::from_secs(60), } } - fn start(cfg: ServiceConfig, hooks: ServiceHooks) -> HostService { + pub(crate) fn start(cfg: ServiceConfig, hooks: ServiceHooks) -> HostService { HostService::start_with(&tokio::runtime::Handle::current(), cfg, hooks).unwrap() } @@ -517,7 +625,7 @@ mod tests { .port() } - fn caps() -> ClientCaps { + pub(crate) fn caps() -> ClientCaps { ClientCaps { display: DisplayInfo { width_px: 1280, @@ -541,9 +649,14 @@ mod tests { } /// Connects like the tablet and completes the handshake. - async fn connect(addr: SocketAddr) -> (MuxSender, MuxReceiver) { + pub(crate) async fn connect(addr: SocketAddr) -> (MuxSender, MuxReceiver) { let sock = tokio::net::TcpStream::connect(addr).await.unwrap(); - let (tx, mut rx, _t) = Link::from_tcp(sock).unwrap().into_mux(DEFAULT_CHUNK_LEN); + handshake(Link::from_tcp(sock).unwrap()).await + } + + /// Completes the handshake on `link` like the tablet. + pub(crate) async fn handshake(link: Link) -> (MuxSender, MuxReceiver) { + let (tx, mut rx, _t) = link.into_mux(DEFAULT_CHUNK_LEN); tx.send_control(Message::Hello(Hello::new(Role::Client, "t", "tablet"))) .unwrap(); tx.send_control(Message::ClientCaps(caps())).unwrap(); @@ -563,7 +676,7 @@ mod tests { (tx, rx) } - async fn wait_status( + pub(crate) async fn wait_status( rx: &mut watch::Receiver, pred: impl FnMut(&HostStatus) -> bool, ) -> HostStatus { @@ -574,7 +687,9 @@ mod tests { .clone() } - async fn wait_session_end(ev: &mut broadcast::Receiver) -> ezd_host_core::EndReason { + pub(crate) async fn wait_session_end( + ev: &mut broadcast::Receiver, + ) -> ezd_host_core::EndReason { loop { if let HostEvent::SessionEnded(r) = timeout(WAIT, ev.recv()).await.unwrap().unwrap() { return r.unwrap().end; diff --git a/crates/ezd-host-service/src/status.rs b/crates/ezd-host-service/src/status.rs index e07d9dc..4b3a6b5 100644 --- a/crates/ezd-host-service/src/status.rs +++ b/crates/ezd-host-service/src/status.rs @@ -4,6 +4,7 @@ use crate::error::ServiceError; use ezd_host_core::{LiveStats, SessionSummary}; use ezd_proto::{DynamicRange, InputStatus, StreamConfig}; use std::net::SocketAddr; +use std::time::Instant; /// What the service is doing, see [`HostService::status`](crate::HostService::status). // One live session at a time, so the size of the variant does not matter. @@ -39,6 +40,33 @@ pub struct LiveSession { pub stats: Option, /// Latest input status reported to the client. pub input: Option, + /// How the client reached the host. + pub transport: Transport, +} + +/// How a client reached the host. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Transport { + /// The plaintext TCP listener (USB through `adb reverse`, or loopback). + #[default] + Tcp, + /// Wi-Fi: QUIC with a paired device. + Wifi, +} + +/// The Wi-Fi listener, see [`HostService::wifi`](crate::HostService::wifi). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WifiInfo { + /// UDP address being listened on. + pub addr: SocketAddr, + /// Host certificate fingerprint, lower-case hex. + pub fingerprint: String, + /// Host certificate fingerprint in the short form people compare. + pub fingerprint_short: String, + /// Name announced to clients and on the network. + pub host_name: String, + /// Whether a pairing window is open. + pub pairing_open: bool, } /// An adb device. @@ -78,4 +106,61 @@ pub enum HostEvent { SourceFailed(ServiceError), /// A session ended; `Err` carries the failure text. SessionEnded(Result), + /// A pairing window opened (also when it is reopened with a new PIN). + PairingOpen { + /// The PIN to type on the tablet. + pin: String, + /// The `ezd://pair?...` URI for the QR code (it carries the PIN). + uri: String, + /// Short form of the host fingerprint, for people to compare. + fingerprint: String, + /// When the window closes by itself. + expires: Instant, + }, + /// The pairing window closed. + PairingClosed { + /// Why. + reason: PairingCloseReason, + }, + /// A device paired. + Paired { + /// Name the device announced. + device: String, + }, + /// A pairing attempt failed (wrong PIN, window closed, broken connection). + PairingFailed { + /// The client. + peer: SocketAddr, + /// English description, for logs. + reason: String, + }, + /// A Wi-Fi client was turned away. + SessionRefused { + /// The client. + peer: SocketAddr, + /// Why. + why: RefusedWhy, + }, +} + +/// Why a pairing window closed. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PairingCloseReason { + /// Closed on request. + Closed, + /// A device paired. + Paired, + /// Too many wrong PINs. + TooManyAttempts, + /// The time ran out. + Expired, +} + +/// Why a Wi-Fi session request was refused. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum RefusedWhy { + /// The device is not paired. + NotPaired, + /// Another session is running. + Busy, } diff --git a/crates/ezd-host-service/src/store.rs b/crates/ezd-host-service/src/store.rs new file mode 100644 index 0000000..a58927f --- /dev/null +++ b/crates/ezd-host-service/src/store.rs @@ -0,0 +1,346 @@ +//! The host's pairing data: the identity certificate and the list of paired devices. +//! +//! `paired.json` is a JSON array of [`PairedDevice`]. Times are Unix seconds (UTC). The file is +//! the source of truth and is read on every call, so `ezd-host paired forget` takes effect in a +//! running service. A file that does not parse is an error, never silently replaced: the +//! owner must fix or delete it. + +use ezd_link::identity::{fingerprint_hex, parse_fingerprint, write_atomic}; +use ezd_link::pair::PairedClient; +use ezd_proto::pair::Fingerprint; +use serde::{Deserialize, Serialize}; +use std::io; +use std::path::{Path, PathBuf}; +use std::sync::Mutex; +use std::time::{SystemTime, UNIX_EPOCH}; + +/// Name of the paired-devices file inside the config directory. +pub const PAIRED_FILE: &str = "paired.json"; + +/// The default config directory: `ezdisplay` inside the user's config directory. +pub fn default_config_dir() -> Option { + dirs::config_dir().map(|d| d.join("ezdisplay")) +} + +/// Seconds since the Unix epoch. +pub fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_secs()) +} + +/// A device allowed to start sessions. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct PairedDevice { + /// Name the device announced when it paired. + pub name: String, + /// Certificate fingerprint, lower-case hex. + pub fingerprint: String, + /// When it paired, Unix seconds. + pub paired_at: u64, + /// When it last started a session, Unix seconds. + pub last_seen: Option, +} + +/// Why the store cannot be used. +#[derive(Debug, thiserror::Error)] +pub enum StoreError { + /// The file could not be read or written. + #[error("{}: {source}", path.display())] + Io { + /// The file. + path: PathBuf, + /// The OS error. + source: io::Error, + }, + /// The file is not a valid list of devices; it was left untouched. + #[error("{} is corrupt: {reason}", path.display())] + Corrupt { + /// The file. + path: PathBuf, + /// What is wrong with it. + reason: String, + }, +} + +/// Why a device could not be forgotten. +#[derive(Debug, thiserror::Error)] +pub enum ForgetError { + /// Nothing matches the name or fingerprint. + #[error("no paired device matches")] + NotFound, + /// More than one device matches; use more of the fingerprint. + #[error("{0} paired devices match")] + Ambiguous(usize), + /// The store is unusable. + #[error(transparent)] + Store(#[from] StoreError), +} + +/// The paired devices of a config directory. +#[derive(Debug)] +pub struct PairedStore { + path: PathBuf, + /// Serializes read-modify-write cycles inside this process. + lock: Mutex<()>, +} + +impl PairedStore { + /// The store in `dir`; the file is created by the first pairing. + pub fn new(dir: &Path) -> PairedStore { + PairedStore { + path: dir.join(PAIRED_FILE), + lock: Mutex::new(()), + } + } + + /// Where the list is kept. + pub fn path(&self) -> &Path { + &self.path + } + + fn io_err(&self, source: io::Error) -> StoreError { + StoreError::Io { + path: self.path.clone(), + source, + } + } + + fn read(&self) -> Result, StoreError> { + let data = match std::fs::read(&self.path) { + Ok(d) => d, + Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(e) => return Err(self.io_err(e)), + }; + let corrupt = |reason: String| StoreError::Corrupt { + path: self.path.clone(), + reason, + }; + let devices: Vec = + serde_json::from_slice(&data).map_err(|e| corrupt(e.to_string()))?; + if let Some(d) = devices + .iter() + .find(|d| parse_fingerprint(&d.fingerprint).is_none()) + { + return Err(corrupt(format!("invalid fingerprint for {:?}", d.name))); + } + Ok(devices) + } + + fn write(&self, devices: &[PairedDevice]) -> Result<(), StoreError> { + if let Some(dir) = self.path.parent() { + std::fs::create_dir_all(dir).map_err(|e| self.io_err(e))?; + } + let json = serde_json::to_vec_pretty(devices).expect("devices serialize"); + write_atomic(&self.path, &json).map_err(|e| self.io_err(e)) + } + + fn guard(&self) -> std::sync::MutexGuard<'_, ()> { + self.lock.lock().unwrap_or_else(|e| e.into_inner()) + } + + /// Every paired device, oldest first. A missing file is an empty list. + pub fn list(&self) -> Result, StoreError> { + let _g = self.guard(); + self.read() + } + + /// True if a device with this fingerprint is paired. + pub fn is_paired(&self, fp: &Fingerprint) -> Result { + let hex = fingerprint_hex(fp); + Ok(self.list()?.iter().any(|d| d.fingerprint == hex)) + } + + /// Adds a device, or replaces the one with the same fingerprint (new name, new pairing + /// time, `last_seen` cleared). + pub fn add(&self, client: &PairedClient) -> Result<(), StoreError> { + let _g = self.guard(); + let mut devices = self.read()?; + let hex = fingerprint_hex(&client.fingerprint); + devices.retain(|d| d.fingerprint != hex); + devices.push(PairedDevice { + name: client.name.clone(), + fingerprint: hex, + paired_at: now_secs(), + last_seen: None, + }); + self.write(&devices) + } + + /// Records that the device started a session now. Unknown devices are ignored. + pub fn touch(&self, fp: &Fingerprint) -> Result<(), StoreError> { + let _g = self.guard(); + let mut devices = self.read()?; + let hex = fingerprint_hex(fp); + let Some(d) = devices.iter_mut().find(|d| d.fingerprint == hex) else { + return Ok(()); + }; + d.last_seen = Some(now_secs()); + self.write(&devices) + } + + /// Removes the device whose name (any case) equals `query`, or whose fingerprint is + /// `query` in hex or in the short dashed form, in full or as a prefix of at least 4 digits. + /// A name wins over a fingerprint prefix. + pub fn forget(&self, query: &str) -> Result { + let _g = self.guard(); + let mut devices = self.read()?; + let query = query.trim(); + let mut hits: Vec = (0..devices.len()) + .filter(|&i| devices[i].name.eq_ignore_ascii_case(query)) + .collect(); + if hits.is_empty() { + let prefix: String = query + .chars() + .filter(|c| *c != '-') + .collect::() + .to_ascii_lowercase(); + if prefix.len() >= 4 && prefix.chars().all(|c| c.is_ascii_hexdigit()) { + hits = (0..devices.len()) + .filter(|&i| devices[i].fingerprint.starts_with(&prefix)) + .collect(); + } + } + match hits.as_slice() { + [] => Err(ForgetError::NotFound), + [i] => { + let gone = devices.remove(*i); + self.write(&devices)?; + Ok(gone) + } + more => Err(ForgetError::Ambiguous(more.len())), + } + } +} + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + + /// A unique directory removed on drop. + pub(crate) struct TempDir(pub PathBuf); + + impl TempDir { + pub(crate) fn new(tag: &str) -> TempDir { + static N: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0); + let n = N.fetch_add(1, std::sync::atomic::Ordering::Relaxed); + let dir = std::env::temp_dir() + .join(format!("ezd-host-service-{tag}-{}-{n}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + TempDir(dir) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn client(name: &str, b: u8) -> PairedClient { + PairedClient { + fingerprint: [b; 32], + name: name.into(), + } + } + + #[test] + fn missing_file_is_empty_and_add_round_trips() { + let dir = TempDir::new("store-rt"); + let store = PairedStore::new(&dir.0.join("nested")); + assert!(store.list().unwrap().is_empty()); + assert!(!store.is_paired(&[1; 32]).unwrap()); + store.add(&client("Tab S9", 1)).unwrap(); + store.add(&client("Pixel", 2)).unwrap(); + let list = store.list().unwrap(); + assert_eq!(list.len(), 2); + assert_eq!(list[0].name, "Tab S9"); + assert_eq!(list[0].fingerprint, "01".repeat(32)); + assert_eq!(list[0].last_seen, None); + assert!(list[0].paired_at > 1_600_000_000); + assert!(store.is_paired(&[2; 32]).unwrap()); + // A second handle (another process) sees the same data. + assert_eq!( + PairedStore::new(&dir.0.join("nested")).list().unwrap(), + list + ); + } + + #[test] + fn adding_the_same_fingerprint_replaces() { + let dir = TempDir::new("store-replace"); + let store = PairedStore::new(&dir.0); + store.add(&client("old", 1)).unwrap(); + store.touch(&[1; 32]).unwrap(); + assert!(store.list().unwrap()[0].last_seen.is_some()); + store.add(&client("new", 1)).unwrap(); + let list = store.list().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!((list[0].name.as_str(), list[0].last_seen), ("new", None)); + } + + #[test] + fn touch_sets_last_seen_and_ignores_unknown() { + let dir = TempDir::new("store-touch"); + let store = PairedStore::new(&dir.0); + store.touch(&[9; 32]).unwrap(); + assert!(!store.path().exists()); + store.add(&client("a", 1)).unwrap(); + store.touch(&[1; 32]).unwrap(); + assert!(store.list().unwrap()[0].last_seen.is_some()); + } + + #[test] + fn forget_by_name_hex_and_short_prefix() { + let dir = TempDir::new("store-forget"); + let store = PairedStore::new(&dir.0); + store.add(&client("Tab S9", 0xab)).unwrap(); + store.add(&client("Pixel", 0xcd)).unwrap(); + store.add(&client("Other", 0xcf)).unwrap(); + assert_eq!(store.forget("tab s9").unwrap().name, "Tab S9"); + assert_eq!(store.forget(&"cd".repeat(32)).unwrap().name, "Pixel"); + assert!(matches!(store.forget("nobody"), Err(ForgetError::NotFound))); + assert!(matches!(store.forget("ab"), Err(ForgetError::NotFound))); + assert_eq!(store.forget("cfcf-cfcf").unwrap().name, "Other"); + assert!(store.list().unwrap().is_empty()); + } + + #[test] + fn forget_refuses_an_ambiguous_prefix() { + let dir = TempDir::new("store-ambiguous"); + let store = PairedStore::new(&dir.0); + let mut a = client("a", 0); + a.fingerprint[31] = 1; + let mut b = client("b", 0); + b.fingerprint[31] = 2; + store.add(&a).unwrap(); + store.add(&b).unwrap(); + assert!(matches!( + store.forget("0000"), + Err(ForgetError::Ambiguous(2)) + )); + assert_eq!(store.list().unwrap().len(), 2); + } + + #[test] + fn a_corrupt_file_is_an_error_and_is_never_overwritten() { + let dir = TempDir::new("store-corrupt"); + let store = PairedStore::new(&dir.0); + for bad in [ + "not json".to_string(), + r#"[{"name":"x","fingerprint":"zz","paired_at":1,"last_seen":null}]"#.to_string(), + ] { + std::fs::write(store.path(), &bad).unwrap(); + assert!(matches!(store.list(), Err(StoreError::Corrupt { .. }))); + assert!(store.is_paired(&[1; 32]).is_err()); + assert!(store.add(&client("a", 1)).is_err()); + assert!(store.touch(&[1; 32]).is_err()); + assert!(matches!( + store.forget("x"), + Err(ForgetError::Store(StoreError::Corrupt { .. })) + )); + assert_eq!(std::fs::read_to_string(store.path()).unwrap(), bad); + } + } +} diff --git a/crates/ezd-host-service/src/wifi.rs b/crates/ezd-host-service/src/wifi.rs new file mode 100644 index 0000000..f27609d --- /dev/null +++ b/crates/ezd-host-service/src/wifi.rs @@ -0,0 +1,763 @@ +//! The Wi-Fi side of the service: the QUIC accept loop, pairing and mDNS. +//! +//! Every incoming connection gets its own task, so a slow handshake or a pairing in progress +//! never delays the next client. Only the streaming session is exclusive, across both +//! transports (see `Inner::slot`). + +use crate::config::WifiConfig; +use crate::error::ServiceError; +use crate::mdns::Advertiser; +use crate::service::{Inner, finish_session, lock}; +use crate::status::{HostEvent, PairingCloseReason, RefusedWhy, Transport, WifiInfo}; +use crate::store::{PairedStore, default_config_dir}; +use ezd_link::identity::{Identity, fingerprint_hex, fingerprint_short}; +use ezd_link::pair::{CloseReason, PairUri, PairingWindow, WindowState, clean_name, host_pair}; +use ezd_link::quic::{Congestion, QuicIncoming, QuicServer}; +use ezd_proto::pair::{Fingerprint, Refusal}; +use std::net::{IpAddr, SocketAddr, UdpSocket}; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant}; +use tokio::sync::{Notify, watch}; +use tokio::task::JoinSet; + +/// Most connections handled at once (handshaking, pairing or streaming); the rest are refused. +const MAX_CONNECTIONS: usize = 8; +/// Time a client has to complete the handshake and say what it wants. +const OPEN_TIMEOUT: Duration = Duration::from_secs(10); + +/// Everything the Wi-Fi tasks share. +pub(crate) struct Wifi { + server: QuicServer, + store: PairedStore, + window: PairingWindow, + /// Wakes the pairing watcher after the window changed. + changed: Notify, + /// The window state last reported as an event: its PIN and deadline. + announced: Mutex>, + fingerprint: Fingerprint, + host_name: String, + bound: SocketAddr, + /// Address written into the pairing URI. + advertised: SocketAddr, + ttl: Duration, +} + +impl Wifi { + /// Loads the identity and the paired devices, binds the UDP socket and decides whether the + /// pairing window starts open. + pub(crate) fn setup( + handle: &tokio::runtime::Handle, + cfg: &WifiConfig, + ttl: Duration, + ) -> Result, ServiceError> { + let dir = cfg + .config_dir + .clone() + .or_else(default_config_dir) + .ok_or_else(|| ServiceError::Wifi("no config directory".into()))?; + let identity = Identity::load_or_create(&dir) + .map_err(|e| ServiceError::Wifi(format!("{}: {e}", dir.display())))?; + let store = PairedStore::new(&dir); + let paired = store + .list() + .map_err(|e| ServiceError::Wifi(e.to_string()))?; + let server = { + let _enter = handle.enter(); + QuicServer::bind(cfg.listen, &identity, congestion(cfg)) + } + .map_err(|e| ServiceError::Bind { + addr: cfg.listen, + reason: e.to_string(), + })?; + let bound = server.local_addr().map_err(|e| ServiceError::Bind { + addr: cfg.listen, + reason: e.to_string(), + })?; + let window = PairingWindow::default(); + if paired.is_empty() || cfg.pair_on_start { + window.open(ttl); + } + Ok(Arc::new(Wifi { + server, + store, + window, + changed: Notify::new(), + announced: Mutex::new(None), + fingerprint: identity.fingerprint(), + host_name: host_name(), + bound, + advertised: pick_lan_addr(bound, outbound_ip(bound)), + ttl, + })) + } + + pub(crate) fn info(&self) -> WifiInfo { + WifiInfo { + addr: self.bound, + fingerprint: fingerprint_hex(&self.fingerprint), + fingerprint_short: fingerprint_short(&self.fingerprint), + host_name: self.host_name.clone(), + pairing_open: self.window.is_open(), + } + } + + pub(crate) fn open_pairing(&self) -> String { + let pin = self.window.open(self.ttl); + self.changed.notify_one(); + pin + } + + pub(crate) fn refresh_pairing(&self) { + *lock(&self.announced) = None; + self.changed.notify_one(); + } + + pub(crate) fn close_pairing(&self) { + self.window.close(); + self.changed.notify_one(); + } + + /// Reports the window's changes since the last call as events. + fn sync(&self, inner: &Inner) { + let state = self.window.state(); + let mut last = lock(&self.announced); + match state { + WindowState::Open { pin, expires, .. } => { + if last.as_ref() == Some(&(pin.clone(), expires)) { + return; + } + *last = Some((pin.clone(), expires)); + let uri = PairUri { + addr: self.advertised, + fingerprint: self.fingerprint, + pin: pin.clone(), + name: self.host_name.clone(), + } + .to_uri(); + inner.wifi_info.send_modify(|i| { + if let Some(i) = i { + i.pairing_open = true; + } + }); + inner.emit(HostEvent::PairingOpen { + pin, + uri, + fingerprint: fingerprint_short(&self.fingerprint), + expires, + }); + } + WindowState::Closed(reason) => { + if last.take().is_none() { + return; + } + inner.wifi_info.send_modify(|i| { + if let Some(i) = i { + i.pairing_open = false; + } + }); + inner.emit(HostEvent::PairingClosed { + reason: match reason { + CloseReason::NotOpen => PairingCloseReason::Closed, + CloseReason::Paired => PairingCloseReason::Paired, + CloseReason::TooManyAttempts => PairingCloseReason::TooManyAttempts, + CloseReason::Expired => PairingCloseReason::Expired, + }, + }); + } + } + } +} + +fn congestion(cfg: &WifiConfig) -> Congestion { + cfg.congestion.into() +} + +/// The machine's name as shown to tablets. +fn host_name() -> String { + let name = clean_name(&gethostname::gethostname().to_string_lossy()); + if name.is_empty() { + "ezdisplay".into() + } else { + name + } +} + +/// The address the machine uses to reach the LAN, found by "connecting" a UDP socket: the +/// kernel picks the route and the source address, and nothing is sent. +fn outbound_ip(bound: SocketAddr) -> Option { + if !bound.ip().is_unspecified() { + return None; + } + let (local, probe): (SocketAddr, SocketAddr) = if bound.is_ipv4() { + ( + (std::net::Ipv4Addr::UNSPECIFIED, 0).into(), + ([192, 0, 2, 1], 9).into(), + ) + } else { + ( + (std::net::Ipv6Addr::UNSPECIFIED, 0).into(), + "[2001:db8::1]:9".parse().ok()?, + ) + }; + let sock = UdpSocket::bind(local).ok()?; + sock.connect(probe).ok()?; + let ip = sock.local_addr().ok()?.ip(); + (!ip.is_unspecified()).then_some(ip) +} + +/// The address to put in the pairing URI: a bound specific address as is; for an unspecified +/// one the LAN address (`outbound`), or the bound address when there is none. +fn pick_lan_addr(bound: SocketAddr, outbound: Option) -> SocketAddr { + match outbound { + Some(ip) if bound.ip().is_unspecified() && ip.is_ipv4() == bound.is_ipv4() => { + SocketAddr::new(ip, bound.port()) + } + _ => bound, + } +} + +async fn stopped(rx: &mut watch::Receiver) { + let _ = rx.wait_for(|v| *v).await; +} + +/// Reports pairing window changes, and its expiry on time. +pub(crate) async fn watch_pairing(inner: Arc, wifi: Arc) { + let mut stop = inner.stop.subscribe(); + loop { + if *stop.borrow() { + break; + } + wifi.sync(&inner); + let wait = match wifi.window.state() { + WindowState::Open { expires, .. } => { + expires.saturating_duration_since(Instant::now()) + Duration::from_millis(5) + } + WindowState::Closed(_) => Duration::from_secs(3600), + }; + tokio::select! { + () = wifi.changed.notified() => {} + () = tokio::time::sleep(wait) => {} + _ = stop.changed() => {} + } + } +} + +/// Accepts Wi-Fi clients until the service stops; waits for the sessions it started. +pub(crate) async fn serve(inner: Arc, wifi: Arc) { + let mut stop = inner.stop.subscribe(); + let advertiser = match Advertiser::start( + wifi.bound.port(), + &fingerprint_short(&wifi.fingerprint), + &wifi.host_name, + ) { + Ok(a) => Some(a), + Err(e) => { + tracing::warn!("mDNS advertisement not started: {e}"); + None + } + }; + tracing::info!(addr = %wifi.bound, "Wi-Fi listening"); + let mut tasks = JoinSet::new(); + loop { + if *stop.borrow() { + break; + } + tokio::select! { + incoming = wifi.server.accept_incoming() => { + let Some(incoming) = incoming else { break }; + if tasks.len() >= MAX_CONNECTIONS { + tracing::warn!(peer = %incoming.remote_address(), "too many connections, refusing"); + incoming.refuse(); + continue; + } + tasks.spawn(handle_incoming(inner.clone(), wifi.clone(), incoming, inner.stop.subscribe())); + } + Some(done) = tasks.join_next(), if !tasks.is_empty() => { + if let Err(e) = done { + tracing::error!("Wi-Fi connection task failed: {e}"); + } + } + _ = stop.changed() => break, + } + } + // Sessions end on their own (they got the stop signal and say Bye); the server stays up + // until they are done so that the Bye is delivered. + while let Some(done) = tasks.join_next().await { + if let Err(e) = done { + tracing::error!("Wi-Fi connection task failed: {e}"); + } + } + // Closing the endpoint discards what is still in flight, such as the last Bye. + wifi.server.wait_idle(Duration::from_secs(2)).await; + wifi.server.close(); + drop(advertiser); +} + +/// One client connection: handshake, then pairing or a session. +async fn handle_incoming( + inner: Arc, + wifi: Arc, + incoming: QuicIncoming, + mut stop: watch::Receiver, +) { + let peer = incoming.remote_address(); + let open = async { + let conn = incoming.handshake().await?; + conn.accept_open().await + }; + let opened = tokio::select! { + r = tokio::time::timeout(OPEN_TIMEOUT, open) => match r { + Ok(Ok(o)) => o, + Ok(Err(e)) => { + tracing::debug!(%peer, "connection dropped before its request: {e}"); + return; + } + Err(_) => { + tracing::debug!(%peer, "connection timed out before its request"); + return; + } + }, + () = stopped(&mut stop) => return, + }; + match opened.open { + ezd_proto::pair::LinkOpen::Session => session(&inner, &wifi, opened, peer, stop).await, + ezd_proto::pair::LinkOpen::Pair { .. } => pairing(&inner, &wifi, opened, peer, stop).await, + } +} + +async fn pairing( + inner: &Inner, + wifi: &Wifi, + opened: ezd_link::quic::Opened, + peer: SocketAddr, + mut stop: watch::Receiver, +) { + let result = tokio::select! { + r = host_pair(opened, &wifi.window, &wifi.host_name, |c| { + wifi.store.add(c).map_err(std::io::Error::other) + }) => r, + () = stopped(&mut stop) => return, + }; + wifi.changed.notify_one(); + match result { + Ok(client) => { + tracing::info!(%peer, device = %client.name, "device paired"); + inner.emit(HostEvent::Paired { + device: client.name, + }); + } + Err(e) => { + tracing::info!(%peer, "pairing failed: {e}"); + inner.emit(HostEvent::PairingFailed { + peer, + reason: e.to_string(), + }); + } + } +} + +async fn session( + inner: &Inner, + wifi: &Wifi, + opened: ezd_link::quic::Opened, + peer: SocketAddr, + mut stop: watch::Receiver, +) { + let refuse = |why: RefusedWhy, opened: ezd_link::quic::Opened| async move { + tracing::info!(%peer, ?why, "Wi-Fi session refused"); + inner.emit(HostEvent::SessionRefused { peer, why }); + opened + .refuse(match why { + RefusedWhy::NotPaired => Refusal::NotPaired, + RefusedWhy::Busy => Refusal::Busy, + }) + .await; + }; + let paired = match opened.peer_fingerprint() { + Some(fp) => match wifi.store.is_paired(&fp) { + Ok(p) => p.then_some(fp), + Err(e) => { + tracing::warn!("cannot read the paired devices: {e}"); + None + } + }, + None => None, + }; + let Some(fp) = paired else { + return refuse(RefusedWhy::NotPaired, opened).await; + }; + let Ok(permit) = inner.slot.clone().try_acquire_owned() else { + return refuse(RefusedWhy::Busy, opened).await; + }; + if let Err(e) = wifi.store.touch(&fp) { + tracing::warn!("cannot record the last use: {e}"); + } + tracing::info!(%peer, "Wi-Fi client connected"); + inner.emit(HostEvent::ClientConnected(peer)); + let cfg = inner.cfg.borrow().clone(); + // The source first: the client only gets its answer once the host can stream. + let source = match (inner.hooks.create_source)(&cfg) { + Ok(s) => s, + Err(e) => { + tracing::warn!("cannot create virtual source: {e}"); + inner.emit(HostEvent::SourceFailed(e.clone())); + inner.update(|st| st.phase = crate::service::Phase::Error(e)); + // The client retries; "busy" is the closest answer the protocol has. + opened.refuse(Refusal::Busy).await; + return; + } + }; + let link = match opened.accept_session().await { + Ok(l) => l, + Err(e) => { + tracing::warn!(%peer, "cannot start the Wi-Fi session: {e}"); + return; + } + }; + finish_session(inner, &cfg, link, Transport::Wifi, source, &mut stop).await; + drop(permit); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::{AdbMode, ServiceConfig}; + use crate::service::tests::{cfg, handshake, hooks, wait_session_end, wait_status}; + use crate::service::{HostService, ServiceHooks}; + use crate::status::HostStatus; + use crate::store::tests::TempDir; + use ezd_link::identity::parse_fingerprint; + use ezd_link::pair::{PairedClient, pair}; + use ezd_link::quic::{QuicError, connect}; + use ezd_proto::{Bye, Message}; + use tokio::sync::broadcast; + use tokio::time::timeout; + + const WAIT: Duration = Duration::from_secs(10); + + fn wifi_cfg(dir: &TempDir, pair_on_start: bool) -> ServiceConfig { + ServiceConfig { + adb: AdbMode::Off, + wifi: Some(WifiConfig { + listen: "127.0.0.1:0".parse().unwrap(), + pair_on_start, + config_dir: Some(dir.0.clone()), + ..WifiConfig::default() + }), + ..cfg() + } + } + + fn start(cfg: ServiceConfig, hooks: ServiceHooks) -> HostService { + HostService::start_with(&tokio::runtime::Handle::current(), cfg, hooks).unwrap() + } + + fn host_fp(svc: &HostService) -> (SocketAddr, Fingerprint) { + let info = svc.wifi().borrow().clone().unwrap(); + (info.addr, parse_fingerprint(&info.fingerprint).unwrap()) + } + + fn seed(dir: &TempDir, id: &Identity, name: &str) { + PairedStore::new(&dir.0) + .add(&PairedClient { + fingerprint: id.fingerprint(), + name: name.into(), + }) + .unwrap(); + } + + async fn next_event( + ev: &mut broadcast::Receiver, + mut pick: impl FnMut(HostEvent) -> Option, + ) -> T { + timeout(WAIT, async { + loop { + if let Some(v) = pick(ev.recv().await.unwrap()) { + return v; + } + } + }) + .await + .unwrap() + } + + async fn session_link( + addr: SocketAddr, + id: &Identity, + fp: Fingerprint, + ) -> Result { + connect(addr, id, Some(fp), Congestion::Cubic) + .await? + .open_session() + .await + } + + #[tokio::test] + async fn pairs_through_the_service_then_streams_without_a_pin() { + let dir = TempDir::new("wifi-pair"); + let svc = start(wifi_cfg(&dir, false), hooks()); + let mut events = svc.events(); + let mut status = svc.status(); + let (addr, fp) = host_fp(&svc); + // The store is empty: the window is open from the start. + let (pin, uri) = next_event(&mut events, |e| match e { + HostEvent::PairingOpen { pin, uri, .. } => Some((pin, uri)), + _ => None, + }) + .await; + let parsed = PairUri::parse(&uri).unwrap(); + assert_eq!( + (parsed.pin.as_str(), parsed.fingerprint), + (pin.as_str(), fp) + ); + + let id = Identity::generate().unwrap(); + let conn = connect(addr, &id, None, Congestion::Cubic).await.unwrap(); + let host = pair(conn, &pin, "Tab S9").await.unwrap(); + assert_eq!(host.fingerprint, fp); + let device = next_event(&mut events, |e| match e { + HostEvent::Paired { device } => Some(device), + _ => None, + }) + .await; + assert_eq!(device, "Tab S9"); + let reason = next_event(&mut events, |e| match e { + HostEvent::PairingClosed { reason } => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, PairingCloseReason::Paired); + assert!(!svc.wifi().borrow().as_ref().unwrap().pairing_open); + assert_eq!(PairedStore::new(&dir.0).list().unwrap()[0].name, "Tab S9"); + + // A later connection needs no PIN. + let link = session_link(addr, &id, fp).await.unwrap(); + let (tx, _rx) = handshake(link).await; + let HostStatus::Streaming(live) = + wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await + else { + unreachable!() + }; + assert_eq!( + (live.transport, live.device_name.as_str()), + (Transport::Wifi, "tablet") + ); + assert_eq!(live.stream.width, 1280); + assert!( + PairedStore::new(&dir.0).list().unwrap()[0] + .last_seen + .is_some() + ); + tx.send_control(Message::Bye(Bye { + reason: "done".into(), + })) + .unwrap(); + assert_eq!( + wait_session_end(&mut events).await, + ezd_host_core::EndReason::ClientBye("done".into()) + ); + wait_status(&mut status, |s| matches!(s, HostStatus::Waiting { .. })).await; + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn an_unpaired_client_is_refused_when_no_window_is_open() { + let dir = TempDir::new("wifi-unpaired"); + seed(&dir, &Identity::generate().unwrap(), "someone else"); + let svc = start(wifi_cfg(&dir, false), hooks()); + let mut events = svc.events(); + let (addr, fp) = host_fp(&svc); + assert!(!svc.wifi().borrow().as_ref().unwrap().pairing_open); + let id = Identity::generate().unwrap(); + let err = session_link(addr, &id, fp).await.unwrap_err(); + assert!( + matches!(err, QuicError::Refused(Refusal::NotPaired)), + "{err:?}" + ); + let why = next_event(&mut events, |e| match e { + HostEvent::SessionRefused { why, .. } => Some(why), + _ => None, + }) + .await; + assert_eq!(why, RefusedWhy::NotPaired); + // Pairing is refused too, with the window closed. + let conn = connect(addr, &id, None, Congestion::Cubic).await.unwrap(); + let err = pair(conn, "123456", "x").await.unwrap_err(); + assert!( + matches!(err, QuicError::Refused(Refusal::PairingClosed)), + "{err:?}" + ); + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn a_second_client_is_busy_while_one_streams() { + let dir = TempDir::new("wifi-busy"); + let (a, b) = (Identity::generate().unwrap(), Identity::generate().unwrap()); + seed(&dir, &a, "A"); + seed(&dir, &b, "B"); + let svc = start(wifi_cfg(&dir, false), hooks()); + let mut events = svc.events(); + let mut status = svc.status(); + let (addr, fp) = host_fp(&svc); + let (tx, _rx) = handshake(session_link(addr, &a, fp).await.unwrap()).await; + wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await; + + let err = session_link(addr, &b, fp).await.unwrap_err(); + assert!(matches!(err, QuicError::Refused(Refusal::Busy)), "{err:?}"); + let why = next_event(&mut events, |e| match e { + HostEvent::SessionRefused { why, .. } => Some(why), + _ => None, + }) + .await; + assert_eq!(why, RefusedWhy::Busy); + // The first session is untouched. + assert!(matches!(*status.borrow(), HostStatus::Streaming(_))); + + // A TCP client waits for the Wi-Fi session instead of starting a second one. + let tcp = tokio::spawn(crate::service::tests::connect(svc.local_addr().unwrap())); + tokio::time::sleep(Duration::from_millis(300)).await; + assert!(!tcp.is_finished()); + tx.send_control(Message::Bye(Bye { + reason: "done".into(), + })) + .unwrap(); + let (_tcp_tx, _tcp_rx) = timeout(WAIT, tcp).await.unwrap().unwrap(); + let HostStatus::Streaming(live) = wait_status( + &mut status, + |s| matches!(s, HostStatus::Streaming(l) if l.transport == Transport::Tcp), + ) + .await + else { + unreachable!() + }; + assert_eq!(live.transport, Transport::Tcp); + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn pairing_can_be_opened_and_closed_and_expires() { + let dir = TempDir::new("wifi-window"); + seed(&dir, &Identity::generate().unwrap(), "someone else"); + let svc = start( + wifi_cfg(&dir, false), + ServiceHooks { + pairing_ttl: Duration::from_millis(300), + ..hooks() + }, + ); + let mut events = svc.events(); + let pin = svc.open_pairing().unwrap(); + let opened = next_event(&mut events, |e| match e { + HostEvent::PairingOpen { pin, .. } => Some(pin), + _ => None, + }) + .await; + assert_eq!(opened, pin); + assert!(svc.wifi().borrow().as_ref().unwrap().pairing_open); + // It closes by itself when the time runs out. + let reason = next_event(&mut events, |e| match e { + HostEvent::PairingClosed { reason } => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, PairingCloseReason::Expired); + + svc.open_pairing().unwrap(); + next_event(&mut events, |e| { + matches!(e, HostEvent::PairingOpen { .. }).then_some(()) + }) + .await; + svc.close_pairing(); + let reason = next_event(&mut events, |e| match e { + HostEvent::PairingClosed { reason } => Some(reason), + _ => None, + }) + .await; + assert_eq!(reason, PairingCloseReason::Closed); + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn pair_on_start_opens_the_window_even_with_a_paired_device() { + let dir = TempDir::new("wifi-pair-on-start"); + seed(&dir, &Identity::generate().unwrap(), "someone else"); + let svc = start(wifi_cfg(&dir, true), hooks()); + let wifi = svc.wifi(); + assert!(wifi.borrow().as_ref().unwrap().pairing_open); + timeout(WAIT, svc.stop()).await.unwrap(); + assert!(wifi.borrow().is_none()); + } + + #[tokio::test] + async fn a_corrupt_paired_file_stops_the_start() { + let dir = TempDir::new("wifi-corrupt"); + std::fs::write(dir.0.join(crate::store::PAIRED_FILE), "garbage").unwrap(); + let r = HostService::start_with( + &tokio::runtime::Handle::current(), + wifi_cfg(&dir, false), + hooks(), + ); + assert!(matches!(r, Err(ServiceError::Wifi(m)) if m.contains("corrupt"))); + assert_eq!( + std::fs::read_to_string(dir.0.join(crate::store::PAIRED_FILE)).unwrap(), + "garbage" + ); + } + + #[tokio::test] + async fn stop_ends_a_wifi_session_with_bye() { + let dir = TempDir::new("wifi-stop"); + let id = Identity::generate().unwrap(); + seed(&dir, &id, "A"); + let svc = start(wifi_cfg(&dir, false), hooks()); + let mut status = svc.status(); + let mut events = svc.events(); + let (addr, fp) = host_fp(&svc); + let (_tx, mut rx) = handshake(session_link(addr, &id, fp).await.unwrap()).await; + wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await; + timeout(WAIT, svc.stop()).await.unwrap(); + assert_eq!( + wait_session_end(&mut events).await, + ezd_host_core::EndReason::HostShutdown + ); + // The connection outlives the session long enough to deliver the Bye. + let bye = timeout(WAIT, async { + while let Ok(Some(m)) = rx.recv().await { + if matches!(m, Message::Bye(_)) { + return true; + } + } + false + }) + .await + .unwrap(); + assert!(bye, "the client never got the Bye"); + } + + #[test] + fn lan_address_replaces_an_unspecified_bind() { + let any: SocketAddr = "0.0.0.0:27183".parse().unwrap(); + let lan: IpAddr = "192.168.1.20".parse().unwrap(); + assert_eq!( + pick_lan_addr(any, Some(lan)), + "192.168.1.20:27183".parse().unwrap() + ); + // No route: keep what was bound. + assert_eq!(pick_lan_addr(any, None), any); + // A wrong family is not used. + assert_eq!(pick_lan_addr(any, Some("fe80::1".parse().unwrap())), any); + // A specific bind is never replaced. + let loopback: SocketAddr = "127.0.0.1:4000".parse().unwrap(); + assert_eq!(pick_lan_addr(loopback, Some(lan)), loopback); + assert_eq!(outbound_ip(loopback), None); + } + + #[test] + fn the_outbound_probe_does_not_return_an_unspecified_address() { + // Without a network the probe finds nothing, which is fine. + if let Some(ip) = outbound_ip("0.0.0.0:1".parse().unwrap()) { + assert!(!ip.is_unspecified() && ip.is_ipv4()); + } + } +} diff --git a/crates/ezd-host/Cargo.toml b/crates/ezd-host/Cargo.toml index e584353..bcc31f6 100644 --- a/crates/ezd-host/Cargo.toml +++ b/crates/ezd-host/Cargo.toml @@ -13,12 +13,15 @@ name = "ezd-host" path = "src/main.rs" [features] -default = ["ffmpeg"] +default = ["ffmpeg", "wifi"] # Encoder probing in `diag` and the service's FFmpeg paths. `--no-default-features` builds without # FFmpeg headers (the Windows cross-check in CI). ffmpeg = ["dep:ezd-ffmpeg", "ezd-host-service/ffmpeg", "ezd-host-windows/ffmpeg"] +# Wi-Fi (QUIC) transport: `run --wifi`, `--pair` and the `paired` commands. +wifi = ["ezd-host-service/wifi", "dep:qrcode"] [dependencies] +qrcode = { workspace = true, optional = true } anyhow.workspace = true clap.workspace = true ezd-ffmpeg = { workspace = true, optional = true } diff --git a/crates/ezd-host/i18n/de/ezd-host.ftl b/crates/ezd-host/i18n/de/ezd-host.ftl index 0dce6c6..db19747 100644 --- a/crates/ezd-host/i18n/de/ezd-host.ftl +++ b/crates/ezd-host/i18n/de/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` ist keine Zahl err-scale-range = Der Maßstab muss zwischen 0,25 und 1,0 liegen, erhalten: { $value } err-no-backend = kein Backend für virtuelle Bildschirme auf dieser Plattform err-source = Die Videoquelle konnte nicht erstellt werden: { $reason } + +cmd-paired = Listet die per WLAN gekoppelten Tablets auf oder entfernt sie. +paired-list = Listet die gekoppelten Tablets auf. +paired-forget = Entfernt ein gekoppeltes Tablet; es muss erneut gekoppelt werden, um zu streamen. +paired-forget-target = Name des Tablets oder sein Fingerabdruck (ganz oder die ersten Stellen, etwa `3f2a-91c0`). +run-wifi = Nimmt zusätzlich per WLAN gekoppelte Tablets an (QUIC über UDP) auf ADDR (Standard 0.0.0.0:27183). Beim ersten Mal werden eine PIN und ein QR-Code zum Koppeln eines Tablets angezeigt. +run-pair = Öffnet das Kopplungsfenster beim Start, auch wenn schon ein Tablet gekoppelt ist (erfordert `--wifi`). + +paired-none = Keine Tablets gekoppelt. +paired-never = nie +paired-col-name = NAME +paired-col-fingerprint = FINGERABDRUCK +paired-col-paired = GEKOPPELT (UTC) +paired-col-last-seen = ZULETZT GENUTZT (UTC) +paired-forgot = { $name } ({ $fingerprint }) wurde entfernt. +pair-open = Die Kopplung ist offen. Scanne auf dem Tablet diesen QR-Code oder gib die PIN ein: +pair-pin = PIN: { $pin } +pair-fingerprint = Fingerabdruck des Hosts: { $fingerprint } +pair-expires = Läuft in { $seconds } s ab. +pair-done = Mit { $device } gekoppelt. +pair-closed = Die Kopplung ist geschlossen. +pair-closed-paired = Die Kopplung ist geschlossen: Ein Tablet wurde gekoppelt. +pair-closed-attempts = Die Kopplung ist geschlossen: zu viele falsche PINs. +pair-closed-expired = Die Kopplung ist geschlossen: Die Zeit ist abgelaufen. Starte mit `--pair` neu, um erneut zu koppeln. +wifi-listening = WLAN: lauscht auf { $addr } (UDP). Fingerabdruck des Hosts: { $fingerprint } +wifi-firewall-hint = Wenn sich Tablets nicht verbinden können, erlaube eingehenden UDP-Port { $port } in der Windows-Firewall (private Netzwerke). +err-paired-not-found = kein gekoppeltes Tablet passt zu `{ $query }` +err-paired-ambiguous = { $count } gekoppelte Tablets passen zu `{ $query }`; gib mehr Stellen des Fingerabdrucks an +err-no-config-dir = Konfigurationsordner nicht gefunden +err-wifi = WLAN: { $reason } diff --git a/crates/ezd-host/i18n/en/ezd-host.ftl b/crates/ezd-host/i18n/en/ezd-host.ftl index 2765a21..8b7a570 100644 --- a/crates/ezd-host/i18n/en/ezd-host.ftl +++ b/crates/ezd-host/i18n/en/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` is not a number err-scale-range = scale must be between 0.25 and 1.0, got { $value } err-no-backend = no virtual display backend for this platform err-source = could not create the video source: { $reason } + +cmd-paired = List or forget the tablets paired over Wi-Fi. +paired-list = List the paired tablets. +paired-forget = Forget a paired tablet; it must pair again to stream. +paired-forget-target = Name of the tablet, or its fingerprint (all of it, or its first digits such as `3f2a-91c0`). +run-wifi = Also accept paired tablets over Wi-Fi (QUIC on UDP) on ADDR (default 0.0.0.0:27183). The first run shows a PIN and a QR code to pair a tablet. +run-pair = Open the pairing window at start even if a tablet is already paired (needs `--wifi`). + +paired-none = No tablets are paired. +paired-never = never +paired-col-name = NAME +paired-col-fingerprint = FINGERPRINT +paired-col-paired = PAIRED (UTC) +paired-col-last-seen = LAST SEEN (UTC) +paired-forgot = Forgot { $name } ({ $fingerprint }). +pair-open = Pairing is open. On the tablet, scan this QR code or type the PIN: +pair-pin = PIN: { $pin } +pair-fingerprint = Host fingerprint: { $fingerprint } +pair-expires = Expires in { $seconds } s. +pair-done = Paired with { $device }. +pair-closed = Pairing is closed. +pair-closed-paired = Pairing is closed: a tablet paired. +pair-closed-attempts = Pairing is closed: too many wrong PINs. +pair-closed-expired = Pairing is closed: time ran out. Restart with `--pair` to pair again. +wifi-listening = Wi-Fi: listening on { $addr } (UDP). Host fingerprint: { $fingerprint } +wifi-firewall-hint = If tablets cannot connect, allow inbound UDP port { $port } in Windows Firewall (private networks). +err-paired-not-found = no paired tablet matches `{ $query }` +err-paired-ambiguous = { $count } paired tablets match `{ $query }`; use more of the fingerprint +err-no-config-dir = cannot find the config folder +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-host/i18n/es/ezd-host.ftl b/crates/ezd-host/i18n/es/ezd-host.ftl index 14e4ce0..a0d5e4b 100644 --- a/crates/ezd-host/i18n/es/ezd-host.ftl +++ b/crates/ezd-host/i18n/es/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` no es un número err-scale-range = la escala debe estar entre 0,25 y 1,0, se recibió { $value } err-no-backend = no hay backend de pantalla virtual para esta plataforma err-source = no se pudo crear la fuente de video: { $reason } + +cmd-paired = Lista o elimina las tabletas vinculadas por Wi-Fi. +paired-list = Lista las tabletas vinculadas. +paired-forget = Elimina una tableta vinculada; tendrá que vincularse de nuevo para transmitir. +paired-forget-target = Nombre de la tableta, o su huella (completa o sus primeros dígitos, como `3f2a-91c0`). +run-wifi = Acepta además tabletas vinculadas por Wi-Fi (QUIC sobre UDP) en ADDR (por defecto 0.0.0.0:27183). La primera vez muestra un PIN y un código QR para vincular una tableta. +run-pair = Abre la ventana de vinculación al iniciar aunque ya haya una tableta vinculada (requiere `--wifi`). + +paired-none = No hay tabletas vinculadas. +paired-never = nunca +paired-col-name = NOMBRE +paired-col-fingerprint = HUELLA +paired-col-paired = VINCULADA (UTC) +paired-col-last-seen = ÚLTIMO USO (UTC) +paired-forgot = Se eliminó { $name } ({ $fingerprint }). +pair-open = La vinculación está abierta. En la tableta, escaneá este código QR o escribí el PIN: +pair-pin = PIN: { $pin } +pair-fingerprint = Huella del host: { $fingerprint } +pair-expires = Vence en { $seconds } s. +pair-done = Vinculada con { $device }. +pair-closed = La vinculación está cerrada. +pair-closed-paired = La vinculación está cerrada: una tableta se vinculó. +pair-closed-attempts = La vinculación está cerrada: demasiados PIN incorrectos. +pair-closed-expired = La vinculación está cerrada: se acabó el tiempo. Reiniciá con `--pair` para vincular de nuevo. +wifi-listening = Wi-Fi: escuchando en { $addr } (UDP). Huella del host: { $fingerprint } +wifi-firewall-hint = Si las tabletas no pueden conectarse, permití el puerto UDP { $port } de entrada en el Firewall de Windows (redes privadas). +err-paired-not-found = ninguna tableta vinculada coincide con `{ $query }` +err-paired-ambiguous = { $count } tabletas vinculadas coinciden con `{ $query }`; usá más dígitos de la huella +err-no-config-dir = no se encontró la carpeta de configuración +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-host/i18n/fr/ezd-host.ftl b/crates/ezd-host/i18n/fr/ezd-host.ftl index 2c7617b..0ac8471 100644 --- a/crates/ezd-host/i18n/fr/ezd-host.ftl +++ b/crates/ezd-host/i18n/fr/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` n'est pas un nombre err-scale-range = l'échelle doit être comprise entre 0,25 et 1,0, reçu { $value } err-no-backend = aucun backend d'affichage virtuel pour cette plateforme err-source = impossible de créer la source vidéo : { $reason } + +cmd-paired = Liste ou oublie les tablettes appairées en Wi-Fi. +paired-list = Liste les tablettes appairées. +paired-forget = Oublie une tablette appairée ; elle devra être appairée à nouveau pour diffuser. +paired-forget-target = Nom de la tablette, ou son empreinte (entière, ou ses premiers chiffres comme `3f2a-91c0`). +run-wifi = Accepte aussi les tablettes appairées en Wi-Fi (QUIC sur UDP) sur ADDR (par défaut 0.0.0.0:27183). La première fois, affiche un code PIN et un QR code pour appairer une tablette. +run-pair = Ouvre la fenêtre d'appairage au démarrage même si une tablette est déjà appairée (nécessite `--wifi`). + +paired-none = Aucune tablette n'est appairée. +paired-never = jamais +paired-col-name = NOM +paired-col-fingerprint = EMPREINTE +paired-col-paired = APPAIRÉE (UTC) +paired-col-last-seen = DERNIÈRE UTILISATION (UTC) +paired-forgot = { $name } ({ $fingerprint }) a été oubliée. +pair-open = L'appairage est ouvert. Sur la tablette, scannez ce QR code ou saisissez le code PIN : +pair-pin = PIN : { $pin } +pair-fingerprint = Empreinte de l'hôte : { $fingerprint } +pair-expires = Expire dans { $seconds } s. +pair-done = Appairage réussi avec { $device }. +pair-closed = L'appairage est fermé. +pair-closed-paired = L'appairage est fermé : une tablette a été appairée. +pair-closed-attempts = L'appairage est fermé : trop de PIN incorrects. +pair-closed-expired = L'appairage est fermé : le temps est écoulé. Relancez avec `--pair` pour appairer à nouveau. +wifi-listening = Wi-Fi : écoute sur { $addr } (UDP). Empreinte de l'hôte : { $fingerprint } +wifi-firewall-hint = Si les tablettes ne parviennent pas à se connecter, autorisez le port UDP { $port } en entrée dans le Pare-feu Windows (réseaux privés). +err-paired-not-found = aucune tablette appairée ne correspond à `{ $query }` +err-paired-ambiguous = { $count } tablettes appairées correspondent à `{ $query }` ; utilisez plus de chiffres de l'empreinte +err-no-config-dir = dossier de configuration introuvable +err-wifi = Wi-Fi : { $reason } diff --git a/crates/ezd-host/i18n/it/ezd-host.ftl b/crates/ezd-host/i18n/it/ezd-host.ftl index 35607b2..b734a5c 100644 --- a/crates/ezd-host/i18n/it/ezd-host.ftl +++ b/crates/ezd-host/i18n/it/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` non è un numero err-scale-range = la scala deve essere compresa tra 0,25 e 1,0, ricevuto { $value } err-no-backend = nessun backend di schermo virtuale per questa piattaforma err-source = impossibile creare la sorgente video: { $reason } + +cmd-paired = Elenca o dimentica i tablet associati via Wi-Fi. +paired-list = Elenca i tablet associati. +paired-forget = Dimentica un tablet associato; dovrà essere associato di nuovo per trasmettere. +paired-forget-target = Nome del tablet, o la sua impronta (intera o le prime cifre, come `3f2a-91c0`). +run-wifi = Accetta anche i tablet associati via Wi-Fi (QUIC su UDP) su ADDR (predefinito 0.0.0.0:27183). La prima volta mostra un PIN e un codice QR per associare un tablet. +run-pair = Apre la finestra di associazione all'avvio anche se un tablet è già associato (richiede `--wifi`). + +paired-none = Nessun tablet associato. +paired-never = mai +paired-col-name = NOME +paired-col-fingerprint = IMPRONTA +paired-col-paired = ASSOCIATO (UTC) +paired-col-last-seen = ULTIMO USO (UTC) +paired-forgot = { $name } ({ $fingerprint }) è stato dimenticato. +pair-open = L'associazione è aperta. Sul tablet, inquadra questo codice QR o digita il PIN: +pair-pin = PIN: { $pin } +pair-fingerprint = Impronta dell'host: { $fingerprint } +pair-expires = Scade tra { $seconds } s. +pair-done = Associato con { $device }. +pair-closed = L'associazione è chiusa. +pair-closed-paired = L'associazione è chiusa: un tablet è stato associato. +pair-closed-attempts = L'associazione è chiusa: troppi PIN errati. +pair-closed-expired = L'associazione è chiusa: tempo scaduto. Riavvia con `--pair` per associare di nuovo. +wifi-listening = Wi-Fi: in ascolto su { $addr } (UDP). Impronta dell'host: { $fingerprint } +wifi-firewall-hint = Se i tablet non riescono a connettersi, consenti la porta UDP { $port } in ingresso nel Firewall di Windows (reti private). +err-paired-not-found = nessun tablet associato corrisponde a `{ $query }` +err-paired-ambiguous = { $count } tablet associati corrispondono a `{ $query }`; usa più cifre dell'impronta +err-no-config-dir = impossibile trovare la cartella di configurazione +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-host/i18n/pt/ezd-host.ftl b/crates/ezd-host/i18n/pt/ezd-host.ftl index d13bce6..191e450 100644 --- a/crates/ezd-host/i18n/pt/ezd-host.ftl +++ b/crates/ezd-host/i18n/pt/ezd-host.ftl @@ -48,3 +48,33 @@ err-scale-nan = `{ $value }` não é um número err-scale-range = a escala deve estar entre 0,25 e 1,0, recebido { $value } err-no-backend = não há backend de tela virtual para esta plataforma err-source = não foi possível criar a fonte de vídeo: { $reason } + +cmd-paired = Lista ou esquece os tablets pareados por Wi-Fi. +paired-list = Lista os tablets pareados. +paired-forget = Esquece um tablet pareado; ele precisará ser pareado de novo para transmitir. +paired-forget-target = Nome do tablet, ou sua impressão digital (inteira ou os primeiros dígitos, como `3f2a-91c0`). +run-wifi = Aceita também tablets pareados por Wi-Fi (QUIC sobre UDP) em ADDR (padrão 0.0.0.0:27183). Na primeira vez, mostra um PIN e um QR code para parear um tablet. +run-pair = Abre a janela de pareamento ao iniciar mesmo que já exista um tablet pareado (requer `--wifi`). + +paired-none = Nenhum tablet pareado. +paired-never = nunca +paired-col-name = NOME +paired-col-fingerprint = IMPRESSÃO DIGITAL +paired-col-paired = PAREADO (UTC) +paired-col-last-seen = ÚLTIMO USO (UTC) +paired-forgot = { $name } ({ $fingerprint }) foi esquecido. +pair-open = O pareamento está aberto. No tablet, escaneie este QR code ou digite o PIN: +pair-pin = PIN: { $pin } +pair-fingerprint = Impressão digital do host: { $fingerprint } +pair-expires = Expira em { $seconds } s. +pair-done = Pareado com { $device }. +pair-closed = O pareamento está fechado. +pair-closed-paired = O pareamento está fechado: um tablet foi pareado. +pair-closed-attempts = O pareamento está fechado: PINs incorretos demais. +pair-closed-expired = O pareamento está fechado: o tempo acabou. Reinicie com `--pair` para parear de novo. +wifi-listening = Wi-Fi: escutando em { $addr } (UDP). Impressão digital do host: { $fingerprint } +wifi-firewall-hint = Se os tablets não conseguirem se conectar, permita a porta UDP { $port } de entrada no Firewall do Windows (redes privadas). +err-paired-not-found = nenhum tablet pareado corresponde a `{ $query }` +err-paired-ambiguous = { $count } tablets pareados correspondem a `{ $query }`; use mais dígitos da impressão digital +err-no-config-dir = não foi possível encontrar a pasta de configuração +err-wifi = Wi-Fi: { $reason } diff --git a/crates/ezd-host/src/main.rs b/crates/ezd-host/src/main.rs index d7d606b..1759378 100644 --- a/crates/ezd-host/src/main.rs +++ b/crates/ezd-host/src/main.rs @@ -1,6 +1,8 @@ //! `ezd-host`: host side of ezdisplay. //! //! * `ezd-host run --source synthetic`: listen for one client at a time and stream. +//! * `ezd-host run --wifi --source synthetic`: also accept paired tablets over Wi-Fi. +//! * `ezd-host paired list|forget`: manage the tablets paired over Wi-Fi. //! * `ezd-host diag`: print a JSON report about the machine (GPUs, encoders, adb). mod diag; @@ -8,6 +10,8 @@ mod i18n; mod run; #[cfg(windows)] mod vdd; +#[cfg(feature = "wifi")] +mod wifi; use anyhow::Result; use clap::{ @@ -28,6 +32,9 @@ struct Cli { enum Command { Run(run::RunArgs), Diag, + #[cfg(feature = "wifi")] + #[command(subcommand)] + Paired(wifi::PairedCommand), #[cfg(windows)] #[command(subcommand)] Vdd(vdd::VddCommand), @@ -41,6 +48,10 @@ fn command(l: &FluentLanguageLoader) -> ClapCommand { .about(fl!(l, "about")) .mut_subcommand("run", |s| run::localize(s.about(fl!(l, "cmd-run")), l)) .mut_subcommand("diag", |s| s.about(fl!(l, "cmd-diag"))); + #[cfg(feature = "wifi")] + let cmd = cmd.mut_subcommand("paired", |s| { + wifi::localize(s.about(fl!(l, "cmd-paired")), l) + }); #[cfg(windows)] let cmd = cmd.mut_subcommand("vdd", |s| vdd::localize(s.about(fl!(l, "cmd-vdd")), l)); i18n::localize_version(i18n::localize_chrome(cmd, l), l) @@ -72,6 +83,8 @@ fn main() -> Result<()> { println!("{}", serde_json::to_string_pretty(&diag::report())?); Ok(()) } + #[cfg(feature = "wifi")] + Command::Paired(cmd) => wifi::run(cmd), #[cfg(windows)] Command::Vdd(cmd) => vdd::run(cmd), } diff --git a/crates/ezd-host/src/run.rs b/crates/ezd-host/src/run.rs index 0854f8e..a186288 100644 --- a/crates/ezd-host/src/run.rs +++ b/crates/ezd-host/src/run.rs @@ -62,12 +62,25 @@ pub struct RunArgs { no_input: bool, #[arg(long, value_enum, default_value = "tablet")] pen_mode: PenModeArg, + #[cfg(feature = "wifi")] + #[arg(long, num_args = 0..=1, value_name = "ADDR", default_missing_value = "0.0.0.0:27183")] + wifi: Option, + #[cfg(feature = "wifi")] + #[arg(long, requires = "wifi")] + pair: bool, + #[cfg(feature = "wifi")] + #[arg(long, value_enum, hide = true, requires = "wifi")] + congestion: Option, + #[cfg(feature = "wifi")] + #[arg(long, hide = true, requires = "wifi", value_name = "DIR")] + config_dir: Option, } /// Applies the localized help of every `run` option. pub fn localize(cmd: Command, l: &FluentLanguageLoader) -> Command { use i18n_embed_fl::fl; - cmd.mut_arg("source", |a| a.help(fl!(l, "run-source"))) + let cmd = cmd + .mut_arg("source", |a| a.help(fl!(l, "run-source"))) .mut_arg("listen", |a| a.help(fl!(l, "run-listen"))) .mut_arg("adb", |a| a.help(fl!(l, "run-adb"))) .mut_arg("link", |a| a.help(fl!(l, "run-link"))) @@ -81,7 +94,12 @@ pub fn localize(cmd: Command, l: &FluentLanguageLoader) -> Command { .mut_arg("video_window", |a| a.help(fl!(l, "run-video-window"))) .mut_arg("telemetry", |a| a.help(fl!(l, "run-telemetry"))) .mut_arg("no_input", |a| a.help(fl!(l, "run-no-input"))) - .mut_arg("pen_mode", |a| a.help(fl!(l, "run-pen-mode"))) + .mut_arg("pen_mode", |a| a.help(fl!(l, "run-pen-mode"))); + #[cfg(feature = "wifi")] + let cmd = cmd + .mut_arg("wifi", |a| a.help(fl!(l, "run-wifi"))) + .mut_arg("pair", |a| a.help(fl!(l, "run-pair"))); + cmd } fn parse_scale(s: &str) -> Result { @@ -93,19 +111,26 @@ fn parse_scale(s: &str) -> Result { } } +/// The first socket address `addr` resolves to. +fn resolve(addr: &str) -> Result { + addr.to_socket_addrs() + .and_then(|mut a| a.next().ok_or_else(|| std::io::Error::other("no address"))) + .map_err(|e| anyhow!(fl!("err-binding", addr = addr, reason = e.to_string()))) +} + /// The service configuration the command line describes. fn config(args: &RunArgs) -> Result { - let listen = args - .listen - .to_socket_addrs() - .and_then(|mut a| a.next().ok_or_else(|| std::io::Error::other("no address"))) - .map_err(|e| { - anyhow!(fl!( - "err-binding", - addr = args.listen.as_str(), - reason = e.to_string() - )) - })?; + let listen = resolve(&args.listen)?; + #[cfg(feature = "wifi")] + let wifi = match &args.wifi { + None => None, + Some(addr) => Some(ezd_host_service::WifiConfig { + listen: resolve(addr)?, + pair_on_start: args.pair, + congestion: args.congestion.map(Into::into).unwrap_or_default(), + config_dir: args.config_dir.clone(), + }), + }; Ok(ServiceConfig { listen, source: match args.source { @@ -138,6 +163,8 @@ fn config(args: &RunArgs) -> Result { }, // The command line never starts the app: that is the tray's convenience. open_app_on_connect: false, + #[cfg(feature = "wifi")] + wifi, // The command line has no HDR switch: it streams HDR10 whenever everything supports it. ..ServiceConfig::default() }) @@ -162,6 +189,7 @@ pub fn localize_error(e: &ServiceError) -> String { ) } ServiceError::UnsupportedPlatform => fl!("err-no-backend"), + ServiceError::Wifi(reason) => fl!("err-wifi", reason = reason.as_str()), ServiceError::Source(reason) => fl!("err-source", reason = reason.as_str()), } } @@ -170,12 +198,21 @@ pub async fn run(args: RunArgs) -> Result<()> { let service = HostService::start(&tokio::runtime::Handle::current(), config(&args)?) .map_err(|e| anyhow!(localize_error(&e)))?; let mut events = service.events(); + #[cfg(feature = "wifi")] + { + if let Some(info) = service.wifi().borrow().clone() { + crate::wifi::print_listening(info.addr, &info.fingerprint_short); + } + // The window may have opened before the subscription above. + service.refresh_pairing(); + } + let mut shown: Shown = None; let reporter = tokio::spawn(report_errors(service.status())); // The service owns the event sender, so the channel stays open until `stop`. loop { tokio::select! { - ev = events.recv() => log_event(ev), + ev = events.recv() => log_event(ev, &mut shown), _ = tokio::signal::ctrl_c() => break, } } @@ -187,7 +224,7 @@ pub async fn run(args: RunArgs) -> Result<()> { loop { tokio::select! { () = &mut stop => break, - ev = events.recv() => log_event(ev), + ev = events.recv() => log_event(ev, &mut shown), _ = tokio::signal::ctrl_c() => { tracing::warn!("interrupted again, exiting now"); return Ok(()); @@ -196,15 +233,46 @@ pub async fn run(args: RunArgs) -> Result<()> { } // Whatever the session reported while stopping. while let Ok(ev) = events.try_recv() { - log_event(Ok(ev)); + log_event(Ok(ev), &mut shown); } reporter.abort(); Ok(()) } -fn log_event(ev: Result) { +/// The pairing window last shown, to not print it twice. +type Shown = Option<(String, std::time::Instant)>; + +#[cfg_attr(not(feature = "wifi"), allow(unused_variables))] +fn log_event(ev: Result, shown: &mut Shown) { match ev { Ok(HostEvent::SessionEnded(r)) => log_session_end(r), + #[cfg(feature = "wifi")] + Ok(HostEvent::PairingOpen { + pin, + uri, + fingerprint, + expires, + }) => { + // The service may announce the same window twice (late subscription). + if shown.replace((pin.clone(), expires)) != Some((pin.clone(), expires)) { + crate::wifi::print_pairing_open(&pin, &uri, &fingerprint, expires); + } + } + #[cfg(feature = "wifi")] + Ok(HostEvent::PairingClosed { reason }) => { + *shown = None; + crate::wifi::print_pairing_closed(reason); + } + #[cfg(feature = "wifi")] + Ok(HostEvent::Paired { device }) => crate::wifi::print_paired(&device), + #[cfg(feature = "wifi")] + Ok(HostEvent::PairingFailed { peer, reason }) => { + tracing::warn!(%peer, "pairing failed: {reason}") + } + #[cfg(feature = "wifi")] + Ok(HostEvent::SessionRefused { peer, why }) => { + tracing::info!(%peer, ?why, "Wi-Fi session refused") + } Ok(_) => {} Err(e) => tracing::debug!("missed service events: {e}"), } diff --git a/crates/ezd-host/src/wifi.rs b/crates/ezd-host/src/wifi.rs new file mode 100644 index 0000000..10941c8 --- /dev/null +++ b/crates/ezd-host/src/wifi.rs @@ -0,0 +1,295 @@ +//! Wi-Fi in the command line: the pairing screen (PIN, fingerprint, QR code) and the +//! `paired` subcommands. + +use crate::i18n::fl; +use anyhow::{Result, anyhow}; +use clap::{Command, Subcommand, ValueEnum}; +use ezd_host_service::store::{ForgetError, PairedDevice, PairedStore, default_config_dir}; +use ezd_host_service::{CongestionChoice, PairingCloseReason}; +use i18n_embed::fluent::FluentLanguageLoader; +use qrcode::render::unicode::Dense1x2; +use qrcode::{EcLevel, QrCode}; +use std::path::PathBuf; +use std::time::Instant; + +#[derive(Debug, Clone, Copy, ValueEnum)] +pub enum CongestionArg { + Cubic, + Bbr, +} + +impl From for CongestionChoice { + fn from(c: CongestionArg) -> Self { + match c { + CongestionArg::Cubic => CongestionChoice::Cubic, + CongestionArg::Bbr => CongestionChoice::Bbr, + } + } +} + +// Help texts live in i18n//ezd-host.ftl (`paired-*` ids); see `localize`. +#[derive(Subcommand, Debug)] +pub enum PairedCommand { + /// Lists the paired tablets. + List { + #[arg(long, hide = true, value_name = "DIR")] + config_dir: Option, + }, + /// Forgets a paired tablet. + Forget { + target: String, + #[arg(long, hide = true, value_name = "DIR")] + config_dir: Option, + }, +} + +/// Applies the localized help of the `paired` subcommands. +pub fn localize(cmd: Command, l: &FluentLanguageLoader) -> Command { + use i18n_embed_fl::fl; + cmd.mut_subcommand("list", |s| s.about(fl!(l, "paired-list"))) + .mut_subcommand("forget", |s| { + s.about(fl!(l, "paired-forget")) + .mut_arg("target", |a| a.help(fl!(l, "paired-forget-target"))) + }) +} + +fn store(dir: Option) -> Result { + let dir = dir + .or_else(default_config_dir) + .ok_or_else(|| anyhow!(fl!("err-no-config-dir")))?; + Ok(PairedStore::new(&dir)) +} + +pub fn run(cmd: PairedCommand) -> Result<()> { + match cmd { + PairedCommand::List { config_dir } => { + let store = store(config_dir)?; + let devices = store.list().map_err(|e| anyhow!(e.to_string()))?; + print!("{}", render_list(&devices)); + Ok(()) + } + PairedCommand::Forget { target, config_dir } => { + let store = store(config_dir)?; + match store.forget(&target) { + Ok(d) => { + println!( + "{}", + fl!( + "paired-forgot", + name = d.name.as_str(), + fingerprint = short(&d.fingerprint) + ) + ); + Ok(()) + } + Err(ForgetError::NotFound) => Err(anyhow!(fl!( + "err-paired-not-found", + query = target.as_str() + ))), + Err(ForgetError::Ambiguous(n)) => Err(anyhow!(fl!( + "err-paired-ambiguous", + count = n, + query = target.as_str() + ))), + Err(ForgetError::Store(e)) => Err(anyhow!(e.to_string())), + } + } + } +} + +/// The short dashed form of a hex fingerprint (first 16 digits). +fn short(hex: &str) -> String { + hex.as_bytes() + .chunks(4) + .take(4) + .map(|c| String::from_utf8_lossy(c).into_owned()) + .collect::>() + .join("-") +} + +/// The table of `paired list`. +fn render_list(devices: &[PairedDevice]) -> String { + if devices.is_empty() { + return format!("{}\n", fl!("paired-none")); + } + let never = fl!("paired-never"); + let mut rows = vec![[ + fl!("paired-col-name"), + fl!("paired-col-fingerprint"), + fl!("paired-col-paired"), + fl!("paired-col-last-seen"), + ]]; + for d in devices { + rows.push([ + d.name.clone(), + short(&d.fingerprint), + format_utc(d.paired_at), + d.last_seen.map_or_else(|| never.clone(), format_utc), + ]); + } + let widths: Vec = (0..4) + .map(|c| rows.iter().map(|r| r[c].chars().count()).max().unwrap_or(0)) + .collect(); + let mut out = String::new(); + for r in &rows { + let cells: Vec = r + .iter() + .zip(&widths) + .map(|(cell, w)| format!("{cell: String { + let (days, rem) = (secs / 86_400, secs % 86_400); + // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm). + let z = days as i64 + 719_468; + let era = z.div_euclid(146_097); + let doe = z.rem_euclid(146_097); + let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365; + let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + let mp = (5 * doy + 2) / 153; + let day = doy - (153 * mp + 2) / 5 + 1; + let month = if mp < 10 { mp + 3 } else { mp - 9 }; + let year = yoe + era * 400 + i64::from(month <= 2); + format!( + "{year:04}-{month:02}-{day:02} {:02}:{:02}", + rem / 3600, + rem % 3600 / 60 + ) +} + +/// The QR code of `text` as Unicode half blocks, light modules drawn as blocks (right for a dark +/// terminal) with the quiet zone the scanners need. Error correction is low to keep it small. +pub fn render_qr(text: &str) -> Option { + let code = QrCode::with_error_correction_level(text, EcLevel::L).ok()?; + Some( + code.render::() + .dark_color(Dense1x2::Light) + .light_color(Dense1x2::Dark) + .quiet_zone(true) + .build(), + ) +} + +/// What the terminal shows when a pairing window opens. +pub fn print_pairing_open(pin: &str, uri: &str, fingerprint: &str, expires: Instant) { + println!(); + println!("{}", fl!("pair-open")); + match render_qr(uri) { + Some(qr) => println!("{qr}"), + None => tracing::warn!("cannot render the pairing QR code"), + } + println!("{}", fl!("pair-pin", pin = pin)); + println!("{}", fl!("pair-fingerprint", fingerprint = fingerprint)); + println!( + "{}", + fl!( + "pair-expires", + seconds = expires.saturating_duration_since(Instant::now()).as_secs() + ) + ); +} + +pub fn print_paired(device: &str) { + println!("{}", fl!("pair-done", device = device)); +} + +pub fn print_pairing_closed(reason: PairingCloseReason) { + println!( + "{}", + match reason { + PairingCloseReason::Closed => fl!("pair-closed"), + PairingCloseReason::Paired => fl!("pair-closed-paired"), + PairingCloseReason::TooManyAttempts => fl!("pair-closed-attempts"), + PairingCloseReason::Expired => fl!("pair-closed-expired"), + } + ); +} + +pub fn print_listening(addr: std::net::SocketAddr, fingerprint: &str) { + println!( + "{}", + fl!( + "wifi-listening", + addr = addr.to_string(), + fingerprint = fingerprint + ) + ); + #[cfg(windows)] + eprintln!("{}", fl!("wifi-firewall-hint", port = addr.port())); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn utc_formatting() { + assert_eq!(format_utc(0), "1970-01-01 00:00"); + assert_eq!(format_utc(1_709_210_096), "2024-02-29 12:34"); + assert_eq!(format_utc(1_767_225_540), "2025-12-31 23:59"); + } + + #[test] + fn short_fingerprint_matches_the_wire_form() { + assert_eq!(short(&"3f2a91c077de0b14".repeat(4)), "3f2a-91c0-77de-0b14"); + } + + #[test] + fn qr_is_compact_and_scannable() { + let uri = format!( + "ezd://pair?a=192.168.100.200:27183&fp={}&pin=123456&n=Desktop+PC", + "ab".repeat(32) + ); + let qr = render_qr(&uri).unwrap(); + let lines: Vec<&str> = qr.lines().collect(); + // Two modules per text line, a quiet zone around: well under a terminal screen. + assert!((20..=40).contains(&lines.len()), "{}", lines.len()); + assert!( + lines + .iter() + .all(|l| l.chars().count() == lines[0].chars().count()) + ); + assert!(qr.contains('█') && qr.contains(' ')); + } + + #[test] + fn list_and_forget_use_the_store() { + let dir = std::env::temp_dir().join(format!("ezd-host-paired-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + let store = PairedStore::new(&dir); + assert_eq!( + render_list(&store.list().unwrap()).trim(), + fl!("paired-none") + ); + store + .add(&ezd_link::pair::PairedClient { + fingerprint: [0xab; 32], + name: "Tab S9".into(), + }) + .unwrap(); + let table = render_list(&store.list().unwrap()); + assert!( + table.contains("Tab S9") && table.contains("abab-abab-abab-abab"), + "{table}" + ); + run(PairedCommand::Forget { + target: "tab s9".into(), + config_dir: Some(dir.clone()), + }) + .unwrap(); + assert!(store.list().unwrap().is_empty()); + let err = run(PairedCommand::Forget { + target: "nobody".into(), + config_dir: Some(dir.clone()), + }) + .unwrap_err(); + assert!(err.to_string().contains("nobody")); + let _ = std::fs::remove_dir_all(&dir); + } +} From 765e37ae7ba78964974d5cf877cadff67960c150 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sat, 24 Oct 2026 21:57:37 -0300 Subject: [PATCH 03/14] Document the Wi-Fi transport and pairing --- README.md | 26 +++++++++++ docs/architecture.md | 6 +-- docs/protocol.md | 107 +++++++++++++++++++++++++++++++++++++++++-- 3 files changed, 132 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index 89a86e8..db8911e 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,32 @@ cargo run --release -p ezd-fake-client -- --connect 127.0.0.1:27183 --frames 300 With a real device, `ezd-host run --source synthetic --adb` sets up `adb reverse tcp:27183 tcp:27183` for the attached device(s) and removes it on exit. +## Wi-Fi + +`--wifi` also listens for tablets on the local network (QUIC over UDP port 27183, encrypted, +paired devices only). The host advertises itself over mDNS so tablets can find it: + +```sh +ezd-host run --wifi +``` + +The first time, or with `--pair`, the host prints a QR code and a 6-digit PIN that are valid for +5 minutes. Once paired, a device reconnects without a PIN. `ezd-host paired list` shows the +paired devices and `ezd-host paired forget ` removes one. (The Android app's Wi-Fi +connect screen is in progress.) + +The fake client pairs the same way, then streams: + +```sh +cargo run --release -p ezd-fake-client -- --wifi 127.0.0.1:27183 --pin 123456 --frames 300 +``` + +On Windows, allow inbound UDP port 27183 in Windows Defender Firewall for private networks. +Wi-Fi also works without pairing through ADB wireless debugging: +`ezd-host run --adb --link network`. + +How the link and the pairing work: [docs/protocol.md](docs/protocol.md#transports). + ## Diagnostics ```sh diff --git a/docs/architecture.md b/docs/architecture.md index f8bacda..eea1f00 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -1,6 +1,6 @@ # ezdisplay architecture -ezdisplay turns an Android tablet into an extended monitor for a Windows or Linux PC, over USB (ADB now, Android Open Accessory later) or Wi-Fi. The design goal is low latency: about 30 ms glass to glass over USB at 120 Hz, with the cursor feeling instant. +ezdisplay turns an Android tablet into an extended monitor for a Windows or Linux PC, over USB (ADB now, Android Open Accessory later) or Wi-Fi (QUIC, paired with a PIN or QR code). The design goal is low latency: about 30 ms glass to glass over USB at 120 Hz, with the cursor feeling instant. ## Why existing tools lag @@ -19,7 +19,7 @@ On hybrid-GPU laptops (for example an Acer Nitro 5 with a MUX switch), existing | Crate / dir | Role | |---|---| | `crates/ezd-proto` | Wire protocol: framing, messages, capabilities negotiation, clock sync. Pure, no I/O. | -| `crates/ezd-link` | Byte-stream links (TCP/ADB now, AOA and QUIC later), ADB helper, prioritized mux with video credit. | +| `crates/ezd-link` | Links (TCP through ADB; QUIC on Wi-Fi with separate control and video streams; AOA later), device identity and PIN pairing, ADB helper, prioritized mux with video credit. | | `crates/ezd-host-core` | Platform-independent host: `VideoSource` / `VirtualDisplay` traits, session, pacing, synthetic frames. | | `crates/ezd-ffmpeg` | Thin safe wrapper over FFmpeg (encoders, decoders, hardware contexts). | | `crates/ezd-host-service` | The host loop as a library: accepts the tablet, keeps `adb reverse` set up for each device, runs sessions and publishes live status. Used by the CLI and the tray app. | @@ -65,7 +65,7 @@ On hybrid-GPU laptops (for example an Acer Nitro 5 with a MUX switch), existing 0. Diagnosis and spikes (Nitro measurements, KDE virtual output, tablet probing). 1. Vertical slice on both hosts: video and local cursor over ADB. 1a core → 1b Android, 1c Linux KDE, 1d Windows in parallel. 2. Input: touch, pen, S Pen button gestures. -3. Transports: AOA, Wi-Fi (QUIC with PIN pairing). +3. Transports: Wi-Fi (QUIC with PIN or QR pairing, mDNS discovery) in progress; AOA later. 4. Audio. 5. GNOME and wlroots backends. 6. Packaging: Windows installer (done, with the tray app), Linux packages (Arch, .deb, AppImage; done) and udev rules, Android `full`/`play` builds. diff --git a/docs/protocol.md b/docs/protocol.md index 7826a85..9162a9c 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -1,7 +1,7 @@ -# ezdisplay wire protocol (version 0.4) +# ezdisplay wire protocol (version 0.5) -All integers are little endian. The protocol runs over any reliable ordered byte stream (TCP -through `adb reverse` today; AOA bulk endpoints later). It is implemented in the `ezd-proto` +All integers are little endian. The protocol runs over any reliable ordered byte stream: TCP +through `adb reverse` over USB, or a QUIC connection on Wi-Fi (see [Transports](#transports)). It is implemented in the `ezd-proto` crate (messages, framing) and `ezd-link` (prioritized mux). ## Framing @@ -93,7 +93,8 @@ per push) and yields complete messages. `Hello` carries `proto_major` and `proto_minor` (currently 0 and 5; 0.2 added `FrameAck`, 0.3 the input messages, `InputStatus` and `ClientOptions`, 0.4 the `Key` message, 0.5 `ClientHdr` and -`StreamColor` for HDR10). A different major version is fatal: the +`StreamColor` for HDR10; the Wi-Fi transport is below the framed protocol and needs no minor +bump). A different major version is fatal: the receiver answers `Reject` and closes. Minor versions only add new `(channel, kind)` pairs, so peers with different minors interoperate. `Hello::supports_input()` is true when the peer's minor is at least `MINOR_INPUT` = 3; a host must not send `InputStatus` or @@ -103,6 +104,104 @@ host's `InputStatus.caps` has `KEYS`, and an older host would skip the unknown p `Hello::supports_hdr()` is true when the peer's minor is at least `MINOR_HDR` = 5: a client sends `ClientHdr` only to such a host, and a host sends `StreamColor` only to such a client. +## Transports + +### USB (TCP through `adb reverse`) + +The host listens on `127.0.0.1:27183` and `adb reverse` maps the tablet's `127.0.0.1:27183` to +it. Everything goes over one TCP stream in the order described in [Priority](#priority). The +link is not encrypted; it never leaves the loopback interface and the USB cable. + +### Wi-Fi (QUIC) + +The host listens on UDP `0.0.0.0:27183` with QUIC (TLS 1.3 only, ALPN `ezd/0`). Both sides +present a long-lived self-signed certificate (ECDSA P-256) and identify each other by its +fingerprint, the SHA-256 of the certificate DER. There is no CA: the client pins the host's +fingerprint, and the host only starts sessions for fingerprints it has paired with. + +Streams: + +* **Control** (bidirectional, opened by the client, higher stream priority): the preamble + below, then the framed protocol for every channel except video. +* **Video** (unidirectional, opened by the host after accepting a session, lower priority): + the byte `'V'`, then the framed `Video` channel messages. + +Video has its own stream so a lost packet of a large frame does not hold back input, cursor or +control messages queued behind it. Every other rule of this document (credit, coalescing, +reassembly) is unchanged; each stream is reassembled on its own. + +Before the framed protocol the client sends one preamble message (`ezd_proto::pair`). Preamble +messages are postcard with a `u16` little-endian length prefix, at most 1024 bytes, and each +step must complete within 10 s. + +``` +client host + | LinkOpen::Session --------------------->| client certificate must be paired + |<--------------------- LinkReply::Accepted | or Refused(NotPaired | Busy) + |<=== video stream: 'V', VideoFrame ... ===| + | Hello ... (as in Handshake and session) | +``` + +Transport settings tuned for latency: keep-alive 1 s, idle timeout 5 s, initial RTT estimate +10 ms. The congestion controller is Cubic; BBR can be selected for experiments. + +The host accepts any client certificate in the handshake, so it treats every peer as untrusted +until the preamble: it finishes each handshake in its own task within 10 s, keeps at most 8 +connections, allows the client one bidirectional stream and no unidirectional ones, and uses +256 KiB receive windows (it never receives video). The client allows the host only the video +stream and uses 8 MiB stream and 16 MiB connection receive windows, room for a large keyframe. +A client only opens a session on a connection whose host certificate it pinned. + +Hosts advertise themselves over mDNS as `_ezdisplay._udp.local.` with TXT records `fp` (short +fingerprint, see below), `name` and `pv` (protocol major version). The client can also be given +an address by hand. + +### Pairing + +A client that is not paired yet asks the host to pair while the host's pairing window is open. +The host shows a random 6-digit PIN, and a QR code of + +``` +ezd://pair?a=&fp=&pin=&n= +``` + +With the QR code the client pins `fp` before connecting. With a typed PIN it accepts any host +certificate for this one connection; the PIN exchange below then authenticates the +certificates of both sides. + +``` +client (SPAKE2 side A) host (SPAKE2 side B) + | LinkOpen::Pair{device_name, spake_A} -->| window closed -> Refused(PairingClosed + | | or TooManyAttempts); else counts an attempt + |<-- LinkReply::PairChallenge{host_name, | + | spake_B, confirm_host} | + | check confirm_host; on mismatch close | + | PairConfirm{confirm_client} ----------->| mismatch -> PairOutcome::Refused(WrongPin) + |<----------------------- PairOutcome::Paired host stored the client first +``` + +* SPAKE2 over Ed25519 with the PIN as the password and the identities `ezdisplay client` (A) + and `ezdisplay host` (B). The shared key `K` only matches if both sides used the same PIN; a + passive observer learns nothing about the PIN and an active attacker tests one guess per + attempt. +* Each confirmation is an HMAC-SHA256 with a per-side key `HMAC(K, side)` (`side` is + `host confirm` or `client confirm`) over the transcript + `"ezd-pair-v1" || exporter || host_fp || client_fp`. `exporter` is the 32-byte TLS keying + material exporter value for the label `EXPORTER-ezd-pair-v1`, so the confirmation is bound to + this TLS connection and both certificates: a machine in the middle running two TLS + connections cannot relay it. +* The window allows 5 attempts and stays open 5 minutes; it closes after a successful pairing, + so at most one device pairs per window. An attempt that started before the window was + closed, reopened or expired is refused at the end even with the right PIN. +* Known limit: anyone on the network can use up the 5 attempts of an open window, which then + has to be reopened. The PIN stays safe (5 guesses out of a million per window); only pairing + is delayed. +* Both sides then store the other's fingerprint and name. Later connections open a session + directly. The pairing connection itself is closed; the client reconnects for the session. + +People compare fingerprints in a short form: the first 8 bytes as hex in 4 groups +(`3f2a-91c0-77de-0b14`). + ## Handshake and session ``` From 72d8e7c4a4513446e4f7e332657326d694ce46de Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 15:09:24 -0300 Subject: [PATCH 04/14] Add Wi-Fi pairing to the tray The Connection page gets a Wi-Fi card: a switch (which restarts the service, as the listener is read at start), a latency warning, the host address and short fingerprint, a Pair a device button that opens the pairing window and shows the PIN, a QR code and the time left, and the paired devices with Forget. HostService gains paired_devices and forget_paired. The Windows installer opens UDP 27183 on the private profile for ezdisplay.exe and ezd-host.exe and removes the rules on uninstall. --- Cargo.lock | 77 ++++++++ crates/ezd-host-service/src/service.rs | 15 ++ crates/ezd-host-service/src/wifi.rs | 10 +- crates/ezd-tray/Cargo.toml | 6 +- crates/ezd-tray/i18n/de/ezd-tray.ftl | 25 +++ crates/ezd-tray/i18n/en/ezd-tray.ftl | 25 +++ crates/ezd-tray/i18n/es/ezd-tray.ftl | 25 +++ crates/ezd-tray/i18n/fr/ezd-tray.ftl | 25 +++ crates/ezd-tray/i18n/it/ezd-tray.ftl | 25 +++ crates/ezd-tray/i18n/pt/ezd-tray.ftl | 25 +++ crates/ezd-tray/src/config.rs | 18 ++ crates/ezd-tray/src/controller.rs | 14 ++ crates/ezd-tray/src/controller/tests.rs | 70 +++++++ crates/ezd-tray/src/controller/wifi.rs | 171 +++++++++++++++++ crates/ezd-tray/src/menu_model.rs | 1 + crates/ezd-tray/src/text.rs | 1 + crates/ezd-tray/src/ui/mod.rs | 1 + crates/ezd-tray/src/ui/qr.rs | 66 +++++++ crates/ezd-tray/src/ui/view.rs | 233 +++++++++++++++++++++++- crates/ezd-tray/src/ui/view/tests.rs | 156 +++++++++++++++- docs/windows-testing.md | 3 + packaging/windows/ezdisplay.iss | 10 + 22 files changed, 998 insertions(+), 4 deletions(-) create mode 100644 crates/ezd-tray/src/controller/wifi.rs create mode 100644 crates/ezd-tray/src/ui/qr.rs diff --git a/Cargo.lock b/Cargo.lock index 8e1ed5b..10013b7 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1619,6 +1619,7 @@ version = "0.1.0-alpha.1" dependencies = [ "anyhow", "clap", + "dirs 6.0.0", "ezd-client-core", "ezd-ffmpeg", "ezd-host-core", @@ -1627,6 +1628,8 @@ dependencies = [ "i18n-embed", "i18n-embed-fl", "rust-embed", + "serde", + "serde_json", "thiserror 2.0.21", "tokio", "tracing", @@ -1657,6 +1660,7 @@ dependencies = [ "ezd-link", "i18n-embed", "i18n-embed-fl", + "qrcode", "rust-embed", "serde_json", "tokio", @@ -1697,12 +1701,15 @@ dependencies = [ name = "ezd-host-service" version = "0.1.0-alpha.1" dependencies = [ + "dirs 6.0.0", "ezd-ffmpeg", "ezd-host-core", "ezd-host-linux", "ezd-host-windows", "ezd-link", "ezd-proto", + "gethostname", + "mdns-sd", "serde", "serde_json", "thiserror 2.0.21", @@ -1778,6 +1785,7 @@ dependencies = [ "i18n-embed-fl", "interprocess", "png", + "qrcode", "rust-embed", "serde", "serde_json", @@ -1917,6 +1925,17 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "flume" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e139bc46ca777eb5efaf62df0ab8cc5fd400866427e56c68b22e414e53bd3be" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + [[package]] name = "foldhash" version = "0.1.5" @@ -2016,6 +2035,12 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + [[package]] name = "futures-task" version = "0.3.34" @@ -2404,6 +2429,16 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "if-addrs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + [[package]] name = "image" version = "0.25.10" @@ -2778,6 +2813,21 @@ dependencies = [ "regex-automata", ] +[[package]] +name = "mdns-sd" +version = "0.21.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8562654710f72a9cbce4b0d5b7c366a2f94330ba1ce3740f15e932ea2d37b161" +dependencies = [ + "fastrand", + "flume", + "if-addrs", + "log", + "mio", + "socket-pktinfo", + "socket2", +] + [[package]] name = "memchr" version = "2.8.3" @@ -2851,6 +2901,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" dependencies = [ "libc", + "log", "wasi", "windows-sys 0.61.2", ] @@ -3890,6 +3941,12 @@ version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qrcode" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d68782463e408eb1e668cf6152704bd856c78c5b6417adaee3203d8f4c1fc9ec" + [[package]] name = "quick-error" version = "2.0.1" @@ -4606,6 +4663,17 @@ dependencies = [ "serde", ] +[[package]] +name = "socket-pktinfo" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "612942246d0cc239cfd83af1dfd39be47f649208a3524e5e9da651910128e0ac" +dependencies = [ + "libc", + "socket2", + "windows-sys 0.61.2", +] + [[package]] name = "socket2" version = "0.6.5" @@ -4628,6 +4696,15 @@ dependencies = [ "sha2 0.10.9", ] +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + [[package]] name = "spirv" version = "0.4.0+sdk-1.4.341.0" diff --git a/crates/ezd-host-service/src/service.rs b/crates/ezd-host-service/src/service.rs index c5ce3d9..fa0ecb8 100644 --- a/crates/ezd-host-service/src/service.rs +++ b/crates/ezd-host-service/src/service.rs @@ -4,6 +4,8 @@ use crate::adb::{AdbClient, AdbLocator, Watcher, locate_system_adb}; use crate::config::{AdbMode, ServiceConfig, SourceKind}; use crate::error::ServiceError; use crate::status::{DeviceInfo, HostEvent, HostStatus, LiveSession, Transport, WifiInfo}; +#[cfg(feature = "wifi")] +use crate::store::{ForgetError, PairedDevice, StoreError}; use ezd_host_core::{SessionEvent, VideoSource, run_host_session_with}; use ezd_link::Link; use ezd_proto::Prefs; @@ -300,6 +302,19 @@ impl HostService { } } + /// The paired devices; `None` while Wi-Fi is off. + #[cfg(feature = "wifi")] + pub fn paired_devices(&self) -> Option, StoreError>> { + Some(self.inner.wifi.as_ref()?.paired()) + } + + /// Forgets the paired device matching `query` (name or fingerprint, see + /// [`PairedStore::forget`](crate::store::PairedStore::forget)); `None` while Wi-Fi is off. + #[cfg(feature = "wifi")] + pub fn forget_paired(&self, query: &str) -> Option> { + Some(self.inner.wifi.as_ref()?.forget(query)) + } + /// Current state; changes are pushed to the receiver. pub fn status(&self) -> watch::Receiver { self.inner.status.subscribe() diff --git a/crates/ezd-host-service/src/wifi.rs b/crates/ezd-host-service/src/wifi.rs index f27609d..b6349da 100644 --- a/crates/ezd-host-service/src/wifi.rs +++ b/crates/ezd-host-service/src/wifi.rs @@ -9,7 +9,7 @@ use crate::error::ServiceError; use crate::mdns::Advertiser; use crate::service::{Inner, finish_session, lock}; use crate::status::{HostEvent, PairingCloseReason, RefusedWhy, Transport, WifiInfo}; -use crate::store::{PairedStore, default_config_dir}; +use crate::store::{ForgetError, PairedDevice, PairedStore, StoreError, default_config_dir}; use ezd_link::identity::{Identity, fingerprint_hex, fingerprint_short}; use ezd_link::pair::{CloseReason, PairUri, PairingWindow, WindowState, clean_name, host_pair}; use ezd_link::quic::{Congestion, QuicIncoming, QuicServer}; @@ -107,6 +107,14 @@ impl Wifi { pin } + pub(crate) fn paired(&self) -> Result, StoreError> { + self.store.list() + } + + pub(crate) fn forget(&self, query: &str) -> Result { + self.store.forget(query) + } + pub(crate) fn refresh_pairing(&self) { *lock(&self.announced) = None; self.changed.notify_one(); diff --git a/crates/ezd-tray/Cargo.toml b/crates/ezd-tray/Cargo.toml index 036091c..0e56898 100644 --- a/crates/ezd-tray/Cargo.toml +++ b/crates/ezd-tray/Cargo.toml @@ -15,10 +15,13 @@ name = "ezdisplay" path = "src/main.rs" [features] -default = ["ffmpeg"] +default = ["ffmpeg", "wifi"] # FFmpeg paths of the service. `--no-default-features` builds without FFmpeg headers (the Windows # cross-check in CI). ffmpeg = ["ezd-host-service/ffmpeg"] +# Wi-Fi card: the QUIC transport and PIN pairing of the service. `--no-default-features` leaves it +# out (ring has C code the Windows cross-check from Linux cannot build). +wifi = ["ezd-host-service/wifi"] # Local only: PNG snapshots of the window (needs a GPU/wgpu). CI never enables it. snapshots = ["egui_kittest/snapshot", "egui_kittest/wgpu"] @@ -34,6 +37,7 @@ i18n-embed.workspace = true i18n-embed-fl.workspace = true interprocess = "2.4" png = "0.18" +qrcode.workspace = true rust-embed.workspace = true serde.workspace = true tokio.workspace = true diff --git a/crates/ezd-tray/i18n/de/ezd-tray.ftl b/crates/ezd-tray/i18n/de/ezd-tray.ftl index 84faf00..263ef9f 100644 --- a/crates/ezd-tray/i18n/de/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/de/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Öffnet den Ordner, in den ezdisplay seine Protokolle schreib about-description = Open-Source-USB-Display für Android-Tablets. repository = Quellcode driver-reinstall = Treiber neu installieren + +## Window: Wi-Fi +card-wifi = WLAN +wifi-enable = Über WLAN verbinden +wifi-latency-warning = WLAN erhöht Latenz und Jitter; zum Zeichnen ist USB am besten. +wifi-starts-with-stream = Das WLAN wird eingeschaltet, sobald das Streaming startet. +wifi-address = Adresse +wifi-fingerprint = Fingerabdruck des Hosts +wifi-pair = Gerät koppeln +wifi-pair-cancel = Abbrechen +wifi-pair-hint = Scanne auf dem Tablet diesen QR-Code oder gib die PIN ein. +wifi-pin = PIN +wifi-qr-label = QR-Code zum Koppeln +wifi-pair-expires = Schließt in { $seconds } s +wifi-notice-paired = Mit { $device } gekoppelt. +wifi-notice-attempts = Kopplung geschlossen: zu viele falsche PINs. +wifi-notice-expired = Kopplung geschlossen: die Zeit ist abgelaufen. +wifi-paired-count = + { $count -> + [one] { $count } gekoppeltes Gerät + *[other] { $count } gekoppelte Geräte + } +wifi-paired-none = Noch keine Geräte gekoppelt. +wifi-forget = Entfernen +error-wifi = Das WLAN kann nicht gestartet werden: { $reason } diff --git a/crates/ezd-tray/i18n/en/ezd-tray.ftl b/crates/ezd-tray/i18n/en/ezd-tray.ftl index cc77d91..6a66f91 100644 --- a/crates/ezd-tray/i18n/en/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/en/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Open the folder where ezdisplay writes its logs. about-description = Open-source USB display for Android tablets. repository = Source code driver-reinstall = Reinstall the driver + +## Window: Wi-Fi +card-wifi = Wi-Fi +wifi-enable = Connect over Wi-Fi +wifi-latency-warning = Wi-Fi adds latency and jitter; USB is best for drawing. +wifi-starts-with-stream = Wi-Fi turns on when streaming starts. +wifi-address = Address +wifi-fingerprint = Host fingerprint +wifi-pair = Pair a device +wifi-pair-cancel = Cancel +wifi-pair-hint = On the tablet, scan this QR code or type the PIN. +wifi-pin = PIN +wifi-qr-label = Pairing QR code +wifi-pair-expires = Closes in { $seconds } s +wifi-notice-paired = Paired with { $device }. +wifi-notice-attempts = Pairing closed: too many wrong PINs. +wifi-notice-expired = Pairing closed: time ran out. +wifi-paired-count = + { $count -> + [one] { $count } paired device + *[other] { $count } paired devices + } +wifi-paired-none = No devices are paired yet. +wifi-forget = Forget +error-wifi = Wi-Fi cannot start: { $reason } diff --git a/crates/ezd-tray/i18n/es/ezd-tray.ftl b/crates/ezd-tray/i18n/es/ezd-tray.ftl index 847090f..6eb9d00 100644 --- a/crates/ezd-tray/i18n/es/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/es/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Abre la carpeta donde ezdisplay guarda sus registros. about-description = Pantalla USB de código abierto para tablets Android. repository = Código fuente driver-reinstall = Reinstalar el controlador + +## Window: Wi-Fi +card-wifi = Wi-Fi +wifi-enable = Conectar por Wi-Fi +wifi-latency-warning = El Wi-Fi agrega latencia y jitter; el USB es lo mejor para dibujar. +wifi-starts-with-stream = El Wi-Fi se activa cuando empieza la transmisión. +wifi-address = Dirección +wifi-fingerprint = Huella del host +wifi-pair = Vincular un dispositivo +wifi-pair-cancel = Cancelar +wifi-pair-hint = En la tablet, escaneá este código QR o escribí el PIN. +wifi-pin = PIN +wifi-qr-label = Código QR de vinculación +wifi-pair-expires = Se cierra en { $seconds } s +wifi-notice-paired = Vinculada con { $device }. +wifi-notice-attempts = La vinculación se cerró: demasiados PIN incorrectos. +wifi-notice-expired = La vinculación se cerró: se acabó el tiempo. +wifi-paired-count = + { $count -> + [one] { $count } dispositivo vinculado + *[other] { $count } dispositivos vinculados + } +wifi-paired-none = Todavía no hay dispositivos vinculados. +wifi-forget = Olvidar +error-wifi = No se puede iniciar el Wi-Fi: { $reason } diff --git a/crates/ezd-tray/i18n/fr/ezd-tray.ftl b/crates/ezd-tray/i18n/fr/ezd-tray.ftl index 9168378..eb74f28 100644 --- a/crates/ezd-tray/i18n/fr/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/fr/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Ouvre le dossier où ezdisplay écrit ses journaux. about-description = Écran USB open source pour tablettes Android. repository = Code source driver-reinstall = Réinstaller le pilote + +## Window: Wi-Fi +card-wifi = Wi-Fi +wifi-enable = Se connecter par Wi-Fi +wifi-latency-warning = Le Wi-Fi ajoute de la latence et de la gigue ; l'USB est préférable pour dessiner. +wifi-starts-with-stream = Le Wi-Fi s'active quand la diffusion démarre. +wifi-address = Adresse +wifi-fingerprint = Empreinte de l'hôte +wifi-pair = Appairer un appareil +wifi-pair-cancel = Annuler +wifi-pair-hint = Sur la tablette, scannez ce QR code ou saisissez le code PIN. +wifi-pin = Code PIN +wifi-qr-label = QR code d'appairage +wifi-pair-expires = Se ferme dans { $seconds } s +wifi-notice-paired = Appairage réussi avec { $device }. +wifi-notice-attempts = L'appairage est fermé : trop de codes PIN incorrects. +wifi-notice-expired = L'appairage est fermé : le temps est écoulé. +wifi-paired-count = + { $count -> + [one] { $count } appareil appairé + *[other] { $count } appareils appairés + } +wifi-paired-none = Aucun appareil n'est encore appairé. +wifi-forget = Oublier +error-wifi = Impossible de démarrer le Wi-Fi : { $reason } diff --git a/crates/ezd-tray/i18n/it/ezd-tray.ftl b/crates/ezd-tray/i18n/it/ezd-tray.ftl index e88cab5..c884e7a 100644 --- a/crates/ezd-tray/i18n/it/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/it/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Apre la cartella in cui ezdisplay salva i log. about-description = Schermo USB open source per tablet Android. repository = Codice sorgente driver-reinstall = Reinstalla il driver + +## Window: Wi-Fi +card-wifi = Wi-Fi +wifi-enable = Connetti tramite Wi-Fi +wifi-latency-warning = Il Wi-Fi aggiunge latenza e jitter; l'USB è il migliore per disegnare. +wifi-starts-with-stream = Il Wi-Fi si attiva quando inizia lo streaming. +wifi-address = Indirizzo +wifi-fingerprint = Impronta dell'host +wifi-pair = Associa un dispositivo +wifi-pair-cancel = Annulla +wifi-pair-hint = Sul tablet, inquadra questo codice QR o digita il PIN. +wifi-pin = PIN +wifi-qr-label = Codice QR di associazione +wifi-pair-expires = Si chiude tra { $seconds } s +wifi-notice-paired = Associato con { $device }. +wifi-notice-attempts = Associazione chiusa: troppi PIN errati. +wifi-notice-expired = Associazione chiusa: il tempo è scaduto. +wifi-paired-count = + { $count -> + [one] { $count } dispositivo associato + *[other] { $count } dispositivi associati + } +wifi-paired-none = Nessun dispositivo è ancora associato. +wifi-forget = Dimentica +error-wifi = Impossibile avviare il Wi-Fi: { $reason } diff --git a/crates/ezd-tray/i18n/pt/ezd-tray.ftl b/crates/ezd-tray/i18n/pt/ezd-tray.ftl index adfba87..e0d0361 100644 --- a/crates/ezd-tray/i18n/pt/ezd-tray.ftl +++ b/crates/ezd-tray/i18n/pt/ezd-tray.ftl @@ -190,3 +190,28 @@ logs-description = Abre a pasta onde o ezdisplay grava seus logs. about-description = Tela USB de código aberto para tablets Android. repository = Código-fonte driver-reinstall = Reinstalar o driver + +## Window: Wi-Fi +card-wifi = Wi-Fi +wifi-enable = Conectar por Wi-Fi +wifi-latency-warning = O Wi-Fi acrescenta latência e jitter; o USB é o melhor para desenhar. +wifi-starts-with-stream = O Wi-Fi é ativado quando a transmissão começa. +wifi-address = Endereço +wifi-fingerprint = Impressão digital do host +wifi-pair = Parear um dispositivo +wifi-pair-cancel = Cancelar +wifi-pair-hint = No tablet, escaneie este QR code ou digite o PIN. +wifi-pin = PIN +wifi-qr-label = QR code de pareamento +wifi-pair-expires = Fecha em { $seconds } s +wifi-notice-paired = Pareado com { $device }. +wifi-notice-attempts = O pareamento foi fechado: PINs incorretos demais. +wifi-notice-expired = O pareamento foi fechado: o tempo acabou. +wifi-paired-count = + { $count -> + [one] { $count } dispositivo pareado + *[other] { $count } dispositivos pareados + } +wifi-paired-none = Ainda não há dispositivos pareados. +wifi-forget = Esquecer +error-wifi = Não foi possível iniciar o Wi-Fi: { $reason } diff --git a/crates/ezd-tray/src/config.rs b/crates/ezd-tray/src/config.rs index 3819d3b..81ae550 100644 --- a/crates/ezd-tray/src/config.rs +++ b/crates/ezd-tray/src/config.rs @@ -188,4 +188,22 @@ mod tests { (1000, 8) ); } + + #[cfg(feature = "wifi")] + #[test] + fn the_wifi_listener_is_off_by_default_and_round_trips() { + use ezd_host_service::WifiConfig; + assert_eq!(TrayConfig::default().service.wifi, None); + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("config.toml"); + let mut c = TrayConfig::default(); + c.service.wifi = Some(WifiConfig::default()); + save(&path, &c).unwrap(); + assert_eq!(load(&path).config, c); + let from_file: TrayConfig = + toml::from_str("[service.wifi]\nlisten = \"0.0.0.0:4000\"").unwrap(); + let wifi = from_file.service.wifi.unwrap(); + assert_eq!(wifi.listen.port(), 4000); + assert!(!wifi.pair_on_start); + } } diff --git a/crates/ezd-tray/src/controller.rs b/crates/ezd-tray/src/controller.rs index 17d2b5e..bf1007b 100644 --- a/crates/ezd-tray/src/controller.rs +++ b/crates/ezd-tray/src/controller.rs @@ -85,6 +85,8 @@ pub struct Controller { want_settings: bool, focus_window: bool, quitting: Option, + #[cfg_attr(not(feature = "wifi"), allow(dead_code))] + wifi: wifi::WifiRuntime, } impl Controller { @@ -117,6 +119,7 @@ impl Controller { want_settings: false, focus_window: false, quitting: None, + wifi: wifi::WifiRuntime::default(), } } @@ -214,6 +217,7 @@ impl Controller { self.status = rx.borrow().clone(); self.status_rx = Some(rx); self.service = Some(svc); + self.wifi_started(); } Err(e) => { tracing::warn!("cannot start the service: {e}"); @@ -226,6 +230,7 @@ impl Controller { fn stop_service(&mut self) { self.status_rx = None; self.status = HostStatus::Stopped; + self.wifi_stopped(); let Some(svc) = self.service.take() else { // Nothing to wait for. let _ = self.tx.send(Event::ServiceStopped); @@ -330,6 +335,7 @@ impl Controller { input_access, input_fix, has_licenses_dir: paths::licenses_dir().is_some(), + wifi: self.wifi_state(), windows: cfg!(windows), version: env!("CARGO_PKG_VERSION").to_string(), } @@ -342,6 +348,7 @@ impl Controller { snap.status = self.status.clone(); snap.config = self.config.clone(); snap.autostart = self.autostart; + snap.wifi = self.wifi_state(); snap.repair = self .repair .lock() @@ -381,6 +388,10 @@ impl Controller { Action::OpenUrl(u) => platform::open(&u), Action::Repair => self.repair_driver(), Action::EnableInput => self.enable_input(), + Action::SetWifi(on) => self.set_wifi(on), + Action::PairDevice => self.pair_device(), + Action::ClosePairing => self.close_pairing(), + Action::ForgetDevice(fp) => self.forget_device(&fp), } } } @@ -493,6 +504,7 @@ impl Controller { self.handle(ev); } self.poll_status(); + self.poll_wifi(); if let Some(q) = &mut self.quitting && !q.timed_out && q.since.elapsed() > QUIT_TIMEOUT @@ -599,5 +611,7 @@ pub fn forward_tray_events(tx: Sender, waker: Waker) { }); } +mod wifi; + #[cfg(test)] mod tests; diff --git a/crates/ezd-tray/src/controller/tests.rs b/crates/ezd-tray/src/controller/tests.rs index a49833a..59ad8ee 100644 --- a/crates/ezd-tray/src/controller/tests.rs +++ b/crates/ezd-tray/src/controller/tests.rs @@ -234,3 +234,73 @@ fn a_cancelled_enable_leaves_access_denied() { wait_for_input_fix(&f.ctl, &mut snap, InputFixState::Cancelled); assert_eq!(snap.input_access, InputAccess::Denied); } + +#[cfg(feature = "wifi")] +mod wifi { + use super::*; + use ezd_host_service::WifiConfig; + + fn wifi_fixture() -> Fixture { + let mut f = fixture(); + let mut c = f.ctl.config().clone(); + c.service.wifi = Some(WifiConfig { + listen: std::net::SocketAddr::from(([127, 0, 0, 1], 0)), + config_dir: Some(f.dir.path().join("wifi")), + ..WifiConfig::default() + }); + f.ctl.set_config(c, false); + f + } + + #[test] + fn the_card_follows_the_service_and_pairing_opens_and_closes() { + let mut f = wifi_fixture(); + assert!(f.ctl.snapshot().wifi.info.is_none()); + f.ctl.start(); + wait_until(&mut f.ctl, "listener", |c| c.snapshot().wifi.info.is_some()); + let snap = f.ctl.snapshot(); + assert!(snap.wifi.supported && snap.wifi.enabled); + // Nobody is paired yet, so the window opens by itself. + wait_until(&mut f.ctl, "the first window", |c| { + c.snapshot().wifi.pairing.is_some() + }); + let offer = f.ctl.snapshot().wifi.pairing.unwrap(); + assert_eq!(offer.pin.len(), 6); + assert!(offer.uri.starts_with("ezd://pair")); + f.ctl.dispatch(vec![Action::ClosePairing]); + wait_until(&mut f.ctl, "closed", |c| { + c.snapshot().wifi.pairing.is_none() + }); + f.ctl.dispatch(vec![Action::PairDevice]); + wait_until(&mut f.ctl, "reopened", |c| { + c.snapshot().wifi.pairing.is_some() + }); + assert!(f.ctl.snapshot().wifi.paired.is_empty()); + // Forgetting an unknown device changes nothing. + f.ctl.dispatch(vec![Action::ForgetDevice("abcd".into())]); + assert!(f.ctl.snapshot().wifi.paired.is_empty()); + } + + #[test] + fn switching_wifi_restarts_the_running_service_and_saves() { + let mut f = fixture(); + f.ctl.start(); + wait_until(&mut f.ctl, "waiting", waiting); + assert!(f.ctl.snapshot().wifi.info.is_none()); + // The default listener port may be taken on a developer machine; the switch itself is + // what is tested, so use a free one. + let mut c = f.ctl.config().clone(); + c.service.wifi = Some(WifiConfig { + listen: std::net::SocketAddr::from(([127, 0, 0, 1], 0)), + config_dir: Some(f.dir.path().join("wifi")), + ..WifiConfig::default() + }); + f.ctl.set_config(c, false); + f.ctl.dispatch(vec![Action::SetWifi(false)]); + wait_until(&mut f.ctl, "restarted", waiting); + assert!(f.ctl.config().service.wifi.is_none()); + assert!(!f.ctl.snapshot().wifi.enabled); + let saved = config::load(&f.dir.path().join("config.toml")).config; + assert!(saved.service.wifi.is_none()); + } +} diff --git a/crates/ezd-tray/src/controller/wifi.rs b/crates/ezd-tray/src/controller/wifi.rs new file mode 100644 index 0000000..132c05a --- /dev/null +++ b/crates/ezd-tray/src/controller/wifi.rs @@ -0,0 +1,171 @@ +//! Wi-Fi in the controller: the switch, the pairing window and the paired devices. Without the +//! `wifi` feature every method is a no-op and the card stays hidden. + +#![cfg_attr(not(feature = "wifi"), allow(dead_code))] + +use super::Controller; +use crate::ui::view::WifiState; +use ezd_host_service::HostEvent; +use tokio::sync::broadcast; + +/// What the controller knows about Wi-Fi besides the configuration. +#[derive(Default)] +pub(super) struct WifiRuntime { + /// Events of the running service. + events: Option>, + pairing: Option, + notice: Option, + paired: Vec, +} + +#[cfg(feature = "wifi")] +impl Controller { + /// The service just started: follow its events and pick up an open pairing window. + pub(super) fn wifi_started(&mut self) { + self.wifi = WifiRuntime::default(); + if let Some(svc) = &self.service { + self.wifi.events = Some(svc.events()); + // A window opened at start was announced before we subscribed. + svc.refresh_pairing(); + } + self.refresh_paired(); + } + + /// The service is going away. + pub(super) fn wifi_stopped(&mut self) { + self.wifi = WifiRuntime::default(); + } + + /// Applies the events that arrived since the last call. + pub(super) fn poll_wifi(&mut self) { + use crate::ui::view::{PairingOffer, WifiNotice}; + use ezd_host_service::PairingCloseReason; + use tokio::sync::broadcast::error::TryRecvError; + loop { + let Some(rx) = &mut self.wifi.events else { + return; + }; + match rx.try_recv() { + Ok(HostEvent::PairingOpen { + pin, uri, expires, .. + }) => { + self.wifi.notice = None; + self.wifi.pairing = Some(PairingOffer { pin, uri, expires }); + } + Ok(HostEvent::PairingClosed { reason }) => { + self.wifi.pairing = None; + match reason { + PairingCloseReason::TooManyAttempts => { + self.wifi.notice = Some(WifiNotice::TooManyAttempts); + } + PairingCloseReason::Expired => self.wifi.notice = Some(WifiNotice::Expired), + PairingCloseReason::Closed | PairingCloseReason::Paired => {} + } + } + Ok(HostEvent::Paired { device }) => { + self.wifi.notice = Some(WifiNotice::Paired(device)); + self.refresh_paired(); + } + Ok(_) => {} + Err(TryRecvError::Lagged(_)) => { + // Events were lost: ask for the window again and reread the devices. + if let Some(svc) = &self.service { + svc.refresh_pairing(); + } + self.refresh_paired(); + } + Err(TryRecvError::Empty | TryRecvError::Closed) => return, + } + } + } + + fn refresh_paired(&mut self) { + use crate::ui::view::PairedEntry; + let list = self.service.as_ref().and_then(|s| s.paired_devices()); + self.wifi.paired = match list { + Some(Ok(devices)) => devices + .into_iter() + .map(|d| PairedEntry { + name: d.name, + fingerprint: d.fingerprint, + }) + .collect(), + Some(Err(e)) => { + tracing::warn!("cannot read the paired devices: {e}"); + Vec::new() + } + None => Vec::new(), + }; + } + + /// Switches the Wi-Fi listener on or off. The service reads it only when it starts, so a + /// running service restarts (the tablet reconnects). + pub(super) fn set_wifi(&mut self, on: bool) { + if on == self.config.service.wifi.is_some() { + return; + } + let mut c = self.config.clone(); + c.service.wifi = on.then(ezd_host_service::WifiConfig::default); + self.set_config(c, false); + if self.lifecycle.wants_running() { + self.stop(); + self.start(); + } + } + + pub(super) fn pair_device(&mut self) { + if let Some(svc) = &self.service + && svc.open_pairing().is_none() + { + tracing::warn!("cannot open pairing: Wi-Fi is off"); + } + } + + pub(super) fn close_pairing(&mut self) { + if let Some(svc) = &self.service { + svc.close_pairing(); + } + } + + pub(super) fn forget_device(&mut self, fingerprint: &str) { + match self + .service + .as_ref() + .and_then(|s| s.forget_paired(fingerprint)) + { + Some(Ok(d)) => tracing::info!("forgot the paired device {}", d.name), + Some(Err(e)) => tracing::warn!("cannot forget the device: {e}"), + None => {} + } + self.refresh_paired(); + } + + /// What the Wi-Fi card shows. + pub(super) fn wifi_state(&self) -> WifiState { + WifiState { + supported: true, + enabled: self.config.service.wifi.is_some(), + info: self + .service + .as_ref() + .and_then(|s| s.wifi().borrow().clone()), + pairing: self.wifi.pairing.clone(), + paired: self.wifi.paired.clone(), + notice: self.wifi.notice.clone(), + } + } +} + +#[cfg(not(feature = "wifi"))] +impl Controller { + pub(super) fn wifi_started(&mut self) {} + pub(super) fn wifi_stopped(&mut self) {} + pub(super) fn poll_wifi(&mut self) {} + pub(super) fn set_wifi(&mut self, _on: bool) {} + pub(super) fn pair_device(&mut self) {} + pub(super) fn close_pairing(&mut self) {} + pub(super) fn forget_device(&mut self, _fingerprint: &str) {} + pub(super) fn wifi_state(&self) -> WifiState { + WifiState::default() + } +} diff --git a/crates/ezd-tray/src/menu_model.rs b/crates/ezd-tray/src/menu_model.rs index 5c47341..393170f 100644 --- a/crates/ezd-tray/src/menu_model.rs +++ b/crates/ezd-tray/src/menu_model.rs @@ -129,6 +129,7 @@ mod tests { devices: vec![], stats: None, input: None, + transport: ezd_host_service::Transport::Tcp, }) } diff --git a/crates/ezd-tray/src/text.rs b/crates/ezd-tray/src/text.rs index 740b260..bc0adf1 100644 --- a/crates/ezd-tray/src/text.rs +++ b/crates/ezd-tray/src/text.rs @@ -74,6 +74,7 @@ pub fn error_text(l: &FluentLanguageLoader, e: &ServiceError) -> String { reason = reason.as_str() ), ServiceError::UnsupportedPlatform => fl!(l, "error-unsupported"), + ServiceError::Wifi(reason) => fl!(l, "error-wifi", reason = reason.as_str()), ServiceError::Source(reason) => fl!(l, "error-source", reason = reason.as_str()), } } diff --git a/crates/ezd-tray/src/ui/mod.rs b/crates/ezd-tray/src/ui/mod.rs index 83504a5..c846cbd 100644 --- a/crates/ezd-tray/src/ui/mod.rs +++ b/crates/ezd-tray/src/ui/mod.rs @@ -3,6 +3,7 @@ pub mod app; pub mod fonts; pub mod glyphs; +pub mod qr; pub mod system_accent; pub mod theme; pub mod view; diff --git a/crates/ezd-tray/src/ui/qr.rs b/crates/ezd-tray/src/ui/qr.rs new file mode 100644 index 0000000..935f640 --- /dev/null +++ b/crates/ezd-tray/src/ui/qr.rs @@ -0,0 +1,66 @@ +//! A QR code drawn with the painter: black modules on a white square, which scanners need +//! whatever the theme is. + +use eframe::egui::{self, Color32, Role, Sense, Ui, WidgetInfo, vec2}; +use qrcode::{Color, EcLevel, QrCode}; + +/// Width of the quiet zone, in modules (the standard asks for four). +const QUIET_MODULES: usize = 4; + +/// The modules of `text` row by row (`true` is dark) and the width of the square, or `None` when +/// the text does not fit in a code. Low error correction keeps the code small. +pub fn modules(text: &str) -> Option<(usize, Vec)> { + let code = QrCode::with_error_correction_level(text, EcLevel::L).ok()?; + let dark = code + .to_colors() + .into_iter() + .map(|c| c == Color::Dark) + .collect(); + Some((code.width(), dark)) +} + +/// Draws the code of `text` in at most `side` points, with whole points per module so the edges +/// stay sharp. `label` names it for assistive technology. Draws nothing for text that does not +/// fit. +pub fn show(ui: &mut Ui, text: &str, side: f32, label: &str) { + let Some((width, dark)) = modules(text) else { + return; + }; + let total = width + 2 * QUIET_MODULES; + let cell = (side / total as f32).floor().max(1.0); + let size = cell * total as f32; + let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); + let painter = ui.painter(); + painter.rect_filled(rect, 6.0, Color32::WHITE); + let origin = rect.min + vec2(cell, cell) * QUIET_MODULES as f32; + for (i, _) in dark.iter().enumerate().filter(|(_, d)| **d) { + let (x, y) = ((i % width) as f32, (i / width) as f32); + let min = origin + vec2(x, y) * cell; + painter.rect_filled( + egui::Rect::from_min_size(min, vec2(cell, cell)), + 0.0, + Color32::BLACK, + ); + } + response.widget_info(|| WidgetInfo::labeled(Role::Image, true, label)); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_pairing_uri_fits_in_a_square_code() { + let (width, dark) = modules("ezd://pair?a=192.168.1.20:27183&pin=123456").unwrap(); + assert_eq!(dark.len(), width * width); + // Version 1 is 21 modules wide; the code grows by 4 per version. + assert!(width >= 21 && (width - 21) % 4 == 0); + // The top-left finder pattern starts with a dark module. + assert!(dark[0]); + } + + #[test] + fn text_too_long_for_a_code_gives_nothing() { + assert!(modules(&"x".repeat(10_000)).is_none()); + } +} diff --git a/crates/ezd-tray/src/ui/view.rs b/crates/ezd-tray/src/ui/view.rs index 7496640..a9991e7 100644 --- a/crates/ezd-tray/src/ui/view.rs +++ b/crates/ezd-tray/src/ui/view.rs @@ -3,6 +3,7 @@ //! the tray or the service, so tests render it with fake state. use super::glyphs; +use super::qr; use super::theme::{self, Palette}; use super::widgets::{self, Tone}; use crate::config::TrayConfig; @@ -11,12 +12,13 @@ use crate::state::Lifecycle; use crate::text; use eframe::egui::{self, ComboBox, Margin, RichText, Ui}; use ezd_host_service::{ - AdbMode, DeviceInfo, DeviceState, HdrChoice, HostStatus, LiveSession, PenChoice, + AdbMode, DeviceInfo, DeviceState, HdrChoice, HostStatus, LiveSession, PenChoice, WifiInfo, }; use ezd_proto::{DynamicRange, SdrReason}; use i18n_embed::fluent::FluentLanguageLoader; use i18n_embed_fl::fl; use std::path::PathBuf; +use std::time::Instant; pub const REPOSITORY_URL: &str = "https://github.com/LibreStatic/ezdisplay"; pub const SAMSUNG_DRIVER_URL: &str = "https://developer.samsung.com/android-usb-driver"; @@ -99,6 +101,49 @@ pub enum InputFixState { Error(String), } +/// An open pairing window of the service. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairingOffer { + /// The PIN to type on the tablet. + pub pin: String, + /// The `ezd://pair?...` text of the QR code. + pub uri: String, + /// When the window closes by itself. + pub expires: Instant, +} + +/// A device allowed to stream over Wi-Fi. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PairedEntry { + pub name: String, + /// Lower-case hex of the certificate fingerprint. + pub fingerprint: String, +} + +/// Why the last pairing window closed, when it did not end in a pairing request of the user. +#[cfg_attr(not(feature = "wifi"), allow(dead_code))] +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum WifiNotice { + /// A device paired. + Paired(String), + TooManyAttempts, + Expired, +} + +/// What the Wi-Fi card shows. +#[derive(Debug, Clone, PartialEq, Default)] +pub struct WifiState { + /// This build has the Wi-Fi transport; without it the card is hidden. + pub supported: bool, + /// Wi-Fi is switched on in the settings. + pub enabled: bool, + /// The listener, while the service runs with Wi-Fi. + pub info: Option, + pub pairing: Option, + pub paired: Vec, + pub notice: Option, +} + /// Everything the window shows, copied from the app each frame. #[derive(Debug, Clone)] pub struct Snapshot { @@ -113,12 +158,15 @@ pub struct Snapshot { pub input_access: InputAccess, pub input_fix: InputFixState, pub has_licenses_dir: bool, + pub wifi: WifiState, /// GPU choices and the USB driver hint are Windows-only. pub windows: bool, pub version: String, } /// What the user asked for; the app carries these out after the frame. +// A few actions per frame at most, so the size of `SetConfig` does not matter. +#[allow(clippy::large_enum_variant)] #[derive(Debug, Clone, PartialEq)] pub enum Action { /// The configuration changed (saved and passed to the service for the next session). @@ -136,6 +184,14 @@ pub enum Action { Repair, /// Install the udev rule that lets the app create input devices (asks for authorization). EnableInput, + /// Switch Wi-Fi on or off (the service restarts to apply it). + SetWifi(bool), + /// Open the pairing window with a new PIN. + PairDevice, + /// Close the pairing window. + ClosePairing, + /// Forget the paired device with this fingerprint (lower-case hex). + ForgetDevice(String), } #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] @@ -183,6 +239,8 @@ const PAGE_PADDING: i8 = 24; const CARD_GAP: f32 = 12.0; /// Width of the drop-down controls of the rows. const COMBO_WIDTH: f32 = 130.0; +/// Side of the pairing QR code, quiet zone included. +const QR_SIDE: f32 = 190.0; /// Narrowest a stat tile gets before the grid drops a column. const TILE_MIN_WIDTH: f32 = 140.0; @@ -1025,6 +1083,12 @@ impl SettingsView { ); ui.add_space(CARD_GAP); + // Wi-Fi. + if self.snap.wifi.supported { + wifi_card(ui, pal, l, &self.snap.wifi, actions); + ui.add_space(CARD_GAP); + } + // Advanced. widgets::disclosure( ui, @@ -1283,6 +1347,173 @@ fn info_rows(ui: &mut Ui, pal: Palette, rows: &[(String, String)]) { } } +/// The first 16 digits of a hex fingerprint in groups of four, as people compare them. +fn short_fingerprint(hex: &str) -> String { + hex.as_bytes() + .chunks(4) + .take(4) + .map(|c| String::from_utf8_lossy(c).into_owned()) + .collect::>() + .join("-") +} + +/// The Wi-Fi card: the switch with its latency warning, then, while the listener runs, the host +/// fingerprint, the pairing window (PIN and QR code) and the paired devices. +fn wifi_card( + ui: &mut Ui, + pal: Palette, + l: &FluentLanguageLoader, + wifi: &WifiState, + actions: &mut Vec, +) { + widgets::card( + ui, + pal, + Some((glyphs::ARROW_SWAP, &fl!(l, "card-wifi"))), + |ui| { + let mut on = wifi.enabled; + if widgets::toggle_row(ui, pal, &fl!(l, "wifi-enable"), None, &mut on).changed() { + actions.push(Action::SetWifi(on)); + } + // Always visible: the cost of Wi-Fi is the point of choosing it. + ui.horizontal_top(|ui| { + ui.label(RichText::new(glyphs::WARNING).size(16.0).color(pal.warning)); + ui.label( + RichText::new(fl!(l, "wifi-latency-warning")) + .size(13.0) + .color(pal.text_secondary), + ); + }); + ui.add_space(10.0); + if !wifi.enabled { + return; + } + let Some(info) = &wifi.info else { + widgets::row_divider(ui, pal); + ui.add_space(10.0); + ui.label( + RichText::new(fl!(l, "wifi-starts-with-stream")) + .size(13.0) + .color(pal.text_secondary), + ); + ui.add_space(10.0); + return; + }; + widgets::row_divider(ui, pal); + widgets::info_row(ui, pal, &fl!(l, "wifi-address"), &info.addr.to_string()); + widgets::row_divider(ui, pal); + widgets::info_row( + ui, + pal, + &fl!(l, "wifi-fingerprint"), + &info.fingerprint_short, + ); + widgets::row_divider(ui, pal); + pairing_block(ui, pal, l, wifi, actions); + widgets::row_divider(ui, pal); + ui.add_space(10.0); + ui.label( + RichText::new(fl!(l, "wifi-paired-count", count = wifi.paired.len())) + .size(13.0) + .color(pal.text_secondary), + ); + if wifi.paired.is_empty() { + widgets::empty_state(ui, pal, glyphs::TABLET, &fl!(l, "wifi-paired-none"), None); + } + for d in &wifi.paired { + widgets::row_divider(ui, pal); + ui.add_space(8.0); + ui.horizontal(|ui| { + ui.label(RichText::new(glyphs::TABLET).size(20.0).color(pal.text)); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + ui.label(RichText::new(&d.name).size(14.0).color(pal.text)); + ui.label( + RichText::new(short_fingerprint(&d.fingerprint)) + .size(12.0) + .color(pal.text_secondary), + ); + }); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if widgets::secondary_button(ui, pal, &fl!(l, "wifi-forget")).clicked() { + actions.push(Action::ForgetDevice(d.fingerprint.clone())); + } + }); + }); + ui.add_space(8.0); + } + }, + ); +} + +/// The pairing window: the PIN, the QR code and the time left, or the button that opens it. +fn pairing_block( + ui: &mut Ui, + pal: Palette, + l: &FluentLanguageLoader, + wifi: &WifiState, + actions: &mut Vec, +) { + ui.add_space(10.0); + if let Some(notice) = &wifi.notice { + let (text, color) = match notice { + WifiNotice::Paired(device) => ( + fl!(l, "wifi-notice-paired", device = device.as_str()), + pal.success, + ), + WifiNotice::TooManyAttempts => (fl!(l, "wifi-notice-attempts"), pal.warning), + WifiNotice::Expired => (fl!(l, "wifi-notice-expired"), pal.warning), + }; + ui.label(RichText::new(text).size(13.0).color(color)); + ui.add_space(8.0); + } + let Some(offer) = &wifi.pairing else { + if widgets::primary_button(ui, pal, &fl!(l, "wifi-pair")).clicked() { + actions.push(Action::PairDevice); + } + ui.add_space(10.0); + return; + }; + ui.label( + RichText::new(fl!(l, "wifi-pair-hint")) + .size(13.0) + .color(pal.text_secondary), + ); + ui.add_space(8.0); + ui.horizontal_top(|ui| { + qr::show(ui, &offer.uri, QR_SIDE, &fl!(l, "wifi-qr-label")); + ui.add_space(12.0); + ui.vertical(|ui| { + ui.label( + RichText::new(fl!(l, "wifi-pin")) + .size(13.0) + .color(pal.text_secondary), + ); + ui.label( + RichText::new(&offer.pin) + .size(32.0) + .strong() + .monospace() + .color(pal.text), + ); + let seconds = offer + .expires + .saturating_duration_since(Instant::now()) + .as_secs(); + ui.label( + RichText::new(fl!(l, "wifi-pair-expires", seconds = seconds)) + .size(13.0) + .color(pal.text_secondary), + ); + ui.add_space(8.0); + if widgets::secondary_button(ui, pal, &fl!(l, "wifi-pair-cancel")).clicked() { + actions.push(Action::ClosePairing); + } + }); + }); + ui.add_space(10.0); +} + /// An adb device: an icon coloured by its state and the line describing it. fn device_row(ui: &mut Ui, pal: Palette, l: &FluentLanguageLoader, d: &DeviceInfo) { let color = match d.state { diff --git a/crates/ezd-tray/src/ui/view/tests.rs b/crates/ezd-tray/src/ui/view/tests.rs index cac0f9a..a13a0b4 100644 --- a/crates/ezd-tray/src/ui/view/tests.rs +++ b/crates/ezd-tray/src/ui/view/tests.rs @@ -7,7 +7,7 @@ use eframe::egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; use ezd_host_core::LiveStats; -use ezd_host_service::{HdrChoice, LiveSession}; +use ezd_host_service::{HdrChoice, LiveSession, Transport}; use ezd_proto::{ClientStats, Codec, DynamicRange, SdrReason, StreamConfig}; use std::time::Duration; @@ -26,6 +26,7 @@ fn live(stats: Option) -> HostStatus { devices: vec![], stats, input: None, + transport: Transport::Tcp, }) } @@ -79,6 +80,7 @@ fn snapshot(status: HostStatus) -> Snapshot { input_access: InputAccess::Ok, input_fix: InputFixState::Idle, has_licenses_dir: false, + wifi: WifiState::default(), windows: false, version: "0.1.0".into(), } @@ -1241,3 +1243,155 @@ mod snapshots { page_snapshots(&mut results); } } + +fn wifi_snapshot(wifi: WifiState) -> Snapshot { + let mut snap = snapshot(HostStatus::Waiting { devices: vec![] }); + snap.wifi = wifi; + snap +} + +fn wifi_info() -> WifiInfo { + WifiInfo { + addr: "192.168.1.20:27183".parse().unwrap(), + fingerprint: "3f2a91c0aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa".into(), + fingerprint_short: "3f2a-91c0-aaaa-aaaa".into(), + host_name: "desk".into(), + pairing_open: false, + } +} + +fn wifi_on() -> WifiState { + WifiState { + supported: true, + enabled: true, + info: Some(wifi_info()), + ..WifiState::default() + } +} + +fn connection_page(snap: Snapshot, lang: &str) -> Harness<'static, SettingsView> { + // Tall enough for the whole page, so that nothing needs scrolling. + let mut h = harness_sized(snap, lang, egui::vec2(820.0, 1400.0)); + let nav = match lang { + "es" => "Conexi\u{f3}n", + "de" => "Verbindung", + _ => "Connection", + }; + h.get_by_role_and_label(Role::Button, nav).click(); + h.run(); + h +} + +#[test] +fn the_wifi_card_is_hidden_without_support() { + let h = connection_page(wifi_snapshot(WifiState::default()), "en"); + assert!(h.query_by_label("Connect over Wi-Fi").is_none()); +} + +#[test] +fn the_wifi_switch_warns_about_latency_and_asks_to_turn_on() { + let wifi = WifiState { + supported: true, + ..WifiState::default() + }; + let mut h = connection_page(wifi_snapshot(wifi), "en"); + h.get_by_label("Wi-Fi adds latency and jitter; USB is best for drawing."); + // Off: nothing but the switch. + assert!(h.query_by_label("Pair a device").is_none()); + h.get_by_label("Connect over Wi-Fi").click(); + h.run(); + assert_eq!(h.state_mut().take_actions(), vec![Action::SetWifi(true)]); + + let h = connection_page( + wifi_snapshot(WifiState { + supported: true, + ..WifiState::default() + }), + "es", + ); + h.get_by_label("Conectar por Wi-Fi"); + h.get_by_label("El Wi-Fi agrega latencia y jitter; el USB es lo mejor para dibujar."); +} + +#[test] +fn enabled_wifi_without_a_listener_says_when_it_starts() { + let wifi = WifiState { + info: None, + ..wifi_on() + }; + let h = connection_page(wifi_snapshot(wifi), "en"); + h.get_by_label("Wi-Fi turns on when streaming starts."); + assert!(h.query_by_label("Pair a device").is_none()); +} + +#[test] +fn the_wifi_card_shows_the_fingerprint_and_opens_pairing() { + let mut h = connection_page(wifi_snapshot(wifi_on()), "en"); + h.get_by_label("3f2a-91c0-aaaa-aaaa"); + h.get_by_label("192.168.1.20:27183"); + h.get_by_label("No devices are paired yet."); + h.get_by_label("Pair a device").click(); + h.run(); + assert_eq!(h.state_mut().take_actions(), vec![Action::PairDevice]); +} + +#[test] +fn an_open_pairing_window_shows_the_pin_the_qr_code_and_can_be_cancelled() { + let wifi = WifiState { + pairing: Some(PairingOffer { + pin: "123456".into(), + uri: "ezd://pair?a=192.168.1.20:27183&pin=123456".into(), + expires: Instant::now() + Duration::from_secs(120), + }), + ..wifi_on() + }; + let mut h = connection_page(wifi_snapshot(wifi), "en"); + h.get_by_label("123456"); + h.get_by_role_and_label(Role::Image, "Pairing QR code"); + h.get_by_label_contains("Closes in 1"); + assert!(h.query_by_label("Pair a device").is_none()); + h.get_by_label("Cancel").click(); + h.run(); + assert_eq!(h.state_mut().take_actions(), vec![Action::ClosePairing]); +} + +#[test] +fn paired_devices_are_listed_and_can_be_forgotten() { + let wifi = WifiState { + paired: vec![ + PairedEntry { + name: "Galaxy Tab S9".into(), + fingerprint: "b00b".repeat(16), + }, + PairedEntry { + name: "Pixel Tablet".into(), + fingerprint: "c0de".repeat(16), + }, + ], + notice: Some(WifiNotice::Paired("Galaxy Tab S9".into())), + ..wifi_on() + }; + let mut h = connection_page(wifi_snapshot(wifi), "en"); + h.get_by_label("2 paired devices"); + h.get_by_label("Paired with Galaxy Tab S9."); + h.get_by_label("b00b-b00b-b00b-b00b"); + let forget: Vec<_> = h.get_all_by_label("Forget").collect(); + assert_eq!(forget.len(), 2); + forget[1].click(); + h.run(); + assert_eq!( + h.state_mut().take_actions(), + vec![Action::ForgetDevice("c0de".repeat(16))] + ); +} + +#[test] +fn pairing_notices_are_localized() { + let wifi = WifiState { + notice: Some(WifiNotice::TooManyAttempts), + ..wifi_on() + }; + let h = connection_page(wifi_snapshot(wifi), "de"); + h.get_by_label("Kopplung geschlossen: zu viele falsche PINs."); + h.get_by_label("Gerät koppeln"); +} diff --git a/docs/windows-testing.md b/docs/windows-testing.md index 5f02545..40374b9 100644 --- a/docs/windows-testing.md +++ b/docs/windows-testing.md @@ -97,6 +97,9 @@ the MUX mode) and, if possible, in a third pass that forces the GPU. - **Autostart:** sign out and back in; ezdisplay must start in the notification area (unless the "Start ezdisplay when you sign in" task was unchecked), elevated and without a UAC prompt. It is the logon trigger of the `ezdisplay` scheduled task (Task Scheduler Library); uninstalling deletes the task. +- **Firewall (Wi-Fi):** after installing, `netsh advfirewall firewall show rule name=all` must list + the two "ezdisplay Wi-Fi" inbound rules (UDP 27183, private profile); a reinstall must not + duplicate them and the uninstall must remove them. - **Uninstall** from *Settings*, *Apps*: afterwards Device Manager (*Display adapters*, with *View*, *Show hidden devices*) must not list "Virtual Display Driver", and `C:\Program Files\ezdisplay` must be gone. diff --git a/packaging/windows/ezdisplay.iss b/packaging/windows/ezdisplay.iss index 9d89449..108f601 100644 --- a/packaging/windows/ezdisplay.iss +++ b/packaging/windows/ezdisplay.iss @@ -155,6 +155,13 @@ Name: "{autodesktop}\ezdisplay"; Filename: "{app}\ezdisplay.exe"; Tasks: desktop ; level follows "run_elevated" in an existing config.toml (elevated by default). Filename: "{app}\ezdisplay.exe"; Parameters: "--autostart on"; Tasks: autostart; Flags: runhidden waituntilterminated Filename: "{app}\ezdisplay.exe"; Parameters: "--autostart off"; Tasks: not autostart; Flags: runhidden waituntilterminated +; Wi-Fi: tablets reach the host on UDP 27183. One inbound rule per executable, for the private +; profile only (a public network never gets the port). The delete first keeps a reinstall from +; stacking duplicates; it fails harmlessly on a first install. +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall delete rule name=""ezdisplay Wi-Fi (ezdisplay.exe)"""; Flags: runhidden waituntilterminated +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall delete rule name=""ezdisplay Wi-Fi (ezd-host.exe)"""; Flags: runhidden waituntilterminated +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall add rule name=""ezdisplay Wi-Fi (ezdisplay.exe)"" dir=in action=allow protocol=UDP localport=27183 profile=private program=""{app}\ezdisplay.exe"""; Flags: runhidden waituntilterminated +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall add rule name=""ezdisplay Wi-Fi (ezd-host.exe)"" dir=in action=allow protocol=UDP localport=27183 profile=private program=""{app}\ezd-host.exe"""; Flags: runhidden waituntilterminated ; Unelevated on purpose: the app asks the task to start its elevated copy. Filename: "{app}\ezdisplay.exe"; Description: "{cm:LaunchProgram,ezdisplay}"; Flags: postinstall nowait runasoriginaluser skipifsilent @@ -164,6 +171,9 @@ Filename: "{app}\ezdisplay.exe"; Description: "{cm:LaunchProgram,ezdisplay}"; Fl Filename: "{app}\ezdisplay.exe"; Parameters: "--quit"; RunOnceId: "QuitTray"; Flags: runhidden waituntilterminated ; The task launches the app elevated and carries the autostart trigger. Filename: "{sys}\schtasks.exe"; Parameters: "/delete /tn ezdisplay /f"; RunOnceId: "DeleteTask"; Flags: runhidden waituntilterminated +; The Wi-Fi firewall rules of [Run]. +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall delete rule name=""ezdisplay Wi-Fi (ezdisplay.exe)"""; RunOnceId: "FirewallTray"; Flags: runhidden waituntilterminated +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall delete rule name=""ezdisplay Wi-Fi (ezd-host.exe)"""; RunOnceId: "FirewallHost"; Flags: runhidden waituntilterminated Filename: "{app}\adb\adb.exe"; Parameters: "kill-server"; RunOnceId: "KillAdb"; Flags: runhidden waituntilterminated ; Only removes the driver if ezdisplay installed it. Exit code 3010 (reboot required) cannot be ; read from [UninstallRun], so no restart prompt is shown for it. From aa4aa7dedd1af4c0427c4db3c46a2dde5ad5fff6 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 15:18:34 -0300 Subject: [PATCH 05/14] Add Wi-Fi card snapshots and polish the pairing QR and paired list --- crates/ezd-tray/src/ui/qr.rs | 7 ++++ crates/ezd-tray/src/ui/view.rs | 2 + crates/ezd-tray/src/ui/view/tests.rs | 59 ++++++++++++++++++++++++++++ 3 files changed, 68 insertions(+) diff --git a/crates/ezd-tray/src/ui/qr.rs b/crates/ezd-tray/src/ui/qr.rs index 935f640..1dec9db 100644 --- a/crates/ezd-tray/src/ui/qr.rs +++ b/crates/ezd-tray/src/ui/qr.rs @@ -32,6 +32,13 @@ pub fn show(ui: &mut Ui, text: &str, side: f32, label: &str) { let (rect, response) = ui.allocate_exact_size(vec2(size, size), Sense::hover()); let painter = ui.painter(); painter.rect_filled(rect, 6.0, Color32::WHITE); + // The quiet zone is white on a white card in the light theme; an outline shows the square. + painter.rect_stroke( + rect, + 6.0, + egui::Stroke::new(1.0, ui.visuals().widgets.noninteractive.bg_stroke.color), + egui::StrokeKind::Inside, + ); let origin = rect.min + vec2(cell, cell) * QUIET_MODULES as f32; for (i, _) in dark.iter().enumerate().filter(|(_, d)| **d) { let (x, y) = ((i % width) as f32, (i / width) as f32); diff --git a/crates/ezd-tray/src/ui/view.rs b/crates/ezd-tray/src/ui/view.rs index a9991e7..db9ce83 100644 --- a/crates/ezd-tray/src/ui/view.rs +++ b/crates/ezd-tray/src/ui/view.rs @@ -1419,6 +1419,8 @@ fn wifi_card( ); if wifi.paired.is_empty() { widgets::empty_state(ui, pal, glyphs::TABLET, &fl!(l, "wifi-paired-none"), None); + } else { + ui.add_space(10.0); } for d in &wifi.paired { widgets::row_divider(ui, pal); diff --git a/crates/ezd-tray/src/ui/view/tests.rs b/crates/ezd-tray/src/ui/view/tests.rs index a13a0b4..3e54e75 100644 --- a/crates/ezd-tray/src/ui/view/tests.rs +++ b/crates/ezd-tray/src/ui/view/tests.rs @@ -1120,6 +1120,64 @@ mod snapshots { snap } + /// The Wi-Fi card on the Connection page, in each state. + fn wifi_snapshots(results: &mut egui_kittest::SnapshotResults) { + let off = WifiState { + supported: true, + ..WifiState::default() + }; + let pairing = WifiState { + pairing: Some(PairingOffer { + pin: "123456".into(), + uri: "ezd://pair?a=192.168.1.20:27183&pin=123456".into(), + // Already over, so that the countdown reads the same on every run. + expires: Instant::now(), + }), + ..wifi_on() + }; + let paired = WifiState { + paired: vec![ + PairedEntry { + name: "Galaxy Tab S9".into(), + fingerprint: "b00b".repeat(16), + }, + PairedEntry { + name: "Pixel Tablet".into(), + fingerprint: "c0de".repeat(16), + }, + ], + notice: Some(WifiNotice::Paired("Galaxy Tab S9".into())), + ..wifi_on() + }; + let size = egui::vec2(820.0, 1250.0); + let cases = [ + ("wifi_off", off, egui::Theme::Light, "en"), + ("wifi_on", wifi_on(), egui::Theme::Light, "en"), + ("wifi_pairing", pairing.clone(), egui::Theme::Light, "en"), + ("wifi_pairing", pairing.clone(), egui::Theme::Dark, "en"), + ("wifi_pairing", pairing.clone(), egui::Theme::Light, "es"), + ("wifi_pairing", pairing, egui::Theme::Light, "de"), + ("wifi_paired", paired, egui::Theme::Dark, "en"), + ]; + for (name, wifi, theme, lang) in cases { + let mut view = SettingsView::new(wifi_snapshot(wifi)); + view.section = Section::Connection; + let t = if theme == egui::Theme::Dark { + "dark" + } else { + "light" + }; + render( + view, + theme, + lang, + size, + &format!("{name}_{t}_{lang}"), + results, + ); + } + } + /// One snapshot per page, matching the mockups (`01` to `07`), the minimum size and the /// longest languages. fn page_snapshots(results: &mut egui_kittest::SnapshotResults) { @@ -1241,6 +1299,7 @@ mod snapshots { input_permission_snapshots(&mut results); hdr_snapshots(&mut results); page_snapshots(&mut results); + wifi_snapshots(&mut results); } } From 979df2768364047ebe4d428ad8ac4f13e67a1173 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:09:12 -0300 Subject: [PATCH 06/14] Share the Wi-Fi client logic and expose it to Android over JNI Move pairing, the paired-host store and the connect-with-retry loop into ezd-client-core, keep the fake client as a thin wrapper, and add the startWifi, wifiPair, wifiHosts, wifiForget and wifiIdentity entry points to ezd-android. --- Cargo.lock | 4 +- crates/ezd-android/Cargo.toml | 2 +- crates/ezd-android/src/bridge.rs | 136 ++++++++++- crates/ezd-android/src/lib.rs | 1 + crates/ezd-android/src/session.rs | 89 ++++++-- crates/ezd-android/src/wifi.rs | 308 +++++++++++++++++++++++++ crates/ezd-client-core/Cargo.toml | 7 + crates/ezd-client-core/src/lib.rs | 2 + crates/ezd-client-core/src/wifi.rs | 322 +++++++++++++++++++++++++++ crates/ezd-fake-client/Cargo.toml | 4 +- crates/ezd-fake-client/src/wifi.rs | 168 +++----------- crates/ezd-fake-client/tests/wifi.rs | 12 +- 12 files changed, 883 insertions(+), 172 deletions(-) create mode 100644 crates/ezd-android/src/wifi.rs create mode 100644 crates/ezd-client-core/src/wifi.rs diff --git a/Cargo.lock b/Cargo.lock index 10013b7..20cccbf 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1608,6 +1608,8 @@ version = "0.1.0-alpha.1" dependencies = [ "ezd-link", "ezd-proto", + "serde", + "serde_json", "thiserror 2.0.21", "tokio", "tracing", @@ -1628,8 +1630,6 @@ dependencies = [ "i18n-embed", "i18n-embed-fl", "rust-embed", - "serde", - "serde_json", "thiserror 2.0.21", "tokio", "tracing", diff --git a/crates/ezd-android/Cargo.toml b/crates/ezd-android/Cargo.toml index 535514d..e2586ba 100644 --- a/crates/ezd-android/Cargo.toml +++ b/crates/ezd-android/Cargo.toml @@ -15,7 +15,7 @@ crate-type = ["cdylib", "rlib"] [dependencies] serde.workspace = true serde_json.workspace = true -ezd-client-core = { path = "../ezd-client-core" } +ezd-client-core = { path = "../ezd-client-core", features = ["wifi"] } ezd-input.workspace = true ezd-link.workspace = true ezd-proto.workspace = true diff --git a/crates/ezd-android/src/bridge.rs b/crates/ezd-android/src/bridge.rs index c0effb1..a352cb9 100644 --- a/crates/ezd-android/src/bridge.rs +++ b/crates/ezd-android/src/bridge.rs @@ -5,14 +5,16 @@ use crate::caps::parse_caps; use crate::decoder::SendWindow; use crate::input::{mono_to_now_us, unpack_motion}; -use crate::session::Session; +use crate::session::{Session, Target}; +use crate::wifi; use ezd_client_core::now_us; use ezd_input::{InputConfig, InputEngine, ViewTransform}; +use ezd_link::identity::parse_fingerprint; use ezd_proto::Message; use jni::EnvUnowned; use jni::errors::ThrowRuntimeExAndDefault; use jni::objects::{JByteArray, JClass, JFloatArray, JIntArray, JLongArray, JObject, JString}; -use jni::sys::jint; +use jni::sys::{jboolean, jint}; use ndk::native_window::NativeWindow; use std::cell::RefCell; use std::sync::Mutex; @@ -116,6 +118,16 @@ fn window_from(env: &jni::Env<'_>, surface: &JObject<'_>) -> Option .map(SendWindow) } +/// Replaces the running session (if any) with one connecting to `target`. +fn start_session(window: Option, target: Target, caps: crate::caps::ParsedCaps) { + let mut guard = session(); + if let Some(old) = guard.take() { + old.stop(); + } + log::info!("start {target:?} surface={}", window.is_some()); + *guard = Some(Session::start(window, target, caps)); +} + /// `external fun start(surface: Surface?, host: String, port: Int, capsJson: String): String?` /// Returns null on success or an error message. #[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] @@ -140,17 +152,125 @@ pub extern "system" fn start<'local>( Err(e) => return err(e), }; let window = window_from(env, &surface); - let mut guard = session(); - if let Some(old) = guard.take() { - old.stop(); - } - log::info!("start {host}:{port} surface={}", window.is_some()); - *guard = Some(Session::start(window, host, port, caps)); + start_session(window, Target::Tcp { host, port }, caps); Ok(JString::null()) }) .resolve::() } +/// `external fun startWifi(surface: Surface?, addr: String, fingerprintHex: String, +/// stateDir: String, capsJson: String): String?` +/// Connects over Wi-Fi to the paired host with this certificate fingerprint. `addr` is +/// `ip:port` (a bare IP uses the default port). Returns null on success or an error message. +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn startWifi<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + surface: JObject<'local>, + addr: JString<'local>, + fingerprint_hex: JString<'local>, + state_dir: JString<'local>, + caps_json: JString<'local>, +) -> JString<'local> { + init_logging(); + env.with_env(|env| -> jni::errors::Result> { + let addr = addr.try_to_string(env)?; + let fingerprint_hex = fingerprint_hex.try_to_string(env)?; + let state_dir = state_dir.try_to_string(env)?; + let caps_json = caps_json.try_to_string(env)?; + let mut err = |m: String| env.new_string(m); + let Some(addr) = wifi::parse_addr(&addr) else { + return err(format!("bad address {addr}")); + }; + let Some(fingerprint) = parse_fingerprint(&fingerprint_hex) else { + return err("bad fingerprint".into()); + }; + let caps = match parse_caps(&caps_json) { + Ok(c) => c, + Err(e) => return err(e), + }; + let window = window_from(env, &surface); + let target = Target::Wifi { + addr, + fingerprint, + state_dir: state_dir.into(), + }; + start_session(window, target, caps); + Ok(JString::null()) + }) + .resolve::() +} + +/// `external fun wifiPair(addr: String, pinOrUri: String, deviceName: String, stateDir: String): +/// String` Blocks (call off the main thread). JSON, see [`wifi::pair_json`]. +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn wifiPair<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + addr: JString<'local>, + pin_or_uri: JString<'local>, + device_name: JString<'local>, + state_dir: JString<'local>, +) -> JString<'local> { + init_logging(); + env.with_env(|env| -> jni::errors::Result> { + let addr = addr.try_to_string(env)?; + let pin_or_uri = pin_or_uri.try_to_string(env)?; + let device_name = device_name.try_to_string(env)?; + let state_dir = state_dir.try_to_string(env)?; + let json = wifi::pair_json(&addr, &pin_or_uri, &device_name, state_dir.as_ref()); + env.new_string(json) + }) + .resolve::() +} + +/// `external fun wifiHosts(stateDir: String): String` JSON array of paired hosts. +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn wifiHosts<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + state_dir: JString<'local>, +) -> JString<'local> { + init_logging(); + env.with_env(|env| -> jni::errors::Result> { + let state_dir = state_dir.try_to_string(env)?; + env.new_string(wifi::hosts_json(state_dir.as_ref())) + }) + .resolve::() +} + +/// `external fun wifiForget(stateDir: String, fingerprint: String): Boolean` +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn wifiForget<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + state_dir: JString<'local>, + fingerprint: JString<'local>, +) -> jboolean { + init_logging(); + env.with_env(|env| -> jni::errors::Result { + let state_dir = state_dir.try_to_string(env)?; + let fingerprint = fingerprint.try_to_string(env)?; + Ok(wifi::forget(state_dir.as_ref(), &fingerprint)) + }) + .resolve::() +} + +/// `external fun wifiIdentity(stateDir: String): String` Short fingerprint of this device. +#[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] +pub extern "system" fn wifiIdentity<'local>( + mut env: EnvUnowned<'local>, + _class: JClass<'local>, + state_dir: JString<'local>, +) -> JString<'local> { + init_logging(); + env.with_env(|env| -> jni::errors::Result> { + let state_dir = state_dir.try_to_string(env)?; + env.new_string(wifi::identity_short(state_dir.as_ref())) + }) + .resolve::() +} + /// `external fun stop()` #[jni::jni_mangle("com.librestatic.ezdisplay.NativeBridge")] pub extern "system" fn stop<'local>(mut env: EnvUnowned<'local>, _class: JClass<'local>) { diff --git a/crates/ezd-android/src/lib.rs b/crates/ezd-android/src/lib.rs index a4b4120..9479bfb 100644 --- a/crates/ezd-android/src/lib.rs +++ b/crates/ezd-android/src/lib.rs @@ -13,6 +13,7 @@ pub mod color; pub mod input; pub mod status; pub mod tracker; +pub mod wifi; #[cfg(target_os = "android")] mod bridge; diff --git a/crates/ezd-android/src/session.rs b/crates/ezd-android/src/session.rs index 4ae57df..a52cc35 100644 --- a/crates/ezd-android/src/session.rs +++ b/crates/ezd-android/src/session.rs @@ -3,17 +3,53 @@ use crate::caps::ParsedCaps; use crate::decoder::{Cmd, DecoderCtl, SendWindow}; use crate::status::{Phase, Shared}; +use ezd_client_core::wifi::connect_paired; use ezd_client_core::{ ClientConfig, ClientEnd, ClientHandle, ClientHandler, CursorSnapshot, Flow, HandlerResult, run_client, }; use ezd_link::Link; +use ezd_proto::pair::Fingerprint; use ezd_proto::{CursorShape, StreamColor, StreamConfig, VideoFrame}; +use std::net::SocketAddr; +use std::path::PathBuf; use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; const CONNECT_TIMEOUT: Duration = Duration::from_secs(5); +/// Wi-Fi sessions retry while the host is busy or not reachable yet, up to this long. +const WIFI_CONNECT_TIMEOUT: Duration = Duration::from_secs(10); + +/// Where a session connects to. +#[derive(Debug, Clone)] +pub enum Target { + /// Raw TCP (the adb-reversed loopback port). + Tcp { + /// Host name or IP. + host: String, + /// TCP port. + port: u16, + }, + /// QUIC to a paired host, pinned to its certificate. + Wifi { + /// Host address. + addr: SocketAddr, + /// Fingerprint of the paired host certificate. + fingerprint: Fingerprint, + /// Directory with this device's identity and the paired hosts. + state_dir: PathBuf, + }, +} + +impl Target { + fn label(&self) -> String { + match self { + Target::Tcp { host, port } => format!("{host}:{port}"), + Target::Wifi { addr, .. } => addr.to_string(), + } + } +} /// A running (or finished) session. pub struct Session { @@ -84,17 +120,17 @@ impl ClientHandler for Handler { } impl Session { - /// Starts connecting to `host:port`. `window` may be `None` until the surface exists. - pub fn start(window: Option, host: String, port: u16, caps: ParsedCaps) -> Session { + /// Starts connecting to `target`. `window` may be `None` until the surface exists. + pub fn start(window: Option, target: Target, caps: ParsedCaps) -> Session { let handle = ClientHandle::new(); let shared = Arc::new(Shared::default()); - shared.set_phase(Phase::Connecting, format!("{host}:{port}")); + shared.set_phase(Phase::Connecting, target.label()); let dec = DecoderCtl::spawn(caps.caps.clone(), handle.clone(), shared.clone(), window); let thread = { let (handle, shared, dec) = (handle.clone(), shared.clone(), dec.clone()); std::thread::Builder::new() .name("ezd-client".into()) - .spawn(move || run(handle, shared, dec, host, port, caps)) + .spawn(move || run(handle, shared, dec, target, caps)) .expect("spawn client thread") }; Session { @@ -160,12 +196,32 @@ impl Session { } } +/// Opens the link to `target`; the error is the text for the status. +async fn connect(target: &Target) -> Result { + match target { + Target::Tcp { host, port } => { + let addr = format!("{host}:{port}"); + match tokio::time::timeout(CONNECT_TIMEOUT, Link::connect_tcp(addr.as_str())).await { + Ok(Ok(l)) => Ok(l), + Ok(Err(e)) => Err(format!("connect {addr}: {e}")), + Err(_) => Err(format!("connect {addr}: timed out")), + } + } + Target::Wifi { + addr, + fingerprint, + state_dir, + } => connect_paired(state_dir, *addr, *fingerprint, WIFI_CONNECT_TIMEOUT) + .await + .map_err(|e| format!("connect {addr}: {e}")), + } +} + fn run( handle: ClientHandle, shared: Arc, dec: Arc, - host: String, - port: u16, + target: Target, caps: ParsedCaps, ) { let rt = match tokio::runtime::Builder::new_current_thread() @@ -179,19 +235,14 @@ fn run( } }; rt.block_on(async { - let addr = format!("{host}:{port}"); - let link = - match tokio::time::timeout(CONNECT_TIMEOUT, Link::connect_tcp(addr.as_str())).await { - Ok(Ok(l)) => l, - Ok(Err(e)) => { - shared.set_phase(Phase::Failed, format!("connect {addr}: {e}")); - return; - } - Err(_) => { - shared.set_phase(Phase::Failed, format!("connect {addr}: timed out")); - return; - } - }; + let addr = target.label(); + let link = match connect(&target).await { + Ok(l) => l, + Err(e) => { + shared.set_phase(Phase::Failed, e); + return; + } + }; if handle.is_stopped() { shared.set_phase(Phase::Ended, "stopped"); return; diff --git a/crates/ezd-android/src/wifi.rs b/crates/ezd-android/src/wifi.rs new file mode 100644 index 0000000..1be052a --- /dev/null +++ b/crates/ezd-android/src/wifi.rs @@ -0,0 +1,308 @@ +//! Wi-Fi pairing and paired-host management behind the JNI calls, as plain functions returning +//! the JSON Kotlin reads. Portable, so it builds and tests on the host. + +use ezd_client_core::wifi::{ + PairRequest, StoredHost, WifiError, forget_host, load_hosts, load_identity, pair_host, +}; +use ezd_link::identity::fingerprint_short; +use ezd_link::pair::PairUri; +use ezd_link::quic::QuicError; +use ezd_proto::pair::{Refusal, is_valid_pin}; +use serde::Serialize; +use std::net::{IpAddr, SocketAddr}; +use std::path::Path; +use std::time::Duration; + +/// Port hosts listen on when an address comes without one. +pub const DEFAULT_PORT: u16 = 27183; + +/// How long a pairing may take (connect plus the SPAKE2 exchange). +const PAIR_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Serialize)] +struct HostJson<'a> { + name: &'a str, + fingerprint: &'a str, + #[serde(rename = "shortFp")] + short_fp: String, + #[serde(skip_serializing_if = "Option::is_none")] + addr: Option<&'a str>, +} + +fn host_json(h: &StoredHost) -> HostJson<'_> { + HostJson { + name: &h.name, + fingerprint: &h.fingerprint, + short_fp: h + .fingerprint_bytes() + .map(|fp| fingerprint_short(&fp)) + .unwrap_or_default(), + addr: h.addr.as_deref(), + } +} + +/// `host:port`, or a bare IP address that gets [`DEFAULT_PORT`]. +pub fn parse_addr(s: &str) -> Option { + let s = s.trim(); + s.parse::() + .ok() + .or_else(|| s.parse::().ok().map(|ip| (ip, DEFAULT_PORT).into())) +} + +/// The stable error code Kotlin maps to a localized message. +fn error_code(e: &WifiError) -> &'static str { + match e { + WifiError::Quic(QuicError::Refused(r)) => match r { + Refusal::WrongPin => "wrong_pin", + Refusal::PairingClosed => "pairing_closed", + Refusal::TooManyAttempts => "too_many_attempts", + Refusal::Busy => "busy", + Refusal::NotPaired => "not_paired", + }, + WifiError::Quic(QuicError::FingerprintMismatch) => "fingerprint_mismatch", + WifiError::Quic(QuicError::InvalidPin) => "invalid_pin", + WifiError::Quic(QuicError::Timeout) => "timeout", + WifiError::Quic(QuicError::Connect(_) | QuicError::Connection(_) | QuicError::Io(_)) => { + "unreachable" + } + _ => "other", + } +} + +fn failure(code: &str, message: &str) -> String { + serde_json::json!({ "ok": false, "error": code, "message": message }).to_string() +} + +/// Pairs with the host at `addr` (`host:port` or an IP) using a 6-digit PIN, or with the host a +/// scanned `ezd://pair?...` URI describes (the URI carries address, PIN and the fingerprint to +/// pin). Blocks until done. Returns `{"ok":true,"host":{name,fingerprint,shortFp}}` or +/// `{"ok":false,"error":,"message":}`. +pub fn pair_json(addr: &str, pin_or_uri: &str, device_name: &str, state_dir: &Path) -> String { + let input = pin_or_uri.trim(); + let req = if input.starts_with("ezd://") { + let Some(uri) = PairUri::parse(input) else { + return failure("invalid_uri", "not a pairing link"); + }; + PairRequest { + addr: uri.addr, + pin: uri.pin, + pinned: Some(uri.fingerprint), + device_name: device_name.into(), + } + } else { + let Some(addr) = parse_addr(addr) else { + return failure("invalid_address", "not a host address"); + }; + PairRequest { + addr, + pin: input.into(), + pinned: None, + device_name: device_name.into(), + } + }; + if !is_valid_pin(&req.pin) { + return failure("invalid_pin", "the PIN must be 6 digits"); + } + let rt = match tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + { + Ok(rt) => rt, + Err(e) => return failure("other", &format!("runtime: {e}")), + }; + let result = rt.block_on(async { + tokio::time::timeout(PAIR_TIMEOUT, pair_host(state_dir, &req)) + .await + .unwrap_or(Err(WifiError::Quic(QuicError::Timeout))) + }); + match result { + Ok(host) => serde_json::json!({ "ok": true, "host": host_json(&host) }).to_string(), + Err(e) => failure(error_code(&e), &e.to_string()), + } +} + +/// The paired hosts as a JSON array of `{name,fingerprint,shortFp,addr?}`; `[]` when there are +/// none or the store is unreadable. +pub fn hosts_json(state_dir: &Path) -> String { + let hosts = load_hosts(state_dir).unwrap_or_else(|e| { + tracing::warn!("cannot read the paired hosts: {e}"); + Vec::new() + }); + let list: Vec> = hosts.iter().map(host_json).collect(); + serde_json::to_string(&list).expect("hosts serialize") +} + +/// Forgets a paired host; false when it was unknown or the store failed. +pub fn forget(state_dir: &Path, fingerprint: &str) -> bool { + forget_host(state_dir, fingerprint).unwrap_or_else(|e| { + tracing::warn!("cannot forget the host: {e}"); + false + }) +} + +/// Short fingerprint of this device (created on first use); empty when the state is unusable. +pub fn identity_short(state_dir: &Path) -> String { + load_identity(state_dir) + .map(|id| fingerprint_short(&id.fingerprint())) + .unwrap_or_else(|e| { + tracing::warn!("cannot load the identity: {e}"); + String::new() + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use ezd_client_core::wifi::add_host; + use ezd_link::identity::{Identity, fingerprint_hex}; + use ezd_link::pair::{PairingWindow, host_pair}; + use ezd_link::quic::{Congestion, QuicServer}; + use std::path::PathBuf; + use std::sync::Arc; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> TempDir { + let dir = + std::env::temp_dir().join(format!("ezd-android-wifi-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + TempDir(dir) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn json(s: &str) -> serde_json::Value { + serde_json::from_str(s).unwrap() + } + + #[test] + fn addresses_default_to_the_host_port() { + assert_eq!( + parse_addr("192.168.1.5"), + Some("192.168.1.5:27183".parse().unwrap()) + ); + assert_eq!( + parse_addr(" 192.168.1.5:4000 "), + Some("192.168.1.5:4000".parse().unwrap()) + ); + assert_eq!(parse_addr("[fe80::1]:27183").map(|a| a.port()), Some(27183)); + assert_eq!(parse_addr("fe80::1").map(|a| a.port()), Some(27183)); + assert_eq!(parse_addr("not an address"), None); + } + + #[test] + fn hosts_json_lists_paired_hosts_with_short_fingerprints() { + let dir = TempDir::new("hosts"); + assert_eq!(hosts_json(&dir.0), "[]"); + add_host( + &dir.0, + StoredHost { + name: "desk".into(), + fingerprint: fingerprint_hex(&[0xab; 32]), + addr: Some("10.0.0.2:27183".into()), + }, + ) + .unwrap(); + add_host( + &dir.0, + StoredHost { + name: "laptop".into(), + fingerprint: fingerprint_hex(&[0x01; 32]), + addr: None, + }, + ) + .unwrap(); + let v = json(&hosts_json(&dir.0)); + assert_eq!(v[0]["name"], "desk"); + assert_eq!(v[0]["shortFp"], "abab-abab-abab-abab"); + assert_eq!(v[0]["addr"], "10.0.0.2:27183"); + assert_eq!(v[1]["fingerprint"], fingerprint_hex(&[0x01; 32])); + assert!(v[1].get("addr").is_none()); + + assert!(forget(&dir.0, &fingerprint_hex(&[0xab; 32]))); + assert!(!forget(&dir.0, &fingerprint_hex(&[0xab; 32]))); + assert_eq!(json(&hosts_json(&dir.0)).as_array().unwrap().len(), 1); + } + + #[test] + fn a_corrupt_store_lists_nothing() { + let dir = TempDir::new("corrupt"); + std::fs::create_dir_all(&dir.0).unwrap(); + std::fs::write(dir.0.join("hosts.json"), "nope").unwrap(); + assert_eq!(hosts_json(&dir.0), "[]"); + assert!(!forget(&dir.0, "00")); + } + + #[test] + fn the_identity_is_stable() { + let dir = TempDir::new("identity"); + let a = identity_short(&dir.0); + assert_eq!(a.len(), 19); + assert_eq!(identity_short(&dir.0), a); + } + + #[test] + fn bad_input_is_reported_with_a_code() { + let dir = TempDir::new("badinput"); + let v = json(&pair_json("nowhere", "123456", "tab", &dir.0)); + assert_eq!(v["ok"], false); + assert_eq!(v["error"], "invalid_address"); + let v = json(&pair_json("", "ezd://pair?a=bad", "tab", &dir.0)); + assert_eq!(v["error"], "invalid_uri"); + let v = json(&pair_json("127.0.0.1:1", "12", "tab", &dir.0)); + assert_eq!(v["error"], "invalid_pin"); + } + + #[test] + fn pairing_over_loopback_reports_the_host_and_then_a_wrong_pin() { + let dir = TempDir::new("pair"); + let host_id = Identity::generate().unwrap(); + let rt = tokio::runtime::Runtime::new().unwrap(); + let (addr, window) = rt.block_on(async { + let server = + QuicServer::bind("127.0.0.1:0".parse().unwrap(), &host_id, Congestion::Cubic) + .unwrap(); + let addr = server.local_addr().unwrap(); + let window = Arc::new(PairingWindow::default()); + window.open_with("123456".into(), Duration::from_secs(60)); + let w = window.clone(); + tokio::spawn(async move { + while let Some(accepted) = server.accept().await { + let Ok(conn) = accepted else { continue }; + let w = w.clone(); + tokio::spawn(async move { + if let Ok(opened) = conn.accept_open().await { + let _ = host_pair(opened, &w, "test host", |_| Ok(())).await; + } + }); + } + }); + (addr, window) + }); + + let v = json(&pair_json(&addr.to_string(), "654321", "tab", &dir.0)); + assert_eq!(v["ok"], false); + assert_eq!(v["error"], "wrong_pin"); + assert_eq!(hosts_json(&dir.0), "[]"); + + window.open_with("123456".into(), Duration::from_secs(60)); + let v = json(&pair_json(&addr.to_string(), " 123456 ", "tab", &dir.0)); + assert_eq!(v["ok"], true, "{v}"); + assert_eq!(v["host"]["name"], "test host"); + assert_eq!( + v["host"]["fingerprint"], + fingerprint_hex(&host_id.fingerprint()) + ); + assert_eq!( + v["host"]["shortFp"], + fingerprint_short(&host_id.fingerprint()) + ); + assert_eq!(json(&hosts_json(&dir.0))[0]["name"], "test host"); + } +} diff --git a/crates/ezd-client-core/Cargo.toml b/crates/ezd-client-core/Cargo.toml index 04c8f52..b80291f 100644 --- a/crates/ezd-client-core/Cargo.toml +++ b/crates/ezd-client-core/Cargo.toml @@ -8,9 +8,16 @@ authors.workspace = true repository.workspace = true rust-version.workspace = true +[features] +default = [] +# Wi-Fi (QUIC) client: paired host store, pairing and session connection (`wifi` module). +wifi = ["ezd-link/quic", "dep:serde", "dep:serde_json"] + [dependencies] ezd-link.workspace = true ezd-proto.workspace = true +serde = { workspace = true, optional = true } +serde_json = { workspace = true, optional = true } thiserror.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/crates/ezd-client-core/src/lib.rs b/crates/ezd-client-core/src/lib.rs index 997af12..25a5c55 100644 --- a/crates/ezd-client-core/src/lib.rs +++ b/crates/ezd-client-core/src/lib.rs @@ -11,6 +11,8 @@ mod handle; mod session; +#[cfg(feature = "wifi")] +pub mod wifi; pub use handle::{ClientHandle, ClientSnapshot, CursorSnapshot}; pub use session::{ diff --git a/crates/ezd-client-core/src/wifi.rs b/crates/ezd-client-core/src/wifi.rs new file mode 100644 index 0000000..298fa37 --- /dev/null +++ b/crates/ezd-client-core/src/wifi.rs @@ -0,0 +1,322 @@ +//! Wi-Fi (QUIC) client side shared by the Android app and the fake client: the store of paired +//! hosts, pairing (PIN or scanned URI) and opening sessions on a paired host. +//! +//! The client keeps its identity (`identity.crt`/`identity.key`) and the paired hosts +//! (`hosts.json`, a list keyed by certificate fingerprint) in a state directory. + +use ezd_link::Link; +use ezd_link::identity::{Identity, fingerprint_hex, parse_fingerprint, write_atomic}; +use ezd_link::pair::pair; +use ezd_link::quic::{Congestion, QuicError, connect}; +use ezd_proto::pair::{Fingerprint, Refusal}; +use serde::{Deserialize, Serialize}; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +const HOSTS_FILE: &str = "hosts.json"; +const RETRY_DELAY: Duration = Duration::from_millis(200); + +/// A host this client paired with. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct StoredHost { + /// Host name, as announced when pairing. + pub name: String, + /// Host certificate fingerprint, lower-case hex. + pub fingerprint: String, + /// Address the host was last reached at (`ip:port`), a fallback when discovery finds none. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub addr: Option, +} + +impl StoredHost { + /// The parsed fingerprint (validated on load, so `None` only for hand-built values). + pub fn fingerprint_bytes(&self) -> Option { + parse_fingerprint(&self.fingerprint) + } +} + +/// Why a Wi-Fi operation failed. +#[derive(Debug, thiserror::Error)] +pub enum WifiError { + /// No address was given. + #[error("no host address: pass an address or a pairing URI")] + NoAddress, + /// No paired host matches and there is no PIN to pair with. + #[error("not paired with this host: pass --pin or --uri")] + NotPaired, + /// The connection, the handshake or the pairing failed. + #[error("{0}")] + Quic(#[from] QuicError), + /// State directory problem. + #[error("{}: {source}", path.display())] + State { + /// The file or directory. + path: PathBuf, + /// The OS error. + source: std::io::Error, + }, + /// `hosts.json` does not parse; it was left untouched. + #[error("{} is corrupt: {reason}", path.display())] + Corrupt { + /// The file. + path: PathBuf, + /// What is wrong with it. + reason: String, + }, +} + +fn state_err(path: &Path) -> impl FnOnce(std::io::Error) -> WifiError + '_ { + move |source| WifiError::State { + path: path.to_path_buf(), + source, + } +} + +/// Loads the paired hosts; a missing file is an empty list, a corrupt one an error. +pub fn load_hosts(dir: &Path) -> Result, WifiError> { + let path = dir.join(HOSTS_FILE); + let data = match std::fs::read(&path) { + Ok(d) => d, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()), + Err(source) => return Err(WifiError::State { path, source }), + }; + let hosts: Vec = serde_json::from_slice(&data).map_err(|e| WifiError::Corrupt { + path: path.clone(), + reason: e.to_string(), + })?; + if hosts.iter().any(|h| h.fingerprint_bytes().is_none()) { + return Err(WifiError::Corrupt { + path, + reason: "invalid fingerprint".into(), + }); + } + Ok(hosts) +} + +fn save_hosts(dir: &Path, hosts: &[StoredHost]) -> Result<(), WifiError> { + let path = dir.join(HOSTS_FILE); + let json = serde_json::to_vec_pretty(hosts).expect("hosts serialize"); + write_atomic(&path, &json).map_err(|source| WifiError::State { path, source }) +} + +/// Adds `host`, replacing the entry with the same fingerprint (re-pairing renames or moves it). +pub fn add_host(dir: &Path, host: StoredHost) -> Result<(), WifiError> { + std::fs::create_dir_all(dir).map_err(state_err(dir))?; + let mut hosts = load_hosts(dir)?; + match hosts.iter_mut().find(|h| h.fingerprint == host.fingerprint) { + Some(existing) => *existing = host, + None => hosts.push(host), + } + save_hosts(dir, &hosts) +} + +/// Forgets the host with this fingerprint (either case); false when it was not paired. +pub fn forget_host(dir: &Path, fingerprint: &str) -> Result { + let mut hosts = load_hosts(dir)?; + let before = hosts.len(); + hosts.retain(|h| !h.fingerprint.eq_ignore_ascii_case(fingerprint)); + if hosts.len() == before { + return Ok(false); + } + save_hosts(dir, &hosts)?; + Ok(true) +} + +/// Loads the identity of this device from `dir`, creating it on first use. +pub fn load_identity(dir: &Path) -> Result { + std::fs::create_dir_all(dir).map_err(state_err(dir))?; + Identity::load_or_create(dir).map_err(state_err(dir)) +} + +/// What pairing needs. +#[derive(Debug, Clone)] +pub struct PairRequest { + /// Host address. + pub addr: SocketAddr, + /// The 6-digit PIN shown by the host. + pub pin: String, + /// Host certificate fingerprint when known (scanned URI); the handshake requires it. A bare + /// PIN is authenticated by the pairing itself. + pub pinned: Option, + /// Name announced to the host. + pub device_name: String, +} + +/// Pairs with a host and stores it. Nothing is stored on failure. +pub async fn pair_host(dir: &Path, req: &PairRequest) -> Result { + let id = load_identity(dir)?; + let conn = connect(req.addr, &id, req.pinned, Congestion::default()).await?; + let host = pair(conn, &req.pin, &req.device_name).await?; + let stored = StoredHost { + name: host.name, + fingerprint: fingerprint_hex(&host.fingerprint), + addr: Some(req.addr.to_string()), + }; + add_host(dir, stored.clone())?; + Ok(stored) +} + +/// Worth another session attempt: the host is not up yet, or still finishing the previous +/// session (`Busy`). +fn retryable(e: &QuicError) -> bool { + matches!( + e, + QuicError::Connect(_) + | QuicError::Connection(_) + | QuicError::Timeout + | QuicError::Io(_) + | QuicError::Refused(Refusal::Busy) + ) +} + +/// Opens a session on a paired host, retrying while it is unreachable or busy for up to +/// `timeout`. The result is the link to hand to the client. On success the address is stored as +/// the host's last known one. +pub async fn connect_paired( + dir: &Path, + addr: SocketAddr, + host: Fingerprint, + timeout: Duration, +) -> Result { + let id = load_identity(dir)?; + let cc = Congestion::default(); + let start = Instant::now(); + let link = loop { + let attempt = async { + connect(addr, &id, Some(host), cc) + .await? + .open_session() + .await + }; + match attempt.await { + Ok(l) => break l, + Err(e) if retryable(&e) && start.elapsed() < timeout => { + tracing::debug!("connect failed ({e}), retrying"); + tokio::time::sleep(RETRY_DELAY).await; + } + Err(e) => return Err(e.into()), + } + }; + remember_addr(dir, &fingerprint_hex(&host), addr); + Ok(link) +} + +/// Stores the address a host was reached at; failures only cost the fallback address. +fn remember_addr(dir: &Path, fingerprint: &str, addr: SocketAddr) { + let Ok(mut hosts) = load_hosts(dir) else { + return; + }; + let addr = addr.to_string(); + if let Some(h) = hosts.iter_mut().find(|h| h.fingerprint == fingerprint) + && h.addr.as_deref() != Some(&addr) + { + h.addr = Some(addr); + if let Err(e) = save_hosts(dir, &hosts) { + tracing::debug!("cannot store the host address: {e}"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct TempDir(PathBuf); + + impl TempDir { + fn new(tag: &str) -> TempDir { + let dir = std::env::temp_dir() + .join(format!("ezd-client-core-wifi-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + TempDir(dir) + } + } + + impl Drop for TempDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + fn host(name: &str, byte: u8, addr: Option<&str>) -> StoredHost { + StoredHost { + name: name.into(), + fingerprint: fingerprint_hex(&[byte; 32]), + addr: addr.map(Into::into), + } + } + + #[test] + fn a_missing_store_is_empty() { + let dir = TempDir::new("missing"); + assert!(load_hosts(&dir.0).unwrap().is_empty()); + assert!(!forget_host(&dir.0, &fingerprint_hex(&[1; 32])).unwrap()); + } + + #[test] + fn hosts_are_added_replaced_and_forgotten() { + let dir = TempDir::new("multi"); + add_host(&dir.0, host("desk", 1, Some("192.168.1.5:27183"))).unwrap(); + add_host(&dir.0, host("laptop", 2, None)).unwrap(); + assert_eq!(load_hosts(&dir.0).unwrap().len(), 2); + + // Same fingerprint replaces: name and address change, order is kept. + add_host(&dir.0, host("desk renamed", 1, Some("10.0.0.9:27183"))).unwrap(); + let hosts = load_hosts(&dir.0).unwrap(); + assert_eq!(hosts.len(), 2); + assert_eq!(hosts[0].name, "desk renamed"); + assert_eq!(hosts[0].addr.as_deref(), Some("10.0.0.9:27183")); + assert_eq!(hosts[1].name, "laptop"); + + // Forget is case-insensitive and leaves the others. + let upper = fingerprint_hex(&[1; 32]).to_uppercase(); + assert!(forget_host(&dir.0, &upper).unwrap()); + assert!(!forget_host(&dir.0, &upper).unwrap()); + let hosts = load_hosts(&dir.0).unwrap(); + assert_eq!(hosts, vec![host("laptop", 2, None)]); + } + + #[test] + fn the_json_round_trips_and_omits_a_missing_address() { + let hosts = vec![host("desk", 1, Some("1.2.3.4:5")), host("laptop", 2, None)]; + let json = serde_json::to_string(&hosts).unwrap(); + assert!(!json.contains("null")); + assert_eq!( + serde_json::from_str::>(&json).unwrap(), + hosts + ); + } + + #[test] + fn a_corrupt_store_is_an_error_and_is_left_alone() { + let dir = TempDir::new("corrupt"); + std::fs::create_dir_all(&dir.0).unwrap(); + std::fs::write(dir.0.join(HOSTS_FILE), "nope").unwrap(); + assert!(matches!(load_hosts(&dir.0), Err(WifiError::Corrupt { .. }))); + assert!(add_host(&dir.0, host("desk", 1, None)).is_err()); + assert_eq!(std::fs::read(dir.0.join(HOSTS_FILE)).unwrap(), b"nope"); + + std::fs::write( + dir.0.join(HOSTS_FILE), + r#"[{"name":"x","fingerprint":"abcd"}]"#, + ) + .unwrap(); + assert!(matches!(load_hosts(&dir.0), Err(WifiError::Corrupt { .. }))); + } + + #[test] + fn remembering_an_address_updates_only_that_host() { + let dir = TempDir::new("remember"); + add_host(&dir.0, host("desk", 1, None)).unwrap(); + add_host(&dir.0, host("laptop", 2, Some("9.9.9.9:1"))).unwrap(); + remember_addr( + &dir.0, + &fingerprint_hex(&[1; 32]), + "192.168.1.5:27183".parse().unwrap(), + ); + let hosts = load_hosts(&dir.0).unwrap(); + assert_eq!(hosts[0].addr.as_deref(), Some("192.168.1.5:27183")); + assert_eq!(hosts[1].addr.as_deref(), Some("9.9.9.9:1")); + } +} diff --git a/crates/ezd-fake-client/Cargo.toml b/crates/ezd-fake-client/Cargo.toml index be43437..b9b06f0 100644 --- a/crates/ezd-fake-client/Cargo.toml +++ b/crates/ezd-fake-client/Cargo.toml @@ -18,7 +18,7 @@ path = "src/main.rs" [features] default = ["wifi"] # Wi-Fi (QUIC) transport: `--wifi`, `--pin`, `--uri`. -wifi = ["ezd-link/quic", "dep:dirs", "dep:serde", "dep:serde_json"] +wifi = ["ezd-client-core/wifi", "ezd-link/quic", "dep:dirs"] [dependencies] dirs = { workspace = true, optional = true } @@ -32,8 +32,6 @@ ezd-proto.workspace = true i18n-embed.workspace = true i18n-embed-fl.workspace = true rust-embed.workspace = true -serde = { workspace = true, optional = true } -serde_json = { workspace = true, optional = true } thiserror.workspace = true tokio.workspace = true tracing.workspace = true diff --git a/crates/ezd-fake-client/src/wifi.rs b/crates/ezd-fake-client/src/wifi.rs index 1a62e0b..bd60d76 100644 --- a/crates/ezd-fake-client/src/wifi.rs +++ b/crates/ezd-fake-client/src/wifi.rs @@ -1,35 +1,23 @@ //! Wi-Fi (QUIC) connection of the fake client: pairing with a PIN, remembering the host, and -//! opening sessions on the paired host. +//! opening sessions on a paired host. The store and the connection logic are shared with the +//! Android app (`ezd_client_core::wifi`). //! -//! The client keeps its identity (`identity.crt`/`identity.key`) and the paired host -//! (`host.json`) in a state directory. +//! The client keeps its identity (`identity.crt`/`identity.key`) and the paired hosts +//! (`hosts.json`) in a state directory. +use ezd_client_core::wifi::{PairRequest, connect_paired, pair_host}; +pub use ezd_client_core::wifi::{StoredHost, WifiError, load_hosts}; use ezd_link::Link; -use ezd_link::identity::{Identity, fingerprint_hex, parse_fingerprint, write_atomic}; -use ezd_link::pair::{PairUri, pair}; -use ezd_link::quic::{Congestion, QuicError, connect}; -use ezd_proto::pair::{Fingerprint, Refusal}; -use serde::{Deserialize, Serialize}; +use ezd_link::pair::PairUri; use std::net::SocketAddr; -use std::path::{Path, PathBuf}; -use std::time::{Duration, Instant}; - -const HOST_FILE: &str = "host.json"; +use std::path::PathBuf; +use std::time::Duration; /// The default state directory: `ezdisplay-fake-client` inside the user's config directory. pub fn default_state_dir() -> Option { dirs::config_dir().map(|d| d.join("ezdisplay-fake-client")) } -/// The host this client paired with. -#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] -pub struct StoredHost { - /// Host name, as announced when pairing. - pub name: String, - /// Host certificate fingerprint, lower-case hex. - pub fingerprint: String, -} - /// What to connect to and how. #[derive(Debug, Clone)] pub struct WifiOptions { @@ -39,7 +27,7 @@ pub struct WifiOptions { pub pin: Option, /// Pairing URI (pins the host fingerprint and carries a PIN). pub uri: Option, - /// Identity and paired host live here. + /// Identity and paired hosts live here. pub state_dir: PathBuf, /// Name announced when pairing. pub device_name: String, @@ -47,36 +35,6 @@ pub struct WifiOptions { pub connect_timeout: Duration, } -/// Why the Wi-Fi connection failed. -#[derive(Debug, thiserror::Error)] -pub enum WifiError { - /// No address was given. - #[error("no host address: pass an address or a pairing URI")] - NoAddress, - /// No paired host and no PIN to pair with. - #[error("not paired with this host: pass --pin or --uri")] - NotPaired, - /// The connection, the handshake or the pairing failed. - #[error("{0}")] - Quic(#[from] QuicError), - /// State directory problem. - #[error("{}: {source}", path.display())] - State { - /// The file or directory. - path: PathBuf, - /// The OS error. - source: std::io::Error, - }, - /// `host.json` does not parse; it was left untouched. - #[error("{} is corrupt: {reason}", path.display())] - Corrupt { - /// The file. - path: PathBuf, - /// What is wrong with it. - reason: String, - }, -} - /// What happened besides the connection, for the caller to tell the user. #[derive(Debug, Clone, PartialEq, Eq)] pub struct WifiOutcome { @@ -84,101 +42,45 @@ pub struct WifiOutcome { pub paired_with: Option, } -/// Loads the stored host; a missing file is `None`, a corrupt one an error. -pub fn load_host(dir: &Path) -> Result, WifiError> { - let path = dir.join(HOST_FILE); - let data = match std::fs::read(&path) { - Ok(d) => d, - Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None), - Err(source) => return Err(WifiError::State { path, source }), - }; - let host: StoredHost = serde_json::from_slice(&data).map_err(|e| WifiError::Corrupt { - path: path.clone(), - reason: e.to_string(), - })?; - if parse_fingerprint(&host.fingerprint).is_none() { - return Err(WifiError::Corrupt { - path, - reason: "invalid fingerprint".into(), - }); - } - Ok(Some(host)) -} - -fn save_host(dir: &Path, host: &StoredHost) -> Result<(), WifiError> { - let path = dir.join(HOST_FILE); - let json = serde_json::to_vec_pretty(host).expect("host serializes"); - write_atomic(&path, &json).map_err(|source| WifiError::State { path, source }) -} - -/// Worth another session attempt: the host is not up yet, or still finishing the previous -/// session (`Busy`). -fn retryable(e: &QuicError) -> bool { - matches!( - e, - QuicError::Connect(_) - | QuicError::Connection(_) - | QuicError::Timeout - | QuicError::Io(_) - | QuicError::Refused(Refusal::Busy) - ) -} - -/// Pairs if asked to, then opens a session. The result is the link to hand to +/// Pairs if asked to, then opens a session. Without pairing, the host is the paired one stored +/// for `addr`, or the only paired host. The result is the link to hand to /// [`run_fake_client`](crate::run_fake_client). pub async fn connect_wifi(opts: &WifiOptions) -> Result<(Link, WifiOutcome), WifiError> { let addr = opts .addr .or(opts.uri.as_ref().map(|u| u.addr)) .ok_or(WifiError::NoAddress)?; - std::fs::create_dir_all(&opts.state_dir).map_err(|source| WifiError::State { - path: opts.state_dir.clone(), - source, - })?; - let id = Identity::load_or_create(&opts.state_dir).map_err(|source| WifiError::State { - path: opts.state_dir.clone(), - source, - })?; - let cc = Congestion::default(); - let pin = opts .pin .clone() .or(opts.uri.as_ref().map(|u| u.pin.clone())); let mut paired_with = None; - let host_fp: Fingerprint = if let Some(pin) = pin { - // The URI pins the host certificate; a bare PIN is authenticated by the pairing itself. - let pinned = opts.uri.as_ref().map(|u| u.fingerprint); - let conn = connect(addr, &id, pinned, cc).await?; - let host = pair(conn, &pin, &opts.device_name).await?; - let stored = StoredHost { - name: host.name, - fingerprint: fingerprint_hex(&host.fingerprint), + let fingerprint = if let Some(pin) = pin { + let req = PairRequest { + addr, + pin, + // The URI pins the host certificate. + pinned: opts.uri.as_ref().map(|u| u.fingerprint), + device_name: opts.device_name.clone(), }; - save_host(&opts.state_dir, &stored)?; + let stored = pair_host(&opts.state_dir, &req).await?; + let fp = stored.fingerprint_bytes().expect("fresh pairing"); paired_with = Some(stored); - host.fingerprint + fp } else { - let host = load_host(&opts.state_dir)?.ok_or(WifiError::NotPaired)?; - parse_fingerprint(&host.fingerprint).expect("checked by load_host") - }; - - let start = Instant::now(); - let link = loop { - let attempt = async { - connect(addr, &id, Some(host_fp), cc) - .await? - .open_session() - .await - }; - match attempt.await { - Ok(l) => break l, - Err(e) if retryable(&e) && start.elapsed() < opts.connect_timeout => { - tracing::debug!("connect failed ({e}), retrying"); - tokio::time::sleep(Duration::from_millis(200)).await; - } - Err(e) => return Err(e.into()), - } + let hosts = load_hosts(&opts.state_dir)?; + let by_addr = hosts + .iter() + .find(|h| h.addr.as_deref() == Some(addr.to_string().as_str())); + let host = by_addr + .or(if hosts.len() == 1 { + hosts.first() + } else { + None + }) + .ok_or(WifiError::NotPaired)?; + host.fingerprint_bytes().expect("checked by load_hosts") }; + let link = connect_paired(&opts.state_dir, addr, fingerprint, opts.connect_timeout).await?; Ok((link, WifiOutcome { paired_with })) } diff --git a/crates/ezd-fake-client/tests/wifi.rs b/crates/ezd-fake-client/tests/wifi.rs index 7c8f31c..cb1fc7a 100644 --- a/crates/ezd-fake-client/tests/wifi.rs +++ b/crates/ezd-fake-client/tests/wifi.rs @@ -2,7 +2,7 @@ //! with the stored pairing and no PIN. #![cfg(feature = "wifi")] -use ezd_fake_client::wifi::{WifiError, WifiOptions, connect_wifi, load_host}; +use ezd_fake_client::wifi::{WifiError, WifiOptions, connect_wifi, load_hosts}; use ezd_fake_client::{ClientEnd, FakeClientConfig, run_fake_client}; use ezd_ffmpeg::{SwVideoSource, encoder_available}; use ezd_host_core::run_host_session; @@ -134,7 +134,7 @@ async fn pairs_with_a_pin_then_reconnects_without_one() { assert_eq!(report.end, ClientEnd::FramesReached); assert!(report.frames_decoded >= 30); assert_eq!( - load_host(&dir.0).unwrap().unwrap().fingerprint, + load_hosts(&dir.0).unwrap()[0].fingerprint, ezd_link::identity::fingerprint_hex(&host_id.fingerprint()) ); @@ -168,7 +168,7 @@ async fn a_wrong_pin_is_refused_and_nothing_is_stored() { matches!(err, WifiError::Quic(QuicError::Refused(_))), "{err:?}" ); - assert!(load_host(&dir.0).unwrap().is_none()); + assert!(load_hosts(&dir.0).unwrap().is_empty()); host.abort(); } @@ -201,7 +201,7 @@ async fn a_uri_pins_the_host_and_supplies_address_and_pin() { matches!(err, WifiError::Quic(QuicError::FingerprintMismatch)), "{err:?}" ); - assert!(load_host(&dir.0).unwrap().is_none()); + assert!(load_hosts(&dir.0).unwrap().is_empty()); let (_link, outcome) = connect_wifi(&opts(uri(host_id.fingerprint()))) .await @@ -214,6 +214,6 @@ async fn a_uri_pins_the_host_and_supplies_address_and_pin() { fn a_corrupt_host_file_is_an_error() { let dir = TempDir::new("corrupt"); std::fs::create_dir_all(&dir.0).unwrap(); - std::fs::write(dir.0.join("host.json"), "nope").unwrap(); - assert!(matches!(load_host(&dir.0), Err(WifiError::Corrupt { .. }))); + std::fs::write(dir.0.join("hosts.json"), "nope").unwrap(); + assert!(matches!(load_hosts(&dir.0), Err(WifiError::Corrupt { .. }))); } From 29a5da50314f51f71ce28ac52ce5cca8e9c7f22d Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:09:12 -0300 Subject: [PATCH 07/14] Add Wi-Fi connection to the Android client Discover hosts with NsdManager, pair by PIN or ezd://pair link, fall back from USB to a paired host, and add a Connection settings section for all layouts, localized in six languages. --- android/app/src/main/AndroidManifest.xml | 19 +- .../com/librestatic/ezdisplay/MainActivity.kt | 99 +++- .../com/librestatic/ezdisplay/NativeBridge.kt | 23 + .../librestatic/ezdisplay/SettingsActivity.kt | 36 +- .../ezdisplay/settings/ConnectionSection.kt | 445 ++++++++++++++++++ .../ezdisplay/settings/SettingsScreen.kt | 20 +- .../ezdisplay/settings/SettingsStore.kt | 132 +++++- .../ezdisplay/wifi/HostDiscovery.kt | 192 ++++++++ .../librestatic/ezdisplay/wifi/WifiBackend.kt | 40 ++ .../librestatic/ezdisplay/wifi/WifiModel.kt | 155 ++++++ .../app/src/main/res/drawable/ic_computer.xml | 13 + .../app/src/main/res/drawable/ic_delete.xml | 13 + .../src/main/res/drawable/ic_fingerprint.xml | 13 + android/app/src/main/res/drawable/ic_link.xml | 13 + android/app/src/main/res/drawable/ic_wifi.xml | 13 + .../app/src/main/res/values-de/strings.xml | 47 ++ .../app/src/main/res/values-es/strings.xml | 49 ++ .../app/src/main/res/values-fr/strings.xml | 49 ++ .../app/src/main/res/values-it/strings.xml | 49 ++ .../app/src/main/res/values-pt/strings.xml | 49 ++ android/app/src/main/res/values/strings.xml | 47 ++ .../ezdisplay/settings/FakeWifiBackend.kt | 30 ++ .../settings/SettingsConnectionTest.kt | 263 +++++++++++ .../settings/SettingsScreenshotTest.kt | 50 +- .../ezdisplay/settings/SettingsUiTestBase.kt | 15 +- .../ezdisplay/wifi/WifiModelTest.kt | 124 +++++ 26 files changed, 1968 insertions(+), 30 deletions(-) create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/HostDiscovery.kt create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiBackend.kt create mode 100644 android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt create mode 100644 android/app/src/main/res/drawable/ic_computer.xml create mode 100644 android/app/src/main/res/drawable/ic_delete.xml create mode 100644 android/app/src/main/res/drawable/ic_fingerprint.xml create mode 100644 android/app/src/main/res/drawable/ic_link.xml create mode 100644 android/app/src/main/res/drawable/ic_wifi.xml create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/FakeWifiBackend.kt create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt create mode 100644 android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml index 6c75377..71ec566 100644 --- a/android/app/src/main/AndroidManifest.xml +++ b/android/app/src/main/AndroidManifest.xml @@ -1,8 +1,15 @@ - + + + + + + android:theme="@style/Theme.EzDisplay.Settings"> + + + + + + + + diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index 57b2fdd..e54cb7d 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -29,6 +29,11 @@ import android.widget.FrameLayout import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView +import com.librestatic.ezdisplay.settings.SettingsStore +import com.librestatic.ezdisplay.wifi.HostDiscovery +import com.librestatic.ezdisplay.wifi.NativeWifiBackend +import com.librestatic.ezdisplay.wifi.WifiChoice +import com.librestatic.ezdisplay.wifi.chooseWifiTarget import org.json.JSONObject import java.nio.ByteBuffer import java.nio.ByteOrder @@ -41,12 +46,17 @@ import java.util.Locale * While streaming, every pointer event is forwarded to the native input engine, which sends * touch/pen input to the host and drives the local zoom of the [stage] (surface + cursor). * Outside of streaming a settings button is shown. + * + * Connection order: USB first (the adb-reversed loopback port). When that fails and Wi-Fi is enabled in the settings + * with a paired host known, the next attempt goes to that host over Wi-Fi; if the Wi-Fi attempt fails the next one is + * USB again, so plugging the cable in always wins. */ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCallback { private companion object { const val TAG = "ezdisplay" const val HOST = "127.0.0.1" const val PORT = 27183 + const val LAST_WIFI_HOST = "wifi_last_host" const val BACKOFF_MIN_MS = 1000L const val BACKOFF_MAX_MS = 5000L const val STATS_INTERVAL_MS = 250L @@ -111,6 +121,11 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private val connectRunnable = Runnable { connect() } + private lateinit var discovery: HostDiscovery + private val wifi by lazy { NativeWifiBackend(this) } + private var activeWifi: WifiChoice? = null // set while the current session is over Wi-Fi + private var tryWifiNext = false // the loopback connection just failed: try the paired host + override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) @@ -121,6 +136,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } } pickDisplayMode() + discovery = HostDiscovery(this) { } buildUi() hideSystemBars() } @@ -231,6 +247,21 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall override fun onResume() { super.onResume() applyInputConfig() + updateDiscovery() + } + + private fun wifiEnabled() = InputPrefs.prefs(this).getBoolean(SettingsStore.WIFI_ENABLED, false) + + /** Looks for hosts on the network while the waiting screen is up and Wi-Fi is enabled. */ + private fun updateDiscovery() { + if (started && !inputActive() && wifiEnabled()) discovery.start() else discovery.stop() + } + + /** The paired host to try over Wi-Fi, or null when Wi-Fi is off or no paired host has an address. */ + private fun wifiTarget(): WifiChoice? { + if (!wifiEnabled()) return null + val last = InputPrefs.prefs(this).getString(LAST_WIFI_HOST, null) + return chooseWifiTarget(wifi.hosts(), discovery.hosts, last) } private fun applyInputConfig() { @@ -241,8 +272,10 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall super.onStart() started = true backoffMs = BACKOFF_MIN_MS + tryWifiNext = false setStatus(getString(R.string.status_waiting, "$HOST:$PORT")) Choreographer.getInstance().postFrameCallback(this) + updateDiscovery() scheduleConnect(0) } @@ -251,6 +284,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall handler.removeCallbacks(connectRunnable) Choreographer.getInstance().removeFrameCallback(this) stopSession() + discovery.stop() super.onStop() } @@ -283,7 +317,16 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall if (!started || sessionActive) return if (!surfaceReady) return // surfaceCreated reschedules val caps = capsJson ?: Capabilities.toJson(this, chosenMode).also { capsJson = it } - val err = NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps) + val choice = if (tryWifiNext) wifiTarget() else null + tryWifiNext = false + val err = if (choice != null) { + NativeBridge.startWifi( + surfaceView.holder.surface, choice.addr, choice.host.fingerprint, + NativeWifiBackend.stateDir(this).absolutePath, caps, + ) + } else { + NativeBridge.start(surfaceView.holder.surface, HOST, PORT, caps) + } if (err != null) { Log.w(TAG, "start failed: $err") setStatus(getString(R.string.status_bad_caps, err)) @@ -292,6 +335,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall return } sessionActive = true + activeWifi = choice applyInputConfig() wasStreaming = false lastInputNote = "" @@ -303,14 +347,20 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall bufH = 0 fitSurface() frameRateSet = 0 - setStatus(getString(R.string.status_waiting, "$HOST:$PORT")) + setStatus( + if (choice != null) getString(R.string.status_wifi_connecting, hostLabel(choice)) + else getString(R.string.status_waiting, "$HOST:$PORT"), + ) } + private fun hostLabel(choice: WifiChoice) = choice.host.name.ifEmpty { choice.host.shortFp } + private fun stopSession() { if (sessionActive) { NativeBridge.stop() sessionActive = false } + activeWifi = null cursorVisible = false cursorView.visibility = View.GONE cursorSeq = 0 @@ -327,6 +377,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall /** The settings button is only available while input is not being forwarded. */ private fun updateChrome() { settingsButton.visibility = if (inputActive()) View.GONE else View.VISIBLE + updateDiscovery() } // --- Per-frame polling --- @@ -458,10 +509,16 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall bufH = bh fitSurface() } - val addr = "$HOST:$PORT" + val wifiChoice = activeWifi + val addr = if (wifiChoice != null) hostLabel(wifiChoice) else "$HOST:$PORT" when (j.optString("phase")) { - "connecting" -> setStatus(getString(R.string.status_waiting, addr)) - "handshaking" -> setStatus(getString(R.string.status_handshake, addr)) + "connecting" -> setStatus( + if (wifiChoice != null) getString(R.string.status_wifi_connecting, addr) + else getString(R.string.status_waiting, addr), + ) + "handshaking" -> setStatus( + getString(if (wifiChoice != null) R.string.status_wifi_handshake else R.string.status_handshake, addr), + ) "streaming" -> { if (!wasStreaming) { wasStreaming = true @@ -470,21 +527,26 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall streamW = j.optInt("width") streamH = j.optInt("height") val hz = formatHz(j.optInt("refresh_mhz")) - setStatus( - getString( - R.string.status_connected, streamW, streamH, hz, - j.optString("codec"), j.optString("decoder").takeIf { it != "null" }.orEmpty(), - ).trim(), - ) - statusHideAt = now + STATUS_HIDE_MS + val connected = getString( + R.string.status_connected, streamW, streamH, hz, + j.optString("codec"), j.optString("decoder").takeIf { it != "null" }.orEmpty(), + ).trim() + if (wifiChoice != null) { + InputPrefs.prefs(this).edit().putString(LAST_WIFI_HOST, wifiChoice.host.fingerprint).apply() + // Drawing over Wi-Fi works but feels different: say so, and keep it up a little longer. + setStatus(connected + "\n" + getString(R.string.status_wifi_latency)) + } else { + setStatus(connected) + } + statusHideAt = now + if (wifiChoice != null) NOTE_SHOW_MS else STATUS_HIDE_MS applyFrameRate(j.optInt("refresh_mhz")) } else if (statusHideAt != 0L && now >= statusHideAt) { statusHideAt = 0 statusView.visibility = View.GONE } } - "ended" -> disconnected(getString(R.string.status_ended, j.optString("detail"), addr)) - "failed" -> disconnected(getString(R.string.status_error, j.optString("detail"))) + "ended" -> disconnected(getString(R.string.status_ended, j.optString("detail"), addr), false) + "failed" -> disconnected(getString(R.string.status_error, j.optString("detail")), true) } val flags = if (j.isNull("client_flags")) 0 else j.optInt("client_flags") telemetryOn = (flags and 1) != 0 @@ -511,10 +573,17 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall statusHideAt = SystemClock.uptimeMillis() + ms } - private fun disconnected(message: String) { + private fun disconnected(message: String, failed: Boolean) { Log.i(TAG, "disconnected: $message") + val wasWifi = activeWifi != null stopSession() setStatus(message) + // The loopback connection failed (no cable, no adb reverse): try the paired host over Wi-Fi right away. + if (failed && !wasWifi && wifiTarget() != null) { + tryWifiNext = true + scheduleConnect(0) + return + } scheduleConnect(backoffMs) backoffMs = (backoffMs * 2).coerceAtMost(BACKOFF_MAX_MS) } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt index b6112ed..5cab151 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/NativeBridge.kt @@ -16,6 +16,29 @@ object NativeBridge { /** Starts one connection attempt to [host]:[port]. Returns null on success or an error message. */ @JvmStatic external fun start(surface: Surface?, host: String, port: Int, capsJson: String): String? + /** + * Starts one connection attempt over Wi-Fi to the paired host with certificate [fingerprintHex] at [addr] + * (`ip:port`). [stateDir] holds this device's identity and the paired hosts. Null on success, else an error. + */ + @JvmStatic external fun startWifi( + surface: Surface?, addr: String, fingerprintHex: String, stateDir: String, capsJson: String, + ): String? + + /** + * Pairs with the host at [addr] using a typed PIN, or with the host of an `ezd://pair?...` link in [pinOrUri]. + * Blocks (call off the main thread). JSON: `{ok, host:{name, fingerprint, shortFp}}` or `{ok:false, error, message}`. + */ + @JvmStatic external fun wifiPair(addr: String, pinOrUri: String, deviceName: String, stateDir: String): String + + /** Paired hosts as a JSON array of `{name, fingerprint, shortFp, addr?}`. */ + @JvmStatic external fun wifiHosts(stateDir: String): String + + /** Forgets a paired host; false when it was not paired. */ + @JvmStatic external fun wifiForget(stateDir: String, fingerprint: String): Boolean + + /** This device's short fingerprint (empty if the state is unusable). */ + @JvmStatic external fun wifiIdentity(stateDir: String): String + /** Stops the session; the decoder is released before this returns. */ @JvmStatic external fun stop() diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt index 4a59450..aa6c5f4 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt @@ -1,6 +1,8 @@ package com.librestatic.ezdisplay +import android.content.Intent import android.os.Bundle +import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge @@ -8,21 +10,53 @@ import com.librestatic.ezdisplay.settings.SettingsScreen import com.librestatic.ezdisplay.settings.SettingsStore import com.librestatic.ezdisplay.settings.SettingsTheme import com.librestatic.ezdisplay.settings.readAirActions +import com.librestatic.ezdisplay.settings.wifiErrorText +import com.librestatic.ezdisplay.wifi.HostDiscovery +import com.librestatic.ezdisplay.wifi.parsePairUri -/** Pen and touch input settings, stored in [InputPrefs]; MainActivity re-reads them on resume. */ +/** + * Pen and touch input settings, stored in [InputPrefs], and the Wi-Fi connection settings; MainActivity re-reads + * them on resume. Also opens the `ezd://pair?...` code of the PC host (the system camera starts it): the pairing + * dialog shows the host before anything is sent. + */ class SettingsActivity : ComponentActivity() { private lateinit var store: SettingsStore + private lateinit var discovery: HostDiscovery override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) enableEdgeToEdge() store = SettingsStore.create(this) + discovery = HostDiscovery(this) { store.setDiscovered(it) } + if (savedInstanceState == null) handlePairIntent(intent) setContent { SettingsTheme { SettingsScreen(store) } } } + override fun onNewIntent(intent: Intent) { + super.onNewIntent(intent) + setIntent(intent) + handlePairIntent(intent) + } + + private fun handlePairIntent(intent: Intent) { + if (intent.action != Intent.ACTION_VIEW) return + val link = parsePairUri(intent.dataString) + if (link == null) { + Toast.makeText(this, wifiErrorText("invalid_uri"), Toast.LENGTH_LONG).show() + return + } + store.startPairing(link) + } + override fun onResume() { super.onResume() // The user may have changed Samsung's Air actions while away. store.setAirActions(readAirActions(this)) + discovery.start() + } + + override fun onPause() { + discovery.stop() + super.onPause() } } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt new file mode 100644 index 0000000..b6ba66e --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt @@ -0,0 +1,445 @@ +package com.librestatic.ezdisplay.settings + +import androidx.annotation.StringRes +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.PaddingValues +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.heightIn +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material3.Button +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Switch +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.testTag +import androidx.compose.ui.res.pluralStringResource +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.semantics.Role +import androidx.compose.ui.semantics.role +import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.librestatic.ezdisplay.R +import com.librestatic.ezdisplay.wifi.DiscoveredHost +import com.librestatic.ezdisplay.wifi.PIN_LENGTH +import com.librestatic.ezdisplay.wifi.WifiHost +import com.librestatic.ezdisplay.wifi.fingerprintMatches +import com.librestatic.ezdisplay.wifi.isValidPin +import com.librestatic.ezdisplay.wifi.parseManualAddress + +private val RowMinHeight = 72.dp +private val RowPadding = PaddingValues(horizontal = 16.dp, vertical = 12.dp) + +/** The localized message of a pairing error code (`wifiPair` JSON `error`). */ +@StringRes +fun wifiErrorText(code: String?): Int = when (code) { + "wrong_pin" -> R.string.pair_error_wrong_pin + "pairing_closed" -> R.string.pair_error_closed + "too_many_attempts" -> R.string.pair_error_attempts + "busy" -> R.string.pair_error_busy + "unreachable" -> R.string.pair_error_unreachable + "timeout" -> R.string.pair_error_timeout + "fingerprint_mismatch" -> R.string.pair_error_fingerprint + "invalid_pin" -> R.string.pair_error_invalid_pin + "invalid_uri" -> R.string.pair_error_invalid_uri + "invalid_address" -> R.string.pair_error_invalid_address + else -> R.string.pair_error_other +} + +/** Discovered hosts that are not paired yet. */ +internal fun unpairedDiscovered(state: SettingsState): List = + state.discovered.filter { d -> state.wifiHosts.none { fingerprintMatches(it.fingerprint, d.shortFp) } } + +/** The whole Connection section: [WifiSwitchAndWarning] then [HostsContent]. */ +@Composable +fun ConnectionContent(state: SettingsState, actions: SettingsActions, modifier: Modifier = Modifier) { + Column(modifier.fillMaxWidth().testTag("connection_content"), verticalArrangement = Arrangement.spacedBy(12.dp)) { + WifiSwitchAndWarning(state, actions) + HostsContent(state, actions) + } +} + +/** The Wi-Fi switch and the latency warning under it. */ +@Composable +fun WifiSwitchAndWarning(state: SettingsState, actions: SettingsActions, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + Column(modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(12.dp)) { + WifiSwitchRow(state.wifiEnabled, actions::setWifiEnabled) + Surface( + shape = RoundedCornerShape(28.dp), color = colors.surfaceContainerHigh, + modifier = Modifier.fillMaxWidth().testTag("wifi_warning"), + ) { + Row(Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(10.dp)) { + Symbol(R.drawable.ic_info, tint = colors.onSurfaceVariant) + Text( + stringResource(R.string.wifi_latency_warning), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } + } + } +} + +/** + * Paired hosts (Forget), hosts found on the network (Pair), a manual address and this device's fingerprint. The + * pairing dialog itself is [PairDialog]. + */ +@Composable +fun HostsContent(state: SettingsState, actions: SettingsActions, modifier: Modifier = Modifier) { + val found = unpairedDiscovered(state) + Column(modifier.fillMaxWidth().testTag("hosts_content"), verticalArrangement = Arrangement.spacedBy(12.dp)) { + GroupTitle(R.string.wifi_paired_title) + HostGroup(count = state.wifiHosts.size, empty = R.string.wifi_paired_empty, emptyTag = "paired_empty") { i, shape -> + PairedRow(state.wifiHosts[i], shape, actions) + } + GroupTitle(R.string.wifi_discovered_title) + HostGroup(count = found.size, empty = R.string.wifi_discovered_empty, emptyTag = "discovered_empty") { i, shape -> + DiscoveredRow(found[i], shape, actions) + } + ManualAddress(actions) + DeviceFingerprint(state.deviceFingerprint) + } +} + +/** + * Wide page version of the section: the switch and warning, and a row that opens the hosts in a dialog, so the + * page keeps its height (it must not scroll). + */ +@Composable +fun ConnectionSummary(state: SettingsState, actions: SettingsActions, modifier: Modifier = Modifier) { + val colors = MaterialTheme.colorScheme + var open by rememberSaveable { mutableStateOf(false) } + Column(modifier.fillMaxWidth().testTag("connection_content"), verticalArrangement = Arrangement.spacedBy(12.dp)) { + WifiSwitchAndWarning(state, actions) + Surface( + onClick = { open = true }, + shape = RoundedCornerShape(24.dp), color = colors.surfaceBright, + modifier = Modifier.fillMaxWidth().testTag("connection_manage"), + ) { + Row( + Modifier.heightIn(min = RowMinHeight).padding(RowPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Symbol(R.drawable.ic_computer, tint = colors.secondary) + Column(Modifier.weight(1f)) { + Text( + stringResource(R.string.wifi_manage_title), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Text( + pluralStringResource(R.plurals.wifi_manage_summary, state.wifiHosts.size, state.wifiHosts.size), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } + Symbol(R.drawable.ic_chevron_right, tint = colors.primary) + } + } + } + if (open) { + Dialog(onDismissRequest = { open = false }, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Surface( + shape = RoundedCornerShape(28.dp), color = colors.surfaceContainer, + modifier = Modifier.widthIn(max = 560.dp).fillMaxWidth(0.9f).testTag("hosts_dialog"), + ) { + Column(Modifier.verticalScroll(rememberScrollState()).padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Row(verticalAlignment = Alignment.CenterVertically) { + Text( + stringResource(R.string.wifi_manage_title), Modifier.weight(1f), + style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.Bold, + ) + TextButton(onClick = { open = false }, modifier = Modifier.testTag("hosts_dialog_close")) { + Text(stringResource(R.string.wifi_manage_close)) + } + } + HostsContent(state, actions) + } + } + } + } +} + +@Composable +private fun PairedRow(h: WifiHost, shape: RoundedCornerShape, actions: SettingsActions) { + val name = h.name.ifEmpty { h.shortFp } + HostRow(icon = R.drawable.ic_link, title = name, subtitle = h.shortFp, shape = shape, tag = "paired_${h.fingerprint}") { + IconButton(onClick = { actions.forgetHost(h.fingerprint) }, modifier = Modifier.testTag("forget_${h.fingerprint}")) { + Symbol(R.drawable.ic_delete, contentDescription = stringResource(R.string.wifi_forget_cd, name)) + } + } +} + +@Composable +private fun DiscoveredRow(h: DiscoveredHost, shape: RoundedCornerShape, actions: SettingsActions) { + HostRow( + icon = R.drawable.ic_computer, title = h.name, subtitle = h.shortFp.ifEmpty { h.addr }, shape = shape, + tag = "discovered_${h.serviceName}", + ) { + TextButton( + onClick = { actions.startPairing(h.name, h.shortFp, h.addr) }, + modifier = Modifier.testTag("pair_${h.serviceName}"), + ) { + Text(stringResource(R.string.wifi_pair_action)) + } + } +} + +@Composable +private fun GroupTitle(@StringRes text: Int) { + Text( + stringResource(text), Modifier.padding(start = 8.dp, top = 4.dp), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) +} + +@Composable +private fun WifiSwitchRow(on: Boolean, onChange: (Boolean) -> Unit) { + val colors = MaterialTheme.colorScheme + Surface( + checked = on, + onCheckedChange = onChange, + shape = RoundedCornerShape(24.dp), + color = colors.surfaceBright, + modifier = Modifier.fillMaxWidth().semantics { role = Role.Switch }.testTag("wifi_row"), + ) { + Row( + Modifier.heightIn(min = RowMinHeight).padding(RowPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Symbol(R.drawable.ic_wifi, tint = colors.secondary) + Column(Modifier.weight(1f)) { + Text( + stringResource(R.string.wifi_switch_title), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Text( + stringResource(R.string.wifi_switch_desc), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } + Switch( + checked = on, + onCheckedChange = null, + thumbContent = if (on) { + { Symbol(R.drawable.ic_check, size = 16.dp) } + } else { + null + }, + ) + } + } +} + +/** A segmented group of [count] rows from [row], or one row with the [empty] text. */ +@Composable +private fun HostGroup( + count: Int, + @StringRes empty: Int, + emptyTag: String, + row: @Composable (index: Int, shape: RoundedCornerShape) -> Unit, +) { + Column(Modifier.fillMaxWidth(), verticalArrangement = Arrangement.spacedBy(2.dp)) { + if (count == 0) { + Surface(shape = RoundedCornerShape(24.dp), color = MaterialTheme.colorScheme.surfaceBright, modifier = Modifier.fillMaxWidth()) { + Text( + stringResource(empty), + Modifier.padding(RowPadding).testTag(emptyTag), + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } + } else { + repeat(count) { row(it, segmentShape(it, count)) } + } + } +} + +@Composable +private fun HostRow( + icon: Int, + title: String, + subtitle: String, + shape: RoundedCornerShape, + tag: String, + trailing: @Composable () -> Unit, +) { + val colors = MaterialTheme.colorScheme + Surface(shape = shape, color = colors.surfaceBright, modifier = Modifier.fillMaxWidth().testTag(tag)) { + Row( + Modifier.heightIn(min = RowMinHeight).padding(RowPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Surface(shape = RoundedCornerShape(14.dp), color = colors.secondaryContainer, modifier = Modifier.size(42.dp)) { + Box(contentAlignment = Alignment.Center) { Symbol(icon, tint = colors.onSecondaryContainer) } + } + Column(Modifier.weight(1f)) { + Text( + title, maxLines = 1, overflow = TextOverflow.Ellipsis, + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + if (subtitle.isNotEmpty()) { + Text(subtitle, style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant) + } + } + trailing() + } + } +} + +@Composable +private fun ManualAddress(actions: SettingsActions) { + val colors = MaterialTheme.colorScheme + var text by rememberSaveable { mutableStateOf("") } + val addr = parseManualAddress(text) + Surface(shape = RoundedCornerShape(24.dp), color = colors.surfaceBright, modifier = Modifier.fillMaxWidth().testTag("manual_row")) { + Column(Modifier.padding(RowPadding), verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + stringResource(R.string.wifi_manual_title), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + OutlinedTextField( + value = text, + onValueChange = { text = it.take(60) }, + modifier = Modifier.weight(1f).testTag("manual_field"), + label = { Text(stringResource(R.string.wifi_manual_label)) }, + singleLine = true, + isError = text.isNotBlank() && addr == null, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), + ) + Button( + onClick = { addr?.let { actions.startPairing(it, "", it) } }, + enabled = addr != null, + modifier = Modifier.testTag("manual_pair"), + ) { Text(stringResource(R.string.wifi_pair_action)) } + } + } + } +} + +@Composable +private fun DeviceFingerprint(shortFp: String) { + val colors = MaterialTheme.colorScheme + Surface(shape = RoundedCornerShape(24.dp), color = colors.surfaceBright, modifier = Modifier.fillMaxWidth().testTag("device_fp")) { + Row( + Modifier.heightIn(min = RowMinHeight).padding(RowPadding), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(12.dp), + ) { + Symbol(R.drawable.ic_fingerprint, tint = colors.secondary) + Column(Modifier.weight(1f)) { + Text( + stringResource(R.string.wifi_device_fp_title), + style = MaterialTheme.typography.titleSmall, fontWeight = FontWeight.Bold, + ) + Text( + stringResource(R.string.wifi_device_fp_desc), + style = MaterialTheme.typography.bodySmall, color = colors.onSurfaceVariant, + ) + } + Text( + shortFp.ifEmpty { "-" }, + style = MaterialTheme.typography.bodyMedium, fontWeight = FontWeight.Bold, + fontFamily = androidx.compose.ui.text.font.FontFamily.Monospace, + ) + } + } +} + +/** Summary line of the Connection section for the list. */ +@Composable +internal fun connectionSummary(state: SettingsState): String = + if (!state.wifiEnabled) stringResource(R.string.connection_summary_usb) + else pluralStringResource(R.plurals.connection_summary_wifi, state.wifiHosts.size, state.wifiHosts.size) + +/** The pairing dialog: PIN entry for a found or typed host, or the confirmation for a scanned code. */ +@Composable +fun PairDialog(pairing: PairingState, actions: SettingsActions) { + var pin by rememberSaveable { mutableStateOf("") } + val scanned = pairing.link != null + val canPair = !pairing.busy && (scanned || isValidPin(pin)) + Dialog( + onDismissRequest = { if (!pairing.busy) actions.cancelPairing() }, + properties = DialogProperties(usePlatformDefaultWidth = false), + ) { + Surface( + shape = RoundedCornerShape(28.dp), color = MaterialTheme.colorScheme.surfaceContainerHigh, + modifier = Modifier.widthIn(max = 560.dp).fillMaxWidth(0.9f).testTag("pair_dialog"), + ) { + Column(Modifier.padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text( + stringResource(R.string.pair_dialog_title, pairing.name), + style = MaterialTheme.typography.headlineSmall, + ) + if (pairing.shortFp.isNotEmpty()) { + Text( + stringResource(R.string.pair_dialog_fingerprint, pairing.shortFp), + Modifier.testTag("pair_fp"), + style = MaterialTheme.typography.bodyMedium, + ) + } + if (scanned) { + Text(stringResource(R.string.pair_dialog_scanned), style = MaterialTheme.typography.bodyMedium) + } else { + OutlinedTextField( + value = pin, + onValueChange = { v -> pin = v.filter { it in '0'..'9' }.take(PIN_LENGTH) }, + modifier = Modifier.fillMaxWidth().testTag("pin_field"), + label = { Text(stringResource(R.string.pair_dialog_pin_label)) }, + supportingText = { Text(stringResource(R.string.pair_dialog_pin_help)) }, + singleLine = true, + enabled = !pairing.busy, + isError = pairing.error != null, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), + ) + } + if (pairing.busy) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + CircularProgressIndicator(Modifier.size(24.dp), strokeWidth = 3.dp) + Text(stringResource(R.string.pair_dialog_busy), style = MaterialTheme.typography.bodyMedium) + } + } + pairing.error?.let { + Text( + stringResource(wifiErrorText(it)), Modifier.testTag("pair_error"), + style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.error, + ) + } + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End)) { + TextButton(onClick = actions::cancelPairing, enabled = !pairing.busy, modifier = Modifier.testTag("pair_cancel")) { + Text(stringResource(R.string.pair_dialog_cancel)) + } + TextButton(onClick = { actions.submitPairing(pin) }, enabled = canPair, modifier = Modifier.testTag("pair_confirm")) { + Text(stringResource(R.string.pair_dialog_confirm)) + } + } + } + } + } +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt index a7ede82..b66fb22 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt @@ -55,8 +55,8 @@ import androidx.compose.ui.unit.dp import com.librestatic.ezdisplay.InputPrefs import com.librestatic.ezdisplay.R -/** Settings sections; AirActions only exists while its card is shown. */ -enum class SettingsSection { Pen, Zoom, Touch, AirActions } +/** Settings sections; AirActions only exists while its card is shown (and is always last). */ +enum class SettingsSection { Pen, Zoom, Touch, Connection, AirActions } private fun airCardShown(state: SettingsState) = state.airActions == AirActions.On || state.airActions == AirActions.Unknown @@ -96,6 +96,7 @@ fun SettingsContent(state: SettingsState, actions: SettingsActions, modifier: Mo } } } + state.pairing?.let { PairDialog(it, actions) } } // ---------------------------------------------------------------- Shared content @@ -176,6 +177,8 @@ private fun PhoneMain(state: SettingsState, actions: SettingsActions, onOpenEdit SectionTitle(stringResource(R.string.section_touch)) PalmRow(state.palmRejection, actions::setPalmRejection) AirActionsCard(state.airActions, Modifier.padding(top = profileGap(2))) + SectionTitle(stringResource(R.string.section_connection)) + ConnectionContent(state, actions) } } } @@ -224,7 +227,7 @@ private fun ListDetailLayout( ) { val colors = MaterialTheme.colorScheme val sections = buildList { - add(SettingsSection.Pen); add(SettingsSection.Zoom); add(SettingsSection.Touch) + add(SettingsSection.Pen); add(SettingsSection.Zoom); add(SettingsSection.Touch); add(SettingsSection.Connection) if (airCardShown(state)) add(SettingsSection.AirActions) } val current = selected.takeIf { it in sections } ?: SettingsSection.Pen @@ -283,6 +286,7 @@ private fun ListDetailLayout( ) SettingsSection.Zoom -> ZoomGroup(state, actions) SettingsSection.Touch -> PalmRow(state.palmRejection, actions::setPalmRejection) + SettingsSection.Connection -> ConnectionContent(state, actions) SettingsSection.AirActions -> AirActionsCard(state.airActions) } } @@ -294,6 +298,7 @@ private fun sectionTitle(s: SettingsSection) = when (s) { SettingsSection.Pen -> R.string.settings_profile SettingsSection.Zoom -> R.string.section_zoom SettingsSection.Touch -> R.string.settings_palm_title + SettingsSection.Connection -> R.string.section_connection SettingsSection.AirActions -> R.string.section_air_actions } @@ -301,6 +306,7 @@ private fun sectionIcon(s: SettingsSection) = when (s) { SettingsSection.Pen -> R.drawable.ic_stylus SettingsSection.Zoom -> R.drawable.ic_zoom_in SettingsSection.Touch -> R.drawable.ic_back_hand + SettingsSection.Connection -> R.drawable.ic_wifi SettingsSection.AirActions -> R.drawable.ic_info } @@ -309,6 +315,7 @@ private fun sectionValue(s: SettingsSection, state: SettingsState): String = whe SettingsSection.Pen -> stringResource(Profiles.firstOrNull { it.value == state.profile }?.title ?: R.string.profile_raw) SettingsSection.Zoom -> stringResource(R.string.settings_zoom_summary, formatZoom(state.zoomFactor), state.doubleClickMs) SettingsSection.Touch -> stringResource(if (state.palmRejection) R.string.settings_on else R.string.settings_off) + SettingsSection.Connection -> connectionSummary(state) SettingsSection.AirActions -> stringResource(R.string.section_air_actions_value) } @@ -414,6 +421,10 @@ private fun WideLayout( PalmRow(state.palmRejection, actions::setPalmRejection) AirActionsCard(state.airActions, Modifier.padding(top = profileGap(3))) } + Column(Modifier.weight(1f)) { + WideHeading(stringResource(R.string.section_connection)) + ConnectionSummary(state, actions) + } } } else { WideHeading(stringResource(R.string.section_zoom)) @@ -422,6 +433,9 @@ private fun WideLayout( WideHeading(stringResource(R.string.section_touch)) PalmRow(state.palmRejection, actions::setPalmRejection) AirActionsCard(state.airActions, Modifier.padding(top = profileGap(2))) + Spacer(Modifier.height(20.dp)) + WideHeading(stringResource(R.string.section_connection)) + ConnectionSummary(state, actions) } } } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt index 5becfb2..d32cdf8 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsStore.kt @@ -3,6 +3,8 @@ package com.librestatic.ezdisplay.settings import android.content.Context import android.content.SharedPreferences import android.os.Build +import android.os.Handler +import android.os.Looper import android.provider.Settings import androidx.core.content.edit import androidx.compose.runtime.State @@ -10,6 +12,15 @@ import androidx.compose.runtime.mutableStateOf import com.librestatic.ezdisplay.InputPrefs import com.librestatic.ezdisplay.InputPrefs.KeyCombo import com.librestatic.ezdisplay.R +import com.librestatic.ezdisplay.wifi.DiscoveredHost +import com.librestatic.ezdisplay.wifi.NativeWifiBackend +import com.librestatic.ezdisplay.wifi.PairLink +import com.librestatic.ezdisplay.wifi.PairResult +import com.librestatic.ezdisplay.wifi.WifiBackend +import com.librestatic.ezdisplay.wifi.WifiHost +import com.librestatic.ezdisplay.wifi.isValidPin +import java.util.concurrent.Executor +import java.util.concurrent.Executors import kotlin.math.roundToInt /** State of the Samsung S Pen "Air actions" system setting. */ @@ -86,6 +97,29 @@ data class SettingsState( val doubleClickMs: Int = 300, val palmRejection: Boolean = true, val airActions: AirActions = AirActions.NotSamsung, + /** Connect over Wi-Fi when the USB connection is not there. */ + val wifiEnabled: Boolean = false, + val wifiHosts: List = emptyList(), + /** Hosts seen on the network right now (only while discovery runs). */ + val discovered: List = emptyList(), + /** This device's short certificate fingerprint, for the host to show; empty until known. */ + val deviceFingerprint: String = "", + /** The pairing dialog, when one is open. */ + val pairing: PairingState? = null, +) + +/** + * A pairing in progress. [link] is set when it comes from a scanned code (no PIN to type: the code has it); + * [shortFp] is empty for a manually typed address (the host's fingerprint is not known yet). + */ +data class PairingState( + val name: String, + val shortFp: String, + val addr: String, + val link: PairLink? = null, + val busy: Boolean = false, + /** Error code of the last attempt (see `wifiErrorText`). */ + val error: String? = null, ) private fun defaultKeys(): Map = mapOf( @@ -142,10 +176,30 @@ interface SettingsActions { fun setZoomFactor(factor: Float) fun setDoubleClickMs(ms: Int) fun setPalmRejection(on: Boolean) + fun setWifiEnabled(on: Boolean) + + /** Opens the PIN dialog for a host that was found or typed. */ + fun startPairing(name: String, shortFp: String, addr: String) + + /** Opens the confirmation for a scanned pairing code. */ + fun startPairing(link: PairLink) + + /** Pairs with the open dialog's host; [pin] is ignored for a scanned code. */ + fun submitPairing(pin: String) + fun cancelPairing() + fun forgetHost(fingerprint: String) } /** Holds [SettingsState] backed by the `input` prefs; every action persists at once with `apply()`. */ -class SettingsStore(private val prefs: SharedPreferences, airActions: AirActions) : SettingsActions { +class SettingsStore( + private val prefs: SharedPreferences, + airActions: AirActions, + private val wifi: WifiBackend = WifiBackend.None, + private val deviceName: String = Build.MODEL, + /** Runs the blocking pairing; replaced by a direct executor in tests. */ + private val io: Executor = Executors.newSingleThreadExecutor(), +) : SettingsActions { + private val main = Handler(Looper.getMainLooper()) private val _state = mutableStateOf(read(airActions)) val state: State get() = _state @@ -158,6 +212,9 @@ class SettingsStore(private val prefs: SharedPreferences, airActions: AirActions .coerceIn(InputPrefs.DOUBLE_CLICK_MIN, InputPrefs.DOUBLE_CLICK_MAX), palmRejection = prefs.getBoolean(InputPrefs.PALM_REJECTION, true), airActions = airActions, + wifiEnabled = prefs.getBoolean(WIFI_ENABLED, false), + wifiHosts = wifi.hosts(), + deviceFingerprint = wifi.identity(), ) override fun setProfile(profile: String) { @@ -214,7 +271,78 @@ class SettingsStore(private val prefs: SharedPreferences, airActions: AirActions _state.value = _state.value.copy(palmRejection = on) } + override fun setWifiEnabled(on: Boolean) { + prefs.edit { putBoolean(WIFI_ENABLED, on) } + _state.value = _state.value.copy(wifiEnabled = on) + } + + /** Hosts seen on the network changed. */ + fun setDiscovered(hosts: List) { + _state.value = _state.value.copy(discovered = hosts) + } + + /** Re-reads the paired hosts (they live in the native state, not in the prefs). */ + fun reloadHosts() { + _state.value = _state.value.copy(wifiHosts = wifi.hosts(), deviceFingerprint = wifi.identity()) + } + + override fun startPairing(name: String, shortFp: String, addr: String) { + _state.value = _state.value.copy(pairing = PairingState(name, shortFp, addr)) + } + + override fun startPairing(link: PairLink) { + _state.value = _state.value.copy( + pairing = PairingState(link.name.ifEmpty { link.addr }, link.shortFp, link.addr, link), + ) + } + + override fun cancelPairing() { + _state.value = _state.value.copy(pairing = null) + } + + override fun submitPairing(pin: String) { + val p = _state.value.pairing ?: return + if (p.busy) return + val input = p.link?.let { it.toUri() } ?: pin.trim() + if (p.link == null && !isValidPin(input)) { + _state.value = _state.value.copy(pairing = p.copy(error = "invalid_pin")) + return + } + _state.value = _state.value.copy(pairing = p.copy(busy = true, error = null)) + io.execute { + val result = wifi.pair(p.addr, input, deviceName) + main.post { pairingDone(p, result) } + } + } + + private fun pairingDone(p: PairingState, result: PairResult) { + // Ignore the answer of a dialog that was cancelled or replaced meanwhile (the host is paired anyway). + val current = _state.value.pairing + val hosts = wifi.hosts() + if (current?.addr != p.addr) { + _state.value = _state.value.copy(wifiHosts = hosts) + return + } + _state.value = if (result.ok) { + // Pairing means the user wants to use it: turn Wi-Fi on. + prefs.edit { putBoolean(WIFI_ENABLED, true) } + _state.value.copy(pairing = null, wifiHosts = hosts, wifiEnabled = true) + } else { + _state.value.copy(pairing = current.copy(busy = false, error = result.error ?: "other")) + } + } + + override fun forgetHost(fingerprint: String) { + wifi.forget(fingerprint) + _state.value = _state.value.copy(wifiHosts = wifi.hosts()) + } + companion object { - fun create(context: Context) = SettingsStore(InputPrefs.prefs(context), readAirActions(context)) + /** Pref key of the Wi-Fi switch, read by MainActivity. */ + const val WIFI_ENABLED = "wifi_enabled" + + fun create(context: Context) = SettingsStore( + InputPrefs.prefs(context), readAirActions(context), NativeWifiBackend(context), + ) } } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/HostDiscovery.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/HostDiscovery.kt new file mode 100644 index 0000000..53ab837 --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/HostDiscovery.kt @@ -0,0 +1,192 @@ +package com.librestatic.ezdisplay.wifi + +import android.content.Context +import android.net.nsd.NsdManager +import android.net.nsd.NsdServiceInfo +import android.net.wifi.WifiManager +import android.os.Build +import android.os.Handler +import android.os.Looper +import android.util.Log +import java.net.Inet4Address +import java.net.Inet6Address +import java.net.InetAddress +import java.util.concurrent.Executor + +/** + * Finds ezdisplay hosts (`_ezdisplay._udp`) on the network with [NsdManager]. Call [start] while a screen that + * needs the list is visible and [stop] when it is not. [onChange] runs on the main thread with the current list. + * + * API 34+ resolves with `registerServiceInfoCallback` (which also follows address changes); older versions resolve + * one service at a time with `resolveService`. + */ +class HostDiscovery(context: Context, private val onChange: (List) -> Unit) { + private val app = context.applicationContext + private val nsd = app.getSystemService(Context.NSD_SERVICE) as NsdManager + private val main = Handler(Looper.getMainLooper()) + private val mainExecutor = Executor { main.post(it) } + + private var running = false + private var lock: WifiManager.MulticastLock? = null + private val found = LinkedHashMap() + private val infoCallbacks = HashMap() + private val pendingResolve = ArrayDeque() + private var resolving = false + + /** The hosts found so far. */ + val hosts: List get() = found.values.toList() + + private val discoveryListener = object : NsdManager.DiscoveryListener { + override fun onDiscoveryStarted(serviceType: String) {} + override fun onDiscoveryStopped(serviceType: String) {} + override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { + Log.w(TAG, "discovery failed: $errorCode") + } + + override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {} + override fun onServiceFound(info: NsdServiceInfo) { + main.post { serviceFound(info) } + } + + override fun onServiceLost(info: NsdServiceInfo) { + main.post { serviceLost(info.serviceName) } + } + } + + /** Starts discovery; a no-op while running. */ + fun start() { + if (running) return + running = true + acquireMulticast() + try { + nsd.discoverServices(SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener) + } catch (e: RuntimeException) { + Log.w(TAG, "cannot start discovery", e) + running = false + releaseMulticast() + } + } + + /** Stops discovery and forgets what was found. */ + fun stop() { + if (!running) return + running = false + try { + nsd.stopServiceDiscovery(discoveryListener) + } catch (e: RuntimeException) { + Log.w(TAG, "cannot stop discovery", e) + } + if (Build.VERSION.SDK_INT >= 34) { + infoCallbacks.values.forEach { runCatching { nsd.unregisterServiceInfoCallback(it) } } + } + infoCallbacks.clear() + pendingResolve.clear() + resolving = false + releaseMulticast() + if (found.isNotEmpty()) { + found.clear() + onChange(emptyList()) + } + } + + private fun serviceFound(info: NsdServiceInfo) { + if (!running) return + if (Build.VERSION.SDK_INT >= 34) { + if (infoCallbacks.containsKey(info.serviceName)) return + val cb = object : NsdManager.ServiceInfoCallback { + override fun onServiceInfoCallbackRegistrationFailed(errorCode: Int) { + Log.w(TAG, "resolve ${info.serviceName} failed: $errorCode") + infoCallbacks.remove(info.serviceName) + } + + override fun onServiceUpdated(updated: NsdServiceInfo) = resolved(updated) + override fun onServiceLost() = serviceLost(info.serviceName) + override fun onServiceInfoCallbackUnregistered() {} + } + infoCallbacks[info.serviceName] = cb + nsd.registerServiceInfoCallback(info, mainExecutor, cb) + } else { + pendingResolve.add(info) + resolveNext() + } + } + + @Suppress("DEPRECATION") + private fun resolveNext() { + if (resolving) return + val info = pendingResolve.removeFirstOrNull() ?: return + resolving = true + nsd.resolveService( + info, + object : NsdManager.ResolveListener { + override fun onResolveFailed(serviceInfo: NsdServiceInfo, errorCode: Int) { + Log.w(TAG, "resolve ${serviceInfo.serviceName} failed: $errorCode") + main.post { resolving = false; resolveNext() } + } + + override fun onServiceResolved(serviceInfo: NsdServiceInfo) { + main.post { resolving = false; resolved(serviceInfo); resolveNext() } + } + }, + ) + } + + private fun resolved(info: NsdServiceInfo) { + if (!running) return + val addresses = if (Build.VERSION.SDK_INT >= 34) info.hostAddresses else listOfNotNull(legacyHost(info)) + val ip = pickAddress(addresses) ?: return + val txt = info.attributes.mapValues { (_, v) -> v?.toString(Charsets.UTF_8).orEmpty() } + val host = DiscoveredHost( + serviceName = info.serviceName, + name = txt["name"]?.takeIf { it.isNotBlank() } ?: info.serviceName, + shortFp = txt["fp"].orEmpty(), + addr = formatAddr(ip, info.port), + ) + if (found[info.serviceName] != host) { + found[info.serviceName] = host + onChange(hosts) + } + } + + @Suppress("DEPRECATION") + private fun legacyHost(info: NsdServiceInfo): InetAddress? = info.host + + private fun serviceLost(serviceName: String) { + if (Build.VERSION.SDK_INT >= 34) { + infoCallbacks.remove(serviceName)?.let { runCatching { nsd.unregisterServiceInfoCallback(it) } } + } + if (found.remove(serviceName) != null) onChange(hosts) + } + + private fun acquireMulticast() { + val wifi = app.getSystemService(Context.WIFI_SERVICE) as? WifiManager ?: return + lock = runCatching { + wifi.createMulticastLock("ezdisplay-discovery").apply { + setReferenceCounted(false) + acquire() + } + }.getOrNull() + } + + private fun releaseMulticast() { + runCatching { lock?.takeIf { it.isHeld }?.release() } + lock = null + } + + companion object { + private const val TAG = "ezdisplay" + + /** NsdManager wants the service type without the `.local.` suffix. */ + const val SERVICE_TYPE = "_ezdisplay._udp" + + /** IPv4 first; otherwise a global IPv6 address (link-local ones need a scope id and are skipped). */ + internal fun pickAddress(addresses: List): InetAddress? = + addresses.firstOrNull { it is Inet4Address } + ?: addresses.firstOrNull { it is Inet6Address && !it.isLinkLocalAddress && !it.isLoopbackAddress } + + internal fun formatAddr(ip: InetAddress, port: Int): String { + val text = ip.hostAddress.orEmpty().substringBefore('%') + return if (ip is Inet6Address) "[$text]:$port" else "$text:$port" + } + } +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiBackend.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiBackend.kt new file mode 100644 index 0000000..ee86f4b --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiBackend.kt @@ -0,0 +1,40 @@ +package com.librestatic.ezdisplay.wifi + +import android.content.Context +import com.librestatic.ezdisplay.NativeBridge +import java.io.File + +/** The native Wi-Fi operations the settings need. Pairing blocks: call it off the main thread. */ +interface WifiBackend { + fun hosts(): List + fun identity(): String + fun forget(fingerprint: String): Boolean + + /** [pinOrUri] is the typed PIN (with [addr]) or a full `ezd://pair?...` link (which carries its own address). */ + fun pair(addr: String, pinOrUri: String, deviceName: String): PairResult + + /** Nothing is paired and nothing can be paired. */ + object None : WifiBackend { + override fun hosts() = emptyList() + override fun identity() = "" + override fun forget(fingerprint: String) = false + override fun pair(addr: String, pinOrUri: String, deviceName: String) = + PairResult(null, "other", "Wi-Fi is not available") + } +} + +/** [WifiBackend] over the JNI bridge; identity and paired hosts live in `filesDir/wifi`. */ +class NativeWifiBackend(context: Context) : WifiBackend { + private val dir: String = stateDir(context).absolutePath + + override fun hosts() = parseHostsJson(NativeBridge.wifiHosts(dir)) + override fun identity(): String = NativeBridge.wifiIdentity(dir) + override fun forget(fingerprint: String) = NativeBridge.wifiForget(dir, fingerprint) + override fun pair(addr: String, pinOrUri: String, deviceName: String) = + parsePairResultJson(NativeBridge.wifiPair(addr, pinOrUri, deviceName, dir)) + + companion object { + /** The private directory with this device's identity and the paired hosts. */ + fun stateDir(context: Context): File = File(context.filesDir, "wifi") + } +} diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt new file mode 100644 index 0000000..3216177 --- /dev/null +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt @@ -0,0 +1,155 @@ +package com.librestatic.ezdisplay.wifi + +import org.json.JSONArray +import org.json.JSONObject +import java.net.URLDecoder + +/** Port hosts listen on for Wi-Fi when an address is typed without one. */ +const val DEFAULT_PORT = 27183 + +/** Length of the pairing PIN the host shows. */ +const val PIN_LENGTH = 6 + +/** A host this device paired with (`wifiHosts` JSON). [addr] is the address it was last reached at. */ +data class WifiHost(val name: String, val fingerprint: String, val shortFp: String, val addr: String? = null) + +/** A host found on the network by mDNS: [addr] is `ip:port`, [shortFp] the `fp` TXT record. */ +data class DiscoveredHost(val serviceName: String, val name: String, val shortFp: String, val addr: String) + +/** Contents of the QR code the host shows: `ezd://pair?a=&fp=<64 hex>&pin=&n=`. */ +data class PairLink(val addr: String, val fingerprint: String, val pin: String, val name: String) { + val shortFp: String get() = shortFingerprint(fingerprint) + + /** The link again, as the native pairing takes it. */ + fun toUri(): String = "ezd://pair?a=$addr&fp=$fingerprint&pin=$pin&n=${percentEncode(name)}" +} + +/** Percent-encodes everything but unreserved characters (the host decodes `%XX` only, not `+`). */ +internal fun percentEncode(s: String): String = buildString { + for (b in s.toByteArray(Charsets.UTF_8)) { + val c = b.toInt().toChar() + if (c.isLetterOrDigit() && b >= 0 || c in "-_.~") append(c) else append("%%%02X".format(b.toInt() and 0xFF)) + } +} + +/** Result of `wifiPair`: the paired [host], or an [error] code (see `wifiErrorText`) with a technical [message]. */ +data class PairResult(val host: WifiHost?, val error: String? = null, val message: String = "") { + val ok: Boolean get() = host != null +} + +/** True for exactly [PIN_LENGTH] ASCII digits. */ +fun isValidPin(pin: String): Boolean = pin.length == PIN_LENGTH && pin.all { it in '0'..'9' } + +/** `3f2a-91c0-77de-0b14`: the first 16 hex digits of [fingerprint] in four groups (what the host shows). */ +fun shortFingerprint(fingerprint: String): String = + fingerprint.lowercase().take(16).chunked(4).joinToString("-") + +/** True when the full [fingerprint] starts with the dash-separated [shortFp] (from mDNS or the host's screen). */ +fun fingerprintMatches(fingerprint: String, shortFp: String): Boolean { + val short = shortFp.replace("-", "").lowercase() + return short.length >= 8 && fingerprint.lowercase().startsWith(short) +} + +private const val PAIR_URI_PREFIX = "ezd://pair?" +private val HEX64 = Regex("[0-9a-fA-F]{64}") + +/** Parses a pairing link; null unless address, a 64-digit fingerprint and a valid PIN are present. */ +fun parsePairUri(uri: String?): PairLink? { + val trimmed = uri?.trim() ?: return null + if (!trimmed.startsWith(PAIR_URI_PREFIX)) return null + val query = trimmed.removePrefix(PAIR_URI_PREFIX) + var addr: String? = null + var fp: String? = null + var pin: String? = null + var name = "" + for (kv in query.split('&')) { + val (k, v) = kv.split('=', limit = 2).takeIf { it.size == 2 } ?: return null + val value = try { + URLDecoder.decode(v.replace("+", "%2B"), "UTF-8") + } catch (e: IllegalArgumentException) { + return null + } + when (k) { + "a" -> addr = value + "fp" -> fp = value + "pin" -> pin = value + "n" -> name = value.filter { !it.isISOControl() }.trim().take(64) + } + } + if (addr.isNullOrBlank() || parseManualAddress(addr) == null) return null + if (fp == null || !HEX64.matches(fp) || pin == null || !isValidPin(pin)) return null + return PairLink(parseManualAddress(addr)!!, fp.lowercase(), pin, name) +} + +private val IPV4 = Regex("""(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""") + +/** + * Normalizes a typed host address to `ip:port`: an IPv4 address or an IPv6 address (in brackets when a port + * follows), with [DEFAULT_PORT] when there is none. Null when it is not an address. + */ +fun parseManualAddress(text: String): String? { + val s = text.trim() + if (s.isEmpty()) return null + if (s.startsWith("[")) { + val end = s.indexOf(']') + if (end < 0) return null + val ip = s.substring(1, end) + val port = when { + end == s.lastIndex -> DEFAULT_PORT + s[end + 1] == ':' -> parsePort(s.substring(end + 2)) ?: return null + else -> return null + } + return if (isIpv6(ip)) "[$ip]:$port" else null + } + if (s.count { it == ':' } > 1) return if (isIpv6(s)) "[$s]:$DEFAULT_PORT" else null + val host = s.substringBefore(':') + val port = if (':' in s) parsePort(s.substringAfter(':')) ?: return null else DEFAULT_PORT + val m = IPV4.matchEntire(host) ?: return null + if (m.groupValues.drop(1).any { it.toInt() > 255 }) return null + return "$host:$port" +} + +private fun parsePort(s: String): Int? = s.toIntOrNull()?.takeIf { s.all(Char::isDigit) && it in 1..65535 } + +private fun isIpv6(s: String): Boolean = + s.contains(':') && s.all { it in '0'..'9' || it in 'a'..'f' || it in 'A'..'F' || it == ':' || it == '.' } && + s.count { it == ':' } in 2..7 + +/** Parses the `wifiHosts` JSON array; bad input gives an empty list. */ +fun parseHostsJson(json: String): List = try { + val a = JSONArray(json) + (0 until a.length()).map { parseHost(a.getJSONObject(it)) } +} catch (e: Exception) { + emptyList() +} + +private fun parseHost(o: JSONObject) = WifiHost( + name = o.optString("name"), + fingerprint = o.getString("fingerprint"), + shortFp = o.optString("shortFp"), + addr = o.optString("addr").takeIf { it.isNotEmpty() }, +) + +/** Parses the `wifiPair` JSON. Anything unreadable is an `other` error. */ +fun parsePairResultJson(json: String): PairResult = try { + val o = JSONObject(json) + if (o.optBoolean("ok")) PairResult(parseHost(o.getJSONObject("host"))) + else PairResult(null, o.optString("error", "other"), o.optString("message")) +} catch (e: Exception) { + PairResult(null, "other", json) +} + +/** Where to connect over Wi-Fi: the paired [host] at [addr] (`ip:port`). */ +data class WifiChoice(val host: WifiHost, val addr: String) + +/** + * The paired host to try over Wi-Fi and its address. Prefers a host that is on the network now (address from + * discovery), then the one used last ([lastFingerprint]) and its stored address, then any host with a stored + * address. Null when no paired host has an address. + */ +fun chooseWifiTarget(hosts: List, discovered: List, lastFingerprint: String?): WifiChoice? { + fun live(h: WifiHost) = discovered.firstOrNull { fingerprintMatches(h.fingerprint, it.shortFp) }?.addr + val ordered = hosts.sortedBy { if (it.fingerprint == lastFingerprint) 0 else 1 } + ordered.firstNotNullOfOrNull { h -> live(h)?.let { WifiChoice(h, it) } }?.let { return it } + return ordered.firstNotNullOfOrNull { h -> h.addr?.let { WifiChoice(h, it) } } +} diff --git a/android/app/src/main/res/drawable/ic_computer.xml b/android/app/src/main/res/drawable/ic_computer.xml new file mode 100644 index 0000000..5e51ef2 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_computer.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_delete.xml b/android/app/src/main/res/drawable/ic_delete.xml new file mode 100644 index 0000000..5e2ff7e --- /dev/null +++ b/android/app/src/main/res/drawable/ic_delete.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_fingerprint.xml b/android/app/src/main/res/drawable/ic_fingerprint.xml new file mode 100644 index 0000000..b8c7b44 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_fingerprint.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_link.xml b/android/app/src/main/res/drawable/ic_link.xml new file mode 100644 index 0000000..ad02042 --- /dev/null +++ b/android/app/src/main/res/drawable/ic_link.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/drawable/ic_wifi.xml b/android/app/src/main/res/drawable/ic_wifi.xml new file mode 100644 index 0000000..f3dbc5c --- /dev/null +++ b/android/app/src/main/res/drawable/ic_wifi.xml @@ -0,0 +1,13 @@ + + + + + + + diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml index 2fbbad8..87131e7 100644 --- a/android/app/src/main/res/values-de/strings.xml +++ b/android/app/src/main/res/values-de/strings.xml @@ -85,4 +85,51 @@ Zurück Kürzel bearbeiten Aktion auswählen + Verbinde über WLAN mit %1$s… + Über WLAN mit %1$s verbunden, Verhandlung läuft… + WLAN erhöht die Latenz; USB ist am besten zum Zeichnen. + Verbindung + Nur USB + Über WLAN verbinden + Wird verwendet, wenn keine USB-Verbindung besteht + WLAN erhöht Latenz und Jitter; USB ist am besten zum Zeichnen. + Gekoppelte Hosts + Noch keine gekoppelten Hosts + %1$s entfernen + Hosts in diesem Netzwerk + Suche nach Hosts… Starte ezdisplay auf deinem PC. + Koppeln + Per Adresse hinzufügen + IP-Adresse (Standardport 27183) + Dieses Gerät + Fingerabdruck des Zertifikats + Mit %1$s koppeln + Fingerabdruck: %1$s + Prüfe, ob der Fingerabdruck mit dem auf deinem PC übereinstimmt, und koppele dann dieses Gerät. + 6-stellige PIN + Wird auf dem PC angezeigt, wenn du die Kopplung startest. + Kopplung läuft… + Koppeln + Abbrechen + Falsche PIN. Prüfe die PIN auf dem PC. + Der PC akzeptiert keine Kopplung. Starte zuerst die Kopplung auf dem PC. + Zu viele Fehlversuche. Starte die Kopplung auf dem PC neu. + Der Host ist beschäftigt. Versuche es gleich noch einmal. + Der Host ist nicht erreichbar. Prüfe die Adresse und ob beide Geräte im selben Netzwerk sind. + Der Host hat nicht rechtzeitig geantwortet. + Das ist nicht der Host aus dem Code: Der Fingerabdruck weicht ab. + Die PIN hat 6 Ziffern. + Das ist kein ezdisplay-Kopplungscode. + Das ist keine gültige Adresse. + Kopplung fehlgeschlagen. + + WLAN · %1$d gekoppelter Host + WLAN · %1$d gekoppelte Hosts + + Hosts und Kopplung + Schließen + + %1$d gekoppelter Host + %1$d gekoppelte Hosts + diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 307f03c..8facc3b 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -85,4 +85,53 @@ Volver Editar atajo Elegir acción + Conectando por Wi-Fi a %1$s… + Conectado por Wi-Fi a %1$s, negociando… + El Wi-Fi agrega latencia; el USB es lo mejor para dibujar. + Conexión + Solo USB + Conectar por Wi-Fi + Se usa cuando no hay conexión USB + El Wi-Fi agrega latencia y jitter; el USB es lo mejor para dibujar. + Hosts vinculados + Todavía no hay hosts vinculados + Olvidar %1$s + Hosts en esta red + Buscando hosts… Iniciá ezdisplay en tu PC. + Vincular + Agregar por dirección + Dirección IP (puerto 27183 por defecto) + Este dispositivo + Huella de su certificado + Vincular con %1$s + Huella: %1$s + Verificá que la huella coincida con la de tu PC y luego vinculá este dispositivo. + PIN de 6 dígitos + Se muestra en la PC al iniciar la vinculación. + Vinculando… + Vincular + Cancelar + PIN incorrecto. Revisá el PIN en la PC. + La PC no acepta vinculaciones. Iniciá primero la vinculación en la PC. + Demasiados intentos fallidos. Iniciá la vinculación de nuevo en la PC. + El host está ocupado. Probá de nuevo en un momento. + No se puede llegar al host. Revisá la dirección y que ambos dispositivos estén en la misma red. + El host no respondió a tiempo. + Este no es el host del código: su huella es distinta. + El PIN tiene 6 dígitos. + Este no es un código de vinculación de ezdisplay. + Esta no es una dirección válida. + No se pudo vincular. + + Wi-Fi · %1$d host vinculado + Wi-Fi · %1$d hosts vinculados + Wi-Fi · %1$d hosts vinculados + + Hosts y vinculación + Cerrar + + %1$d host vinculado + %1$d hosts vinculados + %1$d hosts vinculados + diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml index f75609d..a381b2b 100644 --- a/android/app/src/main/res/values-fr/strings.xml +++ b/android/app/src/main/res/values-fr/strings.xml @@ -85,4 +85,53 @@ Retour Modifier le raccourci Choisir l\'action + Connexion en Wi-Fi à %1$s… + Connecté en Wi-Fi à %1$s, négociation… + Le Wi-Fi ajoute de la latence ; l\'USB est idéal pour dessiner. + Connexion + USB uniquement + Se connecter en Wi-Fi + Utilisé quand la connexion USB n\'est pas disponible + Le Wi-Fi ajoute de la latence et de la gigue ; l\'USB est idéal pour dessiner. + Hôtes associés + Aucun hôte associé pour l\'instant + Oublier %1$s + Hôtes sur ce réseau + Recherche d\'hôtes… Lancez ezdisplay sur votre PC. + Associer + Ajouter par adresse + Adresse IP (port 27183 par défaut) + Cet appareil + Empreinte de son certificat + Associer avec %1$s + Empreinte : %1$s + Vérifiez que l\'empreinte correspond à celle de votre PC, puis associez cet appareil. + PIN à 6 chiffres + Affiché sur le PC au début de l\'association. + Association… + Associer + Annuler + PIN incorrect. Vérifiez le PIN sur le PC. + Le PC n\'accepte pas d\'association. Lancez d\'abord l\'association sur le PC. + Trop de tentatives échouées. Relancez l\'association sur le PC. + L\'hôte est occupé. Réessayez dans un instant. + Impossible de joindre l\'hôte. Vérifiez l\'adresse et que les deux appareils sont sur le même réseau. + L\'hôte n\'a pas répondu à temps. + Ce n\'est pas l\'hôte du code : son empreinte est différente. + Le PIN comporte 6 chiffres. + Ce n\'est pas un code d\'association ezdisplay. + Cette adresse n\'est pas valide. + Échec de l\'association. + + Wi-Fi · %1$d hôte associé + Wi-Fi · %1$d hôtes associés + Wi-Fi · %1$d hôtes associés + + Hôtes et association + Fermer + + %1$d hôte associé + %1$d hôtes associés + %1$d hôtes associés + diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml index 3a81e3a..9ed35b0 100644 --- a/android/app/src/main/res/values-it/strings.xml +++ b/android/app/src/main/res/values-it/strings.xml @@ -85,4 +85,53 @@ Indietro Modifica scorciatoia Scegli azione + Connessione via Wi-Fi a %1$s… + Connesso via Wi-Fi a %1$s, negoziazione… + Il Wi-Fi aggiunge latenza; l\'USB è il migliore per disegnare. + Connessione + Solo USB + Connetti via Wi-Fi + Usato quando la connessione USB non è disponibile + Il Wi-Fi aggiunge latenza e jitter; l\'USB è il migliore per disegnare. + Host associati + Nessun host associato per ora + Dimentica %1$s + Host su questa rete + Ricerca di host… Avvia ezdisplay sul PC. + Associa + Aggiungi tramite indirizzo + Indirizzo IP (porta 27183 predefinita) + Questo dispositivo + Impronta del certificato + Associa con %1$s + Impronta: %1$s + Controlla che l\'impronta coincida con quella sul PC, poi associa questo dispositivo. + PIN a 6 cifre + Mostrato sul PC quando avvii l\'associazione. + Associazione… + Associa + Annulla + PIN errato. Controlla il PIN sul PC. + Il PC non accetta associazioni. Avvia prima l\'associazione sul PC. + Troppi tentativi errati. Avvia di nuovo l\'associazione sul PC. + L\'host è occupato. Riprova tra un momento. + Impossibile raggiungere l\'host. Controlla l\'indirizzo e che i due dispositivi siano sulla stessa rete. + L\'host non ha risposto in tempo. + Questo non è l\'host del codice: l\'impronta è diversa. + Il PIN ha 6 cifre. + Questo non è un codice di associazione di ezdisplay. + Questo indirizzo non è valido. + Associazione non riuscita. + + Wi-Fi · %1$d host associato + Wi-Fi · %1$d host associati + Wi-Fi · %1$d host associati + + Host e associazione + Chiudi + + %1$d host associato + %1$d host associati + %1$d host associati + diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml index 96eda1b..b902012 100644 --- a/android/app/src/main/res/values-pt/strings.xml +++ b/android/app/src/main/res/values-pt/strings.xml @@ -85,4 +85,53 @@ Voltar Editar atalho Escolher ação + Conectando por Wi-Fi a %1$s… + Conectado por Wi-Fi a %1$s, negociando… + O Wi-Fi adiciona latência; o USB é o melhor para desenhar. + Conexão + Somente USB + Conectar por Wi-Fi + Usado quando a conexão USB não está disponível + O Wi-Fi adiciona latência e jitter; o USB é o melhor para desenhar. + Hosts pareados + Nenhum host pareado ainda + Esquecer %1$s + Hosts nesta rede + Procurando hosts… Inicie o ezdisplay no seu PC. + Parear + Adicionar por endereço + Endereço IP (porta 27183 por padrão) + Este dispositivo + Impressão digital do certificado + Parear com %1$s + Impressão digital: %1$s + Confira se a impressão digital é igual à do seu PC e depois pareie este dispositivo. + PIN de 6 dígitos + Exibido no PC ao iniciar o pareamento. + Pareando… + Parear + Cancelar + PIN incorreto. Confira o PIN no PC. + O PC não está aceitando pareamentos. Inicie primeiro o pareamento no PC. + Muitas tentativas incorretas. Inicie o pareamento de novo no PC. + O host está ocupado. Tente novamente em instantes. + Não foi possível alcançar o host. Confira o endereço e se os dois dispositivos estão na mesma rede. + O host não respondeu a tempo. + Este não é o host do código: a impressão digital é diferente. + O PIN tem 6 dígitos. + Este não é um código de pareamento do ezdisplay. + Este endereço não é válido. + Falha ao parear. + + Wi-Fi · %1$d host pareado + Wi-Fi · %1$d hosts pareados + Wi-Fi · %1$d hosts pareados + + Hosts e pareamento + Fechar + + %1$d host pareado + %1$d hosts pareados + %1$d hosts pareados + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 04b2afd..bdf9cbb 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -85,4 +85,51 @@ Back Edit shortcut Choose action + Connecting over Wi-Fi to %1$s… + Connected over Wi-Fi to %1$s, negotiating… + Wi-Fi adds latency; USB is best for drawing. + Connection + USB only + Connect over Wi-Fi + Used when the USB connection is not available + Wi-Fi adds latency and jitter; USB is best for drawing. + Paired hosts + No paired hosts yet + Forget %1$s + Hosts on this network + Looking for hosts… Start ezdisplay on your PC. + Pair + Add by address + IP address (port 27183 by default) + This device + Fingerprint of its certificate + Pair with %1$s + Fingerprint: %1$s + Check that the fingerprint matches the one on your PC, then pair this device. + 6-digit PIN + Shown on the PC when you start pairing. + Pairing… + Pair + Cancel + Wrong PIN. Check the PIN on the PC. + The PC is not accepting pairings. Start pairing on the PC first. + Too many wrong attempts. Start pairing again on the PC. + The host is busy. Try again in a moment. + Cannot reach the host. Check the address and that both devices are on the same network. + The host did not answer in time. + This is not the host from the code: its fingerprint differs. + The PIN has 6 digits. + This is not an ezdisplay pairing code. + This is not a valid address. + Pairing failed. + + Wi-Fi · %1$d paired host + Wi-Fi · %1$d paired hosts + + Hosts and pairing + Close + + %1$d paired host + %1$d paired hosts + diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/FakeWifiBackend.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/FakeWifiBackend.kt new file mode 100644 index 0000000..ee2db15 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/FakeWifiBackend.kt @@ -0,0 +1,30 @@ +package com.librestatic.ezdisplay.settings + +import com.librestatic.ezdisplay.wifi.PairResult +import com.librestatic.ezdisplay.wifi.WifiBackend +import com.librestatic.ezdisplay.wifi.WifiHost +import com.librestatic.ezdisplay.wifi.shortFingerprint + +/** In-memory [WifiBackend]: pairing succeeds with [pin] and answers [error] otherwise. */ +class FakeWifiBackend( + initial: List = emptyList(), + private val pin: String = "123456", + private var error: String = "wrong_pin", +) : WifiBackend { + val paired = initial.toMutableList() + val calls = mutableListOf>() + + override fun hosts(): List = paired.toList() + override fun identity() = "abcd-0123-4567-89ef" + override fun forget(fingerprint: String) = paired.removeAll { it.fingerprint == fingerprint } + + override fun pair(addr: String, pinOrUri: String, deviceName: String): PairResult { + calls += Triple(addr, pinOrUri, deviceName) + if (!pinOrUri.startsWith("ezd://") && pinOrUri != pin) return PairResult(null, error, "refused") + val fp = "ab".repeat(32) + val host = WifiHost("Studio PC", fp, shortFingerprint(fp), addr) + paired.removeAll { it.fingerprint == fp } + paired += host + return PairResult(host) + } +} diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt new file mode 100644 index 0000000..608b0d1 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt @@ -0,0 +1,263 @@ +package com.librestatic.ezdisplay.settings + +import androidx.compose.ui.semantics.SemanticsProperties +import androidx.compose.ui.test.assertIsEnabled +import androidx.compose.ui.test.assertIsNotEnabled +import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.onNodeWithText +import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo +import androidx.compose.ui.test.performTextInput +import com.librestatic.ezdisplay.R +import com.librestatic.ezdisplay.wifi.DiscoveredHost +import com.librestatic.ezdisplay.wifi.PairLink +import com.librestatic.ezdisplay.wifi.WifiHost +import com.librestatic.ezdisplay.wifi.shortFingerprint +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.robolectric.annotation.Config + +private val FP = "ab".repeat(32) +private val OTHER_FP = "cd".repeat(32) +private val PAIRED = WifiHost("Laptop", OTHER_FP, shortFingerprint(OTHER_FP), "10.0.0.7:27183") +private val SEEN = DiscoveredHost("desk-svc", "Studio PC", shortFingerprint(FP), "192.168.1.9:27183") + +/** The Connection section on a phone: one scrolling column. */ +@Config(sdk = [36], qualifiers = "w412dp-h915dp") +class SettingsConnectionPhoneTest : SettingsUiTestBase() { + private fun openConnection(backend: FakeWifiBackend = FakeWifiBackend(listOf(PAIRED))) { + launch(wifi = backend) + rule.runOnUiThread { store.setDiscovered(listOf(SEEN)) } + rule.waitForIdle() + tag("connection_content").performScrollTo() + } + + @Test fun showsTheSwitchWarningHostsAndFingerprint() { + openConnection() + dumpTree("phone-connection") + rule.onNodeWithText(str(R.string.wifi_latency_warning)).performScrollTo().assertExists() + tag("wifi_row").assertExists() + tag("paired_$OTHER_FP").performScrollTo().assertExists() + tag("discovered_desk-svc").performScrollTo().assertExists() + tag("manual_row").performScrollTo().assertExists() + tag("device_fp").performScrollTo().assertExists() + rule.onNodeWithText("abcd-0123-4567-89ef").assertExists() + } + + @Test fun theSwitchStartsOffAndSaves() { + launch(wifi = FakeWifiBackend()) + tag("wifi_row").performScrollTo().performClick() + assertTrue(prefs.getBoolean(SettingsStore.WIFI_ENABLED, false)) + assertTrue(store.state.value.wifiEnabled) + tag("wifi_row").performClick() + assertFalse(prefs.getBoolean(SettingsStore.WIFI_ENABLED, true)) + } + + @Test fun emptyListsSayWhatToDo() { + launch(wifi = FakeWifiBackend()) + tag("paired_empty").performScrollTo().assertExists() + tag("discovered_empty").performScrollTo().assertExists() + } + + @Test fun pairedHostsAreNotOfferedAgain() { + launch(wifi = FakeWifiBackend(listOf(WifiHost("Studio PC", FP, shortFingerprint(FP), null)))) + rule.runOnUiThread { store.setDiscovered(listOf(SEEN)) } + rule.waitForIdle() + tag("discovered_desk-svc").assertDoesNotExist() + tag("discovered_empty").performScrollTo().assertExists() + } + + @Test fun pairingAFoundHostAsksForThePin() { + val backend = FakeWifiBackend(listOf(PAIRED), pin = "424242") + openConnection(backend) + tag("pair_desk-svc").performScrollTo().performClick() + tag("pair_dialog").assertExists() + rule.onNodeWithText(str(R.string.pair_dialog_title, "Studio PC")).assertExists() + tag("pair_fp").assertTextContains(shortFingerprint(FP), substring = true) + tag("pair_confirm").assertIsNotEnabled() + + // Only digits, at most six. + tag("pin_field").performTextInput("12ab34567") + tag("pin_field").assertTextContains("123456") + tag("pair_confirm").assertIsEnabled() + + // A wrong PIN keeps the dialog open with the message and nothing is paired. + tag("pair_confirm").performClick() + rule.waitForIdle() + assertEquals(listOf(Triple("192.168.1.9:27183", "123456", "test tablet")), backend.calls) + tag("pair_error").assertTextContains(str(R.string.pair_error_wrong_pin)) + assertEquals(1, store.state.value.wifiHosts.size) + } + + @Test fun aCorrectPinPairsClosesTheDialogAndEnablesWifi() { + val backend = FakeWifiBackend(listOf(PAIRED), pin = "424242") + openConnection(backend) + assertFalse(store.state.value.wifiEnabled) + tag("pair_desk-svc").performScrollTo().performClick() + tag("pin_field").performTextInput("424242") + tag("pair_confirm").performClick() + rule.waitForIdle() + tag("pair_dialog").assertDoesNotExist() + assertNull(store.state.value.pairing) + assertEquals(2, store.state.value.wifiHosts.size) + assertTrue(store.state.value.wifiEnabled) + assertTrue(prefs.getBoolean(SettingsStore.WIFI_ENABLED, false)) + // The paired host moved from "found" to "paired". + tag("paired_$FP").performScrollTo().assertExists() + tag("discovered_desk-svc").assertDoesNotExist() + } + + @Test fun cancelClosesTheDialogWithoutPairing() { + val backend = FakeWifiBackend() + openConnection(backend) + tag("pair_desk-svc").performScrollTo().performClick() + tag("pair_cancel").performClick() + tag("pair_dialog").assertDoesNotExist() + assertTrue(backend.calls.isEmpty()) + } + + @Test fun forgetRemovesThePairedHost() { + val backend = FakeWifiBackend(listOf(PAIRED)) + openConnection(backend) + tag("forget_$OTHER_FP").performScrollTo().performClick() + assertTrue(backend.paired.isEmpty()) + assertTrue(store.state.value.wifiHosts.isEmpty()) + tag("paired_empty").performScrollTo().assertExists() + } + + @Test fun theManualPairButtonNeedsAValidAddress() { + openConnection() + tag("manual_pair").performScrollTo().assertIsNotEnabled() + tag("manual_field").performTextInput("not an address") + tag("manual_pair").assertIsNotEnabled() + } + + @Test fun aManualAddressGetsTheDefaultPort() { + val backend = FakeWifiBackend() + openConnection(backend) + tag("manual_field").performScrollTo().performTextInput("192.168.1.20") + tag("manual_pair").assertIsEnabled().performClick() + rule.onNodeWithText(str(R.string.pair_dialog_title, "192.168.1.20:27183")).assertExists() + tag("pin_field").performTextInput("123456") + tag("pair_confirm").performClick() + rule.waitForIdle() + assertEquals("192.168.1.20:27183", backend.calls.single().first) + } + + @Test fun aScannedCodeAsksForConfirmationAndPairsWithoutAPin() { + val backend = FakeWifiBackend() + launch(wifi = backend) + val link = PairLink("192.168.1.9:27183", FP, "424242", "Studio PC") + rule.runOnUiThread { store.startPairing(link) } + rule.waitForIdle() + dumpTree("phone-scanned") + tag("pair_dialog").assertExists() + rule.onNodeWithText(str(R.string.pair_dialog_title, "Studio PC")).assertExists() + tag("pair_fp").assertTextContains(shortFingerprint(FP), substring = true) + tag("pin_field").assertDoesNotExist() + tag("pair_confirm").assertIsEnabled().performClick() + rule.waitForIdle() + val call = backend.calls.single() + assertEquals(link.toUri(), call.second) + tag("pair_dialog").assertDoesNotExist() + assertEquals(1, store.state.value.wifiHosts.size) + } + + @Test fun anUnreachableHostShowsItsMessage() { + val backend = FakeWifiBackend(error = "unreachable") + openConnection(backend) + tag("pair_desk-svc").performScrollTo().performClick() + tag("pin_field").performTextInput("000000") + tag("pair_confirm").performClick() + rule.waitForIdle() + tag("pair_error").assertTextContains(str(R.string.pair_error_unreachable)) + // The dialog can be retried: the button is enabled again. + tag("pair_confirm").assertIsEnabled() + } + + @Test fun everyErrorCodeHasItsOwnMessage() { + val codes = listOf( + "wrong_pin", "pairing_closed", "too_many_attempts", "busy", "unreachable", "timeout", + "fingerprint_mismatch", "invalid_pin", "invalid_uri", "invalid_address", + ) + assertEquals(codes.size, codes.map { wifiErrorText(it) }.toSet().size) + assertEquals(R.string.pair_error_other, wifiErrorText("something new")) + assertEquals(R.string.pair_error_other, wifiErrorText(null)) + // The pairing view model never leaks a missing code. + assertFalse(codes.contains("other")) + } + + @Test fun pinValidationRunsBeforeAnythingIsSent() { + val backend = FakeWifiBackend() + launch(wifi = backend) + rule.runOnUiThread { store.startPairing("x", "", "10.0.0.1:27183"); store.submitPairing("12") } + rule.waitForIdle() + assertEquals("invalid_pin", store.state.value.pairing?.error) + assertTrue(backend.calls.isEmpty()) + val semantics = tag("pair_error").fetchSemanticsNode().config[SemanticsProperties.Text].joinToString { it.text } + assertEquals(str(R.string.pair_error_invalid_pin), semantics) + } +} + +/** On a foldable the section is a list entry with the content as detail. */ +@Config(sdk = [36], qualifiers = "w841dp-h701dp") +class SettingsConnectionListDetailTest : SettingsUiTestBase() { + @Test fun theSectionSummarizesAndShowsTheContent() { + launch(wifi = FakeWifiBackend(listOf(PAIRED))) + tag("section_Connection").assertExists() + rule.onNodeWithText(str(R.string.connection_summary_usb)).assertExists() + tag("section_Connection").performClick() + tag("connection_content").assertExists() + tag("paired_$OTHER_FP").assertExists() + tag("wifi_row").performClick() + rule.onNodeWithText("Wi-Fi · 1 paired host").assertExists() + } +} + +/** On a tablet the page shows the switch and warning, and the hosts open in a dialog so the page never scrolls. */ +@Config(sdk = [36], qualifiers = "w1691dp-h978dp-280dpi") +class SettingsConnectionWideTest : SettingsUiTestBase() { + private fun scrollMax(): Float = tag("wide_page").fetchSemanticsNode().config[SemanticsProperties.VerticalScrollAxisRange].maxValue() + + @Test fun pageShowsSwitchWarningAndAManageRow() { + launch(wifi = FakeWifiBackend(listOf(PAIRED))) + dumpTree("wide-connection") + tag("wifi_row").assertExists() + tag("wifi_warning").assertExists() + tag("connection_manage").assertExists() + tag("paired_$OTHER_FP").assertDoesNotExist() + } + + @Test fun theManageRowOpensTheHostsAndPairingWorks() { + val backend = FakeWifiBackend(listOf(PAIRED), pin = "111111") + launch(wifi = backend) + rule.runOnUiThread { store.setDiscovered(listOf(SEEN)) } + tag("connection_manage").performClick() + tag("hosts_dialog").assertExists() + tag("paired_$OTHER_FP").assertExists() + tag("pair_desk-svc").performClick() + tag("pin_field").performTextInput("111111") + tag("pair_confirm").performClick() + rule.waitForIdle() + assertEquals(2, store.state.value.wifiHosts.size) + tag("hosts_dialog_close").performClick() + tag("hosts_dialog").assertDoesNotExist() + } + + @Test fun pageDoesNotScrollWithManyHostsAndEveryProfile() { + val many = (1..8).map { WifiHost("Host $it", "%02x".format(it).repeat(32), "0$it-0$it-0$it-0$it", "10.0.0.$it:27183") } + launch(AirActions.On, FakeWifiBackend(many)) + rule.runOnUiThread { + store.setDiscovered((1..5).map { DiscoveredHost("svc$it", "Found $it", "ee$it-ee$it-ee$it-ee$it", "10.1.0.$it:27183") }) + store.setWifiEnabled(true) + } + for (profile in listOf("raw", "desktop", "drawing", "graphics_tablet")) { + rule.runOnUiThread { store.setProfile(profile) } + rule.waitForIdle() + assertEquals("page scrolls with profile $profile", 0f, scrollMax(), 0f) + } + } +} diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt index 56087ab..9d3cad5 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt @@ -4,14 +4,18 @@ import androidx.activity.ComponentActivity import androidx.compose.ui.test.hasScrollAction import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag -import androidx.compose.ui.test.onRoot +import androidx.compose.ui.test.isRoot import androidx.compose.ui.test.performClick +import androidx.compose.ui.test.performScrollTo import androidx.compose.ui.test.performTouchInput import androidx.compose.ui.test.printToString import androidx.compose.ui.test.swipeUp import com.github.takahirom.roborazzi.captureRoboImage import com.librestatic.ezdisplay.InputPrefs import com.librestatic.ezdisplay.InputPrefs.KeyCombo +import com.librestatic.ezdisplay.wifi.DiscoveredHost +import com.librestatic.ezdisplay.wifi.PairLink +import com.librestatic.ezdisplay.wifi.WifiHost import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith @@ -37,6 +41,12 @@ class SettingsScreenshotTest { override fun setZoomFactor(factor: Float) {} override fun setDoubleClickMs(ms: Int) {} override fun setPalmRejection(on: Boolean) {} + override fun setWifiEnabled(on: Boolean) {} + override fun startPairing(name: String, shortFp: String, addr: String) {} + override fun startPairing(link: PairLink) {} + override fun submitPairing(pin: String) {} + override fun cancelPairing() {} + override fun forgetHost(fingerprint: String) {} } private val tabletState = SettingsState( @@ -60,8 +70,10 @@ class SettingsScreenshotTest { } private fun capture(name: String) { - println("=== SEMANTICS $name ===\n" + rule.onRoot().printToString(maxDepth = 14) + "\n=== END $name ===") - rule.onRoot().captureRoboImage("build/outputs/roborazzi/$name.png") + val roots = rule.onAllNodes(isRoot()) + val last = roots[roots.fetchSemanticsNodes().size - 1] + println("=== SEMANTICS $name ===\n" + last.printToString(maxDepth = 14) + "\n=== END $name ===") + last.captureRoboImage("build/outputs/roborazzi/$name.png") } @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") @@ -76,6 +88,38 @@ class SettingsScreenshotTest { capture("phone_main_bottom_dark") } + private val connectionState = SettingsState( + wifiEnabled = true, + wifiHosts = listOf(WifiHost("Laptop", "cd".repeat(32), "cdcd-cdcd-cdcd-cdcd", "10.0.0.7:27183")), + discovered = listOf(DiscoveredHost("desk", "Studio PC", "3f2a-91c0-77de-0b14", "192.168.1.9:27183")), + deviceFingerprint = "abcd-0123-4567-89ef", + ) + + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") + fun phone_connection_dark() { + show(connectionState) + rule.onNodeWithTag("connection_content").performScrollTo() + rule.waitForIdle() + capture("phone_connection_dark") + } + + @Test @Config(sdk = [36], qualifiers = "w841dp-h701dp-night") + fun foldable_connection_dark() { + show(connectionState) + rule.onNodeWithTag("section_Connection").performClick() + rule.waitForIdle() + capture("foldable_connection_dark") + } + + @Test @Config(sdk = [36], qualifiers = "w1691dp-h978dp-night-280dpi") + fun tablet_connection_dark() { show(connectionState.copy(profile = "graphics_tablet")); capture("tablet_connection_dark") } + + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") + fun phone_pair_dialog_dark() { + show(connectionState.copy(pairing = PairingState("Studio PC", "3f2a-91c0-77de-0b14", "192.168.1.9:27183"))) + capture("phone_pair_dialog_dark") + } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") fun phone_editor_dark() { show(tabletState) diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsUiTestBase.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsUiTestBase.kt index fc8bf3d..77a04c1 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsUiTestBase.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsUiTestBase.kt @@ -12,13 +12,16 @@ import androidx.compose.ui.test.junit4.AndroidComposeTestRule import androidx.compose.ui.test.junit4.createAndroidComposeRule import androidx.compose.ui.test.onNodeWithTag import androidx.compose.ui.test.printToString +import androidx.compose.ui.test.isRoot import androidx.compose.ui.test.onRoot import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 import com.librestatic.ezdisplay.InputPrefs +import com.librestatic.ezdisplay.wifi.WifiBackend import org.junit.Before import org.junit.Rule import org.junit.runner.RunWith +import java.util.concurrent.Executor /** Shared setup: a real [SettingsStore] on cleared Robolectric prefs, rendered inside [SettingsTheme]. */ @RunWith(AndroidJUnit4::class) @@ -34,14 +37,18 @@ abstract class SettingsUiTestBase { } /** Seeds [seed] into prefs, then shows the screen. */ - protected fun launch(airActions: AirActions = AirActions.Off, seed: SharedPreferences.Editor.() -> Unit = {}) { + protected fun launch( + airActions: AirActions = AirActions.Off, + wifi: WifiBackend = WifiBackend.None, + seed: SharedPreferences.Editor.() -> Unit = {}, + ) { prefs.edit().apply(seed).commit() - store = SettingsStore(prefs, airActions) + store = SettingsStore(prefs, airActions, wifi, "test tablet", io = Executor { it.run() }) rule.setContent { SettingsTheme { SettingsScreen(store) } } rule.waitForIdle() } - protected fun str(id: Int): String = rule.activity.getString(id) + protected fun str(id: Int, vararg args: Any): String = rule.activity.getString(id, *args) protected fun tag(t: String): SemanticsNodeInteraction = rule.onNodeWithTag(t) @@ -59,7 +66,7 @@ abstract class SettingsUiTestBase { } protected fun dumpTree(label: String) { - println("=== SEMANTICS $label ===\n" + rule.onRoot().printToString(maxDepth = 12) + "\n=== END $label ===") + println("=== SEMANTICS $label ===\n" + rule.onAllNodes(isRoot()).fetchSemanticsNodes().indices.joinToString("\n--- window ---\n") { rule.onAllNodes(isRoot())[it].printToString(maxDepth = 12) } + "\n=== END $label ===") } protected fun SharedPreferences.editor(block: SharedPreferences.Editor.() -> Unit) = edit().apply(block).commit() diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt new file mode 100644 index 0000000..9a03141 --- /dev/null +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt @@ -0,0 +1,124 @@ +package com.librestatic.ezdisplay.wifi + +import androidx.test.ext.junit.runners.AndroidJUnit4 +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertNotNull +import org.junit.Assert.assertNull +import org.junit.Assert.assertTrue +import org.junit.Test +import org.junit.runner.RunWith + +@RunWith(AndroidJUnit4::class) +class WifiModelTest { + private val fpA = "3f2a91c077de0b14" + "00".repeat(24) + private val fpB = "aaaabbbbccccdddd" + "11".repeat(24) + + @Test fun pinsAreSixDigits() { + assertTrue(isValidPin("123456")) + assertTrue(isValidPin("000000")) + listOf("", "12345", "1234567", "12345a", " 12345", "١٢٣٤٥٦").forEach { assertFalse(it, isValidPin(it)) } + } + + @Test fun shortFingerprintGroupsTheFirstSixteenDigits() { + assertEquals("3f2a-91c0-77de-0b14", shortFingerprint(fpA.uppercase())) + assertTrue(fingerprintMatches(fpA, "3f2a-91c0-77de-0b14")) + assertTrue(fingerprintMatches(fpA.uppercase(), "3F2A-91C0-77DE-0B14")) + assertFalse(fingerprintMatches(fpA, "3f2a-91c0-77de-0b15")) + // Too short a prefix identifies nothing. + assertFalse(fingerprintMatches(fpA, "")) + assertFalse(fingerprintMatches(fpA, "3f2a")) + } + + @Test fun parsesAPairingLink() { + val link = parsePairUri("ezd://pair?a=192.168.1.5:27183&fp=$fpA&pin=123456&n=Studio%20PC%20%C3%A9") + assertNotNull(link) + assertEquals("192.168.1.5:27183", link!!.addr) + assertEquals(fpA, link.fingerprint) + assertEquals("123456", link.pin) + assertEquals("Studio PC é", link.name) + assertEquals("3f2a-91c0-77de-0b14", link.shortFp) + } + + @Test fun aPairingLinkSurvivesTheRoundTripToTheNativeSide() { + val link = PairLink("[fe80::1]:27183", fpA, "000123", "A&B = C+D %é") + assertEquals(link, parsePairUri(link.toUri())) + // The host decodes %XX only, so no raw spaces or plus signs. + assertFalse(link.toUri().contains(' ')) + assertEquals("A%26B%20%3D%20C%2BD%20%25%C3%A9", percentEncode(link.name)) + } + + @Test fun rejectsBadPairingLinks() { + val ok = "ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=123456&n=x" + assertNotNull(parsePairUri(ok)) + assertNotNull(parsePairUri(" $ok ")) + listOf( + null, "", "https://example.com", "ezd://pair", "ezd://pair?", + "ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=12345", + "ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=abcdef", + "ezd://pair?a=10.0.0.2:27183&fp=abcd&pin=123456", + "ezd://pair?a=10.0.0.2:27183&pin=123456", + "ezd://pair?a=not-an-address&fp=$fpA&pin=123456", + "ezd://pair?a=300.0.0.1:27183&fp=$fpA&pin=123456", + "ezd://pair?fp=$fpA&pin=123456", + "ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=123456&n=%zz", + "ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=123456&broken", + ).forEach { assertNull(it, parsePairUri(it)) } + } + + @Test fun aLinkWithoutANameIsStillValid() { + assertEquals("", parsePairUri("ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=123456")!!.name) + } + + @Test fun manualAddressesGetTheDefaultPort() { + assertEquals("192.168.1.5:27183", parseManualAddress("192.168.1.5")) + assertEquals("192.168.1.5:4000", parseManualAddress(" 192.168.1.5:4000 ")) + assertEquals("[fe80::1]:27183", parseManualAddress("fe80::1")) + assertEquals("[2001:db8::2]:5000", parseManualAddress("[2001:db8::2]:5000")) + assertEquals("[2001:db8::2]:27183", parseManualAddress("[2001:db8::2]")) + listOf("", " ", "desk", "1.2.3", "300.1.1.1", "1.2.3.4:0", "1.2.3.4:70000", "1.2.3.4:x", "1.2.3.4:", "[::1", "::zz") + .forEach { assertNull(it, parseManualAddress(it)) } + } + + @Test fun parsesHostsJson() { + val json = """[{"name":"desk","fingerprint":"$fpA","shortFp":"3f2a-91c0-77de-0b14","addr":"10.0.0.2:27183"}, + {"name":"laptop","fingerprint":"$fpB","shortFp":"aaaa-bbbb-cccc-dddd"}]""" + val hosts = parseHostsJson(json) + assertEquals(2, hosts.size) + assertEquals(WifiHost("desk", fpA, "3f2a-91c0-77de-0b14", "10.0.0.2:27183"), hosts[0]) + assertNull(hosts[1].addr) + assertEquals(emptyList(), parseHostsJson("[]")) + assertEquals(emptyList(), parseHostsJson("nope")) + } + + @Test fun parsesPairResults() { + val ok = parsePairResultJson( + """{"ok":true,"host":{"name":"desk","fingerprint":"$fpA","shortFp":"3f2a-91c0-77de-0b14"}}""", + ) + assertTrue(ok.ok) + assertEquals("desk", ok.host!!.name) + val bad = parsePairResultJson("""{"ok":false,"error":"wrong_pin","message":"refused"}""") + assertFalse(bad.ok) + assertEquals("wrong_pin", bad.error) + assertEquals("other", parsePairResultJson("garbage").error) + } + + @Test fun choosesTheLiveHostThenTheLastOneThenAStoredAddress() { + val a = WifiHost("a", fpA, shortFingerprint(fpA), "10.0.0.2:27183") + val b = WifiHost("b", fpB, shortFingerprint(fpB), "10.0.0.3:27183") + val noAddr = WifiHost("c", "ff".repeat(32), "ffff-ffff-ffff-ffff", null) + val seenB = DiscoveredHost("b-svc", "b", "aaaa-bbbb-cccc-dddd", "192.168.1.9:27183") + + // Discovery beats everything and brings the fresh address. + assertEquals(WifiChoice(b, "192.168.1.9:27183"), chooseWifiTarget(listOf(a, b), listOf(seenB), fpA)) + // Nothing discovered: the last used host with its stored address. + assertEquals(WifiChoice(b, "10.0.0.3:27183"), chooseWifiTarget(listOf(a, b), emptyList(), fpB)) + assertEquals(WifiChoice(a, "10.0.0.2:27183"), chooseWifiTarget(listOf(a, b), emptyList(), null)) + // A host with no address is skipped; none at all means no Wi-Fi attempt. + assertEquals(WifiChoice(a, "10.0.0.2:27183"), chooseWifiTarget(listOf(noAddr, a), emptyList(), noAddr.fingerprint)) + assertNull(chooseWifiTarget(listOf(noAddr), emptyList(), null)) + assertNull(chooseWifiTarget(emptyList(), listOf(seenB), null)) + // A discovered host nobody paired is never chosen. + assertNull(chooseWifiTarget(listOf(noAddr), listOf(seenB), null)) + } +} From 526fe4fe003ee45a96fb6235dd7200f05d0fb222 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:09:43 -0300 Subject: [PATCH 08/14] Give each channel its own QUIC stream A Wi-Fi session now uses one stream per channel: control (bidirectional), input (client), cursor and video (host), so loss on one channel never delays another. Unidirectional streams start with a tag byte and are dispatched by tag. The mux gains per-channel lanes (spawn_mux_lanes, MuxReceiver::new_lanes); a channel without a lane stays on the control stream in priority order. Send priorities: control 4, input 3, cursor 2, audio 1 (reserved), video 0. --- crates/ezd-link/src/lib.rs | 2 +- crates/ezd-link/src/link.rs | 84 +++-- crates/ezd-link/src/mux.rs | 706 ++++++++++++++++++++++++----------- crates/ezd-link/src/quic.rs | 131 +++++-- crates/ezd-proto/src/pair.rs | 13 +- docs/protocol.md | 37 +- 6 files changed, 674 insertions(+), 299 deletions(-) diff --git a/crates/ezd-link/src/lib.rs b/crates/ezd-link/src/lib.rs index aa185d6..0c09516 100644 --- a/crates/ezd-link/src/lib.rs +++ b/crates/ezd-link/src/lib.rs @@ -16,7 +16,7 @@ pub mod pair; #[cfg(feature = "quic")] pub mod quic; -pub use link::{BoxRead, BoxWrite, Link}; +pub use link::{BoxRead, BoxWrite, Lanes, Link}; pub use mux::{ MuxClosed, MuxError, MuxOptions, MuxReceiver, MuxSender, MuxStats, MuxTask, VideoCredit, }; diff --git a/crates/ezd-link/src/link.rs b/crates/ezd-link/src/link.rs index e0d2558..3c52313 100644 --- a/crates/ezd-link/src/link.rs +++ b/crates/ezd-link/src/link.rs @@ -1,6 +1,6 @@ //! [`Link`]: a reliable ordered byte stream. -use crate::mux::{MuxOptions, MuxReceiver, MuxSender, MuxTask, spawn_mux, spawn_mux_split}; +use crate::mux::{MuxOptions, MuxReceiver, MuxSender, MuxTask, spawn_mux_lanes}; use std::io; use tokio::io::{AsyncRead, AsyncWrite}; use tokio::net::{TcpStream, ToSocketAddrs}; @@ -10,12 +10,51 @@ pub type BoxRead = Box; /// Boxed write half of a link. pub type BoxWrite = Box; +/// The streams of a link besides the control stream, one per channel that gets its own stream. +/// +/// A channel without a lane (`None`) travels on the control stream, in the mux's priority order. +/// Audio will be one more field here. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Lanes { + /// Input channel (pen, touch, buttons, scroll, keys). + pub input: Option, + /// Cursor channel (shapes and the latest-wins cursor state). + pub cursor: Option, + /// Video channel. + pub video: Option, +} + +impl Default for Lanes { + fn default() -> Self { + Lanes { + input: None, + cursor: None, + video: None, + } + } +} + +impl Lanes { + /// True when no channel has a lane. + pub fn is_empty(&self) -> bool { + self.input.is_none() && self.cursor.is_none() && self.video.is_none() + } + + /// The present lanes in the fixed order input, cursor, video. + pub fn into_vec(self) -> Vec { + [self.input, self.cursor, self.video] + .into_iter() + .flatten() + .collect() + } +} + /// A connected, reliable, ordered byte stream split into halves. /// /// Transports (TCP and QUIC now; AOA bulk endpoints later) only have to produce a -/// `Link`; everything above it is transport-agnostic. A link may carry a second -/// stream for video (see [`Link::with_video`]), which the mux then uses so video -/// cannot delay control, input or cursor traffic. +/// `Link`; everything above it is transport-agnostic. A link may carry further streams for +/// input, cursor and video (see [`Link::with_lanes`]), which the mux then uses so a stalled +/// channel cannot delay the others. pub struct Link { /// Read half. pub reader: BoxRead, @@ -23,8 +62,10 @@ pub struct Link { pub writer: BoxWrite, /// Human readable description of the peer, for logs. pub peer: String, - /// Separate video stream (read, write), if the transport has one. - video: Option<(BoxRead, BoxWrite)>, + /// Streams this side reads besides the control stream. + read_lanes: Lanes, + /// Streams this side writes besides the control stream. + write_lanes: Lanes, } impl std::fmt::Debug for Link { @@ -42,20 +83,22 @@ impl Link { reader, writer, peer: peer.into(), - video: None, + read_lanes: Lanes::default(), + write_lanes: Lanes::default(), } } - /// Adds a separate video stream. A side that only receives video passes - /// `tokio::io::sink()` as the write half; one that only sends passes `tokio::io::empty()`. - pub fn with_video(mut self, reader: BoxRead, writer: BoxWrite) -> Self { - self.video = Some((reader, writer)); + /// Adds the streams besides control. A side that never sends on a channel leaves that write + /// lane `None`, and one that never receives on it leaves the read lane `None`. + pub fn with_lanes(mut self, read: Lanes, write: Lanes) -> Self { + self.read_lanes = read; + self.write_lanes = write; self } - /// True when the link has a separate video stream. + /// True when the link has a separate video stream (in either direction). pub fn has_video_stream(&self) -> bool { - self.video.is_some() + self.read_lanes.video.is_some() || self.write_lanes.video.is_some() } /// Wraps a connected TCP stream and enables `TCP_NODELAY`. @@ -97,18 +140,9 @@ impl Link { /// Starts the mux with explicit [`MuxOptions`]. pub fn into_mux_with(self, opts: MuxOptions) -> (MuxSender, MuxReceiver, MuxTask) { - match self.video { - None => { - let rx = MuxReceiver::new(self.reader); - let (tx, task) = spawn_mux(self.writer, opts); - (tx, rx, task) - } - Some((video_r, video_w)) => { - let rx = MuxReceiver::new_split(self.reader, video_r); - let (tx, task) = spawn_mux_split(self.writer, video_w, opts); - (tx, rx, task) - } - } + let rx = MuxReceiver::new_lanes(self.reader, self.read_lanes); + let (tx, task) = spawn_mux_lanes(self.writer, self.write_lanes, opts); + (tx, rx, task) } } diff --git a/crates/ezd-link/src/mux.rs b/crates/ezd-link/src/mux.rs index 04d9711..a67a82b 100644 --- a/crates/ezd-link/src/mux.rs +++ b/crates/ezd-link/src/mux.rs @@ -24,16 +24,19 @@ //! would corrupt the reference chain); producers coalesce *before* capture by //! pulling the newest frame only when a slot is free. //! -//! [`spawn_mux_split`] serves the same queues onto two byte streams: control, -//! input and cursor traffic on one, video on the other, so a stalled or -//! retransmitting video stream cannot delay them (head-of-line blocking on a -//! QUIC-like transport). [`MuxReceiver::new_split`] is its counterpart. +//! [`spawn_mux_lanes`] serves the same queues onto several byte streams: a control +//! stream plus, optionally, one *lane* each for input, cursor and video (audio will be one more). +//! A stalled or retransmitting lane cannot delay the others (head-of-line blocking on a +//! QUIC-like transport). A channel without a lane is written on the control stream in the +//! priority order above. Each lane has its own writer loop and wake-up. [`MuxReceiver::new_lanes`] +//! is the counterpart. //! //! Reassembly on the receiving side ([`MuxReceiver`]) is keyed by //! `(channel, kind)`, so complete frames interleaved between video fragments are fine. use crate::link::BoxRead; use crate::link::BoxWrite; +use crate::link::Lanes; use ezd_proto::{ Channel, CursorState, FrameDecoder, Incoming, Message, ProtoError, TouchContact, VideoFrame, encode_message, fragments, frame::put_frame, @@ -44,7 +47,7 @@ use std::io; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::{Arc, Mutex, MutexGuard}; use std::time::{Duration, Instant}; -use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::io::{AsyncRead, AsyncWriteExt, ReadBuf}; use tokio::sync::{Notify, watch}; /// The mux (or its link) has been closed; nothing more can be sent. @@ -213,10 +216,14 @@ struct SlotState { struct Shared { q: Mutex, + /// Wakes the control writer (and, without lanes, the only writer). wake: Notify, - /// Wakes the video writer in split mode (`wake` serves control/input/cursor then). + /// Wakes the writer of each lane that exists; the other channels use `wake`. + wake_input: Notify, + wake_cursor: Notify, wake_video: Notify, - split: bool, + /// Which channels have their own stream. + lanes: Lanes<()>, slot: watch::Sender, coalesced: AtomicU64, states_sent: AtomicU64, @@ -251,19 +258,36 @@ impl Shared { fn close(&self) { self.lock().closing = true; self.wake.notify_one(); + self.wake_input.notify_one(); + self.wake_cursor.notify_one(); self.wake_video.notify_one(); } - /// Wakes the writer that serves video (`video`) or everything else. - fn wake_writer(&self, video: bool) { - if video && self.split { - self.wake_video.notify_one(); + /// Wakes the writer that serves `lane`: its own if it has a stream, else the control one. + fn wake_writer(&self, lane: Lane) { + let (present, notify) = match lane { + Lane::Control => (false, &self.wake), + Lane::Input => (self.lanes.input.is_some(), &self.wake_input), + Lane::Cursor => (self.lanes.cursor.is_some(), &self.wake_cursor), + Lane::Video => (self.lanes.video.is_some(), &self.wake_video), + }; + if present { + notify.notify_one(); } else { self.wake.notify_one(); } } } +/// Which queue a message goes to, for waking the right writer. +#[derive(Clone, Copy)] +enum Lane { + Control, + Input, + Cursor, + Video, +} + /// Calls `close` when the last `MuxSender` clone is dropped. struct CloseOnDrop(Arc); @@ -309,7 +333,7 @@ impl MuxSender { payload, ack_id, }; - { + let lane = { let mut q = self.shared.lock(); if q.closing || self.shared.slot.borrow().closed { return Err(MuxClosed.into()); @@ -319,6 +343,7 @@ impl MuxSender { if q.cursor_state.replace(enc).is_some() { self.shared.coalesced.fetch_add(1, Ordering::Relaxed); } + Lane::Cursor } Message::Pen(_) | Message::Touch(_) @@ -337,17 +362,24 @@ impl MuxSender { } else { q.input.push_back(QueuedInput { enc, class }); } + Lane::Input + } + Message::CursorShape(_) => { + q.cursor_shapes.push_back(enc); + Lane::Cursor } - Message::CursorShape(_) => q.cursor_shapes.push_back(enc), Message::VideoFrame(_) => { q.video.push_back(enc); self.shared.update_slot(&q); + Lane::Video + } + _ => { + q.control.push_back(enc); + Lane::Control } - _ => q.control.push_back(enc), } - } - self.shared - .wake_writer(matches!(msg, Message::VideoFrame(_))); + }; + self.shared.wake_writer(lane); Ok(()) } @@ -446,7 +478,7 @@ impl MuxTask { } } -fn new_shared(opts: MuxOptions, split: bool) -> Arc { +fn new_shared(opts: MuxOptions, lanes: Lanes<()>) -> Arc { let (slot, _) = watch::channel(SlotState { busy: false, closed: false, @@ -454,8 +486,10 @@ fn new_shared(opts: MuxOptions, split: bool) -> Arc { Arc::new(Shared { q: Mutex::new(Queues::default()), wake: Notify::new(), + wake_input: Notify::new(), + wake_cursor: Notify::new(), wake_video: Notify::new(), - split, + lanes, slot, coalesced: AtomicU64::new(0), states_sent: AtomicU64::new(0), @@ -481,25 +515,28 @@ fn clamp_chunk(opts: MuxOptions) -> usize { /// Spawns the writer task on the current tokio runtime. pub fn spawn_mux(writer: BoxWrite, opts: MuxOptions) -> (MuxSender, MuxTask) { - let shared = new_shared(opts, false); - let task = tokio::spawn(writer_task(shared.clone(), writer, clamp_chunk(opts))); - (sender_for(shared), MuxTask(task)) + spawn_mux_lanes(writer, Lanes::default(), opts) } -/// Like [`spawn_mux`] but with two streams: control, input and cursor traffic -/// go to `control`, video to `video`. Both writers run in one task; if either -/// fails the mux closes and the other stops too. On a graceful close each -/// drains its queues and shuts down its own half. -pub fn spawn_mux_split( +/// Like [`spawn_mux`] but with a lane (own stream) for each channel in `lanes` that is `Some`. +/// A channel without a lane is written on `control` in the priority order of the module docs. +/// All writer loops run in one task; if one fails the mux closes and the others stop too. On a +/// graceful close each drains its queues and every half is shut down. +pub fn spawn_mux_lanes( control: BoxWrite, - video: BoxWrite, + lanes: Lanes, opts: MuxOptions, ) -> (MuxSender, MuxTask) { - let shared = new_shared(opts, true); - let task = tokio::spawn(split_task( + let present = Lanes { + input: lanes.input.as_ref().map(|_| ()), + cursor: lanes.cursor.as_ref().map(|_| ()), + video: lanes.video.as_ref().map(|_| ()), + }; + let shared = new_shared(opts, present); + let task = tokio::spawn(lanes_task( shared.clone(), control, - video, + lanes, clamp_chunk(opts), )); (sender_for(shared), MuxTask(task)) @@ -513,39 +550,101 @@ enum Next { Idle(Option), } -async fn writer_task(shared: Arc, mut w: BoxWrite, chunk_len: usize) -> io::Result<()> { - let res = writer_loop(&shared, &mut w, chunk_len).await; - { - let mut q = shared.lock(); - q.closing = true; - } +/// Runs the writer loops of every stream; the first error stops the others. +async fn lanes_task( + shared: Arc, + mut control: BoxWrite, + mut lanes: Lanes, + chunk_len: usize, +) -> io::Result<()> { + let serves = Serves { + input: lanes.input.is_none(), + cursor: lanes.cursor.is_none(), + video: lanes.video.is_none(), + }; + let res = { + // `try_join!` returns at the first error and otherwise waits for every loop to drain. + // Audio: add its lane to `Lanes`, `Serves` and this join. + tokio::try_join!( + writer_loop(&shared, &mut control, chunk_len, serves), + async { + match lanes.input.as_mut() { + Some(w) => input_loop(&shared, w, chunk_len).await, + None => Ok(()), + } + }, + async { + match lanes.cursor.as_mut() { + Some(w) => cursor_loop(&shared, w, chunk_len).await, + None => Ok(()), + } + }, + async { + match lanes.video.as_mut() { + Some(w) => video_loop(&shared, w, chunk_len).await, + None => Ok(()), + } + }, + ) + .map(|_| ()) + }; + shared.lock().closing = true; shared.slot.send_modify(|s| s.closed = true); - let _ = w.shutdown().await; + async fn shut(w: Option<&mut BoxWrite>) { + if let Some(w) = w { + let _ = w.shutdown().await; + } + } + let _ = tokio::join!( + shut(Some(&mut control)), + shut(lanes.input.as_mut()), + shut(lanes.cursor.as_mut()), + shut(lanes.video.as_mut()), + ); if let Err(e) = &res { tracing::debug!("mux writer stopped: {e}"); } res } -async fn writer_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { +/// Channels the control writer serves because they have no stream of their own. +#[derive(Clone, Copy)] +struct Serves { + input: bool, + cursor: bool, + video: bool, +} + +/// Writer of the control stream: control, then (when they have no lane) input, cursor shapes, +/// cursor state and video chunks, in that order. +async fn writer_loop( + shared: &Shared, + w: &mut BoxWrite, + chunk_len: usize, + serves: Serves, +) -> io::Result<()> { // Video frame currently being written and the offset of its next chunk. let mut in_flight: Option<(Encoded, usize)> = None; let mut buf: Vec = Vec::with_capacity(chunk_len + 16); loop { let next = { let mut q = shared.lock(); - let deadline = expire_acks(shared, &mut q); + let deadline = if serves.video { + expire_acks(shared, &mut q) + } else { + None + }; if let Some(m) = q.control.pop_front() { Next::Whole(m, false) - } else if !q.input.is_empty() { + } else if serves.input && !q.input.is_empty() { Next::Input(q.input.drain(..).map(|i| i.enc).collect()) - } else if let Some(m) = q.cursor_shapes.pop_front() { + } else if let Some(m) = serves.cursor.then(|| q.cursor_shapes.pop_front()).flatten() { Next::Whole(m, false) - } else if let Some(m) = q.cursor_state.take() { + } else if let Some(m) = serves.cursor.then(|| q.cursor_state.take()).flatten() { Next::Whole(m, true) } else if in_flight.is_some() { Next::VideoChunk - } else if let Some(v) = q.video.pop_front() { + } else if let Some(v) = serves.video.then(|| q.video.pop_front()).flatten() { in_flight = Some((v, 0)); q.writing = true; Next::VideoChunk @@ -656,48 +755,32 @@ fn finish_video(shared: &Shared, ack_id: Option) { shared.update_slot(&q); } -/// Runs both split writers; the first error stops the other one. -async fn split_task( - shared: Arc, - mut control: BoxWrite, - mut video: BoxWrite, - chunk_len: usize, -) -> io::Result<()> { - let res = { - let c = control_loop(&shared, &mut control, chunk_len); - let v = video_loop(&shared, &mut video, chunk_len); - tokio::pin!(c, v); - tokio::select! { - r = &mut c => match r { - Ok(()) => v.await, - Err(e) => Err(e), - }, - r = &mut v => match r { - Ok(()) => c.await, - Err(e) => Err(e), - }, +/// Writer of the input lane: reliable FIFO, one write and flush per batch. +async fn input_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { + let mut buf: Vec = Vec::with_capacity(chunk_len + 16); + loop { + let (batch, closing) = { + let mut q = shared.lock(); + let batch: Vec = q.input.drain(..).map(|i| i.enc).collect(); + (batch, q.closing) + }; + if !batch.is_empty() { + write_input(shared, w, &mut buf, &batch, chunk_len).await?; + } else if closing { + return Ok(()); + } else { + shared.wake_input.notified().await; } - }; - shared.lock().closing = true; - shared.slot.send_modify(|s| s.closed = true); - let _ = tokio::join!(control.shutdown(), video.shutdown()); - if let Err(e) = &res { - tracing::debug!("mux writer stopped: {e}"); } - res } -/// Split-mode writer for control > input > cursor shapes > cursor state. -async fn control_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { +/// Writer of the cursor lane: shapes (FIFO) before the latest-wins state. +async fn cursor_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { let mut buf: Vec = Vec::with_capacity(chunk_len + 16); loop { let next = { let mut q = shared.lock(); - if let Some(m) = q.control.pop_front() { - Next::Whole(m, false) - } else if !q.input.is_empty() { - Next::Input(q.input.drain(..).map(|i| i.enc).collect()) - } else if let Some(m) = q.cursor_shapes.pop_front() { + if let Some(m) = q.cursor_shapes.pop_front() { Next::Whole(m, false) } else if let Some(m) = q.cursor_state.take() { Next::Whole(m, true) @@ -712,13 +795,12 @@ async fn control_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io Next::Whole(m, is_state) => { write_whole(shared, w, &mut buf, &m, is_state, chunk_len).await?; } - Next::Input(batch) => write_input(shared, w, &mut buf, &batch, chunk_len).await?, - _ => shared.wake.notified().await, + _ => shared.wake_cursor.notified().await, } } } -/// Split-mode writer for video; also expires ack deadlines while idle. +/// Writer of the video lane; also expires ack deadlines while idle. async fn video_loop(shared: &Shared, w: &mut BoxWrite, chunk_len: usize) -> io::Result<()> { let mut buf: Vec = Vec::with_capacity(chunk_len + 16); loop { @@ -780,20 +862,15 @@ fn expire_acks(shared: &Shared, q: &mut Queues) -> Option { q.unacked.front().map(|&(_, at)| at + timeout) } -/// Reads and decodes messages from a link's read half (or from the two halves -/// of a split link). +/// Reads and decodes messages from a link's read half (or from the control stream and the lane +/// streams of a link with lanes). pub struct MuxReceiver { - reader: BoxRead, - decoder: FrameDecoder, - buf: Vec, + /// The control stream first, then the lanes; polled in this order. + streams: Vec, unknown: u64, - /// Video stream of a split receiver; `None` for a single-stream one. - video: Option, - /// The primary reader ended cleanly (split mode only). - ended: bool, } -/// Reader, decoder and read buffer of the second stream of a split receiver. +/// Reader, decoder and read buffer of one stream of a receiver. struct Side { reader: BoxRead, decoder: FrameDecoder, @@ -801,6 +878,17 @@ struct Side { ended: bool, } +impl Side { + fn new(reader: BoxRead) -> Self { + Side { + reader, + decoder: FrameDecoder::new(), + buf: vec![0; 64 * 1024], + ended: false, + } + } +} + impl std::fmt::Debug for MuxReceiver { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("MuxReceiver") @@ -824,20 +912,15 @@ fn pop_known(decoder: &mut FrameDecoder, unknown: &mut u64) -> Result, - ended: &mut bool, -) -> Result<(), MuxError> { +fn feed(side: &mut Side, n: io::Result) -> Result<(), MuxError> { let n = n?; if n == 0 { - if decoder.buffered() != 0 { + if side.decoder.buffered() != 0 { return Err(io::Error::from(io::ErrorKind::UnexpectedEof).into()); } - *ended = true; + side.ended = true; } else { - decoder.push(&buf[..n]); + side.decoder.push(&side.buf[..n]); } Ok(()) } @@ -845,27 +928,19 @@ fn feed( impl MuxReceiver { /// Wraps a read half. pub fn new(reader: BoxRead) -> Self { - MuxReceiver { - reader, - decoder: FrameDecoder::new(), - buf: vec![0; 64 * 1024], - unknown: 0, - video: None, - ended: false, - } + Self::new_lanes(reader, Lanes::default()) } - /// Wraps the two read halves of a split link (see [`spawn_mux_split`]). - /// Each stream has its own decoder; control is preferred when both have data. - pub fn new_split(control: BoxRead, video: BoxRead) -> Self { + /// Wraps the control read half and the lane streams of a link (see [`spawn_mux_lanes`]). + /// Each stream has its own decoder; control is preferred when several have data. + pub fn new_lanes(control: BoxRead, lanes: Lanes) -> Self { + let streams = std::iter::once(control) + .chain(lanes.into_vec()) + .map(Side::new) + .collect(); MuxReceiver { - video: Some(Side { - reader: video, - decoder: FrameDecoder::new(), - buf: vec![0; 64 * 1024], - ended: false, - }), - ..Self::new(control) + streams, + unknown: 0, } } @@ -875,58 +950,41 @@ impl MuxReceiver { } /// Receives the next known message; `Ok(None)` on a clean EOF between messages - /// (for a split receiver: once both streams ended). Unknown message kinds are - /// skipped transparently. Cancel-safe. + /// (with lanes: once every stream ended). Unknown message kinds are skipped + /// transparently. A stream that ends in the middle of a message is an error. Cancel-safe. pub async fn recv(&mut self) -> Result, MuxError> { - if self.video.is_some() { - return self.recv_split().await; - } loop { - match self.decoder.pop()? { - Some(Incoming::Message(m)) => return Ok(Some(m)), - Some(Incoming::Unknown { channel, kind, len }) => { - self.unknown += 1; - tracing::debug!(channel, kind, len, "skipping unknown message"); - continue; + for s in &mut self.streams { + if let Some(m) = pop_known(&mut s.decoder, &mut self.unknown)? { + return Ok(Some(m)); } - None => {} - } - let n = self.reader.read(&mut self.buf).await?; - if n == 0 { - return if self.decoder.buffered() == 0 { - Ok(None) - } else { - Err(io::Error::from(io::ErrorKind::UnexpectedEof).into()) - }; } - self.decoder.push(&self.buf[..n]); - } - } - - async fn recv_split(&mut self) -> Result, MuxError> { - let Some(video) = self.video.as_mut() else { - return Ok(None); - }; - loop { - if let Some(m) = pop_known(&mut self.decoder, &mut self.unknown)? { - return Ok(Some(m)); - } - if let Some(m) = pop_known(&mut video.decoder, &mut self.unknown)? { - return Ok(Some(m)); - } - if self.ended && video.ended { + if self.streams.iter().all(|s| s.ended) { return Ok(None); } - // Reads are cancel-safe: the losing branch of the select drops no data. - tokio::select! { - biased; - n = self.reader.read(&mut self.buf), if !self.ended => { - feed(&mut self.decoder, &self.buf, n, &mut self.ended)?; - } - n = video.reader.read(&mut video.buf), if !video.ended => { - feed(&mut video.decoder, &video.buf, n, &mut video.ended)?; + // A read completes inside the poll that returns it, so dropping this future never + // loses data that was already read. + let streams = &mut self.streams; + let (i, n) = std::future::poll_fn(|cx| { + for (i, s) in streams.iter_mut().enumerate() { + if s.ended { + continue; + } + let mut rb = ReadBuf::new(&mut s.buf); + match std::pin::Pin::new(&mut s.reader).poll_read(cx, &mut rb) { + std::task::Poll::Ready(Ok(())) => { + return std::task::Poll::Ready((i, Ok(rb.filled().len()))); + } + std::task::Poll::Ready(Err(e)) => { + return std::task::Poll::Ready((i, Err(e))); + } + std::task::Poll::Pending => {} + } } - } + std::task::Poll::Pending + }) + .await; + feed(&mut self.streams[i], n)?; } } } @@ -1545,16 +1603,47 @@ mod tests { assert!(tx.video_slot_free()); } - /// Split mux over two duplex streams; returns the sender, its task and a split receiver. - fn split_pair( + /// Capacities of the duplex streams of a test mux (`None`: that channel has no lane). + type Caps = Lanes; + + fn video_caps(cap: usize) -> Caps { + Lanes { + video: Some(cap), + ..Lanes::default() + } + } + + fn all_caps(cap: usize) -> Caps { + Lanes { + input: Some(cap), + cursor: Some(cap), + video: Some(cap), + } + } + + /// Mux over duplex streams (control plus one per lane in `caps`); returns the sender, its + /// task and the matching lanes receiver. + fn lanes_pair( ctl_cap: usize, - vid_cap: usize, + caps: Caps, opts: MuxOptions, ) -> (MuxSender, MuxTask, MuxReceiver) { let (cw, cr) = tokio::io::duplex(ctl_cap); - let (vw, vr) = tokio::io::duplex(vid_cap); - let (tx, task) = spawn_mux_split(Box::new(cw), Box::new(vw), opts); - (tx, task, MuxReceiver::new_split(Box::new(cr), Box::new(vr))) + let mut writes = Lanes::::default(); + let mut reads = Lanes::::default(); + for (cap, w, r) in [ + (caps.input, &mut writes.input, &mut reads.input), + (caps.cursor, &mut writes.cursor, &mut reads.cursor), + (caps.video, &mut writes.video, &mut reads.video), + ] { + if let Some(cap) = cap { + let (lw, lr) = tokio::io::duplex(cap); + *w = Some(Box::new(lw)); + *r = Some(Box::new(lr)); + } + } + let (tx, task) = spawn_mux_lanes(Box::new(cw), writes, opts); + (tx, task, MuxReceiver::new_lanes(Box::new(cr), reads)) } /// Writer that fails every write. @@ -1581,27 +1670,46 @@ mod tests { } } + fn shape(id: u32) -> Message { + Message::CursorShape(CursorShape { + shape_id: id, + width: 1, + height: 1, + hot_x: 0, + hot_y: 0, + rgba: vec![0; 4], + }) + } + + fn ping(seq: u32) -> Message { + Message::Ping(Ping { seq, t0_us: 0 }) + } + + /// Raw frame bytes of `msg`, as a lane peer would write them. + fn framed(msg: &Message) -> Vec { + let mut buf = Vec::new(); + let (ch, kind, payload) = encode_message(msg).unwrap(); + put_frame(&mut buf, ch as u8, kind, 0, &payload); + buf + } + #[tokio::test] - async fn split_stalled_video_does_not_delay_control_traffic() { + async fn lanes_stalled_video_does_not_delay_control_traffic() { let (cw, cr) = tokio::io::duplex(64 * 1024); let (vw, _vr_never_read) = tokio::io::duplex(1024); - let (tx, _task) = spawn_mux_split(Box::new(cw), Box::new(vw), onwrite(4096)); + let lanes = Lanes { + video: Some(Box::new(vw) as BoxWrite), + ..Lanes::default() + }; + let (tx, _task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(4096)); let mut rx = MuxReceiver::new(Box::new(cr)); tx.send_video(vf(1, 1024 * 1024)).unwrap(); sleep(Duration::from_millis(50)).await; // video writer is blocked on a full stream - tx.send_control(Message::Ping(Ping { seq: 1, t0_us: 0 })) - .unwrap(); + tx.send_control(ping(1)).unwrap(); tx.send(&pen(7, PenSample::IN_RANGE)).unwrap(); - tx.send(&Message::CursorShape(CursorShape { - shape_id: 4, - width: 1, - height: 1, - hot_x: 0, - hot_y: 0, - rgba: vec![0; 4], - })) - .unwrap(); + tx.send(&shape(4)).unwrap(); tx.send_cursor_state(cs(5)).unwrap(); + // Input and cursor have no lane here: control stream, in priority order. assert!(matches!(recv(&mut rx).await, Message::Ping(_))); assert!(matches!(recv(&mut rx).await, Message::Pen(p) if p.t_us == 7)); assert!(matches!(recv(&mut rx).await, Message::CursorShape(s) if s.shape_id == 4)); @@ -1610,19 +1718,131 @@ mod tests { } #[tokio::test] - async fn split_delivers_both_streams_in_per_channel_order() { - let (tx, _task, mut rx) = split_pair(4096, 4096, onwrite(1024)); + async fn lanes_stalled_video_does_not_delay_cursor_lane() { + let (cw, _cr) = tokio::io::duplex(64 * 1024); + let (iw, _ir) = tokio::io::duplex(64 * 1024); + let (kw, kr) = tokio::io::duplex(64 * 1024); + let (vw, _vr_never_read) = tokio::io::duplex(1024); + let lanes = Lanes { + input: Some(Box::new(iw) as BoxWrite), + cursor: Some(Box::new(kw) as BoxWrite), + video: Some(Box::new(vw) as BoxWrite), + }; + let (tx, _task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(4096)); + let mut rx = MuxReceiver::new(Box::new(kr)); + tx.send_video(vf(1, 1024 * 1024)).unwrap(); + sleep(Duration::from_millis(50)).await; + tx.send(&shape(2)).unwrap(); + tx.send_cursor_state(cs(9)).unwrap(); + assert!(matches!(recv(&mut rx).await, Message::CursorShape(s) if s.shape_id == 2)); + assert!(matches!(recv(&mut rx).await, Message::CursorState(s) if s.x == 9)); + } + + #[tokio::test] + async fn lanes_stalled_cursor_does_not_delay_input_or_control() { + let (cw, cr) = tokio::io::duplex(64 * 1024); + let (iw, ir) = tokio::io::duplex(64 * 1024); + let (kw, _kr_never_read) = tokio::io::duplex(64); + let lanes = Lanes { + input: Some(Box::new(iw) as BoxWrite), + cursor: Some(Box::new(kw) as BoxWrite), + video: None, + }; + let (tx, _task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(4096)); + let mut ctl = MuxReceiver::new(Box::new(cr)); + let mut inp = MuxReceiver::new(Box::new(ir)); + tx.send(&shape(1)).unwrap(); + tx.send(&Message::CursorShape(CursorShape { + shape_id: 2, + width: 64, + height: 64, + hot_x: 0, + hot_y: 0, + rgba: vec![0; 64 * 64 * 4], + })) + .unwrap(); + sleep(Duration::from_millis(50)).await; // cursor writer is blocked on a full stream + tx.send(&pen(3, PenSample::IN_RANGE)).unwrap(); + tx.send_control(ping(2)).unwrap(); + assert!(matches!(recv(&mut inp).await, Message::Pen(p) if p.t_us == 3)); + assert!(matches!(recv(&mut ctl).await, Message::Ping(_))); + } + + #[tokio::test] + async fn lanes_stalled_input_does_not_delay_control() { + let (cw, cr) = tokio::io::duplex(64 * 1024); + let (iw, _ir_never_read) = tokio::io::duplex(64); + let lanes = Lanes { + input: Some(Box::new(iw) as BoxWrite), + ..Lanes::default() + }; + let (tx, _task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(4096)); + let mut rx = MuxReceiver::new(Box::new(cr)); + for i in 0..200 { + tx.send(&pen(i, PenSample::IN_RANGE)).unwrap(); + } + sleep(Duration::from_millis(50)).await; + tx.send_control(ping(1)).unwrap(); + tx.send_cursor_state(cs(1)).unwrap(); + // Control first, then the cursor traffic that has no lane here. + assert!(matches!(recv(&mut rx).await, Message::Ping(_))); + assert!(matches!(recv(&mut rx).await, Message::CursorState(_))); + } + + #[tokio::test] + async fn lanes_absent_traffic_falls_back_to_control_in_priority_order() { + let (cw, cr) = tokio::io::duplex(1 << 20); + let (tx, _task) = spawn_mux_lanes(Box::new(cw), Lanes::default(), onwrite(4096)); + let mut rx = MuxReceiver::new(Box::new(cr)); + // Everything is queued before the writer can run (single-threaded test runtime). + tx.send_cursor_state(cs(1)).unwrap(); + tx.send(&shape(1)).unwrap(); + tx.send(&pen(1, PenSample::IN_RANGE)).unwrap(); + tx.send_control(ping(1)).unwrap(); + assert!(matches!(recv(&mut rx).await, Message::Ping(_))); + assert!(matches!(recv(&mut rx).await, Message::Pen(_))); + assert!(matches!(recv(&mut rx).await, Message::CursorShape(_))); + assert!(matches!(recv(&mut rx).await, Message::CursorState(_))); + } + + #[tokio::test] + async fn lanes_each_channel_uses_its_own_stream() { + let (cw, cr) = tokio::io::duplex(1 << 20); + let (iw, ir) = tokio::io::duplex(1 << 20); + let (kw, kr) = tokio::io::duplex(1 << 20); + let (vw, vr) = tokio::io::duplex(1 << 20); + let lanes = Lanes { + input: Some(Box::new(iw) as BoxWrite), + cursor: Some(Box::new(kw) as BoxWrite), + video: Some(Box::new(vw) as BoxWrite), + }; + let (tx, _task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(4096)); + tx.send_control(ping(1)).unwrap(); + tx.send(&pen(1, PenSample::IN_RANGE)).unwrap(); + tx.send(&shape(1)).unwrap(); + tx.send_cursor_state(cs(1)).unwrap(); + tx.send_video(vf(1, 100)).unwrap(); + let mut c = MuxReceiver::new(Box::new(cr)); + let mut i = MuxReceiver::new(Box::new(ir)); + let mut k = MuxReceiver::new(Box::new(kr)); + let mut v = MuxReceiver::new(Box::new(vr)); + assert!(matches!(recv(&mut c).await, Message::Ping(_))); + assert!(matches!(recv(&mut i).await, Message::Pen(_))); + assert!(matches!(recv(&mut k).await, Message::CursorShape(_))); + assert!(matches!(recv(&mut k).await, Message::CursorState(_))); + assert!(matches!(recv(&mut v).await, Message::VideoFrame(_))); + } + + #[tokio::test] + async fn lanes_deliver_all_streams_in_per_channel_order() { + let (tx, _task, mut rx) = lanes_pair(4096, all_caps(4096), onwrite(1024)); let sender = { let tx = tx.clone(); tokio::spawn(async move { for i in 0..10u64 { tx.send_video(vf(i, 20_000)).unwrap(); tx.send(&pen(i, PenSample::IN_RANGE)).unwrap(); - tx.send_control(Message::Ping(Ping { - seq: i as u32, - t0_us: 0, - })) - .unwrap(); + tx.send_control(ping(i as u32)).unwrap(); tx.wait_video_slot().await.unwrap(); } }) @@ -1652,8 +1872,8 @@ mod tests { } #[tokio::test] - async fn split_credit_is_held_until_ack_and_early_ack_works() { - let (tx, _task, mut rx) = split_pair(1 << 20, 1 << 20, acked(1, 5000)); + async fn lanes_credit_is_held_until_ack_and_early_ack_works() { + let (tx, _task, mut rx) = lanes_pair(1 << 20, video_caps(1 << 20), acked(1, 5000)); tx.send_video(vf(7, 100)).unwrap(); assert!(matches!(recv(&mut rx).await, Message::VideoFrame(_))); sleep(Duration::from_millis(50)).await; @@ -1675,8 +1895,8 @@ mod tests { } #[tokio::test] - async fn split_ack_timeout_frees_slot_while_idle() { - let (tx, _task, mut rx) = split_pair(1 << 20, 1 << 20, acked(1, 100)); + async fn lanes_ack_timeout_frees_slot_while_idle() { + let (tx, _task, mut rx) = lanes_pair(1 << 20, video_caps(1 << 20), acked(1, 100)); tx.send_video(vf(1, 100)).unwrap(); recv(&mut rx).await; timeout(Duration::from_secs(2), tx.wait_video_slot()) @@ -1687,10 +1907,11 @@ mod tests { } #[tokio::test] - async fn split_close_flushes_both_streams_then_ends() { - let (tx, task, mut rx) = split_pair(64 * 1024, 64 * 1024, onwrite(1024)); + async fn lanes_close_flushes_every_stream_then_ends() { + let (tx, task, mut rx) = lanes_pair(64 * 1024, all_caps(64 * 1024), onwrite(1024)); tx.send_video(vf(1, 10_000)).unwrap(); tx.send_cursor_state(cs(3)).unwrap(); + tx.send(&pen(4, PenSample::IN_RANGE)).unwrap(); tx.send_control(Message::Bye(Bye { reason: "done".into(), })) @@ -1705,9 +1926,10 @@ mod tests { { got.push(m); } - assert_eq!(got.len(), 3); + assert_eq!(got.len(), 4); assert!(got.iter().any(|m| matches!(m, Message::Bye(_)))); assert!(got.iter().any(|m| matches!(m, Message::CursorState(_)))); + assert!(got.iter().any(|m| matches!(m, Message::Pen(_)))); assert!( got.iter() .any(|m| matches!(m, Message::VideoFrame(v) if v.data.len() == 10_000)) @@ -1716,47 +1938,87 @@ mod tests { } #[tokio::test] - async fn split_receiver_survives_one_stream_eof() { + async fn lanes_receiver_ends_only_when_all_streams_end() { let (mut cw, cr) = tokio::io::duplex(4096); + let (mut iw, ir) = tokio::io::duplex(4096); + let (mut kw, kr) = tokio::io::duplex(4096); let (mut vw, vr) = tokio::io::duplex(4096); - let mut rx = MuxReceiver::new_split(Box::new(cr), Box::new(vr)); - let mut buf = Vec::new(); - let (ch, kind, payload) = encode_message(&Message::ConfigAck).unwrap(); - put_frame(&mut buf, ch as u8, kind, 0, &payload); - cw.write_all(&buf).await.unwrap(); + let lanes = Lanes { + input: Some(Box::new(ir) as BoxRead), + cursor: Some(Box::new(kr) as BoxRead), + video: Some(Box::new(vr) as BoxRead), + }; + let mut rx = MuxReceiver::new_lanes(Box::new(cr), lanes); + cw.write_all(&framed(&Message::ConfigAck)).await.unwrap(); cw.shutdown().await.unwrap(); // control ends first assert!(matches!(recv(&mut rx).await, Message::ConfigAck)); + iw.write_all(&framed(&pen(1, PenSample::IN_RANGE))) + .await + .unwrap(); + iw.shutdown().await.unwrap(); + assert!(matches!(recv(&mut rx).await, Message::Pen(_))); + kw.shutdown().await.unwrap(); assert!( timeout(Duration::from_millis(100), rx.recv()) .await .is_err(), "video is still open" ); - let (ch, kind, payload) = encode_message(&Message::VideoFrame(vf(1, 10))).unwrap(); - buf.clear(); - put_frame(&mut buf, ch as u8, kind, 0, &payload); - vw.write_all(&buf).await.unwrap(); + let frame = framed(&Message::VideoFrame(vf(1, 10))); + vw.write_all(&frame).await.unwrap(); assert!(matches!(recv(&mut rx).await, Message::VideoFrame(_))); - // Mid-message EOF on video is an error. - vw.write_all(&buf[..5]).await.unwrap(); vw.shutdown().await.unwrap(); + assert!(rx.recv().await.unwrap().is_none()); + } + + #[tokio::test] + async fn lanes_receiver_mid_message_eof_on_a_lane_is_an_error() { + let (_cw, cr) = tokio::io::duplex(4096); + let (mut kw, kr) = tokio::io::duplex(4096); + let lanes = Lanes { + cursor: Some(Box::new(kr) as BoxRead), + ..Lanes::default() + }; + let mut rx = MuxReceiver::new_lanes(Box::new(cr), lanes); + let frame = framed(&Message::CursorState(cs(1))); + kw.write_all(&frame[..5]).await.unwrap(); + kw.shutdown().await.unwrap(); assert!(matches!(rx.recv().await, Err(MuxError::Io(_)))); } #[tokio::test] - async fn split_video_write_error_closes_the_mux() { - let (cw, _cr) = tokio::io::duplex(4096); - let (tx, task) = spawn_mux_split(Box::new(cw), Box::new(FailWriter), onwrite(1024)); - tx.send_video(vf(1, 100)).unwrap(); - let err = timeout(Duration::from_secs(5), task.join()) - .await - .unwrap() - .unwrap_err(); - assert_eq!(err.kind(), io::ErrorKind::BrokenPipe); - assert!(matches!( - tx.send_control(Message::ConfigAck), - Err(MuxError::Closed(_)) - )); - assert!(tx.wait_video_slot().await.is_err()); + async fn lanes_write_error_on_any_lane_closes_the_mux() { + for failing in ["input", "cursor", "video"] { + let (cw, _cr) = tokio::io::duplex(4096); + let (ow, _or) = tokio::io::duplex(4096); + let bad = || Some(Box::new(FailWriter) as BoxWrite); + let ok = || Some(Box::new(ow) as BoxWrite); + let mut lanes = Lanes { + input: ok(), + cursor: None, + video: None, + }; + match failing { + "input" => lanes.input = bad(), + "cursor" => lanes.cursor = bad(), + _ => lanes.video = bad(), + } + let (tx, task) = spawn_mux_lanes(Box::new(cw), lanes, onwrite(1024)); + match failing { + "input" => tx.send(&pen(1, PenSample::IN_RANGE)).unwrap(), + "cursor" => tx.send_cursor_state(cs(1)).unwrap(), + _ => tx.send_video(vf(1, 100)).unwrap(), + } + let err = timeout(Duration::from_secs(5), task.join()) + .await + .unwrap() + .unwrap_err(); + assert_eq!(err.kind(), io::ErrorKind::BrokenPipe, "{failing}"); + assert!(matches!( + tx.send_control(Message::ConfigAck), + Err(MuxError::Closed(_)) + )); + assert!(tx.wait_video_slot().await.is_err()); + } } } diff --git a/crates/ezd-link/src/quic.rs b/crates/ezd-link/src/quic.rs index 0630903..d452326 100644 --- a/crates/ezd-link/src/quic.rs +++ b/crates/ezd-link/src/quic.rs @@ -8,18 +8,24 @@ //! //! Streams (see `docs/protocol.md`): //! * control, bidirectional, opened by the client: [`LinkOpen`] / [`LinkReply`], then the framed -//! control, input and cursor traffic; -//! * video, unidirectional, opened by the host after [`LinkReply::Accepted`]: one -//! [`VIDEO_STREAM_TAG`] byte, then framed video. +//! control traffic; +//! * cursor and video, unidirectional, opened by the host after [`LinkReply::Accepted`]; +//! * input, unidirectional, opened by the client after it read [`LinkReply::Accepted`]. //! -//! The control stream has the higher send priority, and since the streams are independent a -//! lost video packet never delays cursor or input traffic. +//! Every unidirectional stream starts with one tag byte ([`CURSOR_STREAM_TAG`], +//! [`VIDEO_STREAM_TAG`], [`INPUT_STREAM_TAG`]) and then carries the framed messages of its +//! channel. The receiver dispatches by tag, not by arrival order. Audio will be one more stream +//! ([`AUDIO_STREAM_TAG`] is reserved). +//! +//! Send priorities (higher first): control 4, input 3, cursor 2, audio 1 (reserved), video 0. +//! Each channel has its own stream, so a lost packet delays only the channel it belongs to. use crate::identity::{Identity, fingerprint_of}; -use crate::link::Link; +use crate::link::{BoxRead, BoxWrite, Lanes, Link}; use ezd_proto::ProtoError; use ezd_proto::pair::{ - self, ALPN, Fingerprint, LinkOpen, LinkReply, MAX_PREAMBLE_LEN, Refusal, VIDEO_STREAM_TAG, + self, ALPN, CURSOR_STREAM_TAG, Fingerprint, INPUT_STREAM_TAG, LinkOpen, LinkReply, + MAX_PREAMBLE_LEN, Refusal, VIDEO_STREAM_TAG, }; use quinn::{Connection, Endpoint, RecvStream, SendStream, VarInt}; use rustls::client::danger::{HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier}; @@ -40,12 +46,16 @@ use tokio::io::{AsyncRead, ReadBuf}; /// TLS server name. Certificates are checked by fingerprint, so it is only a placeholder. const SERVER_NAME: &str = "ezdisplay"; -/// Time allowed for each preamble step (open, reply, video stream). +/// Time allowed for each preamble step (open, reply, lane streams). pub const PREAMBLE_TIMEOUT: Duration = Duration::from_secs(10); /// Application close code for a normal end or a refusal. const CLOSE_OK: u32 = 0; -/// Send priority of the control stream (higher is served first); video uses 0. -const CONTROL_PRIORITY: i32 = 1; +/// Send priorities (higher is served first). 1 is left for audio, which slots between cursor +/// and video. +const CONTROL_PRIORITY: i32 = 4; +const INPUT_PRIORITY: i32 = 3; +const CURSOR_PRIORITY: i32 = 2; +const VIDEO_PRIORITY: i32 = 0; /// Congestion controller of a Wi-Fi link. #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] @@ -138,8 +148,8 @@ enum Side { /// Only the host receives from peers it has not authenticated yet (it accepts any client /// certificate), so its receive windows are small: it only reads the preamble and input, never /// video. The client receives video and needs room for a large keyframe in flight. Each side -/// allows exactly the streams the other opens: one bidirectional stream from the client, one -/// unidirectional stream from the host. +/// allows exactly the streams the other opens: one bidirectional stream and one unidirectional +/// stream (input) from the client, two unidirectional streams (cursor, video) from the host. fn transport(cc: Congestion, side: Side) -> quinn::TransportConfig { let mut t = quinn::TransportConfig::default(); t.keep_alive_interval(Some(Duration::from_secs(1))) @@ -153,12 +163,12 @@ fn transport(cc: Congestion, side: Side) -> quinn::TransportConfig { .stream_receive_window(VarInt::from_u32(256 << 10)) .receive_window(VarInt::from_u32(256 << 10)) .max_concurrent_bidi_streams(VarInt::from_u32(1)) - .max_concurrent_uni_streams(VarInt::from_u32(0)), + .max_concurrent_uni_streams(VarInt::from_u32(1)), Side::Client => t .stream_receive_window(VarInt::from_u32(8 << 20)) .receive_window(VarInt::from_u32(16 << 20)) .max_concurrent_bidi_streams(VarInt::from_u32(0)) - .max_concurrent_uni_streams(VarInt::from_u32(1)), + .max_concurrent_uni_streams(VarInt::from_u32(2)), }; if cc == Congestion::Bbr { t.congestion_controller_factory(Arc::new(quinn::congestion::BbrConfig::default())); @@ -355,23 +365,24 @@ impl QuicConn { return Err(QuicError::Unexpected("pairing reply to a session request")); } } - let mut video = tokio::time::timeout(PREAMBLE_TIMEOUT, self.conn.accept_uni()) - .await - .map_err(|_| QuicError::Timeout)??; - let mut tag = [0u8; 1]; - tokio::time::timeout(PREAMBLE_TIMEOUT, video.read_exact(&mut tag)) - .await - .map_err(|_| QuicError::Timeout)??; - if tag[0] != VIDEO_STREAM_TAG { - return Err(QuicError::Unexpected("video stream tag")); - } + let input = open_tagged(&self.conn, INPUT_STREAM_TAG, INPUT_PRIORITY).await?; + let [cursor, video] = + accept_tagged(&self.conn, [CURSOR_STREAM_TAG, VIDEO_STREAM_TAG]).await?; let peer = format!("quic:{}", self.conn.remote_address()); let keep = Arc::new(Lingering(self)); + let read = Lanes { + input: None, + cursor: Some(Box::new(Keep::new(cursor, &keep)) as BoxRead), + video: Some(Box::new(Keep::new(video, &keep)) as BoxRead), + }; + let write = Lanes { + input: Some(Box::new(input) as BoxWrite), + cursor: None, + video: None, + }; Ok( - Link::new(Box::new(Keep::new(recv, &keep)), Box::new(send), peer).with_video( - Box::new(Keep::new(video, &keep)), - Box::new(tokio::io::sink()), - ), + Link::new(Box::new(Keep::new(recv, &keep)), Box::new(send), peer) + .with_lanes(read, write), ) } @@ -412,23 +423,31 @@ impl Opened { self.conn.remote_address() } - /// Accepts a session: answers [`LinkReply::Accepted`], opens the video stream and returns - /// the two-stream link. + /// Accepts a session: answers [`LinkReply::Accepted`], opens the cursor and video streams, + /// accepts the client's input stream and returns the link. pub async fn accept_session(mut self) -> Result { write_msg(&mut self.send, &LinkReply::Accepted).await?; - let mut video = tokio::time::timeout(PREAMBLE_TIMEOUT, self.conn.conn.open_uni()) - .await - .map_err(|_| QuicError::Timeout)??; - let _ = video.set_priority(0); - video.write_all(&[VIDEO_STREAM_TAG]).await?; + let cursor = open_tagged(&self.conn.conn, CURSOR_STREAM_TAG, CURSOR_PRIORITY).await?; + let video = open_tagged(&self.conn.conn, VIDEO_STREAM_TAG, VIDEO_PRIORITY).await?; + let [input] = accept_tagged(&self.conn.conn, [INPUT_STREAM_TAG]).await?; let peer = format!("quic:{}", self.conn.remote_address()); let keep = Arc::new(Lingering(self.conn)); + let read = Lanes { + input: Some(Box::new(Keep::new(input, &keep)) as BoxRead), + cursor: None, + video: None, + }; + let write = Lanes { + input: None, + cursor: Some(Box::new(cursor) as BoxWrite), + video: Some(Box::new(video) as BoxWrite), + }; Ok(Link::new( Box::new(Keep::new(self.recv, &keep)), Box::new(self.send), peer, ) - .with_video(Box::new(tokio::io::empty()), Box::new(video))) + .with_lanes(read, write)) } /// Refuses the request and closes the connection once the answer is delivered (or after @@ -439,6 +458,46 @@ impl Opened { } } +/// Opens a unidirectional stream with the given send priority and writes its tag byte (which +/// also makes the stream visible to the peer). +async fn open_tagged(conn: &Connection, tag: u8, priority: i32) -> Result { + let mut stream = tokio::time::timeout(PREAMBLE_TIMEOUT, conn.open_uni()) + .await + .map_err(|_| QuicError::Timeout)??; + let _ = stream.set_priority(priority); + stream.write_all(&[tag]).await?; + Ok(stream) +} + +/// Accepts `N` unidirectional streams and returns them in the order of `tags`, whatever order +/// they arrive in. An unknown or repeated tag is an error. The whole exchange must finish within +/// [`PREAMBLE_TIMEOUT`]. +async fn accept_tagged( + conn: &Connection, + tags: [u8; N], +) -> Result<[RecvStream; N], QuicError> { + let accept = async { + let mut found: [Option; N] = std::array::from_fn(|_| None); + for _ in 0..N { + let mut stream = conn.accept_uni().await?; + let mut tag = [0u8; 1]; + stream.read_exact(&mut tag).await?; + let slot = tags + .iter() + .position(|&t| t == tag[0]) + .ok_or(QuicError::Unexpected("unknown stream tag"))?; + if found[slot].replace(stream).is_some() { + return Err(QuicError::Unexpected("duplicate stream tag")); + } + } + Ok::<_, QuicError>(found) + }; + let found = tokio::time::timeout(PREAMBLE_TIMEOUT, accept) + .await + .map_err(|_| QuicError::Timeout)??; + Ok(found.map(|s| s.expect("every tag was filled once"))) +} + /// Finishes `send`, waits briefly for the peer to read it, then closes the connection. pub(crate) async fn finish_and_close(send: &mut SendStream, conn: &QuicConn, reason: &str) { let _ = send.finish(); diff --git a/crates/ezd-proto/src/pair.rs b/crates/ezd-proto/src/pair.rs index bdf2faa..2818740 100644 --- a/crates/ezd-proto/src/pair.rs +++ b/crates/ezd-proto/src/pair.rs @@ -2,9 +2,10 @@ //! //! A Wi-Fi link is a QUIC connection with mutual TLS (self-signed certificates, pinned by //! fingerprint after pairing). The client opens the control stream (bidirectional) and sends a -//! [`LinkOpen`]; the host answers with a [`LinkReply`]. For a session the host then opens the -//! video stream (unidirectional), starting with [`VIDEO_STREAM_TAG`], and both sides run the -//! normal framed protocol. Pairing is a SPAKE2 exchange keyed by a 6-digit PIN, see +//! [`LinkOpen`]; the host answers with a [`LinkReply`]. For a session each side then opens +//! one unidirectional stream per channel it sends besides control (the host: cursor and video; +//! the client: input), each starting with its tag byte ([`CURSOR_STREAM_TAG`], +//! [`VIDEO_STREAM_TAG`], [`INPUT_STREAM_TAG`]), and both sides run the normal framed protocol. Pairing is a SPAKE2 exchange keyed by a 6-digit PIN, see //! `docs/protocol.md`. //! //! Preamble messages are postcard encoded with a little-endian `u16` length prefix @@ -14,8 +15,14 @@ use serde::{Deserialize, Serialize, de::DeserializeOwned}; /// ALPN protocol id of a Wi-Fi link. pub const ALPN: &[u8] = b"ezd/0"; +/// First byte of the client's input stream. +pub const INPUT_STREAM_TAG: u8 = b'I'; +/// First byte of the host's cursor stream. +pub const CURSOR_STREAM_TAG: u8 = b'C'; /// First byte of the host's video stream. pub const VIDEO_STREAM_TAG: u8 = b'V'; +/// First byte reserved for the audio stream (not used yet). +pub const AUDIO_STREAM_TAG: u8 = b'A'; /// Largest preamble message payload. pub const MAX_PREAMBLE_LEN: usize = 1024; /// Number of digits in a pairing PIN. diff --git a/docs/protocol.md b/docs/protocol.md index 9162a9c..9eb472a 100644 --- a/docs/protocol.md +++ b/docs/protocol.md @@ -119,16 +119,27 @@ present a long-lived self-signed certificate (ECDSA P-256) and identify each oth fingerprint, the SHA-256 of the certificate DER. There is no CA: the client pins the host's fingerprint, and the host only starts sessions for fingerprints it has paired with. -Streams: +Streams, one per channel: -* **Control** (bidirectional, opened by the client, higher stream priority): the preamble - below, then the framed protocol for every channel except video. -* **Video** (unidirectional, opened by the host after accepting a session, lower priority): - the byte `'V'`, then the framed `Video` channel messages. - -Video has its own stream so a lost packet of a large frame does not hold back input, cursor or -control messages queued behind it. Every other rule of this document (credit, coalescing, -reassembly) is unchanged; each stream is reassembled on its own. +| Stream | Kind | Opened by | Tag | Send priority | +| --- | --- | --- | --- | --- | +| Control | bidirectional | client | none (preamble first) | 4 (highest) | +| Input | unidirectional | client, after reading `Accepted` | `'I'` | 3 | +| Cursor | unidirectional | host, after writing `Accepted` | `'C'` | 2 | +| Audio (reserved) | unidirectional | host | `'A'` | 1 | +| Video | unidirectional | host, after writing `Accepted` | `'V'` | 0 (lowest) | + +Every unidirectional stream starts with its tag byte, then carries the framed messages of its +channel. Control carries the preamble, then the framed protocol for the control channel. The +receiver accepts the expected streams (the host one, the client two) within 10 s and dispatches +them by tag, not by arrival order; an unknown or repeated tag ends the session. The cursor stream +carries cursor shapes and the latest-wins cursor state, shapes first. There is no compatibility +with earlier layouts. + +Each channel has its own stream so a lost packet on one never holds back another: a lost packet +of a large video frame does not delay input, cursor or control messages. Every other rule of +this document (credit, coalescing, reassembly) is unchanged; each stream is reassembled on its +own, and the priorities above are QUIC send priorities between the streams. Before the framed protocol the client sends one preamble message (`ezd_proto::pair`). Preamble messages are postcard with a `u16` little-endian length prefix, at most 1024 bytes, and each @@ -138,6 +149,8 @@ step must complete within 10 s. client host | LinkOpen::Session --------------------->| client certificate must be paired |<--------------------- LinkReply::Accepted | or Refused(NotPaired | Busy) + |=== input stream: 'I', Pen/Touch ... ===>| opened after reading Accepted + |<== cursor stream: 'C', CursorState ... ==| opened after writing Accepted |<=== video stream: 'V', VideoFrame ... ===| | Hello ... (as in Handshake and session) | ``` @@ -147,9 +160,9 @@ Transport settings tuned for latency: keep-alive 1 s, idle timeout 5 s, initial The host accepts any client certificate in the handshake, so it treats every peer as untrusted until the preamble: it finishes each handshake in its own task within 10 s, keeps at most 8 -connections, allows the client one bidirectional stream and no unidirectional ones, and uses -256 KiB receive windows (it never receives video). The client allows the host only the video -stream and uses 8 MiB stream and 16 MiB connection receive windows, room for a large keyframe. +connections, allows the client one bidirectional stream and one unidirectional one (input), and uses +256 KiB receive windows (it never receives video). The client allows the host only the cursor +and video streams and uses 8 MiB stream and 16 MiB connection receive windows, room for a large keyframe. A client only opens a session on a connection whose host certificate it pinned. Hosts advertise themselves over mDNS as `_ezdisplay._udp.local.` with TXT records `fp` (short From 7c08519f4227744d643d10dde99a316a211c0a03 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:21:18 -0300 Subject: [PATCH 09/14] Revoke live Wi-Fi sessions on forget and harden the host listener Forgetting a device ends its streaming session at once, and a session re-checks the store every 2 s so a forget from another process also ends it. Unvalidated UDP sources get a stateless retry before taking a connection slot. Forget by fingerprint never matches names, and an exact fingerprint wins over a name in the CLI lookup. --- crates/ezd-host-service/src/service.rs | 13 ++ crates/ezd-host-service/src/store.rs | 106 +++++++++++--- crates/ezd-host-service/src/wifi.rs | 195 ++++++++++++++++++++++++- crates/ezd-link/src/quic.rs | 25 +++- crates/ezd-tray/src/controller/wifi.rs | 2 +- 5 files changed, 314 insertions(+), 27 deletions(-) diff --git a/crates/ezd-host-service/src/service.rs b/crates/ezd-host-service/src/service.rs index fa0ecb8..8033c75 100644 --- a/crates/ezd-host-service/src/service.rs +++ b/crates/ezd-host-service/src/service.rs @@ -310,11 +310,24 @@ impl HostService { /// Forgets the paired device matching `query` (name or fingerprint, see /// [`PairedStore::forget`](crate::store::PairedStore::forget)); `None` while Wi-Fi is off. + /// If the device is streaming, its session ends at once. #[cfg(feature = "wifi")] pub fn forget_paired(&self, query: &str) -> Option> { Some(self.inner.wifi.as_ref()?.forget(query)) } + /// Forgets the paired device with exactly this fingerprint (hex), never one that merely has + /// it as a name; `None` while Wi-Fi is off. If the device is streaming, its session ends at + /// once. Another process that forgets a device (`ezd-host paired forget`) cannot signal + /// the service: its session ends at the next periodic check of the store (about 2 s). + #[cfg(feature = "wifi")] + pub fn forget_paired_fingerprint( + &self, + fingerprint: &str, + ) -> Option> { + Some(self.inner.wifi.as_ref()?.forget_fingerprint(fingerprint)) + } + /// Current state; changes are pushed to the receiver. pub fn status(&self) -> watch::Receiver { self.inner.status.subscribe() diff --git a/crates/ezd-host-service/src/store.rs b/crates/ezd-host-service/src/store.rs index a58927f..e7a9062 100644 --- a/crates/ezd-host-service/src/store.rs +++ b/crates/ezd-host-service/src/store.rs @@ -167,7 +167,9 @@ impl PairedStore { self.write(&devices) } - /// Records that the device started a session now. Unknown devices are ignored. + /// Records that the device started a session now. The file is read again under the lock and + /// a record that is gone (forgotten meanwhile) is never added back: unknown devices are + /// ignored. pub fn touch(&self, fp: &Fingerprint) -> Result<(), StoreError> { let _g = self.guard(); let mut devices = self.read()?; @@ -179,27 +181,50 @@ impl PairedStore { self.write(&devices) } - /// Removes the device whose name (any case) equals `query`, or whose fingerprint is - /// `query` in hex or in the short dashed form, in full or as a prefix of at least 4 digits. - /// A name wins over a fingerprint prefix. + /// Removes the device with exactly this fingerprint. Names are never consulted, so a device + /// cannot take another one's place by announcing a fingerprint as its name. + pub fn forget_by_fingerprint(&self, fp: &Fingerprint) -> Result { + let _g = self.guard(); + let mut devices = self.read()?; + let hex = fingerprint_hex(fp); + let Some(i) = devices.iter().position(|d| d.fingerprint == hex) else { + return Err(ForgetError::NotFound); + }; + let gone = devices.remove(i); + self.write(&devices)?; + Ok(gone) + } + + /// Removes the device whose full fingerprint is `query` in hex, else the one whose name + /// (any case) equals `query`, else the one whose fingerprint starts with `query` (hex or the + /// short dashed form, at least 4 digits). For typed input (the CLI); callers that hold a + /// fingerprint use [`forget_by_fingerprint`](Self::forget_by_fingerprint). pub fn forget(&self, query: &str) -> Result { let _g = self.guard(); let mut devices = self.read()?; let query = query.trim(); - let mut hits: Vec = (0..devices.len()) - .filter(|&i| devices[i].name.eq_ignore_ascii_case(query)) - .collect(); + let prefix: String = query + .chars() + .filter(|c| *c != '-') + .collect::() + .to_ascii_lowercase(); + // A full fingerprint is exact and cannot be shadowed by a device name. + let mut hits: Vec = if parse_fingerprint(&prefix).is_some() { + (0..devices.len()) + .filter(|&i| devices[i].fingerprint == prefix) + .collect() + } else { + Vec::new() + }; if hits.is_empty() { - let prefix: String = query - .chars() - .filter(|c| *c != '-') - .collect::() - .to_ascii_lowercase(); - if prefix.len() >= 4 && prefix.chars().all(|c| c.is_ascii_hexdigit()) { - hits = (0..devices.len()) - .filter(|&i| devices[i].fingerprint.starts_with(&prefix)) - .collect(); - } + hits = (0..devices.len()) + .filter(|&i| devices[i].name.eq_ignore_ascii_case(query)) + .collect(); + } + if hits.is_empty() && prefix.len() >= 4 && prefix.chars().all(|c| c.is_ascii_hexdigit()) { + hits = (0..devices.len()) + .filter(|&i| devices[i].fingerprint.starts_with(&prefix)) + .collect(); } match hits.as_slice() { [] => Err(ForgetError::NotFound), @@ -306,6 +331,53 @@ pub(crate) mod tests { assert!(store.list().unwrap().is_empty()); } + #[test] + fn touch_after_an_external_removal_does_not_re_add_the_record() { + let dir = TempDir::new("store-touch-removed"); + let store = PairedStore::new(&dir.0); + store.add(&client("a", 1)).unwrap(); + store.add(&client("b", 2)).unwrap(); + // Another process forgets the device. + PairedStore::new(&dir.0).forget("a").unwrap(); + store.touch(&[1; 32]).unwrap(); + let list = store.list().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].name, "b"); + } + + #[test] + fn forget_by_fingerprint_ignores_names() { + let dir = TempDir::new("store-forget-fp"); + let store = PairedStore::new(&dir.0); + let victim = "cd".repeat(32); + // A device that names itself after another one's fingerprint. + store.add(&client(&victim, 0xab)).unwrap(); + store.add(&client("Pixel", 0xcd)).unwrap(); + assert!(matches!( + store.forget_by_fingerprint(&[0xee; 32]), + Err(ForgetError::NotFound) + )); + assert_eq!( + store.forget_by_fingerprint(&[0xcd; 32]).unwrap().name, + "Pixel" + ); + let left = store.list().unwrap(); + assert_eq!(left.len(), 1); + assert_eq!(left[0].fingerprint, "ab".repeat(32)); + } + + #[test] + fn forget_prefers_an_exact_fingerprint_over_a_name() { + let dir = TempDir::new("store-forget-exact"); + let store = PairedStore::new(&dir.0); + let victim = "cd".repeat(32); + store.add(&client(&victim, 0xab)).unwrap(); + store.add(&client("Pixel", 0xcd)).unwrap(); + assert_eq!(store.forget(&victim).unwrap().name, "Pixel"); + // Only the name-squatter is left, and it can still be forgotten by its name. + assert_eq!(store.forget(&victim).unwrap().fingerprint, "ab".repeat(32)); + } + #[test] fn forget_refuses_an_ambiguous_prefix() { let dir = TempDir::new("store-ambiguous"); diff --git a/crates/ezd-host-service/src/wifi.rs b/crates/ezd-host-service/src/wifi.rs index b6349da..66142fe 100644 --- a/crates/ezd-host-service/src/wifi.rs +++ b/crates/ezd-host-service/src/wifi.rs @@ -10,7 +10,7 @@ use crate::mdns::Advertiser; use crate::service::{Inner, finish_session, lock}; use crate::status::{HostEvent, PairingCloseReason, RefusedWhy, Transport, WifiInfo}; use crate::store::{ForgetError, PairedDevice, PairedStore, StoreError, default_config_dir}; -use ezd_link::identity::{Identity, fingerprint_hex, fingerprint_short}; +use ezd_link::identity::{Identity, fingerprint_hex, fingerprint_short, parse_fingerprint}; use ezd_link::pair::{CloseReason, PairUri, PairingWindow, WindowState, clean_name, host_pair}; use ezd_link::quic::{Congestion, QuicIncoming, QuicServer}; use ezd_proto::pair::{Fingerprint, Refusal}; @@ -25,6 +25,17 @@ const MAX_CONNECTIONS: usize = 8; /// Time a client has to complete the handshake and say what it wants. const OPEN_TIMEOUT: Duration = Duration::from_secs(10); +/// How often a running session checks that its device is still paired. This is what ends a +/// session when the record is removed by another process (`ezd-host paired forget`, an edit of +/// the file); a forget through the service ends it at once. +const RECHECK_EVERY: Duration = Duration::from_secs(2); + +/// The paired device that streams over Wi-Fi now, and how to end its session. +struct LiveSession { + fingerprint: String, + revoke: watch::Sender, +} + /// Everything the Wi-Fi tasks share. pub(crate) struct Wifi { server: QuicServer, @@ -40,6 +51,10 @@ pub(crate) struct Wifi { /// Address written into the pairing URI. advertised: SocketAddr, ttl: Duration, + /// The streaming session, if any (at most one: see `Inner::slot`). + live: Mutex>, + /// How often a session re-reads the store. + recheck: Duration, } impl Wifi { @@ -88,6 +103,8 @@ impl Wifi { bound, advertised: pick_lan_addr(bound, outbound_ip(bound)), ttl, + live: Mutex::new(None), + recheck: RECHECK_EVERY, })) } @@ -111,8 +128,28 @@ impl Wifi { self.store.list() } + /// Forgets a device by name or fingerprint (typed input) and ends its live session. pub(crate) fn forget(&self, query: &str) -> Result { - self.store.forget(query) + let gone = self.store.forget(query)?; + self.revoke(&gone.fingerprint); + Ok(gone) + } + + /// Forgets the device with exactly this fingerprint (hex) and ends its live session. + pub(crate) fn forget_fingerprint(&self, hex: &str) -> Result { + let fp = parse_fingerprint(hex).ok_or(ForgetError::NotFound)?; + let gone = self.store.forget_by_fingerprint(&fp)?; + self.revoke(&gone.fingerprint); + Ok(gone) + } + + /// Ends the live session if it belongs to this fingerprint (hex). + fn revoke(&self, hex: &str) { + if let Some(live) = &*lock(&self.live) + && live.fingerprint == hex + { + live.revoke.send_replace(true); + } } pub(crate) fn refresh_pairing(&self) { @@ -422,10 +459,68 @@ async fn session( return; } }; - finish_session(inner, &cfg, link, Transport::Wifi, source, &mut stop).await; + let (revoke_tx, mut revoke_rx) = watch::channel(false); + *lock(&wifi.live) = Some(LiveSession { + fingerprint: fingerprint_hex(&fp), + revoke: revoke_tx, + }); + // One end signal for everything that stops the session: the service stopping, a forget + // through the service, and the store no longer listing the device. The guard checks the + // store right away, which covers a forget since the check above. + let (end_tx, mut end_rx) = watch::channel(false); + { + let run = finish_session(inner, &cfg, link, Transport::Wifi, source, &mut end_rx); + tokio::pin!(run); + let guard = guard_session(wifi, &fp, &mut stop, &mut revoke_rx, &end_tx); + tokio::pin!(guard); + // The guard never completes; it is dropped when the session returns. + tokio::select! { + () = &mut run => {} + () = &mut guard => unreachable!("the guard never completes"), + } + } + *lock(&wifi.live) = None; drop(permit); } +/// Sends the end signal when the session must stop for a reason of its own: the service stops, +/// the device is forgotten through the service (`revoke`) or the store no longer has it. It +/// then waits forever, so the caller keeps the session running until it returns. A store that +/// cannot be read does not end the session. +async fn guard_session( + wifi: &Wifi, + fp: &Fingerprint, + stop: &mut watch::Receiver, + revoke: &mut watch::Receiver, + end: &watch::Sender, +) { + let mut tick = tokio::time::interval(wifi.recheck); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tokio::select! { + () = stopped(stop) => break, + r = async { revoke.wait_for(|v| *v).await.is_ok() } => { + if r { + tracing::info!("the device was forgotten, ending its Wi-Fi session"); + break; + } + // The sender is gone only after the session; nothing to do. + std::future::pending::<()>().await; + } + _ = tick.tick() => match wifi.store.is_paired(fp) { + Ok(true) => {} + Ok(false) => { + tracing::info!("the device is no longer paired, ending its Wi-Fi session"); + break; + } + Err(e) => tracing::debug!("cannot re-check the paired devices: {e}"), + }, + } + } + end.send_replace(true); + std::future::pending::<()>().await; +} + #[cfg(test)] mod tests { use super::*; @@ -743,6 +838,100 @@ mod tests { assert!(bye, "the client never got the Bye"); } + /// Pairs `id` into `dir`, streams, and returns what a test needs to watch the end. + async fn stream( + dir: &TempDir, + id: &Identity, + ) -> ( + HostService, + broadcast::Receiver, + ezd_link::MuxReceiver, + ezd_link::MuxSender, + ) { + seed(dir, id, "A"); + let svc = start(wifi_cfg(dir, false), hooks()); + let mut status = svc.status(); + let events = svc.events(); + let (addr, fp) = host_fp(&svc); + let (tx, rx) = handshake(session_link(addr, id, fp).await.unwrap()).await; + wait_status(&mut status, |s| matches!(s, HostStatus::Streaming(_))).await; + (svc, events, rx, tx) + } + + async fn client_sees_the_end(mut rx: ezd_link::MuxReceiver) { + let bye = timeout(WAIT, async { + loop { + match rx.recv().await { + Ok(Some(Message::Bye(_))) => return true, + Ok(Some(_)) => {} + _ => return false, + } + } + }) + .await + .unwrap(); + assert!(bye, "the client never got the Bye"); + } + + #[tokio::test] + async fn forgetting_the_streaming_device_ends_its_session() { + let dir = TempDir::new("wifi-forget-live"); + let id = Identity::generate().unwrap(); + let (svc, mut events, rx, _tx) = stream(&dir, &id).await; + let fp_hex = fingerprint_hex(&id.fingerprint()); + let started = Instant::now(); + svc.forget_paired_fingerprint(&fp_hex).unwrap().unwrap(); + timeout(Duration::from_secs(3), wait_session_end(&mut events)) + .await + .expect("the session outlived the forget"); + assert!(started.elapsed() < Duration::from_secs(3)); + client_sees_the_end(rx).await; + assert!(PairedStore::new(&dir.0).list().unwrap().is_empty()); + // The device is refused from now on. + let (addr, fp) = host_fp(&svc); + let err = session_link(addr, &id, fp).await.unwrap_err(); + assert!( + matches!(err, QuicError::Refused(Refusal::NotPaired)), + "{err:?}" + ); + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn removing_the_record_from_the_file_ends_the_session() { + let dir = TempDir::new("wifi-forget-file"); + let id = Identity::generate().unwrap(); + let (svc, mut events, rx, _tx) = stream(&dir, &id).await; + // Another process (the CLI) forgets the device. + PairedStore::new(&dir.0) + .forget_by_fingerprint(&id.fingerprint()) + .unwrap(); + timeout(Duration::from_secs(4), wait_session_end(&mut events)) + .await + .expect("the periodic re-check never ended the session"); + client_sees_the_end(rx).await; + timeout(WAIT, svc.stop()).await.unwrap(); + } + + #[tokio::test] + async fn an_unreadable_store_does_not_end_the_session() { + let dir = TempDir::new("wifi-store-unreadable"); + let id = Identity::generate().unwrap(); + let (svc, mut events, _rx, _tx) = stream(&dir, &id).await; + let path = dir.0.join(crate::store::PAIRED_FILE); + let good = std::fs::read(&path).unwrap(); + std::fs::write(&path, "garbage").unwrap(); + // Several re-checks pass while the file is corrupt. + assert!( + timeout(Duration::from_millis(4500), wait_session_end(&mut events)) + .await + .is_err(), + "a read error ended the session" + ); + std::fs::write(&path, good).unwrap(); + timeout(WAIT, svc.stop()).await.unwrap(); + } + #[test] fn lan_address_replaces_an_unspecified_bind() { let any: SocketAddr = "0.0.0.0:27183".parse().unwrap(); diff --git a/crates/ezd-link/src/quic.rs b/crates/ezd-link/src/quic.rs index d452326..793e3ae 100644 --- a/crates/ezd-link/src/quic.rs +++ b/crates/ezd-link/src/quic.rs @@ -541,12 +541,25 @@ impl QuicServer { /// Waits for the next incoming connection without completing its handshake, so a slow /// client never delays the next one: complete it with [`QuicIncoming::handshake`] in its /// own task. `None` once the endpoint is closed. + /// + /// An attempt whose source address is not validated yet (a spoofed source would never + /// answer) gets a stateless retry here and is never returned: callers only see attempts + /// from addresses that proved they can receive, so they cost no connection slot. pub async fn accept_incoming(&self) -> Option { - let incoming = self.endpoint.accept().await?; - Some(QuicIncoming { - incoming, - local_fp: self.local_fp, - }) + loop { + let incoming = self.endpoint.accept().await?; + if !incoming.remote_address_validated() { + // Costs the client one extra round trip; nothing is kept for the attempt. + if let Err(e) = incoming.retry() { + tracing::debug!("cannot send a retry: {e}"); + } + continue; + } + return Some(QuicIncoming { + incoming, + local_fp: self.local_fp, + }); + } } /// Waits for the next client handshake; `None` once the endpoint is closed. A failed @@ -582,7 +595,7 @@ pub struct QuicIncoming { } impl QuicIncoming { - /// Address of the peer (not yet validated). + /// Address of the peer (validated by a retry, see [`QuicServer::accept_incoming`]). pub fn remote_address(&self) -> SocketAddr { self.incoming.remote_address() } diff --git a/crates/ezd-tray/src/controller/wifi.rs b/crates/ezd-tray/src/controller/wifi.rs index 132c05a..dfa1659 100644 --- a/crates/ezd-tray/src/controller/wifi.rs +++ b/crates/ezd-tray/src/controller/wifi.rs @@ -131,7 +131,7 @@ impl Controller { match self .service .as_ref() - .and_then(|s| s.forget_paired(fingerprint)) + .and_then(|s| s.forget_paired_fingerprint(fingerprint)) { Some(Ok(d)) => tracing::info!("forgot the paired device {}", d.name), Some(Err(e)) => tracing::warn!("cannot forget the device: {e}"), From 40d93b02b451af16d2122205de86f148fa5a3e7c Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:24:00 -0300 Subject: [PATCH 10/14] Show the address and PIN when pairing from a link and keep links on the local network Links now show the host address and the PIN and are refused unless the address is on the local network (checked in Kotlin and in the native pairing). Typed public addresses get a warning. Names lose bidi and format characters. A failing discovered address is skipped for 60 s so a spoofed announcement cannot block the connection. --- .../com/librestatic/ezdisplay/MainActivity.kt | 7 +- .../librestatic/ezdisplay/SettingsActivity.kt | 6 ++ .../ezdisplay/settings/ConnectionSection.kt | 23 ++++- .../librestatic/ezdisplay/wifi/WifiModel.kt | 88 +++++++++++++++++-- .../app/src/main/res/values-de/strings.xml | 4 + .../app/src/main/res/values-es/strings.xml | 4 + .../app/src/main/res/values-fr/strings.xml | 4 + .../app/src/main/res/values-it/strings.xml | 4 + .../app/src/main/res/values-pt/strings.xml | 4 + android/app/src/main/res/values/strings.xml | 4 + .../settings/SettingsConnectionTest.kt | 25 ++++++ .../settings/SettingsScreenshotTest.kt | 7 ++ .../ezdisplay/wifi/WifiModelTest.kt | 50 +++++++++++ crates/ezd-android/src/wifi.rs | 73 +++++++++++++++ 14 files changed, 292 insertions(+), 11 deletions(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index e54cb7d..e46f8a1 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -33,6 +33,7 @@ import com.librestatic.ezdisplay.settings.SettingsStore import com.librestatic.ezdisplay.wifi.HostDiscovery import com.librestatic.ezdisplay.wifi.NativeWifiBackend import com.librestatic.ezdisplay.wifi.WifiChoice +import com.librestatic.ezdisplay.wifi.WifiFailures import com.librestatic.ezdisplay.wifi.chooseWifiTarget import org.json.JSONObject import java.nio.ByteBuffer @@ -124,6 +125,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private lateinit var discovery: HostDiscovery private val wifi by lazy { NativeWifiBackend(this) } private var activeWifi: WifiChoice? = null // set while the current session is over Wi-Fi + private val wifiFailures = WifiFailures() // discovered or stored addresses that failed lately: tried last private var tryWifiNext = false // the loopback connection just failed: try the paired host override fun onCreate(savedInstanceState: Bundle?) { @@ -261,7 +263,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private fun wifiTarget(): WifiChoice? { if (!wifiEnabled()) return null val last = InputPrefs.prefs(this).getString(LAST_WIFI_HOST, null) - return chooseWifiTarget(wifi.hosts(), discovery.hosts, last) + return chooseWifiTarget(wifi.hosts(), discovery.hosts, last, wifiFailures.active(SystemClock.elapsedRealtime())) } private fun applyInputConfig() { @@ -533,6 +535,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall ).trim() if (wifiChoice != null) { InputPrefs.prefs(this).edit().putString(LAST_WIFI_HOST, wifiChoice.host.fingerprint).apply() + wifiFailures.clear(wifiChoice.host.fingerprint, wifiChoice.addr) // Drawing over Wi-Fi works but feels different: say so, and keep it up a little longer. setStatus(connected + "\n" + getString(R.string.status_wifi_latency)) } else { @@ -576,6 +579,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private fun disconnected(message: String, failed: Boolean) { Log.i(TAG, "disconnected: $message") val wasWifi = activeWifi != null + // Any failure over Wi-Fi demotes that address, so the next attempt tries another candidate. + if (failed) activeWifi?.let { wifiFailures.record(it.host.fingerprint, it.addr, SystemClock.elapsedRealtime()) } stopSession() setStatus(message) // The loopback connection failed (no cable, no adb reverse): try the paired host over Wi-Fi right away. diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt index aa6c5f4..bdee112 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt @@ -12,6 +12,7 @@ import com.librestatic.ezdisplay.settings.SettingsTheme import com.librestatic.ezdisplay.settings.readAirActions import com.librestatic.ezdisplay.settings.wifiErrorText import com.librestatic.ezdisplay.wifi.HostDiscovery +import com.librestatic.ezdisplay.wifi.isLocalAddress import com.librestatic.ezdisplay.wifi.parsePairUri /** @@ -45,6 +46,11 @@ class SettingsActivity : ComponentActivity() { Toast.makeText(this, wifiErrorText("invalid_uri"), Toast.LENGTH_LONG).show() return } + if (!isLocalAddress(link.addr)) { + // A link can come from any web page or app: it may only point at the local network. + Toast.makeText(this, wifiErrorText("not_local_address"), Toast.LENGTH_LONG).show() + return + } store.startPairing(link) } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt index b6ba66e..5628edc 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt @@ -37,7 +37,10 @@ import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.role import androidx.compose.ui.semantics.semantics +import androidx.compose.ui.text.font.FontFamily import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.style.TextAlign +import androidx.compose.ui.unit.sp import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp @@ -48,6 +51,7 @@ import com.librestatic.ezdisplay.wifi.DiscoveredHost import com.librestatic.ezdisplay.wifi.PIN_LENGTH import com.librestatic.ezdisplay.wifi.WifiHost import com.librestatic.ezdisplay.wifi.fingerprintMatches +import com.librestatic.ezdisplay.wifi.isLocalAddress import com.librestatic.ezdisplay.wifi.isValidPin import com.librestatic.ezdisplay.wifi.parseManualAddress @@ -66,6 +70,7 @@ fun wifiErrorText(code: String?): Int = when (code) { "fingerprint_mismatch" -> R.string.pair_error_fingerprint "invalid_pin" -> R.string.pair_error_invalid_pin "invalid_uri" -> R.string.pair_error_invalid_uri + "not_local_address" -> R.string.pair_error_not_local "invalid_address" -> R.string.pair_error_invalid_address else -> R.string.pair_error_other } @@ -331,6 +336,9 @@ private fun ManualAddress(actions: SettingsActions) { label = { Text(stringResource(R.string.wifi_manual_label)) }, singleLine = true, isError = text.isNotBlank() && addr == null, + supportingText = if (addr != null && !isLocalAddress(addr)) { + { Text(stringResource(R.string.wifi_manual_public_warning), Modifier.testTag("manual_warning")) } + } else null, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Uri), ) Button( @@ -404,7 +412,20 @@ fun PairDialog(pairing: PairingState, actions: SettingsActions) { style = MaterialTheme.typography.bodyMedium, ) } - if (scanned) { + if (pairing.link != null) { + Text( + stringResource(R.string.pair_dialog_address, pairing.link.addr), + Modifier.testTag("pair_addr"), + style = MaterialTheme.typography.bodyLarge, + ) + Text( + pairing.link.pin, + Modifier.fillMaxWidth().testTag("pair_pin"), + style = MaterialTheme.typography.displayMedium.copy(fontFamily = FontFamily.Monospace, letterSpacing = 6.sp), + fontWeight = FontWeight.Bold, + textAlign = TextAlign.Center, + ) + Text(stringResource(R.string.pair_dialog_pin_check), style = MaterialTheme.typography.bodyMedium) Text(stringResource(R.string.pair_dialog_scanned), style = MaterialTheme.typography.bodyMedium) } else { OutlinedTextField( diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt index 3216177..b4b6c71 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/wifi/WifiModel.kt @@ -73,7 +73,7 @@ fun parsePairUri(uri: String?): PairLink? { "a" -> addr = value "fp" -> fp = value "pin" -> pin = value - "n" -> name = value.filter { !it.isISOControl() }.trim().take(64) + "n" -> name = cleanName(value) } } if (addr.isNullOrBlank() || parseManualAddress(addr) == null) return null @@ -81,6 +81,45 @@ fun parsePairUri(uri: String?): PairLink? { return PairLink(parseManualAddress(addr)!!, fp.lowercase(), pin, name) } +/** + * A display name safe to show: no control characters and no invisible or direction-changing format characters + * (Unicode category Cf, e.g. U+202A-U+202E, U+2066-U+2069, U+200E/F, U+061C), at most 64 characters. Twin of + * `clean_name` in `ezd-link`. + */ +fun cleanName(name: String): String { + val sb = StringBuilder() + var i = 0 + while (i < name.length) { + val cp = name.codePointAt(i) + i += Character.charCount(cp) + if (Character.isISOControl(cp) || Character.getType(cp) == Character.FORMAT.toInt() || cp in EXTRA_FORMAT) continue + sb.appendCodePoint(cp) + } + return sb.toString().trim().let { t -> t.substring(0, t.offsetByCodePoints(0, minOf(64, t.codePointCount(0, t.length)))) } +} + +/** Format characters of `clean_name` in `ezd-link` that older Unicode tables may not class as Cf. */ +private val EXTRA_FORMAT: Set = + (listOf(0x00AD, 0x061C, 0x180E, 0xFEFF) + (0x200B..0x200F) + (0x202A..0x202E) + (0x2060..0x206F) + (0xFFF9..0xFFFB)) + .toSet() + +/** + * True when [addr] (`ip`, `ip:port` or `[ipv6]:port`) is on the local network: IPv4 private (10/8, 172.16/12, + * 192.168/16), link-local (169.254/16) or CGNAT (100.64/10, VPN overlays); IPv6 unique-local (fc00::/7) or + * link-local (fe80::/10). Twin of `is_local_ip` in `ezd-android`. + */ +fun isLocalAddress(addr: String): Boolean { + val normalized = parseManualAddress(addr) ?: return false + if (normalized.startsWith("[")) { + val ip = normalized.substring(1, normalized.indexOf(']')) + val first = ip.substringBefore(':').let { if (it.isEmpty()) 0 else it.toIntOrNull(16) ?: return false } + return (first and 0xFE00) == 0xFC00 || (first and 0xFFC0) == 0xFE80 + } + val (a, b) = normalized.substringBefore(':').split('.').map { it.toInt() } + return a == 10 || (a == 172 && b in 16..31) || (a == 192 && b == 168) || (a == 169 && b == 254) || + (a == 100 && b in 64..127) +} + private val IPV4 = Regex("""(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})""") /** @@ -139,17 +178,48 @@ fun parsePairResultJson(json: String): PairResult = try { PairResult(null, "other", json) } -/** Where to connect over Wi-Fi: the paired [host] at [addr] (`ip:port`). */ +/** Where to connect over Wi-Fi: the paired host at [addr] (`ip:port`). */ data class WifiChoice(val host: WifiHost, val addr: String) /** - * The paired host to try over Wi-Fi and its address. Prefers a host that is on the network now (address from - * discovery), then the one used last ([lastFingerprint]) and its stored address, then any host with a stored - * address. Null when no paired host has an address. + * The paired host to try over Wi-Fi and its address. Prefers a host that is on the network now (every address + * discovery reports for it), then the one used last ([lastFingerprint]) and its stored address, then any host with + * a stored address. Candidates in [avoid] (host fingerprint to address, recently failed) come last, so a spoofed + * announcement cannot keep winning; when only avoided candidates remain, the first of them is still returned so a + * transient failure never blocks the only real host. Null when no paired host has an address. */ -fun chooseWifiTarget(hosts: List, discovered: List, lastFingerprint: String?): WifiChoice? { - fun live(h: WifiHost) = discovered.firstOrNull { fingerprintMatches(h.fingerprint, it.shortFp) }?.addr +fun chooseWifiTarget( + hosts: List, + discovered: List, + lastFingerprint: String?, + avoid: Set> = emptySet(), +): WifiChoice? { val ordered = hosts.sortedBy { if (it.fingerprint == lastFingerprint) 0 else 1 } - ordered.firstNotNullOfOrNull { h -> live(h)?.let { WifiChoice(h, it) } }?.let { return it } - return ordered.firstNotNullOfOrNull { h -> h.addr?.let { WifiChoice(h, it) } } + val live = ordered.flatMap { h -> + discovered.filter { fingerprintMatches(h.fingerprint, it.shortFp) }.map { WifiChoice(h, it.addr) } + } + val stored = ordered.mapNotNull { h -> h.addr?.let { WifiChoice(h, it) } } + val candidates = (live + stored).distinct() + return candidates.firstOrNull { (it.host.fingerprint to it.addr) !in avoid } ?: candidates.firstOrNull() +} + +/** Wi-Fi attempts that failed recently (host fingerprint, address), kept in memory for [ttlMs]. */ +class WifiFailures(private val ttlMs: Long = 60_000) { + private val failed = LinkedHashMap, Long>() + + fun record(fingerprint: String, addr: String, nowMs: Long) { + failed.remove(fingerprint to addr) + failed[fingerprint to addr] = nowMs + } + + /** A connection to this pair worked: forget its failures. */ + fun clear(fingerprint: String, addr: String) { + failed.remove(fingerprint to addr) + } + + /** The pairs to avoid at [nowMs]; expired ones are dropped. */ + fun active(nowMs: Long): Set> { + failed.values.removeAll { nowMs - it >= ttlMs } + return failed.keys.toSet() + } } diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml index 87131e7..5b8b51b 100644 --- a/android/app/src/main/res/values-de/strings.xml +++ b/android/app/src/main/res/values-de/strings.xml @@ -101,10 +101,13 @@ Koppeln Per Adresse hinzufügen IP-Adresse (Standardport 27183) + Diese Adresse liegt nicht in deinem lokalen Netzwerk. Koppele nur mit einem PC, dem du vertraust. Dieses Gerät Fingerabdruck des Zertifikats Mit %1$s koppeln Fingerabdruck: %1$s + Adresse: %1$s + Prüfe, ob dein PC diese PIN anzeigt. Prüfe, ob der Fingerabdruck mit dem auf deinem PC übereinstimmt, und koppele dann dieses Gerät. 6-stellige PIN Wird auf dem PC angezeigt, wenn du die Kopplung startest. @@ -120,6 +123,7 @@ Das ist nicht der Host aus dem Code: Der Fingerabdruck weicht ab. Die PIN hat 6 Ziffern. Das ist kein ezdisplay-Kopplungscode. + Dieser Kopplungslink verweist nicht auf ein Gerät in deinem lokalen Netzwerk und wurde abgelehnt. Das ist keine gültige Adresse. Kopplung fehlgeschlagen. diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 8facc3b..6eadd67 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -101,10 +101,13 @@ Vincular Agregar por dirección Dirección IP (puerto 27183 por defecto) + Esta dirección no está en tu red local. Vinculá solo con una PC de confianza. Este dispositivo Huella de su certificado Vincular con %1$s Huella: %1$s + Dirección: %1$s + Verificá que tu PC muestre este PIN. Verificá que la huella coincida con la de tu PC y luego vinculá este dispositivo. PIN de 6 dígitos Se muestra en la PC al iniciar la vinculación. @@ -120,6 +123,7 @@ Este no es el host del código: su huella es distinta. El PIN tiene 6 dígitos. Este no es un código de vinculación de ezdisplay. + Este enlace de vinculación no apunta a un dispositivo de tu red local, así que se rechazó. Esta no es una dirección válida. No se pudo vincular. diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml index a381b2b..cee8bd0 100644 --- a/android/app/src/main/res/values-fr/strings.xml +++ b/android/app/src/main/res/values-fr/strings.xml @@ -101,10 +101,13 @@ Associer Ajouter par adresse Adresse IP (port 27183 par défaut) + Cette adresse n\'est pas sur votre réseau local. Associez uniquement un PC de confiance. Cet appareil Empreinte de son certificat Associer avec %1$s Empreinte : %1$s + Adresse : %1$s + Vérifiez que votre PC affiche ce code PIN. Vérifiez que l\'empreinte correspond à celle de votre PC, puis associez cet appareil. PIN à 6 chiffres Affiché sur le PC au début de l\'association. @@ -120,6 +123,7 @@ Ce n\'est pas l\'hôte du code : son empreinte est différente. Le PIN comporte 6 chiffres. Ce n\'est pas un code d\'association ezdisplay. + Ce lien d\'association ne pointe pas vers un appareil de votre réseau local ; il a donc été refusé. Cette adresse n\'est pas valide. Échec de l\'association. diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml index 9ed35b0..6b86716 100644 --- a/android/app/src/main/res/values-it/strings.xml +++ b/android/app/src/main/res/values-it/strings.xml @@ -101,10 +101,13 @@ Associa Aggiungi tramite indirizzo Indirizzo IP (porta 27183 predefinita) + Questo indirizzo non è nella tua rete locale. Associa solo un PC di cui ti fidi. Questo dispositivo Impronta del certificato Associa con %1$s Impronta: %1$s + Indirizzo: %1$s + Controlla che il tuo PC mostri questo PIN. Controlla che l\'impronta coincida con quella sul PC, poi associa questo dispositivo. PIN a 6 cifre Mostrato sul PC quando avvii l\'associazione. @@ -120,6 +123,7 @@ Questo non è l\'host del codice: l\'impronta è diversa. Il PIN ha 6 cifre. Questo non è un codice di associazione di ezdisplay. + Questo link di associazione non punta a un dispositivo della tua rete locale ed è stato rifiutato. Questo indirizzo non è valido. Associazione non riuscita. diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml index b902012..9015d85 100644 --- a/android/app/src/main/res/values-pt/strings.xml +++ b/android/app/src/main/res/values-pt/strings.xml @@ -101,10 +101,13 @@ Parear Adicionar por endereço Endereço IP (porta 27183 por padrão) + Este endereço não está na sua rede local. Pareie apenas com um PC de confiança. Este dispositivo Impressão digital do certificado Parear com %1$s Impressão digital: %1$s + Endereço: %1$s + Confira se o seu PC mostra este PIN. Confira se a impressão digital é igual à do seu PC e depois pareie este dispositivo. PIN de 6 dígitos Exibido no PC ao iniciar o pareamento. @@ -120,6 +123,7 @@ Este não é o host do código: a impressão digital é diferente. O PIN tem 6 dígitos. Este não é um código de pareamento do ezdisplay. + Este link de pareamento não aponta para um dispositivo da sua rede local e foi recusado. Este endereço não é válido. Falha ao parear. diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index bdf9cbb..01fd1e4 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -101,10 +101,13 @@ Pair Add by address IP address (port 27183 by default) + This address is not on your local network. Only pair with a PC you trust. This device Fingerprint of its certificate Pair with %1$s Fingerprint: %1$s + Address: %1$s + Check that your PC shows this PIN. Check that the fingerprint matches the one on your PC, then pair this device. 6-digit PIN Shown on the PC when you start pairing. @@ -120,6 +123,7 @@ This is not the host from the code: its fingerprint differs. The PIN has 6 digits. This is not an ezdisplay pairing code. + This pairing link does not point to a device on your local network, so it was refused. This is not a valid address. Pairing failed. diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt index 608b0d1..938da3a 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt @@ -4,6 +4,8 @@ import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.assertIsEnabled import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertTextContains +import androidx.compose.ui.test.assertTextEquals +import androidx.compose.ui.test.performTextClearance import androidx.compose.ui.test.onNodeWithText import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performScrollTo @@ -12,6 +14,8 @@ import com.librestatic.ezdisplay.R import com.librestatic.ezdisplay.wifi.DiscoveredHost import com.librestatic.ezdisplay.wifi.PairLink import com.librestatic.ezdisplay.wifi.WifiHost +import com.librestatic.ezdisplay.wifi.isLocalAddress +import com.librestatic.ezdisplay.wifi.parsePairUri import com.librestatic.ezdisplay.wifi.shortFingerprint import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse @@ -158,6 +162,9 @@ class SettingsConnectionPhoneTest : SettingsUiTestBase() { rule.onNodeWithText(str(R.string.pair_dialog_title, "Studio PC")).assertExists() tag("pair_fp").assertTextContains(shortFingerprint(FP), substring = true) tag("pin_field").assertDoesNotExist() + tag("pair_addr").assertTextContains("192.168.1.9:27183", substring = true) + tag("pair_pin").assertTextEquals("424242") + rule.onNodeWithText(str(R.string.pair_dialog_pin_check)).assertExists() tag("pair_confirm").assertIsEnabled().performClick() rule.waitForIdle() val call = backend.calls.single() @@ -166,6 +173,24 @@ class SettingsConnectionPhoneTest : SettingsUiTestBase() { assertEquals(1, store.state.value.wifiHosts.size) } + @Test fun aManualPublicAddressShowsAWarning() { + openConnection() + tag("manual_field").performScrollTo().performTextInput("192.168.1.20") + rule.onNodeWithText(str(R.string.wifi_manual_public_warning)).assertDoesNotExist() + tag("manual_field").performTextClearance() + tag("manual_field").performTextInput("203.0.113.9") + rule.onNodeWithText(str(R.string.wifi_manual_public_warning)).assertExists() + // The address is still allowed: the user typed it. + tag("manual_pair").assertIsEnabled() + } + + @Test fun aPublicAddressLinkIsRefusedWithAnError() { + val link = parsePairUri("ezd://pair?a=203.0.113.9:27183&fp=$FP&pin=424242&n=Office%20PC")!! + assertFalse(isLocalAddress(link.addr)) + assertEquals(R.string.pair_error_not_local, wifiErrorText("not_local_address")) + assertTrue(str(R.string.pair_error_not_local).isNotEmpty()) + } + @Test fun anUnreachableHostShowsItsMessage() { val backend = FakeWifiBackend(error = "unreachable") openConnection(backend) diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt index 9d3cad5..888e0eb 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsScreenshotTest.kt @@ -120,6 +120,13 @@ class SettingsScreenshotTest { capture("phone_pair_dialog_dark") } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") + fun phone_pair_link_dialog_dark() { + val link = PairLink("192.168.1.9:27183", "3f2a91c077de0b14".padEnd(64, '0'), "424242", "Studio PC") + show(connectionState.copy(pairing = PairingState(link.name, link.shortFp, link.addr, link))) + capture("phone_pair_link_dialog_dark") + } + @Test @Config(sdk = [36], qualifiers = "w412dp-h915dp-night") fun phone_editor_dark() { show(tabletState) diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt index 9a03141..9480224 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/wifi/WifiModelTest.kt @@ -121,4 +121,54 @@ class WifiModelTest { // A discovered host nobody paired is never chosen. assertNull(chooseWifiTarget(listOf(noAddr), listOf(seenB), null)) } + + @Test fun spoofedAnnouncementsAreRotatedOut() { + val real = WifiHost("Real", fpA, shortFingerprint(fpA), "10.0.0.2:27183") + val spoof = DiscoveredHost("evil", "Real", shortFingerprint(fpA), "192.168.1.66:27183") + val genuine = DiscoveredHost("real", "Real", shortFingerprint(fpA), "192.168.1.9:27183") + val seen = listOf(spoof, genuine) + // The first announcement wins until it fails. + assertEquals(WifiChoice(real, spoof.addr), chooseWifiTarget(listOf(real), seen, fpA)) + // Then the other discovered address, then the stored one. + val avoid = mutableSetOf(fpA to spoof.addr) + assertEquals(WifiChoice(real, genuine.addr), chooseWifiTarget(listOf(real), seen, fpA, avoid)) + avoid += fpA to genuine.addr + assertEquals(WifiChoice(real, "10.0.0.2:27183"), chooseWifiTarget(listOf(real), seen, fpA, avoid)) + // Only avoided candidates left: still try one rather than never connecting. + avoid += fpA to "10.0.0.2:27183" + assertEquals(WifiChoice(real, spoof.addr), chooseWifiTarget(listOf(real), seen, fpA, avoid)) + // Another host is preferred to an avoided address of the first. + val other = WifiHost("Other", fpB, shortFingerprint(fpB), "10.0.0.3:27183") + assertEquals(WifiChoice(other, "10.0.0.3:27183"), chooseWifiTarget(listOf(real, other), emptyList(), fpA, setOf(fpA to "10.0.0.2:27183"))) + } + + @Test fun failuresAreRememberedForAWhile() { + val f = WifiFailures(ttlMs = 60_000) + f.record(fpA, "1.2.3.4:1", 1_000) + assertEquals(setOf(fpA to "1.2.3.4:1"), f.active(30_000)) + assertTrue(f.active(61_000).isEmpty()) + f.record(fpA, "1.2.3.4:1", 100_000) + f.clear(fpA, "1.2.3.4:1") + assertTrue(f.active(100_001).isEmpty()) + } + + @Test fun localAddressesAreOnTheLocalNetwork() { + listOf( + "10.0.0.1", "10.255.0.1:1234", "172.16.0.1", "172.31.255.255", "192.168.1.5:27183", "169.254.1.1", + "100.64.0.1", "100.127.1.1", "[fc00::1]:27183", "fd12:3456::1", "fe80::1", "[febf::1]:5", + ).forEach { assertTrue(it, isLocalAddress(it)) } + listOf( + "8.8.8.8", "203.0.113.9:27183", "172.15.0.1", "172.32.0.1", "192.169.0.1", "100.63.0.1", "100.128.0.1", + "127.0.0.1", "2001:db8::1", "[2001:db8::1]:27183", "fec0::1", "::1", "::ffff:192.168.1.5", "garbage", "", + ).forEach { assertFalse(it, isLocalAddress(it)) } + } + + @Test fun namesLoseControlAndFormatCharacters() { + val spoof = "Of\u202Efice\u202C\u2066 PC\u2069\u200E\u200F\u061C\u0007\n\uFEFF" + assertEquals("Office PC", cleanName(spoof)) + assertEquals("Studio PC", cleanName(" Studio PC ")) + assertEquals(64, cleanName("x".repeat(100)).length) + val link = parsePairUri("ezd://pair?a=10.0.0.2:27183&fp=$fpA&pin=123456&n=Of%E2%80%AEfice%E2%80%AC%E2%81%A6%20PC") + assertEquals("Office PC", link!!.name) + } } diff --git a/crates/ezd-android/src/wifi.rs b/crates/ezd-android/src/wifi.rs index 1be052a..2622723 100644 --- a/crates/ezd-android/src/wifi.rs +++ b/crates/ezd-android/src/wifi.rs @@ -49,6 +49,22 @@ pub fn parse_addr(s: &str) -> Option { .or_else(|| s.parse::().ok().map(|ip| (ip, DEFAULT_PORT).into())) } +/// True for an address on the local network: IPv4 private (RFC 1918), link-local and CGNAT +/// (100.64/10, used by VPN overlays), IPv6 unique-local (fc00::/7) and link-local (fe80::/10). +/// Pairing links must point here; the Kotlin twin is `isLocalAddress` in `WifiModel.kt`. +pub fn is_local_ip(ip: IpAddr) -> bool { + match ip { + IpAddr::V4(v4) => { + let [a, b, ..] = v4.octets(); + v4.is_private() || v4.is_link_local() || (a == 100 && (64..=127).contains(&b)) + } + IpAddr::V6(v6) => { + let first = v6.segments()[0]; + (first & 0xfe00) == 0xfc00 || (first & 0xffc0) == 0xfe80 + } + } +} + /// The stable error code Kotlin maps to a localized message. fn error_code(e: &WifiError) -> &'static str { match e { @@ -83,6 +99,13 @@ pub fn pair_json(addr: &str, pin_or_uri: &str, device_name: &str, state_dir: &Pa let Some(uri) = PairUri::parse(input) else { return failure("invalid_uri", "not a pairing link"); }; + // A link can come from any web page: it may only point at the local network. + if !is_local_ip(uri.addr.ip()) { + return failure( + "not_local_address", + "the pairing link is not on the local network", + ); + } PairRequest { addr: uri.addr, pin: uri.pin, @@ -181,6 +204,56 @@ mod tests { serde_json::from_str(s).unwrap() } + #[test] + fn local_addresses_are_private_link_local_cgnat_and_ula() { + for ok in [ + "10.0.0.1", + "10.255.255.255", + "172.16.0.1", + "172.31.255.255", + "192.168.1.5", + "169.254.3.4", + "100.64.0.1", + "100.127.255.255", + "fc00::1", + "fd12:3456::1", + "fe80::1", + "febf::1", + ] { + assert!(is_local_ip(ok.parse().unwrap()), "{ok}"); + } + for bad in [ + "8.8.8.8", + "172.15.0.1", + "172.32.0.1", + "192.169.0.1", + "100.63.255.255", + "100.128.0.1", + "169.253.0.1", + "127.0.0.1", + "2001:db8::1", + "fec0::1", + "::1", + "::ffff:192.168.1.5", + ] { + assert!(!is_local_ip(bad.parse().unwrap()), "{bad}"); + } + } + + #[test] + fn a_link_to_a_public_address_is_refused_before_connecting() { + let dir = TempDir::new("public-link"); + let uri = PairUri { + addr: "203.0.113.9:27183".parse().unwrap(), + fingerprint: [7; 32], + pin: "123456".into(), + name: "Office PC".into(), + }; + let out = json(&pair_json("", &uri.to_uri(), "Tablet", &dir.0)); + assert_eq!(out["ok"], false); + assert_eq!(out["error"], "not_local_address"); + } + #[test] fn addresses_default_to_the_host_port() { assert_eq!( From a9001b076fc9c0bff40596b9f3603555675f420b Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:37:11 -0300 Subject: [PATCH 11/14] Ship firewall profiles for the Wi-Fi port on Linux Add a ufw application profile and a firewalld service for UDP 27183, installed by the Arch package and the .deb (nothing is opened automatically), document the commands, and report the firewall state in diag and in a localized hint when Wi-Fi starts. --- README.md | 32 ++++- crates/ezd-host/i18n/de/ezd-host.ftl | 1 + crates/ezd-host/i18n/en/ezd-host.ftl | 1 + crates/ezd-host/i18n/es/ezd-host.ftl | 1 + crates/ezd-host/i18n/fr/ezd-host.ftl | 1 + crates/ezd-host/i18n/it/ezd-host.ftl | 1 + crates/ezd-host/i18n/pt/ezd-host.ftl | 1 + crates/ezd-host/src/diag.rs | 13 ++ crates/ezd-host/src/firewall.rs | 166 ++++++++++++++++++++++++ crates/ezd-host/src/main.rs | 2 + crates/ezd-host/src/wifi.rs | 4 + crates/ezd-tray/Cargo.toml | 2 + packaging/linux/README.md | 6 + packaging/linux/arch/PKGBUILD | 3 + packaging/linux/arch/ezdisplay.install | 8 +- packaging/linux/firewalld/ezdisplay.xml | 6 + packaging/linux/ufw/ezdisplay | 4 + 17 files changed, 250 insertions(+), 2 deletions(-) create mode 100644 crates/ezd-host/src/firewall.rs create mode 100644 packaging/linux/firewalld/ezdisplay.xml create mode 100644 packaging/linux/ufw/ezdisplay diff --git a/README.md b/README.md index db8911e..ae172d7 100644 --- a/README.md +++ b/README.md @@ -164,7 +164,37 @@ The fake client pairs the same way, then streams: cargo run --release -p ezd-fake-client -- --wifi 127.0.0.1:27183 --pin 123456 --frames 300 ``` -On Windows, allow inbound UDP port 27183 in Windows Defender Firewall for private networks. +### Firewall (Linux) + +A host firewall such as ufw or firewalld usually blocks inbound UDP 27183, so tablets cannot +connect. `ezd-host diag` reports the state (`firewall` key) and `ezd-host run --wifi` prints a hint +when one is active. The Arch package and the `.deb` install a ufw application profile and a firewalld +service named `ezdisplay` but never open the port: that is your decision. Allow it only for your LAN. + +ufw (replace the network with yours): + +```sh +sudo ufw allow from 192.168.0.0/24 to any app ezdisplay +# without the profile (AppImage, source builds): +sudo ufw allow from /24 to any port 27183 proto udp +``` + +firewalld: + +```sh +sudo firewall-cmd --permanent --add-service=ezdisplay && sudo firewall-cmd --reload +``` + +The service is added to the default zone; to limit it to your home network, add `--zone=home` (or +`trusted`) to both commands, and make sure your Wi-Fi interface is in that zone. Without the +packaged service, use `--add-port=27183/udp` instead. The AppImage cannot install the profiles; copy +them from `packaging/linux/` (see its README) or use the port forms above. + +### Firewall (Windows) + +The Windows installer already adds an inbound UDP 27183 rule for private networks. For a portable +build, allow that port in Windows Defender Firewall for private networks. + Wi-Fi also works without pairing through ADB wireless debugging: `ezd-host run --adb --link network`. diff --git a/crates/ezd-host/i18n/de/ezd-host.ftl b/crates/ezd-host/i18n/de/ezd-host.ftl index db19747..68edf7e 100644 --- a/crates/ezd-host/i18n/de/ezd-host.ftl +++ b/crates/ezd-host/i18n/de/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = Die Kopplung ist geschlossen: zu viele falsche PINs. pair-closed-expired = Die Kopplung ist geschlossen: Die Zeit ist abgelaufen. Starte mit `--pair` neu, um erneut zu koppeln. wifi-listening = WLAN: lauscht auf { $addr } (UDP). Fingerabdruck des Hosts: { $fingerprint } wifi-firewall-hint = Wenn sich Tablets nicht verbinden können, erlaube eingehenden UDP-Port { $port } in der Windows-Firewall (private Netzwerke). +wifi-firewall-hint-linux = Eine Firewall ist aktiv. Wenn sich Tablets nicht verbinden können, erlaube eingehenden UDP-Port { $port } (ufw oder firewalld; siehe den Wi-Fi-Abschnitt der README). err-paired-not-found = kein gekoppeltes Tablet passt zu `{ $query }` err-paired-ambiguous = { $count } gekoppelte Tablets passen zu `{ $query }`; gib mehr Stellen des Fingerabdrucks an err-no-config-dir = Konfigurationsordner nicht gefunden diff --git a/crates/ezd-host/i18n/en/ezd-host.ftl b/crates/ezd-host/i18n/en/ezd-host.ftl index 8b7a570..617b924 100644 --- a/crates/ezd-host/i18n/en/ezd-host.ftl +++ b/crates/ezd-host/i18n/en/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = Pairing is closed: too many wrong PINs. pair-closed-expired = Pairing is closed: time ran out. Restart with `--pair` to pair again. wifi-listening = Wi-Fi: listening on { $addr } (UDP). Host fingerprint: { $fingerprint } wifi-firewall-hint = If tablets cannot connect, allow inbound UDP port { $port } in Windows Firewall (private networks). +wifi-firewall-hint-linux = A firewall is active. If tablets cannot connect, allow inbound UDP port { $port } (ufw or firewalld; see the Wi-Fi section of the README). err-paired-not-found = no paired tablet matches `{ $query }` err-paired-ambiguous = { $count } paired tablets match `{ $query }`; use more of the fingerprint err-no-config-dir = cannot find the config folder diff --git a/crates/ezd-host/i18n/es/ezd-host.ftl b/crates/ezd-host/i18n/es/ezd-host.ftl index a0d5e4b..2a3ba03 100644 --- a/crates/ezd-host/i18n/es/ezd-host.ftl +++ b/crates/ezd-host/i18n/es/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = La vinculación está cerrada: demasiados PIN incorrectos pair-closed-expired = La vinculación está cerrada: se acabó el tiempo. Reiniciá con `--pair` para vincular de nuevo. wifi-listening = Wi-Fi: escuchando en { $addr } (UDP). Huella del host: { $fingerprint } wifi-firewall-hint = Si las tabletas no pueden conectarse, permití el puerto UDP { $port } de entrada en el Firewall de Windows (redes privadas). +wifi-firewall-hint-linux = Hay un firewall activo. Si las tabletas no pueden conectarse, permití el puerto UDP { $port } de entrada (ufw o firewalld; mirá la sección Wi-Fi del README). err-paired-not-found = ninguna tableta vinculada coincide con `{ $query }` err-paired-ambiguous = { $count } tabletas vinculadas coinciden con `{ $query }`; usá más dígitos de la huella err-no-config-dir = no se encontró la carpeta de configuración diff --git a/crates/ezd-host/i18n/fr/ezd-host.ftl b/crates/ezd-host/i18n/fr/ezd-host.ftl index 0ac8471..ad9e7a9 100644 --- a/crates/ezd-host/i18n/fr/ezd-host.ftl +++ b/crates/ezd-host/i18n/fr/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = L'appairage est fermé : trop de PIN incorrects. pair-closed-expired = L'appairage est fermé : le temps est écoulé. Relancez avec `--pair` pour appairer à nouveau. wifi-listening = Wi-Fi : écoute sur { $addr } (UDP). Empreinte de l'hôte : { $fingerprint } wifi-firewall-hint = Si les tablettes ne parviennent pas à se connecter, autorisez le port UDP { $port } en entrée dans le Pare-feu Windows (réseaux privés). +wifi-firewall-hint-linux = Un pare-feu est actif. Si les tablettes ne parviennent pas à se connecter, autorisez le port UDP { $port } en entrée (ufw ou firewalld ; voir la section Wi-Fi du README). err-paired-not-found = aucune tablette appairée ne correspond à `{ $query }` err-paired-ambiguous = { $count } tablettes appairées correspondent à `{ $query }` ; utilisez plus de chiffres de l'empreinte err-no-config-dir = dossier de configuration introuvable diff --git a/crates/ezd-host/i18n/it/ezd-host.ftl b/crates/ezd-host/i18n/it/ezd-host.ftl index b734a5c..a384caf 100644 --- a/crates/ezd-host/i18n/it/ezd-host.ftl +++ b/crates/ezd-host/i18n/it/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = L'associazione è chiusa: troppi PIN errati. pair-closed-expired = L'associazione è chiusa: tempo scaduto. Riavvia con `--pair` per associare di nuovo. wifi-listening = Wi-Fi: in ascolto su { $addr } (UDP). Impronta dell'host: { $fingerprint } wifi-firewall-hint = Se i tablet non riescono a connettersi, consenti la porta UDP { $port } in ingresso nel Firewall di Windows (reti private). +wifi-firewall-hint-linux = Un firewall è attivo. Se i tablet non riescono a connettersi, consenti la porta UDP { $port } in ingresso (ufw o firewalld; vedi la sezione Wi-Fi del README). err-paired-not-found = nessun tablet associato corrisponde a `{ $query }` err-paired-ambiguous = { $count } tablet associati corrispondono a `{ $query }`; usa più cifre dell'impronta err-no-config-dir = impossibile trovare la cartella di configurazione diff --git a/crates/ezd-host/i18n/pt/ezd-host.ftl b/crates/ezd-host/i18n/pt/ezd-host.ftl index 191e450..fe4b4e0 100644 --- a/crates/ezd-host/i18n/pt/ezd-host.ftl +++ b/crates/ezd-host/i18n/pt/ezd-host.ftl @@ -74,6 +74,7 @@ pair-closed-attempts = O pareamento está fechado: PINs incorretos demais. pair-closed-expired = O pareamento está fechado: o tempo acabou. Reinicie com `--pair` para parear de novo. wifi-listening = Wi-Fi: escutando em { $addr } (UDP). Impressão digital do host: { $fingerprint } wifi-firewall-hint = Se os tablets não conseguirem se conectar, permita a porta UDP { $port } de entrada no Firewall do Windows (redes privadas). +wifi-firewall-hint-linux = Há um firewall ativo. Se os tablets não conseguirem se conectar, permita a porta UDP { $port } de entrada (ufw ou firewalld; veja a seção Wi-Fi do README). err-paired-not-found = nenhum tablet pareado corresponde a `{ $query }` err-paired-ambiguous = { $count } tablets pareados correspondem a `{ $query }`; use mais dígitos da impressão digital err-no-config-dir = não foi possível encontrar a pasta de configuração diff --git a/crates/ezd-host/src/diag.rs b/crates/ezd-host/src/diag.rs index 82c1eb6..59e5d83 100644 --- a/crates/ezd-host/src/diag.rs +++ b/crates/ezd-host/src/diag.rs @@ -25,6 +25,7 @@ pub fn sections() -> Vec> { { v.push(Box::new(LinuxSession)); v.push(Box::new(LinuxGpus)); + v.push(Box::new(LinuxFirewall)); } v.push(Box::new(Platform)); v.push(Box::new(Encoders)); @@ -137,6 +138,18 @@ impl Section for LinuxGpus { } } +#[cfg(target_os = "linux")] +struct LinuxFirewall; +#[cfg(target_os = "linux")] +impl Section for LinuxFirewall { + fn name(&self) -> &'static str { + "firewall" + } + fn collect(&self) -> Value { + crate::firewall::diag_value(crate::firewall::detect()) + } +} + /// Backend-specific section; the platform crates fill it in. struct Platform; impl Section for Platform { diff --git a/crates/ezd-host/src/firewall.rs b/crates/ezd-host/src/firewall.rs new file mode 100644 index 0000000..80c6af5 --- /dev/null +++ b/crates/ezd-host/src/firewall.rs @@ -0,0 +1,166 @@ +//! Linux firewall detection, used by `diag` and by the Wi-Fi start-up hint. Needs no root: it reads +//! `/etc/ufw/ufw.conf` and asks systemd whether `firewalld` is running. Nothing here changes the +//! firewall; opening the port is the user's decision (README, Wi-Fi section). + +use serde_json::{Value, json}; +use std::path::Path; +use std::process::Command; + +const UFW_CONF: &str = "/etc/ufw/ufw.conf"; +const FIREWALLD_UNITS: [&str; 3] = [ + "/usr/lib/systemd/system/firewalld.service", + "/lib/systemd/system/firewalld.service", + "/etc/systemd/system/firewalld.service", +]; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Ufw { + Enabled, + Disabled, + Absent, + /// The config exists but cannot be read. + Unknown, +} + +impl Ufw { + fn as_str(self) -> &'static str { + match self { + Ufw::Enabled => "enabled", + Ufw::Disabled => "disabled", + Ufw::Absent => "absent", + Ufw::Unknown => "unknown", + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Firewalld { + Active, + Inactive, + Absent, +} + +impl Firewalld { + fn as_str(self) -> &'static str { + match self { + Firewalld::Active => "active", + Firewalld::Inactive => "inactive", + Firewalld::Absent => "absent", + } + } +} + +#[derive(Clone, Copy, Debug)] +pub struct State { + pub ufw: Ufw, + pub firewalld: Firewalld, +} + +impl State { + /// Whether a firewall that may block inbound UDP is running. + pub fn any_active(self) -> bool { + self.ufw == Ufw::Enabled || self.firewalld == Firewalld::Active + } +} + +/// Whether `ufw.conf` text has `ENABLED=yes` (case-insensitive, optional quotes, `#` comments). +pub fn parse_ufw_enabled(conf: &str) -> bool { + conf.lines() + .map(str::trim) + .filter(|l| !l.starts_with('#')) + .filter_map(|l| l.split_once('=')) + .rfind(|(k, _)| k.trim().eq_ignore_ascii_case("ENABLED")) + .is_some_and(|(_, v)| { + v.split('#') + .next() + .unwrap_or("") + .trim() + .trim_matches(['"', '\'']) + .eq_ignore_ascii_case("yes") + }) +} + +fn ufw_state() -> Ufw { + match std::fs::read_to_string(UFW_CONF) { + Ok(s) if parse_ufw_enabled(&s) => Ufw::Enabled, + Ok(_) => Ufw::Disabled, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ufw::Absent, + Err(_) => Ufw::Unknown, + } +} + +fn firewalld_state() -> Firewalld { + let active = Command::new("systemctl") + .args(["is-active", "--quiet", "firewalld"]) + .status() + .is_ok_and(|s| s.success()); + if active { + Firewalld::Active + } else if FIREWALLD_UNITS.iter().any(|p| Path::new(p).exists()) { + Firewalld::Inactive + } else { + Firewalld::Absent + } +} + +pub fn detect() -> State { + State { + ufw: ufw_state(), + firewalld: firewalld_state(), + } +} + +/// The `firewall` object of the diag report. +pub fn diag_value(state: State) -> Value { + let hint = state.any_active().then_some( + "A firewall is active; if tablets cannot connect over Wi-Fi, allow inbound UDP port 27183 \ + (ufw application profile or firewalld service `ezdisplay`; see the README).", + ); + json!({ + "ufw": state.ufw.as_str(), + "firewalld": state.firewalld.as_str(), + "hint": hint, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ufw_conf_enabled() { + assert!(parse_ufw_enabled("# comment\nENABLED=yes\nLOGLEVEL=low\n")); + assert!(parse_ufw_enabled(" enabled = \"YES\" # on\n")); + assert!(parse_ufw_enabled("ENABLED=yes\r\n")); + } + + #[test] + fn ufw_conf_disabled() { + assert!(!parse_ufw_enabled("ENABLED=no\n")); + assert!(!parse_ufw_enabled("#ENABLED=yes\n")); + assert!(!parse_ufw_enabled("OTHER_ENABLED=yes\n")); + assert!(!parse_ufw_enabled("")); + assert!(!parse_ufw_enabled("ENABLED=yesno\n")); + } + + #[test] + fn ufw_conf_last_assignment_wins() { + assert!(!parse_ufw_enabled("ENABLED=yes\nENABLED=no\n")); + assert!(parse_ufw_enabled("ENABLED=no\nENABLED=yes\n")); + } + + #[test] + fn diag_hint_only_when_active() { + let off = State { + ufw: Ufw::Disabled, + firewalld: Firewalld::Inactive, + }; + assert!(diag_value(off)["hint"].is_null()); + let on = State { + ufw: Ufw::Absent, + firewalld: Firewalld::Active, + }; + assert!(diag_value(on)["hint"].is_string()); + assert_eq!(diag_value(on)["firewalld"], "active"); + } +} diff --git a/crates/ezd-host/src/main.rs b/crates/ezd-host/src/main.rs index 1759378..6a66d67 100644 --- a/crates/ezd-host/src/main.rs +++ b/crates/ezd-host/src/main.rs @@ -6,6 +6,8 @@ //! * `ezd-host diag`: print a JSON report about the machine (GPUs, encoders, adb). mod diag; +#[cfg(target_os = "linux")] +mod firewall; mod i18n; mod run; #[cfg(windows)] diff --git a/crates/ezd-host/src/wifi.rs b/crates/ezd-host/src/wifi.rs index 10941c8..ba0c7af 100644 --- a/crates/ezd-host/src/wifi.rs +++ b/crates/ezd-host/src/wifi.rs @@ -222,6 +222,10 @@ pub fn print_listening(addr: std::net::SocketAddr, fingerprint: &str) { ); #[cfg(windows)] eprintln!("{}", fl!("wifi-firewall-hint", port = addr.port())); + #[cfg(target_os = "linux")] + if crate::firewall::detect().any_active() { + eprintln!("{}", fl!("wifi-firewall-hint-linux", port = addr.port())); + } } #[cfg(test)] diff --git a/crates/ezd-tray/Cargo.toml b/crates/ezd-tray/Cargo.toml index 0e56898..0777f41 100644 --- a/crates/ezd-tray/Cargo.toml +++ b/crates/ezd-tray/Cargo.toml @@ -87,6 +87,8 @@ assets = [ ["target/release/ezdisplay", "usr/bin/", "755"], ["target/release/ezd-host", "usr/bin/", "755"], ["../../packaging/linux/70-ezdisplay-uinput.rules", "usr/lib/udev/rules.d/", "644"], + ["../../packaging/linux/ufw/ezdisplay", "etc/ufw/applications.d/", "644"], + ["../../packaging/linux/firewalld/ezdisplay.xml", "usr/lib/firewalld/services/", "644"], ["../../packaging/linux/com.librestatic.ezdisplay.desktop", "usr/share/applications/", "644"], ["../../packaging/linux/com.librestatic.ezdisplay.svg", "usr/share/icons/hicolor/scalable/apps/", "644"], ["../../LICENSE-MIT", "usr/share/doc/ezdisplay/", "644"], diff --git a/packaging/linux/README.md b/packaging/linux/README.md index 3d7037c..0de78c5 100644 --- a/packaging/linux/README.md +++ b/packaging/linux/README.md @@ -9,6 +9,7 @@ Only KDE Plasma 6 on Wayland is supported today. CI builds all of this in | Path | What it is | | --- | --- | | `70-ezdisplay-uinput.rules` | udev rule that lets the logged-in user create uinput devices (touch and pen input). | +| `ufw/ezdisplay`, `firewalld/ezdisplay.xml` | ufw application profile and firewalld service for the Wi-Fi port (UDP 27183). The Arch package and the `.deb` install them to `/etc/ufw/applications.d/` and `/usr/lib/firewalld/services/`; nothing is enabled or opened automatically. | | `com.librestatic.ezdisplay.desktop`, `.svg` | Desktop entry and icon. | | `arch/PKGBUILD`, `arch/ezdisplay.install` | Arch package built from this checkout (no source download). | | `debian/postinst` | Maintainer script of the `.deb`: reloads udev and re-triggers `/dev/uinput`. The package metadata is `[package.metadata.deb]` in `crates/ezd-tray/Cargo.toml`. | @@ -87,3 +88,8 @@ packaging/linux/appimage/smoke.sh out/ezdisplay-*.AppImage Inside the image, `AppRun` starts the tray app; `AppRun host ...` runs `ezd-host`. The bundled adb is at `usr/bin/adb/adb` and the licence texts at `usr/bin/licenses/`, where the app looks for them. + +An AppImage cannot install system files. To use the firewall profiles with it, copy them from +this directory (`ufw/ezdisplay` to `/etc/ufw/applications.d/`, `firewalld/ezdisplay.xml` to +`/etc/firewalld/services/`), or open the port directly; see the Wi-Fi section of the +[README](../../README.md#firewall-linux). diff --git a/packaging/linux/arch/PKGBUILD b/packaging/linux/arch/PKGBUILD index bc6110d..b6c0ed4 100644 --- a/packaging/linux/arch/PKGBUILD +++ b/packaging/linux/arch/PKGBUILD @@ -38,6 +38,9 @@ package() { install -Dm755 "$t/ezd-host" "$pkgdir/usr/bin/ezd-host" install -Dm644 packaging/linux/70-ezdisplay-uinput.rules \ "$pkgdir/usr/lib/udev/rules.d/70-ezdisplay-uinput.rules" + install -Dm644 packaging/linux/ufw/ezdisplay "$pkgdir/etc/ufw/applications.d/ezdisplay" + install -Dm644 packaging/linux/firewalld/ezdisplay.xml \ + "$pkgdir/usr/lib/firewalld/services/ezdisplay.xml" install -Dm644 packaging/linux/com.librestatic.ezdisplay.desktop \ "$pkgdir/usr/share/applications/com.librestatic.ezdisplay.desktop" install -Dm644 packaging/linux/com.librestatic.ezdisplay.svg \ diff --git a/packaging/linux/arch/ezdisplay.install b/packaging/linux/arch/ezdisplay.install index 49d0f18..ccd2f15 100644 --- a/packaging/linux/arch/ezdisplay.install +++ b/packaging/linux/arch/ezdisplay.install @@ -1,8 +1,14 @@ post_install() { # pacman's own hook reloads the udev rules; apply the uaccess tag to an existing /dev/uinput. udevadm trigger --name-match=uinput 2>/dev/null || true + cat <<'MSG' +==> ezdisplay: nothing was opened in your firewall. To let tablets reach the host over Wi-Fi + (UDP port 27183), allow it yourself, scoped to your LAN: + ufw: sudo ufw allow from 192.168.0.0/24 to any app ezdisplay + firewalld: sudo firewall-cmd --permanent --add-service=ezdisplay && sudo firewall-cmd --reload +MSG } post_upgrade() { - post_install + udevadm trigger --name-match=uinput 2>/dev/null || true } diff --git a/packaging/linux/firewalld/ezdisplay.xml b/packaging/linux/firewalld/ezdisplay.xml new file mode 100644 index 0000000..614987f --- /dev/null +++ b/packaging/linux/firewalld/ezdisplay.xml @@ -0,0 +1,6 @@ + + + ezdisplay + Use an Android tablet as an extended monitor over Wi-Fi. Tablets connect to the host on UDP port 27183 (QUIC). + + diff --git a/packaging/linux/ufw/ezdisplay b/packaging/linux/ufw/ezdisplay new file mode 100644 index 0000000..abb0913 --- /dev/null +++ b/packaging/linux/ufw/ezdisplay @@ -0,0 +1,4 @@ +[ezdisplay] +title=ezdisplay +description=Use an Android tablet as an extended monitor over Wi-Fi +ports=27183/udp From ac28a5a089b6a787fab626b93d2b4d7a13322194 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 16:50:42 -0300 Subject: [PATCH 12/14] Forget a Wi-Fi host that no longer knows this device When the pinned host refuses with NotPaired, the client removes it from its paired hosts instead of retrying. Android gets a stable failure code next to the English detail, shows the localized reason and keeps it above the USB retry messages until a host is paired again. --- .../com/librestatic/ezdisplay/MainActivity.kt | 22 +++++++- .../librestatic/ezdisplay/SettingsActivity.kt | 2 + .../ezdisplay/settings/ConnectionSection.kt | 1 + .../app/src/main/res/values-de/strings.xml | 1 + .../app/src/main/res/values-es/strings.xml | 1 + .../app/src/main/res/values-fr/strings.xml | 1 + .../app/src/main/res/values-it/strings.xml | 1 + .../app/src/main/res/values-pt/strings.xml | 1 + android/app/src/main/res/values/strings.xml | 1 + .../settings/SettingsConnectionTest.kt | 2 +- crates/ezd-android/src/session.rs | 33 +++++++++-- crates/ezd-android/src/status.rs | 31 ++++++++++ crates/ezd-android/src/wifi.rs | 2 +- crates/ezd-client-core/src/wifi.rs | 56 +++++++++++++++++++ 14 files changed, 145 insertions(+), 10 deletions(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt index e46f8a1..5137c38 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/MainActivity.kt @@ -30,6 +30,7 @@ import android.widget.ImageButton import android.widget.ImageView import android.widget.TextView import com.librestatic.ezdisplay.settings.SettingsStore +import com.librestatic.ezdisplay.settings.wifiErrorText import com.librestatic.ezdisplay.wifi.HostDiscovery import com.librestatic.ezdisplay.wifi.NativeWifiBackend import com.librestatic.ezdisplay.wifi.WifiChoice @@ -127,6 +128,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall private var activeWifi: WifiChoice? = null // set while the current session is over Wi-Fi private val wifiFailures = WifiFailures() // discovered or stored addresses that failed lately: tried last private var tryWifiNext = false // the loopback connection just failed: try the paired host + private var pairingLost: String? = null // the host forgot this device: kept above later retry messages override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) @@ -524,6 +526,7 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall "streaming" -> { if (!wasStreaming) { wasStreaming = true + pairingLost = null updateChrome() backoffMs = BACKOFF_MIN_MS streamW = j.optInt("width") @@ -549,7 +552,19 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } } "ended" -> disconnected(getString(R.string.status_ended, j.optString("detail"), addr), false) - "failed" -> disconnected(getString(R.string.status_error, j.optString("detail")), true) + "failed" -> { + // A Wi-Fi failure carries a stable code; the detail is English text for the log. + val code = if (j.isNull("code")) null else j.optString("code") + val message = if (code != null && activeWifi != null) { + getString(wifiErrorText(code)) + } else { + getString(R.string.status_error, j.optString("detail")) + } + // On not_paired the native layer already forgot the host, so wifiTarget() finds no + // address for it and the retries go back to USB only. + if (code == "not_paired" && activeWifi != null) pairingLost = message + disconnected(message, true) + } } val flags = if (j.isNull("client_flags")) 0 else j.optInt("client_flags") telemetryOn = (flags and 1) != 0 @@ -582,6 +597,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall // Any failure over Wi-Fi demotes that address, so the next attempt tries another candidate. if (failed) activeWifi?.let { wifiFailures.record(it.host.fingerprint, it.addr, SystemClock.elapsedRealtime()) } stopSession() + // Keep telling the user why Wi-Fi stopped until a host is paired again. + if (wifiTarget() != null) pairingLost = null setStatus(message) // The loopback connection failed (no cable, no adb reverse): try the paired host over Wi-Fi right away. if (failed && !wasWifi && wifiTarget() != null) { @@ -594,7 +611,8 @@ class MainActivity : Activity(), SurfaceHolder.Callback, Choreographer.FrameCall } private fun setStatus(text: String) { - statusView.text = text + val notice = pairingLost?.takeIf { it != text } + statusView.text = if (notice != null) "$notice\n$text" else text statusView.visibility = View.VISIBLE statusHideAt = 0 } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt index bdee112..0183184 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/SettingsActivity.kt @@ -58,6 +58,8 @@ class SettingsActivity : ComponentActivity() { super.onResume() // The user may have changed Samsung's Air actions while away. store.setAirActions(readAirActions(this)) + // The host may have refused this device meanwhile, which forgets it. + store.reloadHosts() discovery.start() } diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt index 5628edc..07fd0a8 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/ConnectionSection.kt @@ -65,6 +65,7 @@ fun wifiErrorText(code: String?): Int = when (code) { "pairing_closed" -> R.string.pair_error_closed "too_many_attempts" -> R.string.pair_error_attempts "busy" -> R.string.pair_error_busy + "not_paired" -> R.string.pair_error_not_paired "unreachable" -> R.string.pair_error_unreachable "timeout" -> R.string.pair_error_timeout "fingerprint_mismatch" -> R.string.pair_error_fingerprint diff --git a/android/app/src/main/res/values-de/strings.xml b/android/app/src/main/res/values-de/strings.xml index 5b8b51b..5f35510 100644 --- a/android/app/src/main/res/values-de/strings.xml +++ b/android/app/src/main/res/values-de/strings.xml @@ -118,6 +118,7 @@ Der PC akzeptiert keine Kopplung. Starte zuerst die Kopplung auf dem PC. Zu viele Fehlversuche. Starte die Kopplung auf dem PC neu. Der Host ist beschäftigt. Versuche es gleich noch einmal. + Der PC hat dieses Gerät vergessen. Koppele es erneut. Der Host ist nicht erreichbar. Prüfe die Adresse und ob beide Geräte im selben Netzwerk sind. Der Host hat nicht rechtzeitig geantwortet. Das ist nicht der Host aus dem Code: Der Fingerabdruck weicht ab. diff --git a/android/app/src/main/res/values-es/strings.xml b/android/app/src/main/res/values-es/strings.xml index 6eadd67..38e716a 100644 --- a/android/app/src/main/res/values-es/strings.xml +++ b/android/app/src/main/res/values-es/strings.xml @@ -118,6 +118,7 @@ La PC no acepta vinculaciones. Iniciá primero la vinculación en la PC. Demasiados intentos fallidos. Iniciá la vinculación de nuevo en la PC. El host está ocupado. Probá de nuevo en un momento. + La PC olvidó este dispositivo. Vinculalo de nuevo. No se puede llegar al host. Revisá la dirección y que ambos dispositivos estén en la misma red. El host no respondió a tiempo. Este no es el host del código: su huella es distinta. diff --git a/android/app/src/main/res/values-fr/strings.xml b/android/app/src/main/res/values-fr/strings.xml index cee8bd0..a9dba10 100644 --- a/android/app/src/main/res/values-fr/strings.xml +++ b/android/app/src/main/res/values-fr/strings.xml @@ -118,6 +118,7 @@ Le PC n\'accepte pas d\'association. Lancez d\'abord l\'association sur le PC. Trop de tentatives échouées. Relancez l\'association sur le PC. L\'hôte est occupé. Réessayez dans un instant. + Ce PC a oublié cet appareil. Associez-le à nouveau. Impossible de joindre l\'hôte. Vérifiez l\'adresse et que les deux appareils sont sur le même réseau. L\'hôte n\'a pas répondu à temps. Ce n\'est pas l\'hôte du code : son empreinte est différente. diff --git a/android/app/src/main/res/values-it/strings.xml b/android/app/src/main/res/values-it/strings.xml index 6b86716..7861039 100644 --- a/android/app/src/main/res/values-it/strings.xml +++ b/android/app/src/main/res/values-it/strings.xml @@ -118,6 +118,7 @@ Il PC non accetta associazioni. Avvia prima l\'associazione sul PC. Troppi tentativi errati. Avvia di nuovo l\'associazione sul PC. L\'host è occupato. Riprova tra un momento. + Il PC ha dimenticato questo dispositivo. Associalo di nuovo. Impossibile raggiungere l\'host. Controlla l\'indirizzo e che i due dispositivi siano sulla stessa rete. L\'host non ha risposto in tempo. Questo non è l\'host del codice: l\'impronta è diversa. diff --git a/android/app/src/main/res/values-pt/strings.xml b/android/app/src/main/res/values-pt/strings.xml index 9015d85..bee9298 100644 --- a/android/app/src/main/res/values-pt/strings.xml +++ b/android/app/src/main/res/values-pt/strings.xml @@ -118,6 +118,7 @@ O PC não está aceitando pareamentos. Inicie primeiro o pareamento no PC. Muitas tentativas incorretas. Inicie o pareamento de novo no PC. O host está ocupado. Tente novamente em instantes. + O PC esqueceu este dispositivo. Pareie-o novamente. Não foi possível alcançar o host. Confira o endereço e se os dois dispositivos estão na mesma rede. O host não respondeu a tempo. Este não é o host do código: a impressão digital é diferente. diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index 01fd1e4..ba3d2af 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -118,6 +118,7 @@ The PC is not accepting pairings. Start pairing on the PC first. Too many wrong attempts. Start pairing again on the PC. The host is busy. Try again in a moment. + This PC forgot this device. Pair it again. Cannot reach the host. Check the address and that both devices are on the same network. The host did not answer in time. This is not the host from the code: its fingerprint differs. diff --git a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt index 938da3a..c77b140 100644 --- a/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt +++ b/android/app/src/test/kotlin/com/librestatic/ezdisplay/settings/SettingsConnectionTest.kt @@ -205,7 +205,7 @@ class SettingsConnectionPhoneTest : SettingsUiTestBase() { @Test fun everyErrorCodeHasItsOwnMessage() { val codes = listOf( - "wrong_pin", "pairing_closed", "too_many_attempts", "busy", "unreachable", "timeout", + "wrong_pin", "pairing_closed", "too_many_attempts", "busy", "not_paired", "unreachable", "timeout", "fingerprint_mismatch", "invalid_pin", "invalid_uri", "invalid_address", ) assertEquals(codes.size, codes.map { wifiErrorText(it) }.toSet().size) diff --git a/crates/ezd-android/src/session.rs b/crates/ezd-android/src/session.rs index a52cc35..59cc6fc 100644 --- a/crates/ezd-android/src/session.rs +++ b/crates/ezd-android/src/session.rs @@ -3,6 +3,7 @@ use crate::caps::ParsedCaps; use crate::decoder::{Cmd, DecoderCtl, SendWindow}; use crate::status::{Phase, Shared}; +use crate::wifi::error_code; use ezd_client_core::wifi::connect_paired; use ezd_client_core::{ ClientConfig, ClientEnd, ClientHandle, ClientHandler, CursorSnapshot, Flow, HandlerResult, @@ -196,15 +197,28 @@ impl Session { } } -/// Opens the link to `target`; the error is the text for the status. -async fn connect(target: &Target) -> Result { +/// Why a connection failed: English text for the status detail and logs, plus a stable code +/// Kotlin localizes (Wi-Fi only). +struct ConnectError { + detail: String, + code: Option<&'static str>, +} + +impl From for ConnectError { + fn from(detail: String) -> Self { + ConnectError { detail, code: None } + } +} + +/// Opens the link to `target`. +async fn connect(target: &Target) -> Result { match target { Target::Tcp { host, port } => { let addr = format!("{host}:{port}"); match tokio::time::timeout(CONNECT_TIMEOUT, Link::connect_tcp(addr.as_str())).await { Ok(Ok(l)) => Ok(l), - Ok(Err(e)) => Err(format!("connect {addr}: {e}")), - Err(_) => Err(format!("connect {addr}: timed out")), + Ok(Err(e)) => Err(format!("connect {addr}: {e}").into()), + Err(_) => Err(format!("connect {addr}: timed out").into()), } } Target::Wifi { @@ -213,7 +227,10 @@ async fn connect(target: &Target) -> Result { state_dir, } => connect_paired(state_dir, *addr, *fingerprint, WIFI_CONNECT_TIMEOUT) .await - .map_err(|e| format!("connect {addr}: {e}")), + .map_err(|e| ConnectError { + detail: format!("connect {addr}: {e}"), + code: Some(error_code(&e)), + }), } } @@ -239,7 +256,11 @@ fn run( let link = match connect(&target).await { Ok(l) => l, Err(e) => { - shared.set_phase(Phase::Failed, e); + tracing::warn!("{}", e.detail); + match e.code { + Some(code) => shared.set_failed_code(e.detail, code), + None => shared.set_phase(Phase::Failed, e.detail), + } return; } }; diff --git a/crates/ezd-android/src/status.rs b/crates/ezd-android/src/status.rs index e09c28a..0416acb 100644 --- a/crates/ezd-android/src/status.rs +++ b/crates/ezd-android/src/status.rs @@ -27,6 +27,8 @@ pub enum Phase { struct State { phase: Phase, detail: String, + /// Stable error code of a failure Kotlin localizes; `None` for the free-form detail. + code: Option<&'static str>, stream: Option, decoder: Option, /// Size of the decoder's output buffers, which can exceed the stream (coded vs cropped size). @@ -41,6 +43,7 @@ impl Default for Shared { Shared(Mutex::new(State { phase: Phase::Idle, detail: String::new(), + code: None, stream: None, decoder: None, buffer: None, @@ -63,6 +66,17 @@ impl Shared { } s.phase = phase; s.detail = detail; + s.code = None; + }); + } + + /// Fails with `detail` (English, for logs and fallbacks) and a stable `code` for Kotlin. + pub fn set_failed_code(&self, detail: impl Into, code: &'static str) { + let detail = detail.into(); + self.with(|s| { + s.phase = Phase::Failed; + s.detail = detail; + s.code = Some(code); }); } @@ -117,6 +131,7 @@ impl Shared { let v = serde_json::json!({ "phase": s.phase, "detail": s.detail, + "code": s.code, "width": s.stream.as_ref().map_or(0, |c| c.width), "height": s.stream.as_ref().map_or(0, |c| c.height), "refresh_mhz": s.stream.as_ref().map_or(0, |c| c.refresh_mhz), @@ -211,6 +226,22 @@ mod tests { assert_eq!(j["inputs_sent"], 9); } + #[test] + fn a_failure_code_is_reported_and_cleared_by_the_next_phase() { + let sh = Shared::default(); + let snap = ClientSnapshot::default(); + sh.set_failed_code("connect: refused", "not_paired"); + let j: serde_json::Value = serde_json::from_str(&sh.to_json(&snap)).unwrap(); + assert_eq!( + (j["phase"].as_str(), j["code"].as_str()), + (Some("failed"), Some("not_paired")) + ); + assert_eq!(j["detail"], "connect: refused"); + sh.set_phase(Phase::Connecting, "x"); + let j: serde_json::Value = serde_json::from_str(&sh.to_json(&snap)).unwrap(); + assert!(j["code"].is_null()); + } + #[test] fn failure_is_sticky() { let sh = Shared::default(); diff --git a/crates/ezd-android/src/wifi.rs b/crates/ezd-android/src/wifi.rs index 2622723..c3ca74a 100644 --- a/crates/ezd-android/src/wifi.rs +++ b/crates/ezd-android/src/wifi.rs @@ -66,7 +66,7 @@ pub fn is_local_ip(ip: IpAddr) -> bool { } /// The stable error code Kotlin maps to a localized message. -fn error_code(e: &WifiError) -> &'static str { +pub fn error_code(e: &WifiError) -> &'static str { match e { WifiError::Quic(QuicError::Refused(r)) => match r { Refusal::WrongPin => "wrong_pin", diff --git a/crates/ezd-client-core/src/wifi.rs b/crates/ezd-client-core/src/wifi.rs index 298fa37..31f0dac 100644 --- a/crates/ezd-client-core/src/wifi.rs +++ b/crates/ezd-client-core/src/wifi.rs @@ -195,6 +195,15 @@ pub async fn connect_paired( tracing::debug!("connect failed ({e}), retrying"); tokio::time::sleep(RETRY_DELAY).await; } + Err(QuicError::Refused(Refusal::NotPaired)) => { + // The connection is pinned to the host's certificate, so only the real host can + // say this: it forgot this device, and the pairing is gone for good. + tracing::info!("the host no longer knows this device, forgetting it"); + if let Err(e) = forget_host(dir, &fingerprint_hex(&host)) { + tracing::warn!("cannot forget the host: {e}"); + } + return Err(QuicError::Refused(Refusal::NotPaired).into()); + } Err(e) => return Err(e.into()), } }; @@ -305,6 +314,53 @@ mod tests { assert!(matches!(load_hosts(&dir.0), Err(WifiError::Corrupt { .. }))); } + #[tokio::test] + async fn a_host_that_forgot_us_is_forgotten_without_retrying() { + let dir = TempDir::new("not-paired"); + let host_id = Identity::generate().unwrap(); + let server = ezd_link::quic::QuicServer::bind( + "127.0.0.1:0".parse().unwrap(), + &host_id, + Congestion::default(), + ) + .unwrap(); + let addr = server.local_addr().unwrap(); + let fp = host_id.fingerprint(); + add_host( + &dir.0, + StoredHost { + name: "desk".into(), + fingerprint: fingerprint_hex(&fp), + addr: Some(addr.to_string()), + }, + ) + .unwrap(); + add_host(&dir.0, host("laptop", 2, None)).unwrap(); + let served = tokio::spawn(async move { + let mut refused = 0; + while let Some(Ok(conn)) = server.accept().await { + if let Ok(opened) = conn.accept_open().await { + opened.refuse(Refusal::NotPaired).await; + refused += 1; + } + if refused > 0 { + break; + } + } + refused + }); + let err = connect_paired(&dir.0, addr, fp, Duration::from_secs(5)) + .await + .map(|_| ()) + .unwrap_err(); + assert!( + matches!(err, WifiError::Quic(QuicError::Refused(Refusal::NotPaired))), + "{err:?}" + ); + assert_eq!(served.await.unwrap(), 1, "the refusal must not be retried"); + assert_eq!(load_hosts(&dir.0).unwrap(), vec![host("laptop", 2, None)]); + } + #[test] fn remembering_an_address_updates_only_that_host() { let dir = TempDir::new("remember"); From c42172f8b2a0874684f7ce394349d4956a416e61 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 22:18:30 -0300 Subject: [PATCH 13/14] Check the Android native library through cargo-ndk so ring finds the NDK compiler --- .github/workflows/android.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/android.yml b/.github/workflows/android.yml index 56e40b9..03150fd 100644 --- a/.github/workflows/android.yml +++ b/.github/workflows/android.yml @@ -44,7 +44,8 @@ jobs: - name: Native library (aarch64) run: | export ANDROID_NDK_HOME="$ANDROID_HOME/ndk/$NDK_VERSION" - cargo check --target aarch64-linux-android -p ezd-android -p ezd-client-core + # cargo-ndk points ring's C build at the NDK clang, which a plain cargo check lacks. + cargo ndk -t arm64-v8a check -p ezd-android -p ezd-client-core cargo ndk -t arm64-v8a clippy -p ezd-android -p ezd-client-core -- -D warnings - name: Host tests of the portable parts run: cargo test -p ezd-android -p ezd-client-core From f6b8c558e7ed8ecc82a6869ab5c78d8f0469d774 Mon Sep 17 00:00:00 2001 From: FacuM Date: Sun, 25 Oct 2026 22:19:29 -0300 Subject: [PATCH 14/14] Lower the wide pen shortcut rows so the standard profiles fit without scrolling --- .../kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt index 58ba35a..1d78e66 100644 --- a/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt +++ b/android/app/src/main/kotlin/com/librestatic/ezdisplay/settings/SettingsScreen.kt @@ -409,7 +409,7 @@ private fun WideLayout( WideHeading(stringResource(R.string.settings_profile)) PenContent( state, actions, if (sideBySide) 3 else 2, setPaneEditor, - selectedEditor = editor, shortcutMinHeight = 80.dp, + selectedEditor = editor, shortcutMinHeight = 64.dp, ) Spacer(Modifier.height(20.dp)) if (sideBySide) {