diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6f6a67c..c9e4d31 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -207,6 +207,8 @@ jobs: - name: plugin and host unit tests run: | cargo test -p leaf --features plugin --lib + cargo test -p leaf --features plugin-fetch --lib + cargo test -p leaf-ffi --lib --features plugin-fetch cargo test -p leaf-plugin-abi cargo test -p tls-cabi-rs -p shadowsocks-cabi-rs diff --git a/Makefile b/Makefile index bbdda72..1ed71c1 100644 --- a/Makefile +++ b/Makefile @@ -38,6 +38,8 @@ ABI_INCLUDE := leaf-plugin-abi/include plugin-test: cargo test -p leaf --features plugin --lib + cargo test -p leaf --features plugin-fetch --lib + cargo test -p leaf-ffi --lib --features plugin-fetch cargo test -p leaf-plugin-abi cargo test -p tls-cabi-rs -p shadowsocks-cabi-rs cd leaf-plugins/leaf-abi-go && go test -race ./... diff --git a/README.md b/README.md index af885e7..a01442c 100644 --- a/README.md +++ b/README.md @@ -133,6 +133,73 @@ surviving a plugin that is merely wrong. cooperative and deliberately hostile plugins; `make e2e` runs it, and `make plugin-test` runs each plugin's own unit tests. +### Plugins in a conf file, and downloading them + +A conf file declares each plugin once, in `[Plugin]`, and refers to it by name +from `[Proxy]`. The proxy lines say what a proxy does and are the same on every +platform; only `[Plugin]` says how this client gets hold of the code. + +```ini +[Plugin] +tls = url=https://cdn.example.com/plugins/1.2.0/tls_cabi_rs.dll, sha256=9f86d0..., size=3145728 +ss = path=./plugins/shadowsocks_cabi_rs.dll + +[Proxy] +; A layer inside a chain: no address or port. +TLS = plugin, plugin=tls, args-b64=eyJzZXJ2ZXJfbmFtZSI6ImV4YW1wbGUuY29tIn0 +; A plugin with a server of its own: address and port, as for any proxy. +SS = plugin, 1.2.3.4, 8388, plugin=ss, args=chacha20-ietf-poly1305;password +``` + +A `[Plugin]` entry takes `path`, `url`, `sha256` and `size`, and anything else +is an error rather than being skipped: this is the section that says where +executable code comes from. `args` is passed to the plugin as it is written; +`args-b64` is for arguments that contain a comma -- JSON, usually -- and accepts +either base64 alphabet, padded or not. The JSON config takes the same `url`, +`size` and `name` in a plugin outbound's settings. + +With the `plugin-fetch` feature, a plugin given by `url` is downloaded before +any outbound is built, into a cache keyed by its digest: +`//`. The digest is the version -- the same one is never +fetched twice, and a start whose cache already holds everything needs no +network. What makes that safe: + +- `https` only, redirects included, and only with `sha256`. The config vouches + for the file, so it has to say which file. +- The download goes to a temporary file, hashed as it arrives, and is renamed + into place only once the digest matches; nothing partial or unverified is ever + where the loader looks. A download that runs past `size` -- or past 64 MiB + when no size is given -- is stopped there. +- There is no default cache directory. Whether a directory is safe to load code + from depends on who can write to it, which only the app embedding leaf knows: + set `PLUGIN_CACHE_DIR` (and optionally `PLUGIN_FETCH_TIMEOUT`, in seconds; + 30 by default). A service running as SYSTEM wants a directory only + administrators can write to, such as one under `%ProgramData%` set up by the + installer. +- A reload uses the cache and never the network. A reload that needs a plugin + the cache does not have is refused, and asks for a restart. + +The download happens on the way into a start, before any listener or TUN route +exists, so it goes over the network directly rather than through the proxy +being started. To keep that start instant, an app can fetch ahead of time with +`leaf_prefetch_plugins` (in `leaf-ffi`, built with `--features plugin-fetch`) +as soon as it has the config, and show progress while it does. Its callback +runs on the calling thread, never concurrently and never after the call +returns, and gets: + +- one `QUEUED` or `CACHED` event per plugin, all of them before any download + starts, so the whole list -- and, with `size` in the config, the total -- is + known from the first events; +- for each download, `STARTED`, some `PROGRESS` (repeated about once a second + while a download waits on the server -- before `STARTED` too, while it is + still connecting -- so that a stalled one can still be cancelled), and + exactly one `DONE` or `FAILED`; +- per-plugin and overall byte counts, with -1 for a size not yet known. + +The callback returns `false` to cancel. The call returns `ERR_OK`, +`ERR_PLUGIN_FETCH` (some failed; the others are in the cache), `ERR_CANCELLED`, +or `ERR_CONFIG`. + ### Checking a plugin before you deploy it `--verify-plugin` runs the loader's own checks -- the path, the file's @@ -183,6 +250,10 @@ for a dynamically linked target instead -- `x86_64-unknown-linux-gnu` or `aarch64-unknown-linux-gnu` -- with cargo on the host, or with `cross` and the matching toolchain image. +To download plugins named by `url`, add `leaf/plugin-fetch`, which implies +`leaf/plugin` and needs the rustls TLS backend the default features already +select. + `leaf --verify-plugin ` on the result is the quickest way to tell a build that can load plugins from one that cannot: a build without the feature says so and exits non-zero. diff --git a/leaf-e2e/Cargo.toml b/leaf-e2e/Cargo.toml index 9efa24f..4f29b68 100644 --- a/leaf-e2e/Cargo.toml +++ b/leaf-e2e/Cargo.toml @@ -20,10 +20,13 @@ futures = "0.3" # our own: it changes the shape of `StartOptions`, and cargo unifies features # across a workspace build, so leaf-cli asking for it would otherwise leave this # crate compiling against a struct it cannot see. Every node passes `false`. -leaf = { path = "../leaf", features = ["auto-reload", "plugin"] } +leaf = { path = "../leaf", features = ["auto-reload", "plugin", "plugin-fetch"] } libloading = "0.7" libtest-mimic = "0.8" rcgen = "0.13" +# The https server the plugin-download cases fetch from. +rustls = { version = "0.23", default-features = false, features = ["std", "tls12", "aws_lc_rs"] } +tokio-rustls = { version = "0.26", default-features = false, features = ["tls12", "aws_lc_rs"] } rand = "0.8" serde_json = "1" sha2 = "0.10" diff --git a/leaf-e2e/README.md b/leaf-e2e/README.md index 7bfe61a..d9595ee 100644 --- a/leaf-e2e/README.md +++ b/leaf-e2e/README.md @@ -18,6 +18,7 @@ cargo test -p leaf-e2e -- --tag go # only the Go plugin cases cargo test -p leaf-e2e -- --tag hostile # only the misbehaving-plugin lane cargo test -p leaf-e2e -- --tag cli # only the cases that run the real binary cargo test -p leaf-e2e -- --tag stress # only the loads +cargo test -p leaf-e2e -- --tag fetch # only the plugin downloads cargo test -p leaf-e2e -- --no-tag perf # skip the cost meters cargo test -p leaf-e2e -- --no-tag slow # skip the bulk transfers and the loads cargo test -p leaf-e2e -- --tag soak # the nightly lane, minutes per case @@ -151,7 +152,7 @@ output. | Flag | Environment | Meaning | | --- | --- | --- | | `--strict` | `LEAF_E2E_STRICT=1` | A case skipped for a missing fixture fails instead | -| `--tag ` / `--no-tag ` | -- | Select by label: `native`, `plugin`, `go`, `cc`, `zig`, `differential`, `perf`, `hostile`, `cli`, `stress`, `soak`, `slow` | +| `--tag ` / `--no-tag ` | -- | Select by label: `native`, `plugin`, `go`, `cc`, `zig`, `differential`, `perf`, `hostile`, `cli`, `stress`, `soak`, `fetch`, `slow` | | -- | `TCP_INBOUND_ABORT_ON_CLOSE` | leaf's own option, inherited by the nodes a case starts. Turning it on runs the suite against inbound sockets that are reset rather than closed | | -- | `LEAF_CONFORMANCE_DESCRIPTOR` | Which descriptor the conformance plugin publishes; set per case, not by hand | | `--timeout-scale ` | `LEAF_E2E_TIMEOUT_SCALE` | Multiplies every deadline; for slow or sanitized runs | @@ -353,6 +354,33 @@ instead, for the things that live only there: own into it. The ABI warns about this one, and no in-process test can observe it. +## Plugin downloads + +`fetch/` covers plugins a config names by url. The cases download from +`src/plugin_server.rs`, an https server started per case whose routes are +scripted: a length that is announced, omitted or wrong, an error status, a +redirect, or a body held at a gate until the case opens it. Gates, not sleeps, +are how a case gets a download that is provably in flight, or a server that +provably never answers. + +The server's certificate comes from a CA generated for it, which the client +trusts only because the case passes it in `FetchOptions::extra_roots` -- a +field neither a config file nor the C API can reach. `refuses-an-untrusted- +server` leaves it out, and must fail. + +Every case that downloads runs its events through one checker, +`check_contract`, which is the promise an app builds its progress UI on: every +plugin announced before any download starts, each plugin's events in order, +exactly one terminal event each, byte counts that only grow and add up, and +every callback on the calling thread. After a failure, a cancel or a timeout, +the cases also check that the cache holds nothing at all -- no temporary file, +no unverified one. + +The C API's side of the same thing -- the event struct, the error codes, the +callback thread -- is tested in `leaf-ffi`'s own unit tests +(`cargo test -p leaf-ffi --lib --features plugin-fetch`) rather than here: the +FFI library is a Rust `dylib`, which does not link in a Windows debug build. + ## Known defects A case that hits a defect nobody has fixed yet is marked with diff --git a/leaf-e2e/src/lib.rs b/leaf-e2e/src/lib.rs index fec9d90..dd18fb3 100644 --- a/leaf-e2e/src/lib.rs +++ b/leaf-e2e/src/lib.rs @@ -33,6 +33,7 @@ pub mod meters; pub mod net; pub mod node; pub mod paths; +pub mod plugin_server; pub mod process; pub mod report; pub mod runner; diff --git a/leaf-e2e/src/node.rs b/leaf-e2e/src/node.rs index b36674f..c7a3d3a 100644 --- a/leaf-e2e/src/node.rs +++ b/leaf-e2e/src/node.rs @@ -246,6 +246,42 @@ impl Node { } } + /// Starts a node from conf text, the format the clients download, whose + /// socks inbound is on `socks_port`. Everything else about the node -- + /// outbounds, rules -- is whatever the text says. + pub async fn start_conf(name: &str, conf: &str, socks_port: u16) -> Result { + let node = Self::conf_node(name, socks_port); + node.start_with(leaf::Config::Str(conf.to_string()), None) + .await + } + + /// The same, expecting leaf to refuse the conf; returns what it said. + pub async fn start_conf_expecting_failure(name: &str, conf: &str) -> Result { + let node = Self::new(name); + let (rt_id, failure) = node.spawn(leaf::Config::Str(conf.to_string()))?; + match tokio::time::timeout(START_TIMEOUT, failure).await { + Ok(Ok(err)) => Ok(err), + Ok(Err(_)) => bail!("node [{}] start task vanished", name), + Err(_) => { + shutdown_detached(rt_id); + bail!( + "node [{}] started successfully but was expected to fail", + name + ) + } + } + } + + /// A node that stands for a conf started elsewhere: it carries only the + /// socks inbound, so that readiness is probed where the conf listens. + fn conf_node(name: &str, socks_port: u16) -> Self { + let mut node = Self::new(name); + node.inbounds + .push(cfg::socks_inbound("socks-in", socks_port)); + node.socks = Some(net::loopback(socks_port)); + node + } + fn spawn(&self, config: leaf::Config) -> Result<(u16, tokio::sync::oneshot::Receiver)> { let rt_id = NEXT_RUNTIME_ID.fetch_add(1, Ordering::Relaxed); let (tx, rx) = tokio::sync::oneshot::channel(); diff --git a/leaf-e2e/src/plugin_server.rs b/leaf-e2e/src/plugin_server.rs new file mode 100644 index 0000000..620afa4 --- /dev/null +++ b/leaf-e2e/src/plugin_server.rs @@ -0,0 +1,376 @@ +//! An https server that hands out plugin files, and misbehaves on request. +//! +//! This is what the `fetch/` cases download from. Each path has a [`Route`] +//! saying what to send and how: a length that is announced, omitted or wrong, +//! an error status, a redirect, or a body that stops at a [`Gate`] until the +//! case opens it. Gates are how the cases get the timing they need -- a +//! download that is provably in flight, a server that provably never answers +//! -- without sleeping and hoping. +//! +//! The certificate is issued by a CA generated per server, and the client side +//! trusts that CA explicitly through `FetchOptions::extra_roots`. Nothing else +//! does, which is what lets a case check that an untrusted server is refused. +//! +//! HTTP is written out by hand rather than served by a library, because +//! several routes exist to say things a correct server never would. + +use std::collections::HashMap; +use std::net::SocketAddr; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex}; + +use anyhow::{anyhow, Context, Result}; +use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpListener; +use tokio::sync::watch; +use tokio::task::JoinHandle; + +/// Holds a body back after `after` bytes until [`Gate::open`] is called. A +/// gate that is never opened is a server that stalls. +#[derive(Clone)] +pub struct Gate { + after: usize, + open: Arc>, +} + +impl Gate { + pub fn after(bytes: usize) -> Self { + Self { + after: bytes, + open: Arc::new(watch::channel(false).0), + } + } + + pub fn open(&self) { + self.open.send_replace(true); + } + + async fn wait(&self) { + let mut open = self.open.subscribe(); + let _ = open.wait_for(|open| *open).await; + } +} + +#[derive(Clone, Copy, Debug)] +pub enum Length { + /// `Content-Length` is the size of the body. + Exact, + /// `Transfer-Encoding: chunked`, so the client learns the size only at the + /// end. + Chunked, + /// `Content-Length` says this, whatever the body is. + Claim(u64), +} + +#[derive(Clone)] +pub struct Route { + status: u16, + body: Arc>, + length: Length, + location: Option, + gate: Option, +} + +impl Route { + pub fn ok(body: impl Into>>) -> Self { + Self { + status: 200, + body: body.into(), + length: Length::Exact, + location: None, + gate: None, + } + } + + pub fn status(status: u16) -> Self { + Self { + status, + body: Arc::new(Vec::new()), + length: Length::Exact, + location: None, + gate: None, + } + } + + pub fn redirect(location: impl Into) -> Self { + Self { + location: Some(location.into()), + ..Self::status(302) + } + } + + pub fn length(mut self, length: Length) -> Self { + self.length = length; + self + } + + pub fn gate(mut self, gate: Gate) -> Self { + self.gate = Some(gate); + self + } +} + +#[derive(Default)] +struct State { + routes: Mutex>, + requests: Mutex>, + /// Requests whose response is still being written. + active: AtomicUsize, + max_active: AtomicUsize, +} + +/// Counts a request as active for as long as it is alive. +struct Active(Arc); + +impl Active { + fn enter(state: &Arc) -> Self { + let now = state.active.fetch_add(1, Ordering::SeqCst) + 1; + state.max_active.fetch_max(now, Ordering::SeqCst); + Self(state.clone()) + } +} + +impl Drop for Active { + fn drop(&mut self) { + self.0.active.fetch_sub(1, Ordering::SeqCst); + } +} + +pub struct PluginServer { + addr: SocketAddr, + ca: CertificateDer<'static>, + state: Arc, + task: JoinHandle<()>, +} + +impl PluginServer { + pub async fn start() -> Result { + let (ca, chain, key) = issue_certificate()?; + let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); + let mut config = rustls::ServerConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .context("choosing TLS versions")? + .with_no_client_auth() + .with_single_cert(chain, key) + .context("installing the server certificate")?; + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + let acceptor = tokio_rustls::TlsAcceptor::from(Arc::new(config)); + + let listener = TcpListener::bind(("127.0.0.1", 0)).await?; + let addr = listener.local_addr()?; + let state = Arc::new(State::default()); + let serving = state.clone(); + let task = tokio::spawn(async move { + loop { + let Ok((tcp, _)) = listener.accept().await else { + return; + }; + let (acceptor, state) = (acceptor.clone(), serving.clone()); + tokio::spawn(async move { + // A client that gives up, or refuses the certificate, is + // one of the things under test; it is not a server error. + if let Ok(stream) = acceptor.accept(tcp).await { + let _ = serve(stream, state).await; + } + }); + } + }); + Ok(Self { + addr, + ca, + state, + task, + }) + } + + /// The CA to hand the client as its extra trusted root. + pub fn ca(&self) -> CertificateDer<'static> { + self.ca.clone() + } + + pub fn url(&self, path: &str) -> String { + format!("https://{}{}", self.addr, path) + } + + pub fn route(&self, path: &str, route: Route) { + self.state + .routes + .lock() + .unwrap() + .insert(path.to_string(), route); + } + + pub fn requests(&self, path: &str) -> usize { + self.state + .requests + .lock() + .unwrap() + .get(path) + .copied() + .unwrap_or(0) + } + + pub fn total_requests(&self) -> usize { + self.state.requests.lock().unwrap().values().sum() + } + + pub fn active(&self) -> usize { + self.state.active.load(Ordering::SeqCst) + } + + pub fn max_active(&self) -> usize { + self.state.max_active.load(Ordering::SeqCst) + } +} + +impl Drop for PluginServer { + fn drop(&mut self) { + self.task.abort(); + } +} + +async fn serve(mut stream: S, state: Arc) -> Result<()> +where + S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Unpin, +{ + let path = read_request_path(&mut stream).await?; + *state + .requests + .lock() + .unwrap() + .entry(path.clone()) + .or_default() += 1; + let _active = Active::enter(&state); + let route = state.routes.lock().unwrap().get(&path).cloned(); + let Some(route) = route else { + stream + .write_all(b"HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\nConnection: close\r\n\r\n") + .await?; + return Ok(stream.shutdown().await?); + }; + + if route.status != 200 { + let mut head = format!("HTTP/1.1 {} Scripted\r\n", route.status); + if let Some(location) = &route.location { + head.push_str(&format!("Location: {}\r\n", location)); + } + head.push_str("Content-Length: 0\r\nConnection: close\r\n\r\n"); + stream.write_all(head.as_bytes()).await?; + return Ok(stream.shutdown().await?); + } + + let mut head = String::from("HTTP/1.1 200 OK\r\nConnection: close\r\n"); + match route.length { + Length::Exact => head.push_str(&format!("Content-Length: {}\r\n", route.body.len())), + Length::Claim(claimed) => head.push_str(&format!("Content-Length: {}\r\n", claimed)), + Length::Chunked => head.push_str("Transfer-Encoding: chunked\r\n"), + } + head.push_str("\r\n"); + stream.write_all(head.as_bytes()).await?; + stream.flush().await?; + + let chunked = matches!(route.length, Length::Chunked); + let mut sent = 0; + for chunk in route.body.chunks(16 * 1024) { + if let Some(gate) = &route.gate { + // Split the chunk that crosses the gate, so exactly `after` bytes + // are out before it holds. + if sent <= gate.after && gate.after < sent + chunk.len() { + let (before, after) = chunk.split_at(gate.after - sent); + write_body(&mut stream, before, chunked).await?; + stream.flush().await?; + gate.wait().await; + write_body(&mut stream, after, chunked).await?; + sent += chunk.len(); + continue; + } + } + write_body(&mut stream, chunk, chunked).await?; + sent += chunk.len(); + } + if let Some(gate) = &route.gate { + if gate.after >= route.body.len() { + stream.flush().await?; + gate.wait().await; + } + } + if chunked { + stream.write_all(b"0\r\n\r\n").await?; + } + stream.flush().await?; + Ok(stream.shutdown().await?) +} + +async fn write_body(stream: &mut S, bytes: &[u8], chunked: bool) -> Result<()> +where + S: tokio::io::AsyncWrite + Unpin, +{ + if bytes.is_empty() { + return Ok(()); + } + if chunked { + stream + .write_all(format!("{:x}\r\n", bytes.len()).as_bytes()) + .await?; + stream.write_all(bytes).await?; + stream.write_all(b"\r\n").await?; + } else { + stream.write_all(bytes).await?; + } + Ok(()) +} + +/// Reads a request head and returns its path. Only GET is spoken here. +async fn read_request_path(stream: &mut S) -> Result +where + S: tokio::io::AsyncRead + Unpin, +{ + let mut head = Vec::new(); + let mut byte = [0u8; 1]; + while !head.ends_with(b"\r\n\r\n") { + if head.len() > 16 * 1024 { + return Err(anyhow!("request head is too long")); + } + if stream.read(&mut byte).await? == 0 { + return Err(anyhow!("connection closed inside the request head")); + } + head.push(byte[0]); + } + let head = String::from_utf8_lossy(&head); + let line = head.lines().next().unwrap_or_default(); + let mut parts = line.split_whitespace(); + match (parts.next(), parts.next()) { + (Some("GET"), Some(path)) => Ok(path.to_string()), + _ => Err(anyhow!("not a GET: [{}]", line)), + } +} + +/// A CA, and a certificate from it for the loopback address and `localhost`. +fn issue_certificate() -> Result<( + CertificateDer<'static>, + Vec>, + PrivateKeyDer<'static>, +)> { + let mut ca_params = rcgen::CertificateParams::new(Vec::::new())?; + ca_params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained); + ca_params + .distinguished_name + .push(rcgen::DnType::CommonName, "leaf-e2e plugin server CA"); + let ca_key = rcgen::KeyPair::generate()?; + let ca = ca_params.self_signed(&ca_key)?; + + let mut params = + rcgen::CertificateParams::new(vec!["localhost".to_string(), "127.0.0.1".to_string()])?; + params + .distinguished_name + .push(rcgen::DnType::CommonName, "leaf-e2e plugin server"); + let key = rcgen::KeyPair::generate()?; + let cert = params.signed_by(&key, &ca, &ca_key)?; + + Ok(( + ca.der().clone(), + vec![cert.der().clone()], + PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key.serialize_der())), + )) +} diff --git a/leaf-e2e/src/scenario.rs b/leaf-e2e/src/scenario.rs index c95815a..2d47c91 100644 --- a/leaf-e2e/src/scenario.rs +++ b/leaf-e2e/src/scenario.rs @@ -57,6 +57,9 @@ pub enum Tag { /// Runs for minutes rather than seconds. Excluded from the default lane; /// a nightly job runs it on its own. Soak, + /// Downloads plugins from the suite's own https server, the way a client + /// fetches the ones its config names by url. + Fetch, /// Noticeably slower than the rest; excluded from the quick lane. Slow, } @@ -74,6 +77,7 @@ impl Tag { Tag::Cli, Tag::Stress, Tag::Soak, + Tag::Fetch, Tag::Slow, ]; @@ -90,6 +94,7 @@ impl Tag { Tag::Cli => "cli", Tag::Stress => "stress", Tag::Soak => "soak", + Tag::Fetch => "fetch", Tag::Slow => "slow", } } diff --git a/leaf-e2e/src/scenarios/fetch.rs b/leaf-e2e/src/scenarios/fetch.rs new file mode 100644 index 0000000..a2bc148 --- /dev/null +++ b/leaf-e2e/src/scenarios/fetch.rs @@ -0,0 +1,1311 @@ +//! Downloading plugins by url, observed from the outside. +//! +//! A client downloads its config, and the config names some of its plugins by +//! url. These cases serve those plugins from [`PluginServer`] and check what a +//! client relies on: that a start or a prefetch puts the right file in the +//! cache and nothing else, that a full cache needs no network, that a bad or +//! hostile server costs a clear failure and never a file, and that the events +//! an app builds its progress UI on keep the shape they promise. +//! +//! Every download case runs its events through [`check_contract`], which is +//! that promise written down once: every plugin announced before any download +//! starts, each one's events in order, exactly one terminal event each, totals +//! that only grow and add up, and every callback on the calling thread. + +use std::path::{Path, PathBuf}; +use std::time::{Duration, Instant}; + +use anyhow::{anyhow, bail, ensure, Context, Result}; +use leaf::app::outbound::plugin_fetch::{self, FetchError, FetchEventKind, FetchOptions}; +use serde_json::json; +use sha2::{Digest, Sha256}; + +use crate::client::Socks5; +use crate::fixtures::Fixture; +use crate::flow; +use crate::net; +use crate::node::{cfg, Node}; +use crate::paths; +use crate::plugin_server::{Gate, Length, PluginServer, Route}; +use crate::scenario::{boxed, Scenario, Tag}; +use crate::servers::Origin; + +pub fn scenarios() -> Vec { + let plain = |id: &str, run: fn() -> crate::scenario::CaseFuture| { + Scenario::new(id.to_string(), "fetch", run) + .tags([Tag::Fetch]) + .timeout(Duration::from_secs(30)) + }; + let with_plugin = |id: &str, run: fn() -> crate::scenario::CaseFuture| { + Scenario::new(id.to_string(), "fetch", run) + .tags([Tag::Fetch, Tag::Plugin]) + .needs([Fixture::Conformance]) + .timeout(Duration::from_secs(30)) + }; + vec![ + with_plugin("fetch/prefetch-then-carry-traffic", || { + boxed(prefetch_then_carry_traffic()) + }), + with_plugin("fetch/start-downloads-what-was-not-prefetched", || { + boxed(start_downloads_what_was_not_prefetched()) + }), + with_plugin("fetch/a-url-without-an-extension-loads", || { + boxed(a_url_without_an_extension_loads()) + }), + with_plugin("fetch/reload-uses-the-cache-only", || { + boxed(reload_uses_the_cache_only()) + }), + with_plugin("fetch/outbound-test-uses-the-cache-only", || { + boxed(outbound_test_uses_the_cache_only()) + }), + plain("fetch/start-fails-when-a-download-fails", || { + boxed(start_fails_when_a_download_fails()) + }), + plain("fetch/start-requires-a-cache-directory", || { + boxed(start_requires_a_cache_directory()) + }), + plain("fetch/cache-hit-needs-no-network", || { + boxed(cache_hit_needs_no_network()) + }), + plain("fetch/events/parallel-with-a-cached-plugin", || { + boxed(parallel_with_a_cached_plugin()) + }), + plain("fetch/events/unknown-size", || boxed(unknown_size())), + plain("fetch/one-download-per-digest", || { + boxed(one_download_per_digest()) + }), + plain("fetch/rejects-a-digest-mismatch", || { + boxed(rejects_a_digest_mismatch()) + }), + plain("fetch/rejects-a-size-the-server-contradicts", || { + boxed(rejects_a_size_the_server_contradicts()) + }), + plain("fetch/stops-at-the-declared-size", || { + boxed(stops_at_the_declared_size()) + }), + plain("fetch/partial-failure-keeps-the-rest", || { + boxed(partial_failure_keeps_the_rest()) + }), + plain("fetch/cancel-mid-download", || boxed(cancel_mid_download())), + plain("fetch/times-out-on-a-stalled-server", || { + boxed(times_out_on_a_stalled_server()) + }), + plain("fetch/refuses-insecure-configs", || { + boxed(refuses_insecure_configs()) + }), + plain("fetch/refuses-a-redirect-to-http", || { + boxed(refuses_a_redirect_to_http()) + }), + plain("fetch/follows-an-https-redirect", || { + boxed(follows_an_https_redirect()) + }), + plain("fetch/refuses-an-untrusted-server", || { + boxed(refuses_an_untrusted_server()) + }), + plain("fetch/concurrent-prefetches-share-a-cache", || { + boxed(concurrent_prefetches_share_a_cache()) + }), + plain("fetch/respects-the-concurrency-limit", || { + boxed(respects_the_concurrency_limit()) + }), + ] +} + +// --------------------------------------------------------------------------- +// What a prefetch reported, and the contract it has to keep. + +#[derive(Clone, Debug)] +struct Seen { + kind: FetchEventKind, + index: usize, + count: usize, + plugin: String, + downloaded: u64, + total: Option, + all_downloaded: u64, + all_total: Option, + error: Option, + on_caller_thread: bool, +} + +struct Outcome { + result: Result<(), FetchError>, + events: Vec, + elapsed: Duration, +} + +impl Outcome { + fn kinds(&self, index: usize) -> Vec { + self.events + .iter() + .filter(|e| e.index == index) + .map(|e| e.kind) + .collect() + } + + fn failures(&self) -> Result> { + match &self.result { + Err(FetchError::Failed(failures)) => Ok(failures + .iter() + .map(|f| (f.plugin.clone(), f.reason.clone())) + .collect()), + other => bail!("expected some downloads to fail, got {:?}", other), + } + } + + fn succeeded(&self) -> Result<()> { + match &self.result { + Ok(()) => Ok(()), + Err(err) => bail!("prefetch failed: {}; events: {:#?}", err, self.events), + } + } +} + +/// Runs a prefetch on a blocking thread, as an app would, so that the case's +/// runtime -- and the server on it -- keeps going meanwhile. `answer` decides +/// what the callback returns. +async fn prefetch( + conf: &str, + options: FetchOptions, + mut answer: impl FnMut(&Seen) -> bool + Send + 'static, +) -> Result { + let config = leaf::config::from_string(conf).map_err(|e| anyhow!("bad conf: {:#}", e))?; + tokio::task::spawn_blocking(move || { + let caller = std::thread::current().id(); + let mut events = Vec::new(); + let started = Instant::now(); + let result = plugin_fetch::prefetch(&config, &options, &mut |event| { + let seen = Seen { + kind: event.kind, + index: event.index, + count: event.count, + plugin: event.plugin.to_string(), + downloaded: event.downloaded, + total: event.total, + all_downloaded: event.all_downloaded, + all_total: event.all_total, + error: event.error.map(str::to_string), + on_caller_thread: std::thread::current().id() == caller, + }; + let keep_going = answer(&seen); + events.push(seen); + keep_going + }); + Outcome { + result, + events, + elapsed: started.elapsed(), + } + }) + .await + .context("the prefetch thread panicked") +} + +/// Where each plugin can be in its events. +#[derive(Clone, Copy, Debug, PartialEq)] +enum Stage { + Unannounced, + Queued, + Started, + Finished, +} + +/// The promise [`plugin_fetch::prefetch`] makes to whoever builds a UI on it. +/// A cancelled prefetch keeps all of it except that plugins may be left +/// unfinished. +fn check_contract(events: &[Seen], count: usize, cancelled: bool) -> Result<()> { + let describe = || format!("{:#?}", events); + ensure!( + events.iter().all(|e| e.count == count && e.index < count), + "every event must say count={} and carry an index below it: {}", + count, + describe() + ); + ensure!( + events.iter().all(|e| e.on_caller_thread), + "a callback ran on a thread other than the caller's: {}", + describe() + ); + + // Every plugin announced, in order, before anything else. + let announced = count.min(events.len()); + ensure!( + cancelled || announced == count, + "only {} of {} plugins were announced: {}", + announced, + count, + describe() + ); + for (position, event) in events[..announced].iter().enumerate() { + ensure!( + matches!(event.kind, FetchEventKind::Queued | FetchEventKind::Cached) + && event.index == position, + "event {} should announce plugin {}: {}", + position, + position, + describe() + ); + } + + for event in events { + ensure!( + event.plugin == events[event.index].plugin, + "plugin {} changed its name: {}", + event.index, + describe() + ); + } + + let mut stages = vec![Stage::Unannounced; count]; + let mut downloaded = vec![0u64; count]; + let mut all_downloaded = 0u64; + for event in events { + let stage = &mut stages[event.index]; + *stage = match (*stage, event.kind) { + (Stage::Unannounced, FetchEventKind::Queued) => Stage::Queued, + (Stage::Unannounced, FetchEventKind::Cached) => Stage::Finished, + // The heartbeat: a download still connecting is reported too, + // so that it can be cancelled before the server answers. + (Stage::Queued, FetchEventKind::Progress) => Stage::Queued, + (Stage::Queued, FetchEventKind::Started) => Stage::Started, + (Stage::Queued, FetchEventKind::Failed) => Stage::Finished, + (Stage::Started, FetchEventKind::Progress) => Stage::Started, + (Stage::Started, FetchEventKind::Done | FetchEventKind::Failed) => Stage::Finished, + (from, kind) => bail!( + "plugin {} went from {:?} on {:?}: {}", + event.index, + from, + kind, + describe() + ), + }; + ensure!( + event.downloaded >= downloaded[event.index], + "plugin {}'s download count went backwards: {}", + event.index, + describe() + ); + downloaded[event.index] = event.downloaded; + ensure!( + event.all_downloaded >= all_downloaded, + "the overall download count went backwards: {}", + describe() + ); + all_downloaded = event.all_downloaded; + ensure!( + (event.kind == FetchEventKind::Failed) == event.error.is_some(), + "an error comes with FAILED and only with FAILED: {}", + describe() + ); + if event.kind == FetchEventKind::Done { + if let Some(total) = event.total { + ensure!( + event.downloaded == total, + "plugin {} finished at {} of {} bytes: {}", + event.index, + event.downloaded, + total, + describe() + ); + } + } + } + if !cancelled { + ensure!( + stages.iter().all(|s| *s == Stage::Finished), + "a plugin was left without a terminal event: {:?}: {}", + stages, + describe() + ); + let all_fine = events.iter().all(|e| e.kind != FetchEventKind::Failed); + if let Some(last) = events.last() { + if let (true, Some(all_total)) = (all_fine, last.all_total) { + ensure!( + last.all_downloaded == all_total, + "everything finished at {} of {} bytes overall: {}", + last.all_downloaded, + all_total, + describe() + ); + } + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// Configs, caches and files. + +fn sha256(bytes: &[u8]) -> String { + flow::hex(&Sha256::digest(bytes)) +} + +fn plugin_line(name: &str, url: &str, sha: &str, size: Option) -> String { + let mut line = format!("{} = url={}, sha256={}", name, url, sha); + if let Some(size) = size { + line.push_str(&format!(", size={}", size)); + } + line +} + +/// A conf that does nothing but name `plugins`: one proxy per plugin, which is +/// all a prefetch looks at. +fn prefetch_conf(plugins: &[String]) -> String { + let proxies: Vec = plugins + .iter() + .map(|line| { + let name = line.split('=').next().unwrap_or_default().trim(); + format!("P-{} = plugin, plugin={}", name, name) + }) + .collect(); + format!( + "[Plugin]\n{}\n[Proxy]\n{}\n", + plugins.join("\n"), + proxies.join("\n") + ) +} + +/// A conf a client could run: a socks inbound, one plugin relaying to +/// `origin`, and every connection through it. +fn relay_conf(socks_port: u16, plugin: &str, origin: std::net::SocketAddr) -> String { + format!( + "[General]\nloglevel = trace\nsocks-interface = 127.0.0.1\nsocks-port = {}\n\n\ + [Plugin]\n{}\n\n\ + [Proxy]\nRelay = plugin, {}, {}, plugin=relay\n\n\ + [Rule]\nFINAL, Relay\n", + socks_port, + plugin, + origin.ip(), + origin.port() + ) +} + +/// An empty cache directory of this case's own, kept with its artifacts so a +/// failure leaves the evidence behind. +fn fresh_cache(label: &str) -> Result { + let case = crate::report::case().unwrap_or_else(|| "in-process".to_string()); + let dir = paths::artifacts_dir()? + .join(paths::artifact_slug(&case)) + .join(format!("plugin-cache-{}", label)); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).with_context(|| format!("creating {}", dir.display()))?; + Ok(dir) +} + +fn scaled(duration: Duration) -> Duration { + duration.mul_f64(crate::runner::timeout_scale()) +} + +/// Options that trust `server`, and nothing else beyond the public roots. +fn trusting(server: &PluginServer, cache: &Path) -> FetchOptions { + let mut options = FetchOptions::new(cache); + options.extra_roots = vec![server.ca()]; + options.timeout = Some(scaled(Duration::from_secs(20))); + options +} + +fn files_in(dir: &Path) -> Vec { + let mut found = Vec::new(); + let mut pending = vec![dir.to_path_buf()]; + while let Some(dir) = pending.pop() { + let Ok(entries) = std::fs::read_dir(&dir) else { + continue; + }; + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + pending.push(path); + } else { + found.push(path); + } + } + } + found.sort(); + found +} + +/// A failure has to cost a clear error and never a file: nothing half-written +/// and nothing unverified may be left where the host could load it. +fn ensure_nothing_in(cache: &Path) -> Result<()> { + let files = files_in(cache); + ensure!( + files.is_empty(), + "the cache should hold nothing, and holds {:?}", + files + ); + Ok(()) +} + +fn ensure_cached(cache: &Path, sha: &str) -> Result { + let files = files_in(&cache.join(sha)); + ensure!( + files.len() == 1, + "expected one file under {}, found {:?}", + sha, + files + ); + let bytes = std::fs::read(&files[0])?; + ensure!( + sha256(&bytes) == sha, + "the cached file is not the pinned one" + ); + Ok(files[0].clone()) +} + +fn conformance_bytes() -> Result<(Vec, String)> { + let path = Fixture::Conformance.path()?; + let bytes = std::fs::read(&path).with_context(|| format!("reading {}", path.display()))?; + let name = path + .file_name() + .and_then(|n| n.to_str()) + .ok_or_else(|| anyhow!("unnamed fixture"))? + .to_string(); + Ok((bytes, name)) +} + +async fn wait_until(what: &str, mut condition: impl FnMut() -> bool) -> Result<()> { + let deadline = Instant::now() + scaled(Duration::from_secs(10)); + while !condition() { + if Instant::now() >= deadline { + bail!("gave up waiting until {}", what); + } + tokio::time::sleep(Duration::from_millis(5)).await; + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// With a real plugin: the file that was fetched is the file that runs. + +/// The flow a client follows: prefetch with progress, then start, and the +/// start finds everything in the cache and loads the plugin from there. +async fn prefetch_then_carry_traffic() -> Result<()> { + let server = PluginServer::start().await?; + let (bytes, name) = conformance_bytes()?; + let sha = sha256(&bytes); + let path = format!("/plugins/{}", name); + server.route(&path, Route::ok(bytes.clone())); + let cache = fresh_cache("main")?; + let origin = Origin::tcp_echo().await?; + let socks_port = net::reserve_dual_port()?; + let conf = relay_conf( + socks_port, + &plugin_line("relay", &server.url(&path), &sha, Some(bytes.len() as u64)), + origin.addr(), + ); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + outcome.succeeded()?; + check_contract(&outcome.events, 1, false)?; + ensure!( + outcome.events[0].total == Some(bytes.len() as u64) + && outcome.events[0].all_total == Some(bytes.len() as u64), + "the declared size should be known from the first event: {:?}", + outcome.events[0] + ); + let cached = ensure_cached(&cache, &sha)?; + ensure!( + cached.file_name().and_then(|n| n.to_str()) == Some(name.as_str()), + "the cached file should keep the url's name, got {}", + cached.display() + ); + + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + let node = Node::start_conf("client", &conf, socks_port).await?; + ensure!( + server.requests(&path) == 1, + "the start downloaded again instead of using the cache" + ); + let mut stream = Socks5::new(node.socks_addr()?) + .connect(origin.addr()) + .await?; + flow::echo_roundtrip(&mut stream, b"through a downloaded plugin").await?; + drop(stream); + node.shutdown().await +} + +/// An app that skips the prefetch still starts: the start downloads what is +/// missing itself, and then runs it. +async fn start_downloads_what_was_not_prefetched() -> Result<()> { + let server = PluginServer::start().await?; + let (bytes, name) = conformance_bytes()?; + let sha = sha256(&bytes); + let path = format!("/plugins/{}", name); + server.route(&path, Route::ok(bytes)); + let cache = fresh_cache("main")?; + let origin = Origin::tcp_echo().await?; + let socks_port = net::reserve_dual_port()?; + let conf = relay_conf( + socks_port, + &plugin_line("relay", &server.url(&path), &sha, None), + origin.addr(), + ); + + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + let node = Node::start_conf("client", &conf, socks_port).await?; + ensure!(server.requests(&path) == 1, "expected exactly one download"); + ensure_cached(&cache, &sha)?; + let mut stream = Socks5::new(node.socks_addr()?) + .connect(origin.addr()) + .await?; + flow::echo_roundtrip(&mut stream, b"hello").await?; + drop(stream); + node.shutdown().await +} + +/// A url whose last segment has no extension -- a release download, a `get` +/// endpoint -- still gives a file the platform's loader will open. +async fn a_url_without_an_extension_loads() -> Result<()> { + let server = PluginServer::start().await?; + let (bytes, _) = conformance_bytes()?; + let sha = sha256(&bytes); + let path = "/releases/download/v1/relay"; + server.route(path, Route::ok(bytes)); + let cache = fresh_cache("main")?; + let origin = Origin::tcp_echo().await?; + let socks_port = net::reserve_dual_port()?; + let conf = relay_conf( + socks_port, + &plugin_line("relay", &server.url(path), &sha, None), + origin.addr(), + ); + + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + let node = Node::start_conf("client", &conf, socks_port).await?; + let cached = ensure_cached(&cache, &sha)?; + let expected = format!("relay{}", std::env::consts::DLL_SUFFIX); + ensure!( + cached.file_name().and_then(|n| n.to_str()) == Some(expected.as_str()), + "the cached file should be named {}, got {}", + expected, + cached.display() + ); + let mut stream = Socks5::new(node.socks_addr()?) + .connect(origin.addr()) + .await?; + flow::echo_roundtrip(&mut stream, b"hello").await?; + drop(stream); + node.shutdown().await +} + +/// A reload never downloads. With the plugin unchanged it goes through from +/// the cache; with a plugin the cache has never seen it is refused, says a +/// restart is needed, and leaves the running config as it was. +async fn reload_uses_the_cache_only() -> Result<()> { + let server = PluginServer::start().await?; + let (bytes, name) = conformance_bytes()?; + let sha = sha256(&bytes); + let path = format!("/plugins/{}", name); + server.route(&path, Route::ok(bytes.clone())); + let other = flow::pseudo_random(4096, 7); + server.route("/plugins/other.dll", Route::ok(other.clone())); + let cache = fresh_cache("main")?; + let origin = Origin::tcp_echo().await?; + + let outbound = |url: &str, sha: &str| { + json!({ + "protocol": "plugin", + "tag": "relay", + "settings": { + "url": url, + "sha256": sha, + "name": "relay", + "host": origin.addr().ip().to_string(), + "port": origin.addr().port(), + }, + }) + }; + // One socks port for every version of the config: a reload keeps the + // inbounds it started with, and the file should say so too. + let socks_port = net::reserve_dual_port()?; + let node_config = |url: &str, sha: &str| { + Node::new("client") + .inbound(cfg::socks_inbound("socks-in", socks_port)) + .outbound(outbound(url, sha)) + }; + + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + let node = node_config(&server.url(&path), &sha) + .start_reloadable() + .await?; + ensure!( + server.requests(&path) == 1, + "the start should download once" + ); + + // Same plugin: from the cache, no request. + node.reload_to(&node_config(&server.url(&path), &sha)) + .await + .map_err(|e| anyhow!("an unchanged plugin should reload from the cache: {:#}", e))?; + ensure!(server.requests(&path) == 1, "the reload downloaded"); + + // A plugin the cache does not have: refused, and nothing fetched. + let refused = node + .reload_to(&node_config( + &server.url("/plugins/other.dll"), + &sha256(&other), + )) + .await; + let message = match refused { + Ok(()) => bail!("a reload that needs a new plugin should have been refused"), + Err(err) => format!("{:#}", err), + }; + ensure!( + message.contains("requires a restart"), + "unexpected error: {}", + message + ); + ensure!( + server.requests("/plugins/other.dll") == 0, + "the reload downloaded" + ); + + let mut stream = Socks5::new(net::loopback(socks_port)) + .connect(origin.addr()) + .await?; + flow::echo_roundtrip(&mut stream, b"still the old config").await?; + drop(stream); + node.shutdown().await +} + +/// Testing an outbound never downloads, but reads the cache: it fails, saying +/// so, until the plugin is there, and a file put there by hand is as good as +/// a downloaded one. +async fn outbound_test_uses_the_cache_only() -> Result<()> { + let server = PluginServer::start().await?; + let (bytes, name) = conformance_bytes()?; + let sha = sha256(&bytes); + let path = format!("/plugins/{}", name); + server.route(&path, Route::ok(bytes.clone())); + let cache = fresh_cache("main")?; + let origin = Origin::tcp_echo().await?; + let conf = relay_conf( + net::reserve_dual_port()?, + &plugin_line("relay", &server.url(&path), &sha, None), + origin.addr(), + ); + let config = leaf::config::from_string(&conf)?; + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + + let message = match leaf::util::test_outbound("Relay", &config, None).await { + Ok(_) => bail!("testing a plugin the cache does not have should fail"), + Err(err) => format!("{:#}", err), + }; + ensure!( + message.contains("does not download plugins"), + "unexpected error: {}", + message + ); + ensure!(server.requests(&path) == 0, "the test downloaded"); + + // What a manual download leaves: the file at the place the cache names. + std::fs::create_dir_all(cache.join(&sha))?; + std::fs::write(cache.join(&sha).join(&name), &bytes)?; + // What the test then reaches is not the point here, only that it gets + // as far as trying. + let _ = leaf::util::test_outbound("Relay", &config, None) + .await + .map_err(|e| anyhow!("a cached plugin should build for a test: {:#}", e))?; + ensure!(server.requests(&path) == 0, "the test downloaded"); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Starts that cannot get their plugins. + +async fn start_fails_when_a_download_fails() -> Result<()> { + let server = PluginServer::start().await?; + server.route("/plugins/gone.dll", Route::status(404)); + let cache = fresh_cache("main")?; + let conf = relay_conf( + net::reserve_dual_port()?, + &plugin_line( + "relay", + &server.url("/plugins/gone.dll"), + &sha256(b"x"), + None, + ), + net::loopback(9), + ); + plugin_fetch::set_default_options(Some(trusting(&server, &cache))); + let error = Node::start_conf_expecting_failure("client", &conf).await?; + ensure!( + error.contains("plugin [relay]") && error.contains("HTTP 404"), + "the error should name the plugin and the reason: {}", + error + ); + ensure_nothing_in(&cache) +} + +/// There is no default cache: where code may be loaded from is the app's call. +async fn start_requires_a_cache_directory() -> Result<()> { + let server = PluginServer::start().await?; + plugin_fetch::set_default_options(None); + std::env::remove_var(plugin_fetch::ENV_CACHE_DIR); + let conf = relay_conf( + net::reserve_dual_port()?, + &plugin_line("relay", &server.url("/p.dll"), &sha256(b"x"), None), + net::loopback(9), + ); + let error = Node::start_conf_expecting_failure("client", &conf).await?; + ensure!( + error.contains(plugin_fetch::ENV_CACHE_DIR), + "the error should say what to set: {}", + error + ); + ensure!(server.total_requests() == 0, "nothing should be requested"); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Prefetch: the cache, and the events. + +async fn cache_hit_needs_no_network() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(100_000, 1); + let sha = sha256(&body); + server.route("/p.dll", Route::ok(body)); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line("p", &server.url("/p.dll"), &sha, None)]); + let options = trusting(&server, &cache); + + prefetch(&conf, options.clone(), |_| true) + .await? + .succeeded()?; + drop(server); + + let again = prefetch(&conf, options, |_| true).await?; + again.succeeded()?; + check_contract(&again.events, 1, false)?; + ensure!( + again.kinds(0) == [FetchEventKind::Cached], + "a second prefetch should only report the cache: {:?}", + again.events + ); + Ok(()) +} + +/// One cached plugin and two downloads running side by side: the list and the +/// overall total are there from the first events, and add up at the end. +async fn parallel_with_a_cached_plugin() -> Result<()> { + let server = PluginServer::start().await?; + let cache = fresh_cache("main")?; + let cached = flow::pseudo_random(10_000, 1); + let small = flow::pseudo_random(300_000, 2); + let large = flow::pseudo_random(1_000_000, 3); + std::fs::create_dir_all(cache.join(sha256(&cached)))?; + std::fs::write(cache.join(sha256(&cached)).join("cached.dll"), &cached)?; + server.route("/small.dll", Route::ok(small.clone())); + server.route("/large.dll", Route::ok(large.clone())); + let conf = prefetch_conf(&[ + plugin_line("cached", &server.url("/cached.dll"), &sha256(&cached), None), + plugin_line( + "small", + &server.url("/small.dll"), + &sha256(&small), + Some(300_000), + ), + plugin_line( + "large", + &server.url("/large.dll"), + &sha256(&large), + Some(1_000_000), + ), + ]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + outcome.succeeded()?; + check_contract(&outcome.events, 3, false)?; + let first: Vec<_> = outcome.events[..3].iter().map(|e| e.kind).collect(); + ensure!( + first + == [ + FetchEventKind::Cached, + FetchEventKind::Queued, + FetchEventKind::Queued + ], + "unexpected announcements: {:?}", + first + ); + ensure!( + outcome.events[..3] + .iter() + .all(|e| e.all_total == Some(1_300_000)), + "the overall total should be known before any download: {:?}", + &outcome.events[..3] + ); + ensure!( + server.requests("/cached.dll") == 0, + "a cached plugin was requested" + ); + ensure_cached(&cache, &sha256(&small))?; + ensure_cached(&cache, &sha256(&large))?; + Ok(()) +} + +async fn unknown_size() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(200_000, 4); + server.route("/p.dll", Route::ok(body.clone()).length(Length::Chunked)); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(&body), + None, + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + outcome.succeeded()?; + check_contract(&outcome.events, 1, false)?; + ensure!( + outcome + .events + .iter() + .all(|e| e.total.is_none() && e.all_total.is_none()), + "no size was declared or announced, so none should be reported: {:?}", + outcome.events + ); + let done = outcome.events.last().unwrap(); + ensure!( + done.kind == FetchEventKind::Done && done.downloaded == body.len() as u64, + "{:?}", + done + ); + ensure_cached(&cache, &sha256(&body))?; + Ok(()) +} + +/// Two names for one digest, used by three proxies, are one file. +async fn one_download_per_digest() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(50_000, 5); + let sha = sha256(&body); + server.route("/p.dll", Route::ok(body)); + let cache = fresh_cache("main")?; + let conf = format!( + "[Plugin]\n{}\n{}\n[Proxy]\nA = plugin, plugin=a\nB = plugin, plugin=b\nC = plugin, plugin=a\n", + plugin_line("a", &server.url("/p.dll"), &sha, None), + plugin_line("b", &server.url("/p.dll"), &sha.to_ascii_uppercase(), None), + ); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + outcome.succeeded()?; + check_contract(&outcome.events, 1, false)?; + ensure!(server.requests("/p.dll") == 1, "downloaded more than once"); + + let mut config = leaf::config::from_string(&conf).map_err(|e| anyhow!("{:#}", e))?; + plugin_fetch::resolve_from_cache(&mut config, &cache)?; + ensure!( + !plugin_fetch::has_url_plugins(&config)?, + "every outbound should now have its path" + ); + ensure!(files_in(&cache).len() == 1, "{:?}", files_in(&cache)); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Servers that send the wrong thing. + +async fn rejects_a_digest_mismatch() -> Result<()> { + let server = PluginServer::start().await?; + server.route("/p.dll", Route::ok(b"not what was pinned".to_vec())); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(b"the pinned file"), + None, + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!( + failures.len() == 1 && failures[0].1.contains("sha256 mismatch"), + "{:?}", + failures + ); + ensure_nothing_in(&cache) +} + +/// A server that announces a size other than the one the config declared is +/// refused before any of the body is read. +async fn rejects_a_size_the_server_contradicts() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(10_000, 6); + server.route( + "/p.dll", + Route::ok(body.clone()).length(Length::Claim(20_000)), + ); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(&body), + Some(10_000), + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!( + failures[0] + .1 + .contains("the server says the file is 20000 bytes"), + "{:?}", + failures + ); + ensure!( + outcome.kinds(0) == [FetchEventKind::Queued, FetchEventKind::Failed], + "nothing should have started: {:?}", + outcome.events + ); + ensure_nothing_in(&cache) +} + +/// A body that keeps coming past the declared size is cut off there, rather +/// than filling the disk. +async fn stops_at_the_declared_size() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(4 * 1024 * 1024, 7); + server.route("/p.dll", Route::ok(body).length(Length::Chunked)); + let cache = fresh_cache("main")?; + let declared = 64 * 1024u64; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(b"whatever"), + Some(declared), + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!(failures[0].1.contains("ran past"), "{:?}", failures); + ensure!( + outcome.events.iter().all(|e| e.downloaded <= declared), + "a download was reported past its declared size: {:?}", + outcome.events + ); + ensure_nothing_in(&cache) +} + +async fn partial_failure_keeps_the_rest() -> Result<()> { + let server = PluginServer::start().await?; + let good = flow::pseudo_random(100_000, 8); + server.route("/good.dll", Route::ok(good.clone())); + server.route("/bad.dll", Route::status(500)); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[ + plugin_line("good", &server.url("/good.dll"), &sha256(&good), None), + plugin_line("bad", &server.url("/bad.dll"), &sha256(b"x"), None), + ]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + check_contract(&outcome.events, 2, false)?; + let failures = outcome.failures()?; + ensure!( + failures.len() == 1 && failures[0].0 == "bad" && failures[0].1.contains("HTTP 500"), + "{:?}", + failures + ); + ensure_cached(&cache, &sha256(&good))?; + ensure!(files_in(&cache).len() == 1, "{:?}", files_in(&cache)); + Ok(()) +} + +// --------------------------------------------------------------------------- +// Stopping: by the app, and by the clock. + +/// The app cancels while a download is provably in flight: the prefetch ends +/// at once, says so, reports nothing further, and leaves nothing behind. +async fn cancel_mid_download() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(1024 * 1024, 9); + // Held after a quarter, and never let go: the download cannot finish, so + // it is still running whenever the callback is asked. + server.route( + "/p.dll", + Route::ok(body.clone()).gate(Gate::after(256 * 1024)), + ); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(&body), + None, + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |event| { + event.kind != FetchEventKind::Progress + }) + .await?; + ensure!( + matches!(outcome.result, Err(FetchError::Cancelled)), + "expected a cancel, got {:?}", + outcome.result + ); + check_contract(&outcome.events, 1, true)?; + ensure!( + outcome.events.last().map(|e| e.kind) == Some(FetchEventKind::Progress), + "nothing may be reported after the callback cancels: {:?}", + outcome.events + ); + ensure_nothing_in(&cache) +} + +/// A server that answers and then sends nothing: the heartbeat keeps the +/// callback informed, and the timeout ends it with a failure for that plugin. +async fn times_out_on_a_stalled_server() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(100_000, 10); + server.route("/p.dll", Route::ok(body.clone()).gate(Gate::after(0))); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(&body), + None, + )]); + let mut options = trusting(&server, &cache); + let timeout = Duration::from_millis(2500); + options.timeout = Some(timeout); + + let outcome = prefetch(&conf, options, |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!(failures[0].1.contains("timed out"), "{:?}", failures); + ensure!( + outcome.elapsed < timeout + scaled(Duration::from_secs(5)), + "took {:?} to time out after {:?}", + outcome.elapsed, + timeout + ); + ensure!( + outcome + .events + .iter() + .any(|e| e.kind == FetchEventKind::Progress && e.downloaded == 0), + "a stalled download should still be reported, so an app can cancel it: {:?}", + outcome.events + ); + ensure_nothing_in(&cache) +} + +// --------------------------------------------------------------------------- +// What will not be fetched at all. + +async fn refuses_insecure_configs() -> Result<()> { + let server = PluginServer::start().await?; + let cache = fresh_cache("main")?; + let sha = sha256(b"x"); + for (line, expected) in [ + ( + plugin_line( + "p", + &server.url("/p.dll").replace("https", "http"), + &sha, + None, + ), + "is not https", + ), + ( + format!("p = url={}", server.url("/p.dll")), + "pinned with sha256", + ), + ( + plugin_line("p", &server.url("/p.dll"), "1234", None), + "not 64 hex digits", + ), + ] { + let outcome = prefetch( + &prefetch_conf(std::slice::from_ref(&line)), + trusting(&server, &cache), + |_| true, + ) + .await?; + match &outcome.result { + Err(FetchError::Config(err)) if err.to_string().contains(expected) => {} + other => bail!( + "[{}]: expected a config error about [{}], got {:?}", + line, + expected, + other + ), + } + ensure!(outcome.events.is_empty(), "[{}] produced events", line); + } + ensure!(server.total_requests() == 0, "something was requested"); + ensure_nothing_in(&cache) +} + +async fn refuses_a_redirect_to_http() -> Result<()> { + let server = PluginServer::start().await?; + let insecure = server.url("/p2.dll").replace("https", "http"); + server.route("/p.dll", Route::redirect(insecure)); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line("p", &server.url("/p.dll"), &sha256(b"x"), None)]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!( + failures[0].1.contains("which is not https"), + "{:?}", + failures + ); + ensure_nothing_in(&cache) +} + +async fn follows_an_https_redirect() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(20_000, 11); + server.route("/old.dll", Route::redirect(server.url("/new.dll"))); + server.route("/new.dll", Route::ok(body.clone())); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/old.dll"), + &sha256(&body), + None, + )]); + + let outcome = prefetch(&conf, trusting(&server, &cache), |_| true).await?; + outcome.succeeded()?; + check_contract(&outcome.events, 1, false)?; + ensure!( + server.requests("/new.dll") == 1, + "the redirect was not followed" + ); + // Cached under the url the config gave, not the one it was redirected to. + ensure!( + cache.join(sha256(&body)).join("old.dll").is_file(), + "{:?}", + files_in(&cache) + ); + Ok(()) +} + +/// Without being told to trust the server's CA, the client must refuse it -- +/// which is what shows that the cases above trust it only because they said so. +async fn refuses_an_untrusted_server() -> Result<()> { + let server = PluginServer::start().await?; + server.route("/p.dll", Route::ok(b"x".to_vec())); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line("p", &server.url("/p.dll"), &sha256(b"x"), None)]); + let mut options = FetchOptions::new(&cache); + options.timeout = Some(scaled(Duration::from_secs(20))); + + let outcome = prefetch(&conf, options, |_| true).await?; + check_contract(&outcome.events, 1, false)?; + let failures = outcome.failures()?; + ensure!(failures[0].1.contains("TLS handshake"), "{:?}", failures); + ensure!(server.requests("/p.dll") == 0, "a request got through"); + ensure_nothing_in(&cache) +} + +// --------------------------------------------------------------------------- +// Concurrency. + +/// Two prefetches into one cache at once -- the app's and a start's, say -- +/// both succeed, and leave one whole file. +async fn concurrent_prefetches_share_a_cache() -> Result<()> { + let server = PluginServer::start().await?; + let body = flow::pseudo_random(1024 * 1024, 12); + let gate = Gate::after(0); + server.route("/p.dll", Route::ok(body.clone()).gate(gate.clone())); + let cache = fresh_cache("main")?; + let conf = prefetch_conf(&[plugin_line( + "p", + &server.url("/p.dll"), + &sha256(&body), + None, + )]); + + let first = tokio::spawn({ + let (conf, options) = (conf.clone(), trusting(&server, &cache)); + async move { prefetch(&conf, options, |_| true).await } + }); + let second = tokio::spawn({ + let (conf, options) = (conf.clone(), trusting(&server, &cache)); + async move { prefetch(&conf, options, |_| true).await } + }); + // Both in flight before either can finish. + wait_until("both prefetches have asked", || { + server.requests("/p.dll") == 2 + }) + .await?; + gate.open(); + + for outcome in [first.await??, second.await??] { + outcome.succeeded()?; + check_contract(&outcome.events, 1, false)?; + } + ensure_cached(&cache, &sha256(&body))?; + ensure!(files_in(&cache).len() == 1, "{:?}", files_in(&cache)); + Ok(()) +} + +/// Five plugins through a limit of two: two at a time, never more, and each +/// one let through only once the server has seen the limit reached. +async fn respects_the_concurrency_limit() -> Result<()> { + let server = PluginServer::start().await?; + let cache = fresh_cache("main")?; + let limit = 2; + let mut lines = Vec::new(); + let mut gates = Vec::new(); + for i in 0..5 { + let body = flow::pseudo_random(10_000, 100 + i); + let path = format!("/p{}.dll", i); + let gate = Gate::after(0); + server.route(&path, Route::ok(body.clone()).gate(gate.clone())); + lines.push(plugin_line( + &format!("p{}", i), + &server.url(&path), + &sha256(&body), + None, + )); + gates.push((path, gate, false)); + } + let mut options = trusting(&server, &cache); + options.max_concurrent = limit; + let conf = prefetch_conf(&lines); + let running = tokio::spawn(async move { prefetch(&conf, options, |_| true).await }); + + // Counted from the gates rather than from the server's active requests: a + // download that was just let through is still active while it finishes, + // and would stand in for one that has not yet been admitted. + let held = |gates: &[(String, Gate, bool)]| { + gates + .iter() + .filter(|(path, _, open)| !*open && server.requests(path) == 1) + .count() + }; + for released in 0..gates.len() { + let expected = limit.min(gates.len() - released); + wait_until( + &format!("{} downloads are held at their gates", expected), + || held(&gates) == expected, + ) + .await?; + // Let go of one that has been asked for. + let next = gates + .iter_mut() + .find(|(path, _, open)| !*open && server.requests(path) == 1) + .ok_or_else(|| anyhow!("no download is waiting at a gate"))?; + next.1.open(); + next.2 = true; + } + + let outcome = running.await??; + outcome.succeeded()?; + check_contract(&outcome.events, 5, false)?; + ensure!( + server.max_active() == limit, + "at most {} downloads should run at once, and that many should; saw {}", + limit, + server.max_active() + ); + Ok(()) +} diff --git a/leaf-e2e/src/scenarios/mod.rs b/leaf-e2e/src/scenarios/mod.rs index bc4ed67..2e8cc74 100644 --- a/leaf-e2e/src/scenarios/mod.rs +++ b/leaf-e2e/src/scenarios/mod.rs @@ -12,6 +12,7 @@ pub mod blackbox; pub mod coexist; pub mod datagram; pub mod differential; +pub mod fetch; pub mod halfclose; pub mod hostile; pub mod loader; @@ -34,6 +35,7 @@ pub fn all() -> Vec { .chain(teardown::scenarios()) .chain(halfclose::scenarios()) .chain(protocols::scenarios()) + .chain(fetch::scenarios()) .collect(); let mut seen = std::collections::BTreeSet::new(); diff --git a/leaf-ffi/Cargo.toml b/leaf-ffi/Cargo.toml index 28344a9..9b25998 100644 --- a/leaf-ffi/Cargo.toml +++ b/leaf-ffi/Cargo.toml @@ -29,8 +29,15 @@ default-openssl = [ auto-reload = ["leaf/auto-reload"] +plugin = ["leaf/plugin"] +# Adds downloading plugins by url to the start, and leaf_prefetch_plugins. +plugin-fetch = ["plugin", "leaf/plugin-fetch"] + [dependencies] leaf = { path = "../leaf", default-features = false, optional = true } tokio = { version = "1", features = ["rt"] } anyhow = "1.0" futures = "0.3" + +[dev-dependencies] +sha2 = "0.10" diff --git a/leaf-ffi/src/lib.rs b/leaf-ffi/src/lib.rs index 77927e0..e652b4c 100644 --- a/leaf-ffi/src/lib.rs +++ b/leaf-ffi/src/lib.rs @@ -21,6 +21,12 @@ pub const ERR_RUNTIME_MANAGER: i32 = 7; pub const ERR_NO_CONFIG_FILE: i32 = 8; /// No data found. pub const ERR_NO_DATA: i32 = 9; +/// At least one plugin the config names by url could not be downloaded. +pub const ERR_PLUGIN_FETCH: i32 = 10; +/// The caller cancelled the operation. +pub const ERR_CANCELLED: i32 = 11; +/// This build does not include what the call needs. +pub const ERR_UNSUPPORTED: i32 = 12; fn to_errno(e: leaf::Error) -> i32 { match e { @@ -32,6 +38,157 @@ fn to_errno(e: leaf::Error) -> i32 { leaf::Error::AsyncChannelSend(..) => ERR_ASYNC_CHANNEL_SEND, leaf::Error::SyncChannelRecv(..) => ERR_SYNC_CHANNEL_RECV, leaf::Error::RuntimeManager => ERR_RUNTIME_MANAGER, + leaf::Error::PluginFetch(..) => ERR_PLUGIN_FETCH, + leaf::Error::Cancelled => ERR_CANCELLED, + } +} + +/// The plugin is not in the cache and will be downloaded. +pub const LEAF_FETCH_QUEUED: i32 = 0; +/// The plugin is already in the cache. Terminal. +pub const LEAF_FETCH_CACHED: i32 = 1; +/// The server answered; `total` is known from here on if the server said. +pub const LEAF_FETCH_STARTED: i32 = 2; +/// Bytes arrived, or a download is still waiting for them; may come before +/// STARTED while the connection is being made. +pub const LEAF_FETCH_PROGRESS: i32 = 3; +/// Downloaded, and the sha256 matched. Terminal. +pub const LEAF_FETCH_DONE: i32 = 4; +/// Could not be fetched; `error` says why. Terminal. +pub const LEAF_FETCH_FAILED: i32 = 5; + +/// One event of a `leaf_prefetch_plugins` call. +/// +/// Fields may be added at the end in later versions; `size` is +/// `sizeof(LeafFetchEvent)` as this library knows it, so a caller built against +/// an older header can tell which fields are there. +#[repr(C)] +pub struct LeafFetchEvent { + pub size: u32, + /// One of the `LEAF_FETCH_*` values. + pub event: i32, + /// `0 .. count - 1`, stable for the whole call. + pub index: u32, + /// How many distinct plugins the call covers. + pub count: u32, + /// The name the config gave the plugin. Valid only during the callback. + pub plugin: *const c_char, + pub downloaded: i64, + /// -1 while unknown. + pub total: i64, + /// Summed over the plugins being downloaded; cached ones do not count. + pub all_downloaded: i64, + /// -1 while any download's size is unknown. + pub all_total: i64, + /// Set only for `LEAF_FETCH_FAILED`. Valid only during the callback. + pub error: *const c_char, +} + +/// Returns false to cancel the whole call. +pub type LeafFetchCallback = + extern "C" fn(event: *const LeafFetchEvent, context: *mut std::ffi::c_void) -> bool; + +/// Downloads the plugins a config names by url and the cache does not yet +/// hold, without starting anything. A later `leaf_run_*` with the same config +/// then finds them in the cache and starts at once. +/// +/// The cache directory comes from the `PLUGIN_CACHE_DIR` environment variable, +/// read when this is called. It must be a directory only this app can write +/// to; there is no default. +/// +/// Blocks until every plugin is in the cache, has failed, or the callback +/// cancelled. Each plugin first gets a QUEUED or CACHED event, all of them +/// before any download starts; each downloaded one then gets STARTED, some +/// PROGRESS, and exactly one DONE or FAILED. A download that has not finished +/// is reported with PROGRESS about once a second even when nothing has +/// arrived -- including before STARTED, while it is still connecting -- so +/// that the callback can cancel it. After a cancel there are no further events. +/// +/// The callback runs on the thread that called this function, never +/// concurrently, and never after it returns. +/// +/// @param config The content of the config file. +/// @param timeout_sec Limit for the whole call; 0 for the default of 30 seconds, +/// or `PLUGIN_FETCH_TIMEOUT` when that is set. +/// @param context Passed back to the callback. +/// @param callback May be NULL. +/// @return ERR_OK when every plugin is in the cache; ERR_PLUGIN_FETCH when at +/// least one could not be fetched, the rest having been; ERR_CANCELLED; +/// ERR_CONFIG for a config that cannot be fetched from as it is, or a +/// missing cache directory; ERR_UNSUPPORTED for a build without +/// plugin downloads. +#[no_mangle] +#[allow(unused_variables)] +pub unsafe extern "C" fn leaf_prefetch_plugins( + config: *const c_char, + timeout_sec: u32, + context: *mut std::ffi::c_void, + callback: Option, +) -> i32 { + #[cfg(not(feature = "plugin-fetch"))] + { + ERR_UNSUPPORTED + } + #[cfg(feature = "plugin-fetch")] + { + use leaf::app::outbound::plugin_fetch::{self, FetchEventKind, FetchOptions}; + use std::ffi::CString; + + let Ok(config) = (unsafe { CStr::from_ptr(config).to_str() }) else { + return ERR_CONFIG; + }; + let config = match leaf::config::from_string(config) { + Ok(config) => config, + Err(e) => return to_errno(leaf::Error::Config(e)), + }; + let mut options = match FetchOptions::from_env() { + Ok(options) => options, + // Only an error when there is something to download. + Err(e) => match plugin_fetch::has_url_plugins(&config) { + Ok(false) => return ERR_OK, + Ok(true) => return to_errno(leaf::Error::Config(e)), + Err(e) => return to_errno(leaf::Error::Config(e)), + }, + }; + if timeout_sec > 0 { + options.timeout = Some(std::time::Duration::from_secs(timeout_sec as u64)); + } + + let mut on_event = |event: &plugin_fetch::FetchEvent<'_>| -> bool { + let Some(callback) = callback else { + return true; + }; + // Interior NULs cannot come from a conf name or from an error this + // library wrote, but a C string cannot carry one either way. + let plugin = CString::new(event.plugin.replace('\0', "")).unwrap_or_default(); + let error = event + .error + .map(|e| CString::new(e.replace('\0', "")).unwrap_or_default()); + let raw = LeafFetchEvent { + size: std::mem::size_of::() as u32, + event: match event.kind { + FetchEventKind::Queued => LEAF_FETCH_QUEUED, + FetchEventKind::Cached => LEAF_FETCH_CACHED, + FetchEventKind::Started => LEAF_FETCH_STARTED, + FetchEventKind::Progress => LEAF_FETCH_PROGRESS, + FetchEventKind::Done => LEAF_FETCH_DONE, + FetchEventKind::Failed => LEAF_FETCH_FAILED, + }, + index: event.index as u32, + count: event.count as u32, + plugin: plugin.as_ptr(), + downloaded: event.downloaded as i64, + total: event.total.map_or(-1, |t| t as i64), + all_downloaded: event.all_downloaded as i64, + all_total: event.all_total.map_or(-1, |t| t as i64), + error: error.as_ref().map_or(std::ptr::null(), |e| e.as_ptr()), + }; + callback(&raw, context) + }; + match plugin_fetch::prefetch(&config, &options, &mut on_event) { + Ok(()) => ERR_OK, + Err(e) => to_errno(e.into()), + } } } @@ -382,3 +539,178 @@ pub unsafe extern "C" fn leaf_get_since_last_active( Err(e) => to_errno(e), } } + +/// The C side of `leaf_prefetch_plugins`: what reaches a callback, which codes +/// come back, and on which thread. What a download does is the fetch module's +/// business and is tested there and end to end; this is about the translation. +#[cfg(all(test, feature = "plugin-fetch"))] +mod prefetch_tests { + use super::*; + use sha2::Digest; + use std::ffi::{c_void, CString}; + + #[derive(Debug, Clone, PartialEq)] + struct Seen { + size: u32, + event: i32, + index: u32, + count: u32, + plugin: String, + downloaded: i64, + total: i64, + all_downloaded: i64, + all_total: i64, + error: Option, + } + + #[derive(Default)] + struct Recorder { + seen: Vec, + threads: Vec, + /// Answer `false` to the first event of this kind. + cancel_on: Option, + } + + extern "C" fn record(event: *const LeafFetchEvent, context: *mut c_void) -> bool { + let recorder = unsafe { &mut *(context as *mut Recorder) }; + let event = unsafe { &*event }; + let text = |p: *const c_char| unsafe { CStr::from_ptr(p) }.to_str().unwrap().to_string(); + recorder.seen.push(Seen { + size: event.size, + event: event.event, + index: event.index, + count: event.count, + plugin: text(event.plugin), + downloaded: event.downloaded, + total: event.total, + all_downloaded: event.all_downloaded, + all_total: event.all_total, + error: (!event.error.is_null()).then(|| text(event.error)), + }); + recorder.threads.push(std::thread::current().id()); + recorder.cancel_on != Some(event.event) + } + + fn prefetch(config: &str, recorder: &mut Recorder) -> i32 { + let config = CString::new(config).unwrap(); + unsafe { + leaf_prefetch_plugins( + config.as_ptr(), + 5, + recorder as *mut Recorder as *mut c_void, + Some(record), + ) + } + } + + fn conf(plugins: &str) -> String { + format!("[Plugin]\n{}\n[Proxy]\nP = plugin, plugin=p\n", plugins) + } + + /// One test, because the cache directory comes from the environment, which + /// every test in the process shares. + #[test] + fn translates_events_codes_and_threads() { + let dir = std::env::temp_dir().join(format!("leaf-ffi-prefetch-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + + // Without a cache directory: fine when there is nothing to download, + // a config error when there is. + std::env::remove_var("PLUGIN_CACHE_DIR"); + let mut recorder = Recorder::default(); + assert_eq!(prefetch(&conf("p = path=./p.dll"), &mut recorder), ERR_OK); + let sha = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; + // A closed port on loopback: refused at once, never anything else. + let refused = { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap().port() + }; + let unreachable = conf(&format!( + "p = url=https://127.0.0.1:{}/p.dll, sha256={}, size=1234", + refused, sha + )); + assert_eq!(prefetch(&unreachable, &mut recorder), ERR_CONFIG); + assert!(recorder.seen.is_empty()); + + std::env::set_var("PLUGIN_CACHE_DIR", &dir); + + // A config it will not download from is a config error, with no event. + let http = conf(&format!("p = url=http://127.0.0.1/p.dll, sha256={}", sha)); + assert_eq!(prefetch(&http, &mut recorder), ERR_CONFIG); + assert!(recorder.seen.is_empty()); + + // Everything cached: one CACHED event, and ERR_OK. + let body = b"cached plugin"; + let cached_sha = hex_of(&sha2::Sha256::digest(body)); + std::fs::create_dir_all(dir.join(&cached_sha)).unwrap(); + std::fs::write(dir.join(&cached_sha).join("c.dll"), body).unwrap(); + let cached = conf(&format!( + "p = url=https://127.0.0.1:{}/c.dll, sha256={}", + refused, cached_sha + )); + let mut recorder = Recorder::default(); + assert_eq!(prefetch(&cached, &mut recorder), ERR_OK); + assert_eq!( + recorder.seen, + vec![Seen { + size: std::mem::size_of::() as u32, + event: LEAF_FETCH_CACHED, + index: 0, + count: 1, + plugin: "p".to_string(), + downloaded: 0, + total: -1, + all_downloaded: 0, + all_total: 0, + error: None, + }] + ); + + // A download that fails: QUEUED with the declared size, then FAILED + // with a reason, ERR_PLUGIN_FETCH, all on this thread. Windows takes a + // couple of seconds to give up on a refused port, and the heartbeat + // reports the wait as PROGRESS; that is left out here. + let mut recorder = Recorder::default(); + assert_eq!(prefetch(&unreachable, &mut recorder), ERR_PLUGIN_FETCH); + let kinds: Vec = recorder + .seen + .iter() + .map(|s| s.event) + .filter(|&e| e != LEAF_FETCH_PROGRESS) + .collect(); + assert_eq!( + kinds, + vec![LEAF_FETCH_QUEUED, LEAF_FETCH_FAILED], + "{:?}", + recorder.seen + ); + assert_eq!(recorder.seen[0].total, 1234); + assert_eq!(recorder.seen[0].all_total, 1234); + assert!(recorder.seen[0].error.is_none()); + let reason = recorder.seen.last().unwrap().error.as_deref().unwrap(); + assert!(reason.contains("connecting to 127.0.0.1"), "{}", reason); + let me = std::thread::current().id(); + assert!(recorder.threads.iter().all(|t| *t == me)); + + // A callback that answers false: ERR_CANCELLED, and no further events. + let mut recorder = Recorder { + cancel_on: Some(LEAF_FETCH_QUEUED), + ..Default::default() + }; + assert_eq!(prefetch(&unreachable, &mut recorder), ERR_CANCELLED); + assert_eq!(recorder.seen.len(), 1); + + // A NULL callback is allowed. + let config = CString::new(unreachable).unwrap(); + let code = unsafe { leaf_prefetch_plugins(config.as_ptr(), 5, std::ptr::null_mut(), None) }; + assert_eq!(code, ERR_PLUGIN_FETCH); + + std::env::remove_var("PLUGIN_CACHE_DIR"); + let _ = std::fs::remove_dir_all(&dir); + } + + fn hex_of(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{:02x}", b)).collect() + } +} diff --git a/leaf/Cargo.toml b/leaf/Cargo.toml index 616699c..d9e9c02 100644 --- a/leaf/Cargo.toml +++ b/leaf/Cargo.toml @@ -101,7 +101,7 @@ openssl-aead = ["openssl"] openssl-tls = ["openssl", "tokio-openssl", "openssl-probe"] # Config formats -config-conf = ["regex"] +config-conf = ["regex", "base64"] config-json = ["serde", "serde_derive", "serde_json"] # Router rules @@ -146,6 +146,9 @@ inbound-cat = ["tokio/io-std"] inbound-nf = ["libloading"] plugin = ["async-ffi", "libloading", "leaf-plugin-abi", "sha2", "hex"] +# Downloads the plugins a config names by url, into a cache keyed by digest, +# before the outbounds are built. Needs rustls for the https client. +plugin-fetch = ["plugin", "rustls-tls", "url", "hyper", "hyper-util", "http-body-util", "http", "tokio/fs", "tokio/macros"] api = ["axum"] auto-reload = ["notify"] ctrlc = ["tokio/signal"] @@ -264,6 +267,11 @@ rustls = { version = "0.23", default-features = false, features = ["std"], optio reality = { git = "https://github.com/eycorsican/reality-rs.git", optional = true } reality-rustls = { package = "rustls", git = "https://github.com/eycorsican/reality-rustls.git", branch = "reality-rebase-0.23.36", optional = true, default-features = false, features = ["ring", "std", "tls12", "logging"] } +# plugin-fetch +hyper = { version = "1", default-features = false, features = ["client", "http1"], optional = true } +hyper-util = { version = "0.1", default-features = false, features = ["tokio"], optional = true } +http-body-util = { version = "0.1", optional = true } + # API axum = { version = "0.7", default-features = false, features = ["http1", "tokio", "json"], optional = true } diff --git a/leaf/src/app/outbound/manager.rs b/leaf/src/app/outbound/manager.rs index f9b4cbd..4659d88 100644 --- a/leaf/src/app/outbound/manager.rs +++ b/leaf/src/app/outbound/manager.rs @@ -674,6 +674,16 @@ impl OutboundManager { .map_err(|e| { anyhow!("invalid [{}] outbound settings: {}", &tag, e) })?; + if settings.path.is_empty() && !settings.url.is_empty() { + // With plugin-fetch the start fills the path in + // before this runs, so this is a build without it. + return Err(anyhow!( + "outbound [{}] names its plugin by url, and this build cannot \ + download plugins; rebuild with `--features leaf/plugin-fetch`, \ + or give the plugin a path", + &tag + )); + } if settings.path.is_empty() { return Err(anyhow!( "invalid [{}] outbound settings: plugin path is empty", diff --git a/leaf/src/app/outbound/mod.rs b/leaf/src/app/outbound/mod.rs index b37b815..8543464 100644 --- a/leaf/src/app/outbound/mod.rs +++ b/leaf/src/app/outbound/mod.rs @@ -14,5 +14,8 @@ pub mod selector_cache; #[cfg(feature = "plugin")] pub mod plugin; +#[cfg(feature = "plugin-fetch")] +pub mod plugin_fetch; + #[cfg(feature = "outbound-select")] pub type Selectors = HashMap>>; diff --git a/leaf/src/app/outbound/plugin.rs b/leaf/src/app/outbound/plugin.rs index 2d4fdd3..09ec94c 100644 --- a/leaf/src/app/outbound/plugin.rs +++ b/leaf/src/app/outbound/plugin.rs @@ -2062,7 +2062,7 @@ fn verify_plugin_digest(path: &Path, expected: &str) -> io::Result<()> { /// This is the value an operator puts in `sha256`, which is why /// [`inspect_plugin`] prints it whether or not one was pinned: the digest of a /// build you have in front of you is exactly what you need to pin it to. -fn plugin_file_digest(path: &Path) -> io::Result { +pub(crate) fn plugin_file_digest(path: &Path) -> io::Result { let mut file = std::fs::File::open(path).map_err(|err| { io::Error::other(format!( "failed to open plugin [{}] to digest it: {}", diff --git a/leaf/src/app/outbound/plugin_fetch.rs b/leaf/src/app/outbound/plugin_fetch.rs new file mode 100644 index 0000000..737b54d --- /dev/null +++ b/leaf/src/app/outbound/plugin_fetch.rs @@ -0,0 +1,1271 @@ +//! Downloading the plugins a config names by url. +//! +//! A plugin outbound that gives a `url` instead of a `path` is fetched into a +//! cache keyed by its digest -- `//` -- and its `path` is +//! filled in before any outbound is built. The digest is the version: the same +//! `sha256` is never downloaded twice, a config that moves to a new build moves +//! to a new directory, and a cache that already holds every file is all a start +//! needs, network or not. +//! +//! The rules that make that safe: +//! +//! * Only `https`, including every redirect along the way, and only together +//! with a `sha256`. The config is what vouches for the file, so the file has +//! to be pinned by it; a url alone would let whoever serves it decide what +//! runs. +//! * A download is written to a temporary file beside its destination, hashed +//! as it arrives, and renamed into place only once the digest matches. A +//! partial or wrong file is never at the path the host loads. The host checks +//! the pin again when it opens the library, which also covers the window +//! between this check and that one. +//! * A download that runs past the size the config declared, or past +//! [`MAX_UNDECLARED_SIZE`] when it declared none, is stopped there. +//! +//! [`prefetch`] reports what it does through a callback, on the calling thread +//! and never concurrently, with a fixed shape an embedding app can build a UI +//! on: one `Queued` or `Cached` event per plugin before any download starts, +//! then `Started`, `Progress` and exactly one `Done` or `Failed` for each one +//! it downloads. A download that has not finished is reported at least once a +//! second -- as `Progress`, even before the server has answered -- so the +//! callback can cancel one stuck connecting as well as one stuck mid-body. The +//! callback returns `false` to cancel. +//! +//! Where the cache lives is the embedding app's decision, not this module's: +//! whether a directory is safe to load code from depends on who can write to +//! it, which only the app and its installer know. It comes from +//! [`FetchOptions`], or from `PLUGIN_CACHE_DIR`, and there is no default. + +use std::net::IpAddr; +use std::path::{Path, PathBuf}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use anyhow::{anyhow, bail, Context}; +use bytes::Bytes; +use http_body_util::{BodyExt, Empty}; +use hyper_util::rt::TokioIo; +use protobuf::Message; +use sha2::{Digest, Sha256}; +use tokio::io::AsyncWriteExt; +use tokio::sync::{mpsc, Semaphore}; +use tokio::time::Instant; +use tokio_rustls::rustls::{ + self, + pki_types::{CertificateDer, ServerName}, + ClientConfig, RootCertStore, +}; +use tracing::{debug, info, warn}; + +use crate::config::internal; + +/// Where downloaded plugins are cached, when [`FetchOptions`] are not given. +pub const ENV_CACHE_DIR: &str = "PLUGIN_CACHE_DIR"; + +/// How long, in seconds, the download a start falls back to may take. +pub const ENV_TIMEOUT: &str = "PLUGIN_FETCH_TIMEOUT"; + +pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30); + +pub const DEFAULT_MAX_CONCURRENT: usize = 4; + +/// The most a download may bring in when the config declares no size. +pub const MAX_UNDECLARED_SIZE: u64 = 64 * 1024 * 1024; + +const MAX_REDIRECTS: usize = 5; + +/// How often a download in progress is reported. Bytes arrive far more often +/// than any UI wants to hear about them. +const PROGRESS_INTERVAL: Duration = Duration::from_millis(100); + +/// How long a download that has not finished may go unreported before it is +/// reported again with no new bytes. This is what gives the callback -- and so +/// the app -- a chance to cancel a download that has stalled, whether it is +/// stuck connecting, in the TLS handshake, waiting for a turn, or mid-body. +const HEARTBEAT_INTERVAL: Duration = Duration::from_secs(1); + +#[derive(Clone, Debug)] +pub struct FetchOptions { + pub cache_dir: PathBuf, + /// The whole prefetch, not each download. `None` waits as long as it takes. + pub timeout: Option, + pub max_concurrent: usize, + /// Trusted in addition to the public roots. Not reachable from a config + /// file or the C API: it exists for a test that serves plugins itself. + pub extra_roots: Vec>, +} + +impl FetchOptions { + pub fn new(cache_dir: impl Into) -> Self { + Self { + cache_dir: cache_dir.into(), + timeout: Some(DEFAULT_TIMEOUT), + max_concurrent: DEFAULT_MAX_CONCURRENT, + extra_roots: Vec::new(), + } + } + + /// Options from `PLUGIN_CACHE_DIR` and `PLUGIN_FETCH_TIMEOUT`, read now + /// rather than once per process, so an app can set them just before it + /// calls in. + pub fn from_env() -> anyhow::Result { + let cache_dir = std::env::var_os(ENV_CACHE_DIR) + .filter(|dir| !dir.is_empty()) + .ok_or_else(|| { + anyhow!( + "the config downloads plugins, but no cache directory was given; set {} to \ + a directory only this app can write to", + ENV_CACHE_DIR + ) + })?; + let mut options = Self::new(cache_dir); + if let Ok(secs) = std::env::var(ENV_TIMEOUT) { + let secs: u64 = secs + .trim() + .parse() + .map_err(|_| anyhow!("{} [{}] is not a number of seconds", ENV_TIMEOUT, secs))?; + options.timeout = Some(Duration::from_secs(secs)); + } + Ok(options) + } +} + +static DEFAULT_OPTIONS: Mutex> = Mutex::new(None); + +/// The options a start and a reload use, in place of the environment. +/// +/// For an embedder that links leaf as a Rust library; the C API has +/// `PLUGIN_CACHE_DIR` instead. +pub fn set_default_options(options: Option) { + *DEFAULT_OPTIONS.lock().unwrap() = options; +} + +fn default_options() -> anyhow::Result { + if let Some(options) = DEFAULT_OPTIONS.lock().unwrap().clone() { + return Ok(options); + } + FetchOptions::from_env() +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum FetchEventKind { + /// Not in the cache; will be downloaded. + Queued, + /// Already in the cache. Terminal. + Cached, + /// The server answered; `total` is known now if it was not before. + Started, + Progress, + /// Downloaded, and the digest matched. Terminal. + Done, + /// Terminal; `error` says why. + Failed, +} + +impl FetchEventKind { + pub fn is_terminal(self) -> bool { + matches!(self, Self::Cached | Self::Done | Self::Failed) + } +} + +#[derive(Clone, Debug)] +pub struct FetchEvent<'a> { + pub kind: FetchEventKind, + /// `0..count`, stable for the whole prefetch. + pub index: usize, + /// How many distinct plugins this prefetch covers. Plugins that share a + /// digest are one file, and count once. + pub count: usize, + /// The name the config gave the plugin. + pub plugin: &'a str, + pub downloaded: u64, + pub total: Option, + /// Summed over the plugins being downloaded; cached ones are not counted. + pub all_downloaded: u64, + /// `None` while any download's size is unknown. + pub all_total: Option, + pub error: Option<&'a str>, +} + +#[derive(Clone, Debug)] +pub struct FetchFailure { + pub plugin: String, + pub reason: String, +} + +#[derive(Debug, thiserror::Error)] +pub enum FetchError { + /// The config asks for something this module will not do, or there is + /// nowhere to put the result. Nothing was downloaded. + #[error(transparent)] + Config(anyhow::Error), + /// At least one plugin could not be fetched. The others were, and are in + /// the cache. + #[error("{}", describe_failures(.0))] + Failed(Vec), + #[error("plugin download cancelled")] + Cancelled, +} + +fn describe_failures(failures: &[FetchFailure]) -> String { + let each: Vec = failures + .iter() + .map(|f| format!("plugin [{}]: {}", f.plugin, f.reason)) + .collect(); + format!("failed to download plugins: {}", each.join("; ")) +} + +impl From for crate::Error { + fn from(err: FetchError) -> Self { + match err { + FetchError::Config(err) => crate::Error::Config(err), + FetchError::Failed(_) => crate::Error::PluginFetch(err.to_string()), + FetchError::Cancelled => crate::Error::Cancelled, + } + } +} + +/// One plugin outbound that is to come from a url. +struct UrlPlugin { + /// Index into `config.outbounds`. + outbound: usize, + name: String, + url: url::Url, + sha256: String, + size: Option, +} + +/// One file to have in the cache. Outbounds that name the same digest share it. +#[derive(Clone)] +struct Job { + name: String, + url: url::Url, + sha256: String, + size: Option, + path: PathBuf, +} + +fn plugin_settings( + outbound: &internal::Outbound, +) -> anyhow::Result { + internal::PluginOutboundSettings::parse_from_bytes(&outbound.settings) + .map_err(|e| anyhow!("invalid [{}] outbound settings: {}", outbound.tag, e)) +} + +/// The plugin outbounds that give a url and no path, validated. +fn url_plugins(config: &internal::Config) -> anyhow::Result> { + let mut found = Vec::new(); + for (index, outbound) in config.outbounds.iter().enumerate() { + if outbound.protocol != "plugin" { + continue; + } + let settings = plugin_settings(outbound)?; + if settings.url.is_empty() || !settings.path.is_empty() { + continue; + } + let name = if settings.name.is_empty() { + outbound.tag.clone() + } else { + settings.name.clone() + }; + let url = url::Url::parse(&settings.url).map_err(|e| { + anyhow!( + "plugin [{}]: url [{}] is not a url: {}", + name, + settings.url, + e + ) + })?; + if url.scheme() != "https" { + bail!( + "plugin [{}]: url [{}] is not https; plugins are only downloaded over https", + name, + settings.url + ); + } + if url.host().is_none() { + bail!("plugin [{}]: url [{}] names no host", name, settings.url); + } + let sha256 = settings.sha256.trim().to_ascii_lowercase(); + if sha256.is_empty() { + bail!( + "plugin [{}]: a plugin downloaded from a url has to be pinned with sha256; the \ + config is what vouches for the file, so it has to say which file", + name + ); + } + if sha256.len() != 64 || !sha256.bytes().all(|b| b.is_ascii_hexdigit()) { + bail!( + "plugin [{}]: sha256 [{}] is not 64 hex digits", + name, + settings.sha256 + ); + } + found.push(UrlPlugin { + outbound: index, + name, + url, + sha256, + size: (settings.size != 0).then_some(settings.size), + }); + } + Ok(found) +} + +/// Whether the config names any plugin by url, which is what decides whether a +/// start needs a cache directory at all. +pub fn has_url_plugins(config: &internal::Config) -> anyhow::Result { + Ok(!url_plugins(config)?.is_empty()) +} + +/// The last segment of the url's path, reduced to characters that are safe in +/// a file name on every platform. The name matters to nobody but a person +/// looking in the cache, and to Windows, which wants a `.dll` to load a DLL: +/// given a name with no extension, it looks for that name plus `.dll`, so a +/// name without one gets the platform's. +fn file_name_for(url: &url::Url) -> String { + let last = url + .path_segments() + .and_then(|mut segments| segments.next_back()) + .unwrap_or(""); + let cleaned: String = last + .chars() + .map(|c| { + if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_') { + c + } else { + '_' + } + }) + .collect(); + // A trailing dot is one more way for Windows to read a name as having no + // extension, and it drops the dot from the file anyway. + let cleaned = cleaned.trim_matches('.'); + if cleaned.is_empty() { + format!("plugin{}", std::env::consts::DLL_SUFFIX) + } else if !cleaned.contains('.') { + format!("{}{}", cleaned, std::env::consts::DLL_SUFFIX) + } else { + cleaned.to_string() + } +} + +/// One job per digest, in the order the config first names each one, and the +/// outbounds that each job's file serves. +fn plan(config: &internal::Config, cache_dir: &Path) -> anyhow::Result)>> { + let mut jobs: Vec<(Job, Vec)> = Vec::new(); + for plugin in url_plugins(config)? { + if let Some((_, outbounds)) = jobs.iter_mut().find(|(job, _)| job.sha256 == plugin.sha256) { + outbounds.push(plugin.outbound); + continue; + } + let path = cache_dir + .join(&plugin.sha256) + .join(file_name_for(&plugin.url)); + jobs.push(( + Job { + name: plugin.name, + url: plugin.url, + sha256: plugin.sha256, + size: plugin.size, + path, + }, + vec![plugin.outbound], + )); + } + Ok(jobs) +} + +/// Fills in `path` for every plugin outbound that gives a url, from the cache +/// alone. Fails, naming the plugin, if its file is not there. +pub fn resolve_from_cache(config: &mut internal::Config, cache_dir: &Path) -> anyhow::Result<()> { + for (job, outbounds) in plan(config, cache_dir)? { + if !job.path.is_file() { + bail!( + "plugin [{}] is not in the cache at [{}]", + job.name, + job.path.display() + ); + } + for index in outbounds { + let outbound = &mut config.outbounds[index]; + let mut settings = plugin_settings(outbound)?; + settings.path = job.path.display().to_string(); + outbound.settings = settings + .write_to_bytes() + .map_err(|e| anyhow!("re-encoding [{}] outbound settings: {}", outbound.tag, e))?; + } + } + Ok(()) +} + +/// Downloads whatever the config names by url and the cache does not yet +/// hold, reporting through `on_event` on this thread. Blocks until every +/// plugin is in the cache, has failed, or `on_event` returned `false`. +/// +/// It does not start anything, and it does not touch `config`; a start after +/// it finds everything in the cache. +pub fn prefetch( + config: &internal::Config, + options: &FetchOptions, + on_event: &mut dyn FnMut(&FetchEvent<'_>) -> bool, +) -> Result<(), FetchError> { + let jobs: Vec = plan(config, &options.cache_dir) + .map_err(FetchError::Config)? + .into_iter() + .map(|(job, _)| job) + .collect(); + if jobs.is_empty() { + return Ok(()); + } + // Current-thread, so that the callback runs on the caller's thread, which + // is what the C API promises and what lets an app skip locking. + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .map_err(|e| FetchError::Config(anyhow!("creating the download runtime: {}", e)))?; + rt.block_on(run(jobs, options, on_event)) +} + +/// What a start does before it builds any outbound: fetch what is missing, +/// then point the outbounds at the cache. A config that names nothing by url +/// needs no cache directory and costs nothing here. +pub fn prepare_for_start(config: &mut internal::Config) -> Result<(), crate::Error> { + if !has_url_plugins(config).map_err(crate::Error::Config)? { + return Ok(()); + } + let options = default_options().map_err(crate::Error::Config)?; + prefetch(config, &options, &mut log_event)?; + resolve_from_cache(config, &options.cache_dir).map_err(crate::Error::Config) +} + +/// What a reload does instead: the cache only, and never the network. Plugins +/// are not swapped under a running instance, so a reload that needs a plugin +/// the cache does not have is refused rather than half-applied. +pub fn prepare_for_reload(config: &mut internal::Config) -> Result<(), crate::Error> { + if !has_url_plugins(config).map_err(crate::Error::Config)? { + return Ok(()); + } + let options = default_options().map_err(crate::Error::Config)?; + resolve_from_cache(config, &options.cache_dir).map_err(|e| { + crate::Error::Config(anyhow!( + "{:#}; a reload does not download plugins, so a config that changes a plugin \ + requires a restart", + e + )) + }) +} + +/// What an outbound test does: like a reload, the cache only. A test is not +/// the place for a download the app did not ask for, so a plugin the cache +/// does not hold fails the test until something puts it there: a start, +/// `prefetch`, or a copy made by hand. +pub fn prepare_for_test(config: &mut internal::Config) -> Result<(), crate::Error> { + if !has_url_plugins(config).map_err(crate::Error::Config)? { + return Ok(()); + } + let options = default_options().map_err(crate::Error::Config)?; + resolve_from_cache(config, &options.cache_dir).map_err(|e| { + crate::Error::Config(anyhow!( + "{:#}; testing an outbound does not download plugins, so fetch them first \ + (leaf_prefetch_plugins, or a start)", + e + )) + }) +} + +fn log_event(event: &FetchEvent<'_>) -> bool { + match event.kind { + FetchEventKind::Cached => debug!(plugin = %event.plugin, "plugin is in the cache"), + FetchEventKind::Queued => { + info!(plugin = %event.plugin, total = ?event.total, "plugin will be downloaded") + } + FetchEventKind::Started => { + info!(plugin = %event.plugin, total = ?event.total, "downloading plugin") + } + FetchEventKind::Progress => {} + FetchEventKind::Done => { + info!(plugin = %event.plugin, bytes = event.downloaded, "downloaded plugin") + } + FetchEventKind::Failed => warn!( + plugin = %event.plugin, + error = event.error.unwrap_or(""), + "failed to download plugin" + ), + } + true +} + +/// What a download task tells the coordinator. Only the coordinator calls the +/// callback, so it is only ever called from one place, one event at a time. +enum Report { + Started { index: usize, total: Option }, + Progress { index: usize, downloaded: u64 }, + Done { index: usize, downloaded: u64 }, + Failed { index: usize, reason: String }, +} + +struct Tracker<'a> { + names: Vec, + cached: Vec, + downloaded: Vec, + total: Vec>, + terminal: Vec, + last_report: Vec>, + on_event: &'a mut dyn FnMut(&FetchEvent<'_>) -> bool, +} + +impl Tracker<'_> { + /// Reports one event, returning `false` when the callback asked to stop. + fn report(&mut self, kind: FetchEventKind, index: usize, error: Option<&str>) -> bool { + let downloading = || (0..self.names.len()).filter(|&i| !self.cached[i]); + let all_downloaded = downloading().map(|i| self.downloaded[i]).sum(); + let all_total = downloading().map(|i| self.total[i]).sum::>(); + if kind.is_terminal() { + self.terminal[index] = true; + } + self.last_report[index] = Some(Instant::now()); + let event = FetchEvent { + kind, + index, + count: self.names.len(), + plugin: &self.names[index], + downloaded: self.downloaded[index], + total: self.total[index], + all_downloaded, + all_total, + error, + }; + (self.on_event)(&event) + } + + /// Records what a task reported and passes it on, returning `false` when + /// the callback asked to stop. + fn apply(&mut self, message: Report, failures: &mut Vec) -> bool { + match message { + Report::Started { index, total } => { + if self.total[index].is_none() { + self.total[index] = total; + } + self.report(FetchEventKind::Started, index, None) + } + Report::Progress { index, downloaded } => { + self.downloaded[index] = downloaded; + // By time alone. A rule that also reported every percent would + // send a fast download's hundred of them in a tenth of a + // second, which no UI can use; the final count comes with DONE. + let due = + self.last_report[index].is_none_or(|at| at.elapsed() >= PROGRESS_INTERVAL); + if due { + self.report(FetchEventKind::Progress, index, None) + } else { + true + } + } + Report::Done { index, downloaded } => { + self.downloaded[index] = downloaded; + self.report(FetchEventKind::Done, index, None) + } + Report::Failed { index, reason } => { + failures.push(FetchFailure { + plugin: self.names[index].clone(), + reason: reason.clone(), + }); + self.report(FetchEventKind::Failed, index, Some(&reason)) + } + } + } +} + +async fn run( + jobs: Vec, + options: &FetchOptions, + on_event: &mut dyn FnMut(&FetchEvent<'_>) -> bool, +) -> Result<(), FetchError> { + let count = jobs.len(); + let cached: Vec = jobs.iter().map(is_cached).collect(); + let mut tracker = Tracker { + names: jobs.iter().map(|job| job.name.clone()).collect(), + cached: cached.clone(), + downloaded: vec![0; count], + total: jobs.iter().map(|job| job.size).collect(), + terminal: vec![false; count], + last_report: vec![None; count], + on_event, + }; + + // Every plugin is announced before anything touches the network, so an app + // can lay out its whole list, and its total, from the first events. + for (index, &is_cached) in cached.iter().enumerate() { + let kind = if is_cached { + FetchEventKind::Cached + } else { + FetchEventKind::Queued + }; + if !tracker.report(kind, index, None) { + return Err(FetchError::Cancelled); + } + } + if cached.iter().all(|&c| c) { + return Ok(()); + } + + let tls = Arc::new(client_config(&options.extra_roots).map_err(FetchError::Config)?); + let (tx, mut rx) = mpsc::unbounded_channel(); + let permits = Arc::new(Semaphore::new(options.max_concurrent.max(1))); + let mut tasks = tokio::task::JoinSet::new(); + for (index, job) in jobs.into_iter().enumerate() { + if cached[index] { + continue; + } + let (tls, permits, tx) = (tls.clone(), permits.clone(), tx.clone()); + tasks.spawn(async move { + let Ok(_permit) = permits.acquire_owned().await else { + return; + }; + let message = match download(index, &job, &tls, &tx).await { + Ok(downloaded) => Report::Done { index, downloaded }, + Err(err) => Report::Failed { + index, + reason: format!("{:#}", err), + }, + }; + let _ = tx.send(message); + }); + } + // Once the tasks' senders are all gone, the channel ends, and so does the + // loop below. + drop(tx); + + let deadline = options.timeout.map(|timeout| Instant::now() + timeout); + let mut failures = Vec::new(); + let mut heartbeat = tokio::time::interval(HEARTBEAT_INTERVAL / 2); + let cancelled = loop { + let expired = async { + match deadline { + Some(deadline) => tokio::time::sleep_until(deadline).await, + None => std::future::pending().await, + } + }; + let message = tokio::select! { + message = rx.recv() => message, + _ = expired => { + // Stop everything first, so that no task is still writing when + // its temporary file is removed. + tasks.abort_all(); + while tasks.join_next().await.is_some() {} + // A download can finish just as the deadline passes, with its + // DONE still queued: its file is in the cache by then, since + // nothing awaits between the rename and the send. Every task + // has stopped, so what is queued is all that will come. + let mut cancelled = false; + while let Ok(message) = rx.try_recv() { + if !tracker.apply(message, &mut failures) { + cancelled = true; + break; + } + } + let reason = format!( + "timed out after {:?}", + options.timeout.unwrap_or_default() + ); + for index in 0..count { + if cancelled { + break; + } + if tracker.terminal[index] { + continue; + } + failures.push(FetchFailure { + plugin: tracker.names[index].clone(), + reason: reason.clone(), + }); + if !tracker.report(FetchEventKind::Failed, index, Some(&reason)) { + cancelled = true; + break; + } + } + break cancelled; + } + _ = heartbeat.tick() => { + // Every download that has not finished, started or not: one + // stuck connecting or in the handshake is as much in need of a + // way to be cancelled as one stuck waiting for the body. + let now = Instant::now(); + let stale: Vec = (0..count) + .filter(|&i| { + !tracker.terminal[i] + && !cached[i] + && tracker.last_report[i] + .is_some_and(|at| now.duration_since(at) >= HEARTBEAT_INTERVAL) + }) + .collect(); + let mut keep_going = true; + for index in stale { + if !tracker.report(FetchEventKind::Progress, index, None) { + keep_going = false; + break; + } + } + if !keep_going { + break true; + } + continue; + } + }; + let Some(message) = message else { + break false; + }; + if !tracker.apply(message, &mut failures) { + break true; + } + }; + + tasks.abort_all(); + while tasks.join_next().await.is_some() {} + if cancelled { + return Err(FetchError::Cancelled); + } + + // A task that ended without saying how -- it panicked -- still owes its + // plugin a terminal event. + for index in 0..count { + if !tracker.terminal[index] { + let reason = "the download ended without a result".to_string(); + failures.push(FetchFailure { + plugin: tracker.names[index].clone(), + reason: reason.clone(), + }); + if !tracker.report(FetchEventKind::Failed, index, Some(&reason)) { + return Err(FetchError::Cancelled); + } + } + } + if failures.is_empty() { + Ok(()) + } else { + Err(FetchError::Failed(failures)) + } +} + +/// Whether the file for `job` is already in place, and is the file the config +/// pinned. A file that is there but wrong -- truncated by a disk that filled, +/// or replaced -- is removed, so that the download that follows can put the +/// right one in its place instead of failing on the pin forever. +fn is_cached(job: &Job) -> bool { + if !job.path.is_file() { + return false; + } + match super::plugin::plugin_file_digest(&job.path) { + Ok(digest) if digest == job.sha256 => true, + Ok(digest) => { + warn!( + plugin = %job.name, + path = %job.path.display(), + expected = %job.sha256, + found = %digest, + "cached plugin does not match its pin; downloading it again" + ); + if let Err(err) = std::fs::remove_file(&job.path) { + warn!(path = %job.path.display(), "failed to remove it: {}", err); + } + false + } + Err(err) => { + warn!(plugin = %job.name, "cannot read cached plugin: {}", err); + false + } + } +} + +fn client_config(extra_roots: &[CertificateDer<'static>]) -> anyhow::Result { + let mut roots = RootCertStore::empty(); + roots.extend(webpki_roots::TLS_SERVER_ROOTS.iter().cloned()); + for root in extra_roots { + roots + .add(root.clone()) + .map_err(|e| anyhow!("adding a trusted root: {}", e))?; + } + #[cfg(feature = "rustls-tls-aws-lc")] + let provider = rustls::crypto::aws_lc_rs::default_provider().into(); + #[cfg(not(feature = "rustls-tls-aws-lc"))] + let provider = rustls::crypto::ring::default_provider().into(); + let mut config = ClientConfig::builder_with_provider(provider) + .with_safe_default_protocol_versions() + .map_err(|e| anyhow!("building the TLS client: {}", e))? + .with_root_certificates(roots) + .with_no_client_auth(); + config.alpn_protocols = vec![b"http/1.1".to_vec()]; + Ok(config) +} + +/// A download in progress, removed when dropped unless it was put in place -- +/// which is what cleans up after a failure, a cancel and a timeout alike, +/// since each of them ends by dropping the task that owns it. +struct PartialFile { + path: PathBuf, + kept: bool, +} + +impl PartialFile { + fn beside(destination: &Path) -> Self { + static NEXT: AtomicU64 = AtomicU64::new(0); + let file_name = destination + .file_name() + .map(|name| name.to_string_lossy().into_owned()) + .unwrap_or_default(); + // Unique per process and per download, so that two processes, or two + // prefetches in one, never write to the same temporary file. + let temporary = format!( + ".{}.{}.{}.partial", + file_name, + std::process::id(), + NEXT.fetch_add(1, Ordering::Relaxed) + ); + Self { + path: destination.with_file_name(temporary), + kept: false, + } + } + + /// Moves the finished file to `destination`. When that fails because + /// someone else got there first -- another prefetch into the same cache, + /// or a loaded library Windows will not let anyone replace -- what is there + /// is as good as this, provided it is the same file. + fn persist(mut self, destination: &Path, sha256: &str) -> anyhow::Result<()> { + match std::fs::rename(&self.path, destination) { + Ok(()) => { + self.kept = true; + Ok(()) + } + Err(err) => match super::plugin::plugin_file_digest(destination) { + Ok(digest) if digest == sha256 => Ok(()), + _ => Err(anyhow!( + "moving the download to [{}] failed: {}", + destination.display(), + err + )), + }, + } + } +} + +impl Drop for PartialFile { + fn drop(&mut self) { + if !self.kept { + let _ = std::fs::remove_file(&self.path); + } + } +} + +/// Fetches one file into the cache, returning how many bytes it was. +async fn download( + index: usize, + job: &Job, + tls: &Arc, + tx: &mpsc::UnboundedSender, +) -> anyhow::Result { + let response = get_following_redirects(&job.url, tls).await?; + + let content_length = response + .headers() + .get(http::header::CONTENT_LENGTH) + .and_then(|value| value.to_str().ok()) + .and_then(|value| value.trim().parse::().ok()); + let limit = job.size.unwrap_or(MAX_UNDECLARED_SIZE); + if let (Some(declared), Some(announced)) = (job.size, content_length) { + if declared != announced { + bail!( + "the server says the file is {} bytes, and the config says {}", + announced, + declared + ); + } + } + if let Some(announced) = content_length { + if announced > limit { + bail!( + "the server says the file is {} bytes, more than the {} allowed", + announced, + limit + ); + } + } + let _ = tx.send(Report::Started { + index, + total: job.size.or(content_length), + }); + + let directory = job + .path + .parent() + .ok_or_else(|| anyhow!("[{}] has no parent directory", job.path.display()))?; + tokio::fs::create_dir_all(directory) + .await + .with_context(|| format!("creating [{}]", directory.display()))?; + let partial = PartialFile::beside(&job.path); + let mut file = tokio::fs::File::create(&partial.path) + .await + .with_context(|| format!("creating [{}]", partial.path.display()))?; + + let mut hasher = Sha256::new(); + let mut downloaded: u64 = 0; + let mut body = response.into_body(); + while let Some(frame) = body.frame().await { + let frame = frame.context("reading the response")?; + let Ok(data) = frame.into_data() else { + continue; + }; + downloaded += data.len() as u64; + if downloaded > limit { + bail!( + "the download ran past {} bytes, the most {} allows, and was stopped", + limit, + if job.size.is_some() { + "the size the config declares" + } else { + "a plugin with no declared size" + } + ); + } + hasher.update(&data); + file.write_all(&data) + .await + .with_context(|| format!("writing [{}]", partial.path.display()))?; + let _ = tx.send(Report::Progress { index, downloaded }); + } + file.flush().await?; + file.sync_all().await?; + // Closed before the rename: Windows will not move a file that is open. + drop(file); + + if let Some(declared) = job.size { + if downloaded != declared { + bail!("got {} bytes, and the config says {}", downloaded, declared); + } + } + let digest = hex::encode(hasher.finalize()); + if digest != job.sha256 { + bail!("sha256 mismatch: expected {}, found {}", job.sha256, digest); + } + partial.persist(&job.path, &job.sha256)?; + debug!(plugin = %job.name, path = %job.path.display(), "plugin is in the cache"); + Ok(downloaded) +} + +async fn get_following_redirects( + url: &url::Url, + tls: &Arc, +) -> anyhow::Result> { + let mut url = url.clone(); + for _ in 0..=MAX_REDIRECTS { + let response = get(&url, tls).await?; + let status = response.status(); + if status.is_redirection() { + let location = response + .headers() + .get(http::header::LOCATION) + .and_then(|value| value.to_str().ok()) + .ok_or_else(|| anyhow!("HTTP {} from [{}] with no location", status, url))?; + let next = url.join(location).map_err(|e| { + anyhow!( + "HTTP {} to [{}], which is not a url: {}", + status, + location, + e + ) + })?; + if next.scheme() != "https" { + bail!( + "[{}] redirects to [{}], which is not https; plugins are only downloaded \ + over https", + url, + next + ); + } + debug!(from = %url, to = %next, "following redirect"); + url = next; + continue; + } + if status != http::StatusCode::OK { + bail!("HTTP {} from [{}]", status, url); + } + return Ok(response); + } + bail!("more than {} redirects from [{}]", MAX_REDIRECTS, url) +} + +/// One GET, on a connection of its own. Plugins are few and fetched rarely, so +/// there is nothing a connection pool would save. +async fn get( + url: &url::Url, + tls: &Arc, +) -> anyhow::Result> { + let port = url.port_or_known_default().unwrap_or(443); + let (server_name, tcp) = match url.host() { + Some(url::Host::Domain(domain)) => ( + ServerName::try_from(domain.to_string()) + .map_err(|e| anyhow!("[{}] is not a valid server name: {}", domain, e))?, + tokio::net::TcpStream::connect((domain, port)).await, + ), + Some(url::Host::Ipv4(ip)) => ( + ServerName::IpAddress(IpAddr::V4(ip).into()), + tokio::net::TcpStream::connect((ip, port)).await, + ), + Some(url::Host::Ipv6(ip)) => ( + ServerName::IpAddress(IpAddr::V6(ip).into()), + tokio::net::TcpStream::connect((ip, port)).await, + ), + None => bail!("[{}] names no host", url), + }; + let authority = &url[url::Position::BeforeHost..url::Position::AfterPort]; + let tcp = tcp.with_context(|| format!("connecting to {}", authority))?; + let stream = tokio_rustls::TlsConnector::from(tls.clone()) + .connect(server_name, tcp) + .await + .with_context(|| format!("TLS handshake with {}", authority))?; + let (mut sender, connection) = hyper::client::conn::http1::handshake(TokioIo::new(stream)) + .await + .with_context(|| format!("HTTP handshake with {}", authority))?; + tokio::spawn(async move { + let _ = connection.await; + }); + let request = hyper::Request::get(&url[url::Position::BeforePath..url::Position::AfterQuery]) + .header(http::header::HOST, authority) + .header(http::header::USER_AGENT, "leaf-plugin-fetch") + .header(http::header::ACCEPT_ENCODING, "identity") + .body(Empty::::new())?; + sender + .send_request(request) + .await + .with_context(|| format!("requesting [{}]", url)) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn config(plugins: &str, proxies: &str) -> internal::Config { + crate::config::conf::from_string(&format!("[Plugin]\n{}\n[Proxy]\n{}\n", plugins, proxies)) + .unwrap() + } + + fn scratch(name: &str) -> PathBuf { + let dir = + std::env::temp_dir().join(format!("leaf-plugin-fetch-{}-{}", std::process::id(), name)); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir + } + + fn sha256_hex(bytes: &[u8]) -> String { + hex::encode(Sha256::digest(bytes)) + } + + const SHA: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; + + #[test] + fn refuses_what_it_will_not_download() { + for (plugin, expected) in [ + ( + format!("p = url=http://example.com/p.dll, sha256={SHA}"), + "is not https", + ), + ( + "p = url=https://example.com/p.dll".to_string(), + "has to be pinned with sha256", + ), + ( + "p = url=https://example.com/p.dll, sha256=abc".to_string(), + "not 64 hex digits", + ), + ( + format!("p = url=example.com/p.dll, sha256={SHA}"), + "is not a url", + ), + ] { + let config = config(&plugin, "P = plugin, plugin=p"); + let err = has_url_plugins(&config).unwrap_err().to_string(); + assert!(err.contains(expected), "[{}]: {}", plugin, err); + } + } + + #[test] + fn a_path_wins_over_a_url() { + let config = config( + &format!("p = path=./p.dll, url=https://example.com/p.dll, sha256={SHA}"), + "P = plugin, plugin=p", + ); + assert!(!has_url_plugins(&config).unwrap()); + } + + #[test] + fn file_names_are_safe_on_every_platform() { + let name = |url: &str| file_name_for(&url::Url::parse(url).unwrap()); + assert_eq!(name("https://x/a/tls_cabi_go.dll?v=2"), "tls_cabi_go.dll"); + assert_eq!(name("https://x/a/b%20c:d.dll"), "b_20c_d.dll"); + assert_eq!( + name("https://x/a/..."), + format!("plugin{}", std::env::consts::DLL_SUFFIX) + ); + assert_eq!( + name("https://x/"), + format!("plugin{}", std::env::consts::DLL_SUFFIX) + ); + // No extension, and a library loader has to be told what it is. + assert_eq!( + name("https://x/releases/download/v1/tls-plugin"), + format!("tls-plugin{}", std::env::consts::DLL_SUFFIX) + ); + assert_eq!( + name("https://x/get."), + format!("get{}", std::env::consts::DLL_SUFFIX) + ); + // An extension of any kind is left alone: the loader then takes the + // name as it is. + assert_eq!(name("https://x/libfoo.so.1"), "libfoo.so.1"); + } + + /// Two names for one digest are one file: one job, and both outbounds + /// pointed at it. + #[test] + fn plugins_that_share_a_digest_share_a_file() { + let dir = scratch("share"); + let config_in = config( + &format!( + "a = url=https://x/one.dll, sha256={SHA}\nb = url=https://y/two.dll, sha256={}", + SHA.to_ascii_uppercase() + ), + "A = plugin, plugin=a\nB = plugin, plugin=b\nC = plugin, plugin=a", + ); + let jobs = plan(&config_in, &dir).unwrap(); + assert_eq!(jobs.len(), 1); + assert_eq!(jobs[0].1.len(), 3); + assert_eq!(jobs[0].0.path, dir.join(SHA).join("one.dll")); + + let mut config_out = config_in.clone(); + let err = resolve_from_cache(&mut config_out, &dir) + .unwrap_err() + .to_string(); + assert!(err.contains("plugin [a] is not in the cache"), "{}", err); + + std::fs::create_dir_all(dir.join(SHA)).unwrap(); + std::fs::write(dir.join(SHA).join("one.dll"), b"x").unwrap(); + resolve_from_cache(&mut config_out, &dir).unwrap(); + for outbound in &config_out.outbounds { + let settings = plugin_settings(outbound).unwrap(); + assert_eq!(PathBuf::from(&settings.path), dir.join(SHA).join("one.dll")); + } + assert!( + !has_url_plugins(&config_out).unwrap(), + "every path is filled in" + ); + } + + /// A cache that already holds every file needs no network, and says so + /// with one `Cached` event per plugin. + #[test] + fn a_full_cache_is_reported_without_touching_the_network() { + let dir = scratch("full"); + let body = b"plugin bytes"; + let sha = sha256_hex(body); + std::fs::create_dir_all(dir.join(&sha)).unwrap(); + std::fs::write(dir.join(&sha).join("p.dll"), body).unwrap(); + let config = config( + // Port 9 on a documentation address: nothing answers there, so a + // request would fail the test rather than succeed by accident. + &format!("p = url=https://192.0.2.1:9/p.dll, sha256={sha}"), + "P = plugin, plugin=p", + ); + let mut events = Vec::new(); + prefetch(&config, &FetchOptions::new(&dir), &mut |event| { + events.push(( + event.kind, + event.index, + event.count, + event.plugin.to_string(), + )); + true + }) + .unwrap(); + assert_eq!( + events, + vec![(FetchEventKind::Cached, 0, 1, "p".to_string())] + ); + } + + /// A cached file that is not the one the config pinned is removed, so the + /// download that follows can replace it instead of failing the pin forever. + #[test] + fn a_wrong_file_in_the_cache_is_not_cached() { + let dir = scratch("wrong"); + std::fs::create_dir_all(dir.join(SHA)).unwrap(); + let path = dir.join(SHA).join("p.dll"); + std::fs::write(&path, b"not the pinned file").unwrap(); + let job = Job { + name: "p".to_string(), + url: url::Url::parse("https://x/p.dll").unwrap(), + sha256: SHA.to_string(), + size: None, + path: path.clone(), + }; + assert!(!is_cached(&job)); + assert!(!path.exists()); + } + + /// A server that takes the connection and then says nothing leaves the + /// download stuck in the TLS handshake, before any `Started`. It is still + /// reported once a second, so the callback can cancel it long before the + /// timeout would. + #[test] + fn a_download_stuck_before_the_server_answers_can_be_cancelled() { + let dir = scratch("stuck"); + // Never accepted: the kernel completes the connection from the + // backlog, and nothing ever writes a byte back. + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let port = listener.local_addr().unwrap().port(); + let config = config( + &format!("p = url=https://127.0.0.1:{port}/p.dll, sha256={SHA}"), + "P = plugin, plugin=p", + ); + let mut options = FetchOptions::new(&dir); + options.timeout = Some(Duration::from_secs(60)); + let mut seen = Vec::new(); + let began = std::time::Instant::now(); + let result = prefetch(&config, &options, &mut |event| { + seen.push(event.kind); + event.kind != FetchEventKind::Progress + }); + assert!(matches!(result, Err(FetchError::Cancelled)), "{:?}", result); + assert_eq!(seen, vec![FetchEventKind::Queued, FetchEventKind::Progress]); + assert!( + began.elapsed() < Duration::from_secs(10), + "cancelled only after {:?}", + began.elapsed() + ); + drop(listener); + } + + #[test] + fn cancelling_from_the_first_event_stops_before_any_download() { + let dir = scratch("cancel"); + let config = config( + &format!("p = url=https://192.0.2.1:9/p.dll, sha256={SHA}"), + "P = plugin, plugin=p", + ); + let mut seen = Vec::new(); + let result = prefetch(&config, &FetchOptions::new(&dir), &mut |event| { + seen.push(event.kind); + false + }); + assert!(matches!(result, Err(FetchError::Cancelled)), "{:?}", result); + assert_eq!(seen, vec![FetchEventKind::Queued]); + } + + #[test] + fn a_config_without_url_plugins_needs_no_cache_directory() { + let mut config = config("p = path=./p.dll", "P = plugin, plugin=p"); + // No options set, no environment: nothing to do, so nothing asked for. + prepare_for_start(&mut config).unwrap(); + } +} diff --git a/leaf/src/config/common.rs b/leaf/src/config/common.rs index 8c4eed8..29586dd 100644 --- a/leaf/src/config/common.rs +++ b/leaf/src/config/common.rs @@ -328,6 +328,9 @@ pub struct PluginOutboundSettings { pub host: Option, pub port: Option, pub sha256: Option, + pub url: Option, + pub size: Option, + pub name: Option, } #[derive(Serialize, Deserialize, Debug, Clone)] @@ -1430,6 +1433,15 @@ pub fn to_internal(mut config: Config) -> Result { if let Some(ext_sha256) = &ext_settings.sha256 { settings.sha256 = ext_sha256.clone(); } + if let Some(ext_url) = &ext_settings.url { + settings.url = ext_url.clone(); + } + if let Some(ext_size) = ext_settings.size { + settings.size = ext_size; + } + if let Some(ext_name) = &ext_settings.name { + settings.name = ext_name.clone(); + } let settings = settings.write_to_bytes().unwrap(); outbound.settings = settings; } diff --git a/leaf/src/config/conf/config.rs b/leaf/src/config/conf/config.rs index ed1f2c0..a6c800e 100644 --- a/leaf/src/config/conf/config.rs +++ b/leaf/src/config/conf/config.rs @@ -4,7 +4,8 @@ use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; -use anyhow::Result; +use anyhow::{anyhow, bail, Result}; +use base64::Engine; use regex::Regex; use crate::config::{common, internal}; @@ -100,6 +101,12 @@ pub struct Proxy { pub reality: Option, pub reality_public_key: Option, pub reality_short_id: Option, + + // plugin + /// The `[Plugin]` entry this proxy runs. + pub plugin: Option, + /// Handed to the plugin verbatim. Its shape is the plugin's business. + pub plugin_args: Option, } impl Default for Proxy { @@ -137,9 +144,27 @@ impl Default for Proxy { reality: Some(false), reality_public_key: None, reality_short_id: None, + plugin: None, + plugin_args: None, } } } + +/// A `[Plugin]` entry: where one plugin library comes from. +/// +/// Declared once and referenced by name from `[Proxy]` lines, so that the +/// lines that say what a proxy does stay the same on every platform, and only +/// this section says how a given client gets hold of the code. +#[derive(Debug, Default, Clone)] +pub struct PluginDecl { + /// A library already on disk. Wins over `url` when both are given. + pub path: Option, + /// Where to download the library from; https only, and only with `sha256`. + pub url: Option, + pub sha256: Option, + /// The size of the file at `url`, in bytes. + pub size: Option, +} #[derive(Debug)] pub struct ProxyGroup { pub tag: String, @@ -221,6 +246,7 @@ pub struct Config { pub host: Option>>, pub certificates: Option>, pub ech_configs: Option>, + pub plugin: Option>, } fn read_lines

