Something went wrong. Try again.
QUIC for Zig 0.17: RFC 9000-9002 with TLS 1.3, as a sans-I/O core plus a socket layer, with datagrams, multipath and raw public keys.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! n0's NAT traversal, as noq has it: which addresses each end offers, which//! it has been offered, and when to punch at them.//!//! Not a standard, and not `draft-seemann-quic-nat-traversal-02`, from which//! it takes its ideas and none of its codepoints -- see `docs/iroh-transport.md`,//! Stage 5, which says why this one. What follows is read from noq's//! `n0_nat_traversal.rs` and `connection/mod.rs`, commit `89ed00c`.//!//! The roles are fixed and unequal. The **server** advertises its candidate//! addresses with ADD_ADDRESS and withdraws them with REMOVE_ADDRESS. The//! **client** starts a *round*: it sends each of its own candidates in a//! REACH_OUT carrying the round number, and punches at every address the//! server advertised. The server punches back at every REACH_OUT address.//! A punch -- a *probe* -- is a PATH_CHALLENGE sent on an existing path to//! the candidate address; an answer from that address with the same token is//! a hole that has opened. Only the client acts on one, by opening a//! multipath path to it.//!//! This file is the bookkeeping and nothing else. It never sees a packet://! the connection asks it what to send and tells it what arrived, and it//! answers in addresses and tokens. Everything is bounded -- `max_addresses`//! of each kind -- because the number of candidates is the peer's to choose//! and the memory is not.
const std = @import("std");
const frame = @import("frame.zig");const recovery = @import("recovery.zig");
const Address = frame.Address;
/// The most candidate addresses kept of either kind, whatever the transport/// parameters say. iroh asks for 32, and that is what this holds.pub const max_addresses = 32;
/// noq's `MAX_NAT_PROBE_ATTEMPTS`: how many probes one address gets in one/// round -- the first when the round starts and eight retries. "Probe packets/// could be lost", and "we may need two probes to reach the NAT firewall to/// get through", but they "may be sending probes to innocent bystanders on/// the internet", so it stops.pub const max_probe_attempts = 9;
/// The longest wait between retries.pub const max_retry_delay: recovery.Duration = 2 * std.time.ns_per_s;
/// Challenges remembered, so that an answer can be matched to the address/// it was sent to. A round sends at most `max_addresses * max_probe_attempts`,/// and an answer to one that has been pushed out by later ones is taken for/// an unrelated PATH_RESPONSE -- which costs a hole the next round finds/// again, not an error.const max_challenges = 64;
pub const Role = enum { client, server };
pub const Error = error{ /// More candidates than the peer said it would take, or than this holds. TooManyAddresses, /// A round needs at least one local candidate to send in REACH_OUT. NoLocalAddresses,};
/// One of this endpoint's own candidates.const Local = struct { address: Address, /// The server's sequence number for it, which REMOVE_ADDRESS names. sequence: u64, /// Server: its ADD_ADDRESS is owed. Client: its REACH_OUT is owed for the /// current round. owed: bool,};
/// One of the peer's candidates.const Remote = struct { address: Address, /// The client's key for a server candidate: its ADD_ADDRESS sequence /// number. Unused on the server, whose remotes are one round's REACH_OUT /// addresses. sequence: u64, /// Probes still to come after the next, noq's `Active(remaining)`. remaining: u8, /// A probe is due now. pending: bool, succeeded: bool,};
const Challenge = struct { token: [8]u8, address: Address };
pub const State = struct { role: Role, /// How many candidates the peer may advertise to this end: this end's /// own transport parameter. max_remote: u8, /// How many this end may advertise: the peer's. max_local: u8,
local: [max_addresses]?Local = @splat(null), /// The server's next ADD_ADDRESS sequence number, from zero. A removed /// address added again takes a new one. next_sequence: u64 = 0, /// REMOVE_ADDRESS frames owed, by sequence number. removed: [max_addresses]?u64 = @splat(null),
remotes: [max_addresses]?Remote = @splat(null), /// The client's current round, from one; the server's is the highest it /// has seen, from zero. round: u64 = 0, /// Retry ticks so far this round, which the delay doubles with. attempt: u8 = 0, retry_at: ?recovery.Instant = null,
challenges: [max_challenges]?Challenge = @splat(null), next_challenge: usize = 0,
pub fn init(role: Role, max_remote: u8, max_local: u8) State { return .{ .role = role, .max_remote = max_remote, .max_local = max_local }; }
// -- this end's candidates ------------------------------------------------
/// Adds one of this end's addresses. A server owes an ADD_ADDRESS for it; /// a client keeps it for the next round's REACH_OUT. pub fn addLocal(s: *State, address: Address) error{TooManyAddresses}!void { const canonical = address.canonical(); var count: usize = 0; for (&s.local) |*slot| { const entry = slot.* orelse continue; if (entry.address.eql(canonical)) return; count += 1; } if (count >= @min(s.max_local, max_addresses)) return error.TooManyAddresses; for (&s.local) |*slot| { if (slot.* != null) continue; slot.* = .{ .address = canonical, .sequence = s.next_sequence, .owed = s.role == .server }; if (s.role == .server) s.next_sequence += 1; return; } unreachable; }
/// Withdraws one. A server owes a REMOVE_ADDRESS naming it; a client /// simply leaves it out of the next round. pub fn removeLocal(s: *State, address: Address) void { const canonical = address.canonical(); for (&s.local) |*slot| { const entry = slot.* orelse continue; if (!entry.address.eql(canonical)) continue; slot.* = null; if (s.role == .server) s.oweRemove(entry.sequence); return; } }
fn oweRemove(s: *State, sequence: u64) void { for (&s.removed) |*slot| { if (slot.* == null) { slot.* = sequence; return; } } }
// -- frames owed, and lost -----------------------------------------------
/// An ADD_ADDRESS the server owes. pub fn owedAdd(s: *const State) ?frame.NumberedAddress { if (s.role != .server) return null; for (&s.local) |*slot| { const entry = slot.* orelse continue; if (entry.owed) return .{ .sequence = entry.sequence, .address = entry.address }; } return null; }
pub fn sentAdd(s: *State, sequence: u64) void { for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.sequence == sequence) { entry.owed = false; }; } }
/// A lost ADD_ADDRESS, owed again if the address is still offered. noq /// sends it again regardless, and a peer can then hear of an address /// after hearing it withdrawn; asking first costs nothing. pub fn lostAdd(s: *State, sequence: u64) void { for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.sequence == sequence) { entry.owed = true; }; } }
pub fn owedRemove(s: *const State) ?u64 { for (&s.removed) |slot| if (slot) |sequence| return sequence; return null; }
pub fn sentRemove(s: *State, sequence: u64) void { for (&s.removed) |*slot| { if (slot.* == sequence) slot.* = null; } }
pub fn lostRemove(s: *State, sequence: u64) void { s.oweRemove(sequence); }
/// A REACH_OUT the client owes for the current round. pub fn owedReach(s: *const State) ?frame.NumberedAddress { if (s.role != .client) return null; for (&s.local) |*slot| { const entry = slot.* orelse continue; if (entry.owed) return .{ .sequence = s.round, .address = entry.address }; } return null; }
pub fn sentReach(s: *State, address: Address) void { for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.address.eql(address)) { entry.owed = false; }; } }
/// A lost REACH_OUT, owed again only while its round is the current one. pub fn lostReach(s: *State, round: u64, address: Address) void { if (round != s.round) return; for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.address.eql(address)) { entry.owed = true; }; } }
// -- the peer's candidates -----------------------------------------------
/// The client hears of a server candidate. /// /// A sequence number already held with the same address changes nothing; /// with another address the entry is replaced, which noq logs as illegal /// and then does. A new one past this end's limit is dropped rather than /// refused -- the server is not held to account for it, as it is for too /// many REACH_OUT addresses. Either way the address waits for the next /// retry tick or the next round to be probed. /// /// Returns whether the set changed, which is noq's AddressAdded event -- /// the thing iroh starts a new round on. pub fn onAddAddress(s: *State, sequence: u64, address: Address) bool { const canonical = address.canonical(); const fresh: Remote = .{ .address = canonical, .sequence = sequence, .remaining = max_probe_attempts, .pending = false, .succeeded = false, }; var count: usize = 0; for (&s.remotes) |*slot| { const entry = slot.* orelse continue; if (entry.sequence == sequence) { if (entry.address.eql(canonical)) return false; slot.* = fresh; return true; } count += 1; } if (count >= @min(s.max_remote, max_addresses)) return false; for (&s.remotes) |*slot| { if (slot.* == null) { slot.* = fresh; return true; } } return false; }
/// The client hears a server candidate withdrawn. Returns whether it was /// held. A probe already due is not cancelled, as it is not in noq. pub fn onRemoveAddress(s: *State, sequence: u64) bool { for (&s.remotes) |*slot| { const entry = slot.* orelse continue; if (entry.sequence == sequence) { slot.* = null; return true; } } return false; }
/// The server hears one of the client's candidates for round `round`. /// /// A round lower than the current one is stale and ignored. A higher one /// starts afresh -- everything of the old round forgotten, and the retry /// timer armed from `now`. The same round adds to it, and an address past /// this end's limit is an error the caller makes a PROTOCOL_VIOLATION. pub fn onReachOut(s: *State, round: u64, address: Address, now: recovery.Instant) error{TooManyAddresses}!void { if (round < s.round) return; const canonical = address.canonical(); if (round > s.round) { s.round = round; s.attempt = 0; s.remotes = @splat(null); s.forgetChallenges(); s.remotes[0] = .{ .address = canonical, .sequence = 0, .remaining = max_probe_attempts - 1, .pending = true, .succeeded = false, }; s.retry_at = if (s.retryDelay()) |delay| now +| delay else null; return; } var count: usize = 0; for (&s.remotes) |*slot| { const entry = slot.* orelse continue; if (entry.address.eql(canonical)) return; // a retransmission count += 1; } if (count >= @min(s.max_remote, max_addresses)) return error.TooManyAddresses; for (&s.remotes) |*slot| { if (slot.* != null) continue; slot.* = .{ .address = canonical, .sequence = 0, .remaining = max_probe_attempts - 1, .pending = true, .succeeded = false, }; return; } unreachable; }
// -- rounds and probes -----------------------------------------------------
/// The client starts a round: REACH_OUT owed for each of its candidates, /// a probe due at each of the server's, and the retry timer armed. pub fn startRound(s: *State, now: recovery.Instant) error{NoLocalAddresses}!void { var any_local = false; for (&s.local) |*slot| { if (slot.*) |*entry| { entry.owed = true; any_local = true; } } if (!any_local) return error.NoLocalAddresses; s.round +|= 1; s.attempt = 0; s.forgetChallenges(); for (&s.remotes) |*slot| { if (slot.*) |*entry| { entry.remaining = max_probe_attempts - 1; entry.pending = true; entry.succeeded = false; } } s.retry_at = if (s.retryDelay()) |delay| now +| delay else null; }
/// The next address a probe is due at. pub fn nextProbe(s: *const State) ?Address { for (&s.remotes) |slot| { const entry = slot orelse continue; if (entry.pending) return entry.address; } return null; }
/// A probe carrying `token` has gone to `address`. pub fn sentProbe(s: *State, address: Address, token: [8]u8) void { for (&s.remotes) |*slot| { if (slot.*) |*entry| if (entry.address.eql(address)) { entry.pending = false; }; } s.recordChallenge(token, address); }
/// A challenge sent to `address` that is not a probe of an advertised /// candidate -- the client's, riding on its answer to a server's probe. pub fn recordChallenge(s: *State, token: [8]u8, address: Address) void { s.challenges[s.next_challenge] = .{ .token = token, .address = address.canonical() }; s.next_challenge = (s.next_challenge + 1) % max_challenges; }
fn forgetChallenges(s: *State) void { s.challenges = @splat(null); s.next_challenge = 0; }
/// A PATH_RESPONSE with `token` arrived from `from`. True if it answers /// a challenge this state sent to that very address -- the token alone /// is not enough, since the point is that *this* address is reachable. /// The address stops being probed. pub fn onResponse(s: *State, token: [8]u8, from: Address) bool { const canonical = from.canonical(); for (&s.challenges) |*slot| { const entry = slot.* orelse continue; if (!std.mem.eql(u8, &entry.token, &token)) continue; if (!entry.address.eql(canonical)) return false; slot.* = null; for (&s.remotes) |*remote| { if (remote.*) |*r| if (r.address.eql(canonical)) { r.succeeded = true; r.pending = false; r.remaining = 0; }; } return true; } return false; }
/// Runs the retry timer if it is due: every address with probes left gets /// one more, and the timer is armed again while any has. pub fn onTimeout(s: *State, now: recovery.Instant) void { const at = s.retry_at orelse return; if (now < at) return; s.attempt +|= 1; for (&s.remotes) |*slot| { if (slot.*) |*entry| if (!entry.succeeded and entry.remaining > 0) { entry.remaining -= 1; entry.pending = true; }; } s.retry_at = if (s.retryDelay()) |delay| now +| delay else null; }
/// noq's `retry_delay`: a tenth of the configured initial RTT, doubling /// with each tick after the first, capped at two seconds -- or null when /// no address has a probe left. The configured RTT, not a measured one: /// the addresses being probed are not the path the RTT was measured on. pub fn retryDelay(s: *const State) ?recovery.Duration { var any = false; for (&s.remotes) |slot| { const entry = slot orelse continue; if (!entry.succeeded and entry.remaining > 0) any = true; } if (!any) return null; const base = recovery.initial_rtt / 10; const a = @min(s.attempt, 8); const interval = if (a == 0) base else base << @intCast(a - 1); return @min(interval, max_retry_delay); }
/// How many of the peer's candidates are held. pub fn remoteCount(s: *const State) usize { var count: usize = 0; for (&s.remotes) |slot| { if (slot != null) count += 1; } return count; }};
const testing = std.testing;
fn v4(a: u8, b: u8, c: u8, d: u8, port: u16) Address { return .{ .ip = .{ .v4 = .{ a, b, c, d } }, .port = port };}
test "a server offers its addresses with sequence numbers from zero, never reused" { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); try s.addLocal(v4(192, 0, 2, 2, 443)); try s.addLocal(v4(192, 0, 2, 1, 443)); // already offered: nothing try testing.expectEqual(@as(u64, 0), s.owedAdd().?.sequence); s.sentAdd(0); try testing.expectEqual(@as(u64, 1), s.owedAdd().?.sequence); s.sentAdd(1); try testing.expect(s.owedAdd() == null);
s.removeLocal(v4(192, 0, 2, 1, 443)); try testing.expectEqual(@as(?u64, 0), s.owedRemove()); s.sentRemove(0); // Added again, it is a new address as far as the client can tell. try s.addLocal(v4(192, 0, 2, 1, 443)); try testing.expectEqual(@as(u64, 2), s.owedAdd().?.sequence);}
test "a server offers no more addresses than the client will take" { var s: State = .init(.server, 8, 2); try s.addLocal(v4(192, 0, 2, 1, 1)); try s.addLocal(v4(192, 0, 2, 2, 1)); try testing.expectError(error.TooManyAddresses, s.addLocal(v4(192, 0, 2, 3, 1)));}
test "a lost ADD_ADDRESS is owed again only while the address is offered" { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 1)); s.sentAdd(0); s.lostAdd(0); try testing.expectEqual(@as(u64, 0), s.owedAdd().?.sequence); s.sentAdd(0); s.removeLocal(v4(192, 0, 2, 1, 1)); s.lostAdd(0); try testing.expect(s.owedAdd() == null);}
test "a client's round owes a REACH_OUT per address and probes every server candidate" { var s: State = .init(.client, 8, 8); try testing.expectError(error.NoLocalAddresses, s.startRound(0)); try s.addLocal(v4(198, 51, 100, 1, 5000)); try testing.expect(s.owedReach() == null); // not until a round try testing.expect(s.onAddAddress(0, v4(192, 0, 2, 1, 443))); try testing.expect(s.nextProbe() == null); // not until a round either
try s.startRound(1000); try testing.expectEqual(@as(u64, 1), s.round); const reach = s.owedReach().?; try testing.expectEqual(@as(u64, 1), reach.sequence); s.sentReach(reach.address); try testing.expect(s.owedReach() == null); // Lost in an old round: not owed again. try s.startRound(2000); s.sentReach(reach.address); s.lostReach(1, reach.address); try testing.expect(s.owedReach() == null); s.lostReach(2, reach.address); try testing.expect(s.owedReach() != null);
try testing.expect(s.nextProbe().?.eql(v4(192, 0, 2, 1, 443)));}
test "a client's view of the server's candidates follows ADD_ADDRESS and REMOVE_ADDRESS" { var s: State = .init(.client, 2, 8); try testing.expect(s.onAddAddress(0, v4(192, 0, 2, 1, 1))); try testing.expect(!s.onAddAddress(0, v4(192, 0, 2, 1, 1))); // a repeat try testing.expect(s.onAddAddress(0, v4(192, 0, 2, 9, 1))); // replaced try testing.expect(s.onAddAddress(1, v4(192, 0, 2, 2, 1))); // Past this end's limit: dropped, not an error. try testing.expect(!s.onAddAddress(2, v4(192, 0, 2, 3, 1))); try testing.expectEqual(@as(usize, 2), s.remoteCount()); try testing.expect(s.onRemoveAddress(0)); try testing.expect(!s.onRemoveAddress(0)); try testing.expectEqual(@as(usize, 1), s.remoteCount());}
test "a server's REACH_OUT set is one round's, and too many in a round is refused" { var s: State = .init(.server, 2, 8); try s.onReachOut(1, v4(198, 51, 100, 1, 1), 0); try s.onReachOut(1, v4(198, 51, 100, 1, 1), 0); // a retransmission try s.onReachOut(1, v4(198, 51, 100, 2, 1), 0); try testing.expectError(error.TooManyAddresses, s.onReachOut(1, v4(198, 51, 100, 3, 1), 0)); // A stale round is ignored; a newer one starts over and fits. try s.onReachOut(0, v4(198, 51, 100, 4, 1), 0); try s.onReachOut(2, v4(198, 51, 100, 5, 1), 0); try testing.expectEqual(@as(usize, 1), s.remoteCount()); try testing.expect(s.nextProbe().?.eql(v4(198, 51, 100, 5, 1)));}
test "an answer counts only from the address the challenge went to" { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 1)); _ = s.onAddAddress(0, v4(192, 0, 2, 1, 443)); try s.startRound(0); const to = s.nextProbe().?; s.sentProbe(to, .{ 1, 2, 3, 4, 5, 6, 7, 8 }); try testing.expect(s.nextProbe() == null); try testing.expect(!s.onResponse(.{ 1, 2, 3, 4, 5, 6, 7, 8 }, v4(192, 0, 2, 99, 443))); try testing.expect(!s.onResponse(.{ 9, 9, 9, 9, 9, 9, 9, 9 }, to)); try testing.expect(s.onResponse(.{ 1, 2, 3, 4, 5, 6, 7, 8 }, to)); // Succeeded, so the retries leave it alone. try testing.expect(s.retryDelay() == null);}
test "an IPv4-mapped source matches the IPv4 address that was probed" { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 1)); _ = s.onAddAddress(0, v4(192, 0, 2, 7, 51820)); try s.startRound(0); s.sentProbe(s.nextProbe().?, @splat(7)); const mapped: Address = .{ .ip = .{ .v6 = .{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 192, 0, 2, 7 } }, .port = 51820 }; try testing.expect(s.onResponse(@splat(7), mapped));}
test "nine probes per address per round, on noq's schedule" { // noq's test_retry_delay: 33.3, 33.3, 66.6, 133.2, 266.4, 532.8, // 1065.6, then 2000 ms capped -- and after the ninth probe, nothing. var s: State = .init(.server, 8, 8); var now: recovery.Instant = 0; try s.onReachOut(1, v4(198, 51, 100, 1, 1), now); const base = recovery.initial_rtt / 10; const expected = [_]recovery.Duration{ base, base, 2 * base, 4 * base, 8 * base, 16 * base, 32 * base, max_retry_delay }; var probes: usize = 0; for (expected) |delay| { try testing.expectEqual(now + delay, s.retry_at.?); s.sentProbe(s.nextProbe().?, @splat(0)); probes += 1; now = s.retry_at.?; s.onTimeout(now); } s.sentProbe(s.nextProbe().?, @splat(0)); probes += 1; try testing.expectEqual(@as(usize, max_probe_attempts), probes); try testing.expect(s.retry_at == null); try testing.expect(s.nextProbe() == null);}