Skip to content
Merged
10 changes: 10 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,16 @@ Unreleased

### Behavior changes

- **Forward resolution no longer runs on the tracer actor or a cooperative thread.** `trace`,
`traceClassified`, `traceStream`, `ping`, `tcpProbe`, `udpProbe` and multipath flows resolve
their destination in an executor slot. The wait ends at a deadline: 20 s for traces and ping,
`config.timeout` from entry for the probes, whose connect or receive window is what resolution
leaves. A trace or ping whose lookup times out throws `resolutionFailed` with details
`"timed out"`; a probe reports its usual resolution failure and opens no socket. Cancelling the
task, `cancelActiveTraces()` or `networkChanged()` during resolution returns at once, and a
ping cancelled during its lookup throws `CancellationError` even if the lookup then fails.
Names share the eight executor slots with STUN server names; literals never queue behind
names (finding 5 in docs/ROBUSTNESS-TESTING.md).
- **The library's public-IP resolver asks every STUN server at once, and the first answer
decides** (David, 2026-11-24: "return as decisive the first public IP we get … The goal is to
be as fast as possible"). Each server's request goes out as soon as its name has resolved, on
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -467,13 +467,13 @@ Every tracked Markdown file has exactly one entry in one of these indexes.
- [Bufferbloat](Sources/SwiftFTR/SwiftFTR.docc/Bufferbloat.md): `testBufferbloat` usage, load generation, grading and RPM calculation, video-call severity and baseline-only bound mode. (updated 2026-11-22; update when: grading thresholds, the RPM method, default load endpoints or `BufferbloatConfig` change)
- [Multipath](Sources/SwiftFTR/SwiftFTR.docc/Multipath.md): `discoverPaths` usage, topology analysis, ICMP-versus-UDP limitations and the IPv4-only restriction. (updated 2026-11-21; update when: multipath gains UDP or IPv6 support, or `MultipathConfig` or `NetworkTopology` change)
- [Interface binding](Sources/SwiftFTR/SwiftFTR.docc/InterfaceBinding.md): which operations honor interface and source-address binding, resolution order and binding errors. (updated 2026-11-24; update when: an operation gains or loses binding support, or HTTP probes become bindable)
- [Migrating to 0.19](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md): upgrade guide from 0.18 to 0.19 for people and coding agents, one entry per change a caller can observe, with what changed, what a caller sees and before-and-after code. (updated 2026-11-24; update when: a change bound for 0.19 alters behavior or source a caller depends on, or 0.18 adopters no longer need it)
- [Migrating to 0.19](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo019.md): upgrade guide from 0.18 to 0.19 for people and coding agents, one entry per change a caller can observe, with what changed, what a caller sees and before-and-after code. (updated 2026-11-27; update when: a change bound for 0.19 alters behavior or source a caller depends on, or 0.18 adopters no longer need it)
- [Migrating to 0.18](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo018.md): upgrade guide from 0.17 to 0.18 for people and coding agents, one entry per behavior change with what changed, what a caller sees and before-and-after code, including adopting the structured DNS probe outcome. (updated 2026-11-22; update when: a change bound for 0.18 alters behavior a caller can observe, or 0.17 adopters no longer need it)
- [Migrating to 0.14](Sources/SwiftFTR/SwiftFTR.docc/MigratingTo014.md): upgrade guide from 0.13 to 0.14 covering new `DNSError` cases, behavior and CLI changes, plus runtime changes in later releases. (updated 2026-11-21; update when: a later release changes a behavior it describes, or 0.13 adopters no longer need it)

### Reference and examples
- [Examples](docs/guides/EXAMPLES.md): worked Swift examples for each feature area, including trace, hop outcomes, configuration, network-change lifecycle, streaming, DNS, ping, multipath, bufferbloat, SwiftUI, concurrency, errors, DNS probe outcomes and ASN strategies. (updated 2026-11-23; update when: a public API used in a sample changes shape, or a release adds a feature area with no example)
- [Condensed API reference](docs/reference/AI_REFERENCE.md): public types, method signatures, defaults, enum and error cases and CLI flags with short snippets, sized to load whole into an agent's context. (updated 2026-11-24; update when: a release changes a public signature, default, enum case or CLI flag)
- [Condensed API reference](docs/reference/AI_REFERENCE.md): public types, method signatures, defaults, enum and error cases and CLI flags with short snippets, sized to load whole into an agent's context. (updated 2026-11-27; update when: a release changes a public signature, default, enum case or CLI flag)

### Tools and fixtures
- [hop-monitor](Sources/hop-monitor/README.md): the demo CLI that traces a path and then pings every hop continuously, with its output, statistics and limits. (updated 2026-11-21; update when: `Sources/hop-monitor/main.swift` changes its arguments, limits or statistics)
Expand Down
12 changes: 6 additions & 6 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,12 @@ a network that drops mid-operation, a peer that accepts and then goes silent.
What remains is the findings it left open, each with a disabled or missing test named there.
- **Sequenced plan**: [docs/BLOCKING-IO.md](docs/BLOCKING-IO.md) orders the work into stages, each one
pull request, with the gates each must pass.
- **Known unbounded waits** (#84): `traceClassified` has no overall deadline, and forward
resolution runs `getaddrinfo` synchronously on the actor where it can be neither bounded nor
cancelled; a 5 s resolver stall made `cancelActiveTraces()` wait 5 s (finding 5). An overall
deadline whose error names the phase that was running is the requested API; a resolution
budget is what moving `getaddrinfo` onto the executor needs; a way to read executor pressure
(queued and running operations) is the companion.
- **Known unbounded waits** (#84): `traceClassified` has no overall deadline. An overall
deadline whose error names the phase that was running is the requested API; a way to read
executor pressure (queued and running operations) is the companion.
- **An absolute cutoff for the TCP and UDP probe operations**, as `UDPExchange` has. Their connect
and receive timers are relative and armed after socket setup, on Dispatch's uptime clock, so a
probe can run past `timeout` by its setup time, and by a system sleep.
- **Standalone `getPublicIPs` has no caller-set bound** (finding 9): each STUN exchange is bounded
by `stunTimeout` and each server-name lookup wait by a fixed 20 s, so a stalled resolver holds
the call for about 20 s plus `stunTimeout` (longer if more sweeps than executor workers are
Expand Down
204 changes: 133 additions & 71 deletions Sources/SwiftFTR/Hostname.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,96 +129,75 @@ internal func makeProbeSocketNonBlocking(sockfd: Int32) -> String? {
}
}

/// Dual-stack host resolver shared across `ping()`, `trace()`, and friends.
/// Dual-stack host resolver shared across `ping()`, `trace()`, and friends, synchronously: the
/// inline answers of ``inlineResolution(host:prefer:)``, otherwise ``blockingResolution(host:prefer:substitute:)``
/// with the task's `TestSeams.resolveHost`. Operations resolve through
/// ``resolveDestination(_:prefer:until:clock:handle:)``, which runs the blocking branch in an
/// executor slot.
///
/// Honors `PreferredFamily`:
/// - `.auto`: literal IPs are dispatched by `detectAddressFamily`; hostnames use
/// `getaddrinfo(AF_UNSPEC)` and take the first answer. Darwin's `getaddrinfo`
/// returns addresses in RFC 6724 source/destination ordering, so the first
/// answer is the system-preferred address for an outgoing connection from this
/// host — not an arbitrary one. On a dual-stack host this typically means v6
/// first when a routable v6 path exists, v4 otherwise.
/// - `.auto`: hostnames and most literals use `getaddrinfo(AF_UNSPEC)` and take the first answer.
/// Darwin's `getaddrinfo` returns addresses in RFC 6724 source/destination ordering, so the
/// first answer is the system-preferred address for an outgoing connection from this host. A
/// literal goes through it too, so the system can synthesize an IPv6 address for an IPv4
/// literal on a NAT64 network.
/// - `.v4` / `.v6`: forces the family; throws `.resolutionFailed` if unavailable.
///
/// The canonical printable form (`inet_ntop`) is returned in `ResolvedHost.canonical`,
/// with link-local scope suffix preserved as `addr%ifname` (downstream contract).
///
/// This helper lives at file scope rather than inside a particular executor so
/// `Ping`, `Trace`, and (eventually) the probes can share it without duplication
/// or cross-module coupling. The full resolver-dedup across `TCPProbe.swift` /
/// `UDPProbe.swift` is Stage 5 in `docs/IPV6.md`; this is the smaller extraction
/// that unblocks Stage 2 traceroute.
internal func resolveHost(host: String, prefer: PreferredFamily) throws -> ResolvedHost {
if let substitute = TestSeams.resolveHost { return try substitute(host, prefer) }
if let answer = try inlineResolution(host: host, prefer: prefer) { return answer }
return try blockingResolution(host: host, prefer: prefer, substitute: TestSeams.resolveHost)
}

/// The answer for `host` that needs no resolver, or `nil` when it needs one. Throws for a NUL and
/// for a literal of the other family than a forced one.
///
/// Answered here: a literal of a forced family; under `.auto`, an IPv4 loopback literal, which
/// the system never synthesizes for (Libinfo's `_gai_nat64_can_v4_address_be_synthesized`), and
/// an IPv6 literal with no zone outside fe80::/10, fec0::/10 and ff00::/8, which `getaddrinfo`
/// returns unchanged. A zoned or scoped IPv6 literal (`getaddrinfo` turns `fe80:1::1` into
/// `fe80::1` with scope 1) and every other `.auto` IPv4 literal (NAT64) are left to the resolver.
/// Never consults a test seam, so it can run on any thread.
internal func inlineResolution(host: String, prefer: PreferredFamily) throws -> ResolvedHost? {
// `getaddrinfo` and `inet_pton` would see only the text before a NUL and resolve that instead.
guard !containsNUL(host) else {
throw TracerouteError.resolutionFailed(host: host, details: "contains a NUL character")
}
let detected = detectAddressFamily(host)

// Force-mode fast paths: when the caller explicitly asked for v4 or v6, skip
// getaddrinfo and use the literal directly. This preserves the original
// behavior for callers that know their family and want microsecond resolution.
//
// In `.auto` mode we always go through getaddrinfo (even for literals) so
// macOS's resolver can synthesize a v4-mapped v6 address for v4 literals on
// NAT64 networks (RFC 6147 / Apple's CLAT). On dual-stack networks the
// resolver returns the v4 literal unchanged; on v6-only NAT64 networks it
// returns the synthesized v6 address and the trace/probe goes via v6
// transparently — no caller code changes required. The extra getaddrinfo
// call costs ~tens of microseconds; the NAT64 transparency it buys is worth
// it (matches Apple's own guidance for IPv6-compatible apps).
if prefer == .v4 && detected == AF_INET {
var sin = sockaddr_in()
sin.sin_family = sa_family_t(AF_INET)
sin.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
_ = inet_pton(AF_INET, host, &sin.sin_addr)
var storage = sockaddr_storage()
_ = withUnsafePointer(to: &sin) { src in
withUnsafeMutablePointer(to: &storage) { dst in
memcpy(dst, src, MemoryLayout<sockaddr_in>.size)
}
}
return ResolvedHost(
family: AF_INET, address: storage,
addressLen: socklen_t(MemoryLayout<sockaddr_in>.size), canonical: ipString(sin))
}
if prefer == .v6 && detected == AF_INET6 {
let (bare, scopeID) = parseIPv6Scoped(host)
var sin6 = sockaddr_in6()
sin6.sin6_family = sa_family_t(AF_INET6)
sin6.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
sin6.sin6_scope_id = scopeID
_ = inet_pton(AF_INET6, bare, &sin6.sin6_addr)
var storage = sockaddr_storage()
_ = withUnsafePointer(to: &sin6) { src in
withUnsafeMutablePointer(to: &storage) { dst in
memcpy(dst, src, MemoryLayout<sockaddr_in6>.size)
}
}
return ResolvedHost(
family: AF_INET6, address: storage,
addressLen: socklen_t(MemoryLayout<sockaddr_in6>.size),
canonical: ipv6String(sin6.sin6_addr, scopeID: scopeID))
}
// Mismatched literal vs preferred family throws.
if prefer == .v4 && detected == AF_INET6 {
switch (prefer, detectAddressFamily(host)) {
case (.v4, AF_INET): return ipv4Literal(host)
case (.v6, AF_INET6): return ipv6Literal(host)
case (.v4, AF_INET6):
throw TracerouteError.resolutionFailed(
host: host, details: "Preferred family v4 but literal is v6")
}
if prefer == .v6 && detected == AF_INET {
case (.v6, AF_INET):
throw TracerouteError.resolutionFailed(
host: host, details: "Preferred family v6 but literal is v4")
case (.auto, AF_INET):
var addr = in_addr()
_ = inet_pton(AF_INET, host, &addr)
return UInt32(bigEndian: addr.s_addr) >> 24 == 127 ? ipv4Literal(host) : nil
case (.auto, AF_INET6):
var addr = in6_addr()
guard !host.contains("%"), inet_pton(AF_INET6, host, &addr) == 1 else { return nil }
let (first, second) = (addr.__u6_addr.__u6_addr8.0, addr.__u6_addr.__u6_addr8.1)
let scoped = first == 0xFF || (first == 0xFE && second & 0x80 == 0x80)
return scoped ? nil : ipv6Literal(host)
default:
return nil
}
}

// `.auto` mode (and any hostname path) — let getaddrinfo handle everything,
// including NAT64 synthesis for v4 literals on v6-only networks. The
// `AI_V4MAPPED | AI_ADDRCONFIG | AI_DEFAULT` flag set tells Darwin's resolver
// to synthesize a v4-mapped v6 address when only v6 is configured locally.
/// The resolver branch for `host`: `substitute` when a test supplies one, otherwise
/// `getaddrinfo`. Blocks for as long as the system resolver takes, so it runs in an executor slot.
internal func blockingResolution(
host: String, prefer: PreferredFamily, substitute: TestSeams.ResolveHost?
) throws -> ResolvedHost {
if let substitute { return try substitute(host, prefer) }
// `AI_V4MAPPED | AI_ADDRCONFIG` (`AI_DEFAULT`, not exposed in every Swift overlay) lets Darwin
// synthesize an IPv6 address for an IPv4 literal when only IPv6 is configured (NAT64).
var hints = addrinfo()
hints.ai_socktype = SOCK_DGRAM
// AI_DEFAULT == AI_V4MAPPED | AI_ADDRCONFIG. Hardcoded numeric form below
// because AI_DEFAULT isn't exposed in all Swift overlay versions.
hints.ai_flags = AI_V4MAPPED | AI_ADDRCONFIG
switch prefer {
case .v4: hints.ai_family = AF_INET
Expand Down Expand Up @@ -263,3 +242,86 @@ internal func resolveHost(host: String, prefer: PreferredFamily) throws -> Resol
throw TracerouteError.resolutionFailed(
host: host, details: "No matching address for preferred family")
}

/// How long a trace or ping waits for its destination to resolve (docs/BLOCKING-IO.md, decision 7).
let forwardResolutionLimit: TimeInterval = 20

/// Whether `host` is numeric to the system resolver, so its lookup takes the Literal Lane. Wider
/// than a literal the library parses: the resolver also takes IPv4 shorthand ("127.1"), which
/// `inet_aton` recognizes and `inet_pton` does not. `inet_aton` stops at whitespace and accepts
/// what came before it, so only digits, dots and the hex and octal forms' characters qualify:
/// nothing that could be a name reaches the lane.
internal func isNumericDestination(_ host: String) -> Bool {
if detectAddressFamily(host) != -1 { return true }
guard !host.isEmpty,
host.utf8.allSatisfy({
$0 == 0x2E || Character(UnicodeScalar($0)).isHexDigit || $0 == 0x78 || $0 == 0x58
})
else { return false }
var shorthand = in_addr()
return inet_aton(host, &shorthand) == 1
}

/// Resolves `host` for an operation: inline when ``inlineResolution(host:prefer:)`` answers,
/// otherwise in an executor slot, a literal on the Literal Lane (``literalLookupExecutor``) and a
/// name on the main executor, so stalled name lookups cannot hold back a numeric destination.
///
/// The wait ends at `deadline` on `clock` with `resolutionFailed(details: "timed out")`, and at
/// once when the calling task is cancelled (`CancellationError`) or `handle` is (its reason's
/// error); a `getaddrinfo` already running finishes in its slot. The seam and the executor are
/// read here, on the async side.
internal func resolveDestination(
_ host: String, prefer: PreferredFamily, until deadline: TimeInterval, clock: DiscoveryClock,
handle: TraceHandle? = nil
) async throws -> ResolvedHost {
if let answer = try inlineResolution(host: host, prefer: prefer) { return answer }
let substitute = TestSeams.resolveHost
let lane =
isNumericDestination(host) ? (TestSeams.literalLookupExecutor ?? literalLookupExecutor) : nil
let found = try await withTraceCancellation(handle: handle) {
try await awaitBlockingLookup(until: deadline, clock: clock, on: lane) {
try blockingResolution(host: host, prefer: prefer, substitute: substitute)
}
}
guard let found else {
throw TracerouteError.resolutionFailed(host: host, details: "timed out")
}
return found
}

/// A literal of IPv4, parsed without the resolver. `host` must be one (``detectAddressFamily(_:)``).
private func ipv4Literal(_ host: String) -> ResolvedHost {
var sin = sockaddr_in()
sin.sin_family = sa_family_t(AF_INET)
sin.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
_ = inet_pton(AF_INET, host, &sin.sin_addr)
var storage = sockaddr_storage()
_ = withUnsafePointer(to: &sin) { src in
withUnsafeMutablePointer(to: &storage) { dst in
memcpy(dst, src, MemoryLayout<sockaddr_in>.size)
}
}
return ResolvedHost(
family: AF_INET, address: storage,
addressLen: socklen_t(MemoryLayout<sockaddr_in>.size), canonical: ipString(sin))
}

/// A literal of IPv6, with its `%zone` as the scope, parsed without the resolver.
private func ipv6Literal(_ host: String) -> ResolvedHost {
let (bare, scopeID) = parseIPv6Scoped(host)
var sin6 = sockaddr_in6()
sin6.sin6_family = sa_family_t(AF_INET6)
sin6.sin6_len = UInt8(MemoryLayout<sockaddr_in6>.size)
sin6.sin6_scope_id = scopeID
_ = inet_pton(AF_INET6, bare, &sin6.sin6_addr)
var storage = sockaddr_storage()
_ = withUnsafePointer(to: &sin6) { src in
withUnsafeMutablePointer(to: &storage) { dst in
memcpy(dst, src, MemoryLayout<sockaddr_in6>.size)
}
}
return ResolvedHost(
family: AF_INET6, address: storage,
addressLen: socklen_t(MemoryLayout<sockaddr_in6>.size),
canonical: ipv6String(sin6.sin6_addr, scopeID: scopeID))
}
6 changes: 2 additions & 4 deletions Sources/SwiftFTR/Multipath.swift
Original file line number Diff line number Diff line change
Expand Up @@ -703,10 +703,8 @@ extension SwiftFTR {
throw TracerouteError.sourceIPBindFailed(sourceIP: source, errno: errno, details: message)
}
}
// Literals resolve without `getaddrinfo` under a forced family.
if containsNUL(target) || detectAddressFamily(target) != -1 {
_ = try resolveHost(host: target, prefer: .v4)
}
// A literal, and a NUL, is decided without a resolver under the forced family.
_ = try inlineResolution(host: target, prefer: .v4)
}

/// Runs flow workers that reuse caches without escaping the caller's task group.
Expand Down
8 changes: 6 additions & 2 deletions Sources/SwiftFTR/Ping.swift
Original file line number Diff line number Diff line change
Expand Up @@ -220,8 +220,12 @@ struct PingExecutor: Sendable {
try config.validateForOperation()
try Task.checkCancellation()

// 1. Resolve target, honoring PreferredFamily.
let resolved = try resolveHost(host: target, prefer: config.preferredFamily)
// 1. Resolve target, honoring PreferredFamily, off this thread, within the tracer's
// forward-resolution budget; `config.timeout` is the reply window and is not spent here.
let clock = DiscoveryClock.current
let resolved = try await resolveDestination(
target, prefer: config.preferredFamily, until: clock.now() + forwardResolutionLimit,
clock: clock)
try Task.checkCancellation()

// 2. Create datagram ICMP socket for the resolved family.
Expand Down
Loading
Loading