diff --git a/README.md b/README.md index a8dce5da..f0de5997 100644 --- a/README.md +++ b/README.md @@ -1,364 +1,150 @@ # mqproxy -A **multipath application proxy/accelerator** built on [Multipath QUIC](https://datatracker.ietf.org/doc/draft-ietf-quic-multipath/), using a [fork of XQUIC](https://github.com/mp0rta/xquic). mqproxy maps application flows directly onto MPQUIC primitives — one TCP flow becomes one MPQUIC stream, one HTTP request becomes one H3 stream over MPQUIC, one UDP session becomes MPQUIC DATAGRAMs — so that applications get path diversity, seamless failover, and **bandwidth aggregation** without implementing MPQUIC themselves. +A **multipath proxy** built on [Multipath QUIC](https://datatracker.ietf.org/doc/draft-ietf-quic-multipath/) (via a [fork of XQUIC](https://github.com/mp0rta/xquic)). A client/server pair carries application traffic over one MPQUIC tunnel, so apps get **bandwidth aggregation** and seamless failover across links (e.g. WiFi + LTE) without knowing anything about MPQUIC. -mqproxy runs as a **client/server pair**: the client exposes one or more local ingresses, carries traffic to the server over a single multipath QUIC tunnel, and the server reaches the origin. Four ingress modes are available — a **TCP proxy** (SOCKS5 / HTTP CONNECT), an **HTTP request gateway** (`POST /_mqproxy/fetch`, executed against origins with TLS verification always on), a **UDP relay** (SOCKS5 UDP ASSOCIATE over MPQUIC DATAGRAMs), and **transparent capture** of kernel-redirected TCP with an optional TLS-terminating MITM mode. Every mode gets path diversity, seamless failover, and within-stream bandwidth aggregation across the bound paths. Production features include automatic reconnect/keepalive, per-path and per-request metrics, congestion-control and multipath-scheduler selection, a pre-auth connection cap, masquerade mode, INI config files, and systemd service packaging. +mqproxy maps each application flow onto an MPQUIC primitive: -mqproxy is the L4/L7 sibling of [mqvpn](https://github.com/mp0rta/mqvpn): where mqvpn is a standards-based L3 VPN that carries IP packets in QUIC DATAGRAMs (MASQUE CONNECT-IP), mqproxy works at the application-flow layer and is **MPQUIC-native**. - -| | mqvpn | mqproxy | +| Mode | Mapping | Client flag | |---|---|---| -| Layer | L3 | L4 / L7 | -| Data plane | QUIC DATAGRAM | QUIC STREAM + DATAGRAM | -| Model | IP packet tunnel | Application-flow proxy | -| Strength | IP transparency, standards-oriented | MPQUIC-native flow mapping | - -The two are complementary and can coexist: run mqvpn for whole-device transparency while delegating specific high-priority transfers to mqproxy. - -## Why MPQUIC-native? - -Because a QUIC **stream** is reassembled by offset, the STREAM frames of a single stream can be spread across multiple paths while correctness is preserved. So a single large download/upload — carried as one MPQUIC stream — gets *within-stream* multipath aggregation. This is a structural advantage over carrying inner traffic in DATAGRAMs (the mqvpn/MASQUE path), where flow pinning forces a single path and not-pinning risks inner-QUIC reordering. - -**Measured:** in a 2-path 100 Mbit/s testbed the TCP proxy aggregates even a *single* TCP stream — **1.81× single-path at `-P 1`**, 1.93× at `-P 16` — whereas a flow-pinned L3 datagram tunnel needs multiple parallel flows before its second path engages. Full matrix (`-P 1…16`, symmetric + asymmetric, vs mqvpn `wlb`/`minrtt`) in the [TCP aggregation benchmark](docs/report/2026-06-23-single-tcp-aggregation-mqvpn-vs-mqproxy.md). +| **TCP proxy** (SOCKS5 / HTTP CONNECT) | 1 TCP connection → 1 MPQUIC stream | `--socks5`, `--http-connect` | +| **HTTP gateway** | 1 HTTP request → 1 HTTP/3 stream | `--gateway` | +| **UDP relay** (SOCKS5 UDP ASSOCIATE) | 1 UDP session → MPQUIC DATAGRAMs | `--socks5` | +| **Transparent capture** | kernel-redirected TCP → 1 MPQUIC stream | `--tproxy` | +| **TLS MITM** (opt-in) | 1 browser HTTP/2 request → 1 HTTP/3 stream | `--tproxy --mitm` | -![Single-TCP aggregation across two paths: mqproxy-tcp roughly doubles the single-path goodput](docs/report/figures/2026-06-23-single-tcp-simple.png) +The client picks the mode with its ingress flags; the server serves them all. Only TLS MITM decrypts traffic — every other mode keeps TLS end-to-end between app and origin. -*`direct-single` = no tunnel, one path (the baseline); `mqproxy-single` = mqproxy over a single path (tunnel overhead only); `mqproxy-tcp` = mqproxy aggregating one TCP stream across both paths.* +mqproxy is the L4/L7 sibling of [mqvpn](https://github.com/mp0rta/mqvpn) (an L3 VPN carrying IP packets in QUIC DATAGRAMs). They coexist: mqvpn for whole-device coverage, mqproxy for the flows you want aggregated. -## Operating Modes +## Why MPQUIC streams? -| Mode | Mapping | | -|---|---|---| -| **TCP Proxy** | 1 TCP flow → 1 MPQUIC bidi stream | ✅ | -| **HTTP Request Execution Gateway** | 1 HTTP request → 1 H3 stream over MPQUIC | ✅ | -| **UDP Relay** | 1 UDP session → MPQUIC DATAGRAMs | ✅ | -| **Transparent TCP Capture** | kernel-redirected TCP → opaque MPQUIC stream | ✅ | -| **TLS MITM Ingress** | terminate browser TLS (forged leaf) → H2 → Gateway tunnel | ✅ optional | - -**What each mode gives you:** - -- **TCP Proxy** — zero app changes, end-to-end TLS preserved (mqproxy never sees plaintext). Each TCP connection becomes one MPQUIC stream, so even a single download aggregates bandwidth across all paths. Separate TCP connections get separate MPQUIC streams and do not block each other. The trade-off: when a browser multiplexes many HTTP/2 requests over a *single* TCP connection, all those requests share one MPQUIC stream, so a retransmission within that stream stalls them all (the same transport-layer head-of-line blocking that HTTP/3 was designed to eliminate). -- **TLS MITM** — opt-in TLS termination lifts the proxy to L7 visibility. Each HTTP/2 request stream is mapped to its *own* MPQUIC stream, so a loss on one request does not block others — your HTTP/2 traffic effectively gains HTTP/3-class stream independence, plus multipath aggregation that even native HTTP/3 does not provide. Requires installing the operator's CA on the device. -- **HTTP Gateway** — an explicit request-delegation API (`POST /_mqproxy/fetch`); each request is one H3 stream with independent multipath aggregation. Useful for SDKs and server-to-server calls that can set `X-Mq-*` headers directly, without SOCKS5 or transparent capture. -- **UDP Relay** — carries non-QUIC UDP (DNS, game, VoIP) over MPQUIC DATAGRAMs, preserving the lossy/unordered semantics applications expect. Packets ride the multipath tunnel but are not retransmitted — latency-sensitive traffic stays latency-sensitive. -- **Transparent Capture** (without `--mitm`) — kernel-level redirect with no app config; same aggregation and end-to-end TLS guarantees as TCP Proxy mode, but apps need no SOCKS5/proxy configuration at all. - -TCP Proxy and Transparent Capture (without `--mitm`) do **not** terminate TLS: for HTTPS, TLS stays end-to-end between the application and the origin. Only the WAN segment between mqproxy-client and mqproxy-server is carried over MPQUIC. - -## How It Works - -```text -Application (curl / SDK / app) - │ TCP via SOCKS5 / HTTP CONNECT - ▼ -mqproxy-client ──────────────── MPQUIC (multipath) ──────────────► mqproxy-server - │ CONNECT_TCP(host:port) 1 TCP flow = 1 bidi stream │ dial host:port - │ spread across paths ▼ - └─ bidirectional byte relay ◄─────────────────────────────────► Origin server -``` +A QUIC stream is reassembled by offset, so one stream can be spread across several paths and still arrive intact. A single download carried as one stream is therefore aggregated across paths. A datagram tunnel can't do this: it either pins a flow to one path or reorders it. -A TCP flow arriving at the client (via SOCKS5 or HTTP CONNECT) opens a new MPQUIC bidirectional stream. The stream begins with a `CONNECT_TCP_REQUEST` (SOCKS5-style address types); the server dials the target and replies `CONNECT_TCP_RESPONSE`, after which the same stream relays raw bytes in both directions. Connection-level authentication happens once on a control stream before any flow is opened. +In a 2 × 100 Mbit/s testbed, mqproxy speeds up a **single** TCP stream by **1.81×** (1.93× at 16 streams), while a flow-pinned L3 tunnel needs several parallel flows before it uses its second path. See the [benchmark report](docs/report/2026-06-23-single-tcp-aggregation-mqvpn-vs-mqproxy.md). -### HTTP Request Execution Gateway +![Single-TCP aggregation across two paths](docs/report/figures/2026-06-23-single-tcp-simple.png) -```text -Application (curl / SDK) - │ POST /_mqproxy/fetch (X-Mq-Auth / X-Mq-Target / X-Mq-Method + raw body) - ▼ -mqproxy-client ──────── HTTP/3 over MPQUIC (ALPN h3) ────────► mqproxy-server - 1 HTTP request = 1 H3 request stream = 1 MPQUIC stream │ hyper (h2→h1, - spread across paths │ TLS verify ON) - ▼ - Origin server -``` +*`direct-single`: no tunnel, one path. `mqproxy-single`: tunnel over one path. `mqproxy-tcp`: tunnel aggregating one TCP stream over both paths.* -Instead of tunneling opaque bytes, the gateway **executes delegated HTTP requests**: the client validates `X-Mq-*` headers, maps the request onto a standard H3 request stream (QPACK, trailers and stream management come from the H3 stack — no custom HTTP framing on the wire), and the server authenticates each request (`X-Mq-Auth`, per-request), strips the `X-Mq-*` controls, and runs the request against the origin with full TLS verification. Errors map to HTTP statuses (DNS failure → 502, connect timeout → 504, bad token → 403, …) and responses carry an `X-Mq-Origin-Protocol` diagnostic header. Because each request is one MPQUIC stream, large downloads *and uploads* get within-stream multipath aggregation. +## Build -Per-request `X-Mq-*` controls let a caller opt into gateway features without changing the API: `X-Mq-Origin-Protocol` pins the upstream HTTP version (`h1`/`h2`; `h3` is rejected), `X-Mq-Accept-Encoding` requests download compression, `X-Mq-Forward-Cookie` forwards the `Cookie` header upstream (otherwise withheld), and the legacy `X-Mq-Cache` control is ignored (the origin cache has been removed). The server also pools and reuses origin connections across requests. - -### UDP Relay - -```text -UDP app (DNS / game / VoIP / …) - │ SOCKS5 UDP ASSOCIATE - ▼ -mqproxy-client ──────── MPQUIC DATAGRAMs (multipath) ────────► mqproxy-server - 1 UDP session = a bidi signalling stream + DATAGRAMs │ connected - carrying session_id-tagged packets │ UDP socket - ▼ - UDP target -``` - -UDP relay carries non-QUIC UDP traffic (DNS, NTP, game, VoIP, app-specific UDP) over MPQUIC DATAGRAMs. The ingress is **SOCKS5 UDP ASSOCIATE** (RFC 1928 §7) on the same `--socks5` listener used for TCP. For each target the client opens a small bidi signalling stream (`UDP_SESSION_OPEN`/`RESP`, multiplexed alongside TCP on the one `mqproxy-tcp/1` connection), then sends packets as DATAGRAMs tagged with a session id; the server keeps a connected UDP socket per session and relays both ways. Packets larger than the path MTU are fragmented and reassembled (4-slot LRU, no retransmission — UDP stays lossy). Sessions are torn down on idle timeout (server-driven, `--udp-idle-timeout`), on stream close, or when the SOCKS5 control connection drops. The server advertises the capability at auth and can refuse all UDP with `--no-udp`. UDP relay rides the `mqproxy-tcp/1` connection, so a client running `--gateway` only (H3 connection) does not get it. - -## Building from source - -Install Rust with rustup; `rust-toolchain.toml` pins the supported toolchain. -Native dependencies are a C/C++ toolchain, CMake, Go and Git for the vendored -xquic/BoringSSL build. Cargo builds and statically links them automatically. +Needs Rust (the version is pinned in `rust-toolchain.toml`), plus a C/C++ toolchain, CMake, Go and Git. Cargo builds xquic and BoringSSL from the submodules and links them statically. ```bash sudo apt-get install -y build-essential cmake git golang-go git clone --recursive https://github.com/mp0rta/mqproxy.git cd mqproxy -git submodule update --init --recursive cargo build --release --locked -p mqproxy -./target/release/mqproxy --help ``` -The application is Rust. HTTP/3 uses h3wire; origin HTTP/1.1 and HTTP/2 use -hyper and rustls. xquic and its nested BoringSSL remain pinned submodules. - -## Quick Start +Or install a prebuilt `.deb` (amd64/arm64) from [Releases](https://github.com/mp0rta/mqproxy/releases); see [Run as a service](#run-as-a-service). -Run a server and a client locally, then send TCP traffic through the client's SOCKS5 ingress. +## Quick start ```bash -# Server — listens for MPQUIC on UDP :4433. --cert/--key are required; -# the repo ships a self-signed test cert under tests/certs for local use. +# Server: MPQUIC on UDP :4433 (test cert for local use only) ./target/release/mqproxy server --listen 0.0.0.0:4433 --token secret123 \ --cert tests/certs/test.crt --key tests/certs/test.key -# Client — connects to the server, exposes a local SOCKS5 listener on :1080. -./target/release/mqproxy client \ - --server 127.0.0.1:4433 \ - --token secret123 \ - --socks5 127.0.0.1:1080 -``` +# Client: SOCKS5 on :1080; each --path binds one local IP as an MPQUIC path +./target/release/mqproxy client --server :4433 --token secret123 \ + --socks5 127.0.0.1:1080 \ + --path 192.168.1.50 --path 10.20.0.30 -```bash -# Send traffic through the proxy curl --socks5-hostname 127.0.0.1:1080 https://example.com/ ``` -**Multipath** — bind additional local IPs as MPQUIC paths (e.g. WiFi + LTE) by repeating `--path`; the stream is then aggregated across them: - -```bash -./target/release/mqproxy client \ - --server :4433 --token secret123 \ - --socks5 127.0.0.1:1080 \ - --path 192.168.1.50 \ - --path 10.20.0.30 -``` - -You can also expose an HTTP CONNECT ingress with `--http-connect ` (use it via `curl --proxy http://127.0.0.1: https://...`). +All flags: `mqproxy server --help`, `mqproxy client --help`. -### HTTP Gateway quick start +### HTTP gateway -The gateway is enabled on the server by default. On the client, add `--gateway` (works with or without `--socks5`): +The client sends an HTTP request to an explicit API, and the server fetches it from the origin (origin TLS is always verified). Each request is its own HTTP/3 stream, so both downloads and uploads are aggregated. Useful for SDKs and server-to-server calls. ```bash -./target/release/mqproxy client \ - --server 127.0.0.1:4433 --token secret123 \ +./target/release/mqproxy client --server :4433 --token secret123 \ --gateway 127.0.0.1:8080 -# Delegate a download (any HTTP method via X-Mq-Method; default GET) curl -X POST http://127.0.0.1:8080/_mqproxy/fetch \ -H "X-Mq-Auth: Bearer secret123" \ -H "X-Mq-Target: https://example.com/large.bin" \ - -o large.bin - -# Delegate an upload -curl -X POST http://127.0.0.1:8080/_mqproxy/fetch \ - -H "X-Mq-Auth: Bearer secret123" \ - -H "X-Mq-Target: https://example.com/upload" \ - -H "X-Mq-Method: PUT" \ - --data-binary @large.bin + -o large.bin # add -H "X-Mq-Method: PUT" --data-binary @f to upload ``` -`--path` works the same way here: the gateway's MPQUIC connection aggregates each request across all bound paths. +Optional request headers: -### UDP relay quick start +| Header | Effect | +|---|---| +| `X-Mq-Method` | Method used toward the origin (default `GET`) | +| `X-Mq-Origin-Protocol` | Pins the origin protocol to `h1` or `h2` | +| `X-Mq-Accept-Encoding` | Asks for compression on the download | +| `X-Mq-Forward-Cookie` | Forwards `Cookie` to the origin (withheld by default) | -UDP relay is exposed on the **same `--socks5` listener** — any SOCKS5 client that speaks UDP ASSOCIATE can use it. The server advertises the capability at auth; pass `--udp-idle-timeout ` to tune session lifetime, or `--no-udp` to refuse UDP entirely. +Errors come back as HTTP statuses (DNS failure 502, connect timeout 504, bad token 403, …). The server pools origin connections. Server flags: `--no-gateway`, `--origin-ca `, `--request-metrics`, `--masquerade` (unauthenticated requests get a bare 404 instead of 403; recommended on internet-facing servers). -```bash -# Server (UDP relay on by default; 30s idle timeout shown) -./target/release/mqproxy server --listen 0.0.0.0:4433 --token secret123 \ - --udp-idle-timeout 30 +### UDP relay -# Client — the SOCKS5 listener handles both TCP and UDP -./target/release/mqproxy client \ - --server 127.0.0.1:4433 --token secret123 \ - --socks5 127.0.0.1:1080 -``` - -`curl` does not speak SOCKS5 UDP ASSOCIATE, so use a UDP-capable SOCKS5 client. The repo ships `udpsocks`, a minimal test client (built by the test suite), which is handy for a quick check: +UDP relay uses the same `--socks5` listener, through SOCKS5 UDP ASSOCIATE. Packets travel as DATAGRAMs and are never retransmitted, so DNS, game and VoIP traffic stays latency-first. `curl` can't speak UDP ASSOCIATE; use the bundled test client instead: ```bash -# Relay a UDP packet to a target through the client's SOCKS5 listener ./target/release/examples/udpsocks --proxy 127.0.0.1:1080 --target 8.8.8.8:53 --send 32 --count 1 ``` -### Transparent capture quick start - -Transparent capture redirects TCP connections at the kernel level directly into mqproxy without any application changes — no SOCKS5 configuration, no proxy settings, no app awareness. By default each captured connection is relayed **opaquely** (byte-for-byte, without decryption) over the MPQUIC tunnel as a single stream, giving flow-level multipath aggregation. End-to-end TLS is then fully preserved between the application and the origin; **mqproxy never sees plaintext**. Adding `--mitm` instead terminates and inspects the TLS as HTTP/2 — that opt-in mode is documented in [TLS MITM mode](#tls-mitm-mode). - -> **Linux + IPv4 only.** Transparent capture installs kernel firewall rules, so it needs root or `CAP_NET_ADMIN`. - -Two kernel capture mechanisms are supported: +Server flags: `--udp-idle-timeout ` (default 60), `--no-udp`. A client running only `--gateway` has no UDP relay. -- **`redirect` (default)** — uses `nft nat OUTPUT` (REDIRECT target). Captures the *local machine's own outbound* TCP. Does not need `IP_TRANSPARENT` on the socket. This is the right mode when mqproxy and the apps being accelerated run on the same host. -- **`tproxy`** — uses `nft mangle PREROUTING` (TPROXY target) with `IP_TRANSPARENT` on the listening socket. Captures *forwarded* traffic from downstream LAN hosts, as on a router gateway. Requires `fwmark` + a policy-routing table so the local TCP stack's reply packets are routed back out the right interface. This is the standard Linux TPROXY setup; it composes with any router/policy-routing stack that can mark packets and steer them to the listener. +### Transparent capture (Linux, IPv4) -**Single-host quickstart (redirect mode, `--setup-redirect`):** +TCP is redirected in the kernel, so apps need no proxy settings. Traffic is relayed byte-for-byte; TLS is not touched. ```bash -# Server — no change from the regular config. -./target/release/mqproxy server --listen 0.0.0.0:4433 --token secret123 - -# Client — transparent listener on :12443; self-installs nft rules (needs root). -sudo ./target/release/mqproxy client \ - --server 127.0.0.1:4433 --token secret123 \ - --tproxy 127.0.0.1:12443 \ - --setup-redirect - -# Any app on this host connecting outbound to TCP :443 is now transparently -# captured, aggregated over MPQUIC, and forwarded to the origin. -# No curl --socks5 / --proxy flags needed. -curl https://example.com/ -``` - -`--setup-redirect` tells mqproxy to install the nft rules on start and remove them on exit. It needs `root` or `CAP_NET_ADMIN`. The self-installed rule captures **TCP destination port 443 by default**; use `--tproxy-dport ` to capture a different port. For multiple ports or finer control, install the firewall rules yourself and just point the traffic at the listener — mqproxy reads the original destination of whatever the rules redirect. - -**Router/gateway deployment (tproxy mode):** - -When the router stack already owns the firewall and policy-routing rules (any setup that places a `TPROXY` target in `PREROUTING` and marks the packets), leave `--setup-redirect` OFF and let mqproxy just provide the listener — match its `--tproxy-fwmark`/`--tproxy-table` to whatever the rules use: +# Single host: capture this machine's outbound TCP :443. Needs root or CAP_NET_ADMIN. +sudo ./target/release/mqproxy client --server :4433 --token secret123 \ + --tproxy 127.0.0.1:12443 --setup-redirect # --tproxy-dport to change 443 -```bash -sudo ./target/release/mqproxy client \ - --server :4433 --token secret123 \ - --tproxy 0.0.0.0:12443 \ - --tproxy-mode tproxy \ - --tproxy-fwmark 1 \ - --tproxy-table 100 - # no --setup-redirect — the router stack owns the rules +curl https://example.com/ # captured, no proxy flags ``` -**Loop-avoidance and security notes:** - -- `--tproxy-uid ` marks one UID whose *own outbound* traffic is exempt from redirection (so mqproxy's own connections to the server are not re-captured into itself). Defaults to `geteuid()` of the process. Running as a dedicated non-root service account is recommended; using uid 0 would exempt all root traffic, which is wider than intended. -- By default transparent capture is **opaque**: mqproxy relays raw TLS bytes and never decrypts them. Applications with certificate pinning continue to work. Adding `--mitm` turns this capture path into a TLS-terminating L7 proxy — see [TLS MITM mode](#tls-mitm-mode) below. MITM is off unless `--mitm` is passed. - -### TLS MITM mode +- `--setup-redirect` adds the nft rules (`nat OUTPUT` REDIRECT) at start and removes them at exit. You can instead write your own rules and just point them at the listener. +- **Router** (forwarded LAN traffic): use `--tproxy-mode tproxy`, which needs a `mangle PREROUTING` TPROXY rule plus policy routing. Leave `--setup-redirect` off and set `--tproxy-fwmark` / `--tproxy-table` (defaults 1 / 100) to match your rules. +- **Loop avoidance:** outbound traffic from `--tproxy-uid` (default: the process's euid) is not redirected. Run mqproxy as a dedicated non-root user; with uid 0, all root traffic would bypass capture. -`--mitm` turns the transparent-capture path into a **TLS-terminating L7 proxy**. For each captured connection the client peeks the TLS ClientHello SNI, forges a per-host leaf certificate signed by the operator's CA (`--ca-cert`/`--ca-key`), terminates TLS speaking **HTTP/2**, and maps each H2 request onto its own H3 request on the MPQUIC tunnel; the server's gateway fetches the origin. The browser↔client side speaks plain h2; the client↔server tunnel is MPQUIC, so every request gets its own stream (no head-of-line blocking across requests) and its own multipath scheduling. +## TLS MITM -> **Trust model.** This is an **operator-controlled / consenting-endpoint** MITM (a corporate-proxy or personal-VPN posture), not an attack tool. It only works because the operator has installed their own CA on the device so the browser trusts the forged leaves. The CA private key is the trust anchor — protect it: mqproxy refuses a key file that is a symlink, is not owned by the user running mqproxy, or is readable by group or others. +`--mitm` turns transparent capture into an HTTP/2-terminating proxy. For each connection, the client reads the SNI, forges a leaf certificate signed by **your** CA, terminates TLS, and sends each HTTP/2 request on its own HTTP/3 stream. Requests no longer block one another, and each one is scheduled across paths independently. -**Create a CA.** mqproxy needs a CA certificate and its **unencrypted PKCS#8** private key (`-----BEGIN PRIVATE KEY-----`): +> **Trust model:** This is for an operator who controls the device (like a corporate proxy or personal VPN), not for intercepting third parties. It works only on devices that trust your CA. The CA key is the trust anchor: mqproxy refuses a key that is a symlink, belongs to another user, or is readable by group or others. ```bash +# CA: unencrypted PKCS#8 key (PKCS#1/SEC1/encrypted keys are rejected with a conversion hint) openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:P-256 -nodes \ -keyout mitm-ca.key -out mitm-ca.crt -days 825 -subj "/CN=mqproxy MITM CA" \ - -addext basicConstraints=critical,CA:TRUE \ - -addext keyUsage=critical,keyCertSign + -addext basicConstraints=critical,CA:TRUE -addext keyUsage=critical,keyCertSign + # optional scope: -addext "nameConstraints=critical,permitted;DNS:example.com" chmod 600 mitm-ca.key -``` - -Install `mitm-ca.crt` in the trust store of every device whose traffic you capture. EC (P-256, P-384), Ed25519 and RSA CAs work. **PKCS#8 only:** a PKCS#1 (`BEGIN RSA PRIVATE KEY`) or SEC1 (`BEGIN EC PRIVATE KEY`) key is a startup error that tells you to convert it with `openssl pkcs8 -topk8 -nocrypt -in old.key -out mitm-ca.key`; an encrypted key is rejected too. - -To limit the CA to your own domains, add a `nameConstraints` extension to the command above (browsers enforce it, and mqproxy relays every other host opaquely instead of forging a certificate the browser would reject): - -```bash - -addext "nameConstraints=critical,permitted;DNS:example.com,permitted;DNS:example.org" -``` - -`DNS:example.com` permits that name and all its subdomains; `DNS:.example.com` permits subdomains only. `IP` constraints are ignored; any other constraint type, or a `DNS` constraint that is not a host name, is a startup error. -```bash -# Server — unchanged; the gateway origin bridge does the origin fetch. -./target/release/mqproxy server --listen 0.0.0.0:4433 --token secret123 \ - --cert /etc/mqproxy/tls/server.pem --key /etc/mqproxy/tls/server.key - -# Client — transparent capture + MITM. Requires --tproxy and a signing CA. -sudo ./target/release/mqproxy client \ - --server 127.0.0.1:4433 --token secret123 \ +sudo ./target/release/mqproxy client --server :4433 --token secret123 \ --tproxy 127.0.0.1:12443 --setup-redirect \ - --mitm \ - --ca-cert /etc/mqproxy/mitm-ca.crt \ - --ca-key /etc/mqproxy/mitm-ca.key \ - --ignore-host signal.org \ - --ignore-hosts .apple.com,.icloud.com - -# With the CA trusted by the device, browsing TCP :443 is now terminated, -# inspected as H2, and carried request-by-request over the MPQUIC tunnel. -curl https://example.com/ -``` - -**Requirements (fail-closed):** `--mitm` requires `--tproxy` (transparent capture is the only MITM ingress) **and** `--ca-cert ` + `--ca-key `. Any of these missing, a CA that cannot be loaded, or an invalid ignore entry is a startup error (exit code 2) with a message naming the problem; mqproxy never silently falls back to opaque passthrough because of a configuration mistake. `--mitm` is client-only (the server subcommand rejects it; a `[Mitm]` section in a server config is skipped with a warning). - -**What is relayed opaquely.** MITM is applied only when everything is positively confirmed. Everything else is relayed **opaquely** — byte for byte, so the client sees the origin's real certificate — and keeps working instead of being dropped: - -- the client does not offer `h2` in ALPN (this includes `curl --http1.1`, most non-browser clients, and **WebSocket**, which arrives as HTTP/1.1); -- the traffic is not TLS, or there is no SNI, an invalid SNI, or an IP-literal SNI; -- the host is in the ignore list, or outside the scope of a `nameConstraints` CA; -- the client's TLS settings are incompatible with the forged certificate; -- the ClientHello takes longer than 5 seconds, is larger than 8 KiB, or the client closes before it is complete; -- 256 connections are already in MITM (extra connections degrade to opaque relay). - -**Ignore-hosts.** `--ignore-host ` (repeatable) and `--ignore-hosts ` (comma-separated, no spaces) list hosts to relay opaquely — use this for cert-pinned apps that would reject a forged leaf. Matching is on the lowercased SNI without a trailing dot: `example.com` matches that host **only**; `.example.com` matches **strict subdomains only** (`www.example.com`, `a.b.example.com`, but not `example.com`). To exclude a site and its subdomains, list both. CLI and config entries are combined. An entry that is not a valid host name (an IP address, a wildcard, characters outside letters, digits, `-` and `.`, an empty `--ignore-host ""`, …) is a **startup error** (exit code 2) naming the entry. (Empty items in a comma-separated `--ignore-hosts a,,b` are skipped.) - -**Config** (`[Mitm]`, client-only — see [Configuration file](#configuration-file)): - -```ini -[Mitm] -Enabled = true -CACert = /etc/mqproxy/mitm-ca.crt -CAKey = /etc/mqproxy/mitm-ca.key -IgnoreHosts = .apple.com -IgnoreHosts = signal.org -``` - -`IgnoreHosts` is a repeatable key with **one host per line** (not a comma-separated list), like `[Multipath] Path`. CLI `--ignore-host(s)` and these entries are combined. - -**Block UDP/443.** mqproxy MITMs TCP only. A browser that learns of HTTP/3 (an `Alt-Svc` header or a cached HTTPS DNS record) may switch a site to QUIC over UDP/443 and bypass the proxy entirely. mqproxy strips `alt-svc` from the responses it relays, but you should also block UDP/443 on the capture path so browsers fall back to TCP/TLS. On a router: - -```bash -nft add table inet mqproxy_block -nft add chain inet mqproxy_block forward '{ type filter hook forward priority 0; }' -nft add rule inet mqproxy_block forward udp dport 443 reject -``` - -(For the local machine's own browsers, hook `output` instead of `forward`.) - -**Request handling and limits:** - -- **One host per connection.** A request whose `:authority` differs from the connection's SNI gets `421 Misdirected Request`; the browser retries on a connection of its own. -- **Header limits** (same on both ends of the gateway tunnel): a header field (name + value) up to 8 KiB, a header section up to 32 KiB, up to 256 fields, a request path with query up to about 8 KiB. A browser request head over the limits gets `431` (or a stream reset) from the h2 layer. Large cookies, long URLs and big CSP headers within these limits pass. -- **HTTP/2:** up to 128 concurrent streams per connection; 256 KiB receive window per stream, 512 KiB per connection. -- **Connections:** at most 256 in MITM; a connection with no open streams is closed after 60 seconds idle, and a peer silent for 60 seconds while streams are open is pinged and closed after 90 seconds of silence (long-lived responses such as server-sent events are fine). -- Methods keep their case (up to 32 bytes); `CONNECT` and asterisk-form requests get `400`. A browser's split `cookie` fields are joined; `Cookie` and `Authorization` are forwarded; `alt-svc` is removed from responses. - -**Metrics.** With `--metrics-interval`, the client also prints a `mq.mitm` line on every tick and at shutdown (nothing while every counter is zero): - -``` -mq.mitm conns= streams= mitm= opaque_not_tls= opaque_no_sni= opaque_bad_sni= opaque_no_h2= opaque_ignored= opaque_ca_scope= opaque_tls_incompat= opaque_timeout= opaque_too_large= opaque_eof= opaque_capacity= tls_fail= h2_fail= dead= leaf_hit= leaf_miss= reqs= rejects= -``` - -`conns` and `streams` are what is open now; the rest are cumulative. Each `opaque_*` counter counts connections relayed opaquely for one reason above; `leaf_hit`/`leaf_miss` are forged-certificate cache hits and misses; `reqs` counts every h2 request received, and `rejects` counts those refused before a tunnel request was opened: an `x-mq-error` or 421 answer from the request mapping, an unavailable or refused tunnel, an `RST_STREAM` for a malformed request, or a `REFUSED_STREAM` past the per-connection stream limit. - -**Security posture:** - -- **Untrusted browser headers.** All browser-supplied `X-Mq-*` headers are stripped — they are never interpreted as proxy controls; the client injects its own `x-mq-auth` / `x-mq-forward-cookie`. `Cookie` and `Authorization` are forwarded so normal browsing works. -- **Fail-closed & bounded.** A misconfigured MITM is a startup error, never a silent passthrough. The ClientHello is read with a size cap and a deadline, and the limits above bound the new ingress. -- **Leaf certificates** are forged per SNI, live 24 hours, are signed by your CA and are cached in memory. The CA key stays in memory while mqproxy runs. -- **HTTP/2 only.** Other protocols are relayed opaquely, not inspected. - -> HTTP/3 uses h3wire over raw xquic streams. Receive credit follows consumption, with bounded adapter queues for slow consumers. - -### Resilience: reconnect and keepalive - -The client automatically re-establishes its MPQUIC tunnel after a transient loss. On disconnect it enters an exponential back-off retry loop (capped at `--reconnect-max-backoff`, jittered to avoid thundering herds) and retries indefinitely until the tunnel comes back — with no process restart and without touching the local SOCKS5, HTTP CONNECT, or gateway listeners. An idle tunnel is kept alive by periodic QUIC PINGs (`--keepalive-idle`). Reconnect is enabled by default and can be disabled with `--no-reconnect`. - -> **Limitation:** flows that are in flight at the moment of a total connection loss are failed — they are not resurrected after recovery. New flows opened after the tunnel is back work automatically. + --mitm --ca-cert mitm-ca.crt --ca-key mitm-ca.key \ + --ignore-host signal.org --ignore-hosts .apple.com,.icloud.com +``` + +- **Fail-closed:** if `--tproxy`, `--ca-cert` or `--ca-key` is missing, or the CA or an ignore entry is invalid, mqproxy exits with code 2 at startup. It never quietly falls back to passthrough. +- **Relayed opaquely** (origin's real cert, no inspection) are: clients without `h2` in ALPN (including HTTP/1.1 and WebSocket), non-TLS traffic, missing/invalid/IP SNI, ignored hosts, hosts outside the CA's `nameConstraints`, TLS settings incompatible with the forged cert, a ClientHello over 8 KiB or slower than 5 s, and connections past 256 concurrent. +- **Ignore hosts** (for cert-pinned apps): `example.com` matches that host only, and `.example.com` matches only its subdomains. List both to cover a site and its subdomains. +- **Block UDP/443** on the capture path, or browsers may switch to HTTP/3 and bypass the proxy. mqproxy already strips `alt-svc` from responses. + ```bash + nft add table inet mqproxy_block + nft add chain inet mqproxy_block forward '{ type filter hook forward priority 0; }' + nft add rule inet mqproxy_block forward udp dport 443 reject # use "output" for local browsers + ``` +- **Requests:** a request whose `:authority` doesn't match the SNI gets 421. Header limits are 8 KiB per field, 32 KiB per header section, and 256 fields; a request over the limits gets 431 or a stream reset. HTTP/2 allows 128 concurrent streams per connection. Browser-supplied `X-Mq-*` headers are always stripped; `Cookie` and `Authorization` are forwarded. +- **Leaf certs** are valid for 24 h and cached in memory, keyed by SNI. ## Configuration file -Instead of a long command line, either subcommand can read its settings from a WireGuard-style INI file with `--config `. This is the intended way to run mqproxy as a managed service (one config file per instance) and keeps the shared token out of `ps` / `/proc//cmdline`. +`--config ` reads an INI file, which keeps the token off the command line. Values are resolved in the order defaults < file < CLI flags. ```ini -# /etc/mqproxy/edge1.conf (chmod 0600 — keeps the token private) +# /etc/mqproxy/edge1.conf (chmod 0600; mqproxy warns if group/world-readable) [Interface] Listen = 0.0.0.0:4433 MaxConns = 64 @@ -375,244 +161,61 @@ CC = bbr Scheduler = minrtt ``` -```bash -mqproxy server --config /etc/mqproxy/edge1.conf -``` - -- **Precedence:** built-in defaults < config file < CLI flags. A flag passed alongside `--config` overrides the file, so you can pin steady state in the file and override transiently on the command line (e.g. add `--qlog /tmp/dbg` for one debug run). -- **Format:** sectioned INI, CamelCase keys (case-insensitive), `#` and `;` comments **on their own line** (an inline `# …` after a value is read as part of the value, not stripped), booleans are `true`/`yes`/`1`. `Path` may be repeated for multipath. Unknown keys and bad values warn and are skipped (the default stands); a missing `--config` file is a fatal error. -- **Secrets:** the token lives in `[Auth] Key`. mqproxy warns at startup if the file is group/world-readable — `chmod 0600` it. - -**Key reference** — config keys map to the CLI flags in the [Options reference](#options-reference): - | Section | Server keys | Client keys | |---|---|---| | `[Interface]` | `Listen`, `MaxConns` | `Reconnect`, `KeepaliveIdle`, `ReconnectMaxBackoff` | | `[Server]` | — | `Address`, `ClientId` | | `[TLS]` | `Cert`, `Key` | — | -| `[Auth]` | `Key` (token) | `Key` (token) | -| `[Multipath]` | `CC`, `Scheduler` | `CC`, `Scheduler`, `Path` (repeatable) | +| `[Auth]` | `Key` | `Key` | +| `[Multipath]` | `CC`, `Scheduler` | `CC`, `Scheduler`, `Path`* | | `[Ingress]` | — | `Socks5`, `HttpConnect`, `Gateway`, `TProxy`, `Mode`, `Fwmark`, `Table`, `Dport`, `SetupRedirect`, `SkipUid` | -| `[Gateway]` | `Enabled`, `Masquerade`, `OriginCA`, `CacheMaxBytes` | — | -| `[Mitm]` | — | `Enabled`, `CACert`, `CAKey`, `IgnoreHosts` (repeatable) | +| `[Gateway]` | `Enabled`, `Masquerade`, `OriginCA` | — | +| `[Mitm]` | — | `Enabled`, `CACert`, `CAKey`, `IgnoreHosts`* | | `[UDP]` | `Enabled`, `IdleTimeout` | — | | `[Metrics]` | `Interval`, `PerRequest` | `Interval` | | `[Log]` | `QLog` | `QLog` | -See [`server.conf.example`](server.conf.example) and [`client.conf.example`](client.conf.example) for complete starting points. - -## Install from a `.deb` - -Prebuilt `amd64` and `arm64` packages are attached to each [GitHub Release](https://github.com/mp0rta/mqproxy/releases). Rust packages statically link xquic, BoringSSL and the Rust dependencies. Their system runtime dependencies are recorded in the `.deb` metadata; libevent, libcurl and nghttp2 are no longer required. - -```bash -# pick the .deb for your architecture from the latest release -sudo apt install ./mqproxy__amd64.deb # or _arm64.deb -``` - -The package installs `/usr/bin/mqproxy`, the `mqproxy-server@` / `mqproxy-client@` systemd template units, and creates the unprivileged `mqproxy` user plus `/etc/mqproxy` (via the bundled `sysusers.d`/`tmpfiles.d`, applied in the package's `postinst`). Continue from the per-instance config steps in [Install as a systemd service](#install-as-a-systemd-service) below — the configure/enable steps are identical; only the build-from-source steps are skipped. - -## Install as a systemd service - -mqproxy ships hardened, unprivileged systemd template units. Install a release -package, or build a native package locally (amd64 or arm64): - -```bash -sudo apt-get install -y dpkg-dev python3 -python3 packaging/build.py -sudo apt install ./target/dist/mqproxy_*.deb -``` +\* repeatable, one value per line. Keys are case-insensitive. Comments (`#` or `;`) must sit on their own line. Booleans accept `true`, `yes` or `1`. An unknown key or bad value prints a warning and is skipped; a missing config file is fatal. Full examples: [`server.conf.example`](server.conf.example), [`client.conf.example`](client.conf.example). -The build also creates a tar archive with the same `/usr` layout. `.deb` -installation applies the bundled sysusers/tmpfiles rules automatically. +## Run as a service -Drop a per-instance config and lock it down (the service reads it as user `mqproxy`): +The package installs `/usr/bin/mqproxy`, hardened `mqproxy-server@` / `mqproxy-client@` systemd templates, a `mqproxy` system user, and `/etc/mqproxy`. ```bash -sudoedit /etc/mqproxy/edge1.conf # see the [server config](#configuration-file) above -sudo chown mqproxy:mqproxy /etc/mqproxy/edge1.conf -sudo chmod 0600 /etc/mqproxy/edge1.conf # 0600 keeps the token-permission warning quiet -``` - -Enable and start the instance — the part after `@` is the config basename: +sudo apt install ./mqproxy__amd64.deb # or build one: python3 packaging/build.py → target/dist/ -```bash -sudo systemctl enable --now mqproxy-server@edge1 # → /etc/mqproxy/edge1.conf -journalctl -u mqproxy-server@edge1 -f # logs +sudoedit /etc/mqproxy/edge1.conf +sudo chown mqproxy:mqproxy /etc/mqproxy/edge1.conf && sudo chmod 0600 /etc/mqproxy/edge1.conf +sudo systemctl enable --now mqproxy-server@edge1 # instance name = config basename +journalctl -u mqproxy-server@edge1 -f ``` -The client side uses `mqproxy-client@` the same way (`/etc/mqproxy/.conf`). Instance names use 1–64 ASCII letters, digits, dots, underscores or dashes; units pass the name as `--instance-id`, which appends `instance_id=` to logs. Use separate QLog directories when running multiple instances; the label does not change filenames. - -**Notes:** -- **qlog:** to capture xquic qlog, set `[Log] QLog = /var/log/mqproxy` in the config. The unit's `LogsDirectory=` creates `/var/log/mqproxy`; `ProtectSystem=strict` blocks writing qlog anywhere else (except `PrivateTmp`). qlog stays off unless `QLog` is set. -- **Privileged ports:** the default `4433` needs no capabilities. To listen on a port below 1024, add `AmbientCapabilities=CAP_NET_BIND_SERVICE` via `sudo systemctl edit mqproxy-server@edge1`. -- **TLS cert:** set `[TLS] Cert`/`Key` to paths the service can read (e.g. under `/etc/mqproxy`); the built-in test cert is not present in a packaged install. - -## Options reference - -Both binaries take a small set of **common flags** (connection, TLS, paths, metrics) that apply no matter which mode you run. Each operating mode then adds a few mode-specific flags — and crucially, a mode is *selected on the client* by which ingress flag you pass (`--socks5`, `--http-connect`, `--gateway`). The server simply offers all enabled capabilities; the client decides what to use. - -The tables below are split: **common flags first**, then one block per mode. Within each mode, server- and client-side flags are listed separately. - -### Common flags (all modes) - -`--instance-id ` optionally labels process logs (1–64 ASCII letters, digits, dots, underscores or dashes). It does not change protocol identity or qlog filenames. - -**Server** — `mqproxy server …` - -| Flag | Description | -|---|---| -| `--listen ` | **(required)** UDP address to accept MPQUIC connections on | -| `--token ` | **(required)** Shared auth token clients must present | -| `--cert ` / `--key ` | **(required)** TLS cert/key (PEM). The repo ships a self-signed test cert under `tests/certs` for local use. | -| `--max-conns ` | Cap on simultaneous QUIC connections (default 16; `0` = unlimited). At the cap, a new connection evicts the oldest one that has not authenticated yet (`AUTH`, or a gateway request with a valid token); when every connection is authenticated, new ones are refused (`CONNECTION_REFUSED`) — a pre-auth DoS guard. | -| `--cc ` | Congestion control: `bbr` (default) \| `bbr2` \| `cubic` | -| `--scheduler ` | Multipath scheduler: `minrtt` (default) \| `backup` \| `wlb` | -| `--qlog ` | Write xquic qlog to `/server.qlog` | -| `--metrics-interval ` | Periodically log per-path stats (`mq.conn` / `mq.path` logfmt lines) every ``s (must be > 0; omit to disable). Logs the most-recently-accepted TCP and gateway conn. | - -**Client** — `mqproxy client …` - -| Flag | Description | -|---|---| -| `--server ` | **(required)** UDP address of the mqproxy server | -| `--token ` | **(required)** Shared auth token | -| `--path ` | Local IP to bind a path to — **repeat for multipath aggregation** (e.g. WiFi + LTE) | -| `--client-id ` | Client identifier sent at auth | -| `--cc ` | Congestion control: `bbr` (default) \| `bbr2` \| `cubic` | -| `--scheduler ` | Multipath scheduler: `minrtt` (default) \| `backup` \| `wlb` | -| `--qlog ` | Write xquic qlog to `/client.qlog` | -| `--reconnect` / `--no-reconnect` | Auto-reconnect on tunnel loss (default: enabled) | -| `--reconnect-max-backoff ` | Cap on exponential reconnect backoff in seconds (default 30; must be > 0) | -| `--keepalive-idle ` | Send QUIC PINGs when idle for this many seconds (default 30; 0 = disable; values <15 have no additional effect since xquic's PING cadence is ~15 s) | -| `--metrics-interval ` | Periodically log per-path stats (`mq.conn` / `mq.path` logfmt lines) every ``s (must be > 0; omit to disable). Logs the proxy conn (and the gateway conn when `--gateway` is set). | - -> At least one client ingress flag (`--socks5`, `--http-connect`, or `--gateway`) is what actually puts the client to work — see the per-mode blocks below. - -### TCP Proxy mode - -*1 TCP flow → 1 MPQUIC bidi stream. TLS stays end-to-end between app and origin (no termination).* - -**Server:** no mode-specific flags — TCP proxying is always available. - -**Client** - -| Flag | Description | -|---|---| -| `--socks5 ` | Local SOCKS5 ingress (TCP CONNECT). Also serves UDP ASSOCIATE — see UDP Relay mode. | -| `--http-connect ` | Local HTTP CONNECT ingress (use via `curl --proxy http:// …`) | - -### HTTP Gateway mode - -*1 HTTP request → 1 H3 stream over MPQUIC; the server executes the delegated request against the origin. Enabled on the server by default.* - -**Server** - -| Flag | Description | -|---|---| -| `--no-gateway` | **Disables HTTP Gateway mode for this server** (it is enabled by default). The TCP-proxy core keeps running; only the gateway origin bridge is turned off, so a client's `--gateway` ingress has nothing to talk to. | -| `--origin-ca ` | Extra CA bundle for origin TLS verification (private CAs / tests); verification itself is always on | -| `--request-metrics` | Emit one `mq.req` logfmt line per gateway request (method/status/target/ttfb/origin_protocol/cache/…). Opt-in; off by default. Independent of `--metrics-interval`. | -| `--cache-max-bytes ` | Accepted with a warning and ignored; the origin response cache has been removed. | -| `--masquerade` | Answer **unauthenticated** gateway requests with a bare `404` (no `X-Mq-*` headers), so probes/scanners see a generic HTTP/3 server instead of a fingerprintable `403 auth-failed`. Authenticated requests are unaffected. Gateway-only; off by default; recommended for internet-exposed servers. | - -**Client** - -| Flag | Description | -|---|---| -| `--gateway ` | Local TCP address for the HTTP gateway fetch API (`POST /_mqproxy/fetch`). Works with or without `--socks5`. | - -### UDP Relay mode - -*1 UDP session → MPQUIC DATAGRAMs. Exposed on the same `--socks5` listener via SOCKS5 UDP ASSOCIATE; rides the `mqproxy-tcp/1` connection (a `--gateway`-only client does not get it).* - -**Server** - -| Flag | Description | -|---|---| -| `--no-udp` | **Disables UDP Relay mode entirely for this server** — the capability is not advertised at auth (clients see it as unavailable) and any session that is still attempted is refused. There is no client-side override. | -| `--udp-idle-timeout ` | UDP session idle timeout (default 60); the effective value is `min(client request, this)` | - -**Client** - -| Flag | Description | -|---|---| -| `--socks5 ` | Same listener as TCP Proxy mode — any SOCKS5 client speaking UDP ASSOCIATE uses it. No separate flag needed. | - -### Transparent Capture mode - -*Kernel-redirected TCP → opaque MPQUIC stream. No app config needed. Linux + IPv4 only. TLS is preserved end-to-end by default; add `--mitm` to terminate and inspect it — see [TLS MITM mode](#tls-mitm-mode).* +- The instance name is also passed as `--instance-id`, so it shows up in the logs. +- qlog can only be written to `/var/log/mqproxy` (`[Log] QLog = /var/log/mqproxy`). +- Listening on a port below 1024 needs `AmbientCapabilities=CAP_NET_BIND_SERVICE`, added via `systemctl edit`. -**Server:** no mode-specific flags — transparent capture is a client-side ingress mechanism; the server handles the resulting TCP streams exactly like SOCKS5-originated ones. +## Operations -**Client** - -| Flag | Description | -|---|---| -| `--tproxy ` | Local TCP address for the transparent capture ingress (redirect or tproxy mode). Enables transparent capture; at least one of `--socks5`, `--http-connect`, `--gateway`, or `--tproxy` is required. | -| `--tproxy-mode redirect\|tproxy` | Kernel capture mechanism (default: `redirect`). `redirect` — `nft nat OUTPUT` REDIRECT target; captures the local machine's own outbound TCP; no `IP_TRANSPARENT` on the socket. `tproxy` — `nft mangle PREROUTING` TPROXY target; captures forwarded LAN traffic on a router/gateway (standard Linux TPROXY; works with any policy-routing stack); needs `CAP_NET_ADMIN` for `IP_TRANSPARENT`. | -| `--tproxy-fwmark ` | Packet mark for policy routing in tproxy mode (default: 1; tproxy mode only). | -| `--tproxy-table ` | IP routing table for tproxy reply routing (default: 100; tproxy mode only). | -| `--tproxy-dport ` | TCP destination port the `--setup-redirect` rule captures (default: 443). | -| `--setup-redirect` | Install `nft`/`ip rule` firewall rules on start and remove them on exit (requires root or `CAP_NET_ADMIN`; off by default). For single-host self-contained use; leave OFF on a router/gateway and let the router stack manage the rules. | -| `--tproxy-uid ` | UID whose outbound traffic is exempt from redirection (default: `geteuid()` of the process). Used for loop avoidance — mqproxy's own tunnel connections are not re-captured into itself. | - -### TLS MITM mode (client-only) - -*Terminate captured browser TLS with a forged per-host leaf, speak HTTP/2, and map each request onto the Gateway tunnel. Requires `--tproxy`; HTTP/2 only; off unless `--mitm`. See [TLS MITM mode](#tls-mitm-mode) for the trust model and security posture.* - -**Server:** no mode-specific flags — MITM is a client-side ingress mode; the resulting requests reach the server as ordinary Gateway requests. - -**Client** - -| Flag | Description | -|---|---| -| `--mitm` | Terminate TLS on the transparent-capture path (forge a leaf per SNI, speak h2, feed the Gateway tunnel) instead of relaying opaquely. **Requires `--tproxy`, `--ca-cert`, and `--ca-key`**; any of these missing is a fail-closed startup error (exit 2). Flows that cannot be MITM'd are relayed opaquely — see [TLS MITM mode](#tls-mitm-mode). | -| `--ca-cert ` | Signing CA certificate (PEM). The operator's CA must be trusted by the device. A CA with `nameConstraints` is supported; hosts outside its scope are relayed opaquely. | -| `--ca-key ` | Signing CA private key: **unencrypted PKCS#8** PEM (PKCS#1/SEC1 are rejected with the `openssl pkcs8 -topk8 -nocrypt` conversion hint). Must be owned by the running user, not group/other accessible, and not a symlink. | -| `--ignore-host ` | Host to relay **opaquely** (bypass MITM — the origin's real cert reaches the client; for cert-pinned apps). **Repeatable.** `example.com` matches that host only; `.example.com` matches strict subdomains only. An invalid entry is a startup error naming it. | -| `--ignore-hosts ` | Same as `--ignore-host` but a comma-separated list (no spaces). CLI and `[Mitm] IgnoreHosts` config entries combine. | - -> The test certificate under `tests/certs` is for local testing only. For real deployments, pass your own `--cert`/`--key` and a strong `--token`. +- **Reconnect:** if the tunnel drops, the client reconnects with jittered exponential backoff (`--reconnect-max-backoff`, default 30 s) and keeps its listeners up. While idle, QUIC PINGs keep the tunnel alive (`--keepalive-idle`). Flows that are in flight when the connection is lost fail; new flows work again once the tunnel is back. +- **Connection cap:** `--max-conns` (default 16) limits the server's QUIC connections. At the cap, the oldest unauthenticated connection is evicted to make room. +- **Metrics:** `--metrics-interval ` logs per-path `mq.conn` / `mq.path` lines; with `--mitm`, the client also logs `mq.mitm` counters. `--request-metrics` logs one `mq.req` line per gateway request. +- **qlog:** `--qlog ` writes xquic qlog. Per-path byte counts there show whether a flow is really split across paths. +- **Tuning:** `--cc bbr|bbr2|cubic` and `--scheduler minrtt|backup|wlb`. ## Testing -After building, run the bundled test suite: - ```bash cargo test --workspace --locked cargo clippy --workspace --all-targets --locked -- -D warnings cargo build --release --locked -p mqproxy --bins --examples bash tests/test_cli_help.sh target/release/mqproxy -bash tests/integration/e2e_udp.sh +bash tests/integration/e2e_udp.sh # also e2e_{gateway,multipath,tproxy,mitm_h2,...}.sh ``` -It covers wire framing, the relay/flow state machine, ingress parsing, the gateway request path, and the TLS MITM crypto core, alongside end-to-end scripts for multipath aggregation, the full gateway chain, UDP relay, and transparent capture. Tests that need root or `NET_ADMIN` (the multipath and transparent-capture end-to-end runs) skip automatically when run unprivileged. - -## Observability - -Pass `--qlog ` to either side to emit xquic qlog. Per-path byte counts confirm that within-stream multipath is actually splitting a flow across paths — the key signal that aggregation is working. (xquic must be built with `XQC_ENABLE_EVENT_LOG=ON`, which `scripts/build-xquic.sh` does.) - -## Security Model - -mqproxy uses a **trusted proxy** model: mqproxy-client, mqproxy-server, and the MPQUIC connection between them are trusted. In TCP Proxy Mode and Transparent Capture mode (without `--mitm`), application↔origin TLS is preserved end-to-end (mqproxy never sees plaintext — it relays raw TLS bytes opaquely). Applications with certificate pinning continue to work. The HTTP Request Execution Gateway is an explicit delegation model — the client delegates HTTP request execution to a trusted gateway that establishes (and always verifies) the origin TLS — not a transparent MITM. Gateway requests are authenticated individually (`X-Mq-Auth`, per-request); `Authorization` is reserved for the origin and forwarded, while `Cookie` and `X-Mq-*` never leave the gateway. - -**TLS MITM ingress** (`--mitm`, opt-in) is an **operator-controlled / consenting-endpoint** model for managed devices where the operator's CA is installed locally — a corporate-proxy or personal-VPN posture, not a transparent attack on third parties. The client forges per-host leaves from that CA, terminates the browser's TLS as HTTP/2, and maps each request onto the Gateway tunnel. Its trust assumptions: the **CA private key is the anchor** (an unencrypted PKCS#8 file owned by the running user, not group/other accessible, not a symlink; it stays in memory while mqproxy runs); a CA can be limited to your own domains with an X.509 `nameConstraints` extension; browser-supplied `X-Mq-*` headers are **always stripped** (never interpreted as controls — the client injects its own `x-mq-auth`); and the feature is **fail-closed** (misconfiguration is a startup error, never silent passthrough, with a bounded ClientHello read and header, stream and connection limits). Anything that is not positively an HTTP/2 TLS client for a valid host name is relayed opaquely and never inspected. Cert-pinned hosts can be excluded with `--ignore-host(s)`, which relays them opaquely so the origin's real certificate reaches the client. +End-to-end scripts that need root or `NET_ADMIN` skip themselves when run unprivileged. ## License -Apache-2.0. See [LICENSE](LICENSE). - -## Disclaimer - -mqproxy is licensed under the Apache License 2.0 and is provided "AS IS", without warranties or conditions of any kind. - -Use of mqproxy is at your own risk. Users are solely responsible for validating its suitability, security, and operational safety, especially in production or commercial environments. - -## Acknowledgments +Apache-2.0 (see [LICENSE](LICENSE)). Provided "AS IS", without warranty; you are responsible for validating it for your use. -- [XQUIC](https://github.com/alibaba/xquic) (Alibaba) — the QUIC/MPQUIC transport, via the [mp0rta fork](https://github.com/mp0rta/xquic). -- [BoringSSL](https://boringssl.googlesource.com/boringssl) — TLS backend. -- [h3wire](https://crates.io/crates/h3wire) — HTTP/3 framing and QPACK. -- [hyper](https://hyper.rs/), h2 and [rustls](https://rustls.dev/) — origin HTTP and MITM TLS/HTTP/2. -- All bundled dependency licenses are included in release artifacts. +Built on [XQUIC](https://github.com/alibaba/xquic) ([mp0rta fork](https://github.com/mp0rta/xquic)), [BoringSSL](https://boringssl.googlesource.com/boringssl), [h3wire](https://crates.io/crates/h3wire), [hyper](https://hyper.rs/), h2 and [rustls](https://rustls.dev/). Bundled dependency licenses ship with release artifacts. diff --git a/crates/mq-http/src/h1.rs b/crates/mq-http/src/h1.rs index 3043678e..fc57636e 100644 --- a/crates/mq-http/src/h1.rs +++ b/crates/mq-http/src/h1.rs @@ -1,12 +1,12 @@ -//! HTTP/1.1 request head parser (spec §2.1), port of `src/gateway/mq_http1.c`. +//! HTTP/1.1 request head parser (spec §2.1). pub const HEAD_MAX: usize = 16 * 1024; pub const MAX_HEADERS: usize = 64; -/// Longest method (bytes) of the fetch listener's own request line only -/// (C `char[16]` minus NUL); the shared method bound is `limits::METHOD_MAX`. +/// Longest method (bytes) of the fetch listener's own request line only; +/// the shared method bound is `limits::METHOD_MAX`. pub const METHOD_MAX: usize = 15; -/// Longest request-target of the fetch listener's own request line only -/// (C `char[1024]` minus NUL); the shared bound is `limits::TARGET_PATH_MAX`. +/// Longest request-target of the fetch listener's own request line only; +/// the shared bound is `limits::TARGET_PATH_MAX`. pub const PATH_MAX: usize = 1023; /// One header line; `value` is OWS-trimmed. @@ -61,7 +61,7 @@ fn trim_ows(mut v: &[u8]) -> &[u8] { v } -/// Strict decimal in `0..=i64::MAX` (leading zeros accepted, as C). +/// Strict decimal in `0..=i64::MAX` (leading zeros accepted). pub fn parse_content_length(v: &[u8]) -> Option { if v.is_empty() { return None; @@ -86,7 +86,7 @@ fn te_lists_chunked(v: &[u8]) -> bool { } /// Parse a request head from the start of `buf` (spec §2.1). A head whose -/// terminator lies beyond `HEAD_MAX` is `TooLarge` (C answered Bad). +/// terminator lies beyond `HEAD_MAX` is `TooLarge`. pub fn parse_head(buf: &[u8]) -> Progress<'_> { let Some(p) = find(buf, b"\r\n\r\n") else { return if buf.len() >= HEAD_MAX { @@ -122,7 +122,7 @@ fn parse_complete(head: &[u8]) -> Option> { let rest = &line[m_end + 1..]; let t_end = rest.iter().position(|&c| c == b' ')?; let target = &rest[..t_end]; - // < 1024 bytes, origin-form, no control bytes / DEL (C parity; NUL would truncate). + // < 1024 bytes, origin-form, no control bytes / DEL. if target.first() != Some(&b'/') || target.len() > PATH_MAX { return None; } @@ -178,7 +178,7 @@ fn parse_complete(head: &[u8]) -> Option> { }) } -// ---- serializer (spec §2.2), port of the `mq_http1_write_*` helpers ---- +// ---- serializer (spec §2.2) ---- /// `HTTP/1.1 \r\n`; the fetch client passes an empty reason. pub fn write_status(out: &mut Vec, code: u16, reason: &str) { @@ -219,7 +219,7 @@ pub fn chunk_end(out: &mut Vec) { } /// Listener/reject reply: status, `Connection: close`, `Content-Length: 0`, -/// optional `X-Mq-Error`, blank line (C `gw_build_error`). +/// optional `X-Mq-Error`, blank line. pub fn error_reply(code: u16, reason: &str, xmq: Option<&str>) -> Vec { let mut o = Vec::with_capacity(96); write_status(&mut o, code, reason); @@ -315,7 +315,7 @@ mod tests { b[..5].copy_from_slice(b"GET /"); assert_eq!(parse_head(&b), Progress::TooLarge); assert_eq!(parse_head(&b[..HEAD_MAX - 1]), Progress::Need); - b.push(b'a'); // C's 17 KiB case + b.push(b'a'); assert_eq!(parse_head(&b), Progress::TooLarge); } @@ -362,7 +362,7 @@ mod tests { b.resize(5 + 1100, b'a'); b.extend_from_slice(b" HTTP/1.1\r\n\r\n"); b - }); // C test_path_too_long + }); } #[test] diff --git a/crates/mq-http/src/headers.rs b/crates/mq-http/src/headers.rs index 08779877..a2e027d8 100644 --- a/crates/mq-http/src/headers.rs +++ b/crates/mq-http/src/headers.rs @@ -1,11 +1,11 @@ -//! Gateway header rules (spec §2.3), port of `src/gateway/mq_gw_headers.c`. +//! Gateway header rules (spec §2.3). use crate::h1::is_tchar; use crate::limits::{METHOD_MAX, TARGET_PATH_MAX}; /// Longest `X-Mq-Cache` TTL in seconds (1 year). pub const CACHE_TTL_MAX: u32 = 31_536_000; -/// Longest target authority, both intakes (C `char authority[256]`). +/// Longest target authority, both intakes. pub const AUTHORITY_MAX: usize = 255; /// Parsed `X-Mq-Target` (bytes: any non-control, non-DEL, non-space byte round-trips). @@ -82,7 +82,7 @@ pub fn parse_target(s: &[u8]) -> Option { .map(|p| p + scan_from) { let port = &auth[pc + 1..]; - // No numeric range check (as C). + // No numeric range check. if port.is_empty() || !port.iter().all(u8::is_ascii_digit) || pc == 0 { return None; } @@ -328,7 +328,7 @@ mod tests { t(s).unwrap_or_else(|| panic!("expected Some for {s:?}")) } - // ---- parse_target (test_gw_headers.c) ---- + // ---- parse_target ---- #[test] fn target_https_full() { let x = ok("https://example.com/foo/bar?x=1&y=2"); @@ -415,7 +415,7 @@ mod tests { assert!(t("https://h:/x").is_none()); assert!(t("https://:80").is_none()); assert!(t("https://h:80:90").is_none()); - // no numeric range check, as C + // no numeric range check assert_eq!(ok("https://h:99999").authority, b"h:99999"); } #[test] diff --git a/crates/mq-http/src/metrics.rs b/crates/mq-http/src/metrics.rs index 3fc32f5b..4fa5de3b 100644 --- a/crates/mq-http/src/metrics.rs +++ b/crates/mq-http/src/metrics.rs @@ -1,8 +1,8 @@ -//! `mq.req` log-line formatter (spec §2.4), byte-for-byte as C `mq_gw_format_req_line`. +//! `mq.req` log-line formatter (spec §2.4). //! Works on bytes: no `String`, truncation is bytewise. use std::io::Write; -/// C's `char line[1024]` including the NUL: a line of this length or more is dropped. +/// A line of this length or more is dropped. pub const LINE_MAX: usize = 1024; const AUTHORITY_CAP: usize = 128; /// The quoted `path` cap; the server's call site also cuts the path here (spec §6.6). @@ -261,7 +261,7 @@ reset=\"client-reset\"" #[test] fn line_1024_dropped() { - // inflate `method` (uncapped, like C's %s) to hit the boundary. + // inflate `method` (uncapped) to hit the boundary. let l = base(); let len = fmt(&l).len(); let m1023 = vec![b'M'; 3 + 1023 - len]; diff --git a/crates/mq-integration/src/shard_pair.rs b/crates/mq-integration/src/shard_pair.rs index ba5dc464..f84d4369 100644 --- a/crates/mq-integration/src/shard_pair.rs +++ b/crates/mq-integration/src/shard_pair.rs @@ -86,8 +86,8 @@ pub fn server_role() -> Role { } } -/// The client settings the ports use: token "secret", reconnect off (as the -/// C fixtures), a 1 s maximum backoff for the reconnect cases. +/// The client settings the pair tests use: token "secret", reconnect off, a +/// 1 s maximum backoff for the reconnect cases. pub fn client_cfg() -> ClientConfig { ClientConfig { server: server_addr(), @@ -720,7 +720,7 @@ impl Pair { self.with_server(|n| n.tap().open_conns()) } - /// `Cx::close_conn` on the client side (C `mq_conn_close`). + /// `Cx::close_conn` on the client side. pub fn close_client_conn(&self, c: ConnId) { self.with_client(move |n| n.with_app(|_, cx| cx.close_conn(c))); } @@ -916,8 +916,8 @@ pub struct RawConn { /// spec §8.1: a client app below the real `Client` — it opens connections /// and streams on command, sends and receives raw bytes, and on each -/// connection's first stream sends the C `AUTH_REQUEST` (or, unauthenticated, -/// one `0x00` byte, as C's `preauth` case, and never authenticates). +/// connection's first stream sends the `AUTH_REQUEST` (or, unauthenticated, +/// one `0x00` byte, and never authenticates). /// Received bytes are read on every `StreamReadable` (the app-owned stream /// rule, spec §5.4). Commands run through `Node::with_app`. /// @@ -1043,7 +1043,7 @@ impl App for RawClient { let bytes = if k.authenticate { auth_request(&self.token) } else { - vec![0x00] // C `preauth_on_state`'s nudge: never a complete AUTH_REQUEST + vec![0x00] // a nudge that is never a complete AUTH_REQUEST }; let s = self.open_stream(cx, c); self.conns.get_mut(&c).expect("known").ctrl = Some(s); @@ -1107,7 +1107,7 @@ impl App for RawClient { // --- Wire bytes --- -/// The C `AUTH_REQUEST` (version 1, client id "client-1", features 0). +/// The `AUTH_REQUEST` (version 1, client id "client-1", features 0). pub fn auth_request(token: &[u8]) -> Vec { let mut b = [0u8; 512]; let n = AuthReq { @@ -1121,7 +1121,7 @@ pub fn auth_request(token: &[u8]) -> Vec { b[..n].to_vec() } -/// Stream type 0x01 then `CONNECT_TCP_REQUEST` to an IPv4 target (C `open_tcp_data_stream`). +/// Stream type 0x01 then `CONNECT_TCP_REQUEST` to an IPv4 target. pub fn connect_request(target: SocketAddr) -> Vec { let SocketAddr::V4(a) = target else { panic!("IPv4 target"); @@ -1190,7 +1190,7 @@ pub fn socks_udp(dst: SocketAddr, payload: &[u8]) -> Vec { b } -/// Deterministic payload (C bulk origin: byte i is `i & 0xff`). +/// Deterministic payload (byte i is `i & 0xff`). pub fn bulk(n: usize) -> Vec { (0..n).map(|i| i as u8).collect() } diff --git a/crates/mq-integration/tests/common/mod.rs b/crates/mq-integration/tests/common/mod.rs index 42a85fab..02bada31 100644 --- a/crates/mq-integration/tests/common/mod.rs +++ b/crates/mq-integration/tests/common/mod.rs @@ -35,7 +35,7 @@ pub fn wait(timeout: Duration, mut f: impl FnMut() -> bool) -> bool { } } -/// Stream type 0x01 then C `mq_encode_connect_tcp_req` for example.com:443. +/// Stream type 0x01 then a `CONNECT_TCP_REQUEST` for example.com:443. pub const CONNECT_REQ_C: &[u8] = &[ 0x01, 0x00, 0x03, 11, b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'c', b'o', b'm', 0x01, 0xBB, 0x00, diff --git a/crates/mq-integration/tests/driver_loopback.rs b/crates/mq-integration/tests/driver_loopback.rs index 7f9ba79c..f73d0f3c 100644 --- a/crates/mq-integration/tests/driver_loopback.rs +++ b/crates/mq-integration/tests/driver_loopback.rs @@ -390,7 +390,6 @@ fn accept_meta_has_local() { stop(h); } -/// Port of C `test_path_bind`. #[test] fn driver_path_bind() { let mut d = Driver::new(DriverConfig { diff --git a/crates/mq-integration/tests/driver_socks5_listener.rs b/crates/mq-integration/tests/driver_socks5_listener.rs index ba51967e..4becf6f4 100644 --- a/crates/mq-integration/tests/driver_socks5_listener.rs +++ b/crates/mq-integration/tests/driver_socks5_listener.rs @@ -1,15 +1,7 @@ -//! Port of C `tests/integration/test_socks5_listener.c` (spec §8.1, §6.1): -//! the real `Client`'s SOCKS5 and HTTP CONNECT listeners under the production -//! driver; the test is the ingress client, and the scripted transport stands -//! in for the server (AUTH answered by the rig, CONNECT answered here) where C -//! used a mock `tcp_open`. -//! -//! Ported: `socks5_happy`, `socks5_unsupported`, `socks5_malformed`, -//! `http_connect_smoke`, `socks5_pipelined_prebuf`, `http_pipelined_prebuf`, -//! `assoc_refused_no_udp`, `assoc_refused_unavail`. Not ported (SP2, UDP -//! ASSOCIATE served): `assoc_establish_free`, `assoc_tcp_close_teardown`, -//! `assoc_mixed_shutdown`, `assoc_no_close_after_err`, -//! `assoc_availability_sweep`, `assoc_dst_reclaim_churn`. +//! Spec §8.1, §6.1: the real `Client`'s SOCKS5 and HTTP CONNECT listeners +//! under the production driver; the test is the ingress client, and the +//! scripted transport stands in for the server (AUTH answered by the rig, +//! CONNECT answered here). Served UDP ASSOCIATE (SP2) is not covered here. #![forbid(unsafe_code)] mod common; @@ -137,8 +129,7 @@ fn associate_refused(r: &ClientRig, opened: usize) { assert_eq!(r.opened(), opened); } -/// C: a listener without the UDP boundary. Here: no tunnel at all, so UDP -/// availability is still unknown and the ASSOCIATE is accepted optimistically +/// No tunnel at all, so UDP availability is still unknown and the ASSOCIATE is accepted optimistically /// (SP2 spec §6.2) on a UDP socket bound on the control connection's local IP. #[test] fn assoc_refused_no_udp() { @@ -153,7 +144,7 @@ fn assoc_refused_no_udp() { r.stop(); } -/// C: UDP availability 0. Here: serving, the `AUTH_RESPONSE` without +/// Serving, the `AUTH_RESPONSE` without /// `MQ_FEAT_UDP_RELAY`. #[test] fn assoc_refused_unavail() { diff --git a/crates/mq-integration/tests/loop_e2e_single_path.rs b/crates/mq-integration/tests/loop_e2e_single_path.rs index 75d3ce0b..409dfd89 100644 --- a/crates/mq-integration/tests/loop_e2e_single_path.rs +++ b/crates/mq-integration/tests/loop_e2e_single_path.rs @@ -1,24 +1,22 @@ -//! Ports `tests/integration/test_e2e_single_path.c` onto the loopback harness -//! (spec §8.1 "Loopback"): the real `Server` and `Client` on real transports, +//! Single-path cases on the loopback harness (spec §8.1 "Loopback"): the real `Server` and `Client` on real transports, //! each on its own production driver thread, over loopback UDP. The test //! thread plays the origin (`TcpListener`) and the application (`TcpStream` //! through the client's SOCKS5 / HTTP CONNECT listener). //! -//! | C case | here | sizes / patterns | -//! |--------------------------------|-----------------------------|------------------| -//! | `test_socks5_download` | `socks5_download` | 200000 B, `i & 0xff`, then EOF | -//! | `test_socks5_echo` | `socks5_echo` | 4096 B, `i*31+7` | -//! | `test_http_echo` | `http_echo` | 4096 B, `i*17+3` | -//! | `test_socks5_pipelined_payload`| `socks5_pipelined_payload` | `EARLY-PIPELINED-BYTES` in the request write | -//! | `test_http_pipelined_payload` | `http_pipelined_payload` | `EARLY-HTTP-BYTES` in the head write | -//! | `test_concurrent_ingress` | `concurrent_ingress` | 1 SOCKS5 + 1 HTTP, 4096 B each, `i*31+7` / `(i*17+3)^0xa5` | -//! | `test_socks5_refused` | `socks5_refused` | dead port → REP 0x05, then close | -//! | `test_http_refused` | `http_refused` | dead port → `HTTP/1.1 502`, then close | +//! | test | sizes / patterns | +//! |-----------------------------|------------------| +//! | `socks5_download` | 200000 B, `i & 0xff`, then EOF | +//! | `socks5_echo` | 4096 B, `i*31+7` | +//! | `http_echo` | 4096 B, `i*17+3` | +//! | `socks5_pipelined_payload` | `EARLY-PIPELINED-BYTES` in the request write | +//! | `http_pipelined_payload` | `EARLY-HTTP-BYTES` in the head write | +//! | `concurrent_ingress` | 1 SOCKS5 + 1 HTTP, 4096 B each, `i*31+7` / `(i*17+3)^0xa5` | +//! | `socks5_refused` | dead port → REP 0x05, then close | +//! | `http_refused` | dead port → `HTTP/1.1 502`, then close | //! -//! `socks5_echo_ipv6_path` (no C counterpart in this file; C supports -//! `AF_INET6` QUIC paths) runs the tunnel over `::1` with IPv4 ingress; +//! `socks5_echo_ipv6_path` runs the tunnel over `::1` with IPv4 ingress; //! `socks5_echo_v6_wildcard_path_to_v4_server` runs it from a dual-stack -//! `[::]` client path to a `127.0.0.1` server (C's `--path ::`). +//! `[::]` client path (`--path ::`) to a `127.0.0.1` server. //! //! Each test ends with both drivers stopped through their handles, exit (0, 0). #![forbid(unsafe_code)] diff --git a/crates/mq-integration/tests/loop_engine_boot.rs b/crates/mq-integration/tests/loop_engine_boot.rs index 1196f7cb..1ee78d14 100644 --- a/crates/mq-integration/tests/loop_engine_boot.rs +++ b/crates/mq-integration/tests/loop_engine_boot.rs @@ -1,9 +1,7 @@ -//! Ports `tests/integration/test_engine_boot.c` onto the loopback harness -//! (spec §8.1 "Loopback"). The C test boots one client transport + runtime, -//! opens the primary UDP path on `127.0.0.1:0`, runs the loop and stops it -//! cleanly. Here both sides boot (real xquic engine, production driver, each -//! on its own thread), the client completes a handshake with the server, and -//! each driver is stopped through its `ShutdownHandle` with exit status 0. +//! Engine boot on the loopback harness (spec §8.1 "Loopback"): both sides +//! boot (real xquic engine, production driver, each on its own thread) on +//! `127.0.0.1:0`, the client completes a handshake with the server, and each +//! driver is stopped through its `ShutdownHandle` with exit status 0. use mq_integration::loopback::LoopbackPair; use mq_runtime::Shard; @@ -90,7 +88,7 @@ fn loop_engine_boot() { (Shard::new(t, app, local, 2), rec) }, ); - // The C test's `mq_runtime_open_udp_path("127.0.0.1", 0) == 0`. + // Both primary UDP paths are bound on loopback with a kernel-chosen port. for a in [pair.server.udp_addr, pair.client.udp_addr] { assert!(a.ip().is_loopback() && a.port() != 0, "{a}"); } @@ -109,6 +107,6 @@ fn loop_engine_boot() { ); assert!(pair.server.stats.iterations() > 0 && pair.client.stats.iterations() > 0); - // The C test's stop timer: each side stopped through its own handle. + // Each side stopped through its own handle. assert_eq!(pair.join_both(), (0, 0)); } diff --git a/crates/mq-integration/tests/pair_cs.rs b/crates/mq-integration/tests/pair_cs.rs index 6f2c3cf0..5f7728b1 100644 --- a/crates/mq-integration/tests/pair_cs.rs +++ b/crates/mq-integration/tests/pair_cs.rs @@ -1,28 +1,25 @@ -//! Ports `tests/integration/test_client_server.c` onto the shard pair -//! (spec §8.1 "Shard pair"), one test per C case: +//! Client↔server cases on the shard pair (spec §8.1 "Shard pair"): //! -//! | C case | test | client side | +//! | case | test | client side | //! |---|---|---| -//! | `test_auth_wrong_token` (A) | `pair_cs_auth_wrong_token` | real `Client` | -//! | `test_auth_matching_token` (B) | `pair_cs_auth_matching_token` | `RawClient` | -//! | `test_data_stream_echo` (C) | `pair_cs_data_stream_echo` | `RawClient` | -//! | `test_data_stream_refused` (D) | `pair_cs_data_stream_refused` | `RawClient` | -//! | `test_data_stream_preauth_reset` (E) | `pair_cs_data_stream_preauth_reset` | `RawClient` | -//! | `test_data_stream_teardown` (F) | `pair_cs_data_stream_teardown` | `RawClient` | -//! | `test_data_stream_download_completion` (G) | `pair_cs_data_stream_download_completion` | `RawClient` | -//! | `test_data_stream_halfclose_nospin` (H) | `pair_cs_data_stream_halfclose_nospin` | `RawClient` | -//! | `test_data_stream_coalesced_payload` (M) | `pair_cs_data_stream_coalesced_payload` | `RawClient` | -//! | `test_client_open_echo` (I) | `pair_cs_client_open_echo` | real `Client` | -//! | `test_client_open_download` (J) | `pair_cs_client_open_download` | real `Client` | -//! | `test_client_open_preauth_queue` (K) | `pair_cs_client_open_preauth_queue` | real `Client` | -//! | `test_client_open_refused` (L) | `pair_cs_client_open_refused` | real `Client` | +//! | A | `pair_cs_auth_wrong_token` | real `Client` | +//! | B | `pair_cs_auth_matching_token` | `RawClient` | +//! | C | `pair_cs_data_stream_echo` | `RawClient` | +//! | D | `pair_cs_data_stream_refused` | `RawClient` | +//! | E | `pair_cs_data_stream_preauth_reset` | `RawClient` | +//! | F | `pair_cs_data_stream_teardown` | `RawClient` | +//! | G | `pair_cs_data_stream_download_completion` | `RawClient` | +//! | H | `pair_cs_data_stream_halfclose_nospin` | `RawClient` | +//! | M | `pair_cs_data_stream_coalesced_payload` | `RawClient` | +//! | I | `pair_cs_client_open_echo` | real `Client` | +//! | J | `pair_cs_client_open_download` | real `Client` | +//! | K | `pair_cs_client_open_preauth_queue` | real `Client` | +//! | L | `pair_cs_client_open_refused` | real `Client` | //! -//! No case is excluded. The C test's in-process origins become the server -//! side's `Origin` (echo / bulk-then-close / refusing); the C -//! `mq_client_tcp_open` over a socketpair becomes a SOCKS5 request from a -//! scripted local socket, whose SOCKS5 reply stands for the open callback -//! (`ok` = success reply, `err` = the reply code). Reconnect is off, as in -//! the C fixture. +//! The origins are the server side's `Origin` (echo / bulk-then-close / +//! refusing); a client open is a SOCKS5 request from a scripted local socket, +//! whose SOCKS5 reply stands for the open callback (`ok` = success reply, +//! `err` = the reply code). Reconnect is off. #![forbid(unsafe_code)] use mq_integration::shard_pair::*; diff --git a/crates/mq-integration/tests/pair_max_conns.rs b/crates/mq-integration/tests/pair_max_conns.rs index a0aa6c9f..7dd7e01c 100644 --- a/crates/mq-integration/tests/pair_max_conns.rs +++ b/crates/mq-integration/tests/pair_max_conns.rs @@ -1,8 +1,6 @@ -//! Ports `tests/integration/test_max_conns_e2e.c` onto the shard pair (spec -//! §8.1 "Shard pair", §4.7 `max_conns`). The C test's three `mq_client`s A, -//! B and C are three connections of one `RawClient` (each sends the C -//! `AUTH_REQUEST`); C's `mq_transport_n_conns` is `Transport::conn_count`. -//! Nothing is excluded. +//! `max_conns` on the shard pair (spec §8.1 "Shard pair", §4.7 `max_conns`): +//! clients A, B and C are three connections of one `RawClient` (each sends the +//! `AUTH_REQUEST`), counted by `Transport::conn_count`. #![forbid(unsafe_code)] use mq_integration::shard_pair::*; diff --git a/crates/mq-integration/tests/pair_metrics.rs b/crates/mq-integration/tests/pair_metrics.rs index 51a22298..ea6c8a7a 100644 --- a/crates/mq-integration/tests/pair_metrics.rs +++ b/crates/mq-integration/tests/pair_metrics.rs @@ -1,10 +1,7 @@ -//! Ports `tests/integration/test_metrics_active_conn.c` onto the shard pair -//! (spec §8.1 "Shard pair", §6.5: the server reports the most recently -//! *accepted* connection — set at `NewConn`, before auth, as C `last_conn` -//! in `srv_on_new_conn` — and clears it only when that same connection -//! closes). The C `mq_conn_dump_stats` smoke is `conn_stats` + the formatter. -//! Nothing is excluded; `pair_metrics_active_conn_replaced_by_unauthenticated_accept` -//! is added. +//! Active-connection metrics on the shard pair (spec §8.1 "Shard pair", +//! §6.5: the server reports the most recently *accepted* connection — set at +//! `NewConn`, before auth — and clears it only when that same connection +//! closes), plus a `conn_stats` + formatter smoke. #![forbid(unsafe_code)] use mq_integration::shard_pair::*; diff --git a/crates/mq-integration/tests/pair_rc.rs b/crates/mq-integration/tests/pair_rc.rs index c9b700df..5bbee0aa 100644 --- a/crates/mq-integration/tests/pair_rc.rs +++ b/crates/mq-integration/tests/pair_rc.rs @@ -1,26 +1,14 @@ -//! Ports `tests/integration/test_client_reconnect.c` onto the shard pair -//! (spec §8.1 "Shard pair", §6.2 reconnect), real `Client` and `Server`: +//! Client reconnect on the shard pair (spec §8.1 "Shard pair", §6.2 +//! reconnect), real `Client` and `Server`. Case 3 covers the TCP half only +//! (UDP reconnect is SP2). //! -//! | C case | test | -//! |---|---| -//! | `test_case1_tcp_reconnect` | `pair_rc_case1_tcp_reconnect` | -//! | `test_case2_udp_reconnect` | excluded: UDP relay is SP2 | -//! | `test_case3_open_during_window` | `pair_rc_case3_open_during_window` (TCP half; its UDP half is SP2) | -//! | `test_case4_queue_carryover` | `pair_rc_case4_queue_carryover` | -//! | `test_case5_free_while_reconnecting` | excluded: C object lifetimes (`mq_client_free`) | -//! | `test_case6_keepalive_holds` | `pair_rc_case6_keepalive_holds` | -//! | `test_case7_persistent_outage` | `pair_rc_case7_persistent_outage` | -//! | `test_case8_open_after_terminal` | `pair_rc_case8_open_after_terminal` | -//! | `test_case9_free_before_engine_destroy` | excluded: C object lifetimes (free order) | -//! -//! The C `mq_conn_close(mq_client_conn(..))` is `Cx::close_conn` on the -//! client's connection; "re-authed" (C `on_auth` count) is the server's -//! `auth_attempts`; the C `tcp_open` over a socketpair is a SOCKS5 request +//! A connection drop is `Cx::close_conn` on the client's connection; +//! "re-authed" is the server's `auth_attempts`; an open is a SOCKS5 request //! whose reply stands for the open callback. Case 7's "server gone" is a //! fabric black hole (every datagram dropped both ways) instead of tearing //! the server down and rebuilding it on the same port. Case 8 runs with -//! reconnect off from the start (C turns it off after the first auth; the -//! `ClientConfig` is fixed at construction). +//! reconnect off from the start (the `ClientConfig` is fixed at +//! construction). #![forbid(unsafe_code)] use mq_integration::shard_pair::*; @@ -53,7 +41,7 @@ fn auths(p: &mut P, n: u64, limit: Duration) { ); } -/// C `run_tcp_echo_flow`: open, "ping", byte-exact echo. +/// Open, "ping", byte-exact echo. fn echo_flow(p: &mut P) { let s = p.socks_open(origin_addr(), b""); assert!( diff --git a/crates/mq-integration/tests/pair_udp.rs b/crates/mq-integration/tests/pair_udp.rs index cd60f004..ae8eae19 100644 --- a/crates/mq-integration/tests/pair_udp.rs +++ b/crates/mq-integration/tests/pair_udp.rs @@ -64,7 +64,7 @@ fn pair_udp_3000_byte_roundtrip_frags_reassembled_gt_0() { assert!(cli.frags_reassembled > 0, "{cli:?}"); } -/// spec §6.3/§7.2 (C design §2): the client hands the OPEN and the first +/// spec §6.3/§7.2: the client hands the OPEN and the first /// datagram to the transport in one iteration and one server iteration takes /// that flight; the real engine surfaces the datagram before the OPEN's /// bytes, so the server holds it in the pre-OPEN buffer and delivers it once diff --git a/crates/mq-linux/src/sockopt.rs b/crates/mq-linux/src/sockopt.rs index 744694f6..60bc65a1 100644 --- a/crates/mq-linux/src/sockopt.rs +++ b/crates/mq-linux/src/sockopt.rs @@ -1,8 +1,7 @@ //! Socket options and sockaddr conversion. spec §2.2. //! -//! `original_dst` reads the pre-NAT destination of a REDIRECTed TCP flow -//! (port of `src/ingress/mq_listener.c`); `set_linger_zero` makes the next -//! close abort with RST (spec §5.2). +//! `original_dst` reads the pre-NAT destination of a REDIRECTed TCP flow; +//! `set_linger_zero` makes the next close abort with RST (spec §5.2). use std::fs::{File, OpenOptions}; use std::io; @@ -151,8 +150,7 @@ pub(crate) fn sockaddr_storage(a: SocketAddr) -> (libc::sockaddr_storage, libc:: (ss, len as _) } -/// `AF_INET` or `AF_INET6`; rejects every other family (the -/// `unsupported_family` case of `tests/test_origdst.c`). +/// `AF_INET` or `AF_INET6`; rejects every other family. pub(crate) fn from_sockaddr_storage(ss: &libc::sockaddr_storage) -> io::Result { match ss.ss_family as libc::c_int { libc::AF_INET => { diff --git a/crates/mq-linux/src/udp.rs b/crates/mq-linux/src/udp.rs index 8538cd83..1c7fa41a 100644 --- a/crates/mq-linux/src/udp.rs +++ b/crates/mq-linux/src/udp.rs @@ -1,7 +1,6 @@ //! UDP sockets with GSO (`UDP_SEGMENT`) send and GRO (`UDP_GRO`) batched -//! receive. spec §2.2. IPv4 or IPv6 by the bind address (C supports -//! `AF_INET6` QUIC paths). An IPv6 socket is dual-stack (`IPV6_V6ONLY` = 0, -//! as C's default socket): it sends to IPv4 destinations as v4-mapped +//! receive. spec §2.2. IPv4 or IPv6 by the bind address. An IPv6 socket is +//! dual-stack (`IPV6_V6ONLY` = 0): it sends to IPv4 destinations as v4-mapped //! addresses and reports IPv4 peers as `SocketAddr::V4`. An IPv4 socket //! sends only to IPv4. //! diff --git a/crates/mq-linux/tests/udp.rs b/crates/mq-linux/tests/udp.rs index 7bbaaf78..2fef31e4 100644 --- a/crates/mq-linux/tests/udp.rs +++ b/crates/mq-linux/tests/udp.rs @@ -114,7 +114,7 @@ fn send_gso_rejects_more_than_64_segments_or_65507_bytes() { assert!(got.iter().all(|(_, d)| d == &vec![7u8; 100])); } -// --- IPv6 (C supports AF_INET6 QUIC paths): the same three on [::1]. --- +// --- IPv6: the same three on [::1]. --- #[test] fn v6_gso_send_arrives_as_segments() { diff --git a/crates/mq-proxy/src/client/backoff.rs b/crates/mq-proxy/src/client/backoff.rs index 16129c1d..80ede5ae 100644 --- a/crates/mq-proxy/src/client/backoff.rs +++ b/crates/mq-proxy/src/client/backoff.rs @@ -3,14 +3,14 @@ use mq_transport_api::Time; use std::time::Duration; -/// spec §6.2: C `MQ_CLIENT_RECONNECT_BASE_MS`. +/// spec §6.2: the reconnect base delay. pub const BASE_MS: u64 = 250; -/// spec §6.2: `--reconnect-max-backoff` is floored to this (C `mq_client_set_reconnect`). +/// spec §6.2: `--reconnect-max-backoff` is floored to this. pub const MIN_CAP: Duration = Duration::from_secs(1); /// spec §6.2: being `Serving` this long resets the attempt counter. pub const SERVING_RESET: Duration = Duration::from_secs(10); -/// spec §6.2: port of C `mq_backoff_ms`: `min(cap, base << min(attempt, 31))`. +/// spec §6.2: `min(cap, base << min(attempt, 31))`. pub fn backoff_ms(base_ms: u64, cap_ms: u64, attempt: u32) -> u64 { (base_ms << attempt.min(31)).min(cap_ms) } @@ -41,8 +41,8 @@ impl Backoff { /// spec §6.2: the delay before the next attempt, taken on leaving for `Backoff` at /// `now`; `rnd` is a random value (the shard's `Cx::rng()`). If the client had been - /// `Serving` for 10 s the counter resets first; then, as in C `client_reconnect_arm`, - /// it is incremented before the delay is computed (first retry: 250–500 ms). + /// `Serving` for 10 s the counter resets first; then it is incremented + /// before the delay is computed (first retry: 250–500 ms). pub fn next_delay(&mut self, now: Time, rnd: u64) -> Duration { if let Some(since) = self.serving_since.take() && now - since >= SERVING_RESET diff --git a/crates/mq-proxy/src/client/exchange/resp.rs b/crates/mq-proxy/src/client/exchange/resp.rs index d782cc1f..acbe69fd 100644 --- a/crates/mq-proxy/src/client/exchange/resp.rs +++ b/crates/mq-proxy/src/client/exchange/resp.rs @@ -12,7 +12,7 @@ pub struct Malformed; /// A collected response head (spec §5.4). #[derive(Debug, PartialEq, Eq)] pub struct RespHead { - /// `:status`, 502 when outside 100..=599 (as C). + /// `:status`, 502 when outside 100..=599. pub status: u16, /// Every relayed header, as received (pseudo and hop-by-hop dropped). pub headers: Vec<(Vec, Vec)>, @@ -39,7 +39,7 @@ impl HeadCollector { if self.bad { return; } - // Exactly three ASCII digits (C: no overflow on a hostile value). + // Exactly three ASCII digits: no overflow on a hostile value. if name == b":status" { match value { [a, b, c] if value.iter().all(u8::is_ascii_digit) => { @@ -57,7 +57,7 @@ impl HeadCollector { } return; } - // Other pseudo-headers and hop-by-hop: dropped; `x-mq-*` kept (as C). + // Other pseudo-headers and hop-by-hop: dropped; `x-mq-*` kept. if name.first() == Some(&b':') || is_hop_by_hop(name) { return; } @@ -121,7 +121,7 @@ mod tests { assert_eq!(collect(&[(":status", s)]), Err(Malformed), "{s:?}"); } assert_eq!(collect(&[("x", "y")]), Err(Malformed), "no :status"); - // C: the last `:status` wins. + // The last `:status` wins. let two = collect(&[(":status", "200"), (":status", "404")]); assert_eq!(two.unwrap().status, 404); } diff --git a/crates/mq-proxy/src/client/gateway/head.rs b/crates/mq-proxy/src/client/gateway/head.rs index 955fcfff..f8e622ba 100644 --- a/crates/mq-proxy/src/client/gateway/head.rs +++ b/crates/mq-proxy/src/client/gateway/head.rs @@ -26,7 +26,7 @@ pub fn fetch_head(h: &h1::Head<'_>) -> Result { return Err(Reject::DupControl); } let auth = find(b"x-mq-auth").ok_or(Reject::MissingAuth)?; - // C `mq_gw_client_prevalidate`: case-sensitive prefix, non-empty token. + // Case-sensitive prefix, non-empty token. if auth.len() <= 7 || !auth.starts_with(b"Bearer ") { return Err(Reject::BadAuthFormat); } @@ -61,8 +61,8 @@ pub fn fetch_head(h: &h1::Head<'_>) -> Result { if long(Some(auth)) || long(class) || long(ae) { return Err(Reject::HeaderTooLong); } - // An empty control header leaves the caller's `Accept-Encoding` alone (as - // C); a non-empty one replaces it, so the caller's is not forwarded. + // An empty control header leaves the caller's `Accept-Encoding` alone; a + // non-empty one replaces it, so the caller's is not forwarded. let ae = ae.filter(|v| !v.is_empty()); let cookie = forward_cookie_requested(h.headers.iter().map(|x| (x.name, x.value))); let headers = (h.headers.iter()) @@ -121,7 +121,7 @@ mod tests { const CTL_VAL_MAX: usize = 1024; - /// C `MQ_GW_MAX_SEND_HDRS` (spec §5.2: at most 64 + 8 headers). + /// spec §5.2: at most 64 + 8 headers. const MAX_FWD: usize = h1::MAX_HEADERS + 8; /// The request head, owned (spec §5.2: the parser's borrows end at @@ -194,7 +194,7 @@ mod tests { return Err(Reject::DupControl); } let auth = head.auth.as_ref().ok_or(Reject::MissingAuth)?; - // C `mq_gw_client_prevalidate`: case-sensitive prefix, non-empty token. + // Case-sensitive prefix, non-empty token. if auth.len() <= 7 || !auth.starts_with(b"Bearer ") { return Err(Reject::BadAuthFormat); } @@ -271,7 +271,7 @@ mod tests { { out.push(h("x-mq-cache", v)); } - // An empty control header leaves the caller's `Accept-Encoding` alone (as C). + // An empty control header leaves the caller's `Accept-Encoding` alone. let ae = head.accept_encoding.as_ref().filter(|v| !v.is_empty()); if let Some(v) = ae { out.push(h("accept-encoding", v)); diff --git a/crates/mq-proxy/src/client/mitm/head.rs b/crates/mq-proxy/src/client/mitm/head.rs index c02dfb3f..fe59c5cf 100644 --- a/crates/mq-proxy/src/client/mitm/head.rs +++ b/crates/mq-proxy/src/client/mitm/head.rs @@ -23,7 +23,7 @@ pub enum MapErr { Malformed, } -/// `"Bearer " + token`; a token that already has the prefix is used as is (C dedup). +/// `"Bearer " + token`; a token that already has the prefix is used as is. pub fn auth_value(token: &str) -> Vec { if token.starts_with("Bearer ") { token.as_bytes().to_vec() diff --git a/crates/mq-proxy/src/client/mod.rs b/crates/mq-proxy/src/client/mod.rs index e1f61435..1ae7c5e0 100644 --- a/crates/mq-proxy/src/client/mod.rs +++ b/crates/mq-proxy/src/client/mod.rs @@ -56,9 +56,9 @@ pub const TRANSPARENT: ListenerTag = ListenerTag(3); /// SP3 spec §5.1: the fetch listener. pub const FETCH: ListenerTag = ListenerTag(4); -/// spec §6.2: the TLS server name, as C. +/// spec §6.2: the TLS server name. const SNI: &str = "mqproxy"; -/// spec §6.2: wire limits of `client_id` / `auth_token` (C `char[64]` / `char[256]`). +/// spec §6.2: wire limits of `client_id` / `auth_token`. const MAX_CLIENT_ID: usize = 63; const MAX_TOKEN: usize = 255; const MAX_HOST: usize = 255; @@ -153,7 +153,7 @@ pub(crate) enum Owner { Mitm(mitm::MStreamKey), } -/// spec §6.2: truncate to the wire limit with a warning (C truncates silently). +/// spec §6.2: truncate to the wire limit with a warning. fn truncated(s: &str, max: usize, flag: &str) -> Vec { let b = s.as_bytes(); if b.len() > max { @@ -185,7 +185,7 @@ fn discard(cx: &mut Cx<'_>, tcp: TcpId) { cx.tcp_consume(tcp, n); } -/// spec §6.2: stream type `0x01` then `CONNECT_TCP_REQUEST` (flags 0), as C sends it. +/// spec §6.2: stream type `0x01` then `CONNECT_TCP_REQUEST` (flags 0). fn connect_request(target: &Target) -> Vec { let (address_type, host): (AddrType, Vec) = match &target.host { Host::Ip(IpAddr::V4(a)) => (AddrType::Ipv4, a.octets().to_vec()), @@ -412,7 +412,7 @@ impl Client { } }; let Some(features) = features else { - // spec §6.2 "Auth refused": pending requests fail, as in C. + // spec §6.2 "Auth refused": pending requests fail. self.set_udp(cx, UdpAvail::Unavailable); for o in self.pending.drain() { refuse(cx, o.tcp, o.kind, TcpErr::ConnRefused); @@ -594,7 +594,7 @@ impl Client { if let Some(t) = self.conn.take().and_then(|c| c.auth_timer) { self.cancel(cx, t); } - // Relays were closed by the shard's sweep; in-flight opens fail, as in C. + // Relays were closed by the shard's sweep; in-flight opens fail. for (_, o) in self.opens.drain() { refuse(cx, o.tcp, o.kind, TcpErr::ConnRefused); } @@ -732,7 +732,7 @@ impl App for Client { self.end_session(cx, sid, SessionEnd::Closed, false); } Event::StreamClosed(s) => { - // spec §6.2: closed before the response → CONN_REFUSED, as in C. + // spec §6.2: closed before the response → CONN_REFUSED. if let Some(o) = self.opens.remove(&s) { refuse(cx, o.tcp, o.kind, TcpErr::ConnRefused); cx.stream_reset(s); @@ -950,7 +950,7 @@ impl App for Client { if let Some(every) = self.cfg.metrics_interval { self.timer(cx, every, Tm::Metrics); } - // spec §6.5: nothing without a connection, as C `cli_metrics_tick`; + // spec §6.5: nothing without a connection; // SP3 spec §5.7: then the H3 tunnel's block. self.dump_metrics(cx); if let Some(t) = self.h3.as_ref() { diff --git a/crates/mq-proxy/src/client/paths.rs b/crates/mq-proxy/src/client/paths.rs index 26e68fe9..86eba89a 100644 --- a/crates/mq-proxy/src/client/paths.rs +++ b/crates/mq-proxy/src/client/paths.rs @@ -39,7 +39,7 @@ pub(super) struct Paths { /// spec §6.2: under the `backup` scheduler paths are added as standby. standby: bool, /// The log prefix: `mq_client` (raw tunnel) or `mq_gw_client` (gateway - /// tunnel), as C's two owners log (SP3 spec §5.7). + /// tunnel); SP3 spec §5.7. log: &'static str, } diff --git a/crates/mq-proxy/src/client/pending.rs b/crates/mq-proxy/src/client/pending.rs index d6f3390e..2e6be4ac 100644 --- a/crates/mq-proxy/src/client/pending.rs +++ b/crates/mq-proxy/src/client/pending.rs @@ -10,7 +10,7 @@ use mq_wire::frames::TcpErr; use std::collections::VecDeque; use std::time::Duration; -/// spec §6.2: C `MQ_CLIENT_QUEUE_MAX`. +/// spec §6.2: the pending-request queue bound. pub const MAX_PENDING: usize = 256; /// spec §6.1: which ingress accepted the socket, i.e. which reply format it expects. diff --git a/crates/mq-proxy/src/client/tunnel_h3.rs b/crates/mq-proxy/src/client/tunnel_h3.rs index 4679700a..d459039f 100644 --- a/crates/mq-proxy/src/client/tunnel_h3.rs +++ b/crates/mq-proxy/src/client/tunnel_h3.rs @@ -80,7 +80,7 @@ impl H3Tunnel { self.reconnect = Some(cx.set_timer(d)); } - /// SP3 spec §5.7: eager, as C's constructor; the first failure is fatal. + /// SP3 spec §5.7: eager; the first failure is fatal. pub fn on_start(&mut self, cx: &mut Cx<'_>) { if !self.connect(cx) { cx.request_exit(1); diff --git a/crates/mq-proxy/src/client/udp_assoc.rs b/crates/mq-proxy/src/client/udp_assoc.rs index 763b6deb..58f32942 100644 --- a/crates/mq-proxy/src/client/udp_assoc.rs +++ b/crates/mq-proxy/src/client/udp_assoc.rs @@ -66,7 +66,7 @@ impl Assoc { now: Time, ) -> Option<&mut DstEntry> { if self.dsts.len() >= MAX_DST_PER_ASSOC { - // C `dst_alloc`: `failed_at == 0 || now - failed_at >= NEGCACHE`. + // A free entry: no session and no live negative-cache mark. let free = self.dsts.iter().find(|(_, e)| { e.session.is_none() && e.failed_at.is_none_or(|f| now - f >= NEG_CACHE) }); diff --git a/crates/mq-proxy/src/client/udp_session.rs b/crates/mq-proxy/src/client/udp_session.rs index a1f19f96..5f175253 100644 --- a/crates/mq-proxy/src/client/udp_session.rs +++ b/crates/mq-proxy/src/client/udp_session.rs @@ -43,7 +43,7 @@ struct Session { /// spec §6.3: the session table of the client (one connection at a time). pub(super) struct Sessions { - /// Per client: it survives connections, as C `next_sid`. + /// Per client: it survives connections. next_sid: u32, /// By sid; ordered, so a post-auth flush runs in sid order (creation /// order until the counter wraps). @@ -58,7 +58,7 @@ pub(super) struct Sessions { impl Sessions { pub(super) fn new() -> Sessions { Sessions { - next_sid: 1, // as C: 0 is valid, 1 reads better in logs + next_sid: 1, // 0 is valid, 1 reads better in logs by_sid: BTreeMap::new(), by_stream: HashMap::new(), mss: MssCache::new(), @@ -79,7 +79,7 @@ fn alloc_sid(next: &mut u32, live: impl Fn(u32) -> bool) -> u32 { } } -/// spec §6.3: C `cli_sendq_push` — an item over 8 KiB on its own is dropped, +/// spec §6.3: an item over 8 KiB on its own is dropped, /// otherwise the oldest go until both bounds hold; each loss is one `sendq_evictions`. fn enqueue(q: &mut VecDeque>, p: &[u8], c: &mut Counters) { if p.len() > PREAUTH_SENDQ_BYTES { @@ -95,7 +95,7 @@ fn enqueue(q: &mut VecDeque>, p: &[u8], c: &mut Counters) { } /// spec §6.3: stream type `0x02` then `UDP_SESSION_OPEN` for `dst` with -/// `idle_timeout_ms = 0` (the server default), as C `mq_udp_cli_open`. +/// `idle_timeout_ms = 0` (the server default). fn open_request(sid: u32, dst: &Dst<'_>) -> Vec { let mut buf = vec![0u8; MAX_FRAME]; buf[0] = STREAM_TYPE_UDP_SESSION as u8; @@ -167,7 +167,7 @@ impl Client { } /// spec §6.3/§5: queue while `PendingAuth`, else split onto the tunnel - /// under the fragment send policy; `packet_id` moves iff the split ran (C). + /// under the fragment send policy; `packet_id` moves iff the split ran. fn session_send(&mut self, cx: &mut Cx<'_>, sid: u32, payload: &[u8]) { let Sessions { by_sid, @@ -381,7 +381,7 @@ impl Client { /// to the learned source. fn deliver(&mut self, cx: &mut Cx<'_>, d: &[u8]) { let Some(h) = UdpMsgHdr::decode(d) else { - return; // short: silent, as C + return; // short: silent }; let c = &mut self.sess.counters; let Some(s) = self.sess.by_sid.get_mut(&h.session_id) else { diff --git a/crates/mq-proxy/src/config.rs b/crates/mq-proxy/src/config.rs index 09408382..7d42a96a 100644 --- a/crates/mq-proxy/src/config.rs +++ b/crates/mq-proxy/src/config.rs @@ -23,7 +23,7 @@ pub struct ClientConfig { pub scheduler: Scheduler, /// `--keepalive-idle`: the QUIC idle timeout; `None` disables it. pub keepalive_idle: Option, - /// `--client-id` (C default "mqproxy"); truncated to 63 bytes on the wire. + /// `--client-id` (default "mqproxy"); truncated to 63 bytes on the wire. pub client_id: String, /// `--token`; truncated to 255 bytes on the wire. pub token: String, @@ -44,7 +44,7 @@ pub struct ClientConfig { /// its own H3 tunnel connection. pub gateway: Option, /// SP3 spec §5.7: a TCP ingress (`--socks5` / `--http-connect` / `--tproxy`) - /// is configured, so the raw tunnel is created (C `need_client`). + /// is configured, so the raw tunnel is created. pub has_tcp_ingress: bool, /// SP4 spec §9: `--mitm` with its CA and IgnoreHosts. pub mitm: Option, diff --git a/crates/mq-proxy/src/ingress/http_connect.rs b/crates/mq-proxy/src/ingress/http_connect.rs index 0a060a5c..50925273 100644 --- a/crates/mq-proxy/src/ingress/http_connect.rs +++ b/crates/mq-proxy/src/ingress/http_connect.rs @@ -1,5 +1,4 @@ -//! spec §6.1: HTTP CONNECT (authority-form) — port of `src/ingress/mq_http_connect.c` -//! plus the parse-error replies of `mq_listener.c:drive_http`. +//! spec §6.1: HTTP CONNECT (authority-form) parser and its replies. use super::Progress; use super::request::capped; @@ -7,7 +6,7 @@ use mq_runtime::{Host, Target}; use mq_wire::frames::TcpErr; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; -const MAX_HOST: usize = 255; // MQ_MAX_HOST +const MAX_HOST: usize = 255; const R405: &[u8] = b"HTTP/1.1 405 Method Not Allowed\r\n\r\n"; const R400: &[u8] = b"HTTP/1.1 400 Bad Request\r\n\r\n"; @@ -106,7 +105,7 @@ pub fn http_success_reply() -> &'static [u8] { b"HTTP/1.1 200 Connection Established\r\n\r\n" } -/// spec §6.1: CONNECT failed (`mq_http_status_line`). +/// spec §6.1: CONNECT failed. pub fn http_error_reply(e: TcpErr) -> &'static [u8] { match e { TcpErr::Timeout => b"HTTP/1.1 504 Gateway Timeout\r\n\r\n", diff --git a/crates/mq-proxy/src/ingress/request.rs b/crates/mq-proxy/src/ingress/request.rs index 4b60d342..fd016576 100644 --- a/crates/mq-proxy/src/ingress/request.rs +++ b/crates/mq-proxy/src/ingress/request.rs @@ -2,7 +2,7 @@ use mq_runtime::Target; -/// spec §6.1: a parser looks at no more than this many buffered bytes (C `MQ_LISTENER_RXCAP`). +/// spec §6.1: a parser looks at no more than this many buffered bytes. pub const INGRESS_CAP: usize = 8192; /// spec §6.1: what one `feed` over the buffered bytes produced. `consumed` counts bytes @@ -26,7 +26,7 @@ pub enum Progress<'a> { } /// spec §6.1: parse at most `INGRESS_CAP` bytes; a full cap without a complete request -/// closes without a reply, as `mq_listener.c:346` does. +/// closes without a reply. pub(crate) fn capped<'a>(buf: &[u8], parse: impl FnOnce(&[u8]) -> Progress<'a>) -> Progress<'a> { match parse(&buf[..buf.len().min(INGRESS_CAP)]) { Progress::Need if buf.len() >= INGRESS_CAP => Progress::Close, diff --git a/crates/mq-proxy/src/ingress/socks5.rs b/crates/mq-proxy/src/ingress/socks5.rs index 4a652af4..51ba6449 100644 --- a/crates/mq-proxy/src/ingress/socks5.rs +++ b/crates/mq-proxy/src/ingress/socks5.rs @@ -1,5 +1,5 @@ -//! spec §6.1: SOCKS5 (RFC 1928, no-auth, CONNECT and UDP ASSOCIATE) — port of -//! `src/ingress/mq_socks5.c` plus the reply choices of `mq_listener.c:drive_socks5`. +//! spec §6.1: SOCKS5 (RFC 1928, no-auth, CONNECT and UDP ASSOCIATE) parser +//! and its replies. use super::Progress; use super::request::capped; @@ -48,7 +48,7 @@ fn greeting(b: &[u8], greeted: &mut bool) -> Progress<'static> { return Progress::Need; } if b[0] != VER { - return Progress::Close; // mq_socks5.c:25 → MQ_DRIVE_CLOSE, no reply + return Progress::Close; // no reply } let total = 2 + b[1] as usize; if b.len() < total { @@ -83,13 +83,13 @@ fn request(b: &[u8]) -> Progress<'static> { return Progress::Need; } if b[0] != VER { - return Progress::Close; // mq_socks5.c:52 → MQ_DRIVE_CLOSE, no reply + return Progress::Close; // no reply } let cmd = b[1]; if cmd != CMD_CONNECT && cmd != CMD_ASSOCIATE { return refuse(&REP_CMD_UNSUPPORTED); // BIND and unknown commands } - // b[2] RSV ignored, as in C. + // b[2] RSV ignored. let atyp = b[3]; let (off, len) = match atyp { 0x01 => (4, 4), @@ -105,7 +105,7 @@ fn request(b: &[u8]) -> Progress<'static> { return Progress::Need; } if cmd == CMD_ASSOCIATE { - // spec §6.1: parsed in full, the DST ignored (as C and RFC 1928 allow). + // spec §6.1: parsed in full, the DST ignored (as RFC 1928 allows). return Progress::Associate { consumed: total }; } let addr = &b[off..off + len]; @@ -156,7 +156,7 @@ pub fn socks5_assoc_reply(bound: SocketAddr) -> Vec { b } -/// spec §6.1: CONNECT failed; REP from `mq_socks5_reply_code`, with `Ok` as general failure. +/// spec §6.1: CONNECT failed; REP per error, with `Ok` as general failure. pub fn socks5_error_reply(e: TcpErr) -> [u8; 10] { reply(match e { TcpErr::DnsFailed => 0x04, diff --git a/crates/mq-proxy/src/metrics.rs b/crates/mq-proxy/src/metrics.rs index 0fce2a22..fa50b96e 100644 --- a/crates/mq-proxy/src/metrics.rs +++ b/crates/mq-proxy/src/metrics.rs @@ -1,5 +1,4 @@ -//! spec §6.5: `mq.conn` / `mq.path` lines, byte-identical to C -//! `mq_conn_format_conn_line` / `mq_conn_format_path_line` / `mq_conn_dump_stats_cid`. +//! spec §6.5: `mq.conn` / `mq.path` lines. use mq_transport_api::{ConnStats, PathStats}; diff --git a/crates/mq-proxy/src/server/gateway/intake.rs b/crates/mq-proxy/src/server/gateway/intake.rs index 3af9d127..b615f41e 100644 --- a/crates/mq-proxy/src/server/gateway/intake.rs +++ b/crates/mq-proxy/src/server/gateway/intake.rs @@ -14,11 +14,9 @@ use mq_http::headers::{ use mq_http::limits::{SectionBudget, TARGET_PATH_MAX}; use subtle::ConstantTimeEq; -/// C's fixed buffers `char auth[512]` / `char cls[128]`: the only two -/// values truncated instead of rejected (§9.3). +/// The only two values truncated instead of rejected (§9.3). const AUTH_CAP: usize = 511; const CLASS_CAP: usize = 127; -/// C `sanitize_for_log(cls_safe, 64, …)`. const CLASS_LOG: usize = 64; /// What one header section said, before any judgement. @@ -45,8 +43,8 @@ pub(super) struct Capture { } impl Capture { - /// One header; names compare case-insensitively (C `slice_ieq`), a - /// repeated pseudo-header or control header keeps the last value (C). + /// One header; names compare case-insensitively, a repeated + /// pseudo-header or control header keeps the last value. pub(super) fn each(&mut self, n: &[u8], v: &[u8]) { let is = |s: &[u8]| n.eq_ignore_ascii_case(s); let cut = |cap: usize| Some(v[..v.len().min(cap)].to_vec()); @@ -56,7 +54,7 @@ impl Capture { _ if is(b":scheme") => &mut self.scheme, _ if is(b":authority") => &mut self.authority, _ if is(b":path") => &mut self.path, - _ => return, // other pseudo-headers: ignored, as C + _ => return, // other pseudo-headers: ignored }; // A pseudo-header is a field too (`:path` at 8188 overflows here). self.bad_header |= self.budget.add(n, v).is_err(); @@ -330,13 +328,13 @@ mod tests { Err((403, "auth-failed")) ); assert_eq!(outcome(&req(&[], false)), Ok(())); - // An empty configured token never matches (C: `al > pl`). + // An empty configured token never matches. assert!( decide(&req(&[("x-mq-auth", Some(b"Bearer "))], false), b"") .outcome .is_err() ); - // C's `char auth[512]`: the value is cut at 511 bytes before the compare. + // The value is cut at 511 bytes before the compare. let token = vec![b't'; 504]; let mut v = b"Bearer ".to_vec(); v.extend_from_slice(&token); @@ -344,7 +342,7 @@ mod tests { let c = req(&[("x-mq-auth", Some(&v))], false); assert_eq!(c.auth.as_ref().map(Vec::len), Some(511)); assert!(decide(&c, &token).authed, "the cut value matches"); - // Header names match case-insensitively, as C's `slice_ieq`. + // Header names match case-insensitively. let mut c = req(&[("x-mq-auth", None)], false); c.each(b"X-Mq-Auth", b"Bearer secret"); assert_eq!(outcome(&c), Ok(())); @@ -391,7 +389,7 @@ mod tests { class_line(b"x", b"Bearer nope").is_empty(), "step 5 follows auth" ); - // C's `char cls[128]`. + // The class is cut at 127 bytes. let c = req(&[("x-mq-class", Some(&[b'c'; 200]))], false); assert_eq!(c.class.as_ref().map(Vec::len), Some(127)); } diff --git a/crates/mq-proxy/src/server/gateway/mod.rs b/crates/mq-proxy/src/server/gateway/mod.rs index 131c12de..dc6bc590 100644 --- a/crates/mq-proxy/src/server/gateway/mod.rs +++ b/crates/mq-proxy/src/server/gateway/mod.rs @@ -52,7 +52,7 @@ struct ReqMeta { origin_is_tls: bool, } -/// spec §6.6: how the origin transfer ended, committed C-style (`on_done`). +/// spec §6.6: how the origin transfer ended. #[derive(Copy, Clone)] struct OriginEnd { tls: TlsOutcome, @@ -347,7 +347,7 @@ impl GwCore { hs.push(h("x-mq-error", xmq.as_bytes())); } hs.push(h("content-length", b"0")); - // `Blocked` on this tiny block is treated as sent (as C). + // `Blocked` on this tiny block is treated as sent. if !matches!( cx.h3_send_headers(id, &hs, true), Ok(()) | Err(StreamError::Blocked) @@ -479,7 +479,7 @@ impl GwCore { } } -/// spec §6.6/§2.4: the request's `mq.req` line, inputs derived as C's call site. +/// spec §6.6/§2.4: the request's `mq.req` line. fn log_req(r: &GwReq, s: &H3ReqStats) { let m = r.meta.as_ref(); let path = m.map_or(&b"-"[..], |m| { diff --git a/crates/mq-proxy/src/server/mod.rs b/crates/mq-proxy/src/server/mod.rs index 60a9f372..c785e7a3 100644 --- a/crates/mq-proxy/src/server/mod.rs +++ b/crates/mq-proxy/src/server/mod.rs @@ -45,9 +45,9 @@ use std::time::Duration; use subtle::ConstantTimeEq; use udp_session::SrvSession; -/// spec §6.3 "Auth accepted": as C `MQ_SERVER_ID`. +/// spec §6.3 "Auth accepted": the `server_id`. const SERVER_ID: &[u8] = b"mqproxy-server"; -/// spec §6.3: the wire limit of `auth_token` (C `char[256]`). +/// spec §6.3: the wire limit of `auth_token`. const MAX_TOKEN: usize = 255; /// spec §6.3: app-held streams per connection, control included. const STREAM_BUDGET: usize = 4096; @@ -139,7 +139,7 @@ struct Data { enum Parsed { Wait, Bad, - /// A request whose target cannot be dialled: answered, not reset (as C). + /// A request whose target cannot be dialled: answered, not reset. Undialable(usize), Dial(usize, Target), /// SP2 spec §7.1: `UDP_SESSION_OPEN` — sid, target (`None`: undialable, @@ -162,7 +162,7 @@ pub struct Server { /// SP2 spec §7.2: the `datagram_recv` scratch. rx: Vec, timers: HashMap, - /// spec §6.5: the most recently accepted connection (C `last_conn`). + /// spec §6.5: the most recently accepted connection. active: Option, auth_attempts: u64, shutting_down: bool, @@ -184,7 +184,7 @@ fn tcp_resp(status: u8, e: TcpErr) -> Vec { b } -/// spec §6.3 dial error table (C `srv_map_errno` maps unclassified errors to CONN_REFUSED). +/// spec §6.3 dial error table; unclassified errors map to CONN_REFUSED. fn map_dial_error(e: DialError) -> TcpErr { match e { DialError::Dns => TcpErr::DnsFailed, @@ -195,10 +195,10 @@ fn map_dial_error(e: DialError) -> TcpErr { } /// spec §6.3: stream type then `CONNECT_TCP_REQUEST` (or, SP2 spec §7.1, -/// `UDP_SESSION_OPEN`), as C `srv_data_header_readable`. +/// `UDP_SESSION_OPEN`). fn parse_request(buf: &[u8], fin: bool) -> Parsed { - // spec §6.2: a header (discriminator + frame) over 512 bytes never fits - // C's 512-byte frame buffer, complete or not. + // spec §6.2: a header (discriminator + frame) over 512 bytes is rejected, + // complete or not. let wait = if fin || buf.len() >= MAX_FRAME { Parsed::Bad } else { @@ -214,7 +214,7 @@ fn parse_request(buf: &[u8], fin: bool) -> Parsed { Err(DecodeError::Short) => return wait, _ => return Parsed::Bad, }; - // C `srv_resolve_target`: a wrong address length or an unusable name is DNS_FAILED. + // A wrong address length or an unusable name is DNS_FAILED. match host_of(req.address_type, req.host) { Some(host) => Parsed::Dial( used, @@ -279,7 +279,7 @@ impl Server { self.gw.as_mut().map(Gateway::core_mut) } - /// Complete `AUTH_REQUEST`s seen (C `auth_attempts`), malformed ones included. + /// Complete `AUTH_REQUEST`s seen, malformed ones included. #[cfg(feature = "test-support")] pub fn auth_attempts(&self) -> u64 { self.auth_attempts @@ -347,7 +347,7 @@ impl Server { }, ); if raw { - // spec §6.5: C sets `last_conn` at acceptance, before auth. + // spec §6.5: set at acceptance, before auth. self.active = Some(c); } else if let Some(g) = self.gw.as_mut() { g.on_new_conn(cx, c); @@ -475,7 +475,7 @@ impl Server { status: if ok { STATUS_OK } else { STATUS_ERROR }, error_code: u64::from(!ok), // AUTH_FAILED server_id: SERVER_ID, - // spec §7.3: as C, only an accepted auth advertises the capability. + // spec §7.3: only an accepted auth advertises the capability. features: if ok && self.cfg.udp_enabled { FEAT_UDP_RELAY } else { @@ -686,7 +686,7 @@ impl Server { } /// spec §6.5: the lines of the most recently accepted connection, if - /// open, then (SP3 spec §6) those of the most recent H3 conn, as C. + /// open, then (SP3 spec §6) those of the most recent H3 conn. fn dump_metrics(&self, cx: &Cx<'_>) { let last_h3 = self.gw.as_ref().and_then(Gateway::last_h3); for c in [self.active, last_h3].into_iter().flatten() { @@ -852,7 +852,7 @@ impl App for Server { if let Some(every) = self.cfg.metrics_interval { self.timer(cx, every, Tm::Metrics); } - // spec §6.5: silent without a connection, as C `srv_metrics_tick`. + // spec §6.5: silent without a connection. self.dump_metrics(cx); } Tm::UdpIdle(c, sid) => self.udp_idle(cx, c, sid), diff --git a/crates/mq-proxy/src/server/origin/mod.rs b/crates/mq-proxy/src/server/origin/mod.rs index 870ff769..24a2bbe0 100644 --- a/crates/mq-proxy/src/server/origin/mod.rs +++ b/crates/mq-proxy/src/server/origin/mod.rs @@ -45,7 +45,7 @@ use std::time::Duration; pub const HYPER_VERSION: &str = "1.10"; /// spec §6.3/§9.3: one request's `UploadBuf`. pub const UPLOAD_CAP: usize = 256 * 1024; -/// spec §7.7: idle expiry (curl's default `MAXAGE_CONN`). +/// spec §7.7: idle expiry. pub const IDLE_MAX: Duration = Duration::from_secs(118); /// spec §7.7: the idle sweep interval. pub const SWEEP: Duration = Duration::from_secs(10); @@ -590,7 +590,7 @@ impl Origin { let https = rec.https(); match r { Ok(tcp) => { - // libcurl parity: Nagle would hold a request's later writes + // TCP_NODELAY: Nagle would hold a request's later writes // behind the origin's delayed ACK (~40 ms per small upload). cx.tcp_set_nodelay(tcp); self.connected(cx, tcp, rec, ev) @@ -751,7 +751,7 @@ impl Origin { self.by_tcp.insert(tcp, id); self.by_h3.insert(h3, Where::Conn(id)); if plain { - // C used CONNECT_TIME_T: the TCP dial's duration. + // `connect_ms` is the TCP dial's duration. self.begin_hyper(cx, id, OriginProto::H1); } } diff --git a/crates/mq-proxy/src/server/origin/pump.rs b/crates/mq-proxy/src/server/origin/pump.rs index 6d784fe6..e208b56f 100644 --- a/crates/mq-proxy/src/server/origin/pump.rs +++ b/crates/mq-proxy/src/server/origin/pump.rs @@ -516,7 +516,7 @@ impl Origin { } } -/// §7.7 libcurl's second retry, h1 only (no h2 retry at all): a reused conn +/// §7.7 retry, h1 only (no h2 retry at all): a reused conn /// closed before any response byte, for a bodiless request, once. fn bodiless_retry( proto: OriginProto, diff --git a/crates/mq-proxy/src/server/origin/request.rs b/crates/mq-proxy/src/server/origin/request.rs index f2095721..fc70afc8 100644 --- a/crates/mq-proxy/src/server/origin/request.rs +++ b/crates/mq-proxy/src/server/origin/request.rs @@ -30,7 +30,7 @@ pub(super) fn build_request( .method(req.method.as_bytes()) .uri(uri) .header("host", req.authority.as_slice()); - // libcurl: `name:` suppresses, so an empty `accept` suppresses the default too. + // `name:` suppresses the header, so an empty `accept` suppresses the default too. if !req .headers .iter() diff --git a/crates/mq-proxy/src/server/udp_session.rs b/crates/mq-proxy/src/server/udp_session.rs index e02fbc3e..31732f7f 100644 --- a/crates/mq-proxy/src/server/udp_session.rs +++ b/crates/mq-proxy/src/server/udp_session.rs @@ -56,12 +56,12 @@ pub(super) struct SrvSession { pub(super) idle_len: Duration, /// Client → target reassembly (spec §2.3). defrag: Defrag, - /// The next target → client `packet_id` (C `next_packet_id`). + /// The next target → client `packet_id`. packet_id: u16, } /// spec §7.3: the stats line of a connection that just closed, after its -/// sessions were reaped. The C fields in C order, then `drops_empty`. +/// sessions were reaped. pub(super) fn log_stats(c: &Counters) { log::info!( "mq_udp_srv: stats frags_sent={} frags_reassembled={} drops_send_fail={} \ @@ -78,7 +78,7 @@ pub(super) fn log_stats(c: &Counters) { } /// spec §7.1: `UDP_SESSION_RESP`, no message — OK with the negotiated idle -/// timeout, or an error with idle 0 (C `srv_open_reject`). +/// timeout, or an error with idle 0. fn udp_resp(r: Result) -> Vec { let (status, error_code, idle_timeout_ms) = match r { Ok(idle) => (STATUS_OK, 0, idle), @@ -109,7 +109,7 @@ fn negotiated_idle(requested_ms: u64, server: Duration) -> u64 { } /// spec §7.2: the form `target` is kept in — IPv4-mapped unmapped, unspecified -/// → loopback (C `connect()`s to it and the kernel picks loopback). +/// → loopback (a `connect()` to it lands on loopback). fn canonical(mut a: SocketAddr) -> SocketAddr { a.set_ip(match a.ip().to_canonical() { IpAddr::V4(v) if v.is_unspecified() => Ipv4Addr::LOCALHOST.into(), @@ -163,7 +163,7 @@ impl Server { let c = self.data[&s].conn; let udp = &self.conns[&c].udp; if udp.contains_key(&sid) { - // C design §9.2: the existing session is kept. + // The existing session is kept. log::warn!("mq_udp_srv: duplicate session_id {sid}, resetting new stream (no RESP)"); return self.drop_data(cx, s, true); } @@ -195,7 +195,7 @@ impl Server { } /// spec §7.1: `Resolving` → `Opening` on a socket of the resolved - /// address's family, or `DnsFailed` (`Dns` and `Timeout` alike, as C). + /// address's family, or `DnsFailed` (`Dns` and `Timeout` alike). pub(super) fn udp_resolved( &mut self, cx: &mut Cx<'_>, @@ -328,13 +328,13 @@ impl Server { let Some(k) = self.conns.get_mut(&c) else { return; }; - // C design §9.2: the only auth boundary for DATAGRAM frames. + // The only auth boundary for DATAGRAM frames. if !enabled || !k.authed() { k.counters.drops_preauth += 1; return; } let Some(h) = UdpMsgHdr::decode(d) else { - return; // short: silent, as C + return; // short: silent }; let sid = h.session_id; let Some(SrvSession { @@ -403,7 +403,7 @@ impl Server { } let out = send_packet(cx, c, &mut k.mss, sid, *packet_id, data, &mut k.counters); if out.frags_ok + out.failed > 0 { - *packet_id = packet_id.wrapping_add(1); // the split ran (C) + *packet_id = packet_id.wrapping_add(1); // the split ran } if out.frags_ok > 0 { *active = cx.now(); diff --git a/crates/mq-proxy/src/udp/defrag.rs b/crates/mq-proxy/src/udp/defrag.rs index d3f59bd7..69937391 100644 --- a/crates/mq-proxy/src/udp/defrag.rs +++ b/crates/mq-proxy/src/udp/defrag.rs @@ -1,9 +1,9 @@ -//! spec §2.3: 4-slot LRU datagram defragmenter — C `mq_defrag_feed`. +//! spec §2.3: 4-slot LRU datagram defragmenter. use mq_wire::udp_msg::UdpMsgHdr; const SLOTS: usize = 4; -/// Largest reassembled packet (C `DEFRAG_MAX_TOTAL`). +/// Largest reassembled packet. const MAX_TOTAL: usize = 65_535; #[derive(PartialEq, Eq, Debug)] @@ -15,7 +15,7 @@ pub enum Feed { struct Slot { packet_id: u16, - /// One entry per expected fragment; `Some` is the C bitmap bit. + /// One entry per expected fragment; `Some` once received. frags: Vec>>, received: usize, total_len: usize, diff --git a/crates/mq-proxy/src/udp/mod.rs b/crates/mq-proxy/src/udp/mod.rs index 09e01b9c..6478ab2c 100644 --- a/crates/mq-proxy/src/udp/mod.rs +++ b/crates/mq-proxy/src/udp/mod.rs @@ -21,14 +21,14 @@ pub const PREOPEN_BYTES: usize = 32 * 1024; pub const PREOPEN_TTL: Duration = Duration::from_millis(250); pub const DEFAULT_IDLE: Duration = Duration::from_secs(60); pub const SESSION_RESP_WAIT: Duration = Duration::from_secs(10); -/// Successful emits between `datagram_mss` refreshes (C `MQ_MSS_REFRESH_INTERVAL`). +/// Successful emits between `datagram_mss` refreshes. pub const MSS_REFRESH: u32 = 64; -/// Per association, live sessions and negative-cache entries together (C `MQ_UDP_ASSOC_MAX_DST`). +/// Per association, live sessions and negative-cache entries together. pub const MAX_DST_PER_ASSOC: usize = 64; /// The largest UDP datagram: the `datagram_recv` scratch, and the bound of a reply. pub(crate) const MAX_DGRAM: usize = 65_535; -/// The host that wire address bytes name (C `srv_resolve_target`); `None` for a +/// The host that wire address bytes name; `None` for a /// wrong address length or a non-UTF-8 name. An empty name is left to the caller. pub(crate) fn host_of(atype: AddrType, addr: &[u8]) -> Option { Some(match atype { @@ -47,7 +47,7 @@ pub enum SessionEnd { Closed, } -/// The fields of the `mq_udp_srv:` (§7.3) and `mq_udp_cli:` (§6.5) stats lines; `u32` as C `%u`. +/// The fields of the `mq_udp_srv:` (§7.3) and `mq_udp_cli:` (§6.5) stats lines. /// The first eight are the server line, the next two exist on the client only, and the /// last two (spec §6.3 admission-limit drops) are on neither line. #[derive(Clone, Copy, Default, PartialEq, Eq, Debug)] diff --git a/crates/mq-proxy/src/udp/preopen.rs b/crates/mq-proxy/src/udp/preopen.rs index 3ede6e75..52789e8d 100644 --- a/crates/mq-proxy/src/udp/preopen.rs +++ b/crates/mq-proxy/src/udp/preopen.rs @@ -1,4 +1,4 @@ -//! spec §7.2: per-connection pre-OPEN datagram buffer — C `srv_preopen_*`. +//! spec §7.2: per-connection pre-OPEN datagram buffer. use super::{PREOPEN_BYTES, PREOPEN_DGRAMS, PREOPEN_TTL}; use mq_transport_api::Time; @@ -14,7 +14,7 @@ pub struct PreOpen { impl PreOpen { /// Parks `datagram` for `sid`; returns the evictions it caused (the caller adds them - /// to `preopen_evictions`). Entries past the TTL are swept first and not counted (C). + /// to `preopen_evictions`). Entries past the TTL are swept first and not counted. pub fn push(&mut self, now: Time, sid: u32, datagram: &[u8]) -> u32 { // Pushes arrive in time order, so the expired entries are a prefix. while self.q.front().is_some_and(|e| now - e.1 > PREOPEN_TTL) { @@ -37,7 +37,7 @@ impl PreOpen { } /// Removes and returns `sid`'s datagrams in arrival order; entries past the TTL at - /// `now` are dropped uncounted (C `srv_preopen_flush`). Other sids stay queued. + /// `now` are dropped uncounted. Other sids stay queued. pub fn take(&mut self, now: Time, sid: u32) -> Vec> { let mut out = Vec::new(); for e in std::mem::take(&mut self.q) { diff --git a/crates/mq-proxy/src/udp/send.rs b/crates/mq-proxy/src/udp/send.rs index 8b3e7f3e..8acc449e 100644 --- a/crates/mq-proxy/src/udp/send.rs +++ b/crates/mq-proxy/src/udp/send.rs @@ -1,5 +1,5 @@ -//! spec §5: the per-connection datagram MSS cache and the C fragment send policy, -//! shared by both roles — C `{srv,cli}_get_mss_payload` / `{srv_split,cli}_emit_*`. +//! spec §5: the per-connection datagram MSS cache and the fragment send policy, +//! shared by both roles. use super::{Counters, MSS_REFRESH, UDP_MSG_HDR}; use mq_runtime::Cx; @@ -45,7 +45,7 @@ impl MssCache { /// Fragments `send_packet` got out and fragments whose `datagram_send` failed. /// Both 0 means nothing was attempted (unusable MSS, or too many fragments); otherwise /// `frags_ok + failed` is the fragment count, so a caller that advances `packet_id` -/// only for a split that ran (C) can tell by `frags_ok + failed > 0`. +/// only for a split that ran can tell by `frags_ok + failed > 0`. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub struct SendOutcome { pub frags_ok: u8, @@ -97,7 +97,7 @@ pub fn send_packet( } }); match res { - // C: a split with at most one surviving fragment adds nothing. + // A split with at most one surviving fragment adds nothing. Ok(()) if out.frags_ok > 1 => c.frags_sent += u32::from(out.frags_ok), Ok(()) => {} Err(SplitError::TooManyFrags) => c.drops_oversize += 1, diff --git a/crates/mq-proxy/src/udp/socks5udp.rs b/crates/mq-proxy/src/udp/socks5udp.rs index 098903b6..ce4eb2ee 100644 --- a/crates/mq-proxy/src/udp/socks5udp.rs +++ b/crates/mq-proxy/src/udp/socks5udp.rs @@ -1,4 +1,4 @@ -//! spec §5: SOCKS5 UDP encapsulation header (RFC 1928 §7) — `mq_socks5_parse_udp_hdr`. +//! spec §5: SOCKS5 UDP encapsulation header (RFC 1928 §7). use mq_runtime::Target; use mq_wire::frames::AddrType; @@ -12,7 +12,7 @@ pub struct Dst<'a> { } /// `RSV u16 | FRAG u8 | ATYP | DST.ADDR | DST.PORT`; returns the payload offset. -/// `None`: short, `RSV != 0`, `FRAG != 0` (C: -2, dropped alike), unknown ATYP. +/// `None`: short, `RSV != 0`, `FRAG != 0` (dropped alike), unknown ATYP. pub fn parse(buf: &[u8]) -> Option<(Dst<'_>, usize)> { let [0, 0, 0, atyp, rest @ ..] = buf else { return None; diff --git a/crates/mq-proxy/tests/backoff.rs b/crates/mq-proxy/tests/backoff.rs index 0e273e9d..a9efa3d1 100644 --- a/crates/mq-proxy/tests/backoff.rs +++ b/crates/mq-proxy/tests/backoff.rs @@ -1,4 +1,4 @@ -//! spec §6.2: reconnect backoff — port of tests/test_backoff.c plus the Rust-side schedule cases. +//! spec §6.2: reconnect backoff schedule. use mq_proxy::client::backoff::{Backoff, backoff_ms}; use mq_runtime::Rng; @@ -8,14 +8,12 @@ use std::time::Duration; const BASE: u64 = 250; const CAP: u64 = 30_000; -// test_backoff.c: test_doubling_sequence #[test] fn doubling_sequence() { let got: Vec = (0..=6).map(|a| backoff_ms(BASE, CAP, a)).collect(); assert_eq!(got, [250, 500, 1000, 2000, 4000, 8000, 16000]); } -// test_backoff.c: test_saturates_at_cap #[test] fn saturates_at_cap() { for a in [7, 8, 10] { @@ -23,7 +21,6 @@ fn saturates_at_cap() { } } -// test_backoff.c: test_no_overflow_large_attempts #[test] fn no_overflow_large_attempts() { assert_eq!(backoff_ms(BASE, CAP, 31), CAP); @@ -31,7 +28,6 @@ fn no_overflow_large_attempts() { assert_eq!(backoff_ms(BASE, CAP, u32::MAX), CAP); } -// test_backoff.c: test_generic #[test] fn generic() { let got = [0, 1, 2, 3, 4, 31].map(|a| backoff_ms(1, 8, a)); diff --git a/crates/mq-proxy/tests/client_gateway_tunnel.rs b/crates/mq-proxy/tests/client_gateway_tunnel.rs index 4a0a79c0..8a84d582 100644 --- a/crates/mq-proxy/tests/client_gateway_tunnel.rs +++ b/crates/mq-proxy/tests/client_gateway_tunnel.rs @@ -282,7 +282,7 @@ fn mp_ready_and_udp_socket_route_to_gateway_paths() { log_capture::take(); h.sh.on_udp_socket(h.now, op, Ok(SocketAddr::new(a, 40000))) .unwrap(); - // C `mq_gw_client.c`: the gateway tunnel's own prefix. + // The gateway tunnel's own prefix. let lines = log_capture::take(); assert!( lines diff --git a/crates/mq-proxy/tests/client_udp_session.rs b/crates/mq-proxy/tests/client_udp_session.rs index d7be5403..69550e24 100644 --- a/crates/mq-proxy/tests/client_udp_session.rs +++ b/crates/mq-proxy/tests/client_udp_session.rs @@ -18,7 +18,7 @@ use std::time::Duration; const ASSOCIATE: &[u8] = &[0x05, 0x03, 0x00, 0x01, 0, 0, 0, 0, 0, 0]; /// Type `0x02` then `UDP_SESSION_OPEN` { sid 1, flags 0, IPv4 10.0.0.9, port 53, idle 0 }. const OPEN_SID1_53: &[u8] = &[ - 0x02, // MQ_STREAM_TYPE_UDP_SESSION + 0x02, // stream type: UDP_SESSION 0x01, // session_id 0x00, // flags 0x01, // address_type = IPv4 diff --git a/crates/mq-proxy/tests/common/mod.rs b/crates/mq-proxy/tests/common/mod.rs index 881698e6..48475579 100644 --- a/crates/mq-proxy/tests/common/mod.rs +++ b/crates/mq-proxy/tests/common/mod.rs @@ -13,7 +13,7 @@ use std::time::Duration; pub const SEED: u64 = 7; -/// C `mq_encode_auth_req` for client_id "mqproxy", token "secret". +/// `AUTH_REQUEST` for client_id "mqproxy", token "secret". pub const AUTH_REQ_C: &[u8] = &[ 0x01, // version 0x07, b'm', b'q', b'p', b'r', b'o', b'x', b'y', // client_id @@ -28,9 +28,9 @@ pub const SOCKS_CONNECT: &[u8] = &[ 0x05, 0x01, 0x00, 0x03, 11, b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'c', b'o', b'm', 0x01, 0xBB, ]; -/// Stream type 0x01 then C `mq_encode_connect_tcp_req` for example.com:443. +/// Stream type 0x01 then `CONNECT_TCP_REQUEST` for example.com:443. pub const CONNECT_REQ_C: &[u8] = &[ - 0x01, // MQ_STREAM_TYPE_CONNECT_TCP + 0x01, // stream type: CONNECT_TCP 0x00, // flags 0x03, // address_type = domain 11, b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'c', b'o', b'm', // host diff --git a/crates/mq-proxy/tests/http_connect.rs b/crates/mq-proxy/tests/http_connect.rs index 52e7d7b0..362ee070 100644 --- a/crates/mq-proxy/tests/http_connect.rs +++ b/crates/mq-proxy/tests/http_connect.rs @@ -1,5 +1,4 @@ -//! spec §6.1: HTTP CONNECT ingress parser — port of tests/test_http_connect.c -//! (`build_200_too_small` excluded: the Rust reply is a `&'static` slice, no caller buffer). +//! spec §6.1: HTTP CONNECT ingress parser. use mq_proxy::ingress::{ HttpConnectParser, INGRESS_CAP, Progress, http_error_reply, http_success_reply, @@ -105,7 +104,7 @@ fn overlong_domain() { parse(format!("CONNECT {host}:443 HTTP/1.1\r\n\r\n").as_bytes()), bad() ); - // 255 is still accepted (MQ_MAX_HOST). + // 255 is still accepted. let host = "a".repeat(255); let req = format!("CONNECT {host}:443 HTTP/1.1\r\n\r\n"); assert_eq!( @@ -201,13 +200,13 @@ fn pipelined_bytes_left_unconsumed() { #[test] fn cap_8k_closes_without_reply() { - // As mq_listener.c:346: a full 8 KiB buffer with no complete head → close, no reply. + // A full 8 KiB buffer with no complete head → close, no reply. let mut buf = b"CONNECT example.com:443 HTTP/1.1\r\n".to_vec(); buf.resize(INGRESS_CAP - 1, b'x'); assert_eq!(parse(&buf), Progress::Need); buf.push(b'x'); assert_eq!(parse(&buf), Progress::Close); - // A terminator past the cap is never seen (C's rxbuf cannot hold it). + // A terminator past the cap is never seen. buf.extend_from_slice(b"\r\n\r\n"); assert_eq!(parse(&buf), Progress::Close); // A head ending exactly at the cap still parses. diff --git a/crates/mq-proxy/tests/metrics_format.rs b/crates/mq-proxy/tests/metrics_format.rs index bf96e487..e28d7e6c 100644 --- a/crates/mq-proxy/tests/metrics_format.rs +++ b/crates/mq-proxy/tests/metrics_format.rs @@ -1,10 +1,8 @@ -//! spec §6.5: `mq.conn` / `mq.path` lines — port of tests/test_metrics_format.c -//! (`test_truncation` excluded: the Rust formatter returns a `String`, nothing truncates). +//! spec §6.5: `mq.conn` / `mq.path` lines. use mq_proxy::metrics::{format_conn_line, format_metrics, format_path_line}; use mq_transport_api::{ConnStats, PathStats}; -// test_metrics_format.c: test_path_line #[test] fn path_line() { let p = PathStats { @@ -34,7 +32,6 @@ fn path_line() { assert!(l2.ends_with("inflight=4096"), "{l2}"); } -// test_metrics_format.c: test_conn_line #[test] fn conn_line() { let st = ConnStats { @@ -61,7 +58,7 @@ fn negative_mp_state_is_signed() { ); } -// mq_conn_dump_stats_cid: the conn line, then one path line per path in order, or a diagnostic. +// The conn line, then one path line per path in order, or a diagnostic. #[test] fn dump_lines_and_diagnostics() { assert_eq!(format_metrics(None), ["mq_conn stats: no connection"]); diff --git a/crates/mq-proxy/tests/origdst.rs b/crates/mq-proxy/tests/origdst.rs index d952b08d..38ca47c1 100644 --- a/crates/mq-proxy/tests/origdst.rs +++ b/crates/mq-proxy/tests/origdst.rs @@ -1,4 +1,4 @@ -//! spec §6.1: transparent capture target — port of tests/test_origdst.c. +//! spec §6.1: transparent capture target. //! `unsupported_family` is covered by mq-linux's `sockaddr_conversion_rejects_unix_family`; //! `short_buffer` has no equivalent (owned `SocketAddr`, no caller buffer). @@ -27,7 +27,7 @@ fn ipv4() { #[test] fn ipv6() { - // IPv4-only in SP1: expectation inverted from the C test. + // IPv4-only in SP1. assert_eq!( target_from_original_dst(&meta(Some("[2001:db8::1]:8080".parse().unwrap()))), None diff --git a/crates/mq-proxy/tests/server_dial.rs b/crates/mq-proxy/tests/server_dial.rs index b2831d9b..118b2892 100644 --- a/crates/mq-proxy/tests/server_dial.rs +++ b/crates/mq-proxy/tests/server_dial.rs @@ -18,14 +18,14 @@ fn dial_error_mapping_table() { (DialError::Refused, 2), // CONN_REFUSED (DialError::Timeout, 3), // TIMEOUT (DialError::Limit, 4), // POLICY_DENIED - (DialError::Other, 2), // CONN_REFUSED, as C maps unclassified errors + (DialError::Other, 2), // CONN_REFUSED: unclassified errors ] { let (s, op) = h.request(c, b""); h.dial_err(op, e); assert_eq!(h.t.sent_bytes(s), connect_resp(1, code), "{e:?}"); } - // An IPv4 address that is not 4 bytes is DNS_FAILED without a dial, as C - // `srv_resolve_target` (answered, not reset). + // An IPv4 address that is not 4 bytes is DNS_FAILED without a dial + // (answered, not reset). let s = h.data(c); h.feed( s, diff --git a/crates/mq-proxy/tests/server_gateway_relay.rs b/crates/mq-proxy/tests/server_gateway_relay.rs index 64f9d342..52a8a6ac 100644 --- a/crates/mq-proxy/tests/server_gateway_relay.rs +++ b/crates/mq-proxy/tests/server_gateway_relay.rs @@ -508,7 +508,7 @@ fn text(b: &[u8]) -> String { String::from_utf8_lossy(b).into_owned() } -/// libcurl parity: Nagle on the origin socket held the second write of a +/// Without TCP_NODELAY, Nagle on the origin socket holds the second write of a /// request behind the origin's delayed ACK (~40 ms per 20 KB upload). #[test] fn origin_dial_sets_nodelay() { diff --git a/crates/mq-proxy/tests/server_harness/mod.rs b/crates/mq-proxy/tests/server_harness/mod.rs index db108ee7..49ab9f07 100644 --- a/crates/mq-proxy/tests/server_harness/mod.rs +++ b/crates/mq-proxy/tests/server_harness/mod.rs @@ -18,13 +18,13 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; -/// Stream type 0x01 then C `mq_encode_connect_tcp_req` for example.com:443. +/// Stream type 0x01 then `CONNECT_TCP_REQUEST` for example.com:443. pub const CONNECT_REQ_C: &[u8] = &[ 0x01, 0x00, 0x03, 11, b'e', b'x', b'a', b'm', b'p', b'l', b'e', b'.', b'c', b'o', b'm', 0x01, 0xBB, 0x00, ]; -/// C `mq_encode_auth_resp` for OK / ERROR+AUTH_FAILED, server_id "mqproxy-server". +/// `AUTH_RESPONSE` for OK / ERROR+AUTH_FAILED, server_id "mqproxy-server". /// `AUTH_OK_C` carries MQ_FEAT_UDP_RELAY (the default config); `AUTH_OK_NO_UDP_C` /// is the `udp_enabled = false` form (features 0). pub const AUTH_OK_C: &[u8] = &[ diff --git a/crates/mq-proxy/tests/server_udp_open.rs b/crates/mq-proxy/tests/server_udp_open.rs index c815b3ac..3348670c 100644 --- a/crates/mq-proxy/tests/server_udp_open.rs +++ b/crates/mq-proxy/tests/server_udp_open.rs @@ -26,7 +26,7 @@ fn open_domain(sid: u32) -> Vec { fn resp_ok(idle_ms: u64) -> Vec { udp_resp(0, 0, idle_ms) } -/// C `srv_open_reject`: an error RESP carries idle 0. +/// An error RESP carries idle 0. fn resp_err(code: u64) -> Vec { udp_resp(1, code, 0) } @@ -160,7 +160,7 @@ fn open_requested_idle_min_with_server() { } } -/// spec §7.1: `Dns` and `Timeout` are both `DnsFailed` (C has no other code). +/// spec §7.1: `Dns` and `Timeout` are both `DnsFailed`. fn resolve_fails_with(e: DialError) { let mut h = H::new(cfg()); let (c, _) = h.authed(); @@ -280,8 +280,8 @@ fn cap_1025_session_limit_before_resolve() { fn undialable_host_dns_failed() { let mut h = H::new(cfg()); let (c, _) = h.authed(); - // An IPv4 address of 3 bytes and a name that is not UTF-8 (C - // `srv_resolve_udp_target`): answered, not reset. + // An IPv4 address of 3 bytes and a name that is not UTF-8: + // answered, not reset. for open in [ udp_open(7, AddrType::Ipv4, &[10, 0, 0], 53, 0), udp_open(8, AddrType::Domain, &[0xFF, 0xFE], 53, 0), diff --git a/crates/mq-proxy/tests/socks5.rs b/crates/mq-proxy/tests/socks5.rs index ddde5c8f..70399adb 100644 --- a/crates/mq-proxy/tests/socks5.rs +++ b/crates/mq-proxy/tests/socks5.rs @@ -1,4 +1,4 @@ -//! spec §6.1: SOCKS5 ingress parser — port of tests/test_socks5.c (SP2 UDP cases excluded). +//! spec §6.1: SOCKS5 ingress parser. use mq_proxy::ingress::{Progress, Socks5Parser, socks5_error_reply, socks5_success_reply}; use mq_runtime::{Host, Target}; @@ -164,7 +164,7 @@ fn request_need_more_every_prefix() { #[test] fn request_cmd_unsupported() { - // C: MQ_SOCKS5_UNSUPPORTED_CMD → mq_listener.c sends REP 0x07 and closes. + // An unsupported command: REP 0x07, then close. assert_eq!( greeted().feed(REQ_CMD_BIND), Progress::Reply { @@ -332,7 +332,7 @@ fn pipelined_bytes_left_unconsumed() { #[test] fn bad_version_closes_without_reply() { - // Bad VER in the greeting or in the request: Close, no reply bytes (mq_socks5.c:25,52). + // Bad VER in the greeting or in the request: Close, no reply bytes. let mut buf = GREETING_BADVER.to_vec(); buf.extend_from_slice(REQ_IPV4); assert_eq!(Socks5Parser::default().feed(&buf), Progress::Close); diff --git a/crates/mq-proxy/tests/udp_defrag.rs b/crates/mq-proxy/tests/udp_defrag.rs index 85744104..f1a88387 100644 --- a/crates/mq-proxy/tests/udp_defrag.rs +++ b/crates/mq-proxy/tests/udp_defrag.rs @@ -1,4 +1,4 @@ -//! spec §2.3: 4-slot LRU datagram defragmenter (C `tests/test_defrag.c` plus the §2.3 additions). +//! spec §2.3: 4-slot LRU datagram defragmenter. use mq_proxy::udp::defrag::{Defrag, Feed}; use mq_wire::udp_msg::UdpMsgHdr; diff --git a/crates/mq-proxy/tests/udp_preopen.rs b/crates/mq-proxy/tests/udp_preopen.rs index d1a4c538..4d39c3e0 100644 --- a/crates/mq-proxy/tests/udp_preopen.rs +++ b/crates/mq-proxy/tests/udp_preopen.rs @@ -1,4 +1,4 @@ -//! spec §7.2: server pre-OPEN datagram buffer (C `srv_preopen_*`). +//! spec §7.2: server pre-OPEN datagram buffer. use mq_proxy::udp::preopen::PreOpen; use mq_proxy::udp::{PREOPEN_BYTES, PREOPEN_DGRAMS, PREOPEN_TTL}; @@ -14,13 +14,13 @@ fn push_evicts_expired_lazily() { assert_eq!(p.push(T0, 1, &[i as u8]), 0); } // All 16 are past the TTL: the new entry sweeps them instead of evicting - // the oldest, and a TTL sweep is not an eviction (C). + // the oldest, and a TTL sweep is not an eviction. let later = T0 + PREOPEN_TTL + Duration::from_millis(1); assert_eq!(p.push(later, 2, &[9]), 0); assert!(p.take(later, 1).is_empty()); assert_eq!(p.take(later, 2), vec![vec![9]]); - // Exactly the TTL old is not expired (C `<=`). + // Exactly the TTL old is not expired. p.push(later, 3, &[3]); p.push(later + PREOPEN_TTL, 4, &[4]); assert_eq!(p.take(later + PREOPEN_TTL, 3), vec![vec![3]]); @@ -93,7 +93,7 @@ fn take_applies_ttl_without_intervening_push() { let mut p = PreOpen::default(); p.push(T0, 1, &[1]); p.push(T0, 2, &[2]); - // The TTL is inclusive (C `<=`). + // The TTL is inclusive. assert_eq!(p.take(T0 + PREOPEN_TTL, 1), vec![vec![1]]); let late = T0 + Duration::from_millis(300); assert!(p.take(late, 2).is_empty()); diff --git a/crates/mq-proxy/tests/udp_send.rs b/crates/mq-proxy/tests/udp_send.rs index b605a933..c5c3f786 100644 --- a/crates/mq-proxy/tests/udp_send.rs +++ b/crates/mq-proxy/tests/udp_send.rs @@ -1,4 +1,4 @@ -//! spec §5: datagram MSS cache and the C fragment send policy (`send_packet`). +//! spec §5: datagram MSS cache and the fragment send policy (`send_packet`). mod common; @@ -177,7 +177,7 @@ fn single_fragment_and_empty_payload() { h.t.datagram_sends(h.conn), vec![cat(hdr(1, 0, 1), b"abc"), hdr(2, 0, 1)] ); - // unfragmented packets never add to frags_sent (C) + // unfragmented packets never add to frags_sent assert_eq!(c, Counters::default()); } diff --git a/crates/mq-proxy/tests/udp_socks5udp.rs b/crates/mq-proxy/tests/udp_socks5udp.rs index 040bafa1..3d5f65cf 100644 --- a/crates/mq-proxy/tests/udp_socks5udp.rs +++ b/crates/mq-proxy/tests/udp_socks5udp.rs @@ -133,7 +133,7 @@ fn target_of_maps_each_atype() { #[test] fn target_of_empty_domain_is_none() { - // parse accepts a zero-length domain (as C); only the Target conversion refuses it. + // parse accepts a zero-length domain; only the Target conversion refuses it. let (dst, off) = parse(&[0, 0, 0, 0x03, 0, 0x00, 0x50]).unwrap(); assert_eq!((dst.addr.len(), off), (0, 7)); assert_eq!(target_of(&dst), None); diff --git a/crates/mq-runtime/src/app.rs b/crates/mq-runtime/src/app.rs index 4e7076b5..3ebedc6e 100644 --- a/crates/mq-runtime/src/app.rs +++ b/crates/mq-runtime/src/app.rs @@ -117,7 +117,7 @@ pub enum IoRequest { TcpShutdownWrite { tcp: TcpId, }, - /// `TCP_NODELAY` on the socket (SP3: the origin bridge, libcurl parity). + /// `TCP_NODELAY` on the socket (SP3: the origin bridge). TcpSetNodelay { tcp: TcpId, }, diff --git a/crates/mq-runtime/src/driver/core.rs b/crates/mq-runtime/src/driver/core.rs index b3661a69..a430e5af 100644 --- a/crates/mq-runtime/src/driver/core.rs +++ b/crates/mq-runtime/src/driver/core.rs @@ -269,7 +269,7 @@ impl LoopCore { return Next::Exit(code); } if self.cap_hit { - return Next::Exit(0); // spec §5.3: exit 0 after a signal, as C does + return Next::Exit(0); // spec §5.3: exit 0 after a signal } // 10. self.next_wait = if self.runnable() { @@ -542,7 +542,7 @@ impl LoopCore { } => { self.deadlines.set(Expired::Dial(op), now + deadline); match target.host { - // C resolves only domains (mq_server.c:441). + // Only domains are resolved. Host::Ip(ip) => { let a = SocketAddr::new(ip, target.port); self.dials.insert(op, DialState::Connecting(a)); @@ -683,7 +683,7 @@ impl LoopCore { } } -/// spec §5.3 `io::Error → DialError` (C `srv_map_errno`) for connects; +/// spec §5.3 `io::Error → DialError` for connects; /// resolve failures are `Dns`, the deadline `Timeout`, `Limit` only the cap. fn connect_error(e: &io::Error) -> DialError { match e.kind() { diff --git a/crates/mq-runtime/tests/relay.rs b/crates/mq-runtime/tests/relay.rs index 7e954e61..edc6ab6e 100644 --- a/crates/mq-runtime/tests/relay.rs +++ b/crates/mq-runtime/tests/relay.rs @@ -1,10 +1,10 @@ //! spec §5.6: the flow relay, driven by `ScriptedTransport` on the QUIC side //! and `FakeTcp` (which applies commits the way the driver does) on the TCP side. //! -//! Mapping of `tests/test_relay.c` (side A = TCP, side B = the QUIC stream): -//! `happy_both_directions`, `backpressure`, `eof_one_side` (inverted: half-close -//! keeps the other direction open), `hard_error` (B's writer = `stream_send`), -//! `read_hard_error`, `read_would_block_chunked`, `data_and_eof_same_read`. +//! Side A = TCP, side B = the QUIC stream: `happy_both_directions`, +//! `backpressure`, `eof_one_side` (half-close keeps the other direction open), +//! `hard_error` (B's writer = `stream_send`), `read_hard_error`, +//! `read_would_block_chunked`, `data_and_eof_same_read`. use mq_runtime::testing::{Call, ScriptedHandle, ScriptedTransport}; use mq_runtime::{ @@ -217,7 +217,7 @@ const NONE: Interest = Interest { write: false, }; -// ---- the seven cases of tests/test_relay.c ---- +// ---- the seven relay cases ---- #[test] fn happy_both_directions() { @@ -260,7 +260,7 @@ fn backpressure() { #[test] fn eof_one_side() { - // Inverted from C: TCP EOF sends FIN but the relay stays open. + // TCP EOF sends FIN but the relay stays open. let (mut t, h, s) = setup(); let mut r = relay(&h, s); let mut tcp = FakeTcp::new(b"hi").eof_after(2); diff --git a/crates/mq-transport-api/src/ringbuf.rs b/crates/mq-transport-api/src/ringbuf.rs index 9420e6bf..8af993c5 100644 --- a/crates/mq-transport-api/src/ringbuf.rs +++ b/crates/mq-transport-api/src/ringbuf.rs @@ -1,5 +1,5 @@ //! The relay's byte buffer (SP0/SP1 spec §5.6), also the transport's datagram receive ring -//! (SP2 spec §3.2): a port of `src/util/mq_buf.c`. +//! (SP2 spec §3.2). //! //! Linear, not wrapping: `space()` is the tail room after the write cursor, and //! both cursors return to 0 when everything written has been consumed. diff --git a/crates/mq-transport/src/conn.rs b/crates/mq-transport/src/conn.rs index d6245ed1..f2aa2dd6 100644 --- a/crates/mq-transport/src/conn.rs +++ b/crates/mq-transport/src/conn.rs @@ -119,7 +119,7 @@ pub(crate) fn connect( ConnProto::Raw => t.inner.alpn.as_ptr(), ConnProto::H3 => c"h3".as_ptr(), }; - // SAFETY: a plain C struct; all-zero is valid and what C passes. + // SAFETY: a plain C struct; all-zero is valid. let zero_cid: xqc_cid_t = unsafe { core::mem::zeroed() }; let s = t .inner @@ -269,7 +269,7 @@ pub(crate) fn add_path( let mut pid = 0u64; // SAFETY: the engine is live; the cid and `pid` outlive the calls. unsafe { - // 0 = AVAILABLE; the status is then set explicitly, as in C. + // 0 = AVAILABLE; the status is then set explicitly. let r = xqc_conn_create_path(engine, &cid, &mut pid, 0); if r == -(XQC_EMP_NO_AVAIL_PATH_ID as xqc_int_t) { return Err(PathError::NoPathId); diff --git a/crates/mq-transport/src/datagram.rs b/crates/mq-transport/src/datagram.rs index 9e77812a..01067b40 100644 --- a/crates/mq-transport/src/datagram.rs +++ b/crates/mq-transport/src/datagram.rs @@ -53,7 +53,7 @@ pub(crate) fn datagram_send( if r < 0 { Err(dgram_err(r)) } else { Ok(()) } } -/// SP2 spec §3.1: as C `mq_conn_datagram_mss` — the min over active paths, re-read per call. +/// SP2 spec §3.1: the min over active paths, re-read per call. pub(crate) fn datagram_mss(t: &Transport, c: ConnId) -> usize { let Some(xqc) = xqc_of(t, c) else { return 0; diff --git a/crates/mq-transport/src/engine.rs b/crates/mq-transport/src/engine.rs index 29d8b476..022fb9d0 100644 --- a/crates/mq-transport/src/engine.rs +++ b/crates/mq-transport/src/engine.rs @@ -10,7 +10,7 @@ use std::io::Write; use std::time::Duration; use xquic_sys::*; -/// Connection settings (spec §4.9), built from a zeroed struct like C's `memset`. +/// Connection settings (spec §4.9), built from a zeroed struct. /// `idle` is the client's `--keepalive-idle`; the server passes `None`. /// spec §7: live skipped-id entries a peer may make xquic hold per connection. pub(crate) const MAX_IMPLICIT_STREAMS: u64 = 16384; @@ -21,7 +21,7 @@ pub const H3_FIELD_SECTION_MAX: usize = 64 * 1024; pub(crate) fn conn_settings(cfg: &TransportConfig, idle: Option) -> xqc_conn_settings_t { let server = matches!(cfg.role, Role::Server { .. }); // SAFETY: a plain C struct of integers, floats, arrays and Option fields; all-zero is - // valid and is exactly what the C version starts from. + // valid. let mut s: xqc_conn_settings_t = unsafe { core::mem::zeroed() }; s.proto_version = XQC_VERSION_V1; s.pacing_on = 1; @@ -231,7 +231,7 @@ unsafe extern "C" fn set_event_timer(wake_after: xqc_usec_t, _ud: *mut c_void) { }) } -/// xquic logs → `log` with the C level mapping (`mq_transport_log_write`). +/// xquic logs → `log`, with xquic's levels mapped onto `log::Level`. unsafe extern "C" fn log_write( lvl: xqc_log_level_t, buf: *const c_void, @@ -254,7 +254,7 @@ unsafe extern "C" fn log_write( }) } -/// qlog sink (`mq_transport_qlog_write`): the line plus a newline, only while a file is open. +/// qlog sink: the line plus a newline, only while a file is open. unsafe extern "C" fn qlog_write( _imp: qlog_event_importance_t, buf: *const c_void, @@ -270,7 +270,7 @@ unsafe extern "C" fn qlog_write( unsafe { if let Some(f) = (*inner).qlog.as_mut() { let line = core::slice::from_raw_parts(buf.cast::(), size); - // Best effort, as in C. + // Best effort. let _ = f.write_all(line).and_then(|()| f.write_all(b"\n")); } } @@ -324,15 +324,15 @@ mod tests { }; assert_eq!(bytes(&s.cong_ctrl_callback), bytes(&want_cc)); assert_eq!(bytes(&s.scheduler_callback), bytes(&want_sched)); - // Left at the xquic default (zero = "use default"), as in C. + // Left at the xquic default (zero = "use default"). assert_eq!(s.max_streams_bidi, 0); assert_eq!(s.init_idle_time_out, 0); assert_eq!(s.enable_stream_rate_limit, 0); assert_eq!(s.init_recv_window, 0); - assert_eq!(s.cc_params.customize_on, 0, "cc_params zeroed, as in C"); + assert_eq!(s.cc_params.customize_on, 0, "cc_params zeroed"); } - /// Ports `test_sched` (spec §8.3): each scheduler selects its own xquic callback table, + /// spec §8.3: each scheduler selects its own xquic callback table, /// on both roles. (Parsing the `--scheduler` names belongs to the config crate.) #[test] fn sched_selects_callback() { diff --git a/crates/mq-transport/src/ffi/mod.rs b/crates/mq-transport/src/ffi/mod.rs index 9615ef05..b46e43e7 100644 --- a/crates/mq-transport/src/ffi/mod.rs +++ b/crates/mq-transport/src/ffi/mod.rs @@ -87,7 +87,7 @@ pub(crate) fn app_proto_callbacks(proto: ConnProto) -> xqc_app_proto_callbacks_t // ── callbacks with no state ───────────────────────────────────────────── -/// spec §4.7: accept any certificate (as the C client does). +/// spec §4.7: accept any certificate. unsafe extern "C" fn cert_verify( _certs: *mut *const c_uchar, _cert_len: *const usize, @@ -101,10 +101,10 @@ unsafe extern "C" fn cert_verify( /// the facade does not rely on the fork's null check. unsafe extern "C" fn datagram_write_notify(_conn: *mut xqc_connection_t, _ud: *mut c_void) {} -/// No resumption store, as in C. +/// No resumption store. unsafe extern "C" fn save_token(_token: *const c_uchar, _len: u32, _ud: *mut c_void) {} -/// `save_session_cb` and `save_tp_cb`: no-ops, as in C. +/// `save_session_cb` and `save_tp_cb`: no-ops. unsafe extern "C" fn save_string(_data: *const c_char, _len: usize, _ud: *mut c_void) {} // ── socket addresses ──────────────────────────────────────────────────── diff --git a/crates/mq-transport/tests/fabric_conn_cap.rs b/crates/mq-transport/tests/fabric_conn_cap.rs index 6f763b31..c6485623 100644 --- a/crates/mq-transport/tests/fabric_conn_cap.rs +++ b/crates/mq-transport/tests/fabric_conn_cap.rs @@ -1,4 +1,4 @@ -//! Ports `test_max_conns` (spec §8.3, §4.7): with `max_conns = 1` a second client is refused +//! Spec §8.3, §4.7: with `max_conns = 1` a second client is refused //! in `server_accept`; after the first connection is destroyed a third client connects; //! `conn_count()` follows. mod common; diff --git a/crates/mq-transport/tests/fabric_qlog.rs b/crates/mq-transport/tests/fabric_qlog.rs index 6a40cc91..013aa8da 100644 --- a/crates/mq-transport/tests/fabric_qlog.rs +++ b/crates/mq-transport/tests/fabric_qlog.rs @@ -1,4 +1,4 @@ -//! Ports `test_qlog_blocked` (spec §8.3, §4.9): a handshake plus an unblocked download; +//! Spec §8.3, §4.9: a handshake plus an unblocked download; //! `/client.qlog` holds frame events and no DATA_BLOCKED / STREAM_DATA_BLOCKED frames. mod common; diff --git a/crates/mq-transport/tests/fabric_transport_fabric.rs b/crates/mq-transport/tests/fabric_transport_fabric.rs index a78028d2..7410b421 100644 --- a/crates/mq-transport/tests/fabric_transport_fabric.rs +++ b/crates/mq-transport/tests/fabric_transport_fabric.rs @@ -1,9 +1,6 @@ -//! Ports `test_transport_fabric` and `test_conn_handshake` (spec §8.3): a full handshake and -//! a stream echo with FIN both ways, entirely in memory; per-connection `MpReady` with two -//! connections on one client transport, one of which then closes. -//! -//! Not ported: the C mp-ready subscriber table (`mq_transport_add/remove_mp_ready_cb`) and its -//! capacity tests — the facade has no subscriber table; `MpReady` carries the connection id. +//! Spec §8.3: a full handshake and a stream echo with FIN both ways, entirely in memory; +//! per-connection `MpReady` with two connections on one client transport, one of which then +//! closes. There is no mp-ready subscriber table; `MpReady` carries the connection id. mod common; use common::pair::{MS, Pair, conn_cfg, new_streams, recv, send}; @@ -11,7 +8,7 @@ use mq_transport_api::{ConnId, Event, StreamKind, TransportOps}; const PAYLOAD: &[u8] = b"the quick brown fox jumps over the lazy dog"; -/// `test_conn_handshake`: handshake, `NewConn`, one client stream seen by the server, close, +/// Handshake, `NewConn`, one client stream seen by the server, close, /// teardown. #[test] fn conn_handshake() { @@ -39,7 +36,7 @@ fn conn_handshake() { // Teardown: the peers drop their transports on their own threads. } -/// `test_transport_fabric`: the server echoes the client's payload with FIN; byte integrity +/// The server echoes the client's payload with FIN; byte integrity /// and a clean FIN in both directions. #[test] fn stream_echo_round_trip() { @@ -72,7 +69,7 @@ fn mp_ready(ev: &[Event], c: ConnId) -> bool { ev.contains(&Event::MpReady(c)) } -/// `test_mp_ready_broadcast`: each connection gets its own `MpReady`; closing one leaves the +/// Each connection gets its own `MpReady`; closing one leaves the /// other working. #[test] fn mp_ready_per_connection_and_close_one_keep_one() { diff --git a/crates/mq-transport/tests/fabric_two_paths.rs b/crates/mq-transport/tests/fabric_two_paths.rs index c2b0903d..172322ad 100644 --- a/crates/mq-transport/tests/fabric_two_paths.rs +++ b/crates/mq-transport/tests/fabric_two_paths.rs @@ -1,5 +1,4 @@ -//! Ports `test_two_paths` and the address assertions of `test_path_bind` (spec §8.3), plus -//! spec §4.2 "MpReady may repeat". +//! Two paths and their per-path addresses (spec §8.3), plus spec §4.2 "MpReady may repeat". mod common; use common::pair::{ @@ -69,7 +68,7 @@ fn second_path_comes_up_and_carries_traffic() { "sent {sent} recv {recv}" ); - // Addresses (test_path_bind): each path keeps its own 4-tuple on both sides. + // Addresses: each path keeps its own 4-tuple on both sides. let srv_key_path1 = |d: &&common::lockstep::Datagram| d.key.1 == pid && d.from == srv_addr(); assert!( p.wire.iter().any(|d| d.from == cli_addr(1)), diff --git a/crates/mq-wire/src/frames.rs b/crates/mq-wire/src/frames.rs index c9c109fe..e3e13968 100644 --- a/crates/mq-wire/src/frames.rs +++ b/crates/mq-wire/src/frames.rs @@ -1,11 +1,11 @@ -// spec §2.3; mirrors src/wire/mq_wire.c +// spec §2.3 //! AUTH, CONNECT_TCP and UDP_SESSION control frames. All fixed ints are //! big-endian; a `string` is a varint length + raw bytes. Decoders are strict //! (truncation → `Short`, over-cap field / bad address type → `BadValue`), //! accept non-minimal varints, skip trailing padding, and keep `status` / //! `error_code` raw. Encoders never allocate and always write //! `padding_length = 0`. The UDP_SESSION frames additionally validate -//! semantics on both sides, as the C codec does (spec §2.1): `Invalid` on +//! semantics on both sides (spec §2.1): `Invalid` on //! decode, `EncodeError::BadValue` on encode. use crate::varint; @@ -67,7 +67,7 @@ impl TcpErr { } /// Wire `error_code` of a `UDP_SESSION_RESP` with `STATUS_ERROR` (spec §2.1). -/// C's boundary-only `MQ_UDP_CLOSED` (5) never appears on the wire and has no variant. +/// Code 5 (boundary-only "closed") never appears on the wire and has no variant. #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub enum UdpErr { DnsFailed = 1, @@ -119,7 +119,7 @@ pub enum DecodeError { pub enum EncodeError { Short, TooLong, - /// varint > 2^62-1, or a `UdpSessionResp` status / error_code pair the C codec rejects + /// varint > 2^62-1, or a `UdpSessionResp` status / error_code pair that is inconsistent BadValue, } @@ -203,7 +203,7 @@ impl ConnectTcpResp<'_> { } } -// ---- private cursors mirroring the C put_*/get_* helpers ---- +// ---- private cursors ---- struct Cursor<'a> { buf: &'a [u8], @@ -394,7 +394,7 @@ impl<'a> UdpSessionOpen<'a> { w.finish() } - // spec §2.1: sid > u32 and an unknown address type are rejected as soon as read, as in C. + // spec §2.1: sid > u32 and an unknown address type are rejected as soon as read. pub fn decode(buf: &'a [u8]) -> Result<(Self, usize), DecodeError> { let mut r = Cursor::new(buf); let session_id = u32::try_from(r.varint()?).map_err(|_| DecodeError::Invalid)?; @@ -412,7 +412,7 @@ impl<'a> UdpSessionOpen<'a> { } } -/// C `udp_err_valid_for_wire` + `udp_status_err_consistent`: OK <=> code 0, ERROR <=> code 1..=4. +/// OK <=> code 0, ERROR <=> code 1..=4. fn udp_status_code_valid(status: u8, error_code: u64) -> bool { matches!((status, error_code), (STATUS_OK, 0) | (STATUS_ERROR, 1..=4)) } @@ -431,7 +431,7 @@ impl<'a> UdpSessionResp<'a> { w.finish() } - // spec §2.1: the status / error_code pairing is checked before the message is read, as in C. + // spec §2.1: the status / error_code pairing is checked before the message is read. pub fn decode(buf: &'a [u8]) -> Result<(Self, usize), DecodeError> { let mut r = Cursor::new(buf); let status = r.u8()?; diff --git a/crates/mq-wire/src/udp_msg.rs b/crates/mq-wire/src/udp_msg.rs index 07805f05..9e52b448 100644 --- a/crates/mq-wire/src/udp_msg.rs +++ b/crates/mq-wire/src/udp_msg.rs @@ -1,4 +1,4 @@ -// spec §2.2; mirrors src/wire/mq_udp_msg.c +// spec §2.2 //! The fixed 9-byte header that prefixes every UDP payload carried in a QUIC //! DATAGRAM frame (all big-endian) and the pure fragment split. Nothing here //! allocates; `split` hands out slices that borrow the caller's payload. diff --git a/crates/mq-wire/src/varint.rs b/crates/mq-wire/src/varint.rs index 2077a9ca..a7f9a396 100644 --- a/crates/mq-wire/src/varint.rs +++ b/crates/mq-wire/src/varint.rs @@ -1,4 +1,4 @@ -// spec §2.3; mirrors src/wire/mq_varint.c +// spec §2.3 pub const MAX: u64 = 0x3FFF_FFFF_FFFF_FFFF; #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/crates/mq-wire/tests/frames.rs b/crates/mq-wire/tests/frames.rs index 59cf4a21..6a751f08 100644 --- a/crates/mq-wire/tests/frames.rs +++ b/crates/mq-wire/tests/frames.rs @@ -1,4 +1,4 @@ -// spec §2.3; ports the non-UDP cases of tests/test_wire.c +// spec §2.3 use mq_wire::frames::*; use mq_wire::varint; use proptest::prelude::*; @@ -98,7 +98,7 @@ fn connect_tcp_resp_roundtrip() { } } -// ---- test_truncation (C covers AUTH_REQUEST; extended to all four frames) ---- +// ---- truncation, all four frames ---- #[test] fn truncation() { let ar = AuthReq { @@ -194,7 +194,7 @@ fn padding_skipped() { ); } -// ---- test_padding_overflow (C covers CONNECT_TCP_REQUEST; extended to all four) ---- +// ---- padding overflow, all four frames ---- #[test] fn padding_overflow() { let buf = [0x00, 0x01, 0x04, 1, 2, 3, 4, 0x00, 0x50, 0x40, 99]; @@ -594,7 +594,7 @@ fn constants() { } // ---- UDP_SESSION_OPEN / UDP_SESSION_RESP (spec §2.1; unlike the TCP frames, both -// sides validate semantics as src/wire/mq_wire.c does) ---- +// sides validate semantics) ---- fn udp_open(at: AddrType, host: &[u8]) -> UdpSessionOpen<'_> { UdpSessionOpen { session_id: 0xDEAD_BEEF, @@ -693,7 +693,7 @@ fn udp_resp_rejects_code_5() { UdpSessionResp::decode(&[0x01, 0x40, 0x64, 0x00, 0x00, 0x00]), Err(DecodeError::Invalid) ); - // C checks the pairing before the message: Invalid wins over a truncated or over-long message. + // The pairing is checked before the message: Invalid wins over a truncated or over-long message. assert_eq!( UdpSessionResp::decode(&[0x01, 0x05]), Err(DecodeError::Invalid) @@ -752,7 +752,7 @@ fn udp_resp_encode_rejects_inconsistent() { assert_eq!(udp_resp(0x02, 0, b"").encode(&mut b), e); // a code that is not a valid varint is rejected the same way assert_eq!(udp_resp(STATUS_ERROR, BIG, b"").encode(&mut b), e); - // the semantic check precedes the buffer check, as in C + // the semantic check precedes the buffer check assert_eq!(udp_resp(STATUS_OK, 1, b"").encode(&mut b[..0]), e); } diff --git a/crates/mq-wire/tests/udp_msg.rs b/crates/mq-wire/tests/udp_msg.rs index 294009c0..ca49dc33 100644 --- a/crates/mq-wire/tests/udp_msg.rs +++ b/crates/mq-wire/tests/udp_msg.rs @@ -1,4 +1,4 @@ -// spec §2.2; ports tests/test_udp_msg.c +// spec §2.2 use mq_wire::udp_msg::*; /// Collects (header, slice length) per fragment. diff --git a/crates/mq-wire/tests/varint.rs b/crates/mq-wire/tests/varint.rs index 02b07499..95469b40 100644 --- a/crates/mq-wire/tests/varint.rs +++ b/crates/mq-wire/tests/varint.rs @@ -1,4 +1,4 @@ -// spec §2.3; ports tests/test_varint.c +// spec §2.3 use mq_wire::varint::{Error, MAX, decode, encode, len}; use proptest::prelude::*; diff --git a/crates/mqproxy/src/cli.rs b/crates/mqproxy/src/cli.rs index 4739a2cd..cd85aecf 100644 --- a/crates/mqproxy/src/cli.rs +++ b/crates/mqproxy/src/cli.rs @@ -1,4 +1,4 @@ -//! spec §6.4: the C-identical command line (cli/main.c `usage_*`, `longopts`). +//! spec §6.4: the command line. //! `parse` turns argv into a fully resolved `Resolved` or an `Exit`. use crate::config::{self, FileConfig}; @@ -15,7 +15,7 @@ use std::path::PathBuf; use std::sync::Arc; use std::time::Duration; -/// C `MQ_MAX_EXTRA_PATHS`. +/// The most `--path` entries kept; extras warn and are ignored. const MAX_PATHS: usize = 8; /// xquic's client PING interval (fixed); an idle timeout at or below it still closes. const XQUIC_PING_SECS: u64 = 15; @@ -318,7 +318,7 @@ fn usage_error(sub: &str, msg: String) -> Exit { } } -// spec §6.4: each value below is `CLI.or(file)`, then the C default. +// spec §6.4: each value below is `CLI.or(file)`, then the default. fn server(a: ServerArgs, f: FileConfig) -> Result { let mut warnings = f.warnings; // spec §8: default on; `--no-gateway` only ever turns the file's value off. @@ -330,8 +330,8 @@ fn server(a: ServerArgs, f: FileConfig) -> Result { request_metrics, ..GatewayConfig::default() }); - // C's order: request-metrics, cache, masquerade; the gateway-only two are - // warned and ignored with the gateway off (C text). + // Warning order: request-metrics, cache, masquerade; the gateway-only two are + // warned and ignored with the gateway off. let off = gateway.is_none(); if off && request_metrics { warnings.push( @@ -376,7 +376,7 @@ fn server(a: ServerArgs, f: FileConfig) -> Result { config: ServerConfig { token, metrics_interval: metrics_interval(a.metrics_interval, f.metrics_interval), - // `--no-udp` only ever turns the file's value off (C: it clears the flag). + // `--no-udp` only ever turns the file's value off. udp_enabled: !a.no_udp && f.udp_enabled.unwrap_or(true), udp_idle_timeout: a .udp_idle_timeout @@ -388,7 +388,7 @@ fn server(a: ServerArgs, f: FileConfig) -> Result { listen, cert: cert.into(), key: key.into(), - max_conns: a.max_conns.or(f.max_conns).unwrap_or(16), // C default + max_conns: a.max_conns.or(f.max_conns).unwrap_or(16), }), config: a.config, qlog: a.qlog.or(f.qlog), @@ -436,7 +436,7 @@ fn client(a: ClientArgs, f: FileConfig) -> Result { .map_err(|_| format!("invalid --path address: {p}"))?, ); } - // C default 30; 0 disables the idle timeout (and so the PINGs). + // Default 30; 0 disables the idle timeout (and so the PINGs). let ka = a.keepalive_idle.or(f.keepalive_idle).unwrap_or(30); let keepalive_idle = (ka > 0).then(|| Duration::from_secs(ka)); if (1..=XQUIC_PING_SECS).contains(&ka) { @@ -446,7 +446,7 @@ fn client(a: ClientArgs, f: FileConfig) -> Result { ka )); } - // C's validation order: server, socks5, http-connect, gateway, tproxy. + // Validation order: server, socks5, http-connect, gateway, tproxy. let server = ip_port("--server", &server)?; let socks5 = opt("--socks5", socks5)?; let http_connect = opt("--http-connect", http_connect)?; @@ -456,7 +456,7 @@ fn client(a: ClientArgs, f: FileConfig) -> Result { // settings are accepted and never looked at. let mitm = (a.mitm || f.mitm) .then(|| { - // File entries first, then the flags (the comma form skips empty tokens, as in C). + // File entries first, then the flags (the comma form skips empty tokens). let ignore = f.ignore_hosts.into_iter().chain(a.ignore_host).chain( a.ignore_hosts .into_iter() @@ -501,7 +501,7 @@ fn client(a: ClientArgs, f: FileConfig) -> Result { http_connect, tproxy, tproxy_mode, - // C defaults: fwmark 1, table 100, dport 443, uid = geteuid(). + // Defaults: fwmark 1, table 100, dport 443, uid = geteuid(). tproxy_fwmark: a.tproxy_fwmark.or(f.tproxy_fwmark).unwrap_or(1), tproxy_table: a.tproxy_table.or(f.tproxy_table).unwrap_or(100), tproxy_dport: a.tproxy_dport.or(f.tproxy_dport).unwrap_or(443), @@ -546,12 +546,12 @@ fn mitm_config( }) } -/// `--metrics-interval`, else the file's `[Metrics] Interval` (0 = off, as in C). +/// `--metrics-interval`, else the file's `[Metrics] Interval` (0 = off). fn metrics_interval(cli: Option, file: Option) -> Option { cli.or(file.filter(|&s| s > 0)).map(Duration::from_secs) } -/// C `mq_cc_from_string`: exact, case-sensitive. +/// Exact, case-sensitive. pub fn cc(s: Option<&str>) -> Result { match s { None | Some("bbr") => Ok(CongestionControl::Bbr), @@ -561,7 +561,7 @@ pub fn cc(s: Option<&str>) -> Result { } } -/// C `mq_sched_from_string`: exact, case-sensitive. +/// Exact, case-sensitive. pub fn scheduler(s: Option<&str>) -> Result { match s { None | Some("minrtt") => Ok(Scheduler::MinRtt), @@ -571,7 +571,7 @@ pub fn scheduler(s: Option<&str>) -> Result { } } -/// C `parse_ip_port`: `[v6]:port`, or `ip:port` split at the last ':'; port 1..=65535. +/// `[v6]:port`, or `ip:port` split at the last ':'; port 1..=65535. pub fn ip_port(flag: &str, s: &str) -> Result { let split = match s.strip_prefix('[') { Some(rest) => rest.split_once("]:"), @@ -594,7 +594,7 @@ pub fn wants_h3(r: &Resolved) -> bool { } } -/// spec §8: `MQ_GW_ORIGIN_CONNECT_TIMEOUT_S` (test-only, as C): an integer in +/// spec §8: `MQ_GW_ORIGIN_CONNECT_TIMEOUT_S` (test-only): an integer in /// [1, 600], else 10 s (not clamped). `main` reads the variable. pub fn origin_connect_timeout(env: Option<&str>) -> Duration { let s = env diff --git a/crates/mqproxy/src/config.rs b/crates/mqproxy/src/config.rs index db306786..ae830879 100644 --- a/crates/mqproxy/src/config.rs +++ b/crates/mqproxy/src/config.rs @@ -1,5 +1,4 @@ -//! spec §6.4 "Config file": C `mq_config_load` — the typed values an INI file -//! sets. `cli` layers the command line on top (defaults < file < CLI). Text +//! spec §6.4 "Config file": the typed values an INI file sets. `cli` layers the command line on top (defaults < file < CLI). Text //! values (`CC`, `Scheduler`, addresses, `[Ingress] Mode`, `Path`) are kept as //! text and validated by `cli` at startup, exactly like the flag values. @@ -8,7 +7,7 @@ use crate::ini::{self, Line}; use std::os::unix::fs::PermissionsExt; use std::path::{Path, PathBuf}; -/// C `parse_section` names (compared case-insensitively). +/// Section names (compared case-insensitively). const SECTIONS: &[&str] = &[ "Interface", "Server", @@ -33,7 +32,7 @@ pub struct FileConfig { pub cc: Option, pub scheduler: Option, pub qlog: Option, - /// 0 = off, as in C. + /// 0 = off. pub metrics_interval: Option, // server pub listen: Option, @@ -63,7 +62,7 @@ pub struct FileConfig { pub tproxy_table: Option, pub tproxy_dport: Option, pub setup_redirect: bool, - /// `SkipUid = -1` (C's "use geteuid()") is `None`. + /// `SkipUid = -1` ("use geteuid()") is `None`. pub tproxy_uid: Option, pub mitm: bool, pub ca_cert: Option, @@ -71,7 +70,7 @@ pub struct FileConfig { pub ignore_hosts: Vec, } -/// C `parse_bool`: exact `true`, `yes`, `1`. +/// Exact `true`, `yes`, `1`. fn bool_(v: &str) -> bool { matches!(v, "true" | "yes" | "1") } @@ -85,7 +84,7 @@ pub fn load(path: Option<&Path>, server: bool) -> Result { code: 2, message: format!("error: config: cannot open '{}': {e}\n", path.display()), })?; - // C `mq_config_perms_insecure`: any group/other bit. + // Insecure: any group/other bit. if std::fs::metadata(path).is_ok_and(|m| m.permissions().mode() & 0o077 != 0) { f.warnings.push(format!( "config {} is group/world-readable; chmod 0600 to protect the token", @@ -126,7 +125,7 @@ pub fn load(path: Option<&Path>, server: bool) -> Result { } impl FileConfig { - /// C LONGV: an integer in `lo..=hi`, else warn and keep the previous value. + /// An integer in `lo..=hi`, else warn and keep the previous value. fn num(&mut self, at: &str, k: &str, v: &str, lo: i64, hi: i64) -> Option { let n = v.parse::().ok().filter(|n| (lo..=hi).contains(n)); if n.is_none() { @@ -137,7 +136,7 @@ impl FileConfig { n } - /// C `handle_kv`. `sec` is canonical, `key` lower-cased; `k` is the key as written. + /// Applies one key: `sec` is canonical, `key` lower-cased; `k` is the key as written. /// Returns false if the key is unknown for this mode. fn set(&mut self, at: &str, sec: &str, key: &str, k: &str, v: &str, server: bool) -> bool { let (s, c) = (server, !server); diff --git a/crates/mqproxy/src/ini.rs b/crates/mqproxy/src/ini.rs index 61891b86..de72140b 100644 --- a/crates/mqproxy/src/ini.rs +++ b/crates/mqproxy/src/ini.rs @@ -1,4 +1,4 @@ -//! spec §6.4: the INI scanner of C `mq_config_load` — `[Section]` headers, +//! spec §6.4: the INI scanner — `[Section]` headers, //! `Key = Value` lines, `#`/`;` comments, whitespace trimmed. Names are //! returned as written (the caller compares them case-insensitively). @@ -6,7 +6,7 @@ #[derive(Debug, PartialEq, Eq)] pub enum Line<'a> { Section(&'a str), - /// The value is non-empty: C treats an empty value as not set and skips it. + /// The value is non-empty: an empty value counts as not set and is skipped. Kv(&'a str, &'a str), /// A warning text (malformed header or a line without `=`). Malformed(&'static str), @@ -18,7 +18,7 @@ pub fn lines(text: &str) -> impl Iterator)> { let line = if t.is_empty() || t.starts_with(['#', ';']) { return None; } else if let Some(h) = t.strip_prefix('[') { - // C: everything after the first ']' is ignored. + // Everything after the first ']' is ignored. match h.split_once(']') { Some((name, _)) => Line::Section(name), None => Line::Malformed("malformed section header"), diff --git a/crates/mqproxy/src/logger.rs b/crates/mqproxy/src/logger.rs index 623b2077..5bf03ea8 100644 --- a/crates/mqproxy/src/logger.rs +++ b/crates/mqproxy/src/logger.rs @@ -1,5 +1,4 @@ -//! spec §6.5: C `mq_log` (`src/util/mq_log.c:30`): `[LEVEL] msg\n` on stderr, -//! no timestamp, level fixed at INFO (`main` calls `mq_log_set_level(MQ_LOG_INFO)`). +//! spec §6.5: `[LEVEL] msg\n` on stderr, no timestamp, level fixed at INFO. use log::{Level, LevelFilter, Log, Metadata, Record}; use std::io::Write; @@ -32,7 +31,7 @@ impl Log for Stderr { fn flush(&self) {} } -/// C's prefixes: ERROR, WARN, INFO, DEBUG (`Trace` never passes the INFO level). +/// Prefixes: ERROR, WARN, INFO, DEBUG (`Trace` never passes the INFO level). fn line(level: Level, msg: &std::fmt::Arguments, instance: Option<&str>) -> String { let prefix = match level { Level::Error => "ERROR", @@ -46,7 +45,7 @@ fn line(level: Level, msg: &std::fmt::Arguments, instance: Option<&str>) -> Stri } } -/// Installs the logger; the max level is INFO, as C. +/// Installs the logger; the max level is INFO. pub fn init() { if log::set_logger(&Stderr).is_ok() { log::set_max_level(LevelFilter::Info); diff --git a/crates/mqproxy/src/run.rs b/crates/mqproxy/src/run.rs index 12439685..58530c62 100644 --- a/crates/mqproxy/src/run.rs +++ b/crates/mqproxy/src/run.rs @@ -1,6 +1,5 @@ //! spec §5.3 "Setup", §6.4, §6.6: `run_server` / `run_client` build the -//! transport, the driver and the shard in C `cmd_server` / `cmd_client` order, -//! run the loop and return the exit status (1 for cert/bind/qlog/origin-TLS failures). +//! transport, the driver and the shard, run the loop and return the exit status (1 for cert/bind/qlog/origin-TLS failures). use crate::cli::{self, Client as ClientArgs, Mode, Resolved, Server as ServerArgs}; use crate::setup_redirect; @@ -59,7 +58,7 @@ fn realtime_offset_us() -> i64 { wall - now().as_micros() as i64 } -/// C `getpid() ^ time(NULL)`. +/// Process id XOR Unix time in seconds. fn seed() -> u64 { let secs = SystemTime::now() .duration_since(UNIX_EPOCH) @@ -114,7 +113,7 @@ fn driver() -> Result { .map_err(|e| format!("failed to create runtime ({e})")) } -/// The startup INFO lines, logged once the signal handlers are in (as C). +/// The startup INFO lines, logged once the signal handlers are in. fn ready(r: &Resolved, line: String) { for l in &r.startup_lines { log::info!("{l}"); @@ -173,7 +172,7 @@ fn run_server(r: &Resolved, s: &ServerArgs) -> Result { let app = match &s.config.gateway { Some(g) => { let tls = build_client_config(g.origin_ca.as_deref(), &native_roots).map_err(|e| { - // C's line, plus the cause (as the transport's). + // The line plus the cause (as the transport's). let ca = g.origin_ca.as_deref().map_or("(system)".into(), |p| p.display().to_string()); format!( "failed to create HTTP gateway server (origin_ca={ca}, connect_timeout={}s) ({e})", @@ -214,7 +213,7 @@ fn run_client(r: &Resolved, c: &ClientArgs) -> Result { "failed to create client transport".into(), )?; let mut d = driver()?; - // C: the first --path is the primary bind, else 0.0.0.0 with an ephemeral port. + // The first --path is the primary bind, else 0.0.0.0 with an ephemeral port. let primary_ip = c .config .paths @@ -250,8 +249,8 @@ fn run_client(r: &Resolved, c: &ClientArgs) -> Result { d.attach_listener(l, shard.add_listener(tag)); ingress += &format!(" {key}={addr}"); } - // C binds tproxy (and installs its rules) before the fetch listener, but - // logs the ingress list as socks5, http-connect, gateway, tproxy. + // Tproxy is bound (and its rules installed) before the fetch listener, but + // the ingress list is logged as socks5, http-connect, gateway, tproxy. let mut tproxy = String::new(); if let Some(addr) = c.tproxy { let l = d diff --git a/crates/mqproxy/src/setup_redirect.rs b/crates/mqproxy/src/setup_redirect.rs index c74d3bee..966affae 100644 --- a/crates/mqproxy/src/setup_redirect.rs +++ b/crates/mqproxy/src/setup_redirect.rs @@ -1,7 +1,7 @@ -//! spec §6.4 `--setup-redirect`: the nft / ip-rule commands of C -//! `src/ingress/mq_tproxy_setup.c`, table `mqproxy`. Every invocation goes -//! through `run`: a direct exec with separate argv elements, no shell, and the -//! child's `PATH` pinned to `/usr/sbin:/usr/bin:/sbin:/bin` (C `run_cmd`). +//! spec §6.4 `--setup-redirect`: the nft / ip-rule commands, table +//! `mqproxy`. Every invocation goes through `run`: a direct exec with separate +//! argv elements, no shell, and the child's `PATH` pinned to +//! `/usr/sbin:/usr/bin:/sbin:/bin`. use mq_runtime::ListenKind; use std::io; @@ -35,7 +35,7 @@ fn v(a: &[&str]) -> Vec { a.iter().map(|s| s.to_string()).collect() } -/// C `install_redirect` / `install_tproxy`, in order; element 0 is the program. +/// The redirect or tproxy install commands, in order; element 0 is the program. pub fn install_cmds(o: &Opts) -> Vec> { let (uid, dport, mark, table) = ( o.uid.to_string(), @@ -100,7 +100,7 @@ pub fn install_cmds(o: &Opts) -> Vec> { } } -/// C `uninstall_redirect` / `uninstall_tproxy`, in order. +/// The redirect or tproxy uninstall commands, in order. pub fn uninstall_cmds(o: &Opts) -> Vec> { let mut c = vec![v(&["nft", "delete", "table", "ip", "mqproxy"])]; if o.mode == ListenKind::Tproxy { @@ -121,7 +121,7 @@ pub fn uninstall_cmds(o: &Opts) -> Vec> { c } -/// C `run_cmd`: logs the command, runs it, logs a failure; true on exit 0. +/// Logs the command, runs it, logs a failure; true on exit 0. fn cmd(argv: &[String], log_failure: bool) -> bool { log::info!("mq_tproxy_setup: run: {}", argv.join(" ")); let prog = &argv[0]; @@ -141,7 +141,7 @@ fn cmd(argv: &[String], log_failure: bool) -> bool { /// spec §6.4: removes leftovers of a crashed run (failures expected, not /// logged), then installs. `false` = a failed install, which the caller logs as a -/// warning; as C, every command is tried and a partial install is left for +/// warning; every command is tried and a partial install is left for /// `uninstall`. pub fn install(o: &Opts) -> bool { for c in uninstall_cmds(o) { @@ -169,7 +169,7 @@ pub fn install(o: &Opts) -> bool { ok } -/// spec §6.6: the shutdown hook; each failure is tolerated, as C. +/// spec §6.6: the shutdown hook; each failure is tolerated. pub fn uninstall(o: &Opts) { let tproxy = o.mode == ListenKind::Tproxy; let mode = if tproxy { "TPROXY" } else { "REDIRECT" }; @@ -213,7 +213,6 @@ mod tests { #[test] fn argv_lists_match_c() { - // Transcribed from the `const char *const a[]` arrays of mq_tproxy_setup.c. let r = opts(ListenKind::Redirect); assert_eq!( install_cmds(&r), diff --git a/crates/mqproxy/tests/cli.rs b/crates/mqproxy/tests/cli.rs index 1178b20e..bb9fb7b5 100644 --- a/crates/mqproxy/tests/cli.rs +++ b/crates/mqproxy/tests/cli.rs @@ -100,7 +100,7 @@ fn server_implemented_flags_resolve() { assert_eq!(r.cc, CongestionControl::Cubic); assert_eq!(r.scheduler, Scheduler::Wlb); assert!(r.warnings.is_empty(), "{:?}", r.warnings); - // C parse_ip_port also takes an unbracketed IPv6 literal (split at the last ':'). + // An unbracketed IPv6 literal is also accepted (split at the last ':'). let r = cli::parse(&[ "mqproxy", "server", "--listen", "::1:9443", "--token", "t", "--cert", "c", "--key", "k", ]) @@ -216,7 +216,7 @@ fn client_implemented_flags_resolve() { ]); assert!(r.is_ok(), "{flag}: {r:?}"); } - // More than 8 --path: C warns and ignores the extras. + // More than 8 --path: warns and ignores the extras. let mut extra = Vec::new(); for _ in 0..9 { extra.extend(["--path", "10.0.0.1"]); @@ -262,7 +262,7 @@ fn server_gateway_on_by_default() { } /// spec §8: `--no-gateway` → `gateway = None`, no H3, no `mq_origin:` line; -/// `--masquerade` / `--request-metrics` with it warn and are ignored (C text). +/// `--masquerade` / `--request-metrics` with it warn and are ignored. #[test] fn no_gateway_disables_h3_and_warns_masquerade_and_metrics() { let r = parse(SERVER, &["--no-gateway", "--origin-ca", "/ca.pem"]).unwrap(); @@ -270,7 +270,7 @@ fn no_gateway_disables_h3_and_warns_masquerade_and_metrics() { assert_eq!(server(&r).config.gateway, None); assert!(!cli::wants_h3(&r)); assert!(r.startup_lines.is_empty(), "{:?}", r.startup_lines); - // C's order: request-metrics, cache, masquerade. + // Warning order: request-metrics, cache, masquerade. let r = parse( SERVER, &[ @@ -327,7 +327,7 @@ fn client_gateway_counts_as_ingress() { "{extra:?}" ); } - // C's validation order: server, socks5, http-connect, gateway, tproxy. + // Validation order: server, socks5, http-connect, gateway, tproxy. for (extra, first) in [ (&["--server", "x", "--socks5", "y"][..], "--server"), (&["--socks5", "x", "--gateway", "y"], "--socks5"), @@ -393,7 +393,7 @@ fn origin_connect_timeout_pure() { ); } -/// spec §8: `--no-udp` and `--udp-idle-timeout` reach `ServerConfig` (C defaults: on, 60 s). +/// spec §8: `--no-udp` and `--udp-idle-timeout` reach `ServerConfig` (defaults: on, 60 s). #[test] fn server_udp_flags_change_config() { let d = parse(SERVER, &[]).unwrap(); @@ -553,7 +553,7 @@ fn mitm_on_server_exit2() { } /// A good CA + tproxy builds `config.mitm`; repeated and comma-split ignore -/// flags (empty tokens skipped, as in C) are unioned. +/// flags (empty tokens skipped) are unioned. #[test] fn mitm_ok_builds_config() { let r = parse_mitm( @@ -600,8 +600,7 @@ fn ca_flags_without_mitm_no_effect() { assert!(client(&r).config.mitm.is_none()); } -/// The cache was removed: one warning, gateway on or off (it replaces C's -/// "no effect with --no-gateway" warning for this flag). +/// The cache was removed: one warning, gateway on or off. #[test] fn cache_max_bytes_warns() { for extra in [&[][..], &["--no-gateway"]] { @@ -706,7 +705,7 @@ fn no_ingress_rejected() { "t", ])); assert_eq!(e.code, 2); - // C text, naming --gateway too (tests/test_cli_help.sh greps for it). + // Names --gateway too (tests/test_cli_help.sh greps for it). assert!( e.message.contains( "at least one ingress is required (--socks5, --http-connect, --gateway, or --tproxy)" @@ -856,13 +855,13 @@ fn help_and_version_exit_0_in_process() { (0, concat!("mqproxy ", env!("CARGO_PKG_VERSION"))) ); } - // -V is top-level only, as in C. + // -V is top-level only. assert_eq!(exit(parse(SERVER, &["-V"])).code, 2); } // ---- the only tests that spawn the binary ---- -/// The C `longopts` tables (cli/main.c `cmd_server` / `cmd_client`). +/// Every long option `server` / `client` accepts. const SERVER_LONGOPTS: &[&str] = &[ "listen", "token", @@ -932,7 +931,7 @@ fn mitm_help_no_unavailable_marker() { assert!(!text.contains("not available"), "{text}"); } -/// spec §11.5: every C long option is listed, and no flag carries an old SP1 marker. +/// spec §11.5: every long option is listed, and no flag carries an old SP1 marker. #[test] fn help_lists_every_longopt() { for (sub, opts) in [("server", SERVER_LONGOPTS), ("client", CLIENT_LONGOPTS)] { @@ -949,7 +948,7 @@ fn help_lists_every_longopt() { "{sub} --help lacks {flag}:\n{text}" ); } - // C's wording now that the gateway conn exists. + // The wording now that the gateway conn exists. let metrics = match sub { "server" => "Logs the most-recently-accepted TCP and gateway conn", _ => "Logs the proxy conn (and the gateway conn with --gateway)", diff --git a/crates/mqproxy/tests/config.rs b/crates/mqproxy/tests/config.rs index 10ac9029..c5a7ea05 100644 --- a/crates/mqproxy/tests/config.rs +++ b/crates/mqproxy/tests/config.rs @@ -1,6 +1,6 @@ //! spec §6.4 "Config file": the INI loader, in process through `cli::parse` -//! with `--config `. Ports C `tests/test_config.c` and gives every -//! row of the SP1 flag table its INI equivalent. +//! with `--config `. Every row of the SP1 flag table gets +//! its INI equivalent. mod common; @@ -93,10 +93,7 @@ fn warned(r: &Resolved, needle: &str) -> bool { r.warnings.iter().any(|w| w.contains(needle)) } -// ---- C tests/test_config.c ports ---- - -/// C test_defaults + test_partial_file_keeps_defaults: keys absent from the -/// file keep the defaults. +/// Keys absent from the file keep the defaults. #[test] fn c_defaults_and_partial_file() { let r = srv("").unwrap(); @@ -113,7 +110,7 @@ fn c_defaults_and_partial_file() { ); } -/// C test_server_roundtrip. +/// Every server key round-trips. #[test] fn c_server_roundtrip() { let ini = Ini::new( @@ -136,7 +133,7 @@ fn c_server_roundtrip() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } -/// C test_client_roundtrip (bracketed IPv6 Address). +/// Every client key round-trips (bracketed IPv6 `Address`). #[test] fn c_client_roundtrip() { let ini = Ini::new( @@ -175,8 +172,8 @@ fn c_client_roundtrip() { assert!(r.warnings.is_empty(), "{:?}", r.warnings); } -/// C test_bool_variants: `yes`/`0` on the bool keys. C `parse_bool` is exact -/// `true`/`yes`/`1`; anything else is false. +/// `yes`/`0` on the bool keys. A bool is exact `true`/`yes`/`1`; anything +/// else is false. #[test] fn c_bool_variants() { let r = srv("[Gateway]\nEnabled = yes\n[UDP]\nEnabled = 0\n").unwrap(); @@ -201,7 +198,7 @@ fn c_bool_variants() { } } -/// C test_path_cap: 10 file paths → 8 kept, with a warning. +/// 10 file paths → 8 kept, with a warning. #[test] fn c_path_cap() { let paths: String = (1..=10).map(|i| format!("Path = 10.0.0.{i}\n")).collect(); @@ -210,7 +207,7 @@ fn c_path_cap() { assert!(warned(&r, "10.0.0.9"), "{:?}", r.warnings); } -/// C test_lenient_and_comments. +/// Comments, unknown sections/keys and bad values warn but still load. #[test] fn c_lenient_and_comments() { let ini = Ini::new(&format!( @@ -228,7 +225,7 @@ fn c_lenient_and_comments() { assert!(warned(&r, "Foo"), "{:?}", r.warnings); } -/// C test_mitm_section: `[Mitm] Enabled = true` without `--tproxy` is exit 2 +/// `[Mitm] Enabled = true` without `--tproxy` is exit 2 /// (this INI's only ingress is SOCKS5). #[test] fn c_mitm_section_enabled_exit_2() { @@ -297,7 +294,7 @@ fn server_config_mitm_section_warns() { ); } -/// C test_mitm_enabled_missing_cacert: `Enabled = true` with `--tproxy` but no +/// `Enabled = true` with `--tproxy` but no /// `CACert`/`CAKey` is exit 2 naming the missing key's flag. #[test] fn c_mitm_enabled_missing_cacert_exit_2() { @@ -308,7 +305,7 @@ fn c_mitm_enabled_missing_cacert_exit_2() { assert!(e.message.contains("--ca-cert"), "{}", e.message); } -/// C test_perms_warning (+ spec §6.4: 0620 warns too). +/// spec §6.4: any group/other permission bit warns (0620 too). #[test] fn perms_warning() { for (mode, warns) in [(0o640, true), (0o620, true), (0o644, true), (0o600, false)] { @@ -323,7 +320,6 @@ fn perms_warning() { } } -/// C test_missing_file_fatal. #[test] fn unreadable_file_exit_2() { let e = exit(cli::parse(&[ @@ -409,7 +405,7 @@ fn paths_accumulate_file_then_cli_max_8_warn() { #[test] fn bool_values_exact_case() { - // C parse_bool: strcmp against "true", "yes", "1" — exact case. + // Only "true", "yes", "1" — exact case. let redirect = |v: &str| { client(&cli_(&format!("[Ingress]\nSetupRedirect = {v}\n")).unwrap()).setup_redirect }; @@ -504,7 +500,7 @@ fn client_implemented_keys_resolve() { } /// spec §8: `[Gateway] Enabled = false` is `--no-gateway`; the CLI can only -/// turn the gateway off (C has no `--gateway` on the server). +/// turn the gateway off (the server has no `--gateway`). #[test] fn ini_gateway_enabled_false_disables() { let r = srv("[Gateway]\nEnabled = false\n").unwrap(); @@ -522,7 +518,7 @@ fn ini_gateway_enabled_false_disables() { ); let r = run("server", &ini, &["--no-gateway"]).unwrap(); assert_eq!(server(&r).config.gateway, None); - // The gateway-only keys with the gateway off: warned, ignored (C text). + // The gateway-only keys with the gateway off: warned, ignored. let r = srv("[Gateway]\nEnabled = no\nMasquerade = true\n[Metrics]\nPerRequest = 1\n").unwrap(); assert_eq!(server(&r).config.gateway, None); assert!( @@ -575,7 +571,7 @@ fn server_udp_keys_take_effect() { assert!(!server(&r).config.udp_enabled); assert_eq!(server(&r).config.udp_idle_timeout, Duration::from_secs(30)); - // C LONGV: below 1 warns and keeps the previous value. + // Below 1 warns and keeps the previous value. for v in ["0", "-3", "x"] { let r = srv(&format!("[UDP]\nIdleTimeout = 7\nIdleTimeout = {v}\n")).unwrap(); assert!(warned(&r, "IdleTimeout"), "{v}: {:?}", r.warnings); diff --git a/crates/mqproxy/tests/smoke.rs b/crates/mqproxy/tests/smoke.rs index f7225b60..eece0f2d 100644 --- a/crates/mqproxy/tests/smoke.rs +++ b/crates/mqproxy/tests/smoke.rs @@ -104,7 +104,7 @@ fn origin_ca_unreadable_exits_1_with_message() { ); } -/// C order: the tproxy listener is bound before the fetch listener. +/// The tproxy listener is bound before the fetch listener. #[test] fn client_binds_tproxy_before_fetch_listener() { let (tp, gw) = ( @@ -153,7 +153,7 @@ fn lines_until(p: &mut Proc, last: &str) -> Vec { } /// spec §8: the server line's real `gateway=on|off`, the `mq_origin:` line -/// only with the gateway on, the client's `gateway=ip:port` in C's ingress order. +/// only with the gateway on, the client's `gateway=ip:port` in ingress order. #[test] fn startup_lines_golden() { let listen = format!("127.0.0.1:{}", free_udp()); diff --git a/tests/integration/bench_ab_lanes.sh b/tests/integration/bench_ab_lanes.sh index 30742b11..06714f90 100755 --- a/tests/integration/bench_ab_lanes.sh +++ b/tests/integration/bench_ab_lanes.sh @@ -158,7 +158,6 @@ start_origin() { # returning. The marker is: # # "mq_client: extra path up: bind -> path_id " -# (src/proxy/mq_client.c, client_mp_timer_cb) # # The bench passes --path PATH_A (primary bind, no log) and --path PATH_B # (one extra path, logged once when mp-ready fires). We therefore poll for 1 diff --git a/tests/integration/e2e_gateway.sh b/tests/integration/e2e_gateway.sh index c6dd95bb..dabbb25a 100755 --- a/tests/integration/e2e_gateway.sh +++ b/tests/integration/e2e_gateway.sh @@ -7,8 +7,8 @@ # byte-for-byte what the spec promises: # # curl → POST /_mqproxy/fetch (local fetch ingress) -# → mq_gw_client → H3 over MPQUIC → mqproxy-server -# → mq_gw_server → libcurl → ORIGIN (TLS, verified) → back. +# → gateway client → H3 over MPQUIC → mqproxy-server +# → gateway server → ORIGIN (TLS, verified) → back. # # Cases (all over the real chain, against a real TLS origin): # 1. 8MB download, byte-exact (cmp). @@ -20,7 +20,7 @@ # 7. x-mq-origin-protocol present on the download response (http/1.1). # 8. (NET_ADMIN-gated) 2-path aggregation smoke: shape two loopback # paths, download 8MB over both, confirm BOTH gateway paths moved bytes -# (client logs mq_h3_conn_dump_stats per-path counters at SIGTERM). +# (client logs per-path counters at SIGTERM). # Without NET_ADMIN this sub-case is SKIPPED (a note) — cases 1-7 still # decide the exit status. # @@ -499,10 +499,10 @@ note "cases 1-7 PASS (${PASS_COUNT}/7 checks)." # ── case 9: L1 origin-connection reuse proof (no root required) ────────────── # Proves that two sequential same-origin requests flip origin_reuse 0→1, which -# validates both the Task-2 capture wiring and libcurl's implicit keep-alive. +# validates both the capture wiring and the origin pool's keep-alive. # # COLD conncache: case 6 restarted the server with a short connect timeout; -# there may be residual connections in the server's libcurl conncache from +# there may be residual connections in the server's origin pool from # earlier cases. Restart server+client clean so the conncache starts fresh and # server.log is truncated to only case-9 traffic. stop_client @@ -643,7 +643,7 @@ grep -qi '^x-mq-error:[[:space:]]*bad-origin-protocol' "${HV}" || \ # mis-anchor onto case 1's default h1 download (which is 8 MiB). Then a REAL # 25×0.2s retry loop with fail-on-miss (mirror case 9) — an unconditional ok # would prove nothing. Field order is resp_bytes=… … origin_protocol=… so anchor -# left-to-right (mq_gw_metrics.c). +# left-to-right. C13_SIZE=4194304 # 4 MiB — NEW reserved size (not in {8MiB,3MiB,1MiB,2MiB,512KiB,73728}) head -c "${C13_SIZE}" /dev/zero >"${WORK}/c13.bin" code13="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 \ @@ -670,7 +670,7 @@ ok 13 "X-Mq-Origin-Protocol: invalid→400 (+x-mq-error); h1→honored (origin_p # This is the only honest switch-proof: select h3 to an h3-capable origin and # assert the server actually negotiated h3 (mq.req origin_protocol=h3). It needs # (1) the gateway built with MQPROXY_H3_CURL (server.log logs "HTTP3=yes" at -# startup — mq_origin_curl.c:49), and +# startup), and # (2) an h3 origin: xquic's demo_server (NOT built by default). # On the system (no-h3) curl build this SKIPs with a note — it NEVER flips RESULT. if grep -q 'HTTP3=yes' "${WORK}/server.log" 2>/dev/null; then @@ -704,7 +704,7 @@ if grep -q 'HTTP3=yes' "${WORK}/server.log" 2>/dev/null; then # until demo_server's QUIC listener is up (a not-yet-ready origin → non-200). code13h3=000 H3_HDR="${WORK}/c13h3_headers.txt" - # Target https://localhost (NOT 127.0.0.1): the gateway's libcurl sends SNI + # Target https://localhost (NOT 127.0.0.1): the gateway sends SNI # only for a hostname, never for an IP literal, and xquic's demo_server REQUIRES # SNI (its cert callback errors "hostname is NULL" → CERT_CB_ERROR → 504). localhost # resolves to 127.0.0.1 where demo_server listens, and the dual-SAN origin cert @@ -770,8 +770,8 @@ head -c "${C14_HIT}" /dev/urandom >"${WORK}/cache_hit.bin" head -c "${C14_NS}" /dev/urandom >"${WORK}/nostore-x.bin" # Spec §10.4: the Rust server has no response cache (it warns "origin response -# cache was removed" for --cache-max-bytes), so a-c are skipped against it; the -# C server still runs them. (d) is a client-side reject and always runs. +# cache was removed" for --cache-max-bytes), so a-c are skipped against it. +# (d) is a client-side reject and always runs. C14_RAN="14" if grep -q "origin response cache was removed" "${WORK}/server.log"; then note "case 14 (a-c) skipped: server has no response cache (origin response cache was removed); (d) still runs." @@ -787,7 +787,7 @@ else [ "${code14a1}" = "200" ] || fail 14 "(a) first cacheable fetch HTTP code = ${code14a1} (want 200)" # First fetch must be a miss (anchored to resp_bytes=1572864 cache=miss; field - # order is resp_bytes=… … cache=… so anchor left-to-right — mq_gw_metrics.c). + # order is resp_bytes=… … cache=… so anchor left-to-right). c14_miss_found=0 for _ in $(seq 1 25); do if grep -Eq 'mq\.req .* resp_bytes=1572864 .* cache=miss' "${WORK}/server.log"; then @@ -912,8 +912,7 @@ ok 14 "X-Mq-Cache invalid TTL → 400 + x-mq-error: bad-cache-ttl" # already passed → exit 0). With it: shape two equal-rate loopback paths, run a # gateway-only client bound to both --path IPs, download 8MB over the tunnel, # SIGTERM the client, and confirm BOTH gateway paths carried bytes (the client -# logs mq_h3_conn_dump_stats per-path counters at SIGTERM via -# mq_gw_client_dump_stats). +# logs per-path counters at SIGTERM). RATE="50mbit"; DELAY="10ms" can_tc=0 if [ "$(id -u)" -eq 0 ] && tc qdisc add dev lo root netem delay 1ms 2>/dev/null; then @@ -971,8 +970,9 @@ cmp -s "${BIGFILE}" "${DL8}" || fail 8 "2-path download body differs" # the per-stream-per-path cumulative byte counters) and classifies by path # APP-STATUS, not path count: 1=stream used both an Available- AND a Standby-class # path, 2=Standby-class only, 3=Available-class only. mqproxy creates ALL paths as -# Available-class (path_status 0; it never marks a path STANDBY — see -# mq_conn.c:412), so a multipath request here ALWAYS reads mp_state=3, never 1/2. +# Available-class (path_status 0; only --scheduler backup marks paths STANDBY, +# and this case uses the default), so a multipath request here ALWAYS reads +# mp_state=3, never 1/2. # Note mp_state=3 does NOT prove 2-path aggregation: it's 3 whether 1 or 2 # Available paths carried the stream (this download does aggregate — 8MiB in # ~750ms ≈ 90Mbit > a single 50mbit path — but mp_state alone can't show that). @@ -1031,8 +1031,8 @@ ok 8 "2-path aggregation: both gateway paths carried bytes" # the QUIC port if it happened to collide numerically (free_port tcp vs # free_port udp are allocated independently). # -# COLD conncache: case 8 may have left a live origin connection in libcurl's -# pool. Restart server+client AFTER applying the shaping so the first shaped +# COLD conncache: case 8 may have left a live origin connection in the +# origin pool. Restart server+client AFTER applying the shaping so the first shaped # request opens a NEW, delayed connection. # Clear any tc state case 8 left, then install a fresh single-class HTB+netem diff --git a/tests/integration/e2e_mitm_h2.sh b/tests/integration/e2e_mitm_h2.sh index 0a6dc796..24cad82a 100755 --- a/tests/integration/e2e_mitm_h2.sh +++ b/tests/integration/e2e_mitm_h2.sh @@ -3,25 +3,23 @@ # e2e_mitm_h2.sh — Phase 7 MITM Slice 3 Task 16: NET_ADMIN transparent-MITM H2 e2e. # # WHAT THIS PROVES (the capstone for the 🔒 security gate): -# This is the ONLY test that drives the LIVE mq_mitm_conn orchestrator end to +# This is the ONLY test that drives the LIVE MITM orchestrator end to # end. A real browser (curl --http2) is transparently captured (nft REDIRECT), # the client forges a per-SNI leaf signed by the MITM CA, terminates TLS, # speaks h2 over the tunnel to the gateway server, which fetches the real -# origin via libcurl. The full live data path is: +# origin. The full live data path is: # # curl (as nobody, --http2) # → nft REDIRECT # → mqproxy-client tproxy listener -# → mq_mitm_conn orchestrator (forge leaf for SNI, terminate TLS, ALPN=h2) -# → mq_gw_h2_adapter -# → gwc (gateway client) → MPQUIC tunnel -# → mqproxy-server (gateway mode) → libcurl → ORIGIN (HTTPS). +# → MITM orchestrator (forge leaf for SNI, terminate TLS, ALPN=h2) +# → H2 adapter +# → gateway client → MPQUIC tunnel +# → mqproxy-server (gateway mode) → ORIGIN (HTTPS). # -# The Slice-2 e2e (e2e_mitm_smoke.sh) only exercised mq_mitm_core over an -# SSL_set_fd socket with a hand-rolled single-shot server; the live -# orchestrator's BIO-pump + handshake + adapter→tunnel submit + teardown is -# NOT unit-covered (test_mitm_teardown is a fake-SSL teardown). THIS script is -# what genuinely exercises that path. +# e2e_mitm_smoke.sh only checks the MITM TLS endpoint with openssl s_client; +# THIS script is what exercises the live orchestrator's handshake + +# adapter→tunnel submit + teardown. # # THE TWO FALSIFIABILITY AXES (one per host, mirror e2e_tproxy's opacity proof): # * MITM host (SNI=mitm.test): curl trusts the MITM CA (--cacert mitm-ca.crt) @@ -38,7 +36,7 @@ # handshake that FAILS against the MITM CA) proves the ignore-hosts splice # is opaque (the origin's real ClientHello/cert reach the wire untouched). # -# ASSERTIONS (cases a-f run by default; g and h are Rust-only): +# ASSERTIONS (cases a-f run by default; g and h are opt-in): # (a) curl --http2 to the MITM host gets the origin object over h2 # (http_version == 2, body byte-exact) → transparent MITM works. # (b) a second same-origin fetch REUSES the warm origin connection @@ -59,18 +57,17 @@ # (the orchestrator's single h2 conn multiplexes N streams onto the tunnel). # (f) a POST upload body reaches the origin byte-exact over h2 (no FIN-before-body # regression: the H2 adapter must report a streaming body). -# (g) [Rust] curl --http1.1 --cacert succeeds: a client that does not +# (g) curl --http1.1 --cacert succeeds: a client that does not # offer h2 takes the OPAQUE path (origin cert verifies; the MITM CA is rejected). -# (h) [Rust] a 6 KiB Cookie and a 3 KiB URL succeed (the C server stores forwarded -# values in 1024 bytes, so this case is not C-compatible). +# (h) a 6 KiB Cookie and a 3 KiB URL succeed. # -# CASE SELECTION: MITM_CASES (default "a b c d e f", which CTest and the C interop -# runs use). Rust<->Rust runs set MITM_CASES="a b c d e f g h". +# CASE SELECTION: MITM_CASES (default "a b c d e f"); set +# MITM_CASES="a b c d e f g h" to run all. # # HOW HOSTNAMES RESOLVE (both client AND server sides): # The H2 adapter forwards the browser's :authority verbatim; the gateway server -# fetches https://<:authority><:path> via libcurl and verifies the origin cert -# against --origin-ca. So BOTH the SNI host (browser→client) and the libcurl +# fetches https://<:authority><:path> and verifies the origin cert +# against --origin-ca. So BOTH the SNI host (browser→client) and the origin # target host (server→origin) are the SAME hostname, and BOTH must resolve to # 127.0.0.1 and be covered by the origin cert's SAN. We therefore: # * generate a DEDICATED origin CA + leaf at runtime (in WORK); the leaf's SAN @@ -81,7 +78,7 @@ # end-entity (CaUsedAsEndEntity). The e2e is self-contained, like # e2e_gateway, which also generates its own files. # * add /etc/hosts entries mitm.test/pinned.example → 127.0.0.1 (we are root -# in the NET_ADMIN container) so BOTH curl's SNI and the server's libcurl +# in the NET_ADMIN container) so BOTH curl's SNI and the server's origin fetch # resolve the hostnames. The entries are removed on cleanup. # curl connects to https://:${ORIGIN_PORT}/ ; the nft REDIRECT (dport # ${ORIGIN_PORT}) captures nobody's connection to the tproxy listener. @@ -206,9 +203,8 @@ if [ ! -x "${MQPROXY_BIN}" ]; then note " Build first (cargo build --release -p mqproxy --bins --examples) or set MQPROXY_BIN." exit 1 fi -# MITM capability is gated at runtime, not here: the Rust binary always has it; -# a C binary built without the BoringSSL archives hard-errors on --mitm -# ("--mitm unavailable"), which wait_mitm_ready below turns into a SKIP. +# MITM capability is not checked here (the binary always has it); +# wait_mitm_ready below still turns a "--mitm unavailable" error into a SKIP. for f in "${MITM_CA_CRT}" "${MITM_CA_KEY}" "${MQPROXY_CERT}" "${MQPROXY_KEY}"; do if [ ! -f "${f}" ]; then note "ERROR: cert/key missing: ${f} (run bash tests/certs/generate-mitm.sh or set MQ_MITM_CA_*)." @@ -255,9 +251,9 @@ ORIGIN_CA_KEY="${WORK}/origin-ca.key" # the e2e_tproxy.sh note on the HTTP-000 path-permission trap). MITM_CA_PUB="${WORK}/mitm_ca.crt" ORIGIN_CA_PUB="${WORK}/origin_ca.crt" -# Private CA copies that --ca-cert/--ca-key consume. mq_mitm_core REQUIRES the CA +# Private CA copies that --ca-cert/--ca-key consume. The client REQUIRES the CA # KEY to be owned by the running euid with NO group/other perms (a deliberate -# 0600-owner security gate — read_pem_file_safely). The tracked fixture key is +# 0600-owner security gate). The tracked fixture key is # owned by the repo user, so when this script runs as root (uid 0) the original # would be REJECTED (st_uid != geteuid). We therefore stage root-owned 0600 copies # in WORK and point --ca-key/--ca-cert at THOSE. @@ -333,8 +329,8 @@ mint_origin_cert() { } # ── /etc/hosts: map both test hostnames to 127.0.0.1 ───────────────────────── -# Needed on BOTH sides: curl's SNI (client) and the server's libcurl (origin -# fetch) must resolve the hostnames to 127.0.0.1. +# Needed on BOTH sides: curl's SNI (client) and the server's origin fetch +# must resolve the hostnames to 127.0.0.1. install_hosts() { cp /etc/hosts "${WORK}/hosts.bak" || return 1 HOSTS_BACKED_UP=1 @@ -642,7 +638,7 @@ if want b; then # ── case (b): cache HIT — second fetch served origin-once ──────────────────── # MITM-MODEL NOTE — why this is origin-CONNECTION-REUSE, not a server cache HIT: # The Task-16 plan text says "origin-once (cache hit)". But §4.5 step 1 (the - # S3-D11 untrusted-browser-header policy, enforced in mq_gw_h2_adapter on_header) + # S3-D11 untrusted-browser-header policy, enforced in the H2 adapter) # STRIPS every browser-supplied x-mq-* header UNCONDITIONALLY, and the MITM path # injects EXACTLY two controls (x-mq-auth, x-mq-forward-cookie) — NOT X-Mq-Cache. # The server-side response cache is therefore NOT reachable from a transparently diff --git a/tests/integration/e2e_multipath.sh b/tests/integration/e2e_multipath.sh index 7da8bbd5..c18f5a1f 100755 --- a/tests/integration/e2e_multipath.sh +++ b/tests/integration/e2e_multipath.sh @@ -272,8 +272,8 @@ start_client() { } stop_client() { - # SIGTERM: the CLI handles it (mq_runtime_stop -> loop breaks -> it logs - # mq_conn_dump_stats per-path counters to client.log before teardown). + # SIGTERM: the CLI handles it (the loop stops and it logs per-path + # counters to client.log before teardown). [ -n "${CLIENT_PID}" ] && kill -TERM "${CLIENT_PID}" 2>/dev/null wait "${CLIENT_PID}" 2>/dev/null CLIENT_PID="" @@ -313,7 +313,7 @@ note "e2e_multipath: === two-path run (path A + path B) ===" start_client "${PATH_A_IP}" "${PATH_B_IP}" DUAL_BPS="$(run_transfer)" # Dump the client's per-path stats before killing it (logged at INFO on signal/ -# exit via mq_conn_dump_stats — captured in client.log). Give it a moment. +# exit — captured in client.log). Give it a moment. stop_client note "e2e_multipath: two-path speed = ${DUAL_BPS} bytes/s" @@ -341,7 +341,7 @@ count_token() { } # (2) per-path split: both paths moved real bytes (GATE). The client logs -# "mq.path id= ... sent= recv= ..." on teardown (mq_conn_dump_stats). +# "mq.path id= ... sent= recv= ..." on teardown. PATHS_WITH_BYTES="$(grep -E 'mq\.path id=' "${WORK}/client.log" 2>/dev/null \ | sed -E 's/.*mq\.path id=([0-9]+).*sent=([0-9]+) recv=([0-9]+).*/\1 \2 \3/' \ | awk '($2+0 > 0 || $3+0 > 0) { print $1 }' \ diff --git a/tests/integration/e2e_tproxy.sh b/tests/integration/e2e_tproxy.sh index 0ed149e2..db597da4 100755 --- a/tests/integration/e2e_tproxy.sh +++ b/tests/integration/e2e_tproxy.sh @@ -354,8 +354,8 @@ stop_client() { # 2. The nft table "ip mqproxy" exists (rules are installed). # 3. The QUIC tunnel to the server is established (the client logged its # "mqproxy client: server=..." startup line AND the server is alive). -# The REDIRECT rules are installed during client startup (mq_tproxy_setup_install -# is called before the event loop). The QUIC handshake completes asynchronously; +# The REDIRECT rules are installed during client startup (before the event +# loop). The QUIC handshake completes asynchronously; # we poll for up to 8s total. wait_tproxy_ready() { for _ in $(seq 1 80); do diff --git a/tests/integration/e2e_udp.sh b/tests/integration/e2e_udp.sh index 7e6ebeb7..cebfcbd5 100755 --- a/tests/integration/e2e_udp.sh +++ b/tests/integration/e2e_udp.sh @@ -7,10 +7,10 @@ # matches the spec: # # udpsocks (SOCKS5 UDP ASSOCIATE client) -# → SOCKS5 TCP ingress (mq_listener / mq_udp_assoc) -# → mq_udp_cli (client-side session table, frag, datagram) +# → SOCKS5 TCP ingress (UDP ASSOCIATE) +# → client UDP lane (session table, frag, datagram) # → MPQUIC tunnel -# → mq_udp_srv (server-side session table, defrag, UDP forward) +# → server UDP lane (session table, defrag, UDP forward) # → udp_echo (loopback UDP echo server) # → back along the same path. # @@ -27,7 +27,7 @@ # process mid-flight (TCP EOF → server reaps session); assert server # health by running a fresh udpsocks that succeeds. # 6. (NET_ADMIN-gated) 2-path: tc shapes two loopback paths; both paths' -# recv bytes > 0 from `mq_conn_dump_stats` in client.log after +# recv bytes > 0 from the per-path stats in client.log after # SIGTERM. Without NET_ADMIN this sub-case prints a SKIP note; the # script continues and exits 0 (cases 1-5,7 decide the result, mirroring # e2e_gateway semantics). @@ -44,9 +44,8 @@ # Server C (default, 2-path for case 6): NET_ADMIN-gated only. # Server D (--scheduler backup, 2-path for case 8): NET_ADMIN-gated only. # -# Case 2 frag assertion: the frags_sent / frags_reassembled counters live on -# the per-conn mq_udp_srv struct and are logged at mq_udp_srv_free time -# (conn teardown, not per-session). So the assertion fires at Server A +# Case 2 frag assertion: the frags_sent / frags_reassembled counters are +# per-conn and logged at conn teardown (not per-session). So the assertion fires at Server A # teardown (after all A-group cases complete), by grepping server_a.log. # # SKIP DISCIPLINE (matches e2e_gateway): @@ -320,7 +319,7 @@ fi # datagrams (MSS is typically ~1200-1400 bytes). The byte-exact assertion is # handled by udpsocks internally (exit 0 = all sent/received/matched). # The frags_reassembled > 0 assertion happens at Server A teardown below -# (mq_udp_srv_free logs the stats line to server_a.log on conn close). +# (the server logs the stats line to server_a.log on conn close). if want 2; then if "${UDPSOCKS_BIN}" \ --proxy "127.0.0.1:${SOCKS_PORT_A}" \ @@ -452,7 +451,7 @@ fi # ── Tear down Server A group + assert case 2 frags_reassembled > 0 ─────────── # SIGTERM the client first (normal teardown), then the server. -# mq_udp_srv_free → mq_udp_srv_dump_stats fires on server conn close, writing +# The server's conn close writes # "mq_udp_srv: stats frags_sent=... frags_reassembled=... ..." # to server_a.log. We wait for this line to appear after server exit. if [ "${NEED_A}" -eq 1 ]; then @@ -461,7 +460,7 @@ if [ "${NEED_A}" -eq 1 ]; then fi # Wait up to 3s for the stats line to appear (the server may not flush -# immediately; it writes on mq_udp_srv_free which runs at conn teardown). +# immediately; it writes at conn teardown). if want 2; then STATS_A="" for _ in $(seq 1 30); do @@ -538,7 +537,7 @@ want 4 && note "case 4 PASS (${PASS_COUNT} checks so far)." # Requires tc/netem on lo (NET_ADMIN). Without it: print a note and exit 0 # (cases 1-5 already passed). With it: shape two equal-rate loopback paths, # start a client bound to both --path IPs, send a packet, SIGTERM the client, -# and confirm BOTH paths carried bytes via `mq_conn_dump_stats` in client.log. +# and confirm BOTH paths carried bytes via the per-path stats in client.log. if want 6 || want 8; then RATE="50mbit"; DELAY="10ms" can_tc=0 @@ -599,12 +598,12 @@ if want 6 || want 8; then exit 1 fi - # SIGTERM the client → it dumps mq_conn_dump_stats per-path counters to client_c.log. + # SIGTERM the client → it dumps per-path counters to client_c.log. stop_process "${CLIENT_C_PID}"; CLIENT_C_PID="" # Assert both paths carried bytes: "mq.path id= ... sent= recv= ..." lines - # where (sent > 0 OR recv > 0). The client logs these at INFO on SIGTERM via - # mq_conn_dump_stats (same pattern as e2e_multipath and e2e_gateway case 8). + # where (sent > 0 OR recv > 0). The client logs these at INFO on SIGTERM + # (same pattern as e2e_multipath and e2e_gateway case 8). PATHS_WITH_BYTES="$(grep -E 'mq\.path id=' \ "${WORK}/client_c.log" 2>/dev/null \ | sed -E 's/.*mq\.path id=([0-9]+).*sent=([0-9]+) recv=([0-9]+).*/\1 \2 \3/' \ @@ -625,12 +624,12 @@ if want 6 || want 8; then # ───────────────────────────────────────────────────────────────────────────── # tc shaping is already active from case 6 (same two loopback paths). # We start a fresh server+client pair with --scheduler backup on BOTH sides, - # send a substantial burst, SIGTERM the client to flush mq_conn_dump_stats, + # send a substantial burst, SIGTERM the client to flush the per-path stats, # then assert that the busiest single path holds >=95% of total bytes. # The 5% headroom covers path-validation / mp-ping control traffic on the # secondary path, which the backup scheduler still uses for keepalives. # The pin is enforced by the backup scheduler TOGETHER WITH the STANDBY - # marking of extra paths in mq_conn_add_path / mq_h3_conn_add_path — without + # marking of extra paths when they are added — without # the standby marking, backup degenerates to minrtt-with-spill under # saturating load (it pins only while the best path has cwnd headroom). # Inverse of case 6: same shaped 2-path topology, but case 6 asserts the @@ -673,7 +672,7 @@ if want 6 || want 8; then exit 1 fi - # SIGTERM the client → flushes mq_conn_dump_stats per-path counters. + # SIGTERM the client → flushes the per-path counters. stop_process "${CLIENT_D_PID}"; CLIENT_D_PID="" # primary-pin assertion: with --scheduler backup, >=95% of bytes on one path.