From 41c8ed4406411d6e32ef5d5557b5254afe01b2cb Mon Sep 17 00:00:00 2001 From: faumaray Date: Mon, 26 Oct 2026 23:13:19 +0300 Subject: [PATCH] windows: the service, its API and proxy-ctl ps-ipc: line-delimited JSON over a named pipe whose ACL admits SYSTEM, Administrators and (with userControl) the interactive user; the caller is identified by impersonation, never by what it claims. A Unix socket stands in off Windows. ps-service (proxy-suite-service.exe): a Windows service, or --console. Keeps the configuration with revisions, runtime state and generated secrets; renders, checks with sing-box check before replacing what runs, and supervises the backends (restart with backoff, start limit, logs in a ring and a file, a Job Object on Windows). Enforces scopes, admin-only edits and secret redaction that round-trips. Fetches subscriptions and rule sets through the proxy or directly with upstream's redirect rules, on timers. ps-ctl (proxy-ctl.exe): status, restart, logs [-f], config get/set/ validate, and proxy on/off, outbounds, pin, mode, subs, rules, rulesets, tun and config. An end-to-end test runs it all offline: a sing-box Shadowsocks server, the service, proxy-ctl adding the outbound, a page fetched through the local proxy. Co-Authored-By: Claude Opus 5.5 --- windows/Cargo.lock | 1828 ++++++++++++++++- windows/Cargo.toml | 15 +- windows/crates/ps-core/src/config/proxy.rs | 5 +- windows/crates/ps-core/src/config/validate.rs | 4 +- windows/crates/ps-core/src/duration.rs | 58 + windows/crates/ps-core/src/lib.rs | 1 + windows/crates/ps-core/src/render/sing_box.rs | 2 +- windows/crates/ps-ctl/Cargo.toml | 21 + windows/crates/ps-ctl/src/main.rs | 696 +++++++ windows/crates/ps-ctl/tests/e2e.rs | 189 ++ windows/crates/ps-ipc/Cargo.toml | 25 + windows/crates/ps-ipc/src/lib.rs | 115 ++ windows/crates/ps-ipc/src/transport.rs | 326 +++ windows/crates/ps-service/Cargo.toml | 35 + windows/crates/ps-service/src/api.rs | 488 +++++ windows/crates/ps-service/src/clash.rs | 90 + windows/crates/ps-service/src/components.rs | 39 + windows/crates/ps-service/src/fetch.rs | 146 ++ windows/crates/ps-service/src/job.rs | 63 + windows/crates/ps-service/src/main.rs | 127 ++ windows/crates/ps-service/src/paths.rs | 87 + windows/crates/ps-service/src/service.rs | 385 ++++ windows/crates/ps-service/src/store.rs | 125 ++ windows/crates/ps-service/src/units.rs | 429 ++++ windows/crates/ps-service/src/winsvc.rs | 119 ++ 25 files changed, 5411 insertions(+), 7 deletions(-) create mode 100644 windows/crates/ps-core/src/duration.rs create mode 100644 windows/crates/ps-ctl/Cargo.toml create mode 100644 windows/crates/ps-ctl/src/main.rs create mode 100644 windows/crates/ps-ctl/tests/e2e.rs create mode 100644 windows/crates/ps-ipc/Cargo.toml create mode 100644 windows/crates/ps-ipc/src/lib.rs create mode 100644 windows/crates/ps-ipc/src/transport.rs create mode 100644 windows/crates/ps-service/Cargo.toml create mode 100644 windows/crates/ps-service/src/api.rs create mode 100644 windows/crates/ps-service/src/clash.rs create mode 100644 windows/crates/ps-service/src/components.rs create mode 100644 windows/crates/ps-service/src/fetch.rs create mode 100644 windows/crates/ps-service/src/job.rs create mode 100644 windows/crates/ps-service/src/main.rs create mode 100644 windows/crates/ps-service/src/paths.rs create mode 100644 windows/crates/ps-service/src/service.rs create mode 100644 windows/crates/ps-service/src/store.rs create mode 100644 windows/crates/ps-service/src/units.rs create mode 100644 windows/crates/ps-service/src/winsvc.rs diff --git a/windows/Cargo.lock b/windows/Cargo.lock index e9e0323..191163d 100644 --- a/windows/Cargo.lock +++ b/windows/Cargo.lock @@ -2,6 +2,12 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + [[package]] name = "aho-corasick" version = "1.1.5" @@ -11,30 +17,650 @@ 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 = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" +dependencies = [ + "derive_arbitrary", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[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 = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +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.9", +] + +[[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 = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[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 = "derive_arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b034bd7d5f032402a2479444dcc6f74e36a03f31854d41680fb240ef682a1ac" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[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.9", +] + [[package]] name = "equivalent" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" +[[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 = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + [[package]] name = "foldhash" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" +[[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-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[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.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +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-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "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 = "h2" +version = "0.4.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d29020232d6aa3fb1daca64c1127cf662cf97f254ae16c18c05b8ab635fc118" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http", + "indexmap", + "slab", + "tokio", + "tokio-util", + "tracing", +] + [[package]] name = "hashbrown" version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[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 = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "h2", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[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 = "indexmap" version = "2.14.2" @@ -53,24 +679,195 @@ version = "2.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" +[[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.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[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 = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[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 = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.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 = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[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" @@ -84,7 +881,7 @@ dependencies = [ name = "ps-core" version = "0.1.0" dependencies = [ - "base64", + "base64 0.22.1", "indexmap", "ipnet", "percent-encoding", @@ -94,6 +891,51 @@ dependencies = [ "thiserror", ] +[[package]] +name = "ps-ctl" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "ps-core", + "ps-ipc", + "serde_json", + "tokio", +] + +[[package]] +name = "ps-ipc" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", + "thiserror", + "tokio", + "windows-sys 0.61.2", +] + +[[package]] +name = "ps-service" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap", + "ps-core", + "ps-ipc", + "rand", + "reqwest", + "rustls", + "serde", + "serde_json", + "sha2", + "tokio", + "tracing", + "tracing-subscriber", + "windows-service", + "windows-sys 0.61.2", + "zip", +] + [[package]] name = "quote" version = "1.0.47" @@ -103,6 +945,41 @@ 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 = "regex" version = "1.13.1" @@ -132,6 +1009,202 @@ version = "0.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "h2", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[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 = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + +[[package]] +name = "rustls-pki-types" +version = "1.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + +[[package]] +name = "rustls-webpki" +version = "0.103.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4443b1b6d39d7c663139942cc4558262562d2c84123bb6282ef177009ca8b281" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -159,7 +1232,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -177,6 +1250,127 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "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 = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[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.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[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.9" @@ -188,6 +1382,26 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[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.9", +] + [[package]] name = "thiserror" version = "2.0.21" @@ -205,17 +1419,625 @@ checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] +[[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", + "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.9", +] + +[[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-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[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 = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[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 = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[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 = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[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 = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e49d0e65abc00c142e8f9428da991da9f1a250c39be97459901eb12b9b49f62a" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "widestring" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-service" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "857224b3b211c6f3616921f081ee54721ee3ad2ace2fac6a6337e032f7b4dcf2" +dependencies = [ + "bitflags", + "widestring", + "windows-sys 0.61.2", +] + +[[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.9", + "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.9", + "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.9", +] + +[[package]] +name = "zip" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dcb24d0152526ae49b9b96c1dcf71850ca1e0b882e4e28ed898a93c41334744" +dependencies = [ + "arbitrary", + "crc32fast", + "crossbeam-utils", + "flate2", + "indexmap", + "memchr", + "zopfli", +] + [[package]] name = "zmij" version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zopfli" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aaf7fc5d30c28483d93805c4a5e12b05bbb52407fa67c5f8bd552374cd01fb11" +dependencies = [ + "bumpalo", + "crc32fast", + "log", + "simd-adler32", +] diff --git a/windows/Cargo.toml b/windows/Cargo.toml index 75b3569..511d68e 100644 --- a/windows/Cargo.toml +++ b/windows/Cargo.toml @@ -1,6 +1,6 @@ [workspace] resolver = "2" -members = ["crates/ps-core"] +members = ["crates/ps-core", "crates/ps-ipc", "crates/ps-service", "crates/ps-ctl"] [workspace.package] version = "0.1.0" @@ -18,3 +18,16 @@ thiserror = "2" percent-encoding = "2" ipnet = "2" indexmap = { version = "2", features = ["serde"] } +tokio = { version = "1.54", features = ["rt-multi-thread", "macros", "net", "io-util", "process", "time", "sync", "fs", "signal"] } +clap = { version = "4.6", features = ["derive"] } +reqwest = { version = "0.13", default-features = false, features = ["rustls-no-provider", "socks", "json", "stream", "http2", "query"] } +rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12"] } +windows-service = "0.8" +windows-sys = "0.61" +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } +rand = "0.9" +sha2 = "0.10" +zip = { version = "2", default-features = false, features = ["deflate"] } +ps-core = { path = "crates/ps-core" } +ps-ipc = { path = "crates/ps-ipc" } diff --git a/windows/crates/ps-core/src/config/proxy.rs b/windows/crates/ps-core/src/config/proxy.rs index 9d772b4..27e2aac 100644 --- a/windows/crates/ps-core/src/config/proxy.rs +++ b/windows/crates/ps-core/src/config/proxy.rs @@ -158,11 +158,14 @@ impl Default for AutoProxy { #[serde(rename_all = "camelCase", default, deny_unknown_fields)] pub struct SingBoxOptions { pub clash_api_port: u16, + /// Windows only: the loopback listener `proxy-ctl proxy outbounds test` reaches each + /// outbound through. Upstream fixes it at 18537. + pub test_port: u16, } impl Default for SingBoxOptions { fn default() -> Self { - Self { clash_api_port: 9090 } + Self { clash_api_port: 9090, test_port: 18537 } } } diff --git a/windows/crates/ps-core/src/config/validate.rs b/windows/crates/ps-core/src/config/validate.rs index 34262c6..34428e3 100644 --- a/windows/crates/ps-core/src/config/validate.rs +++ b/windows/crates/ps-core/src/config/validate.rs @@ -565,7 +565,9 @@ fn ports(cfg: &Config, v: &mut Issues) { if p.backend.runs_sing_box() { claim(p.sing_box.clash_api_port, "proxy.singBox.clashApiPort".into(), v); } - claim(derived::ports::OUTBOUND_TEST, "the outbound test listener".into(), v); + if p.backend.runs_sing_box() { + claim(p.sing_box.test_port, "proxy.singBox.testPort".into(), v); + } } if cfg.tor.enable { claim(cfg.tor.socks_port, "tor.socksPort".into(), v); diff --git a/windows/crates/ps-core/src/duration.rs b/windows/crates/ps-core/src/duration.rs new file mode 100644 index 0000000..c4cbd68 --- /dev/null +++ b/windows/crates/ps-core/src/duration.rs @@ -0,0 +1,58 @@ +//! Time spans as the options write them: systemd's ("1d", "6h", "1h 30min") and Go's +//! ("3m", "15s", "1m30s", "500ms"). + +use std::time::Duration; + +/// A span such as "1d", "6h 30m", "1m30s" or "500ms". A bare number is seconds. +pub fn parse(text: &str) -> Option { + let text = text.trim(); + if text.is_empty() { + return None; + } + if let Ok(secs) = text.parse::() { + return (secs >= 0.0).then(|| Duration::from_secs_f64(secs)); + } + let mut total = 0f64; + let mut rest = text; + while !rest.is_empty() { + rest = rest.trim_start(); + let num_len = rest.find(|c: char| !(c.is_ascii_digit() || c == '.')).unwrap_or(rest.len()); + if num_len == 0 { + return None; + } + let value: f64 = rest[..num_len].parse().ok()?; + rest = &rest[num_len..]; + let unit_len = rest.find(|c: char| !c.is_ascii_alphabetic()).unwrap_or(rest.len()); + let unit = &rest[..unit_len]; + rest = &rest[unit_len..]; + let factor = match unit { + "ns" => 1e-9, + "us" | "µs" => 1e-6, + "ms" | "msec" => 1e-3, + "s" | "sec" | "second" | "seconds" | "" => 1.0, + "m" | "min" | "minute" | "minutes" => 60.0, + "h" | "hr" | "hour" | "hours" => 3600.0, + "d" | "day" | "days" => 86400.0, + "w" | "week" | "weeks" => 604800.0, + _ => return None, + }; + total += value * factor; + } + Some(Duration::from_secs_f64(total)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn both_spellings_read() { + assert_eq!(parse("1d"), Some(Duration::from_secs(86400))); + assert_eq!(parse("6h 30min"), Some(Duration::from_secs(6 * 3600 + 1800))); + assert_eq!(parse("1m30s"), Some(Duration::from_secs(90))); + assert_eq!(parse("500ms"), Some(Duration::from_millis(500))); + assert_eq!(parse("45"), Some(Duration::from_secs(45))); + assert_eq!(parse("soon"), None); + assert_eq!(parse("3x"), None); + } +} diff --git a/windows/crates/ps-core/src/lib.rs b/windows/crates/ps-core/src/lib.rs index 9e2e0d8..e6ddbe3 100644 --- a/windows/crates/ps-core/src/lib.rs +++ b/windows/crates/ps-core/src/lib.rs @@ -6,6 +6,7 @@ pub mod config; pub mod derived; +pub mod duration; pub mod links; pub mod render; pub mod wg; diff --git a/windows/crates/ps-core/src/render/sing_box.rs b/windows/crates/ps-core/src/render/sing_box.rs index a2887cf..4bc3a6f 100644 --- a/windows/crates/ps-core/src/render/sing_box.rs +++ b/windows/crates/ps-core/src/render/sing_box.rs @@ -104,7 +104,7 @@ pub(super) fn config(input: &Input, asm: &Assembly, warnings: &mut Vec) inbounds.push(mixed); // The test listener `proxy-ctl proxy outbounds test` dials each outbound through, by the // Clash API's switching of its selector. - let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": ports::OUTBOUND_TEST }); + let mut test_in = json!({ "type": "mixed", "tag": "proxy-suite-test-in", "listen": "127.0.0.1", "listen_port": p.sing_box.test_port }); if let Some(users) = &users { test_in["users"] = users.clone(); } diff --git a/windows/crates/ps-ctl/Cargo.toml b/windows/crates/ps-ctl/Cargo.toml new file mode 100644 index 0000000..7b04461 --- /dev/null +++ b/windows/crates/ps-ctl/Cargo.toml @@ -0,0 +1,21 @@ +[package] +name = "ps-ctl" +description = "Proxy Suite for Windows: proxy-ctl, the command line" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "proxy-ctl" +path = "src/main.rs" + +[dependencies] +ps-core.workspace = true +ps-ipc.workspace = true +anyhow.workspace = true +serde_json.workspace = true +tokio.workspace = true +clap.workspace = true + +[dev-dependencies] +serde_json.workspace = true diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs new file mode 100644 index 0000000..8bdd575 --- /dev/null +++ b/windows/crates/ps-ctl/src/main.rs @@ -0,0 +1,696 @@ +//! proxy-ctl: upstream's command line, over the service's API. + +use std::io::Read; + +use anyhow::{Context, Result, anyhow, bail}; +use clap::{Args, Parser, Subcommand}; +use ps_ipc::transport::{self, Address}; +use ps_ipc::{Request, Response}; +use serde_json::{Value, json}; + +#[derive(Parser)] +#[command(name = "proxy-ctl", version, about = "Control Proxy Suite", disable_help_subcommand = true)] +struct Cli { + /// The service's pipe or socket. + #[arg(long, global = true, value_name = "ADDRESS")] + socket: Option, + /// Print what the service answers, as JSON. + #[arg(long, global = true)] + json: bool, + #[command(subcommand)] + command: Cmd, +} + +#[derive(Subcommand)] +enum Cmd { + /// Services and routing mode. + Status, + /// Restart running services. + Restart { units: Vec }, + /// Show logs (all units, or the ones named); -f follows. + Logs { + units: Vec, + #[arg(short = 'n', long, default_value_t = 100)] + lines: usize, + #[arg(short = 'f', long)] + follow: bool, + }, + /// The local proxy. + Proxy(ProxyArgs), + /// The whole configuration. + Config { + #[command(subcommand)] + verb: ConfigVerb, + }, +} + +#[derive(Subcommand)] +enum ConfigVerb { + /// Print it (secrets hidden without the secrets scope). + Get, + /// Replace it with a file's (or stdin's, with -). + Set { file: String }, + /// Check a file without taking it. + Validate { file: String }, +} + +#[derive(Args)] +struct ProxyArgs { + #[command(subcommand)] + verb: Option, +} + +#[derive(Subcommand)] +enum ProxyVerb { + Status, + On, + Off, + /// Outbounds, their source, and the current pick. + Outbounds { + #[command(subcommand)] + verb: Option, + }, + /// Always use this outbound. + Pin { + tag: String, + #[arg(long = "in", value_name = "GROUP")] + group: Option, + }, + /// Back to automatic selection. + Unpin { + #[arg(long = "in", value_name = "GROUP")] + group: Option, + }, + /// Show or override the routing mode: default, whitelist, blacklist, all-proxy, all-bypass. + Mode { mode: Option }, + /// Subscriptions. + Subs { + #[command(subcommand)] + verb: Option, + }, + /// Routing rules. + Rules { + #[command(subcommand)] + verb: Option, + }, + /// Rule sets: update refetches them. + Rulesets { + #[command(subcommand)] + verb: Option, + }, + /// Global TUN mode. + Tun { + #[command(subcommand)] + verb: Option, + }, + /// The config the backend runs. + Config, +} + +#[derive(Subcommand)] +enum OnOff { + Status, + On, + Off, +} + +#[derive(Subcommand)] +enum OutboundVerb { + List, + /// Add an outbound from a link (- reads it from stdin). + Add { + /// The tag, then the link; or the link alone. + args: Vec, + #[arg(long)] + detour: Option, + }, + Rm { tag: String }, + Disable { tag: String }, + Enable { tag: String }, + /// Delay through each (all, or the named). + Test { tags: Vec }, + /// Its link. + Link { tag: String }, +} + +#[derive(Subcommand)] +enum SubsVerb { + List, + Update { tag: Option }, + /// Add a subscription (no tag: named after its host; - reads the URL from stdin). + Add { args: Vec }, + Rm { tag: String }, +} + +#[derive(Subcommand)] +enum RulesVerb { + List, + /// Send domains, addresses, geosite:x, geoip:x, ruleset:x or process:x.exe to a target. + Add { + target: String, + matches: Vec, + #[arg(long)] + name: Option, + #[arg(long)] + priority: Option, + }, + Rm { name: String }, + Disable { name: String }, + Enable { name: String }, +} + +#[derive(Subcommand)] +enum RulesetsVerb { + List, + Update, +} + +struct Ctl { + addr: Address, + json: bool, +} + +impl Ctl { + async fn call(&self, req: Request) -> Result { + let resp: Response = transport::call(&self.addr, &req).await?; + if !resp.ok { + let mut msg = resp.error.unwrap_or_else(|| "failed".into()); + if let Some(issues) = resp.data.get("issues").and_then(Value::as_array) { + for i in issues { + msg.push_str(&format!("\n {} {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or(""))); + } + } + bail!(msg); + } + Ok(resp.data) + } + + fn print(&self, v: &Value) { + println!("{}", serde_json::to_string_pretty(v).unwrap()); + } + + /// Reads the configuration, lets `edit` change it, writes it back against the revision + /// read; a concurrent change is retried. + async fn edit(&self, edit: impl Fn(&mut Value) -> Result<()>) -> Result { + for _ in 0..3 { + let got = self.call(Request::ConfigGet).await?; + let mut config = got["config"].clone(); + edit(&mut config)?; + match self.call(Request::ConfigSet { config, base: got["revision"].as_u64() }).await { + Err(e) if e.to_string().contains("changed since revision") => continue, + other => { + let r = other?; + for i in r["issues"].as_array().into_iter().flatten() { + eprintln!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or("")); + } + if let Some(e) = r["error"].as_str() { + eprintln!("saved, but not applied: {e}"); + } + return Ok(r); + } + } + } + bail!("the configuration kept changing; try again") + } +} + +fn read_arg(value: &str) -> Result { + if value == "-" { + let mut s = String::new(); + std::io::stdin().read_to_string(&mut s)?; + Ok(s.trim().to_owned()) + } else { + Ok(value.to_owned()) + } +} + +fn read_file_arg(file: &str) -> Result { + let text = if file == "-" { read_arg("-")? } else { std::fs::read_to_string(file).with_context(|| format!("reading {file}"))? }; + serde_json::from_str(&text).with_context(|| format!("{file} is not JSON")) +} + +fn arr<'a>(v: &'a mut Value, path: &[&str]) -> &'a mut Vec { + let mut cur = v; + for p in path { + if cur.get(*p).is_none_or(Value::is_null) { + cur[*p] = if *p == path[path.len() - 1] { json!([]) } else { json!({}) }; + } + cur = cur.get_mut(*p).unwrap(); + } + cur.as_array_mut().expect("a list") +} + +/// A tag for a link without one: its remark, else its host. +fn tag_for(link: &str) -> String { + if let Some((_, remark)) = link.split_once('#') { + let t = ps_core::links::subscription::slugify_tag(&ps_core::links::py::unquote(remark)); + if t != "proxy" { + return t; + } + } + let host = link.split("://").nth(1).unwrap_or("").split(['@']).last().unwrap_or("").split([':', '/', '?', '#']).next().unwrap_or(""); + let t = ps_core::links::subscription::slugify_tag(host); + if t.is_empty() { "outbound".into() } else { t } +} + +/// A rule's matches, sorted into their kinds. +fn sort_matches(matches: &[String]) -> Value { + let mut m = json!({ "domains": [], "ips": [], "geosites": [], "geoips": [], "ruleSets": [], "processNames": [] }); + for x in matches { + let (key, value) = if let Some(v) = x.strip_prefix("geosite:") { + ("geosites", v.to_owned()) + } else if let Some(v) = x.strip_prefix("geoip:") { + ("geoips", v.to_owned()) + } else if let Some(v) = x.strip_prefix("ruleset:") { + ("ruleSets", v.to_owned()) + } else if let Some(v) = x.strip_prefix("process:") { + ("processNames", v.to_owned()) + } else if x.parse::().is_ok() || x.split_once('/').is_some_and(|(a, _)| a.parse::().is_ok()) { + ("ips", x.clone()) + } else { + ("domains", x.trim_start_matches('.').to_lowercase()) + }; + m[key].as_array_mut().unwrap().push(value.into()); + } + m +} + +async fn status(ctl: &Ctl) -> Result<()> { + let s = ctl.call(Request::Status).await?; + if ctl.json { + ctl.print(&s); + return Ok(()); + } + let p = &s["proxy"]; + println!( + "proxy: {} ({}, {}){}", + p["state"].as_str().unwrap_or("?"), + p["backend"].as_str().unwrap_or("?"), + p["listener"].as_str().unwrap_or("?"), + if p["tun"] == true { ", global TUN" } else { "" } + ); + println!( + " selection {}, mode {}{}", + p["selection"].as_str().unwrap_or("?"), + p["mode"].as_str().unwrap_or("default"), + p["pinned"].as_str().map(|t| format!(", pinned to {t}")).unwrap_or_default() + ); + for u in s["units"].as_array().into_iter().flatten() { + println!("{:32} {}", u["name"].as_str().unwrap_or(""), u["state"].as_str().unwrap_or("")); + } + if let Some(e) = s["error"].as_str() { + println!("error: {e}"); + } + for w in s["warnings"].as_array().into_iter().flatten() { + println!("warning: {}", w.as_str().unwrap_or("")); + } + Ok(()) +} + +async fn outbounds(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(OutboundVerb::List) { + OutboundVerb::List => { + let r = ctl.call(Request::Outbounds).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let inv = &r["inventory"]; + let pinned = inv["pinned"].as_str().unwrap_or(""); + for t in inv["tags"].as_array().into_iter().flatten() { + let t = t.as_str().unwrap_or(""); + let mut notes = Vec::new(); + if t == pinned { + notes.push("pinned".to_owned()); + } + if inv["disabled"].as_array().is_some_and(|d| d.iter().any(|x| x == t)) { + notes.push("disabled".into()); + } + if let Some(h) = inv["detours"][t].as_str() { + notes.push(format!("through {h}")); + } + println!("{t:32} {:20} {}", inv["sources"][t].as_str().unwrap_or(""), notes.join(", ")); + } + for (g, info) in inv["groups"].as_object().into_iter().flatten() { + let members: Vec<&str> = info["members"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); + println!("{g:32} {:20} {}", format!("group, {}", info["strategy"].as_str().unwrap_or("")), members.join(" ")); + } + } + OutboundVerb::Add { args, detour } => { + let (tag, link) = match args.as_slice() { + [link] => { + let link = read_arg(link)?; + (tag_for(&link), link) + } + [tag, link] => (tag.clone(), read_arg(link)?), + _ => bail!("usage: proxy outbounds add [tag] "), + }; + if link.trim_start().starts_with('{') { + let json: Value = serde_json::from_str(&link).context("not JSON")?; + let key = if json.get("protocol").is_some() { "xrayJson" } else { "singBoxJson" }; + let tag2 = tag.clone(); + ctl.edit(move |c| { + let list = arr(c, &["proxy", "outbounds"]); + if list.iter().any(|o| o["tag"] == tag2.as_str()) { + bail!("an outbound '{tag2}' exists"); + } + let mut ob = json!({ "tag": tag2, key: json }); + if let Some(d) = &detour { + ob["detour"] = d.clone().into(); + } + list.push(ob); + Ok(()) + }) + .await?; + } else { + // Checked here first: the service would only say the outbound was left out. + ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::SingBox) + .or_else(|_| ps_core::links::build_outbound(&link, &tag, ps_core::links::LinkBackend::Xray)) + .map_err(|e| anyhow!("{e}"))?; + let tag2 = tag.clone(); + ctl.edit(move |c| { + let list = arr(c, &["proxy", "outbounds"]); + if list.iter().any(|o| o["tag"] == tag2.as_str()) { + bail!("an outbound '{tag2}' exists"); + } + let mut ob = json!({ "tag": tag2, "url": link }); + if let Some(d) = &detour { + ob["detour"] = d.clone().into(); + } + list.push(ob); + Ok(()) + }) + .await?; + } + println!("added {tag}"); + } + OutboundVerb::Rm { tag } => { + ctl.edit(|c| { + let list = arr(c, &["proxy", "outbounds"]); + let before = list.len(); + list.retain(|o| o["tag"] != tag.as_str()); + if list.len() == before { + bail!("no outbound '{tag}' in the configuration"); + } + Ok(()) + }) + .await?; + println!("removed {tag}"); + } + OutboundVerb::Disable { tag } => { + ctl.call(Request::Disable { tag, disabled: true }).await?; + } + OutboundVerb::Enable { tag } => { + ctl.call(Request::Disable { tag, disabled: false }).await?; + } + OutboundVerb::Test { tags } => { + let r = ctl.call(Request::Test { tags }).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + for t in r.as_array().into_iter().flatten() { + match t["delay"].as_u64() { + Some(d) => println!("{:32} {d} ms", t["tag"].as_str().unwrap_or("")), + None => println!("{:32} {}", t["tag"].as_str().unwrap_or(""), t["error"].as_str().unwrap_or("failed")), + } + } + } + OutboundVerb::Link { tag } => { + let r = ctl.call(Request::Outbounds).await?; + match r["inventory"]["links"][&tag].as_str() { + Some(l) => println!("{l}"), + None => bail!("no link for '{tag}' (it has none, or you lack the secrets scope)"), + } + } + } + Ok(()) +} + +async fn subs(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(SubsVerb::List) { + SubsVerb::List => { + let c = ctl.call(Request::ConfigGet).await?; + for s in c["config"]["proxy"]["subscriptions"].as_array().into_iter().flatten() { + println!("{}", s["tag"].as_str().unwrap_or("")); + } + } + SubsVerb::Update { tag } => { + let r = ctl.call(Request::SubsUpdate { tag }).await?; + for s in r.as_array().into_iter().flatten() { + match s["links"].as_u64() { + Some(n) => println!("{}: {n} links", s["tag"].as_str().unwrap_or("")), + None => println!("{}: {}", s["tag"].as_str().unwrap_or(""), s["error"].as_str().unwrap_or("failed")), + } + } + } + SubsVerb::Add { args } => { + let (tag, url) = match args.as_slice() { + [url] => { + let url = read_arg(url)?; + let host = ps_core::links::subscription::url_parts::split(&url).ok().and_then(|u| u.hostname).unwrap_or_else(|| "sub".into()); + (ps_core::links::subscription::slugify_tag(&host), url) + } + [tag, url] => (tag.clone(), read_arg(url)?), + _ => bail!("usage: proxy subs add [tag] "), + }; + let tag2 = tag.clone(); + ctl.edit(move |c| { + let list = arr(c, &["proxy", "subscriptions"]); + if list.iter().any(|s| s["tag"] == tag2.as_str()) { + bail!("a subscription '{tag2}' exists"); + } + list.push(json!({ "tag": tag2, "url": url })); + Ok(()) + }) + .await?; + println!("added {tag}; fetching it"); + } + SubsVerb::Rm { tag } => { + ctl.edit(|c| { + let list = arr(c, &["proxy", "subscriptions"]); + let before = list.len(); + list.retain(|s| s["tag"] != tag.as_str()); + if list.len() == before { + bail!("no subscription '{tag}'"); + } + Ok(()) + }) + .await?; + } + } + Ok(()) +} + +async fn rules(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(RulesVerb::List) { + RulesVerb::List => { + let c = ctl.call(Request::ConfigGet).await?; + for (i, r) in c["config"]["proxy"]["routing"]["rules"].as_array().into_iter().flatten().enumerate() { + let name = r["name"].as_str().map(str::to_owned).unwrap_or_else(|| format!("#{i}")); + let mut matches = Vec::new(); + for (k, prefix) in [("domains", ""), ("ips", ""), ("geosites", "geosite:"), ("geoips", "geoip:"), ("ruleSets", "ruleset:"), ("processNames", "process:")] { + for v in r[k].as_array().into_iter().flatten() { + matches.push(format!("{prefix}{}", v.as_str().unwrap_or(""))); + } + } + println!( + "{:4} {:20} -> {:16} {}{}", + r["priority"].as_i64().unwrap_or(100), + name, + r["outbound"].as_str().unwrap_or(""), + matches.join(" "), + if r["disabled"] == true { " (disabled)" } else { "" } + ); + } + } + RulesVerb::Add { target, matches, name, priority } => { + if matches.is_empty() { + bail!("usage: proxy rules add "); + } + let m = sort_matches(&matches); + let name = name.unwrap_or_else(|| target.clone()); + ctl.edit(|c| { + let list = arr(c, &["proxy", "routing", "rules"]); + // No --name: the rule named after the target, extended. + if let Some(rule) = list.iter_mut().find(|r| r["name"] == name.as_str()) { + for (k, v) in m.as_object().unwrap() { + let have = rule[k.as_str()].as_array().cloned().unwrap_or_default(); + let mut merged = have; + for x in v.as_array().unwrap() { + if !merged.contains(x) { + merged.push(x.clone()); + } + } + rule[k.as_str()] = Value::Array(merged); + } + rule["outbound"] = target.clone().into(); + if let Some(p) = priority { + rule["priority"] = p.into(); + } + } else { + let mut rule = m.clone(); + rule["name"] = name.clone().into(); + rule["outbound"] = target.clone().into(); + rule["priority"] = priority.unwrap_or(50).into(); + list.push(rule); + } + Ok(()) + }) + .await?; + } + RulesVerb::Rm { name } => { + ctl.edit(|c| { + let list = arr(c, &["proxy", "routing", "rules"]); + let before = list.len(); + list.retain(|r| r["name"] != name.as_str()); + if list.len() == before { + bail!("no rule named '{name}'"); + } + Ok(()) + }) + .await?; + } + RulesVerb::Disable { name } | RulesVerb::Enable { name } if name.is_empty() => bail!("a rule name"), + RulesVerb::Disable { name } => set_rule_disabled(ctl, &name, true).await?, + RulesVerb::Enable { name } => set_rule_disabled(ctl, &name, false).await?, + } + Ok(()) +} + +async fn set_rule_disabled(ctl: &Ctl, name: &str, disabled: bool) -> Result<()> { + ctl.edit(|c| { + let list = arr(c, &["proxy", "routing", "rules"]); + let rule = list.iter_mut().find(|r| r["name"] == name).ok_or_else(|| anyhow!("no rule named '{name}'"))?; + rule["disabled"] = disabled.into(); + Ok(()) + }) + .await?; + Ok(()) +} + +async fn proxy(ctl: &Ctl, verb: Option) -> Result<()> { + match verb.unwrap_or(ProxyVerb::Status) { + ProxyVerb::Status => status(ctl).await?, + ProxyVerb::On => { + ctl.edit(|c| { + c["proxy"]["enable"] = true.into(); + Ok(()) + }) + .await?; + ctl.call(Request::Start { unit: "proxy-suite-socks".into() }).await?; + } + ProxyVerb::Off => { + ctl.call(Request::Stop { unit: "proxy-suite-socks".into() }).await?; + } + ProxyVerb::Outbounds { verb } => outbounds(ctl, verb).await?, + ProxyVerb::Pin { tag, group } => { + ctl.call(Request::Pin { tag: Some(tag), group }).await?; + } + ProxyVerb::Unpin { group } => { + ctl.call(Request::Pin { tag: None, group }).await?; + } + ProxyVerb::Mode { mode: None } => { + let s = ctl.call(Request::Status).await?; + println!("{}", s["proxy"]["mode"].as_str().unwrap_or("default")); + } + ProxyVerb::Mode { mode } => { + ctl.call(Request::Mode { mode }).await?; + } + ProxyVerb::Subs { verb } => subs(ctl, verb).await?, + ProxyVerb::Rules { verb } => rules(ctl, verb).await?, + ProxyVerb::Rulesets { verb } => match verb.unwrap_or(RulesetsVerb::List) { + RulesetsVerb::List => { + let c = ctl.call(Request::ConfigGet).await?; + for (name, rs) in c["config"]["proxy"]["routing"]["ruleSets"].as_object().into_iter().flatten() { + println!("{name:24} {}", rs["url"].as_str().unwrap_or("")); + } + } + RulesetsVerb::Update => { + let r = ctl.call(Request::RuleSetsUpdate).await?; + for x in r.as_array().into_iter().flatten() { + println!("{:32} {}", x["tag"].as_str().unwrap_or(""), x["error"].as_str().unwrap_or("ok")); + } + } + }, + ProxyVerb::Tun { verb } => match verb.unwrap_or(OnOff::Status) { + OnOff::Status => { + let s = ctl.call(Request::Status).await?; + println!("{}", if s["proxy"]["tun"] == true { "on" } else { "off" }); + } + OnOff::On => { + ctl.call(Request::Start { unit: "proxy-suite-tun".into() }).await?; + } + OnOff::Off => { + ctl.call(Request::Stop { unit: "proxy-suite-tun".into() }).await?; + } + }, + ProxyVerb::Config => ctl.print(&ctl.call(Request::RenderedConfig).await?), + } + Ok(()) +} + +async fn real_main() -> Result<()> { + let cli = Cli::parse(); + let addr = match cli.socket { + Some(s) if cfg!(windows) => Address::Pipe(s), + Some(s) => Address::Unix(s.into()), + None => Address::default_for_platform(), + }; + let ctl = Ctl { addr, json: cli.json }; + match cli.command { + Cmd::Status => status(&ctl).await?, + Cmd::Restart { units } => { + ctl.call(Request::Restart { units }).await?; + } + Cmd::Logs { units, lines, follow } => { + let unit = units.first().cloned(); + let print = |r: Response| { + if let Some(arr) = r.data.as_array() { + for l in arr { + println!("{}: {}", l["unit"].as_str().unwrap_or(""), l["line"].as_str().unwrap_or("")); + } + } else if r.data.is_object() { + println!("{}: {}", r.data["unit"].as_str().unwrap_or(""), r.data["line"].as_str().unwrap_or("")); + } + true + }; + if follow { + transport::stream(&ctl.addr, &Request::Logs { unit, lines, follow: true }, print).await?; + } else { + print(transport::call(&ctl.addr, &Request::Logs { unit, lines, follow: false }).await?); + } + } + Cmd::Proxy(p) => proxy(&ctl, p.verb).await?, + Cmd::Config { verb } => match verb { + ConfigVerb::Get => { + let c = ctl.call(Request::ConfigGet).await?; + ctl.print(&c["config"]); + } + ConfigVerb::Set { file } => { + let config = read_file_arg(&file)?; + let r = ctl.call(Request::ConfigSet { config, base: None }).await?; + println!("revision {}", r["revision"]); + } + ConfigVerb::Validate { file } => { + let r = ctl.call(Request::ConfigValidate { config: read_file_arg(&file)? }).await?; + let issues = r["issues"].as_array().cloned().unwrap_or_default(); + if issues.is_empty() { + println!("valid"); + } + for i in issues { + println!("{}: {}: {}", i["severity"].as_str().unwrap_or(""), i["path"].as_str().unwrap_or(""), i["message"].as_str().unwrap_or("")); + } + } + }, + } + Ok(()) +} + +fn main() { + let rt = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime"); + if let Err(e) = rt.block_on(real_main()) { + eprintln!("proxy-ctl: {e}"); + std::process::exit(1); + } +} diff --git a/windows/crates/ps-ctl/tests/e2e.rs b/windows/crates/ps-ctl/tests/e2e.rs new file mode 100644 index 0000000..4179768 --- /dev/null +++ b/windows/crates/ps-ctl/tests/e2e.rs @@ -0,0 +1,189 @@ +//! The whole stack, offline: a sing-box Shadowsocks server and a small web server on +//! loopback, the service in console mode with a fresh state directory, proxy-ctl adding the +//! server as an outbound, and a page fetched through the local proxy. +//! +//! Needs sing-box on PATH (the dev shell has it); skipped otherwise. Unix only: the Windows +//! side of the transport is a named pipe. + +#![cfg(unix)] + +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::path::{Path, PathBuf}; +use std::process::{Child, Command, Stdio}; +use std::time::{Duration, Instant}; + +const KEY: &str = "a2tra2tra2tra2tra2traw=="; // base64 of 16 'k's + +fn free_port() -> u16 { + TcpListener::bind("127.0.0.1:0").unwrap().local_addr().unwrap().port() +} + +struct Kill(Child); +impl Drop for Kill { + fn drop(&mut self) { + let _ = self.0.kill(); + let _ = self.0.wait(); + } +} + +fn service_binary() -> PathBuf { + let ctl = PathBuf::from(env!("CARGO_BIN_EXE_proxy-ctl")); + let dir = ctl.parent().unwrap(); + let status = Command::new(env!("CARGO")) + .args(["build", "-q", "-p", "ps-service", "--bin", "proxy-suite-service"]) + .status() + .unwrap(); + assert!(status.success()); + dir.join("proxy-suite-service") +} + +fn ctl(socket: &Path, args: &[&str]) -> (bool, String) { + let out = Command::new(env!("CARGO_BIN_EXE_proxy-ctl")).arg("--socket").arg(socket).args(args).output().unwrap(); + (out.status.success(), format!("{}{}", String::from_utf8_lossy(&out.stdout), String::from_utf8_lossy(&out.stderr))) +} + +/// GET http://:/ through a SOCKS5 proxy, with the name resolved by the proxy. +fn socks_get(proxy: u16, host: &str, port: u16) -> std::io::Result { + let mut s = TcpStream::connect(("127.0.0.1", proxy))?; + s.set_read_timeout(Some(Duration::from_secs(10)))?; + s.write_all(&[5, 1, 0])?; + let mut buf = [0u8; 2]; + s.read_exact(&mut buf)?; + let mut req = vec![5, 1, 0, 3, host.len() as u8]; + req.extend_from_slice(host.as_bytes()); + req.extend_from_slice(&port.to_be_bytes()); + s.write_all(&req)?; + let mut reply = [0u8; 10]; + s.read_exact(&mut reply)?; + if reply[1] != 0 { + return Err(std::io::Error::other(format!("SOCKS reply {}", reply[1]))); + } + s.write_all(format!("GET / HTTP/1.0\r\nHost: {host}\r\n\r\n").as_bytes())?; + let mut body = String::new(); + s.read_to_string(&mut body)?; + Ok(body) +} + +fn wait_for(what: &str, timeout: Duration, mut check: impl FnMut() -> bool) { + let start = Instant::now(); + while start.elapsed() < timeout { + if check() { + return; + } + std::thread::sleep(Duration::from_millis(250)); + } + panic!("timed out waiting for {what}"); +} + +#[test] +fn a_page_through_the_whole_stack() { + if Command::new("sing-box").arg("version").output().is_err() { + eprintln!("sing-box is not on PATH: skipping"); + return; + } + let dir = std::env::temp_dir().join(format!("ps-e2e-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let (ss_port, web_port, proxy_port, clash_port, test_port) = (free_port(), free_port(), free_port(), free_port(), free_port()); + + // The web server. + let web = TcpListener::bind(("127.0.0.1", web_port)).unwrap(); + std::thread::spawn(move || { + for mut s in web.incoming().flatten() { + let mut buf = [0u8; 1024]; + let _ = s.read(&mut buf); + let _ = s.write_all(b"HTTP/1.0 200 OK\r\nContent-Length: 19\r\n\r\nhello-through-proxy"); + } + }); + + // The Shadowsocks server, which knows web.test as loopback. + let server_cfg = serde_json::json!({ + "log": { "level": "warn" }, + "dns": { "servers": [{ "type": "hosts", "tag": "hosts", "predefined": { "web.test": ["127.0.0.1"] } }] }, + "inbounds": [{ "type": "shadowsocks", "tag": "ss-in", "listen": "127.0.0.1", "listen_port": ss_port, + "method": "2022-blake3-aes-128-gcm", "password": KEY }], + "outbounds": [{ "type": "direct", "tag": "direct" }], + "route": { "default_domain_resolver": "hosts", "final": "direct" }, + }); + std::fs::write(dir.join("server.json"), server_cfg.to_string()).unwrap(); + let _server = Kill(Command::new("sing-box").args(["run", "-c"]).arg(dir.join("server.json")).stderr(Stdio::null()).spawn().unwrap()); + + // The service, with no outbound yet and nothing to download. + let state = dir.join("state"); + std::fs::create_dir_all(&state).unwrap(); + let config = serde_json::json!({ + "proxy": { + "enable": true, + "listener": { "port": proxy_port }, + "singBox": { "clashApiPort": clash_port, "testPort": test_port }, + "routing": { "directRu": false }, + }, + }); + std::fs::write(state.join("config.json"), config.to_string()).unwrap(); + let socket = dir.join("api.sock"); + let _service = Kill( + Command::new(service_binary()) + .args(["--console", "--state-dir"]) + .arg(&state) + .arg("--socket") + .arg(&socket) + .stderr(std::fs::File::create(dir.join("service.log")).unwrap()) + .spawn() + .unwrap(), + ); + wait_for("the service's API", Duration::from_secs(10), || ctl(&socket, &["status"]).0); + + // proxy-ctl adds the server; the service renders, checks and starts sing-box. + let link = format!("ss://2022-blake3-aes-128-gcm:{}@127.0.0.1:{ss_port}#Test%20Server", KEY.replace('=', "%3D")); + let (ok, out) = ctl(&socket, &["proxy", "outbounds", "add", &link]); + assert!(ok, "{out}"); + assert!(out.contains("added Test-Server"), "{out}"); + let start = Instant::now(); + while !ctl(&socket, &["status"]).1.contains("proxy: active") { + if start.elapsed() > Duration::from_secs(15) { + panic!( + "the proxy did not come up\nstatus:\n{}\nlogs:\n{}\nservice:\n{}", + ctl(&socket, &["status"]).1, + ctl(&socket, &["logs", "-n", "60"]).1, + std::fs::read_to_string(dir.join("service.log")).unwrap_or_default() + ); + } + std::thread::sleep(Duration::from_millis(250)); + } + + let body = (0..20) + .find_map(|_| { + std::thread::sleep(Duration::from_millis(300)); + socks_get(proxy_port, "web.test", web_port).ok() + }) + .unwrap_or_else(|| { + panic!( + "no page through the proxy\nservice log:\n{}\nunit log:\n{}", + std::fs::read_to_string(dir.join("service.log")).unwrap_or_default(), + ctl(&socket, &["logs", "-n", "50"]).1 + ) + }); + assert!(body.ends_with("hello-through-proxy"), "{body}"); + + // The inventory, a pin, and a route mode that sends everything direct, where web.test + // does not resolve. + let (_, list) = ctl(&socket, &["proxy", "outbounds"]); + assert!(list.contains("Test-Server") && list.contains("static"), "{list}"); + assert!(ctl(&socket, &["proxy", "pin", "Test-Server"]).0); + assert!(ctl(&socket, &["status"]).1.contains("pinned to Test-Server")); + assert!(ctl(&socket, &["proxy", "mode", "all-bypass"]).0); + std::thread::sleep(Duration::from_secs(2)); + assert!(socks_get(proxy_port, "web.test", web_port).map_or(true, |b| !b.ends_with("hello-through-proxy"))); + assert!(ctl(&socket, &["proxy", "mode", "default"]).0); + + // A bad edit is refused and changes nothing. + let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "nowhere-real", "example.com"]); + assert!(!ok && out.contains("is not an outbound"), "{out}"); + assert!(!ctl(&socket, &["proxy", "rules"]).1.contains("nowhere-real")); + // A good one goes in. + let (ok, out) = ctl(&socket, &["proxy", "rules", "add", "Test-Server", "example.com", "geoip:us", "process:Telegram.exe"]); + assert!(ok, "{out}"); + assert!(ctl(&socket, &["proxy", "rules"]).1.contains("process:Telegram.exe")); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/windows/crates/ps-ipc/Cargo.toml b/windows/crates/ps-ipc/Cargo.toml new file mode 100644 index 0000000..19b7fcb --- /dev/null +++ b/windows/crates/ps-ipc/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "ps-ipc" +description = "Proxy Suite for Windows: the service's API and its transport" +version.workspace = true +edition.workspace = true +license.workspace = true + +[dependencies] +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +thiserror.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_Security_Authorization", + "Win32_System_Pipes", + "Win32_System_Threading", + "Win32_System_SystemServices", +] } + +[dev-dependencies] +tokio = { workspace = true } diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs new file mode 100644 index 0000000..f12b83d --- /dev/null +++ b/windows/crates/ps-ipc/src/lib.rs @@ -0,0 +1,115 @@ +//! The service's API: what proxy-ctl and the app ask, what it answers, and how the two +//! reach each other. One JSON request per line, answered by one JSON response per line (a +//! log follow answers with many, up to a final one). +//! +//! On Windows the transport is the named pipe `\\.\pipe\proxy-suite`, whose security +//! descriptor admits SYSTEM, Administrators and (with `userControl`) the interactive user. +//! Elsewhere it is a Unix socket, so the whole stack runs on Linux for development. + +pub mod transport; + +use serde::{Deserialize, Serialize}; +use serde_json::Value; + +/// The pipe on Windows. +pub const PIPE_NAME: &str = r"\\.\pipe\proxy-suite"; + +/// Who is asking, as the transport established it (never as the client claims). +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +pub struct Peer { + /// An administrator (elevated on Windows, root elsewhere): every scope, and the + /// admin-only options. + pub admin: bool, + /// The account, for the log. + pub user: String, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +#[serde(tag = "op", rename_all = "kebab-case")] +pub enum Request { + /// Units, their state, the proxy's mode. + Status, + /// The configuration. Secrets (links, passwords) need the `secrets` scope. + ConfigGet, + /// Replaces the whole configuration, if it is valid and `base` (a revision from + /// `config-get`) is still current. + ConfigSet { config: Value, base: Option }, + /// Checks a configuration without taking it. + ConfigValidate { config: Value }, + /// Runtime state: pins, disabled outbounds, the route mode. + StateGet, + Pin { tag: Option, group: Option }, + Disable { tag: String, disabled: bool }, + Mode { mode: Option }, + /// What the proxy runs: tags, sources, groups, the pick. + Outbounds, + /// The backend configs as rendered last. Secrets scope. + RenderedConfig, + Restart { units: Vec }, + Start { unit: String }, + Stop { unit: String }, + /// The last `lines` of a unit's log (every unit's, interleaved, without one); `follow` + /// keeps the answer open with each new line. + Logs { unit: Option, lines: usize, follow: bool }, + /// Refetch subscriptions (all, or one). + SubsUpdate { tag: Option }, + /// Refetch rule sets and geodata. + RuleSetsUpdate, + /// Latency of outbounds through the Clash API. + Test { tags: Vec }, + /// Components: what is installed, what the manifest wants. + Components, + /// Fetch and install components (all wanted, or the named ones). + ComponentsInstall { names: Vec }, +} + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +pub struct Response { + pub ok: bool, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub error: Option, + #[serde(default, skip_serializing_if = "Value::is_null")] + pub data: Value, + /// More responses follow (a log follow). + #[serde(default, skip_serializing_if = "std::ops::Not::not")] + pub more: bool, +} + +impl Response { + pub fn ok(data: Value) -> Self { + Self { ok: true, error: None, data, more: false } + } + + pub fn err(message: impl Into) -> Self { + Self { ok: false, error: Some(message.into()), data: Value::Null, more: false } + } + + pub fn partial(data: Value) -> Self { + Self { ok: true, error: None, data, more: true } + } +} + +#[derive(Debug, thiserror::Error)] +pub enum IpcError { + #[error("cannot reach the Proxy Suite service ({0}); is it running?")] + Connect(std::io::Error), + #[error("the service closed the connection")] + Closed, + #[error("{0}")] + Io(#[from] std::io::Error), + #[error("bad message: {0}")] + Json(#[from] serde_json::Error), +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn requests_read_as_upstream_verbs() { + let r: Request = serde_json::from_str(r#"{"op":"pin","tag":"nl","group":null}"#).unwrap(); + assert_eq!(r, Request::Pin { tag: Some("nl".into()), group: None }); + let s = serde_json::to_string(&Request::Logs { unit: None, lines: 50, follow: true }).unwrap(); + assert_eq!(s, r#"{"op":"logs","unit":null,"lines":50,"follow":true}"#); + } +} diff --git a/windows/crates/ps-ipc/src/transport.rs b/windows/crates/ps-ipc/src/transport.rs new file mode 100644 index 0000000..ef06996 --- /dev/null +++ b/windows/crates/ps-ipc/src/transport.rs @@ -0,0 +1,326 @@ +//! Line-delimited JSON over a named pipe (Windows) or a Unix socket (elsewhere). + +use std::path::PathBuf; + +use serde::Serialize; +use serde::de::DeserializeOwned; +use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, BufReader, ReadHalf, WriteHalf}; + +use crate::{IpcError, Peer, Request, Response}; + +/// Where the service listens. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Address { + Pipe(String), + Unix(PathBuf), +} + +impl Address { + /// `PROXY_SUITE_SOCKET` if set, else the platform's default. + pub fn default_for_platform() -> Self { + if let Ok(s) = std::env::var("PROXY_SUITE_SOCKET") { + return if cfg!(windows) { Address::Pipe(s) } else { Address::Unix(s.into()) }; + } + if cfg!(windows) { + Address::Pipe(crate::PIPE_NAME.into()) + } else { + Address::Unix(std::env::temp_dir().join("proxy-suite.sock")) + } + } +} + +trait Stream: AsyncRead + AsyncWrite + Send + Unpin + 'static {} +impl Stream for T {} + +/// One connection, either end. +pub struct Conn { + reader: BufReader>>, + writer: WriteHalf>, + identity: Identity, +} + +enum Identity { + Client, + #[cfg(unix)] + Unix(Option), + #[cfg(windows)] + Pipe(isize), +} + +impl Conn { + fn new(stream: Box, identity: Identity) -> Self { + let (r, w) = tokio::io::split(stream); + Self { reader: BufReader::new(r), writer: w, identity } + } + + /// The next message, or `None` once the other end closed. + pub async fn read_json(&mut self) -> Result, IpcError> { + let mut line = String::new(); + // A request is a configuration at most: 16 MiB is far past any. + let n = (&mut self.reader).take(16 * 1024 * 1024).read_line(&mut line).await?; + if n == 0 { + return Ok(None); + } + Ok(Some(serde_json::from_str(line.trim_end())?)) + } + + pub async fn write_json(&mut self, value: &T) -> Result<(), IpcError> { + let mut line = serde_json::to_vec(value)?; + line.push(b'\n'); + self.writer.write_all(&line).await?; + self.writer.flush().await?; + Ok(()) + } + + /// Who the other end is. On Windows the client must have sent its first message: only + /// then can the server impersonate it. + pub fn peer(&self) -> Peer { + match &self.identity { + Identity::Client => Peer { admin: false, user: "client".into() }, + #[cfg(unix)] + Identity::Unix(uid) => Peer { + admin: *uid == Some(0), + user: uid.map_or_else(|| "unknown".into(), |u| format!("uid {u}")), + }, + #[cfg(windows)] + Identity::Pipe(handle) => windows::peer(*handle), + } + } +} + +/// The listening end. +pub struct Server { + #[cfg(unix)] + listener: tokio::net::UnixListener, + #[cfg(windows)] + next: tokio::net::windows::named_pipe::NamedPipeServer, + #[cfg(windows)] + name: String, + #[cfg(windows)] + sddl: String, +} + +impl Server { + /// Listens on `address`. `interactive`: whether signed-in users may connect, besides + /// SYSTEM and Administrators (`userControl.enable`); on Unix the socket's mode does it. + pub fn bind(address: &Address, interactive: bool) -> std::io::Result { + match address { + #[cfg(unix)] + Address::Unix(path) => { + use std::os::unix::fs::PermissionsExt; + let _ = std::fs::remove_file(path); + let listener = tokio::net::UnixListener::bind(path)?; + std::fs::set_permissions(path, std::fs::Permissions::from_mode(if interactive { 0o666 } else { 0o600 }))?; + Ok(Self { listener }) + } + #[cfg(windows)] + Address::Pipe(name) => { + let sddl = windows::sddl(interactive); + let next = windows::create(name, &sddl, true)?; + Ok(Self { next, name: name.clone(), sddl }) + } + #[allow(unreachable_patterns)] + _ => Err(std::io::Error::new(std::io::ErrorKind::Unsupported, "this address does not exist on this platform")), + } + } + + pub async fn accept(&mut self) -> std::io::Result { + #[cfg(unix)] + { + let (stream, _) = self.listener.accept().await?; + let uid = stream.peer_cred().ok().map(|c| c.uid()); + Ok(Conn::new(Box::new(stream), Identity::Unix(uid))) + } + #[cfg(windows)] + { + use std::os::windows::io::AsRawHandle; + self.next.connect().await?; + let connected = std::mem::replace(&mut self.next, windows::create(&self.name, &self.sddl, false)?); + let handle = connected.as_raw_handle() as isize; + Ok(Conn::new(Box::new(connected), Identity::Pipe(handle))) + } + } +} + +pub async fn connect(address: &Address) -> Result { + match address { + #[cfg(unix)] + Address::Unix(path) => { + let stream = tokio::net::UnixStream::connect(path).await.map_err(IpcError::Connect)?; + Ok(Conn::new(Box::new(stream), Identity::Client)) + } + #[cfg(windows)] + Address::Pipe(name) => { + use tokio::net::windows::named_pipe::ClientOptions; + let client = loop { + match ClientOptions::new().open(name) { + Ok(c) => break c, + // Every instance busy: the next is a moment away. + Err(e) if e.raw_os_error() == Some(231) => tokio::time::sleep(std::time::Duration::from_millis(50)).await, + Err(e) => return Err(IpcError::Connect(e)), + } + }; + Ok(Conn::new(Box::new(client), Identity::Client)) + } + #[allow(unreachable_patterns)] + _ => Err(IpcError::Connect(std::io::Error::new(std::io::ErrorKind::Unsupported, "no such transport here"))), + } +} + +/// One request, its one answer. +pub async fn call(address: &Address, request: &Request) -> Result { + let mut conn = connect(address).await?; + conn.write_json(request).await?; + conn.read_json().await?.ok_or(IpcError::Closed) +} + +/// One request, every answer until the last (a log follow), each handed to `each`. +pub async fn stream(address: &Address, request: &Request, mut each: impl FnMut(Response) -> bool) -> Result<(), IpcError> { + let mut conn = connect(address).await?; + conn.write_json(request).await?; + while let Some(response) = conn.read_json::().await? { + let more = response.more; + if !each(response) || !more { + break; + } + } + Ok(()) +} + +#[cfg(windows)] +mod windows { + use std::ffi::c_void; + use std::ptr::null_mut; + + use tokio::net::windows::named_pipe::{NamedPipeServer, ServerOptions}; + use windows_sys::Win32::Foundation::{CloseHandle, FALSE, HANDLE, LocalFree, TRUE}; + use windows_sys::Win32::Security::Authorization::{ + ConvertStringSecurityDescriptorToSecurityDescriptorW, SDDL_REVISION_1, + }; + use windows_sys::Win32::Security::{ + CheckTokenMembership, CreateWellKnownSid, GetTokenInformation, LookupAccountSidW, RevertToSelf, + SECURITY_ATTRIBUTES, SID_NAME_USE, TOKEN_QUERY, TOKEN_USER, TokenUser, WinBuiltinAdministratorsSid, + }; + use windows_sys::Win32::System::Pipes::ImpersonateNamedPipeClient; + use windows_sys::Win32::System::Threading::{GetCurrentThread, OpenThreadToken}; + + use crate::Peer; + + /// SYSTEM and Administrators get everything; the interactive user read and write. + pub fn sddl(interactive: bool) -> String { + let mut s = String::from("D:P(A;;GA;;;SY)(A;;GA;;;BA)"); + if interactive { + s.push_str("(A;;GRGW;;;IU)"); + } + s + } + + fn wide(s: &str) -> Vec { + s.encode_utf16().chain(std::iter::once(0)).collect() + } + + pub fn create(name: &str, sddl: &str, first: bool) -> std::io::Result { + let sddl_w = wide(sddl); + let mut descriptor: *mut c_void = null_mut(); + // SAFETY: a NUL-terminated string in, a descriptor LocalFree'd below out. + let ok = unsafe { + ConvertStringSecurityDescriptorToSecurityDescriptorW(sddl_w.as_ptr(), SDDL_REVISION_1, &mut descriptor, null_mut()) + }; + if ok == 0 { + return Err(std::io::Error::last_os_error()); + } + let mut attrs = SECURITY_ATTRIBUTES { + nLength: std::mem::size_of::() as u32, + lpSecurityDescriptor: descriptor, + bInheritHandle: FALSE, + }; + // SAFETY: attrs and the descriptor it points at outlive the call. + let server = unsafe { + ServerOptions::new() + // The first instance: nobody else may have made the pipe first (squatting). + .first_pipe_instance(first) + .reject_remote_clients(true) + .create_with_security_attributes_raw(name, &mut attrs as *mut _ as *mut c_void) + }; + // SAFETY: allocated by ConvertStringSecurityDescriptorToSecurityDescriptorW. + unsafe { LocalFree(descriptor) }; + server + } + + /// The client of the pipe, impersonated to read its token: an administrator only when + /// its token holds Administrators enabled (elevated), never as it claims. + pub fn peer(pipe: isize) -> Peer { + let unknown = Peer { admin: false, user: "unknown".into() }; + // SAFETY: the pipe handle is live for the connection; the impersonation is undone + // before anything else runs on this thread. + unsafe { + if ImpersonateNamedPipeClient(pipe as HANDLE) == 0 { + return unknown; + } + let mut token: HANDLE = null_mut(); + let opened = OpenThreadToken(GetCurrentThread(), TOKEN_QUERY, TRUE, &mut token); + RevertToSelf(); + if opened == 0 { + return unknown; + } + let mut sid = [0u8; 68]; + let mut size = sid.len() as u32; + let mut admin = 0; + if CreateWellKnownSid(WinBuiltinAdministratorsSid, null_mut(), sid.as_mut_ptr() as *mut c_void, &mut size) != 0 { + CheckTokenMembership(token, sid.as_mut_ptr() as *mut c_void, &mut admin); + } + let user = token_user(token).unwrap_or_else(|| "unknown".into()); + CloseHandle(token); + Peer { admin: admin != 0, user } + } + } + + unsafe fn token_user(token: HANDLE) -> Option { + let mut buf = vec![0u8; 256]; + let mut len = 0u32; + // SAFETY: buf is as long as said. + if unsafe { GetTokenInformation(token, TokenUser, buf.as_mut_ptr() as *mut c_void, buf.len() as u32, &mut len) } == 0 { + return None; + } + let user = unsafe { &*(buf.as_ptr() as *const TOKEN_USER) }; + let mut name = vec![0u16; 256]; + let mut domain = vec![0u16; 256]; + let (mut nlen, mut dlen) = (name.len() as u32, domain.len() as u32); + let mut kind: SID_NAME_USE = 0; + // SAFETY: the SID points into buf, which is alive; the buffers are as long as said. + let ok = unsafe { + LookupAccountSidW(null_mut(), user.User.Sid, name.as_mut_ptr(), &mut nlen, domain.as_mut_ptr(), &mut dlen, &mut kind) + }; + if ok == 0 { + return None; + } + let name = String::from_utf16_lossy(&name[..nlen as usize]); + let domain = String::from_utf16_lossy(&domain[..dlen as usize]); + Some(if domain.is_empty() { name } else { format!("{domain}\\{name}") }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[cfg(unix)] + #[tokio::test] + async fn a_round_trip_over_a_socket() { + let path = std::env::temp_dir().join(format!("ps-ipc-test-{}.sock", std::process::id())); + let address = Address::Unix(path.clone()); + let mut server = Server::bind(&address, true).unwrap(); + let handle = tokio::spawn(async move { + let mut conn = server.accept().await.unwrap(); + let req: Request = conn.read_json().await.unwrap().unwrap(); + let peer = conn.peer(); + conn.write_json(&Response::ok(serde_json::json!({ "echo": req, "uid": peer.user }))).await.unwrap(); + }); + let resp = call(&address, &Request::Status).await.unwrap(); + assert!(resp.ok); + assert_eq!(resp.data["echo"]["op"], "status"); + assert!(resp.data["uid"].as_str().unwrap().starts_with("uid ")); + handle.await.unwrap(); + let _ = std::fs::remove_file(path); + } +} diff --git a/windows/crates/ps-service/Cargo.toml b/windows/crates/ps-service/Cargo.toml new file mode 100644 index 0000000..01dc2a4 --- /dev/null +++ b/windows/crates/ps-service/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "ps-service" +description = "Proxy Suite for Windows: the service that runs the backends" +version.workspace = true +edition.workspace = true +license.workspace = true + +[[bin]] +name = "proxy-suite-service" +path = "src/main.rs" + +[dependencies] +ps-core.workspace = true +ps-ipc.workspace = true +anyhow.workspace = true +serde.workspace = true +serde_json.workspace = true +tokio.workspace = true +clap.workspace = true +reqwest.workspace = true +rustls.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true +rand.workspace = true +sha2.workspace = true +zip.workspace = true + +[target.'cfg(windows)'.dependencies] +windows-service.workspace = true +windows-sys = { workspace = true, features = [ + "Win32_Foundation", + "Win32_Security", + "Win32_System_JobObjects", + "Win32_System_Threading", +] } diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs new file mode 100644 index 0000000..7bea934 --- /dev/null +++ b/windows/crates/ps-service/src/api.rs @@ -0,0 +1,488 @@ +//! The API: who may do what, and doing it. + +use ps_core::config::{Config, Issue, Scope, Severity, privileged_changes, validate}; +use ps_core::render::RouteMode; +use ps_ipc::transport::{Conn, Server}; +use ps_ipc::{Peer, Request, Response}; +use serde_json::{Value, json}; + +use crate::service::{self, Shared}; + +/// What stands in for a secret a caller may not read. Sent back unchanged, it keeps the +/// value it hides. +pub const REDACTED: &str = "\u{2022}\u{2022}\u{2022}redacted\u{2022}\u{2022}\u{2022}"; + +/// Option paths holding secrets (`*`: any key or list entry). +const SECRET_PATHS: [&str; 19] = [ + "proxy.outbounds.*.url", + "proxy.outbounds.*.singBoxJson", + "proxy.outbounds.*.xrayJson", + "proxy.subscriptions.*.url", + "proxy.listener.auth.password", + "amneziaWg.profiles.*.config", + "amneziaWg.profiles.*.vpn", + "amneziaWg.profiles.*.settings.privateKey", + "amneziaWg.profiles.*.settings.peers.*.presharedKey", + "amneziaWg.profiles.*.settings.obfuscation.headerProtectionKey", + "warp.config", + "warp.devices.*.config", + "tgWsProxy.secret", + "inbounds.users.*.uuid", + "inbounds.users.*.password", + "inbounds.listeners.*.serverPassword", + "inbounds.listeners.*.reality.privateKey", + "inbounds.listeners.*.hysteria.salamander.password", + "inbounds.listeners.*.xrayJson", +]; + +fn redact_at(value: &mut Value, path: &[&str]) { + let Some((head, rest)) = path.split_first() else { + if !value.is_null() { + *value = REDACTED.into(); + } + return; + }; + match value { + Value::Object(map) => { + if *head == "*" { + map.values_mut().for_each(|v| redact_at(v, rest)); + } else if let Some(v) = map.get_mut(*head) { + redact_at(v, rest); + } + } + Value::Array(list) if *head == "*" => list.iter_mut().for_each(|v| redact_at(v, rest)), + _ => {} + } +} + +pub fn redact(config: &Config) -> Value { + let mut v = serde_json::to_value(config).expect("the config serializes"); + for p in SECRET_PATHS { + redact_at(&mut v, &p.split('.').collect::>()); + } + v +} + +/// The entry of `old` a list entry of `new` stands for: by its tag or name, else its index. +fn counterpart<'a>(old: &'a [Value], new: &Value, index: usize) -> Option<&'a Value> { + for key in ["tag", "name"] { + if let Some(id) = new.get(key).filter(|v| v.is_string()) { + return old.iter().find(|o| o.get(key) == Some(id)); + } + } + old.get(index) +} + +fn unredact_at(new: &mut Value, old: Option<&Value>, path: &[&str]) { + let Some((head, rest)) = path.split_first() else { + if new.as_str() == Some(REDACTED) { + *new = old.cloned().unwrap_or(Value::Null); + } + return; + }; + match new { + Value::Object(map) => { + let old_map = old.and_then(Value::as_object); + if *head == "*" { + for (k, v) in map.iter_mut() { + unredact_at(v, old_map.and_then(|m| m.get(k)), rest); + } + } else if let Some(v) = map.get_mut(*head) { + unredact_at(v, old_map.and_then(|m| m.get(*head)), rest); + } + } + Value::Array(list) if *head == "*" => { + let old_list = old.and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]); + for (i, v) in list.iter_mut().enumerate() { + let o = counterpart(old_list, v, i).cloned(); + unredact_at(v, o.as_ref(), rest); + } + } + _ => {} + } +} + +/// `new` with every placeholder replaced by the value it hid in `old`. +pub fn unredact(new: &mut Value, old: &Config) { + let old = serde_json::to_value(old).expect("the config serializes"); + for p in SECRET_PATHS { + unredact_at(new, Some(&old), &p.split('.').collect::>()); + } +} + +/// Whether `peer` may use `scope`, under `cfg.userControl`. +fn allowed(cfg: &Config, peer: &Peer, scope: Option) -> Result<(), String> { + if peer.admin { + return Ok(()); + } + let Some(scope) = scope else { return Ok(()) }; + let uc = &cfg.user_control; + if !uc.enable { + return Err("this needs an administrator (userControl is off)".into()); + } + if uc.scopes.is_empty() || uc.scopes.contains(&scope) { + Ok(()) + } else { + Err(format!("this needs the {scope:?} scope, which userControl does not give").to_lowercase()) + } +} + +fn scope_of(req: &Request) -> Option { + match req { + Request::ConfigSet { .. } => Some(Scope::Config), + Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing), + Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds), + Request::RenderedConfig => Some(Scope::Secrets), + Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), + _ => None, + } +} + +fn has_secrets(cfg: &Config, peer: &Peer) -> bool { + allowed(cfg, peer, Some(Scope::Secrets)).is_ok() +} + +fn issues_json(issues: &[Issue]) -> Value { + serde_json::to_value(issues).unwrap() +} + +/// Serves the API until the process ends. +pub async fn serve(mut server: Server, shared: Shared) { + loop { + match server.accept().await { + Ok(conn) => { + let shared = shared.clone(); + tokio::spawn(async move { connection(conn, shared).await }); + } + Err(e) => { + tracing::warn!("accepting a client: {e}"); + tokio::time::sleep(std::time::Duration::from_millis(200)).await; + } + } + } +} + +async fn connection(mut conn: Conn, shared: Shared) { + loop { + let req: Request = match conn.read_json().await { + Ok(Some(r)) => r, + Ok(None) => return, + Err(e) => { + let _ = conn.write_json(&Response::err(format!("bad request: {e}"))).await; + return; + } + }; + let peer = conn.peer(); + if let Request::Logs { unit, lines, follow: true } = &req { + follow_logs(&mut conn, &shared, unit.clone(), *lines).await; + return; + } + let resp = handle(req, &peer, &shared).await; + if conn.write_json(&resp).await.is_err() { + return; + } + } +} + +async fn follow_logs(conn: &mut Conn, shared: &Shared, unit: Option, lines: usize) { + let (backlog, mut feed) = { + let s = shared.lock().await; + (s.sup.tail(unit.as_deref(), lines), s.sup.subscribe()) + }; + for line in backlog { + if conn.write_json(&Response::partial(json!(line))).await.is_err() { + return; + } + } + loop { + match feed.recv().await { + Ok(line) if unit.as_ref().is_none_or(|u| *u == line.unit) => { + if conn.write_json(&Response::partial(json!(line))).await.is_err() { + return; + } + } + Ok(_) | Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {} + Err(_) => return, + } + } +} + +pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { + { + let s = shared.lock().await; + if let Err(e) = allowed(s.cfg(), peer, scope_of(&req)) { + return Response::err(e); + } + } + match req { + Request::Status => Response::ok(shared.lock().await.status()), + + Request::ConfigGet => { + let s = shared.lock().await; + let config = if has_secrets(s.cfg(), peer) { serde_json::to_value(s.cfg()).unwrap() } else { redact(s.cfg()) }; + Response::ok(json!({ "config": config, "revision": s.store.revision, "redacted": !has_secrets(s.cfg(), peer) })) + } + + Request::ConfigValidate { config } => match serde_json::from_value::(config) { + Ok(cfg) => Response::ok(json!({ "issues": issues_json(&validate(&cfg)) })), + Err(e) => Response::err(format!("not a configuration: {e}")), + }, + + Request::ConfigSet { mut config, base } => { + let mut s = shared.lock().await; + if let Some(base) = base { + if base != s.store.revision { + return Response::err(format!( + "the configuration changed since revision {base} (now {}): read it again", + s.store.revision + )); + } + } + unredact(&mut config, s.cfg()); + let new: Config = match serde_json::from_value(config) { + Ok(c) => c, + Err(e) => return Response::err(format!("not a configuration: {e}")), + }; + let issues = validate(&new); + if issues.iter().any(|i| i.severity == Severity::Error) { + return Response { ok: false, error: Some("the configuration has errors".into()), data: json!({ "issues": issues_json(&issues) }), more: false }; + } + if !peer.admin { + let privileged = privileged_changes(s.cfg(), &new); + if !privileged.is_empty() { + return Response { + ok: false, + error: Some(format!("only an administrator may change {}", privileged.join(", "))), + data: json!({ "privileged": privileged }), + more: false, + }; + } + } + let subs_before: Vec = s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).collect(); + if let Err(e) = s.store.save_config(new) { + return Response::err(format!("cannot save the configuration: {e}")); + } + tracing::info!("configuration revision {} set by {}", s.store.revision, peer.user); + let new_subs: Vec = + s.cfg().proxy.subscriptions.iter().map(|x| x.tag.clone()).filter(|t| !subs_before.contains(t)).collect(); + let applied = s.apply().await; + let revision = s.store.revision; + drop(s); + // A new subscription is fetched at once, as upstream fetches on first start. + for tag in new_subs { + let shared = shared.clone(); + tokio::spawn(async move { service::update_subscriptions(&shared, Some(&tag)).await }); + } + { + let shared = shared.clone(); + tokio::spawn(async move { service::update_rule_sets(&shared, true).await }); + } + Response::ok(json!({ + "revision": revision, + "issues": issues_json(&issues), + "applied": applied.as_ref().map(|_| true).unwrap_or(false), + "error": applied.err().map(|e| e.to_string()), + })) + } + + Request::StateGet => Response::ok(serde_json::to_value(&shared.lock().await.store.state).unwrap()), + + Request::Pin { tag, group } => { + let mut s = shared.lock().await; + match group { + Some(g) => match tag { + Some(t) => { + s.store.state.group_pins.insert(g, t); + } + None => { + s.store.state.group_pins.remove(&g); + } + }, + None => s.store.state.pin = tag, + } + finish_state(&mut s).await + } + + Request::Disable { tag, disabled } => { + let mut s = shared.lock().await; + s.store.state.disabled.retain(|t| *t != tag); + if disabled { + s.store.state.disabled.push(tag); + } + finish_state(&mut s).await + } + + Request::Mode { mode } => { + let mut s = shared.lock().await; + s.store.state.route_mode = match mode.as_deref() { + None | Some("default") => None, + Some(m) => match serde_json::from_value::(json!(m)) { + Ok(m) => Some(m), + Err(_) => return Response::err(format!("unknown mode '{m}': default, whitelist, blacklist, all-proxy or all-bypass")), + }, + }; + finish_state(&mut s).await + } + + Request::Outbounds => { + let s = shared.lock().await; + let secrets = has_secrets(s.cfg(), peer); + match &s.last { + Some(r) => { + let mut inv = serde_json::to_value(&r.inventory).unwrap(); + if !secrets { + inv["links"] = json!({}); + } + Response::ok(json!({ "inventory": inv, "warnings": r.warnings })) + } + None => Response::err(s.last_error.clone().unwrap_or_else(|| "the proxy is not running".into())), + } + } + + Request::RenderedConfig => { + let s = shared.lock().await; + match &s.last { + Some(r) => Response::ok(json!({ "sing-box": r.sing_box, "xray": r.xray })), + None => Response::err("nothing rendered yet"), + } + } + + Request::Restart { units } => { + let mut s = shared.lock().await; + let names = if units.is_empty() { s.sup.names() } else { units }; + let mut missing = Vec::new(); + for n in &names { + if !s.sup.restart(n) { + missing.push(n.clone()); + } + } + if missing.is_empty() { Response::ok(json!({ "restarted": names })) } else { Response::err(format!("no such unit: {}", missing.join(", "))) } + } + + Request::Start { unit } | Request::Stop { unit } if unit != service::SOCKS_UNIT && unit != "proxy-suite-tun" => { + Response::err(format!("unit '{unit}' cannot be started or stopped on its own")) + } + + Request::Start { unit } => { + let mut s = shared.lock().await; + if unit == "proxy-suite-tun" { + if !s.cfg().proxy.tun.enable { + return Response::err("the global TUN is off in the configuration (proxy.tun.enable)"); + } + s.tun = true; + } + s.proxy_on = true; + applied(s.apply().await) + } + + Request::Stop { unit } => { + let mut s = shared.lock().await; + if unit == "proxy-suite-tun" { + s.tun = false; + } else { + s.proxy_on = false; + } + applied(s.apply().await) + } + + Request::Logs { unit, lines, .. } => { + let s = shared.lock().await; + Response::ok(json!(s.sup.tail(unit.as_deref(), lines))) + } + + Request::SubsUpdate { tag } => { + let results = service::update_subscriptions(shared, tag.as_deref()).await; + Response::ok(json!(results.into_iter().map(|(t, r)| match r { + Ok(n) => json!({ "tag": t, "links": n }), + Err(e) => json!({ "tag": t, "error": e }), + }).collect::>())) + } + + Request::RuleSetsUpdate => { + let results = service::update_rule_sets(shared, false).await; + Response::ok(json!(results.into_iter().map(|(t, r)| match r { + Ok(()) => json!({ "tag": t }), + Err(e) => json!({ "tag": t, "error": e }), + }).collect::>())) + } + + Request::Test { tags } => { + let (clash, tags, url) = { + let s = shared.lock().await; + let Some(r) = &s.last else { return Response::err("the proxy is not running") }; + let tags = if tags.is_empty() { r.inventory.exits.clone() } else { tags }; + ( + crate::clash::Clash::new(s.cfg().proxy.sing_box.clash_api_port, &s.store.secrets.clash_secret), + tags, + s.cfg().proxy.url_test.url.clone(), + ) + }; + let mut out = Vec::new(); + for t in tags { + out.push(match clash.delay(&t, &url, 5000).await { + Ok(ms) => json!({ "tag": t, "delay": ms }), + Err(e) => json!({ "tag": t, "error": e.to_string() }), + }); + } + Response::ok(json!(out)) + } + + Request::Components | Request::ComponentsInstall { .. } => Response::err("the component manager is not there yet"), + } +} + +fn applied(r: anyhow::Result<()>) -> Response { + match r { + Ok(()) => Response::ok(Value::Null), + Err(e) => Response::err(e.to_string()), + } +} + +async fn finish_state(s: &mut tokio::sync::MutexGuard<'_, service::Service>) -> Response { + if let Err(e) = s.store.save_state() { + return Response::err(format!("cannot save the state: {e}")); + } + applied(s.apply().await) +} + +#[cfg(test)] +mod tests { + use super::*; + use ps_core::config::Outbound; + + #[test] + fn redaction_round_trips_by_tag() { + let mut cfg = Config::default(); + cfg.proxy.outbounds = vec![ + Outbound { tag: "a".into(), url: Some("hy2://secret-a@a:443".into()), ..Default::default() }, + Outbound { tag: "b".into(), url: Some("hy2://secret-b@b:443".into()), ..Default::default() }, + ]; + cfg.proxy.listener.auth.password = Some("pw".into()); + let mut shown = redact(&cfg); + assert_eq!(shown["proxy"]["outbounds"][0]["url"], REDACTED); + assert_eq!(shown["proxy"]["listener"]["auth"]["password"], REDACTED); + // The client reorders and adds one; the hidden values follow their tags. + let list = shown["proxy"]["outbounds"].as_array_mut().unwrap(); + list.swap(0, 1); + list.push(json!({ "tag": "c", "url": "hy2://new@c:443" })); + unredact(&mut shown, &cfg); + let back: Config = serde_json::from_value(shown).unwrap(); + assert_eq!(back.proxy.outbounds[0].url.as_deref(), Some("hy2://secret-b@b:443")); + assert_eq!(back.proxy.outbounds[1].url.as_deref(), Some("hy2://secret-a@a:443")); + assert_eq!(back.proxy.outbounds[2].url.as_deref(), Some("hy2://new@c:443")); + assert_eq!(back.proxy.listener.auth.password.as_deref(), Some("pw")); + } + + #[test] + fn scopes_follow_user_control() { + let mut cfg = Config::default(); + let user = Peer { admin: false, user: "u".into() }; + assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok()); + cfg.user_control.scopes = vec![Scope::Routing]; + assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_ok()); + assert!(allowed(&cfg, &user, Some(Scope::Config)).is_err()); + cfg.user_control.enable = false; + assert!(allowed(&cfg, &user, Some(Scope::Routing)).is_err()); + assert!(allowed(&cfg, &Peer { admin: true, user: "a".into() }, Some(Scope::Config)).is_ok()); + } +} diff --git a/windows/crates/ps-service/src/clash.rs b/windows/crates/ps-service/src/clash.rs new file mode 100644 index 0000000..c619855 --- /dev/null +++ b/windows/crates/ps-service/src/clash.rs @@ -0,0 +1,90 @@ +//! sing-box's Clash API on loopback: what selectors pick, and outbound latency. + +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use serde_json::Value; + +pub struct Clash { + base: String, + secret: String, + http: reqwest::Client, +} + +fn encode(segment: &str) -> String { + let mut out = String::new(); + for b in segment.bytes() { + if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { + out.push(b as char); + } else { + out.push_str(&format!("%{b:02X}")); + } + } + out +} + +impl Clash { + pub fn new(port: u16, secret: &str) -> Self { + let http = reqwest::Client::builder() + .no_proxy() + .timeout(Duration::from_secs(20)) + .build() + .expect("an HTTP client"); + Self { base: format!("http://127.0.0.1:{port}"), secret: secret.to_owned(), http } + } + + async fn get(&self, path: &str) -> Result { + let resp = self.http.get(format!("{}{path}", self.base)).bearer_auth(&self.secret).send().await?; + let status = resp.status(); + let body: Value = resp.json().await.unwrap_or(Value::Null); + if !status.is_success() { + bail!("{}", body["message"].as_str().unwrap_or(status.as_str())); + } + Ok(body) + } + + /// Every proxy (outbound or group) with what a selector holds now. + pub async fn proxies(&self) -> Result { + self.get("/proxies").await.map(|v| v["proxies"].clone()) + } + + /// What `group` (a selector or urltest) uses now. + pub async fn current(&self, group: &str) -> Result> { + let v = self.get(&format!("/proxies/{}", encode(group))).await?; + Ok(v["now"].as_str().map(str::to_owned)) + } + + /// Switches the selector `group` to `tag`, live. + pub async fn select(&self, group: &str, tag: &str) -> Result<()> { + let resp = self + .http + .put(format!("{}/proxies/{}", self.base, encode(group))) + .bearer_auth(&self.secret) + .json(&serde_json::json!({ "name": tag })) + .send() + .await + .context("the Clash API")?; + if !resp.status().is_success() { + let body: Value = resp.json().await.unwrap_or(Value::Null); + bail!("cannot switch {group} to {tag}: {}", body["message"].as_str().unwrap_or("refused")); + } + Ok(()) + } + + /// The delay to `url` through `tag`, in milliseconds. + pub async fn delay(&self, tag: &str, url: &str, timeout_ms: u32) -> Result { + let resp = self + .http + .get(format!("{}/proxies/{}/delay", self.base, encode(tag))) + .bearer_auth(&self.secret) + .query(&[("url", url), ("timeout", &timeout_ms.to_string())]) + .send() + .await?; + let status = resp.status(); + let body: Value = resp.json().await.unwrap_or(Value::Null); + if !status.is_success() { + bail!("{}", body["message"].as_str().unwrap_or("timed out")); + } + body["delay"].as_u64().map(|d| d as u32).context("no delay in the answer") + } +} diff --git a/windows/crates/ps-service/src/components.rs b/windows/crates/ps-service/src/components.rs new file mode 100644 index 0000000..b86f1d4 --- /dev/null +++ b/windows/crates/ps-service/src/components.rs @@ -0,0 +1,39 @@ +//! Where the backend programs are. +//! +//! The service installs each into `bin\\` (the component manager); a program +//! found there wins. Elsewhere (development on Linux) the one on PATH is taken. + +use std::path::{Path, PathBuf}; + +pub struct Components { + bin: PathBuf, +} + +impl Components { + pub fn new(bin: PathBuf) -> Self { + Self { bin } + } + + /// The program `name` (without `.exe`) of `component`. + pub fn find(&self, component: &str, name: &str) -> Option { + let file = if cfg!(windows) { format!("{name}.exe") } else { name.to_owned() }; + let installed = self.bin.join(component).join(&file); + if installed.is_file() { + return Some(installed); + } + let path = std::env::var_os("PATH")?; + std::env::split_paths(&path).map(|dir| dir.join(&file)).find(|p| p.is_file()) + } + + pub fn sing_box(&self) -> Option { + self.find("sing-box", "sing-box") + } + + pub fn xray(&self) -> Option { + self.find("xray", "xray") + } + + pub fn bin_dir(&self) -> &Path { + &self.bin + } +} diff --git a/windows/crates/ps-service/src/fetch.rs b/windows/crates/ps-service/src/fetch.rs new file mode 100644 index 0000000..d0073a6 --- /dev/null +++ b/windows/crates/ps-service/src/fetch.rs @@ -0,0 +1,146 @@ +//! Fetching subscriptions and rule sets: through the local proxy when it runs, else (or +//! when that fails, with `killSwitch.directFallbacks`) directly. Redirects follow upstream's +//! rule: http and https only, never down to http, never nearer to this host. + +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use ps_core::links::subscription::{self, MAX_SUBSCRIPTION_BYTES, USER_AGENT, url_parts}; + +/// How to reach the network for a fetch. +#[derive(Debug, Clone)] +pub enum Route { + Direct, + /// The local proxy's mixed listener, with its login. + Proxy { port: u16, login: Option<(String, String)> }, +} + +fn client(route: &Route) -> Result { + let policy = reqwest::redirect::Policy::custom(|attempt| { + let from = attempt.previous().last().map(|u| u.as_str().to_owned()).unwrap_or_default(); + let to = attempt.url().as_str().to_owned(); + if attempt.previous().len() > 10 { + return attempt.error("too many redirects"); + } + match (url_parts::split(&from), url_parts::split(&to)) { + (Ok(f), Ok(t)) => match subscription::redirect_allowed(&f, &t) { + Ok(()) => attempt.follow(), + Err(why) => attempt.error(why), + }, + _ => attempt.error("a redirect to an unreadable URL"), + } + }); + let mut b = reqwest::Client::builder() + .user_agent(USER_AGENT) + .redirect(policy) + .connect_timeout(Duration::from_secs(15)) + .timeout(Duration::from_secs(60)); + b = match route { + Route::Direct => b.no_proxy(), + Route::Proxy { port, login } => { + // socks5h: the proxy resolves the name, as it would for an app. + let url = match login { + Some((u, p)) => format!("socks5h://{u}:{p}@127.0.0.1:{port}"), + None => format!("socks5h://127.0.0.1:{port}"), + }; + b.proxy(reqwest::Proxy::all(url)?) + } + }; + Ok(b.build()?) +} + +/// The body of `url`, at most `limit` bytes. The error never quotes the URL: it is a secret. +pub async fn get(url: &str, route: &Route, limit: usize) -> Result> { + let scheme = url_parts::split(url).map(|u| u.scheme).unwrap_or_default(); + if scheme != "http" && scheme != "https" { + bail!("the URL must be http:// or https://"); + } + let mut resp = client(route)?.get(url).send().await.map_err(|e| anyhow::anyhow!(describe(&e)))?; + if !resp.status().is_success() { + bail!("the server answered {}", resp.status()); + } + let mut body = Vec::new(); + while let Some(chunk) = resp.chunk().await.map_err(|e| anyhow::anyhow!(describe(&e)))? { + body.extend_from_slice(&chunk); + if body.len() > limit { + bail!("the answer is larger than {limit} bytes"); + } + } + Ok(body) +} + +/// A reqwest error without the URL it carries. +fn describe(e: &reqwest::Error) -> String { + let kind = if e.is_timeout() { + "timed out" + } else if e.is_connect() { + "cannot connect" + } else if e.is_redirect() { + "a redirect was refused" + } else if e.is_request() { + "the request failed" + } else { + "the transfer failed" + }; + let mut source = std::error::Error::source(e); + let mut detail = String::new(); + while let Some(s) = source { + detail = s.to_string(); + source = s.source(); + } + if detail.is_empty() { kind.into() } else { format!("{kind}: {detail}") } +} + +/// A subscription's links: fetched by the first route that works. +pub async fn subscription(url: &str, routes: &[Route]) -> Result> { + let mut last = None; + for route in routes { + match get(url, route, MAX_SUBSCRIPTION_BYTES).await { + Ok(body) => { + let lines = subscription::decode_subscription(&body); + if lines.is_empty() { + bail!("the subscription is empty"); + } + return Ok(lines); + } + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it"))) +} + +/// A rule set to `dest`, written atomically. +pub async fn rule_set(url: &str, routes: &[Route], dest: &std::path::Path) -> Result<()> { + let mut last = None; + for route in routes { + match get(url, route, 64 * 1024 * 1024).await { + Ok(body) => { + crate::paths::write_atomic(dest, &body).with_context(|| format!("writing {}", dest.display()))?; + return Ok(()); + } + Err(e) => last = Some(e), + } + } + Err(last.unwrap_or_else(|| anyhow::anyhow!("no way to fetch it"))) +} + +/// The domain-only copy of a source rule set, for DNS rules: sing-box refuses address +/// matches there. +pub fn domain_only(source: &serde_json::Value) -> serde_json::Value { + const DOMAIN_KEYS: [&str; 4] = ["domain", "domain_suffix", "domain_keyword", "domain_regex"]; + let rules: Vec = source["rules"] + .as_array() + .map(|rules| { + rules + .iter() + .filter_map(|r| { + let obj = r.as_object()?; + let kept: serde_json::Map = + obj.iter().filter(|(k, _)| DOMAIN_KEYS.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone())).collect(); + (!kept.is_empty()).then_some(serde_json::Value::Object(kept)) + }) + .collect() + }) + .unwrap_or_default(); + serde_json::json!({ "version": source["version"].as_u64().unwrap_or(1), "rules": rules }) +} diff --git a/windows/crates/ps-service/src/job.rs b/windows/crates/ps-service/src/job.rs new file mode 100644 index 0000000..4a45ff1 --- /dev/null +++ b/windows/crates/ps-service/src/job.rs @@ -0,0 +1,63 @@ +//! A Windows Job Object that kills every child with the service: a crash of the service +//! must not leave sing-box or winws running, holding the TUN or WinDivert. + +use std::ffi::c_void; +use std::ptr::null; + +use windows_sys::Win32::Foundation::{CloseHandle, HANDLE}; +use windows_sys::Win32::System::JobObjects::{ + AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, + JobObjectExtendedLimitInformation, SetInformationJobObject, +}; + +pub struct Job(HANDLE); + +// SAFETY: a job handle may be used from any thread. +unsafe impl Send for Job {} +unsafe impl Sync for Job {} + +impl Job { + pub fn new() -> std::io::Result { + // SAFETY: an anonymous job; the handle is closed in Drop. + unsafe { + let job = CreateJobObjectW(null(), null()); + if job.is_null() { + return Err(std::io::Error::last_os_error()); + } + let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed(); + info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE; + let ok = SetInformationJobObject( + job, + JobObjectExtendedLimitInformation, + &info as *const _ as *const c_void, + std::mem::size_of::() as u32, + ); + if ok == 0 { + let err = std::io::Error::last_os_error(); + CloseHandle(job); + return Err(err); + } + Ok(Self(job)) + } + } + + pub fn handle(&self) -> isize { + self.0 as isize + } +} + +impl Drop for Job { + fn drop(&mut self) { + // SAFETY: ours, closed once. + unsafe { CloseHandle(self.0) }; + } +} + +/// Puts a process into the job. A failure is logged, not fatal: the process still runs. +pub fn assign(job: isize, process: isize) { + // SAFETY: both handles are live: the job for the service's life, the process until it + // has been waited on. + if unsafe { AssignProcessToJobObject(job as HANDLE, process as HANDLE) } == 0 { + tracing::warn!("cannot add a child to the job: {}", std::io::Error::last_os_error()); + } +} diff --git a/windows/crates/ps-service/src/main.rs b/windows/crates/ps-service/src/main.rs new file mode 100644 index 0000000..e41c455 --- /dev/null +++ b/windows/crates/ps-service/src/main.rs @@ -0,0 +1,127 @@ +//! proxy-suite-service: runs the backends, keeps the configuration, serves the API. +//! +//! As a Windows service it is started by the Service Control Manager (`install` registers +//! it); `--console` runs it in the foreground, which is also how it runs off Windows. + +mod api; +mod clash; +mod components; +mod fetch; +#[cfg(windows)] +mod job; +mod paths; +mod service; +mod store; +mod units; +#[cfg(windows)] +mod winsvc; + +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::{Parser, Subcommand}; +use ps_ipc::transport::{Address, Server}; +use tokio::sync::Mutex; + +#[derive(Parser)] +#[command(name = "proxy-suite-service", version, about = "Proxy Suite's service")] +struct Args { + /// Run in the foreground instead of under the Service Control Manager. + #[arg(long)] + console: bool, + /// Where the configuration and state live (default: %ProgramData%\ProxySuite). + #[arg(long, value_name = "DIR")] + state_dir: Option, + /// The API's pipe or socket (default: \\.\pipe\proxy-suite, or $TMPDIR/proxy-suite.sock). + #[arg(long, value_name = "ADDRESS")] + socket: Option, + #[command(subcommand)] + command: Option, +} + +#[derive(Subcommand)] +enum Command { + /// Register the Windows service (started at boot, as LocalSystem). + Install, + /// Remove the Windows service. + Uninstall, +} + +fn address(arg: Option) -> Address { + match arg { + Some(s) if cfg!(windows) => Address::Pipe(s), + Some(s) => Address::Unix(s.into()), + None => Address::default_for_platform(), + } +} + +/// Everything the service does, until `shutdown` resolves. +pub async fn run(state_dir: Option, socket: Option, shutdown: impl std::future::Future) -> Result<()> { + let _ = rustls::crypto::ring::default_provider().install_default(); + let paths = state_dir.map(paths::Paths::new).unwrap_or_else(paths::Paths::platform_default); + let svc = service::Service::new(paths.clone()).with_context(|| format!("opening {}", paths.root.display()))?; + let interactive = svc.cfg().user_control.enable; + let shared = Arc::new(Mutex::new(svc)); + + let addr = address(socket); + let server = Server::bind(&addr, interactive).with_context(|| format!("listening on {addr:?}"))?; + tracing::info!("listening on {addr:?}, state in {}", paths.root.display()); + + if let Err(e) = shared.lock().await.apply().await { + tracing::warn!("not starting the proxy yet: {e}"); + } + tokio::spawn(api::serve(server, shared.clone())); + // First fetches: what the configuration needs and has not got yet. + { + let shared = shared.clone(); + tokio::spawn(async move { + let missing: Vec = { + let s = shared.lock().await; + s.cfg().proxy.subscriptions.iter().filter(|x| !s.store.subscriptions.contains_key(&x.tag)).map(|x| x.tag.clone()).collect() + }; + for tag in missing { + service::update_subscriptions(&shared, Some(&tag)).await; + } + service::update_rule_sets(&shared, true).await; + service::timers(shared).await; + }); + } + + shutdown.await; + tracing::info!("stopping"); + shared.lock().await.sup.stop_all().await; + if let Address::Unix(path) = addr { + let _ = std::fs::remove_file(path); + } + Ok(()) +} + +fn main() -> Result<()> { + let args = Args::parse(); + tracing_subscriber::fmt() + .with_env_filter(tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| "info".into())) + .with_writer(std::io::stderr) + .init(); + match args.command { + #[cfg(windows)] + Some(Command::Install) => return winsvc::install(), + #[cfg(windows)] + Some(Command::Uninstall) => return winsvc::uninstall(), + #[cfg(not(windows))] + Some(_) => anyhow::bail!("there are no services to install off Windows; use --console"), + None => {} + } + if args.console || !cfg!(windows) { + let rt = tokio::runtime::Runtime::new()?; + return rt.block_on(run(args.state_dir, args.socket, async { + let _ = tokio::signal::ctrl_c().await; + })); + } + #[cfg(windows)] + { + winsvc::dispatch() + } + #[cfg(not(windows))] + unreachable!() +} diff --git a/windows/crates/ps-service/src/paths.rs b/windows/crates/ps-service/src/paths.rs new file mode 100644 index 0000000..a56321c --- /dev/null +++ b/windows/crates/ps-service/src/paths.rs @@ -0,0 +1,87 @@ +//! Where the service keeps everything. +//! +//! `%ProgramData%\ProxySuite` on Windows, or `--state-dir` (any platform, for development +//! and tests): +//! +//! ```text +//! config.json the configuration, written only by the service +//! state.json pins, disabled outbounds, the route mode +//! secrets.json what the service generated: the Clash API secret, the hop login +//! subscriptions/ each subscription's links as fetched last +//! rule-sets/ downloaded geodata and rule sets +//! cache/ sing-box's fake IP cache +//! run/ the rendered backend configs +//! logs/ one log per unit +//! bin/ the components (sing-box, xray, winws, …) +//! ``` + +use std::path::{Path, PathBuf}; + +#[derive(Debug, Clone)] +pub struct Paths { + pub root: PathBuf, +} + +impl Paths { + pub fn new(root: impl Into) -> Self { + Self { root: root.into() } + } + + /// `%ProgramData%\ProxySuite`, or `/var/lib/proxy-suite-windows` elsewhere. + pub fn platform_default() -> Self { + if cfg!(windows) { + let base = std::env::var_os("ProgramData").map(PathBuf::from).unwrap_or_else(|| PathBuf::from(r"C:\ProgramData")); + Self::new(base.join("ProxySuite")) + } else { + Self::new("/var/lib/proxy-suite-windows") + } + } + + pub fn config(&self) -> PathBuf { + self.root.join("config.json") + } + pub fn state(&self) -> PathBuf { + self.root.join("state.json") + } + pub fn secrets(&self) -> PathBuf { + self.root.join("secrets.json") + } + pub fn subscriptions(&self) -> PathBuf { + self.root.join("subscriptions") + } + pub fn rule_sets(&self) -> PathBuf { + self.root.join("rule-sets") + } + pub fn cache(&self) -> PathBuf { + self.root.join("cache") + } + pub fn run(&self) -> PathBuf { + self.root.join("run") + } + pub fn logs(&self) -> PathBuf { + self.root.join("logs") + } + pub fn bin(&self) -> PathBuf { + self.root.join("bin") + } + + pub fn create_all(&self) -> std::io::Result<()> { + for dir in [self.root.clone(), self.subscriptions(), self.rule_sets(), self.cache(), self.run(), self.logs(), self.bin()] { + std::fs::create_dir_all(dir)?; + } + Ok(()) + } +} + +/// Writes `data` to `path` through a temporary file and a rename, so a reader never sees half +/// of it and a crash leaves the old one. +pub fn write_atomic(path: &Path, data: &[u8]) -> std::io::Result<()> { + let tmp = path.with_extension("tmp"); + std::fs::write(&tmp, data)?; + std::fs::rename(&tmp, path) +} + +/// Whether `path` holds exactly `data` already. +pub fn same_content(path: &Path, data: &[u8]) -> bool { + std::fs::read(path).is_ok_and(|old| old == data) +} diff --git a/windows/crates/ps-service/src/service.rs b/windows/crates/ps-service/src/service.rs new file mode 100644 index 0000000..0f32547 --- /dev/null +++ b/windows/crates/ps-service/src/service.rs @@ -0,0 +1,385 @@ +//! The service's state and what it does with it: render, write, check, (re)start, fetch. + +use std::collections::BTreeMap; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::{Duration, SystemTime}; + +use anyhow::{Context, Result}; +use ps_core::config::{Backend, Config, RuleSetFormat}; +use ps_core::render::{self, Env, Input, Rendered}; +use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; +use tokio::sync::Mutex; + +use crate::components::Components; +use crate::fetch; +use crate::paths::{Paths, same_content, write_atomic}; +use crate::store::{Store, random_uuid}; +use crate::units::{Supervisor, UnitSpec, UnitState}; + +pub const SOCKS_UNIT: &str = "proxy-suite-socks"; +pub const SIDECAR_UNIT: &str = "proxy-suite-xray-sidecar"; + +pub type Shared = Arc>; + +pub struct Service { + pub store: Store, + pub sup: Supervisor, + pub comps: Components, + /// `proxy-ctl proxy off` stops the local proxy until `on` or the next start. + pub proxy_on: bool, + /// The global TUN, on with `proxy.autostart = "tun"` or `proxy-ctl proxy tun on`. + pub tun: bool, + sidecar_secret: String, + pub last: Option, + /// Why the last apply did not take. + pub last_error: Option, + pub last_fetch: BTreeMap, +} + +fn digest(data: &[u8]) -> String { + let mut h = Sha256::new(); + h.update(data); + h.finalize().iter().map(|b| format!("{b:02x}")).collect() +} + +impl Service { + pub fn new(paths: Paths) -> Result { + let store = Store::open(paths.clone())?; + let tun = store.config.proxy.autostart.is_some() && store.config.proxy.tun.enable; + Ok(Self { + sup: Supervisor::new(paths.logs()), + comps: Components::new(paths.bin()), + proxy_on: true, + tun, + sidecar_secret: random_uuid(), + last: None, + last_error: None, + last_fetch: BTreeMap::new(), + store, + }) + } + + pub fn paths(&self) -> &Paths { + &self.store.paths + } + + pub fn cfg(&self) -> &Config { + &self.store.config + } + + fn proxy_wanted(&self) -> bool { + let cfg = self.cfg(); + cfg.enable && cfg.proxy.enable && self.proxy_on + } + + fn env(&self) -> Env { + let paths = self.paths(); + let cfg = self.cfg(); + let mut direct = Vec::new(); + if cfg.proxy.backend == Backend::Hybrid { + if let Some(x) = self.comps.xray() { + direct.push(x.to_string_lossy().into_owned()); + } + } + Env { + rule_sets: self.store.rule_set_files(), + empty_rule_set: paths.run().join("empty-rule-set.json").to_string_lossy().into_owned(), + cache_dir: paths.cache().to_string_lossy().into_owned(), + clash_secret: Some(self.store.secrets.clash_secret.clone()), + hop_login: Some((self.store.secrets.hop_user.clone(), self.store.secrets.hop_password.clone())), + direct_processes: direct, + groups_watched: false, + sidecar_secret: self.sidecar_secret.clone(), + windows: cfg!(windows), + ..Default::default() + } + } + + /// Renders and returns the result, without touching anything. + pub fn render(&self) -> Result { + let env = self.env(); + let read = |path: &str| std::fs::read_to_string(path).map_err(|e| format!("{path}: {e}")); + render::render(&Input { + cfg: self.cfg(), + state: &self.store.state, + subscriptions: &self.store.subscriptions, + env: &env, + read_file: &read, + tun: self.tun && self.cfg().proxy.tun.enable, + }) + } + + /// Brings the units in line with the configuration: render, write, check, start or + /// restart what changed, stop what is no longer wanted. + pub async fn apply(&mut self) -> Result<()> { + if !self.proxy_wanted() { + self.sup.stop(SOCKS_UNIT).await; + self.sup.stop(SIDECAR_UNIT).await; + self.last_error = None; + return Ok(()); + } + let run = self.paths().run(); + let empty = run.join("empty-rule-set.json"); + if !empty.exists() { + write_atomic(&empty, br#"{"version":1,"rules":[]}"#)?; + } + let rendered = match self.render() { + Ok(r) => r, + Err(e) => { + self.last_error = Some(e.0.clone()); + self.sup.note(SOCKS_UNIT, format!("proxy-suite: not starting: {e}")); + return Err(anyhow::anyhow!(e.0)); + } + }; + for w in &rendered.warnings { + self.sup.note(SOCKS_UNIT, format!("proxy-suite: warning: {w}")); + } + + let backend = self.cfg().proxy.backend; + let main_program = match backend { + Backend::Xray => self.comps.xray().context("xray is not installed")?, + _ => self.comps.sing_box().context("sing-box is not installed (proxy-ctl components install)")?, + }; + let main_json = serde_json::to_vec_pretty(rendered.sing_box.as_ref().or(rendered.xray.as_ref()).unwrap())?; + let main_path = run.join(if backend == Backend::Xray { "xray.json" } else { "sing-box.json" }); + // Checked before it replaces the running one: a config the backend refuses keeps the + // last good one running. + let candidate = run.join("candidate.json"); + write_atomic(&candidate, &main_json)?; + if backend != Backend::Xray { + let out = tokio::process::Command::new(&main_program).args(["check", "-c"]).arg(&candidate).output().await?; + if !out.status.success() { + let why = String::from_utf8_lossy(&out.stderr).trim().to_owned(); + self.last_error = Some(format!("sing-box refused the rendered config: {why}")); + self.sup.note(SOCKS_UNIT, format!("proxy-suite: sing-box refused the new config, keeping the old one: {why}")); + anyhow::bail!("sing-box refused the rendered config: {why}"); + } + } + if !same_content(&main_path, &main_json) { + std::fs::rename(&candidate, &main_path)?; + } + let mut args: Vec = vec!["run".into(), "-c".into(), main_path.to_string_lossy().into_owned()]; + if backend != Backend::Xray { + args.extend(["-D".into(), run.to_string_lossy().into_owned(), "--disable-color".into()]); + } + self.sup.ensure(UnitSpec { + name: SOCKS_UNIT.into(), + program: main_program, + args, + env: Vec::new(), + cwd: Some(run.clone()), + generation: digest(&main_json), + }); + + match (backend, &rendered.xray) { + (Backend::Hybrid, Some(sidecar)) => { + let xray = self.comps.xray().context("xray is not installed; the hybrid backend needs it")?; + let json = serde_json::to_vec_pretty(sidecar)?; + let path = run.join("xray-sidecar.json"); + if !same_content(&path, &json) { + write_atomic(&path, &json)?; + } + self.sup.ensure(UnitSpec { + name: SIDECAR_UNIT.into(), + program: xray, + args: vec!["run".into(), "-c".into(), path.to_string_lossy().into_owned()], + env: Vec::new(), + cwd: Some(run.clone()), + generation: digest(&json), + }); + } + _ => self.sup.stop(SIDECAR_UNIT).await, + } + self.last = Some(rendered); + self.last_error = None; + Ok(()) + } + + /// The routes a fetch tries: the local proxy if it runs, and (with directFallbacks or + /// without it) directly. + pub fn fetch_routes(&self, via_proxy: bool) -> Vec { + let cfg = self.cfg(); + let mut routes = Vec::new(); + if via_proxy && self.sup.state_of(SOCKS_UNIT) == UnitState::Active { + let auth = &cfg.proxy.listener.auth; + let login = auth.username.clone().zip(auth.password.clone()); + routes.push(fetch::Route::Proxy { port: cfg.proxy.listener.port, login }); + if !cfg.kill_switch.enable || cfg.kill_switch.direct_fallbacks { + routes.push(fetch::Route::Direct); + } + } else { + routes.push(fetch::Route::Direct); + } + routes + } + + pub fn status(&self) -> Value { + let cfg = self.cfg(); + let units: Vec = self.sup.status().into_iter().map(|u| serde_json::to_value(u).unwrap()).collect(); + let socks = self.sup.state_of(SOCKS_UNIT); + json!({ + "units": units, + "proxy": { + "enabled": cfg.proxy.enable, + "on": self.proxy_wanted(), + "state": socks.as_str(), + "backend": cfg.proxy.backend.as_str(), + "listener": format!("{}:{}", cfg.proxy.listener.address, cfg.proxy.listener.port), + "tun": self.tun && cfg.proxy.tun.enable, + "mode": self.store.state.route_mode.map(|m| m.as_str()), + "pinned": self.store.state.pin, + "selection": cfg.proxy.selection.as_str(), + }, + "warnings": self.last.as_ref().map(|r| r.warnings.clone()).unwrap_or_default(), + "error": self.last_error, + "revision": self.store.revision, + }) + } +} + +/// Fetches the subscriptions (all, or `only`), saves what came, and applies. +pub async fn update_subscriptions(shared: &Shared, only: Option<&str>) -> Vec<(String, Result)> { + let jobs: Vec<(String, Result, Vec)> = { + let s = shared.lock().await; + s.cfg() + .proxy + .subscriptions + .iter() + .filter(|sub| only.is_none_or(|t| t == sub.tag)) + .map(|sub| { + let url = match (&sub.url, &sub.url_file) { + (Some(u), _) => Ok(u.trim().to_owned()), + (None, Some(f)) => std::fs::read_to_string(f).map(|s| s.trim().to_owned()).map_err(|e| format!("{f}: {e}")), + (None, None) => Err("no url or urlFile".into()), + }; + (sub.tag.clone(), url, s.fetch_routes(true)) + }) + .collect() + }; + let mut results = Vec::new(); + for (tag, url, routes) in jobs { + let result = match url { + Err(e) => Err(e), + Ok(url) => fetch::subscription(&url, &routes).await.map_err(|e| e.to_string()), + }; + let mut s = shared.lock().await; + match result { + Ok(lines) => { + let n = lines.len(); + if let Err(e) = s.store.save_subscription(&tag, lines) { + results.push((tag, Err(e.to_string()))); + continue; + } + s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now()); + s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}': {n} links")); + results.push((tag, Ok(n))); + } + Err(e) => { + s.last_fetch.insert(format!("sub:{tag}"), SystemTime::now()); + s.sup.note(SOCKS_UNIT, format!("proxy-suite: subscription '{tag}' could not be fetched: {e}")); + results.push((tag, Err(e))); + } + } + } + let mut s = shared.lock().await; + let _ = s.apply().await; + results +} + +/// Fetches the rule sets and geodata the configuration wants (all, or those missing), and +/// applies when something new came. +pub async fn update_rule_sets(shared: &Shared, missing_only: bool) -> Vec<(String, Result<(), String>)> { + let (wanted, have, dir, sing_box, routes_proxy, routes_direct) = { + let s = shared.lock().await; + ( + render::wanted_rule_sets(s.cfg()), + s.store.rule_set_files(), + s.paths().rule_sets(), + s.comps.sing_box(), + s.fetch_routes(true), + s.fetch_routes(false), + ) + }; + let mut results = Vec::new(); + let mut changed = false; + for w in wanted.iter().filter(|w| w.dns_copy_of.is_none()) { + if missing_only && have.contains_key(&w.tag) { + continue; + } + let ext = if w.format == RuleSetFormat::Binary { "srs" } else { "json" }; + let dest = dir.join(format!("{}.{ext}", w.tag)); + let routes = if w.via_proxy { &routes_proxy } else { &routes_direct }; + let r = fetch::rule_set(&w.url, routes, &dest).await.map_err(|e| e.to_string()); + changed |= r.is_ok(); + results.push((w.tag.clone(), r)); + } + // The DNS copies, from what was fetched. + for w in wanted.iter().filter(|w| w.dns_copy_of.is_some()) { + let of = w.dns_copy_of.as_deref().unwrap(); + let src_json = dir.join(format!("{of}.json")); + let src_srs = dir.join(format!("{of}.srs")); + let dest = dir.join(format!("{}.json", w.tag)); + if missing_only && dest.exists() && !changed { + continue; + } + let source: Result = if src_json.exists() { + std::fs::read_to_string(&src_json).map_err(Into::into).and_then(|t| serde_json::from_str(&t).map_err(Into::into)) + } else if let (true, Some(sb)) = (src_srs.exists(), &sing_box) { + decompile(sb, &src_srs).await + } else { + continue; + }; + let r = source + .and_then(|src| Ok(write_atomic(&dest, serde_json::to_string(&fetch::domain_only(&src))?.as_bytes())?)) + .map_err(|e| e.to_string()); + results.push((w.tag.clone(), r)); + } + if changed { + let mut s = shared.lock().await; + let _ = s.apply().await; + } + results +} + +async fn decompile(sing_box: &PathBuf, srs: &std::path::Path) -> Result { + let out = srs.with_extension("decompiled.json"); + let status = tokio::process::Command::new(sing_box) + .args(["rule-set", "decompile", "--output"]) + .arg(&out) + .arg(srs) + .status() + .await?; + anyhow::ensure!(status.success(), "sing-box could not decompile {}", srs.display()); + let v = serde_json::from_str(&std::fs::read_to_string(&out)?)?; + let _ = std::fs::remove_file(&out); + Ok(v) +} + +/// The timers: subscriptions and rule sets, each on its interval. +pub async fn timers(shared: Shared) { + loop { + tokio::time::sleep(Duration::from_secs(60)).await; + let (sub_due, rules_due) = { + let s = shared.lock().await; + let cfg = s.cfg(); + let every = |text: &str, default: u64| ps_core::duration::parse(text).unwrap_or(Duration::from_secs(default)); + let sub_every = every(&cfg.proxy.subscription_update_interval, 86400); + let rules_every = every(&cfg.proxy.routing.rule_set_update_interval, 86400); + let due = |key: &str, every: Duration| { + s.last_fetch.get(key).is_none_or(|t| t.elapsed().unwrap_or_default() >= every) + }; + let subs: Vec = + cfg.proxy.subscriptions.iter().filter(|x| due(&format!("sub:{}", x.tag), sub_every)).map(|x| x.tag.clone()).collect(); + (subs, due("rule-sets", rules_every)) + }; + for tag in sub_due { + update_subscriptions(&shared, Some(&tag)).await; + } + if rules_due { + shared.lock().await.last_fetch.insert("rule-sets".into(), SystemTime::now()); + update_rule_sets(&shared, false).await; + } + } +} diff --git a/windows/crates/ps-service/src/store.rs b/windows/crates/ps-service/src/store.rs new file mode 100644 index 0000000..9f6e62e --- /dev/null +++ b/windows/crates/ps-service/src/store.rs @@ -0,0 +1,125 @@ +//! The configuration, runtime state and generated secrets, as files. + +use std::collections::BTreeMap; + +use anyhow::{Context, Result}; +use ps_core::config::Config; +use ps_core::render::{RuleSetFile, State}; +use rand::Rng; +use serde::{Deserialize, Serialize}; + +use crate::paths::{Paths, write_atomic}; + +/// What the service generated once and keeps. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Secrets { + pub clash_secret: String, + pub hop_user: String, + pub hop_password: String, +} + +pub fn random_token(len: usize) -> String { + const CHARS: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; + let mut rng = rand::rng(); + (0..len).map(|_| CHARS[rng.random_range(0..CHARS.len())] as char).collect() +} + +pub fn random_uuid() -> String { + let mut rng = rand::rng(); + let b: [u8; 16] = rng.random(); + format!( + "{:08x}-{:04x}-4{:03x}-{:04x}-{:012x}", + u32::from_be_bytes([b[0], b[1], b[2], b[3]]), + u16::from_be_bytes([b[4], b[5]]), + u16::from_be_bytes([b[6], b[7]]) & 0x0fff, + (u16::from_be_bytes([b[8], b[9]]) & 0x3fff) | 0x8000, + u64::from_be_bytes([0, 0, b[10], b[11], b[12], b[13], b[14], b[15]]) + ) +} + +pub struct Store { + pub paths: Paths, + pub config: Config, + /// Bumped by every change of `config`: a client edits against a revision. + pub revision: u64, + pub state: State, + pub secrets: Secrets, + /// Each subscription's links as fetched last. + pub subscriptions: BTreeMap>, +} + +impl Store { + pub fn open(paths: Paths) -> Result { + paths.create_all().with_context(|| format!("creating {}", paths.root.display()))?; + let config = match std::fs::read_to_string(paths.config()) { + Ok(text) => Config::from_json(&text).with_context(|| format!("reading {}", paths.config().display()))?, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => Config::default(), + Err(e) => return Err(e).with_context(|| format!("reading {}", paths.config().display())), + }; + let state = std::fs::read_to_string(paths.state()) + .ok() + .and_then(|t| serde_json::from_str(&t).ok()) + .unwrap_or_default(); + let secrets = match std::fs::read_to_string(paths.secrets()).ok().and_then(|t| serde_json::from_str(&t).ok()) { + Some(s) => s, + None => { + let s = Secrets { clash_secret: random_token(32), hop_user: "hop".into(), hop_password: random_token(32) }; + write_atomic(&paths.secrets(), serde_json::to_string_pretty(&s)?.as_bytes())?; + s + } + }; + let mut store = Self { paths, config, revision: 1, state, secrets, subscriptions: BTreeMap::new() }; + store.load_subscriptions(); + Ok(store) + } + + pub fn save_config(&mut self, config: Config) -> Result<()> { + write_atomic(&self.paths.config(), config.to_json_pretty().as_bytes())?; + self.config = config; + self.revision += 1; + Ok(()) + } + + pub fn save_state(&self) -> Result<()> { + write_atomic(&self.paths.state(), serde_json::to_string_pretty(&self.state)?.as_bytes())?; + Ok(()) + } + + fn sub_path(&self, tag: &str) -> std::path::PathBuf { + self.paths.subscriptions().join(format!("{tag}.txt")) + } + + fn load_subscriptions(&mut self) { + for sub in &self.config.proxy.subscriptions { + if let Ok(text) = std::fs::read_to_string(self.sub_path(&sub.tag)) { + self.subscriptions.insert(sub.tag.clone(), text.lines().map(str::to_owned).collect()); + } + } + } + + pub fn save_subscription(&mut self, tag: &str, lines: Vec) -> Result<()> { + write_atomic(&self.sub_path(tag), lines.join("\n").as_bytes())?; + self.subscriptions.insert(tag.to_owned(), lines); + Ok(()) + } + + /// The downloaded rule sets, by tag. + pub fn rule_set_files(&self) -> BTreeMap { + let mut out = BTreeMap::new(); + let Ok(dir) = std::fs::read_dir(self.paths.rule_sets()) else { return out }; + for entry in dir.flatten() { + let path = entry.path(); + let (Some(stem), Some(ext)) = (path.file_stem().and_then(|s| s.to_str()), path.extension().and_then(|s| s.to_str())) else { + continue; + }; + let format = match ext { + "srs" => ps_core::config::RuleSetFormat::Binary, + "json" => ps_core::config::RuleSetFormat::Source, + _ => continue, + }; + out.insert(stem.to_owned(), RuleSetFile { path: path.to_string_lossy().into_owned(), format }); + } + out + } +} diff --git a/windows/crates/ps-service/src/units.rs b/windows/crates/ps-service/src/units.rs new file mode 100644 index 0000000..4bdb0a8 --- /dev/null +++ b/windows/crates/ps-service/src/units.rs @@ -0,0 +1,429 @@ +//! The supervisor: what systemd does for upstream. Each unit is one program, started, +//! watched, restarted with backoff when it dies, its output kept in a ring and a log file. +//! On Windows every child joins a Job Object that kills it with the service. + +use std::collections::{BTreeMap, VecDeque}; +use std::io::Write; +use std::path::PathBuf; +use std::process::Stdio; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde::Serialize; +use tokio::io::{AsyncBufReadExt, BufReader}; +use tokio::process::Command; +use tokio::sync::{broadcast, watch}; + +/// How to run a unit. Two specs that compare equal need no restart. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UnitSpec { + pub name: String, + pub program: PathBuf, + pub args: Vec, + pub env: Vec<(String, String)>, + pub cwd: Option, + /// Changes when a file the unit reads changes (its rendered config): a restart. + pub generation: String, +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "lowercase")] +pub enum UnitState { + Inactive, + Activating, + Active, + Deactivating, + Failed, +} + +impl UnitState { + pub fn as_str(self) -> &'static str { + match self { + Self::Inactive => "inactive", + Self::Activating => "activating", + Self::Active => "active", + Self::Deactivating => "deactivating", + Self::Failed => "failed", + } + } +} + +#[derive(Debug, Clone, Serialize)] +pub struct LogLine { + pub unit: String, + /// Unix time, milliseconds. + pub at: u64, + pub line: String, +} + +#[derive(Debug, Clone, Serialize)] +pub struct UnitStatus { + pub name: String, + pub state: UnitState, + pub pid: Option, + pub restarts: u32, + /// Why it failed last. + pub result: Option, + pub since: Option, +} + +const RING: usize = 2000; +/// A unit that fails this many times within `START_LIMIT_INTERVAL` stays failed. +const START_LIMIT: usize = 5; +const START_LIMIT_INTERVAL: Duration = Duration::from_secs(60); +/// A unit whose log file outgrows this starts a new one, keeping one old. +const LOG_FILE_MAX: u64 = 5 * 1024 * 1024; + +struct Shared { + state: UnitState, + pid: Option, + restarts: u32, + result: Option, + since: Option, +} + +struct Unit { + spec: UnitSpec, + shared: Arc>, + stop: watch::Sender, + task: tokio::task::JoinHandle<()>, +} + +pub struct Supervisor { + units: BTreeMap, + logs: Arc>>>, + log_dir: PathBuf, + feed: broadcast::Sender, + #[cfg(windows)] + job: Option, +} + +fn now_ms() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map_or(0, |d| d.as_millis() as u64) +} + +impl Supervisor { + pub fn new(log_dir: PathBuf) -> Self { + let (feed, _) = broadcast::channel(1024); + Self { + units: BTreeMap::new(), + logs: Arc::new(Mutex::new(BTreeMap::new())), + log_dir, + feed, + #[cfg(windows)] + job: crate::job::Job::new().map_err(|e| tracing::warn!("no job object: {e}")).ok(), + } + } + + pub fn subscribe(&self) -> broadcast::Receiver { + self.feed.subscribe() + } + + /// The last `n` log lines of `unit`, or of every unit by time. + pub fn tail(&self, unit: Option<&str>, n: usize) -> Vec { + let logs = self.logs.lock().unwrap(); + let mut lines: Vec = match unit { + Some(u) => logs.get(u).map(|r| r.iter().cloned().collect()).unwrap_or_default(), + None => logs.values().flatten().cloned().collect(), + }; + lines.sort_by_key(|l| l.at); + let skip = lines.len().saturating_sub(n); + lines.split_off(skip) + } + + /// A line of the service's own about a unit, in that unit's log. + pub fn note(&self, unit: &str, line: impl Into) { + push_log(&self.logs, &self.feed, &self.log_dir, unit, line.into()); + } + + pub fn status(&self) -> Vec { + self.units + .iter() + .map(|(name, u)| { + let s = u.shared.lock().unwrap(); + UnitStatus { name: name.clone(), state: s.state, pid: s.pid, restarts: s.restarts, result: s.result.clone(), since: s.since } + }) + .collect() + } + + pub fn state_of(&self, name: &str) -> UnitState { + self.units.get(name).map_or(UnitState::Inactive, |u| u.shared.lock().unwrap().state) + } + + /// Runs `spec`, restarting the unit if it runs another spec, leaving it be if it runs this one. + pub fn ensure(&mut self, spec: UnitSpec) { + if let Some(u) = self.units.get(&spec.name) { + let alive = !u.task.is_finished(); + if alive && u.spec == spec && u.shared.lock().unwrap().state != UnitState::Failed { + return; + } + } + self.start(spec); + } + + /// Starts `spec`, stopping what ran under its name first. + pub fn start(&mut self, spec: UnitSpec) { + let name = spec.name.clone(); + self.stop_now(&name); + let shared = Arc::new(Mutex::new(Shared { state: UnitState::Activating, pid: None, restarts: 0, result: None, since: Some(now_ms()) })); + let (stop_tx, stop_rx) = watch::channel(false); + let ctx = RunCtx { + spec: spec.clone(), + shared: shared.clone(), + logs: self.logs.clone(), + feed: self.feed.clone(), + log_dir: self.log_dir.clone(), + #[cfg(windows)] + job: self.job.as_ref().map(|j| j.handle()), + }; + let task = tokio::spawn(run(ctx, stop_rx)); + self.units.insert(name, Unit { spec, shared, stop: stop_tx, task }); + } + + /// Restarts a unit with the spec it has. + pub fn restart(&mut self, name: &str) -> bool { + match self.units.get(name).map(|u| u.spec.clone()) { + Some(spec) => { + self.start(spec); + true + } + None => false, + } + } + + fn stop_now(&mut self, name: &str) { + if let Some(u) = self.units.remove(name) { + let _ = u.stop.send(true); + // The task kills the child as it sees the flag; it is not waited for here, but + // the next start of the unit waits for nothing either: a listener still held for a + // moment shows as one restart. + let shared = u.shared.clone(); + tokio::spawn(async move { + let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await; + shared.lock().unwrap().state = UnitState::Inactive; + }); + } + } + + /// Stops a unit and waits for its process to be gone. + pub async fn stop(&mut self, name: &str) { + if let Some(u) = self.units.remove(name) { + let _ = u.stop.send(true); + let _ = tokio::time::timeout(Duration::from_secs(10), u.task).await; + } + } + + pub fn names(&self) -> Vec { + self.units.keys().cloned().collect() + } + + pub async fn stop_all(&mut self) { + for name in self.names() { + self.stop(&name).await; + } + } +} + +struct RunCtx { + spec: UnitSpec, + shared: Arc>, + logs: Arc>>>, + feed: broadcast::Sender, + log_dir: PathBuf, + #[cfg(windows)] + job: Option, +} + +fn push_log( + logs: &Arc>>>, + feed: &broadcast::Sender, + log_dir: &std::path::Path, + unit: &str, + line: String, +) { + let entry = LogLine { unit: unit.to_owned(), at: now_ms(), line }; + { + let mut logs = logs.lock().unwrap(); + let ring = logs.entry(unit.to_owned()).or_default(); + if ring.len() >= RING { + ring.pop_front(); + } + ring.push_back(entry.clone()); + } + let path = log_dir.join(format!("{unit}.log")); + if std::fs::metadata(&path).is_ok_and(|m| m.len() > LOG_FILE_MAX) { + let _ = std::fs::rename(&path, log_dir.join(format!("{unit}.log.1"))); + } + if let Ok(mut f) = std::fs::OpenOptions::new().create(true).append(true).open(&path) { + let _ = writeln!(f, "{} {}", entry.at, entry.line); + } + let _ = feed.send(entry); +} + +async fn run(ctx: RunCtx, mut stop: watch::Receiver) { + let mut failures: VecDeque = VecDeque::new(); + let mut backoff = Duration::from_millis(500); + let log = |line: String| push_log(&ctx.logs, &ctx.feed, &ctx.log_dir, &ctx.spec.name, line); + loop { + let mut cmd = Command::new(&ctx.spec.program); + cmd.args(&ctx.spec.args) + .envs(ctx.spec.env.iter().map(|(k, v)| (k, v))) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .kill_on_drop(true); + if let Some(cwd) = &ctx.spec.cwd { + cmd.current_dir(cwd); + } + #[cfg(windows)] + { + // No console window for the children. + cmd.creation_flags(0x0800_0000); + } + let mut child = match cmd.spawn() { + Ok(c) => c, + Err(e) => { + let why = format!("cannot start {}: {e}", ctx.spec.program.display()); + log(format!("proxy-suite: {why}")); + let mut s = ctx.shared.lock().unwrap(); + s.state = UnitState::Failed; + s.result = Some(why); + return; + } + }; + #[cfg(windows)] + if let (Some(job), Some(handle)) = (ctx.job, child.raw_handle()) { + crate::job::assign(job, handle as isize); + } + { + let mut s = ctx.shared.lock().unwrap(); + s.pid = child.id(); + s.state = UnitState::Activating; + s.since = Some(now_ms()); + } + log(format!("proxy-suite: started {} (pid {})", ctx.spec.program.display(), child.id().unwrap_or(0))); + for pipe in [child.stdout.take().map(|p| Box::new(p) as Box), child.stderr.take().map(|p| Box::new(p) as _)].into_iter().flatten() { + let logs = ctx.logs.clone(); + let feed = ctx.feed.clone(); + let dir = ctx.log_dir.clone(); + let unit = ctx.spec.name.clone(); + tokio::spawn(async move { + let mut lines = BufReader::new(pipe).lines(); + while let Ok(Some(line)) = lines.next_line().await { + push_log(&logs, &feed, &dir, &unit, line); + } + }); + } + // Up once it has lived a moment: none of the backends tells when it is ready. + let started = Instant::now(); + let status = loop { + tokio::select! { + status = child.wait() => break Some(status), + _ = tokio::time::sleep(Duration::from_millis(700)), if ctx.shared.lock().unwrap().state == UnitState::Activating => { + ctx.shared.lock().unwrap().state = UnitState::Active; + } + _ = stop.changed() => { + if *stop.borrow() { + ctx.shared.lock().unwrap().state = UnitState::Deactivating; + let _ = child.start_kill(); + let _ = tokio::time::timeout(Duration::from_secs(5), child.wait()).await; + let mut s = ctx.shared.lock().unwrap(); + s.state = UnitState::Inactive; + s.pid = None; + return; + } + } + } + }; + let why = match status { + Some(Ok(s)) => format!("exited ({s})"), + Some(Err(e)) => format!("lost ({e})"), + None => "stopped".into(), + }; + log(format!("proxy-suite: {} {why}", ctx.spec.name)); + let now = Instant::now(); + failures.push_back(now); + while failures.front().is_some_and(|t| now - *t > START_LIMIT_INTERVAL) { + failures.pop_front(); + } + { + let mut s = ctx.shared.lock().unwrap(); + s.pid = None; + s.result = Some(why.clone()); + if failures.len() >= START_LIMIT { + s.state = UnitState::Failed; + drop(s); + log(format!("proxy-suite: {} failed {START_LIMIT} times in a minute; not restarting it", ctx.spec.name)); + return; + } + s.state = UnitState::Activating; + s.restarts += 1; + } + // A run that lasted a while starts the backoff over. + if started.elapsed() > Duration::from_secs(30) { + backoff = Duration::from_millis(500); + } + tokio::select! { + _ = tokio::time::sleep(backoff) => {} + _ = stop.changed() => { + if *stop.borrow() { + ctx.shared.lock().unwrap().state = UnitState::Inactive; + return; + } + } + } + backoff = (backoff * 2).min(Duration::from_secs(30)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn spec(name: &str, program: &str, args: &[&str]) -> UnitSpec { + UnitSpec { + name: name.into(), + program: program.into(), + args: args.iter().map(|s| s.to_string()).collect(), + env: Vec::new(), + cwd: None, + generation: "1".into(), + } + } + + #[cfg(unix)] + #[tokio::test] + async fn a_unit_runs_logs_and_stops() { + let dir = std::env::temp_dir().join(format!("ps-units-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut sup = Supervisor::new(dir.clone()); + sup.start(spec("echo", "sh", &["-c", "echo hello; sleep 30"])); + tokio::time::sleep(Duration::from_millis(1200)).await; + assert_eq!(sup.state_of("echo"), UnitState::Active); + assert!(sup.tail(Some("echo"), 10).iter().any(|l| l.line == "hello")); + sup.stop("echo").await; + assert_eq!(sup.state_of("echo"), UnitState::Inactive); + assert!(std::fs::read_to_string(dir.join("echo.log")).unwrap().contains("hello")); + } + + #[cfg(unix)] + #[tokio::test] + async fn a_dying_unit_is_restarted_then_given_up_on() { + let dir = std::env::temp_dir().join(format!("ps-units-die-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut sup = Supervisor::new(dir); + sup.start(spec("dies", "sh", &["-c", "exit 3"])); + tokio::time::sleep(Duration::from_secs(10)).await; + let st = sup.status(); + assert_eq!(st[0].state, UnitState::Failed); + assert!(st[0].restarts >= 3, "{st:?}"); + } + + #[tokio::test] + async fn a_missing_program_fails_at_once() { + let mut sup = Supervisor::new(std::env::temp_dir()); + sup.start(spec("missing", "/nonexistent/program", &[])); + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(sup.state_of("missing"), UnitState::Failed); + } +} diff --git a/windows/crates/ps-service/src/winsvc.rs b/windows/crates/ps-service/src/winsvc.rs new file mode 100644 index 0000000..0fa105a --- /dev/null +++ b/windows/crates/ps-service/src/winsvc.rs @@ -0,0 +1,119 @@ +//! The Windows service: registration, and the Service Control Manager's entry point. + +use std::ffi::OsString; +use std::time::Duration; + +use anyhow::{Context, Result}; +use windows_service::service::{ + ServiceAccess, ServiceAction, ServiceActionType, ServiceControl, ServiceControlAccept, ServiceErrorControl, + ServiceExitCode, ServiceFailureActions, ServiceFailureResetPeriod, ServiceInfo, ServiceStartType, ServiceState, + ServiceStatus, ServiceType, +}; +use windows_service::service_control_handler::{self, ServiceControlHandlerResult}; +use windows_service::service_manager::{ServiceManager, ServiceManagerAccess}; +use windows_service::{define_windows_service, service_dispatcher}; + +pub const NAME: &str = "ProxySuite"; +const DISPLAY: &str = "Proxy Suite"; +const DESCRIPTION: &str = "Runs Proxy Suite's proxy, tunnels and DPI bypass, and serves the app's settings."; + +pub fn install() -> Result<()> { + let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT | ServiceManagerAccess::CREATE_SERVICE) + .context("opening the Service Control Manager (run as an administrator)")?; + let info = ServiceInfo { + name: OsString::from(NAME), + display_name: OsString::from(DISPLAY), + service_type: ServiceType::OWN_PROCESS, + start_type: ServiceStartType::AutoStart, + error_control: ServiceErrorControl::Normal, + executable_path: std::env::current_exe()?, + launch_arguments: vec![], + dependencies: vec![], + account_name: None, // LocalSystem + account_password: None, + }; + let service = manager + .create_service(&info, ServiceAccess::CHANGE_CONFIG | ServiceAccess::START) + .context("creating the service")?; + service.set_description(DESCRIPTION)?; + // Restarted when it dies, as systemd's Restart=always. + service.update_failure_actions(ServiceFailureActions { + reset_period: ServiceFailureResetPeriod::After(Duration::from_secs(86400)), + reboot_msg: None, + command: None, + actions: Some(vec![ + ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(2) }, + ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(10) }, + ServiceAction { action_type: ServiceActionType::Restart, delay: Duration::from_secs(60) }, + ]), + })?; + service.start::<&str>(&[]).context("starting the service")?; + println!("{DISPLAY} is installed and started."); + Ok(()) +} + +pub fn uninstall() -> Result<()> { + let manager = ServiceManager::local_computer(None::<&str>, ServiceManagerAccess::CONNECT) + .context("opening the Service Control Manager (run as an administrator)")?; + let service = manager + .open_service(NAME, ServiceAccess::QUERY_STATUS | ServiceAccess::STOP | ServiceAccess::DELETE) + .context("opening the service")?; + if service.query_status()?.current_state != ServiceState::Stopped { + let _ = service.stop(); + for _ in 0..30 { + if service.query_status()?.current_state == ServiceState::Stopped { + break; + } + std::thread::sleep(Duration::from_millis(500)); + } + } + service.delete()?; + println!("{DISPLAY} is removed."); + Ok(()) +} + +define_windows_service!(ffi_service_main, service_main); + +pub fn dispatch() -> Result<()> { + service_dispatcher::start(NAME, ffi_service_main).context("not started by the Service Control Manager; use --console to run in a terminal") +} + +fn service_main(_args: Vec) { + if let Err(e) = run_service() { + tracing::error!("the service failed: {e:#}"); + } +} + +fn run_service() -> Result<()> { + let (stop_tx, stop_rx) = tokio::sync::oneshot::channel::<()>(); + let mut stop_tx = Some(stop_tx); + let handler = move |control| match control { + ServiceControl::Stop | ServiceControl::Shutdown => { + if let Some(tx) = stop_tx.take() { + let _ = tx.send(()); + } + ServiceControlHandlerResult::NoError + } + ServiceControl::Interrogate => ServiceControlHandlerResult::NoError, + _ => ServiceControlHandlerResult::NotImplemented, + }; + let status = service_control_handler::register(NAME, handler)?; + let set = |state: ServiceState, accept: ServiceControlAccept| { + status.set_service_status(ServiceStatus { + service_type: ServiceType::OWN_PROCESS, + current_state: state, + controls_accepted: accept, + exit_code: ServiceExitCode::Win32(0), + checkpoint: 0, + wait_hint: Duration::from_secs(10), + process_id: None, + }) + }; + set(ServiceState::Running, ServiceControlAccept::STOP | ServiceControlAccept::SHUTDOWN)?; + let rt = tokio::runtime::Runtime::new()?; + let result = rt.block_on(crate::run(None, None, async { + let _ = stop_rx.await; + })); + set(ServiceState::Stopped, ServiceControlAccept::empty())?; + result +}