diff --git a/windows/crates/ps-ctl/src/main.rs b/windows/crates/ps-ctl/src/main.rs index 3e7d622..fa85453 100644 --- a/windows/crates/ps-ctl/src/main.rs +++ b/windows/crates/ps-ctl/src/main.rs @@ -49,6 +49,11 @@ enum Cmd { #[command(subcommand)] verb: Option, }, + /// Telegram's WebSocket proxy (tg-ws-proxy). + Tg { + #[command(subcommand)] + verb: TgVerb, + }, /// The backend programs: what is installed, and installing them (administrator). Components { #[command(subcommand)] @@ -56,11 +61,19 @@ enum Cmd { }, } +#[derive(Subcommand)] +enum TgVerb { + /// Its tg:// links, to open in Telegram. + Link, +} + #[derive(Subcommand)] enum ZapretVerb { Status, On, Off, + /// The presets of the installed release; the one in use is marked. + Presets, /// Use this preset (zapret-discord-youtube), e.g. "general (ALT9)". Preset { name: String }, /// Which game traffic to handle: all, tcp, udp or null. @@ -509,6 +522,17 @@ async fn zapret(ctl: &Ctl, verb: Option) -> Result<()> { }) .await?; } + ZapretVerb::Presets => { + let r = ctl.call(Request::ZapretPresets).await?; + if ctl.json { + ctl.print(&r); + return Ok(()); + } + let current = r["current"].as_str().unwrap_or(""); + for p in r["presets"].as_array().into_iter().flatten().filter_map(Value::as_str) { + println!("{} {p}", if p == current { "*" } else { " " }); + } + } ZapretVerb::Preset { name } => { ctl.edit(|c| { edits::set_zapret_preset(c, &name); @@ -577,6 +601,12 @@ async fn real_main() -> Result<()> { Cmd::Proxy(p) => proxy(&ctl, p.verb).await?, Cmd::Zapret { verb } => zapret(&ctl, verb).await?, Cmd::Components { verb } => components(&ctl, verb).await?, + Cmd::Tg { verb: TgVerb::Link } => { + let r = ctl.call(Request::TgLinks).await?; + for l in r["links"].as_array().into_iter().flatten().filter_map(Value::as_str) { + println!("{l}"); + } + } Cmd::Config { verb } => match verb { ConfigVerb::Get => { let c = ctl.call(Request::ConfigGet).await?; diff --git a/windows/crates/ps-ipc/src/lib.rs b/windows/crates/ps-ipc/src/lib.rs index f12b83d..d4d4819 100644 --- a/windows/crates/ps-ipc/src/lib.rs +++ b/windows/crates/ps-ipc/src/lib.rs @@ -59,6 +59,10 @@ pub enum Request { Test { tags: Vec }, /// Components: what is installed, what the manifest wants. Components, + /// The presets the installed zapret release has, and the one configured. + ZapretPresets, + /// tg-ws-proxy's tg:// links, which carry its secret. Secrets scope. + TgLinks, /// Fetch and install components (all wanted, or the named ones). ComponentsInstall { names: Vec }, } diff --git a/windows/crates/ps-service/src/api.rs b/windows/crates/ps-service/src/api.rs index f908112..dc4ffc3 100644 --- a/windows/crates/ps-service/src/api.rs +++ b/windows/crates/ps-service/src/api.rs @@ -133,7 +133,7 @@ fn scope_of(req: &Request) -> Option { Request::Pin { .. } | Request::Mode { .. } | Request::RuleSetsUpdate => Some(Scope::Routing), Request::Disable { .. } | Request::SubsUpdate { .. } | Request::Test { .. } => Some(Scope::Outbounds), // Backend logs name the sites visited (at info), and errors may quote what was dialled. - Request::RenderedConfig | Request::Logs { .. } => Some(Scope::Secrets), + Request::RenderedConfig | Request::Logs { .. } | Request::TgLinks => Some(Scope::Secrets), Request::Restart { .. } | Request::Start { .. } | Request::Stop { .. } => Some(Scope::Services), _ => None, } @@ -454,6 +454,27 @@ pub async fn handle(req: Request, peer: &Peer, shared: &Shared) -> Response { Response::ok(json!(list)) } + Request::ZapretPresets => { + let s = shared.lock().await; + let bats: Vec = std::fs::read_dir(s.paths().bin().join("zapret")) + .into_iter() + .flatten() + .filter_map(|e| e.ok()?.file_name().into_string().ok()) + .collect(); + Response::ok(json!({ + "presets": ps_core::zapret::presets(&bats), + "current": s.cfg().zapret.discord_youtube.config_name, + })) + } + + Request::TgLinks => { + let s = shared.lock().await; + match crate::tg::secret(s.cfg(), s.paths()) { + Ok(secret) => Response::ok(json!({ "links": crate::tg::links(s.cfg(), &secret) })), + Err(e) => Response::err(format!("tg-ws-proxy's secret: {e:#}")), + } + } + Request::ComponentsInstall { names } => { // Programs the service runs as SYSTEM: an administrator's call, whatever the scopes. if !peer.admin { diff --git a/windows/crates/ps-service/src/tg.rs b/windows/crates/ps-service/src/tg.rs index 55afbed..4a092df 100644 --- a/windows/crates/ps-service/src/tg.rs +++ b/windows/crates/ps-service/src/tg.rs @@ -52,6 +52,26 @@ pub fn args(cfg: &Config, secret: &str) -> Vec { a } +/// The links tg-ws-proxy prints for itself: `dd` with the secret, and `ee` with the fake-TLS +/// domain after it when one is set. A wildcard listener is named by this machine's address. +pub fn links(cfg: &Config, secret: &str) -> Vec { + let t = &cfg.tg_ws_proxy; + let host = match t.listener.address.as_str() { + "0.0.0.0" => std::net::UdpSocket::bind("0.0.0.0:0") + .and_then(|s| s.connect("8.8.8.8:80").and_then(|()| s.local_addr())) + .map(|a| a.ip().to_string()) + .unwrap_or_else(|_| "127.0.0.1".into()), + h => h.to_owned(), + }; + let base = format!("tg://proxy?server={host}&port={}&secret=", t.listener.port); + let mut out = vec![format!("{base}dd{secret}")]; + if let Some(domain) = t.fake_tls_domain.as_deref().filter(|d| !d.is_empty()) { + let hex: String = domain.bytes().map(|b| format!("{b:02x}")).collect(); + out.push(format!("{base}ee{secret}{hex}")); + } + out +} + /// The secret: given, or read from `secretFile`, or one generated once and kept. pub fn secret(cfg: &Config, paths: &Paths) -> Result { let t = &cfg.tg_ws_proxy; @@ -89,6 +109,15 @@ pub fn unit(cfg: &Config, paths: &Paths, python: PathBuf) -> Result { mod tests { use super::*; + #[test] + fn links_are_tg_ws_proxys() { + let mut cfg = Config::default(); + cfg.tg_ws_proxy.listener.port = 1443; + assert_eq!(links(&cfg, "ab"), ["tg://proxy?server=127.0.0.1&port=1443&secret=ddab"]); + cfg.tg_ws_proxy.fake_tls_domain = Some("x.io".into()); + assert_eq!(links(&cfg, "ab")[1], "tg://proxy?server=127.0.0.1&port=1443&secret=eeab782e696f"); + } + #[test] fn upstreams_flags() { let mut cfg = Config::default(); diff --git a/windows/tools/dev-service.sh b/windows/tools/dev-service.sh new file mode 100755 index 0000000..0bc2dba --- /dev/null +++ b/windows/tools/dev-service.sh @@ -0,0 +1,51 @@ +#!/usr/bin/env bash +# The service on Linux, for working on the app: console mode with its own state directory and +# socket, a local sing-box Shadowsocks server as a demo outbound, and the zapret presets of a +# built release (tools/package.sh) when there is one. In the dev shell: +# +# tools/dev-service.sh [STATE_DIR] (Ctrl-C stops it all) +# cargo run -p ps-gui -- --socket "$XDG_RUNTIME_DIR/proxy-suite-dev.sock" +# +# The socket is not in STATE_DIR: a Unix socket's path is limited to about 100 bytes. +set -euo pipefail +cd "$(dirname "$0")/.." +STATE=$(realpath -m "${1:-${TMPDIR:-/tmp}/proxy-suite-dev}") +mkdir -p "$STATE" +SOCK=${SOCK:-${XDG_RUNTIME_DIR:-/tmp}/proxy-suite-dev.sock} +free_port() { python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1])'; } +# Chosen once and kept, as the configuration that names them is. +if [ ! -f "$STATE/ports" ]; then + echo "SS=$(free_port) PROXY=$(free_port) CLASH=$(free_port) TEST=$(free_port)" >"$STATE/ports" +fi +. "$STATE/ports" +KEY=a2tra2tra2tra2tra2traw== + +cat >"$STATE/server.json" </dev/null || true' EXIT + +# A configuration on the first run; after that, whatever the app made of it. +if [ ! -f "$STATE/config.json" ]; then + cat >"$STATE/config.json" </dev/null | tail -1 || true) +if [ -n "$release" ] && [ ! -e "$STATE/bin/zapret" ]; then + mkdir -p "$STATE/bin" && cp -r "$release" "$STATE/bin/zapret" +fi + +cargo build -q -p ps-service +target/debug/proxy-suite-service --console --state-dir "$STATE" --socket "$SOCK" & +SERVICE=$! +echo "the service: $SOCK (state in $STATE)" +wait $SERVICE