Compare commits

..
25 Commits
Author SHA1 Message Date
Aleksandr Bogomiakov 7dacc4517e Tighten icon spacing in network cards
Let the metadata grid size its icon column to the glyphs and give the
values the remaining width. Use a three-point gutter for all five
fields on both desktop and Android.

Check the rendered gap on each row at desktop and phone widths. All 45
shared UI tests passed on macOS, along with formatting and workspace
Clippy. The full workspace suite passed on the preceding release commit.
2026-11-26 02:01:24 +02:00
Aleksandr Bogomiakov 43894612ee Fix macOS exit sharing and bring exit selection onto the phone home screen
A Mac could install PF rules and advertise itself while IPv4 forwarding
was still off. Check and enable forwarding when applying the offer and
refresh the physical route when the uplink changes. Try the agent's
existing privileges first. When an existing utun needs additional
permission, the foreground tray or CLI can obtain an administrator grant
scoped to the local UID and overlay subnet. Reconcile the current offer
after the dialog so a withdrawal during authorization stays effective.

A user agent denied a host utun can serve peers over bounded TCP, UDP
and ICMP echo sockets bound to the physical interface. Keep host routes
and ordinary local application traffic on the system-utun path. Preserve
the saved choice for intentionally off-host setups and report readiness
separately.

Report exit selection directly to the selected peer over its authenticated
session. Older peers appear for one minute following forwarded traffic.
The optional announcement trailer remains compatible with control v8.
Local IPC v29 carries the new status and authorization results.

Keep the exit user count, left-aligned names and one-row scroll controls
in a single fixed-height block alongside the network details. Show health
and a small traffic trace on folded cards. Open desktop Devices at a
usable width and keep the exit action clickable in its compact layout.

Replace Android's per-card exit buttons with a fixed thumb-sized control.
The chooser and Quick Settings share one list with a single local option,
network groups, measured latency and an accessible confirmation sheet.

Release the applications and packages as 1.0.9.

On macOS, checked formatting, strict workspace Clippy and the workspace
all-target test suite, including real encrypted agents and loopback TCP,
UDP and ICMP. Ran the opt-in user-mode exit UDP round trip on a physical
IPv4 interface. Verified the authorization scripts and syntax of their
PF, sudoers and AppleScript components. The privileged two-utun kernel
test is reserved for an isolated macOS runner. Rendered phone and desktop
layouts in both themes, built the arm64 Android debug APK and cross-
checked all workspace targets for Windows GNU.
2026-11-26 01:57:51 +02:00
Aleksandr Bogomiakov d8b7787430 Keep the devices window responsive and make traffic flows sortable
A waiting peer or speed-test animation in an immediate egui viewport
repainted the parent and its other windows. Each pass also supersampled
the same 64-pixel logo and handed the new allocation to the OS. Give
each Devices window its own repaint schedule. Wake it when status or
shared controls change, reuse the native icon, and skip measuring the
wide roster when its remembered minimum width exceeds the viewport.
Use the bundled Phosphor StopCircle for single and batch tests.

Bind incoming throughput probes to the signed address pair for the
running diagnostic. Cache its validity across packets under a routing
revision. A change of ownership, including removal or reassignment,
revalidates the pair under the routing read lock. This removes a lock
and a linear peer search from the steady-state receive path and keeps
the timing, byte limits and wire protocol compatible.

Give the traffic inspector a pinned header and compact, aligned rows
with readable text in both themes. The column chooser keeps the peer
visible on a narrow screen. Clicking a header sorts the complete
filtered capture with a stable cursor across pages. Maintain one sort
index on the window's scratch database and expire idle rates there.
Address sorting uses numeric IP and port values. Peer and network
sorting follows displayed names, including live name changes.

Bump the applications, Android package and Nix package to 1.0.8.
On macOS, verified formatting, workspace Clippy and all-target tests,
including real encrypted tests between local agents. Rendered the
monitor in light and dark desktop themes and at phone width. Built the
arm64 Android debug APK and cross-checked the Windows GNU target.
Across 500 optimized viewport updates, egui produced 500 native icon
replacements on 1.0.7 and zero with this change.
2026-11-25 21:57:14 +02:00
Aleksandr Bogomiakov b47acb8321 Fix peer speed measurements and fit compact traffic counters
A slow first download could make the rate search settle around 60 Mbit/s
on a much faster link. A final faster train could also exhaust the byte
budget before its feedback reached the sender. Reprobe above the first
apparent limit and use unique payload actually delivered over sustained
sender and receiver intervals. Count each submitted packet even when the
tunnel is backpressured, and keep the unused part of the pacing batch
available. The five-second deadline, metered limits and v1 wire format
remain compatible with existing peers.

Show achieved Mbit/s in the devices list and describe a lower bound in
the tooltip. Reserve a font-measured TX/RX width independent of changing
byte counts on narrow desktop windows and landscape Android. Support
counters through exabytes and retain exact packet counts. Align the
application, Android and Nix versions for 1.0.7.

On a shaped 300/250 Mbit/s path with a cold download, the regression
measured 295/247 Mbit/s after the fix and 59/244 on 1.0.6. The suite
also covers trailing feedback, local tunnel pressure and compact layouts
at multiple font sizes and display densities. Mixed 1.0.6/1.0.7 speed
sessions completed in both roles. Two unmetered runs over real WireGuard
on loopback measured 251 and 250 Mbit/s down and completed both directions
in 3.0 and 3.1 seconds.

On macOS arm64, workspace formatting and strict Clippy passed, and the
locked all-targets suite passed 646 tests with six opt-in tests ignored.
Cargo also reported the existing directories manifest warning. The GNU
Windows workspace cross-check and Android arm64 debug APK build passed.
2026-11-25 20:46:43 +02:00
Aleksandr Bogomiakov e3b74babba Add an on-demand traffic monitor to the tray and Android
Show bidirectional IP conversations with network and peer names, ports,
traffic roles, packet totals and directional rates. Aggregate ICMP echoes
by address pair. Attribute exit requests and replies from each endpoint's
perspective and match VIP traffic on the client-facing side of NAT. Keep
authenticated control sessions and opaque relay pairs in a transport view.

Each open window owns a bounded interval subscription. The idle path only
checks whether a reader exists. Contended writers can use another lane,
and observations lost under load are counted without delaying forwarding.
Use a dedicated local control connection on desktop and a service handle
on Android. Closing or backgrounding the Android screen releases capture.
The local IPC format advances to 28. Existing mesh peers and databases
remain compatible.

Accumulate intervals off the render thread in a private temporary SQLite
database. Expire inactive rows after a minute or retain them until close.
Indexed, cursor-based pages keep long sessions out of UI memory. Closing
the window interrupts pending queries and releases the scratch database.

On macOS arm64, workspace formatting and strict Clippy passed. The locked
all-targets workspace suite passed 641 tests with five opt-in tests ignored.
Coverage includes real WireGuard exit traffic in both directions, local IPC
lifetime, Android pause/resume, relay opacity, VIP translation, bounded
capture, simulated three-day retention and 320–900 point layouts. The
Windows GNU workspace cross-check and the offline Android arm64 debug APK
build passed. Windows and Android hardware were not exercised.
2026-11-25 20:19:40 +02:00
Aleksandr Bogomiakov 7afed15f76 Release Tsunagi 1.0.6
Align the application packages, internal dependency requirements, lockfile,
Android version name and Nix package with this release. The optional peer
speed test negotiates its own version-one wire format. Existing network
identities and stored configurations work across the upgrade.

On macOS arm64 the locked workspace test run passed 632 tests with five
opt-in tests ignored. Workspace formatting and strict Clippy passed. The
Windows GNU workspace cross-check and strict Windows core Clippy passed.
The independent Linux namespace and socket regressions are recorded in
the routing commit. The local ARM64 debug APK reports versionName 1.0.6.
2026-11-25 19:34:49 +02:00
Aleksandr Bogomiakov e7de9b44af Keep forwarded exit traffic on the gateway’s own uplink
When A selects B and B selects C, B’s own default route must not carry A’s
forwarded packets on to C. Accept only locally sourced overlay traffic for
the client default, while keeping authenticated member traffic on the
physical uplink from its first packet. Replies still route to the owning
member. Switching B’s default does not tear down A’s existing flows.

On Linux, distinguish forwarded packets and SNAT replies from local
traffic, including strict reverse-path checks when the agent runs as
root. On macOS, tag packets on the offered utun and keep their PF NAT
state on the physical interface. On Windows, use interface-bound sockets
and a bounded smoltcp TCP endpoint, UDP flow mappings and ICMP echo. An
offer and its live sockets survive changes to the client's split routes
and transient uplink discovery failures. Remove only owned legacy WinNAT
objects. Document the supported IPv4 protocols and resource limits.

Real WireGuard agents exercised A, B and C. Two Linux ARM64 namespace
tests passed in an isolated Colima container with strict reverse-path
filtering. The same destination saw A keep its physical SNAT TCP session
while B's local connections switched to C and back. Strict Linux core
Clippy passed. Six portable socket regressions passed on macOS, including
TCP resets, both half-close orders, UDP port stability and resource limits.

The macOS PF rules passed native syntax checking and the Windows target
cross-compiled on macOS. Extended privileged macOS and Windows fixtures
are available in CI; neither native system routing test ran on this host.
2026-11-25 19:34:27 +02:00
Aleksandr Bogomiakov 200e716c28 Measure live peer throughput on the encrypted mesh path
Advertise an optional versioned diagnostic to authenticated peers. A small
control exchange negotiates limits and carries receiver feedback. Paced
IPv4 probes enter the ordinary WireGuard tunnel and follow its current
carrier or relay. Accept them only for an active session and the peer's
actual signed address pair. Agents without the capability still exchange
normal mesh traffic.

Raise the offered rate using receiver-clock windows and unique payload
bytes. Require sustained delivery before reporting a rate, distinguish a
lower bound from a measured ceiling, and discard interrupted live values.
An agent runs one exchange at a time, with a five-second deadline and a
cap at both ends. Queued exit tests share a separate batch budget. Keep
bounded per-network results in memory and cancel on session replacement,
network removal or a change to a metered underlay.

Add a fixed speed cell to desktop and Android device views. Show direction
and live rate, let a click on the result rerun the test, and offer a
stoppable sequential test of compatible exit nodes. Expose local actions
and progress over IPC v27. Mesh identity and stored state are unchanged.

On macOS arm64 the real WireGuard test covered both directions, a
control-only peer, the responder's metered limit and stopping a repeat.
The three-peer exit batch test passed. The diagnostic crate passed 17
tests including shaped throughput, loss, delay, duplication and bursts.
All 33 shared UI tests passed. Strict Clippy passed for the diagnostic
and core libraries and an ARM64 Android debug APK was built.
2026-11-25 19:25:58 +02:00
Aleksandr Bogomiakov fb7a959d23 Restore WireGuard tunnels after rapid reconnects and log QUIC closes
A peer can leave and return with the same WireGuard public key between
reconciliation passes. The old reader then stays attached to a closed
logical channel even though the carrier is up. Retain a tunnel only while
its endpoint, announced key and open channel still match. Stop retired
readers and start a handshake on the replacement channel. Carrier changes
under the same channel keep the session and traffic counters.

Record the newest channel before waking the worker, including while a
network key is loading. A burst that fills the bounded command queue can
now delay a sync without losing the channel the core handed over.

Capture the QUIC close cause before local session cleanup. Include the
network name and last known peer hostname alongside their IDs in the
disconnect log. Report transport and application codes without copying
arbitrary peer-supplied close text. The in-process disconnect event gains
name fields. Mesh protocols, local IPC and storage formats stay compatible.

On macOS arm64 both the loopback reconnect and close-code tests failed
before the fix. The locked workspace suite now passes 606 tests with five
opt-in tests ignored. It covers bidirectional IP after reconnect and a
saturated notification queue. Formatting and strict workspace Clippy passed.
2026-11-25 18:22:50 +02:00
Aleksandr Bogomiakov 6a0a87e76c Keep the selected exit ready and report idle tunnels in 1.0.5
Read the exit network and endpoint from the published routing choice.
Start a normal WireGuard exchange at 120 seconds for that tunnel even
when idle. BoringTun keeps the current key usable during the exchange
and owns retry and expiry. Switching or clearing the route also moves
or removes the renewal policy.

Show Idle in the tray, on Android and in CLI status after 30 seconds
without IP traffic on a previously established tunnel. Keep key changes
and keepalives out of activity, and keep waiting packets, missing paths
and transport errors visible. Preserve queued flow tags when a native
keepalive occupies a slot and drain pending IP on key confirmation.

Bump the local status IPC to 26 and update the workspace, Android and
Nix versions. Upgrade the daemon and desktop clients together. Mesh
protocols, key lifetimes and persistent storage remain compatible.

On macOS arm64 the initial workspace run passed 602 tests. A separate
181-second two-agent test observed renewal only in the selected mesh
and delivered its first internet packet after idle. Formatting and
strict workspace Clippy passed on the release sources. The maintainer
requested publication without waiting for another full test run.
2026-11-25 16:57:10 +02:00
Aleksandr Bogomiakov e3e6089d0b Adapt mesh views to phone rotation and toggle the exit from Quick Settings
Use the available width for the Android device table, keeping individual
peers expandable and their full details reachable in both orientations.
Show network selection and settings side by side in landscape and reuse
the VIP editor with a compact toolbar and width-aware backend columns.
Retain the selected network, expanded peer, traffic unit and VIP draft
across rotation.

Show data-channel readiness consistently in the tray and on Android.
Distinguish an establishing channel, a disabled data plane, an offline
peer and a transport failure. Use an animated arc for visible waiting
peers. Explain Phosphor controls on hover, focus and long press, and
provide a masked-by-default reveal button in the shared secret field.

Store the last confirmed exit network and endpoint in Android's private
preferences. A Quick Settings tap disconnects that selection or restores
the exact peer through the existing agent. First use opens the chooser.
On a cold start, wait for an authenticated exit offer outside the command
loop. Check the current selection again before changing the route. Only
changed exit offers wake roster subscribers. Wire formats, software
version and mesh identity storage remain compatible.

On macOS arm64, cargo fmt and strict workspace Clippy passed. The locked
workspace suite passed 598 tests with four opt-in tests ignored. Built the
tray, the ARM64 debug APK and its test APK. All three instrumentation tests
passed on an Android API 37 emulator. Opened the chooser from the actual
Quick Settings tile, rotated the activity and inspected rendered device
lists with ready, waiting, failed and offline peers. Physical phones and
native Linux and Windows builds were not exercised.
2026-11-25 15:38:10 +02:00
Aleksandr Bogomiakov 50c0ecea45 Reduce idle mesh traffic and Android background work for 1.0.4
A phone keeping its mesh online was paying for two data-path probe exchanges
per WG or AWG link, repeated control snapshots, and a full Android status
and DNS rebuild every two seconds while the activity was closed.

Let a timely, authenticated reply of the requested size on the physical
carrier satisfy its native delivery check. Keep the full-sized probe, RTT
window, loss thresholds, roaming, and independent silence detection. Resume
native probes when shared confirmations go stale and answer both probe
formats throughout the lifetime of the pair.

Index the latest signed objects once per network. Each reliable session
sends a full snapshot on connect and advances its cursor only when a frame
enters its send queue. Reopen the affected stream if a replica cannot
persist a received update. Send canonical peer hints in bounded batches,
publish changed edges immediately, and refresh reachability ahead of its
90-second expiry. The scheduling revisions live in memory and peers use
the existing wire formats and database schema.

Drive Android DNS and selected-exit notifications from coalesced roster
changes. The visible activity requests fresh counters, reusing the current
DNS zones. Set the workspace, Android, and Nix package versions to 1.0.4.

Formatting and strict workspace Clippy passed on macOS arm64. The locked
workspace suite passed 594 tests with four opt-in checks ignored. Both
Android instrumentation tests passed on an API 37 arm64 emulator. Tested
mixed 1.0.3/1.0.4 pairs on WG and AWG. In a 30-second idle WG comparison,
one endpoint's combined UDP bytes fell from 220950 to 138596 and its
control messages from 24 to 2. Physical phone discharge and native Linux
and Windows runs remain unverified.
2026-11-25 15:04:07 +02:00
Aleksandr Bogomiakov 8c4c2fa34e Fold network cards and show which peer carries exit traffic
Start the tray and Android overviews with each network folded under its
bold name. Keep the selected exit, its host name and its sent and received
byte totals visible. Put VIP beside Copy secret and Show devices.

Default to bytes and make the unit switch update the desktop traffic
column, totals, rates and plots together. Open the devices window at
1000 points wide and bound the network and per-peer plots. Use both sides
of the phone detail view for transport, latency, version and traffic.

Attach counters to the current network and exit peer. Count off-mesh IP
bytes after carrier acceptance and replies after local interface delivery.
Changing the selection starts new totals. Ordinary mesh traffic to the
same peer and rejected packets stay out of the exit counters.

Advertise the agent release as an optional bounded trailer on an
authenticated control v8 announcement. Older readers can ignore it and
older peers display an unknown version. Release labels live for the
session and do not participate in authentication or wire negotiation.
The new status fields require local IPC v25, so update the daemon, CLI
and tray together. Existing mesh identities and databases need no migration.

On Android, request system interface consent on the first app launch.
Respect an explicit stop or declined consent across launches. Start
Tsunagi Agent re-enables automatic startup.

Checked formatting and strict workspace Clippy on macOS arm64. The full
locked workspace suite passed 588 tests with four opt-in tests ignored.
Built the tray and Android debug APKs. Both instrumentation tests passed
on an Android 37 arm64 emulator, including app startup, stop and restart.
Checked the first-run permission prompt and the rendered phone and desktop
layouts. Native Linux and Windows tests were not run on this host.
2026-11-25 14:33:50 +02:00
Aleksandr Bogomiakov f9f67f88b1 Prepare the 1.0.3 release
Promote the confirmed release candidate to 1.0.3 across the workspace packages, internal dependency requirements, lockfile, Android app and Nix package. The change is limited to release metadata. Tests were skipped at the maintainer's request.
2026-11-25 04:22:24 +02:00
Aleksandr Bogomiakov a189d0ad3e Preserve mesh transport through an internet exit in 1.0.3-rc1
On macOS a connected socket using the physical source lost its route before
PF could see the packet. Fresh sockets could leave via the physical uplink,
but Darwin rejected reverse-NAT replies delivered to a utun address there.
With two live meshes remote control and data sessions expired within a minute.

Install matching interface-scoped uplink routes before capturing the two
unscoped defaults. Keep PF state on the physical interface, preserve transport
ports and return tagged replies via loopback. Reconcile uplink changes and
recover only owned routes using a private journal and kernel markers. On
Windows keep existing LAN routes, retain recent verified reconnect paths and
refresh the gateway and relay DNS without replacing the split defaults.

Exercise two memberships of the same peer, new and established native
transport sockets, ordinary application traffic and scoped route cleanup.
Run hosted macOS and Windows native regressions on affected changes. Bump the
packages to 1.0.3-rc1 and encode Debian prereleases with a tilde so apt can
upgrade to the final release. Mesh wire formats and identities are unchanged.

Checked workspace formatting, strict Clippy and the full workspace suite on
macOS (586 passed, four opt-in tests skipped by default). The privileged macOS
kernel test passed separately. A launchd trial of the RC kept master and ch
reachable over both meshes and used the external exit past the original
timeout. Disabling the exit restored the physical IP and cleared the routes.
Linux ARM64 passed four real-agent exit tests and the privileged netns
regression. The RC APK passed the dual-subnet UDP/ICMP test on an Android 37
ARM64 emulator. Verified Debian and pacman version ordering. Native Windows
execution is covered by the hosted workflow and was not run on this Mac.
2026-11-25 03:47:49 +02:00
Aleksandr Bogomiakov 32aa73721a Keep every active mesh reachable through a single internet exit
With several IPv4 aliases on a single TUN, the default route could select an address from a different mesh. The exit peer then rejected internet traffic as an invalid source. Concurrent cross-network exit selections could also clear each other in the running agent while SQLite kept one winner.

Serialize validated exit choices with network lifecycle and persist each choice before publishing it to the shared routing table. Replace the previous exit atomically and preserve it across allocation updates. Both mesh subnets keep their own routes. Only replies from the selected exit to the local address of its network qualify for the external-source exception.

Prefer the selected source on Linux and macOS default routes. Preserve physical transport paths and update split routes in place. On Windows reuse the Android packet translation to restore off-mesh TCP, UDP and ICMP replies to the original local socket. Existing databases, IPC commands and wire protocols remain compatible.

On macOS, formatting and strict workspace Clippy passed. The full locked workspace suite passed 577 tests with three ignored, after correcting a stale Windows script-test matcher. Three real agents covered switching, concurrent selection, offline isolation and restart. On Linux arm64, 88 focused tests and the privileged kernel routing/firewall test passed. The Android arm64 library built and linked. Wintun and privileged macOS utun were not exercised on live hosts.
2026-11-25 02:32:09 +02:00
Aleksandr Bogomiakov 21b8381fa3 Restore Homebrew publication after stable GitHub releases
The v1.0.2 build published a valid macOS archive, but its release workflow lacked the Homebrew job that published v1.0.0. Restore the job, updater, tests and setup notes from a707076 alongside the existing Arch and OpenArtifact jobs.

Verify the Apple Silicon archive against the published GitHub digest before updating the CLI formula and GUI cask in one tap commit. Skip prereleases and older versions, and retry from the current tap head after a concurrent push. Use the existing HOMEBREW_TAP_TOKEN with the same tap and branch.

On macOS, all three updater tests passed. Exercised the workflow shell with the real v1.0.2 archive, mocked release transport and a local Git remote, including checksum rejection, concurrent updates and retries. Actionlint and ShellCheck passed with the old actionlint runner list exception for ubuntu-26.04. Workspace formatting and strict Clippy passed. All 568 default tests passed with three ignored after enabling loopback for the test run. No live workflow was triggered.
2026-11-25 01:11:33 +02:00
Aleksandr Bogomiakov ee77ddb9ac Prepare the 1.0.2 release
Set package versions and internal dependency requirements to 1.0.2 throughout the workspace, lockfile, Android app and Nix package. The optional link comparison uses the existing mesh wire versions. Upgrade the CLI and tray with the local agent for IPC v24.

Checked locked Cargo metadata and tsng --version. Workspace formatting and strict Clippy passed on macOS, and 568 tests passed with three opt-in checks skipped by default. Native elevated macOS utun and Windows Wintun source selection passed on hosted runners. Verified Linux kernel source selection in a disposable network namespace and bidirectional UDP and system ping on an Android API 37 ARM64 emulator.
2026-11-25 00:12:11 +02:00
Aleksandr Bogomiakov 219bd018db Let healthy carrier comparisons recover from startup probe loss
The first probe on a newly opened carrier can precede the responder’s private health profile. Keep measuring for up to 30 seconds if the 20-probe window still contains losses or too few samples. A clean link still qualifies after six seconds. The ordinary 60-percent link failure detector continues to count every missed probe.

Tested the acquisition, recovery, insufficient data and persistent-loss decisions. The slow TLS and fast QUIC loopback fixture can expose its measurements through the existing test logging switch. Workspace Clippy and formatting passed.
2026-11-25 00:09:53 +02:00
Aleksandr Bogomiakov 15a4e45710 Prioritize live traffic recovery over a stalled carrier comparison
When the incumbent went down during a background dial, an unrelated healthy third carrier could wait up to 30 seconds. Restore the configured fallback order immediately if another carrier is eligible. Cancel the pending dial and invalidate its result so a late link cannot overwrite recovery. Keep the comparison alive if it is the only available fallback.

Reproduced the timeout with two loopback agents, a real WG carrier, a stalled TLS handshake and QUIC. All four carrier integration tests passed after the change, including bidirectional delivery over the recovered path. Workspace formatting and Clippy passed on macOS.
2026-11-25 00:05:51 +02:00
Aleksandr Bogomiakov 972b98363d Restore the socket source address across Android mesh networks
Android VpnService routes can select the primary VPN address for traffic to a second subnet even when both aliases are installed. Keep a bounded binding at the local TUN boundary so the peer receives the source it owns in that network and the original Android socket receives the reply. Preserve native primary traffic, separate per-subnet capacity, handle fragmented IPv4 and quoted ICMP errors, and retain eligible bindings when VpnService replaces its descriptor.

Support TCP, UDP and ICMP echo. An ambiguous tuple retains its original binding. Explicitly bound traffic for other IPv4 protocols passes using the proper network address. Mesh authentication, address admission and wire formats stay unchanged.

Reproduced the wrong source on a disposable Android API 37 ARM64 emulator. After the fix, system ping and an unbound connected UDP socket both received replies across each real VPN subnet. Built both debug APKs and confirmed that only the instrumentation APK includes its helper. Eleven focused Rust checks cover reverse mapping, checksums, fragments, limits and reconfiguration.
2026-11-25 00:03:02 +02:00
Aleksandr Bogomiakov 2e83483f00 Restore Windows native test compilation
The real Wintun check exposed three Windows-only test calls that predated the access argument to ControlSocket::bind. Pass Private for these isolated named pipes, matching the Unix fixtures. Run native subnet checks for edits to the underlying TUN implementation as well.

Confirmed the first hosted Windows compilation failed on exactly these calls. The revised Windows checks run on the hosted runner. Production IPC behavior is unchanged.
2026-11-25 00:00:16 +02:00
Aleksandr Bogomiakov 27e29cf8a7 Keep concurrent overlays working and select faster data carriers
A second subnet on macOS could send with the first utun alias. Reconcile and verify each owned subnet route with its actual source, retry partially applied plans and expose host errors to clients. On Windows verify the alias and prefix on the intended adapter. Do not restart underlay sockets when the only network change is a local overlay address.

Compare mutually enabled carriers using authenticated data probes while the incumbent carries traffic. The dialler coordinates a generation-scoped decision after a sustained median RTT improvement. Old peers retain ordered fallback. Local IPC moves to v24 to report data RTT and the physical path independently of control RTT. The mesh wire versions, keys and saved network settings stay compatible.

Validated formatting, workspace Clippy and the workspace test suite on macOS, including bidirectional dual-network traffic and a live TLS-to-QUIC switch on loopback. Added focused native CI tests for macOS and Windows. The elevated utun test requires administrative access unavailable on the development host.
2026-11-24 23:55:55 +02:00
Aleksandr Bogomiakov 8d107cf0e9 Declare installer and tray dependencies in Linux packages
Require adduser on Debian and shadow on Arch for the package installation hooks. For GUI packages, derive the minimum glibc version from the tray ELF imports so the dependency follows the binary built by each runner.

Checked generated Debian control files and Arch package metadata for both variants on macOS using the released tray binary (glibc 2.43). Checked shell syntax; no Rust changes or release rebuild.
2026-11-24 22:11:42 +02:00
Aleksandr Bogomiakov 01b51081c3 Publish pacman packages with the version from PKGINFO
OpenArtifact validates the upload path against the full Arch package version. Keep the release assets as built and derive the registry filename, including its epoch, from the package metadata. Duplicate checks use the same URL.

Checked actionlint, Bash syntax and the upload paths for all four SHA-256-verified v1.0.1 Arch release assets.
2026-11-24 21:44:03 +02:00
172 changed files with 22565 additions and 2441 deletions

No files matched your search

+42
View File
@@ -0,0 +1,42 @@
import tempfile
import unittest
from pathlib import Path
from update_homebrew import update_tap
class UpdateTapTest(unittest.TestCase):
def setUp(self):
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
self.tap = Path(directory.name)
self.formula = self.tap / "Formula/tsunagi.rb"
self.cask = self.tap / "Casks/tsunagi-gui.rb"
self.formula.parent.mkdir()
self.cask.parent.mkdir()
self.old_hash = "a" * 64
self.new_hash = "b" * 64
self.formula.write_text(f' VERSION = "1.9.0"\n SHA256 = "{self.old_hash}"\n')
self.cask.write_text(f' version "1.9.0"\n sha256 "{self.old_hash}"\n')
def test_updates_both_packages_and_allows_retry(self):
for _ in range(2):
update_tap(self.tap, "v1.10.0", self.new_hash)
self.assertEqual(self.formula.read_text(), f' VERSION = "1.10.0"\n SHA256 = "{self.new_hash}"\n')
self.assertEqual(self.cask.read_text(), f' version "1.10.0"\n sha256 "{self.new_hash}"\n')
def test_older_release_does_not_replace_either_package(self):
before = self.formula.read_bytes(), self.cask.read_bytes()
update_tap(self.tap, "v1.8.9", self.new_hash)
self.assertEqual((self.formula.read_bytes(), self.cask.read_bytes()), before)
def test_invalid_release_or_cask_leaves_formula_untouched(self):
before = self.formula.read_bytes()
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0-rc.1", self.new_hash)
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0", "invalid")
self.cask.write_text(' version "1.9.0"\n')
with self.assertRaises(ValueError):
update_tap(self.tap, "v1.10.0", self.new_hash)
self.assertEqual(self.formula.read_bytes(), before)
+51
View File
@@ -0,0 +1,51 @@
"""Update the tap's formula and cask for a verified macOS release archive."""
import argparse
import re
from pathlib import Path
VERSION = r"(?:0|[1-9][0-9]*)(?:\.(?:0|[1-9][0-9]*)){2}"
SHA256 = r"[0-9a-f]{64}"
def update_tap(tap: Path, tag: str, checksum: str) -> None:
if not re.fullmatch(f"v{VERSION}", tag):
raise ValueError("expected a stable vMAJOR.MINOR.PATCH release")
if not re.fullmatch(SHA256, checksum):
raise ValueError("expected a SHA-256 digest")
version = tag[1:]
updates = {}
for filename, version_field, hash_field in (
("Formula/tsunagi.rb", "VERSION = ", "SHA256 = "),
("Casks/tsunagi-gui.rb", "version ", "sha256 "),
):
path = tap / filename
original = path.read_text()
version_pattern = rf'^( {version_field}")({VERSION})(")$'
hash_pattern = rf'^( {hash_field}")({SHA256})(")$'
current = re.findall(version_pattern, original, re.MULTILINE)
if len(current) != 1 or len(re.findall(hash_pattern, original, re.MULTILINE)) != 1:
raise ValueError(f"expected one version and one SHA-256 in {filename}")
if tuple(map(int, version.split("."))) < tuple(map(int, current[0][1].split("."))):
print(f"Skipping older release {tag}: {filename} already has {current[0][1]}")
return
updated = re.sub(version_pattern, rf"\g<1>{version}\g<3>", original, flags=re.MULTILINE)
updated = re.sub(hash_pattern, rf"\g<1>{checksum}\g<3>", updated, flags=re.MULTILINE)
updates[path] = (original, updated)
for path, (original, updated) in updates.items():
if updated != original:
path.write_text(updated)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("tap", type=Path)
parser.add_argument("tag")
parser.add_argument("checksum")
args = parser.parse_args()
try:
update_tap(args.tap, args.tag, args.checksum)
except (OSError, ValueError) as error:
parser.exit(1, f"{error}\n")
+3 -1
View File
@@ -2,7 +2,7 @@ name: CI
on:
push:
branches: [main]
branches: [master, main]
pull_request:
workflow_dispatch:
@@ -25,6 +25,8 @@ jobs:
- uses: Swatinem/rust-cache@v2
- run: cargo fmt --all -- --check
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
- name: Check Debian release candidate upgrade ordering
run: bash dist/deb/test-deb.sh
test:
name: test (${{ matrix.os }})
+101 -3
View File
@@ -412,6 +412,99 @@ jobs:
'{event_type: "new_package", client_payload: {repository: $repository, tag: $tag}}' \
| gh api --method POST repos/house-of-vanity/arch_repo/dispatches --input -
update-homebrew:
name: Update the Homebrew tap
needs: publish
if: github.server_url == 'https://github.com' && github.repository == 'house-of-vanity/tsunagi'
runs-on: ubuntu-latest
permissions:
contents: read
env:
RELEASE_TAG: ${{ github.ref_name }}
steps:
- name: Check the release tag and tap credentials
id: stable
env:
TAP_TOKEN: ${{ secrets.HOMEBREW_TAP_TOKEN }}
run: |
set -euo pipefail
if [[ ! "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]]; then
echo "Skipping Homebrew for non-stable tag $RELEASE_TAG"
exit 0
fi
if [[ -z "$TAP_TOKEN" ]]; then
echo '::error::Set HOMEBREW_TAP_TOKEN with Contents: write access to house-of-vanity/homebrew-tap.'
exit 1
fi
echo "publish=true" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v5
if: steps.stable.outputs.publish == 'true'
with:
persist-credentials: false
- name: Verify the published macOS archive
if: steps.stable.outputs.publish == 'true'
id: archive
env:
GH_TOKEN: ${{ github.token }}
run: |
set -euo pipefail
archive="tsunagi-macos-aarch64-${RELEASE_TAG#v}.tar.gz"
digest=$(gh api "repos/$GITHUB_REPOSITORY/releases/tags/$RELEASE_TAG" \
| jq -er --arg archive "$archive" '
select(.draft == false and .prerelease == false)
| .assets[] | select(.name == $archive and .state == "uploaded")
| .digest | select(type == "string" and test("^sha256:[0-9a-f]{64}$"))
')
gh release download "$RELEASE_TAG" --repo "$GITHUB_REPOSITORY" \
--pattern "$archive" --dir "$RUNNER_TEMP"
hash="${digest#sha256:}"
actual=$(sha256sum "$RUNNER_TEMP/$archive")
if [[ "${actual%% *}" != "$hash" ]]; then
echo "::error::SHA-256 mismatch for $archive."
exit 1
fi
echo "hash=$hash" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@v5
if: steps.stable.outputs.publish == 'true'
with:
repository: house-of-vanity/homebrew-tap
ref: main
path: homebrew-tap
token: ${{ secrets.HOMEBREW_TAP_TOKEN }}
- name: Update and push the formula and cask
if: steps.stable.outputs.publish == 'true'
env:
ARCHIVE_SHA256: ${{ steps.archive.outputs.hash }}
run: |
set -euo pipefail
# Retry from the latest tap state if another publisher pushes first.
for attempt in 1 2 3; do
git -C homebrew-tap fetch origin main
git -C homebrew-tap checkout --detach --force FETCH_HEAD
python3 .github/scripts/update_homebrew.py homebrew-tap "$RELEASE_TAG" "$ARCHIVE_SHA256"
cd homebrew-tap
ruby -c Formula/tsunagi.rb
ruby -c Casks/tsunagi-gui.rb
if git diff --quiet -- Formula/tsunagi.rb Casks/tsunagi-gui.rb; then
exit 0
fi
git config user.name 'github-actions[bot]'
git config user.email '41898282+github-actions[bot]@users.noreply.github.com'
git add -- Formula/tsunagi.rb Casks/tsunagi-gui.rb
git commit -m "tsunagi ${RELEASE_TAG#v}"
if git push origin HEAD:main; then
exit 0
fi
echo "Push to the Homebrew tap failed on attempt $attempt of 3." >&2
cd ..
done
echo '::error::Could not push the updated formula and cask to the tap.'
exit 1
publish-openartifact:
name: Publish APT and pacman packages
needs: publish
@@ -455,9 +548,14 @@ jobs:
"$OA_SERVER/api/v1/repositories/hexor-apt/debs")
;;
*.pkg.tar.zst)
stem=${name%.pkg.tar.zst}
arch=${stem##*-}
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$name"
# Release asset names omit the epoch. OpenArtifact matches the
# upload path against the full version recorded in .PKGINFO.
pkginfo=$(tar --zstd -xOf "$file" .PKGINFO)
pkg=$(sed -n 's/^pkgname = //p' <<< "$pkginfo")
version=$(sed -n 's/^pkgver = //p' <<< "$pkginfo")
arch=$(sed -n 's/^arch = //p' <<< "$pkginfo")
: "${pkg:?missing pkgname}" "${version:?missing pkgver}" "${arch:?missing arch}"
url="$OA_SERVER/repos/hexor-pacman/os/$arch/$pkg-$version-$arch.pkg.tar.zst"
status=$(curl -sS -o "$RUNNER_TEMP/oa-upload.json" -w '%{http_code}' \
"${auth[@]}" -T "$file" "$url")
;;
+120
View File
@@ -0,0 +1,120 @@
name: Native subnet source selection
on:
push:
branches: [master]
paths:
- '.github/workflows/subnet-source.yml'
- 'crates/tsunagi-core/src/overlay/egress.rs'
- 'crates/tsunagi-core/src/overlay/egress/**'
- 'crates/tsunagi-core/src/overlay/interface.rs'
- 'crates/tsunagi-core/src/overlay/router.rs'
- 'crates/tsunagi-core/src/overlay/hostrules/linux_exit*.rs'
- 'crates/tsunagi-core/src/overlay/provision/linux.rs'
- 'crates/tsunagi-core/src/overlay/hostrules/macos*.rs'
- 'crates/tsunagi-core/src/overlay/hostrules/macos/**'
- 'crates/tsunagi-core/src/overlay/hostrules/windows*.rs'
- 'crates/tsunagi-core/src/overlay/provision/macos.rs'
- 'crates/tsunagi-core/src/overlay/provision/windows.rs'
- 'crates/tsunagi-core/src/overlay/provision/mod.rs'
- 'crates/tsunagi-core/src/overlay/provision/factory.rs'
- 'crates/tsunagi-core/src/overlay/tun.rs'
- 'crates/tsunagi-core/src/net.rs'
workflow_dispatch:
permissions:
contents: read
jobs:
source:
if: github.server_url == 'https://github.com'
runs-on: ${{ matrix.os }}
timeout-minutes: 45
strategy:
fail-fast: false
matrix:
include:
- os: ubuntu-latest
test: overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit
- os: macos-latest
test: overlay::provision::macos::tests::unbound_sockets_choose_each_networks_source_on_one_real_utun
- os: windows-latest
test: overlay::provision::windows::tests::two_windows_subnets_choose_their_own_source_and_survive_removal
env:
TEST_NAME: ${{ matrix.test }}
CARGO_PROFILE_TEST_DEBUG: '0'
steps:
- uses: actions/checkout@v4
with:
persist-credentials: false
- uses: dtolnay/rust-toolchain@stable
- uses: Swatinem/rust-cache@v2
- name: Build and locate the native test
shell: pwsh
run: |
$artifacts = @(cargo test --locked -p tsunagi-core --lib --features tun-device --no-run --message-format=json-render-diagnostics |
ForEach-Object { ConvertFrom-Json -InputObject $_ } |
Where-Object { $_.reason -eq 'compiler-artifact' -and $_.target.name -eq 'tsunagi' -and $_.profile.test -and $_.executable })
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($artifacts.Count -ne 1) { throw "Expected one core test binary, found $($artifacts.Count)" }
$binary = $artifacts[0].executable
$tests = @(& $binary --ignored --exact $env:TEST_NAME --list)
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($tests -notcontains "$($env:TEST_NAME): test") { throw "Missing ignored test: $env:TEST_NAME" }
"TEST_BINARY=$binary" >> $env:GITHUB_ENV
- name: Verify separate forwarding and local egress in Linux namespaces
if: runner.os == 'Linux'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify source selection on a real utun
if: runner.os == 'macOS'
shell: bash
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
- name: Verify exit routing and PF translation on two real utuns
if: runner.os == 'macOS'
shell: bash
timeout-minutes: 2
env:
EXIT_TEST: overlay::hostrules::macos_exit::kernel::exit_preserves_underlay_and_both_meshes
run: |
"$TEST_BINARY" --ignored --exact "$EXIT_TEST" --list | grep -Fx "$EXIT_TEST: test"
previous=$(sysctl -n net.inet.ip.forwarding)
trap 'sudo -n sysctl -w "net.inet.ip.forwarding=$previous"' EXIT
sudo -n sysctl -w net.inet.ip.forwarding=0
sudo -n -- "$TEST_BINARY" --ignored --exact "$EXIT_TEST" --nocapture
- name: Verify source selection on a real Wintun adapter
if: runner.os == 'Windows'
shell: pwsh
run: |
$zip = Join-Path $env:RUNNER_TEMP 'wintun.zip'
Invoke-WebRequest -Uri https://www.wintun.net/builds/wintun-0.14.1.zip -OutFile $zip
# This is the signed Wintun distribution pinned by the Windows installer.
if ((Get-FileHash $zip -Algorithm SHA256).Hash -ne '07C256185D6EE3652E09FA55C0B673E2624B565E02C4B9091C79CA7D2F24EF51') {
throw 'Unexpected Wintun archive checksum'
}
$directory = Join-Path $env:RUNNER_TEMP 'wintun-dl'
Expand-Archive -Path $zip -DestinationPath $directory
Copy-Item (Join-Path $directory 'wintun/bin/amd64/wintun.dll') (Split-Path -Parent $env:TEST_BINARY)
& $env:TEST_BINARY --ignored --exact $env:TEST_NAME --nocapture
exit $LASTEXITCODE
- name: Verify forwarded and local traffic to the same destination
if: runner.os == 'Windows'
shell: pwsh
timeout-minutes: 2
run: |
$test = 'overlay::egress::tests::physical_member_sockets_survive_a_more_specific_wintun_route'
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
if ($listing -notcontains "${test}: test") { throw "Missing ignored test $test" }
& $env:TEST_BINARY --ignored --exact $test --nocapture
exit $LASTEXITCODE
- name: Verify one Windows exit bypass route through the physical gateway
if: runner.os == 'Windows'
shell: pwsh
timeout-minutes: 2
run: |
$test = 'overlay::hostrules::windows_exit::tests::windows_refresh_installs_only_the_external_test_address'
$listing = @(& $env:TEST_BINARY --ignored --exact $test --list)
if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
if ($listing -notcontains "${test}: test") { throw "Missing ignored test: $test" }
& $env:TEST_BINARY --ignored --exact $test --nocapture
exit $LASTEXITCODE
Generated
+26 -10
View File
@@ -6296,7 +6296,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
[[package]]
name = "tsunagi"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"anstream",
"anstyle",
@@ -6320,7 +6320,7 @@ dependencies = [
[[package]]
name = "tsunagi-android"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"bytes",
"egui",
@@ -6344,7 +6344,7 @@ dependencies = [
[[package]]
name = "tsunagi-awg"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"bytes",
"iroh",
@@ -6359,7 +6359,7 @@ dependencies = [
[[package]]
name = "tsunagi-core"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"arc-swap",
"bytes",
@@ -6384,6 +6384,8 @@ dependencies = [
"serde",
"sha2",
"simple-dns",
"smoltcp",
"socket2",
"subtle",
"tempfile",
"thiserror 2.0.20",
@@ -6393,6 +6395,7 @@ dependencies = [
"tracing",
"tracing-subscriber",
"tsunagi-core",
"tsunagi-speedtest",
"tun",
"windows-sys 0.61.2",
"zbus",
@@ -6401,7 +6404,7 @@ dependencies = [
[[package]]
name = "tsunagi-runtime"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"tokio",
"tracing",
@@ -6412,9 +6415,19 @@ dependencies = [
"tsunagi-wireguard",
]
[[package]]
name = "tsunagi-speedtest"
version = "0.1.0"
dependencies = [
"bytes",
"postcard",
"serde",
"tokio",
]
[[package]]
name = "tsunagi-tcp-tls"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"bytes",
"caps",
@@ -6434,7 +6447,7 @@ dependencies = [
[[package]]
name = "tsunagi-tray"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"eframe",
"egui-phosphor",
@@ -6450,17 +6463,20 @@ dependencies = [
[[package]]
name = "tsunagi-ui"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"egui",
"egui-phosphor",
"postcard",
"rusqlite",
"tempfile",
"tsunagi-core",
"zeroize",
]
[[package]]
name = "tsunagi-wg-quic"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"boringtun",
"bytes",
@@ -6487,7 +6503,7 @@ dependencies = [
[[package]]
name = "tsunagi-wireguard"
version = "1.0.1"
version = "1.0.9"
dependencies = [
"boringtun",
"bytes",
+55 -6
View File
@@ -114,15 +114,20 @@ explicit Save. [Commands, health, metrics and limits](docs/vip.md).
```sh
tsng network exit-node home on # on the machine that should be the exit
tsng exit-node # on another one: who offers an exit
tsng exit-node laptop # send everything through it
tsng exit-node laptop # send internet traffic through it
tsng exit-node off
```
One exit serves the whole agent. Peers in every active Tsunagi network stay
reachable on their own mesh routes.
The tray does the same with a checkbox. An exit node sees everything you send
through it, so use only members you trust.
through it, so use only members you trust. The folded network card shows its
status and recent traffic. Expand it to see who is using this device for internet
access.
[Details and per-OS notes](docs/exit-node.md).
The default data transport order is `wg,awg,wg-quic,tcp-tls`. AWG negotiates a
The initial data transport order is `wg,awg,wg-quic,tcp-tls` by default. AWG negotiates a
fresh masking profile and outer keys for each pair connection attempt, including
reentry after fallback. Sustained data loss triggers switching independently of
the iroh control connection. [Configuration and limits](docs/amnezia.md).
@@ -132,14 +137,40 @@ Change a network's protocol selection without editing its service or restarting:
```sh
tsng protocols # available protocols and settings
tsng protocols home # this device's choice for home
tsng protocols home awg,wg-quic # prefer AWG, retain QUIC as fallback
tsng protocols home awg,wg-quic # enable AWG and QUIC, try AWG first
tsng protocols home none # control plane only
```
Exact network names, full ids and unique id prefixes work here. The choice is
local to this device, saved per network and applied immediately; an offline
change applies on the next start. In the tray, expand **data transports** on a network
tile to toggle protocols or change their preference order. Adjacent peers need a common external transport at the same wire version.
change applies on the next start. In the tray or on Android, click the network
name to expand its card. Open **data transports** to enable transports and set
their initial preference order. **Show devices** lists peers and their reported
Tsunagi versions. On Android, tap a device to see its version and traffic.
Select a peer’s speedometer in **Devices** to measure download and upload
through its current encrypted mesh path. The cell shows live rates in Mbit/s.
Select the result to test again, or use **Test exits** to check the network’s
online, compatible exit nodes one at a time. The test ends at the peer, so its
Internet uplink beyond that peer is outside the measurement. Hover or long-press
the result for details. “At least” means the receiver sustained that rate and
the test ended before it could confirm the limit. A missing direction means
the sample was too short. Both peers need speed-test support.
A test runs for up to five seconds. It raises the offered rate in steps and
tries a higher rate again after a slow start. The receiver counts unique payload
bytes across sustained trains of packets, including the last train before the
traffic budget runs out. The traffic ceiling is 96 MiB per direction for one
peer, or 8 MiB when either endpoint reports a metered link.
A batch shares 128 MiB per direction among its exits, or 16 MiB on a metered
initiator. These ceilings count probe IP packets before tunnel overhead.
Adjacent peers need a common external transport at the same wire version.
Peers that both support link comparison probe another mutually enabled transport
while traffic continues on the current one. They can switch to a faster healthy link.
`tsng status` and the tray show the direct data link's measured RTT separately
from the control connection's RTT. A mesh relay's first-hop RTT cannot measure
the round trip to the destination.
Selection applies to this device's incoming and outgoing data links; control and
discovery are independent. A relay's next hop may use a different transport.
Every pair uses one internal WireGuard cipher, hidden from these controls.
@@ -167,6 +198,24 @@ when they reconnect. It does not ban the device: a newer signed claim can return
Online nodes and the currently selected exit node cannot be forgotten.
[State and limits](docs/sync-model.md#offline-node-cleanup).
### Traffic monitor
Open **Traffic monitor** (the pulse icon in the tray window or Android header) to
start an empty live capture. **IP flows** groups both directions of a TCP or UDP
address/port pair and repeated ICMP echoes for an address pair into one row. Select a network and peer, protocol or
role to narrow it down. **Via exit node** shows your outgoing internet traffic.
**Serving exit** shows traffic your device forwards for another peer.
**Transport** shows authenticated control sessions and encrypted datagrams
forwarded between two other endpoints. For relay rows the arrows follow the
two displayed endpoints in order. Rates update once per second. Select a row
to see its packet counts. The monitor records header metadata and counters only.
Inactive rows expire after 60 seconds. **Keep until close** retains flows in a
private temporary table owned by the window. Closing it discards the table and
ends collection. Android pauses collection while the activity is in the background.
Under heavy load the monitor displays the number of missed observations.
## Platforms
| Platform | Build | CLI `tsng` | Tray | Exit node: offer / use | Packages |
+20 -2
View File
@@ -16,15 +16,33 @@ cd android
adb install -r app/build/outputs/apk/debug/app-debug.apk
```
Open **tsunagi**, tap **Start VPN**, accept Android’s VPN prompt, then join with the existing network name and secret. Android keeps the established VPN service bound when the activity closes. **About → Stop VPN** disconnects it. The app-private state directory holds the device identity and its saved networks.
Open **tsunagi** to start the agent. On first launch, accept Android’s VPN permission prompt so the agent can create its mesh interface. Join with the existing network name and secret. The service continues when the activity closes. Mesh changes update split DNS and the selected-exit notification in the background. Opening the activity also requests live traffic counters. **About → Stop Tsunagi Agent** keeps it stopped across launches. After stopping or declining consent, tap **Start Tsunagi Agent** to enable automatic startup again. The app-private state directory holds the device identity and its saved networks.
The Rust agent owns one interface across the active networks. The Android service establishes the TUN and supplies its descriptor when addresses or exit routes change. Discovery and transport sockets use the selected physical network. TCP health checks bind to the VPN and the address of their own mesh network. The per-network transport selector offers `wg`, `awg`, `wg-quic` and `tcp-tls` in the same default order as the desktop. Each network retains its saved selection and priority. An advertised remote exit can carry the phone’s IPv4 internet traffic.
When Android chooses the first VPN address for a connection to another mesh, tsunagi translates TCP, UDP and ICMP echo traffic to that mesh’s address and returns replies to the original socket. Applications using other IPv4 protocols should bind to the address of their target mesh. If two sockets would use the same addresses, ports and protocol on the wire, the existing flow keeps its binding.
Applications using Android’s system resolver can connect to `<member>.<network>` and `<vip>.<network>`, for example `k8s.tsng:6443`. The VPN answers UDP and TCP DNS questions locally using the same signed roster and service records as the desktop. Unknown names in a joined mesh receive an authoritative negative answer. Other names go to Android’s resolver on the underlying Wi-Fi or cellular network, including while using a remote exit. Android 10 and later support arbitrary external DNS record types. On Android 8 and 9 the system lookup API supplies external A and AAAA records.
The tray and Android use the same egui network tiles, join form, device list, VIP editor and live traffic diagram from `crates/tsunagi-ui`. On Android, the Rust activity view opens each form in the current viewport. Kotlin handles the service, connectivity, rendering surface, input and clipboard.
Open **Exit node…** on a network tile to compare remote gateways by control RTT and data path. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
Rotate the phone to select a network on the left and see its settings on the right. **Show devices** opens a table sized to the screen. Tap a peer for its version, data path and traffic. A green check marks a ready data channel, an amber spinning arc indicates a pending connection, and a red warning opens the error details. Hold an icon for its label. Rotating the phone keeps the selected peer and any edits in the VIP editor.
Tap the round exit button at the bottom right of the home screen. The list groups available gateways by network and shows each peer’s measured data RTT and path. **No exit node** returns to this phone’s internet connection. Tap a row and confirm to route IPv4 internet traffic through it. The selected exit has an ongoing notification, including when the peer is offline. **Disconnect exit node** restores the ordinary internet route and keeps mesh access and DNS active. Mesh-only mode has no persistent app notification. Android controls the system VPN indicator. Android 13 and later request notification permission for the exit notice. Starting with Android 14, an unlocked device allows an individual swipe to dismiss an ongoing VPN notification. [Android notification behavior](https://developer.android.com/about/versions/14/behavior-changes-all#non-dismissable-notifications)
To switch the exit from the notification shade, edit Android Quick Settings and add **Tsunagi Exit**. The first tap opens the exit chooser if you have never used one. Subsequent taps disconnect the selected exit or reconnect the last peer in its original network. The tile shows the peer name and whether the selected peer is offline. Mesh access stays available when the exit is off.
## Check two networks on an emulator
Use a disposable ARM64 emulator. The test establishes a temporary VPN, sends UDP and system pings through the production TUN adapter to a local echo peer in each subnet, and checks that the originating applications receive their replies. Set `ANDROID_SERIAL` to that emulator's serial and run from the `android` directory.
```sh
./gradlew :app:assembleDebug :app:assembleDebugAndroidTest
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/debug/app-debug.apk
adb -s "$ANDROID_SERIAL" install -r app/build/outputs/apk/androidTest/debug/app-debug-androidTest.apk
adb -s "$ANDROID_SERIAL" shell appops set cy.hexor.tsunagi ACTIVATE_VPN allow
adb -s "$ANDROID_SERIAL" shell am instrument -w cy.hexor.tsunagi.test/androidx.test.runner.AndroidJUnitRunner
```
## Configure GitHub release signing
+25 -3
View File
@@ -22,8 +22,9 @@ android {
applicationId 'cy.hexor.tsunagi'
minSdk 26
targetSdk 35
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.1')
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.9')
ndk { abiFilters abi }
}
}
@@ -33,7 +34,8 @@ def metadata = providers.exec {
workingDir workspace
commandLine 'cargo', 'metadata', '--locked', '--format-version', '1', '--filter-platform', 'aarch64-linux-android'
}.standardOutput.asText.get()
def verifier = new JsonSlurper().parseText(metadata).packages.find { it.name == 'rustls-platform-verifier-android' }
def cargoMetadata = new JsonSlurper().parseText(metadata)
def verifier = cargoMetadata.packages.find { it.name == 'rustls-platform-verifier-android' }
repositories {
maven {
url new File(new File(verifier.manifest_path).parent, 'maven')
@@ -43,7 +45,11 @@ repositories {
google()
mavenCentral()
}
dependencies { implementation "rustls:rustls-platform-verifier:${verifier.version}" }
dependencies {
implementation "rustls:rustls-platform-verifier:${verifier.version}"
androidTestImplementation 'androidx.test:runner:1.5.2'
androidTestImplementation 'junit:junit:4.13.2'
}
abstract class BuildRust extends Exec {
@OutputDirectory abstract DirectoryProperty getJniLibs()
@@ -63,4 +69,20 @@ androidComponents.onVariants(androidComponents.selector().all()) { variant ->
if (mode == 'release') args '--release'
}
variant.sources.jniLibs.addGeneratedSourceDirectory(nativeBuild) { it.jniLibs }
if (variant.androidTest != null) {
def probe = tasks.register('cargoVpnSourceProbe', BuildRust) {
workingDir workspace
jniLibs.set(layout.buildDirectory.dir('generated/rust/vpnSourceTest'))
inputs.files(nativeBuild.map { it.inputs.files }, fileTree("${workspace}/crates/tsunagi-android/examples"))
commandLine 'cargo', 'ndk', '--target', abi, '--platform', '26',
'build', '--locked', '--example', 'vpn_source_probe', '-p', 'tsunagi-android'
doLast {
project.copy {
from "${cargoMetadata.target_directory}/aarch64-linux-android/debug/examples/libvpn_source_probe.so"
into jniLibs.dir(abi)
}
}
}
variant.androidTest.sources.jniLibs.addGeneratedSourceDirectory(probe) { it.jniLibs }
}
}
@@ -0,0 +1,51 @@
package cy.hexor.tsunagi
import android.app.ActivityManager
import android.content.Context
import android.content.Intent
import android.net.VpnService
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class AgentStartupTest {
@Suppress("DEPRECATION")
@Test fun launchStartsAgentAndExplicitStopSurvivesReopening() {
val test = InstrumentationRegistry.getInstrumentation()
val context = test.targetContext
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
val manager = context.getSystemService(ActivityManager::class.java)
fun running() = manager.getRunningServices(Int.MAX_VALUE).any {
it.service.className == MeshVpn::class.java.name && it.started
}
fun awaitRunning(expected: Boolean) {
val deadline = SystemClock.elapsedRealtime() + 5000
while (running() != expected) {
check(SystemClock.elapsedRealtime() < deadline) { "Agent did not reach started=$expected" }
SystemClock.sleep(25)
}
}
fun launch() = test.startActivitySync(Intent(context, MainActivity::class.java)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) as MainActivity
val settings = context.getSharedPreferences("agent", Context.MODE_PRIVATE)
val old = settings.getBoolean("auto_start", true)
var activity: MainActivity? = null
try {
settings.edit().remove("auto_start").commit()
activity = launch()
awaitRunning(true)
test.runOnMainSync { activity!!.stopAgent(); activity!!.finish() }
awaitRunning(false)
activity = launch()
test.waitForIdleSync()
check(!running())
test.runOnMainSync { activity!!.requestAgent() }
awaitRunning(true)
} finally {
test.runOnMainSync { activity?.stopAgent(); activity?.finish() }
awaitRunning(false)
settings.edit().putBoolean("auto_start", old).commit()
}
}
}
@@ -0,0 +1,33 @@
package cy.hexor.tsunagi
import android.content.ComponentName
import android.content.Context
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class ExitTileTest {
@Test fun tileKeepsTheExactLastSelectionOnlyAfterTheAgentConfirmsIt() {
val context = InstrumentationRegistry.getInstrumentation().targetContext
val info = context.packageManager.getServiceInfo(ComponentName(context, ExitTile::class.java), 0)
check(info.permission == "android.permission.BIND_QUICK_SETTINGS_TILE")
check(!context.packageManager.getActivityInfo(ExitTile.entry(context), 0).exported)
check(Native.tileExit(0, "network", "peer", true, false) == "Tsunagi Agent stopped")
val isolated = context.createDeviceProtectedStorageContext()
val settings = isolated.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
settings.edit().clear().commit()
val first = ExitTile.Target("network-a", "peer", "Gateway")
val last = ExitTile.Target("network-b", "peer", "Gateway")
try {
check(ExitTile.last(isolated) == null)
ExitTile.publish(isolated, 1L, first, true)
ExitTile.publish(isolated, 1L, last, true)
ExitTile.publish(isolated, 1L, null, false)
check(ExitTile.last(isolated) == last)
ExitTile.reset(isolated)
check(ExitTile.last(isolated) == last)
} finally {
ExitTile.reset(isolated)
settings.edit().clear().commit()
}
}
}
@@ -0,0 +1,52 @@
package cy.hexor.tsunagi
import android.content.Context
import android.content.ContextWrapper
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.net.VpnService
import android.os.ParcelFileDescriptor
import android.os.SystemClock
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Test
class VpnSourceTest {
private external fun checkSockets(fd: Int, networkCount: Int)
@Test fun udpAndPingReceiveFromBothNetworksAfterAddingTheSecond() {
System.loadLibrary("vpn_source_probe")
val context = InstrumentationRegistry.getInstrumentation().targetContext
check(VpnService.prepare(context) == null) { "Grant VPN consent on the test emulator first" }
val connectivity = context.getSystemService(ConnectivityManager::class.java)
// Android requires the manifest-declared service class. Attach it under the
// application UID without starting the agent and binding this process to the underlay.
val vpn = MeshVpn()
ContextWrapper::class.java.getDeclaredMethod("attachBaseContext", Context::class.java)
.apply { isAccessible = true }.invoke(vpn, context)
MeshVpn::class.java.getDeclaredField("upstream").apply { isAccessible = true }
.set(vpn, connectivity.activeNetwork)
val hosts = listOf("198.18.234.1/24", "198.19.234.1/24")
val routes = listOf("198.18.234.0/24", "198.19.234.0/24")
fun establish(count: Int): ParcelFileDescriptor {
val fd = vpn.establishTun(hosts.take(count).joinToString(","),
routes.take(count).joinToString(","), "", 1280, false)
check(fd >= 0) { "VPN establishment failed" }
return ParcelFileDescriptor.adoptFd(fd)
}
fun checkVpn(fd: ParcelFileDescriptor, count: Int) {
val deadline = SystemClock.elapsedRealtime() + 5000
while (true) {
val active = connectivity.activeNetwork
if (connectivity.getNetworkCapabilities(active)?.hasTransport(NetworkCapabilities.TRANSPORT_VPN) == true
&& connectivity.getLinkProperties(active)?.linkAddresses?.size == count) break
check(SystemClock.elapsedRealtime() < deadline) { "Timed out waiting for VPN routes" }
SystemClock.sleep(25)
}
checkSockets(ParcelFileDescriptor.dup(fd.fileDescriptor).detachFd(), count)
}
establish(1).use { first ->
checkVpn(first, 1)
establish(2).use { both -> checkVpn(both, 2) }
}
}
}
+8
View File
@@ -16,10 +16,18 @@
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity-alias android:name=".OpenExit" android:targetActivity=".MainActivity" android:exported="false" />
<service android:name=".MeshVpn" android:permission="android.permission.BIND_VPN_SERVICE"
android:foregroundServiceType="systemExempted" android:exported="false">
<intent-filter><action android:name="android.net.VpnService" /></intent-filter>
<meta-data android:name="android.net.VpnService.SUPPORTS_ALWAYS_ON" android:value="false" />
</service>
<service android:name=".ExitTile" android:exported="true"
android:label="Tsunagi Exit" android:icon="@drawable/exit_tile"
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE">
<intent-filter><action android:name="android.service.quicksettings.action.QS_TILE" /></intent-filter>
<meta-data android:name="android.service.quicksettings.ACTIVE_TILE" android:value="true" />
<meta-data android:name="android.service.quicksettings.TOGGLEABLE_TILE" android:value="true" />
</service>
</application>
</manifest>
@@ -0,0 +1,113 @@
package cy.hexor.tsunagi
import android.app.PendingIntent
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.service.quicksettings.Tile
import android.service.quicksettings.TileService
import android.widget.Toast
/** Quick Settings changes the internet exit of the existing mesh agent. */
class ExitTile : TileService() {
internal data class Target(val network: String, val peer: String, val name: String)
private data class Snapshot(val session: Long, val active: Target?, val online: Boolean)
companion object {
internal fun entry(context: Context) = ComponentName(context, "${context.packageName}.OpenExit")
private var live = Snapshot(0, null, false)
private var pending = false
private val main = Handler(Looper.getMainLooper())
internal fun last(context: Context): Target? {
val prefs = context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE)
val network = prefs.getString("network", null) ?: return null
val peer = prefs.getString("peer", null) ?: return null
return Target(network, peer, prefs.getString("name", null) ?: peer.take(12))
}
private fun refresh(context: Context) {
requestListeningState(context, ComponentName(context, ExitTile::class.java))
}
internal fun publish(context: Context, session: Long, active: Target?, online: Boolean) {
// Only confirmed agent status updates the last selection. Clearing an exit or
// stopping the process leaves the exact network and peer available for reuse.
if (active != null && last(context) != active) {
context.getSharedPreferences("exit_tile", Context.MODE_PRIVATE).edit()
.putString("network", active.network).putString("peer", active.peer)
.putString("name", active.name).apply()
}
live = Snapshot(session, active, online)
refresh(context)
}
internal fun reset(context: Context) {
live = Snapshot(0, null, false)
refresh(context)
}
internal fun restoreIfReady(context: Context, target: Target): Boolean {
if (live.session == 0L) return false
if (live.active == null) change(context, live.session, target, true, waitForDiscovery = true)
return true
}
private fun change(context: Context, session: Long, target: Target, connect: Boolean, waitForDiscovery: Boolean = false) {
if (pending) return
pending = true
refresh(context)
val app = context.applicationContext
Thread({
val error = Native.tileExit(session, target.network, target.peer, connect, waitForDiscovery)
main.post {
pending = false
if (error != null) Toast.makeText(app, error, Toast.LENGTH_LONG).show()
refresh(app)
}
}, "tsunagi-exit-tile").start()
}
}
private var displayed = live
private var remembered: Target? = null
override fun onStartListening() {
super.onStartListening()
displayed = live
remembered = last(this)
val tile = qsTile ?: return
val active = displayed.active
val peer = active ?: remembered
val subtitle = when {
pending -> "Updating…"
active != null && !displayed.online -> "${active.name} · offline"
peer != null -> peer.name
else -> "Choose exit node"
}
tile.state = when {
pending -> Tile.STATE_UNAVAILABLE
active != null -> Tile.STATE_ACTIVE
else -> Tile.STATE_INACTIVE
}
tile.label = if (Build.VERSION.SDK_INT < 29 && peer != null) "Exit · ${peer.name}" else "Tsunagi Exit"
if (Build.VERSION.SDK_INT >= 29) tile.subtitle = subtitle
tile.contentDescription = "Tsunagi exit node, $subtitle"
tile.updateTile()
}
@Suppress("DEPRECATION")
override fun onClick() {
super.onClick()
if (pending || displayed != live) { onStartListening(); return }
val target = displayed.active ?: remembered
if (displayed.session != 0L && target != null) {
change(this, displayed.session, target, displayed.active == null)
return
}
// Consent, a stopped service, or the first selection needs an activity.
val open = Intent().setComponent(entry(this))
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
if (Build.VERSION.SDK_INT >= 34) {
startActivityAndCollapse(PendingIntent.getActivity(this, 2, open, PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT))
} else startActivityAndCollapse(open)
}
}
@@ -9,6 +9,10 @@ import android.view.WindowInsets
import android.widget.FrameLayout
class MainActivity : Activity() {
private val settings by lazy { getSharedPreferences("agent", MODE_PRIVATE) }
private var checkedAutoStart = false
private var consentPending = false
private var tileRequested = false
private var askedForNotifications = false
internal fun requestExitNotifications() {
if (Build.VERSION.SDK_INT >= 33 && !askedForNotifications &&
@@ -20,6 +24,8 @@ class MainActivity : Activity() {
private lateinit var surface: MeshSurface
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
consentPending = savedInstanceState?.getBoolean("consent_pending") == true
tileRequested = savedInstanceState?.getBoolean("exit_tile") ?: (intent.component == ExitTile.entry(this))
surface = MeshSurface(this)
val root = FrameLayout(this)
if (Build.VERSION.SDK_INT >= 30) {
@@ -33,17 +39,59 @@ class MainActivity : Activity() {
root.addView(surface)
setContentView(root)
}
internal fun requestVpn() {
override fun onPostResume() {
super.onPostResume()
if (tileRequested && !consentPending) {
checkedAutoStart = true
requestAgent()
return
}
if (checkedAutoStart) return
checkedAutoStart = true
if (!MeshVpn.started && settings.getBoolean("auto_start", true)) requestAgent()
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putBoolean("consent_pending", consentPending)
outState.putBoolean("exit_tile", tileRequested)
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.component == ExitTile.entry(this)) tileRequested = true
}
internal fun requestAgent() {
if (consentPending) return
val consent = VpnService.prepare(this)
if (consent == null) startForegroundService(Intent(this, MeshVpn::class.java))
else startActivityForResult(consent, 1)
if (consent == null) startAgent() else {
consentPending = true
startActivityForResult(consent, 1)
}
}
private fun startAgent() {
settings.edit().putBoolean("auto_start", true).apply()
val service = Intent(this, MeshVpn::class.java)
if (tileRequested) {
tileRequested = false
if (ExitTile.last(this) != null) service.action = MeshVpn.RESTORE_EXIT
else surface.openExitPicker()
}
// A retry of an existing service may already have left foreground mode.
if (MeshVpn.started) startService(service) else startForegroundService(service)
}
internal fun stopAgent() {
settings.edit().putBoolean("auto_start", false).apply()
startService(Intent(this, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN))
}
@Deprecated("Platform consent result")
override fun onActivityResult(request: Int, result: Int, data: Intent?) {
super.onActivityResult(request, result, data)
if (request == 1) {
if (result == RESULT_OK) startForegroundService(Intent(this, MeshVpn::class.java))
else surface.input(5, "VPN permission was declined")
consentPending = false
if (result == RESULT_OK) startAgent() else {
tileRequested = false
settings.edit().putBoolean("auto_start", false).apply()
surface.input(5, "Android VPN permission was declined")
}
}
}
@Deprecated("Forward system Back to the current Rust view")
@@ -19,10 +19,13 @@ import javax.microedition.khronos.opengles.GL10
class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity), GLSurfaceView.Renderer {
private val density get() = resources.displayMetrics.density
private val imm = activity.getSystemService(InputMethodManager::class.java)
@Volatile private var paused = false
private var imeMode = 0
private var widthPx = 0
private var heightPx = 0
private val repaint = Runnable { requestRender() }
private val pickExit = java.util.concurrent.atomic.AtomicBoolean()
fun openExitPicker() { pickExit.set(true); requestRender() }
init {
setEGLContextClientVersion(3)
preserveEGLContextOnPause = true
@@ -31,14 +34,23 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
isFocusableInTouchMode = true
requestFocus()
}
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface()
override fun onSurfaceCreated(gl: GL10?, config: EGLConfig?) = Native.surface(context.cacheDir.absolutePath)
override fun onSurfaceChanged(gl: GL10?, w: Int, h: Int) { widthPx = w; heightPx = h }
override fun onDrawFrame(gl: GL10?) {
val delay = Native.draw(this, widthPx, heightPx, density)
if (paused) return
if (pickExit.getAndSet(false)) Native.input(6, "")
val landscape = resources.configuration.orientation == android.content.res.Configuration.ORIENTATION_LANDSCAPE
val delay = Native.draw(this, widthPx, heightPx, density, MeshVpn.started, landscape)
removeCallbacks(repaint)
postDelayed(repaint, delay.coerceAtLeast(16))
}
override fun onPause() { super.onPause(); removeCallbacks(repaint) }
override fun onPause() {
paused = true
queueEvent { Native.pauseTraffic() }
super.onPause()
removeCallbacks(repaint)
}
override fun onResume() { paused = false; super.onResume(); requestRender() }
override fun onTouchEvent(e: MotionEvent): Boolean {
val phase = when (e.actionMasked) {
MotionEvent.ACTION_DOWN, MotionEvent.ACTION_POINTER_DOWN -> 0
@@ -58,8 +70,8 @@ class MeshSurface(private val activity: MainActivity) : GLSurfaceView(activity),
return true
}
fun startVpn() { post { activity.requestVpn() } }
fun stopVpn() { post { activity.startService(Intent(activity, MeshVpn::class.java).setAction(MeshVpn.STOP_VPN)) } }
fun startAgent() { post { activity.requestAgent() } }
fun stopAgent() { post { activity.stopAgent() } }
fun requestExitNotifications() { post { activity.requestExitNotifications() } }
fun closeScreen() { post { activity.finish() } }
fun openUrl(url: String) { post {
@@ -24,19 +24,25 @@ import java.util.concurrent.TimeUnit
class MeshVpn : VpnService() {
companion object {
const val STOP_VPN = "cy.hexor.tsunagi.STOP_VPN"
const val RESTORE_EXIT = "cy.hexor.tsunagi.RESTORE_EXIT"
private const val DISCONNECT_EXIT = "cy.hexor.tsunagi.DISCONNECT_EXIT"
private const val NOTIFICATION_ID = 1
private const val EXIT_CHANNEL = "exit-node"
@Volatile var started = false
private set
}
private val main = Handler(Looper.getMainLooper())
private val notifications by lazy { getSystemService(NotificationManager::class.java) }
@Volatile private var instance = 0L
private var closed = false
private var restore: ExitTile.Target? = null
private val connectivity by lazy { getSystemService(ConnectivityManager::class.java) }
@Volatile private var upstream: Network? = null
private var watching = false
private val changes = object : ConnectivityManager.NetworkCallback() {
override fun onAvailable(network: Network) = useUnderlay(network)
override fun onCapabilitiesChanged(network: Network, capabilities: NetworkCapabilities) {
if (network == upstream && !closed) Native.setMetered(instance, isMetered(capabilities))
}
override fun onLinkPropertiesChanged(network: Network, properties: LinkProperties) {
if (network == upstream && !closed) updateAddresses(properties)
}
@@ -47,11 +53,15 @@ class MeshVpn : VpnService() {
// Falling back to the default network here could send iroh into its own TUN.
setUnderlyingNetworks(emptyArray())
physicalAddresses = ""
Native.setMetered(instance, true)
Native.networkChanged(instance, "")
}
}
private var physicalAddresses = ""
// Query the network the agent actually uses, even while its VPN is the app default.
private fun isMetered(capabilities: NetworkCapabilities?) =
capabilities?.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) != true
private fun addresses(properties: LinkProperties?) = properties?.linkAddresses.orEmpty()
.mapNotNull { it.address.hostAddress?.substringBefore('%') }.distinct().take(32).joinToString(",")
private fun updateAddresses(properties: LinkProperties) {
@@ -66,26 +76,34 @@ class MeshVpn : VpnService() {
upstream = network
setUnderlyingNetworks(arrayOf(network))
physicalAddresses = addresses(connectivity.getLinkProperties(network))
val metered = isMetered(connectivity.getNetworkCapabilities(network))
if (instance == 0L) {
Native.trust(applicationContext)
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses)
} else Native.networkChanged(instance, physicalAddresses)
instance = Native.start(this, applicationContext, noBackupFilesDir.absolutePath, cacheDir.absolutePath, physicalAddresses, metered)
} else {
Native.setMetered(instance, metered)
Native.networkChanged(instance, physicalAddresses)
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
when (intent?.action) {
STOP_VPN -> { shutdown(); stopSelf(startId); return START_NOT_STICKY }
RESTORE_EXIT -> {
restore = ExitTile.last(this)
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
}
DISCONNECT_EXIT -> {
val ids = intent.data?.pathSegments.orEmpty()
if (watching && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
if (started && ids.size == 2 && intent.getLongExtra("instance", 0) == instance) {
if (!Native.disconnectExit(instance, ids[0], ids[1])) {
android.widget.Toast.makeText(this, "Exit node is busy. Try again.", android.widget.Toast.LENGTH_SHORT).show()
}
} else if (!watching) stopSelf(startId)
} else if (!started) stopSelf(startId)
return START_NOT_STICKY
}
}
if (watching) {
if (started) {
if (Native.failed(instance)) {
Native.stop(instance)
instance = 0
@@ -93,12 +111,13 @@ class MeshVpn : VpnService() {
}
return START_NOT_STICKY
}
notifications.createNotificationChannel(NotificationChannel("vpn", "VPN", NotificationManager.IMPORTANCE_LOW))
closed = false
notifications.createNotificationChannel(NotificationChannel("vpn", "Tsunagi Agent", NotificationManager.IMPORTANCE_LOW))
notifications.createNotificationChannel(NotificationChannel(EXIT_CHANNEL, "Exit node", NotificationManager.IMPORTANCE_LOW))
val startup = notification("vpn").setContentTitle("Starting mesh VPN")
val startup = notification("vpn").setContentTitle("Starting Tsunagi Agent")
if (Build.VERSION.SDK_INT >= 31) startup.setForegroundServiceBehavior(Notification.FOREGROUND_SERVICE_DEFERRED)
startForeground(NOTIFICATION_ID, startup.build())
watching = true
started = true
connectivity.requestNetwork(NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET)
.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_VPN).build(), changes, Handler(Looper.getMainLooper()))
@@ -116,9 +135,12 @@ class MeshVpn : VpnService() {
// Rust publishes a change even when the activity is closed. Android holds its
// own service binding for an established TUN, so mesh-only mode can leave
// foreground promotion and remove the app's notification.
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String) {
fun updateExitNotification(session: Long, network: String, peer: String, title: String, text: String, name: String, online: Boolean) {
main.post {
if (closed || session != instance) return@post
val selected = if (peer.isEmpty()) null else ExitTile.Target(network, peer, name)
ExitTile.publish(this, session, selected, online)
restore?.let { if (ExitTile.restoreIfReady(this, it)) restore = null }
if (peer.isEmpty()) {
stopForeground(STOP_FOREGROUND_REMOVE)
return@post
@@ -189,8 +211,14 @@ class MeshVpn : VpnService() {
@Synchronized private fun shutdown() {
if (closed) return
closed = true
if (watching) connectivity.unregisterNetworkCallback(changes)
restore = null
ExitTile.reset(this)
if (started) connectivity.unregisterNetworkCallback(changes)
started = false
if (instance != 0L) Native.stop(instance)
instance = 0L
upstream = null
physicalAddresses = ""
connectivity.bindProcessToNetwork(null)
stopForeground(STOP_FOREGROUND_REMOVE)
}
@@ -6,14 +6,17 @@ import android.content.Context
internal object Native {
init { System.loadLibrary("tsunagi_android") }
external fun trust(context: Context)
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String): Long
external fun start(service: MeshVpn, context: Context, state: String, cache: String, addresses: String, metered: Boolean): Long
external fun failed(instance: Long): Boolean
external fun stop(instance: Long)
external fun disconnectExit(instance: Long, network: String, peer: String): Boolean
external fun tileExit(instance: Long, network: String, peer: String, connect: Boolean, waitForDiscovery: Boolean): String?
external fun networkChanged(instance: Long, addresses: String)
external fun setMetered(instance: Long, metered: Boolean)
external fun surface()
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float): Long
external fun surface(cacheDir: String)
external fun pauseTraffic()
external fun draw(host: MeshSurface, width: Int, height: Int, density: Float, serviceStarted: Boolean, landscape: Boolean): Long
external fun touch(action: Int, id: Int, x: Float, y: Float)
external fun input(kind: Int, value: String)
external fun key(key: Int)
@@ -0,0 +1,6 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="24dp" android:height="24dp" android:viewportWidth="24" android:viewportHeight="24">
<path android:strokeColor="#ffffff" android:strokeWidth="2"
android:strokeLineCap="round" android:strokeLineJoin="round"
android:pathData="M12,3H4v18h8 M9,12h12 M17,8l4,4l-4,4" />
</vector>
+6 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-android"
version = "1.0.1"
version = "1.0.9"
description = "Android VPN client and egui views for tsunagi."
edition.workspace = true
rust-version.workspace = true
@@ -11,8 +11,12 @@ publish = false
[lib]
crate-type = ["cdylib", "rlib"]
[[example]]
name = "vpn_source_probe"
crate-type = ["cdylib"]
[dependencies]
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.1" }
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.9" }
tsunagi-ui = { path = "../tsunagi-ui" }
tsunagi-core = { path = "../tsunagi-core" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
@@ -0,0 +1,142 @@
//! Peer for the Android instrumentation test. Only the test APK packages it.
#![cfg(target_os = "android")]
use jni::{JNIEnv, objects::JObject};
use std::{
fs::File,
io,
net::Ipv4Addr,
os::fd::{FromRawFd, OwnedFd},
process::Command,
time::Duration,
};
use tsunagi::overlay::{Cidr, TunDevice, TunFactory, TunRequest};
use tsunagi_android::{dns::Resolver, tun::AndroidTun};
#[allow(unsafe_code)]
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_VpnSourceTest_checkSockets(
mut env: JNIEnv,
_: JObject,
fd: i32,
count: i32,
) {
// SAFETY: the instrumentation test transfers a duplicate with detachFd().
let file = File::from(unsafe { OwnedFd::from_raw_fd(fd) });
let result = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.and_then(|rt| rt.block_on(check(file, count)));
if let Err(error) = result {
let _ = env.throw_new("java/lang/AssertionError", error.to_string());
}
}
async fn check(file: File, count: i32) -> io::Result<()> {
let factory = AndroidTun::new(
Resolver::new(|_| None),
move |_| file.try_clone(),
|_, _| Ok(()),
);
let locals = [
Ipv4Addr::new(198, 18, 234, 1),
Ipv4Addr::new(198, 19, 234, 1),
];
let mut req = TunRequest::bare("vpn", 1280);
for &local in locals.iter().take(count as usize) {
req.addresses
.push(Cidr::new(local.into(), 24).map_err(io::Error::other)?);
}
let tun = factory.create(req).await.map_err(io::Error::other)?;
for &local in locals.iter().take(count as usize) {
let mut octets = local.octets();
octets[3] = 2;
let remote = Ipv4Addr::from(octets);
let exchange = async {
udp(tun.as_ref(), local, remote).await?;
ping(tun.as_ref(), local, remote).await
};
tokio::time::timeout(Duration::from_secs(8), exchange)
.await
.map_err(|_| io::Error::other(format!("echo timed out on network {local}")))??;
}
Ok(())
}
async fn echo(
tun: &dyn TunDevice,
local: Ipv4Addr,
remote: Ipv4Addr,
protocol: u8,
) -> io::Result<()> {
use smoltcp::wire::{Icmpv4Message, Icmpv4Packet};
loop {
let mut pkt = tun
.recv()
.await
.ok_or_else(|| io::Error::other("VPN closed"))?
.to_vec();
if pkt.len() < 28 || pkt[0] != 0x45 || pkt[9] != protocol || pkt[16..20] != remote.octets()
{
continue;
}
if protocol == 17 {
if pkt[22..24] != 45678u16.to_be_bytes() || &pkt[28..] != b"mesh probe" {
continue;
}
// Swapping ports preserves the UDP checksum.
pkt[20..24].rotate_left(2);
} else {
let mut icmp = Icmpv4Packet::new_checked(&mut pkt[20..]).map_err(io::Error::other)?;
if icmp.msg_type() != Icmpv4Message::EchoRequest {
continue;
}
icmp.set_msg_type(Icmpv4Message::EchoReply);
icmp.fill_checksum();
}
if pkt[12..16] != local.octets() {
return Err(io::Error::other(format!(
"peer {remote} saw source {:?}, expected {local}",
&pkt[12..16]
)));
}
// Swapping addresses preserves the IPv4 checksum and the pseudo-header sum.
pkt[12..20].rotate_left(4);
return tun.send(pkt.into()).await.map_err(io::Error::other);
}
}
async fn udp(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
let socket = tokio::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await?;
socket.connect((remote, 45678)).await?;
socket.send(b"mesh probe").await?;
echo(tun, local, remote, 17).await?;
let mut reply = [0; 64];
let n = socket.recv(&mut reply).await?;
if &reply[..n] != b"mesh probe" {
return Err(io::Error::other("UDP echo payload changed"));
}
Ok(())
}
async fn ping(tun: &dyn TunDevice, local: Ipv4Addr, remote: Ipv4Addr) -> io::Result<()> {
let command = async {
let output = tokio::task::spawn_blocking(move || {
Command::new("/system/bin/ping")
.args(["-n", "-c", "1", "-w", "4"])
.arg(remote.to_string())
.output()
})
.await??;
if !output.status.success() {
return Err(io::Error::other(format!(
"ping {remote} failed: {}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
)));
}
Ok(())
};
tokio::try_join!(command, echo(tun, local, remote, 1))?;
Ok(())
}
+36 -7
View File
@@ -7,7 +7,7 @@ use egui_glow::{Painter, glow};
use jni::{
JNIEnv,
objects::{JObject, JString, JValue},
sys::{jfloat, jint, jlong},
sys::{jboolean, jfloat, jint, jlong},
};
use std::{
cell::RefCell,
@@ -38,7 +38,15 @@ fn with_display<T: Default>(f: impl FnOnce(&mut Display) -> T) -> T {
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObject) {
extern "system" fn Java_cy_hexor_tsunagi_Native_pauseTraffic(_: JNIEnv, _: JObject) {
with_display(|d| d.ui.pause_monitor());
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
mut env: JNIEnv,
_: JObject,
cache: JString,
) {
// SAFETY: GLSurfaceView invokes this callback on the GL thread with its ES3 context current.
let gl = unsafe {
glow::Context::from_loader_function_cstr(|name| eglGetProcAddress(name.as_ptr()))
@@ -52,9 +60,22 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
};
let ctx = egui::Context::default();
crate::view::configure(&ctx);
let cache = env.get_string(&cache).ok().map(String::from);
DISPLAY.with_borrow_mut(|d| {
// If Android discarded the old EGL context, its GPU resources are already gone.
let ui = d.take().map(|old| old.ui).unwrap_or_default();
let mut ui = d
.take()
.map(|old| {
// A rotation can recreate EGL. Keep expanded peers and scroll positions
// while the new context uploads its own font atlas.
let data = old.ctx.data_mut(std::mem::take);
ctx.data_mut(|current| *current = data);
old.ui
})
.unwrap_or_default();
if let Some(cache) = cache {
ui.set_cache_dir(cache.into());
}
*d = Some(Display {
painter,
ctx,
@@ -75,8 +96,11 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
w: jint,
h: jint,
scale: jfloat,
service_started: jboolean,
landscape: jboolean,
) -> jlong {
with_display(|d| {
tsunagi_ui::widgets::set_landscape(&d.ctx, landscape != 0);
let size = egui::vec2(w as f32, h as f32) / scale;
let mut input = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(Pos2::ZERO, size)),
@@ -88,19 +112,23 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
info.native_pixels_per_point = Some(scale);
}
let mut action = None;
let state = super::status();
let state = match super::status() {
crate::service::State::Off if service_started != 0 => crate::service::State::Starting,
state => state,
};
let exit_active = matches!(&state, crate::service::State::Ready(report, _) if report.networks.iter().any(|n| n.active && n.exit.via.is_some()));
if exit_active && !d.exit_active {
let _ = env.call_method(&host, "requestExitNotifications", "()V", &[]);
}
d.exit_active = exit_active;
let output = d.ctx.run(input, |ctx| {
action = d.ui.draw(ctx, &state, super::send);
action = d.ui.draw(ctx, &state, super::send).or(action);
});
d.ui.poll_monitor(|| super::submit(crate::service::Request::WatchTraffic));
if let Some(action) = action {
let method = match action {
SystemAction::Start => "startVpn",
SystemAction::Stop => "stopVpn",
SystemAction::Start => "startAgent",
SystemAction::Stop => "stopAgent",
SystemAction::PasteSecret => "pasteSecret",
SystemAction::Finish => "closeScreen",
};
@@ -227,6 +255,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_input(
}
4 => d.ui.paste_secret(text),
5 => d.ui.error(text),
6 => d.ui.request_exit_picker(),
_ => {}
});
}
+107 -17
View File
@@ -4,7 +4,7 @@ mod display;
mod dns;
use crate::{
plan::VpnPlan,
service::{Reply, Request, Response, State},
service::{Reply, Request, Response, ServiceSignals, State},
tun::AndroidTun,
};
use jni::{
@@ -25,10 +25,11 @@ use tsunagi_wg_quic::{DEFAULT_MTU, WireguardConfig, WireguardPlugin};
struct Session {
id: i64,
last_refresh: Option<std::time::Instant>,
commands: mpsc::Sender<(Request, Reply)>,
state: watch::Receiver<State>,
underlay: watch::Sender<Vec<std::net::IpAddr>>,
stop: watch::Sender<bool>,
signals: watch::Sender<ServiceSignals>,
}
static SESSION: Mutex<Option<Session>> = Mutex::new(None);
// Stop/start can cross on the Android main thread. The previous agent closes
@@ -39,19 +40,38 @@ fn current() -> std::sync::MutexGuard<'static, Option<Session>> {
SESSION.lock().unwrap_or_else(|e| e.into_inner())
}
fn status() -> State {
current()
.as_ref()
.map(|s| s.state.borrow().clone())
.unwrap_or_default()
let mut current = current();
let Some(session) = current.as_mut() else {
return State::Off;
};
let state = session.state.borrow().clone();
let report = match &state {
State::Ready(report, _) => Some(report.as_ref()),
_ => None,
};
if session
.last_refresh
.is_none_or(|last| last.elapsed() >= tsunagi_ui::client::status_poll_interval(report))
&& session
.commands
.try_send((Request::Refresh, oneshot::channel().0))
.is_ok()
{
session.last_refresh = Some(std::time::Instant::now());
}
state
}
fn send(cmd: tsunagi_ui::client::Command) -> Result<Response, String> {
submit(Request::Action(cmd))
}
fn submit(request: Request) -> Result<Response, String> {
let (reply, result) = oneshot::channel();
current()
.as_ref()
.ok_or("VPN service stopped")?
.ok_or("Tsunagi Agent stopped")?
.commands
.try_send((Request::Action(cmd), reply))
.map_err(|_| "VPN service is busy or stopped".to_owned())?;
.try_send((request, reply))
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
Ok(result)
}
@@ -119,6 +139,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
state_dir: JString,
cache_dir: JString,
addresses: JString,
metered: jni::sys::jboolean,
) -> jlong {
let result = (|| -> Result<i64, Box<dyn std::error::Error>> {
// Keep the application (never an activity) alive for DNS throughout the process.
@@ -176,18 +197,21 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
let (underlay, physical) = watch::channel(underlay_ips(&addresses));
let (commands, rx) = mpsc::channel(16);
let (state, state_rx) = watch::channel(State::Starting);
let (stop, stopped) = watch::channel(false);
let (signals, updates) = watch::channel(ServiceSignals {
stopped: false,
metered: metered != 0,
});
static NEXT: std::sync::atomic::AtomicI64 = std::sync::atomic::AtomicI64::new(1);
let id = NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let mut slot = current();
if let Some(old) = slot.as_ref() {
old.stop.send_replace(true);
old.signals.send_modify(|s| s.stopped = true);
}
std::thread::Builder::new()
.name("tsunagi-agent".into())
.spawn(move || {
let _lifetime = LIFETIME.lock().unwrap_or_else(|e| e.into_inner());
if *stopped.borrow() {
if updates.borrow().stopped {
return;
}
let run = || -> Result<(), Box<dyn std::error::Error>> {
@@ -214,7 +238,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
.await?;
let agent = Agent::spawn(config).await?;
let _listeners = carriers.listen(&agent);
crate::service::serve(agent, wg, dns, rx, &state, stopped, |notice| {
crate::service::serve(agent, wg, dns, rx, &state, updates, |notice| {
update_exit_notification(&notice_vm, &notice_service, id, notice);
})
.await;
@@ -227,10 +251,11 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
})?;
*slot = Some(Session {
id,
last_refresh: None,
commands,
state: state_rx,
underlay,
stop,
signals,
});
Ok(id)
})();
@@ -252,9 +277,10 @@ fn update_exit_notification(
let Ok(mut env) = vm.attach_current_thread() else {
return;
};
let _ = env.with_local_frame(6, |env| -> jni::errors::Result<()> {
let _ = env.with_local_frame(8, |env| -> jni::errors::Result<()> {
let network = env.new_string(notice.map_or("", |n| &n.network))?;
let peer = env.new_string(notice.map_or("", |n| &n.peer))?;
let name = env.new_string(notice.map_or("", |n| &n.name))?;
let title = env.new_string(
notice
.map(|n| format!("Exit node · {}", n.name))
@@ -277,13 +303,15 @@ fn update_exit_notification(
env.call_method(
service,
"updateExitNotification",
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V",
"(JLjava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Z)V",
&[
JValue::Long(id),
JValue::Object(&network),
JValue::Object(&peer),
JValue::Object(&title),
JValue::Object(&text),
JValue::Object(&name),
JValue::Bool(notice.is_some_and(|n| n.online).into()),
],
)?;
Ok(())
@@ -321,6 +349,53 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_disconnectExit(
.into()
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_tileExit(
mut env: JNIEnv,
_: JObject,
id: jlong,
network: JString,
peer: JString,
connect: jni::sys::jboolean,
wait_for_discovery: jni::sys::jboolean,
) -> jni::sys::jstring {
// Called on the tile's background worker. Never hold the session lock while awaiting the agent.
let mut run = || -> Result<(), String> {
let network: String = env.get_string(&network).map_err(|e| e.to_string())?.into();
let peer: String = env.get_string(&peer).map_err(|e| e.to_string())?.into();
let (commands, mut state) = current()
.as_ref()
.filter(|s| s.id == id)
.map(|s| (s.commands.clone(), s.state.clone()))
.ok_or("Tsunagi Agent stopped")?;
if connect != 0 && wait_for_discovery != 0 {
tokio::runtime::Builder::new_current_thread()
.enable_time()
.build()
.map_err(|e| e.to_string())?
.block_on(crate::service::wait_for_exit_offer(
&mut state, &network, &peer,
))?;
}
let request = if connect != 0 {
Request::RestoreExit { network, peer }
} else {
Request::DisconnectExit { network, peer }
};
let (reply, result) = oneshot::channel();
commands
.try_send((request, reply))
.map_err(|_| "Tsunagi Agent is busy or stopped")?;
result
.blocking_recv()
.map_err(|_| "Tsunagi Agent stopped")??;
Ok(())
};
run()
.err()
.and_then(|e| env.new_string(e).ok())
.map_or(std::ptr::null_mut(), JString::into_raw)
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_failed(
_: JNIEnv,
_: JObject,
@@ -337,7 +412,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_stop(_: JNIEnv, _: JObject, id:
if slot.as_ref().is_some_and(|s| s.id == id)
&& let Some(session) = slot.take()
{
session.stop.send_replace(true);
session.signals.send_modify(|s| s.stopped = true);
}
}
fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
@@ -348,6 +423,21 @@ fn underlay_ips(addresses: &str) -> Vec<std::net::IpAddr> {
.collect()
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_setMetered(
_: JNIEnv,
_: JObject,
id: jlong,
metered: jni::sys::jboolean,
) {
if let Some(s) = current().as_ref().filter(|s| s.id == id) {
s.signals.send_if_modified(|signals| {
let changed = signals.metered != (metered != 0);
signals.metered = metered != 0;
changed
});
}
}
#[unsafe(no_mangle)]
extern "system" fn Java_cy_hexor_tsunagi_Native_networkChanged(
mut env: JNIEnv,
_: JObject,
+11 -4
View File
@@ -46,11 +46,7 @@ impl Resolver {
let view = tsunagi::dns::RosterZones::from_networks(networks);
let names = view.zones.names() as u32;
self.replace(Some(view.zones));
let address = *self.listening.borrow();
tsunagi::ipc::DnsReport {
listening: address.map(|ip| format!("{ip}:53")).into_iter().collect(),
publish_error: (address.is_none() && !view.labels.is_empty())
.then(|| "Waiting for a VPN interface with a DNS address.".into()),
zones: view.labels,
zone_warnings: view.warnings,
names,
@@ -58,6 +54,17 @@ impl Resolver {
}
}
pub(crate) fn with_listener(
&self,
mut report: tsunagi::ipc::DnsReport,
) -> tsunagi::ipc::DnsReport {
let address = *self.listening.borrow();
report.listening = address.map(|ip| format!("{ip}:53")).into_iter().collect();
report.publish_error = (address.is_none() && !report.zones.is_empty())
.then(|| "Waiting for a VPN interface with a DNS address.".into());
report
}
/// Answer a local DNS request. Slow public lookups never block a mesh answer.
pub async fn answer(&self, query: &[u8]) -> Option<Vec<u8>> {
if query.len() > MAX_MESSAGE_LEN {
+1
View File
@@ -1,6 +1,7 @@
//! The Android application. Mesh state belongs to one service-owned Rust agent.
pub mod dns;
mod monitor;
pub mod plan;
#[cfg(target_os = "android")]
+68
View File
@@ -0,0 +1,68 @@
//! The GL thread holds a service subscription only while the inspector is visible.
use crate::service::{Outcome, Response};
use std::{
path::PathBuf,
time::{Duration, Instant},
};
use tokio::sync::oneshot::error::TryRecvError;
use tsunagi::traffic::TrafficSubscription;
use tsunagi_ui::monitor::Window;
pub(super) struct Monitor {
pub view: Window,
pending: Option<Response>,
subscription: Option<TrafficSubscription>,
next: Instant,
failed: bool,
}
impl Monitor {
pub fn new(cache: Option<PathBuf>) -> Self {
Self {
view: Window::new(cache),
pending: None,
subscription: None,
next: Instant::now(),
failed: false,
}
}
pub fn pause(&mut self) {
self.pending = None;
self.subscription = None;
}
pub fn poll(&mut self, open: impl FnOnce() -> Result<Response, String>) {
if self.failed {
return;
}
if let Some(sub) = &self.subscription {
if Instant::now() >= self.next {
self.next = Instant::now() + Duration::from_secs(1);
if !self.view.feed().sample(sub.snapshot()) {
self.pause();
self.failed = true;
}
}
return;
}
let result = match &mut self.pending {
Some(rx) => match rx.try_recv() {
Ok(Ok(Outcome::Traffic(sub))) => {
// Time spent in the background must expire old rows before new traffic can refresh them.
self.view.feed().sample(Default::default());
self.subscription = Some(sub);
self.next = Instant::now() + Duration::from_secs(1);
self.pending = None;
return;
}
Ok(Err(e)) => Err(e),
Err(TryRecvError::Empty) => return,
_ => Err("Tsunagi Agent stopped".into()),
},
None => open().map(|r| self.pending = Some(r)),
};
if let Err(e) = result {
self.pending = None;
self.failed = true;
self.view.feed().error(e);
}
}
}
+169 -21
View File
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
use tokio::sync::{mpsc, watch};
use tsunagi::{
Agent, NetworkName, NetworkSecret,
ipc::{PrivilegeReport, ProtocolReport, StatusReport},
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
vip::VipStatus,
};
use tsunagi_ui::client::Command;
@@ -12,8 +12,12 @@ use zeroize::Zeroizing;
/// A platform notification or user gesture.
pub enum Request {
/// A visible monitor requested its own fresh observation interval.
WatchTraffic,
/// A command from the same form used by the tray.
Action(Command),
/// The visible activity requested current counters.
Refresh,
/// The physical network changed.
NetworkChanged,
/// Disable only the exit identified by the notification the user tapped.
@@ -23,6 +27,22 @@ pub enum Request {
/// Endpoint id captured at the same time.
peer: String,
},
/// Restore a remembered network/peer pair only while no other exit is selected.
RestoreExit {
/// Network saved at the last successful selection.
network: String,
/// Peer used in that network.
peer: String,
},
}
/// The latest service lifecycle and cost of the physical network Android selected.
#[derive(Clone, Copy, Default)]
pub struct ServiceSignals {
/// End this instance.
pub stopped: bool,
/// Android reports that data on the current underlay may be billed.
pub metered: bool,
}
/// A configured default route stays visible if its remote peer goes offline.
@@ -70,8 +90,70 @@ pub async fn disconnect_exit(
Ok(())
}
async fn restore_exit(agent: &Agent, network: &str, peer: &str) -> Result<Outcome, String> {
let network = network.parse().map_err(|_| "Invalid saved network ID")?;
let peer = peer.parse().map_err(|_| "Invalid saved peer ID")?;
let status = agent.status().await.map_err(|e| e.to_string())?;
for n in &status.networks {
if n.state == tsunagi::agent::NetworkState::Active
&& let Some(current) = n.exit_via
{
return if n.network_id == network && current == peer {
Ok(Outcome::Applied)
} else {
Err("Another exit is already selected".into())
};
}
}
agent
.set_exit_via(network, Some(peer))
.await
.map_err(|e| e.to_string())?;
Ok(Outcome::Applied)
}
// On cold start the first snapshot often precedes peer discovery. Wait on the
// service's roster notifications, outside the command loop, then let the usual
// serialized command validate the selection again before touching the route.
#[cfg(any(target_os = "android", test))]
pub(crate) async fn wait_for_exit_offer(
state: &mut watch::Receiver<State>,
network: &str,
peer: &str,
) -> Result<(), String> {
tokio::time::timeout(std::time::Duration::from_secs(15), async {
loop {
match &*state.borrow_and_update() {
State::Ready(report, _) => {
let n = report
.networks
.iter()
.find(|n| n.network_id == network && n.active)
.ok_or("The saved exit network is no longer active")?;
if report
.networks
.iter()
.any(|n| n.active && n.exit.via.is_some())
|| n.peers.iter().any(|p| p.endpoint_id == peer && p.exit_node)
{
return Ok(());
}
}
State::Off => return Err("Tsunagi Agent stopped".into()),
State::Error(error) => return Err(error.clone()),
State::Starting => {}
}
state.changed().await.map_err(|_| "Tsunagi Agent stopped")?;
}
})
.await
.map_err(|_| "The saved peer is offline or no longer offers an exit")?
}
/// Private reply delivered only to the UI that requested the action.
pub enum Outcome {
/// Owned by one traffic screen and dropped when capture stops.
Traffic(tsunagi::traffic::TrafficSubscription),
/// The agent has applied the action.
Applied,
/// Revisions returned by a successful signed write.
@@ -89,6 +171,14 @@ pub type Response = tokio::sync::oneshot::Receiver<Result<Outcome, String>>;
pub async fn apply(
command: Command,
agent: &Agent,
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
apply_on_link(command, agent, false).await
}
async fn apply_on_link(
command: Command,
agent: &Agent,
metered: bool,
) -> Result<Outcome, Box<dyn std::error::Error + Send + Sync>> {
match command {
Command::Join { name, secret } => {
@@ -132,6 +222,16 @@ pub async fn apply(
.set_exit_via(network_id.parse()?, peer.map(|p| p.parse()).transpose()?)
.await?
}
Command::StartSpeedTest { network_id, peer } => {
agent
.start_speed_test(
network_id.parse()?,
peer.map(|p| p.parse()).transpose()?,
metered,
)
.await?;
}
Command::StopSpeedTest { network_id } => agent.stop_speed_test(network_id.parse()?),
Command::SetExitOffer { .. } => {
return Err("This phone can only use a remote exit node.".into());
}
@@ -176,11 +276,22 @@ pub async fn report(
agent: &Agent,
wg: Option<&WireguardPlugin>,
dns: &crate::dns::Resolver,
) -> tsunagi::Result<StatusReport> {
snapshot(agent, wg, dns, None).await
}
async fn snapshot(
agent: &Agent,
wg: Option<&WireguardPlugin>,
dns: &crate::dns::Resolver,
cached_zones: Option<DnsReport>,
) -> tsunagi::Result<StatusReport> {
let status = agent.status().await?;
let overlay = agent.overlay();
Ok(StatusReport {
networks: tsunagi_runtime::report::networks(&status, agent.overlay().as_ref(), wg),
dns: Some(dns.refresh(&status.networks)),
networks: tsunagi_runtime::report::networks(&status, overlay.as_ref(), wg),
overlay_config_error: overlay.and_then(|state| state.address_error),
dns: Some(dns.with_listener(cached_zones.unwrap_or_else(|| dns.refresh(&status.networks)))),
endpoint_id: status.endpoint_id.to_string(),
hostname: status.hostname,
bound_sockets: status
@@ -213,24 +324,42 @@ pub async fn serve(
dns: crate::dns::Resolver,
mut commands: mpsc::Receiver<(Request, Reply)>,
state: &watch::Sender<State>,
mut stop: watch::Receiver<bool>,
mut signals: watch::Receiver<ServiceSignals>,
mut publish_exit: impl FnMut(Option<&ExitNotice>),
) {
let mut poll = tokio::time::interval(std::time::Duration::from_secs(2));
poll.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let mut roster = agent.watch_roster();
roster.mark_changed(); // Load the initial zones before waiting for any actions.
let mut cached_zones = None;
let mut retry = false;
let mut published_exit = None;
let mut link = *signals.borrow_and_update();
agent.set_speed_test_metered(link.metered);
loop {
let reply = tokio::select! {
if link.stopped {
break;
}
let (reply, mut refresh_zones) = tokio::select! {
biased;
_ = stop.wait_for(|stopped| *stopped) => break,
changed = signals.changed() => {
if changed.is_err() { break; }
link = *signals.borrow_and_update();
agent.set_speed_test_metered(link.metered);
continue;
}
command = commands.recv() => {
let Some((request, reply)) = command else { break };
let refresh_zones = !matches!(request, Request::Refresh);
let result = match request {
Request::WatchTraffic => {
let _ = reply.send(agent.subscribe_traffic().map(Outcome::Traffic));
continue;
}
Request::Refresh => Ok(Outcome::Applied),
Request::Action(cmd) => {
if matches!(cmd, Command::Join { .. } | Command::Leave { .. } | Command::SetActive { .. }) {
dns.replace(None);
}
apply(cmd, &agent).await.map_err(|e| e.to_string())
apply_on_link(cmd, &agent, link.metered).await.map_err(|e| e.to_string())
}
Request::NetworkChanged => {
agent.endpoint().network_change().await;
@@ -239,22 +368,41 @@ pub async fn serve(
}
Request::DisconnectExit {network, peer} => disconnect_exit(&agent, &network, &peer).await
.map(|()| Outcome::Applied).map_err(|e| e.to_string()),
Request::RestoreExit {network, peer} => restore_exit(&agent, &network, &peer).await,
};
Some((reply, result))
(Some((reply, result)), refresh_zones)
}
_ = poll.tick() => None,
changed = roster.changed() => {
if changed.is_err() { break; }
(None, true)
}
_ = tokio::time::sleep(std::time::Duration::from_secs(2)), if retry => (None, true),
};
state.send_replace(match report(&agent, Some(&wg), &dns).await {
Ok(report) => {
let notice = exit_notice(&report);
if published_exit.as_ref() != Some(&notice) {
publish_exit(notice.as_ref());
published_exit = Some(notice);
// A command may itself have changed the roster. Consume notifications
// before taking the snapshot so changes during the read stay pending.
refresh_zones |= roster.has_changed().unwrap_or(false);
if refresh_zones {
roster.borrow_and_update();
cached_zones = None;
}
state.send_replace(
match snapshot(&agent, Some(&wg), &dns, cached_zones.take()).await {
Ok(report) => {
retry = false;
cached_zones.clone_from(&report.dns);
let notice = exit_notice(&report);
if published_exit.as_ref() != Some(&notice) {
publish_exit(notice.as_ref());
published_exit = Some(notice);
}
State::Ready(Arc::new(report), Instant::now())
}
State::Ready(Arc::new(report), Instant::now())
}
Err(error) => State::Error(error.to_string()),
});
Err(error) => {
retry = true;
State::Error(error.to_string())
}
},
);
if let Some((reply, outcome)) = reply {
let _ = reply.send(outcome);
}
+365 -43
View File
@@ -8,9 +8,101 @@ fn addr(octet: u8) -> Cidr {
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, octet, 42, 19)), 24).unwrap()
}
#[tokio::test]
async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand() {
use crate::service::{Request, State, serve};
use std::time::Duration;
use tokio::sync::{mpsc, oneshot, watch};
use tsunagi::{
discovery::SharedMemoryDiscovery,
testing::{TestAgent, network},
};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
let discovery = SharedMemoryDiscovery::new();
let phone = TestAgent::spawn(&discovery).await.unwrap();
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
.await
.unwrap();
let (state, mut snapshots) = watch::channel(State::Starting);
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
let (commands, requests) = mpsc::channel(4);
let agent = phone.agent.clone();
let task = tokio::spawn(async move {
serve(
agent,
wg,
crate::dns::Resolver::new(|_| None),
requests,
&state,
stopped,
|_| {},
)
.await;
});
tokio::time::timeout(Duration::from_secs(5), snapshots.changed())
.await
.unwrap()
.unwrap();
assert!(matches!(*snapshots.borrow_and_update(), State::Ready(..)));
// Occupy the other reader slots so this test observes the real service subscription
// being acquired on screen open and released on both background and close.
let other_windows: Vec<_> = (0..3)
.map(|_| phone.agent.subscribe_traffic().unwrap())
.collect();
let mut monitor = crate::monitor::Monitor::new(None);
for _ in 0..2 {
monitor.poll(|| {
let (tx, rx) = oneshot::channel();
commands.try_send((Request::WatchTraffic, tx)).unwrap();
Ok(rx)
});
tsunagi::testing::wait_until("the visible Android monitor subscribed", || async {
phone.agent.subscribe_traffic().is_err().then_some(())
})
.await;
monitor.poll(|| panic!("a visible monitor must reuse its subscription"));
monitor.pause();
assert!(phone.agent.subscribe_traffic().is_ok());
}
drop((monitor, other_windows));
assert!(
tokio::time::timeout(Duration::from_millis(2200), snapshots.changed())
.await
.is_err(),
"a hidden, idle service rebuilt the status"
);
let (tx, rx) = oneshot::channel();
commands.send((Request::Refresh, tx)).await.unwrap();
rx.await.unwrap().unwrap();
assert!(snapshots.has_changed().unwrap());
let (name, secret) = network("background-mesh");
phone.agent.join_network(&name, &secret).await.unwrap();
tokio::time::timeout(Duration::from_secs(5), snapshots.wait_for(|s| {
matches!(s, State::Ready(r, _) if r.dns.as_ref().is_some_and(|d| d.zones.iter().any(|z| z == "background-mesh")))
})).await.unwrap().unwrap();
stop.send_modify(|s| s.stopped = true);
task.await.unwrap();
}
#[tokio::test]
async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_current_route() {
use crate::service::{disconnect_exit, exit_notice, report};
use crate::service::{ExitNotice, Request, State, disconnect_exit, serve, wait_for_exit_offer};
use tokio::sync::{mpsc, oneshot, watch};
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
async fn notice_matching(
notices: &mut watch::Receiver<Option<ExitNotice>>,
predicate: impl Fn(&Option<ExitNotice>) -> bool,
) -> Option<ExitNotice> {
tokio::time::timeout(
std::time::Duration::from_secs(5),
notices.wait_for(predicate),
)
.await
.unwrap()
.unwrap()
.clone()
}
use tsunagi::{
discovery::SharedMemoryDiscovery,
testing::{TestAgent, network, wait_until},
@@ -43,13 +135,95 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
.then_some(())
})
.await;
let dns = crate::dns::Resolver::new(|_| None);
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
let wg = WireguardPlugin::open(WireguardConfig::new(phone.dir.path().join("wg")))
.await
.unwrap();
let agent = phone.agent.clone();
let (commands, requests) = mpsc::channel(4);
let (stop, stopped) = watch::channel(crate::service::ServiceSignals::default());
let (published, mut notices) = watch::channel(None);
let (state, mut live) = watch::channel(State::Starting);
let task = tokio::spawn(async move {
serve(
agent,
wg,
crate::dns::Resolver::new(|_| None),
requests,
&state,
stopped,
|notice| {
published.send_replace(notice.cloned());
},
)
.await;
});
phone.agent.set_exit_via(id, Some(peer)).await.unwrap();
let notice = exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).unwrap();
let notice = notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online))
.await
.unwrap();
assert_eq!(notice.name, "gateway");
assert_eq!(notice.network_name, "travel");
assert!(notice.online);
let restore = |peer: String| {
let commands = commands.clone();
let network = notice.network.clone();
async move {
let (reply, result) = oneshot::channel();
commands
.send((Request::RestoreExit { network, peer }, reply))
.await
.unwrap();
result.await.unwrap()
}
};
disconnect_exit(&phone.agent, &notice.network, &notice.peer)
.await
.unwrap();
notice_matching(&mut notices, Option::is_none).await;
assert!(
restore(phone.agent.endpoint_id().to_string())
.await
.is_err()
);
assert!(
phone
.agent
.network_status(id)
.await
.unwrap()
.exit_via
.is_none()
);
// A cold service can publish its first status before the gateway advertises.
// Keep the command loop available while waiting for this exact peer.
exit.agent.set_exit_offer(id, false).await.unwrap();
drop(
tokio::time::timeout(
std::time::Duration::from_secs(5),
live.wait_for(|s| {
matches!(s, State::Ready(report, _) if
report.networks[0].peers.iter().any(|p| p.endpoint_id == notice.peer && !p.exit_node))
}),
)
.await
.unwrap()
.unwrap(),
);
let waiting = wait_for_exit_offer(&mut live, &notice.network, &notice.peer);
tokio::pin!(waiting);
tokio::select! {
biased;
_ = &mut waiting => panic!("restored before the peer offered an exit"),
result = exit.agent.set_exit_offer(id, true) => result.unwrap(),
}
waiting.await.unwrap();
assert!(restore(notice.peer.clone()).await.is_ok());
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| n.online)).await;
assert!(
restore(phone.agent.endpoint_id().to_string())
.await
.is_err()
);
disconnect_exit(
&phone.agent,
&id.to_string(),
@@ -61,21 +235,20 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
phone.agent.network_status(id).await.unwrap().exit_via,
Some(peer)
);
exit.stop().await;
wait_until(
"offline exit remains selected in the notification",
|| async {
let report = report(&phone.agent, None, &dns).await.ok()?;
exit_notice(&report).filter(|n| !n.online)
},
)
exit.agent.set_hostname("renamed-gateway").await.unwrap();
notice_matching(&mut notices, |n| {
n.as_ref().is_some_and(|n| n.name == "renamed-gateway")
})
.await;
exit.stop().await;
notice_matching(&mut notices, |n| n.as_ref().is_some_and(|n| !n.online)).await;
disconnect_exit(&phone.agent, &notice.network, &notice.peer)
.await
.unwrap();
assert!(exit_notice(&report(&phone.agent, None, &dns).await.unwrap()).is_none());
notice_matching(&mut notices, Option::is_none).await;
assert!(phone.agent.is_active(id).await);
phone.stop().await;
stop.send_modify(|s| s.stopped = true);
task.await.unwrap();
}
#[tokio::test]
@@ -480,7 +653,7 @@ async fn tun_reader_survives_address_changes_failed_establish_and_last_network_l
}
#[tokio::test]
async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded() {
use crate::{
service::{State, report},
view::{Phone, configure},
@@ -500,42 +673,179 @@ async fn phone_metadata_rows_use_text_line_height_in_a_portrait_view() {
address: Some("10.1.2.3".into()),
..Default::default()
});
let mut other = sample.networks[0].clone();
other.network_id = "another-network".into();
sample.networks.push(other);
sample.networks[0].peers.push(tsunagi::ipc::PeerReport {
endpoint_id: "exit-endpoint-id".into(),
hostname: Some("gateway".into()),
..Default::default()
});
sample.networks[0].exit = tsunagi::ipc::ExitReport {
via: Some("exit-endpoint-id".into()),
via_online: true,
traffic: Some(tsunagi::overlay::exit::ExitTraffic {
tx_bytes: 2048,
rx_bytes: 512,
}),
client_rules: Some(tsunagi::ipc::RuleSetReport {
ok: true,
detail: String::new(),
}),
..Default::default()
};
let state = State::Ready(Arc::new(sample), Instant::now());
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let frame = ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(360., 720.),
)),
..Default::default()
},
|ctx| {
phone.draw(ctx, &state, |_| {
panic!("drawing the overview issued a command")
});
},
);
let y = |label: &str| {
let mut frame = |events| {
ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(360., 720.),
)),
events,
..Default::default()
},
|ctx| {
phone.draw(ctx, &state, |_| {
panic!("drawing the overview issued a command")
});
},
)
};
let positions = |frame: &egui::FullOutput, label: &str| {
frame
.shapes
.iter()
.find_map(|shape| match &shape.shape {
Shape::Text(text) if text.galley.text() == label => Some(text.pos.y),
.filter_map(|shape| match &shape.shape {
Shape::Text(text) if text.galley.text() == label => {
Some(text.pos + text.galley.rect.center().to_vec2())
}
_ => None,
})
.unwrap_or_else(|| panic!("missing label {label}"))
.collect::<Vec<_>>()
};
assert!((0.0..=26.0).contains(&(y("host") - y("device"))));
assert!((0.0..=26.0).contains(&(y("range") - y("id"))));
assert!((0.0..=26.0).contains(&(y("peers") - y("addr"))));
frame(vec![]);
let closed = frame(vec![]);
let titles = positions(&closed, name.as_str());
assert_eq!(titles.len(), 2);
assert!(positions(&closed, "Show devices").is_empty());
use egui_phosphor::regular::{ARROW_DOWN, ARROW_UP};
let font = egui::TextStyle::Body.resolve(&ctx.style());
for icon in [ARROW_UP, ARROW_DOWN] {
assert!(ctx.fonts(|fonts| fonts.has_glyphs(&font, icon)));
}
for label in [
"Exit via gateway".to_owned(),
format!("{ARROW_UP} 2.0 kB"),
format!("{ARROW_DOWN} 512 B"),
] {
assert_eq!(positions(&closed, &label).len(), 1, "missing {label}");
}
let mut click = |pos| {
for pressed in [true, false] {
frame(vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
]);
}
frame(vec![])
};
let opened = click(titles[0]);
assert_eq!(positions(&opened, "Show devices").len(), 1);
assert!(positions(&opened, "Exit node…").is_empty());
use egui_phosphor::regular as icon;
let vip = format!("{} VIP", icon::NETWORK);
let y = |label: &str| positions(&opened, label)[0].y;
assert!((0.0..=26.0).contains(&(y(icon::DESKTOP_TOWER) - y(icon::FINGERPRINT))));
assert!((0.0..=26.0).contains(&(y(icon::TREE_STRUCTURE) - y(icon::HASH))));
assert!((0.0..=26.0).contains(&(y(icon::DEVICES) - y(icon::DEVICE_MOBILE))));
assert!((y(&vip) - y("Show devices")).abs() < 2.0);
assert!((y(&vip) - y(&format!("{} Copy secret", egui_phosphor::regular::COPY))).abs() < 2.0);
let folded = click(positions(&opened, name.as_str())[0]);
assert!(positions(&folded, "Show devices").is_empty());
assert_eq!(positions(&folded, "Exit via gateway").len(), 1);
let fab = positions(&folded, icon::SIGN_OUT)
.into_iter()
.find(|p| p.y > 625. && p.x > 265.)
.expect("fixed exit button");
let picker = click(fab);
assert_eq!(positions(&picker, "No exit node").len(), 1);
assert_eq!(positions(&picker, "gateway").len(), 1);
let dialog = click(positions(&picker, "No exit node")[0]);
assert_eq!(positions(&dialog, "Disconnect").len(), 1);
let picker = click(positions(&dialog, "Cancel")[0]);
assert!(positions(&picker, "Disconnect").is_empty());
assert_eq!(positions(&picker, "gateway").len(), 1);
agent.shutdown().await;
}
#[test]
fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_name() {
use crate::{
service::State,
view::{Phone, configure},
};
use std::{sync::Arc, time::Instant};
use tsunagi::ipc::{NetworkReport, StatusReport};
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let draw = |phone: &mut Phone, state: &State| {
let out = ctx.run(egui::RawInput::default(), |ctx| {
phone.draw(ctx, state, |_| panic!("opening the tile selected a route"));
});
out.shapes
.into_iter()
.filter_map(|s| match s.shape {
egui::Shape::Text(t) => Some(t.galley.text().to_owned()),
_ => None,
})
.collect::<Vec<_>>()
};
phone.request_exit_picker();
draw(&mut phone, &State::Starting);
let networks =
[("alpha", true), ("bravo", true), ("paused", false)].map(|(id, active)| NetworkReport {
network_id: id.into(),
name: "home".into(),
peers: vec![tsunagi::ipc::PeerReport {
endpoint_id: "same-device".into(),
hostname: Some(format!("gateway-{id}")),
exit_node: true,
..Default::default()
}],
active,
..Default::default()
});
let state = State::Ready(
Arc::new(StatusReport {
networks: networks.into(),
..Default::default()
}),
Instant::now(),
);
draw(&mut phone, &state);
let chooser = draw(&mut phone, &state);
assert!(chooser.iter().any(|s| s == "home · alpha"));
assert!(chooser.iter().any(|s| s == "home · bravo"));
assert!(chooser.iter().any(|s| s == "gateway-alpha"));
assert!(chooser.iter().any(|s| s == "gateway-bravo"));
assert_eq!(chooser.iter().filter(|s| *s == "No exit node").count(), 1);
assert!(!chooser.iter().any(|s| s.contains("paused")));
assert!(phone.back().is_none());
assert!(draw(&mut phone, &state).iter().any(|s| s == "tsunagi"));
}
#[test]
fn rotating_the_phone_keeps_the_selected_network_and_unsaved_vip_draft() {
use crate::service::State;
use crate::view::{Phone, configure};
use egui::{Event, PointerButton, Pos2, RawInput, Rect, Shape};
@@ -552,6 +862,7 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
port: 8080,
};
let mut config = VipConfig::new("web");
let name_field = egui::Id::new(("vip-name", &config.id));
let mut listener = Listener::new(Protocol::Tcp, 80);
listener.backends.push(backend.clone());
config.listeners.push(listener);
@@ -591,10 +902,11 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
let ctx = egui::Context::default();
configure(&ctx);
let mut phone = Phone::default();
let size = std::cell::Cell::new(egui::vec2(360., 800.));
let mut frame = |events| {
ctx.run(
RawInput {
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, egui::vec2(360., 800.))),
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, size.get())),
events,
..Default::default()
},
@@ -631,21 +943,31 @@ fn portrait_navigation_opens_the_tray_vip_overview_and_draft_without_writing() {
}
frame(vec![])
};
let live = click("VIP");
for label in ["Overview", "Configuration", "Next new flow", "node:8080"] {
click("lab");
size.set(egui::vec2(800., 360.));
let live = click(&format!("{} VIP", egui_phosphor::regular::NETWORK));
for label in ["Overview", "Configuration", "web.lab", "node:8080"] {
let p = position(&live, label);
assert!(
(0.0..360.0).contains(&p.x),
"{label} is outside the portrait view"
(0.0..800.0).contains(&p.x),
"{label} is outside the landscape view"
);
}
let editor = click("Configuration");
position(&editor, "Name");
ctx.memory_mut(|m| m.request_focus(name_field));
frame(vec![Event::Text("-draft".into())]);
size.set(egui::vec2(360., 800.));
let editor_portrait = frame(vec![]);
position(&editor_portrait, "Unsaved changes");
assert!(editor_portrait.shapes.iter().any(|s| matches!(&s.shape,
Shape::Text(t) if t.galley.text().contains("-draft"))));
for label in [
"Active TCP port checks",
"Checks and flow expiry",
"+ Backend",
"+ Listener",
] {
position(&editor, label);
position(&editor_portrait, label);
}
}
+71 -15
View File
@@ -6,7 +6,7 @@ use std::{
fmt,
fs::File,
io::{self, Read, Write},
sync::Arc,
sync::{Arc, Mutex as StdMutex},
};
use tokio::{
io::unix::AsyncFd,
@@ -20,6 +20,7 @@ use tsunagi::{
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan,
ExitHostReport, ExitHostRules, RuleOutcome,
},
source::{SourceFlows, SourceMode},
},
};
@@ -30,6 +31,17 @@ struct Attachment {
device: Arc<AsyncFd<File>>,
addresses: Vec<std::net::IpAddr>,
dns: DnsPort,
packets: StdMutex<Option<PacketState>>,
}
struct PacketState {
flows: SourceFlows,
// At most one reassembled IPv4 datagram's worth of remaining fragments.
pending: std::vec::IntoIter<Bytes>,
}
impl Attachment {
fn packets(&self) -> std::sync::MutexGuard<'_, Option<PacketState>> {
self.packets.lock().unwrap_or_else(|err| err.into_inner())
}
}
type Descriptor = Option<Arc<Attachment>>;
@@ -76,7 +88,7 @@ impl AndroidTun {
return Ok(());
}
let dns_address = next.dns_address();
let fd = if next.addresses.is_empty() {
let device = if next.addresses.is_empty() {
None
} else {
let address = dns_address.ok_or_else(|| OverlayError::Unavailable(
@@ -92,12 +104,37 @@ impl AndroidTun {
self.0.resolver.clone(),
file.clone(),
);
Some(Arc::new(Attachment {
Some((file, dns))
};
// Only retire the old descriptor once establishing its replacement succeeds.
let previous = self
.0
.current
.borrow()
.clone()
.and_then(|fd| fd.packets().take());
let fd = device.map(|(file, dns)| {
let aliases = next.addresses_in_order();
let exit = match (next.full_tunnel, next.exit) {
(true, Some(std::net::IpAddr::V4(source))) => Some(source),
_ => None,
};
let flows = if let Some(mut previous) = previous {
previous.flows.reconfigure(&aliases, exit, next.mtu);
previous.flows
} else {
SourceFlows::new(&aliases, exit, next.mtu, SourceMode::Primary)
};
Arc::new(Attachment {
device: file,
addresses: next.addresses.iter().map(|a| a.addr).collect(),
dns,
}))
};
packets: StdMutex::new(Some(PacketState {
flows,
pending: Vec::new().into_iter(),
})),
})
});
self.0.current.send_replace(fd);
self.0.resolver.publish(dns_address);
*applied = next;
@@ -122,10 +159,14 @@ impl TunDevice for Device {
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async move {
let mut rx = self.tun.0.current.subscribe();
let mut buffer = vec![0; self.mtu as usize + 1];
let mut buffer = Vec::new();
loop {
let fd = rx.borrow_and_update().clone();
if let Some(fd) = fd {
if let Some(packet) = fd.packets().as_mut().and_then(|p| p.pending.next()) {
return Some(packet);
}
buffer.resize(self.mtu as usize + 1, 0);
let result = tokio::select! {
biased;
_ = rx.changed() => continue,
@@ -136,7 +177,14 @@ impl TunDevice for Device {
continue;
}
buffer.truncate(len);
return Some(buffer.into());
if let Some(state) = fd.packets().as_mut() {
let frames = state.flows.outbound(std::mem::take(&mut buffer).into());
state.pending = frames.into_iter();
if let Some(packet) = state.pending.next() {
return Some(packet);
}
}
continue;
}
}
// No networks yet, last one left, or Android revoked this fd.
@@ -152,14 +200,22 @@ impl TunDevice for Device {
.borrow_and_update()
.clone()
.ok_or_else(|| OverlayError::Unavailable("VPN has no addresses".into()))?;
let len = tokio::select! {
biased;
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
write.map_err(|e| OverlayError::Other(e.to_string()))?,
};
if len != packet.len() {
return Err(OverlayError::Other("short VPN datagram write".into()));
let packets = fd
.packets()
.as_mut()
.ok_or_else(|| OverlayError::Unavailable("VPN was reconfigured".into()))?
.flows
.inbound(packet);
for packet in packets {
let len = tokio::select! {
biased;
_ = rx.changed() => return Err(OverlayError::Unavailable("VPN was reconfigured".into())),
write = fd.device.async_io(tokio::io::Interest::WRITABLE, |mut file| file.write(&packet)) =>
write.map_err(|e| OverlayError::Other(e.to_string()))?,
};
if len != packet.len() {
return Err(OverlayError::Other("short VPN datagram write".into()));
}
}
Ok(())
})
+231 -19
View File
@@ -20,16 +20,17 @@ enum Page {
#[default]
Home,
About,
Monitor,
Join,
Devices(String),
Vips(String),
Exit(String),
Exits,
Leave(String),
}
impl Page {
fn network(&self) -> Option<&str> {
match self {
Self::Devices(id) | Self::Vips(id) | Self::Exit(id) | Self::Leave(id) => Some(id),
Self::Devices(id) | Self::Vips(id) | Self::Leave(id) => Some(id),
_ => None,
}
}
@@ -37,10 +38,11 @@ impl Page {
match self {
Self::Home => "tsunagi",
Self::About => "About",
Self::Monitor => "Traffic monitor",
Self::Join => "Join a network",
Self::Devices(_) => "Devices",
Self::Vips(_) => "VIP",
Self::Exit(_) => "Exit node",
Self::Exits => "Exit nodes",
Self::Leave(_) => "Leave network",
}
}
@@ -84,16 +86,22 @@ struct Pending {
#[derive(Default)]
pub struct Phone {
page: Page,
monitor: Option<crate::monitor::Monitor>,
cache_dir: Option<std::path::PathBuf>,
forms: UiState,
traffic: Traffic,
snapshot: Snapshot,
pending: Option<Pending>,
error: Option<String>,
clipboard: Option<Zeroizing<String>>,
landscape: bool,
pick_exit: bool,
before_picker: Option<Page>,
}
/// Keep reads at tray density. Extra hit area is reserved for the navigation bar.
pub fn configure(ctx: &Context) {
ctx.set_os(egui::os::OperatingSystem::Android);
ctx.set_fonts(tsunagi_ui::app_fonts());
ctx.style_mut(|style| {
style.spacing.interact_size.y = 19.0;
@@ -103,12 +111,33 @@ pub fn configure(ctx: &Context) {
}
impl Phone {
/// Private directory available to a window's temporary SQLite database.
pub fn set_cache_dir(&mut self, path: std::path::PathBuf) {
self.cache_dir = Some(path);
}
/// Release the agent subscription immediately when the activity goes into the background.
pub fn pause_monitor(&mut self) {
if let Some(m) = &mut self.monitor {
m.pause();
}
}
/// Poll the service only while a traffic screen is visible.
pub fn poll_monitor(&mut self, open: impl FnOnce() -> Result<Response, String>) {
if let Some(m) = &mut self.monitor {
m.poll(open);
}
}
fn home(&mut self) {
self.monitor = None;
if let Some(previous) = self.before_picker.take() {
self.forms.exit_confirm = None;
self.page = previous;
return;
}
if let Page::Vips(id) = &self.page {
self.forms.vip_windows.remove(id);
}
self.forms.join.name.clear();
self.forms.join.secret.zeroize();
self.forms.join = Default::default();
self.forms.exit_confirm = None;
self.forms.forget_confirm = None;
self.page = Page::Home;
@@ -127,6 +156,8 @@ impl Phone {
&& editor.dirty()
{
editor.request_close();
} else if self.page == Page::Home && self.landscape && self.forms.close_selection() {
return None;
} else if self.page == Page::Home {
return Some(SystemAction::Finish);
} else {
@@ -150,6 +181,126 @@ impl Phone {
self.error = Some(message);
}
/// The first tile tap opens the chooser once the agent is ready.
pub fn request_exit_picker(&mut self) {
self.pick_exit = true;
}
fn open_exit_picker(&mut self) {
if self.page != Page::Exits {
self.before_picker = Some(std::mem::replace(&mut self.page, Page::Exits));
self.forms.exit_confirm = None;
}
}
/// This control lives outside both portrait and landscape scroll areas.
fn exit_button(&mut self, ctx: &Context, ready: bool) {
let clicked = egui::Area::new("home exit button".into())
.anchor(egui::Align2::RIGHT_BOTTOM, [-16., -16.])
.order(egui::Order::Middle)
.movable(false)
.show(ctx, |ui| {
let (rect, response) = ui.allocate_exact_size(
egui::vec2(60., 60.),
if ready {
egui::Sense::click()
} else {
egui::Sense::hover()
},
);
let (mut fill, mut ink) = devices::exit_action_colors(ui.visuals().dark_mode);
if !ready {
fill = ui.visuals().widgets.inactive.bg_fill;
ink = ui.visuals().weak_text_color();
}
ui.painter().circle_filled(rect.center(), 30., fill);
if ready && (response.hovered() || response.has_focus()) {
ui.painter().circle_stroke(rect.center(), 27., (1_f32, ink));
}
ui.painter().text(
rect.center(),
egui::Align2::CENTER_CENTER,
icon::SIGN_OUT,
egui::FontId::proportional(29.),
ink,
);
response.widget_info(|| {
egui::WidgetInfo::labeled(
egui::WidgetType::Button,
ready,
"Choose an exit node",
)
});
tsunagi_ui::widgets::hint(response, "Choose an exit node").clicked()
})
.inner;
if ready && clicked {
self.open_exit_picker();
}
}
fn landscape_home(
&mut self,
ui: &mut egui::Ui,
actions: &Actions,
report: &tsunagi::ipc::StatusReport,
) {
let width = (ui.available_width() / 3.)
.clamp(146., 300.)
.min(ui.available_width() * 0.45);
egui::SidePanel::left("network selector")
.resizable(false)
.exact_width(width)
.show_inside(ui, |ui| {
if ui.button("Join or create a network").clicked() {
self.page = Page::Join;
}
ui.separator();
egui::ScrollArea::vertical()
.id_salt("network list")
.show(ui, |ui| {
for network in &report.networks {
home::draw_network_selector(
ui,
network,
report,
&mut self.forms,
&self.traffic,
);
}
});
});
egui::CentralPanel::default().show_inside(ui, |ui| {
let selected = report
.networks
.iter()
.find(|n| self.forms.selected_network.as_deref() == Some(&n.network_id));
egui::ScrollArea::vertical()
.id_salt(("network settings", selected.map(|n| &n.network_id)))
.show(ui, |ui| {
if let Some(n) = selected {
ui.heading(&n.name);
ui.push_id(&n.network_id, |ui| {
home::draw_network_details(
ui,
actions,
&mut self.forms,
&self.traffic,
n,
report,
false,
);
});
} else {
ui.heading("This device");
ui.label("Tsunagi Agent is running");
home::draw_header(ui, actions, &mut self.forms, report);
}
ui.add_space(80.);
});
});
}
/// Take a secret once for the platform’s sensitive clipboard.
pub fn take_copied_secret(&mut self) -> Option<Zeroizing<String>> {
self.clipboard.take()
@@ -162,7 +313,7 @@ impl Phone {
let outcome = match pending.result.try_recv() {
Err(tokio::sync::oneshot::error::TryRecvError::Empty) => return,
Err(tokio::sync::oneshot::error::TryRecvError::Closed) => {
Err("VPN service stopped".to_owned())
Err("Tsunagi Agent stopped".to_owned())
}
Ok(v) => v,
};
@@ -191,6 +342,7 @@ impl Phone {
mut submit: impl FnMut(Command) -> Result<Response, String>,
) -> Option<SystemAction> {
self.acknowledge();
self.landscape = tsunagi_ui::widgets::landscape(ctx);
let report = if let State::Ready(report, at) = state {
if self.snapshot.at != Some(*at) {
self.snapshot.generation = self.snapshot.generation.wrapping_add(1);
@@ -205,9 +357,23 @@ impl Phone {
{
self.home();
}
if self
.forms
.selected_network
.as_ref()
.is_some_and(|id| !report.networks.iter().any(|n| &n.network_id == id))
{
self.forms.close_selection();
}
if self.pick_exit && self.pending.is_none() {
self.pick_exit = false;
self.open_exit_picker();
}
Some(report)
} else {
if self.page.network().is_some() || self.page == Page::Join {
if self.page.network().is_some()
|| matches!(self.page, Page::Join | Page::Monitor | Page::Exits)
{
self.home();
}
self.snapshot = Snapshot::default();
@@ -222,25 +388,35 @@ impl Phone {
egui::TopBottomPanel::top("navigation").show(ctx, |ui| {
ui.horizontal(|ui| {
ui.spacing_mut().interact_size.y = 32.0;
if self.page != Page::Home && ui.button(icon::ARROW_LEFT).clicked() {
if self.page != Page::Home
&& tsunagi_ui::widgets::icon_button(ui, icon::ARROW_LEFT, "Back").clicked()
{
system = self.back();
}
ui.heading(self.page.title());
if self.page == Page::Home {
ui.weak(env!("CARGO_PKG_VERSION"));
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
if ui.button(icon::INFO).clicked() {
if tsunagi_ui::widgets::icon_button(ui, icon::INFO, "About Tsunagi")
.clicked()
{
self.page = Page::About;
}
if report.is_some() {
if tsunagi_ui::widgets::icon_button(ui, icon::PULSE, "Traffic monitor")
.clicked()
{
self.page = Page::Monitor;
}
ui.selectable_value(&mut self.forms.unit, Unit::Bytes, "bytes");
ui.selectable_value(&mut self.forms.unit, Unit::Packets, "pkts");
}
});
} else if self.page == Page::About
&& !matches!(state, State::Off)
&& ui.button("Stop VPN").clicked()
&& ui.button("Stop Tsunagi Agent").clicked()
{
self.home();
system = Some(SystemAction::Stop);
}
});
@@ -252,7 +428,19 @@ impl Phone {
.page
.network()
.and_then(|id| report?.networks.iter().find(|n| n.network_id == id));
if self.page != Page::Monitor {
self.monitor = None;
}
match (&self.page, selected) {
(Page::Monitor, _) => {
let m = self
.monitor
.get_or_insert_with(|| crate::monitor::Monitor::new(self.cache_dir.clone()));
egui::CentralPanel::default().show(ctx, |ui| {
m.view
.show(ui, report.map(|r| r.as_ref()), self.snapshot.generation)
});
}
(Page::About, _) => about::show(ctx, None, &self.snapshot),
(Page::Vips(id), Some(network)) => {
let editor = self.forms.vip_windows.entry(id.clone()).or_default();
@@ -275,13 +463,17 @@ impl Phone {
}
_ => {
egui::CentralPanel::default().show(ctx, |ui| {
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
if let Some(report) = report && self.page == Page::Home && self.landscape {
self.landscape_home(ui, &actions, report);
return;
}
egui::ScrollArea::vertical().id_salt(self.page.title()).auto_shrink([false, false]).show(ui, |ui| {
let Some(report) = report else {
match state {
State::Starting => {ui.spinner(); ui.label("Starting VPN…");}
State::Starting => {ui.spinner(); ui.label("Starting Tsunagi Agent…");}
_ => {
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("VPN is stopped");}
if ui.button("Start VPN").clicked() {system = Some(SystemAction::Start);}
if let State::Error(e) = state {ui.colored_label(BAD, e);} else {ui.weak("Tsunagi Agent is stopped");}
if ui.button("Start Tsunagi Agent").clicked() {self.error = None; system = Some(SystemAction::Start);}
}
}
return;
@@ -292,19 +484,22 @@ impl Phone {
ui.separator();
if ui.button("Join or create a network").clicked() {self.page = Page::Join;}
for n in &report.networks {
if home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false) {self.page = Page::Exit(n.network_id.clone());}
if self.forms.open_devices.remove(&n.network_id) {self.page = Page::Devices(n.network_id.clone());}
if self.forms.vip_windows.contains_key(&n.network_id) {self.page = Page::Vips(n.network_id.clone());}
home::draw_network(ui, &actions, &mut self.forms, &self.traffic, n, report, false);
}
ui.add_space(80.);
}
Page::Join => {
home::draw_join(ui, &actions, &mut self.forms.join);
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
}
Page::Exit(_) => {
if let Some(n) = selected && let Some(choice) = devices::choose_exit(ui, n, &report.endpoint_id) {
Page::Exits => {
if let Some(choice) = devices::choose_exit_from_networks(ui, &report.networks, &report.endpoint_id) {
self.forms.exit_confirm = Some(choice);
}
if report.networks.is_empty() && ui.button("Join or create a network").clicked() {
self.before_picker = None;
self.page = Page::Join;
}
}
Page::Leave(id) => {
if let Some(n) = selected {
@@ -317,6 +512,23 @@ impl Phone {
}
});
});
if let Some(report) = report
&& self.page == Page::Home
{
for n in &report.networks {
if self.forms.open_devices.remove(&n.network_id) {
self.page = Page::Devices(n.network_id.clone());
break;
}
if self.forms.vip_windows.contains_key(&n.network_id) {
self.page = Page::Vips(n.network_id.clone());
break;
}
}
}
if self.page == Page::Home && self.forms.exit_confirm.is_none() {
self.exit_button(ctx, report.is_some() && !actions.busy());
}
devices::confirm_exit(ctx, &actions, &mut self.forms.exit_confirm, None);
}
}
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-awg"
version = "1.0.1"
version = "1.0.9"
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
edition.workspace = true
rust-version.workspace = true
+3
View File
@@ -532,6 +532,9 @@ struct FaultLink {
sequence: AtomicU64,
}
impl PacketLink for FaultLink {
fn confirm_delivery(&self) {
self.raw.confirm_delivery();
}
fn network(&self) -> NetworkId {
self.raw.network()
}
+11 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-core"
version = "1.0.1"
version = "1.0.9"
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
readme = "../../README.md"
keywords = ["mesh", "p2p", "iroh", "networking"]
@@ -35,6 +35,7 @@ dns-publish = ["dep:zbus"]
testing = ["dep:tempfile", "dep:tracing-subscriber"]
[dependencies]
tsunagi-speedtest = { path = "../tsunagi-speedtest", version = "0.1.0" }
arc-swap = "1.9"
iroh.workspace = true
# `net` for the local control interface: a Unix socket on Unix, a named pipe
@@ -59,6 +60,8 @@ rand = "0.10"
# zone logic is ours and a full server framework would be a large dependency
# for answering A records from memory.
simple-dns = "0.12"
# IPv4 packet and checksum codecs shared by the Android VPN and Wintun.
smoltcp = { version = "0.12", default-features = false, features = ["std", "proto-ipv4"] }
# The IANA top-level domain list, compiled in: one function, no
# dependencies, no network. Used only to warn that a zone name shadows a
# real public domain, never to refuse one.
@@ -95,14 +98,21 @@ futures-util = { version = "0.3", default-features = false, optional = true }
# safe wrapper, which is how the provisioner observes an adapter by name
# before deciding what to change. Creating an adapter needs the process to be
# elevated and `wintun.dll` to be reachable at run time.
[target.'cfg(any(windows, target_os = "macos"))'.dependencies]
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
socket2 = { version = "0.6", features = ["all"] }
[target.'cfg(target_os = "windows")'.dependencies]
windows-sys = { version = "0.61", features = [
"Win32_Networking_WinSock",
"Win32_Security",
"Win32_Security_Authorization",
"Win32_Foundation",
] }
[dev-dependencies]
smoltcp = { version = "0.12", default-features = false, features = ["medium-ip", "socket-tcp"] }
socket2 = { version = "0.6", features = ["all"] }
# Its own tests use the harness it publishes.
tsunagi-core = { path = ".", features = ["testing"] }
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "process", "test-util"] }
+5 -1
View File
@@ -9,7 +9,7 @@ use std::time::Duration;
use iroh::EndpointId;
use crate::identity::NetworkId;
use crate::identity::{NetworkId, NetworkName};
use crate::net::TransportKind;
use crate::proto::ControlMessage;
use crate::proto::handshake::Role;
@@ -48,8 +48,12 @@ pub enum Event {
PeerDisconnected {
/// The network the session belonged to.
network: NetworkId,
/// Its locally configured name.
network_name: NetworkName,
/// The peer.
peer: EndpointId,
/// Last known name of the authenticated peer, when available.
hostname: Option<String>,
/// Why the session ended. Free of secrets.
reason: String,
},
+82 -64
View File
@@ -22,12 +22,14 @@ mod events;
mod network;
mod session;
mod shutdown;
mod speed;
mod status;
pub use events::Event;
pub use status::{
AgentStatus, CandidateStatus, DataPath, HostnameConflict, MemberStatus, NetworkMetrics,
NetworkState, NetworkStatus, OverlayStatus, PeerStatus, RangeConflict,
AgentStatus, CandidateStatus, DATA_CONNECTING, DATA_DISABLED, DataPath, HostnameConflict,
MemberStatus, NetworkMetrics, NetworkState, NetworkStatus, OverlayStatus, PeerStatus,
RangeConflict,
};
use std::collections::HashMap;
@@ -94,6 +96,7 @@ pub struct Agent {
#[derive(Debug)]
struct Inner {
config: AgentConfig,
speed: speed::SpeedTests,
limits: Arc<Limits>,
storage: Storage,
identity: DeviceIdentity,
@@ -104,8 +107,9 @@ struct Inner {
networks: RwLock<HashMap<NetworkId, NetworkHandle>>,
shutdown: Shutdown,
/// Serialises start, stop, switching and conflict cleanup, including teardown.
lifecycle: Mutex<()>,
lifecycle: Arc<Mutex<()>>,
range_changed: watch::Sender<()>,
roster_changed: watch::Sender<()>,
range_task: std::sync::Mutex<Option<JoinHandle<()>>>,
accept_task: std::sync::Mutex<Option<JoinHandle<()>>>,
plugin_task: std::sync::Mutex<Option<JoinHandle<()>>>,
@@ -135,7 +139,9 @@ impl Inner {
.await
{
Ok(interface) => {
self.adapter.exclude_interface(interface.name());
if interface.on_host() {
self.adapter.exclude_interface(interface.name());
}
for carrier in &self.config.carriers {
carrier.on_interface_ready(interface.name());
}
@@ -216,6 +222,9 @@ impl PacketSink for Sink {
let Some(inner) = self.0.upgrade() else {
return;
};
if speed::receive_packet(&inner, network, peer, &packet) {
return;
}
let Some(interface) = inner.interface.get() else {
return;
};
@@ -297,6 +306,13 @@ impl TransportContext for TransportCtx {
}
impl Agent {
/// Start a fresh, independent observation interval for one local window.
pub fn subscribe_traffic(
&self,
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
self.inner.routes.traffic.subscribe()
}
/// Atomically saves or removes a version-checked shared VIP draft.
/// Every authenticated network member may edit any service.
pub async fn save_vip(
@@ -440,6 +456,7 @@ impl Agent {
let (range_changed, range_updates) = watch::channel(());
let inner = Arc::new(Inner {
speed: speed::SpeedTests::default(),
limits,
storage,
identity,
@@ -448,8 +465,9 @@ impl Agent {
events,
networks: RwLock::new(HashMap::new()),
shutdown: Shutdown::new(),
lifecycle: Mutex::new(()),
lifecycle: Arc::new(Mutex::new(())),
range_changed,
roster_changed: watch::channel(()).0,
range_task: std::sync::Mutex::new(None),
accept_task: std::sync::Mutex::new(None),
plugin_task: std::sync::Mutex::new(None),
@@ -506,7 +524,8 @@ impl Agent {
.tun_factory
.as_ref()
.map(|_| Arc::new(Sink(Arc::downgrade(&inner))) as Arc<dyn PacketSink>);
let context = PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink);
let context =
PluginContext::new(plugin_tx, inner.identity.endpoint_id(), sink, &inner.routes);
if let Some(tunnel) = &inner.config.tunnel {
tunnel.attach(context);
}
@@ -643,6 +662,7 @@ impl Agent {
on_host: interface.on_host(),
mtu: interface.mtu(),
addresses: interface.wanted_addresses(),
address_error: interface.address_error(),
counters: interface.counters(),
broadcast_rules: interface.broadcast_rules(),
})
@@ -687,6 +707,7 @@ impl Agent {
for sender in senders {
let _ = sender.send(NetCommand::SetHostname(hostname.clone())).await;
}
self.inner.roster_changed.send_replace(());
Ok(hostname)
}
@@ -703,6 +724,13 @@ impl Agent {
self.inner.events.subscribe()
}
/// Subscribe to changes affecting the mesh DNS roster, exit offers or selected exit.
/// Changes coalesce. Read the current status after subscribing and again on
/// notification. Packet counters and routine control traffic do not wake subscribers.
pub fn watch_roster(&self) -> watch::Receiver<()> {
self.inner.roster_changed.subscribe()
}
/// Makes this agent a member of a network, activating it.
///
/// The same `(name, secret)` always produces the same [`NetworkId`], on
@@ -794,47 +822,27 @@ impl Agent {
/// choice in the others. The member has to be connected and offering
/// to be an exit node. Remembered across restarts.
pub async fn set_exit_via(&self, network_id: NetworkId, via: Option<EndpointId>) -> Result<()> {
let active = self.is_active(network_id).await;
if via.is_some() && !active {
return Err(Error::NetworkNotActive(network_id));
}
if active {
let (reply, receive) = oneshot::channel();
self.command(network_id, NetCommand::SetExitVia { via, reply })
.await?;
receive
.await
.map_err(|_| Error::Stopped)?
.map_err(|reason| Error::Rejected { reason })?;
}
self.inner
.storage
.set_exit_via(network_id, via.map(|peer| *peer.as_bytes()))
.await?;
if via.is_some() {
// One default route: whatever the other networks were doing, they
// are not any more.
let others: Vec<NetworkId> = self
.inner
.networks
.read()
.await
.keys()
.copied()
.filter(|other| *other != network_id)
.collect();
for other in others {
let (reply, receive) = oneshot::channel();
if self
.command(other, NetCommand::SetExitVia { via: None, reply })
.await
.is_ok()
{
let _ = receive.await;
}
let lifecycle = self.inner.lifecycle.clone().lock_owned().await;
if !self.is_active(network_id).await {
if via.is_some() {
return Err(Error::NetworkNotActive(network_id));
}
return self.inner.storage.set_exit_via(network_id, None).await;
}
Ok(())
// The actor owns the guard through validation, persistence and routing,
// even if the requesting IPC client disconnects halfway through.
let (reply, receive) = oneshot::channel();
self.command(
network_id,
NetCommand::SetExitVia {
via,
lifecycle,
reply,
},
)
.await?;
receive.await.map_err(|_| Error::Stopped)?
}
/// Changes a network's local broadcast policy now and after restart.
@@ -958,6 +966,13 @@ impl Agent {
)?;
}
let range = self.desired_range(network_id).await?;
let exit = crate::overlay::ExitPolicy {
offer: stored.as_ref().is_some_and(|s| s.exit_node),
via: stored
.as_ref()
.and_then(|s| s.exit_via)
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
};
if let Some(range) = range {
let conflicts = self.inner.routes.overlapping_networks(network_id, range);
if !conflicts.is_empty() {
@@ -967,19 +982,20 @@ impl Agent {
conflicts: conflicts.into_iter().map(|(id, _)| id).collect(),
});
}
self.inner
.routes
.set_network(
network_id,
crate::overlay::NetworkRoutes {
range: Some(range),
..Default::default()
},
)
.map_err(|err| Error::Rejected {
reason: err.to_string(),
})?;
}
self.inner
.routes
.set_network(
network_id,
crate::overlay::NetworkRoutes {
range,
exit,
..Default::default()
},
)
.map_err(|err| Error::Rejected {
reason: err.to_string(),
})?;
let mut backends = Vec::new();
if let Some(discovery) = &self.inner.config.discovery {
backends.push(discovery.clone());
@@ -1003,17 +1019,11 @@ impl Agent {
if !plugins.is_empty() {
self.inner.ensure_interface().await;
}
let exit_offer = stored.as_ref().is_some_and(|stored| stored.exit_node);
let exit_via = stored
.as_ref()
.and_then(|stored| stored.exit_via)
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok());
let handle = network::spawn(RuntimeParams {
agent: Arc::downgrade(&self.inner),
vips,
retirements,
broadcast,
exit_offer,
exit_via,
keys,
adapter: self.inner.adapter.clone(),
storage: self.inner.storage.clone(),
@@ -1035,6 +1045,7 @@ impl Agent {
unreachable_data_peers: Arc::clone(&self.inner.config.unreachable_data_peers),
ipv4_range: range,
range_changed: self.inner.range_changed.clone(),
roster_changed: self.inner.roster_changed.clone(),
});
networks.insert(network_id, handle);
drop(networks);
@@ -1046,6 +1057,7 @@ impl Agent {
tunnel.on_network_activated(network_id);
}
self.inner.roster_changed.send_replace(());
let _ = self.inner.events.send(Event::NetworkActivated {
network: network_id,
});
@@ -1082,6 +1094,7 @@ impl Agent {
}
async fn stop_network_locked(&self, network_id: NetworkId) -> Result<()> {
self.inner.speed.remove_network(network_id);
let handle = {
let mut networks = self.inner.networks.write().await;
networks
@@ -1113,6 +1126,7 @@ impl Agent {
interface.sync_broadcast_rules().await;
interface.sync_exit_rules().await;
}
self.inner.roster_changed.send_replace(());
Ok(())
}
@@ -1127,6 +1141,7 @@ impl Agent {
self.stop_network_locked(network_id).await?;
}
self.inner.storage.remove_network(network_id).await?;
self.inner.roster_changed.send_replace(());
for plugin in &self.inner.config.carriers {
plugin.on_network_forgotten(network_id);
}
@@ -1316,6 +1331,7 @@ impl Agent {
})
.collect();
networks.push(NetworkStatus {
speed: Default::default(),
vips,
protocols: self.effective_protocols(stored.protocols.as_ref()),
auto_start: stored.auto_start,
@@ -1325,6 +1341,7 @@ impl Agent {
.exit_via
.and_then(|bytes| EndpointId::from_bytes(&bytes).ok()),
exit_via_online: false,
exit_traffic: None,
exit_rules: Default::default(),
descriptor: keys.descriptor(),
name: stored.name,
@@ -1394,6 +1411,7 @@ impl Agent {
/// After this returns, the state directory can be opened by another agent.
pub async fn shutdown(&self) {
self.inner.shutdown.trigger();
self.inner.speed.shutdown();
let lifecycle_guard = self.inner.lifecycle.lock().await;
let handles: Vec<NetworkHandle> = {
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,359 @@
//! Compare one alternative per peer while normal traffic stays on the incumbent.
//! The elected dialler chooses for both directions. Each decision names the
//! exact two health profiles, so delayed messages cannot retire a reopened link.
use super::{ControlMessage, EndpointId, Event, PacketLink, PluginCapability, Runtime};
use crate::dataplane::transport::{LinkQuality, TransportPayload};
use std::time::{Duration, Instant};
pub(super) const PROTOCOL: &str = "link-choice";
const RETRY: Duration = Duration::from_secs(3);
const NEXT_TRIAL: Duration = Duration::from_secs(120);
const MIN_WINDOW: Duration = Duration::from_secs(6);
// Allow a full rolling health window to replace probes sent before the
// responder installed its profile. Persistent loss still disqualifies a trial.
const MAX_WINDOW: Duration = Duration::from_secs(30);
pub(super) fn capability() -> PluginCapability {
PluginCapability {
protocol: PROTOCOL.into(),
version: 1,
enabled: true,
data: Vec::new(),
}
}
fn supports_choice(caps: &[PluginCapability]) -> bool {
caps.iter()
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
}
/// None keeps measuring on the alternative while user traffic stays on the incumbent.
fn promotion_decision(age: Duration, measured: Option<(LinkQuality, LinkQuality)>) -> Option<bool> {
if age < MIN_WINDOW {
return None;
}
let Some((current, alternative)) = measured.filter(|(current, alternative)| {
current.samples >= 5 && alternative.samples >= 5 && alternative.losses == 0
}) else {
return (age >= MAX_WINDOW).then_some(false);
};
let gain = current.rtt.saturating_sub(alternative.rtt);
Some(gain >= (current.rtt / 5).max(Duration::from_millis(5)))
}
/// Fixed-size identifiers from the two privately negotiated health profiles.
/// The responder echoes this value after accepting a decision.
#[derive(Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
struct Choice {
keep: [u8; 16],
retire: [u8; 16],
}
struct Trial {
protocol: String,
started: Instant,
decision: Option<Choice>,
retry_at: Instant,
}
pub(super) struct Schedule {
next: Instant,
cursor: usize,
trial: Option<Trial>,
}
impl Schedule {
pub(super) fn is_trial(&self, protocol: &str) -> bool {
self.trial
.as_ref()
.is_some_and(|trial| trial.protocol == protocol)
}
/// The responder can close the losing link before its acknowledgement
/// arrives. Only an exact generation match makes this a planned closure.
pub(super) fn retiring(&self, profile: Option<[u8; 16]>) -> bool {
self.trial
.as_ref()
.and_then(|trial| trial.decision)
.is_some_and(|choice| Some(choice.retire) == profile)
}
}
impl Runtime {
pub(super) fn link_installed(&mut self, peer: EndpointId) {
if self.local_id.as_bytes() >= peer.as_bytes() || self.params.carriers.len() < 2 {
return;
}
let now = Instant::now();
let jitter = (peer.as_bytes()[0] ^ self.network_id.as_bytes()[0]) % 6;
let schedule = self.comparisons.entry(peer).or_insert(Schedule {
next: now + Duration::from_secs(12 + u64::from(jitter)),
cursor: 0,
trial: None,
});
if let Some(trial) = &mut schedule.trial {
// Any replacement invalidates an outstanding decision naming the
// previous pair of profiles. Compare both current links afresh.
trial.decision = None;
trial.started = now;
trial.retry_at = now;
}
}
/// At most two alternatives per network are opened or measured at once.
/// Waiting for a peer to acknowledge a decision uses no measurement slot. Old peers
/// keep the original single-carrier behaviour without a wire upgrade.
pub(super) fn next_comparison(
&mut self,
served: &[(String, u16)],
now: Instant,
) -> Option<(EndpointId, String)> {
if !supports_choice(&self.local_capabilities)
|| self
.comparisons
.values()
.filter_map(|s| s.trial.as_ref())
.filter(|trial| trial.decision.is_none())
.count()
>= 2
{
return None;
}
let (peer, index) =
self.comparisons
.iter()
.filter_map(|(peer, schedule)| {
if schedule.next > now
|| schedule.trial.is_some()
|| self.no_direct_data(*peer)
|| self.opening.iter().any(|(id, _)| id == peer)
{
return None;
}
let session = self.sessions.get(peer)?;
if !supports_choice(&session.capabilities)
|| self.hub.direct_kinds(*peer).len() != 1
{
return None;
}
let index = (0..served.len())
.map(|n| (n + schedule.cursor) % served.len())
.find(|i| {
let (name, version) = &served[*i];
let key = (*peer, name.clone());
!self.links.contains_key(&key)
&& self
.protocol_dial_states
.get(&key)
.is_none_or(|s| s.cooldown_until <= now)
&& session.capabilities.iter().any(|c| {
c.enabled && &c.protocol == name && &c.version == version
})
})?;
Some((schedule.next, *peer, index))
})
.min()
.map(|(_, peer, index)| (peer, index))?;
let schedule = self.comparisons.get_mut(&peer)?;
let protocol = served[index].0.clone();
schedule.cursor = index + 1;
schedule.trial = Some(Trial {
protocol: protocol.clone(),
started: now,
decision: None,
retry_at: now,
});
Some((peer, protocol))
}
pub(super) fn finish_comparison(&mut self, peer: EndpointId) {
if let Some(schedule) = self.comparisons.get_mut(&peer) {
schedule.trial = None;
schedule.next = Instant::now() + NEXT_TRIAL;
}
}
pub(super) fn review_comparisons(&mut self) {
let peers: Vec<_> = self
.comparisons
.iter()
.filter(|(_, s)| s.trial.is_some())
.map(|(peer, _)| *peer)
.collect();
for peer in peers {
self.review_trial(peer);
}
}
fn review_trial(&mut self, peer: EndpointId) {
let Some(trial) = self.comparisons.get(&peer).and_then(|s| s.trial.as_ref()) else {
return;
};
let key = (peer, trial.protocol.clone());
if self.opening.contains(&key) {
return;
}
let kinds = self.hub.direct_kinds(peer);
if kinds.len() < 2 || !self.links.contains_key(&key) {
self.finish_comparison(peer);
return;
}
let now = Instant::now();
if now < trial.retry_at {
return;
}
let choice = if let Some(choice) = trial.decision {
choice
} else {
let Some(other) = kinds.iter().find(|kind| **kind != trial.protocol) else {
return;
};
let Some(current) = self.links.get(&(peer, other.clone())) else {
return;
};
let Some(candidate) = self.links.get(&key) else {
return;
};
let age = now.duration_since(trial.started);
let measured = current.quality().zip(candidate.quality());
let Some(promote) = promotion_decision(age, measured) else {
return;
};
tracing::debug!(peer = %peer.fmt_short(), incumbent = %other, candidate = %trial.protocol, ?measured, promote, "compared data carriers");
let (winner, loser) = if promote {
(candidate, current)
} else {
(current, candidate)
};
let (Some(keep), Some(retire)) = (winner.profile_id(), loser.profile_id()) else {
return;
};
self.hub
.prefer_direct(peer, if promote { &trial.protocol } else { other });
Choice { keep, retire }
};
if let Some(trial) = self
.comparisons
.get_mut(&peer)
.and_then(|s| s.trial.as_mut())
{
trial.decision = Some(choice);
trial.retry_at = now + RETRY;
}
self.send_choice(peer, choice);
}
fn send_choice(&mut self, peer: EndpointId, choice: Choice) {
if let Ok(bytes) = postcard::to_stdvec(&choice) {
let _ = self.send_to(
peer,
ControlMessage::Transport {
protocol: PROTOCOL.into(),
payload: TransportPayload::new(bytes),
},
);
}
}
pub(super) fn receive_choice(&mut self, peer: EndpointId, payload: &[u8]) {
if payload.len() != 32 {
return;
}
let Ok(choice) = postcard::from_bytes::<Choice>(payload) else {
return;
};
if choice.keep == choice.retire
|| !supports_choice(&self.local_capabilities)
|| !self
.sessions
.get(&peer)
.is_some_and(|s| supports_choice(&s.capabilities))
{
return;
}
let dialler = self.local_id.as_bytes() < peer.as_bytes();
if dialler
&& self
.comparisons
.get(&peer)
.and_then(|s| s.trial.as_ref())
.and_then(|t| t.decision)
!= Some(choice)
{
return;
}
let find = |profile| {
self.links
.iter()
.find(|((id, _), link)| {
*id == peer && !link.is_closed() && link.profile_id() == Some(profile)
})
.map(|((_, kind), _)| kind.clone())
};
let Some(winner) = find(choice.keep) else {
return;
};
let loser = find(choice.retire);
self.hub.prefer_direct(peer, &winner);
if let Some(kind) = loser {
self.hub.clear_direct(peer, &kind);
if let Some(link) = self.links.remove(&(peer, kind.clone())) {
link.close();
self.emit(Event::DataLinkDown {
network: self.network_id,
peer,
protocol: kind,
reason: format!("carrier comparison kept {winner}"),
});
}
}
if dialler {
self.finish_comparison(peer);
} else {
self.send_choice(peer, choice);
}
self.announce_reach(false);
}
}
#[cfg(test)]
mod tests {
use super::*;
fn measurement(ms: u64, samples: usize, losses: usize) -> LinkQuality {
LinkQuality {
rtt: Duration::from_millis(ms),
samples,
losses,
observed_at: Instant::now(),
}
}
#[test]
fn a_loss_during_profile_installation_can_age_out_before_deciding() {
let observed =
|samples, losses| Some((measurement(200, 20, 0), measurement(30, samples, losses)));
assert_eq!(promotion_decision(MIN_WINDOW, observed(5, 1)), None);
assert_eq!(
promotion_decision(Duration::from_secs(24), observed(20, 0)),
Some(true)
);
assert_eq!(promotion_decision(MAX_WINDOW, observed(18, 2)), Some(false));
assert_eq!(promotion_decision(MAX_WINDOW, observed(4, 0)), Some(false));
assert_eq!(promotion_decision(MIN_WINDOW / 2, observed(5, 0)), None);
}
#[test]
fn promote_only_a_sampled_reliable_and_materially_faster_path() {
let better = |current: &LinkQuality, candidate: &LinkQuality| {
promotion_decision(MAX_WINDOW, Some((*current, *candidate))) == Some(true)
};
let current = measurement(350, 20, 1);
assert!(better(&current, &measurement(60, 6, 0)));
assert!(!better(&current, &measurement(60, 1, 0)));
assert!(!better(&current, &measurement(60, 6, 2)));
assert!(!better(&measurement(61, 20, 0), &measurement(59, 10, 0)));
assert!(!better(&measurement(10, 20, 0), &measurement(7, 10, 0)));
assert!(!better(&measurement(8, 2, 0), &measurement(1, 6, 0)));
}
}
@@ -0,0 +1,152 @@
//! Each ordered stream keeps a cursor into the latest signed state. A slow or
//! reconnecting peer can catch up without a per-peer backlog of signed frames.
use super::{ControlMessage, EndpointId, MAX_RETIREMENT_LEN, Runtime};
use std::collections::BTreeMap;
use std::ops::Bound::{Excluded, Unbounded};
/// The stable identity of a signed object, including tombstones.
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) enum SyncKey {
Claim(EndpointId),
Retirement(EndpointId),
Vip(String),
}
/// One entry per stored object, regardless of its edit count or the number of
/// peers. Revisions are local scheduling information, never persisted or sent.
#[derive(Default)]
pub(super) struct Changes {
latest: u64,
revisions: BTreeMap<SyncKey, u64>,
order: BTreeMap<u64, SyncKey>,
}
impl Changes {
fn note(&mut self, key: SyncKey) {
self.latest += 1;
if let Some(previous) = self.revisions.insert(key.clone(), self.latest) {
self.order.remove(&previous);
}
self.order.insert(self.latest, key);
}
fn after(&self, cursor: u64) -> impl Iterator<Item = (u64, &SyncKey)> {
self.order
.range((Excluded(cursor), Unbounded))
.map(|(&revision, key)| (revision, key))
}
}
impl Runtime {
pub(super) fn index_stored_state(&mut self) {
for record in self.state.records() {
if let Ok(author) = record.author_id() {
self.changes.note(SyncKey::Claim(author));
}
}
for marker in self.state.retirements() {
if let Ok(target) = marker.target.author_id() {
self.changes.note(SyncKey::Retirement(target));
}
}
for id in self.params.vips.ids() {
self.changes.note(SyncKey::Vip(id));
}
}
pub(super) fn share_changes(&mut self, keys: impl IntoIterator<Item = SyncKey>) -> usize {
for key in keys {
self.changes.note(key);
}
self.params.roster_changed.send_replace(());
self.flush_updates();
self.sessions
.values()
.filter(|session| session.state_sent == self.changes.latest)
.count()
}
pub(super) fn flush_updates(&mut self) {
let peers: Vec<_> = self
.sessions
.values()
.filter(|s| s.state_sent < self.changes.latest)
.map(|s| s.peer)
.collect();
for peer in peers {
self.flush_peer(peer);
}
}
pub(super) fn flush_peer(&mut self, peer: EndpointId) {
// A retirement contains a signed claim plus a second signature, so its
// size bound also covers a claim. VIPs are validated as complete frames.
let limits = &self.params.limits;
let batch = (limits.max_frame_len.saturating_sub(128) / MAX_RETIREMENT_LEN)
.max(1)
.min(limits.max_state_records.max(1));
while let Some(session) = self.sessions.get(&peer) {
if session.outbound.capacity() == 0 {
break;
}
let cursor = session.state_sent;
let Some((mut through, first)) = self.changes.after(cursor).next() else {
break;
};
let message = {
let pending = self.changes.after(cursor).take(batch);
match first {
SyncKey::Claim(_) => ControlMessage::State {
records: pending
.map_while(|(revision, key)| {
let SyncKey::Claim(id) = key else { return None };
through = revision;
self.state.get(id).cloned()
})
.collect(),
},
SyncKey::Retirement(_) => ControlMessage::Retirements {
markers: pending
.map_while(|(revision, key)| {
let SyncKey::Retirement(id) = key else {
return None;
};
through = revision;
self.state.retirement_of(id).cloned()
})
.collect(),
},
SyncKey::Vip(id) => ControlMessage::Vips {
entries: self.params.vips.entries(id),
},
}
};
if self.send_to(peer, message).is_err() {
break;
}
if let Some(session) = self.sessions.get_mut(&peer) {
session.state_sent = through;
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn slow_and_returning_sessions_each_get_the_latest_revision() {
let mut index = Changes::default();
let first = SyncKey::Vip("first".into());
let second = SyncKey::Vip("second".into());
index.note(first.clone());
let sent = index.latest;
index.note(second.clone());
index.note(first.clone());
for cursor in [0, sent] {
let pending: Vec<_> = index.after(cursor).map(|(_, key)| key.clone()).collect();
assert_eq!(pending, [second.clone(), first.clone()]);
}
assert_eq!(index.after(index.latest).count(), 0);
}
}
+34 -3
View File
@@ -12,7 +12,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Instant;
use iroh::EndpointId;
use iroh::endpoint::{Connection, RecvStream, SendStream};
use iroh::endpoint::{Connection, ConnectionError, RecvStream, SendStream};
use tokio::sync::mpsc;
use tokio::task::JoinHandle;
@@ -60,6 +60,22 @@ pub(crate) enum SessionEvent {
},
}
/// The transport category and code are useful in logs. Remote close text is
/// arbitrary peer-supplied data and may contain secrets or control characters.
pub(super) fn describe_quic_close(cause: ConnectionError) -> String {
match cause {
ConnectionError::ApplicationClosed(close) => {
format!("QUIC closed by peer, application code {}", close.error_code)
}
ConnectionError::ConnectionClosed(close) => {
format!("QUIC closed by peer, transport code {}", close.error_code)
}
ConnectionError::TransportError(error) => format!("QUIC transport error {}", error.code),
ConnectionError::LocallyClosed => "QUIC closed locally".to_owned(),
other => format!("QUIC: {other}"),
}
}
/// A live session, as held by the network runtime.
#[derive(Debug)]
pub(crate) struct Session {
@@ -68,10 +84,19 @@ pub(crate) struct Session {
pub(crate) role: Role,
pub(crate) established: Instant,
pub(crate) conn: Connection,
/// Already encoded frame payloads, so the runtime can account for the exact
/// number of control bytes it queues.
/// Last signed-state revision queued on this ordered stream.
pub(super) state_sent: u64,
/// Prefix of the current introduction list already queued on this stream.
pub(super) introductions_sent: usize,
pub(super) reach_sent: Option<Instant>,
/// Already encoded frames, accounted for when queued.
pub(crate) outbound: mpsc::Sender<zeroize::Zeroizing<Vec<u8>>>,
pub(crate) hostname: Option<String>,
pub(crate) agent_version: Option<String>,
/// Selection reported by this peer, or unknown for a pre-extension session.
pub(super) uses_our_exit: Option<bool>,
/// Last selection successfully queued to this recipient on this session.
pub(super) notified_exit_use: Option<bool>,
pub(crate) capabilities: Vec<PluginCapability>,
pub(crate) broadcast: bool,
/// The peer offers itself as an exit node in this network.
@@ -227,7 +252,13 @@ pub(crate) fn spawn(
established: Instant::now(),
conn,
outbound: outbound_tx,
state_sent: 0,
introductions_sent: 0,
reach_sent: None,
hostname: None,
agent_version: None,
uses_our_exit: None,
notified_exit_use: None,
capabilities: Vec::new(),
broadcast: false,
exit_node: false,
+606
View File
@@ -0,0 +1,606 @@
//! Local ownership of one bounded throughput diagnostic. Control carries
//! negotiation and receiver feedback. Every data packet uses the current cipher and carrier.
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, Weak};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use arc_swap::ArcSwapOption;
use bytes::Bytes;
use iroh::EndpointId;
use tsunagi_speedtest as wire;
use super::{Agent, DataPath, Inner, PeerStatus};
use crate::dataplane::PluginCapability;
use crate::error::{Error, Result};
use crate::identity::NetworkId;
use crate::ipc::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
use crate::overlay::router::DiagnosticPeer;
use crate::proto::message::{ControlMessage, TransportPayload};
type Key = (NetworkId, EndpointId);
/// A batch can spend at most this many IPv4 bytes in *each* direction.
/// Every remaining peer gets an equal reservation even when earlier probes are lost.
const BATCH_BYTES: u32 = 128 * 1024 * 1024;
const METERED_BATCH_BYTES: u32 = 16 * 1024 * 1024;
pub(super) fn capability() -> PluginCapability {
PluginCapability {
protocol: wire::PROTOCOL.into(),
version: wire::VERSION,
enabled: true,
data: Vec::new(),
}
}
pub(super) fn supported(caps: &[PluginCapability]) -> bool {
caps.iter()
.any(|c| c.enabled && c.protocol == wire::PROTOCOL && c.version == wire::VERSION)
}
fn envelope(message: &wire::Control) -> Option<ControlMessage> {
Some(ControlMessage::Transport {
protocol: wire::PROTOCOL.into(),
payload: TransportPayload::new(message.encode().ok()?),
})
}
fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
struct Channel {
key: Key,
id: u64,
limit: u32,
addresses: DiagnosticPeer,
handle: wire::Handle,
}
struct Job {
generation: u64,
network: NetworkId,
batch: Option<SpeedBatchReport>,
}
#[derive(Default)]
struct Jobs {
job: Option<Job>,
history: BTreeMap<Key, SpeedPeerReport>,
}
#[derive(Default)]
pub(super) struct SpeedTests {
// Admission, completion and cancellation serialize here. Decrypted packets
// only read the active channel and its receiver counter.
jobs: Mutex<Jobs>,
active: ArcSwapOption<Channel>,
metered: AtomicBool,
}
impl std::fmt::Debug for SpeedTests {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SpeedTests").finish_non_exhaustive()
}
}
impl SpeedTests {
fn lock(&self) -> MutexGuard<'_, Jobs> {
self.jobs.lock().unwrap_or_else(|e| e.into_inner())
}
fn clear_channel(&self, key: Key, id: u64) {
// Called with the jobs lock held so an old task cannot clear its successor.
if self
.active
.load()
.as_ref()
.is_some_and(|c| c.key == key && c.id == id)
{
self.active.store(None);
}
}
pub(super) fn report(
&self,
network: NetworkId,
peers: &[PeerStatus],
enabled: bool,
) -> SpeedReport {
let jobs = self.lock();
SpeedReport {
batch: jobs
.job
.as_ref()
.filter(|j| j.network == network)
.and_then(|j| j.batch),
peers: jobs
.history
.iter()
.filter(|((net, _), _)| *net == network)
.map(|((_, peer), report)| (peer.to_string(), report.clone()))
.collect(),
capable: peers
.iter()
.filter(|p| enabled && supported(&p.capabilities))
.map(|p| p.endpoint_id.to_string())
.collect(),
}
}
pub(super) fn disconnected(&self, network: NetworkId, peer: EndpointId) {
if let Some(c) = self
.active
.load()
.as_ref()
.filter(|c| c.key == (network, peer))
{
c.handle.cancel();
}
}
fn cancel_locked(&self, jobs: &mut Jobs, network: NetworkId) {
if let Some(c) = self.active.load().as_ref().filter(|c| c.key.0 == network) {
c.handle.cancel();
}
if jobs.job.as_ref().is_some_and(|job| job.network == network) {
jobs.job = None;
for ((net, _), report) in &mut jobs.history {
if *net == network
&& matches!(
report.phase,
SpeedPhase::Queued
| SpeedPhase::Preparing
| SpeedPhase::Download
| SpeedPhase::Upload
)
{
match report.phase {
SpeedPhase::Download => report.down = None,
SpeedPhase::Upload => report.up = None,
_ => {}
}
report.phase = SpeedPhase::Cancelled;
report.measured_at_unix_secs = now();
}
}
}
}
pub(super) fn remove_network(&self, network: NetworkId) {
let mut jobs = self.lock();
self.cancel_locked(&mut jobs, network);
jobs.history.retain(|(net, _), _| *net != network);
}
pub(super) fn shutdown(&self) {
let mut jobs = self.lock();
jobs.job = None;
if let Some(channel) = self.active.swap(None) {
channel.handle.cancel();
}
}
}
/// Recognized probe frames never go to a host socket. Admission is stricter
/// than exit traffic: both addresses must be the current signed overlay pair.
pub(super) fn receive_packet(
inner: &Inner,
network: NetworkId,
peer: EndpointId,
packet: &[u8],
) -> bool {
if !wire::is_test_packet(packet) {
return false;
}
if let Some(channel) = inner.speed.active.load().as_ref()
&& channel.key == (network, peer)
&& let Some(data) = wire::decode_packet(packet)
&& data.id == channel.id
&& (data.destination, data.source) == (channel.addresses.local, channel.addresses.remote)
&& channel.addresses.is_current(&inner.routes)
{
inner
.routes
.traffic
.packet(network, peer, crate::traffic::Direction::Rx, packet, || {
crate::traffic::Role::SpeedTest
})
.record();
channel.handle.data(data);
}
true
}
fn config(
inner: &Inner,
key: Key,
id: u64,
bytes: u32,
rtt: Option<Duration>,
) -> Option<(wire::Config, DiagnosticPeer)> {
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
wire::METERED_BYTES
} else {
wire::NORMAL_BYTES
};
let cfg = wire::Config {
id,
local: addresses.local,
remote: addresses.remote,
mtu: u16::try_from(inner.config.interface_mtu).unwrap_or(u16::MAX),
byte_limit: bytes.min(ceiling),
rtt: rtt.unwrap_or(Duration::from_millis(100)),
};
Some((cfg, addresses))
}
pub(super) fn receive_control(
inner: &Arc<Inner>,
network: NetworkId,
peer: EndpointId,
message: wire::Control,
rtt: impl FnOnce() -> Option<Duration>,
) -> Option<ControlMessage> {
let key = (network, peer);
let id = message.id();
if let wire::Control::Start(request) = message {
let jobs = inner.speed.lock();
if inner.shutdown.is_triggered()
|| jobs.job.is_some()
|| inner.speed.active.load().is_some()
{
return envelope(&wire::Control::Busy { id });
}
let (cfg, addresses) = config(inner, key, id, request.byte_limit, rtt())?;
let limit = cfg.byte_limit;
let (handle, session) = wire::respond(cfg, request);
inner.speed.active.store(Some(Arc::new(Channel {
key,
id,
limit,
addresses,
handle,
})));
drop(jobs);
let io = TestIo::new(inner, key, None);
tokio::spawn(async move {
let owner = io.inner.clone();
session.run(io).await;
if let Some(inner) = owner.upgrade() {
let _guard = inner.speed.lock();
inner.speed.clear_channel(key, id);
}
});
} else if let Some(c) = inner
.speed
.active
.load()
.as_ref()
.filter(|c| c.key == key && c.id == id)
{
c.handle.control(message);
}
None
}
struct TestIo {
inner: Weak<Inner>,
key: Key,
generation: Option<u64>,
started: Instant,
}
impl TestIo {
fn new(inner: &Arc<Inner>, key: Key, generation: Option<u64>) -> Self {
Self {
inner: Arc::downgrade(inner),
key,
generation,
started: Instant::now(),
}
}
}
impl wire::Io for TestIo {
async fn control(&self, message: wire::Control) -> bool {
let (Some(inner), Some(message)) = (self.inner.upgrade(), envelope(&message)) else {
return false;
};
Agent { inner }
.send(self.key.0, self.key.1, message)
.await
.is_ok()
}
fn packet(&self, packet: Bytes) -> bool {
self.inner.upgrade().is_some_and(|inner| {
let observation = inner.routes.traffic.packet(
self.key.0,
self.key.1,
crate::traffic::Direction::Tx,
&packet,
|| crate::traffic::Role::SpeedTest,
);
let sent = inner
.config
.tunnel
.as_ref()
.is_some_and(|t| t.carry(self.key.0, self.key.1, packet));
if sent {
observation.record();
}
sent
})
}
fn progress(&self, update: wire::Progress) {
if !matches!(
update.state,
wire::State::Starting | wire::State::Download | wire::State::Upload
) {
return; // Publish terminal results together with releasing the slot.
}
if let Some(generation) = self.generation
&& let Some(inner) = self.inner.upgrade()
{
let mut jobs = inner.speed.lock();
if jobs
.job
.as_ref()
.is_some_and(|j| j.generation == generation)
&& let Some(report) = jobs.history.get_mut(&self.key)
{
update_report(report, update, self.started);
}
}
}
}
fn update_report(report: &mut SpeedPeerReport, progress: wire::Progress, started: Instant) {
let live = matches!(progress.state, wire::State::Download | wire::State::Upload);
let rate = |reading: wire::Reading| {
reading
.bps
.filter(|_| match reading.quality {
wire::Quality::Measured | wire::Quality::AtLeast => true,
wire::Quality::Measuring => live,
wire::Quality::Insufficient => false,
})
.map(|bps| SpeedRate {
bps,
lower_bound: reading.quality == wire::Quality::AtLeast,
})
};
report.down = rate(progress.down);
report.up = rate(progress.up);
report.bytes = u64::from(progress.down.bytes) + u64::from(progress.up.bytes);
report.elapsed_ms = u32::try_from(started.elapsed().as_millis()).unwrap_or(u32::MAX);
report.measured_at_unix_secs = now();
report.phase = match progress.state {
wire::State::Starting => SpeedPhase::Preparing,
wire::State::Download => SpeedPhase::Download,
wire::State::Upload => SpeedPhase::Upload,
wire::State::Complete if report.down.is_some() || report.up.is_some() => SpeedPhase::Done,
wire::State::Complete => SpeedPhase::Failed("Insufficient data for a reliable rate".into()),
wire::State::Busy => SpeedPhase::Failed("Peer is already running a speed test".into()),
wire::State::TimedOut => {
SpeedPhase::Failed("Peer did not finish the speed test in time".into())
}
wire::State::Cancelled => SpeedPhase::Cancelled,
wire::State::Failed => {
SpeedPhase::Failed("The data path could not complete the speed test".into())
}
};
}
fn describe_path(peer: &PeerStatus) -> Option<String> {
match &peer.data_path {
DataPath::None => None,
DataPath::Direct { transport } => Some(match &peer.data_transport_detail {
Some(detail) => format!("{transport} · {detail}"),
None => transport.clone(),
}),
DataPath::Relayed { hops, via } => Some(format!("{hops} hops via {}", via.fmt_short())),
}
}
impl Agent {
/// Runs one peer diagnostic, or sequentially tests the capable exit nodes in the network.
pub async fn start_speed_test(
&self,
network: NetworkId,
peer: Option<EndpointId>,
metered: bool,
) -> Result<()> {
let status = self.network_status(network).await?;
let targets: Vec<_> = status
.peers
.iter()
.filter(|p| {
peer.map_or(p.exit_node, |selected| p.endpoint_id == selected)
&& status.speed.capable.contains(&p.endpoint_id.to_string())
})
.map(|p| p.endpoint_id)
.collect();
if targets.is_empty() {
return Err(Error::SpeedTest(
if peer.is_some() {
"Peer is offline or does not support this speed-test version"
} else {
"No online exit nodes support speed tests in this network"
}
.into(),
));
}
let cap = self.inner.limits.max_speed_results;
if targets.len() > cap {
return Err(Error::SpeedTest("Too many peers for one test batch".into()));
}
let generation = rand::random();
let mut jobs = self.inner.speed.lock();
if self.inner.shutdown.is_triggered() {
return Err(Error::Stopped);
}
if jobs.job.is_some() || self.inner.speed.active.load().is_some() {
return Err(Error::SpeedTest(
"Another speed test is already running".into(),
));
}
// Make room before inserting the queue, preserving results of other networks when possible.
for target in &targets {
jobs.history.remove(&(network, *target));
}
while jobs.history.len() + targets.len() > cap {
let Some(oldest) = jobs
.history
.iter()
.min_by_key(|(_, r)| r.measured_at_unix_secs)
.map(|(k, _)| *k)
else {
break;
};
jobs.history.remove(&oldest);
}
let count = targets.len() as u32;
jobs.job = Some(Job {
generation,
network,
batch: peer.is_none().then_some(SpeedBatchReport {
done: 0,
total: count,
}),
});
for target in &targets {
jobs.history.insert(
(network, *target),
SpeedPeerReport {
measured_at_unix_secs: now(),
..Default::default()
},
);
}
let owner = Arc::downgrade(&self.inner);
let metered = metered || self.inner.speed.metered.load(Ordering::Relaxed);
let per_peer = if metered {
wire::METERED_BYTES
} else {
wire::NORMAL_BYTES
};
let limit = if peer.is_none() {
per_peer.min(
if metered {
METERED_BATCH_BYTES
} else {
BATCH_BYTES
} / count,
)
} else {
per_peer
};
tokio::spawn(async move {
for (index, target) in targets.into_iter().enumerate() {
let key = (network, target);
let Some(inner) = owner.upgrade() else {
return;
};
let result = run_outgoing(&inner, key, generation, limit, peer.is_none()).await;
let mut jobs = inner.speed.lock();
if let Some((id, _, _)) = &result {
inner.speed.clear_channel(key, *id);
}
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
return;
}
if let Some(report) = jobs.history.get_mut(&key) {
match result {
Some((_, update, started)) => update_report(report, update, started),
None => {
report.phase = SpeedPhase::Failed(
"Peer is no longer eligible or its overlay address is unavailable"
.into(),
)
}
}
}
if index + 1 == count as usize {
jobs.job = None;
} else if let Some(batch) = jobs.job.as_mut().and_then(|j| j.batch.as_mut()) {
batch.done += 1;
}
}
});
Ok(())
}
/// Cancels the current test and any queued peers in this network.
pub fn stop_speed_test(&self, network: NetworkId) {
let mut jobs = self.inner.speed.lock();
self.inner.speed.cancel_locked(&mut jobs, network);
}
/// Applies the host's actual metered-link policy to incoming and outgoing measurements.
pub fn set_speed_test_metered(&self, metered: bool) {
if self.inner.speed.metered.swap(metered, Ordering::Relaxed) || !metered {
return;
}
let mut jobs = self.inner.speed.lock();
if let Some(network) = jobs.job.as_ref().map(|j| j.network) {
self.inner.speed.cancel_locked(&mut jobs, network);
} else if let Some(c) = self
.inner
.speed
.active
.load()
.as_ref()
.filter(|c| c.limit > wire::METERED_BYTES)
{
c.handle.cancel();
}
}
}
async fn run_outgoing(
inner: &Arc<Inner>,
key: Key,
generation: u64,
limit: u32,
exits_only: bool,
) -> Option<(u64, wire::Progress, Instant)> {
let agent = Agent {
inner: Arc::clone(inner),
};
let status = agent.network_status(key.0).await.ok()?;
let peer = status.peers.iter().find(|p| {
p.endpoint_id == key.1 && (!exits_only || p.exit_node) && supported(&p.capabilities)
})?;
let id = rand::random();
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
let limit = cfg.byte_limit;
let (handle, session) = wire::initiate(cfg);
let io = TestIo::new(inner, key, Some(generation));
{
let mut jobs = inner.speed.lock();
if jobs.job.as_ref().is_none_or(|j| j.generation != generation) {
return None;
}
let report = jobs.history.get_mut(&key)?;
report.phase = SpeedPhase::Preparing;
report.path = describe_path(peer);
inner.speed.active.store(Some(Arc::new(Channel {
key,
id,
limit,
addresses,
handle,
})));
}
let started = io.started;
let update = session.run(io).await;
Some((id, update, started))
}
+19
View File
@@ -16,6 +16,11 @@ use crate::net::{ConnectionCounters, PathAddr, PathInfo, TransportKind};
use crate::proto::handshake::Role;
use crate::storage::CacheOutcome;
/// Informational data-channel diagnostics shared by the status UI and runtime.
pub const DATA_CONNECTING: &str = "establishing external data transport";
/// Data transport was disabled by local policy.
pub const DATA_DISABLED: &str = "data transports disabled locally";
/// Whether a configured network is running locally.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NetworkState {
@@ -51,6 +56,8 @@ pub struct OverlayStatus {
pub mtu: u32,
/// The addresses it should be carrying.
pub addresses: Vec<crate::overlay::Cidr>,
/// Last error applying addresses or subnet routes on the shared interface.
pub address_error: Option<String>,
/// What has happened on it.
pub counters: crate::overlay::Counters,
/// The route and firewall allowance installed for LAN broadcast, when
@@ -138,6 +145,8 @@ pub struct MemberStatus {
/// Status of one authenticated session.
#[derive(Debug, Clone)]
pub struct PeerStatus {
/// The connected member has selected this gateway, or recently sent exit traffic on a legacy session.
pub uses_our_exit: bool,
/// This authenticated peer accepts network broadcasts.
pub broadcast: bool,
/// This authenticated peer offers itself as an exit node.
@@ -150,6 +159,8 @@ pub struct PeerStatus {
///
/// A mutable binding, not an identity.
pub hostname: Option<String>,
/// Software version in the peer's latest authenticated announcement.
pub agent_version: Option<String>,
/// Protocols agreed with this peer: both sides have them at the same
/// version.
///
@@ -168,6 +179,10 @@ pub struct PeerStatus {
pub transport: TransportKind,
/// RTT of the selected path, when iroh reported one.
pub rtt: Option<Duration>,
/// Recent RTT of the selected direct data link, measured by authenticated probes.
pub data_rtt: Option<Duration>,
/// The selected direct data carrier's own description of its underlying path.
pub data_transport_detail: Option<String>,
/// Per-connection counters.
pub connection: ConnectionCounters,
/// Control messages sent on this session.
@@ -227,6 +242,8 @@ pub struct RangeConflict {
/// Status of one network.
#[derive(Debug, Clone)]
pub struct NetworkStatus {
/// Available mesh throughput tests, with local progress and results.
pub speed: crate::ipc::SpeedReport,
/// Shared service configuration with this client's routing observations.
pub vips: Vec<crate::vip::VipStatus>,
/// Enabled local data-plane protocols, in preference order.
@@ -241,6 +258,8 @@ pub struct NetworkStatus {
pub exit_via: Option<EndpointId>,
/// Whether that member is connected and still offering to be one.
pub exit_via_online: bool,
/// IP byte totals since this exit route was selected.
pub exit_traffic: Option<crate::overlay::exit::ExitTraffic>,
/// What the host rules for the exit settings are doing.
pub exit_rules: crate::overlay::ExitRulesReport,
/// Immutable deterministic description of the network space.
+21
View File
@@ -21,6 +21,9 @@ use crate::error::Result;
#[cfg_attr(target_os = "macos", allow(dead_code))]
const APP_NAME: &str = "tsunagi";
/// Maximum length of the optional software release label in a peer announcement.
pub const MAX_AGENT_VERSION_LEN: usize = 64;
/// Rendezvous slots per network; this bounds a discovery sample, not membership.
pub const DHT_SLOTS: u8 = 16;
/// BEP44 permits 1000 bencoded bytes; a 996-byte string has a four-byte prefix.
@@ -47,6 +50,16 @@ pub const DATA_REASSEMBLY_TTL: Duration = Duration::from_secs(5);
/// Completed or discarded packet IDs retained to ignore late duplicate fragments.
pub const DATA_RECENT_IDS: usize = 128;
/// Simultaneous TCP, UDP and ICMP work on a userspace exit.
#[cfg(any(windows, target_os = "macos", test))]
pub(crate) const EXIT_FORWARD_FLOWS: usize = 256;
/// Bounded packet queue shared by userspace exit clients.
#[cfg(any(windows, target_os = "macos", test))]
pub(crate) const EXIT_FORWARD_QUEUE: usize = 64;
/// Concurrent fragmented datagrams accepted by a userspace exit.
#[cfg(any(windows, target_os = "macos", test))]
pub(crate) const EXIT_FORWARD_FRAGMENTS: usize = 32;
/// Where the two stores live.
///
/// The mandatory state and the disposable cache are separate both logically and
@@ -208,6 +221,8 @@ pub struct Limits {
pub max_discovery_candidates: usize,
/// Maximum simultaneous authenticated sessions per network.
pub max_sessions_per_network: usize,
/// Maximum per-peer speed results or queued tests retained by the agent.
pub max_speed_results: usize,
/// Maximum simultaneous inbound connections being handshaken.
pub max_inbound_handshakes: usize,
/// Capacity of a session's outbound queue, providing backpressure.
@@ -244,6 +259,7 @@ impl Default for Limits {
max_concurrent_dials: 8,
max_discovery_candidates: 16,
max_sessions_per_network: 64,
max_speed_results: 256,
max_inbound_handshakes: 32,
session_send_queue: 64,
event_buffer: 512,
@@ -566,3 +582,8 @@ impl std::fmt::Debug for AgentConfig {
}
/// Maximum number of transport links a routed datagram may traverse.
pub const ROUTING_HOP_LIMIT: u8 = 16;
/// Maximum distinct flows per local reader between polls (fits one IPC frame).
pub(crate) const MAX_INTERVAL_FLOWS: usize = 2048;
/// Independent local monitor windows per agent.
pub(crate) const MAX_TRAFFIC_READERS: usize = 4;
+14 -3
View File
@@ -15,7 +15,7 @@ pub mod relay;
pub mod routing;
pub mod transport;
use std::sync::Arc;
use std::sync::{Arc, Weak};
use iroh::EndpointId;
use tokio::sync::mpsc;
@@ -176,6 +176,7 @@ pub struct PluginContext {
/// Where decrypted packets go. Absent when nothing is carrying traffic,
/// in which case a protocol still runs and its packets are discarded.
sink: Option<Arc<dyn PacketSink>>,
routes: Weak<crate::overlay::RoutingTable>,
}
impl PluginContext {
@@ -183,14 +184,23 @@ impl PluginContext {
sender: mpsc::Sender<PluginRequest>,
local: EndpointId,
sink: Option<Arc<dyn PacketSink>>,
routes: &Arc<crate::overlay::RoutingTable>,
) -> Self {
Self {
sender: Some(sender),
local: Some(local),
sink,
routes: Arc::downgrade(routes),
}
}
/// The peer whose tunnel should stay ready for traffic even while idle.
/// Only the locally selected internet exit in its own network qualifies.
pub fn warm_peer(&self, network: NetworkId) -> Option<EndpointId> {
let (selected, peer) = self.routes.upgrade()?.exit_via()?;
(selected == network).then_some(peer)
}
/// Where to hand a decrypted packet.
///
/// Always answers: with no interface to write to, the packets are
@@ -208,15 +218,15 @@ impl PluginContext {
sender: None,
local: None,
sink: None,
routes: Weak::new(),
}
}
/// A context configured with a custom packet sink.
pub fn with_sink(sink: Arc<dyn PacketSink>) -> Self {
Self {
sender: None,
local: None,
sink: Some(sink),
..Self::detached()
}
}
@@ -231,6 +241,7 @@ impl PluginContext {
sender: Some(sender),
local: Some(local),
sink,
..Self::detached()
}
}
+51 -1
View File
@@ -134,6 +134,8 @@ struct ForwardingTable {
#[derive(Debug)]
struct Plane {
network: NetworkId,
traffic: Arc<crate::traffic::TrafficMonitor>,
local: PeerId,
table: ArcSwap<ForwardingTable>,
tally: Arc<Tally>,
@@ -176,7 +178,15 @@ impl Plane {
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
return;
};
let len = frame.len();
if hop.send(envelope::decrement(frame)).is_ok() {
self.traffic.relay(
self.network,
header.source,
header.destination,
header.protocol,
len,
);
self.tally.forwarded.fetch_add(1, Ordering::Relaxed);
} else {
self.tally.dropped_no_link.fetch_add(1, Ordering::Relaxed);
@@ -208,6 +218,7 @@ struct State {
/// Transport kinds, best first. A neighbour with several links is
/// reached over the first of these it has.
priority: Vec<String>,
preferred: HashMap<PeerId, String>,
graph: HashMap<PeerId, Vec<PeerId>>,
members: HashSet<PeerId>,
raw: HashMap<PeerId, Vec<RawLink>>,
@@ -229,7 +240,14 @@ impl State {
.get(peer)
.map(|links| links.iter().collect())
.unwrap_or_default();
links.sort_by_key(|raw| (self.rank(&raw.kind), raw.kind.clone()));
let preferred = self.preferred.get(peer);
links.sort_by_key(|raw| {
(
preferred != Some(&raw.kind),
self.rank(&raw.kind),
&raw.kind,
)
});
links
}
@@ -316,16 +334,27 @@ pub struct RelayHub {
impl RelayHub {
/// Creates the router at this network's local endpoint.
pub fn new(network: NetworkId, local: EndpointId) -> Arc<Self> {
Self::with_monitor(network, local, Arc::default())
}
pub(crate) fn with_monitor(
network: NetworkId,
local: EndpointId,
traffic: Arc<crate::traffic::TrafficMonitor>,
) -> Arc<Self> {
let tally = Arc::new(Tally::default());
Arc::new(Self {
network,
state: Mutex::new(State {
plane: Arc::new(Plane {
network,
traffic,
local: *local.as_bytes(),
table: ArcSwap::from_pointee(ForwardingTable::default()),
tally: tally.clone(),
}),
priority: Vec::new(),
preferred: HashMap::new(),
graph: HashMap::new(),
members: HashSet::new(),
raw: HashMap::new(),
@@ -350,6 +379,23 @@ impl RelayHub {
}
}
/// Selects an already open carrier for this neighbour. The existing
/// immutable forwarding snapshot handles packet delivery and fallback.
pub(crate) fn prefer_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
let id = peer.as_bytes();
if state.preferred.get(id).map(String::as_str) != Some(kind)
&& state.raw.get(id).is_some_and(|links| {
links
.iter()
.any(|raw| raw.kind == kind && !raw.link.is_closed())
})
{
state.preferred.insert(*id, kind.to_owned());
state.publish();
}
}
/// Wakes the control loop promptly when a transport reader ends.
pub async fn changed(&self) {
self.changed.notified().await;
@@ -477,6 +523,9 @@ impl RelayHub {
/// Removes one physical link without tearing down end-to-end protocol state.
pub fn clear_direct(&self, peer: EndpointId, kind: &str) {
let mut state = self.state();
if state.preferred.get(peer.as_bytes()).map(String::as_str) == Some(kind) {
state.preferred.remove(peer.as_bytes());
}
let mut changed = false;
if let Some(links) = state.raw.get_mut(peer.as_bytes()) {
if let Some(position) = links.iter().position(|known| known.kind == kind) {
@@ -495,6 +544,7 @@ impl RelayHub {
/// Retires data channels without removing an authenticated peer's topology.
pub fn clear_peer_links(&self, peer: EndpointId) {
let mut state = self.state();
state.preferred.remove(peer.as_bytes());
if let Some(links) = state.raw.remove(peer.as_bytes()) {
for raw in links {
raw.link.close();
@@ -20,6 +20,32 @@ fn tag() -> u64 {
envelope::protocol_tag("ip")
}
#[tokio::test]
async fn measuring_an_alternative_preserves_the_active_link_until_promotion() {
let hub = RelayHub::new(network(), peer(1));
hub.set_priority(vec!["first".into(), "second".into()]);
let first = Wire::new(2, true);
let second = Wire::new(2, true);
hub.set_direct(peer(2), "second", second.clone());
hub.prefer_direct(peer(2), "second");
hub.set_direct(peer(2), "first", first.clone());
let logical = hub.link(peer(2), "ip");
logical.send(Bytes::from_static(b"while testing")).unwrap();
assert_eq!(second.take().len(), 1);
assert!(first.take().is_empty());
hub.prefer_direct(peer(2), "first");
logical
.send(Bytes::from_static(b"after switching"))
.unwrap();
assert_eq!(first.take().len(), 1);
first.dead.store(true, Ordering::Relaxed);
logical.send(Bytes::from_static(b"fallback")).unwrap();
assert_eq!(second.take().len(), 1);
hub.clear_direct(peer(2), "first");
hub.set_direct(peer(2), "first", Wire::new(2, true));
assert!(Arc::ptr_eq(&logical, &hub.link(peer(2), "ip")));
}
#[derive(Debug)]
struct Wire {
peer: EndpointId,
@@ -149,7 +175,10 @@ async fn ecmp_is_per_flow_direct_wins_and_existing_tunnel_survives_changes() {
#[tokio::test]
async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protocols() {
let hub = RelayHub::new(network(), peer(2));
use crate::traffic::{Flow, Role, TrafficMonitor};
let monitor = Arc::new(TrafficMonitor::default());
let window = monitor.subscribe().unwrap();
let hub = RelayHub::with_monitor(network(), peer(2), monitor);
let a = Wire::new(1, true);
let c = Wire::new(3, true);
hub.set_direct(peer(1), "ip", a.clone());
@@ -173,6 +202,20 @@ async fn transport_reader_forwards_without_any_plugin_reader_and_isolates_protoc
);
assert_eq!(&sent[0][RELAY_OVERHEAD..], b"end-to-end encrypted");
assert_eq!(hub.counters().forwarded, 1);
let observed = window.snapshot();
assert_eq!(observed.flows.len(), 1);
let row = &observed.flows[0];
assert_eq!(row.key.role, Role::Relay);
assert_eq!(row.key.peer, id(1).min(id(4)));
assert_eq!(
row.key.flow,
Flow::Relay {
other: id(1).max(id(4)),
wire_protocol: tag()
}
);
assert_eq!(row.tx_bytes + row.rx_bytes, sent[0].len() as u64);
assert_eq!(row.tx_packets + row.rx_packets, 1);
hub.close();
}
@@ -1,6 +1,6 @@
//! Authenticated probes of the actual data link, independent of control RTT.
//! Keys are negotiated privately for each physical link. No fixed wire magic.
use super::{PacketLink, SharedLink, TransportError};
use super::{LinkQuality, PacketLink, SharedLink, TransportError};
use crate::{BoxFuture, NetworkId};
use bytes::Bytes;
use hmac::{Hmac, KeyInit, Mac};
@@ -31,41 +31,80 @@ impl std::fmt::Debug for Settings {
}
}
struct Samples {
pending: VecDeque<(u64, Instant)>,
recent: VecDeque<bool>,
pending: VecDeque<(u64, Instant, usize)>,
recent: VecDeque<Option<Duration>>,
last_reply: Option<Instant>,
}
const PROBE_TIMEOUT: Duration = Duration::from_secs(3);
const WINDOW: usize = 20;
impl Samples {
fn new() -> Self {
Self {
pending: VecDeque::new(),
recent: VecDeque::new(),
last_reply: None,
}
}
fn sent(&mut self, seq: u64, now: Instant) {
self.pending.push_back((seq, now));
fn sent(&mut self, seq: u64, now: Instant, size: usize) {
self.pending.push_back((seq, now, size));
}
fn acknowledge(&mut self, seq: u64) {
if let Some(i) = self.pending.iter().position(|(n, _)| *n == seq) {
self.pending.remove(i);
self.recent.push_back(true);
fn record(&mut self, rtt: Option<Duration>) {
if self.recent.len() == WINDOW {
self.recent.pop_front();
}
self.recent.push_back(rtt);
}
fn acknowledge(&mut self, seq: u64, now: Instant, size: usize) -> bool {
if let Some(i) = self
.pending
.iter()
.position(|(n, _, expected)| *n == seq && *expected == size)
&& let Some((_, sent, _)) = self.pending.remove(i)
{
let rtt = now.saturating_duration_since(sent);
let success = rtt < PROBE_TIMEOUT;
self.record(success.then_some(rtt));
if success {
self.last_reply = Some(now);
}
return success;
}
false
}
fn expire(&mut self, now: Instant) {
while self
.pending
.front()
.is_some_and(|(_, at)| now.duration_since(*at) >= Duration::from_secs(3))
.is_some_and(|(_, at, _)| now.duration_since(*at) >= PROBE_TIMEOUT)
{
self.pending.pop_front();
self.recent.push_back(false);
}
while self.recent.len() > 20 {
self.recent.pop_front();
self.record(None);
}
}
fn degraded(&self) -> bool {
self.recent.len() >= 15
&& self.recent.iter().filter(|ok| !**ok).count() * 100 >= self.recent.len() * 60
&& self.recent.iter().filter(|rtt| rtt.is_none()).count() * 100
>= self.recent.len() * 60
}
fn quality(&self) -> Option<LinkQuality> {
let observed_at = self.last_reply?;
let mut delays = [Duration::ZERO; WINDOW];
let mut samples = 0;
for rtt in self.recent.iter().flatten() {
delays[samples] = *rtt;
samples += 1;
}
if samples == 0 {
return None;
}
delays[..samples].sort_unstable();
let rtt = (delays[(samples - 1) / 2] + delays[samples / 2]) / 2;
Some(LinkQuality {
rtt,
samples,
losses: self.recent.len() - samples,
observed_at,
})
}
}
/// A monitored physical link. It forwards application bytes unchanged.
@@ -75,6 +114,7 @@ pub(crate) struct HealthLink {
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
stop: watch::Sender<bool>,
reason: Mutex<Option<String>>,
quality: Mutex<Option<([u8; 16], LinkQuality)>>,
}
impl std::fmt::Debug for HealthLink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
@@ -99,6 +139,7 @@ impl HealthLink {
rx: tokio::sync::Mutex::new(rx),
stop,
reason: Mutex::new(None),
quality: Mutex::new(None),
});
let weak = Arc::downgrade(&link);
let mut stopped = link.stop.subscribe();
@@ -117,13 +158,14 @@ impl HealthLink {
let Some(link)=weak.upgrade()else{break;};let Some(settings)=lock(&link.settings).clone()else{continue;};
if marker != Some(settings.marker) { marker = Some(settings.marker); samples = Samples::new(); since = None; }
let start=*since.get_or_insert_with(Instant::now);let now=Instant::now();samples.expire(now);
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
if now.duration_since(start)>=Duration::from_secs(20) && samples.degraded() {
*lock(&link.reason)=Some("data delivery checks: at least 60% loss over the last 20 probes".into());break;
}
sequence=sequence.wrapping_add(1);
let size=raw.max_datagram_size();
let packet=probe(&settings,local,1,sequence,size.min(1000));
samples.sent(sequence,now);
samples.sent(sequence,now,packet.len());
let _=raw.send(packet);
}
packet=raw.recv()=>{
@@ -132,7 +174,12 @@ impl HealthLink {
if let Some(settings)=settings && packet.starts_with(&settings.marker) {
if let Some((kind,seq))=verify(&settings,raw.peer(),&packet) {
if kind==1 {let _=raw.send(probe(&settings,local,2,seq,packet.len()));}
else if kind==2 {samples.acknowledge(seq);}
else if kind==2 && marker == Some(settings.marker) {
if samples.acknowledge(seq, Instant::now(), packet.len()) {
raw.confirm_delivery();
}
*lock(&link.quality) = samples.quality().map(|q| (settings.marker, q));
}
}
} else {let _=tx.try_send(packet);}
}
@@ -149,6 +196,11 @@ impl HealthLink {
pub(crate) fn configure(&self, settings: Settings) {
*lock(&self.settings) = Some(settings);
}
pub(crate) fn profile_id(&self) -> Option<[u8; 16]> {
lock(&self.settings)
.as_ref()
.map(|settings| settings.marker)
}
}
fn probe(settings: &Settings, sender: EndpointId, kind: u8, seq: u64, size: usize) -> Bytes {
let mut bytes = vec![0; size.max(57)];
@@ -236,6 +288,15 @@ impl PacketLink for HealthLink {
.clone()
.or_else(|| self.raw.failure_reason())
}
fn quality(&self) -> Option<LinkQuality> {
if self.is_closed() {
return None;
}
let current = self.profile_id()?;
lock(&self.quality)
.filter(|(profile, quality)| *profile == current && quality.is_fresh(Instant::now()))
.map(|(_, quality)| quality)
}
fn path_description(&self) -> String {
self.raw.path_description()
}
@@ -251,22 +312,61 @@ impl Drop for HealthLink {
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn an_authenticated_short_reply_does_not_prove_full_size_delivery() {
let start = Instant::now();
let mut samples = Samples::new();
samples.sent(7, start, 1000);
assert!(!samples.acknowledge(7, start, 57));
assert!(samples.quality().is_none());
assert!(samples.acknowledge(7, start, 1000));
}
#[test]
fn quality_uses_matched_fresh_replies_and_keeps_losses_in_the_window() {
let mut samples = Samples::new();
let start = Instant::now();
assert!(samples.quality().is_none());
for (seq, delay) in [(1, 10), (2, 30), (3, 250)] {
samples.sent(seq, start, 1000);
samples.acknowledge(seq, start + Duration::from_millis(delay), 1000);
}
assert!(!samples.acknowledge(1, start + Duration::from_secs(1), 1000));
samples.sent(4, start, 1000);
samples.expire(start + Duration::from_secs(3));
assert!(!samples.acknowledge(4, start + Duration::from_secs(4), 1000));
let measured = samples.quality().unwrap();
assert_eq!(measured.rtt, Duration::from_millis(30));
assert_eq!((measured.samples, measured.losses), (3, 1));
assert!(measured.is_fresh(start + Duration::from_secs(4)));
assert!(!measured.is_fresh(start + Duration::from_secs(6)));
for seq in 5..25 {
let sent = start + Duration::from_secs(seq);
samples.sent(seq, sent, 1000);
samples.acknowledge(seq, sent + Duration::from_millis(80), 1000);
}
let recovered = samples.quality().unwrap();
assert_eq!(recovered.rtt, Duration::from_millis(80));
assert_eq!((recovered.samples, recovered.losses), (20, 0));
}
#[test]
fn no_false_failure_before_window_but_persistent_loss_is_detected() {
let mut samples = Samples::new();
let now = Instant::now();
for seq in 0..20 {
samples.sent(seq, now);
samples.sent(seq, now, 1000);
if seq % 5 == 0 {
samples.acknowledge(seq);
samples.acknowledge(seq, now, 1000);
}
}
assert!(!samples.degraded());
samples.expire(now + Duration::from_secs(4));
assert!(samples.degraded());
for seq in 20..40 {
samples.sent(seq, now);
samples.acknowledge(seq);
samples.sent(seq, now, 1000);
samples.acknowledge(seq, now, 1000);
}
samples.expire(now + Duration::from_secs(4));
assert!(!samples.degraded());
@@ -37,6 +37,7 @@ pub mod carrier;
pub use carrier::{DataCarrier, SharedCarrier};
use std::sync::Arc;
use std::time::{Duration, Instant};
use bytes::Bytes;
use iroh::EndpointId;
@@ -73,6 +74,25 @@ pub enum TransportError {
Other(String),
}
/// Recent observations from authenticated round trips over a physical data link.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LinkQuality {
/// Median round-trip time of successful probes in the window.
pub rtt: Duration,
/// Successful probes in the window.
pub samples: usize,
/// Timed-out probes in the same window.
pub losses: usize,
/// Receipt time of the latest successful probe.
pub observed_at: Instant,
}
impl LinkQuality {
pub(crate) fn is_fresh(&self, now: Instant) -> bool {
now.saturating_duration_since(self.observed_at) <= Duration::from_secs(5)
}
}
/// An authenticated datagram channel to one peer, for one plugin protocol.
///
/// Dropping the link closes it.
@@ -125,6 +145,15 @@ pub trait PacketLink: Send + Sync + std::fmt::Debug + 'static {
None
}
/// Fresh measurements from this physical link's own authenticated probes.
fn quality(&self) -> Option<LinkQuality> {
None
}
/// The link monitor received a timely, authenticated answer to a data probe
/// on this very link. A carrier can use it in place of its own idle probe.
fn confirm_delivery(&self) {}
/// A short description of the path in use, for diagnostics.
///
/// Reports what the transport actually knows. It must not invent a value.
+6
View File
@@ -15,6 +15,12 @@ pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// The local traffic monitor could not start or poll its subscription.
#[error("{0}")]
TrafficMonitor(String),
/// A requested mesh throughput test cannot run.
#[error("{0}")]
SpeedTest(String),
/// A node-history cleanup is unsafe, stale or cannot be performed.
#[error("cannot forget node: {0}")]
ForgetNode(String),
+174
View File
@@ -0,0 +1,174 @@
//! Exit offers may need the local user's approval. The dialog belongs to the
//! initiating client, outside the daemon's IPC deadline and network actors.
use super::{EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, exchange};
use crate::state::Ipv4Range;
use serde::{Deserialize, Serialize};
/// Result of applying the local exit settings on the host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ExitOfferOutcome {
/// Current setting after applying the requested change.
Set(bool),
/// macOS denied the host operation for this local overlay range.
NeedsAuthorization {
/// Locally selected overlay range.
range: Ipv4Range,
/// Owner of the running agent.
agent_uid: u32,
},
}
/// Offers the running agent as an exit in one network, or withdraws it.
pub async fn set_exit_offer(
path: impl AsRef<Path>,
network_id: &str,
enabled: bool,
) -> Result<bool> {
#[cfg(target_os = "macos")]
let authorize = |path: &Path, range, uid| {
use std::os::unix::fs::{FileTypeExt, MetadataExt};
let socket = std::fs::symlink_metadata(path).map_err(|e| e.to_string())?;
if !socket.file_type().is_socket() || uid == 0 || socket.uid() != uid {
return Err("The local control socket does not belong to the account requesting exit authorization".into());
}
crate::overlay::hostrules::authorize_macos_exit(range, uid)
};
#[cfg(not(target_os = "macos"))]
let authorize =
|_: &Path, _, _| Err("macOS exit authorization is unavailable on this platform".into());
apply(path.as_ref(), network_id, enabled, authorize).await
}
async fn apply(
path: &Path,
id: &str,
enabled: bool,
authorize: impl FnOnce(&Path, Ipv4Range, u32) -> std::result::Result<(), String> + Send + 'static,
) -> Result<bool> {
let request = |choice| Request::SetExitOffer {
network_id: id.to_owned(),
enabled: choice,
};
let decode = |answer| match answer {
Response::ExitOffer(outcome) => Ok(outcome),
Response::Error(message) => Err(Error::Storage(message)),
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
};
let result = decode(exchange(path, &request(Some(enabled)), EXCHANGE_TIMEOUT).await?)?;
match result {
ExitOfferOutcome::Set(on) => Ok(on),
ExitOfferOutcome::NeedsAuthorization { range, agent_uid } if enabled => {
let path_owned = path.to_owned();
tokio::task::spawn_blocking(move || authorize(&path_owned, range, agent_uid))
.await
.map_err(|err| {
Error::Storage(format!("could not finish macOS authorization: {err}"))
})?
.map_err(Error::Storage)?;
// Reconcile the current settings. A different client may have withdrawn
// its offer while the system was waiting for the user to respond.
match decode(exchange(path, &request(None), EXCHANGE_TIMEOUT).await?)? {
ExitOfferOutcome::Set(on) => Ok(on),
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
"macOS still denies the exit settings after authorization".into(),
)),
}
}
ExitOfferOutcome::NeedsAuthorization { .. } => Err(Error::Storage(
"unexpected authorization request while withdrawing an exit".into(),
)),
}
}
#[cfg(all(test, unix))]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::ipc::{ControlSocket, ControlSocketAccess, ReportSource, StatusReport};
use std::{
collections::VecDeque,
sync::{
Arc, Mutex,
atomic::{AtomicUsize, Ordering},
},
};
struct Source {
calls: Mutex<Vec<Option<bool>>>,
answers: Mutex<VecDeque<ExitOfferOutcome>>,
}
impl ReportSource for Source {
fn report(&self) -> crate::BoxFuture<'_, StatusReport> {
Box::pin(async { StatusReport::default() })
}
fn set_exit_offer(
&self,
id: String,
change: Option<bool>,
) -> crate::BoxFuture<'_, std::result::Result<ExitOfferOutcome, String>> {
assert_eq!(id, "lab");
self.calls.lock().unwrap().push(change);
let answer = self
.answers
.lock()
.unwrap()
.pop_front()
.ok_or("unexpected reapply".to_owned());
Box::pin(async move { answer })
}
}
#[tokio::test]
async fn prompt_only_on_denial_and_retry_the_current_plan_once() {
let subnet: Ipv4Range = "10.2.3.0/24".parse().unwrap();
let need = ExitOfferOutcome::NeedsAuthorization {
range: subnet,
agent_uid: 501,
};
let on = ExitOfferOutcome::Set(true);
let off = ExitOfferOutcome::Set(false);
for (answers, enabled, grant, prompts, result) in [
(vec![on], true, true, 0, Some(true)),
(vec![off], false, true, 0, Some(false)),
(vec![need, on], true, true, 1, Some(true)),
(vec![need, off], true, true, 1, Some(false)),
(vec![need, need], true, true, 1, None),
(vec![need], true, false, 1, None),
(vec![need], false, true, 0, None),
] {
let requests = answers.len();
let source = Arc::new(Source {
calls: Default::default(),
answers: Mutex::new(answers.into()),
});
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("agent.sock");
let server = ControlSocket::bind(&path, source.clone(), ControlSocketAccess::Private)
.await
.unwrap();
let approvals = Arc::new(AtomicUsize::new(0));
let seen = approvals.clone();
let actual = apply(&path, "lab", enabled, move |_, range, uid| {
seen.fetch_add(1, Ordering::Relaxed);
assert_eq!((range, uid), (subnet, 501));
if grant {
Ok(())
} else {
Err("cancelled".into())
}
})
.await;
assert_eq!(actual.ok(), result);
assert_eq!(approvals.load(Ordering::Relaxed), prompts);
let expected = if requests == 1 {
vec![Some(enabled)]
} else {
vec![Some(enabled), None]
};
assert_eq!(*source.calls.lock().unwrap(), expected);
server.shutdown().await;
}
}
}
+154 -29
View File
@@ -25,6 +25,13 @@
//! rather than the crate's internal structures, so internal refactors do not
//! silently change what a client sees.
mod exit_offer;
pub use exit_offer::{ExitOfferOutcome, set_exit_offer};
mod traffic;
pub use traffic::TrafficStream;
mod speed;
pub use speed::{SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate, SpeedReport};
#[cfg(unix)]
pub mod unix;
#[cfg(windows)]
@@ -171,6 +178,8 @@ pub fn default_control_socket_path() -> PathBuf {
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Request {
/// Open a dedicated, window-scoped local monitor connection.
WatchTraffic,
/// Save a complete version-checked service draft or its deletion.
SaveVip {
/// Exact network id.
@@ -266,8 +275,8 @@ pub enum Request {
SetExitOffer {
/// Public network identifier.
network_id: String,
/// Whether members may send their internet traffic through this agent.
enabled: bool,
/// Set the desired offer, or reconcile its current value after authorization.
enabled: Option<bool>,
},
/// Send all this device's internet traffic through a member of one
/// network, or back the ordinary way.
@@ -277,6 +286,20 @@ pub enum Request {
/// The member's endpoint id, or `None` to stop using an exit node.
peer: Option<String>,
},
/// Begin a peer test or a sequential batch of advertised exits.
StartSpeedTest {
/// Active network identifier.
network_id: String,
/// One peer, or all online exits when absent.
peer: Option<String>,
/// Apply the smaller metered-link byte budget.
metered: bool,
},
/// Cancel the active local test or batch in this network.
StopSpeedTest {
/// Active network identifier.
network_id: String,
},
}
impl std::fmt::Debug for Request {
@@ -300,6 +323,16 @@ impl std::fmt::Debug for Request {
f,
"SetProtocols {{ {network_id}, protocols: {protocols:?} }}"
),
Request::StartSpeedTest {
network_id,
peer,
metered,
} => write!(
f,
"StartSpeedTest {{ {network_id}, peer: {peer:?}, metered: {metered} }}"
),
Request::StopSpeedTest { network_id } => write!(f, "StopSpeedTest({network_id})"),
Request::WatchTraffic => f.write_str("WatchTraffic"),
Request::Status => f.write_str("Status"),
Request::SetBroadcast {
network_id,
@@ -319,7 +352,7 @@ impl std::fmt::Debug for Request {
Request::SetExitOffer {
network_id,
enabled,
} => write!(f, "SetExitOffer {{ {network_id}, enabled: {enabled} }}"),
} => write!(f, "SetExitOffer {{ {network_id}, enabled: {enabled:?} }}"),
Request::SetExitNode { network_id, peer } => {
write!(f, "SetExitNode {{ {network_id}, peer: {peer:?} }}")
}
@@ -331,6 +364,10 @@ impl std::fmt::Debug for Request {
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum Response {
/// The connection now accepts interval polls.
TrafficReady,
/// A speed-test action was accepted.
SpeedTestAccepted,
/// Accepted configuration with fresh local routing observations.
Vips(Vec<crate::vip::VipStatus>),
/// An observed offline claim was durably retired.
@@ -356,7 +393,7 @@ pub enum Response {
/// A network's shared secret, redacted in `Debug`.
Secret(RedactedText),
/// Whether this agent now offers itself as an exit node.
ExitOffer(bool),
ExitOffer(ExitOfferOutcome),
/// The member this device now sends its internet traffic through.
ExitNode(Option<String>),
/// The request could not be served.
@@ -614,6 +651,8 @@ pub struct LeftReport {
/// Everything the agent is doing, in one snapshot.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct StatusReport {
/// Last error applying the shared overlay interface's host addresses and routes.
pub overlay_config_error: Option<String>,
/// Data-plane protocols this agent can enable at runtime.
pub available_protocols: Vec<ProtocolReport>,
/// This device's persistent endpoint id.
@@ -709,6 +748,9 @@ pub struct ProtocolReport {
/// One network.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkReport {
/// Current capabilities and results of peer speed tests.
#[serde(default)]
pub speed: SpeedReport,
/// Shared VIPs and this client's routing observations.
#[serde(default)]
pub vips: Vec<crate::vip::VipStatus>,
@@ -828,6 +870,11 @@ pub struct MemberReport {
/// One control plane peer.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct PeerReport {
/// The connected member has selected this gateway, or recently sent exit traffic on a legacy session.
#[serde(default)]
pub uses_our_exit: bool,
/// The software version reported by this authenticated peer, when available.
pub agent_version: Option<String>,
/// Actionable carrier failure or policy mismatch; absent for a usable route.
pub data_error: Option<String>,
/// The peer's endpoint id.
@@ -837,8 +884,12 @@ pub struct PeerReport {
/// How the connection reaches the peer: `direct`, `relay` or `unknown`,
/// as the transport reports it.
pub transport: String,
/// Round-trip time in milliseconds, when a path is selected.
/// Round-trip time of the control connection in milliseconds.
pub rtt_ms: Option<u64>,
/// Fresh median RTT of the selected direct data link, in milliseconds.
pub data_rtt_ms: Option<u64>,
/// Underlying path reported by the selected direct data carrier.
pub data_transport_detail: Option<String>,
/// The peer offers itself as an exit node in this network.
pub exit_node: bool,
/// How packets reach it.
@@ -887,6 +938,8 @@ pub struct RuleSetReport {
/// One network's exit-node settings and what they are doing.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct ExitReport {
/// IP bytes carried through this exit since selection, when locally observed.
pub traffic: Option<crate::overlay::exit::ExitTraffic>,
/// This agent offers itself as an exit node in this network.
pub offering: bool,
/// Masquerading and forwarding rules for members' traffic, when offering.
@@ -930,10 +983,12 @@ pub struct OverlayPeerReport {
pub public_key: String,
/// The overlay address the network agreed it holds.
pub address: Option<String>,
/// Seconds since the last WireGuard handshake.
///
/// `None` means the tunnel has never handshaken and cannot carry traffic.
/// Seconds since the last WireGuard handshake while its session key is usable.
pub handshake_secs_ago: Option<u64>,
/// An established tunnel has no recent or pending IP traffic. An expired
/// key on a tunnel required to stay warm is reported as waiting instead.
#[serde(default)]
pub idle: bool,
/// Packets encrypted and sent to this peer.
pub tx_packets: u64,
/// Packets decrypted from this peer.
@@ -979,6 +1034,12 @@ impl OverlayPeerReport {
/// running and what they can report or change. That is what keeps this module
/// free of any knowledge of them.
pub trait ReportSource: Send + Sync + 'static {
/// Start a new independent interval subscription, when supported by the source.
fn subscribe_traffic(
&self,
) -> std::result::Result<crate::traffic::TrafficSubscription, String> {
Err("Traffic monitoring is unavailable".into())
}
/// Atomically saves a complete VIP draft using its original revision.
fn save_vip(
&self,
@@ -1051,6 +1112,24 @@ pub trait ReportSource: Send + Sync + 'static {
Box::pin(async move { Err("this agent cannot change broadcast participation".into()) })
}
/// Queues a diagnostic against one peer, or all current exit peers.
fn start_speed_test(
&self,
_network_id: String,
_peer: Option<String>,
_metered: bool,
) -> BoxFuture<'_, std::result::Result<(), String>> {
Box::pin(async { Err("this agent cannot test peer speeds".into()) })
}
/// Cancels an individual test and any remaining batch members.
fn stop_speed_test(
&self,
_network_id: String,
) -> BoxFuture<'_, std::result::Result<(), String>> {
Box::pin(async { Err("this agent cannot stop speed tests".into()) })
}
/// Stops serving a network, or starts serving it again.
///
/// Defaulted to a refusal, like the others.
@@ -1090,8 +1169,8 @@ pub trait ReportSource: Send + Sync + 'static {
fn set_exit_offer(
&self,
_network_id: String,
_enabled: bool,
) -> BoxFuture<'_, std::result::Result<bool, String>> {
_enabled: Option<bool>,
) -> BoxFuture<'_, std::result::Result<ExitOfferOutcome, String>> {
Box::pin(async move { Err("this agent cannot be an exit node".to_string()) })
}
@@ -1135,13 +1214,17 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
///
/// Bump it whenever [`Request`], [`Response`] or anything they contain
/// changes shape.
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 23]);
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 29]);
/// Reads one request off an accepted stream, answers it, writes the response.
///
/// The per-platform adapters call this for every connection they accept, so
/// the request handling is identical on every transport.
pub(crate) async fn serve_connection<S>(mut stream: S, source: Arc<dyn ReportSource>) -> Result<()>
pub(crate) async fn serve_connection<S>(
mut stream: S,
source: Arc<dyn ReportSource>,
mut stopped: tokio::sync::watch::Receiver<()>,
) -> Result<()>
where
S: AsyncRead + AsyncWrite + Unpin,
{
@@ -1159,6 +1242,16 @@ where
}
};
let response = match request {
Request::WatchTraffic => match source.subscribe_traffic() {
Ok(sub) => {
drop(source);
return tokio::select! {
_ = stopped.changed() => Ok(()),
result = traffic::serve(stream,sub) => result,
};
}
Err(reason) => Response::Error(reason),
},
Request::SaveVip {
network_id,
config,
@@ -1221,6 +1314,18 @@ where
Ok(secret) => Response::Secret(RedactedText::new(secret)),
Err(reason) => Response::Error(reason),
},
Request::StartSpeedTest {
network_id,
peer,
metered,
} => match source.start_speed_test(network_id, peer, metered).await {
Ok(()) => Response::SpeedTestAccepted,
Err(reason) => Response::Error(reason),
},
Request::StopSpeedTest { network_id } => match source.stop_speed_test(network_id).await {
Ok(()) => Response::SpeedTestAccepted,
Err(reason) => Response::Error(reason),
},
Request::SetExitOffer {
network_id,
enabled,
@@ -1405,23 +1510,6 @@ pub async fn set_dns(
}
}
/// Offers the running agent as an exit node in one network, or stops.
pub async fn set_exit_offer(
path: impl AsRef<Path>,
network_id: &str,
enabled: bool,
) -> Result<bool> {
let request = Request::SetExitOffer {
network_id: network_id.to_owned(),
enabled,
};
match exchange(path.as_ref(), &request, EXCHANGE_TIMEOUT).await? {
Response::ExitOffer(enabled) => Ok(enabled),
Response::Error(message) => Err(Error::Storage(message)),
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
}
}
/// Sends the running agent's internet traffic through a member of one
/// network, or back the ordinary way with `None`.
pub async fn set_exit_node(
@@ -1440,6 +1528,43 @@ pub async fn set_exit_node(
}
}
/// Measures the mesh data path to one peer, or queues the network's online exit nodes.
pub async fn start_speed_test(
path: impl AsRef<Path>,
network_id: &str,
peer: Option<&str>,
metered: bool,
) -> Result<()> {
speed_request(
path.as_ref(),
Request::StartSpeedTest {
network_id: network_id.to_owned(),
peer: peer.map(str::to_owned),
metered,
},
)
.await
}
/// Stops the current local speed test and clears its remaining queue.
pub async fn stop_speed_test(path: impl AsRef<Path>, network_id: &str) -> Result<()> {
speed_request(
path.as_ref(),
Request::StopSpeedTest {
network_id: network_id.to_owned(),
},
)
.await
}
async fn speed_request(path: &Path, request: Request) -> Result<()> {
match exchange(path, &request, EXCHANGE_TIMEOUT).await? {
Response::SpeedTestAccepted => Ok(()),
Response::Error(reason) => Err(Error::SpeedTest(reason)),
other => Err(Error::Storage(format!("unexpected answer: {other:?}"))),
}
}
/// Asks a running agent for a configured network's shared secret, in its
/// `tsn1…` text form, so a local client can copy it. The secret is never
/// logged by this path.
+72
View File
@@ -0,0 +1,72 @@
//! Local presentation of receiver-measured peer throughput.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
/// Tests last requested on this device, scoped to one network.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedReport {
/// Progress of the current sequential exit-node test.
pub batch: Option<SpeedBatchReport>,
/// Per-peer progress or the last local result, keyed by endpoint ID.
pub peers: BTreeMap<String, SpeedPeerReport>,
/// Currently connected peers advertising the same diagnostic wire version.
pub capable: Vec<String>,
}
/// Progress of an exit-node batch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedBatchReport {
/// Number of peers that have finished, including failures.
pub done: u32,
/// Number selected when the batch started.
pub total: u32,
}
/// A receiver-confirmed rate in decimal bits per second.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedRate {
/// Measured bits per second.
pub bps: u64,
/// The test reached its budget before establishing a throughput ceiling.
pub lower_bound: bool,
}
/// Locally observed phase of one diagnostic.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum SpeedPhase {
/// Waiting behind another exit in the same batch.
#[default]
Queued,
/// Negotiating over the authenticated control session.
Preparing,
/// Receiving test data.
Download,
/// Sending test data.
Upload,
/// Measurement is complete.
Done,
/// The test could not produce a result, with an explanation for the user.
Failed(String),
/// The test was stopped.
Cancelled,
}
/// A single live or completed diagnostic on this device.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct SpeedPeerReport {
/// Current or terminal phase.
pub phase: SpeedPhase,
/// Download rate from the remote peer.
pub down: Option<SpeedRate>,
/// Upload rate to the remote peer.
pub up: Option<SpeedRate>,
/// Time since the individual test began.
pub elapsed_ms: u32,
/// Unique payload bytes received across both directions.
pub bytes: u64,
/// Wall-clock time of the most recent update, for display only.
pub measured_at_unix_secs: u64,
/// Data path at the start of the measurement, when known.
pub path: Option<String>,
}
+73
View File
@@ -0,0 +1,73 @@
//! A dedicated local connection is the lifetime of one traffic window.
use super::{
EXCHANGE_TIMEOUT, Error, Path, Request, Response, Result, read_message, transport,
write_message,
};
use crate::traffic::{TrafficSnapshot, TrafficSubscription};
use std::{future::Future, time::Duration};
use tokio::io::{AsyncRead, AsyncWrite};
#[cfg(unix)]
type Socket = tokio::net::UnixStream;
#[cfg(windows)]
type Socket = tokio::net::windows::named_pipe::NamedPipeClient;
async fn bounded<T>(duration: Duration, f: impl Future<Output = Result<T>>) -> Result<T> {
tokio::time::timeout(duration, f)
.await
.map_err(|_| Error::Timeout {
what: "local traffic monitor".into(),
})?
}
/// A local monitor stream. Dropping it releases the agent's interval buffer.
pub struct TrafficStream(Socket);
impl TrafficStream {
/// Starts observing now, independently of any other open window.
pub async fn open(path: &Path) -> Result<Self> {
bounded(EXCHANGE_TIMEOUT, async {
let mut socket = transport::connect(path).await?;
write_message(&mut socket, &Request::WatchTraffic).await?;
match read_message(&mut socket).await? {
Response::TrafficReady => Ok(Self(socket)),
Response::Error(reason) => Err(Error::TrafficMonitor(reason)),
_ => Err(Error::TrafficMonitor(
"Unexpected answer opening traffic monitor".into(),
)),
}
})
.await
}
/// Drains only this reader's interval.
pub async fn snapshot(&mut self) -> Result<TrafficSnapshot> {
bounded(EXCHANGE_TIMEOUT, async {
write_message(&mut self.0, &0u8).await?;
read_message(&mut self.0).await
})
.await
}
}
pub(super) async fn serve<S: AsyncRead + AsyncWrite + Unpin>(
mut socket: S,
sub: TrafficSubscription,
) -> Result<()> {
bounded(
EXCHANGE_TIMEOUT,
write_message(&mut socket, &Response::TrafficReady),
)
.await?;
loop {
// A wedged or suspended client cannot keep the collector running indefinitely.
let token: u8 = bounded(Duration::from_secs(15), read_message(&mut socket)).await?;
if token != 0 {
return Err(Error::TrafficMonitor("Invalid monitor poll".into()));
}
bounded(
EXCHANGE_TIMEOUT,
write_message(&mut socket, &sub.snapshot()),
)
.await?;
}
}
+3 -1
View File
@@ -148,13 +148,15 @@ fn set_mode(path: &Path, mode: u32) -> Result<()> {
}
async fn serve(listener: UnixListener, source: Arc<dyn ReportSource>) {
let (_lifetime, stopped) = tokio::sync::watch::channel(());
loop {
let Ok((stream, _)) = listener.accept().await else {
continue;
};
let source = Arc::clone(&source);
let stopped = stopped.clone();
tokio::spawn(async move {
if let Err(err) = super::serve_connection(stream, source).await {
if let Err(err) = super::serve_connection(stream, source, stopped).await {
tracing::debug!(%err, "local control request failed");
}
});
+10 -5
View File
@@ -217,6 +217,7 @@ async fn serve(
first: tokio::net::windows::named_pipe::NamedPipeServer,
source: Arc<dyn ReportSource>,
) {
let (_lifetime, stopped) = tokio::sync::watch::channel(());
let mut server = first;
loop {
if server.connect().await.is_err() {
@@ -235,15 +236,17 @@ async fn serve(
// Nothing left to accept the next client on, but the one in
// hand is still answered before the loop ends.
let source = Arc::clone(&source);
let stopped = stopped.clone();
tokio::spawn(async move {
let _ = super::serve_connection(connected, source).await;
let _ = super::serve_connection(connected, source, stopped).await;
});
return;
}
}
let source = Arc::clone(&source);
let stopped = stopped.clone();
tokio::spawn(async move {
if let Err(err) = super::serve_connection(connected, source).await {
if let Err(err) = super::serve_connection(connected, source, stopped).await {
tracing::debug!(%err, "local control request failed");
}
});
@@ -364,7 +367,9 @@ mod tests {
});
assert!(!is_serving(&path).await, "nothing serves the pipe yet");
let control = ControlSocket::bind(&path, source).await.unwrap();
let control = ControlSocket::bind(&path, source, ControlSocketAccess::Private)
.await
.unwrap();
assert!(is_serving(&path).await, "the agent serves it now");
let answer = exchange(&path, &Request::Status, EXCHANGE_TIMEOUT)
@@ -439,10 +444,10 @@ mod tests {
Box::pin(async { StatusReport::default() })
});
let first = ControlSocket::bind(&path, Arc::clone(&source))
let first = ControlSocket::bind(&path, Arc::clone(&source), ControlSocketAccess::Private)
.await
.unwrap();
let second = ControlSocket::bind(&path, source).await;
let second = ControlSocket::bind(&path, source, ControlSocketAccess::Private).await;
assert!(
matches!(second, Err(Error::StateLocked { .. })),
"{second:?}"
+1
View File
@@ -51,6 +51,7 @@ pub mod storage;
pub mod task;
#[cfg(feature = "testing")]
pub mod testing;
pub mod traffic;
pub mod vip;
pub use agent::{Agent, AgentStatus, Event, NetworkStatus, PeerStatus};
+113 -11
View File
@@ -222,16 +222,13 @@ fn local_addr_string(addr: &iroh::endpoint::LocalTransportAddr) -> Option<String
#[derive(Debug, Clone)]
pub struct EndpointAdapter {
endpoint: Endpoint,
owned_interface: Arc<std::sync::RwLock<String>>,
owned_interface: Arc<std::sync::OnceLock<String>>,
}
impl EndpointAdapter {
/// Excludes the real name after interface creation (macOS assigns utunN).
pub(crate) fn exclude_interface(&self, name: &str) {
*self
.owned_interface
.write()
.unwrap_or_else(|p| p.into_inner()) = name.to_lowercase();
let _ = self.owned_interface.set(name.to_owned());
}
/// Binds an endpoint according to `config`, reusing the persistent device key.
@@ -250,16 +247,40 @@ impl EndpointAdapter {
TransportPolicy::N0Defaults => builder.preset(presets::N0),
};
let owned_interface =
Arc::new(std::sync::RwLock::new(config.interface_name.to_lowercase()));
let owned_interface = Arc::new(std::sync::OnceLock::<String>::new());
{
let monitor_interface = Arc::clone(&owned_interface);
#[cfg(windows)]
let adapter_id = std::sync::OnceLock::<String>::new();
builder = builder.network_change_filter(move |previous, current| {
let Some(name) = monitor_interface.get() else {
return true;
};
// Wintun gives us its friendly name. netwatch keys Windows
// interfaces by GUID. Enumeration can lag adapter creation,
// so cache a successful lookup and retry a miss on later events.
#[cfg(windows)]
let Some(name) = adapter_id.get().or_else(|| {
let id = netdev::get_interfaces()
.into_iter()
.find(|iface| {
iface
.friendly_name
.as_deref()
.is_some_and(|alias| alias.eq_ignore_ascii_case(name))
})?
.name;
Some(adapter_id.get_or_init(|| id))
}) else {
return true;
};
!only_owned_interface_changed(previous, current, name)
});
let interface_filter = Arc::clone(&owned_interface);
let requested = config.interface_name.clone();
let factory = config.tun_factory.clone();
let filter = iroh::address_lookup::AddrFilter::new(move |addrs| {
let owned_interface = interface_filter
.read()
.unwrap_or_else(|p| p.into_inner())
.clone();
let owned_interface = interface_filter.get().unwrap_or(&requested).to_lowercase();
let mut overlay_ips = std::collections::HashSet::new();
if let Some(factory) = &factory {
overlay_ips.extend(factory.assigned_addresses());
@@ -493,3 +514,84 @@ impl EndpointAdapter {
self.endpoint.close().await;
}
}
/// netwatch treats every new unicast prefix as a link change. A second overlay
/// prefix on the same TUN cannot affect the paths carrying those tunnels.
pub(crate) fn only_owned_interface_changed(
previous: &netwatch::netmon::State,
current: &netwatch::netmon::State,
name: &str,
) -> bool {
if previous.default_route_interface != current.default_route_interface
|| current.default_route_interface.as_deref() == Some(name)
|| previous.last_unsuspend != current.last_unsuspend
|| previous.is_expensive != current.is_expensive
{
return false;
}
// Interface equality in netwatch covers identity and flags. Compare
// addresses separately, including family, prefix and IPv6 address flags.
let same_interface = |a: &netwatch::interfaces::Interface,
b: &netwatch::interfaces::Interface| {
a == b && a.addrs().eq(b.addrs())
};
let old_tun = previous.interfaces.get(name);
let new_tun = current.interfaces.get(name);
match (old_tun, new_tun) {
(None, None) => return false,
(Some(a), Some(b)) if same_interface(a, b) => return false,
_ => {}
}
// have_v4, have_v6 and local_addresses are derived from these interfaces
// and can all change when only the TUN changes.
let old_count = previous.interfaces.len() - usize::from(old_tun.is_some());
let new_count = current.interfaces.len() - usize::from(new_tun.is_some());
old_count == new_count
&& previous.interfaces.iter().all(|(iface, old)| {
iface == name
|| current
.interfaces
.get(iface)
.is_some_and(|new| same_interface(old, new))
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use netwatch::netmon::State;
#[test]
fn tun_address_changes_leave_existing_underlay_connections_alone() {
let before = State::fake();
let mut after = before.clone();
// netwatch keys interfaces by their OS name. Its fixture provides a
// unicast address, precisely the kind of change it classifies as major.
let tun = State::fake().interfaces.remove("wifi0").unwrap();
let address = tun.addrs().next().unwrap().addr();
after.interfaces.insert("utun7".into(), tun);
after.local_addresses.regular.push(address);
assert!(after.is_major_change(&before));
assert!(only_owned_interface_changed(&before, &after, "utun7"));
assert!(only_owned_interface_changed(&after, &before, "utun7"));
assert!(!only_owned_interface_changed(&before, &after, "utun6"));
// An update to the real underlay can arrive in the same notification.
let mut lost_wifi = after.clone();
lost_wifi.interfaces.remove("wifi0");
assert!(!only_owned_interface_changed(&before, &lost_wifi, "utun7"));
let mut changed_route = after.clone();
changed_route.default_route_interface = Some("utun7".to_owned());
assert!(!only_owned_interface_changed(
&before,
&changed_route,
"utun7"
));
let mut resumed = after;
resumed.last_unsuspend = Some(std::time::Instant::now().into());
assert!(!only_owned_interface_changed(&before, &resumed, "utun7"));
}
}
+377
View File
@@ -0,0 +1,377 @@
//! On Windows and on Macs without a host utun, an exit terminates forwarded connections on physical
//! sockets. This keeps them out of the destination-only routes used by local
//! applications. The stack and its sockets live for the offer, independently
//! of this device's upstream selection.
use super::router::Route;
use crate::identity::NetworkId;
use crate::vip::{
Protocol,
packet::{self, Tuple},
};
use bytes::Bytes;
use smoltcp::wire::{IpAddress, TcpPacket, UdpPacket};
use std::{
collections::HashMap,
io,
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
sync::Arc,
time::Duration,
};
use tokio::{
net::{TcpSocket, UdpSocket},
sync::{mpsc, watch},
task::{JoinHandle, JoinSet},
};
#[cfg(target_os = "macos")]
pub(super) mod macos;
mod tcp;
#[cfg(test)]
mod tests;
#[cfg(windows)]
mod windows;
use crate::config::{EXIT_FORWARD_FLOWS, EXIT_FORWARD_FRAGMENTS, EXIT_FORWARD_QUEUE};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) struct Physical {
pub index: u32,
pub address: Ipv4Addr,
}
impl Physical {
async fn tcp(self, remote: SocketAddr) -> io::Result<tokio::net::TcpStream> {
let socket = TcpSocket::new_v4()?;
#[cfg(windows)]
windows::pin(&socket, self.index)?;
#[cfg(target_os = "macos")]
self.pin(&socket2::SockRef::from(&socket))?;
socket.bind((self.address, 0).into())?;
socket.connect(remote).await
}
#[cfg(target_os = "macos")]
fn pin(self, socket: &socket2::Socket) -> io::Result<()> {
let index = std::num::NonZeroU32::new(self.index)
.ok_or_else(|| io::Error::other("no physical exit interface"))?;
socket.bind_device_by_index_v4(Some(index))
}
fn datagram(self, protocol: socket2::Protocol) -> io::Result<UdpSocket> {
use socket2::{Domain, Protocol, Socket, Type};
let ty = if protocol == Protocol::UDP || cfg!(target_os = "macos") {
Type::DGRAM
} else {
Type::RAW
};
let socket = Socket::new(Domain::IPV4, ty, Some(protocol))?;
#[cfg(windows)]
windows::pin(&socket, self.index)?;
#[cfg(target_os = "macos")]
self.pin(&socket)?;
socket.bind(&SocketAddr::V4(SocketAddrV4::new(self.address, 0)).into())?;
socket.set_nonblocking(true)?;
UdpSocket::from_std(socket.into())
}
}
type Reply = Arc<dyn Fn(Route, Bytes) + Send + Sync>;
type Offers = Vec<(NetworkId, Physical)>;
pub(super) struct Gateway {
input: mpsc::Sender<(Route, Bytes)>,
offers: watch::Sender<Offers>,
worker: JoinHandle<()>,
}
impl Gateway {
pub fn new(mtu: u32, reply: impl Fn(Route, Bytes) + Send + Sync + 'static) -> Self {
let (input, packets) = mpsc::channel(EXIT_FORWARD_QUEUE);
let (offers, serving) = watch::channel(Vec::new());
let worker = tokio::spawn(run(mtu, Arc::new(reply), packets, serving));
Self {
input,
offers,
worker,
}
}
pub fn configure(&self, mut offers: Offers) {
offers.sort_by_key(|(network, _)| *network);
self.offers.send_if_modified(|old| {
if *old == offers {
return false;
}
*old = offers;
true
});
}
pub fn forward(&self, origin: Route, packet: Bytes) -> bool {
self.offers
.borrow()
.iter()
.any(|(network, _)| *network == origin.network)
&& self.input.try_send((origin, packet)).is_ok()
}
}
impl Drop for Gateway {
fn drop(&mut self) {
self.worker.abort();
}
}
type FlowKey = (NetworkId, iroh::EndpointId, Tuple);
struct Flow {
tx: mpsc::Sender<Bytes>,
task: tokio::task::AbortHandle,
}
async fn run(
mtu: u32,
reply: Reply,
mut incoming: mpsc::Receiver<(Route, Bytes)>,
mut serving: watch::Receiver<Offers>,
) {
let mut flows: HashMap<FlowKey, Flow> = HashMap::new();
let mut jobs = JoinSet::new();
let mut fragments = packet::Reassembly::default();
loop {
let (origin, part) = tokio::select! {
biased;
changed = serving.changed() => {
if changed.is_err() { return; }
let offers = serving.borrow_and_update();
flows.retain(|(network, _, _), flow| {
let keep = offers.iter().any(|(net, _)| net == network);
if !keep { flow.task.abort(); }
keep
});
// Incomplete datagrams from a withdrawn offer must not survive a rejoin.
fragments = packet::Reassembly::default();
continue;
}
Some(result) = jobs.join_next_with_id(), if !jobs.is_empty() => {
if let Ok((id, Some(key))) = result
&& flows.get(&key).is_some_and(|flow| flow.task.id() == id) {
flows.remove(&key);
}
continue;
}
input = incoming.recv() => match input { Some(input) => input, None => return },
};
let Some(physical) = serving
.borrow()
.iter()
.find(|(net, _)| *net == origin.network)
.map(|(_, p)| *p)
else {
continue;
};
let Some(packet) =
fragments.accept(part, EXIT_FORWARD_FRAGMENTS, Some(*origin.peer.as_bytes()))
else {
continue;
};
let Some(n) = packet::header(&packet) else {
continue;
};
if packet[8] <= 1 {
continue;
}
if packet[9] == 1 {
if jobs.len() < EXIT_FORWARD_FLOWS
&& packet.get(n) == Some(&8)
&& packet.len() >= n + 8
&& packet[n + 1] == 0
&& packet::checksum(&packet[n..]) == 0
{
let reply = reply.clone();
let mut offers = serving.clone();
jobs.spawn(async move {
tokio::select! {
_ = offers.wait_for(|nets| !nets.iter().any(|(net, _)| *net == origin.network)) => {},
_ = echo(physical, origin, packet, n, &reply, mtu) => {}
}
None
});
}
continue;
}
let Some(tuple) = packet::tuple(&packet) else {
continue;
};
let src = IpAddress::Ipv4(tuple.src);
let dst = IpAddress::Ipv4(tuple.dst);
let valid =
match tuple.protocol {
Protocol::Tcp => TcpPacket::new_checked(&packet[n..])
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
Protocol::Udp => UdpPacket::new_checked(&packet[n..])
.is_ok_and(|p| p.verify_checksum(&src, &dst)),
};
if !valid {
continue;
}
let key = (origin.network, origin.peer, tuple);
if let Some(flow) = flows.get(&key) {
let _ = flow.tx.try_send(packet);
continue;
}
if jobs.len() >= EXIT_FORWARD_FLOWS
|| (tuple.protocol == Protocol::Tcp && !packet::tcp_syn(&packet))
{
continue;
}
let (tx, rx) = mpsc::channel(EXIT_FORWARD_QUEUE.min(16));
let reply = reply.clone();
let task = jobs.spawn(async move {
match tuple.protocol {
Protocol::Tcp => tcp::serve(physical, origin, tuple, packet, rx, reply, mtu).await,
Protocol::Udp => {
let _ = udp(physical, origin, tuple, packet, rx, reply, mtu).await;
}
}
Some(key)
});
flows.insert(key, Flow { tx, task });
}
}
fn remote(t: Tuple) -> SocketAddr {
SocketAddr::V4(SocketAddrV4::new(t.dst, t.dport))
}
fn respond(reply: &Reply, origin: Route, packet: Bytes, mtu: u32) {
for part in packet::fragments(packet, mtu) {
reply(origin, part);
}
}
async fn udp(
physical: Physical,
origin: Route,
tuple: Tuple,
first: Bytes,
mut incoming: mpsc::Receiver<Bytes>,
reply: Reply,
mtu: u32,
) -> io::Result<()> {
let socket = physical.datagram(socket2::Protocol::UDP)?;
socket.connect(remote(tuple)).await?;
let socket = &socket;
let send = |p: Bytes| async move {
if let Some(n) = packet::header(&p) {
socket.send(&p[n + 8..]).await?;
}
Ok::<_, io::Error>(())
};
send(first).await?;
let mut buf = vec![0; 65_507];
loop {
tokio::select! {
packet = incoming.recv() => match packet { Some(p) => send(p).await?, None => return Ok(()) },
result = socket.recv(&mut buf) => {
let len = result?;
if let Some(p) = udp_packet(tuple.reverse(), &buf[..len]) { respond(&reply, origin, p, mtu); }
},
_ = tokio::time::sleep(Duration::from_secs(120)) => return Ok(()),
}
}
}
fn ip_packet(
source: Ipv4Addr,
destination: Ipv4Addr,
proto: u8,
payload_len: usize,
) -> Option<Vec<u8>> {
let len = u16::try_from(20usize.checked_add(payload_len)?).ok()?;
let mut bytes = vec![0; usize::from(len)];
bytes[0] = 0x45;
bytes[2..4].copy_from_slice(&len.to_be_bytes());
bytes[4..6].copy_from_slice(&rand::random::<u16>().to_be_bytes());
bytes[8] = 64;
bytes[9] = proto;
bytes[12..16].copy_from_slice(&source.octets());
bytes[16..20].copy_from_slice(&destination.octets());
let checksum = packet::checksum(&bytes[..20]);
bytes[10..12].copy_from_slice(&checksum.to_be_bytes());
Some(bytes)
}
fn udp_packet(tuple: Tuple, body: &[u8]) -> Option<Bytes> {
let mut bytes = ip_packet(tuple.src, tuple.dst, 17, body.len().checked_add(8)?)?;
let mut p = UdpPacket::new_unchecked(&mut bytes[20..]);
p.set_src_port(tuple.sport);
p.set_dst_port(tuple.dport);
p.set_len((body.len() + 8) as u16);
p.payload_mut().copy_from_slice(body);
p.fill_checksum(&tuple.src.into(), &tuple.dst.into());
Some(bytes.into())
}
async fn echo(
physical: Physical,
origin: Route,
packet: Bytes,
n: usize,
reply: &Reply,
mtu: u32,
) -> io::Result<()> {
let Some((source, destination)) = packet::addresses(&packet) else {
return Ok(());
};
let socket = physical.datagram(socket2::Protocol::ICMPV4)?;
socket.set_ttl(u32::from(packet[8] - 1))?;
socket.connect((destination, 0)).await?;
// Raw ICMP sockets can observe other echo replies. An independent nonce and
// the original data correlate a reply with this one authenticated request.
let nonce = rand::random::<u32>().to_be_bytes();
let mut request = packet[n..].to_vec();
request[4..8].copy_from_slice(&nonce);
request[2..4].fill(0);
let checksum = packet::checksum(&request);
request[2..4].copy_from_slice(&checksum.to_be_bytes());
socket.send(&request).await?;
// Winsock delivers unrelated replies to other raw ICMP sockets too. A longer
// reply must not trigger WSAEMSGSIZE and abort this request.
let mut buf = vec![0; usize::from(u16::MAX)];
let until = tokio::time::Instant::now() + Duration::from_secs(3);
loop {
let len = tokio::time::timeout_at(until, socket.recv(&mut buf)).await??;
// Darwin ping sockets return a BSD IPv4 header whose length field is
// the host-endian ICMP payload length. The connected socket supplies
// its peer and the checksum and nonce below authenticate this reply.
#[cfg(target_os = "macos")]
let header = buf[..len]
.first()
.filter(|b| *b >> 4 == 4)
.map(|b| usize::from(*b & 15) * 4)
.filter(|h| *h >= 20 && *h <= len);
#[cfg(not(target_os = "macos"))]
let header = packet::header(&buf[..len]);
let Some(h) = header else {
continue;
};
let body = &buf[h..len];
if buf[9] != 1
|| body.len() != request.len()
|| body[0..2] != [0, 0]
|| body[4..] != request[4..]
|| packet::checksum(body) != 0
{
continue;
}
if let Some(mut out) = ip_packet(destination, source, 1, body.len()) {
out[20..].copy_from_slice(body);
out[24..28].copy_from_slice(&packet[n + 4..n + 8]);
out[22..24].fill(0);
let checksum = packet::checksum(&out[20..]);
out[22..24].copy_from_slice(&checksum.to_be_bytes());
respond(reply, origin, out.into(), mtu);
}
return Ok(());
}
}
@@ -0,0 +1,345 @@
//! A Mac that cannot open a system utun can still serve an explicitly offered
//! exit over bound user sockets. Ordinary host applications need a real utun.
use super::Physical;
use crate::BoxFuture;
use crate::overlay::{
OverlayError, TunDevice, TunFactory, TunRequest,
hostrules::{
BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, ExitHostPlan, ExitHostReport,
ExitHostRules, RuleOutcome,
},
};
use std::{
net::Ipv4Addr,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
#[derive(Debug, Clone, Default)]
pub(in crate::overlay) struct SocketExit {
// Only refreshed while offering. Keep the OS route lookup off the packet path.
uplink: Arc<Mutex<Option<(Instant, Physical)>>>,
}
#[derive(Debug)]
struct NoHostTun(u32);
impl TunDevice for NoHostTun {
fn name(&self) -> &str {
"userspace-exit"
}
fn mtu(&self) -> u32 {
self.0
}
fn recv(&self) -> BoxFuture<'_, Option<bytes::Bytes>> {
Box::pin(async { None })
}
fn send<'a>(&'a self, _packet: bytes::Bytes) -> BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(async {
Err(OverlayError::Unavailable(
"this Mac has no host utun".into(),
))
})
}
}
impl TunFactory for SocketExit {
fn name(&self) -> &str {
"userspace-exit"
}
fn on_host(&self) -> bool {
false
}
fn create<'a>(
&'a self,
request: TunRequest,
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
Box::pin(async move { Ok(Arc::new(NoHostTun(request.mtu)) as Arc<dyn TunDevice>) })
}
fn host_rules(&self) -> Option<Arc<dyn BroadcastHostRules>> {
Some(Arc::new(self.clone()))
}
}
impl BroadcastHostRules for SocketExit {
fn name(&self) -> &str {
"userspace-exit"
}
fn exit_rules(&self) -> Option<&dyn ExitHostRules> {
Some(self)
}
fn apply<'a>(&'a self, plan: &'a BroadcastRulesPlan) -> BoxFuture<'a, BroadcastRulesReport> {
Box::pin(async move {
let failed = RuleOutcome::Failed("Local broadcast needs the system utun".into());
BroadcastRulesReport {
plan: plan.clone(),
route: failed.clone(),
firewall: failed,
}
})
}
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async {})
}
}
impl SocketExit {
async fn reconcile(&self, plan: &ExitHostPlan) -> ExitHostReport {
let physical = if plan.offer.is_empty() {
Err("exit sharing is off".to_owned())
} else {
tokio::task::spawn_blocking(|| {
let physical = crate::overlay::hostrules::macos_default_uplink()?;
let iface = netdev::get_interfaces()
.into_iter()
.find(|i| i.name == physical)
.ok_or_else(|| "the physical default interface is unavailable".to_owned())?;
if iface.index == 0 || iface.is_loopback() || iface.name.starts_with("utun") {
return Err("no physical IPv4 interface for exit sharing".into());
}
let address = iface
.ipv4
.iter()
.map(|ip| ip.addr())
.find(|ip| !ip.is_unspecified() && !ip.is_loopback() && !ip.is_link_local())
.ok_or_else(|| {
"the physical interface has no usable IPv4 address".to_owned()
})?;
Ok(Physical {
index: iface.index,
address,
})
})
.await
.map_err(|e| e.to_string())
.and_then(|r| r)
};
*self.uplink.lock().unwrap_or_else(|e| e.into_inner()) =
physical.as_ref().ok().map(|p| (Instant::now(), *p));
let result = match physical {
Ok(_) => RuleOutcome::Applied,
Err(reason) => RuleOutcome::Failed(reason),
};
ExitHostReport {
offer: plan
.offer
.iter()
.map(|range| (*range, result.clone()))
.collect(),
forwarding: None,
client: plan.client.then(|| {
RuleOutcome::Failed(
"Routing this Mac’s applications through a peer needs the system utun".into(),
)
}),
}
}
}
impl ExitHostRules for SocketExit {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(self.reconcile(plan))
}
fn clear<'a>(&'a self, _: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move {
*self.uplink.lock().unwrap_or_else(|e| e.into_inner()) = None;
})
}
fn refresh_offer<'a>(
&'a self,
plan: &'a ExitHostPlan,
) -> BoxFuture<'a, Option<ExitHostReport>> {
Box::pin(async move {
if self
.uplink
.lock()
.unwrap_or_else(|e| e.into_inner())
.is_some_and(|(at, _)| at.elapsed() < Duration::from_secs(5))
{
return None;
}
Some(self.reconcile(plan).await)
})
}
fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> {
self.uplink
.lock()
.unwrap_or_else(|e| e.into_inner())
.map(|(_, p)| (p.index, p.address))
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::overlay::egress::{Route, echo, ip_packet};
#[derive(Debug)]
struct DeniedUtun(bool);
impl TunFactory for DeniedUtun {
fn name(&self) -> &str {
"utun"
}
fn on_host(&self) -> bool {
true
}
fn create<'a>(
&'a self,
_: TunRequest,
) -> BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
Box::pin(async move {
Err(if self.0 {
OverlayError::UtunDenied("permission denied".into())
} else {
OverlayError::Unavailable("system error".into())
})
})
}
}
struct Returns(tokio::sync::mpsc::Sender<bytes::Bytes>);
impl crate::overlay::PacketCarrier for Returns {
fn carry(&self, _: Route, p: bytes::Bytes) -> bool {
self.0.try_send(p).is_ok()
}
}
#[tokio::test]
async fn a_denied_utun_can_offer_while_an_unrelated_interface_failure_is_reported() {
use crate::overlay::{Interface, RoutingTable};
let (tx, _rx) = tokio::sync::mpsc::channel(2);
let start = |denied| {
Interface::start(
Arc::new(DeniedUtun(denied)),
"utun",
1280,
Arc::new(RoutingTable::new()),
Arc::new(Returns(tx.clone())),
)
};
assert!(matches!(
start(false).await,
Err(OverlayError::Unavailable(_))
));
let interface = start(true).await.unwrap();
assert!(!interface.on_host());
assert_eq!(interface.name(), "userspace-exit");
interface.remove().await;
}
#[tokio::test]
#[ignore = "requires an active physical IPv4 interface on macOS; uses a UDP listener on this Mac"]
async fn a_user_exit_delivers_udp_and_the_reply_on_its_physical_interface() {
use crate::{
overlay::{ExitPolicy, Interface, NetworkRoutes, RoutingTable},
vip::{Protocol, packet::Tuple},
};
use tokio::{net::UdpSocket, time::timeout};
let net = crate::NetworkId::from_bytes([7; 32]);
let peer = iroh::SecretKey::from_bytes(&[8; 32]).public();
let own = Ipv4Addr::new(10, 2, 3, 1);
let member = Ipv4Addr::new(10, 2, 3, 2);
let routes = Arc::new(RoutingTable::new());
routes
.set_network(
net,
NetworkRoutes {
local: Some(own),
peers: vec![(member, peer)],
range: Some("10.2.3.0/24".parse().unwrap()),
..Default::default()
},
)
.unwrap();
let (tx, mut returns) = tokio::sync::mpsc::channel(2);
let interface = Interface::start(
Arc::new(DeniedUtun(true)),
"utun",
1280,
routes.clone(),
Arc::new(Returns(tx)),
)
.await
.unwrap();
routes.set_exit(
net,
ExitPolicy {
offer: true,
via: None,
},
);
interface.sync_exit_rules().await;
assert!(
interface.exit_offer_ready(net),
"{:?}",
interface.exit_rules(net)
);
let device = crate::overlay::hostrules::macos_default_uplink().unwrap();
let iface = netdev::get_interfaces()
.into_iter()
.find(|i| i.name == device)
.unwrap();
let external = iface
.ipv4
.iter()
.map(|n| n.addr())
.find(|a| !a.is_link_local())
.unwrap();
let server = UdpSocket::bind((external, 0)).await.unwrap();
let tuple = Tuple {
src: member,
dst: external,
sport: 51234,
dport: server.local_addr().unwrap().port(),
protocol: Protocol::Udp,
};
let request = super::super::udp_packet(tuple, b"exit request").unwrap();
let mut buf = [0; 32];
timeout(Duration::from_secs(3), async {
interface.deliver(net, peer, request.clone()).await.unwrap();
let (len, from) = server.recv_from(&mut buf).await.unwrap();
assert_eq!(&buf[..len], b"exit request");
assert_eq!(from.ip(), external);
server.send_to(b"exit reply", from).await.unwrap();
let reply = returns.recv().await.unwrap();
assert_eq!(crate::vip::packet::tuple(&reply), Some(tuple.reverse()));
assert_eq!(&reply[28..], b"exit reply");
})
.await
.unwrap();
routes.set_exit(net, Default::default());
interface.sync_exit_rules().await;
assert!(!interface.exit_offer_ready(net));
assert!(interface.deliver(net, peer, request).await.is_err());
interface.remove().await;
}
#[tokio::test]
async fn unprivileged_echo_uses_a_bound_datagram_and_restores_the_peer_identifier() {
let lo = netdev::get_interfaces()
.into_iter()
.find(|i| i.is_loopback())
.unwrap();
let physical = Physical {
index: lo.index,
address: Ipv4Addr::LOCALHOST,
};
let (tx, mut rx) = tokio::sync::mpsc::channel(1);
let reply: super::super::Reply = Arc::new(move |_, bytes| {
let _ = tx.try_send(bytes);
});
let origin = Route {
network: crate::NetworkId::from_bytes([7; 32]),
peer: iroh::SecretKey::from_bytes(&[8; 32]).public(),
};
let mut p = ip_packet(Ipv4Addr::new(10, 2, 3, 9), Ipv4Addr::LOCALHOST, 1, 8).unwrap();
p[20] = 8;
p[24..28].copy_from_slice(&[1, 2, 3, 4]);
let sum = crate::vip::packet::checksum(&p[20..]);
p[22..24].copy_from_slice(&sum.to_be_bytes());
echo(physical, origin, p.into(), 20, &reply, 1280)
.await
.unwrap();
let response = rx.try_recv().unwrap();
assert_eq!(&response[20..22], &[0, 0]);
assert_eq!(&response[24..28], &[1, 2, 3, 4]);
assert_eq!(crate::vip::packet::checksum(&response[20..]), 0);
}
}
@@ -0,0 +1,153 @@
//! smoltcp owns the member-facing half of one stream. The OS owns the
//! physical TCP connection. Both directions apply backpressure independently.
use super::*;
use smoltcp::{
iface::{Config, Interface, SocketSet},
phy::{self, Device, DeviceCapabilities, Medium},
socket::tcp::{Socket, SocketBuffer, State},
time::Instant as NetTime,
wire::{HardwareAddress, IpCidr},
};
use std::collections::VecDeque;
use tokio::io::AsyncWriteExt;
struct Wire {
mtu: usize,
input: Option<Bytes>,
output: VecDeque<Bytes>,
}
struct Rx(Bytes);
impl phy::RxToken for Rx {
fn consume<R, F: FnOnce(&[u8]) -> R>(self, f: F) -> R {
f(&self.0)
}
}
struct Tx<'a>(&'a mut VecDeque<Bytes>);
impl phy::TxToken for Tx<'_> {
fn consume<R, F: FnOnce(&mut [u8]) -> R>(self, len: usize, f: F) -> R {
let mut bytes = vec![0; len];
let result = f(&mut bytes);
self.0.push_back(bytes.into());
result
}
}
impl Device for Wire {
type RxToken<'a> = Rx;
type TxToken<'a> = Tx<'a>;
fn receive(&mut self, _: NetTime) -> Option<(Rx, Tx<'_>)> {
self.input.take().map(|p| (Rx(p), Tx(&mut self.output)))
}
fn transmit(&mut self, _: NetTime) -> Option<Tx<'_>> {
(self.output.len() < EXIT_FORWARD_QUEUE).then_some(Tx(&mut self.output))
}
fn capabilities(&self) -> DeviceCapabilities {
let mut caps = DeviceCapabilities::default();
caps.medium = Medium::Ip;
caps.max_transmission_unit = self.mtu;
caps
}
}
pub(super) async fn serve(
physical: Physical,
origin: Route,
flow: Tuple,
syn: Bytes,
mut incoming: mpsc::Receiver<Bytes>,
reply: Reply,
mtu: u32,
) {
let Ok(Ok(mut upstream)) =
tokio::time::timeout(Duration::from_secs(8), physical.tcp(remote(flow))).await
else {
if let Some(reset) = packet::reject(&syn) {
reply(origin, reset);
}
return;
};
let mut wire = Wire {
mtu: mtu as usize,
input: Some(syn),
output: VecDeque::new(),
};
let mut config = Config::new(HardwareAddress::Ip);
config.random_seed = rand::random();
let mut iface = Interface::new(config, &mut wire, NetTime::ZERO);
iface.update_ip_addrs(|ips| {
let _ = ips.push(IpCidr::new(flow.dst.into(), 0));
});
let mut sockets = SocketSet::new(Vec::new());
let buffer = || SocketBuffer::new(vec![0; 64 * 1024]);
let mut tcp = Socket::new(buffer(), buffer());
tcp.set_timeout(Some(smoltcp::time::Duration::from_secs(120)));
if tcp.listen((flow.dst, flow.dport)).is_err() {
return;
}
let handle = sockets.add(tcp);
let start = std::time::Instant::now();
let mut remote_fin = false;
let mut local_fin = false;
loop {
let now = NetTime::from_millis(start.elapsed().as_millis() as i64);
iface.poll(now, &mut wire, &mut sockets);
let tcp = sockets.get_mut::<Socket>(handle);
if tcp.can_recv() {
let write = tcp.recv(|buf| match upstream.try_write(buf) {
Ok(n) => (n, Ok(n > 0)),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(false)),
Err(e) => (0, Err(e)),
});
if matches!(write, Ok(Err(_))) {
tcp.abort();
}
}
if !local_fin
&& !tcp.may_recv()
&& matches!(
tcp.state(),
State::CloseWait | State::Closing | State::LastAck | State::TimeWait
)
{
let _ = upstream.shutdown().await;
local_fin = true;
}
if tcp.can_send() && !remote_fin {
match tcp.send(|buf| match upstream.try_read(buf) {
Ok(n) => (n, Ok(Some(n))),
Err(e) if e.kind() == io::ErrorKind::WouldBlock => (0, Ok(None)),
Err(e) => (0, Err(e)),
}) {
Ok(Ok(Some(0))) => {
remote_fin = true;
tcp.close();
}
Ok(Err(_)) => tcp.abort(),
_ => {}
}
}
iface.poll(now, &mut wire, &mut sockets);
for p in wire.output.drain(..) {
reply(origin, p);
}
let tcp = sockets.get::<Socket>(handle);
// A reset during the handshake returns smoltcp to Listen. This
// worker owns exactly one physical connection and must never accept
// a second SYN on that connection or retain an idle flow slot.
if matches!(tcp.state(), State::Listen | State::Closed) {
return;
}
let delay = iface
.poll_delay(now, &sockets)
.map(Duration::from)
.unwrap_or(Duration::from_secs(3600));
tokio::select! {
packet = incoming.recv() => match packet { Some(p) => wire.input = Some(p), None => return },
ready = upstream.readable(), if !remote_fin && tcp.can_send() => { if ready.is_err() { return; } }
ready = upstream.writable(), if tcp.can_recv() => { if ready.is_err() { return; } }
_ = tokio::time::sleep(delay) => {}
}
}
}
@@ -0,0 +1,458 @@
//! These run on loopback on every host. The gateway uses the same code as
//! Windows, with a loopback source in place of the pinned physical adapter.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use tokio::net::{TcpListener, UdpSocket};
fn route() -> Route {
Route {
network: NetworkId::from_bytes([4; 32]),
peer: iroh::SecretKey::from_bytes(&[3; 32]).public(),
}
}
fn addr() -> Ipv4Addr {
Ipv4Addr::new(10, 13, 37, 9)
}
fn loopback() -> Physical {
#[cfg(target_os = "macos")]
let index = netdev::get_interfaces()
.into_iter()
.find(|i| i.is_loopback())
.unwrap()
.index;
#[cfg(not(target_os = "macos"))]
let index = 0;
Physical {
index,
address: Ipv4Addr::LOCALHOST,
}
}
#[tokio::test]
async fn a_udp_flow_keeps_its_external_port_while_the_upstream_changes_and_stops_with_its_offer() {
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let route = route();
let (replies, mut rx) = mpsc::channel(8);
let gateway = Gateway::new(1280, move |r, p| {
assert_eq!(r, route);
let _ = replies.try_send(p);
});
let physical = loopback();
gateway.configure(vec![(route.network, physical)]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 10403,
dport: server.local_addr().unwrap().port(),
protocol: Protocol::Udp,
};
let mut port = None;
for body in [b"first".as_slice(), b"after upstream change"] {
gateway.configure(vec![(route.network, physical)]);
assert!(gateway.forward(route, udp_packet(flow, body).unwrap()));
let mut buf = [0; 128];
let (n, from) = tokio::time::timeout(Duration::from_secs(2), server.recv_from(&mut buf))
.await
.unwrap()
.unwrap();
assert_eq!(&buf[..n], body);
assert_eq!(port.get_or_insert(from.port()), &from.port());
server.send_to(body, from).await.unwrap();
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
.await
.unwrap()
.unwrap();
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
assert_eq!(&answer[28..], body);
}
gateway.configure(Vec::new());
assert!(!gateway.forward(route, udp_packet(flow, b"withdrawn").unwrap()));
}
#[tokio::test]
async fn refused_tcp_returns_a_reset_to_the_originating_client() {
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
drop(listener);
let (tx, mut rx) = mpsc::channel(2);
let route = route();
let gateway = Gateway::new(1280, move |r, p| {
assert_eq!(r, route);
let _ = tx.try_send(p);
});
gateway.configure(vec![(route.network, loopback())]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 42000,
dport: port,
protocol: Protocol::Tcp,
};
let mut syn = vec![0; 40];
syn[0] = 0x45;
syn[2..4].copy_from_slice(&40u16.to_be_bytes());
syn[8] = 64;
syn[9] = 6;
syn[32] = 0x50;
syn[33] = 2;
let checksum = crate::vip::packet::checksum(&syn[..20]);
syn[10..12].copy_from_slice(&checksum.to_be_bytes());
assert!(gateway.forward(route, crate::vip::packet::rewrite(&syn, flow).unwrap()));
let answer = tokio::time::timeout(Duration::from_secs(2), rx.recv())
.await
.unwrap()
.unwrap();
assert!(crate::vip::packet::tcp_reset(&answer));
assert_eq!(crate::vip::packet::tuple(&answer), Some(flow.reverse()));
}
fn tcp_packet(tuple: Tuple, flags: u8, seq: u32, ack: u32, body: &[u8]) -> Bytes {
let mut bytes = ip_packet(tuple.src, tuple.dst, 6, 20 + body.len()).unwrap();
bytes[24..28].copy_from_slice(&seq.to_be_bytes());
bytes[28..32].copy_from_slice(&ack.to_be_bytes());
bytes[32] = 0x50;
bytes[33] = flags;
bytes[34..36].copy_from_slice(&65535u16.to_be_bytes());
bytes[40..].copy_from_slice(body);
packet::rewrite(&bytes, tuple).unwrap()
}
#[tokio::test]
async fn a_tcp_stream_to_the_same_destination_survives_offer_reconciliation() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let port = listener.local_addr().unwrap().port();
let server = tokio::spawn(async move {
let (mut socket, _) = listener.accept().await.unwrap();
for expected in [b"one", b"two"] {
let mut body = [0; 3];
socket.read_exact(&mut body).await.unwrap();
assert_eq!(&body, expected);
socket.write_all(&body).await.unwrap();
}
});
tokio::time::timeout(Duration::from_secs(4), async {
let route = route();
let (tx, mut rx) = mpsc::channel(16);
let gateway = Gateway::new(1280, move |r, p| {
assert_eq!(r, route);
let _ = tx.try_send(p);
});
let physical = loopback();
gateway.configure(vec![(route.network, physical)]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 43210,
dport: port,
protocol: Protocol::Tcp,
};
let mut seq: u32 = 123;
assert!(gateway.forward(route, tcp_packet(flow, 2, seq, 0, &[])));
let synack = rx.recv().await.unwrap();
assert!(packet::syn_ack(&synack));
let mut ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
seq += 1;
for body in [b"one", b"two"] {
assert!(gateway.forward(route, tcp_packet(flow, 0x18, seq, ack, body)));
seq += body.len() as u32;
loop {
let p = rx.recv().await.unwrap();
let tcp = TcpPacket::new_checked(&p[20..]).unwrap();
if !tcp.payload().is_empty() {
assert_eq!(tcp.payload(), body);
ack = ack.wrapping_add(body.len() as u32);
assert!(gateway.forward(route, tcp_packet(flow, 0x10, seq, ack, &[])));
break;
}
}
// A configuration change for a different membership cannot create a new B socket.
gateway.configure(vec![
(route.network, physical),
(NetworkId::from_bytes([7; 32]), physical),
]);
}
server.await.unwrap();
})
.await
.unwrap();
}
/// Two disposable Wintun adapters provide an offline "WAN" and an upstream.
/// A longer prefix on the latter captures local applications for the same IP.
#[cfg(all(windows, feature = "tun-device"))]
#[tokio::test]
#[ignore = "requires an elevated disposable Windows runner and wintun.dll"]
async fn physical_member_sockets_survive_a_more_specific_wintun_route() {
use crate::overlay::{
Cidr,
provision::{InterfacePlan, InterfaceProvisioner, WintunProvisioner},
tun::TunDevice,
};
let wan = Ipv4Addr::new(198, 18, 222, 1);
let upstream = Ipv4Addr::new(198, 18, 222, 5);
let site = Ipv4Addr::new(198, 18, 222, 6);
for dev in netdev::get_interfaces() {
assert!(
dev.ipv4
.iter()
.all(|net| !net.contains(&wan) && !net.contains(&site)),
"test subnet is in use on {}",
dev.name
);
}
async fn read(device: &dyn TunDevice, endpoint: SocketAddrV4, body: &[u8]) -> Tuple {
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let p = device.recv().await.unwrap();
if let Some(t) = packet::tuple(&p)
&& t.dst == *endpoint.ip()
&& t.dport == endpoint.port()
&& p.get(28..) == Some(body)
{
return t;
}
}
})
.await
.unwrap()
}
async fn wait_source(site: SocketAddrV4, wanted: Ipv4Addr) {
tokio::time::timeout(Duration::from_secs(10), async {
loop {
let s = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
if s.connect(site).await.is_ok() && s.local_addr().unwrap().ip() == wanted {
return;
}
tokio::time::sleep(Duration::from_millis(50)).await;
}
})
.await
.unwrap();
}
let id = rand::random::<u32>();
let provision = WintunProvisioner::new().unwrap();
let uplink = provision
.reconcile(&InterfacePlan::new(
format!("tsfw-a-{id:x}"),
1280,
vec![Cidr::new(wan.into(), 24).unwrap()],
))
.await
.unwrap()
.device
.unwrap();
let site = SocketAddrV4::new(site, 38201);
wait_source(site, wan).await;
let index = netdev::get_interfaces()
.into_iter()
.find(|i| i.ipv4.iter().any(|a| a.addr() == wan))
.unwrap()
.index;
let physical = Physical {
index,
address: wan,
};
let origin = route();
let (tx, mut rx) = mpsc::channel(8);
let gateway = Gateway::new(1280, move |_, packet| {
let _ = tx.try_send(packet);
});
gateway.configure(vec![(origin.network, physical)]);
let flow = Tuple {
src: addr(),
dst: *site.ip(),
sport: 21002,
dport: site.port(),
protocol: Protocol::Udp,
};
let mut send = async |tuple, payload: &[u8]| {
assert!(gateway.forward(origin, udp_packet(tuple, payload).unwrap()));
let observed = read(&*uplink, site, payload).await;
assert_eq!(observed.src, wan);
uplink
.send(udp_packet(observed.reverse(), payload).unwrap())
.await
.unwrap();
let back = tokio::time::timeout(Duration::from_secs(5), rx.recv())
.await
.unwrap()
.unwrap();
assert_eq!(packet::tuple(&back), Some(tuple.reverse()));
observed.sport
};
let initial = send(flow, b"before").await;
let capture = provision
.reconcile(&InterfacePlan::new(
format!("tsfw-c-{id:x}"),
1280,
vec![Cidr::new(upstream.into(), 30).unwrap()],
))
.await
.unwrap()
.device
.unwrap();
wait_source(site, upstream).await;
let local = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
local.send_to(b"local B", site).await.unwrap();
assert_eq!(read(&*capture, site, b"local B").await.src, upstream);
assert_eq!(send(flow, b"same A socket").await, initial);
send(
Tuple {
sport: 21003,
..flow
},
b"new A socket",
)
.await;
// Raw ICMP uses the identical physical interface selection and restores A's
// identifier and sequence after reading the actual reply from the uplink.
let mut ping = ip_packet(addr(), *site.ip(), 1, 12).unwrap();
ping[20] = 8;
ping[24..32].copy_from_slice(b"pingdata");
let checksum = packet::checksum(&ping[20..]);
ping[22..24].copy_from_slice(&checksum.to_be_bytes());
assert!(gateway.forward(origin, ping.into()));
tokio::time::timeout(Duration::from_secs(5), async {
loop {
let wire = uplink.recv().await.unwrap();
let Some(n) = packet::header(&wire) else {
continue;
};
if wire[9] != 1 || wire.get(n + 8..) != Some(b"data") {
continue;
}
assert_eq!(packet::addresses(&wire), Some((wan, *site.ip())));
let mut pong = ip_packet(*site.ip(), wan, 1, wire.len() - n).unwrap();
pong[20..].copy_from_slice(&wire[n..]);
pong[20..24].fill(0);
let checksum = packet::checksum(&pong[20..]);
pong[22..24].copy_from_slice(&checksum.to_be_bytes());
uplink.send(pong.into()).await.unwrap();
break;
}
let reply = rx.recv().await.unwrap();
assert_eq!(packet::addresses(&reply), Some((*site.ip(), addr())));
assert_eq!(&reply[24..], b"pingdata");
assert_eq!(packet::checksum(&reply[20..]), 0);
})
.await
.unwrap();
}
#[tokio::test]
async fn resetting_a_half_open_mesh_handshake_closes_the_physical_socket() {
use tokio::io::AsyncReadExt;
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let route = route();
let (tx, mut rx) = mpsc::channel(4);
let gateway = Gateway::new(1280, move |_, packet| {
let _ = tx.try_send(packet);
});
gateway.configure(vec![(route.network, loopback())]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 43211,
dport: listener.local_addr().unwrap().port(),
protocol: Protocol::Tcp,
};
tokio::time::timeout(Duration::from_secs(3), async {
assert!(gateway.forward(route, tcp_packet(flow, 2, 500, 0, &[])));
let (mut physical, _) = listener.accept().await.unwrap();
let synack = rx.recv().await.unwrap();
assert!(packet::syn_ack(&synack));
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
assert!(gateway.forward(route, tcp_packet(flow, 0x14, 501, ack, &[])));
assert_eq!(physical.read(&mut [0; 1]).await.unwrap(), 0);
})
.await
.unwrap();
}
#[tokio::test]
async fn a_server_half_close_still_receives_the_members_final_bytes_and_fin() {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let (out, mut rx) = mpsc::channel(8);
let origin = route();
let gateway = Gateway::new(1280, move |_, packet| {
let _ = out.try_send(packet);
});
gateway.configure(vec![(origin.network, loopback())]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 42041,
dport: listener.local_addr().unwrap().port(),
protocol: Protocol::Tcp,
};
tokio::time::timeout(Duration::from_secs(3), async {
assert!(gateway.forward(origin, tcp_packet(flow, 2, 200, 0, &[])));
let (mut server, _) = listener.accept().await.unwrap();
server.shutdown().await.unwrap();
let synack = rx.recv().await.unwrap();
assert!(packet::syn_ack(&synack));
let ack = u32::from_be_bytes(synack[24..28].try_into().unwrap()).wrapping_add(1);
assert!(gateway.forward(origin, tcp_packet(flow, 0x10, 201, ack, &[])));
loop {
let p = rx.recv().await.unwrap();
if TcpPacket::new_checked(&p[20..]).unwrap().fin() {
break;
}
}
assert!(gateway.forward(
origin,
tcp_packet(flow, 0x19, 201, ack.wrapping_add(1), b"last bytes")
));
let mut received = Vec::new();
server.read_to_end(&mut received).await.unwrap();
assert_eq!(received, b"last bytes");
})
.await
.unwrap();
}
#[tokio::test]
async fn at_capacity_existing_udp_flows_continue_and_a_new_tuple_is_dropped() {
let server = UdpSocket::bind((Ipv4Addr::LOCALHOST, 0)).await.unwrap();
let origin = route();
let gateway = Gateway::new(1280, |_, _| {});
gateway.configure(vec![(origin.network, loopback())]);
let flow = Tuple {
src: addr(),
dst: Ipv4Addr::LOCALHOST,
sport: 1024,
dport: server.local_addr().unwrap().port(),
protocol: Protocol::Udp,
};
tokio::time::timeout(Duration::from_secs(10), async {
let mut buf = [0; 2];
for i in 0..EXIT_FORWARD_FLOWS {
let p = udp_packet(
Tuple {
sport: flow.sport + i as u16,
..flow
},
b"a",
)
.unwrap();
assert!(gateway.forward(origin, p));
assert_eq!(server.recv(&mut buf).await.unwrap(), 1);
}
let extra = Tuple {
sport: u16::MAX,
..flow
};
assert!(gateway.forward(origin, udp_packet(extra, b"no").unwrap()));
assert!(gateway.forward(origin, udp_packet(flow, b"ok").unwrap()));
assert_eq!(server.recv(&mut buf).await.unwrap(), 2);
assert_eq!(&buf, b"ok");
})
.await
.unwrap();
}
@@ -0,0 +1,32 @@
//! Winsock takes the IPv4 interface index in network byte order.
#![allow(unsafe_code)]
use std::{io, os::windows::io::AsRawSocket};
use windows_sys::Win32::Networking::WinSock::{
IP_UNICAST_IF, IPPROTO_IP, SOCKET_ERROR, WSAGetLastError, setsockopt,
};
pub(super) fn pin(socket: &impl AsRawSocket, index: u32) -> io::Result<()> {
#[cfg(test)]
if index == 0 {
return Ok(());
}
if index == 0 {
return Err(io::Error::other("no physical exit interface"));
}
let bytes = index.to_be_bytes();
// The socket owner stays alive for the call. Winsock reads exactly the
// four bytes of the interface index and retains no pointer to them.
if unsafe {
setsockopt(
socket.as_raw_socket() as _,
IPPROTO_IP,
IP_UNICAST_IF,
bytes.as_ptr(),
4,
)
} == SOCKET_ERROR
{
return Err(io::Error::from_raw_os_error(unsafe { WSAGetLastError() }));
}
Ok(())
}
+11 -3
View File
@@ -5,6 +5,15 @@
//! system sees. It is kept apart from the broadcast rules, which have a
//! different lifetime and different tags.
/// Plaintext IP bytes carried through the client's currently selected internet exit.
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct ExitTraffic {
/// Bytes accepted by the carrier for off-mesh destinations.
pub tx_bytes: u64,
/// Internet reply bytes delivered to the local interface.
pub rx_bytes: u64,
}
/// How one set of host rules went.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RuleSetReport {
@@ -22,9 +31,8 @@ pub struct ExitRulesReport {
pub offer: Option<RuleSetReport>,
/// Whether the kernel forwards packets for the overlay interface.
///
/// `Some(false)` means the rules are in place but nothing passes until
/// forwarding is turned on, which the agent never does itself. `None`
/// when it could not be read.
/// `Some(false)` means kernel forwarding is off. `None` when unavailable
/// or when the exit forwards through physical sockets.
pub forwarding: Option<bool>,
/// The routes that send this device's traffic through its exit node.
/// `None` means it uses none through this network.
@@ -0,0 +1,113 @@
//! Last successful forwarding for older peers that cannot report their exit selection.
use super::NetworkRoutes;
use crate::identity::NetworkId;
use arc_swap::ArcSwap;
use iroh::EndpointId;
use std::{
collections::HashMap,
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::Instant,
};
type Stamps = HashMap<EndpointId, Arc<AtomicU64>>;
const RECENT_SECS: u64 = 60;
#[derive(Debug)]
pub(super) struct ExitActivity {
started: Instant,
networks: ArcSwap<HashMap<NetworkId, Arc<Stamps>>>,
}
impl Default for ExitActivity {
fn default() -> Self {
Self {
started: Instant::now(),
networks: ArcSwap::default(),
}
}
}
impl ExitActivity {
// Serialized by the routing write lock. Provision only signed allocations on
// offering networks. Packets never create entries or lock the routing table here.
pub(super) fn configure(&self, network: NetworkId, routes: Option<&NetworkRoutes>) {
let previous = self.networks.load();
let old = previous.get(&network);
let offering = routes.filter(|r| r.exit.offer);
if offering.is_none() && old.is_none() {
return;
}
let mut next = (**previous).clone();
if let Some(routes) = offering {
let peers = routes
.peers
.iter()
.map(|(_, id)| {
let stamp = old.and_then(|s| s.get(id)).cloned().unwrap_or_default();
(*id, stamp)
})
.collect();
next.insert(network, Arc::new(peers));
} else {
next.remove(&network);
}
self.networks.store(Arc::new(next));
}
pub(super) fn stamp(&self, network: NetworkId, peer: EndpointId) -> Option<Arc<AtomicU64>> {
self.networks.load().get(&network)?.get(&peer).cloned()
}
pub(super) fn forwarded(&self, stamp: &AtomicU64) {
let now = self.started.elapsed().as_secs() + 1;
if stamp.load(Ordering::Relaxed) < now {
stamp.fetch_max(now, Ordering::Relaxed);
}
}
pub(super) fn recent(&self, network: NetworkId, peer: EndpointId) -> bool {
let now = self.started.elapsed().as_secs() + 1;
self.stamp(network, peer).is_some_and(|s| {
let last = s.load(Ordering::Relaxed);
last > 0 && now.saturating_sub(last) < RECENT_SECS
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::overlay::ExitPolicy;
#[test]
fn only_delivered_exit_packets_count_and_old_stamps_cannot_revive_a_removed_offer() {
let mut activity = ExitActivity::default();
let network = NetworkId::from_bytes([1; 32]);
let peer = iroh::SecretKey::from_bytes(&[2; 32]).public();
let routes = NetworkRoutes {
exit: ExitPolicy {
offer: true,
via: None,
},
peers: vec![(std::net::Ipv4Addr::LOCALHOST, peer)],
..Default::default()
};
activity.configure(network, Some(&routes));
assert!(!activity.recent(network, peer));
let Some(stamp) = activity.stamp(network, peer) else {
unreachable!()
};
activity.forwarded(&stamp);
assert!(activity.recent(network, peer));
activity.configure(network, Some(&routes));
assert!(activity.recent(network, peer));
activity.started -= std::time::Duration::from_secs(60);
assert!(!activity.recent(network, peer));
activity.configure(network, None);
activity.configure(network, Some(&routes));
activity.forwarded(&stamp);
assert!(!activity.recent(network, peer));
}
}
@@ -63,8 +63,7 @@ pub struct ExitHostReport {
/// One outcome per offered range: its masquerade and forward rules.
pub offer: Vec<(Ipv4Range, RuleOutcome)>,
/// Whether the kernel forwards packets for the interface. `None` when it
/// could not be read. The agent only reads this: turning forwarding on is
/// the owner's decision.
/// could not be read. A local macOS offer enables forwarding when needed.
pub forwarding: Option<bool>,
/// The routes and rules that send this device's traffic through the
/// interface, when the plan asked for them.
@@ -91,6 +90,20 @@ pub trait ExitHostRules: Send + Sync + std::fmt::Debug + 'static {
Box::pin(async { None })
}
/// Refresh a provider-only plan when the physical egress changes.
fn refresh_offer<'a>(
&'a self,
_plan: &'a ExitHostPlan,
) -> BoxFuture<'a, Option<ExitHostReport>> {
Box::pin(async { None })
}
/// The physical interface index and IPv4 address used by a userspace exit.
/// Kernel-forwarding hosts do not need to expose an egress socket address.
fn forwarded_uplink(&self) -> Option<(u32, std::net::Ipv4Addr)> {
None
}
/// Whether using an exit node on this host needs the underlay addresses
/// the agent talks to, because the host cannot exempt the agent's own
/// traffic from the default route by user id (Windows). The default is no.
@@ -112,6 +125,9 @@ pub fn exit_tag_prefix(interface: &str) -> String {
/// The one-line detail for a set of offer outcomes.
pub fn offer_detail(outcome: &RuleOutcome, range: &Ipv4Range) -> String {
match outcome {
RuleOutcome::Applied if cfg!(windows) => {
format!("physical TCP, UDP and ICMP echo forwarding for {range}")
}
RuleOutcome::Applied => format!("masquerade + forward for {range} in place"),
RuleOutcome::Failed(reason) => reason.clone(),
}
@@ -3,7 +3,7 @@
//!
//! # Offering
//!
//! For every network that offers this agent as an exit node, three rules,
//! For every network that offers this agent as an exit node, rules
//! selected by that network's range and carrying the tag
//! `tsunagi-exit:<if>:<range>`:
//!
@@ -11,6 +11,8 @@
//! -t nat POSTROUTING -s <range> ! -o <if> -j MASQUERADE
//! -t filter FORWARD -i <if> -s <range> ! -o <if> -j ACCEPT
//! -t filter FORWARD -o <if> -d <range> -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
//! -t mangle PREROUTING -i <if> -s <range> -j MARK --set-xmark <underlay bit>
//! -t mangle PREROUTING ! -i <if> -m conntrack --ctorigsrc <range> --ctdir REPLY --ctstate SNAT -j MARK --set-xmark <underlay bit>
//! ```
//!
//! `! -o <if>` is the egress without naming it: whatever interface the
@@ -24,11 +26,11 @@
//! Policy routing, with no `/1` routes and nothing in the main table:
//!
//! ```text
//! table 0x7473: default dev <if>
//! table 0x7473: default dev <if> src <selected overlay address>
//! 5205: from all fwmark 0x40000000/0x40000000 lookup main
//! 5206: from all uidrange <euid>-<euid> lookup main
//! 5290: from all lookup main suppress_prefixlength 0
//! 5300: from all lookup 0x7473
//! 5300: from all iif lo lookup 0x7473
//! ```
//!
//! The first two keep the agent's *own* sockets and marked replies off the tunnel: its QUIC, relay,
@@ -45,6 +47,7 @@
use crate::BoxFuture;
use crate::state::Ipv4Range;
use std::net::Ipv4Addr;
use super::RuleOutcome;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules, exit_tag, exit_tag_prefix};
@@ -55,7 +58,11 @@ use super::linux::{
use super::linux_exit_mark;
/// The chains the offering rules live in: `(table, chain)`.
const CHAINS: [(&str, &str); 2] = [("nat", "POSTROUTING"), ("filter", "FORWARD")];
const CHAINS: [(&str, &str); 3] = [
("nat", "POSTROUTING"),
("filter", "FORWARD"),
("mangle", "PREROUTING"),
];
/// One firewall rule: where it goes, and its match and target.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -69,7 +76,7 @@ fn owned(words: &[&str]) -> Vec<String> {
words.iter().map(|word| word.to_string()).collect()
}
/// The three rules of one offered range.
/// The rules of one offered range.
///
/// Each carries a comment naming its interface and range, which is how it is
/// found again. A kernel without the `comment` match (small router builds
@@ -124,6 +131,37 @@ fn offer_rules(interface: &str, range: &Ipv4Range, comment: bool) -> Vec<Rule> {
&["-j", "ACCEPT"],
),
},
// These marks select the physical routing table for clients we
// forward, including the reverse-path check on physical replies.
// The conntrack original tuple survives switching our own upstream.
Rule {
table: "mangle",
chain: "PREROUTING",
spec: spec(
&["-i", interface, "-s", &range_text],
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
),
},
Rule {
table: "mangle",
chain: "PREROUTING",
spec: spec(
&[
"!",
"-i",
interface,
"-m",
"conntrack",
"--ctorigsrc",
&range_text,
"--ctdir",
"REPLY",
"--ctstate",
"SNAT",
],
&["-j", "MARK", "--set-xmark", linux_exit_mark::MARK],
),
},
]
}
@@ -158,7 +196,7 @@ struct Found {
/// Every rule in an `iptables -S <chain>` listing that is ours: carrying a
/// tag that starts with `prefix`, or, on a kernel with no `comment` match,
/// being exactly one of the three rules this module writes for some range.
/// being exactly one of the rules this module writes for some range.
/// Anything else in the chain is left alone.
fn tagged_rules(listing: &str, chain: &str, prefix: &str) -> Vec<Found> {
// `tsunagi-exit:<interface>:`
@@ -197,7 +235,7 @@ fn uncommented_tag(interface: &str, chain: &str, rest: &[String]) -> Option<Stri
}
let range: Ipv4Range = rest
.windows(2)
.find(|pair| pair[0] == "-s" || pair[0] == "-d")
.find(|pair| matches!(pair[0].as_str(), "-s" | "-d" | "--ctorigsrc"))
.and_then(|pair| pair[1].parse().ok())?;
offer_rules(interface, &range, false)
.iter()
@@ -379,7 +417,7 @@ fn read_sysctl(path: &str) -> Option<String> {
std::fs::read_to_string(path).ok()
}
fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
fn check_kernel_rpf(overlay: &str, uid: u32) -> Result<(), String> {
let directory = "/proc/sys/net/ipv4/conf";
let value = |name: &str, setting: &str| -> Result<u32, String> {
read_sysctl(&format!("{directory}/{name}/{setting}"))
@@ -390,7 +428,7 @@ fn check_kernel_rpf(overlay: &str) -> Result<(), String> {
for entry in std::fs::read_dir(directory).map_err(|err| err.to_string())? {
let entry = entry.map_err(|err| err.to_string())?;
let name = entry.file_name().to_string_lossy().into_owned();
if name != "all" && name != "default" && name != "lo" && name != overlay {
if name != "all" && name != "default" && name != "lo" && (name != overlay || uid == 0) {
interfaces.push((
name.clone(),
value(&name, "rp_filter")?,
@@ -441,7 +479,7 @@ impl LinuxHostRules {
.map_err(|err| format!("the task failed: {err}"))
}
async fn apply_client(&self, interface: &str) -> RuleOutcome {
async fn apply_client(&self, interface: &str, source: Option<Ipv4Addr>) -> RuleOutcome {
let xdg = std::env::var("XDG_RUNTIME_DIR").ok();
if let Some(reason) = client_refusal(xdg.as_deref()) {
// Whatever an earlier run left must not stay in force.
@@ -461,7 +499,15 @@ impl LinuxHostRules {
.as_ref()
.is_some_and(|(name, _, routed)| name == interface && *routed);
if installed {
// A failed socket refresh must never remove an active exit route.
// A different network can now supply the exit on this same TUN.
// Preserve the policy rules and underlay protection during the switch.
let route = self.route.clone();
let name = interface.to_string();
match Self::blocking(move || route.update_exit_source(&name, source)).await {
Ok(Ok(())) => {}
Ok(Err(err)) => return RuleOutcome::Failed(err.to_string()),
Err(reason) => return RuleOutcome::Failed(reason),
}
return self
.refresh_sockets(interface)
.await
@@ -472,7 +518,7 @@ impl LinuxHostRules {
}
let name = interface.to_string();
let prepared = Self::blocking(move || {
check_kernel_rpf(&name)?;
check_kernel_rpf(&name, euid)?;
linux_exit_mark::install(
&run_firewall,
&name,
@@ -492,7 +538,8 @@ impl LinuxHostRules {
}
let route = self.route.clone();
let name = interface.to_string();
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid)).await {
let outcome = match Self::blocking(move || route.set_exit_client(&name, euid, source)).await
{
Ok(Ok(())) => RuleOutcome::Applied,
Ok(Err(err)) => RuleOutcome::Failed(err.to_string()),
Err(reason) => RuleOutcome::Failed(reason),
@@ -557,7 +604,7 @@ impl LinuxHostRules {
.ok()
.and_then(|s| parse_euid(&s))
.ok_or("cannot read agent UID")?;
check_kernel_rpf(&work_name)?;
check_kernel_rpf(&work_name, uid)?;
let v6 = std::path::Path::new("/proc/sys/net/ipv6").is_dir();
let sockets = linux_exit_mark::local_sockets(uid, v6)?;
if previous
@@ -616,7 +663,7 @@ impl ExitHostRules for LinuxHostRules {
forwarding_state(read_sysctl, &interface)
};
let client = if plan.client {
Some(self.apply_client(&interface).await)
Some(self.apply_client(&interface, plan.client_source).await)
} else {
if let Err(reason) = self.clear_client(&interface).await {
tracing::warn!(%reason, "cannot remove exit-client rules");
@@ -661,7 +708,21 @@ mod tests {
#[test]
fn the_rules_masquerade_the_range_out_of_every_other_interface_and_forward_it() {
let rules = offer_rules("tsun0", &range(), true);
assert_eq!(rules.len(), 3);
assert_eq!(rules.len(), 5);
let outgoing = words(&rules[3].spec);
let replies = words(&rules[4].spec);
assert!(
outgoing.starts_with("-i tsun0 -s 10.13.37.0/24 "),
"{outgoing}"
);
assert!(
replies.contains("--ctorigsrc 10.13.37.0/24 --ctdir REPLY --ctstate SNAT"),
"{replies}"
);
for rule in &rules[3..] {
assert_eq!((rule.table, rule.chain), ("mangle", "PREROUTING"));
assert!(words(&rule.spec).ends_with("-j MARK --set-xmark 0x40000000/0x40000000"));
}
assert_eq!(
words(&rules[0].spec),
"-s 10.13.37.0/24 ! -o tsun0 -m comment --comment tsunagi-exit:tsun0:10.13.37.0/24 -j MASQUERADE"
@@ -795,7 +856,7 @@ mod tests {
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
let inserted = fake.verbs("-I");
assert_eq!(inserted.len(), 3, "{inserted:?}");
assert_eq!(inserted.len(), 5, "{inserted:?}");
assert!(
inserted.iter().all(|call| !call.contains("comment")),
"{inserted:?}"
@@ -827,12 +888,12 @@ mod tests {
}
#[test]
fn a_fresh_host_gets_the_three_rules() {
fn a_fresh_host_gets_the_offer_rules() {
let fake = Fake::new(false);
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
let inserted = fake.verbs("-I");
assert_eq!(inserted.len(), 3, "{inserted:?}");
assert_eq!(inserted.len(), 5, "{inserted:?}");
assert!(inserted[0].contains("-t nat -I POSTROUTING 1"));
assert!(fake.verbs("-D").is_empty());
}
@@ -847,6 +908,15 @@ mod tests {
)
.with_rule("filter", &format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"))
.with_rule("filter", &format!("-A FORWARD -o tsun0 -m comment --comment {tag} -j ACCEPT"));
let fake = offer_rules("tsun0", &range(), true)
.into_iter()
.filter(|rule| rule.chain == "PREROUTING")
.fold(fake, |fake, rule| {
fake.with_rule(
rule.table,
&format!("-A {} {}", rule.chain, words(&rule.spec)),
)
});
let outcome = apply_offer(&|args| fake.run(args), "tsun0", &[range()]);
assert_eq!(outcome, vec![(range(), RuleOutcome::Applied)]);
assert!(fake.verbs("-I").is_empty());
@@ -865,7 +935,7 @@ mod tests {
"-A POSTROUTING -s 10.99.0.0/24 -m comment --comment {old_tag} -j MASQUERADE"
),
)
// Only one of the three for the current range.
// Only one rule for the current range.
.with_rule(
"filter",
&format!("-A FORWARD -i tsun0 -m comment --comment {tag} -j ACCEPT"),
@@ -887,7 +957,7 @@ mod tests {
deleted.iter().all(|call| !call.contains("eth0")),
"{deleted:?}"
);
assert_eq!(fake.verbs("-I").len(), 3);
assert_eq!(fake.verbs("-I").len(), 5);
}
#[test]
@@ -217,7 +217,9 @@ fn client() {
ip(&["-6", "route", "add", "throw", prefix, "table", "52"]);
}
let mut passive = spawn_listener("listener");
route.set_exit_client("tsun0", 990).unwrap();
route
.set_exit_client("tsun0", 990, Some("10.99.0.1".parse().unwrap()))
.unwrap();
// uid bypass alone cannot protect reverse lookups, reproducing the bug.
run_probes("blocked");
install(&run_firewall, "tsun0", 990, true).unwrap();
@@ -248,6 +250,25 @@ for family,source,target in [(socket.AF_INET,'198.51.100.2','192.0.2.1'),(socket
install(&run_firewall, "tsun0", 990, true).unwrap();
run_probes("pass");
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("dev tsun0"));
// Check our own default table without the foreign VPN's higher-priority default.
ip(&["-4", "rule", "del", "priority", "5270"]);
for (destination, source) in [
("10.13.37.2", "10.13.37.1"),
("10.99.0.2", "10.99.0.1"),
("198.51.100.2", "10.99.0.1"),
] {
let result = ip(&["-4", "route", "get", destination, "uid", "991"]);
assert!(
result.contains("dev tsun0") && result.contains(&format!("src {source}")),
"{result}"
);
}
route
.update_exit_source("tsun0", Some("10.13.37.1".parse().unwrap()))
.unwrap();
assert!(ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]).contains("src 10.13.37.1"));
assert!(ip(&["-4", "route", "get", "10.99.0.2", "uid", "991"]).contains("src 10.99.0.1"));
ip(&["-4", "rule", "add", "priority", "5270", "table", "52"]);
let blocked = Command::new("ip")
.args(["-6", "route", "get", "2001:db8:2::2", "uid", "991"])
.output()
@@ -384,6 +405,15 @@ fn strict_firewall_preserves_underlay_and_application_exit_routing() {
"tsun0",
]);
ip(&["-n", &client_name, "link", "set", "tsun0", "up"]);
ip(&[
"-n",
&client_name,
"addr",
"add",
"10.99.0.1/24",
"dev",
"tsun0",
]);
let echo_code = r#"import socket,selectors,sys
selector=selectors.DefaultSelector()
for family in [socket.AF_INET,socket.AF_INET6]:
@@ -437,3 +467,214 @@ while True:
String::from_utf8_lossy(&result.stderr)
);
}
const CHAIN_TEST: &str = "overlay::hostrules::linux_exit_kernel::serving_an_established_flow_while_switching_the_local_exit";
fn chain_namespace(role: &str) -> Namespace {
let name = format!("tsng-chain-{role}-{}", std::process::id());
ip(&["netns", "add", &name]);
let guard = Namespace(name);
ip(&["-n", &guard.0, "link", "set", "lo", "up"]);
guard
}
fn connect(a: &Namespace, left: &str, b: &Namespace, right: &str) {
ip(&[
"link", "add", left, "netns", &a.0, "type", "veth", "peer", "name", right, "netns", &b.0,
]);
ip(&["-n", &a.0, "link", "set", left, "up"]);
ip(&["-n", &b.0, "link", "set", right, "up"]);
}
fn python_in(namespace: &str) -> Command {
let mut cmd = Command::new("ip");
cmd.args(["netns", "exec", namespace, "python3"]);
cmd
}
fn chain_echo(namespace: &Namespace, name: &str) -> Echo {
let code = r#"import socketserver, sys
class Echo(socketserver.StreamRequestHandler):
def handle(self):
for line in self.rfile:
self.wfile.write(f'{sys.argv[1]} {self.client_address[0]} '.encode() + line)
with socketserver.ThreadingTCPServer(('198.51.100.2', 42100), Echo) as server:
print('ready', flush=True)
server.serve_forever()
"#;
let mut server = Echo(
python_in(&namespace.0)
.args(["-u", "-c", code, name])
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap(),
);
let mut ready = String::new();
BufReader::new(server.0.stdout.take().unwrap())
.read_line(&mut ready)
.unwrap();
assert_eq!(ready.trim(), "ready");
server
}
fn short_chain_probe(mut cmd: Command, phase: &str, expected: &str) {
let probe = r#"import socket
with socket.create_connection(('198.51.100.2', 42100), timeout=3) as s:
s.sendall(b'new\n')
print(s.makefile('rb').readline().decode().strip())
"#;
let result = cmd.args(["-c", probe]).output().unwrap();
assert!(
result.status.success(),
"TCP probe {phase} expected {expected}: {}\n{}\n{}\n{}",
String::from_utf8_lossy(&result.stderr),
ip(&["-4", "route", "get", "198.51.100.2", "uid", "991"]),
ip(&["-4", "rule", "show"]),
ip(&["neigh", "show"]),
);
assert_eq!(String::from_utf8_lossy(&result.stdout).trim(), expected);
}
fn chain_middle(a: &str) {
use super::{BroadcastHostRules, ExitHostPlan, RuleOutcome};
let range = "10.13.37.0/24".parse().unwrap();
std::fs::write("/proc/sys/net/ipv4/ip_forward", "1").unwrap();
// A root agent's UID bypass can also match a kernel reverse lookup.
// Both the NAT reply from the uplink and the reply from C on tsun0 must
// survive strict filtering when the remote Internet address is identical.
for setting in ["rp_filter", "src_valid_mark"] {
std::fs::write(format!("/proc/sys/net/ipv4/conf/all/{setting}"), "1").unwrap();
}
let filter: Vec<String> = [
"-t",
"mangle",
"-A",
"PREROUTING",
"-m",
"rpfilter",
"--invert",
"--validmark",
"-j",
"DROP",
]
.into_iter()
.map(str::to_owned)
.collect();
let rpf = run_firewall(false, &filter);
assert!(
matches!(rpf, super::linux::Ran::Exited { success: true, .. }),
"{rpf:?}"
);
let provisioner = NetlinkProvisioner::new().unwrap();
let host = provisioner.host_rules();
let exit = host.exit_rules().unwrap();
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let apply = |select| {
let plan = ExitHostPlan {
interface: "tsun0".into(),
offer: vec![range],
overlay: vec![range],
client: select,
client_source: select.then(|| "10.13.37.1".parse().unwrap()),
..Default::default()
};
let result = runtime.block_on(exit.apply(&plan));
assert_eq!(result.offer, [(range, RuleOutcome::Applied)]);
assert_eq!(result.client, select.then_some(RuleOutcome::Applied));
};
apply(false);
// The socket is created once and remains open across both reconciliations.
let persistent = r#"import socket, sys
with socket.create_connection(('198.51.100.2',42100), timeout=3) as s:
out = s.makefile('rb')
for line in sys.stdin.buffer:
s.sendall(line)
print(out.readline().decode().strip(), flush=True)
"#;
let mut stream = Echo(
python_in(a)
.args(["-u", "-c", persistent])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.spawn()
.unwrap(),
);
let mut input = stream.0.stdin.take().unwrap();
let mut output = BufReader::new(stream.0.stdout.take().unwrap());
for (change, phase, b_egress) in [
(None, "before", "uplink 192.0.2.1 new"),
(Some(true), "selected", "exit-c 10.13.37.1 new"),
(Some(false), "cleared", "uplink 192.0.2.1 new"),
] {
if let Some(selected) = change {
apply(selected);
}
writeln!(input, "{phase}").unwrap();
let mut reply = String::new();
output.read_line(&mut reply).unwrap();
assert_eq!(
reply.trim(),
format!("uplink 192.0.2.1 {phase}"),
"ongoing TCP stream from A"
);
short_chain_probe(python_in(a), phase, "uplink 192.0.2.1 new");
// A regular application on B sends to exactly the same IP and port as A.
let mut local = Command::new("python3");
local.uid(991).gid(991);
short_chain_probe(local, phase, b_egress);
}
runtime.block_on(exit.clear("tsun0"));
}
#[test]
#[ignore = "needs Linux network namespaces, iproute2, iptables and Python"]
fn serving_an_established_flow_while_switching_the_local_exit() {
if let Ok(a) = std::env::var("TSUNAGI_EXIT_CHAIN_A") {
chain_middle(&a);
return;
}
let a = chain_namespace("a");
let b = chain_namespace("b");
let c = chain_namespace("c");
let uplink = chain_namespace("wan");
// Emulate the one overlay interface on B. The bridge is a separate
// namespace so that A, B and C see only packets on their own veth.
let mesh = chain_namespace("lan");
ip(&["-n", &mesh.0, "link", "add", "mesh", "type", "bridge"]);
ip(&["-n", &mesh.0, "link", "set", "mesh", "up"]);
for (ns, port, address) in [
(&a, "to-a", "10.13.37.2/24"),
(&b, "to-b", "10.13.37.1/24"),
(&c, "to-c", "10.13.37.3/24"),
] {
connect(ns, "tsun0", &mesh, port);
ip(&["-n", &mesh.0, "link", "set", port, "master", "mesh"]);
ip(&["-n", &ns.0, "addr", "add", address, "dev", "tsun0"]);
}
connect(&b, "wan-b", &uplink, "wan");
ip(&["-n", &b.0, "addr", "add", "192.0.2.1/24", "dev", "wan-b"]);
ip(&["-n", &uplink.0, "addr", "add", "192.0.2.2/24", "dev", "wan"]);
ip(&["-n", &a.0, "route", "add", "default", "via", "10.13.37.1"]);
ip(&["-n", &b.0, "route", "add", "default", "via", "192.0.2.2"]);
for ns in [&uplink, &c] {
ip(&["-n", &ns.0, "addr", "add", "198.51.100.2/32", "dev", "lo"]);
}
let _physical = chain_echo(&uplink, "uplink");
let _exit = chain_echo(&c, "exit-c");
let result = Command::new("ip")
.args(["netns", "exec", &b.0])
.arg(std::env::current_exe().unwrap())
.args(["--ignored", "--exact", CHAIN_TEST, "--nocapture"])
.env("TSUNAGI_EXIT_CHAIN_A", &a.0)
.output()
.unwrap();
assert!(
result.status.success(),
"{}\n{}",
String::from_utf8_lossy(&result.stdout),
String::from_utf8_lossy(&result.stderr)
);
}
@@ -8,8 +8,10 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
/// Outside Tailscale's 0xff0000 mask and ordinary low-bit WireGuard marks.
pub(crate) const UNDERLAY_MARK: u32 = 0x4000_0000;
pub(crate) const UNDERLAY_MASK: u32 = UNDERLAY_MARK;
const MARK: &str = "0x40000000/0x40000000";
pub(super) const MARK: &str = "0x40000000/0x40000000";
const MASK: &str = "0x40000000";
/// An authenticated return packet from this host’s own upstream exit.
pub(crate) const EXIT_REPLY_MARK: u32 = 0x2000_0000;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Listener {
@@ -141,11 +143,11 @@ fn words(values: &[&str]) -> Vec<String> {
values.iter().map(|s| (*s).into()).collect()
}
fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
fn rules(interface: &str, uid: u32, ipv6: bool) -> Vec<(&'static str, Vec<String>)> {
let tag = tag(interface);
let uid = uid.to_string();
let owner = uid.to_string();
// Insert at position one in this order: final OUTPUT order is MARK, SAVE.
vec![
let mut rules = vec![
(
"PREROUTING",
words(&[
@@ -175,7 +177,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
"-m",
"owner",
"--uid-owner",
&uid,
&owner,
"-m",
"mark",
"--mark",
@@ -199,7 +201,7 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
"-m",
"owner",
"--uid-owner",
&uid,
&owner,
"-m",
"comment",
"--comment",
@@ -210,7 +212,40 @@ fn rules(interface: &str, uid: u32) -> Vec<(&'static str, Vec<String>)> {
MARK,
]),
),
]
];
if !ipv6 && uid == 0 {
// Both xt_rpfilter and the kernel's strict rp_filter perform the
// reverse lookup as UID 0. For an established local application's
// reply from our upstream, the /0 must point back to this interface,
// ahead of the root daemon's UID bypass. The actual packet's LOCAL
// destination still uses routing table local at priority zero.
rules.push((
"PREROUTING",
words(&[
"-i",
interface,
"-m",
"addrtype",
"--dst-type",
"LOCAL",
"-m",
"conntrack",
"--ctdir",
"REPLY",
"--ctstate",
"ESTABLISHED,RELATED",
"-m",
"comment",
"--comment",
&tag,
"-j",
"MARK",
"--set-xmark",
"0x20000000/0x20000000",
]),
));
}
rules
}
fn execute(run: RunFamily<'_>, v6: bool, args: Vec<String>) -> Result<String, String> {
@@ -295,7 +330,7 @@ fn install_with_listeners(
clear(run, interface, v6)?;
let result = (|| {
for family in [false, true].into_iter().filter(|family| !family || v6) {
for (chain, spec) in rules(interface, uid) {
for (chain, spec) in rules(interface, uid, family) {
let args = words(&["-t", "mangle", "-I", chain, "1"])
.into_iter()
.chain(spec)
@@ -409,6 +444,25 @@ mod tests {
assert_eq!(UNDERLAY_MASK & 0x00ff_0000, 0);
}
#[test]
fn only_root_daemons_mark_local_ipv4_replies_from_their_own_exit() {
for (uid, v6) in [(990, false), (0, true), (0, false)] {
let rules = rules("tsun0", uid, v6);
let marked: Vec<_> = rules
.iter()
.filter(|(_, args)| args.contains(&"0x20000000/0x20000000".to_string()))
.collect();
if uid == 0 && !v6 {
assert_eq!(marked.len(), 1);
assert_eq!(marked[0].0, "PREROUTING");
let text = marked[0].1.join(" ");
assert!(text.contains("-i tsun0 -m addrtype --dst-type LOCAL -m conntrack --ctdir REPLY --ctstate ESTABLISHED,RELATED"));
} else {
assert!(marked.is_empty());
}
}
}
#[test]
fn cleanup_retains_other_interfaces_and_rolls_back_partial_ipv6_installation() {
let calls = RefCell::new(Vec::new());
@@ -19,10 +19,12 @@
use crate::BoxFuture;
use std::sync::{Arc, Mutex};
use std::sync::Arc;
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
use super::macos_exit::{apply_plan, clear_all, run_tool};
use super::macos_exit::{
HostState, apply_plan, clear_all, refresh_client, refresh_offer, run_tool,
};
use super::{BroadcastHostRules, BroadcastRulesPlan, BroadcastRulesReport, RuleOutcome};
/// The limited-broadcast destination routed through the overlay interface.
@@ -68,17 +70,25 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
#[derive(Debug, Default)]
pub struct MacosHostRules {
/// The reference `pfctl -E` handed out, held while exit-node rules need
/// `pf` on and released when they are removed.
pub(super) pf_token: Arc<Mutex<Option<String>>>,
/// The PF reference and the physical routes owned by this agent.
state: Arc<HostState>,
}
impl MacosHostRules {
/// Creates the host rules.
/// Creates host rules with process-lifetime ownership. System services
/// use [`Self::with_state_dir`] for recovery after abrupt termination.
pub fn new() -> Self {
Self::default()
}
/// Tie crash recovery to this agent's state directory, even when macOS
/// assigns its utun a different number on the next run.
pub fn with_state_dir(dir: &std::path::Path) -> Self {
Self {
state: Arc::new(HostState::with_state_dir(dir)),
}
}
/// Installs the route, replacing one this agent added earlier so the call
/// can be repeated. The delete is best effort: a route that is not there
/// is the state the add then reaches anyway.
@@ -95,7 +105,7 @@ impl ExitHostRules for MacosHostRules {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let job_plan = plan.clone();
let token = Arc::clone(&self.pf_token);
let token = Arc::clone(&self.state);
tokio::task::spawn_blocking(move || apply_plan(&run_tool, &token, &job_plan))
.await
.unwrap_or_else(|err| {
@@ -113,10 +123,39 @@ impl ExitHostRules for MacosHostRules {
})
}
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async move {
if !plan.client {
return None;
}
let state = Arc::clone(&self.state);
let plan = plan.clone();
tokio::task::spawn_blocking(move || refresh_client(&run_tool, &state, &plan))
.await
.unwrap_or_else(|err| Some(RuleOutcome::Failed(err.to_string())))
})
}
fn refresh_offer<'a>(
&'a self,
plan: &'a ExitHostPlan,
) -> BoxFuture<'a, Option<ExitHostReport>> {
Box::pin(async move {
let state = Arc::clone(&self.state);
let plan = plan.clone();
tokio::task::spawn_blocking(move || refresh_offer(&run_tool, &state, &plan))
.await
.unwrap_or_else(|err| {
tracing::warn!(%err, "cannot check the physical egress for exit sharing");
None
})
})
}
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move {
let name = interface.to_string();
let token = Arc::clone(&self.pf_token);
let token = Arc::clone(&self.state);
let _ = tokio::task::spawn_blocking(move || clear_all(&run_tool, &token, &name)).await;
})
}
@@ -0,0 +1,58 @@
//! System authorization for a single local user and IPv4 subnet.
pub(super) const NEEDS_AUTHORIZATION: &str = "Tsunagi exit sharing needs administrator approval";
/// Whether the local user's explicit enable action can be retried after authorization.
pub fn macos_exit_needs_authorization(detail: &str) -> bool {
macos_exit_authorization_uid(detail).is_some()
}
/// The UID of the local agent that needs the grant, from a native authorization result.
pub fn macos_exit_authorization_uid(detail: &str) -> Option<u32> {
let suffix = detail
.strip_prefix(NEEDS_AUTHORIZATION)?
.strip_prefix(" for UID ")?;
if !suffix.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
suffix.parse().ok().filter(|id| *id != 0)
}
/// Ask the system to authorize exit sharing for this local user and subnet.
/// Only a foreground client calls this, after the daemon tried its available rights.
#[cfg(target_os = "macos")]
pub fn authorize_macos_exit(range: crate::state::Ipv4Range, agent_uid: u32) -> Result<(), String> {
use std::process::Command;
const INSTALL: &str = include_str!("authorize-exit.sh");
const HELPER: &str = include_str!("exit-offer.sh");
const DIALOG: &str = r#"on run argv
set installCommand to "/bin/sh -c " & quoted form of (item 1 of argv) & " tsunagi " & quoted form of (item 2 of argv) & " " & quoted form of (item 3 of argv) & " " & quoted form of (item 4 of argv)
do shell script installCommand with prompt ("Allow Tsunagi to share this Mac’s internet connection for " & (item 5 of argv) & " as local user " & (item 2 of argv) & "?") with administrator privileges
end run"#;
if agent_uid == 0 {
return Err("The system agent already runs as administrator.".into());
}
crate::state::Ipv4Range::new(range.base, range.prefix_len).map_err(|e| e.to_string())?;
let output = Command::new("/usr/bin/osascript")
.args([
"-e",
DIALOG,
"--",
INSTALL,
&agent_uid.to_string(),
&format!("{}_{}", range.base, range.prefix_len),
HELPER,
&range.to_string(),
])
.output()
.map_err(|e| format!("could not open macOS authorization: {e}"))?;
if !output.status.success() {
let reason = String::from_utf8_lossy(&output.stderr);
return Err(if reason.contains("(-128)") {
"Exit sharing was not authorized.".to_string()
} else {
format!("Could not authorize exit sharing: {}", reason.trim())
});
}
Ok(())
}
@@ -0,0 +1,24 @@
# Invoked by the system authorization dialog. Each argument is a distinct
# quoted word. The helper body is embedded in the calling binary at build time.
set -eu
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
umask 077
uid=$1
key=$2
helper_body=$3
case "$uid" in ''|*[!0-9]*) exit 1;; esac
case "$key" in ''|*[!0-9._]*) exit 1;; esac
directory=/private/etc/tsunagi-exit
helper="$directory/offer-v1"
/bin/mkdir -p "$directory" /private/etc/sudoers.d
/bin/chmod 0755 "$directory"
tmp=$(/usr/bin/mktemp -d "$directory/.install.XXXXXXXX")
trap '/bin/rm -rf "$tmp"' EXIT
printf '%s\n' "$helper_body" > "$tmp/offer"
printf '#%s ALL = (root) NOPASSWD: NOSETENV: %s\n' "$uid" "$helper" > "$tmp/rule"
/usr/sbin/visudo -c -q -f "$tmp/rule"
/bin/chmod 0755 "$tmp/offer"
/bin/chmod 0440 "$tmp/rule"
/bin/mv -f "$tmp/offer" "$helper"
/bin/mv -f "$tmp/rule" "/private/etc/sudoers.d/tsunagi-exit-$uid"
: > "$directory/grant_${uid}_$key"
@@ -0,0 +1,136 @@
#!/bin/sh -p
# Privileged helper for a previously authorized local account and overlay range.
# The caller supplies no PF text, file names, executable paths or uplink.
set -eu
export PATH=/usr/bin:/bin:/usr/sbin:/sbin LC_ALL=C
umask 077
fail() { echo "Tsunagi exit sharing: $*" >&2; exit 1; }
uid=${SUDO_UID:-}
case "$uid" in ''|*[!0-9]*) fail 'missing local user';; esac
owner=${1:-}
case "$owner" in ''|*[!0-9]*) fail 'invalid agent PID';; esac
shift
process_stamp() {
/bin/ps -p "$1" -o uid= -o lstart= | /usr/bin/awk '{$1=$1; print}'
}
stamp=$(process_stamp "$owner")
[ "${stamp%% *}" = "$uid" ] || fail 'agent PID does not belong to the authorized account'
[ "$#" -ge 2 ] && [ "$#" -le 3 ] || fail 'expected an operation and utun'
action=$1
iface=$2
case "$iface" in utun*) unit=${iface#utun};; *) fail 'expected a utun interface';; esac
case "$unit" in ''|*[!0-9]*) fail 'invalid utun number';; esac
[ "${#unit}" -le 8 ] || fail 'invalid utun number'
case "$action:$#" in clear:2|clear:3|apply:3|forward:3) ;; *) fail 'unknown operation';; esac
state=/private/var/run/tsunagi-exit
grants=/private/etc/tsunagi-exit
/bin/mkdir -p "$state"
prefix="tsng_${uid}_${unit}_"
lock="$state/$uid.lock"
/usr/bin/shlock -f "$lock" -p "$$" || fail 'another update is in progress'
trap '/bin/rm -f "$lock"' EXIT
read_record() {
{ IFS= read -r token && IFS= read -r saved_pid && IFS= read -r saved_stamp; } < "$1" || fail 'invalid PF ownership record'
case "$token" in ''|*[!0-9]*) fail 'invalid PF ownership token';; esac
case "$saved_pid" in ''|*[!0-9]*) fail 'invalid PF owner';; esac
}
clear_one() {
record=$1
[ -f "$record" ] || return 0
name=${record##*/}
anchor="com.apple/${name%.token}"
read_record "$record"
/sbin/pfctl -q -a "$anchor" -f /dev/null
/sbin/pfctl -X "$token" >/dev/null
/bin/rm -f "$record"
}
if [ "$#" = 2 ]; then
# At startup the kernel can assign a different utun. Recover orphaned
# anchors for this account, even after PID reuse, and leave live agents alone.
for record in "$state/tsng_${uid}_"*.token; do
[ -f "$record" ] || continue
read_record "$record"
if [ "$(process_stamp "$saved_pid")" != "$saved_stamp" ]; then
clear_one "$record"
elif [ "$saved_pid" = "$owner" ]; then
case "${record##*/}" in "$prefix"*) clear_one "$record";; esac
fi
done
exit 0
fi
range=$3
[ "${#range}" -le 18 ] || fail 'invalid IPv4 range'
case "$range" in ''|*[!0-9./]*|*/*/*) fail 'invalid IPv4 range';; */*) ;; *) fail 'missing prefix';; esac
key="${range%/*}_${range##*/}"
name="$prefix$key"
record="$state/$name.token"
if [ -f "$record" ]; then
read_record "$record"
if [ "$(process_stamp "$saved_pid")" != "$saved_stamp" ]; then
clear_one "$record"
elif [ "$saved_pid" != "$owner" ]; then
fail 'another live agent owns this exit anchor'
fi
fi
if [ "$action" = clear ]; then clear_one "$record"; exit 0; fi
[ -f "$grants/grant_${uid}_$key" ] || { echo 'Tsunagi exit sharing needs administrator approval' >&2; exit 1; }
# Verify the overlay's exact subnet and mask using the kernel's own address list.
/sbin/ifconfig "$iface" | /usr/bin/awk -v range="$range" '
function ip(s, a, i, n) {
if (split(s, a, ".") != 4) return -1
for (i=1; i<=4; i++) {
if (a[i] !~ /^[0-9]+$/ || a[i] > 255) return -1
n = n*256 + a[i]
}
return n
}
BEGIN { split(range,a,"/"); base=ip(a[1]); p=a[2]; step=2^(32-p) }
$1=="inet" && ip($2)>=0 && base>=0 && p~/^[0-9]+$/ && p<=30 {
for (i=3; i<NF; i++)
if ($i=="netmask" && tolower($(i+1))==sprintf("0x%08x",4294967296-step) &&
int(ip($2)/step)==int(base/step)) found=1
}
END { exit !found }
' || fail 'the authorized range is not configured on this utun'
forward() {
if [ "$(/usr/sbin/sysctl -n net.inet.ip.forwarding)" != 1 ]; then
/usr/sbin/sysctl -w net.inet.ip.forwarding=1 >/dev/null || return 1
fi
[ "$(/usr/sbin/sysctl -n net.inet.ip.forwarding)" = 1 ]
}
if [ "$action" = forward ]; then forward; exit 0; fi
route=$(/sbin/route -n get default)
out=$(printf '%s\n' "$route" | /usr/bin/awk '$1=="interface:" {print $2; exit}')
case "$out" in ''|*[!a-zA-Z0-9]*) fail 'no usable default interface';; esac
[ "$out" != "$iface" ] || fail 'the default route uses this utun'
gateway=$(printf '%s\n' "$route" | /usr/bin/awk '$1=="gateway:" && $2 ~ /^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$/ {print $2; exit}')
via=$out
if [ -n "$gateway" ]; then via="($out $gateway)"; fi
anchor="com.apple/$name"
tag="tsng_forward_$iface"
fresh=false
if [ ! -f "$record" ]; then
message=$(/sbin/pfctl -E 2>&1) || fail "$message"
token=$(printf '%s\n' "$message" | /usr/bin/awk -F: 'tolower($1) ~ /^token *$/ {gsub(/ /,"",$2); if ($2~/^[0-9]+$/) print $2}')
case "$token" in ''|*[!0-9]*) fail 'PF did not return an ownership token';; esac
if ! printf '%s\n' "$token" "$owner" "$stamp" > "$record"; then /sbin/pfctl -X "$token"; exit 1; fi
fresh=true
fi
if ! /sbin/pfctl -q -a "$anchor" -f - <<RULES
nat on $out inet from $range to any tagged $tag -> ($out)
pass out quick on $iface route-to $via inet from any to any tagged $tag no state
pass in quick on $iface inet from $range to ! $range tag $tag no state
pass out quick on $out inet from any to any flags any tagged $tag keep state (if-bound)
RULES
then
if "$fresh"; then clear_one "$record"; fi
fail 'could not load the exit-sharing PF anchor'
fi
if ! forward; then clear_one "$record"; fail 'IPv4 forwarding is still off'; fi
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,187 @@
//! Exercise the installed sharing helper against a throwaway host and PF.
#![allow(clippy::unwrap_used)]
use std::fs;
use std::os::unix::fs::PermissionsExt;
use std::path::Path;
use std::process::{Command, Output};
const HELPER: &str = include_str!("macos/exit-offer.sh");
const INSTALL: &str = include_str!("macos/authorize-exit.sh");
struct Host(tempfile::TempDir);
impl Host {
fn new() -> Self {
let host = Self(tempfile::tempdir().unwrap());
let dir = host.0.path();
let mut helper = HELPER.to_string();
for (program, body) in [
(
"/bin/ps",
r#"test -f "$HOST/process_$2" && cat "$HOST/process_$2""#,
),
(
"/sbin/route",
"printf 'gateway: 192.0.2.1\\ninterface: en7\\n'",
),
(
"/sbin/ifconfig",
"echo 'inet 10.13.37.4 --> 10.13.37.4 netmask 0xffffff00'",
),
("/usr/bin/shlock", "exit 0"),
(
"/usr/sbin/sysctl",
r#"
case "$1" in -n) cat "$HOST/forwarding";; -w) echo 1 > "$HOST/forwarding";; esac"#,
),
(
"/sbin/pfctl",
r#"
echo "$*" >> "$HOST/pf.log"
case "$1" in
-E) echo 'Token : 77' >&2;;
-q) if [ "$5" = - ]; then cat > "$HOST/rules"; fi;;
esac"#,
),
] {
let path = dir.join(Path::new(program).file_name().unwrap());
fs::write(&path, format!("#!/bin/sh\n{body}\n")).unwrap();
fs::set_permissions(&path, fs::Permissions::from_mode(0o700)).unwrap();
helper = helper.replace(program, path.to_str().unwrap());
}
let relocated = |text: &str| {
text.replace(
"/private/etc/tsunagi-exit",
dir.join("grants").to_str().unwrap(),
)
.replace(
"/private/var/run/tsunagi-exit",
dir.join("state").to_str().unwrap(),
)
.replace(
"/private/etc/sudoers.d",
dir.join("policy").to_str().unwrap(),
)
};
fs::write(dir.join("helper.sh"), relocated(&helper)).unwrap();
fs::write(dir.join("forwarding"), "0\n").unwrap();
fs::write(dir.join("process_321"), "501 Tue Nov 24 16:42:52 2026\n").unwrap();
fs::write(
dir.join("installer.sh"),
relocated(INSTALL).replace("/usr/sbin/visudo", "/usr/bin/true"),
)
.unwrap();
host
}
fn run(&self, script: &str, args: &[&str]) -> Output {
self.run_as("321", script, args)
}
fn run_as(&self, pid: &str, script: &str, args: &[&str]) -> Output {
let mut command = Command::new("/bin/sh");
command.arg(self.0.path().join(script));
if script == "helper.sh" {
command.arg(pid);
}
command
.args(args)
.env_clear()
.env("HOST", self.0.path())
.env("SUDO_UID", "501")
.output()
.unwrap()
}
fn grant(&self, uid: &str, key: &str) {
let result = self.run("installer.sh", &[uid, key, HELPER]);
assert!(result.status.success(), "{:?}", result.stderr);
}
}
#[test]
fn restarting_with_a_new_utun_releases_a_dead_agents_rules_and_preserves_other_agents() {
let host = Host::new();
host.grant("501", "10.13.37.0_24");
let dir = host.0.path();
for (pid, iface) in [("321", "utun4"), ("322", "utun5")] {
fs::write(
dir.join(format!("process_{pid}")),
format!("501 born {pid}"),
)
.unwrap();
assert!(
host.run_as(pid, "helper.sh", &["apply", iface, "10.13.37.0/24"])
.status
.success()
);
}
// PID 321 has been reused since that holder's abrupt termination.
fs::write(dir.join("process_321"), "501 later").unwrap();
assert!(host.run("helper.sh", &["clear", "utun9"]).status.success());
assert!(!dir.join("state/tsng_501_4_10.13.37.0_24.token").exists());
assert!(dir.join("state/tsng_501_5_10.13.37.0_24.token").exists());
}
#[test]
fn privileged_helper_accepts_only_a_granted_subnet_configured_on_the_utun() {
let host = Host::new();
host.grant("502", "10.13.37.0_24");
host.grant("501", "10.13.37.0_16");
for args in [
["apply", "utun4", "10.13.37.0/24"],
["apply", "utun4", "10.13.37.0/16"],
["apply", "utun4", "10.13.37.0/24;whoami"],
["apply", "en0", "10.13.37.0/24"],
["apply", "utun4/../", "10.13.37.0/24"],
["shell", "utun4", "10.13.37.0/24"],
] {
assert!(!host.run("helper.sh", &args).status.success(), "{args:?}");
}
assert!(!host.0.path().join("pf.log").exists());
assert_eq!(
fs::read_to_string(host.0.path().join("forwarding")).unwrap(),
"0\n"
);
}
#[test]
fn authorized_exit_owns_one_pf_reference_and_clears_only_its_anchor() {
let host = Host::new();
host.grant("501", "10.13.37.0_24");
let dir = host.0.path();
let rule = fs::read_to_string(dir.join("policy/tsunagi-exit-501")).unwrap();
assert_eq!(
rule,
format!(
"#501 ALL = (root) NOPASSWD: NOSETENV: {}/grants/offer-v1\n",
dir.display()
)
);
for _ in 0..2 {
let result = host.run("helper.sh", &["apply", "utun4", "10.13.37.0/24"]);
assert!(
result.status.success(),
"{}",
String::from_utf8_lossy(&result.stderr)
);
}
assert_eq!(fs::read_to_string(dir.join("forwarding")).unwrap(), "1\n");
let rules = fs::read_to_string(dir.join("rules")).unwrap();
let uplink = super::DefaultRoute {
interface: "en7".into(),
gateway: Some("192.0.2.1".parse().unwrap()),
};
assert_eq!(
rules,
super::pf_rules("utun4", &uplink, &["10.13.37.0/24".parse().unwrap()], None)
);
assert!(host.run("helper.sh", &["clear", "utun4"]).status.success());
assert!(host.run("helper.sh", &["clear", "utun4"]).status.success());
let calls = fs::read_to_string(dir.join("pf.log")).unwrap();
assert_eq!(calls.lines().filter(|line| *line == "-E").count(), 1);
assert_eq!(calls.lines().filter(|line| *line == "-X 77").count(), 1);
assert!(calls.contains("-q -a com.apple/tsng_501_4_10.13.37.0_24 -f /dev/null"));
assert_eq!(fs::read_to_string(dir.join("forwarding")).unwrap(), "1\n");
}
@@ -0,0 +1,391 @@
//! Privileged macOS regression. Both ends are throwaway utuns; only a /30
//! inside the simulated uplink is captured when switching the exit on.
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use bytes::Bytes;
use smoltcp::wire::{IpProtocol, Ipv4Packet, Ipv4Repr, TcpPacket, TcpSeqNumber, UdpPacket};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};
use tokio::time::timeout;
use super::*;
use crate::overlay::Cidr;
use crate::overlay::provision::{InterfacePlan, InterfaceProvisioner, UtunProvisioner};
use crate::overlay::tun::TunDevice;
const UPLINK: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 1);
const REMOTE: Ipv4Addr = Ipv4Addr::new(192, 0, 2, 6);
const CAPTURE: &str = "192.0.2.4/30";
const FIRST: Ipv4Addr = Ipv4Addr::new(198, 18, 222, 1);
const SECOND: Ipv4Addr = Ipv4Addr::new(198, 19, 222, 1);
const WAIT: Duration = Duration::from_secs(5);
async fn utun(addresses: &[Ipv4Addr]) -> Arc<dyn TunDevice> {
let cidrs = addresses
.iter()
.map(|ip| Cidr::new((*ip).into(), 28).unwrap())
.collect();
UtunProvisioner::new()
.unwrap()
.reconcile(&InterfacePlan::new("test", 1280, cidrs))
.await
.unwrap()
.device
.unwrap()
}
struct Capture<'a> {
overlay: &'a str,
uplink: DefaultRoute,
anchor: String,
token: Mutex<Option<String>>,
added_route: bool,
added_scoped: bool,
}
impl Drop for Capture<'_> {
fn drop(&mut self) {
if self.added_route {
let _ = run_tool(Tool::Route, &route_del_args(CAPTURE, self.overlay), None);
}
if self.added_scoped {
let _ = run_tool(
Tool::Route,
&scoped_args("delete", CAPTURE, &self.uplink),
None,
);
}
// Loading an empty ruleset removes just this temporary anchor's rules.
let _ = run_tool(Tool::Pfctl, &load_args(&self.anchor), Some(""));
release_pf(&run_tool, &self.token);
}
}
impl Capture<'_> {
fn offer(&self, use_upstream: bool) {
let ranges = [FIRST, SECOND]
.map(|ip| Ipv4Range::new(Ipv4Addr::from(u32::from(ip) & !0xf), 28).unwrap());
let rules = pf_rules(
self.overlay,
&self.uplink,
&ranges[..1],
use_upstream.then_some(&ClientRules {
uid: 0,
overlay: &ranges,
}),
);
acquire_pf(&run_tool, &self.token).unwrap();
run_ok(
&run_tool,
Tool::Pfctl,
&load_args(&self.anchor),
Some(&rules),
)
.unwrap();
enable_forwarding(&run_tool).unwrap();
}
fn enable(&mut self) {
self.offer(true);
run_ok(
&run_tool,
Tool::Route,
&scoped::marked_args("add", CAPTURE, &self.uplink, 114275),
None,
)
.unwrap();
self.added_scoped = true;
run_ok(
&run_tool,
Tool::Route,
&route_set_args("add", CAPTURE, self.overlay, Some(SECOND)),
None,
)
.unwrap();
self.added_route = true;
}
}
/// Ignore interface housekeeping and pure TCP ACKs while waiting for our packet.
async fn packet(
device: &dyn TunDevice,
destination: Ipv4Addr,
protocol: IpProtocol,
port: u16,
payload: &[u8],
) -> Bytes {
timeout(WAIT, async {
loop {
let raw = device.recv().await.expect("utun closed");
let Ok(ip) = Ipv4Packet::new_checked(&raw[..]) else {
continue;
};
if ip.version() != 4 || ip.dst_addr() != destination || ip.next_header() != protocol {
continue;
}
let matches = match protocol {
IpProtocol::Udp => UdpPacket::new_checked(ip.payload())
.is_ok_and(|udp| udp.dst_port() == port && udp.payload() == payload),
IpProtocol::Tcp => TcpPacket::new_checked(ip.payload()).is_ok_and(|tcp| {
tcp.dst_port() == port
&& tcp.payload() == payload
&& (tcp.syn() || !payload.is_empty())
}),
_ => false,
};
if matches {
return raw;
}
}
})
.await
.unwrap_or_else(|_| {
panic!(
"no {protocol} packet for {destination}:{port} on {}",
device.name()
)
})
}
fn reply(request: &[u8]) -> Bytes {
let ip = Ipv4Packet::new_checked(request).unwrap();
let tcp_request = (ip.next_header() == IpProtocol::Tcp)
.then(|| TcpPacket::new_checked(ip.payload()).unwrap());
// Acknowledge TCP SYNs and echo data so the test observes return traffic
// on the very socket that originated each flow.
let reply_ip = Ipv4Repr {
src_addr: ip.dst_addr(),
dst_addr: ip.src_addr(),
next_header: ip.next_header(),
payload_len: tcp_request
.as_ref()
.map_or(ip.payload().len(), |tcp| 20 + tcp.payload().len()),
hop_limit: 64,
};
let mut bytes = vec![0; reply_ip.buffer_len() + reply_ip.payload_len];
let mut out = Ipv4Packet::new_unchecked(&mut bytes[..]);
reply_ip.emit(&mut out, &Default::default());
let src = reply_ip.src_addr.into();
let dst = reply_ip.dst_addr.into();
if let Some(incoming) = tcp_request {
let mut tcp = TcpPacket::new_unchecked(out.payload_mut());
tcp.set_header_len(20);
tcp.set_src_port(incoming.dst_port());
tcp.set_dst_port(incoming.src_port());
tcp.set_syn(incoming.syn());
tcp.set_ack(true);
tcp.set_seq_number(if incoming.syn() {
TcpSeqNumber(100)
} else {
incoming.ack_number()
});
tcp.set_ack_number(incoming.seq_number() + incoming.segment_len());
tcp.set_window_len(8192);
tcp.payload_mut().copy_from_slice(incoming.payload());
tcp.fill_checksum(&src, &dst);
} else {
out.payload_mut().copy_from_slice(ip.payload());
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
let (src_port, dst_port) = (udp.dst_port(), udp.src_port());
udp.set_src_port(src_port);
udp.set_dst_port(dst_port);
udp.fill_checksum(&src, &dst);
}
bytes.into()
}
async fn open_tcp(uplink: &dyn TunDevice, port: u16) -> TcpStream {
let connect = TcpStream::connect((REMOTE, port));
let peer = async {
let syn = packet(uplink, REMOTE, IpProtocol::Tcp, port, &[]).await;
assert_eq!(
Ipv4Packet::new_checked(&syn[..]).unwrap().src_addr(),
UPLINK
);
uplink.send(reply(&syn)).await.unwrap();
};
let (stream, ()) = tokio::join!(timeout(WAIT, connect), peer);
stream.expect("SYN-ACK did not reach socket").unwrap()
}
fn check_capture_routes(overlay: &str, uplink: &str) {
for (scope, expected) in [(vec![], overlay), (owned(&["-ifscope", uplink]), uplink)] {
let mut args = owned(&["-n", "get"]);
args.extend(scope);
args.extend(owned(&["-net", CAPTURE]));
let output = run_ok(&run_tool, Tool::Route, &args, None).unwrap();
eprintln!("route {}:\n{output}", args.join(" "));
let actual = output
.lines()
.find_map(|line| line.trim().strip_prefix("interface: "));
assert_eq!(actual, Some(expected));
assert_eq!(output.contains("PROTO2"), expected == uplink);
assert_eq!(output.contains("IFSCOPE"), expected == uplink);
assert_eq!(
output.split_whitespace().any(|s| s == "114275"),
expected == uplink
);
}
}
async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str) {
let port = socket.peer_addr().unwrap().port();
eprintln!("{stage}: UDP {}", socket.local_addr().unwrap());
socket
.send(b"QUIC path")
.await
.unwrap_or_else(|e| panic!("{stage}: sending UDP: {e}"));
let raw = packet(uplink, REMOTE, IpProtocol::Udp, port, b"QUIC path").await;
let ip = Ipv4Packet::new_checked(&raw[..]).unwrap();
assert_eq!(ip.src_addr(), UPLINK);
assert_eq!(
UdpPacket::new_checked(ip.payload()).unwrap().src_port(),
socket.local_addr().unwrap().port()
);
uplink.send(reply(&raw)).await.unwrap();
let mut buf = [0; 64];
let len = timeout(WAIT, socket.recv(&mut buf))
.await
.expect("UDP reply did not reach socket")
.unwrap();
assert_eq!(&buf[..len], b"QUIC path");
}
async fn member_round_trip(
overlay: &dyn TunDevice,
uplink: &dyn TunDevice,
port: u16,
data: &[u8],
) -> u16 {
let member = Ipv4Addr::from(u32::from(FIRST) + 2);
let ip = Ipv4Repr {
src_addr: member,
dst_addr: REMOTE,
next_header: IpProtocol::Udp,
payload_len: 8 + data.len(),
hop_limit: 64,
};
let mut raw = vec![0; ip.buffer_len() + ip.payload_len];
let mut out = Ipv4Packet::new_unchecked(&mut raw[..]);
ip.emit(&mut out, &Default::default());
let mut udp = UdpPacket::new_unchecked(out.payload_mut());
udp.set_len(ip.payload_len as u16);
udp.set_src_port(port);
udp.set_dst_port(8020);
udp.payload_mut().copy_from_slice(data);
udp.fill_checksum(&member.into(), &REMOTE.into());
overlay.send(raw.into()).await.unwrap();
let outbound = packet(uplink, REMOTE, IpProtocol::Udp, 8020, data).await;
let physical = Ipv4Packet::new_checked(&outbound[..]).unwrap();
assert_eq!(physical.src_addr(), UPLINK);
let translated = UdpPacket::new_checked(physical.payload())
.unwrap()
.src_port();
uplink.send(reply(&outbound)).await.unwrap();
let inbound = packet(overlay, member, IpProtocol::Udp, port, data).await;
assert_eq!(
Ipv4Packet::new_checked(&inbound[..]).unwrap().src_addr(),
REMOTE
);
translated
}
#[tokio::test]
#[ignore = "requires root, the stock Apple PF anchor, and a disposable macOS runner"]
async fn exit_preserves_underlay_and_both_meshes() {
assert_eq!(agent_uid(&run_tool).unwrap(), 0);
let uplink = utun(&[UPLINK]).await;
let overlay = utun(&[FIRST, SECOND]).await;
let mut relay = open_tcp(&*uplink, 8001).await;
let existing_quic = UdpSocket::bind((UPLINK, 0)).await.unwrap();
existing_quic.connect((REMOTE, 8006)).await.unwrap();
udp_round_trip(&*uplink, &existing_quic, "before exit").await;
let mut capture = Capture {
overlay: overlay.name(),
uplink: DefaultRoute {
interface: uplink.name().to_owned(),
gateway: Some(Ipv4Addr::new(192, 0, 2, 2)),
},
anchor: anchor_name(overlay.name()).unwrap(),
token: Mutex::new(None),
added_route: false,
added_scoped: false,
};
// The local offer enables kernel forwarding. A keeps the same translated
// address and port when B installs an upstream route to this IP.
capture.offer(false);
let port = member_round_trip(&*overlay, &*uplink, 43001, b"member before").await;
capture.enable();
assert_eq!(
member_round_trip(&*overlay, &*uplink, 43001, b"member during").await,
port
);
member_round_trip(&*overlay, &*uplink, 43002, b"new member flow").await;
check_capture_routes(overlay.name(), uplink.name());
udp_round_trip(&*uplink, &existing_quic, "existing socket after exit").await;
// An already established relay must preserve its address and port.
relay.write_all(b"established relay").await.unwrap();
let established = packet(
&*uplink,
REMOTE,
IpProtocol::Tcp,
8001,
b"established relay",
)
.await;
let ip = Ipv4Packet::new_checked(&established[..]).unwrap();
let tcp = TcpPacket::new_checked(ip.payload()).unwrap();
assert_eq!(ip.src_addr(), UPLINK);
assert_eq!(tcp.src_port(), relay.local_addr().unwrap().port());
uplink.send(reply(&established)).await.unwrap();
let mut echo = [0; b"established relay".len()];
timeout(WAIT, relay.read_exact(&mut echo))
.await
.expect("established TCP reply did not reach socket")
.unwrap();
assert_eq!(&echo, b"established relay");
// The kernel selects the overlay source on new wildcard sockets. Real
// replies to the translated address must reach those same sockets.
let socket = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
socket.connect((REMOTE, 8002)).await.unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), SECOND);
udp_round_trip(&*uplink, &socket, "new socket after exit").await;
let new_relay = open_tcp(&*uplink, 8003).await;
assert_eq!(new_relay.local_addr().unwrap().ip(), SECOND);
// Same destination, ordinary UID: external traffic must enter the exit.
let program = "import socket, sys\nsocket.socket(socket.AF_INET, socket.SOCK_DGRAM).sendto(b'ordinary', (sys.argv[1], 8004))";
let mut child = tokio::process::Command::new("/usr/bin/python3");
child
.uid(65534)
.gid(65534)
.args(["-I", "-c", program, &REMOTE.to_string()])
.kill_on_drop(true);
assert!(
timeout(WAIT, child.status())
.await
.unwrap()
.unwrap()
.success()
);
let ordinary = packet(&*overlay, REMOTE, IpProtocol::Udp, 8004, b"ordinary").await;
assert_eq!(
Ipv4Packet::new_checked(&ordinary[..]).unwrap().src_addr(),
SECOND
);
// Root traffic to either mesh also stays on the overlay with its own alias.
let mesh = UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).await.unwrap();
for local in [FIRST, SECOND] {
let peer = Ipv4Addr::from(u32::from(local) + 1);
mesh.send_to(b"mesh", (peer, 8005)).await.unwrap();
let raw = packet(&*overlay, peer, IpProtocol::Udp, 8005, b"mesh").await;
assert_eq!(Ipv4Packet::new_checked(&raw[..]).unwrap().src_addr(), local);
}
}
@@ -0,0 +1,309 @@
//! Route ownership survives the process that installed the scoped physical
//! routes. A pre-existing compatible route may be used, never adopted.
use super::*;
use std::fs;
use std::io::{Read, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub(super) struct ScopedHalf {
half: u8,
egress: DefaultRoute,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
struct Journal {
marker: u32,
routes: Vec<ScopedHalf>,
ipv6: bool,
}
#[derive(Debug)]
pub(super) struct ScopedRoutes {
journal: Option<PathBuf>,
loaded: bool,
owned: Journal,
pub(super) active: Option<DefaultRoute>,
checked: Option<Instant>,
}
impl Default for ScopedRoutes {
fn default() -> Self {
Self {
journal: None,
loaded: false,
owned: Journal {
marker: rand::random_range(1..i32::MAX as u32),
routes: Vec::new(),
ipv6: false,
},
active: None,
checked: None,
}
}
}
pub(super) fn marked_args(
action: &str,
prefix: &str,
egress: &DefaultRoute,
marker: u32,
) -> Vec<String> {
let mut args = scoped_args(action, prefix, egress);
// Darwin exposes this otherwise unused route metric through RTM_GET.
// The nonce separates routes made by independent agents on the same uplink.
args.extend(["-hopcount".into(), marker.to_string()]);
args
}
pub(super) fn field<'a>(text: &'a str, key: &str) -> Option<&'a str> {
text.lines()
.filter_map(|l| l.trim().split_once(':'))
.find_map(|(k, v)| (k == key).then(|| v.trim()))
}
pub(super) fn flag(text: &str, name: &str) -> bool {
field(text, "flags").is_some_and(|v| v.trim_matches(['<', '>']).split(',').any(|f| f == name))
}
pub(super) fn marker(text: &str) -> Option<u32> {
let mut lines = text.lines();
while let Some(line) = lines.next() {
if let Some(i) = line.split_whitespace().position(|v| v == "hopcount") {
return lines.next()?.split_whitespace().nth(i)?.parse().ok();
}
}
None
}
/// A scoped lookup can return an unscoped LAN route or a default. Only an
/// exact scoped /1 on the requested interface can be ours.
fn inspect(
run: Run<'_>,
route: &ScopedHalf,
) -> Result<Option<(DefaultRoute, Option<u32>)>, String> {
let args = owned(&[
"-n",
"get",
"-ifscope",
&route.egress.interface,
"-net",
HALVES[route.half as usize],
]);
let text = match run_ok(run, Tool::Route, &args, None) {
Ok(text) => text,
Err(err)
if err.contains("not in table")
|| err.contains("No such process")
|| err.contains("bad interface name") =>
{
return Ok(None);
}
Err(err) => return Err(err),
};
let destination = field(&text, "destination");
let correct_half = match route.half {
0 => matches!(destination, Some("default" | "0.0.0.0")),
_ => destination == Some("128.0.0.0"),
};
if !correct_half || field(&text, "mask") != Some("128.0.0.0") || !flag(&text, "IFSCOPE") {
return Ok(None);
}
let actual = parse_default_route(&text).ok_or("could not read scoped route interface")?;
if actual.interface != route.egress.interface {
return Ok(None);
}
let mark = flag(&text, "PROTO2").then(|| marker(&text)).flatten();
Ok(Some((actual, mark)))
}
impl ScopedRoutes {
pub(super) fn with_journal(path: PathBuf) -> Self {
Self {
journal: Some(path),
..Self::default()
}
}
pub(super) fn load(&mut self) -> Result<(), String> {
if self.loaded {
return Ok(());
}
if let Some(path) = &self.journal {
match fs::File::open(path) {
Ok(file) => {
let mut bytes = Vec::new();
file.take(4097)
.read_to_end(&mut bytes)
.map_err(|e| e.to_string())?;
if bytes.len() > 4096 {
return Err("oversized macOS exit route journal".into());
}
let data: Journal = postcard::from_bytes(&bytes)
.map_err(|e| format!("invalid macOS exit route journal: {e}"))?;
if data.marker == 0
|| data.routes.len() > 8
|| data
.routes
.iter()
.any(|r| r.half > 1 || !safe_name(&r.egress.interface))
{
return Err("invalid macOS exit route ownership".into());
}
self.owned = data;
}
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
Err(err) => return Err(err.to_string()),
}
}
self.loaded = true;
Ok(())
}
fn save(&self) -> Result<(), String> {
let Some(path) = &self.journal else {
return Ok(());
};
if self.owned.routes.is_empty() && !self.owned.ipv6 {
return match fs::remove_file(path) {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e.to_string()),
};
}
let tmp = path.with_extension(format!("{}.tmp", rand::random::<u64>()));
let mut options = fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
let bytes = postcard::to_allocvec(&self.owned).map_err(|err| err.to_string())?;
let mut file = options.open(&tmp).map_err(|err| err.to_string())?;
let result = file.write_all(&bytes).and_then(|()| fs::rename(&tmp, path));
if result.is_err() {
let _ = fs::remove_file(tmp);
}
result.map_err(|e| e.to_string())
}
pub(super) fn previous(&self) -> Vec<ScopedHalf> {
self.owned.routes.clone()
}
pub(super) fn ipv6_marker(&self) -> Option<u32> {
self.owned.ipv6.then_some(self.owned.marker)
}
pub(super) fn record_ipv6(&mut self, active: bool) -> Result<u32, String> {
if self.owned.ipv6 != active {
self.owned.ipv6 = active;
if let Err(why) = self.save() {
self.owned.ipv6 = !active;
return Err(why);
}
}
Ok(self.owned.marker)
}
pub(super) fn desired(egress: &DefaultRoute) -> Vec<ScopedHalf> {
[0, 1]
.map(|half| ScopedHalf {
half,
egress: egress.clone(),
})
.into()
}
pub(super) fn check_due(&mut self, now: Instant) -> bool {
if self
.checked
.is_some_and(|last| now.duration_since(last) < Duration::from_secs(15))
{
return false;
}
self.checked = Some(now);
true
}
pub(super) fn ensure(&mut self, run: Run<'_>, wanted: &[ScopedHalf]) -> Result<(), String> {
for route in wanted {
let current = inspect(run, route)?;
let action = match current {
Some((actual, tag))
if actual == route.egress
&& (tag.is_none()
|| tag == Some(self.owned.marker)
&& self.owned.routes.contains(route)) =>
{
continue;
}
Some((actual, Some(tag)))
if tag == self.owned.marker
&& self.owned.routes.contains(&ScopedHalf {
half: route.half,
egress: actual.clone(),
}) =>
{
"change"
}
Some(_) => {
return Err(format!(
"scoped route {} on {} already belongs to another route owner",
HALVES[route.half as usize], route.egress.interface
));
}
None => "add",
};
if !self.owned.routes.contains(route) {
if self.owned.routes.len() >= 8 {
return Err("too many unreconciled scoped exit routes".into());
}
self.owned.routes.push(route.clone());
if let Err(reason) = self.save() {
self.owned.routes.pop();
return Err(reason);
}
}
run_ok(
run,
Tool::Route,
&marked_args(
action,
HALVES[route.half as usize],
&route.egress,
self.owned.marker,
),
None,
)?;
if inspect(run, route)? != Some((route.egress.clone(), Some(self.owned.marker))) {
return Err(format!(
"the scoped route for {} on {} failed ownership verification",
HALVES[route.half as usize], route.egress.interface
));
}
}
Ok(())
}
pub(super) fn retain(&mut self, run: Run<'_>, keep: &[ScopedHalf]) -> Result<(), String> {
for route in self.previous() {
if keep.contains(&route) {
continue;
}
if inspect(run, &route)? == Some((route.egress.clone(), Some(self.owned.marker))) {
run_ok(
run,
Tool::Route,
&scoped_args("delete", HALVES[route.half as usize], &route.egress),
None,
)?;
}
self.owned.routes.retain(|r| r != &route);
if let Err(reason) = self.save() {
self.owned.routes.push(route);
return Err(reason);
}
}
Ok(())
}
}
@@ -74,9 +74,22 @@ pub use windows::WindowsHostRules;
#[cfg(all(feature = "tun-device", target_os = "macos"))]
mod macos;
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
#[path = "macos/authorization.rs"]
mod macos_authorization;
#[cfg(any(test, target_os = "macos"))]
#[cfg_attr(
not(all(feature = "tun-device", target_os = "macos")),
allow(dead_code)
)]
mod macos_exit;
#[cfg(all(feature = "tun-device", target_os = "macos"))]
pub use macos::MacosHostRules;
#[cfg(target_os = "macos")]
pub use macos_authorization::{
authorize_macos_exit, macos_exit_authorization_uid, macos_exit_needs_authorization,
};
#[cfg(target_os = "macos")]
pub(in crate::overlay) use macos_exit::macos_default_uplink;
/// What the host should be told for one interface.
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -28,6 +28,10 @@
#![cfg_attr(not(target_os = "windows"), allow(dead_code))]
use crate::BoxFuture;
use std::collections::{BTreeMap, HashMap};
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
use super::windows_exit;
@@ -119,7 +123,7 @@ fn run_powershell(script: &str) -> Result<(), String> {
}
/// Runs a script and returns what it printed, or what it said on failure.
fn run_powershell_output(script: &str) -> Result<String, String> {
pub(super) fn run_powershell_output(script: &str) -> Result<String, String> {
let output = std::process::Command::new(powershell_path())
.args([
"-NoProfile",
@@ -153,12 +157,74 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
/// The Windows implementation, through PowerShell.
#[derive(Debug, Default)]
pub struct WindowsHostRules;
pub struct WindowsHostRules {
relay_cache: Arc<Mutex<RelayCache>>,
uplink: Arc<Mutex<Option<(u32, Ipv4Addr)>>>,
}
/// A temporary inventory failure cannot revoke existing sockets. A positive
/// withdrawal of the last offer releases their uplink.
fn remember_uplink(
cache: &Mutex<Option<(u32, Ipv4Addr)>>,
offering: bool,
observed: Option<(u32, Ipv4Addr)>,
) {
if !offering || observed.is_some() {
*cache.lock().unwrap_or_else(|e| e.into_inner()) = observed;
}
}
impl WindowsHostRules {
/// Creates it. Nothing is run until [`BroadcastHostRules::apply`].
pub fn new() -> Self {
Self
Self::default()
}
}
const REFRESH_INTERVAL: Duration = Duration::from_secs(30);
const DNS_GRACE: Duration = Duration::from_secs(120);
const MAX_RELAY_ADDRESSES: usize = 16;
/// DNS may rotate while the old relay connection is still carrying packets.
/// Keep recent answers for the relays still in use, with a fixed expiry and cap.
#[derive(Debug, Default)]
struct RelayCache {
hosts: HashMap<String, BTreeMap<Ipv4Addr, Instant>>,
last_refresh: Option<Instant>,
}
impl RelayCache {
fn lookup(
&mut self,
hosts: &[String],
now: Instant,
resolve: windows_exit::Resolve<'_>,
) -> HashMap<String, Vec<Ipv4Addr>> {
self.hosts.retain(|host, _| hosts.contains(host));
let due = self
.last_refresh
.is_none_or(|last| now.duration_since(last) >= REFRESH_INTERVAL);
for host in hosts {
let known = self.hosts.entry(host.clone()).or_default();
known.retain(|_, seen| now.duration_since(*seen) < DNS_GRACE);
if due || known.is_empty() {
for address in resolve(host).into_iter().take(MAX_RELAY_ADDRESSES) {
known.insert(address, now);
}
while known.len() > MAX_RELAY_ADDRESSES {
if let Some((&oldest, _)) = known.iter().min_by_key(|(_, seen)| **seen) {
known.remove(&oldest);
}
}
}
}
if due {
self.last_refresh = Some(now);
}
self.hosts
.iter()
.map(|(host, addresses)| (host.clone(), addresses.keys().copied().collect()))
.collect()
}
}
@@ -173,12 +239,17 @@ fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
IpAddr::V4(ip) => Some(ip),
IpAddr::V6(_) => None,
})
.take(MAX_RELAY_ADDRESSES)
.collect()
})
.unwrap_or_default()
}
impl ExitHostRules for WindowsHostRules {
fn forwarded_uplink(&self) -> Option<(u32, Ipv4Addr)> {
*self.uplink.lock().unwrap_or_else(|e| e.into_inner())
}
fn needs_bypass(&self) -> bool {
true
}
@@ -186,12 +257,21 @@ impl ExitHostRules for WindowsHostRules {
fn apply<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, ExitHostReport> {
Box::pin(async move {
let job = plan.clone();
let cache = Arc::clone(&self.relay_cache);
let uplink = Arc::clone(&self.uplink);
tokio::task::spawn_blocking(move || {
windows_exit::apply_plan(
&|script| run_powershell_output(script),
let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup(
&job.bypass_hosts,
Instant::now(),
&resolve_host,
);
let (report, physical) = windows_exit::reconcile(
&|script| run_powershell_output(script),
&|host| hosts.get(host).cloned().unwrap_or_default(),
&job,
)
);
remember_uplink(&uplink, !job.offer.is_empty(), physical);
report
})
.await
.unwrap_or_else(|err| {
@@ -209,10 +289,59 @@ impl ExitHostRules for WindowsHostRules {
})
}
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
Box::pin(async move {
if !plan.client && plan.offer.is_empty() {
return None;
}
let job = plan.clone();
let cache = Arc::clone(&self.relay_cache);
let uplink = Arc::clone(&self.uplink);
tokio::task::spawn_blocking(move || {
let now = Instant::now();
let mut cache = cache.lock().unwrap_or_else(|p| p.into_inner());
if cache
.last_refresh
.is_some_and(|last| now.duration_since(last) < REFRESH_INTERVAL)
{
return None;
}
let hosts = cache.lookup(&job.bypass_hosts, now, &resolve_host);
drop(cache);
if !job.offer.is_empty() {
remember_uplink(
&uplink,
true,
windows_exit::uplink(&run_powershell_output, &job.interface).ok(),
);
}
if !job.client {
return None;
}
Some(
match windows_exit::refresh_bypass(
&run_powershell_output,
&|host| hosts.get(host).cloned().unwrap_or_default(),
&job,
) {
Ok(()) => RuleOutcome::Applied,
Err(reason) => RuleOutcome::Failed(reason),
},
)
})
.await
.unwrap_or_else(|err| Some(RuleOutcome::Failed(format!("the task failed: {err}"))))
})
}
fn clear<'a>(&'a self, interface: &'a str) -> BoxFuture<'a, ()> {
Box::pin(async move {
let name = interface.to_string();
let cache = Arc::clone(&self.relay_cache);
let uplink = Arc::clone(&self.uplink);
let _ = tokio::task::spawn_blocking(move || {
*uplink.lock().unwrap_or_else(|e| e.into_inner()) = None;
*cache.lock().unwrap_or_else(|p| p.into_inner()) = RelayCache::default();
windows_exit::clear_all(&|script| run_powershell_output(script), &name)
})
.await;
@@ -258,6 +387,45 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
#[test]
fn transient_uplink_lookup_failure_preserves_the_live_forwarding_address() {
let cache = Mutex::new(None);
let old = (4, Ipv4Addr::new(192, 0, 2, 5));
let new = (7, Ipv4Addr::new(198, 51, 100, 3));
for (offering, observed, expected) in [
(true, Some(old), Some(old)),
(true, None, Some(old)),
(true, Some(new), Some(new)),
(false, None, None),
] {
remember_uplink(&cache, offering, observed);
assert_eq!(*cache.lock().unwrap(), expected);
}
}
#[test]
fn relay_dns_survives_a_transient_failure_and_retires_rotated_addresses() {
use std::time::{Duration, Instant};
let mut cache = RelayCache::default();
let hosts = vec!["relay.example".into()];
let old = [192, 0, 2, 1].into();
let new = [192, 0, 2, 2].into();
let now = Instant::now();
assert_eq!(cache.lookup(&hosts, now, &|_| vec![old])[&hosts[0]], [old]);
let later = |secs| now + Duration::from_secs(secs);
assert_eq!(
cache.lookup(&hosts, later(32), &|_| Vec::new())[&hosts[0]],
[old]
);
let rotated = cache.lookup(&hosts, later(64), &|_| vec![new]);
assert!(rotated[&hosts[0]].contains(&old) && rotated[&hosts[0]].contains(&new));
assert_eq!(
cache.lookup(&hosts, later(121), &|_| vec![new])[&hosts[0]],
[new]
);
assert!(cache.lookup(&[], later(122), &|_| Vec::new()).is_empty());
}
use std::net::Ipv4Addr;
fn plan() -> BroadcastRulesPlan {
@@ -1,4 +1,4 @@
//! Exit-node host rules on Windows: WinNAT through PowerShell.
//! Physical exit socket selection and client routes on Windows, through PowerShell.
//!
//! Compiled on every platform so the scripts and the plan logic are tested
//! everywhere; only `WindowsHostRules` runs them, and only on Windows. It
@@ -6,20 +6,10 @@
//!
//! # Offering
//!
//! One NAT object per offered range, named with the usual tag
//! `tsunagi-exit:<if>:<range>`:
//!
//! ```text
//! New-NetNat -Name <tag> -InternalIPInterfaceAddressPrefix <range>
//! ```
//!
//! WinNAT translates that range out of whichever interface the traffic leaves
//! by, which is the Windows counterpart of the Linux masquerade. Windows
//! forwards per interface, and the egress is not known here, so forwarding is
//! only *read* for the overlay interface; turning it on for the interfaces
//! involved is the owner's decision (`Set-NetIPInterface -Forwarding Enabled`).
//! Some Windows versions allow a single NAT per host: a second offered range
//! then reports its own failure.
//! Forwarded TCP/UDP and ICMP echo use sockets pinned to the physical
//! interface and address. This keeps a member's traffic independent of local
//! split routes even for the same destination. The userspace gateway owns the
//! flows; changing a local upstream does not recreate them.
//!
//! # Using
//!
@@ -51,7 +41,7 @@
use super::RuleOutcome;
use std::net::Ipv4Addr;
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag, exit_tag_prefix};
use super::exit::{ExitHostPlan, ExitHostReport, exit_tag_prefix};
use crate::state::Ipv4Range;
/// The route metric that marks a bypass route as this agent's.
@@ -68,60 +58,67 @@ fn ps_literal(value: &str) -> String {
format!("'{}'", value.replace('\'', "''"))
}
/// Creates the NAT of one range, replacing one this agent made before.
fn nat_script(interface: &str, range: &Ipv4Range) -> String {
let name = ps_literal(&exit_tag(interface, range));
let prefix = ps_literal(&range.to_string());
format!(
"$ErrorActionPreference = 'Stop'\n\
$name = {name}\n\
Get-NetNat -Name $name -ErrorAction SilentlyContinue | \
Remove-NetNat -Confirm:$false -ErrorAction SilentlyContinue\n\
New-NetNat -Name $name -InternalIPInterfaceAddressPrefix {prefix} | Out-Null\n"
)
}
/// Removes this interface's NAT objects except those named in `keep`.
fn prune_script(interface: &str, keep: &[Ipv4Range]) -> String {
/// Remove only obsolete WinNAT objects created by older Tsunagi releases.
fn legacy_nat_cleanup(interface: &str) -> String {
let prefix = ps_literal(&exit_tag_prefix(interface));
let keep: Vec<String> = keep
.iter()
.map(|range| ps_literal(&exit_tag(interface, range)))
.collect();
format!(
"$ErrorActionPreference = 'SilentlyContinue'\n\
$prefix = {prefix}\n\
$keep = @({})\n\
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) -and \
($keep -notcontains $_.Name) }} | Remove-NetNat -Confirm:$false\n\
exit 0\n",
keep.join(", ")
$prefix = {prefix}\n\
Get-NetNat | Where-Object {{ $_.Name.StartsWith($prefix) }} | Remove-NetNat -Confirm:$false\n\
exit 0"
)
}
/// Prints `Enabled` or `Disabled` for the interface's IPv4 forwarding.
fn forwarding_script(interface: &str) -> String {
/// Both client bypasses and forwarded sockets use the winning /0 outside Wintun.
fn select_gateway(interface: &str) -> String {
let alias = ps_literal(interface);
format!(
"$ErrorActionPreference = 'Stop'\n\
(Get-NetIPInterface -InterfaceAlias {alias} -AddressFamily IPv4).Forwarding\n"
$alias = {alias}\n\
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
$_.NextHop -ne '0.0.0.0' -and $_.State -ne 'Dead' }} | Sort-Object {{ $_.RouteMetric + \
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
Select-Object -First 1\n\
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n"
)
}
/// Prints `<interface index> <next hop>` of the best default route that is
/// not through the overlay interface.
/// Read a usable source on the selected physical interface, even while the two
/// client /1 routes point at Wintun. Never ask the default via the test target.
fn uplink_script(interface: &str) -> String {
format!(
"{}$source = Get-NetIPAddress -InterfaceIndex $best.InterfaceIndex -AddressFamily IPv4 \
-AddressState Preferred | Where-Object {{ -not $_.SkipAsSource }} | Select-Object -First 1\n\
if (-not $source) {{ throw 'the physical interface has no usable IPv4 address' }}\n\
\"$($best.InterfaceIndex) $($source.IPAddress)\"",
select_gateway(interface)
)
}
pub(super) fn uplink(run: RunScript<'_>, interface: &str) -> Result<(u32, Ipv4Addr), String> {
let text = run(&uplink_script(interface))?;
parse_gateway(&text)
.filter(|(i, ip)| {
*i != 0
&& !ip.is_unspecified()
&& !ip.is_multicast()
&& !ip.is_loopback()
&& !ip.is_broadcast()
})
.ok_or_else(|| {
"cannot determine the physical interface and IPv4 source for forwarding".into()
})
}
fn gateway_script(interface: &str) -> String {
let alias = ps_literal(interface);
format!(
"$ErrorActionPreference = 'Stop'\n\
$alias = {alias}\n\
$best = Get-NetRoute -DestinationPrefix '0.0.0.0/0' -AddressFamily IPv4 \
-PolicyStore ActiveStore | Where-Object {{ $_.InterfaceAlias -ne $alias -and \
$_.NextHop -ne '0.0.0.0' }} | Sort-Object {{ $_.RouteMetric + \
(Get-NetIPInterface -InterfaceIndex $_.InterfaceIndex -AddressFamily IPv4).InterfaceMetric }} | \
Select-Object -First 1\n\
if (-not $best) {{ throw 'the host has no default gateway outside the overlay' }}\n\
\"$($best.InterfaceIndex) $($best.NextHop)\"\n"
"{}\"$($best.InterfaceIndex) $($best.NextHop)\"\n\
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{ \
$_.InterfaceAlias -ne $alias -and $_.State -ne 'Dead' -and \
-not ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32')) }} | \
Select-Object -ExpandProperty DestinationPrefix\n",
select_gateway(interface)
)
}
@@ -141,13 +138,18 @@ fn bypass_script(index: u32, gateway: Ipv4Addr, addresses: &[Ipv4Addr]) -> Strin
.collect();
format!(
"$ErrorActionPreference = 'Stop'\n\
$keep = @(@({}) | ForEach-Object {{ \"$_/32\" }})\n\
foreach ($p in $keep) {{\n\
if (-not (Get-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue)) {{\n\
New-NetRoute -DestinationPrefix $p -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore | Out-Null\n\
}}\n\
}}\n\
Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | \
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
foreach ($ip in @({})) {{\n\
New-NetRoute -DestinationPrefix \"$ip/32\" -InterfaceIndex {index} -NextHop '{gateway}' \
-RouteMetric {BYPASS_METRIC} -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n",
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32') -and \
($keep -notcontains $_.DestinationPrefix -or $_.InterfaceIndex -ne {index} -or $_.NextHop -ne '{gateway}') }} | \
Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n",
list.join(", ")
)
}
@@ -159,14 +161,14 @@ fn halves_script(interface: &str) -> String {
"$ErrorActionPreference = 'Stop'\n\
$alias = {alias}\n\
foreach ($p in '0.0.0.0/1', '128.0.0.0/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '0.0.0.0' \
-RouteMetric 1 -PolicyStore ActiveStore | Out-Null\n\
}}\n\
foreach ($p in '::/1', '8000::/1') {{\n\
Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -PolicyStore ActiveStore \
-ErrorAction SilentlyContinue | Remove-NetRoute -Confirm:$false -ErrorAction SilentlyContinue\n\
if (Get-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{ continue }}\n\
New-NetRoute -DestinationPrefix $p -InterfaceAlias $alias -NextHop '::' \
-RouteMetric 1 -PolicyStore ActiveStore -ErrorAction SilentlyContinue | Out-Null\n\
}}\n"
@@ -197,27 +199,60 @@ fn bypass_addresses(
resolve: Resolve<'_>,
addresses: &[Ipv4Addr],
hosts: &[String],
overlay: &[Ipv4Range],
) -> Vec<Ipv4Addr> {
let mut all: std::collections::BTreeSet<Ipv4Addr> = addresses.iter().copied().collect();
for host in hosts {
all.extend(resolve(host));
}
all.into_iter()
.filter(|a| !a.is_loopback() && !a.is_unspecified() && !a.is_multicast())
.filter(|a| {
!a.is_loopback()
&& !a.is_unspecified()
&& !a.is_multicast()
&& !a.is_link_local()
&& !a.is_broadcast()
&& !overlay.iter().any(|range| range.contains(*a))
})
.collect()
}
pub(super) fn refresh_bypass(
run: RunScript<'_>,
resolve: Resolve<'_>,
plan: &ExitHostPlan,
) -> Result<(), String> {
let interface = plan.interface.as_str();
let gateway = run(&gateway_script(interface))?;
let mut lines = gateway.lines();
let first = lines.next().unwrap_or_default();
let (index, hop) = parse_gateway(first)
.ok_or_else(|| format!("cannot read the default gateway from `{first}`"))?;
let mut addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts, &plan.overlay);
for line in lines {
let prefix = line.trim();
let (network, bits) = prefix
.split_once('/')
.and_then(|(address, bits)| {
Some((address.parse::<Ipv4Addr>().ok()?, bits.parse::<u8>().ok()?))
})
.filter(|(_, bits)| *bits <= 32)
.ok_or_else(|| format!("cannot read physical route prefix `{prefix}`"))?;
if bits > 1 {
let mask = u32::MAX << (32 - bits);
addresses.retain(|addr| u32::from(*addr) & mask != u32::from(network) & mask);
}
}
run(&bypass_script(index, hop, &addresses)).map(|_| ())
}
fn apply_client(
run: RunScript<'_>,
resolve: Resolve<'_>,
plan: &ExitHostPlan,
) -> Result<(), String> {
let interface = plan.interface.as_str();
let gateway = run(&gateway_script(interface))?;
let (index, hop) = parse_gateway(&gateway)
.ok_or_else(|| format!("cannot read the default gateway from `{}`", gateway.trim()))?;
let addresses = bypass_addresses(resolve, &plan.bypass, &plan.bypass_hosts);
run(&bypass_script(index, hop, &addresses))?;
refresh_bypass(run, resolve, plan)?;
let interface = &plan.interface;
if let Err(why) = run(&halves_script(interface)) {
// Do not leave a half-installed set: bypass routes alone are harmless
// but the next apply starts clean.
@@ -227,35 +262,25 @@ fn apply_client(
Ok(())
}
fn parse_forwarding(text: &str) -> Option<bool> {
match text.trim().to_ascii_lowercase().as_str() {
"enabled" | "1" => Some(true),
"disabled" | "0" => Some(false),
_ => None,
}
}
/// Makes the host match the plan.
pub(super) fn apply_plan(
/// Decide the egress for all offered memberships, then reconcile the separate
/// destination routes used by this device's applications.
pub(super) fn reconcile(
run: RunScript<'_>,
resolve: Resolve<'_>,
plan: &ExitHostPlan,
) -> ExitHostReport {
) -> (ExitHostReport, Option<(u32, Ipv4Addr)>) {
let interface = plan.interface.as_str();
// What an earlier plan left and this one no longer wants.
let pruned = run(&prune_script(interface, &plan.offer));
let physical = (!plan.offer.is_empty()).then(|| uplink(run, interface));
let offer = plan
.offer
.iter()
.map(|range| {
let outcome = match &pruned {
Err(why) => RuleOutcome::Failed(why.clone()),
Ok(_) => match run(&nat_script(interface, range)) {
Ok(_) => RuleOutcome::Applied,
Err(why) => RuleOutcome::Failed(why),
},
let result = match &physical {
Some(Ok(_)) => RuleOutcome::Applied,
Some(Err(why)) => RuleOutcome::Failed(why.clone()),
None => RuleOutcome::Failed("no exit offer".into()),
};
(*range, outcome)
(*range, result)
})
.collect();
let client = if plan.client {
@@ -268,23 +293,19 @@ pub(super) fn apply_plan(
let _ = run(&remove_client_script(interface));
None
};
let forwarding = if plan.offer.is_empty() {
None
} else {
run(&forwarding_script(interface))
.ok()
.and_then(|text| parse_forwarding(&text))
};
ExitHostReport {
offer,
forwarding,
client,
}
(
ExitHostReport {
offer,
forwarding: None,
client,
},
physical.and_then(Result::ok),
)
}
/// Removes every NAT object of this agent's for the interface.
pub(super) fn clear_all(run: RunScript<'_>, interface: &str) {
if let Err(why) = run(&prune_script(interface, &[])) {
if let Err(why) = run(&legacy_nat_cleanup(interface)) {
tracing::warn!(interface, "cannot remove the exit node NAT: {why}");
}
if let Err(why) = run(&remove_client_script(interface)) {
@@ -315,90 +336,109 @@ mod tests {
}
#[test]
fn the_nat_is_named_with_the_tag_and_replaces_its_own() {
let script = nat_script("tsun0", &range());
assert!(
script.contains("$name = 'tsunagi-exit:tsun0:10.13.37.0/24'"),
"{script}"
);
assert!(script.contains("-InternalIPInterfaceAddressPrefix '10.13.37.0/24'"));
assert!(
script.find("Remove-NetNat").unwrap() < script.find("New-NetNat").unwrap(),
"{script}"
);
}
#[test]
fn a_quote_in_a_value_cannot_escape_the_literal() {
let script = nat_script("x'; Remove-Item C:\\ #", &range());
assert!(script.contains("'tsunagi-exit:x''; Remove-Item C:\\ #:10.13.37.0/24'"));
assert!(prune_script("x'y", &[]).contains("'tsunagi-exit:x''y:'"));
assert!(forwarding_script("x'y").contains("'x''y'"));
}
#[test]
fn pruning_keeps_wanted_ranges_and_only_selects_this_interfaces_nats() {
let script = prune_script("tsun0", &[range()]);
assert!(script.contains("$prefix = 'tsunagi-exit:tsun0:'"));
assert!(script.contains("$keep = @('tsunagi-exit:tsun0:10.13.37.0/24')"));
assert!(script.contains("StartsWith($prefix)"));
assert!(script.contains("exit 0"));
assert!(prune_script("tsun0", &[]).contains("$keep = @()"));
}
#[test]
fn forwarding_text_is_read_never_written() {
assert_eq!(parse_forwarding("Enabled\r\n"), Some(true));
assert_eq!(parse_forwarding("Disabled"), Some(false));
assert_eq!(parse_forwarding("what"), None);
let script = forwarding_script("tsun0");
assert!(script.contains("Get-NetIPInterface"));
assert!(!script.contains("Set-NetIPInterface"));
}
#[test]
fn offering_prunes_then_creates_and_reads_forwarding() {
fn selecting_an_upstream_never_recreates_a_forwarded_session_or_installs_a_destination_exception()
{
let calls = RefCell::new(Vec::new());
let run = |script: &str| -> Result<String, String> {
calls.borrow_mut().push(script.to_string());
Ok(if script.contains("Get-NetIPInterface") {
"Disabled\n".to_string()
Ok(if script.contains("Get-NetIPAddress") {
"7 192.0.2.15".into()
} else if script.contains("Select-Object -ExpandProperty DestinationPrefix") {
"7 192.0.2.1".into()
} else {
String::new()
})
};
let report = apply_plan(&run, &no_names, &plan(false));
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
assert_eq!(report.forwarding, Some(false));
assert_eq!(report.client, None);
let calls = calls.borrow();
assert!(calls[0].contains("StartsWith"), "{calls:?}");
assert!(calls[1].contains("New-NetNat"), "{calls:?}");
// Without a client, the routes of an earlier plan are taken away.
assert!(calls[2].contains("RouteMetric -eq 7373"), "{calls:?}");
assert!(calls[3].contains("Get-NetIPInterface"), "{calls:?}");
for client in [false, true, false] {
let (report, physical) = reconcile(&run, &no_names, &plan(client));
assert_eq!(physical, Some((7, "192.0.2.15".parse().unwrap())));
assert_eq!(report.offer, vec![(range(), RuleOutcome::Applied)]);
assert_eq!(report.forwarding, None);
}
assert!(
!calls
.borrow()
.iter()
.any(|s| s.contains("NetNat") || s.contains("Set-NetIPInterface"))
);
assert!(uplink_script("x'y").contains("'x''y'"));
}
#[test]
fn a_failing_nat_is_that_ranges_failure() {
let run = |script: &str| -> Result<String, String> {
if script.contains("New-NetNat") {
Err("A NAT with this prefix already exists".into())
} else {
Ok(String::new())
}
};
let report = apply_plan(&run, &no_names, &plan(false));
let RuleOutcome::Failed(why) = &report.offer[0].1 else {
panic!("{report:?}");
};
assert!(why.contains("already exists"), "{why}");
fn failure_to_find_a_physical_source_never_advertises_a_working_exit() {
for line in [
"",
"0 198.51.100.3",
"5 0.0.0.0",
"5 127.0.0.1",
"3 10.0.0.1 extra",
] {
let (report, physical) = reconcile(&|_| Ok(line.into()), &no_names, &plan(false));
assert_eq!(physical, None);
assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_)));
}
}
fn apply_plan(run: RunScript<'_>, resolve: Resolve<'_>, plan: &ExitHostPlan) -> ExitHostReport {
reconcile(run, resolve, plan).0
}
fn no_names(_: &str) -> Vec<Ipv4Addr> {
Vec::new()
}
/// Run the real refresh against the Windows ActiveStore. The fixture
/// only permits its TEST-NET /32 and refuses to prune pre-existing routes.
#[cfg(windows)]
#[test]
#[ignore = "requires an elevated disposable Windows runner with a physical default gateway"]
fn windows_refresh_installs_only_the_external_test_address() {
use super::super::windows::run_powershell_output;
let target = Ipv4Addr::new(198, 51, 100, 207);
let inventory = run_powershell_output(&gateway_script("tsng-native-test")).unwrap();
let (index, gateway) = parse_gateway(inventory.lines().next().unwrap()).unwrap();
let plan = ExitHostPlan {
interface: "tsng-native-test".into(),
bypass: vec![gateway, target],
client: true,
..Default::default()
};
let run = |script: &str| {
if script == gateway_script(&plan.interface) {
return Ok(inventory.clone());
}
// Catch a failure to recognize the gateway's connected LAN before
// executing a script which might create a route to the gateway.
assert!(script.contains(&format!("$keep = @(@('{target}') |")));
let guarded = format!(
r#"$ErrorActionPreference = 'Stop'
$prefix = '{target}/32'
$before = @(Get-NetRoute -AddressFamily IPv4 -PolicyStore ActiveStore | Where-Object {{
$_.DestinationPrefix -eq $prefix -or ($_.RouteMetric -eq {BYPASS_METRIC} -and $_.DestinationPrefix.EndsWith('/32'))
}})
if ($before.Count) {{ throw 'fixture requires an unused test prefix and no pre-existing bypass routes' }}
try {{
{script}
$actual = @(Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction Stop)
if ($actual.Count -ne 1 -or $actual[0].InterfaceIndex -ne {index} -or
$actual[0].NextHop -ne '{gateway}' -or $actual[0].RouteMetric -ne {BYPASS_METRIC}) {{
throw 'unexpected physical bypass route'
}}
}} finally {{
Get-NetRoute -DestinationPrefix $prefix -InterfaceIndex {index} -NextHop '{gateway}' -PolicyStore ActiveStore -ErrorAction SilentlyContinue |
Where-Object {{ $_.RouteMetric -eq {BYPASS_METRIC} }} | Remove-NetRoute -Confirm:$false
}}
if (Get-NetRoute -DestinationPrefix $prefix -PolicyStore ActiveStore -ErrorAction SilentlyContinue) {{
throw 'test route still present after cleanup'
}}
exit 0"#
);
run_powershell_output(&guarded)
};
refresh_bypass(&run, &no_names, &plan).unwrap();
}
fn client_plan() -> ExitHostPlan {
ExitHostPlan {
interface: "tsun0".into(),
@@ -437,8 +477,10 @@ mod tests {
assert!(script.contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
assert!(script.contains("-RouteMetric 7373"));
assert!(script.contains("-PolicyStore ActiveStore"));
// Stale marked routes go first, and only /32 ones with our metric.
assert!(script.find("Remove-NetRoute").unwrap() < script.find("New-NetRoute").unwrap());
// Install missing routes before pruning stale entries. Existing paths
// continue carrying the tunnel throughout another network's update.
assert!(script.find("New-NetRoute").unwrap() < script.find("Remove-NetRoute").unwrap());
assert!(script.contains("$keep -notcontains $_.DestinationPrefix"));
assert!(script.contains("RouteMetric -eq 7373"));
assert!(script.contains("EndsWith('/32')"));
}
@@ -446,6 +488,10 @@ mod tests {
#[test]
fn the_halves_go_through_the_overlay_and_ipv6_is_blackholed() {
let script = halves_script("tsun0");
assert!(
!script.contains("Remove-NetRoute"),
"reapplying must keep existing split defaults: {script}"
);
assert!(script.contains("'0.0.0.0/1', '128.0.0.0/1'"));
assert!(script.contains("-InterfaceAlias $alias -NextHop '0.0.0.0'"));
assert!(script.contains("'::/1', '8000::/1'"));
@@ -473,6 +519,7 @@ mod tests {
Ipv4Addr::UNSPECIFIED,
],
&["relay.example".into(), "gone.example".into()],
&[],
);
assert_eq!(
all,
@@ -505,12 +552,77 @@ mod tests {
);
}
#[test]
fn relay_dns_cannot_install_a_host_route_over_either_overlay() {
let mut plan = client_plan();
plan.overlay.push("10.99.0.0/24".parse().unwrap());
let resolve = |_: &str| {
["10.13.37.4", "10.99.0.6", "9.9.9.9"]
.map(|ip| ip.parse().unwrap())
.to_vec()
};
let calls = RefCell::new(Vec::new());
let run = |script: &str| {
calls.borrow_mut().push(script.to_string());
Ok("12 192.168.1.1".to_string())
};
apply_client(&run, &resolve, &plan).unwrap();
let calls = calls.borrow();
let bypass = calls
.iter()
.find(|c| c.contains("-RouteMetric 7373"))
.unwrap();
assert!(bypass.contains("'9.9.9.9'") && bypass.contains("'138.201.61.182'"));
assert!(!bypass.contains("'10.13.37.4'") && !bypass.contains("'10.99.0.6'"));
}
#[test]
fn a_connected_lan_and_an_existing_host_route_stay_on_their_own_paths() {
let mut plan = client_plan();
for addr in ["192.168.1.11", "198.51.100.7", "198.51.100.9"] {
plan.bypass.push(addr.parse().unwrap());
}
let calls = RefCell::new(Vec::new());
let run = |script: &str| {
calls.borrow_mut().push(script.to_string());
Ok("12 192.168.1.1\n192.168.1.0/24\n198.51.100.7/32\n".into())
};
apply_client(&run, &no_names, &plan).unwrap();
let calls = calls.borrow();
let bypass = calls.iter().find(|s| s.contains("New-NetRoute")).unwrap();
assert!(!bypass.contains("'192.168.1.11'"));
assert!(!bypass.contains("'198.51.100.7'"));
assert!(bypass.contains("'198.51.100.9'"));
}
#[test]
fn refreshing_uses_the_new_physical_gateway_without_touching_the_exit_routes() {
let plan = client_plan();
let routes = RefCell::new(Vec::new());
for gateway in ["12 192.168.1.1", "17 10.0.0.1"] {
let run = |script: &str| {
if script.contains("Select-Object -First 1") {
Ok(gateway.into())
} else {
routes.borrow_mut().push(script.to_owned());
Ok(String::new())
}
};
refresh_bypass(&run, &no_names, &plan).unwrap();
}
let routes = routes.into_inner();
assert_eq!(routes.len(), 2);
assert!(routes[0].contains("-InterfaceIndex 12 -NextHop '192.168.1.1'"));
assert!(routes[1].contains("-InterfaceIndex 17 -NextHop '10.0.0.1'"));
assert!(routes.iter().all(|s| !s.contains("'0.0.0.0/1'")));
}
#[test]
fn nothing_goes_through_the_overlay_when_the_bypass_cannot_be_written() {
let run = |script: &str| -> Result<String, String> {
if script.contains("Select-Object -First 1") {
Ok("12 192.168.1.1".to_string())
} else if script.contains("-RouteMetric 7373") && script.contains("foreach ($ip") {
} else if script.contains("-RouteMetric 7373") && script.contains("New-NetRoute") {
Err("Access is denied".to_string())
} else {
assert!(!script.contains("-NextHop '0.0.0.0'"), "{script}");
@@ -598,7 +710,7 @@ mod tests {
};
clear_all(&run, "tsun0");
let seen = seen.borrow();
assert!(seen[0].contains("$keep = @()"));
assert!(seen[0].contains("StartsWith($prefix)"));
assert!(seen[0].contains("'tsunagi-exit:tsun0:'"));
}
}
+506 -61
View File
@@ -28,6 +28,7 @@ use iroh::EndpointId;
use tokio::task::JoinHandle;
use crate::identity::NetworkId;
use crate::traffic::{Direction, Role};
use super::exit::{ExitRulesReport, RuleSetReport};
use super::hostrules::{
@@ -35,7 +36,7 @@ use super::hostrules::{
RuleOutcome, offer_detail,
};
use super::packet::IpHeader;
use super::router::{Route, RoutingTable};
use super::router::{PacketSource, Route, RoutingTable};
use super::tun::{TunDevice, TunFactory, TunRequest};
use super::{Cidr, OverlayError};
@@ -147,15 +148,15 @@ impl Tally {
/// The overlay interface.
pub struct Interface {
device: Arc<dyn TunDevice>,
#[cfg(any(windows, target_os = "macos"))]
forwarding: Option<super::egress::Gateway>,
factory: Arc<dyn TunFactory>,
name: String,
mtu: u32,
routes: Arc<RoutingTable>,
carrier: Arc<dyn PacketCarrier>,
tally: Arc<Tally>,
/// What was last applied to the host, so an unchanged table is not
/// re-applied on every pass.
applied: std::sync::Mutex<Vec<Cidr>>,
addresses: std::sync::Mutex<AddressState>,
task: std::sync::Mutex<Option<JoinHandle<()>>>,
vip_task: std::sync::Mutex<Option<JoinHandle<()>>>,
sync_lock: Arc<tokio::sync::Mutex<()>>,
@@ -171,6 +172,13 @@ pub struct Interface {
underlay: std::sync::Mutex<std::collections::HashMap<NetworkId, Underlay>>,
}
/// Addresses and subnet routes are applied together. A partial change
/// invalidates the cached plan until the whole interface reconciles again.
struct AddressState {
applied: Option<Vec<Cidr>>,
last_error: Option<String>,
}
/// Underlay destinations one network's runtime currently depends on.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
struct Underlay {
@@ -219,8 +227,24 @@ impl Interface {
carrier: Arc<dyn PacketCarrier>,
) -> Result<Self, OverlayError> {
let name = name.into();
let request = TunRequest::bare(name.clone(), mtu);
let device = factory.create(request.clone()).await;
#[cfg(target_os = "macos")]
let (factory, device, use_sockets) = match device {
Err(OverlayError::UtunDenied(reason)) if factory.on_host() => {
tracing::warn!(%reason,"system utun unavailable; exit sharing will use physical sockets");
let sockets: Arc<dyn TunFactory> =
Arc::new(super::egress::macos::SocketExit::default());
let device = sockets.create(request).await?;
(sockets, device, true)
}
result => (factory, result?, false),
};
#[cfg(not(target_os = "macos"))]
let device = device?;
#[cfg(windows)]
let use_sockets = factory.on_host();
let host_rules = factory.host_rules();
let device = factory.create(TunRequest::bare(name.clone(), mtu)).await?;
// The name the operating system actually gave the interface. On Linux
// and Windows that is the one we asked for; on macOS the kernel assigns
// the utun unit, so the real name differs and everything that
@@ -230,6 +254,34 @@ impl Interface {
let name = device.name().to_string();
let tally = Arc::new(Tally::default());
#[cfg(any(windows, target_os = "macos"))]
let forwarding = use_sockets.then(|| {
let routes = routes.clone();
let carrier = carrier.clone();
super::egress::Gateway::new(mtu, move |route, packet| {
if let Some(IpHeader::V4 {
source,
destination,
}) = IpHeader::parse(&packet)
&& routes.accepts_exit_traffic(route.network, source)
&& matches!(
routes.packet_source(route.network, route.peer, destination),
Some(PacketSource::Member)
)
{
let obs = routes.traffic.packet(
route.network,
route.peer,
Direction::Tx,
&packet,
|| Role::ServeExit,
);
if carrier.carry(route, packet) {
obs.record();
}
}
})
});
let vip_task = {
let factory = Arc::clone(&factory);
let routes = Arc::clone(&routes);
@@ -242,7 +294,10 @@ impl Interface {
tokio::select! {
_=interval.tick()=>{
let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len()));
for (route,packet) in probes {carrier.carry(route,packet);}
for (route,packet) in probes {
let obs = routes.traffic.packet(route.network,route.peer,Direction::Tx,&packet,||Role::Vip);
if carrier.carry(route,packet) {obs.record();}
}
for job in jobs {
let factory = Arc::clone(&factory);
checks.spawn(job.run(move |socket, source| factory.bind_overlay_socket(socket, source)));
@@ -268,8 +323,14 @@ impl Interface {
};
match routes.vips.outgoing(packet.clone()) {
crate::vip::router::Decision::Send(route, packet) => {
let obs =
routes
.vips
.observe_outgoing(&routes.traffic, Some(route), &packet);
for part in crate::vip::packet::fragments(packet, mtu) {
let len = part.len();
if carrier.carry(route, part) {
obs.record_fragment(len);
tally.sent.fetch_add(1, Ordering::Relaxed);
} else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
@@ -277,13 +338,22 @@ impl Interface {
}
continue;
}
crate::vip::router::Decision::Local(packet) => {
for part in crate::vip::packet::fragments(packet, mtu) {
let _ = device.send(part).await;
crate::vip::router::Decision::Local(translated)
| crate::vip::router::Decision::Reassembled(translated) => {
let obs =
routes
.vips
.observe_outgoing(&routes.traffic, None, &translated);
for part in crate::vip::packet::fragments(translated, mtu) {
let len = part.len();
if device.send(part).await.is_ok() {
obs.record_fragment(len);
}
}
continue;
}
crate::vip::router::Decision::Drop => continue,
crate::vip::router::Decision::Drop
| crate::vip::router::Decision::ProbeReceived => continue,
crate::vip::router::Decision::Pass => {}
}
let destination = header.destination();
@@ -296,7 +366,15 @@ impl Interface {
.flatten();
if let Some(recipients) = recipients {
for &route in recipients.iter() {
let obs = routes.traffic.packet(
route.network,
route.peer,
Direction::Tx,
&packet,
|| Role::Broadcast,
);
if carrier.carry(route, packet.clone()) {
obs.record();
tally.sent.fetch_add(1, Ordering::Relaxed);
tally.broadcast_sent.fetch_add(1, Ordering::Relaxed);
} else {
@@ -315,11 +393,39 @@ impl Interface {
tally.multicast.fetch_add(1, Ordering::Relaxed);
continue;
}
let Some(route) = routes.route_v4(destination) else {
let selected = match (header.source(), destination) {
(IpAddr::V4(source), IpAddr::V4(address)) => {
routes.packet_route(Some(source), address)
}
_ => None,
};
let Some((route, exit)) = selected else {
tally.note_unroutable(destination);
continue;
};
let len = packet.len() as u64;
let obs = routes.traffic.packet(
route.network,
route.peer,
Direction::Tx,
&packet,
|| {
if exit.is_some() {
Role::ViaExit
} else if let IpAddr::V4(src) = header.source()
&& routes.accepts_exit_traffic(route.network, src)
{
Role::ServeExit
} else {
Role::Mesh
}
},
);
if carrier.carry(route, packet) {
obs.record();
if let Some(exit) = exit {
exit.tx_bytes.fetch_add(len, Ordering::Relaxed);
}
tally.sent.fetch_add(1, Ordering::Relaxed);
} else {
tally.undeliverable.fetch_add(1, Ordering::Relaxed);
@@ -329,6 +435,8 @@ impl Interface {
};
Ok(Self {
#[cfg(any(windows, target_os = "macos"))]
forwarding,
device,
factory,
name,
@@ -336,7 +444,10 @@ impl Interface {
routes,
carrier,
tally,
applied: std::sync::Mutex::new(Vec::new()),
addresses: std::sync::Mutex::new(AddressState {
applied: Some(Vec::new()),
last_error: None,
}),
task: std::sync::Mutex::new(Some(task)),
vip_task: std::sync::Mutex::new(Some(vip_task)),
sync_lock: Arc::new(tokio::sync::Mutex::new(())),
@@ -420,6 +531,9 @@ impl Interface {
ranges.sort_by_key(|range| (range.base, range.prefix_len));
ranges.dedup();
let (client, client_source) = self.routes.exit_client();
#[cfg(windows)]
self.device
.set_exit_source(&self.wanted_addresses(), client_source);
let overlay = self.routes.overlay_ranges();
let (bypass, bypass_hosts) = if client && exit.needs_bypass() {
self.underlay_targets(&overlay)
@@ -445,6 +559,10 @@ impl Interface {
(state.plan.clone(), state.is_ok())
};
if wanted.is_empty() {
#[cfg(any(windows, target_os = "macos"))]
if let Some(gateway) = &self.forwarding {
gateway.configure(Vec::new());
}
if planned.is_some() {
exit.clear(&self.name).await;
let mut state = self.exit_state();
@@ -455,6 +573,12 @@ impl Interface {
return;
}
if planned.as_ref() == Some(&wanted) && ok {
if !wanted.client
&& !wanted.offer.is_empty()
&& let Some(report) = exit.refresh_offer(&wanted).await
{
self.exit_state().report = Some(report);
}
if let Some(outcome) = exit.refresh(&wanted).await {
if let RuleOutcome::Failed(reason) = &outcome {
tracing::warn!(interface = %self.name, %reason, "cannot refresh exit-client socket protection");
@@ -463,9 +587,13 @@ impl Interface {
report.client = Some(outcome);
}
}
#[cfg(any(windows, target_os = "macos"))]
self.configure_forwarding(exit.forwarded_uplink());
return;
}
let report = exit.apply(&wanted).await;
#[cfg(any(windows, target_os = "macos"))]
self.configure_forwarding(exit.forwarded_uplink());
for (range, outcome) in &report.offer {
match outcome {
RuleOutcome::Applied => tracing::info!(
@@ -490,7 +618,7 @@ impl Interface {
if cfg!(target_os = "windows") {
"`Set-NetIPInterface -Forwarding Enabled` on the interfaces involved"
} else if cfg!(target_os = "macos") {
"`sysctl -w net.inet.ip.forwarding=1`, set again after every reboot"
"enable the exit in Tsunagi to authorize forwarding on macOS"
} else {
"`sysctl -w net.ipv4.ip_forward=1` (or `net.ipv4.conf.<interface>.forwarding=1`), \
and set it in sysctl.d to keep it"
@@ -513,6 +641,30 @@ impl Interface {
state.report = Some(report);
}
#[cfg(any(windows, target_os = "macos"))]
fn configure_forwarding(&self, physical: Option<(u32, std::net::Ipv4Addr)>) {
if let Some(gateway) = &self.forwarding {
gateway.configure(
self.routes
.exit_offers()
.into_iter()
.filter_map(|(network, _)| {
let (index, address) = physical?;
Some((network, super::egress::Physical { index, address }))
})
.collect(),
);
}
}
/// Whether the host routes its own transport by destination.
pub(crate) fn needs_underlay_targets(&self) -> bool {
self.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass())
}
/// Tells the interface where a network's runtime reaches peers and
/// relays outside the overlay. When the host needs those kept out of the
/// exit node's default route and the set changed, the rules follow.
@@ -537,13 +689,7 @@ impl Interface {
map.insert(network, new.clone()) != Some(new)
}
};
let needed = changed
&& self.routes.exit_via().is_some()
&& self
.host_rules
.as_ref()
.and_then(|rules| rules.exit_rules())
.is_some_and(|exit| exit.needs_bypass());
let needed = changed && self.routes.exit_via().is_some() && self.needs_underlay_targets();
if needed {
self.sync_exit_rules().await;
}
@@ -620,7 +766,18 @@ impl Interface {
{
Some((_, outcome)) => RuleSetReport {
ok: outcome.is_applied(),
detail: offer_detail(outcome, &range),
detail: {
#[cfg(target_os = "macos")]
if self.forwarding.is_some() && outcome.is_applied() {
format!(
"physical TCP, UDP and ICMP echo forwarding for {range}"
)
} else {
offer_detail(outcome, &range)
}
#[cfg(not(target_os = "macos"))]
offer_detail(outcome, &range)
},
},
None => failed("not applied yet"),
}
@@ -656,8 +813,8 @@ impl Interface {
}
/// Whether this agent can really act as an exit node in a network: the
/// rules members' traffic needs are in place. Kernel forwarding is not
/// part of it, because the agent never turns that on itself.
/// platform reports that its offer rules are applied. The macOS kernel backend
/// includes enabling IPv4 forwarding in that outcome.
pub fn exit_offer_ready(&self, network: NetworkId) -> bool {
let Some((policy, Some(range))) = self.routes.exit_settings(network) else {
return false;
@@ -700,13 +857,13 @@ impl Interface {
let _guard = self.sync_lock.lock().await;
let wanted = self.wanted_addresses();
{
let applied = match self.applied.lock() {
Ok(guard) => guard.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
};
if applied == wanted {
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
if addresses.applied.as_ref() == Some(&wanted) {
return Ok(());
}
// A failed or cancelled reconfiguration can leave some aliases or
// routes installed. Even a return to the previous plan must retry.
addresses.applied = None;
}
// Every address this agent holds, in every network it is in. The
@@ -717,12 +874,25 @@ impl Interface {
addresses: wanted.clone(),
mtu: self.mtu,
};
self.factory.reconfigure(request).await?;
match self.applied.lock() {
Ok(mut guard) => *guard = wanted,
Err(poisoned) => *poisoned.into_inner() = wanted,
let result = self.factory.reconfigure(request).await;
let mut addresses = self.addresses.lock().unwrap_or_else(|e| e.into_inner());
match &result {
Ok(()) => {
addresses.applied = Some(wanted);
addresses.last_error = None;
}
Err(err) => addresses.last_error = Some(format!("{}: {err}", self.name)),
}
Ok(())
result
}
/// Last error applying the shared interface's addresses and subnet routes.
pub fn address_error(&self) -> Option<String> {
self.addresses
.lock()
.unwrap_or_else(|e| e.into_inner())
.last_error
.clone()
}
/// The interface name the operating system gave.
@@ -747,6 +917,10 @@ impl Interface {
/// Removes the interface from the host.
pub async fn remove(&self) {
#[cfg(any(windows, target_os = "macos"))]
if let Some(gateway) = &self.forwarding {
gateway.configure(Vec::new());
}
// The route goes with the interface; the firewall rule does not, so
// it is taken out explicitly while the interface is still known.
if let Some(rules) = &self.host_rules {
@@ -810,27 +984,38 @@ impl Interface {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongFamily);
};
if !self.routes.may_send_from(network, peer, source) {
let Some(origin) = self.routes.packet_source(network, peer, source) else {
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::WrongSource);
}
let broadcast = match header.destination() {
IpAddr::V4(destination) if self.routes.is_broadcast(destination) => {
};
let (broadcast, exit, forwarded) = match (origin, header.destination()) {
(
PacketSource::ExitReply {
local: Some(local),
exit,
},
IpAddr::V4(destination),
) if destination == local => (false, Some(exit), false),
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_broadcast(destination) =>
{
if !super::broadcast::valid_udp(&packet)
|| !self.routes.accepts_broadcast(network, peer, destination)
{
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
return Err(Rejected::BroadcastDenied);
}
true
(true, None, false)
}
IpAddr::V4(destination) if self.routes.is_local_destination(network, destination) => {
false
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.is_local_destination(network, destination) =>
{
(false, None, false)
}
// This agent is an exit node of this network: a member's packet
// for the internet goes to the host, which masquerades it.
IpAddr::V4(destination) if self.routes.accepts_exit_traffic(network, destination) => {
false
(PacketSource::Member, IpAddr::V4(destination))
if self.routes.accepts_exit_traffic(network, destination) =>
{
(false, None, true)
}
_ => {
self.tally.wrong_destination.fetch_add(1, Ordering::Relaxed);
@@ -839,24 +1024,115 @@ impl Interface {
};
// Source ownership was checked before any VIP reverse translation.
let packet = match self.routes.vips.incoming(network, peer, packet.clone()) {
crate::vip::router::Decision::Send(route, packet) => {
crate::vip::router::Decision::Send(route, reply) => {
self.routes
.traffic
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
.record();
let packet = reply;
// Probe replies use the ordinary peer carrier, never the TUN.
self.carrier.carry(route, packet);
let tx = self.routes.traffic.packet(
route.network,
route.peer,
Direction::Tx,
&packet,
|| Role::Vip,
);
if self.carrier.carry(route, packet) {
tx.record();
}
return Ok(());
}
crate::vip::router::Decision::Local(packet) => {
for part in crate::vip::packet::fragments(packet, self.mtu) {
crate::vip::router::Decision::Local(translated) => {
let obs =
self.routes
.traffic
.packet(network, peer, Direction::Rx, &translated, || Role::Vip);
for part in crate::vip::packet::fragments(translated, self.mtu) {
let len = part.len();
if self.device.send(part).await.is_ok() {
obs.record_fragment(len);
self.tally.received.fetch_add(1, Ordering::Relaxed);
}
}
return Ok(());
}
crate::vip::router::Decision::Reassembled(reassembled) => {
for part in crate::vip::packet::fragments(reassembled, self.mtu) {
self.deliver_admitted(network, peer, part, broadcast, exit.as_ref(), forwarded)
.await;
}
return Ok(());
}
crate::vip::router::Decision::ProbeReceived => {
self.routes
.traffic
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
.record();
return Ok(());
}
crate::vip::router::Decision::Drop => return Ok(()),
crate::vip::router::Decision::Pass => packet,
};
self.deliver_admitted(network, peer, packet, broadcast, exit.as_ref(), forwarded)
.await;
Ok(())
}
async fn deliver_admitted(
&self,
network: NetworkId,
peer: EndpointId,
packet: Bytes,
broadcast: bool,
exit: Option<&Arc<super::router::SelectedExit>>,
forwarded: bool,
) {
let obs = self
.routes
.traffic
.packet(network, peer, Direction::Rx, &packet, || {
if forwarded {
Role::ServeExit
} else if exit.is_some() {
Role::ViaExit
} else if broadcast {
Role::Broadcast
} else {
Role::Mesh
}
});
// Only authenticated member traffic admitted by the exit policy can
// open a physical socket. A rejected allocation never falls through
// to Wintun, where the local upstream's split routes might recapture it.
let client = if forwarded {
self.routes.exit_activity.stamp(network, peer)
} else {
None
};
#[cfg(any(windows, target_os = "macos"))]
if forwarded && let Some(gateway) = &self.forwarding {
if gateway.forward(Route { network, peer }, packet) {
if let Some(stamp) = client {
self.routes.exit_activity.forwarded(&stamp);
}
obs.record();
self.tally.received.fetch_add(1, Ordering::Relaxed);
} else {
self.tally.undeliverable.fetch_add(1, Ordering::Relaxed);
}
return;
}
// Remote broadcasts terminate here. Only local TUN ingress can fan out.
let len = packet.len() as u64;
if self.device.send(packet).await.is_ok() {
if let Some(stamp) = client {
self.routes.exit_activity.forwarded(&stamp);
}
obs.record();
if let Some(exit) = exit {
exit.rx_bytes.fetch_add(len, Ordering::Relaxed);
}
if broadcast {
self.tally
.broadcast_received
@@ -864,7 +1140,6 @@ impl Interface {
}
self.tally.received.fetch_add(1, Ordering::Relaxed);
}
Ok(())
}
/// The addresses the interface should be carrying, from the table.
@@ -895,18 +1170,6 @@ impl Drop for Interface {
}
}
impl RoutingTable {
/// The route for a destination, when it is one the overlay carries.
fn route_v4(&self, destination: IpAddr) -> Option<Route> {
match destination {
IpAddr::V4(address) => self.route(address),
// The overlay is IPv4. An IPv6 packet has no owner here, and
// counting it as unroutable is the truth rather than a fault.
IpAddr::V6(_) => None,
}
}
}
/// Whether an address is one the overlay has nowhere to send.
fn is_multicast_or_broadcast(address: IpAddr) -> bool {
match address {
@@ -1244,6 +1507,83 @@ mod tests {
);
}
#[tokio::test]
async fn dropping_a_network_after_partial_provisioning_removes_its_alias() {
#[derive(Debug, Default)]
struct PartialFactory {
devices: MemoryTunFactory,
addresses: std::sync::Mutex<Vec<Cidr>>,
}
impl TunFactory for PartialFactory {
fn name(&self) -> &str {
"partial"
}
fn on_host(&self) -> bool {
false
}
fn create<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<Arc<dyn TunDevice>, OverlayError>> {
self.devices.create(request)
}
fn reconfigure<'a>(
&'a self,
request: TunRequest,
) -> crate::BoxFuture<'a, Result<(), OverlayError>> {
Box::pin(async move {
let mut host = self.addresses.lock().unwrap();
*host = request.addresses;
if !host.is_empty() {
return Err(OverlayError::Unavailable("subnet route failed".into()));
}
Ok(())
})
}
}
let routes = Arc::new(RoutingTable::new());
let network = network("partial");
routes
.set_network(
network,
NetworkRoutes {
local: Some(addr(1)),
range: Some("10.13.37.0/24".parse().unwrap()),
..NetworkRoutes::default()
},
)
.unwrap();
let factory = Arc::new(PartialFactory::default());
let interface = Interface::start(
factory.clone(),
"tsunpartial",
1280,
routes.clone(),
Arc::new(Recorder::default()),
)
.await
.unwrap();
assert!(interface.address_error().is_none());
assert!(interface.sync_addresses().await.is_err());
assert!(
interface
.address_error()
.unwrap()
.contains("subnet route failed")
);
assert_eq!(factory.addresses.lock().unwrap().len(), 1);
routes.remove_network(network);
interface.sync_addresses().await.unwrap();
assert!(interface.address_error().is_none());
assert!(factory.addresses.lock().unwrap().is_empty());
interface.remove().await;
}
#[tokio::test]
async fn the_wanted_addresses_follow_the_table() {
let (interface, _device, routes, _carrier, id) = interface(false).await;
@@ -1422,6 +1762,57 @@ mod tests {
}
}
#[tokio::test]
async fn exit_totals_count_only_accepted_internet_packets_for_the_current_choice() {
let (interface, device, routes, _, id) = interface(false).await;
let totals = |p| {
routes
.exit_traffic(id, peer(p))
.map(|t| (t.tx_bytes, t.rx_bytes))
};
assert_eq!(totals(2), None);
routes.set_exit(id, using(peer(2)));
let outgoing = ipv4(addr(1), INTERNET, b"request");
device.push_from_os(outgoing.clone());
device.push_from_os(ipv4(addr(1), addr(2), b"ordinary mesh traffic"));
wait_for(&interface, |c| c.sent.saturating_sub(1)).await;
let incoming = ipv4(INTERNET, addr(1), b"reply");
interface
.deliver(id, peer(2), incoming.clone())
.await
.unwrap();
interface
.deliver(id, peer(2), ipv4(addr(2), addr(1), b"mesh"))
.await
.unwrap();
assert!(
interface
.deliver(id, peer(3), incoming.clone())
.await
.is_err()
);
assert!(
interface
.deliver(id, peer(2), ipv4(INTERNET, addr(3), b"wrong host"))
.await
.is_err()
);
routes.set_exit(id, using(peer(2)));
assert_eq!(
totals(2),
Some((outgoing.len() as u64, incoming.len() as u64))
);
routes.set_exit(id, using(peer(3)));
assert_eq!(totals(2), None);
assert_eq!(totals(3), Some((0, 0)));
routes.set_exit(id, ExitPolicy::default());
assert_eq!(totals(3), None);
routes.set_exit(id, using(peer(2)));
assert_eq!(totals(2), Some((0, 0)));
interface.remove().await;
}
#[tokio::test]
async fn internet_traffic_goes_to_the_exit_node_and_only_once_one_is_chosen() {
let (interface, device, routes, carrier, id) = interface(false).await;
@@ -1477,6 +1868,47 @@ mod tests {
assert_eq!(interface.counters().received, 1);
}
#[tokio::test]
async fn an_exit_reply_must_terminate_locally_even_while_this_agent_offers_forwarding() {
use super::super::broadcast::BroadcastPolicy;
let (interface, device, routes, _, id) = interface(false).await;
routes.set_exit(
id,
ExitPolicy {
offer: true,
via: Some(peer(2)),
},
);
routes.set_broadcast(
id,
BroadcastPolicy {
enabled: true,
peers: [peer(2)].into_iter().collect(),
},
);
let udp = [0, 1, 0, 2, 0, 8, 0, 0];
for destination in [Ipv4Addr::new(1, 1, 1, 1), Ipv4Addr::BROADCAST] {
assert_eq!(
interface
.deliver(id, peer(2), ipv4(INTERNET, destination, &udp))
.await,
Err(Rejected::WrongDestination)
);
}
assert_eq!(interface.counters().received, 0);
// The same peer can still return internet traffic to us, and can
// originate its own ordinary packets under the network's offer.
for packet in [ipv4(INTERNET, addr(1), &udp), ipv4(addr(2), INTERNET, &udp)] {
interface
.deliver(id, peer(2), packet.clone())
.await
.unwrap();
assert_eq!(device.pop_to_os().await.unwrap(), packet);
}
}
#[tokio::test]
async fn an_exit_node_hands_a_members_internet_packet_to_the_host_only_while_offering() {
let (interface, device, routes, _carrier, id) = interface(false).await;
@@ -1577,6 +2009,19 @@ mod tests {
vec![Ipv4Addr::new(5, 6, 7, 8)]
);
let second = network("second underlay");
let second_path = Ipv4Addr::new(203, 0, 113, 10);
interface.set_underlay(second, [second_path], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8), second_path]
);
interface.set_underlay(second, [], []).await;
assert_eq!(
rules.exit().installed().unwrap().bypass,
[Ipv4Addr::new(5, 6, 7, 8)]
);
// Not using an exit node: nothing to keep direct.
routes.set_exit(id, Default::default());
interface.sync_exit_rules().await;
+8
View File
@@ -33,6 +33,10 @@ pub enum OverlayError {
/// reason and, where there is one, what to do about it.
#[error("overlay unavailable: {0}")]
Unavailable(String),
/// The OS denied creation of a macOS host utun.
#[cfg(target_os = "macos")]
#[error("overlay unavailable: {0}")]
UtunDenied(String),
/// Anything else.
#[error("{0}")]
Other(String),
@@ -40,12 +44,16 @@ pub enum OverlayError {
pub mod broadcast;
pub mod config;
#[cfg(any(windows, target_os = "macos", test))]
mod egress;
pub mod exit;
mod exit_activity;
pub mod hostrules;
pub mod interface;
pub mod packet;
pub mod provision;
pub mod router;
pub mod source;
pub mod tun;
pub use config::{Cidr, DEFAULT_INTERFACE_PREFIX, MAX_INTERFACE_NAME_LEN, interface_name};
@@ -6,6 +6,8 @@
use std::net::{Ipv4Addr, Ipv6Addr};
pub use crate::vip::packet::{Reassembly as Ipv4Reassembly, fragments as fragment_ipv4};
/// The addresses of an IP packet, as far as routing cares.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum IpHeader {
@@ -55,7 +55,7 @@ use crate::BoxFuture;
use crate::overlay::OverlayError;
use super::super::config::Cidr;
use super::super::hostrules::linux_exit_mark::{UNDERLAY_MARK, UNDERLAY_MASK};
use super::super::hostrules::linux_exit_mark::{EXIT_REPLY_MARK, UNDERLAY_MARK, UNDERLAY_MASK};
use super::super::tun::{TunDevice, TunRequest};
use super::privilege::{NetAdmin, Privilege, probe_net_admin};
use super::{
@@ -76,7 +76,9 @@ enum Command {
DelBroadcastRoute(String, Reply<()>),
/// Send the host's default traffic through this interface, except what
/// this user id sends.
SetExitClient(String, u32, Reply<()>),
SetExitClient(String, u32, Option<Ipv4Addr>, Reply<()>),
/// Replace only the default route on an already protected interface.
UpdateExitSource(String, Option<Ipv4Addr>, Reply<()>),
/// Take those routing rules away again.
ClearExitClient(Reply<()>),
/// Stop the thread.
@@ -213,10 +215,25 @@ impl RouteHandle {
/// Sends the host's default traffic through `interface`, except what the
/// user id `uid` sends. Replaces what an earlier call set up.
pub(crate) fn set_exit_client(&self, interface: &str, uid: u32) -> Result<(), OverlayError> {
pub(crate) fn set_exit_client(
&self,
interface: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let interface = interface.to_string();
call_thread(&self.commands, |reply| {
Command::SetExitClient(interface, uid, reply)
Command::SetExitClient(interface, uid, source, reply)
})
}
pub(crate) fn update_exit_source(
&self,
interface: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
call_thread(&self.commands, |reply| {
Command::UpdateExitSource(interface.to_string(), source, reply)
})
}
@@ -346,7 +363,8 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
| Command::Configure(_, reply)
| Command::SetBroadcastRoute(_, _, reply)
| Command::DelBroadcastRoute(_, reply)
| Command::SetExitClient(_, _, reply) => {
| Command::SetExitClient(_, _, _, reply)
| Command::UpdateExitSource(_, _, reply) => {
let _ = reply.send(Err(OverlayError::Unavailable(message)));
}
Command::ClearExitClient(reply) => {
@@ -398,9 +416,19 @@ fn netlink_thread(requests: mpsc::Receiver<Command>) {
});
let _ = reply.send(result);
}
Command::SetExitClient(name, uid, reply) => {
Command::SetExitClient(name, uid, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(set_exit_client(&name, uid));
let result = runtime.block_on(set_exit_client(&name, uid, source));
drop(guard);
result
});
let _ = reply.send(result);
}
Command::UpdateExitSource(name, source, reply) => {
let result = NetAdmin::acquire().and_then(|guard| {
let result = runtime.block_on(with_netlink(|handle| async move {
replace_exit_default(&handle, &name, source).await
}));
drop(guard);
result
});
@@ -643,6 +671,7 @@ const EXIT_TABLE: u32 = 0x7473;
/// The main table.
const MAIN_TABLE: u32 = 254;
/// Protect marked underlay and initial socket routing before Tailscale's rules.
const EXIT_REPLY_PRIORITY: u32 = 5204;
const EXIT_MARK_PRIORITY: u32 = 5205;
const EXIT_BYPASS_PRIORITY: u32 = 5206;
const LEGACY_EXIT_BYPASS_PRIORITY: u32 = 5280;
@@ -676,6 +705,15 @@ fn rule_priority(rule: &RuleMessage) -> Option<u32> {
fn is_exit_rule(rule: &RuleMessage) -> bool {
let table = rule_table(rule);
match rule_priority(rule) {
Some(EXIT_REPLY_PRIORITY) => {
table == EXIT_TABLE
&& rule
.attributes
.contains(&RuleAttribute::FwMark(EXIT_REPLY_MARK))
&& rule
.attributes
.contains(&RuleAttribute::FwMask(EXIT_REPLY_MARK))
}
Some(EXIT_MARK_PRIORITY) => {
table == MAIN_TABLE
&& rule
@@ -704,13 +742,19 @@ fn is_exit_rule(rule: &RuleMessage) -> bool {
}
}
fn exit_default_route(index: Option<u32>) -> rtnetlink::packet_route::route::RouteMessage {
fn exit_default_route(
index: Option<u32>,
source: Option<Ipv4Addr>,
) -> rtnetlink::packet_route::route::RouteMessage {
let mut builder = RouteMessageBuilder::<Ipv4Addr>::new()
.destination_prefix(Ipv4Addr::UNSPECIFIED, 0)
.table_id(EXIT_TABLE);
if let Some(index) = index {
builder = builder.output_interface(index).scope(RouteScope::Link);
}
if let Some(source) = source {
builder = builder.pref_source(source);
}
builder.build()
}
@@ -772,7 +816,12 @@ async fn remove_exit_rules(
async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayError> {
remove_exit_rules(handle, IpVersion::V4).await?;
match handle.route().del(exit_default_route(None)).execute().await {
match handle
.route()
.del(exit_default_route(None, None))
.execute()
.await
{
Ok(()) => {}
// "No such process": no such route, which is the goal.
Err(err) if err.to_string().contains("No such") => {}
@@ -797,42 +846,74 @@ async fn remove_exit_client(handle: &rtnetlink::Handle) -> Result<(), OverlayErr
}
}
/// Replace the default route atomically when the selected overlay address changes.
async fn replace_exit_default(
handle: &rtnetlink::Handle,
name: &str,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
let index = link_index(handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node route could be added"
))
})?;
handle
.route()
.add(exit_default_route(Some(index), source))
.replace()
.execute()
.await
.map_err(|err| {
OverlayError::Unavailable(format!("cannot set the exit node default route: {err}"))
})
}
/// Sets up the using side of an exit node.
///
/// ```text
/// ip route replace default dev <if> table 0x7473
/// ip route replace default dev <if> src <selected overlay address> table 0x7473
/// ip rule add priority 5205 fwmark 0x40000000/0x40000000 lookup main
/// ip rule add priority 5206 uidrange <uid>-<uid> lookup main
/// ip rule add priority 5290 lookup main suppress_prefixlength 0
/// ip rule add priority 5300 lookup 0x7473
/// ip rule add priority 5300 iif lo lookup 0x7473
/// ```
///
/// and the same for IPv6 with `ip -6 route replace unreachable default table
/// 0x7473`, so that IPv6 is refused instead of leaving the ordinary way.
/// 0x7473` and no interface selector, so IPv6 is refused.
///
/// What an earlier call left is removed first, so repeating it is safe, and
/// the rules go in last, so a failure part way never leaves a rule that
/// sends traffic to a table with no route in it.
async fn set_exit_client(name: &str, uid: u32) -> Result<(), OverlayError> {
async fn set_exit_client(
name: &str,
uid: u32,
source: Option<Ipv4Addr>,
) -> Result<(), OverlayError> {
with_netlink(|handle| async move {
let index = link_index(&handle, name).await.ok_or_else(|| {
OverlayError::Unavailable(format!(
"interface `{name}` disappeared before the exit node routes could be added"
))
})?;
remove_exit_client(&handle).await?;
let fail = |what: &str, err: rtnetlink::Error| {
OverlayError::Unavailable(format!("cannot add the exit node {what}: {err}"))
};
handle
.route()
.add(exit_default_route(Some(index)))
.replace()
.execute()
.await
.map_err(|err| fail("default route", err))?;
replace_exit_default(&handle, name, source).await?;
add_mark_bypass(&handle, false).await?;
if uid == 0 {
add_mark_rule(
&handle,
false,
EXIT_TABLE,
EXIT_REPLY_PRIORITY,
EXIT_REPLY_MARK,
)
.await?;
}
add_mark_rule(
&handle,
false,
MAIN_TABLE,
EXIT_MARK_PRIORITY,
UNDERLAY_MARK,
)
.await?;
let mut bypass = handle
.rule()
@@ -876,6 +957,7 @@ async fn set_exit_client(name: &str, uid: u32) -> Result<(), OverlayError> {
.table_id(EXIT_TABLE)
.action(RuleAction::ToTable)
.priority(EXIT_DEFAULT_PRIORITY)
.input_interface("lo")
.execute()
.await
.map_err(|err| fail("rule for the default route", err))?;
@@ -906,7 +988,7 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
};
}
add_mark_bypass(handle, true).await?;
add_mark_rule(handle, true, MAIN_TABLE, EXIT_MARK_PRIORITY, UNDERLAY_MARK).await?;
let mut bypass = handle
.rule()
.add()
@@ -954,14 +1036,20 @@ async fn set_exit_block_v6(handle: &rtnetlink::Handle, uid: u32) -> Result<(), O
.map_err(|err| fail("rule for the default route", err))
}
async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), OverlayError> {
async fn add_mark_rule(
handle: &rtnetlink::Handle,
v6: bool,
table: u32,
priority: u32,
bit: u32,
) -> Result<(), OverlayError> {
let mut rule = handle
.rule()
.add()
.table_id(MAIN_TABLE)
.table_id(table)
.action(RuleAction::ToTable)
.priority(EXIT_MARK_PRIORITY)
.fw_mark(UNDERLAY_MARK);
.priority(priority)
.fw_mark(bit);
rule.message_mut().header.family = if v6 {
rtnetlink::packet_route::AddressFamily::Inet6
} else {
@@ -969,9 +1057,11 @@ async fn add_mark_bypass(handle: &rtnetlink::Handle, v6: bool) -> Result<(), Ove
};
rule.message_mut()
.attributes
.push(RuleAttribute::FwMask(UNDERLAY_MASK));
.push(RuleAttribute::FwMask(bit));
rule.execute().await.map_err(|err| {
OverlayError::Unavailable(format!("cannot protect marked underlay traffic: {err}"))
OverlayError::Unavailable(format!(
"cannot add exit routing rule {priority} for mark {bit:#x}: {err}"
))
})
}
@@ -1190,13 +1280,17 @@ mod tests {
#[test]
fn the_default_route_of_the_exit_table_names_the_table_and_the_interface() {
let route = exit_default_route(Some(7));
let source = Ipv4Addr::new(10, 99, 0, 1);
let route = exit_default_route(Some(7), Some(source));
assert_eq!(route.header.destination_prefix_length, 0);
let debug = format!("{route:?}");
assert!(debug.contains(&format!("Table({EXIT_TABLE})")), "{debug}");
assert!(debug.contains("Oif(7)"), "{debug}");
assert!(route.attributes.contains(
&rtnetlink::packet_route::route::RouteAttribute::PrefSource(source.into())
));
// Deleting names no interface, so it matches whatever it was added on.
assert!(!format!("{:?}", exit_default_route(None)).contains("Oif"));
assert!(!format!("{:?}", exit_default_route(None, None)).contains("Oif"));
}
#[test]
+226 -106
View File
@@ -39,7 +39,8 @@
//! `getifaddrs`. An interface is matched by its real `utunN` name, which only
//! matters on reconfiguration: the first create always makes a fresh device.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use netdev::ipnet::IpNet;
use std::net::IpAddr;
use std::sync::{Arc, Mutex};
use crate::BoxFuture;
@@ -115,7 +116,7 @@ impl InterfaceProvisioner for UtunProvisioner {
if self.is_ours(&plan.name) {
let current = observe(&plan.name).await;
let changes = plan_changes(&current, plan, true)?;
configure(&plan.name, &changes).await?;
configure(&plan.name, &changes, &plan.addresses).await?;
return Ok(Provisioned {
changes,
device: None,
@@ -136,7 +137,7 @@ impl InterfaceProvisioner for UtunProvisioner {
// A failure here leaves an interface that exists but cannot carry
// traffic. Drop the device so the utun closes, and report, rather
// than leave a trap behind.
if let Err(err) = configure(&real, &changes).await {
if let Err(err) = configure(&real, &changes, &plan.addresses).await {
drop(device);
return Err(err);
}
@@ -225,28 +226,25 @@ async fn observe(name: &str) -> InterfaceState {
}
/// Applies MTU, link state, addresses and the on-link routes they imply.
async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayError> {
async fn configure(
name: &str,
changes: &super::Changes,
wanted: &[Cidr],
) -> Result<(), OverlayError> {
if let Some(mtu) = changes.set_mtu {
set_mtu(name, mtu).await?;
}
for cidr in &changes.remove {
// Best effort: an address that is already gone is the outcome wanted.
if let Err(err) = address_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove address");
}
if let Err(err) = route_del(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not remove route");
let network = subnet(*cidr)?;
if !is_host_route(*cidr)
&& matches!(subnet_route(network).await?, SubnetRoute::Present { interface, .. } if interface == name)
{
run("/sbin/route", route_args("delete", name, network)).await?;
}
address_del(name, *cidr).await?;
}
for cidr in &changes.add {
address_add(name, *cidr).await?;
// The subnet route makes the whole overlay range reach the interface;
// a point-to-point utun does not install one from the address alone. A
// host address (/32 or /128) needs none. Best effort: a route that is
// already there is the outcome wanted.
if let Err(err) = route_add(name, *cidr).await {
tracing::debug!(interface = %name, %cidr, %err, "could not add route");
}
}
if changes.bring_up {
// Best effort: a utun with a descriptor open is up already, and a
@@ -255,31 +253,22 @@ async fn configure(name: &str, changes: &super::Changes) -> Result<(), OverlayEr
tracing::debug!(interface = %name, %err, "could not enable the interface");
}
}
Ok(())
}
/// The network address of a CIDR, with the host bits cleared.
fn network_of(cidr: Cidr) -> IpAddr {
match cidr.addr {
IpAddr::V4(addr) => {
let bits = u32::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u32::MAX << (32 - u32::from(cidr.prefix_len))
};
IpAddr::V4(Ipv4Addr::from(bits & mask))
}
IpAddr::V6(addr) => {
let bits = u128::from(addr);
let mask = if cidr.prefix_len == 0 {
0
} else {
u128::MAX << (128 - u32::from(cidr.prefix_len))
};
IpAddr::V6(Ipv6Addr::from(bits & mask))
// An alias may already be present after a partial reconcile, or its old
// subnet route may still select the first alias on this utun.
let mut result = Ok(());
for &cidr in wanted {
if !is_host_route(cidr) {
// Finish the other networks even when one subnet conflicts.
let update = ensure_subnet_route(name, subnet(cidr)?).await;
result = result.and(update);
}
}
result
}
fn subnet(cidr: Cidr) -> Result<IpNet, OverlayError> {
IpNet::new(cidr.addr, cidr.prefix_len)
.map_err(|err| OverlayError::Unavailable(format!("invalid overlay prefix {cidr}: {err}")))
}
/// Whether a CIDR is a single host address, which needs no subnet route.
@@ -326,40 +315,26 @@ fn address_del_args(name: &str, cidr: Cidr) -> Vec<String> {
]
}
/// The `route` arguments that point a CIDR's subnet at the interface.
fn route_add_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
fn route_args(command: &str, name: &str, subnet: IpNet) -> Vec<String> {
let family = match subnet.addr() {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
let mut args = vec![
if command == "get" { "-v" } else { "-q" }.into(),
"-n".into(),
"add".into(),
command.into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
}
/// The `route` arguments that remove that subnet route.
fn route_del_args(name: &str, cidr: Cidr) -> Vec<String> {
let family = match cidr.addr {
IpAddr::V4(_) => "-inet",
IpAddr::V6(_) => "-inet6",
};
vec![
"-q".into(),
"-n".into(),
"delete".into(),
family.into(),
"-net".into(),
format!("{}/{}", network_of(cidr), cidr.prefix_len),
"-interface".into(),
name.into(),
]
subnet.trunc().to_string(),
];
if command != "get" {
args.extend(["-interface".into(), name.into()]);
}
if matches!(command, "add" | "change") {
args.extend(["-ifa".into(), subnet.addr().to_string()]);
}
args
}
async fn address_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
@@ -370,18 +345,92 @@ async fn address_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
ifconfig(address_del_args(name, cidr)).await
}
async fn route_add(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
}
route(route_add_args(name, cidr)).await
#[derive(Debug, Eq, PartialEq)]
enum SubnetRoute {
Absent,
Present { interface: String, source: IpAddr },
}
async fn route_del(name: &str, cidr: Cidr) -> Result<(), OverlayError> {
if is_host_route(cidr) {
return Ok(());
impl SubnetRoute {
fn action(&self, name: &str, subnet: IpNet) -> Result<Option<&'static str>, OverlayError> {
match self {
Self::Absent => Ok(Some("add")),
Self::Present { interface, .. } if interface != name => {
Err(OverlayError::Unavailable(format!(
"route for {}/{} belongs to {interface}; cannot install it on {name}",
subnet.network(),
subnet.prefix_len()
)))
}
Self::Present { source, .. } if *source == subnet.addr() => Ok(None),
Self::Present { .. } => Ok(Some("change")),
}
}
route(route_del_args(name, cidr)).await
}
// A verbose RTM_GET prints two sockaddr lists (request and reply). In the
// kernel's reply IFA follows the variable-width link address of the interface.
fn parse_subnet_route(output: &str, subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
let invalid =
|| OverlayError::Unavailable(format!("could not read the kernel route for {subnet}"));
let field = |key: &str| {
output
.lines()
.find_map(|line| line.trim().strip_prefix(key).map(str::trim))
};
let destination = field("destination:").ok_or_else(invalid)?;
let matches = |text: &str, expected: IpAddr| {
text.parse::<IpAddr>() == Ok(expected) || (text == "default" && expected.is_unspecified())
};
if !matches(destination, subnet.network())
|| !field("mask:").is_some_and(|mask| matches(mask, subnet.netmask()))
{
return Ok(SubnetRoute::Absent);
}
let interface = field("interface:").ok_or_else(invalid)?;
let (_, reply) = output.rsplit_once("sockaddrs:").ok_or_else(invalid)?;
let (fields, addresses) = reply.trim().split_once('\n').ok_or_else(invalid)?;
let after = fields
.trim()
.trim_matches(['<', '>'])
.split(',')
.rev()
.position(|field| field == "IFA")
.ok_or_else(invalid)?;
let source = addresses
.split_whitespace()
.rev()
.nth(after)
.and_then(|ip| ip.parse().ok())
.ok_or_else(invalid)?;
Ok(SubnetRoute::Present {
interface: interface.into(),
source,
})
}
async fn subnet_route(subnet: IpNet) -> Result<SubnetRoute, OverlayError> {
match run("/sbin/route", route_args("get", "", subnet)).await {
Ok(output) => parse_subnet_route(&output, subnet),
Err(OverlayError::Unavailable(message)) if message.ends_with("not in table") => {
Ok(SubnetRoute::Absent)
}
Err(err) => Err(err),
}
}
async fn ensure_subnet_route(name: &str, subnet: IpNet) -> Result<(), OverlayError> {
if let Some(command) = subnet_route(subnet).await?.action(name, subnet)? {
run("/sbin/route", route_args(command, name, subnet)).await?;
let observed = subnet_route(subnet).await?;
if observed.action(name, subnet)?.is_some() {
return Err(OverlayError::Unavailable(format!(
"route for {subnet} on {name} did not select source {} (observed {observed:?})",
subnet.addr()
)));
}
}
Ok(())
}
async fn set_mtu(name: &str, mtu: u32) -> Result<(), OverlayError> {
@@ -394,27 +443,26 @@ async fn set_up(name: &str) -> Result<(), OverlayError> {
/// Runs `/sbin/ifconfig`, turning a non-zero exit into an error with its text.
async fn ifconfig(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/ifconfig", args).await
}
/// Runs `/sbin/route`, turning a non-zero exit into an error with its text.
async fn route(args: Vec<String>) -> Result<(), OverlayError> {
run("/sbin/route", args).await
run("/sbin/ifconfig", args).await.map(|_| ())
}
/// Runs a system tool by absolute path, so nothing on `PATH` can stand in for
/// it, and turns a non-zero exit into an error carrying what it said.
async fn run(program: &'static str, args: Vec<String>) -> Result<(), OverlayError> {
async fn run(program: &'static str, args: Vec<String>) -> Result<String, OverlayError> {
let display = format!("{program} {}", args.join(" "));
let output = tokio::task::spawn_blocking(move || {
std::process::Command::new(program).args(&args).output()
std::process::Command::new(program)
.env("LC_ALL", "C")
.args(&args)
.output()
})
.await
.map_err(|err| OverlayError::Other(format!("could not run {display}: {err}")))?
.map_err(|err| OverlayError::Unavailable(format!("could not run {display}: {err}")))?;
if output.status.success() {
return Ok(());
// Darwin route can exit successfully after a routing-socket write failed.
if output.status.success() && (program != "/sbin/route" || output.stderr.is_empty()) {
return Ok(String::from_utf8_lossy(&output.stdout).into_owned());
}
let message = {
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -429,6 +477,11 @@ async fn run(program: &'static str, args: Vec<String>) -> Result<(), OverlayErro
text
}
};
if message.contains("Operation not permitted") || message.contains("Permission denied") {
return Err(OverlayError::UtunDenied(format!(
"{display} failed: {message}"
)));
}
Err(OverlayError::Unavailable(format!(
"{display} failed: {message}"
)))
@@ -439,6 +492,7 @@ mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::net::{Ipv4Addr, Ipv6Addr};
fn v4(last: u8, prefix: u8) -> Cidr {
Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, last)), prefix).unwrap()
@@ -476,8 +530,8 @@ mod tests {
}
#[test]
fn a_subnet_route_points_the_masked_network_at_the_interface() {
let args = route_add_args("utun5", v4(69, 24));
fn a_subnet_route_names_its_own_overlay_source() {
let args = route_args("add", "utun5", subnet(v4(69, 24)).unwrap());
assert_eq!(
args,
vec![
@@ -488,11 +542,93 @@ mod tests {
"-net",
"10.13.37.0/24",
"-interface",
"utun5"
"utun5",
"-ifa",
"10.13.37.69"
]
);
}
#[test]
fn a_wrong_source_is_repaired_only_on_the_owned_interface() {
let cidr = subnet(v4(69, 24)).unwrap();
let observed = "destination: 10.13.37.0\n mask: 255.255.255.0\n interface: utun5\n\
sockaddrs: <DST,GATEWAY,NETMASK,IFP,IFA>\n 10.13.37.0 index: 20 255.255.255.0 index: 20 utun5 10.99.0.2\n";
let route = parse_subnet_route(observed, cidr).unwrap();
assert_eq!(route.action("utun5", cidr).unwrap(), Some("change"));
assert!(route.action("utun9", cidr).is_err());
let corrected = observed.replace("10.99.0.2", "10.13.37.69");
assert_eq!(
parse_subnet_route(&corrected, cidr)
.unwrap()
.action("utun5", cidr)
.unwrap(),
None
);
assert!(parse_subnet_route(&observed.replace(",IFA>", ">"), cidr).is_err());
assert!(parse_subnet_route("", cidr).is_err());
let broader = observed.replace("255.255.255.0", "255.255.0.0");
assert_eq!(
parse_subnet_route(&broader, cidr).unwrap(),
SubnetRoute::Absent
);
}
#[tokio::test]
#[ignore = "requires root and creates a temporary macOS utun with two subnet routes"]
async fn unbound_sockets_choose_each_networks_source_on_one_real_utun() {
let provisioner = UtunProvisioner::new().unwrap();
let first = Cidr::new("198.18.251.1".parse().unwrap(), 30).unwrap();
let second = Cidr::new("198.19.251.1".parse().unwrap(), 30).unwrap();
let created = provisioner
.reconcile(&InterfacePlan::new("tsuntest", 1280, vec![first]))
.await
.unwrap();
let device = created.device.unwrap();
let plan = InterfacePlan::new(device.name(), 1280, vec![first, second]);
let before = netwatch::netmon::State::new().await;
provisioner.reconcile(&plan).await.unwrap();
let after = netwatch::netmon::State::new().await;
assert!(crate::net::only_owned_interface_changed(
&before,
&after,
device.name()
));
for (peer, expected) in [("198.18.251.2", first), ("198.19.251.2", second)] {
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket
.connect((peer.parse::<Ipv4Addr>().unwrap(), 9))
.unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), expected.addr);
}
// Simulate a route left by an earlier release, with both aliases still present.
let second_subnet = subnet(second).unwrap();
let mut stale = route_args("change", device.name(), second_subnet);
*stale.last_mut().unwrap() = first.addr.to_string();
run("/sbin/route", stale).await.unwrap();
assert_eq!(
subnet_route(second_subnet)
.await
.unwrap()
.action(device.name(), second_subnet)
.unwrap(),
Some("change")
);
provisioner.reconcile(&plan).await.unwrap();
let socket = std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0)).unwrap();
socket.connect(("198.19.251.2", 9)).unwrap();
assert_eq!(socket.local_addr().unwrap().ip(), second.addr);
provisioner
.reconcile(&InterfacePlan::new(device.name(), 1280, vec![first]))
.await
.unwrap();
assert_eq!(
subnet_route(second_subnet).await.unwrap(),
SubnetRoute::Absent
);
provisioner.remove(device.name()).await.unwrap();
}
#[test]
fn a_host_address_installs_no_subnet_route() {
assert!(is_host_route(v4(69, 32)));
@@ -501,22 +637,6 @@ mod tests {
assert!(!is_host_route(v6(1, 64)));
}
#[test]
fn the_network_address_clears_the_host_bits() {
assert_eq!(
network_of(v4(69, 24)),
IpAddr::V4(Ipv4Addr::new(10, 13, 37, 0))
);
assert_eq!(
network_of(Cidr::new(IpAddr::V4(Ipv4Addr::new(10, 13, 37, 69)), 16).unwrap()),
IpAddr::V4(Ipv4Addr::new(10, 13, 0, 0))
);
assert_eq!(
network_of(v6(0x1234, 64)),
IpAddr::V6(Ipv6Addr::new(0xfd00, 0, 0, 0, 0, 0, 0, 0))
);
}
#[test]
fn link_local_addresses_are_not_ours_to_manage() {
assert!(is_link_local(IpAddr::V6(Ipv6Addr::new(
@@ -131,10 +131,14 @@ impl InterfaceProvisioner for WintunProvisioner {
};
for cidr in flush.iter().chain(changes.remove.iter()) {
// Best effort: an address that is already gone is the outcome
// wanted, and refusing to start over one is not worth it.
if let Err(err) = address_del(&plan.name, *cidr).await {
tracing::debug!(interface = %plan.name, %cidr, %err, "could not remove address");
if let Err(err) = address_del(&plan.name, *cidr).await
&& observe(&plan.name)
.await
.addresses
.iter()
.any(|a| a.addr == cidr.addr)
{
return Err(err);
}
}
@@ -262,11 +266,12 @@ async fn configure(plan: &InterfacePlan, changes: &super::Changes) -> Result<(),
set_mtu(&plan.name, mtu).await?;
}
for cidr in &changes.add {
if let Err(err) = address_add(&plan.name, *cidr).await {
let err_str = err.to_string();
if !err_str.contains("already exists") && !err_str.contains("0x80071392") {
return Err(err);
}
// An already-installed alias is idempotent, including on localized
// Windows. A duplicate on a different adapter cannot satisfy the plan.
if let Err(err) = address_add(&plan.name, *cidr).await
&& !observe(&plan.name).await.addresses.contains(cidr)
{
return Err(err);
}
}
if changes.bring_up {
@@ -300,6 +305,7 @@ fn address_add_args(name: &str, cidr: Cidr) -> Vec<String> {
format!("address={addr}"),
format!("mask={}", ipv4_mask(cidr.prefix_len)),
"store=active".into(),
"skipassource=false".into(),
],
IpAddr::V6(addr) => vec![
"interface".into(),
@@ -466,6 +472,70 @@ mod tests {
assert!(args.contains(&"name=tsun0".to_string()));
assert!(args.contains(&"address=10.13.37.69".to_string()));
assert!(args.contains(&"mask=255.255.255.0".to_string()));
assert!(args.contains(&"skipassource=false".to_string()));
}
#[tokio::test]
#[ignore = "requires an elevated Windows host with Wintun"]
async fn two_windows_subnets_choose_their_own_source_and_survive_removal() {
let addresses = [
(
Ipv4Addr::new(198, 18, 251, 1),
Ipv4Addr::new(198, 18, 251, 2),
),
(
Ipv4Addr::new(198, 19, 251, 1),
Ipv4Addr::new(198, 19, 251, 2),
),
];
for iface in netdev::get_interfaces() {
for prefix in iface.ipv4 {
assert!(
addresses.iter().all(|(ip, destination)| {
!prefix.contains(ip) && !prefix.contains(destination)
}),
"test subnets already in use"
);
}
}
let adapter = format!("tsun-test-{:08x}", rand::random::<u32>());
let provisioner = WintunProvisioner::new().unwrap();
let cidrs: Vec<_> = addresses
.iter()
.map(|(ip, _)| Cidr::new((*ip).into(), 30).unwrap())
.collect();
let mut device = None;
for wanted in [&cidrs[..1], &cidrs[..], &cidrs[1..], &cidrs[..]] {
let plan = InterfacePlan::new(&adapter, 1280, wanted.to_vec());
let result = provisioner.reconcile(&plan).await.unwrap();
if let Some(created) = result.device {
assert!(device.replace(created).is_none());
}
// Allow the Windows address to finish duplicate address detection.
tokio::time::timeout(std::time::Duration::from_secs(10), async {
loop {
let ready = addresses
.iter()
.filter(|(ip, _)| wanted.iter().any(|c| c.addr == IpAddr::V4(*ip)))
.all(|(ip, destination)| {
std::net::UdpSocket::bind((Ipv4Addr::UNSPECIFIED, 0))
.and_then(|socket| {
socket.connect((*destination, 9))?;
socket.local_addr()
})
.is_ok_and(|source| source.ip() == IpAddr::V4(*ip))
});
if ready {
break;
}
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
}
})
.await
.expect("Windows selected the wrong source");
assert_eq!(observe(&adapter).await.addresses, plan.addresses);
}
provisioner.remove(&adapter).await.unwrap();
}
#[test]
+354 -26
View File
@@ -21,9 +21,11 @@
//! one is in use.
use super::broadcast::{BroadcastPolicy, BroadcastTable};
use arc_swap::ArcSwap;
use super::exit::ExitTraffic;
use arc_swap::{ArcSwap, ArcSwapOption};
use std::collections::HashMap;
use std::net::Ipv4Addr;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, RwLock};
use iroh::EndpointId;
@@ -40,6 +42,24 @@ pub struct Route {
pub peer: EndpointId,
}
/// An internet source is valid only for a reply to our address in the exit's network.
pub(super) enum PacketSource {
Member,
ExitReply {
local: Option<Ipv4Addr>,
exit: Arc<SelectedExit>,
},
}
/// A packet holds its selection until delivery finishes, even if the operator
/// switches to another exit in the meantime.
#[derive(Debug)]
pub(super) struct SelectedExit {
route: Route,
pub(super) tx_bytes: AtomicU64,
pub(super) rx_bytes: AtomicU64,
}
/// A network's exit-node settings, as far as packets are concerned.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ExitPolicy {
@@ -65,6 +85,44 @@ pub struct NetworkRoutes {
pub peers: Vec<(Ipv4Addr, EndpointId)>,
}
impl NetworkRoutes {
fn address_pair(&self, peer: EndpointId) -> Option<(Ipv4Addr, Ipv4Addr)> {
let local = self.local?;
let (remote, _) = self.peers.iter().find(|(_, owner)| *owner == peer)?;
Some((local, *remote))
}
}
/// The signed addresses negotiated for one running diagnostic. A new allocation can
/// invalidate either end, so an active probe must recheck them when ownership changes.
pub(crate) struct DiagnosticPeer {
network: NetworkId,
peer: EndpointId,
pub(crate) local: Ipv4Addr,
pub(crate) remote: Ipv4Addr,
// Even revision of the checked routing table, plus one if both addresses matched.
checked: AtomicU64,
}
impl DiagnosticPeer {
pub(crate) fn is_current(&self, table: &RoutingTable) -> bool {
let revision = table.address_revision.load(Ordering::Acquire);
let checked = self.checked.load(Ordering::Relaxed);
if checked & !1 == revision {
return checked & 1 != 0;
}
let networks = table.read();
let pair = networks
.get(&self.network)
.and_then(|n| n.address_pair(self.peer));
let valid = pair == Some((self.local, self.remote));
let revision = table.address_revision.load(Ordering::Relaxed);
self.checked
.store(revision | u64::from(valid), Ordering::Relaxed);
valid
}
}
/// Why a network cannot be added to the table.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RouteError {
@@ -89,9 +147,14 @@ pub enum RouteError {
/// Address ownership across every network this agent is in.
#[derive(Debug, Default)]
pub struct RoutingTable {
pub(crate) traffic: Arc<crate::traffic::TrafficMonitor>,
pub(crate) vips: Arc<crate::vip::VipRouter>,
pub(super) exit_activity: super::exit_activity::ExitActivity,
broadcast: ArcSwap<BroadcastTable>,
selected_exit: ArcSwapOption<SelectedExit>,
networks: RwLock<HashMap<NetworkId, NetworkRoutes>>,
/// Advanced by two under the routing write lock when signed address ownership changes.
address_revision: AtomicU64,
}
impl RoutingTable {
@@ -100,6 +163,23 @@ impl RoutingTable {
Self::default()
}
/// Exact local and signed remote addresses for a mesh diagnostic. Exit routes do not qualify.
pub(crate) fn diagnostic_peer(
&self,
network: NetworkId,
peer: EndpointId,
) -> Option<DiagnosticPeer> {
let networks = self.read();
let (local, remote) = networks.get(&network)?.address_pair(peer)?;
Some(DiagnosticPeer {
network,
peer,
local,
remote,
checked: AtomicU64::new(self.address_revision.load(Ordering::Relaxed) | 1),
})
}
fn read(&self) -> std::sync::RwLockReadGuard<'_, HashMap<NetworkId, NetworkRoutes>> {
match self.networks.read() {
Ok(guard) => guard,
@@ -120,7 +200,29 @@ impl RoutingTable {
/// interface an address can belong to only one network, and guessing
/// which would send somebody's traffic to a stranger.
pub fn set_network(&self, network: NetworkId, routes: NetworkRoutes) -> Result<(), RouteError> {
self.replace_network(&mut self.write(), network, routes)
}
/// A fresh allocation snapshot cannot change the operator's exit settings.
pub(crate) fn update_allocations(
&self,
network: NetworkId,
mut routes: NetworkRoutes,
) -> Result<(), RouteError> {
let mut networks = self.write();
routes.exit = networks
.get(&network)
.map(|current| current.exit)
.unwrap_or_default();
self.replace_network(&mut networks, network, routes)
}
fn replace_network(
&self,
networks: &mut HashMap<NetworkId, NetworkRoutes>,
network: NetworkId,
routes: NetworkRoutes,
) -> Result<(), RouteError> {
if let Some(range) = routes.range {
for (other, existing) in networks.iter() {
if *other == network {
@@ -139,9 +241,26 @@ impl RoutingTable {
}
}
}
if routes.exit.via.is_some() {
clear_other_exits(networks, network);
}
let ownership_changed = networks
.get(&network)
.is_none_or(|old| old.local != routes.local || old.peers != routes.peers);
if ownership_changed
|| networks
.get(&network)
.is_some_and(|old| old.exit.offer != routes.exit.offer)
{
self.exit_activity.configure(network, Some(&routes));
}
networks.insert(network, routes);
if ownership_changed {
self.address_revision.fetch_add(2, Ordering::Release);
}
self.refresh_exit(networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
.store(Arc::new(BroadcastTable::build(networks)));
Ok(())
}
@@ -149,7 +268,11 @@ impl RoutingTable {
pub fn remove_network(&self, network: NetworkId) {
self.vips.remove_network(network);
let mut networks = self.write();
networks.remove(&network);
self.exit_activity.configure(network, None);
if networks.remove(&network).is_some() {
self.address_revision.fetch_add(2, Ordering::Release);
}
self.refresh_exit(&networks);
self.broadcast
.store(Arc::new(BroadcastTable::build(&networks)));
}
@@ -172,11 +295,53 @@ impl RoutingTable {
/// A network that has no entry yet (its range is not agreed) takes them
/// from [`NetworkRoutes::exit`] when it is added.
pub fn set_exit(&self, network: NetworkId, policy: ExitPolicy) {
if let Some(routes) = self.write().get_mut(&network) {
routes.exit = policy;
self.update_exit(network, |current| *current = policy);
}
pub(crate) fn update_exit(&self, network: NetworkId, update: impl FnOnce(&mut ExitPolicy)) {
let mut networks = self.write();
if let Some(routes) = networks.get_mut(&network) {
let offered = routes.exit.offer;
update(&mut routes.exit);
if offered != routes.exit.offer {
self.exit_activity.configure(network, Some(routes));
}
if routes.exit.via.is_some() {
clear_other_exits(&mut networks, network);
}
self.refresh_exit(&networks);
}
}
/// Publish the current choice under the same write lock as the route edits.
fn refresh_exit(&self, networks: &HashMap<NetworkId, NetworkRoutes>) {
let route = exit_via(networks).map(|(network, peer)| Route { network, peer });
if self.selected_exit.load().as_ref().map(|exit| exit.route) != route {
self.selected_exit.store(route.map(|route| {
Arc::new(SelectedExit {
route,
tx_bytes: AtomicU64::default(),
rx_bytes: AtomicU64::default(),
})
}));
}
}
pub(crate) fn recent_exit_client(&self, network: NetworkId, peer: EndpointId) -> bool {
self.exit_activity.recent(network, peer)
}
pub(crate) fn exit_traffic(&self, network: NetworkId, peer: EndpointId) -> Option<ExitTraffic> {
let current = self.selected_exit.load();
let exit = current
.as_ref()
.filter(|e| e.route == Route { network, peer })?;
Some(ExitTraffic {
tx_bytes: exit.tx_bytes.load(Ordering::Relaxed),
rx_bytes: exit.rx_bytes.load(Ordering::Relaxed),
})
}
/// Recognizes limited and configured subnet broadcasts before unicast lookup.
pub fn is_broadcast(&self, destination: Ipv4Addr) -> bool {
self.broadcast.load().is_destination(destination)
@@ -210,6 +375,14 @@ impl RoutingTable {
/// unicast destination, goes to this device's exit node when it has one:
/// that is what sending *all* traffic through a member means.
pub fn route(&self, destination: Ipv4Addr) -> Option<Route> {
self.packet_route(None, destination).map(|(route, _)| route)
}
pub(super) fn packet_route(
&self,
source: Option<Ipv4Addr>,
destination: Ipv4Addr,
) -> Option<(Route, Option<Arc<SelectedExit>>)> {
let networks = self.read();
for (network, routes) in networks.iter() {
if routes.local == Some(destination) {
@@ -220,10 +393,13 @@ impl RoutingTable {
.iter()
.find(|(address, _)| *address == destination)
{
return Some(Route {
network: *network,
peer: *peer,
});
return Some((
Route {
network: *network,
peer: *peer,
},
None,
));
}
}
// Inside an overlay range, an unowned address is nobody's, not the
@@ -231,7 +407,16 @@ impl RoutingTable {
if !is_internet_destination(destination) || in_any_range(&networks, destination) {
return None;
}
exit_via(&networks).map(|(network, peer)| Route { network, peer })
let exit = self.selected_exit.load_full()?;
// The host's default route may hand a forwarded packet back to the TUN.
// Only this device can originate traffic for its own upstream. Replies
// to a member above still route by destination with their internet source.
if let Some(source) = source
&& networks.get(&exit.route.network)?.local != Some(source)
{
return None;
}
Some((exit.route, Some(exit)))
}
/// Whether a peer may send from a source address.
@@ -241,20 +426,33 @@ impl RoutingTable {
/// internet carries the internet's addresses, so from *that* peer any
/// source outside the overlay ranges is accepted.
pub fn may_send_from(&self, network: NetworkId, peer: EndpointId, source: Ipv4Addr) -> bool {
self.packet_source(network, peer, source).is_some()
}
pub(super) fn packet_source(
&self,
network: NetworkId,
peer: EndpointId,
source: Ipv4Addr,
) -> Option<PacketSource> {
let networks = self.read();
let Some(routes) = networks.get(&network) else {
return false;
};
let routes = networks.get(&network)?;
if routes
.peers
.iter()
.any(|(address, holder)| *address == source && *holder == peer)
{
return true;
return Some(PacketSource::Member);
}
routes.exit.via == Some(peer)
let current = self.selected_exit.load();
let exit = current.as_ref()?;
(exit.route == Route { network, peer }
&& is_internet_destination(source)
&& !in_any_range(&networks, source)
&& !in_any_range(&networks, source))
.then(|| PacketSource::ExitReply {
local: routes.local,
exit: Arc::clone(exit),
})
}
/// Whether this agent, as an exit node of `network`, takes a member's
@@ -275,10 +473,12 @@ impl RoutingTable {
/// The network and member this device sends its internet traffic through.
///
/// One default route, so one answer; if several networks claim one (they
/// should not) the lowest network id decides, so two runs agree.
/// Choosing another exit replaces the previous one under the table's write lock.
pub fn exit_via(&self) -> Option<(NetworkId, EndpointId)> {
exit_via(&self.read())
self.selected_exit
.load()
.as_ref()
.map(|exit| (exit.route.network, exit.route.peer))
}
/// Whether a default route is selected and the local source valid in that network.
@@ -423,12 +623,19 @@ fn in_any_range(networks: &HashMap<NetworkId, NetworkRoutes>, address: Ipv4Addr)
.any(|routes| routes.range.is_some_and(|range| range.contains(address)))
}
/// The exit node in use, if any, from the lowest network that names one.
fn clear_other_exits(networks: &mut HashMap<NetworkId, NetworkRoutes>, selected: NetworkId) {
for (id, routes) in networks {
if *id != selected {
routes.exit.via = None;
}
}
}
/// Only the selected network can have an exit peer.
fn exit_via(networks: &HashMap<NetworkId, NetworkRoutes>) -> Option<(NetworkId, EndpointId)> {
networks
.iter()
.filter_map(|(network, routes)| Some((*network, routes.exit.via?)))
.min_by_key(|(network, _)| *network)
.find_map(|(network, routes)| Some((*network, routes.exit.via?)))
}
/// Whether two ranges share any address.
@@ -472,6 +679,60 @@ mod tests {
}
}
#[test]
fn a_running_diagnostic_tracks_signed_ownership_across_route_changes() {
let table = RoutingTable::new();
let id = network("diagnostic");
let other = network("other");
table.set_network(id, routes()).unwrap();
let bound = table.diagnostic_peer(id, peer(2)).unwrap();
assert_eq!((bound.local, bound.remote), (addr(1), addr(2)));
assert!(bound.is_current(&table));
assert!(table.diagnostic_peer(id, peer(9)).is_none());
assert!(table.set_network(other, routes()).is_err());
table.set_exit(
id,
ExitPolicy {
offer: true,
via: Some(peer(3)),
},
);
assert!(bound.is_current(&table));
let mut changed = routes();
changed.peers[1].0 = addr(9);
table.update_allocations(id, changed.clone()).unwrap();
assert!(bound.is_current(&table), "another member moved");
changed.peers[0].0 = addr(7);
table.update_allocations(id, changed).unwrap();
assert!(
!bound.is_current(&table),
"the old peer address is no longer owned"
);
assert!(!bound.is_current(&table));
let moved = table.diagnostic_peer(id, peer(2)).unwrap();
assert!(moved.is_current(&table));
table
.update_allocations(
id,
NetworkRoutes {
local: None,
..routes()
},
)
.unwrap();
assert!(!moved.is_current(&table));
assert!(table.diagnostic_peer(id, peer(2)).is_none());
table.update_allocations(id, routes()).unwrap();
assert!(bound.is_current(&table));
table.remove_network(id);
table.set_network(other, routes()).unwrap();
assert!(
!bound.is_current(&table),
"same member and IPs in a different network"
);
}
#[test]
fn a_packet_goes_to_the_member_that_holds_its_destination() {
let table = RoutingTable::new();
@@ -745,6 +1006,72 @@ mod tests {
const INTERNET: Ipv4Addr = Ipv4Addr::new(93, 184, 216, 34);
#[test]
fn tunnel_warming_follows_the_selected_membership_on_restore_switch_and_off() {
let table = Arc::new(RoutingTable::new());
let (tx, _rx) = tokio::sync::mpsc::channel(1);
let context = crate::dataplane::PluginContext::new(tx, peer(1), None, &table);
let (a, b) = (network("left"), network("right"));
let exit = peer(2);
table.set_network(a, with_exit(false, Some(exit))).unwrap();
table.set_network(b, NetworkRoutes::default()).unwrap();
assert_eq!(context.warm_peer(a), Some(exit));
assert_eq!(context.warm_peer(b), None);
let select = |via| ExitPolicy { offer: true, via };
table.set_exit(b, select(Some(exit)));
assert_eq!(context.warm_peer(a), None);
assert_eq!(context.warm_peer(b), Some(exit));
table.set_exit(b, select(None));
assert_eq!(
context.warm_peer(b),
None,
"offering an exit does not select one"
);
table.set_exit(a, select(Some(exit)));
table.remove_network(a);
assert_eq!(context.warm_peer(a), None);
}
#[test]
fn refreshing_either_networks_addresses_preserves_the_last_exit_choice() {
let table = RoutingTable::new();
let (a, b) = (network("first"), network("second"));
let first = with_exit(true, Some(peer(2)));
let second = NetworkRoutes {
range: Some("10.99.0.0/24".parse().unwrap()),
local: Some(Ipv4Addr::new(10, 99, 0, 1)),
..Default::default()
};
table.set_network(a, first.clone()).unwrap();
table.set_network(b, second.clone()).unwrap();
table.set_exit(
b,
ExitPolicy {
offer: false,
via: Some(peer(3)),
},
);
table.update_allocations(a, first).unwrap();
table.update_allocations(b, second).unwrap();
assert_eq!(
table.exit_client(),
(true, Some(Ipv4Addr::new(10, 99, 0, 1)))
);
assert_eq!(table.exit_via(), Some((b, peer(3))));
assert_eq!(
table.exit_settings(a).unwrap().0,
ExitPolicy {
offer: true,
via: None
}
);
table.remove_network(a);
assert_eq!(table.exit_via(), Some((b, peer(3))));
table.remove_network(b);
assert_eq!(table.exit_via(), None);
}
#[test]
fn without_an_exit_node_the_internet_has_nowhere_to_go() {
let table = RoutingTable::new();
@@ -819,7 +1146,7 @@ mod tests {
}
#[test]
fn two_exit_choices_resolve_to_the_lowest_network_id() {
fn competing_exit_choices_use_the_same_peer_for_requests_and_replies() {
let table = RoutingTable::new();
let (a, b) = (network("one"), network("two"));
table
@@ -838,9 +1165,10 @@ mod tests {
},
)
.unwrap();
let (chosen, _) = table.exit_via().unwrap();
assert_eq!(chosen, a.min(b));
assert_eq!(table.route(INTERNET).unwrap().network, a.min(b));
assert_eq!(table.exit_via(), Some((b, peer(9))));
assert_eq!(table.route(INTERNET).unwrap().network, b);
assert!(table.may_send_from(b, peer(9), INTERNET));
assert!(!table.may_send_from(a, peer(2), INTERNET));
}
#[test]
+787
View File
@@ -0,0 +1,787 @@
//! Translate host-selected IPv4 aliases at the local packet interface.
use super::Cidr;
use super::packet::{Ipv4Reassembly, fragment_ipv4};
use bytes::Bytes;
use smoltcp::wire::{Ipv4Cidr, Ipv4Packet};
use std::collections::HashMap;
use std::net::{IpAddr, Ipv4Addr};
use std::time::{Duration, Instant};
mod icmp;
#[cfg(any(all(windows, feature = "tun-device"), test))]
pub(crate) mod windows;
// No mappings are persisted, and a new flow cannot evict a live socket.
const MAX_FLOWS: usize = 4096;
const MAX_FRAGMENTED: usize = 16;
const UDP_IDLE: Duration = Duration::from_secs(120);
const TCP_IDLE: Duration = Duration::from_secs(2 * 60 * 60);
const ECHO_IDLE: Duration = Duration::from_secs(30);
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct WireFlow {
local: Ipv4Addr,
remote: Ipv4Addr,
protocol: u8,
local_port: u16,
remote_port: u16,
}
impl WireFlow {
// ICMP errors quote as few as eight transport bytes; the caller validates
// the outer packet separately. Echo requests in opposite directions can
// have the same identifier without sharing a flow.
fn parse(packet: &[u8], outbound: bool) -> Option<Self> {
let h = usize::from(*packet.first()? & 15) * 4;
if packet[0] >> 4 != 4
|| h < 20
|| packet.len() < h + 8
|| u16::from_be_bytes([packet[6], packet[7]]) & 0x1fff != 0
{
return None;
}
let src = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[12..16]).ok()?);
let dst = Ipv4Addr::from(<[u8; 4]>::try_from(&packet[16..20]).ok()?);
let (local, remote) = if outbound { (src, dst) } else { (dst, src) };
let protocol = packet[9];
let data = &packet[h..];
let (local_port, remote_port) = match protocol {
6 | 17 => {
let src = u16::from_be_bytes([data[0], data[1]]);
let dst = u16::from_be_bytes([data[2], data[3]]);
if outbound { (src, dst) } else { (dst, src) }
}
1 if matches!(data[0], 0 | 8) && data[1] == 0 => {
let id = u16::from_be_bytes([data[4], data[5]]);
(id, u16::from(outbound != (data[0] == 8)))
}
_ => return None,
};
Some(Self {
local,
remote,
protocol,
local_port,
remote_port,
})
}
}
#[derive(Clone, Copy)]
struct Binding {
host: Ipv4Addr,
// A response from an unbound UDP listener can leave Android with the
// primary address even though its request targeted a different alias.
remote_initiated: bool,
expires: Instant,
}
/// How the host chooses a source at the TUN boundary.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SourceMode {
/// Android can choose the primary VPN address even for another mesh.
Primary,
/// Windows chooses the matching subnet for mesh traffic, but may select
/// any local alias for a default route.
ExitOnly,
}
#[derive(Debug, PartialEq, Eq)]
struct Domains {
aliases: Vec<Ipv4Cidr>,
exit: Option<Ipv4Addr>,
mode: SourceMode,
}
impl Domains {
fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mode: SourceMode) -> Self {
let aliases = addresses
.iter()
.filter_map(|cidr| match cidr.addr {
IpAddr::V4(addr) if cidr.prefix_len <= 32 => {
Some(Ipv4Cidr::new(addr, cidr.prefix_len))
}
_ => None,
})
.collect();
Self {
aliases,
exit,
mode,
}
}
fn primary(&self) -> Option<Ipv4Addr> {
match self.mode {
SourceMode::Primary => self.aliases.first().map(Ipv4Cidr::address),
SourceMode::ExitOnly => None,
}
}
fn has(&self, addr: Ipv4Addr) -> bool {
self.aliases.iter().any(|alias| alias.address() == addr)
}
fn owner(&self, remote: Ipv4Addr) -> Option<Ipv4Addr> {
if remote.is_broadcast()
|| remote.is_multicast()
|| remote.is_unspecified()
|| remote.is_loopback()
|| self.has(remote)
{
return None;
}
if let Some(prefix) = self.aliases.iter().find(|p| p.contains_addr(&remote)) {
return (self.mode == SourceMode::Primary && prefix.broadcast() != Some(remote))
.then(|| prefix.address());
}
self.exit
}
}
/// Bounded flow bindings restore replies to the socket that opened each flow.
pub struct SourceFlows {
domains: Domains,
mtu: u32,
flows: HashMap<Ipv4Addr, HashMap<WireFlow, Binding>>,
primary_has_translations: bool,
last_sweep: Instant,
outgoing_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
incoming_parts: HashMap<Ipv4Addr, Ipv4Reassembly>,
}
impl SourceFlows {
/// Addresses are in the same order as on the device, primary first where applicable.
pub fn new(addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32, mode: SourceMode) -> Self {
Self {
domains: Domains::new(addresses, exit, mode),
mtu,
flows: HashMap::new(),
primary_has_translations: false,
last_sweep: Instant::now(),
outgoing_parts: HashMap::new(),
incoming_parts: HashMap::new(),
}
}
/// Keep live bindings whose host and wire addresses still belong to the same domains.
pub fn reconfigure(&mut self, addresses: &[Cidr], exit: Option<Ipv4Addr>, mtu: u32) {
self.domains = Domains::new(addresses, exit, self.domains.mode);
self.mtu = mtu;
self.flows.retain(|_, table| {
table.retain(|wire, entry| {
self.domains.has(entry.host) && self.domains.owner(wire.remote) == Some(wire.local)
});
!table.is_empty()
});
self.refresh_primary();
// Outstanding fragments belong to the previous VPN attachment.
self.outgoing_parts.clear();
self.incoming_parts.clear();
}
fn refresh_primary(&mut self) {
if let Some(primary) = self.domains.primary() {
self.primary_has_translations = self
.flows
.get(&primary)
.is_some_and(|table| table.values().any(|entry| entry.host != primary));
if !self.primary_has_translations {
self.flows.remove(&primary);
}
}
}
/// Packets read from the host.
pub fn outbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, true)
}
/// Packets admitted by the mesh and destined for the host.
pub fn inbound(&mut self, packet: Bytes) -> Vec<Bytes> {
self.process(packet, false)
}
fn process(&mut self, packet: Bytes, outbound: bool) -> Vec<Bytes> {
if self.domains.aliases.len() < 2 || packet.first().is_none_or(|byte| byte >> 4 != 4) {
return vec![packet];
}
let Ok(ip) = Ipv4Packet::new_checked(&packet[..]) else {
return vec![];
};
let h = usize::from(ip.header_len());
if h < 20 || usize::from(ip.total_len()) != packet.len() {
return vec![];
}
let (local, remote) = if outbound {
(ip.src_addr(), ip.dst_addr())
} else {
(ip.dst_addr(), ip.src_addr())
};
// ICMP errors can come from a router other than the original peer.
let is_icmp = packet[9] == 1;
let owner = self.domains.owner(remote);
let fragmented = ip.more_frags() || ip.frag_offset() != 0;
if self.domains.mode == SourceMode::ExitOnly {
// A mesh router can report PMTU for an internet flow whose source
// we translated. All other native mesh and forwarded packets pass
// directly, including fragments and packets headed to the gateway.
let exit_error = !outbound
&& Some(local) == self.domains.exit
&& is_icmp
&& (fragmented || matches!(packet.get(h), Some(3 | 11 | 12)));
if !self.domains.has(local) || (owner.is_none() && !exit_error) {
return vec![packet];
}
}
if !ip.verify_checksum() {
return vec![];
}
let primary = self.domains.primary();
// The kernel already uses the primary address for its own subnet. A
// primary change can leave earlier translated sockets draining there.
if Some(local) == primary
&& (!outbound || owner == primary)
&& !self.primary_has_translations
{
return vec![packet];
}
if owner.is_none() && !(is_icmp && self.domains.has(local)) {
return vec![packet];
}
if !self.domains.has(local) {
// Never translate addresses outside the local host's assignments.
return if outbound { vec![] } else { vec![packet] };
}
let now = Instant::now();
if now.duration_since(self.last_sweep) >= Duration::from_secs(5) {
self.flows.retain(|_, table| {
table.retain(|_, entry| now < entry.expires);
!table.is_empty()
});
self.refresh_primary();
self.last_sweep = now;
}
let packet = if fragmented {
let parts = if outbound {
&mut self.outgoing_parts
} else {
&mut self.incoming_parts
};
let key = if outbound {
owner.unwrap_or(local)
} else {
local
};
let Some(packet) = parts
.entry(key)
.or_default()
.accept(packet, MAX_FRAGMENTED, None)
else {
return vec![];
};
packet
} else {
packet
};
let h = usize::from(packet[0] & 15) * 4;
let output = if is_icmp
&& packet
.get(h)
.is_some_and(|kind| matches!(kind, 3 | 11 | 12))
{
icmp::rewrite_error(packet, h, !outbound, |quote, quote_outbound| {
let binding = WireFlow::parse(quote, quote_outbound)
.and_then(|flow| self.domains.owner(flow.remote).map(|alias| (flow, alias)));
let Some((flow, alias)) = binding else {
// The quote passed validation but never required exit translation,
// for example a native socket talking to a peer inside the mesh.
return (self.domains.mode == SourceMode::ExitOnly).then_some((local, local));
};
let wire = WireFlow {
local: alias,
..flow
};
let entry = self
.flows
.get(&wire.local)
.and_then(|table| table.get(&wire))
.filter(|entry| now < entry.expires);
let Some(entry) = entry else {
return (wire.local == flow.local
&& (Some(wire.local) == primary
|| self.domains.mode == SourceMode::ExitOnly))
.then_some((wire.local, wire.local));
};
if quote_outbound {
(flow.local == wire.local).then_some((wire.local, entry.host))
} else {
(flow.local == entry.host).then_some((entry.host, wire.local))
}
})
} else {
self.translate(packet, h, local, remote, outbound, now)
};
match output {
Some(packet) if fragmented => fragment_ipv4(packet, self.mtu),
Some(packet) => vec![packet],
None => vec![],
}
}
fn translate(
&mut self,
packet: Bytes,
h: usize,
local: Ipv4Addr,
remote: Ipv4Addr,
outbound: bool,
now: Instant,
) -> Option<Bytes> {
let Some(alias) = self.domains.owner(remote) else {
return Some(packet);
};
// VIP/exit replies and any other special delivery already admitted by
// core may have a source outside the addressed subnet.
if !outbound && local != alias {
return Some(packet);
}
let Some(flow) = WireFlow::parse(&packet, outbound) else {
return (local == alias).then_some(packet);
};
let data = &packet[h..];
let idle = match flow.protocol {
6 => {
let n = usize::from(*data.get(12)? >> 4) * 4;
if n < 20 || n > data.len() {
return None;
}
if data[13] & 5 != 0 {
UDP_IDLE
} else {
TCP_IDLE
}
}
17 => {
if usize::from(u16::from_be_bytes([data[4], data[5]])) != data.len() {
return None;
}
UDP_IDLE
}
_ => ECHO_IDLE,
};
let wire = WireFlow {
local: alias,
..flow
};
let table = self.flows.entry(alias).or_default();
if table.get(&wire).is_some_and(|entry| entry.expires <= now) {
table.remove(&wire);
}
if !table.contains_key(&wire) {
if Some(alias) == self.domains.primary() && local == alias {
return Some(packet);
}
if table.len() >= MAX_FLOWS {
return None;
}
if outbound
&& local != alias
&& (self
.domains
.primary()
.is_some_and(|primary| primary != local)
|| flow.protocol == 6 && data[13] & 0x12 != 2)
{
return None;
}
}
let entry = table.entry(wire).or_insert(Binding {
host: local,
remote_initiated: !outbound,
expires: now + idle,
});
let target = if outbound {
if local != entry.host {
let wildcard_reply = entry.remote_initiated
&& entry.host == alias
&& flow.protocol == 17
&& self.domains.primary() == Some(local);
if !wildcard_reply {
return None;
}
}
alias
} else {
if entry.host != alias && flow.protocol == 6 && data[13] & 0x12 == 2 {
return None;
}
entry.host
};
entry.expires = now + idle;
if target == local {
return Some(packet);
}
let mut out = packet.to_vec();
let address = if outbound { 12 } else { 16 };
out[address..address + 4].copy_from_slice(&target.octets());
let check = u16::from_be_bytes([out[10], out[11]]);
out[10..12].copy_from_slice(&update_checksum(check, local, target).to_be_bytes());
if matches!(flow.protocol, 6 | 17) {
let off = h + if flow.protocol == 6 { 16 } else { 6 };
let check = u16::from_be_bytes([out[off], out[off + 1]]);
if flow.protocol == 6 || check != 0 {
let new = update_checksum(check, local, target);
let new = if new == 0 && flow.protocol == 17 {
u16::MAX
} else {
new
};
out[off..off + 2].copy_from_slice(&new.to_be_bytes());
}
}
Some(out.into())
}
}
/// RFC 1624 one's-complement adjustment for replacing an IPv4 address.
fn update_checksum(checksum: u16, old: Ipv4Addr, new: Ipv4Addr) -> u16 {
let mut sum = u32::from(!checksum);
for (old, new) in old
.octets()
.as_chunks::<2>()
.0
.iter()
.zip(new.octets().as_chunks::<2>().0)
{
sum += u32::from(!u16::from_be_bytes(*old)) + u32::from(u16::from_be_bytes(*new));
}
while sum >> 16 != 0 {
sum = (sum & 0xffff) + (sum >> 16);
}
!(sum as u16)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
const FIRST: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const SECOND: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 8);
fn aliases() -> Vec<Cidr> {
vec![
Cidr::new(FIRST.into(), 24).unwrap(),
Cidr::new(SECOND.into(), 24).unwrap(),
]
}
fn udp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, payload: &[u8]) -> Bytes {
use smoltcp::wire::{IpAddress, Ipv4Packet, UdpPacket};
let mut bytes = vec![0; 28 + payload.len()];
bytes[0] = 0x45;
let size = bytes.len() as u16;
bytes[2..4].copy_from_slice(&size.to_be_bytes());
bytes[8] = 64;
bytes[9] = 17;
bytes[12..16].copy_from_slice(&src.octets());
bytes[16..20].copy_from_slice(&dst.octets());
Ipv4Packet::new_unchecked(&mut bytes[..]).fill_checksum();
let mut udp = UdpPacket::new_unchecked(&mut bytes[20..]);
udp.set_src_port(sport);
udp.set_dst_port(dport);
udp.set_len(size - 20);
udp.payload_mut().copy_from_slice(payload);
udp.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
bytes.into()
}
#[test]
fn connected_udp_keeps_its_kernel_address_while_the_peer_sees_the_right_alias() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let request = udp(FIRST, PEER, 4123, 1234, b"request");
assert_eq!(
flows.outbound(request),
vec![udp(SECOND, PEER, 4123, 1234, b"request")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4123, b"reply")),
vec![udp(PEER, FIRST, 1234, 4123, b"reply")]
);
assert!(
flows
.outbound(udp(SECOND, PEER, 4123, 1234, b"bound collision"))
.is_empty()
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"to a listener")),
vec![udp(PEER, SECOND, 1234, 4124, b"to a listener")]
);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 4124, 1234, b"wildcard listener reply")),
vec![udp(SECOND, PEER, 4124, 1234, b"wildcard listener reply")]
);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 1234, 4124, b"again")),
vec![udp(PEER, SECOND, 1234, 4124, b"again")]
);
}
#[test]
fn windows_exit_accepts_any_local_alias_and_restores_external_replies() {
let mut flows = SourceFlows::new(&aliases(), Some(FIRST), 1280, SourceMode::ExitOnly);
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(SECOND, internet, 4123, 443, b"external");
assert_eq!(
flows.outbound(request),
[udp(FIRST, internet, 4123, 443, b"external")]
);
assert_eq!(
flows.inbound(udp(internet, FIRST, 443, 4123, b"reply")),
[udp(internet, SECOND, 443, 4123, b"reply")]
);
// An explicitly bound socket cannot take replies from this flow.
assert!(
flows
.outbound(udp(FIRST, internet, 4123, 443, b"collision"))
.is_empty()
);
// An address in either overlay, including the gateway itself, stays native.
let mesh = udp(SECOND, PEER, 4123, 443, b"mesh");
assert_eq!(flows.outbound(mesh.clone()), [mesh]);
}
#[tokio::test]
async fn wintun_normalizes_only_external_flows_while_an_exit_is_selected() {
use super::windows::ExitSourceTun;
use crate::overlay::{MemoryTun, TunDevice};
let device = MemoryTun::new("test", 1280);
let tun = ExitSourceTun::new(device.clone());
let internet = Ipv4Addr::new(203, 0, 113, 2);
let request = udp(FIRST, internet, 4000, 80, &[1; 1600]);
let on_wire = udp(SECOND, internet, 4000, 80, &[1; 1600]);
tun.set_exit_source(&aliases(), Some(SECOND));
for part in fragment_ipv4(request.clone(), 1280) {
device.push_from_os(part);
}
for expected in fragment_ipv4(on_wire, 1280) {
assert_eq!(tun.recv().await, Some(expected));
}
// Periodic exit rule refreshes must preserve the original socket.
tun.set_exit_source(&aliases(), Some(SECOND));
tun.send(udp(internet, SECOND, 80, 4000, b"reply"))
.await
.unwrap();
assert_eq!(
device.pop_to_os().await,
Some(udp(internet, FIRST, 80, 4000, b"reply"))
);
let forwarded = udp(PEER, internet, 4000, 80, b"forwarded");
device.push_from_os(forwarded.clone());
assert_eq!(tun.recv().await, Some(forwarded));
tun.set_exit_source(&aliases(), None);
device.push_from_os(request.clone());
assert_eq!(tun.recv().await, Some(request));
}
#[test]
fn proper_bound_flows_and_limited_broadcast_keep_their_identity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let native = udp(SECOND, PEER, 3000, 3001, b"bound");
assert_eq!(flows.outbound(native.clone()), vec![native]);
assert!(
flows
.outbound(udp(FIRST, PEER, 3000, 3001, b"collision"))
.is_empty()
);
let reply = udp(PEER, SECOND, 3001, 3000, b"native");
assert_eq!(flows.inbound(reply.clone()), vec![reply]);
let broadcast = udp(FIRST, Ipv4Addr::BROADCAST, 3000, 3001, b"lan");
assert_eq!(flows.outbound(broadcast.clone()), vec![broadcast]);
assert!(
flows
.outbound(udp(PEER, PEER, 3100, 3100, b"forged source"))
.is_empty()
);
}
fn packet(src: Ipv4Addr, dst: Ipv4Addr, protocol: u8, data: &[u8]) -> Bytes {
let mut out = vec![0; 20 + data.len()];
let size = out.len() as u16;
out[0] = 0x45;
out[2..4].copy_from_slice(&size.to_be_bytes());
out[8] = 64;
out[9] = protocol;
out[12..16].copy_from_slice(&src.octets());
out[16..20].copy_from_slice(&dst.octets());
out[20..].copy_from_slice(data);
Ipv4Packet::new_unchecked(&mut out).fill_checksum();
out.into()
}
fn tcp(src: Ipv4Addr, dst: Ipv4Addr, sport: u16, dport: u16, flags: u8) -> Bytes {
use smoltcp::wire::{IpAddress, TcpPacket};
let mut data = [0; 20];
data[..2].copy_from_slice(&sport.to_be_bytes());
data[2..4].copy_from_slice(&dport.to_be_bytes());
data[12] = 0x50;
data[13] = flags;
TcpPacket::new_unchecked(&mut data[..])
.fill_checksum(&IpAddress::Ipv4(src), &IpAddress::Ipv4(dst));
packet(src, dst, 6, &data)
}
#[test]
fn tcp_keeps_direction_and_bindings_survive_unrelated_plans() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert!(flows.outbound(tcp(FIRST, PEER, 333, 443, 16)).is_empty());
assert_eq!(
flows.outbound(tcp(FIRST, PEER, 333, 443, 2)),
[tcp(SECOND, PEER, 333, 443, 2)]
);
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.inbound(tcp(PEER, SECOND, 443, 333, 18)),
[tcp(PEER, FIRST, 443, 333, 18)]
);
// An inbound connection cannot replace a client's active translation.
assert!(flows.inbound(tcp(PEER, SECOND, 443, 333, 2)).is_empty());
let inbound = tcp(PEER, SECOND, 12345, 80, 2);
assert_eq!(flows.inbound(inbound.clone()), [inbound]);
let syn_ack = tcp(SECOND, PEER, 80, 12345, 18);
assert_eq!(flows.outbound(syn_ack.clone()), [syn_ack]);
aliases.remove(0);
flows.reconfigure(&aliases, None, 1280);
assert!(
!flows
.flows
.values()
.any(|table| table.values().any(|e| e.host == FIRST))
);
}
#[test]
fn a_new_primary_drains_earlier_translations_and_passes_its_own_packets() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
assert_eq!(flows.outbound(udp(FIRST, PEER, 2222, 53, b"q")).len(), 1);
aliases.swap(0, 1);
flows.reconfigure(&aliases, Some(SECOND), 1280);
assert_eq!(
flows.inbound(udp(PEER, SECOND, 53, 2222, b"a")),
[udp(PEER, FIRST, 53, 2222, b"a")]
);
let bound = udp(SECOND, PEER, 4444, 443, b"native");
assert_eq!(flows.outbound(bound.clone()), [bound]);
let native_reply = udp(PEER, SECOND, 443, 4444, b"r");
assert_eq!(flows.inbound(native_reply.clone()), [native_reply]);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn untracked_primary_errors_and_point_to_point_destinations_are_preserved() {
let mut aliases = aliases();
let mut flows = SourceFlows::new(&aliases, None, 1280, SourceMode::Primary);
let router = Ipv4Addr::new(10, 1, 0, 7);
let mut unreachable = vec![3, 1, 0, 0, 0, 0, 0, 0];
unreachable.extend_from_slice(&udp(FIRST, router, 50_000, 7, b"probe")[..28]);
smoltcp::wire::Icmpv4Packet::new_unchecked(&mut unreachable).fill_checksum();
let error = packet(router, FIRST, 1, &unreachable);
assert_eq!(flows.inbound(error.clone()), [error]);
let directed = udp(FIRST, Ipv4Addr::new(10, 2, 0, 255), 5, 6, b"broadcast");
assert_eq!(flows.outbound(directed.clone()), [directed]);
let point = Ipv4Addr::new(10, 2, 0, 0);
aliases[1] = Cidr::new(point.into(), 31).unwrap();
flows.reconfigure(&aliases, None, 1280);
assert_eq!(
flows.outbound(udp(FIRST, SECOND, 5, 6, b"p2p")),
[udp(point, SECOND, 5, 6, b"p2p")]
);
}
#[test]
fn echo_ids_can_match_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let message = |src, dst, kind| {
use smoltcp::wire::Icmpv4Packet;
let mut data = [kind, 0, 0, 0, 0x12, 0x34, 0, 2];
Icmpv4Packet::new_unchecked(&mut data[..]).fill_checksum();
packet(src, dst, 1, &data)
};
assert_eq!(
flows.outbound(message(FIRST, PEER, 8)),
[message(SECOND, PEER, 8)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 8)),
[message(PEER, SECOND, 8)]
);
assert_eq!(
flows.outbound(message(SECOND, PEER, 0)),
[message(SECOND, PEER, 0)]
);
assert_eq!(
flows.inbound(message(PEER, SECOND, 0)),
[message(PEER, FIRST, 0)]
);
}
#[test]
fn saturated_network_does_not_take_another_networks_capacity() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
for port in 0..MAX_FLOWS {
assert_eq!(
flows
.outbound(udp(FIRST, PEER, port as u16, 53, b"q"))
.len(),
1
);
}
assert!(
flows
.outbound(udp(FIRST, PEER, 60000, 53, b"full"))
.is_empty()
);
let primary_peer = Ipv4Addr::new(10, 1, 0, 20);
let own = udp(FIRST, primary_peer, 60000, 53, b"first");
assert_eq!(flows.outbound(own.clone()), [own]);
for entry in flows.flows.get_mut(&SECOND).unwrap().values_mut() {
entry.expires = Instant::now();
}
flows.last_sweep -= Duration::from_secs(6);
assert_eq!(
flows.outbound(udp(FIRST, PEER, 60000, 53, b"free")).len(),
1
);
assert_eq!(flows.flows[&SECOND].len(), 1);
}
#[test]
fn fragmented_udp_translates_after_assembly_in_both_directions() {
let mut flows = SourceFlows::new(&aliases(), None, 1280, SourceMode::Primary);
let mut original = udp(FIRST, PEER, 3333, 4444, &[7; 1900]);
let parts = fragment_ipv4(original.clone(), 1280);
let mut output = Vec::new();
for part in parts.into_iter().rev() {
output.extend(flows.outbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(SECOND, PEER, 3333, 4444, &[7; 1900]), 1280)
);
original = udp(PEER, SECOND, 4444, 3333, &[8; 1900]);
let mut output = Vec::new();
for part in fragment_ipv4(original, 1280) {
output.extend(flows.inbound(part));
}
assert_eq!(
output,
fragment_ipv4(udp(PEER, FIRST, 4444, 3333, &[8; 1900]), 1280)
);
}
}
@@ -0,0 +1,255 @@
//! Translate errors on existing flows, including truncated RFC 792 quotations.
use super::update_checksum;
use bytes::Bytes;
use smoltcp::wire::{Icmpv4Packet, IpProtocol, Ipv4Packet};
use std::net::Ipv4Addr;
pub(super) fn rewrite_error(
packet: Bytes,
header_len: usize,
inbound: bool,
mut lookup: impl FnMut(&[u8], bool) -> Option<(Ipv4Addr, Ipv4Addr)>,
) -> Option<Bytes> {
let outer = Ipv4Packet::new_checked(&packet[..]).ok()?;
if outer.version() != 4
|| header_len < 20
|| header_len != usize::from(outer.header_len())
|| usize::from(outer.total_len()) != packet.len()
|| outer.next_header() != IpProtocol::Icmp
|| outer.more_frags()
|| outer.frag_offset() != 0
|| !outer.verify_checksum()
{
return None;
}
let icmp = outer.payload();
if !Icmpv4Packet::new_checked(icmp).ok()?.verify_checksum() || !matches!(icmp[0], 3 | 11 | 12) {
return None;
}
let payload = &icmp[8..];
// RFC 4884 records the padded quotation length in words when extensions follow.
let quote = match icmp[5] {
0 => payload,
words => payload.get(..usize::from(words) * 4)?,
};
quote.get(..20)?;
// The original total length may exceed the bytes the router chose to quote.
let inner = Ipv4Packet::new_unchecked(quote);
let inner_header = usize::from(inner.header_len());
let quote_len = quote.len().min(usize::from(inner.total_len()));
if inner.version() != 4
|| inner_header < 20
|| quote_len < inner_header + 8
|| inner.frag_offset() != 0
|| !inner.verify_checksum()
{
return None;
}
let (outer_local, inner_local) = if inbound {
(outer.dst_addr(), inner.src_addr())
} else {
(outer.src_addr(), inner.dst_addr())
};
if outer_local != inner_local {
return None;
}
let (old, new) = lookup(&quote[..quote_len], inbound)?;
if old != inner_local {
return None;
}
if old == new {
return Some(packet);
}
let transport = inner.next_header();
let mut result = packet.to_vec();
let quote_start = header_len + 8;
let mut inner = Ipv4Packet::new_unchecked(&mut result[quote_start..quote_start + quote_len]);
if inbound {
inner.set_src_addr(new);
} else {
inner.set_dst_addr(new);
}
inner.fill_checksum();
let transport_bytes = &mut inner.into_inner()[inner_header..];
// A minimum TCP quote includes ports and sequence number, but not its checksum.
let field = match transport {
IpProtocol::Tcp => transport_bytes.get_mut(16..18),
IpProtocol::Udp => transport_bytes.get_mut(6..8),
_ => None,
};
if let Some(field) = field {
let previous = u16::from_be_bytes([field[0], field[1]]);
if previous != 0 || transport == IpProtocol::Tcp {
let adjusted = update_checksum(previous, old, new);
let value = if adjusted == 0 && transport == IpProtocol::Udp {
u16::MAX
} else {
adjusted
};
field.copy_from_slice(&value.to_be_bytes());
}
}
Icmpv4Packet::new_unchecked(&mut result[header_len..]).fill_checksum();
let mut outer = Ipv4Packet::new_unchecked(&mut result);
if inbound {
outer.set_dst_addr(new);
} else {
outer.set_src_addr(new);
}
outer.fill_checksum();
Some(result.into())
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use smoltcp::wire::{TcpPacket, UdpPacket};
const APP: Ipv4Addr = Ipv4Addr::new(10, 1, 0, 1);
const WIRE: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 1);
const PEER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 2);
const ROUTER: Ipv4Addr = Ipv4Addr::new(10, 2, 0, 3);
fn ipv4(protocol: u8, src: Ipv4Addr, dst: Ipv4Addr, payload: &[u8]) -> Vec<u8> {
let mut p = vec![0; 20 + payload.len()];
let total = p.len() as u16;
p[0] = 0x45;
p[2..4].copy_from_slice(&total.to_be_bytes());
p[8] = 64;
p[9] = protocol;
p[12..16].copy_from_slice(&src.octets());
p[16..20].copy_from_slice(&dst.octets());
p[20..].copy_from_slice(payload);
Ipv4Packet::new_unchecked(&mut p).fill_checksum();
p
}
fn error(src: Ipv4Addr, dst: Ipv4Addr, quote: &[u8]) -> Bytes {
let mut icmp = vec![3, 4, 0, 0, 0, 0, 5, 0];
icmp.extend_from_slice(quote);
Icmpv4Packet::new_unchecked(&mut icmp).fill_checksum();
ipv4(1, src, dst, &icmp).into()
}
#[test]
fn wintun_keeps_mesh_errors_and_restores_exit_errors_from_a_mesh_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let external = Ipv4Addr::new(203, 0, 113, 200);
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
Some(WIRE),
1280,
SourceMode::ExitOnly,
);
let mut udp = [0; 8];
udp[4..6].copy_from_slice(&8u16.to_be_bytes());
let mesh_packet = ipv4(17, WIRE, PEER, &udp);
let mesh_error = error(ROUTER, WIRE, &mesh_packet);
assert_eq!(flows.inbound(mesh_error.clone()), [mesh_error]);
let original = ipv4(17, APP, external, &udp);
let translated = flows.outbound(original.clone().into()).pop().unwrap();
assert_eq!(
flows.inbound(error(ROUTER, WIRE, &translated)),
[error(ROUTER, APP, &original)]
);
}
#[test]
fn inbound_pmtu_restores_a_truncated_udp_quote_and_preserves_the_reporting_router() {
use super::super::{SourceFlows, SourceMode};
use crate::overlay::Cidr;
let mut flows = SourceFlows::new(
&[
Cidr::new(APP.into(), 24).unwrap(),
Cidr::new(WIRE.into(), 24).unwrap(),
],
None,
1280,
SourceMode::Primary,
);
let mut udp = [0x71; 16];
udp[4..6].copy_from_slice(&16u16.to_be_bytes());
UdpPacket::new_unchecked(&mut udp[..]).fill_checksum(&APP.into(), &PEER.into());
let original = ipv4(17, APP, PEER, &udp);
let wire = flows.outbound(original.clone().into()).pop().unwrap();
let p = error(ROUTER, WIRE, &wire[..28]);
let restored = flows.inbound(p).pop().unwrap();
let outer = Ipv4Packet::new_checked(&restored[..]).unwrap();
assert!(outer.verify_checksum());
assert_eq!(outer.src_addr(), ROUTER);
assert_eq!(outer.dst_addr(), APP);
assert!(
Icmpv4Packet::new_checked(outer.payload())
.unwrap()
.verify_checksum()
);
assert_eq!(outer.payload()[6..8], 1280u16.to_be_bytes());
assert_eq!(outer.payload()[8..], original[..28]);
}
#[test]
fn outbound_error_restores_tcp_quotes_with_or_without_a_transport_checksum() {
let mut tcp = [0x41; 48];
tcp[12] = 0x50;
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &APP.into());
let original = ipv4(6, PEER, APP, &tcp);
TcpPacket::new_unchecked(&mut tcp[..]).fill_checksum(&PEER.into(), &WIRE.into());
let wire = ipv4(6, PEER, WIRE, &tcp);
for length in [28, original.len()] {
let p = error(APP, PEER, &original[..length]);
let rewritten = rewrite_error(p, 20, false, |_, outbound| {
assert!(!outbound);
Some((APP, WIRE))
})
.unwrap();
assert_eq!(rewritten, error(WIRE, PEER, &wire[..length]));
}
}
#[test]
fn malformed_quotes_unknown_flows_and_unrelated_outer_addresses_are_rejected() {
let original = ipv4(17, WIRE, PEER, &[0; 8]);
let p = error(ROUTER, WIRE, &original);
assert_eq!(
rewrite_error(p.clone(), 20, true, |_, _| Some((WIRE, WIRE))),
Some(p.clone())
);
assert!(rewrite_error(p, 20, true, |_, _| None).is_none());
for invalid in [
error(ROUTER, APP, &original),
error(ROUTER, WIRE, &original[..26]),
{
let mut fragment = original.clone();
fragment[7] = 1;
Ipv4Packet::new_unchecked(&mut fragment).fill_checksum();
error(ROUTER, WIRE, &fragment)
},
{
let mut damaged = error(ROUTER, WIRE, &original).to_vec();
damaged[22] ^= 1;
damaged.into()
},
] {
assert!(
rewrite_error(invalid, 20, true, |_, _| panic!(
"invalid quote reached lookup"
))
.is_none()
);
}
// IPv4 UDP allows a zero checksum; translation may not enable it.
let restored = rewrite_error(error(ROUTER, WIRE, &original), 20, true, |_, _| {
Some((WIRE, APP))
})
.unwrap();
assert_eq!(restored[54..56], [0, 0]);
}
}
@@ -0,0 +1,102 @@
//! Wintun default routes cannot specify a preferred IPv4 source address.
use super::{Domains, SourceFlows, SourceMode};
use crate::BoxFuture;
use crate::overlay::{Cidr, OverlayError, TunDevice};
use bytes::Bytes;
use std::net::Ipv4Addr;
use std::sync::{Arc, Mutex, MutexGuard};
pub(crate) struct ExitSourceTun {
device: Arc<dyn TunDevice>,
state: Mutex<Option<State>>,
}
struct State {
flows: SourceFlows,
pending: std::vec::IntoIter<Bytes>,
}
impl std::fmt::Debug for ExitSourceTun {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("ExitSourceTun").field(&self.device).finish()
}
}
impl ExitSourceTun {
pub(crate) fn new(device: Arc<dyn TunDevice>) -> Self {
Self {
device,
state: Mutex::default(),
}
}
fn state(&self) -> MutexGuard<'_, Option<State>> {
self.state.lock().unwrap_or_else(|e| e.into_inner())
}
}
impl TunDevice for ExitSourceTun {
fn name(&self) -> &str {
self.device.name()
}
fn mtu(&self) -> u32 {
self.device.mtu()
}
fn set_exit_source(&self, addresses: &[Cidr], source: Option<Ipv4Addr>) {
let mut active = self.state();
let domains = Domains::new(addresses, source, SourceMode::ExitOnly);
if domains.aliases.len() < 2 || !source.is_some_and(|addr| domains.has(addr)) {
*active = None;
return;
}
if let Some(state) = active.as_mut() {
if state.flows.domains != domains {
state.flows.reconfigure(addresses, source, self.mtu());
state.pending = Vec::new().into_iter();
}
} else {
*active = Some(State {
flows: SourceFlows::new(addresses, source, self.mtu(), SourceMode::ExitOnly),
pending: Vec::new().into_iter(),
});
}
}
fn recv(&self) -> BoxFuture<'_, Option<Bytes>> {
Box::pin(async {
if let Some(part) = self.state().as_mut().and_then(|s| s.pending.next()) {
return Some(part);
}
loop {
let packet = self.device.recv().await?;
let mut active = self.state();
let Some(state) = active.as_mut() else {
return Some(packet);
};
state.pending = state.flows.outbound(packet).into_iter();
if let Some(part) = state.pending.next() {
return Some(part);
}
}
})
}
fn send(&self, packet: Bytes) -> BoxFuture<'_, Result<(), OverlayError>> {
Box::pin(async move {
let parts = self
.state()
.as_mut()
.map(|s| s.flows.inbound(packet.clone()));
if let Some(parts) = parts {
for part in parts {
self.device.send(part).await?;
}
Ok(())
} else {
self.device.send(packet).await
}
})
}
}
+17 -7
View File
@@ -66,6 +66,10 @@ pub trait TunDevice: Send + Sync + std::fmt::Debug + 'static {
/// The interface MTU.
fn mtu(&self) -> u32;
/// Supply the local Wintun address and exit selection used for off-mesh flows.
#[cfg(any(windows, test))]
fn set_exit_source(&self, _addresses: &[super::Cidr], _source: Option<std::net::Ipv4Addr>) {}
/// The next packet the operating system wants to send, or `None` once the
/// device is gone.
fn recv(&self) -> BoxFuture<'_, Option<Bytes>>;
@@ -476,12 +480,16 @@ mod system {
let name = request.name.clone();
let (reader, writer) = tokio::io::split(device);
Ok(Arc::new(SystemTun {
let device: Arc<dyn TunDevice> = Arc::new(SystemTun {
name,
mtu: request.mtu,
reader: Mutex::new(reader),
writer: Mutex::new(writer),
}) as Arc<dyn TunDevice>)
});
#[cfg(windows)]
let device: Arc<dyn TunDevice> =
Arc::new(crate::overlay::source::windows::ExitSourceTun::new(device));
Ok(device)
}
fn open_error(name: &str, error: tun::Error) -> OverlayError {
@@ -501,6 +509,12 @@ mod system {
}
_ => false,
};
#[cfg(target_os = "macos")]
if denied {
return OverlayError::UtunDenied(format!(
"permission denied creating utun for `{name}`: {error}. Use the installed Tsunagi service for a host interface; a per-user `tsng up` can serve an exit through sockets."
));
}
if denied {
let hint = if cfg!(target_os = "windows") {
"Open PowerShell or Command Prompt with 'Run as administrator' and \
@@ -508,9 +522,6 @@ mod system {
} else if cfg!(target_os = "linux") {
"Start `tsng up` as root or grant CAP_NET_ADMIN with \
`sudo setcap cap_net_admin,cap_net_bind_service+p /path/to/tsunagi`."
} else if cfg!(target_os = "macos") {
"Creating a utun interface needs root on macOS; start `tsng up` \
with `sudo`, or install it as a root LaunchDaemon."
} else {
"Start `tsng up` with the privileges required to create a TUN interface."
};
@@ -541,8 +552,7 @@ mod system {
}
#[cfg(target_os = "macos")]
{
"Creating a utun interface needs root; start the agent with `sudo` or as a root \
LaunchDaemon, or run with `--no-tun` to keep the tunnels off the operating system."
"Check the Tsunagi system service and the macOS interface configuration."
}
#[cfg(not(any(target_os = "linux", target_os = "windows", target_os = "macos")))]
{
+77
View File
@@ -90,6 +90,31 @@ pub struct Announcement {
pub hostname: String,
/// Announced IP plugin capabilities. Opaque to the core.
pub capabilities: Vec<PluginCapability>,
/// Software release reported by this peer for display after authentication.
/// Original v8 readers stop after the capabilities.
#[serde(default, deserialize_with = "read_agent_version")]
pub agent_version: Option<String>,
/// Whether the sender selected the recipient of this authenticated session as its exit.
/// Older v8 frames end before this optional display hint.
#[serde(default, deserialize_with = "read_exit_use")]
pub uses_your_exit: Option<bool>,
}
fn read_exit_use<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<bool>, D::Error> {
Ok(Option::<bool>::deserialize(d).ok().flatten())
}
fn read_agent_version<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<String>, D::Error> {
// A frame contains exactly one envelope. EOF here is a legacy announcement.
// An unreadable display hint can also be discarded without losing the
// hostname or capabilities. Borrow the frame until the label is bounded.
let version = Option::<&str>::deserialize(d).ok().flatten().filter(|s| {
!s.is_empty()
&& s.len() <= crate::config::MAX_AGENT_VERSION_LEN
&& s.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'+' | b'-'))
});
Ok(version.map(str::to_owned))
}
/// Opens a data channel, sent by the initiator right after the membership
@@ -395,3 +420,55 @@ pub fn kind(message: &ControlMessage) -> &'static str {
ControlMessage::Bye { .. } => "bye",
}
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::panic)]
use super::*;
#[test]
fn v8_announcements_interoperate_with_and_without_a_software_version() {
// The original v8 frame ends with the capability list. Decode the
// new frame using exactly those fields as an older receiver would.
type OldFrame = ([u8; 32], u8, bool, bool, String, Vec<PluginCapability>);
let old: OldFrame = ([7; 32], 1, true, false, "lab".into(), vec![]);
let legacy = encode(&old).unwrap();
assert!(decode::<Envelope>(&legacy[..legacy.len() - 1]).is_err());
let read = |bytes: &[u8]| match decode::<Envelope>(bytes).unwrap().message {
ControlMessage::Announce(a) => a,
_ => panic!("expected announcement"),
};
let mut a = read(&legacy);
assert_eq!(a.agent_version, None);
a.agent_version = Some("2.1.0-rc.2+android".into());
let mut version_only = legacy.clone();
version_only.extend(encode(&a.agent_version).unwrap());
assert_eq!(read(&version_only).uses_your_exit, None);
a.uses_your_exit = Some(true);
let wire = encode(&Envelope {
network_id: old.0,
message: ControlMessage::Announce(a.clone()),
})
.unwrap();
assert_eq!(decode::<OldFrame>(&wire).unwrap(), old);
assert_eq!(read(&wire), a);
type VersionFrame = (
[u8; 32],
u8,
bool,
bool,
String,
Vec<PluginCapability>,
Option<String>,
);
assert_eq!(decode::<VersionFrame>(&wire).unwrap().6, a.agent_version);
for invalid in ["", "1.2.3\nforged", &"1".repeat(256)] {
let mut wire = legacy.clone();
wire.extend(encode(&Some(invalid)).unwrap());
let a = read(&wire);
assert_eq!(a.agent_version, None);
assert_eq!(a.hostname, "lab");
}
}
}
+460
View File
@@ -0,0 +1,460 @@
//! Window-scoped, local observations. Each reader owns just its current interval.
//! The first branch on the packet path skips all monitor work when nobody is watching.
use arc_swap::ArcSwap;
use serde::{Deserialize, Serialize};
use std::{
collections::HashMap,
sync::{
Arc, Mutex, Weak,
atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering},
},
time::{Duration, Instant},
};
use crate::{
NetworkId,
config::{MAX_INTERVAL_FLOWS, MAX_TRAFFIC_READERS},
iroh_types::EndpointId,
};
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
/// How the local agent handled the observed traffic.
pub enum Role {
/// Ordinary authenticated overlay traffic.
Mesh,
/// Local internet traffic carried by the selected exit peer.
ViaExit,
/// Internet traffic forwarded for a remote exit client.
ServeExit,
/// Traffic translated or probed by the virtual service router.
Vip,
/// One accepted overlay broadcast copy.
Broadcast,
/// A sample from an admitted mesh throughput test.
SpeedTest,
/// Messages on an authenticated control session.
Control,
/// Opaque datagrams forwarded between other mesh members.
Relay,
}
impl Role {
/// Whether this role counts transport data rather than locally visible IP packets.
pub fn transport(self) -> bool {
matches!(self, Self::Control | Self::Relay)
}
}
/// Addresses on the side of this agent and on the side of its authenticated peer.
/// For encrypted transit the two endpoint IDs are ordered, with TX from the first.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
pub struct FlowKey {
/// Public network identity.
pub network: [u8; 32],
/// Authenticated peer, or first endpoint of an opaque relay pair.
pub peer: [u8; 32],
/// Local forwarding or transport role.
pub role: Role,
/// Admitted header metadata used for aggregation.
pub flow: Flow,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
/// One bidirectional IP conversation, control session, or opaque relay pair.
pub enum Flow {
/// IPv4 endpoints from the agent-facing and peer-facing sides.
Ip {
/// Source when sending, destination when receiving.
near: [u8; 4],
/// Destination when sending, source when receiving.
far: [u8; 4],
/// IPv4 protocol number.
protocol: u8,
/// Transport header fields available in this packet.
detail: IpDetail,
},
/// Aggregated authenticated control envelopes.
Control,
/// An end-to-end mesh envelope passing through this device.
Relay {
/// The second endpoint, ordered by public key.
other: [u8; 32],
/// Opaque plugin protocol tag carried by the relay header.
wire_protocol: u64,
},
}
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
/// Transport fields read from an IPv4 header and its bounded prefix.
pub enum IpDetail {
/// TCP/UDP ports in near/far order.
Ports(u16, u16),
/// ICMP echo requests and replies for the address pair.
Echo,
/// Another ICMP type and code.
Icmp(u8, u8),
/// Noninitial fragment with no transport header.
Fragment,
/// Protocol has no recognised, readable transport prefix.
Other,
}
#[derive(Clone, Copy)]
pub(crate) enum Direction {
Tx,
Rx,
}
impl Flow {
pub(crate) fn ip(packet: &[u8], dir: Direction) -> Option<Self> {
let header = packet.get(..20)?;
let offset = usize::from(header[0] & 15) * 4;
let total = usize::from(u16::from_be_bytes([header[2], header[3]]));
if header[0] >> 4 != 4 || offset < 20 {
return None;
}
let body = packet.get(..total)?.get(offset..)?;
let protocol = header[9];
let a: [u8; 4] = header[12..16].try_into().ok()?;
let b: [u8; 4] = header[16..20].try_into().ok()?;
let (near, far) = match dir {
Direction::Tx => (a, b),
Direction::Rx => (b, a),
};
let detail = if (u16::from_be_bytes([header[6], header[7]]) & 0x1fff) != 0 {
IpDetail::Fragment
} else {
match (protocol, body) {
(6 | 17, [a, b, c, d, ..]) => {
let (src, dst) = (u16::from_be_bytes([*a, *b]), u16::from_be_bytes([*c, *d]));
match dir {
Direction::Tx => IpDetail::Ports(src, dst),
Direction::Rx => IpDetail::Ports(dst, src),
}
}
(1, [0 | 8, 0, ..]) => IpDetail::Echo,
(1, [kind, code, ..]) => IpDetail::Icmp(*kind, *code),
_ => IpDetail::Other,
}
};
Some(Self::Ip {
near,
far,
protocol,
detail,
})
}
}
#[derive(Clone, Debug, Serialize, Deserialize)]
/// Counters added during one observation interval.
pub struct FlowDelta {
/// Stable bidirectional identity of this flow.
pub key: FlowKey,
/// Bytes sent in this interval.
pub tx_bytes: u64,
/// Bytes received in this interval.
pub rx_bytes: u64,
/// Packets or transport messages sent.
pub tx_packets: u64,
/// Packets or transport messages received.
pub rx_packets: u64,
/// Age of the most recent observation when the interval was drained.
pub age_ms: u64,
}
#[derive(Default, Debug, Serialize, Deserialize)]
/// An interval delta for one local subscriber.
pub struct TrafficSnapshot {
/// Flows observed since the previous drain.
pub flows: Vec<FlowDelta>,
/// Elapsed monotonic milliseconds since opening or the preceding drain.
pub interval_ms: u64,
/// Packets/messages that could not be counted during this interval.
pub omitted: u64,
}
#[derive(Debug)]
struct Counts {
tx: u64,
rx: u64,
ntx: u64,
nrx: u64,
last: Instant,
}
#[derive(Debug)]
struct Bucket {
// Concurrent writers can spill into a different lane, including the reverse
// direction of the same flow. The window merges these after the drain.
lanes: [Mutex<HashMap<FlowKey, Counts>>; 4],
since: Mutex<Instant>,
entries: AtomicUsize,
omitted: AtomicU64,
}
fn millis(d: Duration) -> u64 {
u64::try_from(d.as_millis()).unwrap_or(u64::MAX)
}
impl Bucket {
fn add(&self, key: FlowKey, dir: Direction, len: u64, now: Instant) {
for lane in &self.lanes {
let Ok(mut flows) = lane.try_lock() else {
continue;
};
let counts = match flows.entry(key) {
std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
std::collections::hash_map::Entry::Vacant(e) => {
if self.entries.fetch_add(1, Ordering::Relaxed) >= MAX_INTERVAL_FLOWS {
self.entries.fetch_sub(1, Ordering::Relaxed);
continue;
}
e.insert(Counts {
tx: 0,
rx: 0,
ntx: 0,
nrx: 0,
last: now,
})
}
};
counts.last = counts.last.max(now);
let (bytes, packets) = match dir {
Direction::Tx => (&mut counts.tx, &mut counts.ntx),
Direction::Rx => (&mut counts.rx, &mut counts.nrx),
};
*bytes = bytes.saturating_add(len);
*packets = packets.saturating_add(1);
return;
}
self.omitted.fetch_add(1, Ordering::Relaxed);
}
}
#[derive(Default, Debug)]
pub(crate) struct TrafficMonitor {
active: AtomicBool,
readers: ArcSwap<Vec<Weak<Bucket>>>,
// Only registration/unregistration use this lock.
registration: Mutex<()>,
}
impl TrafficMonitor {
pub(crate) fn subscribe(self: &Arc<Self>) -> Result<TrafficSubscription, String> {
let _edit = self.registration.lock().unwrap_or_else(|e| e.into_inner());
let mut readers = (**self.readers.load()).clone();
if readers.len() >= MAX_TRAFFIC_READERS {
return Err("Too many traffic monitor windows are open".into());
}
let bucket = Arc::new(Bucket {
lanes: Default::default(),
since: Mutex::new(Instant::now()),
entries: AtomicUsize::new(0),
omitted: AtomicU64::new(0),
});
readers.push(Arc::downgrade(&bucket));
self.readers.store(Arc::new(readers));
self.active.store(true, Ordering::Release);
Ok(TrafficSubscription {
owner: Arc::downgrade(self),
bucket,
})
}
pub(crate) fn prepare(
&self,
make: impl FnOnce() -> Option<(FlowKey, Direction, u64)>,
) -> Observation {
if !self.active.load(Ordering::Acquire) {
return Observation(None);
}
let readers = self.readers.load_full();
Observation(make().map(|(key, dir, len)| Pending {
readers,
key,
dir,
len,
}))
}
pub(crate) fn packet(
&self,
network: NetworkId,
peer: EndpointId,
dir: Direction,
packet: &[u8],
role: impl FnOnce() -> Role,
) -> Observation {
self.prepare(|| {
Some((
FlowKey {
network: *network.as_bytes(),
peer: *peer.as_bytes(),
role: role(),
flow: Flow::ip(packet, dir)?,
},
dir,
packet.len() as u64,
))
})
}
pub(crate) fn control(&self, network: NetworkId, peer: EndpointId, dir: Direction, len: u64) {
self.prepare(|| {
Some((
FlowKey {
network: *network.as_bytes(),
peer: *peer.as_bytes(),
role: Role::Control,
flow: Flow::Control,
},
dir,
len,
))
})
.record();
}
pub(crate) fn relay(
&self,
network: NetworkId,
source: [u8; 32],
dest: [u8; 32],
wire_protocol: u64,
len: usize,
) {
self.prepare(|| {
let (peer, other, dir) = if source <= dest {
(source, dest, Direction::Tx)
} else {
(dest, source, Direction::Rx)
};
Some((
FlowKey {
network: *network.as_bytes(),
peer,
role: Role::Relay,
flow: Flow::Relay {
other,
wire_protocol,
},
},
dir,
len as u64,
))
})
.record();
}
}
struct Pending {
readers: Arc<Vec<Weak<Bucket>>>,
key: FlowKey,
dir: Direction,
len: u64,
}
pub(crate) struct Observation(Option<Pending>);
impl Pending {
fn count(&self, len: u64) {
let now = Instant::now();
for reader in self.readers.iter().filter_map(Weak::upgrade) {
reader.add(self.key, self.dir, len, now);
}
}
}
impl Observation {
pub(crate) fn record(self) {
if let Some(pending) = self.0 {
pending.count(pending.len);
}
}
pub(crate) fn record_fragment(&self, len: usize) {
if let Some(pending) = &self.0 {
pending.count(len as u64);
}
}
}
/// Drops the reader and turns off observation when the last window disconnects.
#[derive(Debug)]
pub struct TrafficSubscription {
owner: Weak<TrafficMonitor>,
bucket: Arc<Bucket>,
}
impl TrafficSubscription {
/// Atomically start a fresh interval; serialisation never holds the collector lock.
pub fn snapshot(&self) -> TrafficSnapshot {
let (now, previous, lanes, omitted) = {
let mut since = self.bucket.since.lock().unwrap_or_else(|e| e.into_inner());
let locks = self
.bucket
.lanes
.each_ref()
.map(|lane| lane.lock().unwrap_or_else(|e| e.into_inner()));
let now = Instant::now();
self.bucket.entries.store(0, Ordering::Relaxed);
let lanes = locks.map(|mut lock| std::mem::take(&mut *lock));
(
now,
std::mem::replace(&mut *since, now),
lanes,
self.bucket.omitted.swap(0, Ordering::Relaxed),
)
};
let [mut flows, second, third, fourth] = lanes;
for (key, c) in [second, third, fourth].into_iter().flatten() {
flows
.entry(key)
.and_modify(|a| {
a.tx = a.tx.saturating_add(c.tx);
a.rx = a.rx.saturating_add(c.rx);
a.ntx = a.ntx.saturating_add(c.ntx);
a.nrx = a.nrx.saturating_add(c.nrx);
a.last = a.last.max(c.last)
})
.or_insert(c);
}
TrafficSnapshot {
interval_ms: millis(now.saturating_duration_since(previous)),
omitted,
flows: flows
.into_iter()
.map(|(key, c)| FlowDelta {
key,
tx_bytes: c.tx,
rx_bytes: c.rx,
tx_packets: c.ntx,
rx_packets: c.nrx,
age_ms: millis(now.saturating_duration_since(c.last)),
})
.collect(),
}
}
}
impl Drop for TrafficSubscription {
fn drop(&mut self) {
if let Some(monitor) = self.owner.upgrade() {
let _edit = monitor
.registration
.lock()
.unwrap_or_else(|e| e.into_inner());
let bucket = Arc::downgrade(&self.bucket);
let remaining: Vec<_> = monitor
.readers
.load()
.iter()
.filter(|r| !Weak::ptr_eq(r, &bucket))
.cloned()
.collect();
let active = !remaining.is_empty();
monitor.readers.store(Arc::new(remaining));
monitor.active.store(active, Ordering::Release);
}
}
}
#[cfg(test)]
mod tests;
+147
View File
@@ -0,0 +1,147 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn ip(proto: u8, reply: bool) -> Vec<u8> {
let mut p = vec![0; 32];
p[0] = 0x45;
p[2..4].copy_from_slice(&32u16.to_be_bytes());
p[9] = proto;
let (a, b, x, y) = if reply {
(2, 1, 443u16, 49152u16)
} else {
(1, 2, 49152, 443)
};
p[12..16].copy_from_slice(&[10, 0, 0, a]);
p[16..20].copy_from_slice(&[10, 0, 0, b]);
p[20..22].copy_from_slice(&x.to_be_bytes());
p[22..24].copy_from_slice(&y.to_be_bytes());
if proto == 1 {
p[20] = if reply { 0 } else { 8 };
p[21] = 0;
}
p
}
#[test]
fn dormant_monitor_and_independent_window_lifetimes() {
let monitor = Arc::new(TrafficMonitor::default());
let submit = || {
monitor
.prepare(|| Some((control(), Direction::Tx, 100)))
.record()
};
fn control() -> FlowKey {
FlowKey {
network: [1; 32],
peer: [2; 32],
role: Role::Control,
flow: Flow::Control,
}
}
assert!(
monitor
.prepare(|| panic!("observer ran while closed"))
.0
.is_none()
);
let a = monitor.subscribe().unwrap();
assert!(a.snapshot().flows.is_empty());
submit();
let pending = monitor.prepare(|| Some((control(), Direction::Rx, 50)));
let b = monitor.subscribe().unwrap();
pending.record();
submit();
let a_sample = a.snapshot();
assert_eq!(a_sample.flows[0].tx_bytes, 200);
assert_eq!(a_sample.flows[0].rx_bytes, 50);
assert_eq!(b.snapshot().flows[0].tx_bytes, 100);
assert!(a.snapshot().flows.is_empty());
drop((a, b));
assert!(
monitor
.prepare(|| panic!("observer left active"))
.0
.is_none()
);
assert!(monitor.subscribe().unwrap().snapshot().flows.is_empty());
}
#[test]
fn tuple_and_echo_replies_have_the_same_key_and_fragments_never_invent_ports() {
for protocol in [6, 17, 1] {
let key = Flow::ip(&ip(protocol, false), Direction::Tx).unwrap();
assert_eq!(Some(key), Flow::ip(&ip(protocol, true), Direction::Rx));
}
let mut packet = ip(17, false);
packet[7] = 1;
assert!(matches!(
Flow::ip(&packet, Direction::Tx),
Some(Flow::Ip {
detail: IpDetail::Fragment,
..
})
));
packet[0] = 0x4f;
assert!(Flow::ip(&packet, Direction::Tx).is_none());
assert!(Flow::ip(&[], Direction::Rx).is_none());
}
#[test]
fn bounded_interval_reports_overflow_and_preserves_known_counters() {
let monitor = Arc::new(TrafficMonitor::default());
let sub = monitor.subscribe().unwrap();
for i in 0..=MAX_INTERVAL_FLOWS {
let mut peer = [0; 32];
peer[..8].copy_from_slice(&(i as u64).to_be_bytes());
monitor
.prepare(|| {
Some((
FlowKey {
network: [0; 32],
peer,
role: Role::Control,
flow: Flow::Control,
},
Direction::Tx,
20,
))
})
.record();
}
let sample = sub.snapshot();
assert_eq!(sample.flows.len(), MAX_INTERVAL_FLOWS);
assert_eq!(sample.omitted, 1);
assert!(postcard::to_stdvec(&sample).unwrap().len() < (1 << 20));
assert_eq!(sub.snapshot().omitted, 0);
}
#[test]
fn busy_writers_share_the_flow_without_waiting_and_closed_windows_release_inflight_buffers() {
let monitor = Arc::new(TrafficMonitor::default());
let sub = monitor.subscribe().unwrap();
let key = FlowKey {
network: [1; 32],
peer: [2; 32],
role: Role::Control,
flow: Flow::Control,
};
monitor.prepare(|| Some((key, Direction::Tx, 20))).record();
let held = sub.bucket.lanes[0].lock().unwrap();
monitor.prepare(|| Some((key, Direction::Rx, 30))).record();
drop(held);
let result = sub.snapshot();
assert_eq!(result.flows.len(), 1);
assert_eq!(
(
result.flows[0].tx_bytes,
result.flows[0].rx_bytes,
result.omitted
),
(20, 30, 0)
);
let pending = monitor.prepare(|| Some((key, Direction::Rx, 10)));
let bucket = Arc::downgrade(&sub.bucket);
drop(sub);
assert!(bucket.upgrade().is_none());
pending.record();
}
+6 -2
View File
@@ -273,15 +273,19 @@ struct Datagram {
bytes: usize,
}
type FragmentKey = (Option<[u8; 32]>, Ipv4Addr, Ipv4Addr, u16, u8);
/// Bounded IPv4 fragment assembly for a local packet consumer.
#[derive(Debug, Default)]
pub(crate) struct Reassembly {
pub struct Reassembly {
pending: HashMap<FragmentKey, Datagram>,
}
impl Reassembly {
/// Forget incomplete datagrams after their five-second lifetime.
pub fn expire(&mut self, now: Instant) {
self.pending
.retain(|_, d| now.duration_since(d.at) < Duration::from_secs(5));
}
/// Accept one fragment or complete packet. `max` bounds pending datagrams;
/// `scope` separates authenticated senders sharing an address domain.
pub fn accept(&mut self, p: Bytes, max: usize, scope: Option<[u8; 32]>) -> Option<Bytes> {
let n = header(&p)?;
let flags = u16::from_be_bytes([p[6], p[7]]);
@@ -363,7 +367,7 @@ impl Reassembly {
}
/// Re-fragments an assembled NAT datagram for the unchanged overlay MTU.
pub(crate) fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
pub fn fragments(packet: Bytes, mtu: u32) -> Vec<Bytes> {
if packet.len() <= mtu as usize {
return vec![packet];
}
+91 -1
View File
@@ -15,6 +15,8 @@ pub(crate) enum Decision {
Pass,
Send(Route, Bytes),
Local(Bytes),
Reassembled(Bytes),
ProbeReceived,
Drop,
}
#[derive(Debug)]
@@ -452,6 +454,69 @@ impl VipRouter {
}
}
}
/// Identify an outgoing VIP datagram on the client-facing side of NAT. Called
/// once on the reassembled datagram; only accepted fragments contribute bytes.
pub(crate) fn observe_outgoing(
&self,
monitor: &crate::traffic::TrafficMonitor,
route: Option<Route>,
bytes: &[u8],
) -> crate::traffic::Observation {
use crate::traffic::{Direction, Flow as ObservedFlow, FlowKey, IpDetail, Role};
monitor.prepare(|| {
let state = self.lock();
let reverse = packet::tuple(bytes).map(Tuple::reverse);
let (route, dir, client) = if let Some(route) = route {
let original = reverse
.and_then(|t| state.reverse.get(&(route.network, route.peer, t)))
.copied();
(route, Direction::Tx, original)
} else {
// A local backend both receives requests and returns replies through this TUN.
let source = packet::addresses(bytes)?.0;
state.networks.iter().find_map(|(id, n)| {
let route = Route {
network: *id,
peer: n.local,
};
if let Some(t) = reverse.and_then(|t| state.reverse.get(&(*id, n.local, t))) {
return Some((route, Direction::Tx, Some(*t)));
}
let reply = reverse
.and_then(|t| state.flows.get(&t))
.is_some_and(|f| f.local && f.key.network == *id);
(reply || n.vips.iter().any(|v| v.address == Some(source))).then_some((
route,
Direction::Rx,
None,
))
})?
};
let flow = match client {
Some(t) => ObservedFlow::Ip {
near: t.src.octets(),
far: t.dst.octets(),
protocol: match t.protocol {
Protocol::Tcp => 6,
Protocol::Udp => 17,
},
detail: IpDetail::Ports(t.sport, t.dport),
},
None => ObservedFlow::ip(bytes, dir)?,
};
Some((
FlowKey {
network: *route.network.as_bytes(),
peer: *route.peer.as_bytes(),
role: Role::Vip,
flow,
},
dir,
bytes.len() as u64,
))
})
}
pub fn outgoing(&self, packet: Bytes) -> Decision {
let mut s = self.lock();
let Some((src, dst)) = packet::addresses(&packet) else {
@@ -716,6 +781,7 @@ impl VipRouter {
p.heard = Some(Instant::now());
p.pending = None;
p.misses = 0;
return Decision::ProbeReceived;
}
return Decision::Drop;
}
@@ -763,7 +829,7 @@ impl VipRouter {
return packet::rewrite_icmp(&packet, original).map_or(Decision::Drop, Decision::Local);
}
if was_fragmented {
Decision::Local(packet)
Decision::Reassembled(packet)
} else {
Decision::Pass
}
@@ -1021,6 +1087,9 @@ mod tests {
};
assert_eq!(route.peer, a);
let wire = packet::tuple(&out).unwrap();
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
let capture = monitor.subscribe().unwrap();
r.observe_outgoing(&monitor, Some(route), &out).record();
assert_eq!(wire.dport, 6443);
assert_ne!(wire.sport, t.sport);
let reply = packet(wire.reverse(), 0x12);
@@ -1028,6 +1097,17 @@ mod tests {
panic!("reverse NAT expected")
};
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
monitor
.packet(n, a, crate::traffic::Direction::Rx, &reply, || {
crate::traffic::Role::Vip
})
.record();
let sample = capture.snapshot();
assert_eq!(sample.flows.len(), 1);
assert_eq!(
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
(1, 1)
);
assert_eq!(packet::checksum(&reply[..20]), 0);
{
r.lock().networks.get_mut(&n).unwrap().vips.clear();
@@ -1073,6 +1153,9 @@ mod tests {
let Decision::Local(out) = r.outgoing(packet(t, 0)) else {
panic!("local delivery expected")
};
let monitor = std::sync::Arc::new(crate::traffic::TrafficMonitor::default());
let capture = monitor.subscribe().unwrap();
r.observe_outgoing(&monitor, None, &out).record();
let wire = packet::tuple(&out).unwrap();
assert_eq!(wire.src, t.dst);
assert_eq!(wire.dst, t.src);
@@ -1080,6 +1163,13 @@ mod tests {
let Decision::Local(reply) = r.outgoing(packet(wire.reverse(), 0)) else {
panic!("local reverse NAT expected")
};
r.observe_outgoing(&monitor, None, &reply).record();
let sample = capture.snapshot();
assert_eq!(sample.flows.len(), 1);
assert_eq!(
(sample.flows[0].tx_packets, sample.flows[0].rx_packets),
(1, 1)
);
assert_eq!(packet::tuple(&reply), Some(t.reverse()));
}
#[tokio::test]
@@ -47,6 +47,80 @@ async fn open_control_stream(
const LIMIT: usize = 64 * 1024;
#[tokio::test]
async fn an_authenticated_disconnect_reports_the_quic_close_code() {
let agent = TestAgent::spawn(&SharedMemoryDiscovery::new())
.await
.unwrap();
let (name, secret) = network("disconnect-diagnostics");
let id = agent.agent.join_network(&name, &secret).await.unwrap();
let member = raw_endpoint().await;
let (conn, mut send, mut recv) = open_control_stream(&member, agent.agent.local_addr()).await;
let mut events = agent.agent.subscribe();
tsunagi::proto::handshake::initiate(
&conn,
&mut send,
&mut recv,
member.id(),
&NetworkKeys::derive(&name, &secret),
&tsunagi::Limits::default(),
)
.await
.unwrap();
let message = ControlMessage::Announce(tsunagi::proto::message::Announcement {
broadcast: true,
exit_node: false,
hostname: "returning-peer".into(),
capabilities: Vec::new(),
agent_version: None,
uses_your_exit: None,
});
write_frame(
&mut send,
&encode(&Envelope {
network_id: *id.as_bytes(),
message,
})
.unwrap(),
LIMIT,
)
.await
.unwrap();
tsunagi::testing::wait_until("peer hostname is known", || async {
agent
.agent
.network_status(id)
.await
.ok()?
.peers
.into_iter()
.find(|p| {
p.endpoint_id == member.id() && p.hostname.as_deref() == Some("returning-peer")
})
})
.await;
conn.close(42u32.into(), b"private remote text\nsecond line");
let (reported_network, hostname, reason) = wait_event(&mut events, |event| match event {
Event::PeerDisconnected {
network,
network_name,
peer,
hostname,
reason,
} if *network == id && *peer == member.id() => {
Some((network_name.clone(), hostname.clone(), reason.clone()))
}
_ => None,
})
.await;
assert_eq!(reported_network, name);
assert_eq!(hostname.as_deref(), Some("returning-peer"));
assert!(reason.contains("application code 42"), "{reason}");
assert!(!reason.contains("private remote text"));
member.close().await;
agent.agent.shutdown().await;
}
/// Sends `Hello` and reads the responder's `HelloAck`.
async fn exchange_hellos(
send: &mut SendStream,
+11 -3
View File
@@ -148,13 +148,21 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() {
// Three that already know each other, and nothing that resolves by
// network: no shared discovery here, only what members pass on.
// A single introduction fits each frame, including when three members
// already know the same bootstrap. No peer may get stuck behind the first.
let small_frames = |dir: &std::path::Path| {
let mut config = local_config(dir);
config.limits.max_state_records = 1;
config.limits.session_send_queue = 2;
config
};
let first_dir = tempfile::TempDir::new().unwrap();
let first = Agent::spawn(local_config(first_dir.path())).await.unwrap();
let first = Agent::spawn(small_frames(first_dir.path())).await.unwrap();
let network_id = first.join_network(&name, &secret).await.unwrap();
let second_dir = tempfile::TempDir::new().unwrap();
let second = Agent::spawn(
local_config(second_dir.path())
small_frames(second_dir.path())
.with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))),
)
.await
@@ -164,7 +172,7 @@ async fn being_told_about_one_member_is_enough_to_meet_them_all() {
let third_dir = tempfile::TempDir::new().unwrap();
let third = Agent::spawn(
local_config(third_dir.path())
small_frames(third_dir.path())
.with_discovery(Arc::new(StaticBootstrap::new([first.local_addr()]))),
)
.await
+13 -9
View File
@@ -43,15 +43,19 @@ async fn four_agents_form_a_mesh_and_exchange_distinguishable_messages() {
// A peer counts as connected as soon as its session is authenticated, which
// can be a round before its announcement carrying the hostname arrives, so
// this waits for the hostnames rather than reading them straight away.
let hostnames: HashSet<String> = wait_until("three distinct peer hostnames", || async {
let status = agents[0].agent.network_status(network_id).await.ok()?;
let hostnames: HashSet<String> = status
.peers
.iter()
.filter_map(|peer| peer.hostname.clone())
.collect();
(hostnames.len() >= 3).then_some(hostnames)
})
let hostnames: HashSet<String> = wait_until(
"three peers announce their hostname and release",
|| async {
let status = agents[0].agent.network_status(network_id).await.ok()?;
let hostnames: HashSet<String> = status
.peers
.iter()
.filter(|peer| peer.agent_version.as_deref() == Some(env!("CARGO_PKG_VERSION")))
.filter_map(|peer| peer.hostname.clone())
.collect();
(hostnames.len() >= 3).then_some(hostnames)
},
)
.await;
assert_eq!(
hostnames.len(),
+91
View File
@@ -16,6 +16,97 @@ async fn view(agent: &Agent, network: NetworkId, id: &str) -> VipStatus {
})
.await
}
#[tokio::test]
async fn a_local_storage_failure_is_repaired_from_the_peer_after_reconnect() {
use tsunagi::{StoragePaths, agent::Event, testing::wait_event};
let discovery = SharedMemoryDiscovery::new();
let a = TestAgent::spawn(&discovery).await.unwrap();
let b = TestAgent::spawn(&discovery).await.unwrap();
let (name, secret) = network("retry-signed-update");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
wait_for_peers(&a.agent, id, 1).await;
let path = StoragePaths::under(b.dir.path()).state_db();
let trigger = |sql: &'static str| {
let path = path.clone();
tokio::task::spawn_blocking(move || {
rusqlite::Connection::open(path)
.unwrap()
.execute_batch(sql)
.unwrap()
})
};
trigger("CREATE TRIGGER reject_vip BEFORE INSERT ON vip_fields BEGIN SELECT RAISE(ABORT, 'test write failure'); END;").await.unwrap();
let mut events = b.agent.subscribe();
let vip = VipConfig::new("recover");
a.agent
.save_vip(id, vip.clone(), None, false)
.await
.unwrap();
wait_event(&mut events, |e| matches!(e, Event::PluginError { protocol, reason, .. } if protocol == "state" && reason.contains("test write failure")).then_some(())).await;
trigger("DROP TRIGGER reject_vip").await.unwrap();
assert_eq!(view(&b.agent, id, &vip.id).await.config, vip);
a.stop().await;
b.stop().await;
}
#[tokio::test]
async fn idle_maintenance_does_not_republish_acknowledged_mesh_state() {
use tsunagi::{agent::Event, proto::ControlMessage};
let discovery = SharedMemoryDiscovery::new();
let a = TestAgent::spawn(&discovery).await.unwrap();
let b = TestAgent::spawn(&discovery).await.unwrap();
let (name, secret) = network("quiet-mesh");
let id = a.agent.join_network(&name, &secret).await.unwrap();
b.agent.join_network(&name, &secret).await.unwrap();
wait_for_peers(&a.agent, id, 1).await;
let vip = VipConfig::new("web");
a.agent
.save_vip(id, vip.clone(), None, false)
.await
.unwrap();
view(&b.agent, id, &vip.id).await;
let mut events = b.agent.subscribe();
// Mark the end of each round on the same ordered control stream.
let last_hints = std::cell::RefCell::new(None);
for round in 0..4 {
a.agent.recheck_network(id).await.unwrap();
a.agent
.send(
id,
b.agent.endpoint_id(),
ControlMessage::Ping {
seq: round,
payload: vec![],
},
)
.await
.unwrap();
tsunagi::testing::wait_event(&mut events, |event| {
if let Event::MessageReceived { message, .. } = event {
match message {
ControlMessage::Ping { seq, .. } if *seq == round => return Some(()),
ControlMessage::Vips { .. } | ControlMessage::Reachable { .. } if round > 0 => {
panic!("republished unchanged state on maintenance round {round}")
}
ControlMessage::Peers { peers } => {
assert_ne!(
last_hints.replace(Some(peers.clone())).as_ref(),
Some(peers),
"unchanged introductions"
);
}
_ => {}
}
}
None
})
.await;
}
a.stop().await;
b.stop().await;
}
#[tokio::test]
async fn any_member_can_edit_services_and_an_offline_creator_is_not_required() {
let discovery = SharedMemoryDiscovery::new();
+6 -6
View File
@@ -1,6 +1,6 @@
[package]
name = "tsunagi-runtime"
version = "1.0.1"
version = "1.0.9"
description = "Built-in mesh transports and status reporting for native tsunagi agents."
edition.workspace = true
rust-version.workspace = true
@@ -8,11 +8,11 @@ license.workspace = true
repository.workspace = true
[dependencies]
tsunagi-core = { path = "../tsunagi-core", version = "1.0.1" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.1" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.1" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.1" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.1" }
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.9" }
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.9" }
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.9" }
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.9" }
tokio.workspace = true
tracing.workspace = true
+7
View File
@@ -35,6 +35,7 @@ pub fn networks(
address: peer.overlay_address_v4.map(|a| a.to_string()),
handshake_secs_ago: tunnel
.and_then(|t| t.health.since_handshake.map(|s| s.as_secs())),
idle: tunnel.is_some_and(|t| t.health.idle),
tx_packets: tunnel.map_or(0, |t| t.stats.tx_packets),
rx_packets: tunnel.map_or(0, |t| t.stats.rx_packets),
tx_bytes: tunnel.map_or(0, |t| t.stats.tx_bytes),
@@ -86,6 +87,7 @@ pub fn networks(
};
NetworkReport {
speed: network.speed.clone(),
vips: network.vips.clone(),
protocols: network.protocols.clone(),
auto_start: network.auto_start,
@@ -102,12 +104,16 @@ pub fn networks(
.peers
.iter()
.map(|peer| PeerReport {
agent_version: peer.agent_version.clone(),
data_error: peer.data_error.clone(),
endpoint_id: peer.endpoint_id.to_string(),
hostname: peer.hostname.clone(),
transport: peer.transport.to_string(),
rtt_ms: peer.rtt.map(|rtt| rtt.as_millis() as u64),
data_rtt_ms: peer.data_rtt.map(|rtt| rtt.as_millis() as u64),
data_transport_detail: peer.data_transport_detail.clone(),
exit_node: peer.exit_node,
uses_our_exit: peer.uses_our_exit,
path: data_path_report(&peer.data_path),
})
.collect(),
@@ -191,6 +197,7 @@ fn exit_report(network: &tsunagi::agent::NetworkStatus) -> tsunagi::ipc::ExitRep
})
};
tsunagi::ipc::ExitReport {
traffic: network.exit_traffic,
offering: network.exit_offer,
offer_rules: rules(&network.exit_rules.offer),
forwarding: network.exit_rules.forwarding,
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more