From 3fe17e572563e34d412a4390fb2be75e6d1b2cd6 Mon Sep 17 00:00:00 2001 From: Luke Curley Date: Wed, 12 Aug 2026 09:04:35 -0700 Subject: [PATCH] refactor(moq-native)!: name the endpoint roles connect and listen The config surface spelled every transport knob twice, `--client-*` and `--server-*`, backed by duplicated quic::Client/quic::Server and tls::Client/tls::Server type definitions. Keep the two roles apart, since most knobs really do belong to one of them, and fix the naming instead. moq_native::connect::Config (--connect-*) is the dial side and moq_native::listen::Config (--listen-*) the accept side, each owning short unprefixed names. The tuning that means the same thing whichever way a connection was opened moves to one shared quic::Config (--quic-*), handed to each role at init; clap cannot flatten one struct twice, so per-role tuning would mean duplicate definitions that drift. backend and version stay per-role: a quiche acceptor with a quinn dialer is a real setup, and a per-role version lets a relay pin its mesh wire version without narrowing what it accepts. Splitting tls is what separates the two trust stores again: connect.tls.root verifies servers you dial, listen.tls.root authenticates mTLS clients, and the dialing identity drops its client_ prefix since the module now supplies the role. The accept-only QUIC knobs (preferred address, QUIC-LB) move onto listen. Reconnecting is the default, so the flag names the exception: connect.once (--connect-once) replaces the released `reconnect` pair of flag and TOML key, which keep working inverted. Every released flag and env var still configures the same thing, which tests/released_cli.rs freezes: the published moq-relay surface, checked against the parser this build has. Writing it found the hole. A clap alias carries the flag name and not the env var, so 20 released variables parsed as before while being silently ignored in the environment, including the MOQ_SERVER_BIND and MOQ_SERVER_TLS_* that this repo's own nix module and fly.toml set. Each released spelling now lives on a hidden arg carrying its original env var, folded by resolved() with a deprecation warning. Three more bugs came out of the same audit. listen::Config::init never resolved the quic section, dropping --server-quic-max-streams entirely, so Client::new and Server::new now resolve their own inputs. Relay::load filled in DEFAULT_MAX_STREAMS before the fold ran, and the fold prefers the canonical field, so a relay still using the released spelling was pinned to 10,000 streams. And --websocket-enabled/--websocket-delay carried a clap default_value, which the post-file CLI re-parse materializes over whatever a config file said. Closes #2696 Co-Authored-By: Claude Opus 5 Co-Authored-By: Claude Fable 5 --- demo/boy/justfile | 2 +- demo/justfile | 6 +- demo/pub/justfile | 14 +- demo/relay/leaf0.toml | 6 +- demo/relay/leaf1.toml | 6 +- demo/relay/localhost.toml | 4 +- demo/relay/prod.toml | 6 +- demo/relay/root.toml | 4 +- doc/bin/cli.md | 100 ++-- doc/bin/hls.md | 10 +- doc/bin/index.md | 2 +- doc/bin/relay/auth.md | 22 +- doc/bin/relay/cluster.md | 2 +- doc/bin/relay/config.md | 63 ++- doc/bin/relay/index.md | 6 +- doc/bin/rtc.md | 2 +- doc/bin/rtmp.md | 8 +- doc/concept/standard/interop.md | 6 +- doc/lib/rs/crate/hang.md | 4 +- doc/lib/rs/crate/moq-mux.md | 4 +- doc/lib/rs/env/native.md | 2 +- doc/lib/rs/index.md | 6 +- doc/setup/windows.md | 4 +- nix/modules/moq-relay.nix | 10 +- rs/hang/examples/subscribe.rs | 2 +- rs/hang/examples/video.rs | 2 +- rs/libmoq/src/api.rs | 63 +-- rs/libmoq/src/client.rs | 27 +- rs/libmoq/src/session.rs | 6 +- rs/libmoq/src/test.rs | 11 +- rs/moq-bench/README.md | 6 +- rs/moq-bench/src/config.rs | 13 +- rs/moq-bench/src/connection.rs | 2 +- rs/moq-bench/src/main.rs | 8 +- rs/moq-boy/src/main.rs | 19 +- rs/moq-cli/README.md | 12 +- rs/moq-cli/src/args.rs | 63 ++- rs/moq-cli/src/cluster.rs | 64 +-- rs/moq-cli/src/hls.rs | 2 +- rs/moq-cli/src/main.rs | 21 +- rs/moq-cli/src/transcode.rs | 2 +- rs/moq-cli/src/web.rs | 2 +- rs/moq-ffi/src/server.rs | 6 +- rs/moq-ffi/src/session.rs | 16 +- rs/moq-gst/src/sink/session.rs | 6 +- rs/moq-gst/src/source/imp.rs | 6 +- rs/moq-native/examples/chat.rs | 2 +- rs/moq-native/examples/clock.rs | 10 +- rs/moq-native/src/client.rs | 499 +++++++++----------- rs/moq-native/src/connect.rs | 357 ++++++++++++++- rs/moq-native/src/connection.rs | 16 +- rs/moq-native/src/error.rs | 4 + rs/moq-native/src/failover.rs | 28 +- rs/moq-native/src/iroh.rs | 6 +- rs/moq-native/src/lib.rs | 7 +- rs/moq-native/src/listen.rs | 376 +++++++++++++++ rs/moq-native/src/noq.rs | 28 +- rs/moq-native/src/quic.rs | 603 ++++++++++++++----------- rs/moq-native/src/quiche.rs | 27 +- rs/moq-native/src/quinn.rs | 58 ++- rs/moq-native/src/server.rs | 169 +++---- rs/moq-native/src/tcp.rs | 77 +++- rs/moq-native/src/tls.rs | 537 ++++++++++++++++++---- rs/moq-native/src/unix.rs | 205 ++++++++- rs/moq-native/src/websocket.rs | 153 ++++++- rs/moq-native/tests/alpn.rs | 20 +- rs/moq-native/tests/backend.rs | 51 ++- rs/moq-native/tests/broadcast.rs | 234 +++++----- rs/moq-native/tests/reconnect.rs | 4 +- rs/moq-relay/fly.toml | 2 +- rs/moq-relay/src/auth.rs | 22 +- rs/moq-relay/src/config.rs | 246 ++++++++-- rs/moq-relay/src/internal.rs | 2 +- rs/moq-relay/src/relay.rs | 20 +- rs/moq-relay/src/web.rs | 2 +- rs/moq-relay/tests/cluster_unknown.rs | 18 +- rs/moq-relay/tests/goaway_cluster.rs | 50 +- rs/moq-relay/tests/released_cli.rs | 193 ++++++++ rs/moq-relay/tests/smoke.rs | 34 +- rs/moq-rtmp/README.md | 4 +- rs/moq-rtmp/src/listen.rs | 2 +- rs/moq-rtmp/src/server.rs | 4 +- rs/moq-transcode/examples/transcode.rs | 2 +- test/smoke/smoke.sh | 4 +- test/ts/README.md | 2 +- test/ts/run.sh | 4 +- 86 files changed, 3270 insertions(+), 1470 deletions(-) create mode 100644 rs/moq-native/src/listen.rs create mode 100644 rs/moq-relay/tests/released_cli.rs diff --git a/demo/boy/justfile b/demo/boy/justfile index 45b7e60bbf9..9312d15bd55 100644 --- a/demo/boy/justfile +++ b/demo/boy/justfile @@ -51,7 +51,7 @@ gb-run: # Start a Game Boy emulator publisher. start rom url='http://localhost:4443': - cargo run --bin moq-boy -- --client-connect "{{ url }}" --rom "{{ rom }}" --location localhost + cargo run --bin moq-boy -- --connect "{{ url }}" --rom "{{ rom }}" --location localhost # Host the web server web url='http://localhost:4443': diff --git a/demo/justfile b/demo/justfile index 36628528619..bfd725f82d1 100644 --- a/demo/justfile +++ b/demo/justfile @@ -11,7 +11,7 @@ mod web # Picks the first free port at/after 4443 (both UDP for QUIC and TCP for HTTP) # so multiple worktrees can run `just dev` without colliding. The relay reads -# the port from MOQ_SERVER_BIND/MOQ_WEB_HTTP_LISTEN, overriding localhost.toml. +# the port from MOQ_LISTEN/MOQ_WEB_HTTP_LISTEN, overriding localhost.toml. default: #!/usr/bin/env bash set -euo pipefail @@ -25,10 +25,10 @@ default: base="http://localhost:$port" # Scope the bind env vars to the relay only. The unified `moq` binary also - # reads MOQ_SERVER_BIND, so exporting it globally would make the `pub` client + # reads MOQ_LISTEN, so exporting it globally would make the `pub` client # try to start a server (and fail without a TLS cert). bun run concurrently --kill-others --names rly,bbb,web --prefix-colors auto \ - "MOQ_SERVER_BIND='[::]:$port' MOQ_WEB_HTTP_LISTEN='[::]:$port' just relay" \ + "MOQ_LISTEN='[::]:$port' MOQ_WEB_HTTP_LISTEN='[::]:$port' just relay" \ "just wait $base/certificate.sha256 && just pub bbb $base" \ "just wait $base/certificate.sha256 && just web serve $base" diff --git a/demo/pub/justfile b/demo/pub/justfile index 8d8886fc614..4df3d7c813f 100644 --- a/demo/pub/justfile +++ b/demo/pub/justfile @@ -48,18 +48,18 @@ tos url='http://localhost:4443' *args: # Publish a video using ffmpeg (CMAF / fMP4) to a relay server. cmaf name url='http://localhost:4443' *args: cargo build --bin moq - just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --client-connect "{{ url }}" --broadcast "{{ name }}.hang" import fmp4 + just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --connect "{{ url }}" --broadcast "{{ name }}.hang" import fmp4 # Publish a video using ffmpeg (MPEG-TS) to a relay server. ts name url='http://localhost:4443' *args: cargo build --bin moq - just ffmpeg-ts "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --client-connect "{{ url }}" --broadcast "{{ name }}.hang" import ts + just ffmpeg-ts "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --connect "{{ url }}" --broadcast "{{ name }}.hang" import ts # Publish a video via iroh. iroh name url prefix="": just download "{{ name }}" cargo build --bin moq - just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- --iroh-enabled --client-connect "{{ url }}" --broadcast "{{ prefix }}{{ name }}.hang" import fmp4 + just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- --iroh-enabled --connect "{{ url }}" --broadcast "{{ prefix }}{{ name }}.hang" import fmp4 # Generate and ingest an HLS stream from a video file. hls name relay="http://localhost:4443": @@ -131,7 +131,7 @@ hls name relay="http://localhost:4443": trap cleanup SIGINT SIGTERM EXIT echo ">>> Importing HLS via moq-cli" - cargo run --bin moq -- --client-connect "{{ relay }}" --broadcast "{{ name }}.hang" import hls "$OUT_DIR/master.m3u8" + cargo run --bin moq -- --connect "{{ relay }}" --broadcast "{{ name }}.hang" import hls "$OUT_DIR/master.m3u8" EXIT_CODE=$? cleanup @@ -148,13 +148,13 @@ h264 name url="http://localhost:4443" *args: -c:v copy -an \ -bsf:v h264_mp4toannexb \ -f h264 \ - - | cargo run --bin moq -- {{ args }} --client-connect "{{ url }}" --broadcast "{{ name }}.hang" import avc3 + - | cargo run --bin moq -- {{ args }} --connect "{{ url }}" --broadcast "{{ name }}.hang" import avc3 # Publish a video using ffmpeg directly from moq to the localhost. serve name *args: just download "{{ name }}" cargo build --bin moq - just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --server-bind "[::]:4443" --tls-generate "localhost" --broadcast "{{ name }}.hang" import fmp4 + just ffmpeg-cmaf "media/{{ name }}.mp4" | cargo run --bin moq -- {{ args }} --listen "[::]:4443" --listen-tls-generate "localhost" --broadcast "{{ name }}.hang" import fmp4 # Generate and serve an HLS stream from a video for testing. serve-hls name port="8000": @@ -205,7 +205,7 @@ clock action url="http://localhost:4443" *args: exit 1; \ fi - cargo run -p moq-native --example clock -- --client-connect "{{ url }}" --broadcast "clock" {{ args }} {{ action }} + cargo run -p moq-native --example clock -- --connect "{{ url }}" --broadcast "clock" {{ args }} {{ action }} # --- GStreamer --- diff --git a/demo/relay/leaf0.toml b/demo/relay/leaf0.toml index fb091655d24..809fe479f13 100644 --- a/demo/relay/leaf0.toml +++ b/demo/relay/leaf0.toml @@ -3,10 +3,10 @@ # The RUST_LOG environment variable will take precedence. level = "debug" -[server] +[listen] # Listen for QUIC connections on UDP:4444 # Sometimes IPv6 causes issues; try 127.0.0.1:4444 instead. -listen = "[::]:4444" +bind = "[::]:4444" # Serve the same cluster-signed certificate that we present as a client, # so other leaves can verify us against `ca.pem`. @@ -19,7 +19,7 @@ tls.key = ["leaf0.key"] # the JWT path and are rejected. tls.root = ["ca.pem"] -[client] +[connect] # Present this certificate and key on outbound cluster connections. # The root maps a valid cert to full access. tls.cert = "leaf0.crt" diff --git a/demo/relay/leaf1.toml b/demo/relay/leaf1.toml index c250ea9b277..682d9ac73a0 100644 --- a/demo/relay/leaf1.toml +++ b/demo/relay/leaf1.toml @@ -3,10 +3,10 @@ # The RUST_LOG environment variable will take precedence. level = "debug" -[server] +[listen] # Listen for QUIC connections on UDP:4445 # Sometimes IPv6 causes issues; try 127.0.0.1:4445 instead. -listen = "[::]:4445" +bind = "[::]:4445" # Serve the same cluster-signed certificate that we present as a client, # so other leaves can verify us against `ca.pem`. @@ -19,7 +19,7 @@ tls.key = ["leaf1.key"] # the JWT path and are rejected. tls.root = ["ca.pem"] -[client] +[connect] # Present this certificate and key on outbound cluster connections. # The root maps a valid cert to full access. tls.cert = "leaf1.crt" diff --git a/demo/relay/localhost.toml b/demo/relay/localhost.toml index 6e92ea461cc..66573fd0a07 100644 --- a/demo/relay/localhost.toml +++ b/demo/relay/localhost.toml @@ -6,10 +6,10 @@ # The RUST_LOG environment variable will take precedence. level = "debug" -[server] +[listen] # Listen for QUIC connections on UDP:4443 # Sometimes IPv6 causes issues; try 127.0.0.1:4443 instead. -listen = "[::]:4443" +bind = "[::]:4443" # Generate a self-signed certificate for the given hostnames. # This is used for local development, in conjunction with a fingerprint, or with TLS verification disabled. diff --git a/demo/relay/prod.toml b/demo/relay/prod.toml index 4726b28ff53..72ad26225bc 100644 --- a/demo/relay/prod.toml +++ b/demo/relay/prod.toml @@ -1,12 +1,12 @@ # An example of a production configuration. # Here's a real one: https://github.com/moq-dev/moq.dev/blob/b4da7dd8f09879cefb593d5e35f99f064caa3943/infra/relay.yml.tpl#L56 -[server] +[listen] # Listen for QUIC connections on UDP:443 # This is the default port for WebTransport -listen = "[::]:443" +bind = "[::]:443" -[server.tls] +[listen.tls] # You'll need to provide a real certificate and key in production. # You can get this via a service like Let's Encrypt. cert = "cert.pem" diff --git a/demo/relay/root.toml b/demo/relay/root.toml index 05e6c23af27..5afdb6125dc 100644 --- a/demo/relay/root.toml +++ b/demo/relay/root.toml @@ -3,10 +3,10 @@ # The RUST_LOG environment variable will take precedence. level = "debug" -[server] +[listen] # Listen for QUIC connections on UDP:4443 # Sometimes IPv6 causes issues; try 127.0.0.1:4443 instead. -listen = "[::]:4443" +bind = "[::]:4443" # Server certificate and key signed by the cluster CA so leaves can # verify via `tls.root`. `just cert root` generates these files. diff --git a/doc/bin/cli.md b/doc/bin/cli.md index ee232259f76..5ef7f55056f 100644 --- a/doc/bin/cli.md +++ b/doc/bin/cli.md @@ -41,7 +41,7 @@ docker pull moqdev/moq-cli # moq-cli reads media from stdin, so pipe an MPEG-TS stream into the container. # `-i` forwards stdin to the container process. ffmpeg -i video.mp4 -c copy -f mpegts - | \ - docker run -i moqdev/moq-cli --client-connect https://relay.example.com/anon --broadcast my-stream.hang import ts + docker run -i moqdev/moq-cli --connect https://relay.example.com/anon --broadcast my-stream.hang import ts ``` Multi-arch images (`linux/amd64` and `linux/arm64`) are published to [Docker Hub](https://hub.docker.com/r/moqdev/moq-cli). @@ -80,11 +80,11 @@ moq play [playback options] - **MoQ side** attaches the Origin to the network, and comes before the verb. At least one of: - - `--client-connect ` dials a relay. The URL path is the relay auth path + - `--connect ` dials a relay. The URL path is the relay auth path (e.g. `/anon`), `?jwt=` supplies a token, and `--broadcast` names the broadcast. - - `--server-bind ` hosts MoQ sessions directly (with `--tls-generate` / - `--tls-cert` + `--tls-key`). + - `--listen ` hosts MoQ sessions directly (with `--listen-tls-generate` / + `--listen-tls-cert` + `--listen-tls-key`). - `--cluster-lan` meshes with every other participating process on the LAN via mDNS, no relay or internet needed. See [LAN Cluster](#lan-cluster-mdns). @@ -124,7 +124,7 @@ cargo install moq-cli --no-default-features --features "iroh,quinn,websocket,pla cargo build --release -p moq-cli --no-default-features --features "iroh,quinn,websocket,play" # or run straight from that checkout: cargo run -p moq-cli --no-default-features --features "iroh,quinn,websocket,play" -- \ - --client-connect https://relay.example.com/anon --broadcast my-stream.hang play + --connect https://relay.example.com/anon --broadcast my-stream.hang play ``` Drop the defaults on Linux, as above: the default `pipewire` feature links @@ -148,7 +148,7 @@ there. Once built, play a broadcast with: ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang play +moq --connect https://relay.example.com/anon --broadcast my-stream.hang play ``` `play` starts each media role as soon as the catalog offers a rendition it can @@ -169,7 +169,7 @@ Playback decodes h264, h265, and av1 video, and opus and pcm audio, so skipped and defaults to `500ms`. These flags all follow the `play` verb: ```bash -moq --client-connect https://relay.example.com/anon --broadcast conference.hang \ +moq --connect https://relay.example.com/anon --broadcast conference.hang \ play --video-name hd --audio-name en --latency-max 250ms ``` @@ -184,7 +184,7 @@ Remux a file to MPEG-TS and pipe it in (`-c copy` avoids re-encoding): ```bash ffmpeg -i video.mp4 -c copy -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang import ts + moq --connect https://relay.example.com/anon --broadcast my-stream.hang import ts ``` ### Captions @@ -210,20 +210,20 @@ ffmpeg -i video.mp4 -c copy -f mpegts - | \ moq --cluster-lan --broadcast lan-demo.hang export ts | mpv - ``` -Peers connect to the `--server-bind` listener, which `--cluster-lan` fills in +Peers connect to the `--listen` listener, which `--cluster-lan` fills in when you haven't: an ephemeral port with a generated certificate, whose SHA-256 fingerprint rides along in the advertisement. Dialers pin that fingerprint, so -sessions are encrypted without a CA. Pass `--server-bind` yourself to put the +sessions are encrypted without a CA. Pass `--listen` yourself to put the mesh on a fixed port and your own certificate, shared with ordinary viewers. It composes with the other MoQ sides. The common pairing is a LAN mesh plus a -CDN for everyone else: `--cluster-lan --client-connect +CDN for everyone else: `--cluster-lan --connect https://relay.example.com/anon` serves viewers on the same network directly while the relay serves external ones, all from one process and one set of broadcasts. With `--cluster-lan` alone nothing leaves the local network. By default anyone who can reach the listener joins, exactly like a bare -`--server-bind`, so use it on networks you trust. On a network you don't +`--listen`, so use it on networks you trust. On a network you don't control, generate a key and give the same one to every peer: ```bash @@ -265,8 +265,8 @@ joining. Run the same command from two aligned encoders, pinning the same id on both: ```bash -moq --origin 42 --client-connect https://relay-a.example.com/anon --broadcast event.hang import ts -moq --origin 42 --client-connect https://relay-b.example.com/anon --broadcast event.hang import ts +moq --origin 42 --connect https://relay-a.example.com/anon --broadcast event.hang import ts +moq --origin 42 --connect https://relay-b.example.com/anon --broadcast event.hang import ts ``` Leave `--origin` unset everywhere else. The default fresh id per run is what @@ -290,25 +290,25 @@ Build (or run) with the feature enabled: ```bash cargo build --release -p moq-cli --features capture # or run straight from a checkout: -cargo run -p moq-cli --features capture -- --client-connect https://relay.example.com/anon --broadcast cam.hang import capture +cargo run -p moq-cli --features capture -- --connect https://relay.example.com/anon --broadcast cam.hang import capture # Default camera + microphone, hardware-encoded H.264 when available: -moq --client-connect https://relay.example.com/anon --broadcast cam.hang import capture +moq --connect https://relay.example.com/anon --broadcast cam.hang import capture # Pick devices, resolution, and bitrates: -moq --client-connect https://relay.example.com/anon --broadcast cam.hang \ +moq --connect https://relay.example.com/anon --broadcast cam.hang \ import capture --camera 0 --width 1280 --height 720 --fps 30 --bitrate 3000000 \ --microphone "MacBook Pro Microphone" --audio-bitrate 64000 # One medium only: -moq --client-connect https://relay.example.com/anon --broadcast cam.hang import capture --no-audio -moq --client-connect https://relay.example.com/anon --broadcast cam.hang import capture --no-video +moq --connect https://relay.example.com/anon --broadcast cam.hang import capture --no-audio +moq --connect https://relay.example.com/anon --broadcast cam.hang import capture --no-video # Pick a codec (default h264). h265 is hardware-only: -moq --client-connect https://relay.example.com/anon --broadcast cam.hang import capture --codec h265 +moq --connect https://relay.example.com/anon --broadcast cam.hang import capture --codec h265 # Capture a display instead of a camera: -moq --client-connect https://relay.example.com/anon --broadcast screen.hang import capture --display --no-audio +moq --connect https://relay.example.com/anon --broadcast screen.hang import capture --display --no-audio ``` ### Pick a source @@ -344,15 +344,15 @@ Microphones: ```bash # A single window, followed as it moves and resizes (macOS only): -moq --client-connect https://relay.example.com/anon --broadcast win.hang \ +moq --connect https://relay.example.com/anon --broadcast win.hang \ import capture --window 39193 --no-audio # Every window of an application, including ones opened later (macOS only): -moq --client-connect https://relay.example.com/anon --broadcast app.hang \ +moq --connect https://relay.example.com/anon --broadcast app.hang \ import capture --app com.apple.Safari --no-audio # A specific display, without the mouse cursor: -moq --client-connect https://relay.example.com/anon --broadcast screen.hang \ +moq --connect https://relay.example.com/anon --broadcast screen.hang \ import capture --display 1 --no-cursor --no-audio ``` @@ -363,7 +363,7 @@ you usually want next to a screen share: ```bash # Share a screen with its sound (macOS only): -moq --client-connect https://relay.example.com/anon --broadcast screen.hang \ +moq --connect https://relay.example.com/anon --broadcast screen.hang \ import capture --display --system-audio ``` @@ -404,12 +404,12 @@ loopback input device, so it goes through ScreenCaptureKit (the same API as screen capture, and the same Screen Recording permission) rather than cpal. `--bitrate` is a ceiling rather than a fixed rate. When publishing with -`--client-connect`, the video encoder follows the connection's congestion +`--connect`, the video encoder follows the connection's congestion estimate: it drops below the ceiling as soon as the uplink tightens, and climbs back gradually once it clears, so a degrading network costs picture quality instead of stalling the stream. It never encodes above `--bitrate`. Encoders that can't retune while running (VAAPI today) hold the configured rate and log a -warning. Without `--client-connect` there is no estimate to follow, so the +warning. Without `--connect` there is no estimate to follow, so the configured rate is used as-is. Alternatively, pipe an external FFmpeg process as MPEG-TS: @@ -417,11 +417,11 @@ Alternatively, pipe an external FFmpeg process as MPEG-TS: ```bash # macOS ffmpeg -f avfoundation -i "0:0" -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast webcam.hang import ts + moq --connect https://relay.example.com/anon --broadcast webcam.hang import ts # Linux ffmpeg -f v4l2 -i /dev/video0 -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast webcam.hang import ts + moq --connect https://relay.example.com/anon --broadcast webcam.hang import ts ``` ### Transcode a Broadcast @@ -437,14 +437,14 @@ cargo build --release -p moq-cli --features transcode # Publish `cam.hang/transcode.hang` with the default ladder (1080p..240p, # filtered to rungs strictly below the source): -moq --client-connect https://relay.example.com/anon --broadcast cam.hang transcode +moq --connect https://relay.example.com/anon --broadcast cam.hang transcode # Pick the ladder (height:bitrate in bits per second) and pin the codecs: -moq --client-connect https://relay.example.com/anon --broadcast cam.hang transcode --rung 720:2500000 --rung 360:600000 --encoder nvenc --decoder nvdec +moq --connect https://relay.example.com/anon --broadcast cam.hang transcode --rung 720:2500000 --rung 360:600000 --encoder nvenc --decoder nvdec # Publish the derivative somewhere else (the catalog then omits the relative # source references): -moq --client-connect https://relay.example.com/anon --broadcast cam.hang transcode --output ladder.hang +moq --connect https://relay.example.com/anon --broadcast cam.hang transcode --output ladder.hang ``` Windows uses the Direct3D11 video processor by default. Pass @@ -461,7 +461,7 @@ default; drop the default features for a software-only build. Pull a broadcast back out and play it: ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang export fmp4 | ffplay - +moq --connect https://relay.example.com/anon --broadcast my-stream.hang export fmp4 | ffplay - ``` ## Encoding Options @@ -473,7 +473,7 @@ ffmpeg -i input.mp4 \ -c:v libx264 -preset ultrafast -tune zerolatency \ -g 30 -keyint_min 30 \ -c:a aac \ - -f mpegts - | moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang import ts + -f mpegts - | moq --connect https://relay.example.com/anon --broadcast my-stream.hang import ts ``` ## Container Formats @@ -497,7 +497,7 @@ egress (HLS/DASH), which may only advertise segments that are still fetchable; lower it when nothing reads history and the memory matters: ```bash -moq --client-connect https://relay.example.com --broadcast my-stream.hang import --latency-max 5s ts +moq --connect https://relay.example.com --broadcast my-stream.hang import --latency-max 5s ts ``` It sits on `import` itself rather than the endpoint, so it applies to every @@ -527,7 +527,7 @@ the sink subcommand here; `play` takes the same four after its own verb (see [Play a Broadcast](#play-a-broadcast)): ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ export --video-name 720p --audio-codec opus fmp4 | ffplay - ``` @@ -559,10 +559,10 @@ Ingest an MPEG-TS stream from FFmpeg and play one back out: ```bash # Import: remux a file to MPEG-TS and pipe it in ffmpeg -i input.mp4 -c copy -f mpegts - | \ - moq --client-connect https://relay.example.com --broadcast my-stream.hang import ts + moq --connect https://relay.example.com --broadcast my-stream.hang import ts # Export: pull MPEG-TS back out and play it -moq --client-connect https://relay.example.com --broadcast my-stream.hang export ts | ffplay - +moq --connect https://relay.example.com --broadcast my-stream.hang export ts | ffplay - ``` TS export carries H.264 / H.265 as Annex-B and AAC as ADTS. Both in-band @@ -590,10 +590,10 @@ captured: they are live or bulky rather than static identity. ```bash # Import: remux a file to FLV and pipe it in ffmpeg -i input.mp4 -c copy -f flv - | \ - moq --client-connect https://relay.example.com --broadcast my-stream.hang import flv + moq --connect https://relay.example.com --broadcast my-stream.hang import flv # Export: pull FLV back out and play it -moq --client-connect https://relay.example.com --broadcast my-stream.hang export flv | ffplay - +moq --connect https://relay.example.com --broadcast my-stream.hang export flv | ffplay - ``` FLV is the classic RTMP container: H.264 video and AAC audio, each with an @@ -605,7 +605,7 @@ older codecs (VP6, MP3) are not supported on the stdin/stdout container path. Import a remote HLS master/media playlist into a MoQ broadcast: ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ import hls https://example.com/live/master.m3u8 ``` @@ -613,7 +613,7 @@ Serve one MoQ broadcast as HLS over HTTP (reached at `http://host:8089//master.m3u8`): ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ export hls --listen '[::]:8089' ``` @@ -644,7 +644,7 @@ libraries' auth-aware API.) Accept OBS / FFmpeg RTMP pushes and forward one broadcast to a relay: ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ import rtmp --listen '[::]:1935' ``` @@ -653,7 +653,7 @@ moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ Pull a broadcast from a relay and push it to a remote RTMP server: ```bash -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ export rtmp --connect 'rtmp://live.twitch.tv/app/' ``` @@ -661,10 +661,10 @@ moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ ```bash # Accept incoming SRT publishes as one broadcast and forward to a relay -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang import srt --listen '[::]:9000' +moq --connect https://relay.example.com/anon --broadcast my-stream.hang import srt --listen '[::]:9000' # Serve a broadcast to SRT players -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang export srt --listen '[::]:9000' +moq --connect https://relay.example.com/anon --broadcast my-stream.hang export srt --listen '[::]:9000' ``` ### WebRTC (WHIP / WHEP) @@ -675,10 +675,10 @@ Direction picks the HTTP role: import `--listen` is a WHIP server, export ```bash # WHIP ingest: browsers publish one broadcast to us, we forward to a relay -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang import rtc --listen '[::]:8080' +moq --connect https://relay.example.com/anon --broadcast my-stream.hang import rtc --listen '[::]:8080' # WHEP playback: serve a broadcast to browsers -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang export rtc --listen '[::]:8080' +moq --connect https://relay.example.com/anon --broadcast my-stream.hang export rtc --listen '[::]:8080' ``` The WHIP/WHEP HTTP listener does not allow cross-origin browser access unless @@ -691,7 +691,7 @@ Pass a JWT token via the URL's `?jwt=` query parameter: ```bash ffmpeg -i video.mp4 -c copy -f mpegts - | \ - moq --client-connect "https://relay.example.com/?jwt=" --broadcast my-stream.hang import ts + moq --connect "https://relay.example.com/?jwt=" --broadcast my-stream.hang import ts ``` `moq token` mints those tokens, so a relay operator needs no extra tool: @@ -733,7 +733,7 @@ just pub tos https://relay.example.com/anon ```bash ffmpeg -i video.mp4 -c copy -f mpegts - | \ - RUST_LOG=debug moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang import ts + RUST_LOG=debug moq --connect https://relay.example.com/anon --broadcast my-stream.hang import ts ``` ### Check Connection diff --git a/doc/bin/hls.md b/doc/bin/hls.md index d531b4c5cb9..872b8bc5959 100644 --- a/doc/bin/hls.md +++ b/doc/bin/hls.md @@ -71,23 +71,23 @@ The gateway ships as `moq import hls` / `moq export hls` (see ```bash # export: expose a MoQ broadcast as HLS over HTTP -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ export hls --listen '[::]:8089' # then point a player at the broadcast: # http://localhost:8089/my-stream.hang/master.m3u8 # import: pull a remote HLS playlist into MoQ -moq --client-connect https://relay.example.com/anon --broadcast my-stream.hang \ +moq --connect https://relay.example.com/anon --broadcast my-stream.hang \ import hls https://example.com/live/master.m3u8 ``` ### `export hls` flags - `--listen`: HTTP bind address (default `[::]:8089`). -- `--tls-cert` / `--tls-key`: serve HTTPS from a cert/key pair on disk. Most - players require HTTPS. `--tls-generate ` instead generates a - self-signed cert, and `--server-tls-root` enables optional mTLS client auth. +- `--listen-tls-cert` / `--listen-tls-key`: serve HTTPS from a cert/key pair on disk. Most + players require HTTPS. `--listen-tls-generate ` instead generates a + self-signed cert, and `--listen-tls-root` enables optional mTLS client auth. - `--window`: minimum duration of media listed per rendition playlist (default `16s`, humantime syntax). Keep it within the relay's group-cache retention, since segments are fetched from there on request. diff --git a/doc/bin/index.md b/doc/bin/index.md index a882ca263a7..d408371d675 100644 --- a/doc/bin/index.md +++ b/doc/bin/index.md @@ -26,7 +26,7 @@ Another tool does the encoding (ex. ffmpeg), making it easy to pipe any media in ```bash # Publish your webcam -ffmpeg -f avfoundation -i "0" -f mpegts - | moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts +ffmpeg -f avfoundation -i "0" -f mpegts - | moq --connect https://relay.example.com/anon --broadcast my-stream import ts ``` ## [moq-rtc](/bin/rtc) diff --git a/doc/bin/relay/auth.md b/doc/bin/relay/auth.md index 7677a790cfd..5f631b90a39 100644 --- a/doc/bin/relay/auth.md +++ b/doc/bin/relay/auth.md @@ -215,10 +215,10 @@ Unlike the standalone flags, the unified call **fails closed**: any network erro ### Authenticating the relay to the auth API -The outbound HTTP the relay makes for auth (`--auth-api` requests and JWK fetches) reuses the cluster client's TLS configuration. The same `--client-tls-cert` / `--client-tls-key` the relay presents when dialing cluster peers also identifies it to the auth API, and `--client-tls-root` trusts a private CA on the endpoint (env `MOQ_CLIENT_TLS_*`, or `[client.tls]` in TOML). So an auth API can require mTLS and recognize the relay by the same certificate it uses for clustering. +The outbound HTTP the relay makes for auth (`--auth-api` requests and JWK fetches) reuses the cluster dial TLS configuration. The same `--connect-tls-cert` / `--connect-tls-key` the relay presents when dialing cluster peers also identifies it to the auth API, and `--connect-tls-root` trusts a private CA on the endpoint (env `MOQ_CONNECT_TLS_*`, or `[connect.tls]` in TOML). So an auth API can require mTLS and recognize the relay by the same certificate it uses for clustering. ```toml -[client.tls] +[connect.tls] cert = "/etc/moq/relay-client.pem" key = "/etc/moq/relay-client.key" root = ["/etc/moq/auth-api-ca.pem"] @@ -275,7 +275,7 @@ Client certificate presentation is **optional**: connections without a certificate fall through to the normal JWT path unchanged. ```toml -[server.tls] +[listen.tls] cert = ["/etc/moq/server.pem"] key = ["/etc/moq/server.key"] # One or more PEM files containing the CAs trusted to sign peer certificates. @@ -295,7 +295,7 @@ backend that does not (e.g. `quiche`) is a startup error. For trusted local workers that don't want the overhead of TLS or UDP, the relay can also listen for the qmux wire format directly over a plain stream: TCP -(`--server-tcp-bind`) or a Unix socket (`--server-unix-bind`). These listeners +(`--listen-tcp-bind`) or a Unix socket (`--listen-unix-bind`). These listeners authenticate **through the same path as QUIC**: a JWT (carried in the moq-lite-05 SETUP path as `/broadcast?jwt=`) is verified and scopes the session, so a memory-safety bug in an out-of-process gateway can reach only what its users' @@ -309,10 +309,10 @@ grant it publicly, e.g. `--auth-public-publish .stats` for a stats publisher. ### TCP ```toml -[server] +[listen] bind = "[::]:443" # QUIC; omit to run stream-only -[server.tcp] +[listen.tcp] bind = "127.0.0.1:4444" ``` @@ -322,7 +322,7 @@ logs a warning when the address is not loopback but does not refuse to start, so firewalling the port is your responsibility. ```bash -moq --client-connect "tcp://127.0.0.1:4444/my-broadcast.hang?jwt=$TOKEN" import fmp4 < video.mp4 +moq --connect "tcp://127.0.0.1:4444/my-broadcast.hang?jwt=$TOKEN" import fmp4 < video.mp4 ``` ### Unix socket (with a uid/gid/pid allowlist) @@ -330,16 +330,16 @@ moq --client-connect "tcp://127.0.0.1:4444/my-broadcast.hang?jwt=$TOKEN" import A Unix socket lets the relay additionally gate the connecting process by its kernel credentials (`SO_PEERCRED` / `LOCAL_PEERCRED`), so you can restrict access to a specific worker user. Requires the relay to be built with the `uds` -feature. The allowlist (`--server-unix-allow-uid` / `-gid` / `-pid`) applies to +feature. The allowlist (`--listen-unix-allow-uid` / `-gid` / `-pid`) applies to the `unix://` listener. ```toml -[server.unix] +[listen.unix] bind = "/run/moq/internal.sock" # Each list is matched independently (AND across fields, OR within a field); # an omitted field imposes no constraint. Empty = any local process. -[server.unix.allow] +[listen.unix.allow] uid = [1001] # gid = [2000] # pid = [12345] @@ -351,7 +351,7 @@ read. A pid requirement rejects peers whose PID the platform doesn't report of the JWT, not a replacement for it. ```bash -moq --client-connect "unix:///run/moq/internal.sock/?jwt=$TOKEN" --broadcast my-broadcast.hang import fmp4 < video.mp4 +moq --connect "unix:///run/moq/internal.sock/?jwt=$TOKEN" --broadcast my-broadcast.hang import fmp4 < video.mp4 ``` ### Notes diff --git a/doc/bin/relay/cluster.md b/doc/bin/relay/cluster.md index 7af3c0352a8..1ba036cf244 100644 --- a/doc/bin/relay/cluster.md +++ b/doc/bin/relay/cluster.md @@ -149,7 +149,7 @@ If a fetch fails or returns garbage, the relay logs and keeps the last good list Cluster peers must authenticate to each other: -- **mTLS** (recommended). Set `tls.root` to the CA that signed the cluster certificates. Inbound connections presenting a valid client cert are granted full access; outbound dials use `client.tls.cert` / `client.tls.key`. +- **mTLS** (recommended). Set `tls.root` to the CA that signed the cluster certificates. Inbound connections presenting a valid client cert are granted full access; outbound dials use `connect.tls.cert` / `connect.tls.key`. - **JWT**. For static `connect` peers, supply the token inline as a `?jwt=` query parameter on the URL. For gossip- and `connect_api`-discovered peers (whose addresses can't carry an inline token), set `cluster.token` to a file holding the JWT; it's presented on any dial whose URL has no inline `?jwt=` (so an inline token wins per-peer). Either way the token needs broad enough scope to cover whatever paths the cluster carries. See [Authentication](/bin/relay/auth) for the full setup. diff --git a/doc/bin/relay/config.md b/doc/bin/relay/config.md index cd05fef608a..84b88014e2d 100644 --- a/doc/bin/relay/config.md +++ b/doc/bin/relay/config.md @@ -14,10 +14,10 @@ moq-relay relay.toml ## Minimal Example ```toml -[server] -listen = "0.0.0.0:4443" +[listen] +bind = "0.0.0.0:4443" -[server.tls] +[listen.tls] cert = "cert.pem" key = "key.pem" ``` @@ -45,7 +45,7 @@ Logging configuration. level = "info" ``` -### \[server] +### \[listen] QUIC/WebTransport server settings. Optionally add plaintext qmux stream listeners for trusted local workers. Every connection authenticates through the @@ -53,24 +53,24 @@ same JWT / public-access path; QUIC additionally accepts an mTLS client certificate, and Unix sockets add optional peer-credential gating. ```toml -[server] +[listen] # QUIC (UDP) bind. Omit to run stream-only (no QUIC) when a tcp/unix listener # is configured below. bind = "[::]:443" # Plaintext qmux over TCP (no TLS, carries no peer identity). Trusted networks # only; a non-loopback bind logs a warning. Requires the `tcp` build feature. -[server.tcp] +[listen.tcp] bind = "127.0.0.1:4444" # Plaintext qmux over a Unix socket, for local workers (e.g. the protocol # gateways or a stats publisher). Requires the `uds` build feature. Restrict # callers by peer credentials (each list AND across, OR within; empty = no # constraint). -[server.unix] +[listen.unix] bind = "/run/moq/internal.sock" -[server.unix.allow] +[listen.unix.allow] uid = [1001] # gid = [2000] # pid = [12345] @@ -80,12 +80,12 @@ No-JWT connections on the stream transports resolve through the same public-access rules as tokenless QUIC clients (see [`[auth]`](#auth) `public`). See [Stream Listeners](/bin/relay/auth#stream-listeners) for details. -### \[server.tls] +### \[listen.tls] TLS configuration for the QUIC endpoint. ```toml -[server.tls] +[listen.tls] # Option 1: Provide certificate files cert = "/path/to/cert.pem" # Certificate chain key = "/path/to/key.pem" # Private key @@ -110,7 +110,7 @@ HTTP server for debugging endpoints. [web.http] # Listen address for HTTP (TCP) # Defaults to disabled if not specified -listen = "0.0.0.0:4443" +bind = "0.0.0.0:4443" ``` See [HTTP Endpoints](/bin/relay/http) for available endpoints. @@ -139,7 +139,7 @@ HTTPS/WSS server for TCP fallback. # Listen address for HTTPS/WSS (TCP) listen = "0.0.0.0:443" -# TLS certificates (can be the same as server.tls) +# TLS certificates (can be the same as listen.tls) cert = "cert.pem" key = "key.pem" ``` @@ -204,18 +204,18 @@ secret = "/etc/moq/cluster.key" See [Clustering](/bin/relay/cluster) for topology choices and the trade-off between hand-listed peers and gossip. -### \[client] +### \[connect] Client settings used when connecting to other relays (clustering). ```toml -[client] +[connect] # Maximum time for one outbound dial and MoQ handshake. Defaults to 30s. # Set to "0" to wait forever. timeout = "30s" # Disable TLS verification (development only!) -tls.disable_verify = true +tls.insecure = true # What to do with the URI an upstream peer names in its GOAWAY: # "follow" (default), "same-host", or "ignore". A followed redirect is dialed @@ -242,34 +242,32 @@ goaway.handover = "10s" # each starting this long after the previous one (or immediately, if that one # fails outright), and the first connection to complete wins. "0s" dials every # address at once. Defaults to 250ms, RFC 8305's Connection Attempt Delay. -# failover_delay = "250ms" +# race = "250ms" ``` -The connect timeout is also available as `--client-connect-timeout` or -`MOQ_CLIENT_CONNECT_TIMEOUT`, and the failover delay as -`--client-failover-delay` or `MOQ_CLIENT_FAILOVER_DELAY`. The two compose: the -failover delay staggers the attempts within one dial, and the timeout bounds -that dial as a whole. +The connect timeout is also available as `--connect-timeout` or +`MOQ_CONNECT_TIMEOUT`, and the address race as `--connect-race` or +`MOQ_CONNECT_RACE`. The two compose: the race staggers the attempts within one +dial, and the timeout bounds that dial as a whole. -Pinning the source port (a non-zero port in `--client-bind`) disables address -failover on the `quiche` backend, which binds a fresh socket per attempt and so +Pinning the source port (a non-zero port in `--connect-bind`) disables address +racing on the `quiche` backend, which binds a fresh socket per attempt and so can only dial one address at a time from a fixed port. The relay logs a warning at startup when both are set. Leave the bind port at `0` to keep failover, or use the `quinn` or `noq` backend, which share one socket across attempts and are unaffected. -### \[server.quic] and \[client.quic] +### \[quic] -Per-connection QUIC transport knobs, applied to incoming connections -(`server.quic`) and to outgoing cluster dials (`client.quic`) independently. +Per-connection QUIC transport knobs. These mean the same thing whichever way a +connection was opened, so they are spelled once and shared by `[listen]` and +`[connect]` alike. The knobs that only apply when accepting (the QUIC preferred +address and QUIC-LB connection IDs) live on `[listen]` instead. ```toml -[server.quic] +[quic] # "loss" or "delay". Defaults per backend; don't set "delay" on noq/iroh (see below). congestion_control = "delay" - -[client.quic] -congestion_control = "delay" ``` `loss` is CUBIC: it grows until it drops packets, so the send rate sawtooths. @@ -291,9 +289,8 @@ noq and iroh are the exception because their shared BBRv3 can panic on packet loss, which aborts the process. Do not select `delay` on those backends unless you are testing that controller on purpose and can tolerate the crash. -Also available as `--server-quic-congestion-control` / -`--client-quic-congestion-control`, or `MOQ_SERVER_QUIC_CONGESTION_CONTROL` / -`MOQ_CLIENT_QUIC_CONGESTION_CONTROL`. +Also available as `--quic-congestion-control` / +`--quic-congestion-control`, or `MOQ_QUIC_CONGESTION_CONTROL`. ### \[stats] diff --git a/doc/bin/relay/index.md b/doc/bin/relay/index.md index 6bb07c540a8..891ee5343fa 100644 --- a/doc/bin/relay/index.md +++ b/doc/bin/relay/index.md @@ -67,10 +67,10 @@ Multi-arch images (`linux/amd64` and `linux/arm64`) are published to [Docker Hub Create a `relay.toml` configuration file: ```toml -[server] +[listen] bind = "[::]:4443" # Listen on all interfaces, port 4443 -[server.tls] +[listen.tls] cert = "/path/to/cert.pem" # TLS certificate key = "/path/to/key.pem" # TLS private key @@ -109,7 +109,7 @@ sudo certbot certonly --standalone -d relay.example.com Update `relay.toml`: ```toml -[server.tls] +[listen.tls] cert = "/etc/letsencrypt/live/relay.example.com/fullchain.pem" key = "/etc/letsencrypt/live/relay.example.com/privkey.pem" ``` diff --git a/doc/bin/rtc.md b/doc/bin/rtc.md index 252f6479d77..0e81fe99511 100644 --- a/doc/bin/rtc.md +++ b/doc/bin/rtc.md @@ -79,7 +79,7 @@ moq-rtc --relay https://relay.example.com --broadcast my-stream \ deployment behind a firewall pins it (e.g. `0.0.0.0:8089`) and opens just that one media port. Pair it with `--public-addr` so the advertised ICE candidate uses the pinned port. -- `--tls-cert` / `--tls-key`: serve HTTPS instead. Most WHIP clients +- `--listen-tls-cert` / `--listen-tls-key`: serve HTTPS instead. Most WHIP clients require it in practice. ### Client flags diff --git a/doc/bin/rtmp.md b/doc/bin/rtmp.md index 8cdca9e4a69..cda68001b98 100644 --- a/doc/bin/rtmp.md +++ b/doc/bin/rtmp.md @@ -33,7 +33,7 @@ The binary has two modes, mirroring `moq-srt`: ```bash # serve: ingest RTMP and serve it directly as a local relay -moq-rtmp serve --server-bind [::]:443 --tls-generate localhost \ +moq-rtmp serve --listen [::]:443 --listen-tls-generate localhost \ --rtmp-listen 0.0.0.0:1935 --rtmp-prefix live/ # publish: ingest RTMP and forward broadcasts to a remote relay @@ -60,10 +60,10 @@ vlc rtmp://127.0.0.1:1935/live/cam0 ### `serve` flags -- `--server-bind`: QUIC/WebTransport bind address (default `[::]:443`). Also +- `--listen`: QUIC/WebTransport bind address (default `[::]:443`). Also serves the `/certificate.sha256` endpoint browsers need for self-signed `http://` origins, and a static player directory with `--dir`. -- `--tls-generate ` / `--tls-cert` / `--tls-key`: server TLS. +- `--listen-tls-generate ` / `--listen-tls-cert` / `--listen-tls-key`: server TLS. ### `publish` flags @@ -87,7 +87,7 @@ plaintext RTMP, sharing the same `--rtmp-prefix`: (testing only; clients must disable verification). ```bash -moq-rtmp serve --server-bind [::]:443 --tls-generate localhost \ +moq-rtmp serve --listen [::]:443 --listen-tls-generate localhost \ --rtmp-listen 0.0.0.0:1935 \ --rtmps-listen 0.0.0.0:1936 --rtmps-tls-cert cert.pem --rtmps-tls-key key.pem \ --rtmp-prefix live/ diff --git a/doc/concept/standard/interop.md b/doc/concept/standard/interop.md index afc903a38c5..20bea697ef2 100644 --- a/doc/concept/standard/interop.md +++ b/doc/concept/standard/interop.md @@ -27,13 +27,13 @@ A test pattern plus tone, so you don't need a media file: ffmpeg -re -f lavfi -i testsrc=size=1280x720:rate=30 -f lavfi -i sine=frequency=440 \ -c:v libx264 -preset ultrafast -tune zerolatency -g 60 -c:a aac \ -f mp4 -movflags cmaf+frag_keyframe+empty_moov+default_base_moof - \ -| moq --client-connect https://your-relay.example.com --broadcast bbb.hang import fmp4 +| moq --connect https://your-relay.example.com --broadcast bbb.hang import fmp4 ``` ## Subscribe ```bash -moq --client-connect https://your-relay.example.com --broadcast bbb.hang export fmp4 | ffplay - +moq --connect https://your-relay.example.com --broadcast bbb.hang export fmp4 | ffplay - ``` If it plays, you interop. That's the whole test. @@ -48,7 +48,7 @@ If it plays, you interop. That's the whole test. resolved on demand via `SUBSCRIBE`, so a single-track `PUBLISH` offer is answered with a request error. Announce with `PUBLISH_NAMESPACE` and serve the resulting `SUBSCRIBE`s instead. -- **Self-signed or expired cert?** Add `--client-tls-disable-verify`. +- **Self-signed or expired cert?** Add `--connect-tls-insecure`. - **Subscriber sees nothing?** If your relay doesn't replay existing announcements, start the subscriber before the publisher. - **Verbose logs:** prefix with `RUST_LOG=info,moq_net=debug`. It prints the diff --git a/doc/lib/rs/crate/hang.md b/doc/lib/rs/crate/hang.md index 2981ea770bd..c1b596f8820 100644 --- a/doc/lib/rs/crate/hang.md +++ b/doc/lib/rs/crate/hang.md @@ -134,11 +134,11 @@ cargo install moq-cli # Publish a video file (remux to MPEG-TS and pipe it in) ffmpeg -i input.mp4 -c copy -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts # Publish from FFmpeg ffmpeg -i input.mp4 -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts ``` See `moq --help` for all options, or [FFmpeg documentation](/bin/cli). diff --git a/doc/lib/rs/crate/moq-mux.md b/doc/lib/rs/crate/moq-mux.md index f9d9583997e..58dc85ce852 100644 --- a/doc/lib/rs/crate/moq-mux.md +++ b/doc/lib/rs/crate/moq-mux.md @@ -86,11 +86,11 @@ cargo install moq-cli # Publish a video file (remux to MPEG-TS and pipe it in) ffmpeg -i input.mp4 -c copy -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts # Publish from FFmpeg ffmpeg -i input.mp4 -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts ``` ## Next Steps diff --git a/doc/lib/rs/env/native.md b/doc/lib/rs/env/native.md index 80fbdc69fc0..75ed87abf4c 100644 --- a/doc/lib/rs/env/native.md +++ b/doc/lib/rs/env/native.md @@ -21,7 +21,7 @@ The key crates: Create a [`ClientConfig`](https://docs.rs/moq-native/latest/moq_native/struct.ClientConfig.html) and connect to a relay: ```rust -let client = moq_native::ClientConfig::default().init()?; +let client = moq_native::connect::Config::default().init()?; let url = url::Url::parse("https://cdn.moq.dev/anon/my-broadcast")?; // A background task dials and redials with backoff if the session drops. diff --git a/doc/lib/rs/index.md b/doc/lib/rs/index.md index 100515ddd60..a6782a41776 100644 --- a/doc/lib/rs/index.md +++ b/doc/lib/rs/index.md @@ -164,11 +164,11 @@ cargo install moq-cli ```bash # Publish a video file (remux to MPEG-TS and pipe it in) ffmpeg -i input.mp4 -c copy -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts # Publish from FFmpeg ffmpeg -i input.mp4 -f mpegts - | \ - moq --client-connect https://relay.example.com/anon --broadcast my-stream import ts + moq --connect https://relay.example.com/anon --broadcast my-stream import ts ``` [Learn more](/bin/cli) @@ -275,7 +275,7 @@ you, then [`moq-net`](/lib/rs/crate/moq-net) handles the MoQ handshake. Connect a relay with a few lines: ```rust -let client = moq_native::ClientConfig::default().init()?; +let client = moq_native::connect::Config::default().init()?; let url = url::Url::parse("https://cdn.moq.dev/anon")?; // The connection redials with backoff if it drops; drop the handle to disconnect. diff --git a/doc/setup/windows.md b/doc/setup/windows.md index c3ab5430b5e..463f392dd44 100644 --- a/doc/setup/windows.md +++ b/doc/setup/windows.md @@ -62,10 +62,10 @@ REM Grab the relay's certificate fingerprint for /f %f in ('curl -s http://localhost:4443/certificate.sha256') do set FP=%f REM Publish -cargo run -p moq-native --example clock -- --client-connect https://localhost:4443 --broadcast clock --client-tls-fingerprint %FP% publish +cargo run -p moq-native --example clock -- --connect https://localhost:4443 --broadcast clock --connect-tls-fingerprint %FP% publish REM Subscribe (separate terminal) -cargo run -p moq-native --example clock -- --client-connect https://localhost:4443 --broadcast clock --client-tls-fingerprint %FP% subscribe +cargo run -p moq-native --example clock -- --connect https://localhost:4443 --broadcast clock --connect-tls-fingerprint %FP% subscribe ``` The subscriber prints the current time once per second, sourced from the diff --git a/nix/modules/moq-relay.nix b/nix/modules/moq-relay.nix index 341a9eb9dd2..cf864f62a99 100644 --- a/nix/modules/moq-relay.nix +++ b/nix/modules/moq-relay.nix @@ -229,19 +229,19 @@ in MOQ_LOG_LEVEL = lib.mkDefault cfg.logLevel; # Server configuration - MOQ_SERVER_BIND = "[::]:${toString cfg.port}"; + MOQ_LISTEN = "[::]:${toString cfg.port}"; - MOQ_CLIENT_TLS_DISABLE_VERIFY = lib.boolToString cfg.cluster.disableTlsVerify; + MOQ_CONNECT_TLS_INSECURE = lib.boolToString cfg.cluster.disableTlsVerify; } // lib.optionalAttrs (cfg.tls.generate != [ ]) { # TLS configuration - MOQ_SERVER_TLS_GENERATE = lib.concatStringsSep "," cfg.tls.generate; + MOQ_LISTEN_TLS_GENERATE = lib.concatStringsSep "," cfg.tls.generate; } // lib.optionalAttrs (cfg.tls.certs != [ ]) { - MOQ_SERVER_TLS_CERT = lib.concatMapStringsSep "," (cert: "${cert.chain}") cfg.tls.certs; + MOQ_LISTEN_TLS_CERT = lib.concatMapStringsSep "," (cert: "${cert.chain}") cfg.tls.certs; } // lib.optionalAttrs (cfg.tls.certs != [ ]) { - MOQ_SERVER_TLS_KEY = lib.concatMapStringsSep "," (cert: "${cert.key}") cfg.tls.certs; + MOQ_LISTEN_TLS_KEY = lib.concatMapStringsSep "," (cert: "${cert.key}") cfg.tls.certs; } // lib.optionalAttrs cfg.auth.enable { # Auth configuration diff --git a/rs/hang/examples/subscribe.rs b/rs/hang/examples/subscribe.rs index 0d6378d3eef..99b16f48c39 100644 --- a/rs/hang/examples/subscribe.rs +++ b/rs/hang/examples/subscribe.rs @@ -24,7 +24,7 @@ async fn main() -> anyhow::Result<()> { // Automatically reconnects if the connection drops. async fn run_session(origin: moq_net::origin::Producer) -> anyhow::Result<()> { // Optional: Use moq_native to make a QUIC client. - let client = moq_native::ClientConfig::default().init()?; + let client = moq_native::connect::Config::default().init(Default::default())?; // For local development, use: http://localhost:4443/video-example // The "anon" path is usually configured to bypass authentication; be careful! diff --git a/rs/hang/examples/video.rs b/rs/hang/examples/video.rs index 1b1b43b32c1..7e61e40f502 100644 --- a/rs/hang/examples/video.rs +++ b/rs/hang/examples/video.rs @@ -23,7 +23,7 @@ async fn main() -> anyhow::Result<()> { // Automatically reconnects if the connection drops. async fn run_session(origin: moq_net::origin::Producer) -> anyhow::Result<()> { // Optional: Use moq_native to make a QUIC client. - let client = moq_native::ClientConfig::default().init()?; + let client = moq_native::connect::Config::default().init(Default::default())?; // For local development, use: http://localhost:4443 // The "anon" path is usually configured to bypass authentication; be careful! diff --git a/rs/libmoq/src/api.rs b/rs/libmoq/src/api.rs index 3c9cb115ed9..2825459199d 100644 --- a/rs/libmoq/src/api.rs +++ b/rs/libmoq/src/api.rs @@ -549,7 +549,7 @@ pub unsafe extern "C" fn moq_client_set_versions(client: u32, versions: *const m .map(|version| moq_net::Version::from_str(&version).map_err(Error::InvalidConfig)) .collect::, Error>>()?; - State::lock().client.get_mut(client)?.version = versions; + State::lock().client.get_mut(client)?.connect.version = versions; Ok(()) }) } @@ -573,7 +573,7 @@ pub unsafe extern "C" fn moq_client_set_backend(client: u32, backend: *const c_c }; let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.backend = backend; + State::lock().client.get_mut(client)?.connect.backend = backend; Ok(()) }) } @@ -595,7 +595,7 @@ pub unsafe extern "C" fn moq_client_set_bind(client: u32, addr: *const c_char, a .map_err(|err| Error::InvalidConfig(format!("invalid bind address {addr:?}: {err}")))?; let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.bind = addr; + State::lock().client.get_mut(client)?.connect.bind = Some(addr); Ok(()) }) } @@ -612,7 +612,7 @@ pub unsafe extern "C" fn moq_client_set_bind(client: u32, addr: *const c_char, a pub extern "C" fn moq_client_set_connect_timeout(client: u32, timeout_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.timeout = Some(std::time::Duration::from_millis(timeout_ms)); + State::lock().client.get_mut(client)?.connect.timeout = Some(std::time::Duration::from_millis(timeout_ms)); Ok(()) }) } @@ -628,7 +628,7 @@ pub extern "C" fn moq_client_set_connect_timeout(client: u32, timeout_ms: u64) - pub extern "C" fn moq_client_set_failover_delay(client: u32, delay_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.failover_delay = Some(std::time::Duration::from_millis(delay_ms)); + State::lock().client.get_mut(client)?.connect.race = Some(std::time::Duration::from_millis(delay_ms)); Ok(()) }) } @@ -643,7 +643,8 @@ pub extern "C" fn moq_client_set_failover_delay(client: u32, delay_ms: u64) -> i pub extern "C" fn moq_client_set_websocket_delay(client: u32, delay_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.websocket.delay = Some(std::time::Duration::from_millis(delay_ms)); + State::lock().client.get_mut(client)?.connect.websocket.delay = + Some(std::time::Duration::from_millis(delay_ms)); Ok(()) }) } @@ -658,7 +659,7 @@ pub extern "C" fn moq_client_set_websocket_delay(client: u32, delay_ms: u64) -> pub extern "C" fn moq_client_set_websocket_enabled(client: u32, enabled: bool) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.websocket.enabled = enabled; + State::lock().client.get_mut(client)?.connect.websocket.enabled = Some(enabled); Ok(()) }) } @@ -673,7 +674,7 @@ pub extern "C" fn moq_client_set_websocket_enabled(client: u32, enabled: bool) - pub extern "C" fn moq_client_set_tls_disable_verify(client: u32, disable: bool) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.disable_verify = Some(disable); + State::lock().client.get_mut(client)?.connect.tls.insecure = Some(disable); Ok(()) }) } @@ -689,7 +690,7 @@ pub extern "C" fn moq_client_set_tls_disable_verify(client: u32, disable: bool) pub extern "C" fn moq_client_set_tls_system_roots(client: u32, enabled: bool) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.system_roots = Some(enabled); + State::lock().client.get_mut(client)?.connect.tls.system_roots = Some(enabled); Ok(()) }) } @@ -708,7 +709,7 @@ pub unsafe extern "C" fn moq_client_set_tls_roots(client: u32, paths: *const moq ffi::enter(move || { let paths = unsafe { ffi::parse_strings(paths, count)? }; let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.root = paths.into_iter().map(Into::into).collect(); + State::lock().client.get_mut(client)?.connect.tls.root = paths.into_iter().map(Into::into).collect(); Ok(()) }) } @@ -737,7 +738,7 @@ pub unsafe extern "C" fn moq_client_set_tls_fingerprints( moq_native::tls::parse_fingerprint(fingerprint).map_err(|err| Error::InvalidConfig(err.to_string()))?; } let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.fingerprint = fingerprints; + State::lock().client.get_mut(client)?.connect.tls.fingerprint = fingerprints; Ok(()) }) } @@ -757,7 +758,7 @@ pub unsafe extern "C" fn moq_client_set_tls_host_name(client: u32, name: *const ffi::enter(move || { let name = unsafe { ffi::parse_str_optional(name, name_len)? }.map(str::to_string); let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.host_name = name; + State::lock().client.get_mut(client)?.connect.tls.host_name = name; Ok(()) }) } @@ -776,7 +777,7 @@ pub unsafe extern "C" fn moq_client_set_tls_cert(client: u32, path: *const c_cha ffi::enter(move || { let path = unsafe { ffi::parse_str_optional(path, path_len)? }.map(Into::into); let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.cert = path; + State::lock().client.get_mut(client)?.connect.tls.cert = path; Ok(()) }) } @@ -796,7 +797,7 @@ pub unsafe extern "C" fn moq_client_set_tls_key(client: u32, path: *const c_char ffi::enter(move || { let path = unsafe { ffi::parse_str_optional(path, path_len)? }.map(Into::into); let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.tls.key = path; + State::lock().client.get_mut(client)?.connect.tls.key = path; Ok(()) }) } @@ -810,7 +811,8 @@ pub unsafe extern "C" fn moq_client_set_tls_key(client: u32, path: *const c_char pub extern "C" fn moq_client_set_backoff_initial(client: u32, delay_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.backoff.initial = Some(std::time::Duration::from_millis(delay_ms)); + State::lock().client.get_mut(client)?.connect.backoff.initial = + Some(std::time::Duration::from_millis(delay_ms)); Ok(()) }) } @@ -824,7 +826,7 @@ pub extern "C" fn moq_client_set_backoff_initial(client: u32, delay_ms: u64) -> pub extern "C" fn moq_client_set_backoff_multiplier(client: u32, multiplier: u32) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.backoff.multiplier = Some(multiplier); + State::lock().client.get_mut(client)?.connect.backoff.multiplier = Some(multiplier); Ok(()) }) } @@ -838,7 +840,7 @@ pub extern "C" fn moq_client_set_backoff_multiplier(client: u32, multiplier: u32 pub extern "C" fn moq_client_set_backoff_max(client: u32, delay_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.backoff.max = Some(std::time::Duration::from_millis(delay_ms)); + State::lock().client.get_mut(client)?.connect.backoff.max = Some(std::time::Duration::from_millis(delay_ms)); Ok(()) }) } @@ -854,7 +856,8 @@ pub extern "C" fn moq_client_set_backoff_max(client: u32, delay_ms: u64) -> i32 pub extern "C" fn moq_client_set_backoff_timeout(client: u32, timeout_ms: u64) -> i32 { ffi::enter(move || { let client = ffi::parse_id(client)?; - State::lock().client.get_mut(client)?.backoff.timeout = Some(std::time::Duration::from_millis(timeout_ms)); + State::lock().client.get_mut(client)?.connect.backoff.timeout = + Some(std::time::Duration::from_millis(timeout_ms)); Ok(()) }) } @@ -997,7 +1000,7 @@ pub unsafe extern "C" fn moq_client_get_connect_timeout(client: u32, out: *mut u ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = millis(State::lock().client.get_mut(client)?.resolved_connect_timeout()); + *out = millis(State::lock().client.get_mut(client)?.connect.resolved_timeout()); Ok(()) }) } @@ -1014,7 +1017,7 @@ pub unsafe extern "C" fn moq_client_get_failover_delay(client: u32, out: *mut u6 ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = millis(State::lock().client.get_mut(client)?.resolved_failover_delay()); + *out = millis(State::lock().client.get_mut(client)?.connect.resolved_race()); Ok(()) }) } @@ -1030,7 +1033,7 @@ pub unsafe extern "C" fn moq_client_get_backoff_initial(client: u32, out: *mut u ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = millis(State::lock().client.get_mut(client)?.backoff.initial()); + *out = millis(State::lock().client.get_mut(client)?.connect.backoff.initial()); Ok(()) }) } @@ -1046,7 +1049,7 @@ pub unsafe extern "C" fn moq_client_get_backoff_multiplier(client: u32, out: *mu ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = State::lock().client.get_mut(client)?.backoff.multiplier(); + *out = State::lock().client.get_mut(client)?.connect.backoff.multiplier(); Ok(()) }) } @@ -1062,7 +1065,7 @@ pub unsafe extern "C" fn moq_client_get_backoff_max(client: u32, out: *mut u64) ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = millis(State::lock().client.get_mut(client)?.backoff.max()); + *out = millis(State::lock().client.get_mut(client)?.connect.backoff.max()); Ok(()) }) } @@ -1079,7 +1082,7 @@ pub unsafe extern "C" fn moq_client_get_backoff_timeout(client: u32, out: *mut u ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = millis(State::lock().client.get_mut(client)?.backoff.timeout()); + *out = millis(State::lock().client.get_mut(client)?.connect.backoff.timeout()); Ok(()) }) } @@ -1146,7 +1149,12 @@ pub unsafe extern "C" fn moq_client_get_websocket_enabled(client: u32, out: *mut ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - *out = State::lock().client.get_mut(client)?.websocket.enabled; + *out = State::lock() + .client + .get_mut(client)? + .connect + .websocket + .resolved_enabled(); Ok(()) }) } @@ -1163,8 +1171,9 @@ pub unsafe extern "C" fn moq_client_get_websocket_delay(client: u32, out: *mut u ffi::enter(move || { let out = unsafe { out.as_mut() }.ok_or(Error::InvalidPointer)?; let client = ffi::parse_id(client)?; - let delay = State::lock().client.get_mut(client)?.websocket.delay; - *out = delay.map(millis).unwrap_or(0); + // Report the resolved default rather than 0, which would read as "no head start". + let delay = State::lock().client.get_mut(client)?.connect.websocket.resolved_delay(); + *out = millis(delay); Ok(()) }) } diff --git a/rs/libmoq/src/client.rs b/rs/libmoq/src/client.rs index acd8d3f5f92..fdae806a837 100644 --- a/rs/libmoq/src/client.rs +++ b/rs/libmoq/src/client.rs @@ -1,18 +1,29 @@ use crate::{Error, Id, NonZeroSlab}; +/// One client handle: the dial config plus the QUIC tuning it dials with. +/// +/// They are separate types in `moq-native` (the tuning is shared by the dial and +/// accept sides of an endpoint), but a C caller configures one client, so the +/// handle carries both and `moq_client_set_*` writes into whichever owns the knob. +#[derive(Clone, Default)] +pub struct Config { + pub connect: moq_native::connect::Config, + pub quic: moq_native::quic::Config, +} + /// Client configurations built up by the `moq_client_*` setters. /// -/// A handle is a plain [`moq_native::ClientConfig`] the caller mutates one knob at a -/// time, then dials with. Dialing clones it, so one handle can open any number of -/// sessions and stays editable in between. +/// A handle is a plain [`Config`] the caller mutates one knob at a time, then +/// dials with. Dialing clones it, so one handle can open any number of sessions +/// and stays editable in between. #[derive(Default)] pub struct Client { - configs: NonZeroSlab, + configs: NonZeroSlab, } impl Client { pub fn create(&mut self) -> Result { - self.configs.insert(moq_native::ClientConfig::default()) + self.configs.insert(Config::default()) } pub fn close(&mut self, id: Id) -> Result<(), Error> { @@ -21,16 +32,16 @@ impl Client { } /// The config a setter should mutate. - pub fn get_mut(&mut self, id: Id) -> Result<&mut moq_native::ClientConfig, Error> { + pub fn get_mut(&mut self, id: Id) -> Result<&mut Config, Error> { self.configs.get_mut(id).ok_or(Error::ClientNotFound) } /// The config to dial with. A missing handle means "no config given", which is the /// defaults, so [`crate::moq_session_connect`] is just this with `None`. - pub fn config(&self, id: Option) -> Result { + pub fn config(&self, id: Option) -> Result { match id { Some(id) => self.configs.get(id).cloned().ok_or(Error::ClientNotFound), - None => Ok(moq_native::ClientConfig::default()), + None => Ok(Config::default()), } } } diff --git a/rs/libmoq/src/session.rs b/rs/libmoq/src/session.rs index 973bdbd8bc2..1210815d153 100644 --- a/rs/libmoq/src/session.rs +++ b/rs/libmoq/src/session.rs @@ -20,7 +20,7 @@ struct TaskEntry { /// Everything needed to prepare a session without holding the global state lock. pub(crate) struct Connect { - pub config: moq_native::ClientConfig, + pub config: crate::client::Config, pub url: Url, pub publish: Option, pub consume: Option, @@ -32,7 +32,9 @@ impl Connect { pub fn prepare(self) -> Result { let mut client = self .config - .init() + .connect + .clone() + .init(self.config.quic.clone()) .map_err(|err| Error::InvalidConfig(err.to_string()))?; if let Some(publish) = &self.publish { client = client.with_publisher(publish); diff --git a/rs/libmoq/src/test.rs b/rs/libmoq/src/test.rs index 53730fff65c..62c3bd41da8 100644 --- a/rs/libmoq/src/test.rs +++ b/rs/libmoq/src/test.rs @@ -2401,6 +2401,7 @@ fn client_set_tls_fingerprints_rejects_malformed_values_before_mutating() { .client .get_mut(client_id) .unwrap() + .connect .tls .fingerprint .is_empty() @@ -2487,15 +2488,15 @@ fn a_fresh_handle_reads_back_the_defaults() { moq_client_close(client); })); - let config = moq_native::ClientConfig::default(); + let config = moq_native::connect::Config::default(); let quic = moq_native::quic::Resolved::default(); let mut value = 0u64; assert_eq!(unsafe { moq_client_get_connect_timeout(client, &mut value) }, 0); - assert_eq!(value, config.resolved_connect_timeout().as_millis() as u64); + assert_eq!(value, config.resolved_timeout().as_millis() as u64); assert_eq!(unsafe { moq_client_get_failover_delay(client, &mut value) }, 0); - assert_eq!(value, config.resolved_failover_delay().as_millis() as u64); + assert_eq!(value, config.resolved_race().as_millis() as u64); assert_eq!(unsafe { moq_client_get_backoff_initial(client, &mut value) }, 0); assert_eq!(value, config.backoff.initial().as_millis() as u64); @@ -2516,7 +2517,7 @@ fn a_fresh_handle_reads_back_the_defaults() { assert_eq!(value, quic.keep_alive.map(|d| d.as_millis() as u64).unwrap_or(0)); assert_eq!(unsafe { moq_client_get_websocket_delay(client, &mut value) }, 0); - assert_eq!(value, config.websocket.delay.map(|d| d.as_millis() as u64).unwrap_or(0)); + assert_eq!(value, config.websocket.resolved_delay().as_millis() as u64); let mut multiplier = 0u32; assert_eq!(unsafe { moq_client_get_backoff_multiplier(client, &mut multiplier) }, 0); @@ -2524,7 +2525,7 @@ fn a_fresh_handle_reads_back_the_defaults() { let mut enabled = false; assert_eq!(unsafe { moq_client_get_websocket_enabled(client, &mut enabled) }, 0); - assert_eq!(enabled, config.websocket.enabled); + assert_eq!(enabled, config.websocket.resolved_enabled()); } /// A getter reports what the matching setter wrote, so the pair can't drift. diff --git a/rs/moq-bench/README.md b/rs/moq-bench/README.md index db730adf159..5c9e06d8c18 100644 --- a/rs/moq-bench/README.md +++ b/rs/moq-bench/README.md @@ -48,11 +48,11 @@ shape, so a subscriber works against peers it didn't publish itself. ```bash # Roll the dice with the built-in defaults (1 connection, 1 broadcast, 30fps). -moq-bench --client-connect https://relay.example.com +moq-bench --connect https://relay.example.com # Use a preset, overriding the target and connection count on the CLI. moq-bench --file rs/moq-bench/config/hd.toml \ - --client-connect https://relay.example.com \ + --connect https://relay.example.com \ --connections 500 ``` @@ -74,7 +74,7 @@ table (`fps = { min = 24, max = 60 }`). | `--duration` | | Stop after this long (runs until interrupted otherwise) | | `--report` | | How often to log throughput stats | -Client TLS/QUIC flags (`--client-tls-disable-verify`, `--client-bind`, ...) come from +Client TLS/QUIC flags (`--connect-tls-insecure`, `--connect-bind`, ...) come from `moq-native` and behave the same as in `moq-cli` and `moq-relay`. ## Presets diff --git a/rs/moq-bench/src/config.rs b/rs/moq-bench/src/config.rs index 7c3ee51bb50..8f60284cf73 100644 --- a/rs/moq-bench/src/config.rs +++ b/rs/moq-bench/src/config.rs @@ -70,7 +70,12 @@ pub struct Config { /// The MoQ client (QUIC/TLS) configuration. #[command(flatten)] #[serde(default)] - pub client: moq_native::ClientConfig, + pub client: moq_native::connect::Config, + + /// QUIC transport tuning (`--quic-*`). + #[command(flatten)] + #[serde(default)] + pub quic: moq_native::quic::Config, /// Log configuration. #[command(flatten)] @@ -164,7 +169,7 @@ fps = "24:60" [client] connect = "https://example.com" -tls.disable_verify = true +tls.insecure = true "#; let dir = std::env::temp_dir().join("moq-bench-config-test"); std::fs::create_dir_all(&dir).unwrap(); @@ -180,8 +185,8 @@ tls.disable_verify = true let config = Config::parse_and_merge(args).unwrap(); assert_eq!(config.connections(), Range::new(100, 100)); assert_eq!(config.fps(), Range::new(24, 60)); - assert_eq!(config.client.connect.as_ref().unwrap().as_str(), "https://example.com/"); - assert_eq!(config.client.tls.disable_verify, Some(true)); + assert_eq!(config.client.url.as_ref().unwrap().as_str(), "https://example.com/"); + assert_eq!(config.client.tls.insecure, Some(true)); // CLI flag wins over the TOML value. let args = vec![ diff --git a/rs/moq-bench/src/connection.rs b/rs/moq-bench/src/connection.rs index 6db111d2908..fe8973432a2 100644 --- a/rs/moq-bench/src/connection.rs +++ b/rs/moq-bench/src/connection.rs @@ -76,7 +76,7 @@ pub async fn run(ctx: Connection) { stats, } = ctx; - let url = config.client.connect.clone().expect("url required"); + let url = config.client.url.clone().expect("url required"); // Publish side: an origin we fill with our broadcasts and hand to the session. let publish = Origin::random().produce(); diff --git a/rs/moq-bench/src/main.rs b/rs/moq-bench/src/main.rs index 77c9e71d561..045f409b8e0 100644 --- a/rs/moq-bench/src/main.rs +++ b/rs/moq-bench/src/main.rs @@ -23,12 +23,12 @@ async fn main() -> anyhow::Result<()> { let config = Config::load()?; anyhow::ensure!( - config.client.connect.is_some(), - "--client-connect is required (or set it in the TOML file)" + config.client.url.is_some(), + "--connect is required (or set it in the TOML file)" ); let config = Arc::new(config); - let client = config.client.clone().init()?; + let client = config.client.clone().init(config.quic.clone())?; let stats = Arc::new(Stats::default()); // Periodic throughput reporter. @@ -45,7 +45,7 @@ async fn main() -> anyhow::Result<()> { let run_id = rng.random_range(0..=u64::MAX); let startup = config.startup(); - tracing::info!(connections = count, url = %config.client.connect.as_ref().unwrap(), "starting benchmark"); + tracing::info!(connections = count, url = %config.client.url.as_ref().unwrap(), "starting benchmark"); let mut tasks = tokio::task::JoinSet::new(); for i in 0..count { diff --git a/rs/moq-boy/src/main.rs b/rs/moq-boy/src/main.rs index a8cae8801ce..2c8f3564500 100644 --- a/rs/moq-boy/src/main.rs +++ b/rs/moq-boy/src/main.rs @@ -71,7 +71,11 @@ pub struct Config { /// The MoQ client configuration. #[command(flatten)] - pub client: moq_native::ClientConfig, + pub client: moq_native::connect::Config, + + /// QUIC transport tuning (`--quic-*`). + #[command(flatten)] + pub quic: moq_native::quic::Config, /// The log configuration. #[command(flatten)] @@ -201,8 +205,8 @@ async fn run(config: &Config) -> Result<()> { tracing::info!(rom = %rom_path.display(), %name, "starting Game Boy emulator"); let (cmd_tx, cmd_rx) = tokio::sync::mpsc::channel::(64); - let url = config.client.connect.clone().context("--client-connect is required")?; - let client = config.client.clone().init()?; + let url = config.client.url.clone().context("--connect is required")?; + let client = config.client.clone().init(config.quic.clone())?; // Publish origin: the game session broadcast. let publish_origin = moq_net::Origin::random().produce(); @@ -485,9 +489,9 @@ async fn main() -> Result<()> { mod tests { use super::*; - /// `--client-connect` is the only way to reach the relay: it must parse without + /// `--connect` is the only way to reach the relay: it must parse without /// a connect flag of our own alongside it, and the URL must land where `run` - /// reads it. A second required flag would leave `--client-connect` inert. + /// reads it. A second required flag would leave `--connect` inert. /// /// The argv is a copy of `demo/boy/justfile`, not a read of it, so this pins the /// binary's flag surface rather than the two staying in sync. @@ -506,8 +510,9 @@ mod tests { let connect = config .client - .connect - .expect("--client-connect should reach the client config"); + .resolved() + .url + .expect("the connect URL should reach the dial config"); assert_eq!(connect.scheme(), "http"); assert_eq!(connect.host_str(), Some("localhost")); assert_eq!(connect.port(), Some(4443)); diff --git a/rs/moq-cli/README.md b/rs/moq-cli/README.md index 3e63955df08..2b1181192a7 100644 --- a/rs/moq-cli/README.md +++ b/rs/moq-cli/README.md @@ -19,26 +19,26 @@ Multi-arch images (`linux/amd64` and `linux/arm64`) are published to [Docker Hub ## Usage -`moq-cli` routes one endpoint onto a shared MoQ Origin: `moq `. The MoQ side (before the verb) is either `--client-connect ` (dial a relay) or `--server-bind ` (self-host). `import` moves media into MoQ, `export` moves it out. The endpoint is a container format (`fmp4`, `ts`, `flv`, ... read from stdin / written to stdout), or a gateway (`hls`, `rtmp`, `srt`, `rtc`). A build with the `play` feature can also render a broadcast locally with `moq play`. +`moq-cli` routes one endpoint onto a shared MoQ Origin: `moq `. The MoQ side (before the verb) is either `--connect ` (dial a relay) or `--listen ` (self-host). `import` moves media into MoQ, `export` moves it out. The endpoint is a container format (`fmp4`, `ts`, `flv`, ... read from stdin / written to stdout), or a gateway (`hls`, `rtmp`, `srt`, `rtc`). A build with the `play` feature can also render a broadcast locally with `moq play`. ### Publish to a remote relay ```bash ffmpeg -i input.mp4 -f mp4 -movflags cmaf - | \ - moq --client-connect https://relay.example.com --broadcast my-stream.hang import fmp4 + moq --connect https://relay.example.com --broadcast my-stream.hang import fmp4 ``` ### Subscribe from a remote relay ```bash -moq --client-connect https://relay.example.com --broadcast my-stream.hang export fmp4 | \ +moq --connect https://relay.example.com --broadcast my-stream.hang export fmp4 | \ ffplay - ``` Play the broadcast in a native window and speaker (requires `--features play` when building): ```bash -moq --client-connect https://relay.example.com --broadcast my-stream.hang play +moq --connect https://relay.example.com --broadcast my-stream.hang play ``` ### Self-host: publish into a local relay @@ -47,7 +47,7 @@ Hosts a MoQ server and publishes a single broadcast read from stdin into it. Use ```bash ffmpeg -i input.mp4 -f mp4 -movflags cmaf - | \ - moq --server-bind '[::]:4443' --tls-generate localhost --broadcast my-stream.hang import fmp4 + moq --listen '[::]:4443' --listen-tls-generate localhost --broadcast my-stream.hang import fmp4 ``` ### Self-host: subscribe to an inbound broadcast @@ -55,7 +55,7 @@ ffmpeg -i input.mp4 -f mp4 -movflags cmaf - | \ Hosts a MoQ server and writes an incoming broadcast's media to stdout. The inverse of the above. ```bash -moq --server-bind '[::]:4443' --tls-generate localhost --broadcast my-stream.hang export fmp4 | ffplay - +moq --listen '[::]:4443' --listen-tls-generate localhost --broadcast my-stream.hang export fmp4 | ffplay - ``` ### Import formats diff --git a/rs/moq-cli/src/args.rs b/rs/moq-cli/src/args.rs index 4c4609b2a62..69132453b02 100644 --- a/rs/moq-cli/src/args.rs +++ b/rs/moq-cli/src/args.rs @@ -3,7 +3,7 @@ //! Grammar: `moq [endpoint opts]`, plus //! `moq play` for native playback. //! -//! - The MoQ side (`--client-connect`, `--server-bind`, `--cluster-lan`; all +//! - The MoQ side (`--connect`, `--listen`, `--cluster-lan`; all //! optional, at least one) attaches the shared Origin to the MoQ network, and //! comes before the verb. They compose: dial a relay, accept incoming //! sessions, and mesh with the LAN all at once. @@ -53,11 +53,11 @@ pub struct Cli { #[derive(Args, Clone)] #[cfg_attr( feature = "cluster-lan", - command(group = ArgGroup::new("moq").multiple(true).args(["client-connect", "server-bind", "cluster-lan"])) + command(group = ArgGroup::new("moq").multiple(true).args(["connect", "listen", "cluster-lan"])) )] #[cfg_attr( not(feature = "cluster-lan"), - command(group = ArgGroup::new("moq").multiple(true).args(["client-connect", "server-bind"])) + command(group = ArgGroup::new("moq").multiple(true).args(["connect", "listen"])) )] pub struct MoqSide { /// The broadcast name. Optional for the point endpoints (stdin/stdout, HLS @@ -78,13 +78,17 @@ pub struct MoqSide { #[arg(long, env = "MOQ_ORIGIN", help_heading = "MoQ")] pub origin: Option, - /// MoQ client config (`--client-connect`, `--client-bind`, `--client-tls-*`, ...). + /// MoQ client config (`--connect`, `--connect-bind`, `--connect-tls-*`, ...). #[command(flatten)] - pub client: moq_native::ClientConfig, + pub client: moq_native::connect::Config, - /// MoQ server transport config (`--server-bind`, `--server-tls-*`, `--tls-*`). + /// QUIC transport tuning (`--quic-*`), shared by the dial and accept sides. #[command(flatten)] - pub server: moq_native::ServerConfig, + pub quic: moq_native::quic::Config, + + /// MoQ server transport config (`--listen`, `--listen-tls-*`). + #[command(flatten)] + pub server: moq_native::listen::Config, /// Iroh transport config (`--iroh-*`), used by both the client and server. #[cfg(feature = "iroh")] @@ -121,10 +125,10 @@ impl MoqSide { /// /// `--cluster-lan` needs a listener for peers to dial, so it fills in the two /// things the user would otherwise have to spell out: an ephemeral port and a - /// generated certificate. An explicit `--server-bind` or `--tls-*` wins, which + /// generated certificate. An explicit `--listen` or `--listen-tls-*` wins, which /// is what puts the mesh on the same port and certificate as everything else. - pub fn server_config(&self) -> moq_native::ServerConfig { - let mut config = self.server.clone(); + pub fn server_config(&self) -> moq_native::listen::Config { + let mut config = self.server.resolved(); if self.lan() { config.bind.get_or_insert_with(|| "[::]:0".to_string()); if config.tls.generate.is_empty() && config.tls.cert.is_empty() { @@ -136,7 +140,7 @@ impl MoqSide { /// Whether a listener has to be bound at all. pub fn serves(&self) -> bool { - self.server.bind.is_some() || self.lan() + self.server.resolved().bind.is_some() || self.lan() } /// Reject a verb that needs the MoQ network but was given no way to reach it. @@ -144,14 +148,14 @@ impl MoqSide { /// `devices` is exempt. pub fn validate(&self) -> anyhow::Result<()> { anyhow::ensure!( - self.client.connect.is_some() || self.serves(), - "a MoQ side is required: pass --client-connect to dial a relay, --server-bind to self-host, or --cluster-lan to mesh over the LAN" + self.client.resolved().url.is_some() || self.serves(), + "a MoQ side is required: pass --connect to dial a relay, --listen to self-host, or --cluster-lan to mesh over the LAN" ); #[cfg(feature = "cluster-lan")] { self.cluster.validate()?; if self.lan() { - crate::cluster::validate_versions(&self.client, &self.server_config())?; + crate::cluster::validate_versions(&self.client.resolved(), &self.server_config())?; } } Ok(()) @@ -170,9 +174,13 @@ impl MoqSide { #[cfg(not(feature = "cluster-lan"))] let cluster_secret = false; + // Read through the fold: a legacy `--client-connect` must be rejected here + // too, and it only lands in `url` once resolved. + let connect = self.client.resolved(); + let listen = self.server.resolved(); let ignored = [ - ("--client-connect", self.client.connect.is_some()), - ("--server-bind", self.server.bind.is_some()), + ("--connect", connect.url.is_some()), + ("--listen", listen.bind.is_some()), ("--cluster-lan", self.lan()), ("--cluster-lan-secret", cluster_secret), ("--broadcast", self.broadcast.is_some()), @@ -415,13 +423,16 @@ mod tests { assert!(cli.moq.reject("token").is_ok()); // ...these it refuses, rather than accepting the flag and ignoring it. - for flag in [ - ["--client-connect", "https://relay.example.com"], - ["--broadcast", "room"], + for (flag, value, reported) in [ + ("--connect", "https://relay.example.com", "--connect"), + // The released spelling folds in, so it is rejected under its + // canonical name rather than silently ignored. + ("--client-connect", "https://relay.example.com", "--connect"), + ("--broadcast", "room", "--broadcast"), ] { - let cli = Cli::try_parse_from(["moq", flag[0], flag[1], "token", "generate"]).unwrap(); + let cli = Cli::try_parse_from(["moq", flag, value, "token", "generate"]).unwrap(); let err = cli.moq.reject("token").unwrap_err().to_string(); - assert!(err.contains(flag[0]), "{err}"); + assert!(err.contains(reported), "{err}"); } #[cfg(feature = "cluster-lan")] @@ -529,11 +540,17 @@ mod tests { #[cfg(feature = "cluster-lan")] #[test] fn cluster_lan_requires_a_path_capable_version() { - for flag in ["--client-version", "--server-version"] { + // Both the canonical spellings and the released ones, which fold in. + for (flag, reported) in [ + ("--connect-version", "--connect-version"), + ("--listen-version", "--listen-version"), + ("--client-version", "--connect-version"), + ("--server-version", "--listen-version"), + ] { let cli = Cli::try_parse_from(["moq", "--cluster-lan", flag, "moq-lite-04", "import", "ts"]).expect("parse"); let err = cli.moq.validate().unwrap_err().to_string(); - assert!(err.contains(flag), "{err}"); + assert!(err.contains(reported), "{flag}: {err}"); } let cli = Cli::try_parse_from([ diff --git a/rs/moq-cli/src/cluster.rs b/rs/moq-cli/src/cluster.rs index ef582cc2f20..a5bb3766d5a 100644 --- a/rs/moq-cli/src/cluster.rs +++ b/rs/moq-cli/src/cluster.rs @@ -1,6 +1,6 @@ //! LAN clustering: find MoQ peers with mDNS and mesh with them. //! -//! [`Lan`] advertises this process's `--server-bind` listener over mDNS, dials +//! [`Lan`] advertises this process's `--listen` listener over mDNS, dials //! every peer it discovers, and attaches each session to the shared origin in //! both directions, so the whole network converges on one set of broadcasts //! with no relay involved. Loop prevention comes from each broadcast's route, @@ -28,8 +28,8 @@ fn carries_request_path(version: &moq_net::Version) -> bool { /// Reject version restrictions that leave the mesh with no request path. pub(crate) fn validate_versions( - client: &moq_native::ClientConfig, - server: &moq_native::ServerConfig, + client: &moq_native::connect::Config, + server: &moq_native::listen::Config, ) -> anyhow::Result<()> { let client = client.versions(); let server = server.versions(); @@ -37,7 +37,7 @@ pub(crate) fn validate_versions( client .iter() .any(|version| carries_request_path(version) && server.contains(version)), - "--cluster-lan needs --client-version and --server-version to share a version that carries a request path (moq-lite-05 or any moq-transport version)" + "--cluster-lan needs --connect-version and --listen-version to share a version that carries a request path (moq-lite-05 or any moq-transport version)" ); Ok(()) } @@ -56,7 +56,7 @@ pub struct Lan { credential: String, /// The dial template, per-peer fingerprint applied on top. - client: moq_native::ClientConfig, + client: moq_native::connect::Config, } /// The discovered details needed to open one LAN dial. @@ -81,7 +81,7 @@ impl From<&mdns::Peer> for DialTarget { impl Lan { /// Advertise `server` on the LAN and start browsing for peers. /// - /// Binds nothing itself: the listener is the one `--server-bind` already + /// Binds nothing itself: the listener is the one `--listen` already /// configured, so peers and ordinary clients share a port and a certificate. /// Returns the live [`mdns::Discovery`] alongside, so a bind or mDNS failure /// surfaces before readiness is signaled and [`run`](Self::run) can consume it. @@ -89,7 +89,7 @@ impl Lan { args: &Args, origin: moq_net::origin::Producer, server: &moq_native::Server, - mut client: moq_native::ClientConfig, + mut client: moq_native::connect::Config, ) -> anyhow::Result<(Self, mdns::Discovery)> { let port = server .local_addr() @@ -109,16 +109,18 @@ impl Lan { // A peer that is still advertising is still wanted, however long it has // been unreachable; mDNS expiry is what ends a dial, not a retry budget. client.backoff.timeout = Some(std::time::Duration::ZERO); - // Whatever `--client-reconnect` means for the relay dial, a mesh dial has to - // keep redialing: the map is keyed on the advertisement, so a one-shot handle - // that stopped after the first session would sit there dead until mDNS - // expired the peer and re-reported it. - client.reconnect = Some(true); + // Whatever `--connect-once` means for the relay dial, a mesh dial has to keep + // redialing: the map is keyed on the advertisement, so a one-shot handle that + // stopped after the first session would sit there dead until mDNS expired the + // peer and re-reported it. + client.once = Some(false); // Each peer gets its own client, so they cannot all share one fixed port. // Keep the configured interface and let the OS pick the port, otherwise a - // nonzero `--client-bind` means the second peer (or the first, when - // `--client-connect` already owns it) fails with EADDRINUSE. - client.bind.set_port(0); + // nonzero `--connect-bind` means the second peer (or the first, when + // `--connect` already owns it) fails with EADDRINUSE. + let mut bind = client.resolved_bind(); + bind.set_port(0); + client.bind = Some(bind); // The membership proof rides in the request path. Legacy moq-lite versions // ignore that path, so they cannot be offered by a mesh dial even when the // same client config also serves an ordinary relay connection. @@ -242,12 +244,12 @@ impl Lan { // the advertised fingerprint is the whole trust decision, and combining it // with roots is rejected outright, so start from a clean TLS config. if let Some(fingerprint) = &peer.fingerprint { - config.tls = moq_native::tls::Client::default(); + config.tls = moq_native::tls::Connect::default(); config.tls.fingerprint = vec![fingerprint.clone()]; } let client = config - .init()? + .init(Default::default())? .with_publisher(&self.origin) .with_subscriber(self.origin.clone()); Ok(client.connect(addrs)) @@ -321,7 +323,7 @@ pub async fn serve( } // The mesh's own listener is not a public one. `--cluster-lan` fills in - // `--server-bind` when it is unset, so a user who asked only to mesh never + // `--listen` when it is unset, so a user who asked only to mesh never // asked to serve viewers, and the membership proof gates the mesh path // alone. Attaching an unauthenticated stranger to the origin here would // hand them exactly what the secret is meant to withhold. @@ -364,8 +366,8 @@ struct Dial { pub struct Args { /// Discover and mesh with every other participating MoQ process on the LAN /// via mDNS: no relay, internet, or certificate setup needed. Reuses the - /// --server-bind listener, defaulting it to an ephemeral port with a - /// generated certificate. Composes with --client-connect, e.g. mesh locally + /// --listen listener, defaulting it to an ephemeral port with a + /// generated certificate. Composes with --connect, e.g. mesh locally /// while a relay serves external viewers. #[arg( id = "cluster-lan", @@ -441,7 +443,7 @@ mod tests { Lan { origin: moq_net::Origin::random().produce(), credential: credential.to_string(), - client: moq_native::ClientConfig::default(), + client: moq_native::connect::Config::default(), } } @@ -491,12 +493,12 @@ mod tests { assert_eq!(lan.dial_urls(&node)[0].path(), "/anon"); } - /// A pinned peer ignores the CA roots configured for `--client-connect`: + /// A pinned peer ignores the CA roots configured for `--connect`: /// combining the two is rejected outright, and they say nothing about a /// generated certificate anyway. #[tokio::test] async fn pinning_a_peer_drops_the_relay_roots() { - let mut client = moq_native::ClientConfig::default(); + let mut client = moq_native::connect::Config::default(); client.tls.root = vec!["ca.pem".into()]; let mut lan = lan("ours"); lan.client = client; @@ -555,10 +557,10 @@ mod tests { fn listener() -> (moq_native::Server, DialTarget) { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.bind = Some("127.0.0.1:0".to_string()); config.tls.generate = vec!["moq-cluster-lan".to_string()]; - let server = config.init().expect("failed to bind listener"); + let server = config.init(Default::default()).expect("failed to bind listener"); let port = server.local_addr().expect("no local addr").port(); let fingerprint = server @@ -656,7 +658,7 @@ mod tests { /// used to skip authorization entirely and be attached to the origin: someone /// who found the advertised ephemeral port could read an `import` or publish /// into an `export` without the secret, which is what the secret is for. A - /// user who passed `--server-bind` did ask to serve, so that case still does. + /// user who passed `--listen` did ask to serve, so that case still does. #[tokio::test] async fn a_mesh_only_listener_refuses_ordinary_clients() { let origin = moq_net::Origin::random().produce(); @@ -667,18 +669,18 @@ mod tests { let (server, peer) = listener(); let mut accept = lan("the-real-proof"); accept.origin = origin.clone(); - // `public: false` is what `--cluster-lan` passes with no `--server-bind`. + // `public: false` is what `--cluster-lan` passes with no `--listen`. tokio::spawn(serve(server, accept, origin.clone(), crate::Direction::Import, false)); // An ordinary client: no mesh marker, no proof, just the advertised port. - let mut config = moq_native::ClientConfig::default(); - config.tls = moq_native::tls::Client::default(); + let mut config = moq_native::connect::Config::default(); + config.tls = moq_native::tls::Connect::default(); config.tls.fingerprint = vec![peer.fingerprint.clone().expect("fingerprint")]; - config.reconnect = Some(false); + config.once = Some(true); let stolen = moq_net::Origin::random().produce(); let url = peer.urls.into_iter().next().expect("an address"); let connection = config - .init() + .init(Default::default()) .expect("client") .with_subscriber(stolen.clone()) .connect(url); diff --git a/rs/moq-cli/src/hls.rs b/rs/moq-cli/src/hls.rs index d95f8a83c79..62ef34d8e89 100644 --- a/rs/moq-cli/src/hls.rs +++ b/rs/moq-cli/src/hls.rs @@ -27,7 +27,7 @@ pub struct ExportArgs { /// TLS certificates, keys, self-signed generation, and optional mTLS roots. #[command(flatten)] - pub tls: moq_native::tls::Server, + pub tls: moq_native::tls::Listen, /// Minimum media listed in each rendition's playlist window. Keep it within the /// relay's group-cache retention, since segments are fetched from there on request. diff --git a/rs/moq-cli/src/main.rs b/rs/moq-cli/src/main.rs index 05045e6303d..b9d6be6fc45 100644 --- a/rs/moq-cli/src/main.rs +++ b/rs/moq-cli/src/main.rs @@ -39,13 +39,15 @@ static ALLOC: moq_native::jemalloc::tikv_jemallocator::Jemalloc = moq_native::je /// iroh endpoint so the rest of the code is feature-agnostic. #[derive(Clone)] struct Net { + /// The shared QUIC tuning, handed to whichever roles this process builds. + quic: moq_native::quic::Config, #[cfg(feature = "iroh")] iroh: Option, } impl Net { - fn client(&self, config: moq_native::ClientConfig) -> anyhow::Result { - let client = config.init()?; + fn client(&self, config: moq_native::connect::Config) -> anyhow::Result { + let client = config.init(self.quic.clone())?; #[cfg(feature = "iroh")] let client = match self.iroh.clone() { Some(iroh) => client.with_iroh(iroh), @@ -54,8 +56,8 @@ impl Net { Ok(client) } - fn server(&self, config: moq_native::ServerConfig) -> anyhow::Result { - let server = config.init()?; + fn server(&self, config: moq_native::listen::Config) -> anyhow::Result { + let server = config.init(self.quic.clone())?; #[cfg(feature = "iroh")] let server = match self.iroh.clone() { Some(iroh) => server.with_iroh(iroh), @@ -76,7 +78,7 @@ pub enum Direction { /// Bind the MoQ listener and spawn everything that serves on it: ordinary /// clients, the LAN mesh when `--cluster-lan` is on, and the certificate -/// endpoint for an explicit `--server-bind`. A no-op with no listener configured. +/// endpoint for an explicit `--listen`. A no-op with no listener configured. /// async fn spawn_server( tasks: &mut JoinSet>, @@ -170,8 +172,9 @@ async fn main() -> anyhow::Result<()> { cli.moq.validate()?; let net = Net { + quic: cli.moq.quic.clone(), #[cfg(feature = "iroh")] - iroh: cli.moq.iroh.clone().bind(&cli.moq.client.quic).await?, + iroh: cli.moq.iroh.clone().bind(&cli.moq.quic).await?, }; #[cfg(feature = "jemalloc")] @@ -207,7 +210,7 @@ async fn spawn_moq_consume( origin: &moq_net::origin::Producer, tasks: &mut JoinSet>, ) -> anyhow::Result<()> { - if moq.client.connect.is_some() + if moq.client.url.is_some() && let Some(reconnect) = net.client(moq.client.clone())?.consume(origin.clone()) { tasks.spawn(async move { Ok(reconnect.closed().await?) }); @@ -257,7 +260,7 @@ async fn run_import(moq: MoqSide, import: Import, net: Net) -> anyhow::Result<() } // The uplink's bandwidth estimate, for sources that can encode to fit it. Only - // an outbound client has one: a `--server-bind` publisher's sessions are + // an outbound client has one: a `--listen` publisher's sessions are // inbound and never surfaced here, so it stays `None` and those sources encode // at their configured rate. Capture is the only such source today, so without // that feature nothing reads this. @@ -265,7 +268,7 @@ async fn run_import(moq: MoqSide, import: Import, net: Net) -> anyhow::Result<() let mut send_bandwidth = None; // MoQ side: publish the Origin outward. - if moq.client.connect.is_some() + if moq.client.url.is_some() && let Some(reconnect) = net.client(moq.client.clone())?.publish(origin.consume()) { // Read before the handle moves into the task. This consumer is diff --git a/rs/moq-cli/src/transcode.rs b/rs/moq-cli/src/transcode.rs index 9336d0afb72..c47c20b8d77 100644 --- a/rs/moq-cli/src/transcode.rs +++ b/rs/moq-cli/src/transcode.rs @@ -83,7 +83,7 @@ pub async fn run(moq: MoqSide, args: Args, net: Net) -> anyhow::Result<()> { .client .connect .clone() - .context("`transcode` requires a relay: pass --client-connect ")?; + .context("`transcode` requires a relay: pass --connect ")?; let publish = moq_net::Origin::random().produce(); // A session drop closes the source broadcast and ends the run: the outage is // surfaced rather than transcoded over. The reconnect loop covers the dial; diff --git a/rs/moq-cli/src/web.rs b/rs/moq-cli/src/web.rs index bdfac2d64ef..e099bb4fa2e 100644 --- a/rs/moq-cli/src/web.rs +++ b/rs/moq-cli/src/web.rs @@ -59,7 +59,7 @@ pub async fn serve( } /// Serve the `/certificate.sha256` self-signed fingerprint over HTTP, so an -/// `http://` client can pin a `--server-bind` server's generated cert. +/// `http://` client can pin a `--listen` server's generated cert. pub async fn run_web(bind: &str, certificates: moq_native::tls::Certificates) -> anyhow::Result<()> { let listen = tokio::net::lookup_host(bind) .await diff --git a/rs/moq-ffi/src/server.rs b/rs/moq-ffi/src/server.rs index 292e95465e2..0e824bf4cc9 100644 --- a/rs/moq-ffi/src/server.rs +++ b/rs/moq-ffi/src/server.rs @@ -7,7 +7,7 @@ use crate::origin::MoqOriginProducer; use crate::session::MoqSession; struct ServerState { - config: moq_native::ServerConfig, + config: moq_native::listen::Config, publish: Option>, consume: Option>, server: Option, @@ -21,7 +21,7 @@ impl ServerState { let server = self .config .clone() - .init() + .init(Default::default()) .map_err(|err| MoqError::Bind(format!("{err}")))? .listen() .await @@ -62,7 +62,7 @@ impl MoqServer { let _guard = crate::ffi::RUNTIME.enter(); Arc::new(Self { task: Task::new(ServerState { - config: moq_native::ServerConfig::default(), + config: moq_native::listen::Config::default(), publish: None, consume: None, server: None, diff --git a/rs/moq-ffi/src/session.rs b/rs/moq-ffi/src/session.rs index c47c812ad5d..fd75d5f4fdc 100644 --- a/rs/moq-ffi/src/session.rs +++ b/rs/moq-ffi/src/session.rs @@ -7,14 +7,18 @@ use crate::ffi::Task; use crate::origin::{MoqOriginConsumer, MoqOriginProducer}; struct Client { - config: moq_native::ClientConfig, + config: moq_native::connect::Config, publish: Option>, consume: Option>, } impl Client { async fn connect(&self, url: Url) -> Result, MoqError> { - let client = self.config.clone().init().map_err(map_connect_error)?; + let client = self + .config + .clone() + .init(Default::default()) + .map_err(map_connect_error)?; // Materialize both origin sides so the session can publish/subscribe and the FFI can // always hand back a publisher/consumer. @@ -182,7 +186,7 @@ impl MoqClient { let _guard = crate::ffi::RUNTIME.enter(); Arc::new(Self { task: Task::new(Client { - config: moq_native::ClientConfig::default(), + config: moq_native::connect::Config::default(), publish: None, consume: None, }), @@ -192,7 +196,7 @@ impl MoqClient { /// Disable TLS certificate verification (for development only). pub fn set_tls_disable_verify(&self, disable: bool) { if let Some(mut state) = self.task.lock() { - state.config.tls.disable_verify = Some(disable); + state.config.tls.insecure = Some(disable); } } @@ -259,7 +263,7 @@ impl MoqClient { .parse() .map_err(|err| MoqError::Bind(format!("invalid bind address: {err}")))?; if let Some(mut state) = self.task.lock() { - state.config.bind = parsed; + state.config.bind = Some(parsed); } Ok(()) } @@ -272,7 +276,7 @@ impl MoqClient { /// (surfaced via [`MoqSession::closed`]). pub fn set_reconnect(&self, enabled: bool) { if let Some(mut state) = self.task.lock() { - state.config.reconnect = Some(enabled); + state.config.once = Some(!enabled); } } diff --git a/rs/moq-gst/src/sink/session.rs b/rs/moq-gst/src/sink/session.rs index 73f7b858da3..1990f9f24fa 100644 --- a/rs/moq-gst/src/sink/session.rs +++ b/rs/moq-gst/src/sink/session.rs @@ -144,10 +144,10 @@ impl Session { // retry), posting the bus error below. During an outage the pad threads keep writing (bounded // by moq-net's per-group eviction) and the relay catches up from a group boundary on // reconnect. A bounded policy is available via `ClientConfig::backoff`. - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(settings.tls_disable_verify); + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(settings.tls_disable_verify); config.backoff.timeout = Some(std::time::Duration::ZERO); - let client = config.init()?.with_publisher(origin.consume()); + let client = config.init(Default::default())?.with_publisher(origin.consume()); let reconnect = client.connect(settings.url.clone()); // Persistent handles that survive reconnects; the getters read them without touching the loop. let send_bandwidth = reconnect.send_bandwidth(); diff --git a/rs/moq-gst/src/source/imp.rs b/rs/moq-gst/src/source/imp.rs index b5af2ec26b2..8f46dcb6306 100644 --- a/rs/moq-gst/src/source/imp.rs +++ b/rs/moq-gst/src/source/imp.rs @@ -280,12 +280,12 @@ async fn run_session( element: glib::WeakRef, shutdown: &mut watch::Receiver, ) -> Result<()> { - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(settings.tls_disable_verify); + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(settings.tls_disable_verify); let origin = moq_net::Origin::random().produce(); let origin_consumer = origin.consume(); - let client = config.init()?.with_subscriber(origin); + let client = config.init(Default::default())?.with_subscriber(origin); // One-shot: the catalog subscription below dies with the session anyway, so a // background redial could not resurrect this run. A drop surfaces as the diff --git a/rs/moq-native/examples/chat.rs b/rs/moq-native/examples/chat.rs index 7f95d4f7d2a..f6eadb7dc0d 100644 --- a/rs/moq-native/examples/chat.rs +++ b/rs/moq-native/examples/chat.rs @@ -22,7 +22,7 @@ async fn main() -> anyhow::Result<()> { // Connect to the server and publish our origin of broadcasts. async fn run_session(origin: moq_net::origin::Producer) -> anyhow::Result<()> { // Optional: Use moq_native to make a QUIC client. - let client = moq_native::ClientConfig::default().init()?; + let client = moq_native::connect::Config::default().init(Default::default())?; // For local development, use: http://localhost:4443 // The "anon" path is usually configured to bypass authentication; be careful! diff --git a/rs/moq-native/examples/clock.rs b/rs/moq-native/examples/clock.rs index f939d43f6b8..6b1ba567074 100644 --- a/rs/moq-native/examples/clock.rs +++ b/rs/moq-native/examples/clock.rs @@ -8,8 +8,8 @@ //! Run with: //! //! ```text -//! cargo run -p moq-native --example clock -- --client-connect https://relay.example.com/anon --broadcast clock publish -//! cargo run -p moq-native --example clock -- --client-connect https://relay.example.com/anon --broadcast clock subscribe +//! cargo run -p moq-native --example clock -- --connect https://relay.example.com/anon --broadcast clock publish +//! cargo run -p moq-native --example clock -- --connect https://relay.example.com/anon --broadcast clock subscribe //! ``` use anyhow::Context; @@ -25,7 +25,7 @@ struct Config { /// The MoQ client configuration. #[command(flatten)] - client: moq_native::ClientConfig, + client: moq_native::connect::Config, /// The name of the clock track. #[arg(long, default_value = "seconds")] @@ -51,8 +51,8 @@ async fn main() -> anyhow::Result<()> { let config = Config::parse(); config.log.init()?; - let url = config.client.connect.clone().context("--client-connect is required")?; - let client = config.client.init()?; + let url = config.client.url.clone().context("--connect is required")?; + let client = config.client.init(Default::default())?; tracing::info!(%url, "connecting to server"); diff --git a/rs/moq-native/src/client.rs b/rs/moq-native/src/client.rs index 1e1bc73a897..33d50a7ea40 100644 --- a/rs/moq-native/src/client.rs +++ b/rs/moq-native/src/client.rs @@ -1,200 +1,11 @@ use crate::{Addrs, Backoff, Connection, Error, GoawayConfig, QuicBackend}; #[cfg(all(feature = "websocket", any(feature = "noq", feature = "quinn", feature = "quiche")))] use std::future::Future; -use std::net; use url::Url; -const DEFAULT_CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); - -/// How long to wait before also dialing the next resolved address, unless -/// overridden by `--client-failover-delay`. RFC 8305's recommended Connection -/// Attempt Delay. -/// -/// Lives here rather than in [`crate::failover`], which is compiled only for the -/// transports that dial an address themselves: the resolved default is config, so -/// [`ClientConfig::resolved_failover_delay`] has to answer in every build. -pub(crate) const DEFAULT_FAILOVER_DELAY: std::time::Duration = std::time::Duration::from_millis(250); - -/// Configuration for the MoQ client. -#[derive(Clone, Debug, clap::Parser, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields, default)] -#[non_exhaustive] -pub struct ClientConfig { - /// The URL to dial. - /// - /// Supports WebTransport (`https`/`http`), WebSocket (`ws`/`wss`), raw QUIC - /// (`moqt`/`moql`), qmux over `tcp`/`unix`, and `iroh`. The URL path is the - /// request/auth path (e.g. `/anon` for a public relay) and `?jwt=` supplies a - /// token. `http://` first fetches `/certificate.sha256` for the (insecure) - /// self-signed fingerprint; `https://` connects directly. - #[serde(skip_serializing_if = "Option::is_none")] - #[arg(id = "client-connect", long = "client-connect", env = "MOQ_CLIENT_CONNECT")] - pub connect: Option, - - /// Listen for UDP packets on the given address. - #[arg( - id = "client-bind", - long = "client-bind", - default_value = "[::]:0", - env = "MOQ_CLIENT_BIND" - )] - pub bind: net::SocketAddr, - - /// The QUIC backend to use. - /// Auto-detected from compiled features if not specified. - #[arg(id = "client-backend", long = "client-backend", env = "MOQ_CLIENT_BACKEND")] - pub backend: Option, - - /// Delay before also dialing the next resolved address (Happy Eyeballs). - /// - /// When DNS returns multiple addresses, attempts alternate between IPv6 and - /// IPv4, each starting this long after the previous one (or immediately when - /// it fails), and the first connection to complete wins. `0s` dials every - /// address at once. Defaults to 250ms. Applies to the QUIC and `tcp://` dials. - /// - /// This staggers the attempts within one [`Client::connect`]; [`Self::timeout`] - /// bounds that call as a whole. - #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] - #[arg( - id = "client-failover-delay", - long = "client-failover-delay", - env = "MOQ_CLIENT_FAILOVER_DELAY", - value_parser = humantime::parse_duration, - )] - pub failover_delay: Option, - - /// Maximum time for one [`Client::connect`], covering the dial and the MoQ - /// handshake. Defaults to 30 seconds; set to 0 to wait forever. - /// - /// This has to live above the transports rather than inside one: QUIC bounds its - /// own dial, but the WebSocket fallback and the handshake that follows either - /// transport have no deadline of their own, so a peer that accepts TCP and then - /// never speaks would hang the whole connect. [`Connection`] only re-arms - /// its backoff between attempts, so an attempt that never returns stalls the - /// retry loop indefinitely. - #[arg( - id = "client-connect-timeout", - long = "client-connect-timeout", - env = "MOQ_CLIENT_CONNECT_TIMEOUT", - value_parser = humantime::parse_duration, - )] - #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] - pub timeout: Option, - - /// QUIC transport tuning (`--client-quic-*`): stream limits, GSO, timeouts. - #[command(flatten)] - #[serde(default)] - pub quic: crate::quic::Client, - - /// Restrict the client to specific MoQ protocol version(s). - /// - /// By default, the client offers all supported versions and lets the server choose. - /// Use this to force a specific version, e.g. `--client-version moq-lite-02`. - /// Can be specified multiple times to offer a subset of versions. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[arg( - id = "client-version", - long = "client-version", - env = "MOQ_CLIENT_VERSION", - value_parser = crate::version_parser(), - )] - pub version: Vec, - - /// TLS trust and client-certificate settings (`--client-tls-*`). - #[command(flatten)] - #[serde(default)] - pub tls: crate::tls::Client, - - /// Whether a [`Connection`] redials (with backoff) after its session drops. - /// - /// Defaults to true. Set to false for a one-shot dial: the session's close - /// then surfaces through [`Connection::closed`] instead of triggering a - /// reconnect. - #[serde(skip_serializing_if = "Option::is_none")] - #[arg( - id = "client-reconnect", - long = "client-reconnect", - env = "MOQ_CLIENT_RECONNECT", - default_missing_value = "true", - num_args = 0..=1, - require_equals = true, - value_parser = clap::value_parser!(bool), - )] - pub reconnect: Option, - - /// Retry pacing for [`Client::connect`] (`--client-backoff-*`). - #[command(flatten)] - #[serde(default)] - pub backoff: Backoff, - - /// How [`Client::connect`] reacts to a peer's GOAWAY (`--goaway-*`). - #[command(flatten)] - #[serde(default)] - pub goaway: GoawayConfig, - - /// WebSocket fallback settings (`--client-websocket-*`), used when QUIC is - /// blocked. - #[cfg(feature = "websocket")] - #[command(flatten)] - #[serde(default)] - pub websocket: crate::websocket::Client, -} - -impl ClientConfig { - /// Build the [`Client`] this config describes. - pub fn init(self) -> crate::Result { - Client::new(self) - } - - /// Returns the configured versions, defaulting to all if none specified. - pub fn versions(&self) -> moq_net::Versions { - if self.version.is_empty() { - moq_net::Versions::all() - } else { - moq_net::Versions::from(self.version.clone()) - } - } - - /// The Happy Eyeballs stagger a dial will actually use, resolving the default. - /// - /// Every backend reads it from here so the four dial paths can't drift apart. The - /// [`failover_delay`](Self::failover_delay) field is the override; this is the value - /// it resolves to, so `ClientConfig::default().resolved_failover_delay()` is the - /// default itself. - pub fn resolved_failover_delay(&self) -> std::time::Duration { - self.failover_delay.unwrap_or(DEFAULT_FAILOVER_DELAY) - } - - /// The deadline one connection attempt will actually get, dial and handshake - /// together, resolving the default from the [`timeout`](Self::timeout) override. - pub fn resolved_connect_timeout(&self) -> std::time::Duration { - self.timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT) - } -} - -impl Default for ClientConfig { - fn default() -> Self { - Self { - connect: None, - bind: "[::]:0".parse().unwrap(), - backend: None, - failover_delay: None, - timeout: None, - quic: crate::quic::Client::default(), - version: Vec::new(), - tls: crate::tls::Client::default(), - reconnect: None, - backoff: Backoff::default(), - goaway: GoawayConfig::default(), - #[cfg(feature = "websocket")] - websocket: crate::websocket::Client::default(), - } - } -} - /// Client for establishing MoQ connections over QUIC, WebTransport, or WebSocket. /// -/// Create via [`ClientConfig::init`] or [`Client::new`]. +/// Create via [`crate::connect::Config::init`] or [`Client::new`]. #[derive(Clone)] pub struct Client { moq: moq_net::Client, @@ -212,9 +23,9 @@ pub struct Client { feature = "uds" ))] versions: moq_net::Versions, - /// The URL from [`ClientConfig::connect`], dialed by [`Client::publish`] / [`Client::consume`]. + /// The URL from [`connect.url`](crate::connect::Config::url), dialed by [`Client::publish`] / [`Client::consume`]. connect: Option, - /// Deadline for one [`Client::connect`], from [`ClientConfig::timeout`]. Zero waits forever. + /// Deadline for one [`Client::connect`], from [`crate::connect::Config::timeout`]. Zero waits forever. timeout: std::time::Duration, pub(crate) reconnect: bool, pub(crate) backoff: Backoff, @@ -224,7 +35,7 @@ pub struct Client { #[cfg(feature = "tcp")] failover_delay: std::time::Duration, #[cfg(feature = "websocket")] - websocket: crate::websocket::Client, + websocket: crate::websocket::Config, /// Only the rustls-based dials read this. quiche builds its own TLS stack, and the /// plaintext qmux transports have none. #[cfg(any(feature = "noq", feature = "quinn", feature = "websocket"))] @@ -254,7 +65,7 @@ impl Client { feature = "tcp", feature = "uds" )))] - pub fn new(_config: ClientConfig) -> crate::Result { + pub fn new(_config: crate::connect::Config, _quic: crate::quic::Config) -> crate::Result { Err(Error::NoBackend( "no backend compiled; enable noq, quinn, quiche, iroh, websocket, tcp, or uds feature", )) @@ -270,11 +81,16 @@ impl Client { feature = "tcp", feature = "uds" ))] - pub fn new(config: ClientConfig) -> crate::Result { + pub fn new(config: crate::connect::Config, quic: crate::quic::Config) -> crate::Result { + // Resolve here rather than in `init`, so a caller that builds the config by hand + // gets the released spellings folded in too. + let config = config.resolved(); + let quic = quic.resolved(); + #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] let backend = config.backend.clone().unwrap_or_else(crate::default_quic_backend); - config.quic.validate()?; + quic.validate()?; // Only the rustls-backed transports use this. Iroh, quiche, and the plaintext // qmux transports must not require a rustls crypto provider. @@ -284,29 +100,29 @@ impl Client { #[cfg(feature = "noq")] #[allow(unreachable_patterns)] let noq = match backend { - QuicBackend::Noq => Some(crate::noq::NoqClient::new(&config)?), + QuicBackend::Noq => Some(crate::noq::NoqClient::new(&config, &quic)?), _ => None, }; #[cfg(feature = "quinn")] #[allow(unreachable_patterns)] let quinn = match backend { - QuicBackend::Quinn => Some(crate::quinn::QuinnClient::new(&config)?), + QuicBackend::Quinn => Some(crate::quinn::QuinnClient::new(&config, &quic)?), _ => None, }; #[cfg(feature = "quiche")] #[allow(unreachable_patterns)] let quiche = match backend { - QuicBackend::Quiche => Some(crate::quiche::QuicheClient::new(&config)?), + QuicBackend::Quiche => Some(crate::quiche::QuicheClient::new(&config, &quic)?), _ => None, }; let versions = config.versions(); // Read before the struct literal below moves fields out of `config`. #[cfg(feature = "tcp")] - let failover_delay = config.resolved_failover_delay(); - let timeout = config.resolved_connect_timeout(); + let failover_delay = config.resolved_race(); + let timeout = config.resolved_timeout(); Ok(Self { moq: moq_net::Client::new().with_versions(versions.clone()), @@ -319,9 +135,9 @@ impl Client { feature = "uds" ))] versions, - connect: config.connect, + connect: config.url, timeout, - reconnect: config.reconnect.unwrap_or(true), + reconnect: !config.once.unwrap_or(false), backoff: config.backoff, goaway: config.goaway, #[cfg(feature = "tcp")] @@ -397,7 +213,7 @@ impl Client { /// Override whether this client redials after a session drop. /// - /// Defaults to [`ClientConfig::reconnect`], which defaults to true. + /// Defaults to true, unless [`crate::connect::Config::once`] turned it off. pub fn with_reconnect(mut self, reconnect: bool) -> Self { self.reconnect = reconnect; self @@ -409,7 +225,7 @@ impl Client { /// redials with exponential backoff whenever the session drops. Wait for the /// first session with [`Connection::established`] and for the loop to stop /// with [`Connection::closed`]; drop the last clone to stop it. Disable the - /// redialing with [`ClientConfig::reconnect`] / [`Self::with_reconnect`] for + /// redialing with [`crate::connect::Config::once`] / [`Self::with_reconnect`] for /// a one-shot dial. /// /// Takes a [`Url`] for the usual case of a peer at a known address. Pass @@ -420,24 +236,24 @@ impl Client { Connection::new(self.clone(), addrs.into()) } - /// Connect to the configured [`ClientConfig::connect`] URL, publishing + /// Connect to the configured [`connect.url`](crate::connect::Config::url) URL, publishing /// `origin` to it. /// - /// Returns `None` when no `--client-connect` URL was configured, so a caller + /// Returns `None` when no `--connect` URL was configured, so a caller /// that may run server-only doesn't have to branch on the URL itself. pub fn publish(self, origin: moq_net::origin::Consumer) -> Option { let url = self.connect.clone()?; Some(self.with_publisher(origin).connect(url)) } - /// Connect to the configured [`ClientConfig::connect`] URL, consuming its + /// Connect to the configured [`connect.url`](crate::connect::Config::url) URL, consuming its /// broadcasts into `origin`. /// /// A session drop closes and unannounces the broadcasts it fed; the reconnect /// loop re-announces them once a replacement session attaches. Applications /// observe the outage rather than reading from a stale route. /// - /// Returns `None` when no `--client-connect` URL was configured. + /// Returns `None` when no `--connect` URL was configured. pub fn consume(self, origin: moq_net::origin::Producer) -> Option { let url = self.connect.clone()?; Some(self.with_subscriber(origin).connect(url)) @@ -799,7 +615,26 @@ where #[cfg(test)] mod tests { use super::*; - use clap::{CommandFactory, Parser}; + use clap::Parser; + + /// A parser wrapping the config, since it derives `Args` (a flattened `Parser` + /// registers an implicit group named after the struct, which collides once two + /// role configs are flattened together). + #[derive(Parser)] + struct Cli { + #[command(flatten)] + config: crate::connect::Config, + } + + impl Cli { + fn config_from(args: I) -> crate::connect::Config + where + I: IntoIterator, + T: Into + Clone, + { + Cli::parse_from(args).config + } + } #[cfg(any( feature = "noq", @@ -884,33 +719,35 @@ mod tests { #[test] fn test_toml_disable_verify_survives_update_from() { let toml = r#" - tls.disable_verify = true + tls.insecure = true "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); - assert_eq!(config.tls.disable_verify, Some(true)); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); + assert_eq!(config.tls.insecure, Some(true)); - // Simulate: TOML loaded, then CLI args re-applied (no --client-tls-disable-verify flag). - config.update_from(["test"]); - assert_eq!(config.tls.disable_verify, Some(true)); + // Simulate: TOML loaded, then CLI args re-applied (no --connect-tls-insecure flag). + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; + assert_eq!(config.tls.insecure, Some(true)); } #[test] fn test_cli_disable_verify_flag() { - let config = ClientConfig::parse_from(["test", "--client-tls-disable-verify"]); - assert_eq!(config.tls.disable_verify, Some(true)); + let config = Cli::config_from(["test", "--connect-tls-insecure"]); + assert_eq!(config.tls.insecure, Some(true)); } #[test] fn test_cli_disable_verify_explicit_false() { - let config = ClientConfig::parse_from(["test", "--client-tls-disable-verify=false"]); - assert_eq!(config.tls.disable_verify, Some(false)); + let config = Cli::config_from(["test", "--connect-tls-insecure=false"]); + assert_eq!(config.tls.insecure, Some(false)); } #[test] fn test_cli_disable_verify_explicit_true() { - let config = ClientConfig::parse_from(["test", "--client-tls-disable-verify=true"]); - assert_eq!(config.tls.disable_verify, Some(true)); + let config = Cli::config_from(["test", "--connect-tls-insecure=true"]); + assert_eq!(config.tls.insecure, Some(true)); } #[test] @@ -918,9 +755,9 @@ mod tests { // The bare --tls-* forms are deprecated. They parse into a hidden field and // fold into the canonical values via the effective_* accessors build() uses, // so they keep working without touching the public Client fields. - let config = ClientConfig::parse_from(["test", "--tls-disable-verify=true", "--tls-fingerprint", "abcd1234"]); + let config = Cli::config_from(["test", "--tls-disable-verify=true", "--tls-fingerprint", "abcd1234"]); assert_eq!( - config.tls.disable_verify, None, + config.tls.insecure, None, "deprecated flag must not set the canonical field" ); assert_eq!(config.tls.effective_disable_verify(), Some(true)); @@ -930,9 +767,9 @@ mod tests { #[test] fn test_canonical_tls_flag_wins_over_deprecated() { // Both spellings given: canonical wins for scalar options, vecs concatenate. - let config = ClientConfig::parse_from([ + let config = Cli::config_from([ "test", - "--client-tls-disable-verify=false", + "--connect-tls-insecure=false", "--tls-disable-verify=true", "--client-tls-fingerprint", "aaaa", @@ -940,13 +777,13 @@ mod tests { "bbbb", ]); assert_eq!(config.tls.effective_disable_verify(), Some(false)); - assert_eq!(config.tls.effective_fingerprint(), vec!["aaaa", "bbbb"]); + assert_eq!(config.tls.effective_fingerprint(), vec!["bbbb", "aaaa"]); } #[test] fn test_cli_no_disable_verify() { - let config = ClientConfig::parse_from(["test"]); - assert_eq!(config.tls.disable_verify, None); + let config = Cli::config_from(["test"]); + assert_eq!(config.tls.insecure, None); } #[test] @@ -955,18 +792,24 @@ mod tests { failover_delay = "1s" "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); - assert_eq!(config.failover_delay, Some(std::time::Duration::from_secs(1))); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); + assert_eq!(config.race, Some(std::time::Duration::from_secs(1))); // Simulate: TOML loaded, then CLI args re-applied (no --client-failover-delay flag). - config.update_from(["test"]); - assert_eq!(config.failover_delay, Some(std::time::Duration::from_secs(1))); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; + assert_eq!(config.race, Some(std::time::Duration::from_secs(1))); } #[test] fn test_cli_failover_delay() { - let config = ClientConfig::parse_from(["test", "--client-failover-delay", "50ms"]); - assert_eq!(config.failover_delay, Some(std::time::Duration::from_millis(50))); + let config = Cli::config_from(["test", "--connect-race", "50ms"]); + assert_eq!(config.race, Some(std::time::Duration::from_millis(50))); + + // The released spelling folds in on resolve. + let config = Cli::config_from(["test", "--client-failover-delay", "50ms"]).resolved(); + assert_eq!(config.race, Some(std::time::Duration::from_millis(50))); } #[test] @@ -975,11 +818,13 @@ mod tests { tls.fingerprint = ["abcd1234", "ef567890"] "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); assert_eq!(config.tls.fingerprint, vec!["abcd1234", "ef567890"]); // Simulate: TOML loaded, then CLI args re-applied (no --client-tls-fingerprint flag). - config.update_from(["test"]); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; assert_eq!(config.tls.fingerprint, vec!["abcd1234", "ef567890"]); } @@ -989,13 +834,13 @@ mod tests { tls.fingerprint = "abcd1234" "#; - let config: ClientConfig = toml::from_str(toml).unwrap(); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); assert_eq!(config.tls.fingerprint, vec!["abcd1234"]); } #[test] fn test_cli_fingerprint() { - let config = ClientConfig::parse_from(["test", "--client-tls-fingerprint", "abcd1234"]); + let config = Cli::config_from(["test", "--client-tls-fingerprint", "abcd1234"]).resolved(); assert_eq!(config.tls.fingerprint, vec!["abcd1234"]); } @@ -1005,23 +850,31 @@ mod tests { version = ["moq-lite-02"] "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); assert_eq!(config.version, vec!["moq-lite-02".parse::().unwrap()]); // Simulate: TOML loaded, then CLI args re-applied (no --client-version flag). - config.update_from(["test"]); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; assert_eq!(config.version, vec!["moq-lite-02".parse::().unwrap()]); } #[test] fn test_cli_version() { - let config = ClientConfig::parse_from(["test", "--client-version", "moq-lite-03"]); + let config = Cli::config_from(["test", "--connect-version", "moq-lite-03"]); + assert_eq!(config.version, vec!["moq-lite-03".parse::().unwrap()]); + + // The released spelling folds in on resolve. + let config = Cli::config_from(["test", "--client-version", "moq-lite-03"]).resolved(); assert_eq!(config.version, vec!["moq-lite-03".parse::().unwrap()]); } #[test] fn test_cli_version_help_lists_every_parseable_name() { - let help = ClientConfig::command().render_long_help().to_string(); + let help = ::augment_args(clap::Command::new("test")) + .render_long_help() + .to_string(); for name in moq_net::Version::names() { assert!(help.contains(name), "missing {name} from --client-version help"); } @@ -1033,53 +886,127 @@ mod tests { connect = "https://relay.example.com/anon" "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); - assert_eq!( - config.connect.as_ref().unwrap().as_str(), - "https://relay.example.com/anon" - ); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); + assert_eq!(config.url.as_ref().unwrap().as_str(), "https://relay.example.com/anon"); // Simulate: TOML loaded, then CLI args re-applied (no --client-connect flag). - config.update_from(["test"]); - assert_eq!( - config.connect.as_ref().unwrap().as_str(), - "https://relay.example.com/anon" - ); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; + assert_eq!(config.url.as_ref().unwrap().as_str(), "https://relay.example.com/anon"); } #[test] fn test_cli_connect() { - let config = ClientConfig::parse_from(["test", "--client-connect", "https://relay.example.com/anon"]); - assert_eq!( - config.connect.as_ref().unwrap().as_str(), - "https://relay.example.com/anon" - ); + let config = Cli::config_from(["test", "--connect", "https://relay.example.com/anon"]); + assert_eq!(config.url.as_ref().unwrap().as_str(), "https://relay.example.com/anon"); + + // The released spelling folds in on resolve. + let config = Cli::config_from(["test", "--client-connect", "https://relay.example.com/anon"]).resolved(); + assert_eq!(config.url.as_ref().unwrap().as_str(), "https://relay.example.com/anon"); } #[test] - fn test_toml_reconnect_survives_update_from() { + fn test_toml_once_survives_update_from() { let toml = r#" - reconnect = false + once = true "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); - assert_eq!(config.reconnect, Some(false)); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); + assert_eq!(config.once, Some(true)); + + // Simulate: TOML loaded, then CLI args re-applied (no --connect-once flag). + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; + assert_eq!(config.once, Some(true)); + } + + /// The released TOML said `reconnect = false`; the flag it became says the + /// opposite thing, so the value has to flip on the way in. + #[test] + fn test_toml_reconnect_inverts_into_once() { + let config: crate::connect::Config = toml::from_str("reconnect = false").unwrap(); + let config = config.resolved(); + assert_eq!(config.once, Some(true)); + assert_eq!(config.reconnect, None, "the shim is consumed by the fold"); + + let config: crate::connect::Config = toml::from_str("reconnect = true").unwrap(); + assert_eq!(config.resolved().once, Some(false)); + + // A canonical `once` wins over the legacy spelling it replaced. + let config: crate::connect::Config = toml::from_str("once = false\nreconnect = false").unwrap(); + assert_eq!(config.resolved().once, Some(false)); + } + + /// An explicit canonical bind wins even when it equals the default, which a + /// `default_value` would have made indistinguishable from "unset". + #[test] + fn test_cli_bind_prefers_canonical() { + let config = Cli::config_from(["test"]).resolved(); + assert_eq!(config.bind, None, "unset means the default"); + assert_eq!(config.resolved_bind(), "[::]:0".parse().unwrap()); + + let config = Cli::config_from(["test", "--client-bind", "127.0.0.1:0"]).resolved(); + assert_eq!(config.bind, Some("127.0.0.1:0".parse().unwrap())); + + let config = Cli::config_from(["test", "--connect-bind", "[::]:0", "--client-bind", "127.0.0.1:0"]).resolved(); + assert_eq!( + config.bind, + Some("[::]:0".parse().unwrap()), + "an explicit canonical bind wins even when it is the default" + ); + } + + /// A config file's bind survives the CLI re-parse, which a clap `default_value` + /// would have clobbered. + #[test] + fn test_toml_bind_survives_update_from() { + let config: crate::connect::Config = toml::from_str(r#"bind = "127.0.0.1:1234""#).unwrap(); + assert_eq!(config.bind, Some("127.0.0.1:1234".parse().unwrap())); - // Simulate: TOML loaded, then CLI args re-applied (no --client-reconnect flag). - config.update_from(["test"]); - assert_eq!(config.reconnect, Some(false)); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + assert_eq!(cli.config.bind, Some("127.0.0.1:1234".parse().unwrap())); } + /// Both spellings name versions to offer, so neither list may be dropped. #[test] - fn test_cli_reconnect_flag() { - let config = ClientConfig::parse_from(["test"]); - assert_eq!(config.reconnect, None, "unset means the default (reconnect)"); + fn test_version_lists_concatenate() { + let config = Cli::config_from([ + "test", + "--connect-version", + "moq-lite-03", + "--client-version", + "moq-lite-02", + ]) + .resolved(); + assert_eq!( + config.version, + vec![ + "moq-lite-03".parse::().unwrap(), + "moq-lite-02".parse::().unwrap() + ] + ); + } + + #[test] + fn test_cli_once_flag() { + let config = Cli::config_from(["test"]); + assert_eq!(config.once, None, "unset means the default (reconnect)"); + + let config = Cli::config_from(["test", "--connect-once"]); + assert_eq!(config.once, Some(true)); + + let config = Cli::config_from(["test", "--connect-once=false"]); + assert_eq!(config.once, Some(false)); - let config = ClientConfig::parse_from(["test", "--client-reconnect"]); - assert_eq!(config.reconnect, Some(true)); + // The released spelling folds in on resolve, inverted. + let config = Cli::config_from(["test", "--client-reconnect=false"]).resolved(); + assert_eq!(config.once, Some(true)); - let config = ClientConfig::parse_from(["test", "--client-reconnect=false"]); - assert_eq!(config.reconnect, Some(false)); + let config = Cli::config_from(["test", "--client-reconnect=true"]).resolved(); + assert_eq!(config.once, Some(false)); } #[test] @@ -1088,23 +1015,25 @@ mod tests { tls.host_name = "example.host" "#; - let mut config: ClientConfig = toml::from_str(toml).unwrap(); + let config: crate::connect::Config = toml::from_str(toml).unwrap(); assert_eq!(config.tls.host_name.as_deref(), Some("example.host")); // Simulate: TOML loaded, then CLI args re-applied (no --client-tls-host-name flag). - config.update_from(["test"]); + let mut cli = Cli { config }; + clap::Parser::update_from(&mut cli, ["test"]); + let config = cli.config; assert_eq!(config.tls.host_name.as_deref(), Some("example.host")); } #[test] fn test_cli_host_name() { - let config = ClientConfig::parse_from(["test", "--client-tls-host-name", "override.example"]); + let config = Cli::config_from(["test", "--client-tls-host-name", "override.example"]).resolved(); assert_eq!(config.tls.host_name.as_deref(), Some("override.example")); } #[test] fn test_cli_no_version_defaults_to_all() { - let config = ClientConfig::parse_from(["test"]); + let config = Cli::config_from(["test"]); assert!(config.version.is_empty()); // versions() helper returns all when none specified assert_eq!(config.versions().alpns().len(), moq_net::ALPNS.len()); @@ -1153,10 +1082,10 @@ mod tests { /// The resolved default has to exist in every build, including ones that compile /// no address-racing transport at all, which is what broke in #2773. #[test] - fn failover_delay_defaults_to_the_rfc_8305_stagger() { - let config = ClientConfig::parse_from(["test"]); - assert_eq!(config.failover_delay, None); - assert_eq!(config.resolved_failover_delay(), std::time::Duration::from_millis(250)); + fn race_defaults_to_the_rfc_8305_stagger() { + let config = crate::connect::Config::default(); + assert_eq!(config.race, None); + assert_eq!(config.resolved_race(), std::time::Duration::from_millis(250)); } /// Iroh carries no rustls state, so constructing its client must not require an @@ -1172,9 +1101,9 @@ mod tests { #[test] fn connect_timeout_defaults_to_thirty_seconds() { - let config = ClientConfig::parse_from(["test"]); + let config = Cli::config_from(["test"]); assert_eq!(config.timeout, None); - assert_eq!(config.resolved_connect_timeout(), DEFAULT_CONNECT_TIMEOUT); + assert_eq!(config.resolved_timeout(), crate::connect::DEFAULT_TIMEOUT); } /// A peer that completes the TCP handshake and then never speaks: the QUIC arm @@ -1190,13 +1119,13 @@ mod tests { let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); - let timeout = DEFAULT_CONNECT_TIMEOUT; - let mut config = ClientConfig { + let timeout = crate::connect::DEFAULT_TIMEOUT; + let mut config = crate::connect::Config { timeout: Some(timeout), ..Default::default() }; config.websocket.delay = Some(std::time::Duration::ZERO); - let client = config.init().unwrap(); + let client = config.init(Default::default()).unwrap(); // Nothing is listening on UDP, so the QUIC arm fails and leaves the WebSocket // arm alone against the silent peer. diff --git a/rs/moq-native/src/connect.rs b/rs/moq-native/src/connect.rs index f028220e285..30a9a0eb48c 100644 --- a/rs/moq-native/src/connect.rs +++ b/rs/moq-native/src/connect.rs @@ -1,9 +1,27 @@ +//! The dial side of an endpoint: where to connect and how to get there. +//! +//! [`Addrs`] is the peer's address list, [`Config`] is how to reach it, and the +//! accept side lives in [`crate::listen`]. + +use crate::{Backoff, GoawayConfig, QuicBackend}; +use std::net; use url::Url; +/// Maximum time for one dial, unless overridden by `--connect-timeout`. +pub(crate) const DEFAULT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30); + +/// How long to wait before also dialing the next resolved address, unless overridden +/// by `--connect-race`. RFC 8305's recommended Connection Attempt Delay. +/// +/// Lives here rather than in [`crate::failover`], which is compiled only for the +/// transports that dial an address themselves: the resolved default is config, so +/// [`Config::resolved_race`] has to answer in every build. +pub(crate) const DEFAULT_RACE: std::time::Duration = std::time::Duration::from_millis(250); + /// One or more addresses for the same peer, tried in order until one connects. /// /// Most callers have a single URL and never name this type: -/// [`Client::connect`](crate::Client::connect) takes `impl Into` and the +/// [`crate::Client::connect`](crate::Client::connect) takes `impl Into` and the /// [`From`] impl covers it. Several addresses are for a peer that was /// discovered rather than configured, where the record lists every interface the /// peer answered on and nothing says which of them routes from here. @@ -43,6 +61,107 @@ impl Addrs { } } +/// The dial socket when `--connect-bind` is unset: an ephemeral dual-stack port. +fn default_bind() -> net::SocketAddr { + "[::]:0".parse().unwrap() +} + +/// The `--client-*` flags from before the dial side was named `connect`. +#[derive(Clone, Debug, Default, clap::Args)] +#[group(id = "connect-legacy")] +pub(crate) struct Legacy { + #[arg( + id = "client-connect", + long = "client-connect", + env = "MOQ_CLIENT_CONNECT", + hide = true + )] + url: Option, + + #[arg(id = "client-bind", long = "client-bind", env = "MOQ_CLIENT_BIND", hide = true)] + bind: Option, + + #[arg( + id = "client-backend", + long = "client-backend", + env = "MOQ_CLIENT_BACKEND", + hide = true + )] + backend: Option, + + #[arg( + id = "client-connect-timeout", + long = "client-connect-timeout", + env = "MOQ_CLIENT_CONNECT_TIMEOUT", + value_parser = humantime::parse_duration, + hide = true, + )] + timeout: Option, + + #[arg( + id = "client-failover-delay", + long = "client-failover-delay", + env = "MOQ_CLIENT_FAILOVER_DELAY", + value_parser = humantime::parse_duration, + hide = true, + )] + race: Option, + + #[arg( + id = "client-reconnect", + long = "client-reconnect", + env = "MOQ_CLIENT_RECONNECT", + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + hide = true, + )] + reconnect: Option, + + #[arg( + id = "client-version", + long = "client-version", + env = "MOQ_CLIENT_VERSION", + value_parser = crate::version_parser(), + hide = true, + )] + version: Vec, +} + +impl Legacy { + /// The legacy flags in use, each paired with its replacement, for one warning. + /// + /// Spelled out rather than listing only the new names: `--client-reconnect` maps + /// to a flag that means the opposite, so a bare list would send someone to a flag + /// whose value they'd have to invert without being told. + fn used(&self) -> Vec<&'static str> { + let mut used = Vec::new(); + if self.url.is_some() { + used.push("--client-connect -> --connect"); + } + if self.bind.is_some() { + used.push("--client-bind -> --connect-bind"); + } + if self.backend.is_some() { + used.push("--client-backend -> --connect-backend"); + } + if self.timeout.is_some() { + used.push("--client-connect-timeout -> --connect-timeout"); + } + if self.race.is_some() { + used.push("--client-failover-delay -> --connect-race"); + } + if self.reconnect.is_some() { + used.push("--client-reconnect -> --connect-once (inverted)"); + } + if !self.version.is_empty() { + used.push("--client-version -> --connect-version"); + } + used + } +} + impl From for Addrs { fn from(url: Url) -> Self { Self::new(url) @@ -199,3 +318,239 @@ mod tests { ); } } + +/// The dial side of an endpoint: where to connect and how to get there. +/// +/// Derives [`clap::Args`], so flatten it into a binary's own parser with +/// `#[command(flatten)]`. The accept side is [`crate::listen::Config`]. +#[derive(Clone, Debug, Default, clap::Args, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields, default)] +#[group(id = "connect-config")] +#[non_exhaustive] +pub struct Config { + /// The URL to dial. + /// + /// Supports WebTransport (`https`/`http`), WebSocket (`ws`/`wss`), raw QUIC + /// (`moqt`/`moql`), qmux over `tcp`/`unix`, and `iroh`. The URL path is the + /// request/auth path (e.g. `/anon` for a public relay) and `?jwt=` supplies a + /// token. `http://` first fetches `/certificate.sha256` for the (insecure) + /// self-signed fingerprint; `https://` connects directly. + #[serde(alias = "connect", skip_serializing_if = "Option::is_none")] + #[arg(id = "connect", long = "connect", env = "MOQ_CONNECT")] + pub url: Option, + + /// Send from this local UDP address. Defaults to an ephemeral dual-stack port. + /// + /// `Option` with the default resolved in code rather than a clap `default_value`, + /// which the post-file CLI re-parse would materialize over whatever a config file + /// said. It also makes "explicitly the default" distinguishable from unset, which + /// the fold below needs. + #[serde(default, skip_serializing_if = "Option::is_none")] + #[arg(id = "connect-bind", long = "connect-bind", env = "MOQ_CONNECT_BIND")] + pub bind: Option, + + /// The QUIC backend to use. + /// Auto-detected from compiled features if not specified. + #[arg(id = "connect-backend", long = "connect-backend", env = "MOQ_CONNECT_BACKEND")] + pub backend: Option, + + /// Delay before also dialing the next resolved address (Happy Eyeballs). + /// + /// When DNS returns multiple addresses, attempts alternate between IPv6 and + /// IPv4, each starting this long after the previous one (or immediately when + /// it fails), and the first connection to complete wins. `0s` dials every + /// address at once. Defaults to 250ms. Applies to the QUIC and `tcp://` dials. + /// + /// This staggers the attempts within one [`crate::Client::connect`]; [`Self::timeout`] + /// bounds that call as a whole. + #[serde( + alias = "failover_delay", + default, + skip_serializing_if = "Option::is_none", + with = "humantime_serde::option" + )] + #[arg( + id = "connect-race", + long = "connect-race", + env = "MOQ_CONNECT_RACE", + value_parser = humantime::parse_duration, + )] + pub race: Option, + + /// Maximum time for one [`crate::Client::connect`], covering the dial and the MoQ + /// handshake. Defaults to 30 seconds; set to 0 to wait forever. + /// + /// This has to live above the transports rather than inside one: QUIC bounds its + /// own dial, but the WebSocket fallback and the handshake that follows either + /// transport have no deadline of their own, so a peer that accepts TCP and then + /// never speaks would hang the whole connect. [`crate::Connection`] only re-arms + /// its backoff between attempts, so an attempt that never returns stalls the + /// retry loop indefinitely. + #[arg( + id = "connect-timeout", + long = "connect-timeout", + env = "MOQ_CONNECT_TIMEOUT", + value_parser = humantime::parse_duration, + )] + #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] + pub timeout: Option, + + /// Restrict the client to specific MoQ protocol version(s). + /// + /// By default, the client offers all supported versions and lets the server choose. + /// Use this to force a specific version, e.g. `--connect-version moq-lite-02`. + /// Can be specified multiple times to offer a subset of versions. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[arg( + id = "connect-version", + long = "connect-version", + env = "MOQ_CONNECT_VERSION", + value_parser = crate::version_parser(), + )] + pub version: Vec, + + /// TLS trust and client-certificate settings (`--connect-tls-*`). + #[command(flatten)] + #[serde(default)] + pub tls: crate::tls::Connect, + + /// Dial once instead of redialing (with backoff) whenever the session drops. + /// + /// A [`crate::Connection`] reconnects by default. With this set, the session's + /// close surfaces through [`crate::Connection::closed`] instead. + #[serde(skip_serializing_if = "Option::is_none")] + #[arg( + id = "connect-once", + long = "connect-once", + env = "MOQ_CONNECT_ONCE", + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + )] + pub once: Option, + + /// The released `reconnect` spelling, which said the same thing the other way + /// around. Inverted into [`once`](Self::once) by [`resolved`](Self::resolved). + /// + /// TOML-only: the `--client-reconnect` flag lives on [`Legacy`] with the rest. + #[serde(default, skip_serializing)] + #[arg(skip)] + pub(crate) reconnect: Option, + + /// Retry pacing for [`crate::Client::connect`] (`--backoff-*`). + #[command(flatten)] + #[serde(default)] + pub backoff: Backoff, + + /// How [`crate::Client::connect`] reacts to a peer's GOAWAY (`--goaway-*`). + #[command(flatten)] + #[serde(default)] + pub goaway: GoawayConfig, + + /// WebSocket fallback settings (`--websocket-*`), used when QUIC is + /// blocked. + #[cfg(feature = "websocket")] + #[command(flatten)] + #[serde(default)] + pub websocket: crate::websocket::Config, + + /// The released `--client-*` spellings and their env vars, kept parsing but + /// hidden. Folded into the canonical fields by [`Config::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, + + /// The released `[client.quic]` table, which is now the shared top-level + /// `[quic]`. See [`crate::listen::Config::quic`]. + #[arg(skip)] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quic: Option, +} + +impl Config { + /// Fold every released `--client-*` spelling into the canonical fields. + /// + /// The canonical spelling wins. Warns once when a legacy spelling contributed. + /// Idempotent, and applied automatically by [`init`](Self::init), so calling it + /// yourself is only needed to inspect the folded values. + pub fn resolved(&self) -> Self { + let used = self.legacy.used(); + if !used.is_empty() { + tracing::warn!( + "deprecated --client-* flags in use; the dial side is now --connect-*: {}", + used.join(", ") + ); + } + let legacy = &self.legacy; + + let mut resolved = self.clone(); + resolved.url = self.url.clone().or(legacy.url.clone()); + resolved.bind = self.bind.or(legacy.bind); + resolved.backend = self.backend.clone().or(legacy.backend.clone()); + resolved.timeout = self.timeout.or(legacy.timeout); + resolved.race = self.race.or(legacy.race); + // The two legacy spellings say "keep reconnecting", so they invert. + resolved.once = self + .once + .or(self.reconnect.map(|reconnect| !reconnect)) + .or(legacy.reconnect.map(|reconnect| !reconnect)); + resolved.reconnect = None; + // Concatenated, not replaced: each spelling is its own list of versions to + // offer, and dropping one would narrow the offer behind the user's back. + for version in &legacy.version { + if !resolved.version.contains(version) { + resolved.version.push(*version); + } + } + resolved.tls = self.tls.resolved(); + #[cfg(feature = "websocket")] + { + resolved.websocket = self.websocket.resolved(); + } + resolved.legacy = Legacy::default(); + resolved + } + + /// Take the released `[client.quic]` table, if a config file carried one. + pub fn take_quic(&mut self) -> Option { + self.quic.take().inspect(|_| { + tracing::warn!("[client.quic] is deprecated; QUIC tuning is now the shared top-level [quic]"); + }) + } + + /// Build the [`crate::Client`] this config describes. + pub fn init(self, quic: crate::quic::Config) -> crate::Result { + crate::Client::new(self, quic) + } + + /// The local address a dial sends from, resolving the default. + pub fn resolved_bind(&self) -> net::SocketAddr { + self.bind.unwrap_or_else(default_bind) + } + + /// Returns the configured versions, defaulting to all if none specified. + pub fn versions(&self) -> moq_net::Versions { + if self.version.is_empty() { + moq_net::Versions::all() + } else { + moq_net::Versions::from(self.version.clone()) + } + } + + /// The Happy Eyeballs stagger a dial will actually use, resolving the default. + /// + /// Every backend reads it from here so the four dial paths can't drift apart. The + /// [`race`](Self::race) field is the override; this is the value + /// it resolves to, so `Config::default().resolved_race()` is the + /// default itself. + pub fn resolved_race(&self) -> std::time::Duration { + self.race.unwrap_or(DEFAULT_RACE) + } + + /// The deadline one connection attempt will actually get, dial and handshake + /// together, resolving the default from the [`timeout`](Self::timeout) override. + pub fn resolved_timeout(&self) -> std::time::Duration { + self.timeout.unwrap_or(DEFAULT_TIMEOUT) + } +} diff --git a/rs/moq-native/src/connection.rs b/rs/moq-native/src/connection.rs index aa690ac8753..08beda4700a 100644 --- a/rs/moq-native/src/connection.rs +++ b/rs/moq-native/src/connection.rs @@ -31,7 +31,7 @@ fn attempt_timeout(index: usize, total: usize) -> Option { /// Only when reconnecting. `Backoff::timeout` is how long to keep *retrying*, so /// applying it to a one-shot dial would cut short the single attempt there will /// ever be: a handshake slower than the retry window but well inside -/// [`ClientConfig::timeout`](crate::ClientConfig::timeout) would fail for a +/// [`crate::connect::Config::timeout`](crate::connect::Config::timeout) would fail for a /// reason that does not apply. That deadline is the one governing a one-shot /// dial, and it already does. fn retry_budget(reconnect: bool, retry_start: tokio::time::Instant, timeout: Duration) -> Option { @@ -461,7 +461,7 @@ impl ConnectionStatsReader { /// Handle to a connection maintained by a background task. /// /// The task connects, waits for the session to end, then (unless reconnecting is -/// disabled, see [`ClientConfig::reconnect`](crate::ClientConfig::reconnect)) +/// disabled, see [`crate::connect::Config::once`](crate::connect::Config::once)) /// redials with exponential backoff. The read surface mirrors [`moq_net::Session`] /// so a caller can treat it like a session that transparently reconnects: /// [`version`](Self::version), [`send_bandwidth`](Self::send_bandwidth), @@ -1506,13 +1506,15 @@ mod tests { let port = probe.local_addr().expect("local addr").port(); drop(probe); - let mut config = crate::ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("valid address")); - let Ok(server) = config.init() else { continue }; + let Ok(server) = config.init(Default::default()) else { + continue; + }; - let mut config = crate::ClientConfig::default(); - config.tls.disable_verify = Some(true); - let client = config.init().expect("build client"); + let mut config = crate::connect::Config::default(); + config.tls.insecure = Some(true); + let client = config.init(Default::default()).expect("build client"); return (server, url(&format!("tcp://127.0.0.1:{port}/")), client); } diff --git a/rs/moq-native/src/error.rs b/rs/moq-native/src/error.rs index 08d471b675b..18980f99475 100644 --- a/rs/moq-native/src/error.rs +++ b/rs/moq-native/src/error.rs @@ -86,6 +86,10 @@ pub enum Error { #[error("tls.root (mTLS) is not supported by the selected QUIC backend")] MtlsUnsupported, + /// A QUIC-LB nonce length was set without the server id it encodes alongside. + #[error("--listen-quic-lb-nonce needs --listen-quic-lb-id")] + LbNonceWithoutId, + /// The server's WebTransport response carried a status outside the valid HTTP range. #[error("invalid status code")] InvalidStatusCode, diff --git a/rs/moq-native/src/failover.rs b/rs/moq-native/src/failover.rs index 7c6f2c53601..6d0a5447234 100644 --- a/rs/moq-native/src/failover.rs +++ b/rs/moq-native/src/failover.rs @@ -4,7 +4,7 @@ //! silently broken (an unrouted AAAA, a blocked v4 path). Rather than dial one //! address and wait out the handshake timeout, a dial staggers attempts across //! every resolved address, alternating families, and takes the first connection -//! to complete. The stagger is [`crate::ClientConfig::failover_delay`]. +//! to complete. The stagger is [`connect::Config::race`](crate::connect::Config::race). //! //! Nothing here needs calling: every client dial goes through it. The one type //! a consumer sees is [`Failure`], which the backend `Error` types carry when @@ -361,7 +361,7 @@ fn collapse(mut failures: Vec>) -> E { #[cfg(test)] mod tests { use super::*; - use crate::client::DEFAULT_FAILOVER_DELAY; + use crate::connect::DEFAULT_RACE; use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; @@ -435,14 +435,10 @@ mod tests { async fn first_success_returns_immediately() { let dials = Arc::new(AtomicUsize::new(0)); let counter = dials.clone(); - let res: Result<&str, TestError> = race( - vec![v4("1.1.1.1:1"), v4("2.2.2.2:2")], - DEFAULT_FAILOVER_DELAY, - move |_| { - counter.fetch_add(1, Ordering::SeqCst); - async { Ok("winner") } - }, - ) + let res: Result<&str, TestError> = race(vec![v4("1.1.1.1:1"), v4("2.2.2.2:2")], DEFAULT_RACE, move |_| { + counter.fetch_add(1, Ordering::SeqCst); + async { Ok("winner") } + }) .await; assert_eq!(res, Ok("winner")); assert_eq!(dials.load(Ordering::SeqCst), 1, "no second dial after a fast success"); @@ -453,7 +449,7 @@ mod tests { let start = tokio::time::Instant::now(); let res: Result<&str, TestError> = race( vec![v4("1.1.1.1:1"), v4("2.2.2.2:2")], - DEFAULT_FAILOVER_DELAY, + DEFAULT_RACE, |addr| async move { if addr == v4("1.1.1.1:1") { std::future::pending().await @@ -464,11 +460,7 @@ mod tests { ) .await; assert_eq!(res, Ok("second")); - assert_eq!( - start.elapsed(), - DEFAULT_FAILOVER_DELAY, - "second dial waits out the stagger" - ); + assert_eq!(start.elapsed(), DEFAULT_RACE, "second dial waits out the stagger"); } #[tokio::test(start_paused = true)] @@ -476,7 +468,7 @@ mod tests { let start = tokio::time::Instant::now(); let res: Result<&str, TestError> = race( vec![v4("1.1.1.1:1"), v4("2.2.2.2:2")], - DEFAULT_FAILOVER_DELAY, + DEFAULT_RACE, |addr| async move { if addr == v4("1.1.1.1:1") { Err(TestError::Dial("boom")) @@ -549,7 +541,7 @@ mod tests { /// produced (variant, source chain and all) instead of an aggregate of one. #[tokio::test(start_paused = true)] async fn a_lone_failure_is_returned_unwrapped() { - let res: Result<&str, TestError> = race(vec![v4("1.1.1.1:1")], DEFAULT_FAILOVER_DELAY, |_| async { + let res: Result<&str, TestError> = race(vec![v4("1.1.1.1:1")], DEFAULT_RACE, |_| async { Err(TestError::Dial("invalid peer certificate")) }) .await; diff --git a/rs/moq-native/src/iroh.rs b/rs/moq-native/src/iroh.rs index 872eda047dc..b3ed5b1fd6c 100644 --- a/rs/moq-native/src/iroh.rs +++ b/rs/moq-native/src/iroh.rs @@ -161,14 +161,14 @@ pub struct EndpointConfig { } impl EndpointConfig { - /// Bind the iroh endpoint, applying the per-connection [`crate::quic::Client`] knobs. + /// Bind the iroh endpoint, applying the per-connection [`crate::quic::Config`] knobs. /// /// iroh is a single P2P endpoint shared by both roles, so it takes the client /// section (the per-connection knobs are symmetric). It only honors the knobs /// its transport-config builder exposes (stream limits, idle timeout, MTU /// discovery, congestion control); it has no keep-alive knob and cannot disable /// GSO, so `gso = false` fails with [`Error::GsoUnsupported`]. - pub async fn bind(self, quic: &crate::quic::Client) -> Result> { + pub async fn bind(self, quic: &crate::quic::Config) -> Result> { if !self.enabled.unwrap_or(false) { return Ok(None); } @@ -378,7 +378,7 @@ mod tests { /// though every other backend defaults to BBR. #[test] fn congestion_control_defaults_to_loss() { - let mut quic = crate::quic::Client::default(); + let mut quic = crate::quic::Config::default(); assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Loss); // An explicit request still gets through. diff --git a/rs/moq-native/src/lib.rs b/rs/moq-native/src/lib.rs index 4783c73a9f5..4dc0ffefe92 100644 --- a/rs/moq-native/src/lib.rs +++ b/rs/moq-native/src/lib.rs @@ -16,7 +16,7 @@ pub mod accept; pub mod bind; mod client; -mod connect; +pub mod connect; mod connection; mod crypto; mod error; @@ -24,6 +24,7 @@ mod error; pub mod failover; #[cfg(feature = "jemalloc")] pub mod jemalloc; +pub mod listen; mod log; #[cfg(feature = "noq")] pub mod noq; @@ -48,12 +49,12 @@ pub mod websocket; // Enumerated rather than globbed, so the root surface is a deliberate list and a // new `pub` item in these modules doesn't silently join it. -pub use client::{Client, ClientConfig}; +pub use client::Client; pub use connect::{Addrs, ConnectError}; pub use connection::{Backoff, Connection, ConnectionStatsReader, GoawayConfig, Redirect, Status}; pub use error::{Error, Result}; pub use log::Log; -pub use server::{Listener, Request, Server, ServerConfig, Transport}; +pub use server::{Listener, Request, Server, Transport}; /// Spawn the session's protocol driver on the current tokio runtime, handing back /// the session it drives. diff --git a/rs/moq-native/src/listen.rs b/rs/moq-native/src/listen.rs new file mode 100644 index 00000000000..4b57e49ed3b --- /dev/null +++ b/rs/moq-native/src/listen.rs @@ -0,0 +1,376 @@ +//! The accept side of an endpoint: what to listen on and how to be trusted. +//! +//! [`Config`] describes the listeners (QUIC, plus optional `tcp`/`unix` qmux) +//! and the served TLS identity. The dial side lives in [`crate::connect`]. + +use crate::QuicBackend; + +/// The accept side of an endpoint: what to listen on and how to be trusted. +/// +/// Derives [`clap::Args`], so flatten it into a binary's own parser with +/// `#[command(flatten)]`. The dial side is [`crate::connect::Config`]. +#[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)] +#[serde(deny_unknown_fields, default)] +#[group(id = "listen-config")] +#[non_exhaustive] +pub struct Config { + /// Listen for QUIC (UDP) on the given address. Defaults to `[::]:443`. + /// + /// Accepts standard socket address syntax (e.g. `[::]:443`) or a DNS + /// `host:port` pair (e.g. `fly-global-services:443`), resolved at bind time + /// (first address only; Quinn cannot bind multiple). Leave unset while a + /// `tcp`/`unix` listener is configured to run a stream-only server with no + /// QUIC. + #[serde(alias = "listen")] + #[arg(id = "listen", long = "listen", env = "MOQ_LISTEN")] + pub bind: Option, + + /// Plaintext qmux TCP listener (`--listen-tcp-bind`, no TLS). Requires the + /// `tcp` feature. + #[cfg(feature = "tcp")] + #[command(flatten)] + #[serde(default)] + pub tcp: crate::tcp::Config, + + /// Plaintext qmux Unix-socket listener (`--listen-unix-bind`) with an optional + /// peer-credential allowlist. Requires the `uds` feature; unix-only. + #[cfg(all(feature = "uds", unix))] + #[command(flatten)] + #[serde(default)] + pub unix: crate::unix::Config, + + /// The QUIC backend to use. + /// Auto-detected from compiled features if not specified. + #[arg(id = "listen-backend", long = "listen-backend", env = "MOQ_LISTEN_BACKEND")] + pub backend: Option, + + /// Restrict the server to specific MoQ protocol version(s). + /// + /// By default, the server accepts all supported versions. + /// Use this to restrict to specific versions, e.g. `--listen-version moq-lite-02`. + /// Can be specified multiple times to accept a subset of versions. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + #[arg( + id = "listen-version", + long = "listen-version", + env = "MOQ_LISTEN_VERSION", + value_parser = crate::version_parser(), + )] + pub version: Vec, + + /// The certificates to serve and the roots that authenticate mTLS clients + /// (`--listen-tls-*`). + #[command(flatten)] + #[serde(default)] + pub tls: crate::tls::Listen, + + /// IPv4 address advertised as the QUIC preferred_address. + /// + /// Supporting clients (Chrome M131+, native Quinn) migrate to this address + /// shortly after the handshake completes. Typical use: handshake on an + /// anycast IP, steady-state on this host's unicast IP. + /// + /// Honored by the Quinn and noq backends. Accept-only, which is why it lives + /// here rather than in the shared [`crate::quic::Config`]. + #[arg( + id = "listen-preferred-v4", + long = "listen-preferred-v4", + env = "MOQ_LISTEN_PREFERRED_V4" + )] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preferred_v4: Option, + + /// IPv6 address advertised as the QUIC preferred_address. See [`Self::preferred_v4`]. + #[arg( + id = "listen-preferred-v6", + long = "listen-preferred-v6", + env = "MOQ_LISTEN_PREFERRED_V6" + )] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub preferred_v6: Option, + + /// Server ID to embed in connection IDs for QUIC-LB compatibility. + /// If set, connection IDs will be derived semi-deterministically. + #[arg(id = "listen-quic-lb-id", long = "listen-quic-lb-id", env = "MOQ_LISTEN_QUIC_LB_ID")] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lb_id: Option, + + /// Number of random nonce bytes in QUIC-LB connection IDs. + /// Must be at least 4, and server_id + nonce + 1 must not exceed 20. + #[arg( + id = "listen-quic-lb-nonce", + long = "listen-quic-lb-nonce", + env = "MOQ_LISTEN_QUIC_LB_NONCE" + )] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub lb_nonce: Option, + + /// The released `--server-*` spellings and their env vars, kept parsing but + /// hidden. Folded into the canonical fields by [`Config::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, + + /// The released `[server.quic]` table, which is now the shared top-level + /// `[quic]`. Parse-only: a caller folds it in (moq-relay's `Config::resolve` + /// does), since this side no longer owns transport tuning. + /// + /// Kept as a field rather than dropped because `deny_unknown_fields` would + /// otherwise refuse a released config file outright, at startup, with nothing + /// running. + #[arg(skip)] + #[serde(default, skip_serializing_if = "Option::is_none")] + pub quic: Option, +} + +/// The `--server-*` flags from before the accept side was named `listen`. +/// +/// They carry their original env vars, which is why these are separate args rather +/// than clap aliases: an alias renames the flag but not the variable, and a relay +/// deployed through the environment is the common case. +#[derive(Clone, Debug, Default, clap::Args)] +#[group(id = "listen-legacy")] +pub(crate) struct Legacy { + #[arg(id = "server-bind", long = "server-bind", env = "MOQ_SERVER_BIND", hide = true)] + bind: Option, + + #[arg( + id = "server-backend", + long = "server-backend", + env = "MOQ_SERVER_BACKEND", + hide = true + )] + backend: Option, + + #[arg( + id = "server-version", + long = "server-version", + env = "MOQ_SERVER_VERSION", + value_parser = crate::version_parser(), + hide = true, + )] + version: Vec, + + #[arg( + id = "server-preferred-v4", + long = "server-preferred-v4", + env = "MOQ_SERVER_PREFERRED_V4", + hide = true + )] + preferred_v4: Option, + + #[arg( + id = "server-preferred-v6", + long = "server-preferred-v6", + env = "MOQ_SERVER_PREFERRED_V6", + hide = true + )] + preferred_v6: Option, + + #[arg( + id = "server-quic-lb-id", + long = "server-quic-lb-id", + env = "MOQ_SERVER_QUIC_LB_ID", + hide = true + )] + lb_id: Option, + + #[arg( + id = "server-quic-lb-nonce", + long = "server-quic-lb-nonce", + env = "MOQ_SERVER_QUIC_LB_NONCE", + hide = true + )] + lb_nonce: Option, +} + +impl Legacy { + /// The legacy flags in use, each paired with its replacement, for one warning. + fn used(&self) -> Vec<&'static str> { + let mut used = Vec::new(); + if self.bind.is_some() { + used.push("--server-bind -> --listen"); + } + if self.backend.is_some() { + used.push("--server-backend -> --listen-backend"); + } + if !self.version.is_empty() { + used.push("--server-version -> --listen-version"); + } + if self.preferred_v4.is_some() { + used.push("--server-preferred-v4 -> --listen-preferred-v4"); + } + if self.preferred_v6.is_some() { + used.push("--server-preferred-v6 -> --listen-preferred-v6"); + } + if self.lb_id.is_some() { + used.push("--server-quic-lb-id -> --listen-quic-lb-id"); + } + if self.lb_nonce.is_some() { + used.push("--server-quic-lb-nonce -> --listen-quic-lb-nonce"); + } + used + } +} + +impl Config { + /// Fold every released `--server-*` spelling into the canonical fields. + /// + /// The canonical spelling wins. Warns once when a legacy spelling contributed. + /// Idempotent, and applied automatically by [`init`](Self::init), so calling it + /// yourself is only needed to inspect the folded values. + pub fn resolved(&self) -> Self { + let used = self.legacy.used(); + if !used.is_empty() { + tracing::warn!( + "deprecated --server-* flags in use; the accept side is now --listen-*: {}", + used.join(", ") + ); + } + let legacy = &self.legacy; + + let mut resolved = self.clone(); + resolved.bind = self.bind.clone().or(legacy.bind.clone()); + resolved.backend = self.backend.clone().or(legacy.backend.clone()); + // Concatenated, not replaced: each spelling is its own list of versions to + // accept, and dropping one would narrow what the listener takes. + for version in &legacy.version { + if !resolved.version.contains(version) { + resolved.version.push(*version); + } + } + resolved.preferred_v4 = self.preferred_v4.or(legacy.preferred_v4); + resolved.preferred_v6 = self.preferred_v6.or(legacy.preferred_v6); + resolved.lb_id = self.lb_id.clone().or(legacy.lb_id.clone()); + resolved.lb_nonce = self.lb_nonce.or(legacy.lb_nonce); + resolved.tls = self.tls.resolved(); + #[cfg(feature = "tcp")] + { + resolved.tcp = self.tcp.resolved(); + } + #[cfg(all(feature = "uds", unix))] + { + resolved.unix = self.unix.resolved(); + } + resolved.legacy = Legacy::default(); + resolved + } + + /// Take the released `[server.quic]` table, if a config file carried one. + pub fn take_quic(&mut self) -> Option { + self.quic.take().inspect(|_| { + tracing::warn!("[server.quic] is deprecated; QUIC tuning is now the shared top-level [quic]"); + }) + } + + /// Reject a QUIC-LB nonce with no server id to pair it with. + /// + /// Checked here rather than with clap's `requires`, which can only name one arg + /// id: the two knobs each have a released spelling of their own, so any mix of + /// the four has to be judged after the fold. + pub(crate) fn validate(&self) -> crate::Result<()> { + let resolved = self.resolved(); + match (resolved.lb_id.is_some(), resolved.lb_nonce.is_some()) { + (false, true) => Err(crate::Error::LbNonceWithoutId), + _ => Ok(()), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + /// A parser wrapping the config, since it derives `Args` (see the note in + /// [`crate::connect`]). + #[derive(Parser)] + struct Cli { + #[command(flatten)] + config: Config, + } + + fn config_from(args: I) -> Config + where + I: IntoIterator, + T: Into + Clone, + { + Cli::parse_from(args).config + } + + /// Every released `--server-*` spelling keeps parsing, so an existing + /// deployment's command line still boots. + #[test] + fn released_server_spellings_still_parse() { + let config = config_from([ + "test", + "--server-bind", + "[::]:4443", + "--server-version", + "moq-lite-03", + "--server-preferred-v4", + "192.0.2.1:443", + "--server-quic-lb-id", + "ab", + "--server-tls-cert", + "/tmp/cert.pem", + "--server-tls-root", + "/tmp/ca.pem", + ]) + .resolved(); + assert_eq!(config.bind.as_deref(), Some("[::]:4443")); + assert_eq!(config.version, vec!["moq-lite-03".parse::().unwrap()]); + assert_eq!(config.preferred_v4, Some("192.0.2.1:443".parse().unwrap())); + assert!(config.lb_id.is_some()); + assert_eq!(config.tls.cert, vec![std::path::PathBuf::from("/tmp/cert.pem")]); + assert_eq!(config.tls.root, vec![std::path::PathBuf::from("/tmp/ca.pem")]); + } + + /// The canonical spelling wins, and folding twice changes nothing. + #[test] + fn canonical_wins_over_legacy() { + let config = config_from(["test", "--listen", "[::]:443", "--server-bind", "[::]:4443"]); + let once = config.resolved(); + assert_eq!(once.bind.as_deref(), Some("[::]:443")); + assert_eq!(once.resolved().bind.as_deref(), Some("[::]:443")); + } + + /// Both spellings name their own files, so neither list may be dropped. + #[test] + fn tls_lists_concatenate_across_spellings() { + let config = config_from([ + "test", + "--listen-tls-root", + "/tmp/new.pem", + "--server-tls-root", + "/tmp/old.pem", + ]) + .resolved(); + assert_eq!( + config.tls.root, + vec![ + std::path::PathBuf::from("/tmp/new.pem"), + std::path::PathBuf::from("/tmp/old.pem") + ] + ); + } + + /// A nonce with no server id is meaningless, whichever spelling each came from. + #[test] + fn lb_nonce_needs_an_id() { + let config = config_from(["test", "--listen-quic-lb-nonce", "8"]); + assert!(matches!(config.validate(), Err(crate::Error::LbNonceWithoutId))); + + // Mixed spellings still pair up, which is what clap `requires` could not do. + let config = config_from(["test", "--server-quic-lb-id", "ab", "--listen-quic-lb-nonce", "8"]); + assert!(config.validate().is_ok()); + } + + /// The canonical spellings, which is what `--help` teaches. + #[test] + fn canonical_spellings_parse() { + let config = config_from(["test", "--listen", "[::]:443", "--listen-version", "moq-lite-03"]); + assert_eq!(config.bind.as_deref(), Some("[::]:443")); + assert_eq!(config.version, vec!["moq-lite-03".parse::().unwrap()]); + } +} diff --git a/rs/moq-native/src/noq.rs b/rs/moq-native/src/noq.rs index f5f5795b682..e6bc0d7a7c2 100644 --- a/rs/moq-native/src/noq.rs +++ b/rs/moq-native/src/noq.rs @@ -1,10 +1,10 @@ //! The noq QUIC backend, used for both WebTransport (`https://`) and raw QUIC (`moqt://`, `moql://`). -use crate::client::ClientConfig; +use crate::connect; +use crate::listen; use crate::quic::CongestionControl; use crate::quic::Resolved; use crate::quic::ServerId; -use crate::server::ServerConfig; use crate::tls::{FingerprintVerifier, ServeCerts}; use std::net; use std::sync::Arc; @@ -232,7 +232,7 @@ type Result = std::result::Result; pub(crate) struct NoqClient { pub quic: noq::Endpoint, pub transport: Arc, - /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]). + /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Connect::allows_http_bootstrap]). pub http_bootstrap: bool, /// Optional TLS SNI / verification hostname override (from config). pub host_name: Option, @@ -245,12 +245,12 @@ pub(crate) struct NoqClient { } impl NoqClient { - pub fn new(config: &ClientConfig) -> Result { - let socket = crate::bind::udp(config.bind).map_err(Error::BindSocket)?; + pub fn new(config: &connect::Config, quic: &crate::quic::Config) -> Result { + let socket = crate::bind::udp(config.resolved_bind()).map_err(Error::BindSocket)?; let dual_stack = crate::bind::udp_is_dual_stack(&socket); let mut transport = noq::TransportConfig::default(); - let quic = config.quic.resolve(); + let quic = quic.resolve(); apply_transport(&mut transport, &quic); apply_qlog(&mut transport, &quic, "client")?; let transport = Arc::new(transport); @@ -267,7 +267,7 @@ impl NoqClient { transport, http_bootstrap: config.tls.allows_http_bootstrap(), host_name: config.tls.host_name.clone(), - failover_delay: config.resolved_failover_delay(), + failover_delay: config.resolved_race(), dual_stack, }) } @@ -464,9 +464,9 @@ pub(crate) struct NoqServer { } impl NoqServer { - pub fn new(config: ServerConfig) -> Result { + pub fn new(config: listen::Config, quic: &crate::quic::Config) -> Result { let mut transport = noq::TransportConfig::default(); - let quic = config.quic.resolve(); + let quic = quic.resolve(); apply_transport(&mut transport, &quic); apply_qlog(&mut transport, &quic, "server")?; let transport = Arc::new(transport); @@ -512,10 +512,10 @@ impl NoqServer { // Advertise the preferred_address transport parameter (RFC 9000 §9.6). // noq allocates a fresh CID + reset token for the address during the handshake. - if let Some(addr) = config.quic.preferred_v4 { + if let Some(addr) = config.preferred_v4 { tls.preferred_address_v4(Some(addr)); } - if let Some(addr) = config.quic.preferred_v6 { + if let Some(addr) = config.preferred_v6 { tls.preferred_address_v6(Some(addr)); } @@ -527,8 +527,8 @@ impl NoqServer { // Configure connection ID generator with server ID if provided let mut endpoint_config = noq::EndpointConfig::default(); - if let Some(server_id) = config.quic.quic_lb_id { - let nonce_len = config.quic.quic_lb_nonce.unwrap_or(8); + if let Some(server_id) = config.lb_id { + let nonce_len = config.lb_nonce.unwrap_or(8); if nonce_len < 4 { return Err(Error::QuicLbNonceTooSmall); } @@ -703,7 +703,7 @@ mod tests { /// though every other backend defaults to BBR. #[test] fn congestion_control_defaults_to_loss() { - let mut quic = crate::quic::Client::default(); + let mut quic = crate::quic::Config::default(); assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Loss); // An explicit request still gets through. diff --git a/rs/moq-native/src/quic.rs b/rs/moq-native/src/quic.rs index 3e09fb3f174..ede123bf38c 100644 --- a/rs/moq-native/src/quic.rs +++ b/rs/moq-native/src/quic.rs @@ -1,15 +1,14 @@ -//! QUIC transport tuning, split by role. +//! QUIC transport tuning. //! -//! [`Client`] (`--client-quic-*`) and [`Server`] (`--server-quic-*`) carry the -//! per-connection knobs (stream limits, GSO, timeouts) that each backend applies. -//! [`Server`] additionally owns the knobs that only make sense when accepting -//! connections: the QUIC preferred address and the QUIC-LB connection-ID encoding. +//! One [`Config`] (`--quic-*`) carries the per-connection knobs (stream limits, +//! GSO, timeouts) that each backend applies. They mean the same thing whichever +//! way a connection was opened, so it is spelled once and shared by +//! [`crate::connect`] and [`crate::listen`] rather than owned by either. //! -//! Each is flattened directly onto [`crate::ClientConfig`] / [`crate::ServerConfig`], -//! so the args parse straight into the config the endpoint is built from. Not -//! every backend honors every knob, see the field docs. +//! The knobs that only apply when accepting (the QUIC preferred address and the +//! QUIC-LB connection-ID encoding) live on [`crate::listen::Config`] instead. +//! Not every backend honors every knob, see the field docs. -use std::net; use std::path::PathBuf; use std::time::Duration; @@ -18,7 +17,7 @@ use std::time::Duration; /// Parsed from, and serialized as, a hex string. Its length must match the load /// balancer's configured server-ID length. #[serde_with::serde_as] -#[derive(Clone, serde::Serialize, serde::Deserialize)] +#[derive(Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ServerId(#[serde_as(as = "serde_with::hex::Hex")] pub(crate) Vec); impl ServerId { @@ -78,20 +77,16 @@ pub(crate) const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(30); /// Default keep-alive ping interval. pub(crate) const DEFAULT_KEEP_ALIVE: Duration = Duration::from_secs(5); -/// The `--client-quic-*` transport section. +/// The `--quic-*` transport section, applied to dialed and accepted connections alike. #[derive(Clone, Debug, Default, clap::Args, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields, default)] +#[group(id = "quic")] #[non_exhaustive] -pub struct Client { +pub struct Config { /// Maximum number of concurrent QUIC streams per connection (both bidi and uni). /// Defaults to 1024. MoQ opens a stream per group, so busy endpoints want this high. #[serde(skip_serializing_if = "Option::is_none")] - #[arg( - id = "client-quic-max-streams", - long = "client-quic-max-streams", - alias = "client-max-streams", - env = "MOQ_CLIENT_QUIC_MAX_STREAMS" - )] + #[arg(id = "quic-max-streams", long = "quic-max-streams", env = "MOQ_QUIC_MAX_STREAMS")] pub max_streams: Option, /// Enable UDP generic segmentation offload (GSO). @@ -101,9 +96,9 @@ pub struct Client { /// cannot turn it off and rejects an explicit `false`. #[serde(skip_serializing_if = "Option::is_none")] #[arg( - id = "client-quic-gso", - long = "client-quic-gso", - env = "MOQ_CLIENT_QUIC_GSO", + id = "quic-gso", + long = "quic-gso", + env = "MOQ_QUIC_GSO", default_missing_value = "true", num_args = 0..=1, require_equals = true, @@ -114,9 +109,9 @@ pub struct Client { /// Idle timeout before an inactive connection is dropped. Defaults to 30s. #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] #[arg( - id = "client-quic-idle-timeout", - long = "client-quic-idle-timeout", - env = "MOQ_CLIENT_QUIC_IDLE_TIMEOUT", + id = "quic-idle-timeout", + long = "quic-idle-timeout", + env = "MOQ_QUIC_IDLE_TIMEOUT", value_parser = humantime::parse_duration, )] pub idle_timeout: Option, @@ -125,9 +120,9 @@ pub struct Client { /// Ignored by the iroh backend, which has no keep-alive knob. #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] #[arg( - id = "client-quic-keep-alive", - long = "client-quic-keep-alive", - env = "MOQ_CLIENT_QUIC_KEEP_ALIVE", + id = "quic-keep-alive", + long = "quic-keep-alive", + env = "MOQ_QUIC_KEEP_ALIVE", value_parser = humantime::parse_duration, )] pub keep_alive: Option, @@ -135,9 +130,9 @@ pub struct Client { /// Enable path MTU discovery. Defaults to off. #[serde(skip_serializing_if = "Option::is_none")] #[arg( - id = "client-quic-mtu-discovery", - long = "client-quic-mtu-discovery", - env = "MOQ_CLIENT_QUIC_MTU_DISCOVERY", + id = "quic-mtu-discovery", + long = "quic-mtu-discovery", + env = "MOQ_QUIC_MTU_DISCOVERY", default_missing_value = "true", num_args = 0..=1, require_equals = true, @@ -150,95 +145,67 @@ pub struct Client { /// the process with it. Selecting `delay` there is for deliberate testing only. #[serde(skip_serializing_if = "Option::is_none")] #[arg( - id = "client-quic-congestion-control", - long = "client-quic-congestion-control", - env = "MOQ_CLIENT_QUIC_CONGESTION_CONTROL", + id = "quic-congestion-control", + long = "quic-congestion-control", + env = "MOQ_QUIC_CONGESTION_CONTROL", value_enum )] pub congestion_control: Option, - /// Write qlog traces into this directory. See [`Server::qlog`]. + /// Write qlog traces into this directory, which must already exist. + /// + /// The layout is backend-specific: quiche and noq write one file per connection, + /// while quinn writes one file per endpoint and tags each event with the qlog + /// `group_id` of the connection it belongs to. + /// + /// Requires the `qlog` feature; setting it errors at init otherwise. #[serde(default, skip_serializing_if = "Option::is_none")] - #[arg(id = "client-quic-qlog", long = "client-quic-qlog", env = "MOQ_CLIENT_QUIC_QLOG")] + #[arg(id = "quic-qlog", long = "quic-qlog", env = "MOQ_QUIC_QLOG")] pub qlog: Option, -} -/// Reject a qlog directory that this build can't honor. -/// -/// Erroring beats silently ignoring the flag: the operator asked for traces and would -/// otherwise go looking for files that were never going to appear. Checked once when -/// the client/server is built, so the backends can assume the directory is usable. -fn validate_qlog(qlog: Option<&PathBuf>) -> crate::Result<()> { - match qlog { - Some(_) if cfg!(not(feature = "qlog")) => Err(crate::Error::QlogUnsupported), - _ => Ok(()), - } -} - -/// QUIC carries `max_idle_timeout` as a varint of milliseconds, so anything past this -/// can't go on the wire. -const MAX_IDLE_TIMEOUT: Duration = Duration::from_millis((1 << 62) - 1); - -/// Reject an idle timeout no QUIC connection can express. -/// -/// Checked here rather than in each backend because the conversion the backends do is -/// infallible-by-panic, and this config reaches them from a TOML file or a C caller. -fn validate_idle_timeout(idle_timeout: Option) -> crate::Result<()> { - match idle_timeout { - Some(timeout) if timeout > MAX_IDLE_TIMEOUT => Err(crate::Error::IdleTimeoutRange), - _ => Ok(()), - } -} - -impl Client { - /// Reject knobs this build can't honor. Called when the client is built. - pub(crate) fn validate(&self) -> crate::Result<()> { - validate_qlog(self.qlog.as_ref())?; - validate_idle_timeout(self.idle_timeout) - } - - /// The per-connection knobs with defaults applied, ready to hand to a backend. - pub fn resolve(&self) -> Resolved { - Resolved::new( - self.max_streams, - self.gso, - self.idle_timeout, - self.keep_alive, - self.mtu_discovery, - self.congestion_control, - self.qlog.clone(), - ) - } + /// The old role-prefixed spellings, kept parsing but hidden. Folded into the + /// canonical fields by [`Config::resolved`]. Not a TOML surface (config files + /// use the canonical names). + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, } -/// Every knob at its default, which is what an untouched [`Client`] resolves to. -impl Default for Resolved { - fn default() -> Self { - Client::default().resolve() - } -} +/// The hidden `--client-quic-*` / `--server-quic-*` spellings (and their env +/// vars), from when the endpoint config was split by role. +#[derive(Clone, Debug, Default, clap::Args)] +#[group(id = "quic-legacy")] +pub(crate) struct Legacy { + #[arg( + id = "client-quic-max-streams", + long = "client-quic-max-streams", + alias = "client-max-streams", + env = "MOQ_CLIENT_QUIC_MAX_STREAMS", + hide = true + )] + client_max_streams: Option, -/// The `--server-quic-*` transport section. -/// -/// Carries the same per-connection knobs as [`Client`] plus the accept-side knobs -/// (preferred address, QUIC-LB connection IDs). -#[derive(Clone, Debug, Default, clap::Args, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields, default)] -#[non_exhaustive] -pub struct Server { - /// Maximum number of concurrent QUIC streams per connection (both bidi and uni). - /// Defaults to 1024. MoQ opens a stream per group, so busy endpoints want this high. - #[serde(skip_serializing_if = "Option::is_none")] #[arg( id = "server-quic-max-streams", long = "server-quic-max-streams", alias = "server-max-streams", - env = "MOQ_SERVER_QUIC_MAX_STREAMS" + env = "MOQ_SERVER_QUIC_MAX_STREAMS", + hide = true )] - pub max_streams: Option, + server_max_streams: Option, + + #[arg( + id = "client-quic-gso", + long = "client-quic-gso", + env = "MOQ_CLIENT_QUIC_GSO", + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + hide = true, + )] + client_gso: Option, - /// Enable UDP generic segmentation offload (GSO). See [`Client::gso`]. - #[serde(skip_serializing_if = "Option::is_none")] #[arg( id = "server-quic-gso", long = "server-quic-gso", @@ -247,31 +214,58 @@ pub struct Server { num_args = 0..=1, require_equals = true, value_parser = clap::value_parser!(bool), + hide = true, )] - pub gso: Option, + server_gso: Option, + + #[arg( + id = "client-quic-idle-timeout", + long = "client-quic-idle-timeout", + env = "MOQ_CLIENT_QUIC_IDLE_TIMEOUT", + value_parser = humantime::parse_duration, + hide = true, + )] + client_idle_timeout: Option, - /// Idle timeout before an inactive connection is dropped. Defaults to 30s. - #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] #[arg( id = "server-quic-idle-timeout", long = "server-quic-idle-timeout", env = "MOQ_SERVER_QUIC_IDLE_TIMEOUT", value_parser = humantime::parse_duration, + hide = true, )] - pub idle_timeout: Option, + server_idle_timeout: Option, + + #[arg( + id = "client-quic-keep-alive", + long = "client-quic-keep-alive", + env = "MOQ_CLIENT_QUIC_KEEP_ALIVE", + value_parser = humantime::parse_duration, + hide = true, + )] + client_keep_alive: Option, - /// Keep-alive ping interval. Defaults to 5s; set `0s` to disable. - #[serde(default, skip_serializing_if = "Option::is_none", with = "humantime_serde::option")] #[arg( id = "server-quic-keep-alive", long = "server-quic-keep-alive", env = "MOQ_SERVER_QUIC_KEEP_ALIVE", value_parser = humantime::parse_duration, + hide = true, )] - pub keep_alive: Option, + server_keep_alive: Option, + + #[arg( + id = "client-quic-mtu-discovery", + long = "client-quic-mtu-discovery", + env = "MOQ_CLIENT_QUIC_MTU_DISCOVERY", + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + hide = true, + )] + client_mtu_discovery: Option, - /// Enable path MTU discovery. Defaults to off. - #[serde(skip_serializing_if = "Option::is_none")] #[arg( id = "server-quic-mtu-discovery", long = "server-quic-mtu-discovery", @@ -280,105 +274,205 @@ pub struct Server { num_args = 0..=1, require_equals = true, value_parser = clap::value_parser!(bool), + hide = true, )] - pub mtu_discovery: Option, + server_mtu_discovery: Option, + + #[arg( + id = "client-quic-congestion-control", + long = "client-quic-congestion-control", + env = "MOQ_CLIENT_QUIC_CONGESTION_CONTROL", + value_enum, + hide = true + )] + client_congestion_control: Option, - /// Congestion control family. Defaults to `delay` on quinn and quiche, and to - /// `loss` on noq, whose BBRv3 can panic on packet loss and take the process with - /// it. Selecting `delay` there is for deliberate testing only. - #[serde(skip_serializing_if = "Option::is_none")] #[arg( id = "server-quic-congestion-control", long = "server-quic-congestion-control", env = "MOQ_SERVER_QUIC_CONGESTION_CONTROL", - value_enum + value_enum, + hide = true )] - pub congestion_control: Option, + server_congestion_control: Option, - /// IPv4 address advertised as the QUIC preferred_address. - /// - /// Supporting clients (Chrome M131+, native Quinn) migrate to this address - /// shortly after the handshake completes. Typical use: handshake on an - /// anycast IP, steady-state on this host's unicast IP. - /// - /// Honored by the Quinn and noq backends. #[arg( - id = "server-preferred-v4", - long = "server-preferred-v4", - env = "MOQ_SERVER_PREFERRED_V4" + id = "client-quic-qlog", + long = "client-quic-qlog", + env = "MOQ_CLIENT_QUIC_QLOG", + hide = true )] - #[serde(default, skip_serializing_if = "Option::is_none")] - pub preferred_v4: Option, + client_qlog: Option, - /// IPv6 address advertised as the QUIC preferred_address. See [`Self::preferred_v4`]. #[arg( - id = "server-preferred-v6", - long = "server-preferred-v6", - env = "MOQ_SERVER_PREFERRED_V6" + id = "server-quic-qlog", + long = "server-quic-qlog", + env = "MOQ_SERVER_QUIC_QLOG", + hide = true )] - #[serde(default, skip_serializing_if = "Option::is_none")] - pub preferred_v6: Option, - - /// Server ID to embed in connection IDs for QUIC-LB compatibility. - /// If set, connection IDs will be derived semi-deterministically. - #[arg(id = "server-quic-lb-id", long = "server-quic-lb-id", env = "MOQ_SERVER_QUIC_LB_ID")] - #[serde(default, skip_serializing_if = "Option::is_none")] - pub quic_lb_id: Option, + server_qlog: Option, +} - /// Number of random nonce bytes in QUIC-LB connection IDs. - /// Must be at least 4, and server_id + nonce + 1 must not exceed 20. - #[arg( - id = "server-quic-lb-nonce", - long = "server-quic-lb-nonce", - requires = "server-quic-lb-id", - env = "MOQ_SERVER_QUIC_LB_NONCE" - )] - #[serde(default, skip_serializing_if = "Option::is_none")] - pub quic_lb_nonce: Option, +impl Legacy { + /// The legacy flags in use, by canonical replacement, for one deprecation warning. + fn used(&self) -> Vec<&'static str> { + let mut used = Vec::new(); + if self.client_max_streams.is_some() || self.server_max_streams.is_some() { + used.push("--quic-max-streams"); + } + if self.client_gso.is_some() || self.server_gso.is_some() { + used.push("--quic-gso"); + } + if self.client_idle_timeout.is_some() || self.server_idle_timeout.is_some() { + used.push("--quic-idle-timeout"); + } + if self.client_keep_alive.is_some() || self.server_keep_alive.is_some() { + used.push("--quic-keep-alive"); + } + if self.client_mtu_discovery.is_some() || self.server_mtu_discovery.is_some() { + used.push("--quic-mtu-discovery"); + } + if self.client_congestion_control.is_some() || self.server_congestion_control.is_some() { + used.push("--quic-congestion-control"); + } + if self.client_qlog.is_some() || self.server_qlog.is_some() { + used.push("--quic-qlog"); + } + used + } +} - /// Write qlog traces into this directory, which must already exist. +impl Config { + /// Fold the legacy role-prefixed spellings into the canonical fields. /// - /// The layout is backend-specific: quiche and noq write one file per connection, - /// while quinn writes one file per endpoint and tags each event with the qlog - /// `group_id` of the connection it belongs to. - /// - /// Requires the `qlog` feature; setting it errors at init otherwise. - #[serde(default, skip_serializing_if = "Option::is_none")] - #[arg(id = "server-quic-qlog", long = "server-quic-qlog", env = "MOQ_SERVER_QUIC_QLOG")] - pub qlog: Option, -} + /// The canonical spelling wins; between the legacy pair, the client spelling + /// wins (the roles now share one value, so a config that set both to + /// different values was relying on a distinction that no longer exists). + /// Warns once when any legacy spelling contributed. Idempotent. + pub fn resolved(&self) -> Self { + let used = self.legacy.used(); + if !used.is_empty() { + // Name the consequence, not just the rename: these knobs used to apply to + // one direction, so a value that only ever bounded outbound connections + // now bounds accepted ones too. + tracing::warn!( + "deprecated --client-quic-*/--server-quic-* flags in use; QUIC tuning is now one shared section applied to dialed and accepted connections alike, so these values now apply to both directions: {}", + used.join(", ") + ); + } + let legacy = &self.legacy; + Self { + max_streams: self + .max_streams + .or(legacy.client_max_streams) + .or(legacy.server_max_streams), + gso: self.gso.or(legacy.client_gso).or(legacy.server_gso), + idle_timeout: self + .idle_timeout + .or(legacy.client_idle_timeout) + .or(legacy.server_idle_timeout), + keep_alive: self + .keep_alive + .or(legacy.client_keep_alive) + .or(legacy.server_keep_alive), + mtu_discovery: self + .mtu_discovery + .or(legacy.client_mtu_discovery) + .or(legacy.server_mtu_discovery), + congestion_control: self + .congestion_control + .or(legacy.client_congestion_control) + .or(legacy.server_congestion_control), + qlog: self + .qlog + .clone() + .or(legacy.client_qlog.clone()) + .or(legacy.server_qlog.clone()), + legacy: Legacy::default(), + } + } -impl Server { - /// Reject knobs this build can't honor. Called when the server is built. + /// Reject knobs this build can't honor. Called when the endpoint is built. pub(crate) fn validate(&self) -> crate::Result<()> { - validate_qlog(self.qlog.as_ref())?; + // Erroring beats silently ignoring the flag: the operator asked for traces and + // would otherwise go looking for files that were never going to appear. + match self.qlog.as_ref() { + Some(_) if cfg!(not(feature = "qlog")) => Err(crate::Error::QlogUnsupported), + _ => Ok(()), + }?; validate_idle_timeout(self.idle_timeout) } + /// Fill every unset knob from `fallback`, keeping the ones this config sets. + /// + /// For merging a lower-precedence source, such as the released per-role + /// `[client.quic]` / `[server.quic]` tables into the shared section. + pub fn or(&self, fallback: &Self) -> Self { + Self { + max_streams: self.max_streams.or(fallback.max_streams), + gso: self.gso.or(fallback.gso), + idle_timeout: self.idle_timeout.or(fallback.idle_timeout), + keep_alive: self.keep_alive.or(fallback.keep_alive), + mtu_discovery: self.mtu_discovery.or(fallback.mtu_discovery), + congestion_control: self.congestion_control.or(fallback.congestion_control), + qlog: self.qlog.clone().or_else(|| fallback.qlog.clone()), + legacy: self.legacy.clone(), + } + } + /// The per-connection knobs with defaults applied, ready to hand to a backend. - #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] - pub(crate) fn resolve(&self) -> Resolved { - Resolved::new( - self.max_streams, - self.gso, - self.idle_timeout, - self.keep_alive, - self.mtu_discovery, - self.congestion_control, - self.qlog.clone(), - ) + pub fn resolve(&self) -> Resolved { + // A zero keep-alive means "disabled"; anything else (including unset) keeps + // the connection warm, defaulting to 5s. + let keep_alive = match self.keep_alive { + Some(d) if d.is_zero() => None, + Some(d) => Some(d), + None => Some(DEFAULT_KEEP_ALIVE), + }; + + Resolved { + max_streams: self.max_streams.unwrap_or(DEFAULT_MAX_STREAMS), + gso: self.gso, + idle_timeout: self.idle_timeout.unwrap_or(DEFAULT_IDLE_TIMEOUT), + keep_alive, + mtu_discovery: self.mtu_discovery.unwrap_or(false), + congestion_control: self.congestion_control, + qlog: self.qlog.clone(), + } + } +} + +/// QUIC carries `max_idle_timeout` as a varint of milliseconds, so anything past this +/// can't go on the wire. +const MAX_IDLE_TIMEOUT: Duration = Duration::from_millis((1 << 62) - 1); + +/// Reject an idle timeout no QUIC connection can express. +/// +/// Checked here rather than in each backend because the conversion the backends do is +/// infallible-by-panic, and this config reaches them from a TOML file or a C caller. +fn validate_idle_timeout(idle_timeout: Option) -> crate::Result<()> { + match idle_timeout { + Some(timeout) if timeout > MAX_IDLE_TIMEOUT => Err(crate::Error::IdleTimeoutRange), + _ => Ok(()), + } +} + +/// Every knob at its default, which is what an untouched [`Config`] resolves to. +impl Default for Resolved { + fn default() -> Self { + Config::default().resolve() } } /// A resolved view of the per-connection knobs (defaults filled in), shared by -/// [`Client`] and [`Server`] so backends apply them the same way regardless of role. +/// the dial and accept paths so backends apply them the same way regardless of role. /// -/// The backends consume it, and [`Client::resolve`] produces it. [`Resolved::default`] +/// The backends consume it, and [`Config::resolve`] produces it. [`Resolved::default`] /// is therefore the canonical statement of what every QUIC knob defaults to, which is /// what a UI should show rather than repeating the numbers. /// -/// Non-exhaustive because it gains a field for every knob [`Client`] gains, so build it -/// from [`Client::resolve`] or [`Resolved::default`] rather than a struct literal. +/// Non-exhaustive because it gains a field for every knob [`Config`] gains, so build it +/// from [`Config::resolve`] or [`Resolved::default`] rather than a struct literal. #[derive(Clone, Debug)] #[non_exhaustive] pub struct Resolved { @@ -400,38 +494,10 @@ pub struct Resolved { } impl Resolved { - fn new( - max_streams: Option, - gso: Option, - idle_timeout: Option, - keep_alive: Option, - mtu_discovery: Option, - congestion_control: Option, - qlog: Option, - ) -> Self { - // A zero keep-alive means "disabled"; anything else (including unset) keeps - // the connection warm, defaulting to 5s. - let keep_alive = match keep_alive { - Some(d) if d.is_zero() => None, - Some(d) => Some(d), - None => Some(DEFAULT_KEEP_ALIVE), - }; - - Self { - max_streams: max_streams.unwrap_or(DEFAULT_MAX_STREAMS), - gso, - idle_timeout: idle_timeout.unwrap_or(DEFAULT_IDLE_TIMEOUT), - keep_alive, - mtu_discovery: mtu_discovery.unwrap_or(false), - congestion_control, - qlog, - } - } - /// The directory to write qlog traces into, if any. /// - /// Only meaningful once [`Client::validate`] / [`Server::validate`] has passed; a - /// build without the `qlog` feature never gets here with a directory set. + /// Only meaningful once [`Config::validate`] has passed; a build without the + /// `qlog` feature never gets here with a directory set. #[cfg_attr(not(any(feature = "quinn", feature = "noq", feature = "quiche")), allow(dead_code))] pub(crate) fn qlog_dir(&self) -> Option<&std::path::Path> { self.qlog.as_deref() @@ -452,25 +518,23 @@ mod tests { use super::*; use clap::Parser; - /// Minimal parsers so we can exercise the `--client-quic-*` / `--server-quic-*` - /// args in isolation (and together, the way relay/cli flatten both). + /// A minimal parser so we can exercise the `--quic-*` args (and the legacy + /// role-prefixed spellings) in isolation. #[derive(Parser)] - struct Both { - #[command(flatten)] - client: Client, + struct Cli { #[command(flatten)] - server: Server, + quic: Config, } - fn parse(args: &[&str]) -> Both { + fn parse(args: &[&str]) -> Config { let mut full = vec!["test"]; full.extend_from_slice(args); - Both::parse_from(full) + Cli::parse_from(full).quic } #[test] fn defaults_apply_when_unset() { - let quic = Client::default().resolve(); + let quic = Config::default().resolve(); assert_eq!(quic.max_streams, DEFAULT_MAX_STREAMS); assert_eq!(quic.idle_timeout, DEFAULT_IDLE_TIMEOUT); assert_eq!(quic.keep_alive, Some(DEFAULT_KEEP_ALIVE)); @@ -479,17 +543,15 @@ mod tests { assert!(!quic.gso_disabled()); } - // `Server::resolve` only exists where a backend consumes it. - #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] #[test] fn zero_keep_alive_disables_it() { - let disabled = Server { + let disabled = Config { keep_alive: Some(Duration::ZERO), ..Default::default() }; assert_eq!(disabled.resolve().keep_alive, None); - let explicit = Client { + let explicit = Config { keep_alive: Some(Duration::from_secs(2)), ..Default::default() }; @@ -498,12 +560,12 @@ mod tests { #[test] fn gso_disabled_only_on_explicit_false() { - let off = Client { + let off = Config { gso: Some(false), ..Default::default() }; assert!(off.resolve().gso_disabled()); - let on = Client { + let on = Config { gso: Some(true), ..Default::default() }; @@ -511,49 +573,55 @@ mod tests { } #[test] - fn client_and_server_flags_are_distinct() { - let both = parse(&["--client-quic-max-streams", "5000", "--server-quic-max-streams", "9000"]); - assert_eq!(both.client.max_streams, Some(5000)); - assert_eq!(both.server.max_streams, Some(9000)); + fn canonical_flags_parse() { + let quic = parse(&[ + "--quic-max-streams", + "5000", + "--quic-gso=false", + "--quic-congestion-control", + "delay", + "--quic-qlog", + "/tmp/qlog", + ]); + assert_eq!(quic.max_streams, Some(5000)); + assert_eq!(quic.gso, Some(false)); + assert_eq!(quic.congestion_control, Some(CongestionControl::Delay)); + assert_eq!(quic.qlog.as_deref(), Some(std::path::Path::new("/tmp/qlog"))); } + /// Every old role-prefixed spelling still parses and folds into the + /// canonical field. #[test] - fn server_only_knobs_parse() { - let both = parse(&["--server-preferred-v4", "192.0.2.1:443", "--server-quic-lb-id", "ab"]); - assert_eq!(both.server.preferred_v4, Some("192.0.2.1:443".parse().unwrap())); - assert!(both.server.quic_lb_id.is_some()); - // The accept-side knobs live only on the server section. - assert_eq!(both.client.max_streams, None); - } + fn legacy_spellings_fold_into_canonical() { + let quic = parse(&["--client-quic-max-streams", "2048"]).resolved(); + assert_eq!(quic.max_streams, Some(2048)); - #[test] - fn deprecated_max_streams_aliases() { - let both = parse(&["--client-max-streams", "2048", "--server-max-streams", "4096"]); - assert_eq!(both.client.max_streams, Some(2048)); - assert_eq!(both.server.max_streams, Some(4096)); + let quic = parse(&["--server-quic-max-streams", "4096"]).resolved(); + assert_eq!(quic.max_streams, Some(4096)); + + let quic = parse(&["--client-max-streams", "1", "--server-quic-gso=false"]).resolved(); + assert_eq!(quic.max_streams, Some(1)); + assert_eq!(quic.gso, Some(false)); } + /// The canonical spelling wins; between the legacy pair, client wins. #[test] - fn qlog_flags_are_distinct_per_role() { - let both = parse(&["--client-quic-qlog", "/tmp/client", "--server-quic-qlog", "/tmp/server"]); - assert_eq!(both.client.qlog.as_deref(), Some(std::path::Path::new("/tmp/client"))); - assert_eq!(both.server.qlog.as_deref(), Some(std::path::Path::new("/tmp/server"))); - - assert_eq!( - both.client.resolve().qlog_dir(), - Some(std::path::Path::new("/tmp/client")) - ); - assert_eq!(Client::default().resolve().qlog_dir(), None); + fn canonical_wins_over_legacy() { + let quic = parse(&["--quic-max-streams", "10", "--client-quic-max-streams", "20"]).resolved(); + assert_eq!(quic.max_streams, Some(10)); + + let quic = parse(&["--client-quic-max-streams", "20", "--server-quic-max-streams", "30"]).resolved(); + assert_eq!(quic.max_streams, Some(20)); } /// A build that can't capture must reject the flag rather than ignore it, so an /// operator isn't left waiting on trace files that will never appear. #[test] fn qlog_requires_the_feature() { - let unset = Client::default().validate(); + let unset = Config::default().validate(); assert!(unset.is_ok(), "no directory configured is always fine"); - let set = Client { + let set = Config { qlog: Some("/tmp/qlog".into()), ..Default::default() }; @@ -569,19 +637,19 @@ mod tests { /// value arrives from a TOML file or a C caller, so validation has to catch it here. #[test] fn idle_timeout_beyond_the_varint_is_rejected() { - let over = Client { + let over = Config { idle_timeout: Some(MAX_IDLE_TIMEOUT + Duration::from_millis(1)), ..Default::default() }; assert!(matches!(over.validate(), Err(crate::Error::IdleTimeoutRange))); - let server = Server { + let saturated = Config { idle_timeout: Some(Duration::from_millis(u64::MAX)), ..Default::default() }; - assert!(matches!(server.validate(), Err(crate::Error::IdleTimeoutRange))); + assert!(matches!(saturated.validate(), Err(crate::Error::IdleTimeoutRange))); - let at_limit = Client { + let at_limit = Config { idle_timeout: Some(MAX_IDLE_TIMEOUT), ..Default::default() }; @@ -593,30 +661,13 @@ mod tests { let toml = r#" max_streams = 7000 gso = false - preferred_v4 = "192.0.2.1:443" congestion_control = "delay" qlog = "/tmp/qlog" "#; - let quic: Server = toml::from_str(toml).unwrap(); + let quic: Config = toml::from_str(toml).unwrap(); assert_eq!(quic.max_streams, Some(7000)); assert_eq!(quic.gso, Some(false)); - assert_eq!(quic.preferred_v4, Some("192.0.2.1:443".parse().unwrap())); assert_eq!(quic.congestion_control, Some(CongestionControl::Delay)); assert_eq!(quic.qlog.as_deref(), Some(std::path::Path::new("/tmp/qlog"))); } - - #[test] - fn congestion_control_flags_parse() { - let both = parse(&[ - "--client-quic-congestion-control", - "delay", - "--server-quic-congestion-control", - "loss", - ]); - assert_eq!(both.client.congestion_control, Some(CongestionControl::Delay)); - assert_eq!(both.server.congestion_control, Some(CongestionControl::Loss)); - - // Unset stays None; each backend then picks its own default. - assert_eq!(Client::default().resolve().congestion_control, None); - } } diff --git a/rs/moq-native/src/quiche.rs b/rs/moq-native/src/quiche.rs index 9906fb07542..69399f4ba7b 100644 --- a/rs/moq-native/src/quiche.rs +++ b/rs/moq-native/src/quiche.rs @@ -1,11 +1,11 @@ //! QUIC backend built on [`web_transport_quiche`], speaking WebTransport over HTTP/3 //! (`https://`) or raw QUIC (`moqt://` / `moql://`). -use crate::client::ClientConfig; +use crate::connect; use crate::crypto; +use crate::listen; use crate::quic::CongestionControl; use crate::quic::Resolved; -use crate::server::ServerConfig; use rustls::pki_types::pem::PemObject; use rustls::pki_types::{CertificateDer, PrivateKeyDer}; use std::net; @@ -202,7 +202,7 @@ pub(crate) struct QuicheClient { pub bind: net::SocketAddr, /// Resolved server-verification policy, shared with the other backends. pub verification: crate::tls::Verification, - /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]). + /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Connect::allows_http_bootstrap]). pub http_bootstrap: bool, pub quic: Resolved, pub host_name: Option, @@ -217,8 +217,8 @@ struct ClientIdentity { } impl QuicheClient { - pub fn new(config: &ClientConfig) -> Result { - let quic = config.quic.resolve(); + pub fn new(config: &crate::connect::Config, quic: &crate::quic::Config) -> Result { + let quic = quic.resolve(); let identity = match (&config.tls.cert, &config.tls.key) { (Some(cert), Some(key)) => { let (chain, key) = load_quiche_cert(cert, key)?; @@ -230,20 +230,21 @@ impl QuicheClient { // Warn once here rather than on every dial: the constraint is a property of // the config, and a relay reconnecting to its peers would repeat it forever. - if config.bind.port() != 0 { + let bind = config.resolved_bind(); + if bind.port() != 0 { tracing::warn!( - bind = %config.bind, + bind = %bind, "pinned client bind port; only the first resolved address is dialed (address failover needs an ephemeral port on this backend)" ); } Ok(Self { - bind: config.bind, + bind, verification: config.tls.verification()?, http_bootstrap: config.tls.allows_http_bootstrap(), quic, host_name: config.tls.host_name.clone(), - failover_delay: config.resolved_failover_delay(), + failover_delay: config.resolved_race(), identity, }) } @@ -547,12 +548,12 @@ pub(crate) struct QuicheServer { } impl QuicheServer { - pub fn new(config: ServerConfig) -> Result { - if config.quic.quic_lb_id.is_some() { + pub fn new(config: listen::Config, quic: &crate::quic::Config) -> Result { + if config.lb_id.is_some() { tracing::warn!("QUIC-LB is not supported with the quiche backend; ignoring server ID"); } - let quic = config.quic.resolve(); + let quic = quic.resolve(); let listen = crate::util::resolve(config.bind.as_deref(), crate::server::DEFAULT_BIND).map_err(Error::ResolveBind)?; @@ -758,7 +759,7 @@ mod tests { /// one must land on BBR rather than quiche's own CUBIC default. #[test] fn apply_settings_writes_cc_algorithm() { - let mut quic = crate::quic::Client::default(); + let mut quic = crate::quic::Config::default(); let mut settings = web_transport_quiche::Settings::default(); apply_settings(&mut settings, &quic.resolve()).unwrap(); diff --git a/rs/moq-native/src/quinn.rs b/rs/moq-native/src/quinn.rs index 0d7f930f495..43091ac6cac 100644 --- a/rs/moq-native/src/quinn.rs +++ b/rs/moq-native/src/quinn.rs @@ -1,10 +1,10 @@ //! The quinn QUIC backend, used for both WebTransport (`https://`) and raw QUIC (`moqt://`, `moql://`). -use crate::client::ClientConfig; +use crate::connect; +use crate::listen; use crate::quic::CongestionControl; use crate::quic::Resolved; use crate::quic::ServerId; -use crate::server::ServerConfig; use crate::tls::{FingerprintVerifier, ServeCerts}; use std::net; use std::sync::Arc; @@ -245,7 +245,7 @@ type Result = std::result::Result; pub(crate) struct QuinnClient { pub quic: quinn::Endpoint, pub transport: Arc, - /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Client::allows_http_bootstrap]). + /// Whether an `http://` URL may bootstrap a pin (see [crate::tls::Connect::allows_http_bootstrap]). pub http_bootstrap: bool, /// Optional TLS SNI / verification hostname override (from config). pub host_name: Option, @@ -258,11 +258,11 @@ pub(crate) struct QuinnClient { } impl QuinnClient { - pub fn new(config: &ClientConfig) -> Result { - let socket = crate::bind::udp(config.bind).map_err(Error::BindSocket)?; + pub fn new(config: &connect::Config, quic: &crate::quic::Config) -> Result { + let socket = crate::bind::udp(config.resolved_bind()).map_err(Error::BindSocket)?; let dual_stack = crate::bind::udp_is_dual_stack(&socket); - let quic = config.quic.resolve(); + let quic = quic.resolve(); let mut transport = quinn::TransportConfig::default(); apply_transport(&mut transport, &quic); apply_qlog(&mut transport, &quic, "client")?; @@ -280,7 +280,7 @@ impl QuinnClient { transport, http_bootstrap: config.tls.allows_http_bootstrap(), host_name: config.tls.host_name.clone(), - failover_delay: config.resolved_failover_delay(), + failover_delay: config.resolved_race(), dual_stack, }) } @@ -477,8 +477,8 @@ pub(crate) struct QuinnServer { } impl QuinnServer { - pub fn new(config: ServerConfig) -> Result { - let quic = config.quic.resolve(); + pub fn new(config: listen::Config, quic: &crate::quic::Config) -> Result { + let quic = quic.resolve(); let mut transport = quinn::TransportConfig::default(); apply_transport(&mut transport, &quic); apply_qlog(&mut transport, &quic, "server")?; @@ -525,10 +525,10 @@ impl QuinnServer { // Advertise the preferred_address transport parameter (RFC 9000 §9.6). // Quinn allocates a fresh CID + reset token for the address during the handshake. - if let Some(addr) = config.quic.preferred_v4 { + if let Some(addr) = config.preferred_v4 { tls.preferred_address_v4(Some(addr)); } - if let Some(addr) = config.quic.preferred_v6 { + if let Some(addr) = config.preferred_v6 { tls.preferred_address_v6(Some(addr)); } @@ -540,8 +540,8 @@ impl QuinnServer { // Configure connection ID generator with server ID if provided let mut endpoint_config = quinn::EndpointConfig::default(); - if let Some(server_id) = config.quic.quic_lb_id { - let nonce_len = config.quic.quic_lb_nonce.unwrap_or(8); + if let Some(server_id) = config.lb_id { + let nonce_len = config.lb_nonce.unwrap_or(8); if nonce_len < 4 { return Err(Error::QuicLbNonceTooSmall); } @@ -751,7 +751,7 @@ mod tests { /// An unset knob must land on BBR rather than quinn's own CUBIC default. #[test] fn congestion_control_defaults_to_delay() { - let mut quic = crate::quic::Client::default(); + let mut quic = crate::quic::Config::default(); assert_eq!(congestion_control(&quic.resolve()), CongestionControl::Delay); // An explicit request still gets through. @@ -763,20 +763,22 @@ mod tests { /// connections that actually run quinn's BBR controller, on both ends. #[tokio::test] async fn delay_reaches_the_live_connection() { - let server_config = ServerConfig { + let server_config = listen::Config { bind: Some("127.0.0.1:0".to_string()), - tls: crate::tls::Server { + tls: crate::tls::Listen { generate: vec!["localhost".into()], ..Default::default() }, - quic: crate::quic::Server { - congestion_control: Some(CongestionControl::Delay), - ..Default::default() - }, ..Default::default() }; - let server = QuinnServer::new(server_config).expect("server init"); + // One shared tuning for both roles, the way a binary composes them. + let quic = crate::quic::Config { + congestion_control: Some(CongestionControl::Delay), + ..Default::default() + }; + + let server = QuinnServer::new(server_config, &quic).expect("server init"); let addr = server.local_addr().expect("local addr"); let accepted = tokio::spawn(async move { @@ -789,21 +791,17 @@ mod tests { }); // tls::Client has a private field, so it can't be built with a struct literal. - let mut tls_config = crate::tls::Client::default(); - tls_config.disable_verify = Some(true); + let mut tls_config = crate::tls::Connect::default(); + tls_config.insecure = Some(true); - let client_config = ClientConfig { - bind: "127.0.0.1:0".parse().unwrap(), + let client_config = connect::Config { + bind: Some("127.0.0.1:0".parse().unwrap()), tls: tls_config, - quic: crate::quic::Client { - congestion_control: Some(CongestionControl::Delay), - ..Default::default() - }, ..Default::default() }; let tls = client_config.tls.build().expect("tls config"); - let client = QuinnClient::new(&client_config).expect("client init"); + let client = QuinnClient::new(&client_config, &quic).expect("client init"); // Dial the loopback IP directly so the system resolver is never involved. let url: Url = format!("moqt://127.0.0.1:{}", addr.port()).parse().unwrap(); diff --git a/rs/moq-native/src/server.rs b/rs/moq-native/src/server.rs index 42fbfef0e21..53dc62dd2b8 100644 --- a/rs/moq-native/src/server.rs +++ b/rs/moq-native/src/server.rs @@ -22,72 +22,10 @@ use futures::future::BoxFuture; use futures::stream::FuturesUnordered; use futures::stream::StreamExt; -/// Configuration for the MoQ server. -#[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)] -#[serde(deny_unknown_fields, default)] -#[non_exhaustive] -pub struct ServerConfig { - /// Listen for QUIC (UDP) on the given address. Defaults to `[::]:443`. - /// - /// Accepts standard socket address syntax (e.g. `[::]:443`) or a DNS - /// `host:port` pair (e.g. `fly-global-services:443`), resolved at bind time - /// (first address only; Quinn cannot bind multiple). Leave unset while a - /// `tcp`/`unix` listener is configured to run a stream-only server with no - /// QUIC. - #[serde(alias = "listen")] - #[arg(id = "server-bind", long = "server-bind", alias = "listen", env = "MOQ_SERVER_BIND")] - pub bind: Option, - - /// Plaintext qmux TCP listener (`--server-tcp-bind`, no TLS). Requires the - /// `tcp` feature. - #[cfg(feature = "tcp")] - #[command(flatten)] - #[serde(default)] - pub tcp: crate::tcp::Config, - - /// Plaintext qmux Unix-socket listener (`--server-unix-bind`) with an optional - /// peer-credential allowlist. Requires the `uds` feature; unix-only. - #[cfg(all(feature = "uds", unix))] - #[command(flatten)] - #[serde(default)] - pub unix: crate::unix::Config, - - /// The QUIC backend to use. - /// Auto-detected from compiled features if not specified. - #[arg(id = "server-backend", long = "server-backend", env = "MOQ_SERVER_BACKEND")] - pub backend: Option, - - /// QUIC transport tuning (`--server-quic-*`): stream limits, GSO, timeouts, - /// plus the accept-side knobs (preferred address, QUIC-LB connection IDs). - #[command(flatten)] - #[serde(default)] - pub quic: crate::quic::Server, - - /// Restrict the server to specific MoQ protocol version(s). - /// - /// By default, the server accepts all supported versions. - /// Use this to restrict to specific versions, e.g. `--server-version moq-lite-02`. - /// Can be specified multiple times to accept a subset of versions. - #[serde(default, skip_serializing_if = "Vec::is_empty")] - #[arg( - id = "server-version", - long = "server-version", - env = "MOQ_SERVER_VERSION", - value_parser = crate::version_parser(), - )] - pub version: Vec, - - /// The certificates to serve and the roots that authenticate mTLS clients - /// (`--server-tls-*`). - #[command(flatten)] - #[serde(default)] - pub tls: crate::tls::Server, -} - -impl ServerConfig { +impl crate::listen::Config { /// Build the [`Server`] this config describes, binding its listeners. - pub fn init(self) -> crate::Result { - Server::new(self) + pub fn init(self, quic: crate::quic::Config) -> crate::Result { + Server::new(self, quic) } /// Returns the configured versions, defaulting to all if none specified. @@ -118,15 +56,15 @@ impl ServerConfig { } } -/// Default bind address used when [`ServerConfig::bind`] is not set. +/// Default bind address used when [`crate::listen::Config::bind`] is not set. #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] pub(crate) const DEFAULT_BIND: &str = "[::]:443"; /// Server for accepting MoQ connections. /// /// Accepts QUIC (and optionally WebSocket), plus plaintext qmux over TCP -/// (`--server-tcp-bind`) and Unix sockets (`--server-unix-bind`). Create via -/// [`ServerConfig::init`] or [`Server::new`]. +/// (`--listen-tcp-bind`) and Unix sockets (`--listen-unix-bind`). Create via +/// [`crate::listen::Config::init`] or [`Server::new`]. pub struct Server { moq: moq_net::Server, versions: moq_net::Versions, @@ -150,7 +88,13 @@ impl Server { /// /// The stream (`tcp`/`unix`) listeners need a runtime, so they wait for /// [`listen`](Self::listen). - pub fn new(config: ServerConfig) -> crate::Result { + pub fn new(config: crate::listen::Config, quic: crate::quic::Config) -> crate::Result { + // Resolve here rather than in `init`, so a caller that builds the config by hand + // gets the released spellings folded in too. + config.validate()?; + let config = config.resolved(); + let quic = quic.resolved(); + // `default_quic_backend` panics when no backend is compiled, so a WebSocket- or // stream-only build must not ask it. #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] @@ -158,16 +102,16 @@ impl Server { let versions = config.versions(); - // Build a QUIC backend when `--server-bind` is set, or when nothing else - // is (the default). A stream-only server (`--server-unix-bind` with no - // `--server-bind`) doesn't also open UDP/443. - config.quic.validate()?; + // Build a QUIC backend when `--listen` is set, or when nothing else + // is (the default). A stream-only server (`--listen-unix-bind` with no + // `--listen`) doesn't also open UDP/443. + quic.validate()?; let build_quic = config.bind.is_some() || !config.has_stream_listener(); #[cfg(not(any(feature = "noq", feature = "quinn", feature = "quiche")))] if config.bind.is_some() { return Err(Error::NoBackend( - "--server-bind requires a noq, quinn, or quiche backend feature", + "--listen requires a noq, quinn, or quiche backend feature", )); } @@ -196,20 +140,20 @@ impl Server { #[cfg(feature = "noq")] #[allow(unreachable_patterns)] let noq = match backend { - QuicBackend::Noq if build_quic => Some(crate::noq::NoqServer::new(config.clone())?), + QuicBackend::Noq if build_quic => Some(crate::noq::NoqServer::new(config.clone(), &quic)?), _ => None, }; #[cfg(feature = "quinn")] #[allow(unreachable_patterns)] let quinn = match backend { - QuicBackend::Quinn if build_quic => Some(crate::quinn::QuinnServer::new(config.clone())?), + QuicBackend::Quinn if build_quic => Some(crate::quinn::QuinnServer::new(config.clone(), &quic)?), _ => None, }; #[cfg(feature = "quiche")] let quiche = match backend { - QuicBackend::Quiche if build_quic => Some(crate::quiche::QuicheServer::new(config.clone())?), + QuicBackend::Quiche if build_quic => Some(crate::quiche::QuicheServer::new(config.clone(), &quic)?), _ => None, }; @@ -347,7 +291,7 @@ impl Server { if let Some(quiche) = self.quiche.as_ref() { return quiche.certificates(); } - // No QUIC backend (e.g. a stream-only `--server-bind`): no certificates. + // No QUIC backend (e.g. a stream-only `--listen-tcp-bind`): no certificates. crate::tls::Certificates::empty() } @@ -393,7 +337,7 @@ impl Server { /// /// Terminal, and that is the point: it consumes the `Server`, so the builders /// above cannot run afterwards and every session is served the configuration - /// this call captured. The QUIC socket is bound by [`ServerConfig::init`], but + /// this call captured. The QUIC socket is bound by [`crate::listen::Config::init`], but /// the stream (`tcp`/`unix`) listeners need a runtime, so they bind here. /// /// A bind failure is the error, not a silent `None` from a later accept. It @@ -596,7 +540,7 @@ impl Server { if let Some(quiche) = self.quiche.as_ref() { return Ok(quiche.local_addr()?); } - // No QUIC backend (e.g. a stream-only `--server-bind`). + // No QUIC backend (e.g. a stream-only `--listen-tcp-bind`). Err(Error::NoBackend("no QUIC listener configured")) } @@ -729,7 +673,7 @@ fn stream_versions(base: &moq_net::Versions) -> moq_net::Versions { moq_net::Versions::from(versions) } -/// A configured stream listener (`--server-tcp-bind` / `--server-unix-bind`). +/// A configured stream listener (`--listen-tcp-bind` / `--listen-unix-bind`). #[cfg(any(feature = "tcp", all(feature = "uds", unix)))] enum StreamBind { #[cfg(feature = "tcp")] @@ -1224,7 +1168,7 @@ impl Request { } /// The client certificate chain the peer presented, if any, validated - /// against a configured [`crate::tls::Server::root`] during the handshake. + /// against a configured [`crate::tls::Listen::root`] during the handshake. /// /// Captured at the transport handshake (before the SETUP). Only the Quinn and noq /// backends support mTLS; other transports always return `None`. Use it to grant @@ -1247,7 +1191,7 @@ mod tests { #[test] fn version_help_lists_every_parseable_name() { - let help = ::augment_args(clap::Command::new("test")) + let help = ::augment_args(clap::Command::new("test")) .render_long_help() .to_string(); for name in moq_net::Version::names() { @@ -1265,9 +1209,9 @@ mod tests { #[cfg(feature = "tcp")] #[test] fn accept_health_covers_stream_listeners_before_they_bind() { - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.tcp.bind = Some("127.0.0.1:0".parse().unwrap()); - let server = Server::new(config).expect("stream-only server"); + let server = Server::new(config, Default::default()).expect("stream-only server"); let names: Vec<_> = server.accept_health().iter().map(|h| h.listener()).collect(); assert_eq!(names, vec!["tcp"], "the tcp listener must report before it binds"); @@ -1294,10 +1238,10 @@ mod tests { let port = probe.local_addr().expect("probe addr").port(); drop(probe); - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse addr")); config.unix.bind = Some(occupied); - let server = Server::new(config).expect("stream-only server"); + let server = Server::new(config, Default::default()).expect("stream-only server"); assert!(server.listen().await.is_err(), "the unix bind must fail"); std::net::TcpListener::bind(("127.0.0.1", port)).expect("the tcp port must be free again"); @@ -1311,9 +1255,9 @@ mod tests { let addr = probe.local_addr().expect("probe addr"); drop(probe); - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.tcp.bind = Some(addr); - let listener = Server::new(config) + let listener = Server::new(config, Default::default()) .expect("stream-only server") .listen() .await @@ -1348,9 +1292,9 @@ mod tests { .expect("write frame"); group.finish().expect("finish group"); - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.unix.bind = Some(path.clone()); - let server = config.init().expect("server init"); + let server = config.init(Default::default()).expect("server init"); // The publisher lives on the server, never on the accepted request. let serve = tokio::spawn(server.serve_publish(origin.consume())); @@ -1377,8 +1321,8 @@ mod tests { let url: Url = format!("unix://{}", path.display()).parse().expect("parse url"); let subscriber = moq_net::Origin::random().produce(); let mut announced = subscriber.consume().announced(); - let client = crate::ClientConfig::default() - .init() + let client = crate::connect::Config::default() + .init(Default::default()) .expect("client init") .with_subscriber(subscriber); let session = tokio::time::timeout(TIMEOUT, client.connect(url).established()) @@ -1428,9 +1372,9 @@ mod tests { let addr = probe.local_addr().unwrap(); drop(probe); - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.tcp.bind = Some(addr); - let server = Server::new(config).expect("stream-only server"); + let server = Server::new(config, Default::default()).expect("stream-only server"); let listener = server.listen().await.expect("listen"); assert!(tokio::net::TcpListener::bind(addr).await.is_err(), "listener is bound"); @@ -1444,12 +1388,15 @@ mod tests { #[cfg(not(any(feature = "noq", feature = "quinn", feature = "quiche")))] #[test] fn quic_bind_without_a_quic_backend_is_rejected() { - let config = ServerConfig { + let config = crate::listen::Config { bind: Some("127.0.0.1:0".to_string()), ..Default::default() }; - assert!(matches!(Server::new(config), Err(Error::NoBackend(_)))); + assert!(matches!( + Server::new(config, Default::default()), + Err(Error::NoBackend(_)) + )); } /// A QUIC-only server reports nothing. It multiplexes over one UDP socket and @@ -1457,7 +1404,9 @@ mod tests { #[cfg(all(feature = "quinn", not(feature = "tcp")))] #[test] fn accept_health_is_empty_without_a_stream_listener() { - let server = ServerConfig::default().init().expect("quic server"); + let server = crate::listen::Config::default() + .init(Default::default()) + .expect("quic server"); assert!(server.accept_health().is_empty()); } @@ -1475,13 +1424,13 @@ mod tests { #[cfg(feature = "quinn")] #[tokio::test] async fn certificates_expose_generated_fingerprints() { - let mut config = ServerConfig { + let mut config = crate::listen::Config { bind: Some("[::]:0".to_string()), ..Default::default() }; config.tls.generate = vec!["localhost".into()]; - let certs = config.init().expect("server init").certificates(); + let certs = config.init(Default::default()).expect("server init").certificates(); let fingerprints = certs.fingerprints(); assert_eq!(fingerprints.len(), 1, "one generated certificate"); // Hex-encoded SHA-256. @@ -1494,10 +1443,10 @@ mod tests { #[cfg(all(feature = "uds", unix))] #[tokio::test] async fn certificates_are_empty_without_a_tls_backend() { - let mut config = ServerConfig::default(); + let mut config = crate::listen::Config::default(); config.unix.bind = Some(PathBuf::from("/tmp/moq-native-certificates-test.sock")); - let server = config.init().expect("server init"); + let server = config.init(Default::default()).expect("server init"); assert!(server.certificates().fingerprints().is_empty()); } @@ -1508,7 +1457,7 @@ mod tests { cert = "cert.pem" key = "key.pem" "#; - let config: crate::tls::Server = toml::from_str(single).unwrap(); + let config: crate::tls::Listen = toml::from_str(single).unwrap(); assert_eq!(config.cert, vec![PathBuf::from("cert.pem")]); assert_eq!(config.key, vec![PathBuf::from("key.pem")]); @@ -1519,7 +1468,7 @@ mod tests { generate = ["localhost"] root = ["ca.pem"] "#; - let config: crate::tls::Server = toml::from_str(array).unwrap(); + let config: crate::tls::Listen = toml::from_str(array).unwrap(); assert_eq!(config.cert, vec![PathBuf::from("a.pem"), PathBuf::from("b.pem")]); assert_eq!(config.key, vec![PathBuf::from("a.key"), PathBuf::from("b.key")]); assert_eq!(config.generate, vec!["localhost".to_string()]); @@ -1529,17 +1478,17 @@ mod tests { #[test] fn bind_string_or_listen_alias() { // The QUIC bind is a plain address; the `listen` alias still works. - let bind: ServerConfig = toml::from_str(r#"bind = "[::]:443""#).unwrap(); + let bind: crate::listen::Config = toml::from_str(r#"bind = "[::]:443""#).unwrap(); assert_eq!(bind.bind.as_deref(), Some("[::]:443")); - let alias: ServerConfig = toml::from_str(r#"listen = "0.0.0.0:4443""#).unwrap(); + let alias: crate::listen::Config = toml::from_str(r#"listen = "0.0.0.0:4443""#).unwrap(); assert_eq!(alias.bind.as_deref(), Some("0.0.0.0:4443")); } #[cfg(all(feature = "uds", unix))] #[test] fn stream_listener_config_parses() { - let config: ServerConfig = toml::from_str( + let config: crate::listen::Config = toml::from_str( r#" bind = "[::]:443" @@ -1560,13 +1509,13 @@ uid = [1001, 1002] #[cfg(all(feature = "uds", unix))] #[test] fn stream_only_config_has_no_quic() { - // A unix listener with no `--server-bind` is stream-only. - let mut config = ServerConfig::default(); + // A unix listener with no `--listen` is stream-only. + let mut config = crate::listen::Config::default(); config.unix.bind = Some(PathBuf::from("/run/moq.sock")); assert!(config.has_stream_listener()); assert!(config.bind.is_none()); // The default (nothing configured) still runs QUIC. - assert!(!ServerConfig::default().has_stream_listener()); + assert!(!crate::listen::Config::default().has_stream_listener()); } } diff --git a/rs/moq-native/src/tcp.rs b/rs/moq-native/src/tcp.rs index f389cae0ac9..fad7634b28c 100644 --- a/rs/moq-native/src/tcp.rs +++ b/rs/moq-native/src/tcp.rs @@ -17,20 +17,57 @@ const WIRE_VERSION: qmux::Version = qmux::Version::QMux01; /// Plaintext-TCP qmux listener settings (no TLS, no UDP). /// -/// Flattened onto [`crate::ServerConfig::tcp`]. TCP carries no peer identity, so +/// Flattened onto [`crate::listen::Config::tcp`]. TCP carries no peer identity, so /// the listener must only be reachable from trusted clients. Bind it to loopback /// or a private interface; a non-loopback bind logs a warning but is allowed. // The derived arg group is named after the struct, so it needs an explicit id to // stay unique across the flattened sections. #[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)] -#[group(id = "server-tcp")] +#[group(id = "listen-tcp")] #[serde(deny_unknown_fields, default)] #[non_exhaustive] pub struct Config { /// Bind a plaintext qmux TCP listener on this address. - #[arg(long = "server-tcp-bind", id = "server-tcp-bind", env = "MOQ_SERVER_TCP_BIND")] + #[arg(long = "listen-tcp-bind", id = "listen-tcp-bind", env = "MOQ_LISTEN_TCP_BIND")] #[serde(default, skip_serializing_if = "Option::is_none")] pub bind: Option, + + /// The released `--server-tcp-bind` spelling and its env var, folded in by + /// [`Config::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, +} + +/// The `--server-tcp-*` flag from before the accept side was named `listen`. +/// +/// A separate arg rather than a clap alias, since an alias renames the flag but +/// leaves its env var behind. +#[derive(clap::Args, Clone, Debug, Default)] +#[group(id = "listen-tcp-legacy")] +pub(crate) struct Legacy { + #[arg( + long = "server-tcp-bind", + id = "server-tcp-bind", + env = "MOQ_SERVER_TCP_BIND", + hide = true + )] + bind: Option, +} + +impl Config { + /// Fold the released spelling into the canonical field. Idempotent. + pub fn resolved(&self) -> Self { + let mut resolved = self.clone(); + if self.bind.is_none() + && let Some(bind) = self.legacy.bind + { + tracing::warn!("--server-tcp-bind is deprecated; use --listen-tcp-bind"); + resolved.bind = Some(bind); + } + resolved.legacy = Legacy::default(); + resolved + } } /// Errors specific to the plain-TCP qmux transport. @@ -250,3 +287,37 @@ mod tests { assert!(matches!(res, Err(Error::NoAddresses))); } } + +#[cfg(test)] +mod legacy_tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + tcp: Config, + } + + /// The released `--server-tcp-bind` still lands in the canonical field. + #[test] + fn released_spelling_folds_in() { + let config = Cli::parse_from(["test", "--server-tcp-bind", "127.0.0.1:4443"]) + .tcp + .resolved(); + assert_eq!(config.bind, Some("127.0.0.1:4443".parse().unwrap())); + + // The canonical spelling wins, and folding twice changes nothing. + let config = Cli::parse_from([ + "test", + "--listen-tcp-bind", + "127.0.0.1:1", + "--server-tcp-bind", + "127.0.0.1:2", + ]) + .tcp + .resolved(); + assert_eq!(config.bind, Some("127.0.0.1:1".parse().unwrap())); + assert_eq!(config.resolved().bind, config.bind); + } +} diff --git a/rs/moq-native/src/tls.rs b/rs/moq-native/src/tls.rs index 771e240399e..0e31d93c724 100644 --- a/rs/moq-native/src/tls.rs +++ b/rs/moq-native/src/tls.rs @@ -1,7 +1,7 @@ //! TLS trust, certificates, and keys, split by role. //! -//! [`Client`] (`--client-tls-*`) picks who to trust: system roots, custom roots, -//! a pinned SHA-256 fingerprint, or nothing at all. [`Server`] (`--server-tls-*`) +//! [`Connect`] (`--connect-tls-*`) picks who to trust: system roots, custom roots, +//! a pinned SHA-256 fingerprint, or nothing at all. [`Listen`] (`--listen-tls-*`) //! supplies the certificate chain to serve, loaded from disk or self-signed on //! startup, and optionally the roots that authenticate mTLS clients. //! @@ -56,7 +56,7 @@ pub enum Error { /// Nothing is configured that could ever verify a server certificate. #[error( - "no trusted roots: provide --client-tls-root, enable --client-tls-system-roots, or use --client-tls-fingerprint / --client-tls-disable-verify" + "no trusted roots: provide --connect-tls-root, enable --connect-tls-system-roots, or use --connect-tls-fingerprint / --connect-tls-insecure" )] NoRoots, @@ -71,13 +71,13 @@ pub enum Error { /// Fingerprint pinning was combined with CA roots. Pinning bypasses the chain, so one of /// the two would be silently ignored. #[error( - "--client-tls-fingerprint cannot be combined with --client-tls-root or --client-tls-system-roots: fingerprint pinning bypasses CA verification" + "--connect-tls-fingerprint cannot be combined with --connect-tls-root or --connect-tls-system-roots: fingerprint pinning bypasses CA verification" )] FingerprintWithRoots, /// Trust material was configured alongside the flag that ignores all of it. #[error( - "--client-tls-disable-verify cannot be combined with --client-tls-fingerprint, --client-tls-root or --client-tls-system-roots: it accepts every certificate, so the trust material would be ignored" + "--connect-tls-insecure cannot be combined with --connect-tls-fingerprint, --connect-tls-root or --connect-tls-system-roots: it accepts every certificate, so the trust material would be ignored" )] DisableVerifyWithTrust, @@ -95,7 +95,7 @@ pub enum Error { ClientAuth(#[source] rustls::Error), /// Only one half of the mTLS client identity was given; it needs both a cert and a key. - #[error("both --client-tls-cert and --client-tls-key must be provided")] + #[error("both --connect-tls-cert and --connect-tls-key must be provided")] IncompleteClientAuth, /// The server was given a different number of certificates than keys. They pair by index. @@ -157,13 +157,13 @@ pub(crate) fn read_certs(path: &Path) -> Result>> { // ── Client ────────────────────────────────────────────────────────── -/// TLS configuration for the client. +/// The dial side's TLS: who to trust, and the optional mTLS identity to present. #[serde_with::serde_as] #[derive(Clone, Default, Debug, clap::Args, serde::Serialize, serde::Deserialize)] #[serde(default, deny_unknown_fields)] #[group(id = "tls-client")] #[non_exhaustive] -pub struct Client { +pub struct Connect { /// Trust the TLS root at this path, encoded as PEM. /// /// This value can be provided multiple times for multiple roots. @@ -171,24 +171,24 @@ pub struct Client { /// /// These roots are added on top of the system roots. By default the system /// roots are only loaded when no custom root is given, so passing a root - /// replaces them; set `--client-tls-system-roots` to trust both (e.g. to reach a + /// replaces them; set `--connect-tls-system-roots` to trust both (e.g. to reach a /// local relay with a private CA and a remote one with a public CA). #[serde(skip_serializing_if = "Vec::is_empty")] - #[arg(id = "client-tls-root", long = "client-tls-root", env = "MOQ_CLIENT_TLS_ROOT")] + #[arg(id = "connect-tls-root", long = "connect-tls-root", env = "MOQ_CONNECT_TLS_ROOT")] #[serde_as(as = "serde_with::OneOrMany<_>")] pub root: Vec, /// Also trust the platform's native root certificates. /// - /// Defaults to enabled only when no `--client-tls-root` is given. Set it + /// Defaults to enabled only when no `--connect-tls-root` is given. Set it /// explicitly to trust the system roots alongside any custom roots, or set it /// to false to trust only the custom roots. Trusting neither (no custom root /// and system roots disabled) is rejected, since verification could never pass. #[serde(skip_serializing_if = "Option::is_none")] #[arg( - id = "client-tls-system-roots", - long = "client-tls-system-roots", - env = "MOQ_CLIENT_TLS_SYSTEM_ROOTS", + id = "connect-tls-system-roots", + long = "connect-tls-system-roots", + env = "MOQ_CONNECT_TLS_SYSTEM_ROOTS", default_missing_value = "true", num_args = 0..=1, require_equals = true, @@ -208,9 +208,9 @@ pub struct Client { /// across a certificate rotation). In config files, accepts either a single string or a TOML array. #[serde(skip_serializing_if = "Vec::is_empty")] #[arg( - id = "client-tls-fingerprint", - long = "client-tls-fingerprint", - env = "MOQ_CLIENT_TLS_FINGERPRINT" + id = "connect-tls-fingerprint", + long = "connect-tls-fingerprint", + env = "MOQ_CONNECT_TLS_FINGERPRINT" )] #[serde_as(as = "serde_with::OneOrMany<_>")] pub fingerprint: Vec, @@ -218,33 +218,33 @@ pub struct Client { /// PEM file containing the client certificate chain for mTLS. /// /// Only certificates are extracted; any private keys in the file are ignored. - /// Must be paired with `--client-tls-key`. + /// Must be paired with `--connect-tls-key`. #[serde(skip_serializing_if = "Option::is_none")] - #[arg(id = "client-tls-cert", long = "client-tls-cert", env = "MOQ_CLIENT_TLS_CERT")] + #[arg(id = "connect-tls-cert", long = "connect-tls-cert", env = "MOQ_CONNECT_TLS_CERT")] pub cert: Option, /// PEM file containing the private key for mTLS. /// /// Only the private key is extracted; any certificates in the file are ignored. - /// Must be paired with `--client-tls-cert`. + /// Must be paired with `--connect-tls-cert`. #[serde(skip_serializing_if = "Option::is_none")] - #[arg(id = "client-tls-key", long = "client-tls-key", env = "MOQ_CLIENT_TLS_KEY")] + #[arg(id = "connect-tls-key", long = "connect-tls-key", env = "MOQ_CONNECT_TLS_KEY")] pub key: Option, /// Danger: Disable TLS certificate verification. /// /// Fine for local development and between relays, but should be used in caution in production. - #[serde(skip_serializing_if = "Option::is_none")] + #[serde(alias = "disable_verify", skip_serializing_if = "Option::is_none")] #[arg( - id = "client-tls-disable-verify", - long = "client-tls-disable-verify", - env = "MOQ_CLIENT_TLS_DISABLE_VERIFY", + id = "connect-tls-insecure", + long = "connect-tls-insecure", + env = "MOQ_CONNECT_TLS_INSECURE", default_missing_value = "true", num_args = 0..=1, require_equals = true, value_parser = clap::value_parser!(bool), )] - pub disable_verify: Option, + pub insecure: Option, /// Override the TLS SNI and certificate verification hostname for outbound connections. /// @@ -252,9 +252,9 @@ pub struct Client { /// raw IP address but needing to present/verify a DNS name the server certificate covers. #[serde(skip_serializing_if = "Option::is_none")] #[arg( - id = "client-tls-host-name", - long = "client-tls-host-name", - env = "MOQ_CLIENT_TLS_HOST_NAME" + id = "connect-tls-host-name", + long = "connect-tls-host-name", + env = "MOQ_CONNECT_TLS_HOST_NAME" )] pub host_name: Option, @@ -266,10 +266,15 @@ pub struct Client { deprecated: Deprecated, } -/// Holds the deprecated bare `--tls-*` flag spellings (renamed to `--client-tls-*`). -/// Flattened into [`Client`] so they keep parsing; folded into the canonical -/// fields by [`Client::build`] with a deprecation warning. No env (the env names -/// were never renamed) and no TOML. +/// Holds the released spellings this section replaced: the bare `--tls-*` flags and +/// the `--client-tls-*` pair of flag and env var. +/// +/// Flattened into [`Connect`] so they keep parsing; folded into the canonical fields +/// by the `effective_*` accessors, with a deprecation warning. Each carries its +/// original env var, since a clap alias renames the flag but not the variable, and a +/// deployment that configures a relay through the environment would otherwise find +/// its TLS settings silently ignored. Not TOML fields: config files use the +/// canonical names. #[derive(Clone, Default, Debug, clap::Args)] struct Deprecated { #[arg(long = "tls-root", hide = true)] @@ -296,7 +301,72 @@ struct Deprecated { require_equals = true, value_parser = clap::value_parser!(bool), )] - disable_verify: Option, + insecure: Option, + + #[arg( + id = "client-tls-root", + long = "client-tls-root", + env = "MOQ_CLIENT_TLS_ROOT", + hide = true + )] + client_root: Vec, + + #[arg( + id = "client-tls-system-roots", + long = "client-tls-system-roots", + env = "MOQ_CLIENT_TLS_SYSTEM_ROOTS", + hide = true, + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + )] + client_system_roots: Option, + + #[arg( + id = "client-tls-fingerprint", + long = "client-tls-fingerprint", + env = "MOQ_CLIENT_TLS_FINGERPRINT", + hide = true + )] + client_fingerprint: Vec, + + #[arg( + id = "client-tls-cert", + long = "client-tls-cert", + env = "MOQ_CLIENT_TLS_CERT", + hide = true + )] + client_cert: Option, + + #[arg( + id = "client-tls-key", + long = "client-tls-key", + env = "MOQ_CLIENT_TLS_KEY", + hide = true + )] + client_key: Option, + + #[arg( + id = "client-tls-disable-verify", + long = "client-tls-disable-verify", + alias = "client-tls-insecure", + env = "MOQ_CLIENT_TLS_DISABLE_VERIFY", + hide = true, + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + )] + client_insecure: Option, + + #[arg( + id = "client-tls-host-name", + long = "client-tls-host-name", + env = "MOQ_CLIENT_TLS_HOST_NAME", + hide = true + )] + client_host_name: Option, } /// The resolved server-certificate verification policy. @@ -307,7 +377,7 @@ struct Deprecated { /// are valid. #[derive(Clone)] pub(crate) enum Verification { - /// No verification at all. Insecure; only via `--client-tls-disable-verify`. + /// No verification at all. Insecure; only via `--connect-tls-insecure`. Disabled, /// Pin the leaf certificate by SHA-256. The CA chain is not consulted, so @@ -324,63 +394,152 @@ pub(crate) enum Verification { }, } -impl Client { +impl Connect { /// Log a warning for each deprecated `--tls-*` flag in use. Called once from /// [`Self::verification`], which every backend runs, so a deprecated flag warns once. pub(crate) fn warn_deprecated(&self) { - if !self.deprecated.root.is_empty() { - tracing::warn!("--tls-root is deprecated; use --client-tls-root"); - } - if self.deprecated.system_roots.is_some() { - tracing::warn!("--tls-system-roots is deprecated; use --client-tls-system-roots"); - } - if !self.deprecated.fingerprint.is_empty() { - tracing::warn!("--tls-fingerprint is deprecated; use --client-tls-fingerprint"); - } - if self.deprecated.disable_verify.is_some() { - tracing::warn!("--tls-disable-verify is deprecated; use --client-tls-disable-verify"); + for (used, deprecated, canonical) in [ + (!self.deprecated.root.is_empty(), "--tls-root", "--connect-tls-root"), + ( + self.deprecated.system_roots.is_some(), + "--tls-system-roots", + "--connect-tls-system-roots", + ), + ( + !self.deprecated.fingerprint.is_empty(), + "--tls-fingerprint", + "--connect-tls-fingerprint", + ), + ( + self.deprecated.insecure.is_some(), + "--tls-disable-verify", + "--connect-tls-insecure", + ), + ( + !self.deprecated.client_root.is_empty(), + "--client-tls-root", + "--connect-tls-root", + ), + ( + self.deprecated.client_system_roots.is_some(), + "--client-tls-system-roots", + "--connect-tls-system-roots", + ), + ( + !self.deprecated.client_fingerprint.is_empty(), + "--client-tls-fingerprint", + "--connect-tls-fingerprint", + ), + ( + self.deprecated.client_cert.is_some(), + "--client-tls-cert", + "--connect-tls-cert", + ), + ( + self.deprecated.client_key.is_some(), + "--client-tls-key", + "--connect-tls-key", + ), + ( + self.deprecated.client_insecure.is_some(), + "--client-tls-disable-verify", + "--connect-tls-insecure", + ), + ( + self.deprecated.client_host_name.is_some(), + "--client-tls-host-name", + "--connect-tls-host-name", + ), + ] { + if used { + tracing::warn!("{deprecated} is deprecated; use {canonical}"); + } } } - /// Roots from the canonical field plus the deprecated `--tls-root` spelling. + /// Roots from the canonical field plus the released spellings it replaced. + /// + /// Concatenated rather than "first non-empty wins": each spelling is a separate + /// list of roots, and dropping one would silently stop trusting a CA. pub(crate) fn effective_root(&self) -> Vec { let mut root = self.root.clone(); root.extend(self.deprecated.root.iter().cloned()); + root.extend(self.deprecated.client_root.iter().cloned()); root } - /// Fingerprints from the canonical field plus the deprecated `--tls-fingerprint`. + /// Fingerprints from the canonical field plus the released spellings it replaced. pub(crate) fn effective_fingerprint(&self) -> Vec { let mut fp = self.fingerprint.clone(); fp.extend(self.deprecated.fingerprint.iter().cloned()); + fp.extend(self.deprecated.client_fingerprint.iter().cloned()); fp } - /// `system_roots`, preferring the canonical flag over the deprecated alias. + /// `system_roots`, preferring the canonical flag over the deprecated spellings. pub(crate) fn effective_system_roots(&self) -> Option { - self.system_roots.or(self.deprecated.system_roots) + self.system_roots + .or(self.deprecated.system_roots) + .or(self.deprecated.client_system_roots) } - /// `disable_verify`, preferring the canonical flag over the deprecated alias. + /// `insecure`, preferring the canonical flag over the deprecated spellings. pub(crate) fn effective_disable_verify(&self) -> Option { - self.disable_verify.or(self.deprecated.disable_verify) + self.insecure + .or(self.deprecated.insecure) + .or(self.deprecated.client_insecure) + } + + /// The mTLS identity, preferring the canonical flags over `--client-tls-cert`/`-key`. + pub(crate) fn effective_identity(&self) -> (Option, Option) { + ( + self.cert.clone().or_else(|| self.deprecated.client_cert.clone()), + self.key.clone().or_else(|| self.deprecated.client_key.clone()), + ) + } + + /// The SNI override, preferring the canonical flag over `--client-tls-host-name`. + pub(crate) fn effective_host_name(&self) -> Option { + self.host_name + .clone() + .or_else(|| self.deprecated.client_host_name.clone()) + } + + /// Fold every released spelling into the canonical fields, warning once for each. + /// + /// Applied by [`crate::connect::Config::resolved`], so the backends read plain + /// fields and can't each forget a fold. Idempotent. + pub fn resolved(&self) -> Self { + self.warn_deprecated(); + + let (cert, key) = self.effective_identity(); + Self { + root: self.effective_root(), + system_roots: self.effective_system_roots(), + fingerprint: self.effective_fingerprint(), + cert, + key, + insecure: self.effective_disable_verify(), + host_name: self.effective_host_name(), + deprecated: Deprecated::default(), + } } /// Resolve the verification policy from the configured flags. /// /// Precedence and rules (shared by all backends): - /// - `--client-tls-disable-verify` disables verification, and combining it with any + /// - `--connect-tls-insecure` disables verification, and combining it with any /// trust material is rejected rather than silently ignoring that material. - /// - `--client-tls-fingerprint` pins the leaf and bypasses the CA chain; combining - /// it with `--client-tls-root` or `--client-tls-system-roots` is rejected rather than + /// - `--connect-tls-fingerprint` pins the leaf and bypasses the CA chain; combining + /// it with `--connect-tls-root` or `--connect-tls-system-roots` is rejected rather than /// silently ignoring one of them. /// - Otherwise, verify against the system roots (default) plus any custom /// roots. The system roots are dropped once a custom root is given unless - /// `--client-tls-system-roots` re-enables them. + /// `--connect-tls-system-roots` re-enables them. /// /// Every combination that would quietly drop one setting is an error. Silently /// weakening trust is the worst outcome here: someone moving off - /// `disable_verify` by adding a fingerprint would otherwise still accept every + /// `insecure` by adding a fingerprint would otherwise still accept every /// certificate, with the UI showing the pin as configured. pub(crate) fn verification(&self) -> Result { self.warn_deprecated(); @@ -431,7 +590,7 @@ impl Client { /// honored for a connection. /// /// Only when no stronger verification is configured: an explicit - /// `--client-tls-fingerprint` must never be weakened by an attacker-controlled + /// `--connect-tls-fingerprint` must never be weakened by an attacker-controlled /// plaintext fetch, and there is nothing to bootstrap when verification is /// disabled. With CA roots (the default), `http://` is the deliberate /// per-connection way to pin a self-signed relay, so it is allowed. @@ -590,7 +749,7 @@ pub fn init_android(env: &mut jni::Env, context: jni::objects::JObject) -> Resul Ok(()) } -// ── Server ────────────────────────────────────────────────────────── +// ── Listen ────────────────────────────────────────────────────────── /// TLS configuration for the server. /// @@ -603,15 +762,15 @@ pub fn init_android(env: &mut jni::Env, context: jni::objects::JObject) -> Resul #[serde(deny_unknown_fields)] #[group(id = "tls-server")] #[non_exhaustive] -pub struct Server { +pub struct Listen { /// Load the given certificate from disk. - #[arg(long = "tls-cert", id = "tls-cert", env = "MOQ_SERVER_TLS_CERT")] + #[arg(long = "listen-tls-cert", id = "listen-tls-cert", env = "MOQ_LISTEN_TLS_CERT")] #[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde_as(as = "serde_with::OneOrMany<_>")] pub cert: Vec, /// Load the given key from disk. - #[arg(long = "tls-key", id = "tls-key", env = "MOQ_SERVER_TLS_KEY")] + #[arg(long = "listen-tls-key", id = "listen-tls-key", env = "MOQ_LISTEN_TLS_KEY")] #[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde_as(as = "serde_with::OneOrMany<_>")] pub key: Vec, @@ -619,10 +778,10 @@ pub struct Server { /// Or generate a new certificate and key with the given hostnames. /// This won't be valid unless the client uses the fingerprint or disables verification. #[arg( - long = "tls-generate", - id = "tls-generate", + long = "listen-tls-generate", + id = "listen-tls-generate", value_delimiter = ',', - env = "MOQ_SERVER_TLS_GENERATE" + env = "MOQ_LISTEN_TLS_GENERATE" )] #[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde_as(as = "serde_with::OneOrMany<_>")] @@ -638,17 +797,107 @@ pub struct Server { /// Plain-TLS listeners built via [`Self::server_config`] also use these roots /// for optional mTLS. #[arg( - long = "server-tls-root", - id = "server-tls-root", + long = "listen-tls-root", + id = "listen-tls-root", value_delimiter = ',', - env = "MOQ_SERVER_TLS_ROOT" + env = "MOQ_LISTEN_TLS_ROOT" )] #[serde(default, skip_serializing_if = "Vec::is_empty")] #[serde_as(as = "serde_with::OneOrMany<_>")] pub root: Vec, + + /// The released `--server-tls-*` spellings and env vars, folded into the fields + /// above by [`Self::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) deprecated: ListenDeprecated, } -impl Server { +/// The released served-identity spellings, kept parsing but hidden. +/// +/// The flags themselves mostly survived this rename (`--tls-cert` is still +/// `--tls-cert`); what they carry here is their original env var, which a clap +/// alias cannot. A relay configured through the environment would otherwise come +/// up with no certificate at all. +#[derive(Clone, Default, Debug, clap::Args)] +pub(crate) struct ListenDeprecated { + #[arg( + id = "server-tls-cert", + long = "tls-cert", + alias = "server-tls-cert", + env = "MOQ_SERVER_TLS_CERT", + hide = true + )] + cert: Vec, + + #[arg( + id = "server-tls-key", + long = "tls-key", + alias = "server-tls-key", + env = "MOQ_SERVER_TLS_KEY", + hide = true + )] + key: Vec, + + #[arg( + id = "server-tls-generate", + long = "tls-generate", + alias = "server-tls-generate", + value_delimiter = ',', + env = "MOQ_SERVER_TLS_GENERATE", + hide = true + )] + generate: Vec, + + #[arg( + id = "server-tls-root", + long = "server-tls-root", + value_delimiter = ',', + env = "MOQ_SERVER_TLS_ROOT", + hide = true + )] + root: Vec, +} + +impl Listen { + /// Fold every released `--server-tls-*` spelling into the canonical fields. + /// + /// Applied by [`crate::listen::Config::resolved`]. Lists concatenate, since each + /// spelling names its own files and dropping one would stop serving (or trusting) + /// a certificate. Idempotent. + pub fn resolved(&self) -> Self { + for (used, deprecated, canonical) in [ + (!self.deprecated.cert.is_empty(), "--tls-cert", "--listen-tls-cert"), + (!self.deprecated.key.is_empty(), "--tls-key", "--listen-tls-key"), + ( + !self.deprecated.generate.is_empty(), + "--tls-generate", + "--listen-tls-generate", + ), + ( + !self.deprecated.root.is_empty(), + "--server-tls-root", + "--listen-tls-root", + ), + ] { + if used { + tracing::warn!("{deprecated} is deprecated; use {canonical}"); + } + } + + let concat = |canonical: &[PathBuf], legacy: &[PathBuf]| -> Vec { + canonical.iter().chain(legacy).cloned().collect() + }; + + Self { + cert: concat(&self.cert, &self.deprecated.cert), + key: concat(&self.key, &self.deprecated.key), + generate: self.generate.iter().chain(&self.deprecated.generate).cloned().collect(), + root: concat(&self.root, &self.deprecated.root), + deprecated: ListenDeprecated::default(), + } + } + /// Load all configured root CAs into a [`rustls::RootCertStore`]. pub fn load_roots(&self) -> Result { let mut roots = rustls::RootCertStore::empty(); @@ -678,9 +927,9 @@ impl Server { } } -/// Build a [`rustls::ServerConfig`] from a [`Server`] for a plain-TLS listener. +/// Build a [`rustls::ServerConfig`] from a [`Listen`] for a plain-TLS listener. #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] -fn server_config(config: &Server, alpn: Vec>) -> Result> { +fn server_config(config: &Listen, alpn: Vec>) -> Result> { let provider = crypto::provider(); let certs = ServeCerts::new(provider.clone()); @@ -709,7 +958,7 @@ fn server_config(config: &Server, alpn: Vec>) -> Result Result<()> { + pub fn load_certs(&self, config: &Listen) -> Result<()> { if config.cert.len() != config.key.len() { return Err(Error::CertKeyCountMismatch); } @@ -1302,7 +1551,7 @@ impl rustls::server::ResolvesServerCert for ServeCerts { /// `mv`-into-place rotate certs with no external signal. Returns immediately when /// only generated certs are configured: there's nothing on disk to watch. #[cfg(any(feature = "quinn", feature = "noq"))] -pub(crate) async fn reload_certs(certs: Arc, tls_config: Server) { +pub(crate) async fn reload_certs(certs: Arc, tls_config: Listen) { let paths: Vec = tls_config.cert.iter().chain(tls_config.key.iter()).cloned().collect(); if paths.is_empty() { return; @@ -1325,3 +1574,95 @@ pub(crate) async fn reload_certs(certs: Arc, tls_config: Server) { } } } + +#[cfg(test)] +mod legacy_tests { + use super::*; + use clap::Parser; + + /// A parser wrapping the sections, which derive `Args` rather than `Parser`. + #[derive(Parser)] + struct Cli { + #[command(flatten)] + connect: Connect, + #[command(flatten)] + listen: Listen, + } + + fn parse(args: &[&str]) -> Cli { + let mut argv = vec!["test"]; + argv.extend_from_slice(args); + Cli::parse_from(argv) + } + + /// The released `--client-tls-*` spellings still land in the canonical fields. + #[test] + fn released_connect_spellings_fold_in() { + let tls = parse(&[ + "--client-tls-root", + "/tmp/ca.pem", + "--client-tls-cert", + "/tmp/client.pem", + "--client-tls-key", + "/tmp/client.key", + "--client-tls-host-name", + "relay.example.com", + "--client-tls-disable-verify=true", + ]) + .connect + .resolved(); + + assert_eq!(tls.root, vec![PathBuf::from("/tmp/ca.pem")]); + assert_eq!(tls.cert, Some(PathBuf::from("/tmp/client.pem"))); + assert_eq!(tls.key, Some(PathBuf::from("/tmp/client.key"))); + assert_eq!(tls.host_name.as_deref(), Some("relay.example.com")); + assert_eq!(tls.insecure, Some(true)); + } + + /// The canonical flag wins, and roots from both spellings are kept: each names + /// its own CA, so dropping either would stop trusting one. + #[test] + fn canonical_wins_and_roots_concatenate() { + let tls = parse(&[ + "--connect-tls-root", + "/tmp/new.pem", + "--client-tls-root", + "/tmp/old.pem", + "--connect-tls-host-name", + "new.example.com", + "--client-tls-host-name", + "old.example.com", + ]) + .connect + .resolved(); + + assert_eq!( + tls.root, + vec![PathBuf::from("/tmp/new.pem"), PathBuf::from("/tmp/old.pem")] + ); + assert_eq!(tls.host_name.as_deref(), Some("new.example.com")); + + // Folding an already-folded config changes nothing. + assert_eq!(tls.resolved().root, tls.root); + } + + /// The released served-identity spellings: the bare `--tls-*` flags and the + /// `--server-tls-*` pair, both carrying `MOQ_SERVER_TLS_*`. + #[test] + fn released_listen_spellings_fold_in() { + let tls = parse(&[ + "--tls-cert", + "/tmp/server.pem", + "--tls-key", + "/tmp/server.key", + "--server-tls-generate", + "localhost", + ]) + .listen + .resolved(); + + assert_eq!(tls.cert, vec![PathBuf::from("/tmp/server.pem")]); + assert_eq!(tls.key, vec![PathBuf::from("/tmp/server.key")]); + assert_eq!(tls.generate, vec!["localhost".to_string()]); + } +} diff --git a/rs/moq-native/src/unix.rs b/rs/moq-native/src/unix.rs index ddd8a58f08e..bd589e9df02 100644 --- a/rs/moq-native/src/unix.rs +++ b/rs/moq-native/src/unix.rs @@ -18,16 +18,16 @@ const WIRE_VERSION: qmux::Version = qmux::Version::QMux01; /// Plaintext Unix-socket qmux listener settings, with an optional /// peer-credential allowlist. /// -/// Flattened onto [`crate::ServerConfig::unix`]. +/// Flattened onto [`crate::listen::Config::unix`]. // The derived arg group is named after the struct, so it needs an explicit id to // stay unique across the flattened sections. #[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)] -#[group(id = "server-unix")] +#[group(id = "listen-unix")] #[serde(deny_unknown_fields, default)] #[non_exhaustive] pub struct Config { /// Bind a plaintext qmux Unix-socket listener at this path. - #[arg(long = "server-unix-bind", id = "server-unix-bind", env = "MOQ_SERVER_UNIX_BIND")] + #[arg(long = "listen-unix-bind", id = "listen-unix-bind", env = "MOQ_LISTEN_UNIX_BIND")] #[serde(default, skip_serializing_if = "Option::is_none")] pub bind: Option, @@ -36,6 +36,117 @@ pub struct Config { #[command(flatten)] #[serde(default, skip_serializing_if = "Option::is_none")] pub allow: Option, + + /// The released `--server-unix-*` spellings and their env vars, folded in by + /// [`Config::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, +} + +/// The `--server-unix-*` flags from before the accept side was named `listen`. +/// +/// Separate args rather than clap aliases, since an alias renames the flag but +/// leaves its env var behind. +#[derive(clap::Args, Clone, Debug, Default)] +#[group(id = "listen-unix-legacy")] +pub(crate) struct Legacy { + #[arg( + long = "server-unix-bind", + id = "server-unix-bind", + env = "MOQ_SERVER_UNIX_BIND", + hide = true + )] + bind: Option, + + #[arg( + long = "server-unix-allow-uid", + id = "server-unix-allow-uid", + env = "MOQ_SERVER_UNIX_ALLOW_UID", + value_delimiter = ',', + hide = true + )] + uid: Vec, + + #[arg( + long = "server-unix-allow-gid", + id = "server-unix-allow-gid", + env = "MOQ_SERVER_UNIX_ALLOW_GID", + value_delimiter = ',', + hide = true + )] + gid: Vec, + + #[arg( + long = "server-unix-allow-pid", + id = "server-unix-allow-pid", + env = "MOQ_SERVER_UNIX_ALLOW_PID", + value_delimiter = ',', + hide = true + )] + pid: Vec, +} + +impl Config { + /// Fold the released spellings into the canonical fields. Idempotent. + pub fn resolved(&self) -> Self { + let legacy = &self.legacy; + let mut resolved = self.clone(); + + for (used, deprecated, canonical) in [ + (legacy.bind.is_some(), "--server-unix-bind", "--listen-unix-bind"), + ( + !legacy.uid.is_empty(), + "--server-unix-allow-uid", + "--listen-unix-allow-uid", + ), + ( + !legacy.gid.is_empty(), + "--server-unix-allow-gid", + "--listen-unix-allow-gid", + ), + ( + !legacy.pid.is_empty(), + "--server-unix-allow-pid", + "--listen-unix-allow-pid", + ), + ] { + if used { + tracing::warn!("{deprecated} is deprecated; use {canonical}"); + } + } + + if resolved.bind.is_none() { + resolved.bind = legacy.bind.clone(); + } + + // Merge per credential rather than letting either allowlist win whole. The + // three lists are ANDed, so taking the canonical one entire would drop a + // legacy `uid` next to a canonical `gid` and *widen* access from "that user" + // to "anyone in that group". + let allow = resolved.allow.take().unwrap_or_default(); + let merged = Allow { + uid: concat(&allow.uid, &legacy.uid), + gid: concat(&allow.gid, &legacy.gid), + pid: concat(&allow.pid, &legacy.pid), + }; + // Clap materializes a flattened `Option` to `Some(default)` even when no + // flag was given, so an empty allowlist means unset, not "allow nothing". + resolved.allow = Some(merged).filter(|allow| !allow.is_empty()); + resolved.legacy = Legacy::default(); + resolved + } +} + +/// Both spellings of one credential, in canonical-then-legacy order, deduplicated. +fn concat(canonical: &[T], legacy: &[T]) -> Vec { + let mut out = canonical.to_vec(); + for value in legacy { + if !out.contains(value) { + out.push(value.clone()); + } + } + out } /// Peer-credential allowlist for a `unix://` listener. @@ -44,14 +155,15 @@ pub struct Config { /// constrains the corresponding credential (AND across the three, OR within /// each); all empty means no check. #[derive(clap::Args, Clone, Debug, Default, serde::Serialize, serde::Deserialize)] -#[group(id = "server-unix-allow")] +#[group(id = "listen-unix-allow")] #[serde(deny_unknown_fields, default)] #[non_exhaustive] pub struct Allow { /// Allowed peer user IDs. Empty means any uid. #[arg( - long = "server-unix-allow-uid", - env = "MOQ_SERVER_UNIX_ALLOW_UID", + long = "listen-unix-allow-uid", + id = "listen-unix-allow-uid", + env = "MOQ_LISTEN_UNIX_ALLOW_UID", value_delimiter = ',' )] #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -59,8 +171,9 @@ pub struct Allow { /// Allowed peer group IDs. Empty means any gid. #[arg( - long = "server-unix-allow-gid", - env = "MOQ_SERVER_UNIX_ALLOW_GID", + long = "listen-unix-allow-gid", + id = "listen-unix-allow-gid", + env = "MOQ_LISTEN_UNIX_ALLOW_GID", value_delimiter = ',' )] #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -69,8 +182,9 @@ pub struct Allow { /// Allowed peer PIDs. Empty means any pid; a populated list rejects peers /// whose PID the platform doesn't report. #[arg( - long = "server-unix-allow-pid", - env = "MOQ_SERVER_UNIX_ALLOW_PID", + long = "listen-unix-allow-pid", + id = "listen-unix-allow-pid", + env = "MOQ_LISTEN_UNIX_ALLOW_PID", value_delimiter = ',' )] #[serde(default, skip_serializing_if = "Vec::is_empty")] @@ -287,3 +401,74 @@ impl Drop for Listener { let _ = fs::remove_file(&self.path); } } + +#[cfg(test)] +mod legacy_tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + unix: Config, + } + + fn parse(args: &[&str]) -> Config { + let mut argv = vec!["test"]; + argv.extend_from_slice(args); + Cli::parse_from(argv).unix + } + + /// The released `--server-unix-*` spellings still land in the canonical fields, + /// allowlist included: clap materializes the flattened `Allow` even when unset, + /// so a naive "already Some" check would drop the legacy credentials. + #[test] + fn released_spellings_fold_in() { + let config = parse(&["--server-unix-bind", "/tmp/moq.sock", "--server-unix-allow-uid", "501"]).resolved(); + + assert_eq!(config.bind, Some(PathBuf::from("/tmp/moq.sock"))); + assert_eq!(config.allow.as_ref().map(|allow| allow.uid.clone()), Some(vec![501])); + } + + /// The canonical bind wins, and folding twice changes nothing. + #[test] + fn canonical_wins_over_legacy() { + let config = parse(&[ + "--listen-unix-bind", + "/tmp/new.sock", + "--server-unix-bind", + "/tmp/old.sock", + ]) + .resolved(); + + assert_eq!(config.bind, Some(PathBuf::from("/tmp/new.sock"))); + assert_eq!(config.resolved().bind, config.bind); + } + + /// The allowlist merges per credential instead of letting one spelling win + /// whole. The three lists are ANDed, so dropping the legacy `uid` next to a + /// canonical `gid` would widen access from one user to a whole group. + #[test] + fn allowlist_merges_across_spellings() { + let config = parse(&["--listen-unix-allow-gid", "20", "--server-unix-allow-uid", "501"]).resolved(); + let allow = config.allow.as_ref().expect("allowlist"); + assert_eq!(allow.uid, vec![501]); + assert_eq!(allow.gid, vec![20]); + + // Same credential from both spellings: canonical first, no duplicates. + let config = parse(&["--listen-unix-allow-uid", "1000", "--server-unix-allow-uid", "501,1000"]).resolved(); + assert_eq!(config.allow.as_ref().expect("allowlist").uid, vec![1000, 501]); + + // Folding twice changes nothing. + let once = config.resolved(); + assert_eq!(once.resolved().allow.map(|a| a.uid), once.allow.map(|a| a.uid)); + } + + /// No flag at all leaves the allowlist unset, so the socket's own permissions + /// stay the only gate. + #[test] + fn no_allowlist_stays_unset() { + let config = parse(&["--listen-unix-bind", "/tmp/moq.sock"]).resolved(); + assert!(config.allow.is_none()); + } +} diff --git a/rs/moq-native/src/websocket.rs b/rs/moq-native/src/websocket.rs index 00707b17937..f34995c40f6 100644 --- a/rs/moq-native/src/websocket.rs +++ b/rs/moq-native/src/websocket.rs @@ -2,7 +2,7 @@ //! //! Used when QUIC is unreachable: UDP blocked by a firewall, a proxy in the way, a //! network that only passes TCP/443. The client races this against QUIC and gives QUIC -//! a small head start ([`Client::delay`]), so WebSocket only wins when QUIC can't get +//! a small head start ([`Config::delay`]), so WebSocket only wins when QUIC can't get //! through. Servers accept it on a separate TCP port via [`Listener`]. use qmux::ws::tokio_tungstenite; @@ -21,7 +21,7 @@ pub enum Error { #[error(transparent)] Io(#[from] std::io::Error), - /// WebSocket fallback was turned off via [`Client::enabled`]. + /// WebSocket fallback was turned off via [`Config::enabled`]. #[error("WebSocket support is disabled")] Disabled, @@ -69,36 +69,106 @@ static WEBSOCKET_WON: LazyLock>> = LazyLock::new(|| #[serde(default, deny_unknown_fields)] #[group(id = "websocket-client")] #[non_exhaustive] -pub struct Client { - /// Whether to enable WebSocket support. +#[derive(Default)] +pub struct Config { + /// Whether to enable the WebSocket fallback. Defaults to true. + /// + /// `Option` with the default resolved in code rather than a clap `default_value`, + /// which a config file could not override: the CLI is re-parsed after the file is + /// read, so a materialized default would win. + #[arg( + id = "connect-websocket-enabled", + long = "connect-websocket-enabled", + env = "MOQ_CONNECT_WEBSOCKET_ENABLED", + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), + )] + #[serde(skip_serializing_if = "Option::is_none")] + pub enabled: Option, + + /// Head start given to the QUIC dial before the WebSocket fallback joins the + /// race. Defaults to 200ms, and drops to zero for a server WebSocket already won. + #[arg( + id = "connect-websocket-delay", + long = "connect-websocket-delay", + env = "MOQ_CONNECT_WEBSOCKET_DELAY", + value_parser = humantime::parse_duration, + )] + #[serde(default, with = "humantime_serde::option")] + #[serde(skip_serializing_if = "Option::is_none")] + pub delay: Option, + + /// The released `MOQ_CLIENT_WEBSOCKET_*` env vars, folded in by [`Config::resolved`]. + #[command(flatten)] + #[serde(skip)] + pub(crate) legacy: Legacy, +} + +/// The released spellings for this section, which moved to `--connect-websocket-*` +/// and `MOQ_CONNECT_WEBSOCKET_*` with the rest of the dial side. +/// +/// Separate args rather than clap aliases, since an alias renames the flag but +/// leaves its env var behind. +#[derive(Clone, Debug, Default, clap::Args)] +#[group(id = "websocket-legacy")] +pub(crate) struct Legacy { #[arg( id = "websocket-enabled", long = "websocket-enabled", + alias = "client-websocket-enabled", env = "MOQ_CLIENT_WEBSOCKET_ENABLED", - default_value = "true" + hide = true, + default_missing_value = "true", + num_args = 0..=1, + require_equals = true, + value_parser = clap::value_parser!(bool), )] - pub enabled: bool, + enabled: Option, - /// Delay in milliseconds before attempting WebSocket fallback (default: 200) - /// If WebSocket won the previous race for a given server, this will be 0. #[arg( id = "websocket-delay", long = "websocket-delay", + alias = "client-websocket-delay", env = "MOQ_CLIENT_WEBSOCKET_DELAY", - default_value = "200ms", + hide = true, value_parser = humantime::parse_duration, )] - #[serde(with = "humantime_serde")] - #[serde(skip_serializing_if = "Option::is_none")] - pub delay: Option, + delay: Option, } -impl Default for Client { - fn default() -> Self { - Self { - enabled: true, - delay: Some(time::Duration::from_millis(200)), +/// The QUIC head start when `--connect-websocket-delay` is unset. +const DEFAULT_DELAY: time::Duration = time::Duration::from_millis(200); + +impl Config { + /// Fold the released env vars into the canonical fields. Idempotent. + pub fn resolved(&self) -> Self { + let mut resolved = self.clone(); + if self.enabled.is_none() + && let Some(enabled) = self.legacy.enabled + { + tracing::warn!("--websocket-enabled is deprecated; use --connect-websocket-enabled"); + resolved.enabled = Some(enabled); } + if self.delay.is_none() + && let Some(delay) = self.legacy.delay + { + tracing::warn!("--websocket-delay is deprecated; use --connect-websocket-delay"); + resolved.delay = Some(delay); + } + resolved.legacy = Legacy::default(); + resolved + } + + /// Whether the fallback runs at all, resolving the default. + pub fn resolved_enabled(&self) -> bool { + self.enabled.unwrap_or(true) + } + + /// The head start a QUIC dial gets, resolving the default. + pub fn resolved_delay(&self) -> time::Duration { + self.delay.unwrap_or(DEFAULT_DELAY) } } @@ -106,12 +176,12 @@ impl Default for Client { /// QUIC dial to race against. A WebSocket-only build calls [`connect`] directly. #[cfg(any(feature = "noq", feature = "quinn", feature = "quiche"))] pub(crate) async fn race_handle( - config: &Client, + config: &Config, tls: &rustls::ClientConfig, url: Url, alpns: &[&str], ) -> Option> { - if !config.enabled { + if !config.resolved_enabled() { return None; } @@ -130,12 +200,12 @@ pub(crate) async fn race_handle( } pub(crate) async fn connect( - config: &Client, + config: &Config, tls: &rustls::ClientConfig, mut url: Url, alpns: &[&str], ) -> Result { - if !config.enabled { + if !config.resolved_enabled() { return Err(Error::Disabled); } @@ -150,8 +220,8 @@ pub(crate) async fn connect( // Apply a small penalty to WebSocket to improve odds for QUIC to connect first, // unless we've already had to fall back to WebSockets for this server. // TODO if let chain - match config.delay { - Some(delay) if !WEBSOCKET_WON.lock().unwrap().contains(&key) => { + match config.resolved_delay() { + delay if !delay.is_zero() && !WEBSOCKET_WON.lock().unwrap().contains(&key) => { tokio::time::sleep(delay).await; tracing::debug!(peer = %crate::connect::Endpoint(&url), delay_ms = %delay.as_millis(), "QUIC not yet connected, attempting WebSocket fallback"); } @@ -478,3 +548,40 @@ mod tests { } } } + +#[cfg(test)] +mod legacy_tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[command(flatten)] + websocket: Config, + } + + fn parse(args: &[&str]) -> Config { + let mut argv = vec!["test"]; + argv.extend_from_slice(args); + Cli::parse_from(argv).websocket + } + + /// The released env vars have hidden flags of their own; both spellings feed the + /// same fields once folded. + #[test] + fn released_spellings_fold_in() { + let config = parse(&["--websocket-enabled=false", "--client-websocket-delay", "1s"]).resolved(); + assert!(!config.resolved_enabled()); + assert_eq!(config.resolved_delay(), time::Duration::from_secs(1)); + + // The canonical spelling wins. + let config = parse(&["--connect-websocket-delay", "2s", "--websocket-delay", "1s"]).resolved(); + assert_eq!(config.resolved_delay(), time::Duration::from_secs(2)); + assert!(config.resolved_enabled(), "unset means the default (enabled)"); + + // Neither given: the defaults, which no config file can be clobbered out of. + let config = parse(&[]).resolved(); + assert_eq!(config.delay, None); + assert_eq!(config.resolved_delay(), DEFAULT_DELAY); + } +} diff --git a/rs/moq-native/tests/alpn.rs b/rs/moq-native/tests/alpn.rs index 52e63ff899b..7bb85d5b4c4 100644 --- a/rs/moq-native/tests/alpn.rs +++ b/rs/moq-native/tests/alpn.rs @@ -14,12 +14,12 @@ async fn connect_with_version(version: &str) { let version: moq_native::moq_net::Version = version.parse().expect("invalid version"); // ── server ────────────────────────────────────────────────────── - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec![version]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); @@ -27,11 +27,11 @@ async fn connect_with_version(version: &str) { let origin = moq_native::moq_net::Origin::random().produce(); // ── client ────────────────────────────────────────────────────── - let mut client_config = moq_native::ClientConfig::default(); + let mut client_config = moq_native::connect::Config::default(); client_config.version = vec![version]; - client_config.tls.disable_verify = Some(true); + client_config.tls.insecure = Some(true); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); // Use raw QUIC URL so ALPN negotiation is direct (no WebTransport framing). let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); @@ -64,27 +64,27 @@ async fn connect_with_webtransport(version: Option<&str>) { let version: Option = version.map(|v| v.parse().expect("invalid version")); // ── server ────────────────────────────────────────────────────── - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; if let Some(v) = version { server_config.version = vec![v]; } - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); let origin = moq_native::moq_net::Origin::random().produce(); // ── client ────────────────────────────────────────────────────── - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); if let Some(v) = version { client_config.version = vec![v]; } - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); // Use https:// URL to trigger the WebTransport path. let url: url::Url = format!("https://localhost:{}", addr.port()).parse().unwrap(); diff --git a/rs/moq-native/tests/backend.rs b/rs/moq-native/tests/backend.rs index e629f2eac57..651b6c43d09 100644 --- a/rs/moq-native/tests/backend.rs +++ b/rs/moq-native/tests/backend.rs @@ -116,13 +116,14 @@ async fn connect_test(config: ConnectTest<'_>) { .expect("failed to write frame"); group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some(bind.to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.backend = Some(backend.clone()); - server_config.quic.qlog = qlog.map(Into::into); + let mut quic = moq_native::quic::Config::default(); + quic.qlog = qlog.map(Into::into); - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(quic.clone()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); @@ -130,15 +131,16 @@ async fn connect_test(config: ConnectTest<'_>) { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.backend = Some(backend); - client_config.quic.qlog = qlog.map(Into::into); + let mut quic = moq_native::quic::Config::default(); + quic.qlog = qlog.map(Into::into); // Bind the client to the same address family as the server so an IPv4 dial // doesn't try to egress from an IPv6 socket (and vice versa). - client_config.bind = client_bind.unwrap_or(bind).parse().expect("invalid bind address"); + client_config.bind = Some(client_bind.unwrap_or(bind).parse().expect("invalid bind address")); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(quic.clone()).expect("failed to init client"); let url: url::Url = format!("{scheme}://{authority}:{}{path}", addr.port()).parse().unwrap(); let expect_query = path.split_once('?').map(|(_, query)| query.to_string()); @@ -279,31 +281,30 @@ async fn mtls_test(scheme: &str, backend: moq_native::QuicBackend, reject: bool) let pub_origin = Origin::random().produce(); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("127.0.0.1:0".to_string()); server_config.tls.cert = vec![paths.server_cert.clone()]; server_config.tls.key = vec![paths.server_key.clone()]; server_config.tls.root = vec![paths.ca.clone()]; server_config.backend = Some(backend.clone()); - server_config.quic.gso = Some(false); - server_config.quic.keep_alive = Some(Duration::from_secs(1)); + // One shared tuning, handed to both roles the way a binary would. + let mut quic = moq_native::quic::Config::default(); + quic.gso = Some(false); + quic.keep_alive = Some(Duration::from_secs(1)); - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(quic.clone()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); - let mut client_config = moq_native::ClientConfig::default(); + let mut client_config = moq_native::connect::Config::default(); client_config.tls.root = vec![paths.ca.clone()]; client_config.tls.system_roots = Some(false); client_config.tls.cert = Some(paths.client_cert.clone()); client_config.tls.key = Some(paths.client_key.clone()); client_config.tls.host_name = Some("localhost".to_string()); client_config.backend = Some(backend); - client_config.bind = "0.0.0.0:0".parse().unwrap(); - client_config.quic.gso = Some(false); - client_config.quic.keep_alive = Some(Duration::from_secs(1)); - - let client = client_config.init().expect("failed to init client"); + client_config.bind = Some("0.0.0.0:0".parse().unwrap()); + let client = client_config.init(quic.clone()).expect("failed to init client"); // Dial the IP while verifying the certificate's localhost SAN. This covers // the independent TLS hostname override alongside client authentication. let url: url::Url = format!("{scheme}://127.0.0.1:{}", addr.port()).parse().unwrap(); @@ -481,7 +482,7 @@ async fn iroh_connect() { let mut server_iroh_config = EndpointConfig::default(); server_iroh_config.enabled = Some(true); let server_endpoint = server_iroh_config - .bind(&moq_native::quic::Client::default()) + .bind(&moq_native::quic::Config::default()) .await .expect("failed to bind server iroh endpoint") .expect("server iroh endpoint not enabled"); @@ -493,12 +494,12 @@ async fn iroh_connect() { let server_endpoint_id = server_endpoint.id(); // Server still needs a QUIC bind for init, but we'll connect via iroh - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; let server = server_config - .init() + .init(Default::default()) .expect("failed to init server") .with_iroh(server_endpoint); let mut server = server.listen().await.expect("failed to listen"); @@ -511,16 +512,16 @@ async fn iroh_connect() { let mut client_iroh_config = EndpointConfig::default(); client_iroh_config.enabled = Some(true); let client_endpoint = client_iroh_config - .bind(&moq_native::quic::Client::default()) + .bind(&moq_native::quic::Config::default()) .await .expect("failed to bind client iroh endpoint") .expect("client iroh endpoint not enabled"); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); let client = client_config - .init() + .init(Default::default()) .expect("failed to init client") .with_iroh(client_endpoint) .with_iroh_addrs(server_addrs); diff --git a/rs/moq-native/tests/broadcast.rs b/rs/moq-native/tests/broadcast.rs index 4012b8bc037..d26651c91fe 100644 --- a/rs/moq-native/tests/broadcast.rs +++ b/rs/moq-native/tests/broadcast.rs @@ -36,14 +36,14 @@ async fn broadcast_test(scheme: &str, client_version: Option<&str>, server_versi .expect("failed to write frame"); group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; if let Some(v) = server_version { server_config.version = vec![v]; } - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); @@ -51,13 +51,13 @@ async fn broadcast_test(scheme: &str, client_version: Option<&str>, server_versi let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); if let Some(v) = client_version { client_config.version = vec![v]; } - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("{scheme}://localhost:{}", addr.port()).parse().unwrap(); // ── run server and client concurrently ────────────────────────── @@ -158,21 +158,21 @@ async fn lite05_timestamp_roundtrip(scheme: &str) { } group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-05".parse().unwrap()]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-05".parse().unwrap()]; - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("{scheme}://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -276,21 +276,21 @@ async fn lite05_fetch_roundtrip(scheme: &str) { } group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-05".parse().unwrap()]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-05".parse().unwrap()]; - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("{scheme}://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -401,21 +401,21 @@ async fn lite05_fetch_during_subscribe(scheme: &str) { w.finish().expect("finish frame 1"); group1.finish().expect("finish group 1"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-05".parse().unwrap()]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-05".parse().unwrap()]; - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("{scheme}://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -509,21 +509,21 @@ async fn broadcast_moq_lite_05_default_timescale() { .expect("write frame"); group.finish().expect("finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-05".parse().unwrap()]; - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("local addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-05".parse().unwrap()]; - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("https://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -599,21 +599,21 @@ async fn broadcast_moq_lite_06_announce_lifecycle() { .create_broadcast("first", moq_net::broadcast::Route::new().with_announce(true)) .expect("create broadcast"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-06-wip".parse().unwrap()]; - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("local addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-06-wip".parse().unwrap()]; - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let server_origin = pub_origin.clone(); @@ -769,16 +769,16 @@ async fn broadcast_route_migration() { group.finish().expect("finish group"); } let server_a = { - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.bind = Some("[::]:0".to_string()); config.tls.generate = vec!["localhost".into()]; - config.init().expect("init server a") + config.init(Default::default()).expect("init server a") }; let server_b = { - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.bind = Some("[::]:0".to_string()); config.tls.generate = vec!["localhost".into()]; - config.init().expect("init server b") + config.init(Default::default()).expect("init server b") }; let mut server_a = server_a.listen().await.expect("listen a"); let mut server_b = server_b.listen().await.expect("listen b"); @@ -807,9 +807,9 @@ async fn broadcast_route_migration() { let mut announcements = sub_origin.consume().announced(); let connect = |port: u16, sub: moq_net::origin::Producer| { - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(true); - let client = config.init().expect("init client"); + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(true); + let client = config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{port}").parse().unwrap(); async move { tokio::time::timeout(TIMEOUT, connect_once(client.with_subscriber(sub), url)) @@ -892,13 +892,13 @@ async fn route_reannounce_test(version: Option<&str>) { group.write_frame(Timestamp::ZERO, b"g0".as_ref()).expect("write frame"); group.finish().expect("finish group"); } - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; if let Some(v) = version { server_config.version = vec![v]; } - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("local addr"); @@ -917,12 +917,12 @@ async fn route_reannounce_test(version: Option<&str>) { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); if let Some(v) = version { client_config.version = vec![v]; } - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let (_client, connection) = tokio::time::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) .await @@ -1029,13 +1029,13 @@ async fn route_replaced_test(version: Option<&str>) { group.write_frame(Timestamp::ZERO, b"g0".as_ref()).expect("write frame"); group.finish().expect("finish group"); } - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; if let Some(v) = version { server_config.version = vec![v]; } - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("local addr"); @@ -1053,12 +1053,12 @@ async fn route_replaced_test(version: Option<&str>) { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); if let Some(v) = version { client_config.version = vec![v]; } - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let (_client, connection) = tokio::time::timeout(TIMEOUT, connect_once(client.with_subscriber(sub_origin), url)) .await @@ -1317,11 +1317,11 @@ async fn latency_max_test(version: &str) -> Duration { let info = moq_net::track::Info::default().with_latency_max(LATENCY_PUBLISHED); let track = broadcast.create_track("video", info).expect("create track"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec![version]; - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("local addr"); @@ -1342,10 +1342,10 @@ async fn latency_max_test(version: &str) -> Duration { .produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec![version]; - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); // Reconnecting off: the assertions below are written against a single dial, and // a background redial would re-announce behind them. @@ -1604,7 +1604,7 @@ async fn broadcast_websocket() { group.finish().expect("failed to finish group"); // Server with both QUIC (required) and WebSocket listeners. - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; @@ -1614,7 +1614,7 @@ async fn broadcast_websocket() { let ws_addr = ws_listener.local_addr().expect("failed to get ws addr"); let server = server_config - .init() + .init(Default::default()) .expect("failed to init server") .with_websocket(ws_listener); let mut server = server.listen().await.expect("failed to listen"); @@ -1623,12 +1623,12 @@ async fn broadcast_websocket() { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Disable WebSocket delay so client connects immediately via ws:// - client_config.websocket.delay = None; + client_config.websocket.delay = Some(std::time::Duration::ZERO); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); // ── run server and client concurrently ────────────────────────── @@ -1716,7 +1716,7 @@ async fn broadcast_websocket_fallback() { group.finish().expect("failed to finish group"); // QUIC binds on its own port; WebSocket on a different port. - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; @@ -1726,7 +1726,7 @@ async fn broadcast_websocket_fallback() { let ws_addr = ws_listener.local_addr().expect("failed to get ws addr"); let server = server_config - .init() + .init(Default::default()) .expect("failed to init server") .with_websocket(ws_listener); let mut server = server.listen().await.expect("failed to listen"); @@ -1735,12 +1735,12 @@ async fn broadcast_websocket_fallback() { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // No delay. Race QUIC and WebSocket simultaneously. - client_config.websocket.delay = None; + client_config.websocket.delay = Some(std::time::Duration::ZERO); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); // Connect via http:// to the WebSocket port. // QUIC will try UDP on this port and fail; WebSocket will try ws:// and succeed. @@ -1837,7 +1837,7 @@ async fn broadcast_websocket_uses_newest_version() { .expect("failed to write frame"); group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; @@ -1847,17 +1847,17 @@ async fn broadcast_websocket_uses_newest_version() { let ws_addr = ws_listener.local_addr().expect("failed to get ws addr"); let server = server_config - .init() + .init(Default::default()) .expect("failed to init server") .with_websocket(ws_listener); let mut server = server.listen().await.expect("failed to listen"); let sub_origin = Origin::random().produce(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); - client_config.websocket.delay = None; + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); + client_config.websocket.delay = Some(std::time::Duration::ZERO); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://localhost:{}", ws_addr.port()).parse().unwrap(); let expected_version: moq_net::Version = NEWEST_LITE.parse().expect("invalid version"); @@ -1916,23 +1916,23 @@ async fn broadcast_race_quic_wins() { .expect("failed to bind WebSocket listener"); let port = ws_listener.local_addr().expect("failed to get ws addr").port(); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some(format!("[::]:{port}")); server_config.tls.generate = vec!["localhost".into()]; let server = server_config - .init() + .init(Default::default()) .expect("failed to init server") .with_websocket(ws_listener); let mut server = server.listen().await.expect("failed to listen"); let sub_origin = Origin::random().produce(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Zero head start: QUIC has to win on its own merit, not by penalising WS. - client_config.websocket.delay = None; + client_config.websocket.delay = Some(std::time::Duration::ZERO); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("https://localhost:{port}").parse().unwrap(); let expected_version: moq_net::Version = NEWEST_LITE.parse().expect("invalid version"); @@ -1992,21 +1992,21 @@ async fn resubscribe_keeps_flowing_moq_lite_03() { .expect("write frame 0"); group0.finish().expect("finish group 0"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec!["moq-lite-03".parse().unwrap()]; - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("server addr"); let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec!["moq-lite-03".parse().unwrap()]; - let client = client_config.init().expect("init client"); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -2124,10 +2124,10 @@ async fn idle_subscription_releases_the_viewer_count() { .expect("write frame"); group.finish().expect("finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; - let server = server_config.init().expect("init server"); + let server = server_config.init(Default::default()).expect("init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("server addr"); @@ -2138,9 +2138,9 @@ async fn idle_subscription_releases_the_viewer_count() { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); - let client = client_config.init().expect("init client"); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); + let client = client_config.init(Default::default()).expect("init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -2223,9 +2223,9 @@ async fn websocket_unauthorized_handshake_is_explicit() { Ok::<_, anyhow::Error>(()) }); - let mut client_config = moq_native::ClientConfig::default(); - client_config.websocket.delay = None; - let client = client_config.init().expect("failed to init client"); + let mut client_config = moq_native::connect::Config::default(); + client_config.websocket.delay = Some(std::time::Duration::ZERO); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); let err = tokio::time::timeout(TIMEOUT, connect_once(client, url)) @@ -2260,9 +2260,9 @@ async fn reconnect_stops_on_websocket_unauthorized() { Ok::<_, anyhow::Error>(()) }); - let mut client_config = moq_native::ClientConfig::default(); - client_config.websocket.delay = None; - let client = client_config.init().expect("failed to init client"); + let mut client_config = moq_native::connect::Config::default(); + client_config.websocket.delay = Some(std::time::Duration::ZERO); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("ws://{addr}").parse().unwrap(); let reconnect = client.connect(url); @@ -2347,12 +2347,12 @@ async fn one_shot_connect_surfaces_the_session_close() { Ok::<_, anyhow::Error>(()) }); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); - client_config.reconnect = Some(false); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); + client_config.once = Some(true); // A tiny backoff so a buggy redial happens well within the sleep below. client_config.backoff.initial = Some(Duration::from_millis(10)); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let connection = tokio::time::timeout(TIMEOUT, client.connect(url).established()) .await @@ -2410,12 +2410,12 @@ async fn a_dead_session_unannounces_while_the_reconnect_retries() { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Retry forever with a fast cadence: the worst case for a stale announce. client_config.backoff.initial = Some(Duration::from_millis(10)); client_config.backoff.timeout = Some(Duration::ZERO); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let connection = tokio::time::timeout(TIMEOUT, client.with_subscriber(sub_origin).connect(url).established()) .await @@ -2620,10 +2620,10 @@ async fn publish_only_client_to_subscribe_only_server() { /// A test server bound to a free port with a generated localhost certificate. async fn test_server() -> (moq_native::Listener, std::net::SocketAddr) { - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.bind = Some("[::]:0".to_string()); config.tls.generate = vec!["localhost".into()]; - let server = config.init().expect("failed to init server"); + let server = config.init(Default::default()).expect("failed to init server"); let server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); (server, addr) @@ -2631,9 +2631,9 @@ async fn test_server() -> (moq_native::Listener, std::net::SocketAddr) { /// A test client that skips TLS verification (servers use self-signed certs). fn test_client() -> moq_native::Client { - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(true); - config.init().expect("failed to init client") + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(true); + config.init(Default::default()).expect("failed to init client") } fn assert_connect_error(err: &moq_native::Error, expected: moq_native::ConnectError) { @@ -2672,12 +2672,12 @@ async fn goaway_test(scheme: &str, version: &str, expect_wire_timeout: bool) { .expect("failed to write frame"); group.finish().expect("failed to finish group"); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec![version]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); @@ -2685,10 +2685,10 @@ async fn goaway_test(scheme: &str, version: &str, expect_wire_timeout: bool) { let sub_origin = Origin::random().produce(); let mut announcements = sub_origin.consume().announced(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec![version]; - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("{scheme}://localhost:{}", addr.port()).parse().unwrap(); // The server accepts one session, waits for the signal, then drains it @@ -2810,18 +2810,18 @@ async fn goaway_timeout_force_close_moq_transport_19_quic() { let pub_origin = Origin::random().produce(); - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; server_config.version = vec![version]; - let server = server_config.init().expect("failed to init server"); + let server = server_config.init(Default::default()).expect("failed to init server"); let mut server = server.listen().await.expect("failed to listen"); let addr = server.local_addr().expect("failed to get local addr"); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.version = vec![version]; - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let url: url::Url = format!("moqt://localhost:{}", addr.port()).parse().unwrap(); let server_handle = tokio::spawn(async move { @@ -2905,11 +2905,11 @@ async fn zero_initial_backoff_still_gives_up_on_a_flapping_peer() { Ok::<_, anyhow::Error>(()) }); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.backoff.initial = Some(Duration::ZERO); client_config.backoff.timeout = Some(Duration::from_millis(500)); - let client = client_config.init().expect("failed to init client"); + let client = client_config.init(Default::default()).expect("failed to init client"); let connection = client.connect(url); tokio::time::timeout(TIMEOUT, connection.closed()) diff --git a/rs/moq-native/tests/reconnect.rs b/rs/moq-native/tests/reconnect.rs index e7aafe8888b..9e4d2a1fdaf 100644 --- a/rs/moq-native/tests/reconnect.rs +++ b/rs/moq-native/tests/reconnect.rs @@ -10,9 +10,9 @@ use std::time::Duration; /// A client whose reconnect loop escalates fast enough to assert on inside a test. fn client(backoff: moq_native::Backoff) -> moq_native::Client { - let mut config = moq_native::ClientConfig::default(); + let mut config = moq_native::connect::Config::default(); config.backoff = backoff; - config.init().expect("failed to init client") + config.init(Default::default()).expect("failed to init client") } /// A transient failure is retried, escalating, until the budget runs out. The give-up error names diff --git a/rs/moq-relay/fly.toml b/rs/moq-relay/fly.toml index 63e454469c0..e26906bb6bb 100644 --- a/rs/moq-relay/fly.toml +++ b/rs/moq-relay/fly.toml @@ -16,7 +16,7 @@ port = 443 # Environment variables [env] # NOTE: A dedicated IPv4 address is required for UDP. -MOQ_SERVER_BIND = "fly-global-services:443" +MOQ_LISTEN = "fly-global-services:443" # Resource allocation per region [[vm]] diff --git a/rs/moq-relay/src/auth.rs b/rs/moq-relay/src/auth.rs index a739e837a66..519926d5259 100644 --- a/rs/moq-relay/src/auth.rs +++ b/rs/moq-relay/src/auth.rs @@ -203,7 +203,7 @@ impl axum::response::IntoResponse for AuthError { } /// Deprecated `--auth-tls-*` overrides, kept for backwards compatibility. The -/// auth client otherwise reuses the cluster client's `--client-tls-*` config. +/// auth client otherwise reuses the cluster client's `--connect-tls-*` config. /// Hidden from `--help`; setting any field logs a deprecation warning. #[doc(hidden)] #[serde_as] @@ -240,25 +240,25 @@ pub struct AuthTls { impl AuthTls { /// True when any deprecated `--auth-tls-*` override is configured, in which - /// case it takes precedence over the shared `--client-tls-*` identity. + /// case it takes precedence over the shared `--connect-tls-*` identity. fn is_set(&self) -> bool { !self.root.is_empty() || self.cert.is_some() || self.key.is_some() || self.disable_verify.is_some() } - /// Convert into a [`moq_native::tls::Client`] so we can reuse its + /// Convert into a [`moq_native::tls::Connect`] so we can reuse its /// rustls-building logic. The fields map one-to-one. - fn to_client_tls(&self) -> anyhow::Result { + fn to_client_tls(&self) -> anyhow::Result { match (&self.cert, &self.key) { (Some(_), None) => anyhow::bail!("--auth-tls-cert requires --auth-tls-key"), (None, Some(_)) => anyhow::bail!("--auth-tls-key requires --auth-tls-cert"), _ => {} } - let mut tls = moq_native::tls::Client::default(); + let mut tls = moq_native::tls::Connect::default(); tls.root = self.root.clone(); tls.cert = self.cert.clone(); tls.key = self.key.clone(); - tls.disable_verify = self.disable_verify; + tls.insecure = self.disable_verify; Ok(tls) } } @@ -291,11 +291,11 @@ pub struct AuthConfig { pub tls: AuthTls, /// Cluster client TLS injected by [`AuthConfig::init`] so outbound auth HTTP - /// (JWK + auth/public-API fetches) reuses the `--client-tls-*` identity. + /// (JWK + auth/public-API fetches) reuses the `--connect-tls-*` identity. /// Not a CLI or TOML field; the deprecated `--auth-tls-*` flags override it. #[arg(skip)] #[serde(skip)] - client_tls: Option, + client_tls: Option, /// Public (unauthenticated) access configuration. /// @@ -581,10 +581,10 @@ impl PublicAccess { impl AuthConfig { /// Initializes an [`Auth`] instance from this configuration. /// - /// `client_tls` is the cluster client TLS (`--client-tls-*`); the auth client + /// `client_tls` is the cluster client TLS (`--connect-tls-*`); the auth client /// reuses it for outbound HTTP unless the deprecated `--auth-tls-*` flags are /// set. - pub async fn init(mut self, client_tls: &moq_native::tls::Client) -> anyhow::Result { + pub async fn init(mut self, client_tls: &moq_native::tls::Connect) -> anyhow::Result { self.client_tls = Some(client_tls.clone()); Auth::new(self).await } @@ -2728,7 +2728,7 @@ api = "https://api.example.com/access" // New path: the identity is supplied via the shared --client-tls-* config // (injected through AuthConfig::init) instead of the deprecated // --auth-tls-* flags. The server accepts it the same way. - let mut client_tls = moq_native::tls::Client::default(); + let mut client_tls = moq_native::tls::Connect::default(); client_tls.root = vec![fx.ca_pem_path.clone()]; client_tls.cert = Some(fx.client_cert_path.clone()); client_tls.key = Some(fx.client_key_path.clone()); diff --git a/rs/moq-relay/src/config.rs b/rs/moq-relay/src/config.rs index 0e73cd8de85..6f047999ea6 100644 --- a/rs/moq-relay/src/config.rs +++ b/rs/moq-relay/src/config.rs @@ -15,12 +15,20 @@ pub struct Config { /// The QUIC/TLS configuration for the server. #[command(flatten)] #[serde(default)] - pub server: moq_native::ServerConfig, + #[serde(alias = "server")] + pub listen: moq_native::listen::Config, /// The QUIC/TLS configuration for the client. (clustering only) #[command(flatten)] #[serde(default)] - pub client: moq_native::ClientConfig, + #[serde(alias = "client")] + pub connect: moq_native::connect::Config, + + /// QUIC transport tuning (`--quic-*`), shared by the dial and accept sides: + /// these knobs mean the same thing whichever way the connection was opened. + #[command(flatten)] + #[serde(default)] + pub quic: moq_native::quic::Config, /// Log configuration. #[command(flatten)] @@ -125,11 +133,197 @@ impl Config { } } +impl Config { + /// Fold every released spelling in, then apply the relay's own defaults. + /// + /// Order matters: `--server-quic-max-streams` lands on the hidden legacy arg, and + /// filling in [`crate::DEFAULT_MAX_STREAMS`] first would give the fold a canonical + /// value to prefer, silently discarding what the deployment asked for. + pub(crate) fn resolve(&mut self) { + // The released config file spelled this per role, under `[client.quic]` and + // `[server.quic]`. Both now feed the one shared section, as the lowest + // precedence source: a flag or env var has to outrank a config file, so the + // legacy flags fold into the canonical fields *first* and these only fill + // what is still unset. Between the two roles the dial side wins, matching + // how the `--client-quic-*` / `--server-quic-*` flags fold. + let per_role = [self.connect.take_quic(), self.listen.take_quic()]; + + self.quic = self.quic.resolved(); + for legacy in per_role.into_iter().flatten() { + self.quic = self.quic.or(&legacy); + } + self.listen = self.listen.resolved(); + self.connect = self.connect.resolved(); + + self.quic.max_streams.get_or_insert(crate::DEFAULT_MAX_STREAMS); + } +} + #[cfg(test)] mod tests { use super::*; use crate::test_env::EnvGuard; + /// A released `--server-quic-max-streams` must survive the relay's own default. + /// + /// The fold prefers the canonical field, so defaulting before folding would pin + /// every deployment that still uses the old spelling to 10,000 streams. + #[test] + fn released_max_streams_survives_the_relay_default() { + let _env = EnvGuard::clear(&["MOQ_QUIC_MAX_STREAMS", "MOQ_SERVER_QUIC_MAX_STREAMS"]); + + let mut config = Config::parse_from(["moq-relay", "--server-quic-max-streams", "4096"]); + config.resolve(); + assert_eq!(config.quic.max_streams, Some(4096)); + + let mut config = Config::parse_from(["moq-relay"]); + config.resolve(); + assert_eq!(config.quic.max_streams, Some(crate::DEFAULT_MAX_STREAMS)); + } + + /// The released `--server-*` accept-side spellings reach the fields the + /// listeners actually read. + #[test] + fn released_listen_spellings_reach_the_listener() { + let _env = EnvGuard::clear(&[ + "MOQ_LISTEN", + "MOQ_SERVER_BIND", + "MOQ_LISTEN_TLS_CERT", + "MOQ_SERVER_TLS_CERT", + ]); + + let mut config = Config::parse_from([ + "moq-relay", + "--server-bind", + "[::]:4443", + "--server-tls-cert", + "/tmp/cert.pem", + "--server-tls-key", + "/tmp/cert.key", + ]); + config.resolve(); + + assert_eq!(config.listen.bind.as_deref(), Some("[::]:4443")); + assert_eq!(config.listen.tls.cert, vec![std::path::PathBuf::from("/tmp/cert.pem")]); + assert_eq!(config.listen.tls.key, vec![std::path::PathBuf::from("/tmp/cert.key")]); + } + + /// A released config file that spelled QUIC tuning per role still boots. + /// + /// A move across tables is the one thing serde aliases cannot express, so + /// `[client.quic]` / `[server.quic]` are parsed where they used to live and + /// folded into the shared section, rather than failing at startup with + /// `unknown field quic`. + #[test] + fn released_per_role_quic_tables_fold_into_the_shared_one() { + let toml = r#" +[server] +listen = "[::]:443" + +[server.quic] +max_streams = 4096 +keep_alive = "9s" + +[client.quic] +max_streams = 64 +"#; + let mut config: Config = toml::from_str(toml).expect("released config must still parse"); + config.resolve(); + + // The dial side wins where both set a knob, as the flags do; the accept side + // still contributes what only it set. + assert_eq!(config.quic.max_streams, Some(64)); + assert_eq!(config.quic.keep_alive, Some(Duration::from_secs(9))); + assert_eq!(config.listen.bind.as_deref(), Some("[::]:443")); + } + + /// A released config survives a serialize/deserialize round trip before it is + /// resolved, so a caller that normalizes a config file does not silently drop + /// the per-role tables. Once resolved they are `None`, and nothing re-emits a + /// deprecated table. + #[test] + fn released_quic_tables_survive_a_round_trip() { + let config: Config = toml::from_str("[client.quic]\nmax_streams = 64\n").expect("parse"); + + let round_tripped: Config = toml::from_str(&toml::to_string(&config).expect("serialize")).expect("reparse"); + let mut round_tripped = round_tripped; + round_tripped.resolve(); + assert_eq!(round_tripped.quic.max_streams, Some(64)); + + // Resolving first drops the deprecated table rather than re-emitting it. + let mut config = config; + config.resolve(); + assert!(config.connect.quic.is_none()); + assert!(!toml::to_string(&config).expect("serialize").contains("[client.quic]")); + } + + /// A flag outranks a config file, including when both are the released spelling. + #[test] + fn released_quic_flag_beats_the_released_quic_table() { + let _env = EnvGuard::clear(&["MOQ_QUIC_MAX_STREAMS", "MOQ_CLIENT_QUIC_MAX_STREAMS"]); + + let toml = r#" +[client.quic] +max_streams = 64 +"#; + let dir = std::env::temp_dir().join("moq-relay-config-test"); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("legacy-quic.toml"); + std::fs::write(&path, toml).unwrap(); + + let args = vec![ + std::ffi::OsString::from("moq-relay"), + std::ffi::OsString::from(&path), + std::ffi::OsString::from("--client-quic-max-streams"), + std::ffi::OsString::from("128"), + ]; + let mut config = Config::parse_and_merge(args).expect("config load"); + config.resolve(); + + assert_eq!( + config.quic.max_streams, + Some(128), + "the flag must win over the config file it shares a spelling with" + ); + } + + /// The canonical top-level table wins over a released per-role one. + #[test] + fn shared_quic_table_wins_over_the_released_tables() { + let toml = r#" +[quic] +max_streams = 128 + +[server.quic] +max_streams = 4096 +"#; + let mut config: Config = toml::from_str(toml).expect("parse"); + config.resolve(); + assert_eq!(config.quic.max_streams, Some(128)); + } + + /// Every config under `demo/relay/` still parses. + /// + /// These are the configs a reader copies, and a rename that lands in the code + /// but not in them is invisible until someone's relay refuses to boot. A move + /// across tables (`[server.quic]` to a top-level `[quic]`) is the case serde + /// aliases cannot cover, which is exactly why this reads the real files. + #[test] + fn demo_configs_parse() { + let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../demo/relay"); + let mut checked = 0; + for entry in std::fs::read_dir(&dir).expect("demo/relay") { + let path = entry.expect("dir entry").path(); + if path.extension().is_none_or(|ext| ext != "toml") { + continue; + } + let toml = std::fs::read_to_string(&path).expect("read config"); + toml::from_str::(&toml).unwrap_or_else(|err| panic!("{}: {err}", path.display())); + checked += 1; + } + assert!(checked > 0, "no demo configs found in {}", dir.display()); + } + /// Regression test for the clap+TOML interaction documented on /// `Config::parse_and_merge`. A TOML file that enables stats with no /// overriding CLI flag must still produce `stats.enabled == Some(true)`. @@ -253,7 +447,7 @@ linger = "30s" } /// Regression test for the same clap+TOML clobber bug applied to the - /// `preferred_v4` / `preferred_v6` fields on `moq-native::ServerConfig`. + /// `preferred_v4` / `preferred_v6` fields on `moq_native::listen::Config`. /// If either field is ever re-typed as a bare `SocketAddrV4` / `SocketAddrV6` /// (without `Option<>`), the CLI re-parse will overwrite the TOML value /// with `Default::default()` and silently disable the @@ -261,10 +455,12 @@ linger = "30s" /// TOML. This test asserts the TOML value survives an absent CLI flag. #[test] fn cli_does_not_clobber_toml_preferred_addresses() { - let _env = EnvGuard::clear(&["MOQ_SERVER_PREFERRED_V4", "MOQ_SERVER_PREFERRED_V6"]); + let _env = EnvGuard::clear(&["MOQ_LISTEN_PREFERRED_V4", "MOQ_LISTEN_PREFERRED_V6"]); + // They are accept-only, so they live on `[listen]` rather than in the + // shared `[listen.quic]` tuning. let toml = r#" -[server.quic] +[listen] preferred_v4 = "192.0.2.1:443" preferred_v6 = "[2001:db8::1]:443" "#; @@ -277,14 +473,14 @@ preferred_v6 = "[2001:db8::1]:443" let config = Config::parse_and_merge(args).expect("config load"); assert_eq!( - config.server.quic.preferred_v4, + config.listen.preferred_v4, Some("192.0.2.1:443".parse().unwrap()), - "TOML's server.quic.preferred_v4 must not be clobbered by the CLI re-parse" + "TOML's listen.preferred_v4 must not be clobbered by the CLI re-parse" ); assert_eq!( - config.server.quic.preferred_v6, + config.listen.preferred_v6, Some("[2001:db8::1]:443".parse().unwrap()), - "TOML's server.quic.preferred_v6 must not be clobbered by the CLI re-parse" + "TOML's listen.preferred_v6 must not be clobbered by the CLI re-parse" ); } @@ -295,7 +491,7 @@ preferred_v6 = "[2001:db8::1]:443" let _env = EnvGuard::clear(&["MOQ_SERVER_QUIC_QLOG"]); let toml = r#" -[server.quic] +[quic] qlog = "/tmp/moq-qlog" "#; let dir = std::env::temp_dir().join("moq-relay-config-test"); @@ -307,9 +503,9 @@ qlog = "/tmp/moq-qlog" let config = Config::parse_and_merge(args).expect("config load"); assert_eq!( - config.server.quic.qlog.as_deref(), + config.quic.qlog.as_deref(), Some(std::path::Path::new("/tmp/moq-qlog")), - "TOML's server.quic.qlog must not be clobbered by the CLI re-parse" + "TOML's quic.qlog must not be clobbered by the CLI re-parse" ); } @@ -326,11 +522,8 @@ qlog = "/tmp/moq-qlog" ]); let toml = r#" -[server.quic] +[quic] congestion_control = "delay" - -[client.quic] -congestion_control = "loss" "#; let dir = std::env::temp_dir().join("moq-relay-config-test"); std::fs::create_dir_all(&dir).unwrap(); @@ -340,15 +533,12 @@ congestion_control = "loss" let args = vec![std::ffi::OsString::from("moq-relay"), std::ffi::OsString::from(&path)]; let config = Config::parse_and_merge(args).expect("config load"); + // One value, shared by the dial and accept sides: the knob means the same + // thing whichever way the connection was opened. assert_eq!( - config.server.quic.congestion_control, + config.quic.congestion_control, Some(moq_native::quic::CongestionControl::Delay), - "TOML's server.quic.congestion_control must not be clobbered by the CLI re-parse" - ); - assert_eq!( - config.client.quic.congestion_control, - Some(moq_native::quic::CongestionControl::Loss), - "TOML's client.quic.congestion_control must not be clobbered by the CLI re-parse" + "TOML's quic.congestion_control must not be clobbered by the CLI re-parse" ); } @@ -370,7 +560,7 @@ timeout = "2m" let args = vec![std::ffi::OsString::from("moq-relay"), std::ffi::OsString::from(&path)]; let config = Config::parse_and_merge(args).expect("config load"); - assert_eq!(config.client.timeout, Some(std::time::Duration::from_secs(120))); + assert_eq!(config.connect.timeout, Some(std::time::Duration::from_secs(120))); } #[test] @@ -477,7 +667,7 @@ system_roots = true let config = Config::parse_and_merge(args).expect("config load"); assert_eq!( - config.client.tls.system_roots, + config.connect.tls.system_roots, Some(true), "TOML's client.tls.system_roots must not be clobbered by the CLI re-parse" ); @@ -571,14 +761,14 @@ uid = [1001] let args = vec![std::ffi::OsString::from("moq-relay"), std::ffi::OsString::from(&path)]; let config = Config::parse_and_merge(args).expect("config load"); - assert_eq!(config.server.bind.as_deref(), Some("[::]:443")); + assert_eq!(config.listen.bind.as_deref(), Some("[::]:443")); assert_eq!( - config.server.unix.bind.as_deref(), + config.listen.unix.bind.as_deref(), Some(std::path::Path::new("/run/moq/internal.sock")), "TOML's server.unix.bind must not be clobbered by the CLI re-parse" ); assert_eq!( - config.server.unix.allow.expect("allow present").uid, + config.listen.unix.allow.expect("allow present").uid, vec![1001], "TOML's server.unix.allow must not be clobbered by the CLI re-parse" ); diff --git a/rs/moq-relay/src/internal.rs b/rs/moq-relay/src/internal.rs index 4c78bdf7f23..3ccce782229 100644 --- a/rs/moq-relay/src/internal.rs +++ b/rs/moq-relay/src/internal.rs @@ -50,7 +50,7 @@ pub struct InternalConfig { /// intentional: on loopback there's nothing to encrypt, and a private /// overlay (e.g. a mesh VPN) already provides transport encryption and peer /// identity. Unset (the default) disables the listener entirely. - #[arg(long = "internal-listen", env = "MOQ_INTERNAL_LISTEN")] + #[arg(id = "internal-listen", long = "internal-listen", env = "MOQ_INTERNAL_LISTEN")] pub listen: Option, } diff --git a/rs/moq-relay/src/relay.rs b/rs/moq-relay/src/relay.rs index e82515470bc..5d99efa12c8 100644 --- a/rs/moq-relay/src/relay.rs +++ b/rs/moq-relay/src/relay.rs @@ -24,10 +24,7 @@ use anyhow::Context; -use crate::{ - Auth, Cluster, Config, Connection, DEFAULT_DRAIN_TIMEOUT, DEFAULT_MAX_STREAMS, Internal, Shutdown, ShutdownTrigger, - Web, -}; +use crate::{Auth, Cluster, Config, Connection, DEFAULT_DRAIN_TIMEOUT, Internal, Shutdown, ShutdownTrigger, Web}; /// A fully assembled relay: the listeners and the shared cluster behind them. /// @@ -87,14 +84,13 @@ impl Relay { /// ready to serve; nothing accepts a connection until [`Self::run`] (or /// [`serve`]) drives it. pub async fn load(mut config: Config) -> anyhow::Result { - config.client.quic.max_streams.get_or_insert(DEFAULT_MAX_STREAMS); - config.server.quic.max_streams.get_or_insert(DEFAULT_MAX_STREAMS); + config.resolve(); - let mtls_enabled = !config.server.tls.root.is_empty(); + let mtls_enabled = !config.listen.tls.root.is_empty(); #[allow(unused_mut)] - let mut server = config.server.init()?; - let client = config.client.clone().init()?; + let mut server = config.listen.init(config.quic.clone())?; + let client = config.connect.clone().init(config.quic.clone())?; // `None` for a stream-only server (no QUIC); any other error is real. let addr = match server.local_addr() { @@ -104,7 +100,7 @@ impl Relay { }; #[cfg(feature = "iroh")] - let (server, client) = match config.iroh.bind(&config.client.quic).await? { + let (server, client) = match config.iroh.bind(&config.quic).await? { Some(iroh) => (server.with_iroh(iroh.clone()), client.with_iroh(iroh)), None => (server, client), }; @@ -123,7 +119,7 @@ impl Relay { // mTLS-only: no JWT/public source, but `--auth-mtls-tier` still applies. Auth::default().with_mtls_tier(config.auth.mtls_tier.clone()) } else { - config.auth.init(&config.client.tls).await? + config.auth.init(&config.connect.tls).await? }; // Before any origin handle is derived: `with_cache` rebuilds the origin, so a @@ -132,7 +128,7 @@ impl Relay { let cluster = Cluster::new(config.cluster)? .with_cache(cache) .with_client(client.clone()) - .with_client_tls(config.client.tls.build()?); + .with_client_tls(config.connect.tls.build()?); let stats = config.stats.build(cluster.origin.clone()); // The cluster takes over keeping the publish task alive, so an embedder that // drops the producer keeps publishing for as long as it serves. diff --git a/rs/moq-relay/src/web.rs b/rs/moq-relay/src/web.rs index b67ee454558..36a5d7a43e5 100644 --- a/rs/moq-relay/src/web.rs +++ b/rs/moq-relay/src/web.rs @@ -313,7 +313,7 @@ fn build_https_config( "web.https.cert and web.https.key must have the same number of entries" ); - let mut tls = moq_native::tls::Server::default(); + let mut tls = moq_native::tls::Listen::default(); tls.cert = cert.to_vec(); tls.key = key.to_vec(); tls.root = root.to_vec(); diff --git a/rs/moq-relay/tests/cluster_unknown.rs b/rs/moq-relay/tests/cluster_unknown.rs index cadbae9002e..b19246d6aba 100644 --- a/rs/moq-relay/tests/cluster_unknown.rs +++ b/rs/moq-relay/tests/cluster_unknown.rs @@ -28,10 +28,10 @@ async fn spawn_relay( let port = free_tcp_port(); let mut config = Config::default(); - config.server.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse bind")); - config.client.bind = "127.0.0.1:0".parse().expect("parse client bind"); - config.client.tls.disable_verify = Some(true); - config.client.version.extend(cluster_version); + config.listen.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse bind")); + config.connect.bind = Some("127.0.0.1:0".parse().expect("parse client bind")); + config.connect.tls.insecure = Some(true); + config.connect.version.extend(cluster_version); #[allow(deprecated)] { config.auth.public = Some(PublicConfig::Simple(vec![String::new()])); @@ -57,12 +57,12 @@ async fn spawn_relay( } fn client(version: Option) -> moq_native::Client { - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(true); - config.websocket.delay = None; - config.bind = "127.0.0.1:0".parse().expect("parse bind"); + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(true); + config.websocket.delay = Some(std::time::Duration::ZERO); + config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); config.version.extend(version); - config.init().expect("client init") + config.init(Default::default()).expect("client init") } struct Publisher { diff --git a/rs/moq-relay/tests/goaway_cluster.rs b/rs/moq-relay/tests/goaway_cluster.rs index a4aff02a67a..82c8b4ed2d7 100644 --- a/rs/moq-relay/tests/goaway_cluster.rs +++ b/rs/moq-relay/tests/goaway_cluster.rs @@ -61,9 +61,9 @@ fn bind_free_tcp_server() -> (u16, moq_native::Server) { let port = probe.local_addr().expect("local addr").port(); drop(probe); - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse addr")); - if let Ok(server) = config.init() { + if let Ok(server) = config.init(Default::default()) { return (port, server); } } @@ -98,9 +98,9 @@ async fn drain_session_with_zero_timeout_closes_at_once_inner() { let (port, mut accepted, _handle) = spawn_upstream(origin); wait_listening(port).await; - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); - let client = client_config.init().expect("client init"); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); + let client = client_config.init(Default::default()).expect("client init"); let (_client_connection_client, client_connection) = within("client connects", async { connect_once(client, format!("tcp://127.0.0.1:{port}/").parse().expect("parse url")).await }) @@ -193,11 +193,11 @@ async fn cluster_migrates_on_upstream_goaway_inner() { wait_listening(port_b).await; // ── the relay cluster under test, dialing sibling A ───────────── - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. client_config.goaway.handover = Some(Duration::from_secs(2)); - let client = client_config.init().expect("client init"); + let client = client_config.init(Default::default()).expect("client init"); let mut cluster_config = ClusterConfig::default(); cluster_config.connect = vec![format!("tcp://127.0.0.1:{port_a}/")]; @@ -304,7 +304,7 @@ async fn spawn_relay_with_upstream( let mut auth_config = AuthConfig::default(); auth_config.public = Some(public); let auth = auth_config - .init(&moq_native::tls::Client::default()) + .init(&moq_native::tls::Connect::default()) .await .expect("auth init"); @@ -312,11 +312,11 @@ async fn spawn_relay_with_upstream( cluster_config.connect = vec![upstream_url.to_string()]; // Short drain so the test observes teardown quickly. - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. client_config.goaway.handover = Some(Duration::from_secs(2)); - let client = client_config.init().expect("client init"); + let client = client_config.init(Default::default()).expect("client init"); let cluster = Cluster::new(cluster_config).expect("cluster init").with_client(client); @@ -388,11 +388,11 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { // ── MID-A: mini-relay consuming TOP, serving BOTTOM, drains later ─── let mid_a_origin = Origin::random().produce(); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. client_config.goaway.handover = Some(Duration::from_secs(2)); - let mid_a_client = client_config.init().expect("mid-a client init"); + let mid_a_client = client_config.init(Default::default()).expect("mid-a client init"); let (_mid_a_upstream_client, mid_a_upstream) = within( "MID-A connects to TOP", connect_once( @@ -420,9 +420,11 @@ async fn cluster_diamond_goaway_seamless_failover_inner() { // ── SUBSCRIBER: connects to BOTTOM ─────────────────────────────────── let sub_origin = Origin::random().produce(); - let mut sub_client_config = moq_native::ClientConfig::default(); - sub_client_config.tls.disable_verify = Some(true); - let sub_client = sub_client_config.init().expect("subscriber client init"); + let mut sub_client_config = moq_native::connect::Config::default(); + sub_client_config.tls.insecure = Some(true); + let sub_client = sub_client_config + .init(Default::default()) + .expect("subscriber client init"); let (_sub_connection_client, sub_connection) = within( "subscriber connects to BOTTOM", connect_once( @@ -605,11 +607,11 @@ async fn cluster_reconnects_on_empty_uri_goaway_inner() { let (port, mut accepted, _handle) = spawn_upstream(upstream_origin.clone()); wait_listening(port).await; - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); // Short handover so the test observes the old session close quickly. client_config.goaway.handover = Some(Duration::from_secs(2)); - let client = client_config.init().expect("client init"); + let client = client_config.init(Default::default()).expect("client init"); let mut cluster_config = ClusterConfig::default(); cluster_config.connect = vec![format!("tcp://127.0.0.1:{port}/")]; @@ -728,14 +730,14 @@ async fn goaway_handover_is_enforced_while_the_replacement_dial_hangs_inner() { }); let handover = Duration::from_millis(200); - let mut client_config = moq_native::ClientConfig::default(); - client_config.tls.disable_verify = Some(true); + let mut client_config = moq_native::connect::Config::default(); + client_config.tls.insecure = Some(true); client_config.goaway.handover = Some(handover); // The GOAWAY has to land on a *healthy* session, which is the path that goes // straight into the replacement dial. Below this bar it takes the immediate // redirect path instead, whose sleep polls the drain either way. client_config.backoff.initial = Some(Duration::from_millis(50)); - let client = client_config.init().expect("client init"); + let client = client_config.init(Default::default()).expect("client init"); let url: Url = format!("tcp://127.0.0.1:{port}/").parse().expect("parse url"); let connection = client.connect(url); diff --git a/rs/moq-relay/tests/released_cli.rs b/rs/moq-relay/tests/released_cli.rs new file mode 100644 index 00000000000..a715187e3d6 --- /dev/null +++ b/rs/moq-relay/tests/released_cli.rs @@ -0,0 +1,193 @@ +//! The released command line, frozen. +//! +//! Every flag and environment variable a published `moq-relay` accepted, checked +//! against the parser this build actually has. Renaming a flag is fine, and so is +//! moving it to another section; dropping the released spelling is not, because a +//! deployment's command line or environment goes on using it. +//! +//! Environment variables are the half a clap `alias` silently misses: an alias +//! renames the flag but leaves the variable behind, so a renamed arg keeps parsing +//! on the command line while quietly ignoring the environment. That is what this +//! pins. +//! +//! The list is from `moq-relay` at the last release before the connect/listen +//! rename. Add to it when a flag ships; only remove an entry when the spelling is +//! deliberately dropped, which is a breaking change to call out in the release +//! notes. + +use clap::CommandFactory; +use std::collections::{HashMap, HashSet}; + +/// `(flag, env)` for every released argument. `None` means it had no env var. +const RELEASED: &[(&str, Option<&str>)] = &[ + ("auth-api", Some("MOQ_AUTH_API")), + ("auth-domain", Some("MOQ_AUTH_DOMAIN")), + ("auth-key", Some("MOQ_AUTH_KEY")), + ("auth-key-dir", Some("MOQ_AUTH_KEY_DIR")), + ("auth-mtls-tier", Some("MOQ_AUTH_MTLS_TIER")), + ("auth-public", Some("MOQ_AUTH_PUBLIC")), + ("auth-public-api", Some("MOQ_AUTH_PUBLIC_API")), + ("auth-public-publish", Some("MOQ_AUTH_PUBLIC_PUBLISH")), + ("auth-public-subscribe", Some("MOQ_AUTH_PUBLIC_SUBSCRIBE")), + ("auth-tls-cert", Some("MOQ_AUTH_TLS_CERT")), + ("auth-tls-disable-verify", Some("MOQ_AUTH_TLS_DISABLE_VERIFY")), + ("auth-tls-key", Some("MOQ_AUTH_TLS_KEY")), + ("auth-tls-root", Some("MOQ_AUTH_TLS_ROOT")), + ("backoff-initial", Some("MOQ_BACKOFF_INITIAL")), + ("backoff-max", Some("MOQ_BACKOFF_MAX")), + ("backoff-multiplier", Some("MOQ_BACKOFF_MULTIPLIER")), + ("backoff-timeout", Some("MOQ_BACKOFF_TIMEOUT")), + ("cache-capacity", Some("MOQ_CACHE_CAPACITY")), + ("cache-duration", Some("MOQ_CACHE_DURATION")), + ("cache-headroom", Some("MOQ_CACHE_HEADROOM")), + ("client-backend", Some("MOQ_CLIENT_BACKEND")), + ("client-bind", Some("MOQ_CLIENT_BIND")), + ("client-connect", Some("MOQ_CLIENT_CONNECT")), + ("client-connect-timeout", Some("MOQ_CLIENT_CONNECT_TIMEOUT")), + ("client-failover-delay", Some("MOQ_CLIENT_FAILOVER_DELAY")), + ("client-max-streams", Some("MOQ_CLIENT_QUIC_MAX_STREAMS")), + ( + "client-quic-congestion-control", + Some("MOQ_CLIENT_QUIC_CONGESTION_CONTROL"), + ), + ("client-quic-gso", Some("MOQ_CLIENT_QUIC_GSO")), + ("client-quic-idle-timeout", Some("MOQ_CLIENT_QUIC_IDLE_TIMEOUT")), + ("client-quic-keep-alive", Some("MOQ_CLIENT_QUIC_KEEP_ALIVE")), + ("client-quic-max-streams", Some("MOQ_CLIENT_QUIC_MAX_STREAMS")), + ("client-quic-mtu-discovery", Some("MOQ_CLIENT_QUIC_MTU_DISCOVERY")), + ("client-quic-qlog", Some("MOQ_CLIENT_QUIC_QLOG")), + ("client-tls-cert", Some("MOQ_CLIENT_TLS_CERT")), + ("client-tls-disable-verify", Some("MOQ_CLIENT_TLS_DISABLE_VERIFY")), + ("client-tls-fingerprint", Some("MOQ_CLIENT_TLS_FINGERPRINT")), + ("client-tls-host-name", Some("MOQ_CLIENT_TLS_HOST_NAME")), + ("client-tls-key", Some("MOQ_CLIENT_TLS_KEY")), + ("client-tls-root", Some("MOQ_CLIENT_TLS_ROOT")), + ("client-tls-system-roots", Some("MOQ_CLIENT_TLS_SYSTEM_ROOTS")), + ("client-version", Some("MOQ_CLIENT_VERSION")), + ("cluster-connect", Some("MOQ_CLUSTER_CONNECT")), + ("cluster-connect-api", Some("MOQ_CLUSTER_CONNECT_API")), + ("cluster-id", Some("MOQ_CLUSTER_ID")), + ("cluster-linger", Some("MOQ_CLUSTER_LINGER")), + ("cluster-mesh", Some("MOQ_CLUSTER_MESH")), + ("cluster-node", Some("MOQ_CLUSTER_NODE")), + ("cluster-tier", Some("MOQ_CLUSTER_TIER")), + ("cluster-token", Some("MOQ_CLUSTER_TOKEN")), + ("internal-listen", Some("MOQ_INTERNAL_LISTEN")), + ("iroh-bind-v4", Some("MOQ_IROH_BIND_V4")), + ("iroh-bind-v6", Some("MOQ_IROH_BIND_V6")), + ("iroh-disable-relay", Some("MOQ_IROH_DISABLE_RELAY")), + ("iroh-enabled", Some("MOQ_IROH_ENABLED")), + ("iroh-secret", Some("MOQ_IROH_SECRET")), + ("listen", Some("MOQ_SERVER_BIND")), + ("log-level", Some("MOQ_LOG_LEVEL")), + ("server-backend", Some("MOQ_SERVER_BACKEND")), + ("server-bind", Some("MOQ_SERVER_BIND")), + ("server-max-streams", Some("MOQ_SERVER_QUIC_MAX_STREAMS")), + ("server-preferred-v4", Some("MOQ_SERVER_PREFERRED_V4")), + ("server-preferred-v6", Some("MOQ_SERVER_PREFERRED_V6")), + ( + "server-quic-congestion-control", + Some("MOQ_SERVER_QUIC_CONGESTION_CONTROL"), + ), + ("server-quic-gso", Some("MOQ_SERVER_QUIC_GSO")), + ("server-quic-idle-timeout", Some("MOQ_SERVER_QUIC_IDLE_TIMEOUT")), + ("server-quic-keep-alive", Some("MOQ_SERVER_QUIC_KEEP_ALIVE")), + ("server-quic-lb-id", Some("MOQ_SERVER_QUIC_LB_ID")), + ("server-quic-lb-nonce", Some("MOQ_SERVER_QUIC_LB_NONCE")), + ("server-quic-max-streams", Some("MOQ_SERVER_QUIC_MAX_STREAMS")), + ("server-quic-mtu-discovery", Some("MOQ_SERVER_QUIC_MTU_DISCOVERY")), + ("server-quic-qlog", Some("MOQ_SERVER_QUIC_QLOG")), + ("server-tcp-bind", Some("MOQ_SERVER_TCP_BIND")), + ("server-tls-root", Some("MOQ_SERVER_TLS_ROOT")), + ("server-unix-allow-gid", Some("MOQ_SERVER_UNIX_ALLOW_GID")), + ("server-unix-allow-pid", Some("MOQ_SERVER_UNIX_ALLOW_PID")), + ("server-unix-allow-uid", Some("MOQ_SERVER_UNIX_ALLOW_UID")), + ("server-unix-bind", Some("MOQ_SERVER_UNIX_BIND")), + ("server-version", Some("MOQ_SERVER_VERSION")), + ("stats-depth", Some("MOQ_STATS_DEPTH")), + ("stats-enabled", Some("MOQ_STATS_ENABLED")), + ("stats-interval", Some("MOQ_STATS_INTERVAL")), + ("stats-node", Some("MOQ_STATS_NODE")), + ("stats-prefix", Some("MOQ_STATS_PREFIX")), + ("tls-cert", Some("MOQ_SERVER_TLS_CERT")), + ("tls-disable-verify", None), + ("tls-fingerprint", None), + ("tls-generate", Some("MOQ_SERVER_TLS_GENERATE")), + ("tls-key", Some("MOQ_SERVER_TLS_KEY")), + ("tls-root", None), + ("tls-system-roots", None), + ("web-http-listen", Some("MOQ_WEB_HTTP_LISTEN")), + ("web-https-cert", Some("MOQ_WEB_HTTPS_CERT")), + ("web-https-key", Some("MOQ_WEB_HTTPS_KEY")), + ("web-https-listen", Some("MOQ_WEB_HTTPS_LISTEN")), + ("web-https-root", Some("MOQ_WEB_HTTPS_ROOT")), + ("web-ws", Some("MOQ_WEB_WS")), + ("websocket-delay", Some("MOQ_CLIENT_WEBSOCKET_DELAY")), + ("websocket-enabled", Some("MOQ_CLIENT_WEBSOCKET_ENABLED")), +]; + +/// Every flag name the parser accepts today, including aliases and hidden args. +fn flags(cmd: &clap::Command) -> HashSet { + let mut out = HashSet::new(); + for arg in cmd.get_arguments() { + if let Some(long) = arg.get_long() { + out.insert(long.to_string()); + } + for alias in arg.get_all_aliases().unwrap_or_default() { + out.insert(alias.to_string()); + } + } + for sub in cmd.get_subcommands() { + out.extend(flags(sub)); + } + out +} + +/// Every environment variable the parser reads, mapped to the flag that reads it. +fn envs(cmd: &clap::Command) -> HashMap { + let mut out = HashMap::new(); + for arg in cmd.get_arguments() { + if let Some(env) = arg.get_env() { + let flag = arg.get_long().unwrap_or_else(|| arg.get_id().as_str()); + out.insert(env.to_string_lossy().to_string(), flag.to_string()); + } + } + for sub in cmd.get_subcommands() { + out.extend(envs(sub)); + } + out +} + +#[test] +fn released_flags_still_parse() { + let cmd = moq_relay::Config::command(); + let flags = flags(&cmd); + + let missing: Vec<&str> = RELEASED + .iter() + .map(|(flag, _)| *flag) + .filter(|flag| !flags.contains(*flag)) + .collect(); + + assert!( + missing.is_empty(), + "released flags no longer parse: {missing:?}\nKeep the old spelling as a clap alias, or as a hidden arg when it also needs its original env var." + ); +} + +#[test] +fn released_env_vars_are_still_read() { + let cmd = moq_relay::Config::command(); + let envs = envs(&cmd); + + let missing: Vec<&str> = RELEASED + .iter() + .filter_map(|(_, env)| *env) + .filter(|env| !envs.contains_key(*env)) + .collect(); + + assert!( + missing.is_empty(), + "released env vars are silently ignored: {missing:?}\nA clap alias carries the flag name only; give the old variable a hidden arg of its own and fold it in." + ); +} diff --git a/rs/moq-relay/tests/smoke.rs b/rs/moq-relay/tests/smoke.rs index bfedc5b6c87..6c965ed6cef 100644 --- a/rs/moq-relay/tests/smoke.rs +++ b/rs/moq-relay/tests/smoke.rs @@ -50,7 +50,7 @@ async fn build_web_with(web_config: WebConfig) -> Web { let mut auth_config = AuthConfig::default(); auth_config.public = Some(public); let auth = auth_config - .init(&moq_native::tls::Client::default()) + .init(&moq_native::tls::Connect::default()) .await .expect("auth init"); @@ -59,10 +59,10 @@ async fn build_web_with(web_config: WebConfig) -> Web { // moq_native::Server is needed for `certificates`, even though we never // expose HTTPS or QUIC in this test. Binding QUIC to `[::]:0` picks an // unused UDP port that we ignore. - let mut server_config = moq_native::ServerConfig::default(); + let mut server_config = moq_native::listen::Config::default(); server_config.bind = Some("[::]:0".to_string()); server_config.tls.generate = vec!["localhost".into()]; - let server = server_config.init().expect("server init"); + let server = server_config.init(Default::default()).expect("server init"); Web::new(auth, cluster, server.certificates(), web_config) } @@ -125,20 +125,20 @@ fn client() -> moq_native::Client { /// A client pinned to a single MoQ version, or all versions when `None`. fn client_version(version: Option) -> moq_native::Client { - let mut config = moq_native::ClientConfig::default(); - config.tls.disable_verify = Some(true); + let mut config = moq_native::connect::Config::default(); + config.tls.insecure = Some(true); // One-shot: these tests were written against a single dial, and a background // redial would re-register with the relay behind the assertions' back. - config.reconnect = Some(false); + config.once = Some(true); // Zero head start so the WebSocket path runs immediately. - config.websocket.delay = None; + config.websocket.delay = Some(std::time::Duration::ZERO); // Every relay in this file listens on IPv4 loopback, so bind the same family // rather than egressing a QUIC dial from a dual-stack IPv6 socket. - config.bind = "127.0.0.1:0".parse().expect("parse bind"); + config.bind = Some("127.0.0.1:0".parse().expect("parse bind")); if let Some(version) = version { config.version = vec![version]; } - config.init().expect("client init") + config.init(Default::default()).expect("client init") } /// Connect a publisher and a subscriber to a real relay over `ws://`, push @@ -462,16 +462,16 @@ async fn two_publish_only_clients_coexist() { /// Returns the QUIC socket the server bound, when it has one, so a caller that /// asked for an ephemeral port can dial it. async fn spawn_accept_relay( - config: moq_native::ServerConfig, + config: moq_native::listen::Config, auth_config: AuthConfig, ) -> (Option, tokio::task::JoinHandle<()>) { let _ = rustls::crypto::aws_lc_rs::default_provider().install_default(); - let server = config.init().expect("server init"); + let server = config.init(Default::default()).expect("server init"); let addr = server.local_addr().ok(); let auth = auth_config - .init(&moq_native::tls::Client::default()) + .init(&moq_native::tls::Connect::default()) .await .expect("auth init"); @@ -504,7 +504,7 @@ async fn spawn_internal_relay() -> (u16, tokio::task::JoinHandle<()>) { drop(probe); // Stream-only: a TCP listener with no `--server-bind`, so no QUIC. - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse addr")); // Public Simple([""]) lets any no-JWT stream client through at the root. @@ -615,7 +615,7 @@ async fn spawn_internal_unix_relay() -> (std::path::PathBuf, tokio::task::JoinHa let path = std::path::PathBuf::from(format!("/tmp/moq-internal-{}-{seq}.sock", std::process::id())); // Stream-only: a Unix listener with no `--server-bind`, so no QUIC. - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.unix.bind = Some(path.clone()); // Public Simple([""]) lets any no-JWT stream client through at the root. @@ -829,7 +829,7 @@ async fn internal_unix_path_reaches_server() { /// loopback port, with fully public auth (no-JWT => whole root). Returns the bound /// address and an abort handle. async fn spawn_quic_relay() -> (std::net::SocketAddr, tokio::task::JoinHandle<()>) { - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.bind = Some("127.0.0.1:0".to_string()); config.tls.generate = vec!["localhost".into()]; @@ -890,7 +890,7 @@ async fn spawn_subscribe_only_relay() -> (u16, tokio::task::JoinHandle<()>) { let port = probe.local_addr().expect("local addr").port(); drop(probe); - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse addr")); // Subscribe-only public access: the root is granted for subscribing, never publishing. @@ -981,7 +981,7 @@ async fn spawn_publish_only_relay() -> (u16, tokio::task::JoinHandle<()>) { let port = probe.local_addr().expect("local addr").port(); drop(probe); - let mut config = moq_native::ServerConfig::default(); + let mut config = moq_native::listen::Config::default(); config.tcp.bind = Some(format!("127.0.0.1:{port}").parse().expect("parse addr")); // Publish-only public access: the root is granted for publishing, never subscribing. diff --git a/rs/moq-rtmp/README.md b/rs/moq-rtmp/README.md index 4dc069d26f4..062a094ea0d 100644 --- a/rs/moq-rtmp/README.md +++ b/rs/moq-rtmp/README.md @@ -84,13 +84,13 @@ Two ways to serve `rtmps://`: - **Let the gateway terminate TLS.** Set `Config::tls` (or call `Server::with_tls`) with a `rustls::ServerConfig`, and the listener speaks - RTMPS with no other change. Build the config from a `moq_native::tls::Server` + RTMPS with no other change. Build the config from a `moq_native::tls::Listen` instance (RTMPS has no ALPN), or supply any `rustls::ServerConfig`. To serve both RTMP and RTMPS, clone one base config so duplicate-publish rejection is shared across both listeners, then call `run` with a cloned origin. ```rust - let mut tls = moq_native::tls::Server::default(); + let mut tls = moq_native::tls::Listen::default(); tls.generate = vec!["your-domain.com".to_string()]; // or set tls.cert / tls.key let server_config = tls.server_config(vec![])?; // RTMPS has no ALPN diff --git a/rs/moq-rtmp/src/listen.rs b/rs/moq-rtmp/src/listen.rs index 0ed0c42e316..1c7918b4f3c 100644 --- a/rs/moq-rtmp/src/listen.rs +++ b/rs/moq-rtmp/src/listen.rs @@ -64,7 +64,7 @@ pub struct Config { /// TLS configuration for RTMPS (RTMP over TLS). When set, the /// [`listen`](Self::listen) address speaks RTMPS instead of plaintext RTMP, /// so clients connect with `rtmps://`. Build it with - /// `moq_native::tls::Server::server_config` (pass an empty ALPN list) or + /// `moq_native::tls::Listen::server_config` (pass an empty ALPN list) or /// any [`rustls::ServerConfig`]. Leave `None` for plaintext. /// /// To serve both RTMP and RTMPS, clone one base config and call [`run`] for diff --git a/rs/moq-rtmp/src/server.rs b/rs/moq-rtmp/src/server.rs index ba0da509dbe..3e2df1a0ccb 100644 --- a/rs/moq-rtmp/src/server.rs +++ b/rs/moq-rtmp/src/server.rs @@ -269,7 +269,7 @@ impl Server { /// Terminate TLS on every accepted connection, turning this into an RTMPS /// listener (`rtmps://`). Pass a `rustls::ServerConfig` (e.g. from - /// `moq_native::tls::Server::server_config` with an empty ALPN list), or + /// `moq_native::tls::Listen::server_config` with an empty ALPN list), or /// `None` to leave it plaintext. #[cfg(feature = "tls")] pub fn with_tls(mut self, tls: impl Into>>) -> Self { @@ -2105,7 +2105,7 @@ mod tests { let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider()); // Server: a self-signed cert for `localhost`, fronting the RTMP listener. - let mut tls = moq_native::tls::Server::default(); + let mut tls = moq_native::tls::Listen::default(); tls.generate = vec!["localhost".to_string()]; let server_config = tls.server_config(vec![]).expect("build RTMPS server config"); diff --git a/rs/moq-transcode/examples/transcode.rs b/rs/moq-transcode/examples/transcode.rs index 0bbfbf90487..f2b550bc452 100644 --- a/rs/moq-transcode/examples/transcode.rs +++ b/rs/moq-transcode/examples/transcode.rs @@ -42,7 +42,7 @@ async fn main() -> anyhow::Result<()> { let publish = moq_net::Origin::random().produce(); let remote = moq_net::Origin::random().produce(); - let client = moq_native::ClientConfig::default().init()?; + let client = moq_native::connect::Config::default().init(Default::default())?; let mut session = client .with_publisher(&publish) .with_subscriber(remote.clone()) diff --git a/test/smoke/smoke.sh b/test/smoke/smoke.sh index b443c68ee87..0235da10a17 100755 --- a/test/smoke/smoke.sh +++ b/test/smoke/smoke.sh @@ -364,7 +364,7 @@ start_publisher() { local lang="$1" broadcast="$2" log="$TMP/pub-$1.log" case "$lang" in rust) - (ffmpeg_h264 | "$MOQ" --client-connect "$URL" --broadcast "$broadcast" import avc3) >"$log" 2>&1 & + (ffmpeg_h264 | "$MOQ" --connect "$URL" --broadcast "$broadcast" import avc3) >"$log" 2>&1 & ;; python) (ffmpeg_h264 | "$PY" "$CLIENTS/python/smoke.py" \ @@ -403,7 +403,7 @@ run_subscriber() { # moq-cli only handles SIGINT, so -k forces SIGKILL if it ignores the # SIGTERM that fires when no data arrives within the timeout. local n - n=$(timeout -k 3 "$TIMEOUT" "$MOQ" --client-connect "$URL" --broadcast "$broadcast" \ + n=$(timeout -k 3 "$TIMEOUT" "$MOQ" --connect "$URL" --broadcast "$broadcast" \ export fmp4 | head -c 1 | wc -c | tr -d ' ' || true) [[ "${n:-0}" -ge 1 ]] ;; diff --git a/test/ts/README.md b/test/ts/README.md index d7c3b297d0a..34f1e1b284a 100644 --- a/test/ts/README.md +++ b/test/ts/README.md @@ -24,7 +24,7 @@ just test ts --strict # also fail on broadcast-shape warnings subscriber output: ```bash -moq --client-connect http://localhost:4443 --broadcast live.hang export ts > sub.ts +moq --connect http://localhost:4443 --broadcast live.hang export ts > sub.ts ./run.sh --analyze-only sub.ts ``` diff --git a/test/ts/run.sh b/test/ts/run.sh index 04d5ed22e9a..b66ea7d802a 100755 --- a/test/ts/run.sh +++ b/test/ts/run.sh @@ -185,7 +185,7 @@ fi # the start of the stream (or the whole thing for a short clip). echo "### capturing subscriber output (export ts)" timeout -k 3 $((DURATION + 20)) \ - "$MOQ" --client-connect "$URL" --broadcast "$BROADCAST" export ts >"$SUB_TS" 2>"$TMP/sub.log" & + "$MOQ" --connect "$URL" --broadcast "$BROADCAST" export ts >"$SUB_TS" 2>"$TMP/sub.log" & SUB_PID=$! sleep 1 @@ -198,7 +198,7 @@ echo "### publishing PCR-paced TS -> $BROADCAST" # shellcheck disable=SC2016 # $1..$4 are the child bash -c positionals, not ours. timeout -k 3 $((DURATION + 20)) bash -c ' tsp -I file "$1" -P regulate --pcr-synchronous | - "$2" --client-connect "$3" --broadcast "$4" import ts + "$2" --connect "$3" --broadcast "$4" import ts ' _ "$SRC_TS" "$MOQ" "$URL" "$BROADCAST" >"$TMP/pub.log" 2>&1 & PUB_PID=$!