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.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879// 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,
/// Starts with no candidates on either side and no round. `max_remote` /// is the limit this end advertised in its own transport parameter, and /// `max_local` the one the peer advertised; both are further capped at /// `max_addresses`. pub fn init(role: Role, max_remote: u8, max_local: u8) State { return .{ .role = role, .max_remote = max_remote, .max_local = max_local }; }
test init { // This end takes up to 8 candidates; the peer takes up to 4 of ours. const s: State = .init(.client, 8, 4); try std.testing.expectEqual(@as(usize, 0), s.remoteCount()); try std.testing.expectEqual(@as(u64, 0), s.round); }
// -- 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. /// /// An IPv4-mapped IPv6 address is held as the IPv4 address it maps, and /// an address already held is not added twice. Fails with /// `error.TooManyAddresses` once the peer's limit, or `max_addresses`, is /// reached. 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; }
test addLocal { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); // The server now owes the client an ADD_ADDRESS for it. const add = s.owedAdd().?; try std.testing.expectEqual(@as(u64, 0), add.sequence); try std.testing.expect(add.address.eql(v4(192, 0, 2, 1, 443))); }
/// Withdraws one. A server owes a REMOVE_ADDRESS naming it; a client /// simply leaves it out of the next round. An address not held is /// ignored. 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; } }
test removeLocal { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); s.sentAdd(0); s.removeLocal(v4(192, 0, 2, 1, 443)); try std.testing.expectEqual(@as(?u64, 0), s.owedRemove()); }
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, with the sequence number and address /// it carries. Always null on a client. It stays owed until `sentAdd`. 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; }
test owedAdd { var s: State = .init(.server, 8, 8); try std.testing.expect(s.owedAdd() == null); try s.addLocal(v4(192, 0, 2, 1, 443)); try std.testing.expectEqual(@as(u64, 0), s.owedAdd().?.sequence); }
/// Notes that the ADD_ADDRESS numbered `sequence` has gone out, so it is /// owed no longer. pub fn sentAdd(s: *State, sequence: u64) void { for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.sequence == sequence) { entry.owed = false; }; } }
test sentAdd { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); const add = s.owedAdd().?; // ...an ADD_ADDRESS frame carrying `add` is sent... s.sentAdd(add.sequence); try std.testing.expect(s.owedAdd() == null); }
/// 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; }; } }
test lostAdd { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); s.sentAdd(0); s.lostAdd(0); try std.testing.expectEqual(@as(u64, 0), s.owedAdd().?.sequence); }
/// A REMOVE_ADDRESS the server owes, as the sequence number it names. It /// stays owed until `sentRemove`. pub fn owedRemove(s: *const State) ?u64 { for (&s.removed) |slot| if (slot) |sequence| return sequence; return null; }
test owedRemove { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); try std.testing.expectEqual(@as(?u64, null), s.owedRemove()); s.removeLocal(v4(192, 0, 2, 1, 443)); try std.testing.expectEqual(@as(?u64, 0), s.owedRemove()); }
/// Notes that the REMOVE_ADDRESS naming `sequence` has gone out, so it /// is owed no longer. pub fn sentRemove(s: *State, sequence: u64) void { for (&s.removed) |*slot| { if (slot.* == sequence) slot.* = null; } }
test sentRemove { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); s.removeLocal(v4(192, 0, 2, 1, 443)); s.sentRemove(s.owedRemove().?); try std.testing.expectEqual(@as(?u64, null), s.owedRemove()); }
/// A lost REMOVE_ADDRESS, owed again unconditionally: unlike an /// ADD_ADDRESS it cannot have been overtaken, since a sequence number is /// never reused for another address. pub fn lostRemove(s: *State, sequence: u64) void { s.oweRemove(sequence); }
test lostRemove { var s: State = .init(.server, 8, 8); try s.addLocal(v4(192, 0, 2, 1, 443)); s.removeLocal(v4(192, 0, 2, 1, 443)); s.sentRemove(0); s.lostRemove(0); try std.testing.expectEqual(@as(?u64, 0), s.owedRemove()); }
/// A REACH_OUT the client owes for the current round, whose `sequence` /// is the round number rather than anything of the address's own. Always /// null on a server, and on a client before `startRound`. It stays owed /// until `sentReach`. 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; }
test owedReach { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 5000)); try std.testing.expect(s.owedReach() == null); try s.startRound(0); const reach = s.owedReach().?; try std.testing.expectEqual(@as(u64, 1), reach.sequence); // the round try std.testing.expect(reach.address.eql(v4(198, 51, 100, 1, 5000))); }
/// Notes that the REACH_OUT for `address` has gone out, so it is owed no /// longer this round. `address` is matched exactly, so pass the one /// `owedReach` answered. pub fn sentReach(s: *State, address: Address) void { for (&s.local) |*slot| { if (slot.*) |*entry| if (entry.address.eql(address)) { entry.owed = false; }; } }
test sentReach { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 5000)); try s.startRound(0); s.sentReach(s.owedReach().?.address); try std.testing.expect(s.owedReach() == null); }
/// A lost REACH_OUT, owed again only while its round is the current one. /// `round` is the sequence number it was sent with, and `address` is /// matched exactly, as in `sentReach`. 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; }; } }
test lostReach { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 5000)); try s.startRound(0); const reach = s.owedReach().?; s.sentReach(reach.address); s.lostReach(reach.sequence, reach.address); try std.testing.expect(s.owedReach() != null); }
// -- 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; }
test onAddAddress { var s: State = .init(.client, 8, 8); // ADD_ADDRESS, sequence 0. try std.testing.expect(s.onAddAddress(0, v4(192, 0, 2, 1, 443))); // The same frame again is no news. try std.testing.expect(!s.onAddAddress(0, v4(192, 0, 2, 1, 443))); try std.testing.expectEqual(@as(usize, 1), s.remoteCount()); }
/// The client hears a server candidate withdrawn. Returns whether it was /// held. /// /// The candidate goes at once, so a probe due at it and not yet sent is /// never sent. One already sent is not cancelled, as it is not in noq: /// its challenge is still remembered, and `onResponse` still counts an /// answer to it. 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; }
test onRemoveAddress { var s: State = .init(.client, 8, 8); _ = s.onAddAddress(3, v4(192, 0, 2, 1, 443)); // REMOVE_ADDRESS names the sequence number, not the address. try std.testing.expect(s.onRemoveAddress(3)); try std.testing.expect(!s.onRemoveAddress(3)); try std.testing.expectEqual(@as(usize, 0), s.remoteCount()); }
/// 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) { // The limit holds for a round's first address as for the rest. A // limit of zero cannot come from a peer -- `parameters.parse` // refuses one -- but a `State` built with it accepts nothing. if (@min(s.max_remote, max_addresses) == 0) return error.TooManyAddresses; 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; }
test onReachOut { var s: State = .init(.server, 8, 8); // REACH_OUT for round 1: the server punches back at once. try s.onReachOut(1, v4(198, 51, 100, 1, 5000), 0); try std.testing.expect(s.nextProbe().?.eql(v4(198, 51, 100, 1, 5000))); try std.testing.expect(s.retry_at != null); // Round 2 replaces everything round 1 offered. try s.onReachOut(2, v4(198, 51, 100, 2, 5000), 0); try std.testing.expectEqual(@as(usize, 1), s.remoteCount()); }
test "a limit of zero refuses a round's first address too" { var s: State = .init(.server, 0, 8); try std.testing.expectError(error.TooManyAddresses, s.onReachOut(1, v4(192, 0, 2, 1, 443), 0)); try std.testing.expectEqual(@as(usize, 0), s.remoteCount()); }
// -- 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. /// /// The round number goes up by one, and challenges from earlier rounds /// are forgotten, so a late answer to one no longer counts. Fails with /// `error.NoLocalAddresses`, changing nothing, when there is no candidate /// of this end's to put in a REACH_OUT. 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; }
test startRound { var s: State = .init(.client, 8, 8); try std.testing.expectError(error.NoLocalAddresses, s.startRound(0)); try s.addLocal(v4(198, 51, 100, 1, 5000)); _ = s.onAddAddress(0, v4(192, 0, 2, 1, 443)); try s.startRound(1000); try std.testing.expectEqual(@as(u64, 1), s.round); try std.testing.expect(s.owedReach() != null); try std.testing.expect(s.nextProbe() != null); try std.testing.expectEqual(1000 + s.retryDelay().?, s.retry_at.?); }
/// The next address a probe is due at, or null when none is. The same /// address is answered until `sentProbe` says its probe went. pub fn nextProbe(s: *const State) ?Address { for (&s.remotes) |slot| { const entry = slot orelse continue; if (entry.pending) return entry.address; } return null; }
test nextProbe { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 5000)); _ = s.onAddAddress(0, v4(192, 0, 2, 1, 443)); // Known, but nothing is due until a round starts. try std.testing.expect(s.nextProbe() == null); try s.startRound(0); try std.testing.expect(s.nextProbe().?.eql(v4(192, 0, 2, 1, 443))); }
/// A probe carrying `token` has gone to `address`: the probe is no /// longer due, and the challenge is remembered (as `recordChallenge` /// does) so that `onResponse` can recognize the answer. `address` is /// matched exactly against the candidates, so pass what `nextProbe` /// answered. 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); }
test sentProbe { var s: State = .init(.server, 8, 8); try s.onReachOut(1, v4(198, 51, 100, 1, 5000), 0); const to = s.nextProbe().?; // ...a PATH_CHALLENGE carrying the token is sent to `to`... s.sentProbe(to, .{ 1, 2, 3, 4, 5, 6, 7, 8 }); try std.testing.expect(s.nextProbe() == null); try std.testing.expect(s.onResponse(.{ 1, 2, 3, 4, 5, 6, 7, 8 }, to)); }
/// 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. /// /// The challenges are remembered in a ring of 64, so the oldest is /// forgotten to make room, and an answer to it then matches nothing. 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; }
test recordChallenge { var s: State = .init(.client, 8, 8); const server = v4(192, 0, 2, 1, 443); s.recordChallenge(@splat(0x42), server); try std.testing.expect(s.onResponse(@splat(0x42), server)); }
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. /// /// A match spends the challenge, so the same answer twice counts once. /// The right token from the wrong address answers false and leaves the /// challenge to be answered properly. 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; }
test onResponse { var s: State = .init(.client, 8, 8); try s.addLocal(v4(198, 51, 100, 1, 5000)); _ = s.onAddAddress(0, v4(192, 0, 2, 1, 443)); try s.startRound(0); const to = s.nextProbe().?; s.sentProbe(to, @splat(0x5c)); // The right token, from somewhere else: not proof of anything. try std.testing.expect(!s.onResponse(@splat(0x5c), v4(203, 0, 113, 9, 443))); // From the address itself: a hole has opened. try std.testing.expect(s.onResponse(@splat(0x5c), to)); try std.testing.expect(!s.onResponse(@splat(0x5c), to)); }
/// 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. Before /// `retry_at`, or with no timer armed, nothing happens, so the caller /// can call this on every tick of its own. 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; }
test onTimeout { var s: State = .init(.server, 8, 8); try s.onReachOut(1, v4(198, 51, 100, 1, 5000), 0); s.sentProbe(s.nextProbe().?, @splat(1)); const at = s.retry_at.?; s.onTimeout(at - 1); // too early: nothing try std.testing.expect(s.nextProbe() == null); s.onTimeout(at); try std.testing.expect(s.nextProbe() != null); try std.testing.expect(s.retry_at.? > at); }
/// noq's `retry_delay`: a tenth of RFC 9002's initial RTT /// (`recovery.initial_rtt`, 333 ms), doubling with each tick after the /// first, capped at two seconds -- or null when no address has a probe /// left. A fixed 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); }
test retryDelay { var s: State = .init(.server, 8, 8); // Nothing to probe, so nothing to wait for. try std.testing.expectEqual(@as(?recovery.Duration, null), s.retryDelay()); try s.onReachOut(1, v4(198, 51, 100, 1, 5000), 0); try std.testing.expectEqual(recovery.initial_rtt / 10, s.retryDelay().?); }
/// How many of the peer's candidates are held: on a client, the server's /// advertised addresses; on a server, the current round's REACH_OUT /// addresses. pub fn remoteCount(s: *const State) usize { var count: usize = 0; for (&s.remotes) |slot| { if (slot != null) count += 1; } return count; }
test remoteCount { var s: State = .init(.client, 8, 8); _ = s.onAddAddress(0, v4(192, 0, 2, 1, 443)); _ = s.onAddAddress(1, v4(192, 0, 2, 2, 443)); try std.testing.expectEqual(@as(usize, 2), s.remoteCount()); }};
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);}