mirror of
https://github.com/eycorsican/leaf.git
synced 2026-12-05 08:01:26 +00:00
feat(plugins): download the plugins a config names by url
A plugin outbound can now give a url instead of a path. With the new plugin-fetch feature, a start downloads what the cache is missing into <cache>/<sha256>/<file> before any outbound is built, and points the outbounds at it; a reload, and testing an outbound, resolve from the cache only and refuse what they would have to download. - https only, redirects included, and only together with a sha256 pin. - Downloads go to a temporary file, are hashed as they arrive, and are renamed into place only once the digest matches, under the url's own name, with the platform's library suffix added when it has no extension, which is what Windows needs to load it. A download past the declared size, or past 64 MiB without one, is stopped. - The cache directory comes from FetchOptions or PLUGIN_CACHE_DIR, with no default: whether a directory is safe to load code from is the embedding app's call. - prefetch() reports QUEUED/CACHED for every plugin before any download, then STARTED, PROGRESS (at most every 100 ms) and exactly one DONE or FAILED each, on the calling thread; the callback can cancel. A download that has not finished gets a PROGRESS heartbeat at least once a second, before STARTED too, so that one stuck connecting or in the handshake can be cancelled as well as one stuck mid-body. conf gains a [Plugin] section that declares each plugin once (path, url, sha256, size) and a `plugin` proxy protocol that refers to it by name, with args= or args-b64= for arguments that contain commas. Proxy parameters are now split at the first `=` only, which used to drop any value that contained one. leaf-ffi gains leaf_prefetch_plugins, so that an app can download the plugins as soon as it has the config, and show progress, and the start that follows finds everything in the cache. Events arrive as a LeafFetchEvent whose first field is its size, on the calling thread and never after the call returns. Adds ERR_PLUGIN_FETCH, ERR_CANCELLED and ERR_UNSUPPORTED, and the plugin and plugin-fetch features. It is tested by unit tests rather than end to end: the library is a Rust dylib, which does not link in a Windows debug build (LNK1189). Twenty-three fetch/ e2e cases download from a per-case https server whose routes can announce a wrong length, omit it, fail, redirect, or hold a body at a gate until the case opens it. Every case checks its events against one statement of the progress contract, and every failure, cancel and timeout case checks that the cache is left empty. One checks that testing an outbound reads the cache, including a file put there by hand, and never downloads. The READMEs describe plugins in conf files and downloading them, and plugin-test and CI run the new unit tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
28d4e825cd
commit
488ff345f3
24 files changed
+3882
-6
No files matched your search
@@ -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
|
||||
|
||||
|
||||
@@ -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 ./...
|
||||
|
||||
@@ -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:
|
||||
`<cache>/<sha256>/<file>`. 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 <path>` 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.
|
||||
|
||||
+4
-1
@@ -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"
|
||||
|
||||
+29
-1
@@ -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 <t>` / `--no-tag <t>` | -- | Select by label: `native`, `plugin`, `go`, `cc`, `zig`, `differential`, `perf`, `hostile`, `cli`, `stress`, `soak`, `slow` |
|
||||
| `--tag <t>` / `--no-tag <t>` | -- | 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 <f>` | `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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<LeafNode> {
|
||||
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<String> {
|
||||
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<String>)> {
|
||||
let rt_id = NEXT_RUNTIME_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let (tx, rx) = tokio::sync::oneshot::channel();
|
||||
|
||||
@@ -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<watch::Sender<bool>>,
|
||||
}
|
||||
|
||||
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<Vec<u8>>,
|
||||
length: Length,
|
||||
location: Option<String>,
|
||||
gate: Option<Gate>,
|
||||
}
|
||||
|
||||
impl Route {
|
||||
pub fn ok(body: impl Into<Arc<Vec<u8>>>) -> 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<String>) -> 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<HashMap<String, Route>>,
|
||||
requests: Mutex<HashMap<String, usize>>,
|
||||
/// 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<State>);
|
||||
|
||||
impl Active {
|
||||
fn enter(state: &Arc<State>) -> 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<State>,
|
||||
task: JoinHandle<()>,
|
||||
}
|
||||
|
||||
impl PluginServer {
|
||||
pub async fn start() -> Result<Self> {
|
||||
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<S>(mut stream: S, state: Arc<State>) -> 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<S>(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<S>(stream: &mut S) -> Result<String>
|
||||
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<CertificateDer<'static>>,
|
||||
PrivateKeyDer<'static>,
|
||||
)> {
|
||||
let mut ca_params = rcgen::CertificateParams::new(Vec::<String>::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())),
|
||||
))
|
||||
}
|
||||
@@ -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",
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<Scenario> {
|
||||
.chain(teardown::scenarios())
|
||||
.chain(halfclose::scenarios())
|
||||
.chain(protocols::scenarios())
|
||||
.chain(fetch::scenarios())
|
||||
.collect();
|
||||
|
||||
let mut seen = std::collections::BTreeSet::new();
|
||||
|
||||
@@ -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"
|
||||
@@ -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<LeafFetchCallback>,
|
||||
) -> 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::<LeafFetchEvent>() 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<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Recorder {
|
||||
seen: Vec<Seen>,
|
||||
threads: Vec<std::thread::ThreadId>,
|
||||
/// Answer `false` to the first event of this kind.
|
||||
cancel_on: Option<i32>,
|
||||
}
|
||||
|
||||
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::<LeafFetchEvent>() 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<i32> = 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()
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -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 }
|
||||
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<String, Arc<RwLock<selector::OutboundSelector>>>;
|
||||
@@ -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<String> {
|
||||
pub(crate) fn plugin_file_digest(path: &Path) -> io::Result<String> {
|
||||
let mut file = std::fs::File::open(path).map_err(|err| {
|
||||
io::Error::other(format!(
|
||||
"failed to open plugin [{}] to digest it: {}",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -328,6 +328,9 @@ pub struct PluginOutboundSettings {
|
||||
pub host: Option<String>,
|
||||
pub port: Option<u16>,
|
||||
pub sha256: Option<String>,
|
||||
pub url: Option<String>,
|
||||
pub size: Option<u64>,
|
||||
pub name: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Debug, Clone)]
|
||||
@@ -1430,6 +1433,15 @@ pub fn to_internal(mut config: Config) -> Result<internal::Config> {
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -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<bool>,
|
||||
pub reality_public_key: Option<String>,
|
||||
pub reality_short_id: Option<String>,
|
||||
|
||||
// plugin
|
||||
/// The `[Plugin]` entry this proxy runs.
|
||||
pub plugin: Option<String>,
|
||||
/// Handed to the plugin verbatim. Its shape is the plugin's business.
|
||||
pub plugin_args: Option<String>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
/// Where to download the library from; https only, and only with `sha256`.
|
||||
pub url: Option<String>,
|
||||
pub sha256: Option<String>,
|
||||
/// The size of the file at `url`, in bytes.
|
||||
pub size: Option<u64>,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ProxyGroup {
|
||||
pub tag: String,
|
||||
@@ -221,6 +246,7 @@ pub struct Config {
|
||||
pub host: Option<HashMap<String, Vec<String>>>,
|
||||
pub certificates: Option<HashMap<String, String>>,
|
||||
pub ech_configs: Option<HashMap<String, String>>,
|
||||
pub plugin: Option<HashMap<String, PluginDecl>>,
|
||||
}
|
||||
|
||||
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
||||
@@ -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<String>) -> Result<HashMap<String, PluginDecl>> {
|
||||
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::<u64>().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<String> {
|
||||
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<io::Result<String>>) -> Result<Config> {
|
||||
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<io::Result<String>>) -> Result<Config> {
|
||||
}
|
||||
}
|
||||
|
||||
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<io::Result<String>>) -> Result<Config> {
|
||||
// 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<io::Result<String>>) -> Result<Config> {
|
||||
"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::<u16>().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<io::Result<String>>) -> Result<Config> {
|
||||
} else {
|
||||
Some(ech_configs)
|
||||
},
|
||||
plugin: if plugins.is_empty() {
|
||||
None
|
||||
} else {
|
||||
Some(plugins)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1144,6 +1284,41 @@ pub fn to_common(conf: &Config) -> Result<common::Config> {
|
||||
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=<a name from [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<io::Result<String>> = 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#"
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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();
|
||||
|
||||
|
||||
@@ -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<std::borrow::Cow<'_, Config>> {
|
||||
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<std::borrow::Cow<'_, Config>> {
|
||||
Ok(std::borrow::Cow::Borrowed(config))
|
||||
}
|
||||
|
||||
pub async fn test_outbound(
|
||||
tag: &str,
|
||||
config: &Config,
|
||||
to: Option<Duration>,
|
||||
) -> Result<(Result<Duration>, Result<Duration>)> {
|
||||
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<HashMap<String, (Result<Duration>, Result<Duration>)>> {
|
||||
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<impl futures::Stream<Item = (String, (Result<Duration>, Result<Duration>))>> {
|
||||
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<Duration>,
|
||||
) -> Result<(Result<Duration>, Result<Duration>)> {
|
||||
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
|
||||
|
||||
Reference in new issue
Block a user