(filename: P) -> io::Result>> @@ -453,6 +479,77 @@ where None } +/// Parses `[Plugin]`: `name = key=value, key=value, ...`. +/// +/// Stricter than the other sections, which skip what they do not understand. +/// This one says where executable code comes from, and a misspelt key there +/// -- `sha-256` for `sha256` -- would otherwise quietly remove the check the +/// operator meant to add. +fn parse_plugin_section(lines: Vec) -> Result> { + let mut plugins = HashMap::new(); + for line in lines { + let Some((name, rest)) = line.split_once('=') else { + bail!("[Plugin] line [{}] is not `name = key=value, ...`", line); + }; + let name = name.trim(); + if name.is_empty() { + bail!("[Plugin] line [{}] has no name", line); + } + let mut decl = PluginDecl::default(); + for param in rest.split(',').map(str::trim).filter(|p| !p.is_empty()) { + let Some((key, value)) = param.split_once('=') else { + bail!("plugin [{}]: [{}] is not key=value", name, param); + }; + let (key, value) = (key.trim(), value.trim()); + if value.is_empty() { + bail!("plugin [{}]: [{}] has no value", name, key); + } + match key { + "path" => decl.path = Some(value.to_string()), + "url" => decl.url = Some(value.to_string()), + "sha256" => decl.sha256 = Some(value.to_string()), + "size" => { + decl.size = Some(value.parse::().map_err(|_| { + anyhow!("plugin [{}]: size [{}] is not a byte count", name, value) + })?) + } + _ => bail!( + "plugin [{}]: unknown key [{}]; expected path, url, sha256 or size", + name, + key + ), + } + } + if decl.path.is_none() && decl.url.is_none() { + bail!( + "plugin [{}] says neither where it is (path) nor where to get it (url)", + name + ); + } + if plugins.insert(name.to_string(), decl).is_some() { + bail!("plugin [{}] is declared twice", name); + } + } + Ok(plugins) +} + +/// Decodes `args-b64`, which is how arguments that contain a comma -- JSON, +/// most often -- get through a format that splits on commas. +/// +/// Both alphabets are accepted, padded or not: the value is usually produced +/// by whatever generates the config, and which base64 it happened to use is +/// not worth failing over. +fn decode_plugin_args(tag: &str, value: &str) -> Result { + use base64::engine::general_purpose::{STANDARD_NO_PAD, URL_SAFE_NO_PAD}; + let trimmed = value.trim().trim_end_matches('='); + let bytes = URL_SAFE_NO_PAD + .decode(trimmed) + .or_else(|_| STANDARD_NO_PAD.decode(trimmed)) + .map_err(|e| anyhow!("proxy [{}]: args-b64 is not base64: {}", tag, e))?; + String::from_utf8(bytes) + .map_err(|_| anyhow!("proxy [{}]: args-b64 does not decode to UTF-8", tag)) +} + pub fn from_lines(lines: Vec>) -> Result { let certificates = get_certificate_sections(lines.iter()); let ech_configs = get_ech_sections(lines.iter()); @@ -573,6 +670,8 @@ pub fn from_lines(lines: Vec>) -> Result { } } + let plugins = parse_plugin_section(get_lines_by_section("Plugin", lines.iter()))?; + let mut proxies = Vec::new(); let proxy_lines = get_lines_by_section("Proxy", lines.iter()); for line in proxy_lines { @@ -601,7 +700,10 @@ pub fn from_lines(lines: Vec>) -> Result { // extract key-value params // let params = ¶ms[2..]; for param in ¶ms { - let parts: Vec<&str> = param.split('=').map(str::trim).collect(); + // Split at the first `=` only: a value may carry its own, as base64 + // padding does, and splitting on every one of them used to drop the + // whole parameter without a word. + let parts: Vec<&str> = param.splitn(2, '=').map(str::trim).collect(); if parts.len() != 2 { continue; } @@ -688,10 +790,43 @@ pub fn from_lines(lines: Vec>) -> Result { "interface" => { proxy.interface = v.to_string(); } + "plugin" => { + proxy.plugin = Some(v.to_string()); + } + "args" => { + proxy.plugin_args = Some(v.to_string()); + } + "args-b64" => { + proxy.plugin_args = Some(decode_plugin_args(&proxy.tag, v)?); + } _ => {} } } + // A plugin is either the last layer of a chain, which connects to its + // own server and so takes an address and a port, or a layer inside one, + // which must not. Which of the two it is, the plugin itself declares; + // the host checks the config against that when it loads it. + if proxy.protocol == "plugin" { + let endpoint: Vec<&String> = params[1..].iter().filter(|p| !p.contains('=')).collect(); + match endpoint.as_slice() { + [] => {} + [address, port] => { + proxy.address = Some(address.to_string()); + proxy.port = + Some(port.parse::().map_err(|_| { + anyhow!("proxy [{}]: [{}] is not a port", proxy.tag, port) + })?); + } + _ => bail!( + "proxy [{}]: a plugin proxy takes an address and a port, or neither", + proxy.tag + ), + } + proxies.push(proxy); + continue; + } + // built-in protocols have no address port, password match proxy.protocol.as_str() { "direct" => { @@ -985,6 +1120,11 @@ pub fn from_lines(lines: Vec>) -> Result { } else { Some(ech_configs) }, + plugin: if plugins.is_empty() { + None + } else { + Some(plugins) + }, }) } @@ -1144,6 +1284,41 @@ pub fn to_common(conf: &Config) -> Result { settings: common::OutboundSettings::Drop, }); } + "plugin" => { + let name = ext_proxy.plugin.as_ref().ok_or_else(|| { + anyhow!( + "proxy [{}] is a plugin proxy but names no plugin; add \ + plugin=", + ext_proxy.tag + ) + })?; + let decl = conf + .plugin + .as_ref() + .and_then(|plugins| plugins.get(name)) + .ok_or_else(|| { + anyhow!( + "proxy [{}] uses plugin [{}], which no [Plugin] entry declares", + ext_proxy.tag, + name + ) + })?; + outbounds.push(common::Outbound { + tag: Some(ext_proxy.tag.clone()), + settings: common::OutboundSettings::Plugin { + settings: Some(common::PluginOutboundSettings { + path: decl.path.clone(), + args: ext_proxy.plugin_args.clone(), + host: ext_proxy.address.clone(), + port: ext_proxy.port, + sha256: decl.sha256.clone(), + url: decl.url.clone(), + size: decl.size, + name: Some(name.clone()), + }), + }, + }); + } "redirect" => { outbounds.push(common::Outbound { tag: Some(ext_proxy.tag.clone()), @@ -1747,12 +1922,147 @@ AQI= host: None, certificates: None, ech_configs: None, + plugin: None, }; let err = to_internal(&config).unwrap_err(); assert!(err.to_string().contains("echConfigList cannot be empty")); } + fn plugin_settings_of( + config: &internal::Config, + tag: &str, + ) -> internal::PluginOutboundSettings { + let outbound = config + .outbounds + .iter() + .find(|o| o.tag == tag) + .unwrap_or_else(|| panic!("no outbound [{}]", tag)); + assert_eq!(outbound.protocol, "plugin"); + internal::PluginOutboundSettings::parse_from_bytes(&outbound.settings).unwrap() + } + + const SHA: &str = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08"; + + #[test] + fn plugin_proxies_take_their_source_from_the_plugin_section() { + let conf = format!( + r#" +[Plugin] +tls-go = url=https://cdn.example.com/p/tls.dll?v=1, sha256={SHA}, size=3145728 +ss = path=./plugins/ss.dll + +[Proxy] +TLS = plugin, plugin=tls-go, args-b64=eyJzZXJ2ZXJfbmFtZSI6ImV4YW1wbGUuY29tIn0 +SS = plugin, 1.2.3.4, 8388, plugin=ss, args=aes-128-gcm;password +"# + ); + let config = from_string(&conf).unwrap(); + + let tls = plugin_settings_of(&config, "TLS"); + assert_eq!(tls.url, "https://cdn.example.com/p/tls.dll?v=1"); + assert_eq!(tls.sha256, SHA); + assert_eq!(tls.size, 3145728); + assert_eq!(tls.name, "tls-go"); + assert_eq!(tls.path, ""); + assert_eq!(tls.args, r#"{"server_name":"example.com"}"#); + assert_eq!((tls.host.as_str(), tls.port), ("", 0)); + + let ss = plugin_settings_of(&config, "SS"); + assert_eq!(ss.path, "./plugins/ss.dll"); + assert_eq!(ss.url, ""); + assert_eq!(ss.args, "aes-128-gcm;password"); + assert_eq!((ss.host.as_str(), ss.port), ("1.2.3.4", 8388)); + } + + /// Whatever produced the config picked one of the base64 alphabets, with or + /// without padding; all four decode to the same arguments. + #[test] + fn args_b64_accepts_either_alphabet_padded_or_not() { + // `{"a":"??>"}` encodes differently in the two alphabets. + for encoded in [ + "eyJhIjoiPz8+In0=", + "eyJhIjoiPz8+In0", + "eyJhIjoiPz8-In0=", + "eyJhIjoiPz8-In0", + ] { + let conf = format!( + "[Plugin]\np = path=./p.dll\n[Proxy]\nP = plugin, plugin=p, args-b64={}\n", + encoded + ); + let config = from_string(&conf).unwrap(); + assert_eq!( + plugin_settings_of(&config, "P").args, + r#"{"a":"??>"}"#, + "{}", + encoded + ); + } + } + + #[test] + fn args_b64_that_is_not_base64_is_an_error() { + let conf = "[Plugin]\np = path=./p.dll\n[Proxy]\nP = plugin, plugin=p, args-b64=!!!\n"; + let err = from_string(conf).unwrap_err().to_string(); + assert!(err.contains("args-b64"), "{}", err); + } + + #[test] + fn plugin_section_rejects_what_it_does_not_understand() { + for (section, expected) in [ + ( + format!("p = url=https://x/p.dll, sha-256={SHA}"), + "unknown key [sha-256]", + ), + ("p = size=12".to_string(), "neither where it is"), + ( + "p = path=./a.dll\np = path=./b.dll".to_string(), + "declared twice", + ), + ("p = path=./a.dll, size=big".to_string(), "not a byte count"), + ("p = path".to_string(), "not key=value"), + ] { + let conf = format!("[Plugin]\n{}\n", section); + let err = from_string(&conf).unwrap_err().to_string(); + assert!(err.contains(expected), "[{}]: {}", section, err); + } + } + + #[test] + fn a_plugin_proxy_must_name_a_declared_plugin() { + let err = from_string("[Proxy]\nP = plugin, args=x\n") + .unwrap_err() + .to_string(); + assert!(err.contains("names no plugin"), "{}", err); + + let err = from_string("[Proxy]\nP = plugin, plugin=nope\n") + .unwrap_err() + .to_string(); + assert!(err.contains("no [Plugin] entry declares"), "{}", err); + } + + #[test] + fn a_plugin_proxy_takes_a_whole_endpoint_or_none() { + let conf = "[Plugin]\np = path=./p.dll\n[Proxy]\nP = plugin, 1.2.3.4, plugin=p\n"; + let err = from_string(conf).unwrap_err().to_string(); + assert!(err.contains("an address and a port, or neither"), "{}", err); + + let conf = "[Plugin]\np = path=./p.dll\n[Proxy]\nP = plugin, 1.2.3.4, http, plugin=p\n"; + let err = from_string(conf).unwrap_err().to_string(); + assert!(err.contains("is not a port"), "{}", err); + } + + /// Values used to be split on every `=`, which dropped any parameter whose + /// value had one -- a password ending in base64 padding, for one. + #[test] + fn a_value_may_contain_an_equals_sign() { + let conf = "[Proxy]\nT = trojan, 1.2.3.4, 443, password=abc==\n"; + let lines: Vec> = conf.lines().map(|s| Ok(s.to_string())).collect(); + let config = from_lines(lines).unwrap(); + let proxy = &config.proxy.unwrap()[0]; + assert_eq!(proxy.password.as_deref(), Some("abc==")); + } + #[test] fn test_wintun_conf() { let conf = r#" diff --git a/leaf/src/config/internal/config.proto b/leaf/src/config/internal/config.proto index 818666f..1795dbf 100644 --- a/leaf/src/config/internal/config.proto +++ b/leaf/src/config/internal/config.proto @@ -284,6 +284,17 @@ message PluginOutboundSettings { // Lowercase hex sha256 of the library file. When set, the plugin is loaded // only if the file on disk matches it. string sha256 = 5; + // Where to download the library from when `path` is empty. https only, and + // only together with `sha256`: the file is cached under its digest and + // `path` is filled in before the outbound is built. + string url = 6; + // The size of the file at `url` in bytes, when the config knows it. It + // makes progress reportable before the download starts, and a download + // that runs past it is stopped. + uint64 size = 7; + // The name the config gave the plugin, for progress and error reports. + // Empty means the outbound's tag. + string name = 8; } message Outbound { diff --git a/leaf/src/config/internal/config.rs b/leaf/src/config/internal/config.rs index 55ebd25..fb6a9ef 100644 --- a/leaf/src/config/internal/config.rs +++ b/leaf/src/config/internal/config.rs @@ -4555,6 +4555,12 @@ pub struct PluginOutboundSettings { pub port: u32, // @@protoc_insertion_point(field:PluginOutboundSettings.sha256) pub sha256: ::std::string::String, + // @@protoc_insertion_point(field:PluginOutboundSettings.url) + pub url: ::std::string::String, + // @@protoc_insertion_point(field:PluginOutboundSettings.size) + pub size: u64, + // @@protoc_insertion_point(field:PluginOutboundSettings.name) + pub name: ::std::string::String, // special fields // @@protoc_insertion_point(special_field:PluginOutboundSettings.special_fields) pub special_fields: ::protobuf::SpecialFields, @@ -4597,6 +4603,15 @@ impl ::protobuf::Message for PluginOutboundSettings { 42 => { self.sha256 = is.read_string()?; }, + 50 => { + self.url = is.read_string()?; + }, + 56 => { + self.size = is.read_uint64()?; + }, + 66 => { + self.name = is.read_string()?; + }, tag => { ::protobuf::rt::read_unknown_or_skip_group(tag, is, self.special_fields.mut_unknown_fields())?; }, @@ -4624,6 +4639,15 @@ impl ::protobuf::Message for PluginOutboundSettings { if !self.sha256.is_empty() { my_size += ::protobuf::rt::string_size(5, &self.sha256); } + if !self.url.is_empty() { + my_size += ::protobuf::rt::string_size(6, &self.url); + } + if self.size != 0 { + my_size += ::protobuf::rt::uint64_size(7, self.size); + } + if !self.name.is_empty() { + my_size += ::protobuf::rt::string_size(8, &self.name); + } my_size += ::protobuf::rt::unknown_fields_size(self.special_fields.unknown_fields()); self.special_fields.cached_size().set(my_size as u32); my_size @@ -4645,6 +4669,15 @@ impl ::protobuf::Message for PluginOutboundSettings { if !self.sha256.is_empty() { os.write_string(5, &self.sha256)?; } + if !self.url.is_empty() { + os.write_string(6, &self.url)?; + } + if self.size != 0 { + os.write_uint64(7, self.size)?; + } + if !self.name.is_empty() { + os.write_string(8, &self.name)?; + } os.write_unknown_fields(self.special_fields.unknown_fields())?; ::std::result::Result::Ok(()) } @@ -4667,6 +4700,9 @@ impl ::protobuf::Message for PluginOutboundSettings { self.host.clear(); self.port = 0; self.sha256.clear(); + self.url.clear(); + self.size = 0; + self.name.clear(); self.special_fields.clear(); } @@ -4677,6 +4713,9 @@ impl ::protobuf::Message for PluginOutboundSettings { host: ::std::string::String::new(), port: 0, sha256: ::std::string::String::new(), + url: ::std::string::String::new(), + size: 0, + name: ::std::string::String::new(), special_fields: ::protobuf::SpecialFields::new(), }; &instance diff --git a/leaf/src/lib.rs b/leaf/src/lib.rs index 9615241..8055d47 100644 --- a/leaf/src/lib.rs +++ b/leaf/src/lib.rs @@ -63,6 +63,12 @@ pub enum Error { SyncChannelRecv(#[from] std::sync::mpsc::RecvError), #[error("runtime manager error")] RuntimeManager, + /// A plugin the config names by url could not be downloaded. + #[error("{0}")] + PluginFetch(String), + /// The caller asked for the operation to stop. + #[error("cancelled")] + Cancelled, } pub type Runner = futures::future::BoxFuture<'static, ()>; @@ -226,6 +232,8 @@ impl RuntimeManager { }; info!("reloading from config file: {}", config_path); let mut config = config::from_file(config_path).map_err(Error::Config)?; + #[cfg(feature = "plugin-fetch")] + app::outbound::plugin_fetch::prepare_for_reload(&mut config)?; app::logger::setup_logger(&config.log)?; self.router.write().await.reload(&mut config.router)?; self.dns_client.write().await.reload(&config.dns)?; @@ -479,6 +487,12 @@ pub fn start(rt_id: RuntimeId, opts: StartOptions) -> Result<(), Error> { app::logger::setup_logger(&config.log)?; + // Before the runtime exists, and so before any listener or TUN route does: + // the download runs on a runtime of its own, and whatever it fetches goes + // over the network as it is, not through the proxy this is about to start. + #[cfg(feature = "plugin-fetch")] + app::outbound::plugin_fetch::prepare_for_start(&mut config)?; + let rt = new_runtime(&opts.runtime_opt)?; let _g = rt.enter(); diff --git a/leaf/src/util.rs b/leaf/src/util.rs index 83bd600..a6c417e 100644 --- a/leaf/src/util.rs +++ b/leaf/src/util.rs @@ -141,12 +141,31 @@ async fn test_healthcheck_udp( crate::app::healthcheck::udp(dns_client, handler).await } +/// The config an outbound test builds from: plugins named by url pointed at +/// the cache, which a test reads but never fills. +#[cfg(feature = "plugin-fetch")] +fn config_for_test(config: &Config) -> Result> { + use crate::app::outbound::plugin_fetch; + if !plugin_fetch::has_url_plugins(config)? { + return Ok(std::borrow::Cow::Borrowed(config)); + } + let mut config = config.clone(); + plugin_fetch::prepare_for_test(&mut config)?; + Ok(std::borrow::Cow::Owned(config)) +} + +#[cfg(not(feature = "plugin-fetch"))] +fn config_for_test(config: &Config) -> Result> { + Ok(std::borrow::Cow::Borrowed(config)) +} + pub async fn test_outbound( tag: &str, config: &Config, to: Option, ) -> Result<(Result, Result)> { let to = to.unwrap_or(Duration::from_secs(4)); + let config = config_for_test(config)?; let dns_client = Arc::new(RwLock::new(DnsClient::new(&config.dns)?)); let outbound_manager = OutboundManager::new(&config.outbounds, dns_client.clone())?; let handler = outbound_manager @@ -180,6 +199,7 @@ pub async fn test_outbounds( concurrency: usize, ) -> Result, Result)>> { let to = to.unwrap_or(Duration::from_secs(4)); + let config = config_for_test(config)?; let dns_client = Arc::new(RwLock::new(DnsClient::new(&config.dns)?)); let outbound_manager = OutboundManager::new(&config.outbounds, dns_client.clone())?; @@ -225,6 +245,7 @@ pub async fn stream_outbounds_tests( concurrency: usize, ) -> Result, Result))>> { let to = to.unwrap_or(Duration::from_secs(4)); + let config = config_for_test(config)?; let dns_client = Arc::new(RwLock::new(DnsClient::new(&config.dns)?)); let outbound_manager = OutboundManager::new(&config.outbounds, dns_client.clone())?; @@ -261,6 +282,7 @@ pub async fn health_check_outbound( to: Option, ) -> Result<(Result, Result)> { let to = to.unwrap_or(Duration::from_secs(4)); + let config = config_for_test(config)?; let dns_client = Arc::new(RwLock::new(DnsClient::new(&config.dns)?)); let outbound_manager = OutboundManager::new(&config.outbounds, dns_client.clone())?; let handler = outbound_manager