From e1c152a65727659b8dca3367a375633765c5779d Mon Sep 17 00:00:00 2001 From: tongtongstudio Date: Thu, 12 Nov 2026 12:33:39 +0800 Subject: [PATCH] Implement authenticated public relay and Rust device daemons --- .gitignore | 1 + Cargo.lock | 1374 ++++++++++++++++++++++++++++ Cargo.toml | 24 + README.md | 175 +++- agent/Cargo.toml | 12 + agent/README.md | 14 + agent/src/main.rs | 126 +++ client/Cargo.toml | 12 + client/README.md | 17 + client/src/main.rs | 166 ++++ crates/ads-core/Cargo.toml | 16 + crates/ads-core/src/lib.rs | 256 ++++++ deploy/Caddyfile | 6 + deploy/README.md | 9 + deploy/ads-agent.service | 18 + deploy/ads-server.service | 18 + deploy/com.example.ads-agent.plist | 17 + docs/local-bridge.md | 77 ++ docs/protocol.md | 36 + docs/verification.md | 21 + scripts/build.ps1 | 20 + scripts/build.sh | 9 + server/README.md | 12 + server/go.mod | 5 + server/go.sum | 2 + server/main.go | 394 ++++++++ server/main_test.go | 152 +++ tests/e2e.py | 196 ++++ tests/real_device.py | 98 ++ 29 files changed, 3244 insertions(+), 39 deletions(-) create mode 100644 Cargo.lock create mode 100644 Cargo.toml create mode 100644 agent/Cargo.toml create mode 100644 agent/README.md create mode 100644 agent/src/main.rs create mode 100644 client/Cargo.toml create mode 100644 client/README.md create mode 100644 client/src/main.rs create mode 100644 crates/ads-core/Cargo.toml create mode 100644 crates/ads-core/src/lib.rs create mode 100644 deploy/Caddyfile create mode 100644 deploy/README.md create mode 100644 deploy/ads-agent.service create mode 100644 deploy/ads-server.service create mode 100644 deploy/com.example.ads-agent.plist create mode 100644 docs/local-bridge.md create mode 100644 docs/protocol.md create mode 100644 docs/verification.md create mode 100644 scripts/build.ps1 create mode 100644 scripts/build.sh create mode 100644 server/README.md create mode 100644 server/go.mod create mode 100644 server/go.sum create mode 100644 server/main.go create mode 100644 server/main_test.go create mode 100644 tests/e2e.py create mode 100644 tests/real_device.py diff --git a/.gitignore b/.gitignore index a32bcd7..4887957 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ __pycache__/ /work/ .env *.log +*.env diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..703279a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,1374 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ads-agent" +version = "0.1.0" +dependencies = [ + "ads-core", + "anyhow", + "clap", + "tokio", + "tracing", +] + +[[package]] +name = "ads-client" +version = "0.1.0" +dependencies = [ + "ads-core", + "anyhow", + "clap", + "tokio", + "tracing", +] + +[[package]] +name = "ads-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "futures-util", + "serde", + "serde_json", + "tokio", + "tokio-tungstenite", + "tracing-subscriber", + "url", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.104" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ff2a8126fff0f8c839080d619675a585e61720bb12d2baceae45769fd66f155" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "clap" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa8876b300ab35ba921adea3dfd70157a46249b33f95c9084ae5709785478946" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0797fb7aeb1406c84efac526901f7ec3ead2124f946b494e72879d4b54704d" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9c751b79415d4e559e3d1fcf128e09e720eb673a06d26cf6f392d37d75b66e0" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "clap_lex" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[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" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-macro", + "futures-sink", + "futures-task", + "pin-project-lite", + "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 = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[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 = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "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 = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +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 = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ae9ccbea3a7b0b09443036490c8f34a8b1b760fd345e5c0dae0aac718faea79" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "parking_lot", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d25a406cddcc431a75d3d9afc6a7c0f7428d4891dd973e4d54c56b46127bf857" +dependencies = [ + "futures-util", + "log", + "rustls", + "rustls-pki-types", + "tokio", + "tokio-rustls", + "tungstenite", + "webpki-roots 0.26.11", +] + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand", + "rustls", + "rustls-pki-types", + "sha1", + "thiserror", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.12", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13084392c5e4bc371903e2935a5eaeed24905a7511356b883835e18a78f6879" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..e6e4f18 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,24 @@ +[workspace] +members = ["crates/ads-core", "agent", "client"] +resolver = "2" + +[workspace.package] +version = "0.1.0" +edition = "2021" +license = "MIT" + +[workspace.dependencies] +anyhow = "1" +clap = { version = "4", features = ["derive", "env"] } +futures-util = { version = "0.3", features = ["sink"] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio = { version = "1", features = ["full"] } +tokio-tungstenite = { version = "0.28", features = ["rustls-tls-webpki-roots"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +url = "2" + +[profile.release] +lto = "thin" +strip = true diff --git a/README.md b/README.md index 8b2bbdd..48fcc47 100644 --- a/README.md +++ b/README.md @@ -1,77 +1,174 @@ -# Android 远程设备桥接 +# Android Device Streaming -让本机普通 `adb devices` 显示远程手机,同时保留本地 ADB 服务及其他本地设备。 +公网中继 + 远程设备守护程序 + 本地连接守护程序。两端主动出站连接服务器,无需 VPN 或路由器端口映射。连接后,普通本地 `adb devices` 可以显示远程手机,Android Studio / scrcpy 使用本地 ADB 的正常设备通道。 ```text -本地 adb → 127.0.0.1:15555(本程序) - → 192.168.5.222:5037(远程 ADB 服务) - → 已连接的 192.168.100.141:5555 - → 手机自身 localhost:5555(adbd) +本地 ADB → 127.0.0.1:15555 → ads-client (Rust) + │ WSS + ads-server (Go) + │ WSS + ads-agent (Rust) → 手机 adbd TCP:5555 ``` -本地无需能访问手机网段。远程电脑必须能访问手机,手机必须已开启 TCP ADB 5555;仅 USB 或 TLS 无线调试设备不能直接套用本方案。 +## 程序划分 -## 远程电脑 +| 目录 | 输出 | 职责 | +|---|---|---| +| `server/` | `ads-server` | 角色认证、网关注册、设备独占、会话配对、二进制转发 | +| `agent/` | `ads-agent` | 远程电脑后台进程,主动注册设备、接通手机、断线重连 | +| `client/` | `ads-client` | 本地后台进程,保持设备租约,提供本地端口,自动调用 `adb connect` | +| `crates/ads-core/` | 共用 Rust 库 | WSS、协议、ADB smart socket、流式转发 | +| `deploy/` | 部署示例 | Caddy、systemd、launchd 示例 | -保持下面的服务运行(停止旧服务会中断已有调试连接): +三个程序均为独立可执行文件。没有 UI,不依赖 Python 运行正式程序。两端守护程序当前作为前台长运行进程,启动安装交给各平台进程管理器;尚未实现原生 Windows Service 安装器。 + +## 编译 + +需要 Go 1.24+、近期稳定版 Rust/Cargo;Windows Rust MSVC 工具链还需要 C++ Build Tools。优先使用仓库中的依赖锁文件。 + +Windows PowerShell: ```powershell -adb kill-server -adb -a -P 5037 nodaemon server start +.\scripts\build.ps1 +# 更快的本地调试构建:.\scripts\build.ps1 -DebugBuild ``` -另开窗口: +Linux / macOS: + +```sh +sh scripts/build.sh +``` + +产物在 `bin/`,Windows 是三个 `.exe`。Go 服务器和 Rust 核心使用跨平台 API;当前实际编译和集成测试平台为 Windows x64,Linux/macOS 仍需在对应平台验证构建、进程托管和 ADB 权限。 + +## 1. 公网服务器 + +生成两枚不同的随机令牌,每枚至少 32 字符。服务器保存两枚,远程端仅配置 agent 令牌,本地端仅配置 client 令牌。不要用演示文字作为真实令牌。 + +PowerShell 生成令牌示例: ```powershell -adb connect 192.168.100.141:5555 -adb devices +python -c "import secrets; print(secrets.token_hex(32))" ``` -只允许可信 VPN 客户端访问远程 TCP 5037。ADB smart socket 没有客户端认证和加密,不应直接暴露公网。以后走公网时,把 `--remote-host` 和 `--remote-port` 改成 SSH 等认证加密隧道的本地入口。 - -## 本地电脑 - -需要 Python 3、ADB;画面操作另外需要 scrcpy。 - -在项目目录执行并保持窗口运行: +配置环境变量后启动(默认仅监听回环地址): ```powershell -python .\adb_bridge.py +$env:ADS_AGENT_TOKEN = '<生成的设备端令牌>' +$env:ADS_CLIENT_TOKEN = '<生成的本地端令牌>' +.\bin\ads-server.exe --listen 127.0.0.1:8080 ``` -另开 PowerShell,清除之前指向远程服务的环境变量,仅影响当前窗口: +公网部署必须启用 TLS,可用 `deploy/Caddyfile` 把 `https://devices.example.com` 代理到该 HTTP 服务;也可直接使用: + +```powershell +.\bin\ads-server.exe --listen 0.0.0.0:443 --tls-cert fullchain.pem --tls-key privkey.pem +``` + +需要客户端信任的有效域名证书。只有域名和 443 对公网暴露,不暴露手机的 5555 和 ADB Server 的 5037。反向代理应支持 WebSocket 升级、长连接,并避免将带会话票据的 URL 写入访问日志。 + +## 2. 远程电脑 + +手机已开启 TCP ADB,且远程电脑能访问 `192.168.100.141:5555` 时: + +```powershell +$env:ADS_AGENT_TOKEN = '<与服务器一致的设备端令牌>' +.\bin\ads-agent.exe --server wss://devices.example.com --device home-phone --target 192.168.100.141:5555 +``` + +该模式直接连接手机,不需要在远程电脑额外公开 ADB Server。 + +也支持通过已有的 ADB Server 选择设备,用于复用当前环境: + +```powershell +.\bin\ads-agent.exe --server wss://devices.example.com --device home-phone --adb-server 127.0.0.1:5037 --adb-serial 192.168.100.141:5555 +``` + +**两个模式都要求手机已经开启 TCP adbd。仅 USB、未开启 TCP adbd 的手机暂不支持;TLS 无线调试端口也不能当作普通 5555 使用。** `--adb-serial` 模式通过已连接的 adbd,在手机自身回环地址打开 `tcp:5555`。 + +一个 agent 进程对应一个设备 ID。多手机可启动多个进程,ID 必须不同。 + +## 3. 本地电脑 + +需要 Android SDK Platform Tools(`adb`);投屏另外安装 scrcpy。先清除当前窗口中旧的远程 ADB 环境设置: ```powershell Remove-Item Env:ADB_SERVER_SOCKET -ErrorAction SilentlyContinue Remove-Item Env:ANDROID_ADB_SERVER_ADDRESS -ErrorAction SilentlyContinue Remove-Item Env:ANDROID_ADB_SERVER_PORT -ErrorAction SilentlyContinue -adb connect 127.0.0.1:15555 -adb devices -l -adb -s 127.0.0.1:15555 shell getprop ro.product.model +$env:ADS_CLIENT_TOKEN = '<与服务器一致的本地端令牌>' +.\bin\ads-client.exe --server wss://devices.example.com --device home-phone ``` -应出现 `127.0.0.1:15555 device`。首次可能是 `unauthorized`,需要在手机上批准本地电脑的 RSA 调试密钥;远程电脑的授权不会自动授予本地电脑。 +客户端默认监听 `127.0.0.1:15555`,获得设备租约后每 5 秒尝试本地 `adb connect`,支持断线后的新连接恢复。ADB 不在 PATH 时加 `--adb 'F:\AndroidSDK\platform-tools\adb.exe'`。令牌优先通过环境变量传入,避免出现在进程命令行中。 -画面及鼠标操作: +另开终端: ```powershell +adb devices -l +adb -s 127.0.0.1:15555 shell getprop ro.product.model scrcpy -s 127.0.0.1:15555 ``` -这是真正注册到本地 ADB 服务的 TCP 设备,Android Studio 应能发现它(需使用同一个本地 ADB 服务)。安装、shell、logcat、forward/reverse 均走本地 ADB 的正常设备通道;实际设备上的兼容性仍需验证。断点调试要求目标应用可调试。 +预期设备是 `127.0.0.1:15555 device`。首次出现 `unauthorized` 时,在手机上批准**本地电脑**的调试密钥;远程电脑已经获得授权不代表本地电脑自动获得授权。程序不会绕过 Android 授权。 -## 参数、诊断及停止 +可用 `--listen 127.0.0.1:15556` 指定其他本地端口;`--no-auto-connect` 禁止自动调用 ADB,由用户手动执行 `adb connect`。本地端口强制使用回环地址。 + +## 本机联调 + +三个窗口分别运行,令牌保持一致: ```powershell -python .\adb_bridge.py --check -python .\adb_bridge.py --remote-host 192.168.5.222 --remote-port 5037 --serial 192.168.100.141:5555 --device-port 5555 --listen-port 15555 -python -m unittest discover -s tests -v +# 窗口 1 +$env:ADS_AGENT_TOKEN = '<设备端令牌>' +$env:ADS_CLIENT_TOKEN = '<本地端令牌>' +.\bin\ads-server.exe + +# 窗口 2:当前 VPN 环境下复用远程 ADB 验证 +$env:ADS_AGENT_TOKEN = '<设备端令牌>' +.\bin\ads-agent.exe --server ws://127.0.0.1:8080 --allow-insecure --device home-phone --adb-server 192.168.5.222:5037 --adb-serial 192.168.100.141:5555 + +# 窗口 3 +$env:ADS_CLIENT_TOKEN = '<本地端令牌>' +.\bin\ads-client.exe --server ws://127.0.0.1:8080 --allow-insecure --device home-phone ``` -- `--check` 只检查远程设备选择和手机 TCP 端口,不验证本地 RSA 授权、投屏或 IDE。 -- 找不到设备:在远程电脑重新 `adb connect`,检查设备序列号。 -- `tcp:5555` 失败:手机必须监听自身 TCP 5555;某些系统可能限制回环访问。 -- 远程链路断开后:恢复远程设备连接,再在本地重跑 `adb connect 127.0.0.1:15555`。当前版本不主动自动重连。 -- 停止:本地执行 `adb disconnect 127.0.0.1:15555`,再在桥接窗口按 Ctrl+C。 +`--allow-insecure` 仅供隔离开发环境使用,禁止用于真实公网。该示例把 agent 临时放在本地是为了验证;真实部署时把 agent 放到远程电脑,改用 WSS 公网服务器和其可达的手机地址,即可去掉 VPN。 -协议依据:本项目自带的 `adb/docs/dev/services.md` 中 `host:transport:` 及设备 `tcp:` 服务。 +## 查询与验证 + +```powershell +Invoke-RestMethod https://devices.example.com/v1/devices -Headers @{Authorization="Bearer $env:ADS_CLIENT_TOKEN"} +``` + +返回 `[{"id":"home-phone","busy":false}]`。在线表示网关控制连接在线,并不保证手机此刻可达;只有建立数据连接时才检查手机 TCP 接入。 + +自动化检查: + +```powershell +Push-Location server +go test ./... +go vet ./... +Pop-Location +cargo test --workspace --locked +cargo clippy --workspace --all-targets --locked -- -D warnings +python tests/e2e.py +``` + +`tests/e2e.py` 启动真实三个程序和模拟手机,验证大数据、多连接、独占和重连;不用接入真手机。可选只读真机测试: + +```powershell +python tests/real_device.py --adb-server 192.168.5.222:5037 --serial 192.168.100.141:5555 +``` + +## 当前边界 + +- 单中继进程、内存设备注册;服务器重启后两端重新注册、获取租约,不保留历史。 +- 两个角色的共享令牌,只适用于同一个受信任管理域;不是多租户账号、每设备权限或完整用户系统。 +- 每台设备只能由一个本地守护程序占用;每设备最多 32 条转发连接。 +- 断线后建立新连接,旧的安装、shell、调试和串流会话不能无缝续传。 +- 数据采用 TLS 分段加密,中继服务器可见转发内容;未实现端到端加密。 +- 原始 ADB 数据流不重新编码;不解析 shell 命令,不改写 ADB 协议,不内置画面解码。 +- 当前 WebSocket 关闭会结束整个 TCP 通道,不保留半关闭语义;已覆盖常规双向流量,额外工具的特殊连接语义需单独测试。 + +协议说明见 `docs/protocol.md`。此前的 Python 局域网桥接保留在 `adb_bridge.py`,说明在 `docs/local-bridge.md`,与新三端实现独立。 diff --git a/agent/Cargo.toml b/agent/Cargo.toml new file mode 100644 index 0000000..9d86cf3 --- /dev/null +++ b/agent/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "ads-agent" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +ads-core = { path = "../crates/ads-core" } +anyhow.workspace = true +clap.workspace = true +tokio.workspace = true +tracing.workspace = true diff --git a/agent/README.md b/agent/README.md new file mode 100644 index 0000000..4638ed5 --- /dev/null +++ b/agent/README.md @@ -0,0 +1,14 @@ +# ads-agent(Rust 远程设备守护程序) + +入口:`src/main.rs`。根目录构建:`cargo build -p ads-agent --release --locked`。 + +```powershell +$env:ADS_AGENT_TOKEN = '<设备端令牌>' +.\ads-agent.exe --server wss://devices.example.com --device home-phone --target 192.168.100.141:5555 +``` + +默认主动出站,不需要对远程电脑开放入站端口。网络故障后以 1–30 秒退避重连,控制连接断开时结束旧数据连接。一个进程对应一台手机,多设备启动多个进程。 + +也可用 `--adb-server 127.0.0.1:5037 --adb-serial <序列号>` 替代 `--target`。该模式仍要求手机开启 TCP adbd(默认 5555,可用 `--device-port` 修改),不是通用的 USB-only 接入。 + +Windows 可由任务计划程序在登录后启动;Linux/macOS 可使用 `deploy/` 示例托管。当前二进制不是原生 Windows Service,不能直接用 `sc.exe create` 安装。 diff --git a/agent/src/main.rs b/agent/src/main.rs new file mode 100644 index 0000000..928a9e9 --- /dev/null +++ b/agent/src/main.rs @@ -0,0 +1,126 @@ +use ads_core::{ + adb_tcp_connect, dial, init_logging, next_control, relay, tcp_connect, valid_device_id, + validate_token, NetworkArgs, +}; +use anyhow::{bail, Context, Result}; +use clap::Parser; +use std::{sync::Arc, time::Duration}; +use tokio::{net::TcpStream, task::JoinSet, time::sleep}; +use tracing::{info, warn}; + +#[derive(Parser)] +#[command( + version, + about = "Remote device gateway: outbound-only connection to the ADS relay" +)] +struct Args { + #[command(flatten)] + network: NetworkArgs, + #[arg(long, env = "ADS_AGENT_TOKEN", hide_env_values = true)] + token: String, + /// Stable public device alias, e.g. home-phone + #[arg(long)] + device: String, + /// Direct phone adbd address reachable from this gateway, e.g. 192.168.100.141:5555 + #[arg( + long, + required_unless_present = "adb_serial", + conflicts_with = "adb_serial" + )] + target: Option, + /// Alternative: choose a transport from an existing ADB server (phone must have TCP adbd enabled) + #[arg(long)] + adb_serial: Option, + #[arg(long, default_value = "127.0.0.1:5037")] + adb_server: String, + #[arg(long, default_value_t = 5555)] + device_port: u16, +} + +async fn upstream(args: &Args) -> Result { + match &args.target { + Some(address) => tcp_connect(address).await, + None => { + adb_tcp_connect( + &args.adb_server, + args.adb_serial.as_deref().context("missing serial")?, + args.device_port, + ) + .await + } + } +} + +async fn serve_session(args: Arc, session: String) -> Result<()> { + let tcp = upstream(&args).await.context("cannot reach phone adbd")?; + let ws = dial( + args.network.url( + "/v1/data", + &[("device", &args.device), ("session", &session)], + )?, + &args.token, + ) + .await?; + relay(tcp, ws).await +} + +async fn online(args: Arc) -> Result<()> { + let mut ws = dial( + args.network.url("/v1/agent", &[("device", &args.device)])?, + &args.token, + ) + .await?; + let hello = next_control(&mut ws).await?; + if hello.kind != "registered" { + bail!("expected registered response"); + } + info!(device = %args.device, "gateway registered"); + let mut tasks = JoinSet::new(); + loop { + tokio::select! { + message = next_control(&mut ws) => { + let message = message?; + if message.kind != "open" { bail!("unexpected gateway control message"); } + let session = message.session.context("missing session ticket")?; + if tasks.len() >= 32 { warn!("gateway stream limit reached"); continue; } + let args = args.clone(); + tasks.spawn(async move { + if let Err(error) = serve_session(args, session).await { warn!(%error, "device stream ended"); } + }); + }, + _ = tasks.join_next(), if !tasks.is_empty() => {}, + } + } + // JoinSet drop aborts all streams when the control connection is lost. +} + +async fn run(args: Arc) { + let mut delay = 1; + loop { + let started = std::time::Instant::now(); + if let Err(error) = online(args.clone()).await { + warn!(%error, "gateway offline; reconnecting"); + } + if started.elapsed() > Duration::from_secs(30) { + delay = 1; + } + sleep(Duration::from_secs(delay)).await; + delay = (delay * 2).min(30); + } +} + +#[tokio::main] +async fn main() -> Result<()> { + init_logging(); + let args = Args::parse(); + validate_token(&args.token)?; + if !valid_device_id(&args.device) { + bail!("invalid device ID (use letters, digits, -, _, .; max 128 bytes)"); + } + args.network.url("/v1/agent", &[])?; + tokio::select! { + _ = run(Arc::new(args)) => {}, + result = tokio::signal::ctrl_c() => { result?; info!("gateway stopping"); }, + } + Ok(()) +} diff --git a/client/Cargo.toml b/client/Cargo.toml new file mode 100644 index 0000000..aaf013a --- /dev/null +++ b/client/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "ads-client" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +ads-core = { path = "../crates/ads-core" } +anyhow.workspace = true +clap.workspace = true +tokio.workspace = true +tracing.workspace = true diff --git a/client/README.md b/client/README.md new file mode 100644 index 0000000..84e5d14 --- /dev/null +++ b/client/README.md @@ -0,0 +1,17 @@ +# ads-client(Rust 本地连接守护程序) + +入口:`src/main.rs`。根目录构建:`cargo build -p ads-client --release --locked`。 + +```powershell +$env:ADS_CLIENT_TOKEN = '<本地端令牌>' +.\ads-client.exe --server wss://devices.example.com --device home-phone +``` + +默认监听 `127.0.0.1:15555`,取得独占设备租约后自动调用本地 ADB 连接;本地普通 `adb devices` 将列出该地址。每 5 秒尝试恢复 ADB 连接。首次调试仍需在手机上授权本地电脑的密钥。 + +- `--listen 127.0.0.1:15556`:修改端口,仅允许回环地址。 +- `--adb <完整路径>`:指定 ADB 可执行文件。 +- `--no-auto-connect`:仅提供转发入口,由用户手动 `adb connect`。 +- Ctrl+C 释放租约,并在启用自动连接时执行该端点的 `adb disconnect`。 + +使用本地 ADB 的正常通道,可配合 Android Studio 和 `scrcpy -s 127.0.0.1:15555`。不要将 `ADB_SERVER_SOCKET` 指向远程服务,否则其他终端可能查询到另一台 ADB Server。 diff --git a/client/src/main.rs b/client/src/main.rs new file mode 100644 index 0000000..e35800c --- /dev/null +++ b/client/src/main.rs @@ -0,0 +1,166 @@ +use ads_core::{ + dial, init_logging, next_control, relay, valid_device_id, validate_token, NetworkArgs, +}; +use anyhow::{bail, Context, Result}; +use clap::Parser; +use std::{net::SocketAddr, path::PathBuf, sync::Arc, time::Duration}; +use tokio::{ + net::TcpListener, + process::Command, + sync::watch, + task::JoinSet, + time::{sleep, timeout}, +}; +use tracing::{info, warn}; + +#[derive(Parser)] +#[command( + version, + about = "Local ADS daemon: expose a remote phone as a local adb connect endpoint" +)] +struct Args { + #[command(flatten)] + network: NetworkArgs, + #[arg(long, env = "ADS_CLIENT_TOKEN", hide_env_values = true)] + token: String, + #[arg(long)] + device: String, + /// Local endpoint; loopback addresses only + #[arg(long, default_value = "127.0.0.1:15555")] + listen: SocketAddr, + #[arg(long, default_value = "adb")] + adb: PathBuf, + /// Do not periodically invoke local adb connect (useful for manual control/tests) + #[arg(long)] + no_auto_connect: bool, +} + +async fn lease_once(args: &Args, state: &watch::Sender>) -> Result<()> { + let mut ws = dial( + args.network.url("/v1/lease", &[("device", &args.device)])?, + &args.token, + ) + .await?; + let response = next_control(&mut ws).await?; + if response.kind != "leased" { + bail!("expected leased response"); + } + let id = response.lease.context("missing lease ticket")?; + state.send_replace(Some(id)); + info!(device = %args.device, endpoint = %args.listen, "device leased; local tunnel ready"); + loop { + next_control(&mut ws).await?; + } +} + +async fn maintain_lease(args: Arc, state: watch::Sender>) { + let mut delay = 1; + loop { + let started = std::time::Instant::now(); + if let Err(error) = lease_once(&args, &state).await { + warn!(%error, "lease unavailable; reconnecting"); + } + state.send_replace(None); + if started.elapsed() > Duration::from_secs(30) { + delay = 1; + } + sleep(Duration::from_secs(delay)).await; + delay = (delay * 2).min(30); + } +} + +async fn adb_command(args: &Args, action: &str) -> Result<()> { + let output = timeout( + Duration::from_secs(8), + Command::new(&args.adb) + .env_remove("ADB_SERVER_SOCKET") + .env_remove("ANDROID_ADB_SERVER_ADDRESS") + .env_remove("ANDROID_ADB_SERVER_PORT") + .arg(action) + .arg(args.listen.to_string()) + .kill_on_drop(true) + .output(), + ) + .await + .context("adb command timed out")??; + if !output.status.success() { + bail!( + "adb command failed: {}", + String::from_utf8_lossy(&output.stderr).trim() + ); + } + // adb can report a connection failure with exit code 0; retain its text. + let message = String::from_utf8_lossy(&output.stdout); + info!(output = %message.trim(), "local adb"); + Ok(()) +} + +async fn maintain_adb(args: Arc, state: watch::Receiver>) { + loop { + if state.borrow().is_some() { + if let Err(error) = adb_command(&args, "connect").await { + warn!(%error, "local adb connect failed"); + } + } + sleep(Duration::from_secs(5)).await; + } +} + +async fn accept_connections( + args: Arc, + listener: TcpListener, + state: watch::Receiver>, +) -> Result<()> { + let mut tasks = JoinSet::new(); + loop { + tokio::select! { + accepted = listener.accept() => { + let (tcp, _) = accepted?; + let lease = state.borrow().clone(); + let Some(lease) = lease else { drop(tcp); continue; }; + if tasks.len() >= 32 { drop(tcp); warn!("local stream limit reached"); continue; } + let args = args.clone(); + tasks.spawn(async move { + let result = async { + let url = args.network.url("/v1/connect", &[("device", &args.device), ("lease", &lease)])?; + let ws = dial(url, &args.token).await?; + relay(tcp, ws).await + }.await; + if let Err(error) = result { warn!(%error, "local device stream ended"); } + }); + }, + _ = tasks.join_next(), if !tasks.is_empty() => {}, + } + } +} + +#[tokio::main] +async fn main() -> Result<()> { + init_logging(); + let args = Arc::new(Args::parse()); + validate_token(&args.token)?; + if !valid_device_id(&args.device) { + bail!("invalid device ID"); + } + if !args.listen.ip().is_loopback() || args.listen.port() == 0 { + bail!("--listen must use a loopback address and a nonzero port"); + } + args.network.url("/v1/lease", &[])?; + let listener = TcpListener::bind(args.listen) + .await + .context("cannot bind local ADB endpoint")?; + let (sender, receiver) = watch::channel(None); + info!(endpoint = %args.listen, "listening; local adb will show this address after connection"); + // Dropping these futures on shutdown closes control and data connections. + tokio::select! { + _ = maintain_lease(args.clone(), sender) => {}, + _ = maintain_adb(args.clone(), receiver.clone()), if !args.no_auto_connect => {}, + result = accept_connections(args.clone(), listener, receiver) => { result?; }, + result = tokio::signal::ctrl_c() => { result?; }, + } + if !args.no_auto_connect { + let _ = adb_command(&args, "disconnect").await; + } + info!("client stopping"); + Ok(()) +} diff --git a/crates/ads-core/Cargo.toml b/crates/ads-core/Cargo.toml new file mode 100644 index 0000000..edb7993 --- /dev/null +++ b/crates/ads-core/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "ads-core" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +anyhow.workspace = true +clap.workspace = true +futures-util.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +tokio-tungstenite.workspace = true +tracing-subscriber.workspace = true +url.workspace = true diff --git a/crates/ads-core/src/lib.rs b/crates/ads-core/src/lib.rs new file mode 100644 index 0000000..7be1a40 --- /dev/null +++ b/crates/ads-core/src/lib.rs @@ -0,0 +1,256 @@ +use anyhow::{bail, Context, Result}; +use clap::Args; +use futures_util::{SinkExt, StreamExt}; +use serde::{Deserialize, Serialize}; +use std::time::Duration; +use tokio::{ + io::{AsyncReadExt, AsyncWriteExt}, + net::TcpStream, + time::timeout, +}; +use tokio_tungstenite::{ + connect_async_with_config, + tungstenite::{client::IntoClientRequest, http::HeaderValue, Message}, + MaybeTlsStream, WebSocketStream, +}; +use url::Url; + +pub type Ws = WebSocketStream>; +pub const CONNECT_TIMEOUT: Duration = Duration::from_secs(10); +pub const IO_TIMEOUT: Duration = Duration::from_secs(30); + +#[derive(Args, Clone, Debug)] +pub struct NetworkArgs { + /// Relay URL, e.g. wss://devices.example.com + #[arg(long)] + pub server: String, + /// Allow unencrypted ws:// for isolated development only + #[arg(long, default_value_t = false)] + pub allow_insecure: bool, +} + +impl NetworkArgs { + pub fn url(&self, path: &str, params: &[(&str, &str)]) -> Result { + let mut url = Url::parse(&self.server).context("invalid relay URL")?; + match url.scheme() { + "wss" => {} + "ws" if self.allow_insecure => {} + _ => bail!("use wss://; ws:// requires --allow-insecure for development"), + } + if !url.username().is_empty() + || url.password().is_some() + || url.query().is_some() + || url.fragment().is_some() + { + bail!("relay URL must not contain credentials, query, or fragment"); + } + if url.path() != "/" && !url.path().is_empty() { + bail!("relay URL must use the root path (no URL prefix)"); + } + url.set_path(path); + url.query_pairs_mut().extend_pairs(params.iter().copied()); + Ok(url) + } +} + +pub fn valid_device_id(id: &str) -> bool { + !id.is_empty() + && id.len() <= 128 + && id + .bytes() + .all(|c| c.is_ascii_alphanumeric() || b"-_.".contains(&c)) +} + +pub fn validate_token(token: &str) -> Result<()> { + if token.len() < 32 { + bail!("token must be at least 32 characters"); + } + HeaderValue::from_str(&format!("Bearer {token}")).context("invalid token characters")?; + Ok(()) +} + +pub async fn dial(url: Url, token: &str) -> Result { + let mut request = url.as_str().into_client_request()?; + request.headers_mut().insert( + "Authorization", + HeaderValue::from_str(&format!("Bearer {token}"))?, + ); + // Do not include the URL in errors: session and lease tickets are secrets. + let config = tokio_tungstenite::tungstenite::protocol::WebSocketConfig::default() + .max_message_size(Some(128 * 1024)) + .max_frame_size(Some(128 * 1024)); + let result = timeout( + CONNECT_TIMEOUT, + connect_async_with_config(request, Some(config), true), + ) + .await + .context("relay handshake timed out")?; + match result { + Ok((socket, _)) => Ok(socket), + Err(tokio_tungstenite::tungstenite::Error::Http(response)) => { + bail!("relay rejected request: HTTP {}", response.status()) + } + Err(_) => bail!("relay connection failed (check address, TLS certificate and network)"), + } +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct Control { + #[serde(rename = "type")] + pub kind: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub device: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lease: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub session: Option, +} + +pub async fn next_control(ws: &mut Ws) -> Result { + loop { + match ws.next().await.context("control connection closed")?? { + Message::Text(text) => { + if text.len() > 16 * 1024 { + bail!("control message too large"); + } + return Ok(serde_json::from_str(&text)?); + } + Message::Ping(data) => ws.send(Message::Pong(data)).await?, + Message::Pong(_) => {} + Message::Close(_) => bail!("control connection closed"), + _ => bail!("unexpected control message"), + } + } +} + +/// Binary-only relay. Bounded chunks and awaited writes provide backpressure. +/// A websocket close terminates both directions; TCP half-close is not preserved. +pub async fn relay(tcp: TcpStream, ws: Ws) -> Result<()> { + tcp.set_nodelay(true)?; + let (mut reader, mut writer) = tcp.into_split(); + let (mut sink, mut stream) = ws.split(); + let to_ws = async { + let mut buffer = vec![0; 64 * 1024]; + loop { + let size = reader.read(&mut buffer).await?; + if size == 0 { + return Ok::<(), anyhow::Error>(()); + } + timeout( + IO_TIMEOUT, + sink.send(Message::Binary(buffer[..size].to_vec().into())), + ) + .await??; + } + }; + let to_tcp = async { + while let Some(message) = stream.next().await { + match message? { + Message::Binary(data) => { + if data.len() > 128 * 1024 { + bail!("data message too large"); + } + timeout(IO_TIMEOUT, writer.write_all(&data)).await??; + } + Message::Close(_) => return Ok::<(), anyhow::Error>(()), + Message::Ping(_) | Message::Pong(_) => {} + _ => bail!("unexpected text on binary tunnel"), + } + } + Ok(()) + }; + // Closing either side tears down this ADB transport; reconnect creates a new one. + tokio::select! { result = to_ws => result, result = to_tcp => result } +} + +pub async fn tcp_connect(address: &str) -> Result { + Ok(timeout(CONNECT_TIMEOUT, TcpStream::connect(address)) + .await + .context("TCP connect timed out")??) +} + +async fn adb_request(stream: &mut TcpStream, service: &str) -> Result<()> { + if service.len() > 65535 { + bail!("ADB service name too long"); + } + stream + .write_all(format!("{:04x}{service}", service.len()).as_bytes()) + .await?; + let mut status = [0; 4]; + stream.read_exact(&mut status).await?; + match &status { + b"OKAY" => Ok(()), + b"FAIL" => { + let mut size = [0; 4]; + stream.read_exact(&mut size).await?; + let size = usize::from_str_radix(std::str::from_utf8(&size)?, 16)?; + let mut error = vec![0; size]; + stream.read_exact(&mut error).await?; + bail!("remote ADB: {}", String::from_utf8_lossy(&error)) + } + _ => bail!("invalid ADB smart socket reply"), + } +} + +/// Requires TCP adbd on the phone, even when selecting a USB transport. +pub async fn adb_tcp_connect(server: &str, serial: &str, port: u16) -> Result { + let mut stream = tcp_connect(server).await?; + timeout(CONNECT_TIMEOUT, async { + adb_request(&mut stream, &format!("host:transport:{serial}")).await?; + adb_request(&mut stream, &format!("tcp:{port}")).await + }) + .await + .context("ADB service handshake timed out")??; + Ok(stream) +} + +pub fn init_logging() { + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into()), + ) + .with_target(false) + .init(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn rejects_unsafe_configuration() { + let network = NetworkArgs { + server: "ws://example.com".into(), + allow_insecure: false, + }; + assert!(network.url("/v1/agent", &[]).is_err()); + assert!(validate_token("short").is_err()); + assert!(!valid_device_id("bad/device")); + assert!(valid_device_id("home-phone_1")); + } + + #[tokio::test] + async fn adb_handshake_selects_transport_and_phone_port() { + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap().to_string(); + let task = tokio::spawn(async move { + let (mut sock, _) = listener.accept().await.unwrap(); + for expected in ["host:transport:test", "tcp:5555"] { + let mut size = [0; 4]; + sock.read_exact(&mut size).await.unwrap(); + let size = usize::from_str_radix(std::str::from_utf8(&size).unwrap(), 16).unwrap(); + let mut payload = vec![0; size]; + sock.read_exact(&mut payload).await.unwrap(); + assert_eq!(payload, expected.as_bytes()); + sock.write_all(b"OK").await.unwrap(); + sock.write_all(b"AY").await.unwrap(); + } + sock.write_all(b"raw-adbd").await.unwrap(); + }); + let mut stream = adb_tcp_connect(&address, "test", 5555).await.unwrap(); + let mut data = [0; 8]; + stream.read_exact(&mut data).await.unwrap(); + assert_eq!(&data, b"raw-adbd"); + task.await.unwrap(); + } +} diff --git a/deploy/Caddyfile b/deploy/Caddyfile new file mode 100644 index 0000000..d2be05e --- /dev/null +++ b/deploy/Caddyfile @@ -0,0 +1,6 @@ +# Replace with your actual DNS name. Caddy obtains a public certificate. +# Keep the relay HTTP listener on loopback. Do not enable URL access logs +# containing session / lease query tickets without redaction. +devices.example.com { + reverse_proxy 127.0.0.1:8080 +} diff --git a/deploy/README.md b/deploy/README.md new file mode 100644 index 0000000..6016834 --- /dev/null +++ b/deploy/README.md @@ -0,0 +1,9 @@ +# Process management examples + +Examples are templates, not installed automatically. Replace paths, domain, user and tokens before use. Public endpoints require HTTPS/WSS. + +- Linux: create a dedicated `ads` user and `/opt/ads`; protect `/etc/ads/*.env` so only the intended account/root can read them. `server.env` contains `ADS_AGENT_TOKEN=...` and `ADS_CLIENT_TOKEN=...`; `agent.env` contains only `ADS_AGENT_TOKEN=...`. Copy the respective systemd unit to `/etc/systemd/system/`, then enable it. The local client normally runs as the desktop user, so it shares that user's ADB server and keys. +- macOS: edit the launchd plist, restrict its file permissions, and install it as the appropriate user's LaunchAgent. It contains a credential, so do not publish the edited file. Client launchd configuration can use the same pattern with `ads-client` and `ADS_CLIENT_TOKEN`. +- Windows: the binaries run as foreground long-lived processes. Use Task Scheduler to launch them under the intended account at logon, with a startup wrapper that sets the token environment variable, and configure restart on failure. Keep wrapper/config files readable only by that account and administrators. Native Service Control Manager support and installers are not implemented; do not use `sc.exe create` directly on these binaries. + +These templates have not been exercised on Linux/macOS yet. Test the binaries and process manager on each target platform before relying on unattended startup. diff --git a/deploy/ads-agent.service b/deploy/ads-agent.service new file mode 100644 index 0000000..e9b3ea7 --- /dev/null +++ b/deploy/ads-agent.service @@ -0,0 +1,18 @@ +[Unit] +Description=Android Device Streaming gateway +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=ads +WorkingDirectory=/opt/ads +EnvironmentFile=/etc/ads/agent.env +ExecStart=/opt/ads/ads-agent --server wss://devices.example.com --device home-phone --target 192.168.100.141:5555 +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/deploy/ads-server.service b/deploy/ads-server.service new file mode 100644 index 0000000..5a13890 --- /dev/null +++ b/deploy/ads-server.service @@ -0,0 +1,18 @@ +[Unit] +Description=Android Device Streaming relay +After=network-online.target +Wants=network-online.target + +[Service] +Type=simple +User=ads +WorkingDirectory=/opt/ads +EnvironmentFile=/etc/ads/server.env +ExecStart=/opt/ads/ads-server --listen 127.0.0.1:8080 +Restart=on-failure +RestartSec=3 +NoNewPrivileges=true +PrivateTmp=true + +[Install] +WantedBy=multi-user.target diff --git a/deploy/com.example.ads-agent.plist b/deploy/com.example.ads-agent.plist new file mode 100644 index 0000000..3180d27 --- /dev/null +++ b/deploy/com.example.ads-agent.plist @@ -0,0 +1,17 @@ + + + + Labelcom.example.ads-agent + ProgramArguments + /opt/ads/ads-agent + --serverwss://devices.example.com + --devicehome-phone + --target192.168.100.141:5555 + + EnvironmentVariables + ADS_AGENT_TOKENREPLACE_WITH_YOUR_RANDOM_AGENT_TOKEN + + RunAtLoad + KeepAlive + ThrottleInterval5 + diff --git a/docs/local-bridge.md b/docs/local-bridge.md new file mode 100644 index 0000000..8b2bbdd --- /dev/null +++ b/docs/local-bridge.md @@ -0,0 +1,77 @@ +# Android 远程设备桥接 + +让本机普通 `adb devices` 显示远程手机,同时保留本地 ADB 服务及其他本地设备。 + +```text +本地 adb → 127.0.0.1:15555(本程序) + → 192.168.5.222:5037(远程 ADB 服务) + → 已连接的 192.168.100.141:5555 + → 手机自身 localhost:5555(adbd) +``` + +本地无需能访问手机网段。远程电脑必须能访问手机,手机必须已开启 TCP ADB 5555;仅 USB 或 TLS 无线调试设备不能直接套用本方案。 + +## 远程电脑 + +保持下面的服务运行(停止旧服务会中断已有调试连接): + +```powershell +adb kill-server +adb -a -P 5037 nodaemon server start +``` + +另开窗口: + +```powershell +adb connect 192.168.100.141:5555 +adb devices +``` + +只允许可信 VPN 客户端访问远程 TCP 5037。ADB smart socket 没有客户端认证和加密,不应直接暴露公网。以后走公网时,把 `--remote-host` 和 `--remote-port` 改成 SSH 等认证加密隧道的本地入口。 + +## 本地电脑 + +需要 Python 3、ADB;画面操作另外需要 scrcpy。 + +在项目目录执行并保持窗口运行: + +```powershell +python .\adb_bridge.py +``` + +另开 PowerShell,清除之前指向远程服务的环境变量,仅影响当前窗口: + +```powershell +Remove-Item Env:ADB_SERVER_SOCKET -ErrorAction SilentlyContinue +Remove-Item Env:ANDROID_ADB_SERVER_ADDRESS -ErrorAction SilentlyContinue +Remove-Item Env:ANDROID_ADB_SERVER_PORT -ErrorAction SilentlyContinue +adb connect 127.0.0.1:15555 +adb devices -l +adb -s 127.0.0.1:15555 shell getprop ro.product.model +``` + +应出现 `127.0.0.1:15555 device`。首次可能是 `unauthorized`,需要在手机上批准本地电脑的 RSA 调试密钥;远程电脑的授权不会自动授予本地电脑。 + +画面及鼠标操作: + +```powershell +scrcpy -s 127.0.0.1:15555 +``` + +这是真正注册到本地 ADB 服务的 TCP 设备,Android Studio 应能发现它(需使用同一个本地 ADB 服务)。安装、shell、logcat、forward/reverse 均走本地 ADB 的正常设备通道;实际设备上的兼容性仍需验证。断点调试要求目标应用可调试。 + +## 参数、诊断及停止 + +```powershell +python .\adb_bridge.py --check +python .\adb_bridge.py --remote-host 192.168.5.222 --remote-port 5037 --serial 192.168.100.141:5555 --device-port 5555 --listen-port 15555 +python -m unittest discover -s tests -v +``` + +- `--check` 只检查远程设备选择和手机 TCP 端口,不验证本地 RSA 授权、投屏或 IDE。 +- 找不到设备:在远程电脑重新 `adb connect`,检查设备序列号。 +- `tcp:5555` 失败:手机必须监听自身 TCP 5555;某些系统可能限制回环访问。 +- 远程链路断开后:恢复远程设备连接,再在本地重跑 `adb connect 127.0.0.1:15555`。当前版本不主动自动重连。 +- 停止:本地执行 `adb disconnect 127.0.0.1:15555`,再在桥接窗口按 Ctrl+C。 + +协议依据:本项目自带的 `adb/docs/dev/services.md` 中 `host:transport:` 及设备 `tcp:` 服务。 diff --git a/docs/protocol.md b/docs/protocol.md new file mode 100644 index 0000000..b453d67 --- /dev/null +++ b/docs/protocol.md @@ -0,0 +1,36 @@ +# ADS relay protocol v1 + +All requests use `Authorization: Bearer `. Agent and client roles have separate shared tokens. Tickets are opaque random 192-bit values and must not be logged. Public deployments use HTTPS/WSS with normal certificate verification; TLS ends at the relay. + +## Endpoints + +| Endpoint | Role | Purpose | +|---|---|---| +| `GET /healthz` | Public | Liveness only | +| `GET /v1/devices` | Client | JSON array of gateway IDs and busy flags | +| `GET /v1/agent?device=ID` | Agent | Persistent gateway control WebSocket | +| `GET /v1/lease?device=ID` | Client | Persistent exclusive ownership WebSocket | +| `GET /v1/connect?device=ID&lease=TICKET` | Client | One binary data WebSocket per local TCP connection | +| `GET /v1/data?device=ID&session=TICKET` | Agent | One binary WebSocket paired to a pending client stream | + +IDs contain 1–128 ASCII letters, digits, `.`, `_`, `-`. Device IDs cannot be replaced by another agent until the original connection ends. Duplicate agents / occupied leases return HTTP 409, missing devices return 404, bad roles return 401. Stream limit is 32 per device. + +## Connection flow + +1. Agent connects and receives `{"type":"registered","device":"home-phone"}`. +2. Client daemon acquires a lease and receives `{"type":"leased","lease":"..."}`. +3. Client daemon accepts a local TCP socket, opens `/v1/connect` with its lease. +4. Relay sends the agent `{"type":"open","session":"..."}`. +5. Agent connects to the phone's raw TCP adbd (directly, or through an existing ADB smart socket), then opens `/v1/data` with that session ticket. +6. Relay pairs the streams. Each session ticket can only be claimed once, by the current registered agent for the requested device. +7. Binary WebSocket messages carry consecutive raw TCP bytes. Message boundaries have no ADB meaning. Chunks are at most 64 KiB from Rust; all peers limit received messages to 128 KiB. + +Agent and lease control channels use server-initiated ping every 20 seconds with a 10-second timeout. Device data must attach within 15 seconds. Payload writes time out after 30 seconds; awaited bounded writes propagate backpressure. Disconnecting agent or lease cancels attached streams. A new agent registration or lease never inherits old sessions. + +The client connects the resulting local TCP endpoint with the local ADB Server. The phone therefore authenticates the local computer's ADB key, not just the gateway key. This is the distinction between a real local ADB transport and pointing an adb CLI at a remote ADB Server. + +## Scope + +One relay process, one trusted administration domain. There is no database, per-user ACL, distributed broker or end-to-end encryption in v1. An agent-role token authorizes registering device aliases within that domain; provision it only to trusted gateway hosts. + +Gateways currently require a raw TCP adbd endpoint. Existing smart socket mode uses `host:transport:` then `tcp:` on the selected device. It does not transparently virtualize a USB-only device. TCP half-close is not carried across a WebSocket close. Reconnection creates fresh transports, not resumable application streams. diff --git a/docs/verification.md b/docs/verification.md new file mode 100644 index 0000000..0fe46dd --- /dev/null +++ b/docs/verification.md @@ -0,0 +1,21 @@ +# Verification record + +Validated on Windows x64 during implementation: + +- `go test ./...`: role authentication, offline devices, duplicate registration, exclusive leases, ticket ownership and replay rejection, bidirectional bytes, stream cancellation, agent disconnect cleanup. +- `go vet ./...`: passed. +- `cargo test --workspace --locked`: configuration validation and ADB smart socket handshake with fragmented replies. +- `cargo clippy --workspace --all-targets --locked -- -D warnings`: passed. +- Release builds: Go relay and both Rust executables built successfully. +- `python tests/e2e.py` against the release binaries: passed 2 MiB binary transfer, eight concurrent streams, an idle stream across control ping/pong, competing-client rejection, agent restart and relay restart recovery. +- Existing Python bridge unit tests: all three passed. + +Read-only real-device smoke test: + +- Remote ADB Server `192.168.5.222:5037` listed `192.168.100.141:5555` as online. +- Started a temporary relay and both Rust daemons, with the gateway using the existing remote ADB transport. +- Local `adb connect` reached the phone through the new three-program path, but Android returned `unauthorized` for the local computer's key. +- Consequently, real `adb shell`, app installation, Android Studio and scrcpy have not been verified through the new path. Approve the local key on the phone, then rerun `tests/real_device.py`. +- Temporary processes and local ADB endpoint were disconnected after the test; unrelated local ADB devices were preserved. + +No public server was deployed. Production WSS certificates, real Internet latency, and Linux/macOS runtime behavior still need deployment-environment validation. The Linux Go server is cross-built separately; cross-building is not a Linux runtime test. diff --git a/scripts/build.ps1 b/scripts/build.ps1 new file mode 100644 index 0000000..7b7f455 --- /dev/null +++ b/scripts/build.ps1 @@ -0,0 +1,20 @@ +param([switch]$DebugBuild) +$ErrorActionPreference = 'Stop' +$projectRoot = Split-Path $PSScriptRoot -Parent +$configuration = if ($DebugBuild) { 'debug' } else { 'release' } +Push-Location $projectRoot +try { + if ($DebugBuild) { cargo build --workspace --locked } + else { cargo build --workspace --release --locked } + if ($LASTEXITCODE -ne 0) { throw 'Rust build failed' } + New-Item -ItemType Directory -Force -Path (Join-Path $projectRoot 'bin') | Out-Null + foreach ($name in @('ads-agent', 'ads-client')) { + Copy-Item -LiteralPath (Join-Path $projectRoot "target/$configuration/$name.exe") -Destination (Join-Path $projectRoot "bin/$name.exe") -Force + } + Push-Location (Join-Path $projectRoot 'server') + try { + go build -trimpath -o (Join-Path $projectRoot 'bin/ads-server.exe') . + if ($LASTEXITCODE -ne 0) { throw 'Go build failed' } + } finally { Pop-Location } +} finally { Pop-Location } +Write-Host "Built server, agent and client in $projectRoot/bin" diff --git a/scripts/build.sh b/scripts/build.sh new file mode 100644 index 0000000..59cfc06 --- /dev/null +++ b/scripts/build.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env sh +set -eu +project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd) +cd "$project_root" +cargo build --workspace --release --locked +mkdir -p bin +cp target/release/ads-agent target/release/ads-client bin/ +cd server +go build -trimpath -o ../bin/ads-server . diff --git a/server/README.md b/server/README.md new file mode 100644 index 0000000..17344c0 --- /dev/null +++ b/server/README.md @@ -0,0 +1,12 @@ +# ads-server(Go 公网服务器) + +入口:`main.go`。独立构建:`go build -o ads-server .`。 + +- 配置:环境变量 `ADS_AGENT_TOKEN`、`ADS_CLIENT_TOKEN`,要求不同且各至少 32 字符。 +- 默认监听:`127.0.0.1:8080`,用 `--listen` 修改。 +- TLS:反向代理或 `--tls-cert` 与 `--tls-key`;公网必须使用有效证书。 +- 路由:`/healthz`、`/v1/agent`、`/v1/devices`、`/v1/lease`、`/v1/connect`、`/v1/data`。 +- 状态存内存;一个 ID 对应一个在线 agent,一个设备对应一个独占租约。 +- Ctrl+C / SIGTERM 关闭控制与数据连接;两端支持重连。 + +部署、令牌配置和三端完整命令见项目根目录 `README.md`。 diff --git a/server/go.mod b/server/go.mod new file mode 100644 index 0000000..439485b --- /dev/null +++ b/server/go.mod @@ -0,0 +1,5 @@ +module android-device-streaming/server + +go 1.24.0 + +require github.com/coder/websocket v1.8.14 diff --git a/server/go.sum b/server/go.sum new file mode 100644 index 0000000..c80e2f0 --- /dev/null +++ b/server/go.sum @@ -0,0 +1,2 @@ +github.com/coder/websocket v1.8.14 h1:9L0p0iKiNOibykf283eHkKUHHrpG7f65OE3BhhO7v9g= +github.com/coder/websocket v1.8.14/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= diff --git a/server/main.go b/server/main.go new file mode 100644 index 0000000..cb5bfff --- /dev/null +++ b/server/main.go @@ -0,0 +1,394 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/subtle" + "encoding/hex" + "encoding/json" + "errors" + "flag" + "fmt" + "io" + "log" + "net/http" + "os" + "os/signal" + "strings" + "sync" + "syscall" + "time" + + "github.com/coder/websocket" +) + +type agent struct { + id string + ws *websocket.Conn +} +type lease struct { + id string + device string + ws *websocket.Conn +} +type session struct { + id string + agent *agent + lease *lease + ready chan *websocket.Conn + ctx context.Context + cancel context.CancelFunc + claimed bool +} +type broker struct { + mu sync.Mutex + agents map[string]*agent + leases map[string]*lease // indexed by device, one owner per device + sessions map[string]*session + agentToken, clientToken string + ctx context.Context +} + +func newBroker(ctx context.Context, agentToken, clientToken string) *broker { + return &broker{agents: make(map[string]*agent), leases: make(map[string]*lease), + sessions: make(map[string]*session), agentToken: agentToken, clientToken: clientToken, ctx: ctx} +} +func newID() string { + var data [24]byte + if _, err := rand.Read(data[:]); err != nil { + panic(err) + } + return hex.EncodeToString(data[:]) +} +func validID(id string) bool { + if len(id) < 1 || len(id) > 128 { + return false + } + for _, c := range id { + if !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || strings.ContainsRune("-_.", c)) { + return false + } + } + return true +} +func (b *broker) auth(token string, handler http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 { + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + handler(w, r) + } +} +func accept(w http.ResponseWriter, r *http.Request) (*websocket.Conn, error) { + conn, err := websocket.Accept(w, r, nil) + if err == nil { + conn.SetReadLimit(128 * 1024) + } + return conn, err +} +func writeJSON(ctx context.Context, ws *websocket.Conn, value any) error { + data, err := json.Marshal(value) + if err != nil { + return err + } + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + return ws.Write(ctx, websocket.MessageText, data) +} + +// A reader must be running while Ping waits for a pong. +func hold(ctx context.Context, ws *websocket.Conn) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + go func() { + ticker := time.NewTicker(20 * time.Second) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-ticker.C: + pingCtx, stop := context.WithTimeout(ctx, 10*time.Second) + err := ws.Ping(pingCtx) + stop() + if err != nil { + cancel() + return + } + } + } + }() + for { + if _, _, err := ws.Read(ctx); err != nil { + return + } + } +} +func (b *broker) agentEndpoint(w http.ResponseWriter, r *http.Request) { + id := r.URL.Query().Get("device") + if !validID(id) { + http.Error(w, "invalid device ID", 400) + return + } + // Reserve before upgrading, so duplicate agents never replace an existing one. + a := &agent{id: id} + b.mu.Lock() + if b.agents[id] != nil { + b.mu.Unlock() + http.Error(w, "device already registered", 409) + return + } + b.agents[id] = a + b.mu.Unlock() + defer func() { + b.mu.Lock() + if b.agents[id] == a { + delete(b.agents, id) + } + for _, s := range b.sessions { + if s.agent == a { + s.cancel() + } + } + l := b.leases[id] + var leaseConn *websocket.Conn + if l != nil { + leaseConn = l.ws + } + b.mu.Unlock() + if leaseConn != nil { + leaseConn.CloseNow() + } + }() + ws, err := accept(w, r) + if err != nil { + return + } + defer ws.CloseNow() + b.mu.Lock() + a.ws = ws + b.mu.Unlock() + if err := writeJSON(b.ctx, ws, map[string]string{"type": "registered", "device": id}); err != nil { + return + } + log.Printf("agent online: %s", id) + hold(b.ctx, ws) + log.Printf("agent offline: %s", id) +} +func (b *broker) devicesEndpoint(w http.ResponseWriter, r *http.Request) { + type device struct { + ID string `json:"id"` + Busy bool `json:"busy"` + } + devices := []device{} + b.mu.Lock() + for id, a := range b.agents { + if a.ws != nil { + devices = append(devices, device{id, b.leases[id] != nil}) + } + } + b.mu.Unlock() + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(devices) +} +func (b *broker) leaseEndpoint(w http.ResponseWriter, r *http.Request) { + id := r.URL.Query().Get("device") + b.mu.Lock() + a := b.agents[id] + if a == nil || a.ws == nil { + b.mu.Unlock() + http.Error(w, "device offline", 404) + return + } + if b.leases[id] != nil { + b.mu.Unlock() + http.Error(w, "device busy", 409) + return + } + l := &lease{id: newID(), device: id} + b.leases[id] = l + b.mu.Unlock() + defer func() { + b.mu.Lock() + if b.leases[id] == l { + delete(b.leases, id) + } + for _, s := range b.sessions { + if s.lease == l { + s.cancel() + } + } + b.mu.Unlock() + }() + ws, err := accept(w, r) + if err != nil { + return + } + defer ws.CloseNow() + b.mu.Lock() + if b.agents[id] != a { + b.mu.Unlock() + return + } + l.ws = ws + b.mu.Unlock() + if err := writeJSON(b.ctx, ws, map[string]string{"type": "leased", "lease": l.id}); err != nil { + return + } + hold(b.ctx, ws) +} +func (b *broker) connectEndpoint(w http.ResponseWriter, r *http.Request) { + id, leaseID := r.URL.Query().Get("device"), r.URL.Query().Get("lease") + b.mu.Lock() + a, l := b.agents[id], b.leases[id] + if a == nil || a.ws == nil || l == nil || l.ws == nil || l.id != leaseID { + b.mu.Unlock() + http.Error(w, "no active lease", 409) + return + } + // Bound pending and active streams for each device. + count := 0 + for _, s := range b.sessions { + if s.agent == a { + count++ + } + } + if count >= 32 { + b.mu.Unlock() + http.Error(w, "stream limit reached", 429) + return + } + ctx, cancel := context.WithCancel(b.ctx) + s := &session{id: newID(), agent: a, lease: l, ready: make(chan *websocket.Conn, 1), ctx: ctx, cancel: cancel} + b.sessions[s.id] = s + b.mu.Unlock() + defer func() { s.cancel(); b.mu.Lock(); delete(b.sessions, s.id); b.mu.Unlock() }() + client, err := accept(w, r) + if err != nil { + return + } + defer client.CloseNow() + if err := writeJSON(ctx, a.ws, map[string]string{"type": "open", "session": s.id}); err != nil { + return + } + timer := time.NewTimer(15 * time.Second) + defer timer.Stop() + select { + case upstream := <-s.ready: + defer upstream.CloseNow() + bridgeWebSockets(ctx, client, upstream) + case <-timer.C: + client.Close(websocket.StatusTryAgainLater, "device connection timed out") + case <-ctx.Done(): + } +} +func (b *broker) dataEndpoint(w http.ResponseWriter, r *http.Request) { + ticket, id := r.URL.Query().Get("session"), r.URL.Query().Get("device") + b.mu.Lock() + s := b.sessions[ticket] + if s == nil || s.agent.id != id || b.agents[id] != s.agent || s.claimed || s.ctx.Err() != nil { + b.mu.Unlock() + http.Error(w, "invalid or expired session", 404) + return + } + s.claimed = true + b.mu.Unlock() + ws, err := accept(w, r) + if err != nil { + s.cancel() + return + } + defer ws.CloseNow() + select { + case s.ready <- ws: + case <-s.ctx.Done(): + return + } + <-s.ctx.Done() +} +func bridgeWebSockets(ctx context.Context, left, right *websocket.Conn) { + ctx, cancel := context.WithCancel(ctx) + defer cancel() + copyMessages := func(dst, src *websocket.Conn) { + defer cancel() + for { + typ, data, err := src.Read(ctx) + if err != nil { + return + } + if typ != websocket.MessageBinary { + return + } + writeCtx, stop := context.WithTimeout(ctx, 30*time.Second) + err = dst.Write(writeCtx, typ, data) + stop() + if err != nil { + return + } + } + } + var wg sync.WaitGroup + wg.Add(2) + go func() { defer wg.Done(); copyMessages(left, right) }() + go func() { defer wg.Done(); copyMessages(right, left) }() + wg.Wait() +} +func (b *broker) handler() http.Handler { + mux := http.NewServeMux() + mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok\n") }) + mux.HandleFunc("GET /v1/agent", b.auth(b.agentToken, b.agentEndpoint)) + mux.HandleFunc("GET /v1/data", b.auth(b.agentToken, b.dataEndpoint)) + mux.HandleFunc("GET /v1/devices", b.auth(b.clientToken, b.devicesEndpoint)) + mux.HandleFunc("GET /v1/lease", b.auth(b.clientToken, b.leaseEndpoint)) + mux.HandleFunc("GET /v1/connect", b.auth(b.clientToken, b.connectEndpoint)) + return mux +} +func main() { + listen := flag.String("listen", "127.0.0.1:8080", "HTTP listen address (use a TLS reverse proxy for public access)") + cert := flag.String("tls-cert", "", "TLS certificate PEM path") + key := flag.String("tls-key", "", "TLS private key PEM path") + flag.Parse() + agentToken, clientToken := os.Getenv("ADS_AGENT_TOKEN"), os.Getenv("ADS_CLIENT_TOKEN") + if len(agentToken) < 32 || len(clientToken) < 32 || agentToken == clientToken { + log.Fatal("set distinct ADS_AGENT_TOKEN and ADS_CLIENT_TOKEN, at least 32 characters each") + } + if (*cert == "") != (*key == "") { + log.Fatal("provide both --tls-cert and --tls-key") + } + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + b := newBroker(ctx, agentToken, clientToken) + server := &http.Server{Addr: *listen, Handler: b.handler(), ReadHeaderTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, MaxHeaderBytes: 16 * 1024} + go func() { + <-ctx.Done() + b.mu.Lock() + for _, a := range b.agents { + if a.ws != nil { + a.ws.CloseNow() + } + } + for _, l := range b.leases { + if l.ws != nil { + l.ws.CloseNow() + } + } + for _, s := range b.sessions { + s.cancel() + } + b.mu.Unlock() + shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + server.Shutdown(shutdownCtx) + }() + log.Printf("ADS relay listening on %s", *listen) + var err error + if *cert != "" { + err = server.ListenAndServeTLS(*cert, *key) + } else { + err = server.ListenAndServe() + } + if err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatal(fmt.Errorf("server: %w", err)) + } +} diff --git a/server/main_test.go b/server/main_test.go new file mode 100644 index 0000000..0efeea8 --- /dev/null +++ b/server/main_test.go @@ -0,0 +1,152 @@ +package main + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "github.com/coder/websocket" +) + +const testAgentToken = "agent-token-for-testing-only-1234567890" +const testClientToken = "client-token-for-testing-only-1234567890" + +func testServer(t *testing.T) (*broker, string) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + b := newBroker(ctx, testAgentToken, testClientToken) + srv := httptest.NewServer(b.handler()) + t.Cleanup(func() { cancel(); srv.Close() }) + return b, srv.URL +} +func dialTest(t *testing.T, base, path, token string) *websocket.Conn { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + ws, _, err := websocket.Dial(ctx, strings.Replace(base, "http", "ws", 1)+path, + &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": []string{"Bearer " + token}}}) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { ws.CloseNow() }) + return ws +} +func readControl(t *testing.T, ws *websocket.Conn) map[string]string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _, data, err := ws.Read(ctx) + if err != nil { + t.Fatal(err) + } + var value map[string]string + if err := json.Unmarshal(data, &value); err != nil { + t.Fatal(err) + } + return value +} +func status(t *testing.T, base, path, token string) int { + t.Helper() + req, _ := http.NewRequest("GET", base+path, nil) + req.Header.Set("Authorization", "Bearer "+token) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + return resp.StatusCode +} + +func TestRoleAuthenticationAndOfflineDevices(t *testing.T) { + _, base := testServer(t) + for _, path := range []string{"/v1/devices", "/v1/lease?device=phone", "/v1/connect?device=phone"} { + if got := status(t, base, path, testAgentToken); got != 401 { + t.Fatalf("%s: got %d", path, got) + } + } + if got := status(t, base, "/v1/agent?device=phone", testClientToken); got != 401 { + t.Fatal(got) + } + if got := status(t, base, "/v1/lease?device=phone", testClientToken); got != 404 { + t.Fatal(got) + } + if got := status(t, base, "/v1/data?session=bad&device=phone", testAgentToken); got != 404 { + t.Fatal(got) + } +} + +func TestExclusiveLeaseAndBidirectionalData(t *testing.T) { + _, base := testServer(t) + agent := dialTest(t, base, "/v1/agent?device=phone", testAgentToken) + if readControl(t, agent)["type"] != "registered" { + t.Fatal("not registered") + } + if got := status(t, base, "/v1/agent?device=phone", testAgentToken); got != 409 { + t.Fatal(got) + } + owner := dialTest(t, base, "/v1/lease?device=phone", testClientToken) + lease := readControl(t, owner)["lease"] + if got := status(t, base, "/v1/lease?device=phone", testClientToken); got != 409 { + t.Fatal(got) + } + if got := status(t, base, "/v1/connect?device=phone&lease=wrong", testClientToken); got != 409 { + t.Fatal(got) + } + client := dialTest(t, base, "/v1/connect?device=phone&lease="+lease, testClientToken) + session := readControl(t, agent)["session"] + if got := status(t, base, "/v1/data?device=other&session="+session, testAgentToken); got != 404 { + t.Fatal(got) + } + device := dialTest(t, base, "/v1/data?device=phone&session="+session, testAgentToken) + if got := status(t, base, "/v1/data?device=phone&session="+session, testAgentToken); got != 404 { + t.Fatal(got) + } + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for _, pair := range [][2]*websocket.Conn{{client, device}, {device, client}} { + payload := []byte{'A', 0, 255, 'D', 'B'} + if err := pair[0].Write(ctx, websocket.MessageBinary, payload); err != nil { + t.Fatal(err) + } + typ, data, err := pair[1].Read(ctx) + if err != nil || typ != websocket.MessageBinary || string(data) != string(payload) { + t.Fatalf("corrupted stream: %v", err) + } + } + // Dropping ownership must tear down existing streams, not just block new ones. + owner.CloseNow() + if _, _, err := client.Read(ctx); err == nil { + t.Fatal("stream survived lease closure") + } +} + +func TestAgentDisconnectReleasesOwnership(t *testing.T) { + b, base := testServer(t) + agent := dialTest(t, base, "/v1/agent?device=phone", testAgentToken) + readControl(t, agent) + owner := dialTest(t, base, "/v1/lease?device=phone", testClientToken) + readControl(t, owner) + agent.CloseNow() + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + if _, _, err := owner.Read(ctx); err == nil { + t.Fatal("lease survived agent disconnect") + } + deadline := time.Now().Add(time.Second) + for { + b.mu.Lock() + remaining := len(b.leases) + len(b.agents) + b.mu.Unlock() + if remaining == 0 { + break + } + if time.Now().After(deadline) { + t.Fatal("stale registration or lease") + } + time.Sleep(time.Millisecond) + } +} diff --git a/tests/e2e.py b/tests/e2e.py new file mode 100644 index 0000000..afac58b --- /dev/null +++ b/tests/e2e.py @@ -0,0 +1,196 @@ +"""Exercise the actual Go relay and Rust daemons using a simulated phone TCP endpoint. + +Build first with scripts/build.ps1 or scripts/build.sh. No external Python packages. +""" +import argparse +import concurrent.futures +import json +import os +from pathlib import Path +import secrets +import socket +import socketserver +import subprocess +import threading +import time +import urllib.error +import urllib.request + +ROOT = Path(__file__).resolve().parents[1] + + +def free_port(): + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return sock.getsockname()[1] + + +def wait_until(predicate, description, seconds=15): + deadline = time.monotonic() + seconds + while time.monotonic() < deadline: + try: + if predicate(): + return + except (OSError, urllib.error.URLError): + pass + time.sleep(0.1) + raise AssertionError(f"Timed out: {description}") + + +class Echo(socketserver.BaseRequestHandler): + def handle(self): + try: + while data := self.request.recv(65536): + self.request.sendall(data) + except OSError: + pass + + +class Phone(socketserver.ThreadingTCPServer): + daemon_threads = True + allow_reuse_address = True + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin") + parser.add_argument("--rust-dir", type=Path) + args = parser.parse_args() + rust_dir = args.rust_dir or args.bin_dir + suffix = ".exe" if os.name == "nt" else "" + server_bin = (args.bin_dir / f"ads-server{suffix}").resolve() + agent_bin = (rust_dir / f"ads-agent{suffix}").resolve() + client_bin = (rust_dir / f"ads-client{suffix}").resolve() + for path in (server_bin, agent_bin, client_bin): + if not path.exists(): + raise SystemExit(f"Build missing binary first: {path}") + + logs = ROOT / "work" / "e2e" + logs.mkdir(parents=True, exist_ok=True) + processes, handles = [], [] + agent_token, client_token = secrets.token_hex(32), secrets.token_hex(32) + relay_port, local_port, second_port = free_port(), free_port(), free_port() + relay = f"ws://127.0.0.1:{relay_port}" + api = f"http://127.0.0.1:{relay_port}" + + def launch(name, command, tokens): + env = os.environ.copy() + env.pop("ADS_AGENT_TOKEN", None) + env.pop("ADS_CLIENT_TOKEN", None) + env.update(tokens) + handle = open(logs / f"{name}.log", "wb") + handles.append(handle) + process = subprocess.Popen([str(item) for item in command], env=env, + stdout=handle, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) + processes.append(process) + return process + + def stop(process): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=8) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + + def devices(token=client_token): + req = urllib.request.Request(api + "/v1/devices", headers={"Authorization": "Bearer " + token}) + with urllib.request.urlopen(req, timeout=2) as response: + return json.load(response) + + def busy(): + return any(device["id"] == "test-phone" and device["busy"] for device in devices()) + + def transfer(size): + payload = secrets.token_bytes(size) + with socket.create_connection(("127.0.0.1", local_port), timeout=8) as sock: + sock.settimeout(10) + with concurrent.futures.ThreadPoolExecutor(max_workers=1) as writer: + sent = writer.submit(sock.sendall, payload) + received = bytearray() + while len(received) < size: + chunk = sock.recv(min(65536, size - len(received))) + if not chunk: + raise AssertionError("Tunnel closed before complete response") + received.extend(chunk) + sent.result(timeout=5) + assert received == payload, "Binary stream corruption" + + with Phone(("127.0.0.1", 0), Echo) as phone: + threading.Thread(target=phone.serve_forever, daemon=True).start() + phone_port = phone.server_address[1] + server_command = [server_bin, "--listen", f"127.0.0.1:{relay_port}"] + agent_command = [agent_bin, "--server", relay, "--allow-insecure", "--device", "test-phone", + "--target", f"127.0.0.1:{phone_port}"] + client_command = [client_bin, "--server", relay, "--allow-insecure", "--device", "test-phone", + "--listen", f"127.0.0.1:{local_port}", "--no-auto-connect"] + try: + server = launch("server", server_command, {"ADS_AGENT_TOKEN": agent_token, "ADS_CLIENT_TOKEN": client_token}) + wait_until(lambda: devices() == [], "relay startup") + try: + devices(agent_token) + raise AssertionError("Agent token granted client access") + except urllib.error.HTTPError as error: + assert error.code == 401 + agent = launch("agent", agent_command, {"ADS_AGENT_TOKEN": agent_token}) + wait_until(lambda: len(devices()) == 1, "agent registration") + client = launch("client", client_command, {"ADS_CLIENT_TOKEN": client_token}) + wait_until(busy, "client exclusive lease") + transfer(2 * 1024 * 1024) + with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: + list(pool.map(transfer, [256 * 1024] * 8)) + print("PASS: 2 MiB binary stream and eight concurrent streams") + + # Keep a data stream idle across the server's 20-second control ping. + with socket.create_connection(("127.0.0.1", local_port), timeout=8) as idle: + idle.settimeout(5) + time.sleep(22) + idle.sendall(b"after-heartbeat") + received = bytearray() + while len(received) < 15: + chunk = idle.recv(15 - len(received)) + assert chunk, "Idle tunnel was closed by heartbeat processing" + received.extend(chunk) + assert received == b"after-heartbeat" + print("PASS: idle tunnel survives control ping/pong heartbeat") + + competitor_command = client_command.copy() + competitor_command[competitor_command.index("--listen") + 1] = f"127.0.0.1:{second_port}" + competitor = launch("competitor", competitor_command, {"ADS_CLIENT_TOKEN": client_token}) + time.sleep(1) + with socket.create_connection(("127.0.0.1", second_port), timeout=3) as sock: + sock.settimeout(3) + try: + sock.sendall(b"denied") + assert sock.recv(16) == b"", "Second client stole exclusive device" + except (ConnectionResetError, ConnectionAbortedError): + pass + stop(competitor) + print("PASS: competing client cannot acquire occupied device") + + stop(agent) + wait_until(lambda: devices() == [], "offline device removal") + agent = launch("agent-restarted", agent_command, {"ADS_AGENT_TOKEN": agent_token}) + wait_until(busy, "client lease recovery after agent restart", seconds=40) + transfer(65536) + print("PASS: agent restart and client reconnection") + + stop(server) + server = launch("server-restarted", server_command, {"ADS_AGENT_TOKEN": agent_token, "ADS_CLIENT_TOKEN": client_token}) + wait_until(busy, "both daemons reconnect after relay restart", seconds=45) + transfer(65536) + print("PASS: relay restart and both-daemon recovery") + assert agent.poll() is None and client.poll() is None + finally: + for process in reversed(processes): + stop(process) + for handle in handles: + handle.close() + phone.shutdown() + print("PASS: all three-program integration checks") + + +if __name__ == "__main__": + main() diff --git a/tests/real_device.py b/tests/real_device.py new file mode 100644 index 0000000..59bbe15 --- /dev/null +++ b/tests/real_device.py @@ -0,0 +1,98 @@ +"""Opt-in, read-only smoke test through a remote ADB smart socket and all three programs.""" +import argparse +import os +from pathlib import Path +import secrets +import subprocess +import time +import urllib.request + +from e2e import ROOT, free_port, wait_until + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--adb-server", required=True) + parser.add_argument("--serial", required=True) + parser.add_argument("--adb", default="adb") + parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin") + parser.add_argument("--rust-dir", type=Path) + args = parser.parse_args() + suffix = ".exe" if os.name == "nt" else "" + rust_dir = args.rust_dir or args.bin_dir + relay_port, local_port = free_port(), free_port() + server_url = f"ws://127.0.0.1:{relay_port}" + endpoint = f"127.0.0.1:{local_port}" + env = os.environ.copy() + env["ADS_AGENT_TOKEN"] = secrets.token_hex(32) + env["ADS_CLIENT_TOKEN"] = secrets.token_hex(32) + for key in ("ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT"): + env.pop(key, None) + folder = ROOT / "work" / "real-device" + folder.mkdir(parents=True, exist_ok=True) + processes, files = [], [] + + def start(name, command): + handle = open(folder / f"{name}.log", "wb") + files.append(handle) + process = subprocess.Popen([str(value) for value in command], env=env, + stdout=handle, stderr=subprocess.STDOUT, + creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) + processes.append(process) + + def adb(*command): + return subprocess.run([args.adb, *command], env=env, capture_output=True, + text=True, timeout=10) + + def leased(): + request = urllib.request.Request(f"http://127.0.0.1:{relay_port}/v1/devices", + headers={"Authorization": "Bearer " + env["ADS_CLIENT_TOKEN"]}) + with urllib.request.urlopen(request, timeout=2) as response: + return b'"busy":true' in response.read() + + try: + start("server", [(args.bin_dir / f"ads-server{suffix}").resolve(), "--listen", f"127.0.0.1:{relay_port}"]) + start("agent", [(rust_dir / f"ads-agent{suffix}").resolve(), "--server", server_url, + "--allow-insecure", "--device", "smoke-phone", "--adb-server", args.adb_server, + "--adb-serial", args.serial]) + start("client", [(rust_dir / f"ads-client{suffix}").resolve(), "--server", server_url, + "--allow-insecure", "--device", "smoke-phone", "--listen", endpoint, + "--no-auto-connect"]) + wait_until(leased, "remote phone lease", seconds=20) + print(adb("connect", endpoint).stdout.strip(), flush=True) + print("If requested, approve this computer's debugging key on the phone.", flush=True) + deadline = time.monotonic() + 20 + while True: + state = adb("-s", endpoint, "get-state") + if state.returncode == 0 and state.stdout.strip() == "device": + break + if time.monotonic() >= deadline: + raise RuntimeError("Phone did not authorize local ADB: " + state.stderr.strip()) + time.sleep(1) + listing = adb("devices", "-l") + assert listing.returncode == 0 and endpoint in listing.stdout + print(listing.stdout.strip()) + model = adb("-s", endpoint, "shell", "getprop", "ro.product.model") + assert model.returncode == 0, model.stderr + marker = adb("-s", endpoint, "shell", "echo", "ads-read-only-smoke-ok") + assert marker.returncode == 0 and marker.stdout.strip() == "ads-read-only-smoke-ok", marker.stderr + print("PASS: ordinary local adb devices and remote shell via Go server + both Rust daemons") + print("Remote model:", model.stdout.strip()) + finally: + try: + adb("disconnect", endpoint) + finally: + for process in reversed(processes): + if process.poll() is None: + process.terminate() + try: + process.wait(timeout=5) + except subprocess.TimeoutExpired: + process.kill() + process.wait(timeout=5) + for handle in files: + handle.close() + + +if __name__ == "__main__": + main()