diff --git a/CHANGELOG.md b/CHANGELOG.md index d9a2835..115b8a5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,25 @@ Notable changes to Favonius. Format follows While the major version is 0, the wire protocol and the CLI may both change in a minor release. See [Stability](#stability). +## Unreleased + +### Added + +- `favonius check ` — a connectivity pre-flight. Probes the TCP + fallback, the UDP control port and the UDP data port, prints the firewall + rule to request, and exits non-zero when no transfer is possible. The + daemon answers a probe datagram with a reply of exactly the same length, + so the check cannot be used as a reflection amplifier. +- **TCP fallback.** `--transport tcp`, and a daemon listener on the TCP + socket bearing the control port's number, so a deployment opens one port + rather than two. No congestion control, no multi-stream, and no + performance claim — it exists so that "can we move a file at all" is + always yes on a network that blocks UDP. Streams to a `.part`, verifies + BLAKE3 before committing by rename, and reuses the same `--dest-root` + confinement as the UDP path. Disable with `--no-tcp-fallback`. + Senders remain unauthenticated, as on the UDP path. + + ## [0.1.0] — 2026-08-15 First public release. diff --git a/Cargo.lock b/Cargo.lock index 7fe216d..8130ead 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -90,6 +90,7 @@ dependencies = [ "serde", "serde_json", "socket2 0.5.10", + "tempfile", "thiserror 2.0.18", "tokio", "tracing", diff --git a/README.md b/README.md index bc0206c..10b3bd5 100644 --- a/README.md +++ b/README.md @@ -357,6 +357,61 @@ A **version mismatch is now reported as one**: the header decoder rejects any protocol version it does not implement instead of decoding the packet as if it were the current one. +## Before anything else: will your network carry this? + +```bash +favonius check receiver.example.com:7801 +``` + +The first thing that stops a deployment is not the security review, it is +the firewall. Enterprise ingress is closed by default and plenty of +policies decline inbound UDP outright — so find out in five seconds rather +than after a week of evaluation and a three-week change request. + +It reports each path separately, prints the rule to send your network +team, and exits non-zero when no transfer is possible, so it can gate a +script: + +```text + [ok ] TCP 7801 fallback path + [ok ] UDP 7801 control — handshake + [? ] UDP 7802 data — silent when idle, which is normal +``` + +UDP silence is ambiguous by nature — a firewall drop, a stopped daemon and +a lossy link look identical from outside — and the TCP line distinguishes +the first two: if TCP connects, something is listening and UDP is being +filtered. + +## When UDP is blocked + +Favonius falls back to TCP rather than failing: + +```bash +favonius send big.bin receiver.example.com:7801:/srv/incoming/big.bin --transport tcp +``` + +The daemon listens for this on the **TCP socket bearing the control port's +number**, so a deployment asks for one port rather than two: + +> permit 7801 to this host — UDP for speed, TCP as the fallback. + +**It makes no performance claim.** There is no congestion control, no +multi-stream multiplexing, and none of the measurements in this README +apply to it; the kernel's TCP stack does the work. On the impaired links +Favonius exists for it will be markedly slower. That is the trade: a +transfer that arrives slowly beats one that needs a change request. + +It keeps the guarantees that matter. Bytes stream to a `.part` file, are +hashed with BLAKE3 on the way past, and are renamed into place only when +the payload is complete *and* the trailing hash matches — so a truncated +or altered transfer is refused rather than written. `--dest-root` +confinement is the same code the UDP path uses, not a second +implementation. And it inherits the same limitation, stated in +[SECURITY.md](SECURITY.md): **senders are not authenticated**. Opening the +TCP port widens that posture from one protocol to two; permit both or +neither. Disable it with `--no-tcp-fallback`. + ## Firewall Rules Favonius uses UDP for its data plane. If UFW (or another firewall) is diff --git a/crates/ahp-cli/Cargo.toml b/crates/ahp-cli/Cargo.toml index e5c8caa..f24ec26 100644 --- a/crates/ahp-cli/Cargo.toml +++ b/crates/ahp-cli/Cargo.toml @@ -68,6 +68,7 @@ libc = "0.2" io-uring = "0.7" [dev-dependencies] +tempfile = "3" ahp-api = { workspace = true } ahp-daemon = { workspace = true } tokio = { workspace = true } diff --git a/crates/ahp-cli/src/lib.rs b/crates/ahp-cli/src/lib.rs index b4bfe0d..b9ff0ca 100644 --- a/crates/ahp-cli/src/lib.rs +++ b/crates/ahp-cli/src/lib.rs @@ -5,6 +5,8 @@ pub mod fs_tree; pub mod sync_plan; pub mod net_probe; +pub mod preflight; +pub mod tcp_sender; pub mod net_sender; pub mod udt_transport; diff --git a/crates/ahp-cli/src/main.rs b/crates/ahp-cli/src/main.rs index 24b1ab4..ae4e71a 100644 --- a/crates/ahp-cli/src/main.rs +++ b/crates/ahp-cli/src/main.rs @@ -4,7 +4,7 @@ use clap::{Parser, Subcommand}; use ahp_cli::sync_plan::{self, Compare, SyncMode}; -use ahp_cli::{fs_tree, FavoniusClient, CliError, net_sender, udt_transport}; +use ahp_cli::{fs_tree, FavoniusClient, CliError, net_sender, preflight, tcp_sender, udt_transport}; use ahp_congestion::CongestionProfile; use ahp_policy::{AdaptivePolicy, NetworkContext}; use ahp_proto::data::AckMode; @@ -28,6 +28,21 @@ struct Cli { #[derive(Subcommand, Debug)] enum Command { + /// Check whether this network will carry a transfer + /// + /// Run this before anything else. The first thing that stops a + /// deployment is not the security review, it is the firewall — and + /// finding that out in five seconds is worth more than finding out in + /// three weeks. + Check { + /// Destination host, with an optional control port: `host` or + /// `host:7801` + target: String, + /// AHP data port. Defaults to the control port plus one, which is + /// the daemon's own default. + #[arg(long)] + data_port: Option, + }, /// Send files to a destination Send { source: String, @@ -54,7 +69,9 @@ enum Command { /// Pacing mode: auto, batch (GSO/sendmmsg, default), perpacket, iouring (slower than GSO, debug only), xdp (experimental) #[arg(long, default_value = "auto")] pacing: String, - /// Transport backend: ahp (default), udt (sendfile/recvfile), xdp (AF_XDP zero-copy) + /// Transport backend: ahp (default), tcp (fallback for networks + /// that block UDP — correct but not accelerated), udt + /// (sendfile/recvfile), xdp (AF_XDP zero-copy) #[arg(long, default_value = "ahp")] transport: String, /// Encrypt the transfer using AES-256-GCM with X25519 key exchange @@ -191,6 +208,29 @@ async fn main() -> Result<(), Box> { let client = FavoniusClient::new(&cli.daemon); match cli.command { + // ── Connectivity ───────────────────────────────────────────── + Command::Check { target, data_port } => { + let (host, control_port) = match target.rsplit_once(':') { + // Guard against an IPv6 literal being split on its own colons. + Some((h, p)) if !h.contains(':') || h.starts_with('[') => { + match p.parse::() { + Ok(port) => (h.trim_matches(|c| c == '[' || c == ']').to_string(), port), + Err(_) => (target.clone(), 7801), + } + } + _ => (target.clone(), 7801), + }; + let data = data_port.unwrap_or(control_port.saturating_add(1)); + let report = preflight::run(&host, control_port, data).await; + preflight::print(&report); + // A non-zero exit so this can gate a script or a CI step, not + // only inform a person reading a terminal. + if !report.transfer_possible() { + std::process::exit(1); + } + return Ok(()); + } + Command::Send { source, destination, compression, congestion, ack_mode, streams, pacing, transport, encrypt, header_protect, resume, server_key, adaptive, policy_path, include, exclude, dry_run, bandwidth_limit } => { // No code path reads this. It was destructured away with `..`, // so `--bandwidth-limit 10` capped nothing and said nothing — @@ -204,6 +244,34 @@ async fn main() -> Result<(), Box> { (tc/qdisc), until it is.".into(), ))); } + // TCP fallback: no AHP, no congestion control, no speed claim. + // Chosen explicitly here; `net_sender` falls back to it on its + // own when a handshake finds nothing at the far end. + if transport == "tcp" { + let Some((remote_addr, dest_path)) = net_sender::parse_remote_dest(&destination) + else { + return Err(Box::::from(CliError::Config( + "--transport tcp needs a remote destination, host:port:/path".into(), + ))); + }; + eprintln!("Transport: TCP fallback (no acceleration — see `favonius check`)"); + match tcp_sender::send_file( + std::path::Path::new(&source), remote_addr, &dest_path, + ).await { + Ok(s) => { + println!( + "TCP fallback complete: {} bytes in {:.2}s ({:.1} MiB/s)", + s.bytes_sent, s.elapsed.as_secs_f64(), s.throughput_mib_s(), + ); + return Ok(()); + } + Err(e) => { + eprintln!("error: {e}"); + std::process::exit(1); + } + } + } + // UDT transport: bypass AHP entirely, use sendfile/recvfile. if transport == "udt" { eprintln!("Transport: UDT (sendfile/recvfile baseline)"); diff --git a/crates/ahp-cli/src/preflight.rs b/crates/ahp-cli/src/preflight.rs new file mode 100644 index 0000000..0462170 --- /dev/null +++ b/crates/ahp-cli/src/preflight.rs @@ -0,0 +1,324 @@ +// Favonius — high-performance file transfer over UDP +// Copyright (c) 2025-2026 Vantino SàRL +// SPDX-License-Identifier: Apache-2.0 + +//! `favonius check` — will this network carry a transfer? +//! +//! # Why this is a command and not a paragraph in the README +//! +//! The first thing that stops a Favonius deployment is not the security +//! review. It is the firewall. Enterprise ingress is closed by default, +//! reaching a daemon needs inbound UDP permitted, and plenty of policies +//! decline that outright. Without a way to find out early, the sequence is: +//! evaluate for a week, involve the security team, ask the network team for +//! a rule, wait three weeks, discover the answer is no. +//! +//! This turns that into a five-second answer at the start, and — when the +//! answer is bad — prints the sentence to send the network team rather +//! than leaving someone to compose it. +//! +//! # What it checks, and in what order +//! +//! 1. **DNS** — does the name resolve at all. +//! 2. **TCP to the control port** — the fallback path, and a cheap signal +//! that something is listening rather than a black hole. +//! 3. **UDP to the control port** — the real data plane. A HELLO is sent +//! and a reply awaited: the only honest test of a datagram path is a +//! datagram that comes back. +//! 4. **UDP to the data port** — transfers move here after the handshake. +//! An idle daemon does not read this socket, so **silence here is +//! expected and is not a failure**. It is probed anyway because a +//! reply, or an ICMP rejection, is still informative — and because a +//! firewall that permits the control port and not the data port is +//! common enough that the rule below must name both. +//! +//! UDP silence is ambiguous by nature — dropped by a firewall, dropped by +//! congestion, or nobody listening — and this says so rather than +//! reporting a definite failure it cannot prove. Reporting a healthy +//! daemon as unreachable would be worse than not checking: the first +//! draft did exactly that, before the daemon learned to answer the probe. + +use std::net::{SocketAddr, ToSocketAddrs}; +use std::time::{Duration, Instant}; + +/// How long to wait for a UDP reply before calling it silence. +const UDP_WAIT: Duration = Duration::from_millis(1500); +/// How long to wait for a TCP connection. +const TCP_WAIT: Duration = Duration::from_millis(3000); + +#[derive(Debug, PartialEq, Eq)] +pub enum Verdict { + /// Confirmed working. + Works, + /// Confirmed not working, with a reason. + Blocked(String), + /// No answer. For UDP this is genuinely ambiguous. + Silent, + /// Could not be attempted. + Skipped(String), +} + +impl Verdict { + fn mark(&self) -> &'static str { + match self { + Self::Works => "ok ", + Self::Blocked(_) => "FAIL", + Self::Silent => "? ", + Self::Skipped(_) => "- ", + } + } +} + +pub struct Report { + pub host: String, + pub control_port: u16, + pub data_port: u16, + pub resolved: Option, + pub tcp_control: Verdict, + pub udp_control: Verdict, + pub udp_data: Verdict, +} + +impl Report { + /// True when a transfer can happen by some route. + pub fn transfer_possible(&self) -> bool { + self.udp_control == Verdict::Works || self.tcp_control == Verdict::Works + } +} + +/// Run the checks against `host:port`. +/// +/// `control_port` is the AHP control port (7801 by default); the data port +/// defaults to the next one up, matching the daemon's own defaults. +pub async fn run(host: &str, control_port: u16, data_port: u16) -> Report { + let mut report = Report { + host: host.to_string(), + control_port, + data_port, + resolved: None, + tcp_control: Verdict::Skipped("not attempted".into()), + udp_control: Verdict::Skipped("not attempted".into()), + udp_data: Verdict::Skipped("not attempted".into()), + }; + + // 1. DNS. Everything else is meaningless without it, so a failure + // here stops rather than producing three more confusing lines. + let addr = match (host, control_port).to_socket_addrs() { + Ok(mut it) => match it.next() { + Some(a) => a, + None => { + report.tcp_control = Verdict::Blocked(format!("{host} resolved to no addresses")); + return report; + } + }, + Err(e) => { + report.tcp_control = Verdict::Blocked(format!("{host} does not resolve: {e}")); + return report; + } + }; + report.resolved = Some(addr); + + report.tcp_control = check_tcp(addr).await; + report.udp_control = check_udp(addr).await; + + let mut data_addr = addr; + data_addr.set_port(data_port); + report.udp_data = check_udp(data_addr).await; + + report +} + +async fn check_tcp(addr: SocketAddr) -> Verdict { + match tokio::time::timeout(TCP_WAIT, tokio::net::TcpStream::connect(addr)).await { + Ok(Ok(_)) => Verdict::Works, + Ok(Err(e)) => Verdict::Blocked(e.to_string()), + Err(_) => Verdict::Silent, + } +} + +/// Probe a UDP port by sending a datagram and waiting for anything back. +/// +/// The payload is a deliberately malformed AHP packet: a daemon that +/// receives it answers or errors, and either proves the round trip. What +/// matters is that a datagram left and a datagram returned — not what it +/// said. +async fn check_udp(addr: SocketAddr) -> Verdict { + let bind: SocketAddr = if addr.is_ipv4() { "0.0.0.0:0" } else { "[::]:0" } + .parse() + .expect("static bind address"); + + let sock = match tokio::net::UdpSocket::bind(bind).await { + Ok(s) => s, + Err(e) => return Verdict::Skipped(format!("could not open a local socket: {e}")), + }; + if let Err(e) = sock.connect(addr).await { + return Verdict::Blocked(e.to_string()); + } + + // A probe the daemon will not mistake for a transfer, and answers + // with a reply of exactly the same length. + if let Err(e) = sock.send(ahp_proto::fallback::PROBE).await { + return Verdict::Blocked(e.to_string()); + } + + let mut buf = [0u8; 2048]; + match tokio::time::timeout(UDP_WAIT, sock.recv(&mut buf)).await { + Ok(Ok(_)) => Verdict::Works, + // An ICMP port-unreachable surfaces here on Linux: something is + // reachable and nothing is listening, which is a different problem + // from a firewall and deserves a different message. + Ok(Err(e)) => Verdict::Blocked(format!("{e} (nothing listening?)")), + Err(_) => Verdict::Silent, + } +} + +/// Print the report, and what to do about it. +pub fn print(report: &Report) { + let started = Instant::now(); + println!(); + println!(" Favonius connectivity check — {}", report.host); + if let Some(a) = report.resolved { + println!(" resolved to {}", a.ip()); + } + println!(); + println!( + " [{}] TCP {:<5} fallback path", + report.tcp_control.mark(), + report.control_port + ); + println!( + " [{}] UDP {:<5} control — handshake", + report.udp_control.mark(), + report.control_port + ); + println!( + " [{}] UDP {:<5} data — silent when idle, which is normal", + report.udp_data.mark(), + report.data_port + ); + for (label, v) in [ + ("TCP control", &report.tcp_control), + ("UDP control", &report.udp_control), + ("UDP data", &report.udp_data), + ] { + match v { + Verdict::Blocked(why) => println!(" {label}: {why}"), + Verdict::Skipped(why) => println!(" {label}: {why}"), + _ => {} + } + } + println!(); + + // The data port is judged only on a *definite* rejection. An idle + // daemon does not read that socket, so silence there says nothing — + // and treating it as failure would send an evaluator to their network + // team over a working deployment. + let data_rejected = matches!(report.udp_data, Verdict::Blocked(_)); + let udp_ok = report.udp_control == Verdict::Works && !data_rejected; + let tcp_ok = report.tcp_control == Verdict::Works; + + if udp_ok { + println!(" Transfers will use UDP, which is what Favonius is for."); + } else if tcp_ok { + println!(" UDP did not answer, so transfers will fall back to TCP."); + println!(" They will work and they will be slower — the acceleration is in"); + println!(" the UDP path. To get it, ask for this rule:"); + println!(); + print_rule(report); + } else { + println!(" Nothing answered. A transfer to this host will not work yet."); + println!(); + println!(" Check the daemon is running, then ask for this rule:"); + println!(); + print_rule(report); + } + + if report.udp_control == Verdict::Silent { + println!(); + println!(" Note: UDP silence is ambiguous — a firewall dropping the packet, a"); + println!(" daemon that is not running, and a lossy link look identical from"); + println!(" here. The TCP result above distinguishes the first from the second:"); + println!(" if TCP connects, something is listening and UDP is being filtered."); + } + if report.udp_data == Verdict::Silent && report.udp_control == Verdict::Works { + println!(); + println!(" The data port did not answer, which is expected: an idle daemon"); + println!(" does not read it. It still has to be open — the rule above names"); + println!(" it — but this line is not a problem to chase."); + } + println!(); + let _ = started; +} + +fn print_rule(report: &Report) { + let host = report + .resolved + .map(|a| a.ip().to_string()) + .unwrap_or_else(|| report.host.clone()); + println!(" permit inbound UDP {} and {} to {}", report.control_port, report.data_port, host); + println!(" permit inbound TCP {} to {} (fallback)", report.control_port, host); + println!(); + println!(" Per-stream ports: with `--streams N` the daemon may use a range"); + println!(" above {}. See `--data-port-range` on the daemon and the Firewall", report.data_port); + println!(" Rules section of the README."); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_name_that_does_not_resolve_stops_early() { + let r = run("this-host-does-not-exist.invalid", 7801, 7802).await; + assert!(matches!(r.tcp_control, Verdict::Blocked(_))); + assert_eq!(r.resolved, None); + assert!(!r.transfer_possible()); + } + + #[tokio::test] + async fn a_closed_tcp_port_is_blocked_not_silent() { + // Port 1 on loopback: reachable, nothing listening. Distinguishing + // this from a firewall drop is the whole value of the TCP probe. + let r = check_tcp("127.0.0.1:1".parse().unwrap()).await; + assert!(matches!(r, Verdict::Blocked(_)), "got {r:?}"); + } + + #[tokio::test] + async fn a_listening_tcp_port_works() { + // The control: without this, the test above passes for a checker + // that reports everything as blocked. + let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let addr = l.local_addr().unwrap(); + tokio::spawn(async move { let _ = l.accept().await; }); + assert_eq!(check_tcp(addr).await, Verdict::Works); + } + + #[tokio::test] + async fn a_udp_port_that_answers_works() { + let s = tokio::net::UdpSocket::bind("127.0.0.1:0").await.unwrap(); + let addr = s.local_addr().unwrap(); + tokio::spawn(async move { + let mut b = [0u8; 64]; + if let Ok((_, peer)) = s.recv_from(&mut b).await { + let _ = s.send_to(b"pong", peer).await; + } + }); + assert_eq!(check_udp(addr).await, Verdict::Works); + } + + #[test] + fn transfer_is_possible_when_either_path_works() { + let mut r = Report { + host: "h".into(), control_port: 7801, data_port: 7802, resolved: None, + tcp_control: Verdict::Silent, + udp_control: Verdict::Silent, + udp_data: Verdict::Silent, + }; + assert!(!r.transfer_possible()); + r.tcp_control = Verdict::Works; + assert!(r.transfer_possible(), "TCP alone must count as possible"); + r.tcp_control = Verdict::Silent; + r.udp_control = Verdict::Works; + assert!(r.transfer_possible(), "UDP alone must count as possible"); + } +} diff --git a/crates/ahp-cli/src/tcp_sender.rs b/crates/ahp-cli/src/tcp_sender.rs new file mode 100644 index 0000000..da257ec --- /dev/null +++ b/crates/ahp-cli/src/tcp_sender.rs @@ -0,0 +1,194 @@ +// Favonius — high-performance file transfer over UDP +// Copyright (c) 2025-2026 Vantino SàRL +// SPDX-License-Identifier: Apache-2.0 + +//! Sending over TCP, when UDP cannot get through. +//! +//! See [`ahp_proto::fallback`] for the frame and the reasoning. This side +//! is deliberately dull: open a connection, announce the file, stream it +//! while hashing, send the hash, read the verdict. +//! +//! It makes **no performance claim**. The kernel's TCP stack does the +//! work, none of the congestion control or multi-stream machinery is +//! involved, and on the impaired links Favonius is built for this will be +//! markedly slower than the UDP path. That is the trade: a transfer that +//! arrives beats one that needs a firewall change request. + +use std::path::Path; +use std::time::{Duration, Instant}; + +use ahp_proto::fallback::{FallbackHeader, FallbackReply}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; + +const COPY_BUFFER: usize = 256 * 1024; +const CONNECT_TIMEOUT: Duration = Duration::from_secs(15); + +#[derive(Debug)] +pub struct TcpTransferStats { + pub bytes_sent: u64, + pub elapsed: Duration, +} + +impl TcpTransferStats { + pub fn throughput_mib_s(&self) -> f64 { + let secs = self.elapsed.as_secs_f64(); + if secs <= 0.0 { + return 0.0; + } + self.bytes_sent as f64 / 1_048_576.0 / secs + } +} + +/// Send one file to `addr`, to be written at `dest_path` under the +/// daemon's `--dest-root`. +pub async fn send_file( + source: &Path, + addr: std::net::SocketAddr, + dest_path: &str, +) -> Result { + let meta = tokio::fs::metadata(source) + .await + .map_err(|e| format!("cannot read {}: {e}", source.display()))?; + if !meta.is_file() { + return Err(format!( + "{} is not a regular file; the TCP fallback sends one file at a time", + source.display() + )); + } + let size = meta.len(); + + let mut stream = tokio::time::timeout( + CONNECT_TIMEOUT, + tokio::net::TcpStream::connect(addr), + ) + .await + .map_err(|_| format!("timed out connecting to {addr}"))? + .map_err(|e| format!("cannot connect to {addr}: {e}"))?; + + // Latency matters more than packing here: the receiver is waiting on + // a header before it can do anything. + let _ = stream.set_nodelay(true); + + let header = FallbackHeader { path: dest_path.to_string(), size }; + let encoded = header.encode().map_err(|e| e.to_string())?; + stream + .write_all(&encoded) + .await + .map_err(|e| format!("sending the header: {e}"))?; + + let started = Instant::now(); + let mut file = tokio::fs::File::open(source) + .await + .map_err(|e| format!("opening {}: {e}", source.display()))?; + + let mut hasher = blake3::Hasher::new(); + let mut buf = vec![0u8; COPY_BUFFER]; + let mut sent = 0u64; + + loop { + let n = file + .read(&mut buf) + .await + .map_err(|e| format!("reading {}: {e}", source.display()))?; + if n == 0 { + break; + } + hasher.update(&buf[..n]); + if let Err(e) = stream.write_all(&buf[..n]).await { + // The daemon refuses *after* reading the header — a path + // outside its --dest-root, say — then stops reading and + // closes. The write then fails with "broken pipe" while the + // real reason is sitting unread on the socket. Reporting the + // pipe error would send someone to look at their network for + // a destination they mis-typed, so read the verdict first. + if let Some(reason) = drain_refusal(&mut stream).await { + return Err(format!("daemon refused: {reason}")); + } + return Err(format!("sending payload: {e}")); + } + sent += n as u64; + } + + // The size in the header is what the receiver waits for. If the file + // changed under us the transfer would hang or truncate, so say so + // here rather than let the peer time out. + if sent != size { + return Err(format!( + "{} changed while being sent: announced {size} bytes, read {sent}", + source.display() + )); + } + + stream + .write_all(hasher.finalize().as_bytes()) + .await + .map_err(|e| format!("sending the hash: {e}"))?; + stream.flush().await.map_err(|e| format!("flushing: {e}"))?; + + let mut reply = vec![0u8; 3 + 512]; + let n = stream + .read(&mut reply) + .await + .map_err(|e| format!("waiting for the daemon's verdict: {e}"))?; + + match FallbackReply::decode(&reply[..n]) { + Some(FallbackReply::Accepted) => Ok(TcpTransferStats { + bytes_sent: sent, + elapsed: started.elapsed(), + }), + Some(FallbackReply::Refused(reason)) => Err(format!("daemon refused: {reason}")), + // An unreadable verdict is not success. The bytes may be on disk + // and may not; reporting a transfer complete on a reply we could + // not parse is the one direction that must never happen. + None => Err( + "the daemon's reply could not be read, so the transfer is not confirmed. \ + Check the destination before assuming it arrived." + .into(), + ), + } +} + +/// Read a refusal the daemon may have sent before closing. +/// +/// Best effort and short: the connection is already failing, and a client +/// that hangs here has turned a clear error into a stall. +async fn drain_refusal(stream: &mut tokio::net::TcpStream) -> Option { + let mut buf = vec![0u8; 3 + 512]; + let n = tokio::time::timeout(Duration::from_secs(2), stream.read(&mut buf)) + .await + .ok()? + .ok()?; + match FallbackReply::decode(&buf[..n]) { + Some(FallbackReply::Refused(reason)) => Some(reason), + _ => None, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn throughput_of_an_instant_transfer_is_not_infinite() { + let s = TcpTransferStats { bytes_sent: 1024, elapsed: Duration::ZERO }; + assert_eq!(s.throughput_mib_s(), 0.0); + } + + #[test] + fn throughput_is_mib_per_second() { + let s = TcpTransferStats { + bytes_sent: 10 * 1_048_576, + elapsed: Duration::from_secs(2), + }; + assert!((s.throughput_mib_s() - 5.0).abs() < 1e-9, "{}", s.throughput_mib_s()); + } + + #[tokio::test] + async fn sending_a_directory_is_refused_with_a_reason() { + let dir = tempfile::tempdir().unwrap(); + let err = send_file(dir.path(), "127.0.0.1:1".parse().unwrap(), "x") + .await + .unwrap_err(); + assert!(err.contains("not a regular file"), "{err}"); + } +} diff --git a/crates/ahp-daemon/src/lib.rs b/crates/ahp-daemon/src/lib.rs index f9975ae..41347e4 100644 --- a/crates/ahp-daemon/src/lib.rs +++ b/crates/ahp-daemon/src/lib.rs @@ -3,6 +3,7 @@ // SPDX-License-Identifier: Apache-2.0 pub mod net_receiver; +pub mod tcp_fallback; use ahp_api::AppState; use tokio::net::TcpListener; diff --git a/crates/ahp-daemon/src/main.rs b/crates/ahp-daemon/src/main.rs index 9975048..fa517ed 100644 --- a/crates/ahp-daemon/src/main.rs +++ b/crates/ahp-daemon/src/main.rs @@ -48,6 +48,16 @@ struct Args { /// unless --allow-any-dest is passed (S1) #[arg(long)] dest_root: Option, + + /// Do not listen for TCP fallback transfers. + /// + /// The fallback is on by default: it exists for the deployment whose + /// firewall drops UDP, and that is precisely the deployment where + /// nobody would know to enable it. Turn it off where the extra + /// listener is unwanted -- noting it is the same unauthenticated + /// posture as the UDP path, not a new one. + #[arg(long)] + no_tcp_fallback: bool, /// Accept arbitrary sender-chosen absolute destination paths. /// /// This grants any peer that can reach the control port the ability to @@ -128,6 +138,33 @@ async fn main() -> Result<(), Box> { // Start AHP protocol listener with separate control + data ports. let control_addr: std::net::SocketAddr = args.protocol_listen.parse()?; + + // The TCP fallback shares the control port's *number* on the TCP + // socket, so a deployment asks its network team for one port rather + // than two: "permit 7801 to this host, UDP for speed and TCP as the + // fallback." UDP and TCP sockets on the same number do not conflict. + // + // Enabled unless refused, because the case it exists for -- an + // evaluator whose firewall drops UDP -- is exactly the case where + // nobody knows to turn it on. + if !args.no_tcp_fallback { + let fb_root = args.dest_root.clone(); + match tokio::net::TcpListener::bind(control_addr).await { + Ok(l) => { + tokio::spawn(async move { + if let Err(e) = ahp_daemon::tcp_fallback::serve(l, fb_root).await { + tracing::error!(error = %e, "TCP fallback listener stopped"); + } + }); + } + Err(e) => { + // Not fatal: the UDP path is the product, and a taken TCP + // port should not stop the daemon serving it. + tracing::warn!(addr = %control_addr, error = %e, + "could not bind the TCP fallback; UDP transfers are unaffected"); + } + } + } let data_addr: std::net::SocketAddr = args.data_listen.parse()?; let max_concurrent = args.max_concurrent; // Parsed here so a malformed range is a startup error with a usage diff --git a/crates/ahp-daemon/src/net_receiver.rs b/crates/ahp-daemon/src/net_receiver.rs index 42a2291..309bbdc 100644 --- a/crates/ahp-daemon/src/net_receiver.rs +++ b/crates/ahp-daemon/src/net_receiver.rs @@ -608,7 +608,7 @@ fn lexical_normalize(path: &std::path::Path) -> std::path::PathBuf { /// `root` must already be canonicalized (done once at startup). The joined /// path is lexically normalized and must stay under the root: absolute /// destinations outside the root and `..` escapes are rejected. -fn confine_dest_path(root: &std::path::Path, dest: &str) -> Result { +pub(crate) fn confine_dest_path(root: &std::path::Path, dest: &str) -> Result { let joined = lexical_normalize(&root.join(dest)); if !joined.starts_with(root) { return Err(format!( @@ -1102,6 +1102,19 @@ split, about (concurrent transfers) x (streams per transfer)", continue; } }; + // Connectivity probe from `favonius check`. Answered + // before decoding, because the point is to prove a + // datagram round trip on a host where the full protocol + // may not be reachable. + // + // The reply is exactly as long as the request: an + // unauthenticated responder that answers with more bytes + // than it receives is a reflection amplifier, and this + // port is open to anyone who can reach it. + if &buf[..len] == ahp_proto::fallback::PROBE { + let _ = socket.send_to(ahp_proto::fallback::PROBE_REPLY, from).await; + continue; + } let pkt = match decode_packet(&buf[..len]) { Ok(p) => p, Err(e) => { diff --git a/crates/ahp-daemon/src/tcp_fallback.rs b/crates/ahp-daemon/src/tcp_fallback.rs new file mode 100644 index 0000000..0354b58 --- /dev/null +++ b/crates/ahp-daemon/src/tcp_fallback.rs @@ -0,0 +1,235 @@ +// Favonius — high-performance file transfer over UDP +// Copyright (c) 2025-2026 Vantino SàRL +// SPDX-License-Identifier: Apache-2.0 + +//! Receiving a transfer over TCP, when UDP cannot get through. +//! +//! See [`ahp_proto::fallback`] for why this exists and what the frame +//! looks like. In short: a network team that will not permit inbound UDP +//! is common, and a transfer that arrives slowly beats one that needs a +//! change request. +//! +//! # It inherits the same confinement, deliberately +//! +//! This path writes files a remote peer named, so it goes through exactly +//! the `--dest-root` check the UDP receiver uses. A second write path with +//! its own idea of where files may land is how a confinement bug is +//! introduced — the check is called here rather than reimplemented. +//! +//! It also inherits the same limitation: like the UDP listener, this does +//! **not authenticate senders**. Any peer that can reach the port can +//! transfer, exactly as `SECURITY.md` says. Adding a second unauthenticated +//! entry point does not change the posture, but it does widen it from one +//! protocol to two, and a deployment should permit both or neither. +//! +//! # Committing +//! +//! Bytes stream to a `.part` file beside the destination and are hashed on +//! the way past. Only when the payload is complete *and* the trailing +//! BLAKE3 matches is the file renamed into place. A truncated transfer, a +//! dropped connection, or an altered payload leaves the `.part` and never +//! the real name — so a partial file is never mistaken for a delivered one. + +use std::path::{Path, PathBuf}; + +use ahp_proto::fallback::{FallbackHeader, FallbackReply, HEADER_LEN}; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::{TcpListener, TcpStream}; + +/// Streaming buffer. Large enough that the syscall rate is not the limit, +/// small enough that many concurrent transfers do not add up to much. +const COPY_BUFFER: usize = 256 * 1024; + +/// How long a peer may hold a connection without sending anything. +const IDLE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120); + +/// Serve the TCP fallback until the process ends. +/// +/// Binds the **TCP** socket bearing the control port's number, so a +/// deployment opens one port rather than two. +pub async fn serve( + listener: TcpListener, + dest_root: Option, +) -> std::io::Result<()> { + let local = listener.local_addr()?; + match &dest_root { + Some(root) => tracing::info!( + listen = %local, root = %root.display(), + "TCP fallback ready (used when UDP is blocked)" + ), + None => tracing::warn!( + listen = %local, + "TCP fallback ready with NO --dest-root: a peer may name any \ + absolute path. This matches the UDP path's --allow-any-dest \ + behaviour and is only safe on a trusted network." + ), + } + + loop { + let (stream, peer) = match listener.accept().await { + Ok(v) => v, + Err(e) => { + tracing::warn!(error = %e, "TCP fallback accept failed"); + continue; + } + }; + let root = dest_root.clone(); + tokio::spawn(async move { + if let Err(e) = handle(stream, peer, root).await { + tracing::warn!(%peer, error = %e, "TCP fallback transfer failed"); + } + }); + } +} + +async fn handle( + mut stream: TcpStream, + peer: std::net::SocketAddr, + dest_root: Option, +) -> std::io::Result<()> { + let result = receive(&mut stream, peer, dest_root).await; + let reply = match &result { + Ok(path) => { + tracing::info!(%peer, dest = %path.display(), "TCP fallback transfer complete"); + FallbackReply::Accepted + } + Err(reason) => { + tracing::warn!(%peer, reason = %reason, "TCP fallback transfer refused"); + FallbackReply::Refused(reason.clone()) + } + }; + stream.write_all(&reply.encode()).await?; + stream.flush().await?; + Ok(()) +} + +/// The transfer itself. `Err` carries a reason meant for a person. +async fn receive( + stream: &mut TcpStream, + peer: std::net::SocketAddr, + dest_root: Option, +) -> Result { + let deadline = || tokio::time::timeout(IDLE_TIMEOUT, std::future::pending::<()>()); + let _ = deadline; // documented intent; per-read timeouts below + + let mut head = [0u8; HEADER_LEN]; + read_exact(stream, &mut head).await?; + let (path_len, size) = + FallbackHeader::decode_head(&head).map_err(|e| e.to_string())?; + + let mut path_bytes = vec![0u8; path_len]; + read_exact(stream, &mut path_bytes).await?; + let header = + FallbackHeader::from_parts(&path_bytes, size).map_err(|e| e.to_string())?; + + // The same confinement the UDP receiver applies. A remote peer names + // the path; it does not choose where the root is. + let dest = match &dest_root { + Some(root) => crate::net_receiver::confine_dest_path(root, &header.path)?, + None => PathBuf::from(&header.path), + }; + + if let Some(parent) = dest.parent() { + tokio::fs::create_dir_all(parent) + .await + .map_err(|e| format!("creating {}: {e}", parent.display()))?; + } + + // Stage beside the destination, commit by rename. A crash or a + // truncated stream leaves the .part, never a short file under the + // real name. + let staging = staging_path(&dest); + let mut file = tokio::fs::File::create(&staging) + .await + .map_err(|e| format!("creating {}: {e}", staging.display()))?; + + let mut hasher = blake3::Hasher::new(); + let mut buf = vec![0u8; COPY_BUFFER]; + let mut remaining = header.size; + + tracing::info!(%peer, dest = %dest.display(), bytes = header.size, + "TCP fallback transfer starting"); + + while remaining > 0 { + let want = (remaining as usize).min(buf.len()); + let n = tokio::time::timeout(IDLE_TIMEOUT, stream.read(&mut buf[..want])) + .await + .map_err(|_| "peer stopped sending".to_string())? + .map_err(|e| format!("reading payload: {e}"))?; + if n == 0 { + let _ = tokio::fs::remove_file(&staging).await; + return Err(format!( + "connection closed with {remaining} of {} bytes still to come", + header.size + )); + } + hasher.update(&buf[..n]); + file.write_all(&buf[..n]) + .await + .map_err(|e| format!("writing {}: {e}", staging.display()))?; + remaining -= n as u64; + } + + let mut claimed = [0u8; 32]; + if let Err(e) = read_exact(stream, &mut claimed).await { + let _ = tokio::fs::remove_file(&staging).await; + return Err(format!("payload arrived but its hash did not: {e}")); + } + + let actual = hasher.finalize(); + if actual.as_bytes() != &claimed { + let _ = tokio::fs::remove_file(&staging).await; + return Err(format!( + "hash mismatch: sender said {}, {} bytes received hash to {}", + hex(&claimed), + header.size, + actual.to_hex() + )); + } + + // Durable before visible: the rename is the moment the file exists + // under its real name, and it must not name a file the kernel has not + // written yet. + file.flush().await.map_err(|e| format!("flushing: {e}"))?; + file.sync_all().await.map_err(|e| format!("syncing: {e}"))?; + drop(file); + + tokio::fs::rename(&staging, &dest) + .await + .map_err(|e| format!("committing {}: {e}", dest.display()))?; + + Ok(dest) +} + +async fn read_exact(stream: &mut TcpStream, buf: &mut [u8]) -> Result<(), String> { + tokio::time::timeout(IDLE_TIMEOUT, stream.read_exact(buf)) + .await + .map_err(|_| "peer stopped sending".to_string())? + .map_err(|e| format!("short read: {e}"))?; + Ok(()) +} + +fn staging_path(dest: &Path) -> PathBuf { + let mut name = dest.file_name().unwrap_or_default().to_os_string(); + name.push(".part"); + dest.with_file_name(name) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn staging_sits_beside_the_destination() { + // Beside, not in a temp directory: a rename across filesystems is + // not atomic, and the whole point of staging is the atomic commit. + assert_eq!( + staging_path(Path::new("/srv/incoming/a/b.bin")), + PathBuf::from("/srv/incoming/a/b.bin.part") + ); + } +} diff --git a/crates/ahp-proto/src/fallback.rs b/crates/ahp-proto/src/fallback.rs new file mode 100644 index 0000000..c407ab7 --- /dev/null +++ b/crates/ahp-proto/src/fallback.rs @@ -0,0 +1,353 @@ +// Favonius — high-performance file transfer over UDP +// Copyright (c) 2025-2026 Vantino SàRL +// SPDX-License-Identifier: Apache-2.0 + +//! The TCP fallback framing, shared by sender and daemon. +//! +//! # Why a UDP transfer engine ships a TCP path +//! +//! Enterprise egress is proxied and enterprise ingress is closed. Reaching +//! a receiving daemon means asking a network team to permit inbound UDP, +//! and plenty of policies decline that outright. Until now a blocked port +//! meant Favonius did not degrade — it failed. **A transfer that arrives +//! slowly beats one that needs a change request**, and an evaluator who +//! cannot move a file in their first ten minutes does not stay to read the +//! benchmarks. +//! +//! So this is deliberately *not* AHP over TCP. It borrows none of the +//! congestion control, none of the multi-stream machinery, and claims +//! none of the performance. The kernel's TCP stack does the work. It +//! exists so that "can we move a file at all" is always yes. +//! +//! # Same port number, both protocols +//! +//! The daemon listens for this on the **TCP** socket bearing its control +//! port number, so a deployment asks for one port rather than two, in a +//! sentence a network team can act on: *"permit 7801 to this host, UDP for +//! speed and TCP as the fallback."* UDP 7801 and TCP 7801 are separate +//! sockets and do not conflict. +//! +//! # The frame +//! +//! ```text +//! magic 8 b"FVNFALL1" +//! version 1 1 +//! flags 1 reserved, must be 0 +//! path_len 2 big-endian, <= MAX_PATH +//! size 8 big-endian, file length in bytes +//! path path_len UTF-8, relative, resolved against --dest-root +//! payload size the file +//! hash 32 BLAKE3 of the payload +//! ``` +//! +//! The hash travels **after** the payload so the sender can stream a file +//! it is hashing as it reads, without a second pass over the data. The +//! receiver verifies before it commits, so a truncated or altered transfer +//! is refused rather than written. +//! +//! Integers are big-endian throughout, matching the rest of the wire +//! format. A previous module documented little-endian and was wrong, which +//! cost a debugging session — so this one is tested in both directions. + +/// Connectivity probe payload, sent by `favonius check` to a UDP port. +/// +/// A daemon answers with [`PROBE_REPLY`], which proves the round trip +/// without needing a handshake — the honest test of a datagram path is a +/// datagram that comes back. +pub const PROBE: &[u8; 8] = b"FVNPROBE"; + +/// The answer. **Exactly as long as [`PROBE`]**, deliberately: an +/// unauthenticated responder that replies with more bytes than it receives +/// is a reflection amplifier, and this port is reachable by anyone. +pub const PROBE_REPLY: &[u8; 8] = b"FVNPONG1"; + +/// Frame magic. Distinct from the UDP wire format: a client that reaches +/// the wrong port should be told so, not silently misparsed. +pub const MAGIC: &[u8; 8] = b"FVNFALL1"; + +/// Wire version of this framing. +pub const VERSION: u8 = 1; + +/// Bytes before the path. Fixed, so a receiver can read the head in one go. +pub const HEADER_LEN: usize = 8 + 1 + 1 + 2 + 8; + +/// Longest destination path accepted, in bytes. +/// +/// Bounded because it is read from the network before anything is +/// validated: an unbounded length is an allocation an unauthenticated peer +/// controls. +pub const MAX_PATH: usize = 4096; + +/// Largest file this path will accept, 1 TiB. +/// +/// Not a statement about what the engine can move — it is a ceiling on +/// what a single unauthenticated frame may claim, so a bad length field +/// cannot make the receiver wait forever on bytes that are not coming. +pub const MAX_SIZE: u64 = 1024 * 1024 * 1024 * 1024; + +/// What a sender announces before the bytes. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FallbackHeader { + /// Destination path, relative, resolved against the daemon's root. + pub path: String, + /// Payload length in bytes. + pub size: u64, +} + +#[derive(Debug, PartialEq, Eq, thiserror::Error)] +pub enum FallbackError { + #[error("not a Favonius fallback frame (wrong magic)")] + BadMagic, + #[error("unsupported fallback version {0}; this daemon speaks {VERSION}")] + BadVersion(u8), + #[error("reserved flags must be zero, got {0:#x}")] + ReservedFlags(u8), + #[error("path length {0} exceeds the {MAX_PATH}-byte maximum")] + PathTooLong(usize), + #[error("path is empty")] + EmptyPath, + #[error("declared size {0} exceeds the {MAX_SIZE}-byte maximum")] + TooLarge(u64), + #[error("path is not valid UTF-8")] + BadUtf8, + #[error("frame is truncated: expected {expected} bytes, got {got}")] + Truncated { expected: usize, got: usize }, +} + +impl FallbackHeader { + /// Serialise the fixed head plus the path. + pub fn encode(&self) -> Result, FallbackError> { + let path = self.path.as_bytes(); + if path.is_empty() { + return Err(FallbackError::EmptyPath); + } + if path.len() > MAX_PATH { + return Err(FallbackError::PathTooLong(path.len())); + } + if self.size > MAX_SIZE { + return Err(FallbackError::TooLarge(self.size)); + } + + let mut out = Vec::with_capacity(HEADER_LEN + path.len()); + out.extend_from_slice(MAGIC); + out.push(VERSION); + out.push(0); // flags + out.extend_from_slice(&(path.len() as u16).to_be_bytes()); + out.extend_from_slice(&self.size.to_be_bytes()); + out.extend_from_slice(path); + Ok(out) + } + + /// Parse the fixed head. Returns the path length still to be read. + /// + /// Split from the path so a receiver can read exactly `HEADER_LEN` + /// bytes, learn how many more it needs, and never guess. + pub fn decode_head(buf: &[u8]) -> Result<(usize, u64), FallbackError> { + if buf.len() < HEADER_LEN { + return Err(FallbackError::Truncated { + expected: HEADER_LEN, + got: buf.len(), + }); + } + if &buf[0..8] != MAGIC { + return Err(FallbackError::BadMagic); + } + if buf[8] != VERSION { + return Err(FallbackError::BadVersion(buf[8])); + } + if buf[9] != 0 { + return Err(FallbackError::ReservedFlags(buf[9])); + } + let path_len = u16::from_be_bytes([buf[10], buf[11]]) as usize; + if path_len == 0 { + return Err(FallbackError::EmptyPath); + } + if path_len > MAX_PATH { + return Err(FallbackError::PathTooLong(path_len)); + } + let size = u64::from_be_bytes(buf[12..20].try_into().expect("checked length")); + if size > MAX_SIZE { + return Err(FallbackError::TooLarge(size)); + } + Ok((path_len, size)) + } + + /// Complete the header once the path bytes have been read. + pub fn from_parts(path_bytes: &[u8], size: u64) -> Result { + let path = std::str::from_utf8(path_bytes) + .map_err(|_| FallbackError::BadUtf8)? + .to_string(); + Ok(Self { path, size }) + } +} + +/// The daemon's reply, one byte plus an optional reason. +/// +/// Deliberately tiny: the sender needs to know whether the bytes were +/// committed, and if not, something a human can act on. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum FallbackReply { + /// Written and verified. + Accepted, + /// Refused, with a reason meant for a person. + Refused(String), +} + +impl FallbackReply { + pub fn encode(&self) -> Vec { + match self { + Self::Accepted => vec![0x01], + Self::Refused(reason) => { + let r = reason.as_bytes(); + let len = r.len().min(u16::MAX as usize); + let mut out = Vec::with_capacity(3 + len); + out.push(0x02); + out.extend_from_slice(&(len as u16).to_be_bytes()); + out.extend_from_slice(&r[..len]); + out + } + } + } + + pub fn decode(buf: &[u8]) -> Option { + match buf.first()? { + 0x01 => Some(Self::Accepted), + 0x02 => { + let len = u16::from_be_bytes([*buf.get(1)?, *buf.get(2)?]) as usize; + let bytes = buf.get(3..3 + len)?; + Some(Self::Refused(String::from_utf8_lossy(bytes).into_owned())) + } + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The reply must never be longer than the probe. A larger answer to + /// an unauthenticated request is a reflection amplifier. + #[test] + fn the_probe_reply_cannot_amplify() { + assert_eq!(PROBE.len(), PROBE_REPLY.len()); + assert_ne!(PROBE, PROBE_REPLY, "the reply must be distinguishable from the probe"); + } + + #[test] + fn a_header_round_trips() { + let h = FallbackHeader { path: "reports/q3.bin".into(), size: 3_145_728 }; + let bytes = h.encode().unwrap(); + let (path_len, size) = FallbackHeader::decode_head(&bytes).unwrap(); + assert_eq!(size, 3_145_728); + let back = FallbackHeader::from_parts(&bytes[HEADER_LEN..HEADER_LEN + path_len], size).unwrap(); + assert_eq!(back, h); + } + + /// Integers are big-endian. A sibling module documented little-endian, + /// was wrong, and cost a debugging session; this pins the byte order + /// so the next reader does not have to trust a comment. + #[test] + fn integers_are_big_endian_on_the_wire() { + // Distinct bytes so a byte-swap is visible, and under MAX_SIZE -- + // the first draft of this test used a value the size cap + // correctly refused, which is the cap working rather than a bug. + let h = FallbackHeader { path: "x".into(), size: 0x0000_0001_0203_0405 }; + let b = h.encode().unwrap(); + assert_eq!(&b[12..20], &[0, 0, 0, 1, 2, 3, 4, 5], "size is not big-endian"); + assert_eq!(&b[10..12], &[0, 1], "path length is not big-endian"); + } + + #[test] + fn a_unicode_path_survives() { + let h = FallbackHeader { path: "dossier été/note.txt".into(), size: 7 }; + let b = h.encode().unwrap(); + let (n, size) = FallbackHeader::decode_head(&b).unwrap(); + assert_eq!( + FallbackHeader::from_parts(&b[HEADER_LEN..HEADER_LEN + n], size).unwrap(), + h + ); + } + + // ── what must be refused ────────────────────────────────────────── + + #[test] + fn a_foreign_frame_is_refused_rather_than_misparsed() { + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[0] = b'X'; + assert_eq!(FallbackHeader::decode_head(&b), Err(FallbackError::BadMagic)); + } + + #[test] + fn a_future_version_is_named_not_guessed() { + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[8] = 9; + assert_eq!(FallbackHeader::decode_head(&b), Err(FallbackError::BadVersion(9))); + } + + #[test] + fn reserved_flags_must_be_zero() { + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[9] = 0x80; + assert_eq!( + FallbackHeader::decode_head(&b), + Err(FallbackError::ReservedFlags(0x80)) + ); + } + + /// The length fields are read from the network before anything is + /// trusted, so an absurd value must be refused rather than allocated. + #[test] + fn absurd_lengths_are_refused_before_allocating() { + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[10..12].copy_from_slice(&(MAX_PATH as u16 + 1).to_be_bytes()); + assert!(matches!( + FallbackHeader::decode_head(&b), + Err(FallbackError::PathTooLong(_)) + )); + + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[12..20].copy_from_slice(&u64::MAX.to_be_bytes()); + assert!(matches!( + FallbackHeader::decode_head(&b), + Err(FallbackError::TooLarge(_)) + )); + } + + #[test] + fn a_truncated_head_says_how_short_it_is() { + assert_eq!( + FallbackHeader::decode_head(&[0u8; 4]), + Err(FallbackError::Truncated { expected: HEADER_LEN, got: 4 }) + ); + } + + #[test] + fn an_empty_path_is_refused_both_ways() { + assert_eq!( + FallbackHeader { path: String::new(), size: 1 }.encode(), + Err(FallbackError::EmptyPath) + ); + let mut b = FallbackHeader { path: "a".into(), size: 1 }.encode().unwrap(); + b[10..12].copy_from_slice(&0u16.to_be_bytes()); + assert_eq!(FallbackHeader::decode_head(&b), Err(FallbackError::EmptyPath)); + } + + #[test] + fn replies_round_trip() { + assert_eq!( + FallbackReply::decode(&FallbackReply::Accepted.encode()), + Some(FallbackReply::Accepted) + ); + let refused = FallbackReply::Refused("destination path escapes --dest-root".into()); + assert_eq!(FallbackReply::decode(&refused.encode()), Some(refused)); + } + + #[test] + fn a_reply_that_is_neither_is_not_read_as_success() { + // The dangerous direction: an unrecognised byte must not decode as + // Accepted, or a confused peer becomes a successful transfer. + assert_eq!(FallbackReply::decode(&[0xFF]), None); + assert_eq!(FallbackReply::decode(&[]), None); + } +} diff --git a/crates/ahp-proto/src/lib.rs b/crates/ahp-proto/src/lib.rs index aaf7c8e..1a7d448 100644 --- a/crates/ahp-proto/src/lib.rs +++ b/crates/ahp-proto/src/lib.rs @@ -36,6 +36,7 @@ pub mod codec; pub mod data; pub mod error; pub mod extensions; +pub mod fallback; pub mod flags; pub mod header; pub mod hello;