Compare commits
No files matched your search
@@ -23,6 +23,12 @@ jobs:
|
||||
with:
|
||||
components: rustfmt, clippy
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- &linux-tray-deps
|
||||
name: Install GTK and AppIndicator development files
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y --no-install-recommends libgtk-3-dev libayatana-appindicator3-dev
|
||||
- run: cargo fmt --all -- --check
|
||||
- run: cargo clippy --locked --workspace --all-targets -- -D warnings
|
||||
- name: Check Debian release candidate upgrade ordering
|
||||
@@ -39,11 +45,11 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo test --locked --workspace --all-targets
|
||||
- name: run the examples
|
||||
run: |
|
||||
cargo run --locked --example two_agents
|
||||
cargo run --locked --example wireguard_mesh
|
||||
- *linux-tray-deps
|
||||
- name: Test the workspace, including peer exchange and WireGuard integration
|
||||
run: cargo test --locked --workspace --all-targets
|
||||
- name: Start the command line client
|
||||
run: cargo run --locked --bin tsng -- --version
|
||||
|
||||
# The library must keep building without the command line binary and
|
||||
# without interface support, for embedders that want neither.
|
||||
@@ -54,7 +60,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- run: cargo check --locked --no-default-features --lib
|
||||
- run: cargo check --locked -p tsunagi-core --no-default-features --lib
|
||||
|
||||
docs:
|
||||
name: rustdoc
|
||||
@@ -63,6 +69,7 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- *linux-tray-deps
|
||||
- run: cargo doc --locked --workspace --no-deps
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
@@ -74,4 +81,5 @@ jobs:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@1.91.0
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- *linux-tray-deps
|
||||
- run: cargo check --locked --workspace --all-targets
|
||||
@@ -5,7 +5,14 @@ on:
|
||||
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'
|
||||
@@ -27,6 +34,8 @@ jobs:
|
||||
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
|
||||
@@ -53,6 +62,11 @@ jobs:
|
||||
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
|
||||
# The invoking login and the service inside namespace B have distinct environments.
|
||||
run: sudo -n -- env XDG_RUNTIME_DIR="/run/user/$(id -u)" "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
- name: Verify source selection on a real utun
|
||||
if: runner.os == 'macOS'
|
||||
shell: bash
|
||||
@@ -65,6 +79,9 @@ jobs:
|
||||
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'
|
||||
@@ -81,6 +98,16 @@ jobs:
|
||||
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
|
||||
|
||||
Generated
+86
-10
@@ -211,6 +211,9 @@ name = "arrayvec"
|
||||
version = "0.7.8"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||
dependencies = [
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "as-raw-xcb-connection"
|
||||
@@ -493,6 +496,7 @@ dependencies = [
|
||||
"cfg-if",
|
||||
"constant_time_eq",
|
||||
"cpufeatures 0.3.1",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6296,7 +6300,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6363,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6385,6 +6389,7 @@ dependencies = [
|
||||
"sha2",
|
||||
"simple-dns",
|
||||
"smoltcp",
|
||||
"socket2",
|
||||
"subtle",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
@@ -6394,6 +6399,7 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-core",
|
||||
"tsunagi-speedtest",
|
||||
"tun",
|
||||
"windows-sys 0.61.2",
|
||||
"zbus",
|
||||
@@ -6402,20 +6408,62 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"data-encoding",
|
||||
"hex",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tracing",
|
||||
"tsunagi-awg",
|
||||
"tsunagi-core",
|
||||
"tsunagi-shoes",
|
||||
"tsunagi-ss2022",
|
||||
"tsunagi-tcp-tls",
|
||||
"tsunagi-vless-xhttp",
|
||||
"tsunagi-wg-quic",
|
||||
"tsunagi-wireguard",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-shoes"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"iroh",
|
||||
"rand 0.10.3",
|
||||
"tokio",
|
||||
"tsunagi-core",
|
||||
"tsunagi-tcp-tls",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"postcard",
|
||||
"serde",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ss2022"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"blake3",
|
||||
"iroh",
|
||||
"rand 0.10.3",
|
||||
"ring",
|
||||
"tokio",
|
||||
"tsunagi-core",
|
||||
"tsunagi-shoes",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6425,17 +6473,19 @@ dependencies = [
|
||||
"rcgen",
|
||||
"rustls",
|
||||
"serde",
|
||||
"socket2",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-core",
|
||||
"x509-parser",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6451,17 +6501,40 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
"postcard",
|
||||
"rusqlite",
|
||||
"tempfile",
|
||||
"tsunagi-core",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-vless-xhttp"
|
||||
version = "1.0.0"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"h2",
|
||||
"hex",
|
||||
"http",
|
||||
"iroh",
|
||||
"rand 0.10.3",
|
||||
"rustls",
|
||||
"subtle",
|
||||
"tokio",
|
||||
"tokio-rustls",
|
||||
"tsunagi-core",
|
||||
"tsunagi-shoes",
|
||||
"tsunagi-tcp-tls",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wg-quic"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6481,14 +6554,17 @@ dependencies = [
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
"tsunagi-core",
|
||||
"tsunagi-shoes",
|
||||
"tsunagi-ss2022",
|
||||
"tsunagi-tcp-tls",
|
||||
"tsunagi-vless-xhttp",
|
||||
"tsunagi-wireguard",
|
||||
"zeroize",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -122,14 +122,28 @@ 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 initial data transport order is `wg,awg,wg-quic,tcp-tls` by default. AWG negotiates a
|
||||
The initial data transport order is `wg,awg,wg-quic,tcp-tls,vless-xhttp,ss2022` 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).
|
||||
|
||||
The **Shoes** family adds two embedded TCP carriers. `vless-xhttp` uses VLESS
|
||||
over XHTTP stream-one with HTTP/2 and pinned TLS 1.3 (preferred port 9443).
|
||||
`ss2022` uses Shadowsocks 2022 with AES-128-GCM or AES-256-GCM (9444).
|
||||
Peers agree fresh credentials over their authenticated control connection on
|
||||
every attempt. The agent runs both listeners itself. Override their ports with
|
||||
`tsng up -o vless-xhttp:port=10443 -o ss2022:port=10444`.
|
||||
|
||||
With two updated peers, `tcp-tls` and both Shoes carriers try the opposite dial
|
||||
direction if the first fails. One reachable TCP listener suffices. If neither
|
||||
side accepts TCP, the mesh can use another enabled carrier or an available
|
||||
relay route. [Wire profiles and compatibility](docs/shoes.md).
|
||||
|
||||
Change a network's protocol selection without editing its service or restarting:
|
||||
|
||||
```sh
|
||||
@@ -142,9 +156,29 @@ 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 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
|
||||
name to expand its card. Open **Data transports** to toggle a family or expand it to select individual
|
||||
transports. Checking a partial or unchecked family enables every member. The
|
||||
number beside an enabled transport is its priority across all groups. The arrow
|
||||
buttons change it. Hover or tap the information icon for protocol details. **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.
|
||||
@@ -178,6 +212,29 @@ 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.
|
||||
|
||||
**Resolve names** shows known peers and VIPs by their network names in the
|
||||
endpoint columns. Hover over a name, or press and hold on Android, to see the
|
||||
IP address. Clear the checkbox to show all endpoints numerically.
|
||||
|
||||
**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. Use the
|
||||
**TX packets** and **RX packets** columns to see 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 |
|
||||
|
||||
+3
-1
@@ -28,7 +28,9 @@ The tray and Android use the same egui network tiles, join form, device list, VI
|
||||
|
||||
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 network name to expand its card, then open **Exit node…** to compare remote gateways by measured data 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)
|
||||
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)
|
||||
|
||||
Tap the speedometer beside a network name in the exit list to test its compatible online exits one at a time. Each row shows download and upload in Mbit/s. The stop button ends the test and skips queued peers. Testing keeps the current exit selection.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ android {
|
||||
targetSdk 35
|
||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.4')
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.11')
|
||||
ndk { abiFilters abi }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ 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
|
||||
@@ -33,16 +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?) {
|
||||
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
|
||||
|
||||
@@ -40,6 +40,9 @@ class MeshVpn : VpnService() {
|
||||
@Volatile private var upstream: Network? = null
|
||||
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)
|
||||
}
|
||||
@@ -50,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) {
|
||||
@@ -69,10 +76,14 @@ 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 {
|
||||
|
||||
@@ -6,14 +6,16 @@ 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 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)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
description = "Android VPN client and egui views for tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.4" }
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.11" }
|
||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! Android owns the GLES surface, keyboard and clipboard. egui owns the widgets.
|
||||
use crate::view::{Phone, SystemAction};
|
||||
use egui::{
|
||||
Event, ImeEvent, Key, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase,
|
||||
use crate::{
|
||||
touch::TouchInput,
|
||||
view::{Phone, SystemAction},
|
||||
};
|
||||
use egui::{Event, ImeEvent, Key, Modifiers, Pos2, TouchPhase};
|
||||
use egui_glow::{Painter, glow};
|
||||
use jni::{
|
||||
JNIEnv,
|
||||
@@ -26,7 +27,7 @@ struct Display {
|
||||
ctx: egui::Context,
|
||||
ui: Phone,
|
||||
events: Vec<Event>,
|
||||
primary: Option<i32>,
|
||||
touch: TouchInput,
|
||||
start: Instant,
|
||||
ime: i32,
|
||||
exit_active: bool,
|
||||
@@ -38,7 +39,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 +61,10 @@ 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
|
||||
let mut ui = d
|
||||
.take()
|
||||
.map(|old| {
|
||||
// A rotation can recreate EGL. Keep expanded peers and scroll positions
|
||||
@@ -64,12 +74,15 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(mut env: JNIEnv, _: JObj
|
||||
old.ui
|
||||
})
|
||||
.unwrap_or_default();
|
||||
if let Some(cache) = cache {
|
||||
ui.set_cache_dir(cache.into());
|
||||
}
|
||||
*d = Some(Display {
|
||||
painter,
|
||||
ctx,
|
||||
ui,
|
||||
events: Vec::new(),
|
||||
primary: None,
|
||||
touch: TouchInput::default(),
|
||||
start: Instant::now(),
|
||||
ime: -1,
|
||||
exit_active: false,
|
||||
@@ -92,7 +105,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
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)),
|
||||
events: std::mem::take(&mut d.events),
|
||||
events: d.touch.take_frame(&mut d.events),
|
||||
time: Some(d.start.elapsed().as_secs_f64()),
|
||||
..Default::default()
|
||||
};
|
||||
@@ -110,8 +123,12 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_draw(
|
||||
}
|
||||
d.exit_active = exit_active;
|
||||
let output = d.ctx.run(input, |ctx| {
|
||||
if !d.events.is_empty() {
|
||||
ctx.request_repaint();
|
||||
}
|
||||
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 => "startAgent",
|
||||
@@ -188,37 +205,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_touch(
|
||||
2 => TouchPhase::End,
|
||||
_ => TouchPhase::Cancel,
|
||||
};
|
||||
d.events.push(Event::Touch {
|
||||
device_id: TouchDeviceId(0),
|
||||
id: TouchId(id as u64),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
});
|
||||
if phase == TouchPhase::Start && d.primary.is_none() {
|
||||
d.primary = Some(id);
|
||||
}
|
||||
if d.primary != Some(id) {
|
||||
return;
|
||||
}
|
||||
if phase != TouchPhase::Cancel {
|
||||
d.events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
if phase != TouchPhase::Move {
|
||||
if phase == TouchPhase::Cancel {
|
||||
d.events.push(Event::PointerGone);
|
||||
}
|
||||
d.events.push(Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: phase == TouchPhase::Start,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
if matches!(phase, TouchPhase::Cancel | TouchPhase::End) {
|
||||
d.events.push(Event::PointerGone);
|
||||
d.primary = None;
|
||||
}
|
||||
d.touch.push(&mut d.events, phase, id, pos);
|
||||
});
|
||||
}
|
||||
#[unsafe(no_mangle)]
|
||||
|
||||
@@ -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::{
|
||||
@@ -29,7 +29,7 @@ struct Session {
|
||||
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
|
||||
@@ -44,9 +44,14 @@ fn status() -> State {
|
||||
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() >= std::time::Duration::from_secs(2))
|
||||
.is_none_or(|last| last.elapsed() >= tsunagi_ui::client::status_poll_interval(report))
|
||||
&& session
|
||||
.commands
|
||||
.try_send((Request::Refresh, oneshot::channel().0))
|
||||
@@ -54,15 +59,18 @@ fn status() -> State {
|
||||
{
|
||||
session.last_refresh = Some(std::time::Instant::now());
|
||||
}
|
||||
session.state.borrow().clone()
|
||||
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("Tsunagi Agent stopped")?
|
||||
.commands
|
||||
.try_send((Request::Action(cmd), reply))
|
||||
.try_send((request, reply))
|
||||
.map_err(|_| "Tsunagi Agent is busy or stopped".to_owned())?;
|
||||
Ok(result)
|
||||
}
|
||||
@@ -131,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.
|
||||
@@ -188,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>> {
|
||||
@@ -226,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(¬ice_vm, ¬ice_service, id, notice);
|
||||
})
|
||||
.await;
|
||||
@@ -243,7 +255,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_start(
|
||||
commands,
|
||||
state: state_rx,
|
||||
underlay,
|
||||
stop,
|
||||
signals,
|
||||
});
|
||||
Ok(id)
|
||||
})();
|
||||
@@ -400,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> {
|
||||
@@ -411,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,
|
||||
|
||||
@@ -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")]
|
||||
@@ -8,6 +9,8 @@ mod android;
|
||||
pub mod service;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
#[cfg(any(target_os = "android", test))]
|
||||
mod touch;
|
||||
#[cfg(unix)]
|
||||
pub mod tun;
|
||||
pub mod view;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tsunagi::{
|
||||
Agent, NetworkName, NetworkSecret,
|
||||
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
|
||||
ipc::{DnsReport, PrivilegeReport, StatusReport},
|
||||
vip::VipStatus,
|
||||
};
|
||||
use tsunagi_ui::client::Command;
|
||||
@@ -12,6 +12,8 @@ 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.
|
||||
@@ -34,6 +36,15 @@ pub enum Request {
|
||||
},
|
||||
}
|
||||
|
||||
/// 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.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct ExitNotice {
|
||||
@@ -141,6 +152,8 @@ pub(crate) async fn wait_for_exit_offer(
|
||||
|
||||
/// 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.
|
||||
@@ -158,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 } => {
|
||||
@@ -201,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());
|
||||
}
|
||||
@@ -271,10 +302,7 @@ async fn snapshot(
|
||||
cache_healthy: status.cache_healthy,
|
||||
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
.map(|spec| ProtocolReport {
|
||||
name: spec.name.into(),
|
||||
summary: spec.summary.into(),
|
||||
})
|
||||
.map(|spec| spec.report())
|
||||
.collect(),
|
||||
protocols: tsunagi_runtime::PROTOCOLS
|
||||
.iter()
|
||||
@@ -293,7 +321,7 @@ 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 roster = agent.watch_roster();
|
||||
@@ -301,20 +329,34 @@ pub async fn serve(
|
||||
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 {
|
||||
if link.stopped {
|
||||
break;
|
||||
}
|
||||
let (reply, mut refresh_zones) = tokio::select! {
|
||||
biased;
|
||||
_ = async { drop(stop.wait_for(|stopped| *stopped).await) } => 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;
|
||||
|
||||
@@ -24,7 +24,7 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
.await
|
||||
.unwrap();
|
||||
let (state, mut snapshots) = watch::channel(State::Starting);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
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 {
|
||||
@@ -44,6 +44,28 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
.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
|
||||
@@ -59,7 +81,7 @@ async fn a_hidden_service_waits_for_mesh_changes_and_visible_stats_are_on_demand
|
||||
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_replace(true);
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
@@ -118,7 +140,7 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.unwrap();
|
||||
let agent = phone.agent.clone();
|
||||
let (commands, requests) = mpsc::channel(4);
|
||||
let (stop, stopped) = watch::channel(false);
|
||||
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 {
|
||||
@@ -225,7 +247,7 @@ async fn notification_tracks_the_selected_exit_and_a_stale_disconnect_keeps_the_
|
||||
.unwrap();
|
||||
notice_matching(&mut notices, Option::is_none).await;
|
||||
assert!(phone.agent.is_active(id).await);
|
||||
stop.send_replace(true);
|
||||
stop.send_modify(|s| s.stopped = true);
|
||||
task.await.unwrap();
|
||||
}
|
||||
|
||||
@@ -427,16 +449,21 @@ fn broadcast_route_is_only_present_when_requested() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||
async fn all_desktop_carriers_register_and_each_network_keeps_its_preference() {
|
||||
use tsunagi::{Agent, testing};
|
||||
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let names = ["wg", "awg", "wg-quic", "tcp-tls"];
|
||||
let names = ["wg", "awg", "wg-quic", "tcp-tls", "vless-xhttp", "ss2022"];
|
||||
assert_eq!(
|
||||
PROTOCOLS.iter().map(|spec| spec.group).collect::<Vec<_>>(),
|
||||
["WireGuard", "WireGuard", "iroh", "Native", "Shoes", "Shoes"]
|
||||
);
|
||||
let (network, secret) = testing::network("carriers");
|
||||
let (other, other_secret) = testing::network("other");
|
||||
for restart in [false, true] {
|
||||
let config = testing::local_config(dir.path());
|
||||
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
||||
if spec.name == "tcp-tls" {
|
||||
if matches!(spec.name, "tcp-tls" | "vless-xhttp" | "ss2022") {
|
||||
vec![("port".into(), "0".into())]
|
||||
} else {
|
||||
Vec::new()
|
||||
@@ -465,15 +492,24 @@ async fn all_four_desktop_carriers_register_and_each_network_keeps_its_preferenc
|
||||
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||
if restart {
|
||||
assert_eq!(saved, ["tcp-tls", "wg"]);
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert!(
|
||||
agent
|
||||
.network_status(second)
|
||||
.await
|
||||
.unwrap()
|
||||
.protocols
|
||||
.is_empty()
|
||||
);
|
||||
} else {
|
||||
assert_eq!(saved, names);
|
||||
agent
|
||||
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||
.await
|
||||
.unwrap();
|
||||
let (other, secret) = testing::network("other");
|
||||
let second = agent.join_network(&other, &secret).await.unwrap();
|
||||
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||
agent.set_protocols(second, vec![]).await.unwrap();
|
||||
}
|
||||
agent.shutdown().await;
|
||||
}
|
||||
@@ -738,6 +774,7 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded()
|
||||
};
|
||||
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;
|
||||
@@ -749,6 +786,18 @@ async fn network_cards_start_closed_and_keep_exit_traffic_visible_when_folded()
|
||||
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;
|
||||
}
|
||||
|
||||
@@ -781,6 +830,12 @@ fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_
|
||||
[("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()
|
||||
});
|
||||
@@ -795,6 +850,9 @@ fn the_system_tile_waits_for_the_agent_and_distinguishes_networks_with_the_same_
|
||||
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"));
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
//! Translate Android fingers into egui touch events and one primary pointer.
|
||||
use egui::{Event, Modifiers, PointerButton, Pos2, TouchDeviceId, TouchId, TouchPhase};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct TouchInput {
|
||||
primary: Option<i32>,
|
||||
clear_after_release: bool,
|
||||
}
|
||||
|
||||
impl TouchInput {
|
||||
pub(crate) fn push(&mut self, events: &mut Vec<Event>, phase: TouchPhase, id: i32, pos: Pos2) {
|
||||
events.push(Event::Touch {
|
||||
device_id: TouchDeviceId(0),
|
||||
id: TouchId(id as u64),
|
||||
phase,
|
||||
pos,
|
||||
force: None,
|
||||
});
|
||||
if phase == TouchPhase::Start && self.primary.is_none() {
|
||||
self.primary = Some(id);
|
||||
self.clear_after_release = false;
|
||||
}
|
||||
if self.primary != Some(id) {
|
||||
return;
|
||||
}
|
||||
if phase != TouchPhase::Cancel {
|
||||
events.push(Event::PointerMoved(pos));
|
||||
}
|
||||
if phase != TouchPhase::Move {
|
||||
events.push(Event::PointerButton {
|
||||
pos,
|
||||
button: PointerButton::Primary,
|
||||
pressed: phase == TouchPhase::Start,
|
||||
modifiers: Modifiers::NONE,
|
||||
});
|
||||
}
|
||||
match phase {
|
||||
TouchPhase::End => {
|
||||
self.primary = None;
|
||||
self.clear_after_release = true;
|
||||
}
|
||||
TouchPhase::Cancel => {
|
||||
self.primary = None;
|
||||
events.push(Event::PointerGone);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn take_frame(&mut self, events: &mut Vec<Event>) -> Vec<Event> {
|
||||
let frame = std::mem::take(events);
|
||||
// ScrollArea reads the release velocity in this frame. PointerGone clears
|
||||
// egui's position history, so clear the touch hover in the following frame.
|
||||
if std::mem::take(&mut self.clear_after_release) {
|
||||
events.push(Event::PointerGone);
|
||||
}
|
||||
frame
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use egui::{CentralPanel, Context, RawInput, Rect, ScrollArea, pos2, vec2};
|
||||
|
||||
#[test]
|
||||
fn a_flick_coasts_and_slows_while_a_cancelled_drag_stops() {
|
||||
for end in [TouchPhase::End, TouchPhase::Cancel] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
let mut input = TouchInput::default();
|
||||
let mut events = Vec::new();
|
||||
let mut frame_no = 0;
|
||||
let mut frame = |touch| {
|
||||
if let Some((phase, y)) = touch {
|
||||
input.push(&mut events, phase, 0, pos2(80., y));
|
||||
}
|
||||
frame_no += 1;
|
||||
let mut offset = 0.;
|
||||
let _ = ctx.run(
|
||||
RawInput {
|
||||
time: Some(f64::from(frame_no) / 60.),
|
||||
events: input.take_frame(&mut events),
|
||||
screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(320., 320.))),
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
CentralPanel::default().show(ctx, |ui| {
|
||||
offset = ScrollArea::vertical()
|
||||
.auto_shrink([false, false])
|
||||
.show(ui, |ui| {
|
||||
for i in 0..60 {
|
||||
ui.add_sized(
|
||||
[270., 40.],
|
||||
egui::Button::new(format!("Peer {i}")),
|
||||
);
|
||||
}
|
||||
})
|
||||
.state
|
||||
.offset
|
||||
.y;
|
||||
});
|
||||
},
|
||||
);
|
||||
offset
|
||||
};
|
||||
// The first layout measures the content. The next registers its drag area.
|
||||
frame(None);
|
||||
frame(None);
|
||||
frame(Some((TouchPhase::Start, 220.)));
|
||||
for y in [208., 190., 168., 146.] {
|
||||
frame(Some((TouchPhase::Move, y)));
|
||||
}
|
||||
let released = frame(Some((end, 126.)));
|
||||
let first = frame(None);
|
||||
let second = frame(None);
|
||||
assert!(released > 0., "{end:?} should follow a drag");
|
||||
if end == TouchPhase::End {
|
||||
assert!(
|
||||
second > first && first > released,
|
||||
"the scroll should coast after release"
|
||||
);
|
||||
assert!(
|
||||
second - first < first - released,
|
||||
"the fling should decelerate"
|
||||
);
|
||||
} else {
|
||||
assert_eq!((released, first), (first, second));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_new_primary_touch_supersedes_a_release_in_the_same_frame() {
|
||||
let mut input = TouchInput::default();
|
||||
let mut events = Vec::new();
|
||||
for (phase, id) in [
|
||||
(TouchPhase::Start, 1),
|
||||
(TouchPhase::End, 1),
|
||||
(TouchPhase::Start, 2),
|
||||
] {
|
||||
input.push(&mut events, phase, id, Pos2::ZERO);
|
||||
}
|
||||
let frame = input.take_frame(&mut events);
|
||||
assert!(matches!(
|
||||
frame.last(),
|
||||
Some(Event::PointerButton { pressed: true, .. })
|
||||
));
|
||||
assert!(events.is_empty());
|
||||
input.push(&mut events, TouchPhase::End, 2, Pos2::ZERO);
|
||||
let release = input.take_frame(&mut events);
|
||||
assert!(matches!(
|
||||
release.last(),
|
||||
Some(Event::PointerButton { pressed: false, .. })
|
||||
));
|
||||
assert!(matches!(
|
||||
input.take_frame(&mut events).as_slice(),
|
||||
[Event::PointerGone]
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -20,17 +20,17 @@ enum Page {
|
||||
#[default]
|
||||
Home,
|
||||
About,
|
||||
Monitor,
|
||||
Join,
|
||||
Devices(String),
|
||||
Vips(String),
|
||||
Exit(String),
|
||||
ExitNetworks,
|
||||
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,
|
||||
}
|
||||
}
|
||||
@@ -38,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(_) | Self::ExitNetworks => "Exit node",
|
||||
Self::Exits => "Exit nodes",
|
||||
Self::Leave(_) => "Leave network",
|
||||
}
|
||||
}
|
||||
@@ -85,6 +86,8 @@ 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,
|
||||
@@ -108,7 +111,24 @@ 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;
|
||||
@@ -166,34 +186,56 @@ impl Phone {
|
||||
self.pick_exit = true;
|
||||
}
|
||||
|
||||
fn exit_networks(&mut self, ui: &mut egui::Ui, networks: &[tsunagi::ipc::NetworkReport]) {
|
||||
if networks.is_empty() {
|
||||
ui.label("Join a network to choose an exit node.");
|
||||
if ui.button("Join or create a network").clicked() {
|
||||
self.page = Page::Join;
|
||||
}
|
||||
return;
|
||||
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;
|
||||
}
|
||||
if !networks.iter().any(|n| n.active) {
|
||||
ui.label("Start a network to choose an exit node.");
|
||||
if ui.button("Show networks").clicked() {
|
||||
self.home();
|
||||
}
|
||||
return;
|
||||
}
|
||||
ui.label("Choose a network for the exit node");
|
||||
for n in networks.iter().filter(|n| n.active) {
|
||||
let ambiguous = networks.iter().any(|other| {
|
||||
other.active && other.name == n.name && other.network_id != n.network_id
|
||||
});
|
||||
let label = if ambiguous {
|
||||
format!("{} · {}", n.name, tsunagi_ui::format::short(&n.network_id))
|
||||
} else {
|
||||
n.name.clone()
|
||||
};
|
||||
if ui.button(label).clicked() {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// 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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +260,13 @@ impl Phone {
|
||||
.id_salt("network list")
|
||||
.show(ui, |ui| {
|
||||
for network in &report.networks {
|
||||
home::draw_network_selector(ui, network, report, &mut self.forms);
|
||||
home::draw_network_selector(
|
||||
ui,
|
||||
network,
|
||||
report,
|
||||
&mut self.forms,
|
||||
&self.traffic,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -233,7 +281,7 @@ impl Phone {
|
||||
if let Some(n) = selected {
|
||||
ui.heading(&n.name);
|
||||
ui.push_id(&n.network_id, |ui| {
|
||||
if home::draw_network_details(
|
||||
home::draw_network_details(
|
||||
ui,
|
||||
actions,
|
||||
&mut self.forms,
|
||||
@@ -241,15 +289,14 @@ impl Phone {
|
||||
n,
|
||||
report,
|
||||
false,
|
||||
) {
|
||||
self.page = Page::Exit(n.network_id.clone());
|
||||
}
|
||||
);
|
||||
});
|
||||
} else {
|
||||
ui.heading("This device");
|
||||
ui.label("Tsunagi Agent is running");
|
||||
home::draw_header(ui, actions, &mut self.forms, report);
|
||||
}
|
||||
ui.add_space(80.);
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -320,18 +367,13 @@ impl Phone {
|
||||
}
|
||||
if self.pick_exit && self.pending.is_none() {
|
||||
self.pick_exit = false;
|
||||
let mut active = report.networks.iter().filter(|n| n.active);
|
||||
let picker = match (active.next(), active.next()) {
|
||||
(Some(n), None) => Page::Exit(n.network_id.clone()),
|
||||
_ => Page::ExitNetworks,
|
||||
};
|
||||
if !matches!(self.page, Page::Exit(_) | Page::ExitNetworks) {
|
||||
self.before_picker = Some(std::mem::replace(&mut self.page, picker));
|
||||
}
|
||||
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();
|
||||
@@ -361,6 +403,11 @@ impl Phone {
|
||||
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");
|
||||
}
|
||||
@@ -381,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();
|
||||
@@ -408,7 +467,7 @@ impl Phone {
|
||||
self.landscape_home(ui, &actions, report);
|
||||
return;
|
||||
}
|
||||
egui::ScrollArea::vertical().auto_shrink([false, false]).show(ui, |ui| {
|
||||
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 Tsunagi Agent…");}
|
||||
@@ -425,19 +484,23 @@ 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());}
|
||||
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_with_tests(ui, &report.networks, &report.endpoint_id, &actions) {
|
||||
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::ExitNetworks => self.exit_networks(ui, &report.networks),
|
||||
Page::Leave(id) => {
|
||||
if let Some(n) = selected {
|
||||
ui.label(format!("Leave {} on this phone? You will need its secret to join again.", n.name));
|
||||
@@ -463,6 +526,9 @@ impl Phone {
|
||||
}
|
||||
}
|
||||
}
|
||||
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,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
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
|
||||
@@ -97,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"] }
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
|
||||
@@ -22,6 +22,7 @@ mod events;
|
||||
mod network;
|
||||
mod session;
|
||||
mod shutdown;
|
||||
mod speed;
|
||||
mod status;
|
||||
|
||||
pub use events::Event;
|
||||
@@ -95,6 +96,7 @@ pub struct Agent {
|
||||
#[derive(Debug)]
|
||||
struct Inner {
|
||||
config: AgentConfig,
|
||||
speed: speed::SpeedTests,
|
||||
limits: Arc<Limits>,
|
||||
storage: Storage,
|
||||
identity: DeviceIdentity,
|
||||
@@ -220,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;
|
||||
};
|
||||
@@ -301,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(
|
||||
@@ -444,6 +456,7 @@ impl Agent {
|
||||
|
||||
let (range_changed, range_updates) = watch::channel(());
|
||||
let inner = Arc::new(Inner {
|
||||
speed: speed::SpeedTests::default(),
|
||||
limits,
|
||||
storage,
|
||||
identity,
|
||||
@@ -511,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);
|
||||
}
|
||||
@@ -1006,6 +1020,7 @@ impl Agent {
|
||||
self.inner.ensure_interface().await;
|
||||
}
|
||||
let handle = network::spawn(RuntimeParams {
|
||||
agent: Arc::downgrade(&self.inner),
|
||||
vips,
|
||||
retirements,
|
||||
broadcast,
|
||||
@@ -1079,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
|
||||
@@ -1315,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,
|
||||
@@ -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> = {
|
||||
|
||||
@@ -40,6 +40,7 @@ use super::status::{
|
||||
};
|
||||
use sync::{Changes, SyncKey};
|
||||
|
||||
mod reverse;
|
||||
mod selection;
|
||||
mod sync;
|
||||
|
||||
@@ -177,6 +178,7 @@ impl NetworkHandle {
|
||||
|
||||
/// Everything a network runtime needs to run.
|
||||
pub(crate) struct RuntimeParams {
|
||||
pub(super) agent: std::sync::Weak<super::Inner>,
|
||||
pub(crate) vips: crate::vip::VipSet,
|
||||
pub(crate) retirements: Vec<SignedRetirement>,
|
||||
pub(crate) broadcast: bool,
|
||||
@@ -406,6 +408,7 @@ struct Runtime {
|
||||
/// Links currently being opened, so we do not start two.
|
||||
opening: HashSet<(EndpointId, String)>,
|
||||
link_tasks: HashMap<(EndpointId, String), tokio::task::AbortHandle>,
|
||||
reverse_dials: HashMap<(EndpointId, String), u64>,
|
||||
link_attempts: HashMap<(EndpointId, String), u64>,
|
||||
next_link_attempt: u64,
|
||||
link_results_tx: mpsc::Sender<LinkOutcome>,
|
||||
@@ -462,7 +465,11 @@ impl Runtime {
|
||||
let (link_results_tx, link_results_rx) = mpsc::channel(64);
|
||||
let (candidate_tx, discovery_candidates) =
|
||||
mpsc::channel(params.limits.max_discovery_candidates.max(1));
|
||||
let hub = crate::dataplane::relay::RelayHub::new(network_id, local_id);
|
||||
let hub = crate::dataplane::relay::RelayHub::with_monitor(
|
||||
network_id,
|
||||
local_id,
|
||||
params.routes.traffic.clone(),
|
||||
);
|
||||
// The order the protocols were configured in is also how links are
|
||||
// preferred when a neighbour can be reached over more than one.
|
||||
hub.set_priority(
|
||||
@@ -510,6 +517,7 @@ impl Runtime {
|
||||
announced_reach: HashSet::new(),
|
||||
opening: HashSet::new(),
|
||||
link_tasks: HashMap::new(),
|
||||
reverse_dials: HashMap::new(),
|
||||
link_attempts: HashMap::new(),
|
||||
next_link_attempt: 0,
|
||||
link_results_tx,
|
||||
@@ -544,6 +552,7 @@ impl Runtime {
|
||||
// address it holds.
|
||||
self.load_state().await;
|
||||
|
||||
let mut roster = self.params.roster_changed.subscribe();
|
||||
let mut ticker = tokio::time::interval(self.params.discovery_interval);
|
||||
ticker.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
@@ -554,6 +563,7 @@ impl Runtime {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.shutdown.wait() => break,
|
||||
_ = roster.changed() => self.sync_exit_use(),
|
||||
_ = reach_refresh.tick(), if self.params.discovery_interval > REACH_EXPIRY / 3 => self.announce_reach(false),
|
||||
_ = self.hub.changed() => {
|
||||
self.ensure_links();
|
||||
@@ -585,6 +595,7 @@ impl Runtime {
|
||||
self.start_dials();
|
||||
}
|
||||
_ = ticker.tick() => {
|
||||
self.sync_exit_use(); // Retry an announcement if the control queue was full.
|
||||
self.discovery_round().await;
|
||||
self.ensure_links();
|
||||
self.update_paths();
|
||||
@@ -656,7 +667,7 @@ impl Runtime {
|
||||
message,
|
||||
reply,
|
||||
} => {
|
||||
if matches!(&message, ControlMessage::Transport { .. })
|
||||
if matches!(&message, ControlMessage::Transport { protocol, .. } if protocol != tsunagi_speedtest::PROTOCOL)
|
||||
&& let Some(interface) = self.params.interface.clone()
|
||||
{
|
||||
// Locally bound pair sockets must be protected before their
|
||||
@@ -837,10 +848,12 @@ impl Runtime {
|
||||
/// Used when a plugin's capability changed, so peers do not have to wait
|
||||
/// for a reconnect to learn about it.
|
||||
fn reannounce(&mut self) {
|
||||
let announcement = ControlMessage::Announce(self.local_announcement());
|
||||
let announcement = self.local_announcement();
|
||||
self.announced_exit = announcement.exit_node;
|
||||
let via = self.exit_policy().via;
|
||||
let peers: Vec<EndpointId> = self.sessions.keys().copied().collect();
|
||||
for peer in peers {
|
||||
if let Err(err) = self.send_to(peer, announcement.clone()) {
|
||||
if let Err(err) = self.announce_to(peer, announcement.clone(), via) {
|
||||
tracing::debug!(%err, "could not queue re-announcement");
|
||||
}
|
||||
}
|
||||
@@ -848,6 +861,43 @@ impl Runtime {
|
||||
self.update_paths();
|
||||
}
|
||||
|
||||
fn announce_to(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
mut announcement: Announcement,
|
||||
via: Option<EndpointId>,
|
||||
) -> Result<()> {
|
||||
let selected = via == Some(peer);
|
||||
announcement.uses_your_exit = Some(selected);
|
||||
self.send_to(peer, ControlMessage::Announce(announcement))?;
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
session.notified_exit_use = Some(selected);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// The selected route is shared by all network actors. A selection in another
|
||||
// network must also clear the old gateway, even if neither peer sends traffic.
|
||||
fn sync_exit_use(&mut self) {
|
||||
let via = self.exit_policy().via;
|
||||
let changed: Vec<_> = self
|
||||
.sessions
|
||||
.iter()
|
||||
.filter_map(|(id, session)| {
|
||||
(session.notified_exit_use != Some(via == Some(*id))).then_some(*id)
|
||||
})
|
||||
.collect();
|
||||
if changed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let announcement = self.local_announcement();
|
||||
for peer in changed {
|
||||
if let Err(err) = self.announce_to(peer, announcement.clone(), via) {
|
||||
tracing::debug!(%err, "could not queue exit selection");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Queues a message without blocking the runtime loop.
|
||||
///
|
||||
/// The envelope is encoded here so that the exact number of control bytes
|
||||
@@ -871,6 +921,12 @@ impl Runtime {
|
||||
|
||||
match session.outbound.try_send(zeroize::Zeroizing::new(encoded)) {
|
||||
Ok(()) => {
|
||||
self.params.routes.traffic.control(
|
||||
network,
|
||||
peer,
|
||||
crate::traffic::Direction::Tx,
|
||||
bytes,
|
||||
);
|
||||
session.messages_sent += 1;
|
||||
session.bytes_sent += bytes;
|
||||
self.metrics.control_messages_sent += 1;
|
||||
@@ -2033,12 +2089,12 @@ impl Runtime {
|
||||
|
||||
/// Opens whatever data plane links are missing, and forgets dead ones.
|
||||
///
|
||||
/// Only one side dials, chosen by a rule both sides compute the same way,
|
||||
/// so two agents never open two links for the same thing.
|
||||
/// The smaller endpoint coordinates each attempt, including a reverse
|
||||
/// TCP dial if the negotiated carrier supports it.
|
||||
fn ensure_links(&mut self) {
|
||||
let Some(transport) = self.params.transport.clone() else {
|
||||
if self.params.transport.is_none() {
|
||||
return;
|
||||
};
|
||||
}
|
||||
let served = self.served_protocols();
|
||||
if served.is_empty() {
|
||||
return;
|
||||
@@ -2104,8 +2160,7 @@ impl Runtime {
|
||||
if self.no_direct_data(peer) {
|
||||
continue;
|
||||
}
|
||||
// The smaller endpoint id dials; the other side accepts. Both
|
||||
// compute this identically, so exactly one link is created.
|
||||
// The smaller endpoint tries first and can invite a peer to dial back.
|
||||
if self.local_id.as_bytes() >= peer.as_bytes() {
|
||||
continue;
|
||||
}
|
||||
@@ -2153,6 +2208,7 @@ impl Runtime {
|
||||
for key in interrupted {
|
||||
self.opening.remove(&key);
|
||||
self.link_attempts.remove(&key);
|
||||
self.reverse_dials.remove(&key);
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
@@ -2161,49 +2217,57 @@ impl Runtime {
|
||||
let trial = self.next_comparison(&served, now);
|
||||
wanted.extend(trial.iter().cloned());
|
||||
for (peer, protocol) in wanted {
|
||||
let key = (peer, protocol.clone());
|
||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
self.opening.insert(key.clone());
|
||||
|
||||
let results = self.link_results_tx.clone();
|
||||
let transport = Arc::clone(&transport);
|
||||
let network = self.network_id;
|
||||
let shutdown = self.shutdown.clone();
|
||||
let background = trial.as_ref() == Some(&key);
|
||||
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
|
||||
let generation = self.next_link_attempt;
|
||||
self.link_attempts.insert(key.clone(), generation);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => Err("network deactivated".to_string()),
|
||||
result = async {
|
||||
let dial = transport.open(network, peer, &protocol);
|
||||
if background {
|
||||
tokio::time::timeout(Duration::from_secs(30), dial).await
|
||||
.map_err(|_| "carrier comparison timed out".to_owned())?
|
||||
} else {
|
||||
dial.await
|
||||
}.map_err(|err| err.to_string())
|
||||
} => {
|
||||
result
|
||||
}
|
||||
};
|
||||
let _ = results
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
let background = trial.as_ref() == Some(&(peer, protocol.clone()));
|
||||
self.start_link_attempt(peer, protocol, background);
|
||||
}
|
||||
}
|
||||
|
||||
fn start_link_attempt(&mut self, peer: EndpointId, protocol: String, background: bool) {
|
||||
let Some(transport) = self.params.transport.clone() else {
|
||||
return;
|
||||
};
|
||||
let key = (peer, protocol.clone());
|
||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
||||
return;
|
||||
}
|
||||
self.opening.insert(key.clone());
|
||||
|
||||
let results = self.link_results_tx.clone();
|
||||
|
||||
let network = self.network_id;
|
||||
let shutdown = self.shutdown.clone();
|
||||
|
||||
self.next_link_attempt = self.next_link_attempt.wrapping_add(1);
|
||||
let generation = self.next_link_attempt;
|
||||
self.link_attempts.insert(key.clone(), generation);
|
||||
let task = tokio::spawn(async move {
|
||||
let result = tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.wait() => Err("network deactivated".to_string()),
|
||||
result = async {
|
||||
let dial = transport.open(network, peer, &protocol);
|
||||
if background {
|
||||
tokio::time::timeout(Duration::from_secs(30), dial).await
|
||||
.map_err(|_| "carrier comparison timed out".to_owned())?
|
||||
} else {
|
||||
dial.await
|
||||
}.map_err(|err| err.to_string())
|
||||
} => {
|
||||
result
|
||||
}
|
||||
};
|
||||
let _ = results
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result,
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
}
|
||||
|
||||
/// Takes in what another member knows about the rest.
|
||||
///
|
||||
/// Returns how many of them were new here, which is the only reason to
|
||||
@@ -2476,6 +2540,17 @@ impl Runtime {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if outcome.result.is_err() {
|
||||
if let Some(token) = self.reverse_dials.remove(&key) {
|
||||
if self.local_id > outcome.peer {
|
||||
self.send_reverse(outcome.peer, &outcome.protocol, token, false);
|
||||
}
|
||||
} else if self.ask_for_reverse(&outcome) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
self.reverse_dials.remove(&key);
|
||||
}
|
||||
self.link_attempts.remove(&key);
|
||||
self.opening.remove(&key);
|
||||
self.link_tasks.remove(&key);
|
||||
@@ -2533,6 +2608,21 @@ impl Runtime {
|
||||
inbound.link.close();
|
||||
return;
|
||||
}
|
||||
let key = (inbound.peer, inbound.protocol.clone());
|
||||
if self.local_id < inbound.peer
|
||||
&& self.can_reverse(inbound.peer, &inbound.protocol)
|
||||
&& !self.reverse_dials.contains_key(&key)
|
||||
{
|
||||
inbound.link.close();
|
||||
return;
|
||||
}
|
||||
if self.local_id < inbound.peer && self.reverse_dials.remove(&key).is_some() {
|
||||
self.link_attempts.remove(&key);
|
||||
self.opening.remove(&key);
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
self.record_protocol_success(inbound.peer, &inbound.protocol);
|
||||
self.adopt_link(inbound.peer, inbound.protocol, inbound.link);
|
||||
self.update_paths();
|
||||
@@ -2622,6 +2712,7 @@ impl Runtime {
|
||||
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
||||
self.comparisons.remove(&peer);
|
||||
self.data_errors.remove(&peer);
|
||||
self.reverse_dials.retain(|(id, _), _| *id != peer);
|
||||
self.link_attempts.retain(|(id, _), _| *id != peer);
|
||||
self.opening.retain(|(id, _)| *id != peer);
|
||||
self.link_tasks.retain(|(id, _), task| {
|
||||
@@ -2691,6 +2782,9 @@ impl Runtime {
|
||||
return;
|
||||
}
|
||||
if let Some(old) = self.sessions.remove(&peer) {
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
old.abort();
|
||||
old.conn
|
||||
.close(0u32.into(), b"replaced by preferred session");
|
||||
@@ -2723,8 +2817,8 @@ impl Runtime {
|
||||
|
||||
// Announce ourselves straight away so the peer learns our hostname and
|
||||
// capabilities without another round of discovery.
|
||||
let announcement = ControlMessage::Announce(self.local_announcement());
|
||||
if let Err(err) = self.send_to(peer, announcement) {
|
||||
let announcement = self.local_announcement();
|
||||
if let Err(err) = self.announce_to(peer, announcement, self.exit_policy().via) {
|
||||
tracing::debug!(%err, "could not queue initial announcement");
|
||||
}
|
||||
|
||||
@@ -2776,9 +2870,23 @@ impl Runtime {
|
||||
reason,
|
||||
});
|
||||
}
|
||||
if self
|
||||
.params
|
||||
.carriers
|
||||
.iter()
|
||||
.any(|c| c.supports_reverse_dial())
|
||||
{
|
||||
capabilities.push(reverse::capability());
|
||||
}
|
||||
if self.params.carriers.len() > 1 {
|
||||
capabilities.push(selection::capability());
|
||||
}
|
||||
if self.params.interface.is_some()
|
||||
&& self.params.tunnel.is_some()
|
||||
&& !self.params.carriers.is_empty()
|
||||
{
|
||||
capabilities.push(super::speed::capability());
|
||||
}
|
||||
capabilities.truncate(self.params.limits.max_capabilities);
|
||||
self.local_capabilities = capabilities
|
||||
.iter()
|
||||
@@ -2788,13 +2896,13 @@ impl Runtime {
|
||||
})
|
||||
.collect();
|
||||
let exit_node = self.exit_ready();
|
||||
self.announced_exit = exit_node;
|
||||
Announcement {
|
||||
broadcast: self.params.broadcast,
|
||||
exit_node,
|
||||
hostname: self.params.hostname.clone(),
|
||||
capabilities,
|
||||
agent_version: Some(env!("CARGO_PKG_VERSION").to_owned()),
|
||||
uses_your_exit: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2828,6 +2936,12 @@ impl Runtime {
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
self.params.routes.traffic.control(
|
||||
self.network_id,
|
||||
peer,
|
||||
crate::traffic::Direction::Rx,
|
||||
bytes as u64,
|
||||
);
|
||||
self.metrics.control_messages_received += 1;
|
||||
self.metrics.control_bytes_received += bytes as u64;
|
||||
if let Some(session) = self.sessions.get_mut(&peer) {
|
||||
@@ -2855,13 +2969,21 @@ impl Runtime {
|
||||
SessionEvent::Closed {
|
||||
session_id,
|
||||
peer,
|
||||
reason,
|
||||
mut reason,
|
||||
} => {
|
||||
let current = self.sessions.get(&peer).map(|session| session.id);
|
||||
if current != Some(session_id) {
|
||||
return;
|
||||
}
|
||||
if let Some(inner) = self.params.agent.upgrade() {
|
||||
inner.speed.disconnected(self.network_id, peer);
|
||||
}
|
||||
if let Some(session) = self.sessions.remove(&peer) {
|
||||
// Read the cause before local cleanup closes a still-open connection.
|
||||
if let Some(cause) = session.conn.close_reason() {
|
||||
reason =
|
||||
format!("{reason} ({})", super::session::describe_quic_close(cause));
|
||||
}
|
||||
session.abort();
|
||||
session.conn.close(0u32.into(), b"session ended");
|
||||
}
|
||||
@@ -2885,7 +3007,13 @@ impl Runtime {
|
||||
self.params.roster_changed.send_replace(());
|
||||
self.emit(Event::PeerDisconnected {
|
||||
network: self.network_id,
|
||||
network_name: self.params.keys.name().clone(),
|
||||
peer,
|
||||
hostname: self
|
||||
.known_hostnames
|
||||
.get(&peer)
|
||||
.cloned()
|
||||
.or_else(|| self.state.hostname_of(&peer).map(str::to_owned)),
|
||||
reason,
|
||||
});
|
||||
}
|
||||
@@ -2923,6 +3051,29 @@ impl Runtime {
|
||||
fn dispatch_message(&mut self, peer: EndpointId, message: ControlMessage) {
|
||||
match &message {
|
||||
ControlMessage::Transport { protocol, payload } => {
|
||||
if protocol == tsunagi_speedtest::PROTOCOL {
|
||||
if super::speed::supported(&self.local_capabilities)
|
||||
&& let Some(session) = self.sessions.get(&peer)
|
||||
&& super::speed::supported(&session.capabilities)
|
||||
&& let Some(message) =
|
||||
tsunagi_speedtest::Control::decode(payload.as_bytes())
|
||||
&& let Some(inner) = self.params.agent.upgrade()
|
||||
&& let Some(reply) = super::speed::receive_control(
|
||||
&inner,
|
||||
self.network_id,
|
||||
peer,
|
||||
message,
|
||||
|| snapshot_connection(&session.conn).rtt,
|
||||
)
|
||||
{
|
||||
let _ = self.send_to(peer, reply);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if protocol == reverse::PROTOCOL {
|
||||
self.receive_reverse(peer, payload.as_bytes());
|
||||
return;
|
||||
}
|
||||
if protocol == selection::PROTOCOL {
|
||||
self.receive_choice(peer, payload.as_bytes());
|
||||
return;
|
||||
@@ -2975,7 +3126,7 @@ impl Runtime {
|
||||
let changed = self.sessions.get(&peer).is_some_and(|session| {
|
||||
let selection = |caps: &[PluginCapability]| {
|
||||
caps.iter()
|
||||
.filter(|c| c.enabled)
|
||||
.filter(|c| c.enabled && c.protocol != tsunagi_speedtest::PROTOCOL)
|
||||
.map(|c| (c.protocol.clone(), c.version))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
@@ -2989,6 +3140,7 @@ impl Runtime {
|
||||
session
|
||||
.agent_version
|
||||
.clone_from(&announcement.agent_version);
|
||||
session.uses_our_exit = announcement.uses_your_exit;
|
||||
session.broadcast = announcement.broadcast;
|
||||
if session.exit_node != announcement.exit_node {
|
||||
session.exit_node = announcement.exit_node;
|
||||
@@ -3050,6 +3202,14 @@ impl Runtime {
|
||||
|
||||
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
||||
let mut errors = Vec::new();
|
||||
let ranges = self.params.routes.overlay_ranges();
|
||||
let ips: Vec<_> = self.sessions.get(&peer).into_iter()
|
||||
.flat_map(|session| snapshot_connection(&session.conn).paths)
|
||||
.filter_map(|path| match path.remote {
|
||||
PathAddr::Ip(addr) => Some(addr.ip().to_canonical()), _ => None,
|
||||
})
|
||||
.filter(|ip| !matches!(ip, std::net::IpAddr::V4(v4) if ranges.iter().any(|range| range.contains(*v4))))
|
||||
.take(self.params.limits.max_hints_per_peer).collect();
|
||||
for cap in capabilities {
|
||||
let carriers = self
|
||||
.params
|
||||
@@ -3060,7 +3220,7 @@ impl Runtime {
|
||||
(
|
||||
carrier.protocol_version(),
|
||||
if carrier.protocol_version() == cap.version {
|
||||
carrier.on_peer_capability(self.network_id, peer, cap)
|
||||
carrier.on_peer_capability_at(self.network_id, peer, cap, &ips)
|
||||
} else {
|
||||
Ok(())
|
||||
},
|
||||
@@ -3216,6 +3376,7 @@ impl Runtime {
|
||||
.iter()
|
||||
.filter(|cap| {
|
||||
cap.enabled
|
||||
&& cap.protocol != reverse::PROTOCOL
|
||||
&& cap.protocol != selection::PROTOCOL
|
||||
&& self
|
||||
.params
|
||||
@@ -3238,6 +3399,7 @@ impl Runtime {
|
||||
}
|
||||
|
||||
fn status(&self) -> NetworkStatus {
|
||||
let exit = self.exit_policy();
|
||||
let served = self.served_protocols();
|
||||
let mut peers: Vec<PeerStatus> = self
|
||||
.sessions
|
||||
@@ -3257,6 +3419,12 @@ impl Runtime {
|
||||
data_transport_detail: selected.map(|link| link.path_description()),
|
||||
broadcast: session.broadcast,
|
||||
exit_node: session.exit_node,
|
||||
uses_our_exit: exit.offer
|
||||
&& session.uses_our_exit.unwrap_or_else(|| {
|
||||
self.params
|
||||
.routes
|
||||
.recent_exit_client(self.network_id, session.peer)
|
||||
}),
|
||||
endpoint_id: session.peer,
|
||||
role: session.role,
|
||||
agent_version: session.agent_version.clone(),
|
||||
@@ -3334,8 +3502,19 @@ impl Runtime {
|
||||
members.sort_by(|a, b| a.endpoint_id.as_bytes().cmp(b.endpoint_id.as_bytes()));
|
||||
members.dedup_by(|a, b| a.endpoint_id == b.endpoint_id);
|
||||
|
||||
let exit = self.exit_policy();
|
||||
NetworkStatus {
|
||||
speed: self
|
||||
.params
|
||||
.agent
|
||||
.upgrade()
|
||||
.map(|inner| {
|
||||
inner.speed.report(
|
||||
self.network_id,
|
||||
&peers,
|
||||
super::speed::supported(&self.local_capabilities),
|
||||
)
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
vips: self.params.routes.vips.statuses(self.network_id),
|
||||
protocols: self
|
||||
.params
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
//! The elected opener grants one bounded reverse dial over authenticated control.
|
||||
use super::{ControlMessage, EndpointId, LinkOutcome, PluginCapability, Runtime};
|
||||
use crate::dataplane::transport::{DataCarrier, PacketLink, TransportPayload};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub(super) const PROTOCOL: &str = "link-reverse";
|
||||
|
||||
pub(super) fn capability() -> PluginCapability {
|
||||
PluginCapability {
|
||||
protocol: PROTOCOL.into(),
|
||||
version: 1,
|
||||
enabled: true,
|
||||
data: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
impl Runtime {
|
||||
fn mutual_carrier(&self, peer: EndpointId, name: &str) -> Option<&dyn DataCarrier> {
|
||||
let caps = &self.sessions.get(&peer)?.capabilities;
|
||||
self.params
|
||||
.carriers
|
||||
.iter()
|
||||
.find(|c| {
|
||||
c.protocol_id() == name
|
||||
&& caps.iter().any(|cap| {
|
||||
cap.enabled && cap.protocol == name && cap.version == c.protocol_version()
|
||||
})
|
||||
})
|
||||
.map(|c| c.as_ref())
|
||||
}
|
||||
|
||||
pub(super) fn can_reverse(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||
self.mutual_carrier(peer, protocol)
|
||||
.is_some_and(|c| c.supports_reverse_dial())
|
||||
&& self.sessions.get(&peer).is_some_and(|s| {
|
||||
s.capabilities
|
||||
.iter()
|
||||
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn send_reverse(
|
||||
&mut self,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
token: u64,
|
||||
request: bool,
|
||||
) -> bool {
|
||||
let Ok(bytes) = postcard::to_stdvec(&(request, token, protocol)) else {
|
||||
return false;
|
||||
};
|
||||
self.send_to(
|
||||
peer,
|
||||
ControlMessage::Transport {
|
||||
protocol: PROTOCOL.into(),
|
||||
payload: TransportPayload::new(bytes),
|
||||
},
|
||||
)
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
pub(super) fn ask_for_reverse(&mut self, attempt: &LinkOutcome) -> bool {
|
||||
let peer = attempt.peer;
|
||||
let protocol = &attempt.protocol;
|
||||
let generation = attempt.generation;
|
||||
if self.local_id >= peer
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
|| !self.send_reverse(peer, protocol, generation, true)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
let key = (peer, protocol.clone());
|
||||
self.reverse_dials.insert(key.clone(), generation);
|
||||
let tx = self.link_results_tx.clone();
|
||||
let protocol = protocol.clone();
|
||||
let task = tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_secs(12)).await;
|
||||
let _ = tx
|
||||
.send(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol,
|
||||
result: Err("reverse TCP dial timed out".into()),
|
||||
})
|
||||
.await;
|
||||
});
|
||||
self.link_tasks.insert(key, task.abort_handle());
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn receive_reverse(&mut self, peer: EndpointId, payload: &[u8]) {
|
||||
let Ok((request, generation, protocol)) =
|
||||
postcard::from_bytes::<(bool, u64, &str)>(payload)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if protocol.len() > crate::dataplane::MAX_PROTOCOL_ID_LEN
|
||||
|| !self.can_reverse(peer, protocol)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let key = (peer, protocol.to_owned());
|
||||
if request && peer < self.local_id {
|
||||
if self.opening.contains(&key) || self.links.get(&key).is_some_and(|l| !l.is_closed()) {
|
||||
return;
|
||||
}
|
||||
if self.no_direct_data(peer)
|
||||
|| self
|
||||
.protocol_dial_states
|
||||
.get(&key)
|
||||
.is_some_and(|s| s.cooldown_until > Instant::now())
|
||||
{
|
||||
self.send_reverse(peer, protocol, generation, false);
|
||||
return;
|
||||
}
|
||||
self.reverse_dials.insert(key, generation);
|
||||
self.start_link_attempt(peer, protocol.to_owned(), false);
|
||||
} else if !request
|
||||
&& self.local_id < peer
|
||||
&& self.reverse_dials.get(&key) == Some(&generation)
|
||||
{
|
||||
if let Some(task) = self.link_tasks.remove(&key) {
|
||||
task.abort();
|
||||
}
|
||||
self.handle_link_result(LinkOutcome {
|
||||
generation,
|
||||
peer,
|
||||
protocol: protocol.into(),
|
||||
result: Err("neither TCP dial direction succeeded".into()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
@@ -77,6 +93,10 @@ pub(crate) struct Session {
|
||||
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.
|
||||
@@ -237,6 +257,8 @@ pub(crate) fn spawn(
|
||||
reach_sent: None,
|
||||
hostname: None,
|
||||
agent_version: None,
|
||||
uses_our_exit: None,
|
||||
notified_exit_use: None,
|
||||
capabilities: Vec::new(),
|
||||
broadcast: false,
|
||||
exit_node: false,
|
||||
|
||||
@@ -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))
|
||||
}
|
||||
@@ -145,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.
|
||||
@@ -240,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.
|
||||
|
||||
@@ -50,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
|
||||
@@ -211,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.
|
||||
@@ -247,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,
|
||||
@@ -569,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;
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
@@ -324,11 +334,21 @@ 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(),
|
||||
|
||||
@@ -175,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());
|
||||
@@ -199,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,10 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||
fn protocol_id(&self) -> &str;
|
||||
/// Wire version, independent of software releases and the internal tunnel.
|
||||
fn protocol_version(&self) -> u16;
|
||||
/// Whether the peer may dial back after an unsuccessful elected dial.
|
||||
fn supports_reverse_dial(&self) -> bool {
|
||||
false
|
||||
}
|
||||
/// Supported carrier settings.
|
||||
fn options(&self) -> &'static [ProtocolOption] {
|
||||
&[]
|
||||
@@ -25,6 +29,17 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
) -> Result<(), PluginError>;
|
||||
/// Adds IP hints from verified direct control paths. Their UDP ports do not
|
||||
/// identify a TCP listener. Carriers authenticate their own data path.
|
||||
fn on_peer_capability_at(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
capability: &PluginCapability,
|
||||
_ips: &[std::net::IpAddr],
|
||||
) -> Result<(), PluginError> {
|
||||
self.on_peer_capability(network, peer, capability)
|
||||
}
|
||||
/// Supplies the actual owned interface name, including kernel-assigned names.
|
||||
fn on_interface_ready(&self, _name: &str) {}
|
||||
/// Activates this carrier for one local network.
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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.
|
||||
@@ -702,6 +739,10 @@ pub struct RangeConflictReport {
|
||||
/// A data-plane protocol available in the running agent.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProtocolReport {
|
||||
/// UI family of this transport.
|
||||
pub group: String,
|
||||
/// Human-readable protocol name.
|
||||
pub label: String,
|
||||
/// Stable protocol name used by the CLI and network negotiation.
|
||||
pub name: String,
|
||||
/// A short description of encryption and transport.
|
||||
@@ -711,6 +752,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>,
|
||||
@@ -830,6 +874,9 @@ 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.
|
||||
@@ -940,10 +987,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.
|
||||
@@ -989,6 +1038,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,
|
||||
@@ -1061,6 +1116,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.
|
||||
@@ -1100,8 +1173,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()) })
|
||||
}
|
||||
|
||||
@@ -1145,13 +1218,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', 25]);
|
||||
pub const CONTROL_PROTOCOL: u32 = u32::from_be_bytes([b'T', b'S', b'N', 30]);
|
||||
|
||||
/// 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,
|
||||
{
|
||||
@@ -1169,6 +1246,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,
|
||||
@@ -1231,6 +1318,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,
|
||||
@@ -1415,23 +1514,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(
|
||||
@@ -1450,6 +1532,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.
|
||||
|
||||
@@ -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>,
|
||||
}
|
||||
@@ -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,7 +3,7 @@
|
||||
//! One of the per-platform adapters; see [`super`]. It provides only what is
|
||||
//! particular to a Unix socket — binding a listener, connecting a client, and
|
||||
//! the owner-only permissions — and hands every accepted connection to the
|
||||
//! shared [`serve_connection`](super::serve_connection). The request framing,
|
||||
//! shared connection handler. The request framing,
|
||||
//! the dispatch and the client wrappers are the same on every platform and
|
||||
//! live in [`super`], re-exported here so `ipc::unix::request_status` and its
|
||||
//! siblings keep resolving.
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
//! A named-pipe adapter for the local control interface.
|
||||
//!
|
||||
//! The Windows counterpart of [`super::unix`]. It provides only what is
|
||||
//! The Windows counterpart of the Unix socket adapter. It provides only what is
|
||||
//! particular to a named pipe — creating the server instance, opening a client
|
||||
//! and turning the state directory path into a pipe name — and hands every
|
||||
//! accepted connection to the shared [`serve_connection`](super::serve_connection).
|
||||
//! accepted connection to the shared connection handler.
|
||||
//! The framing, the dispatch and the client wrappers are the same on every
|
||||
//! platform and live in [`super`], re-exported here so `ipc::windows::request_status`
|
||||
//! and its siblings resolve just as their Unix equivalents do.
|
||||
@@ -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");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -31,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
|
||||
@@ -28,7 +30,7 @@
|
||||
//! 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,
|
||||
@@ -56,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)]
|
||||
@@ -70,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
|
||||
@@ -125,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],
|
||||
),
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
@@ -159,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>:`
|
||||
@@ -198,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()
|
||||
@@ -380,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}"))
|
||||
@@ -391,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")?,
|
||||
@@ -481,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,
|
||||
@@ -567,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
|
||||
@@ -671,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"
|
||||
@@ -805,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:?}"
|
||||
@@ -837,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());
|
||||
}
|
||||
@@ -857,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());
|
||||
@@ -875,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"),
|
||||
@@ -897,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]
|
||||
|
||||
@@ -467,3 +467,216 @@ 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)
|
||||
// B runs as a system service, even when the test was started from a login.
|
||||
.env_remove("XDG_RUNTIME_DIR")
|
||||
.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());
|
||||
|
||||
@@ -22,7 +22,9 @@ use crate::BoxFuture;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::exit::{ExitHostPlan, ExitHostReport, ExitHostRules};
|
||||
use super::macos_exit::{HostState, apply_plan, clear_all, refresh_client, 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.
|
||||
@@ -64,8 +66,8 @@ fn firewall_todo(plan: &BroadcastRulesPlan) -> String {
|
||||
)
|
||||
}
|
||||
|
||||
/// The macOS implementation: `route` for the route, no firewall yet, and
|
||||
/// `pf` plus `route` for exit nodes (see [`super::macos_exit`]).
|
||||
/// Installs macOS broadcast routes with `route` and manages exit routing with
|
||||
/// `pf` and `route`.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MacosHostRules {
|
||||
/// The PF reference and the physical routes owned by this agent.
|
||||
@@ -134,6 +136,22 @@ impl ExitHostRules for MacosHostRules {
|
||||
})
|
||||
}
|
||||
|
||||
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();
|
||||
|
||||
@@ -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' "$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 $range to ! $range 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
|
||||
@@ -8,19 +8,21 @@
|
||||
//! Per offered range, in the anchor `com.apple/tsunagi-exit-<if>`:
|
||||
//!
|
||||
//! ```text
|
||||
//! nat on <egress> inet from <range> to any -> (<egress>)
|
||||
//! pass in quick on <if> inet from <range> to ! <range>
|
||||
//! nat on <egress> inet from <range> to any tagged <forwarded> -> (<egress>)
|
||||
//! pass in quick on <if> inet from <range> to ! <range> tag <forwarded> no state
|
||||
//! pass out quick on <if> route-to (<egress> <gateway>) inet from <range> to ! <range> tagged <forwarded> no state
|
||||
//! pass out quick on <egress> inet from any to any flags any tagged <forwarded> keep state (if-bound)
|
||||
//! ```
|
||||
//!
|
||||
//! The anchor lives under `com.apple/` on purpose: the stock `/etc/pf.conf`
|
||||
//! evaluates `nat-anchor "com.apple/*"` and `anchor "com.apple/*"`, so the
|
||||
//! rules take effect without editing the user's ruleset. `pf` cannot say
|
||||
//! "every interface but one" in a translation address, so the egress is the
|
||||
//! interface of the physical default route. An active exit client refreshes
|
||||
//! the rules when this egress changes.
|
||||
//! interface of the physical default route. Both roles follow egress changes.
|
||||
//!
|
||||
//! The kernel's `net.inet.ip.forwarding` is only read, never written: it
|
||||
//! changes how the whole host behaves, which is the owner's decision.
|
||||
//! A local offer enables IPv4 forwarding after its rules are loaded. This
|
||||
//! host-wide switch has no ownership token, so cleanup only releases our PF
|
||||
//! reference and removes our own rules.
|
||||
//!
|
||||
//! # Using
|
||||
//!
|
||||
@@ -70,6 +72,9 @@ use crate::state::Ipv4Range;
|
||||
use super::RuleOutcome;
|
||||
use super::exit::{ExitHostPlan, ExitHostReport};
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
#[path = "macos_exit_helper_tests.rs"]
|
||||
mod helper_tests;
|
||||
#[cfg(all(test, target_os = "macos", feature = "tun-device"))]
|
||||
#[path = "macos_exit_kernel.rs"]
|
||||
mod kernel;
|
||||
@@ -77,6 +82,21 @@ mod kernel;
|
||||
mod scoped;
|
||||
use scoped::ScopedRoutes;
|
||||
|
||||
use super::macos_authorization::NEEDS_AUTHORIZATION;
|
||||
#[cfg(test)]
|
||||
use super::macos_authorization::{macos_exit_authorization_uid, macos_exit_needs_authorization};
|
||||
|
||||
const OFFER_HELPER: &str = "/private/etc/tsunagi-exit/offer-v1";
|
||||
|
||||
fn offer_helper_available(path: &std::path::Path, action: &str) -> bool {
|
||||
// A previous release can still remove its own PF anchors. Applying its
|
||||
// obsolete rules would silently restore the broken return path.
|
||||
if action == "clear" {
|
||||
return path.is_file();
|
||||
}
|
||||
std::fs::read(path).is_ok_and(|bytes| bytes == include_bytes!("macos/exit-offer.sh").as_slice())
|
||||
}
|
||||
|
||||
/// The programs this module runs, always by absolute path.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Tool {
|
||||
@@ -84,6 +104,7 @@ pub(super) enum Tool {
|
||||
Pfctl,
|
||||
Sysctl,
|
||||
Id,
|
||||
OfferHelper,
|
||||
}
|
||||
|
||||
impl Tool {
|
||||
@@ -93,6 +114,7 @@ impl Tool {
|
||||
Self::Pfctl => "/sbin/pfctl",
|
||||
Self::Sysctl => "/usr/sbin/sysctl",
|
||||
Self::Id => "/usr/bin/id",
|
||||
Self::OfferHelper => OFFER_HELPER,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -119,7 +141,21 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
|
||||
use std::io::Write;
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
let mut command = Command::new(tool.path());
|
||||
let mut command = if tool == Tool::OfferHelper {
|
||||
let path = std::path::Path::new(OFFER_HELPER);
|
||||
if !args
|
||||
.first()
|
||||
.is_some_and(|op| offer_helper_available(path, op))
|
||||
{
|
||||
return Ran::Missing;
|
||||
}
|
||||
let mut sudo = Command::new("/usr/bin/sudo");
|
||||
sudo.args(["-n", "--", OFFER_HELPER])
|
||||
.arg(std::process::id().to_string());
|
||||
sudo
|
||||
} else {
|
||||
Command::new(tool.path())
|
||||
};
|
||||
command
|
||||
.env("LC_ALL", "C")
|
||||
.args(args)
|
||||
@@ -190,6 +226,7 @@ pub(super) struct DefaultRoute {
|
||||
pub(super) struct HostState {
|
||||
token: Mutex<Option<String>>,
|
||||
routes: Mutex<ScopedRoutes>,
|
||||
helper_offers: Mutex<Vec<Ipv4Range>>,
|
||||
}
|
||||
|
||||
impl HostState {
|
||||
@@ -265,7 +302,13 @@ fn default_route(run: Run<'_>, overlay: &str) -> Result<DefaultRoute, String> {
|
||||
Ok(route)
|
||||
}
|
||||
|
||||
/// Whether the kernel forwards IPv4. Read only.
|
||||
/// Physical default interface shared with the socket-based exit forwarder.
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(in crate::overlay) fn macos_default_uplink() -> Result<String, String> {
|
||||
default_route(&run_tool, "").map(|route| route.interface)
|
||||
}
|
||||
|
||||
/// Whether the kernel forwards IPv4.
|
||||
fn forwarding_state(run: Run<'_>) -> Option<bool> {
|
||||
let out = run_ok(
|
||||
run,
|
||||
@@ -281,6 +324,48 @@ fn forwarding_state(run: Run<'_>) -> Option<bool> {
|
||||
}
|
||||
}
|
||||
|
||||
fn enable_forwarding(run: Run<'_>) -> Result<(), String> {
|
||||
match forwarding_state(run) {
|
||||
Some(true) => return Ok(()),
|
||||
Some(false) => {}
|
||||
None => return Err("cannot determine whether macOS forwards IPv4".into()),
|
||||
}
|
||||
run_ok(
|
||||
run,
|
||||
Tool::Sysctl,
|
||||
&owned(&["-w", "net.inet.ip.forwarding=1"]),
|
||||
None,
|
||||
)?;
|
||||
if forwarding_state(run) == Some(true) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err("macOS did not enable IPv4 forwarding".into())
|
||||
}
|
||||
}
|
||||
|
||||
fn permission_denied(reason: &str) -> bool {
|
||||
let reason = reason.to_ascii_lowercase();
|
||||
reason.contains("permission denied") || reason.contains("operation not permitted")
|
||||
}
|
||||
|
||||
fn authorized_offer(
|
||||
run: Run<'_>,
|
||||
action: &str,
|
||||
interface: &str,
|
||||
range: Ipv4Range,
|
||||
) -> Result<(), String> {
|
||||
let args = owned(&[action, interface, &range.to_string()]);
|
||||
match run(Tool::OfferHelper, &args, None) {
|
||||
Ran::Exited { success: true, .. } => Ok(()),
|
||||
Ran::Exited { stdout, stderr, .. }
|
||||
if !stderr.contains("sudo:") && !stderr.contains(NEEDS_AUTHORIZATION) =>
|
||||
{
|
||||
Err(failure(&stderr, &stdout))
|
||||
}
|
||||
_ => Err(NEEDS_AUTHORIZATION.into()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The effective user id of this process, from `id -u`.
|
||||
fn agent_uid(run: Run<'_>) -> Result<u32, String> {
|
||||
run_ok(run, Tool::Id, &owned(&["-u"]), None)
|
||||
@@ -310,6 +395,10 @@ fn pf_rules(
|
||||
let mut nat = Vec::new();
|
||||
let mut filter = Vec::new();
|
||||
let mut tables = Vec::new();
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
if let Some(client) = client {
|
||||
let tag = format!("tsng_underlay_{interface}");
|
||||
nat.push(format!(
|
||||
@@ -327,10 +416,6 @@ fn pf_rules(
|
||||
));
|
||||
format!("! <tsunagi_overlay_{interface}>")
|
||||
};
|
||||
let via = match egress.gateway {
|
||||
Some(gateway) => format!("({out} {gateway})"),
|
||||
None => out.clone(),
|
||||
};
|
||||
filter.push(format!(
|
||||
"pass out quick on {interface} route-to {via} inet proto {{ tcp udp }} \
|
||||
from any to {target} user {} tag {tag} no state",
|
||||
@@ -343,12 +428,35 @@ fn pf_rules(
|
||||
from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
for range in offer {
|
||||
// PF takes the first matching NAT rule. Preserve the transport's source
|
||||
// port even when its overlay source falls inside one of our own offers.
|
||||
nat.push(format!("nat on {out} inet from {range} to any -> ({out})"));
|
||||
if let [first, rest @ ..] = offer {
|
||||
let members = if rest.is_empty() {
|
||||
first.to_string()
|
||||
} else {
|
||||
let name = format!("<tsunagi_offer_{interface}>");
|
||||
let ranges: Vec<_> = offer.iter().map(ToString::to_string).collect();
|
||||
tables.push(format!("table {name} const {{ {} }}", ranges.join(", ")));
|
||||
name
|
||||
};
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
nat.push(format!(
|
||||
"nat on {out} inet from {members} to any tagged {tag} -> ({out})"
|
||||
));
|
||||
// Classify at authenticated overlay ingress. Only packets the host
|
||||
// actually forwards AND its routes send back to our utun need steering.
|
||||
// Local services, connected LANs and the owner's forwarding switch
|
||||
// retain their native kernel behavior.
|
||||
filter.push(format!(
|
||||
"pass in quick on {interface} inet from {range} to ! {range}"
|
||||
"pass in quick on {interface} inet from {members} to ! {members} tag {tag} no state"
|
||||
));
|
||||
// PF restores the state's tag on replies after undoing NAT. A reply
|
||||
// routed back to a member must leave on the overlay with that tag.
|
||||
filter.insert(0, format!(
|
||||
"pass out quick on {interface} route-to {via} inet from {members} to ! {members} tagged {tag} no state"
|
||||
));
|
||||
// Keep the outbound NAT state on the physical interface. A floating
|
||||
// state could consume packets on the utun before the reroute rule runs.
|
||||
filter.push(format!(
|
||||
"pass out quick on {out} inet from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
tables
|
||||
@@ -593,38 +701,80 @@ fn set_routes(
|
||||
|
||||
/// Makes the host match the plan.
|
||||
pub(super) fn apply_plan(run: Run<'_>, state: &HostState, plan: &ExitHostPlan) -> ExitHostReport {
|
||||
let native = apply_rules(run, state, plan, None);
|
||||
let client = plan.client.then(|| verdict(native.clone()));
|
||||
let offer = native.clone().and_then(|()| {
|
||||
if plan.offer.is_empty() {
|
||||
Ok(())
|
||||
} else {
|
||||
enable_forwarding(run)
|
||||
}
|
||||
});
|
||||
// Permission errors can be fixed by a previously approved local helper.
|
||||
// Configuration and tool errors retain their original diagnostics.
|
||||
let helper_uid =
|
||||
if !plan.offer.is_empty() && offer.as_ref().is_err_and(|why| permission_denied(why)) {
|
||||
agent_uid(run).ok().filter(|uid| *uid != 0)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let action = if native.is_ok() { "forward" } else { "apply" };
|
||||
let mut active = lock(&state.helper_offers);
|
||||
let mut wanted = Vec::new();
|
||||
let mut outcomes = Vec::new();
|
||||
for &range in &plan.offer {
|
||||
let outcome = if let Some(uid) = helper_uid {
|
||||
let outcome = authorized_offer(run, action, &plan.interface, range).map_err(|why| {
|
||||
if why == NEEDS_AUTHORIZATION {
|
||||
format!("{NEEDS_AUTHORIZATION} for UID {uid}")
|
||||
} else {
|
||||
why
|
||||
}
|
||||
});
|
||||
if action == "apply" && outcome.is_ok() {
|
||||
wanted.push(range);
|
||||
}
|
||||
outcome
|
||||
} else {
|
||||
offer.clone()
|
||||
};
|
||||
outcomes.push((range, verdict(outcome)));
|
||||
}
|
||||
for range in std::mem::take(&mut *active) {
|
||||
if !wanted.contains(&range)
|
||||
&& let Err(why) = authorized_offer(run, "clear", &plan.interface, range)
|
||||
{
|
||||
tracing::warn!(%range, %why, "could not clear the authorized exit rules");
|
||||
wanted.push(range);
|
||||
}
|
||||
}
|
||||
*active = wanted;
|
||||
if !active.is_empty() && !plan.client {
|
||||
lock(&state.routes).active = default_route(run, &plan.interface).ok();
|
||||
}
|
||||
let forwarding = if plan.offer.is_empty() {
|
||||
None
|
||||
} else {
|
||||
forwarding_state(run)
|
||||
};
|
||||
let outcome = apply_rules(run, state, plan, None);
|
||||
let verdict = |ok: bool, why: &str| {
|
||||
if ok {
|
||||
RuleOutcome::Applied
|
||||
} else {
|
||||
RuleOutcome::Failed(why.to_string())
|
||||
if forwarding != Some(true) {
|
||||
for (_, outcome) in &mut outcomes {
|
||||
if outcome.is_applied() {
|
||||
*outcome = RuleOutcome::Failed("macOS could not confirm IPv4 forwarding".into());
|
||||
}
|
||||
}
|
||||
};
|
||||
match outcome {
|
||||
Ok(()) => ExitHostReport {
|
||||
offer: plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| (*range, RuleOutcome::Applied))
|
||||
.collect(),
|
||||
forwarding,
|
||||
client: plan.client.then_some(RuleOutcome::Applied),
|
||||
},
|
||||
Err(why) => ExitHostReport {
|
||||
offer: plan
|
||||
.offer
|
||||
.iter()
|
||||
.map(|range| (*range, verdict(false, &why)))
|
||||
.collect(),
|
||||
forwarding,
|
||||
client: plan.client.then(|| verdict(false, &why)),
|
||||
},
|
||||
}
|
||||
ExitHostReport {
|
||||
offer: outcomes,
|
||||
forwarding,
|
||||
client,
|
||||
}
|
||||
}
|
||||
|
||||
fn verdict(result: Result<(), String>) -> RuleOutcome {
|
||||
match result {
|
||||
Ok(()) => RuleOutcome::Applied,
|
||||
Err(why) => RuleOutcome::Failed(why),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,18 +828,21 @@ fn apply_rules(
|
||||
return Err(reason);
|
||||
}
|
||||
scoped.retain(run, &wanted)?;
|
||||
scoped.active = Some(egress);
|
||||
} else {
|
||||
clear_routes(run, interface);
|
||||
clear_v6(run, &mut scoped)?;
|
||||
scoped.retain(run, &[])?;
|
||||
scoped.active = None;
|
||||
}
|
||||
scoped.active = Some(egress);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes everything this agent put there for the interface.
|
||||
pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
|
||||
if safe_name(interface) {
|
||||
let _ = run(Tool::OfferHelper, &owned(&["clear", interface]), None);
|
||||
lock(&state.helper_offers).clear();
|
||||
}
|
||||
let mut scoped = lock(&state.routes);
|
||||
clear_routes(run, interface);
|
||||
if let Err(why) = scoped
|
||||
@@ -710,6 +863,26 @@ pub(super) fn clear_all(run: Run<'_>, state: &HostState, interface: &str) {
|
||||
release_pf(run, &state.token);
|
||||
}
|
||||
|
||||
/// An offer's NAT follows the host's physical default even without a local exit client.
|
||||
pub(super) fn refresh_offer(
|
||||
run: Run<'_>,
|
||||
state: &HostState,
|
||||
plan: &ExitHostPlan,
|
||||
) -> Option<ExitHostReport> {
|
||||
let mut routes = lock(&state.routes);
|
||||
if plan.client || plan.offer.is_empty() || !routes.check_due(std::time::Instant::now()) {
|
||||
return None;
|
||||
}
|
||||
if let Ok(egress) = default_route(run, &plan.interface)
|
||||
&& Some(&egress) == routes.active.as_ref()
|
||||
&& forwarding_state(run) == Some(true)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
drop(routes);
|
||||
Some(apply_plan(run, state, plan))
|
||||
}
|
||||
|
||||
/// The logical plan can be unchanged while Wi-Fi changes gateway or moves
|
||||
/// to Ethernet. Rebuild both PF and physical scope against that new egress.
|
||||
pub(super) fn refresh_client(
|
||||
@@ -750,7 +923,7 @@ pub(super) fn refresh_client(
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
use super::*;
|
||||
|
||||
@@ -777,7 +950,10 @@ destination: default\n\
|
||||
calls: RefCell<Vec<String>>,
|
||||
stdins: RefCell<Vec<String>>,
|
||||
default_route: Option<String>,
|
||||
forwarding: &'static str,
|
||||
forwarding: Cell<&'static str>,
|
||||
deny_forwarding: bool,
|
||||
deny_pf: bool,
|
||||
helper: bool,
|
||||
pf_missing: bool,
|
||||
pf_load_fails: bool,
|
||||
route_add_fails: bool,
|
||||
@@ -794,7 +970,10 @@ destination: default\n\
|
||||
calls: RefCell::new(Vec::new()),
|
||||
stdins: RefCell::new(Vec::new()),
|
||||
default_route: Some(DEFAULT_ROUTE.to_string()),
|
||||
forwarding: "1\n",
|
||||
forwarding: Cell::new("1\n"),
|
||||
deny_forwarding: false,
|
||||
deny_pf: false,
|
||||
helper: false,
|
||||
pf_missing: false,
|
||||
pf_load_fails: false,
|
||||
route_add_fails: false,
|
||||
@@ -823,8 +1002,21 @@ destination: default\n\
|
||||
stderr: why.to_string(),
|
||||
};
|
||||
match tool {
|
||||
Tool::Id if self.deny_forwarding || self.deny_pf => ok("501\n", ""),
|
||||
Tool::Id => ok("0\n", ""),
|
||||
Tool::Sysctl => ok(self.forwarding, ""),
|
||||
Tool::Sysctl if args == ["-w", "net.inet.ip.forwarding=1"] => {
|
||||
if self.deny_forwarding {
|
||||
return fail("Operation not permitted");
|
||||
}
|
||||
self.forwarding.set("1\n");
|
||||
ok("net.inet.ip.forwarding: 0 -> 1", "")
|
||||
}
|
||||
Tool::Sysctl => ok(self.forwarding.get(), ""),
|
||||
Tool::OfferHelper if self.helper => {
|
||||
self.forwarding.set("1\n");
|
||||
ok("", "")
|
||||
}
|
||||
Tool::OfferHelper => fail("sudo: a password is required"),
|
||||
Tool::Route if args.iter().any(|a| a == "-inet6") => {
|
||||
let half = args[args.iter().position(|a| a == "-net").unwrap() + 1].clone();
|
||||
let mut table = self.v6.borrow_mut();
|
||||
@@ -923,6 +1115,7 @@ destination: default\n\
|
||||
}
|
||||
Tool::Route => ok("", ""),
|
||||
Tool::Pfctl if self.pf_missing => Ran::Missing,
|
||||
Tool::Pfctl if self.deny_pf => fail("pfctl: /dev/pf: Permission denied"),
|
||||
Tool::Pfctl if args == ["-E"] => ok("", self.pf_enable_output),
|
||||
Tool::Pfctl if args.contains(&"-f".to_string()) && self.pf_load_fails => {
|
||||
fail("pfctl: Syntax error")
|
||||
@@ -992,13 +1185,41 @@ destination: default\n\
|
||||
let text = pf_rules("utun5", &egress(), &[range()], None);
|
||||
assert_eq!(
|
||||
text,
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// Translation precedes filtering, as pf requires.
|
||||
assert!(text.find("nat on").unwrap() < text.find("pass in").unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_excludes_replies_to_every_offered_mesh() {
|
||||
let ranges = [range(), "10.99.0.0/16".parse().unwrap()];
|
||||
let client = ClientRules {
|
||||
uid: 0,
|
||||
overlay: &ranges,
|
||||
};
|
||||
for local_exit in [None, Some(&client)] {
|
||||
let text = pf_rules("utun5", &egress(), &ranges, local_exit);
|
||||
let offered = "<tsunagi_offer_utun5>";
|
||||
assert!(text.contains(&format!(
|
||||
"table {offered} const {{ 10.13.37.0/24, 10.99.0.0/16 }}"
|
||||
)));
|
||||
let mut steering = text
|
||||
.lines()
|
||||
.filter(|r| r.contains("route-to") && r.contains("tagged tsng_forward_"));
|
||||
assert!(
|
||||
steering
|
||||
.next()
|
||||
.unwrap()
|
||||
.contains(&format!("from {offered} to ! {offered} "))
|
||||
);
|
||||
assert!(steering.next().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agents_tagged_nat_precedes_any_general_masquerade_for_offered_ranges() {
|
||||
let ranges = [range()];
|
||||
@@ -1015,7 +1236,7 @@ destination: default\n\
|
||||
);
|
||||
assert_eq!(
|
||||
nat.next(),
|
||||
Some("nat on en0 inet from 10.13.37.0/24 to any -> (en0)")
|
||||
Some("nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1097,7 +1318,7 @@ destination: default\n\
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn offering_loads_the_anchor_and_reads_but_never_writes_forwarding() {
|
||||
fn offering_leaves_preexisting_forwarding_on() {
|
||||
let fake = Fake::new();
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
@@ -1113,10 +1334,12 @@ destination: default\n\
|
||||
);
|
||||
assert_eq!(
|
||||
fake.stdins.borrow()[0],
|
||||
"nat on en0 inet from 10.13.37.0/24 to any -> (en0)\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24\n"
|
||||
"nat on en0 inet from 10.13.37.0/24 to any tagged tsng_forward_utun5 -> (en0)\n\
|
||||
pass out quick on utun5 route-to (en0 192.168.1.1) inet from 10.13.37.0/24 to ! 10.13.37.0/24 tagged tsng_forward_utun5 no state\n\
|
||||
pass in quick on utun5 inet from 10.13.37.0/24 to ! 10.13.37.0/24 tag tsng_forward_utun5 no state\n\
|
||||
pass out quick on en0 inet from any to any flags any tagged tsng_forward_utun5 keep state (if-bound)\n"
|
||||
);
|
||||
// sysctl is only ever asked, never told.
|
||||
// Forwarding was already enabled by the owner.
|
||||
assert!(
|
||||
calls
|
||||
.iter()
|
||||
@@ -1130,15 +1353,67 @@ destination: default\n\
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forwarding_off_is_reported_and_unreadable_is_none() {
|
||||
fn a_local_offer_enables_forwarding_after_nat_and_never_disables_other_routers() {
|
||||
let fake = Fake::new();
|
||||
fake.forwarding.set("0\n");
|
||||
let state = HostState::default();
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
apply_plan(&run, &state, &plan(false, true));
|
||||
assert_eq!(fake.count("Sysctl"), 0);
|
||||
let report = apply_plan(&run, &state, &plan(true, false));
|
||||
assert_eq!(report.forwarding, Some(true));
|
||||
assert_eq!(report.offer[0].1, RuleOutcome::Applied);
|
||||
assert!(fake.position("Pfctl -q -a").unwrap() < fake.position("Sysctl -w").unwrap());
|
||||
apply_plan(&run, &state, &plan(true, false));
|
||||
clear_all(&run, &state, "utun5");
|
||||
assert_eq!(fake.count("Sysctl -w"), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_forwarding_or_an_unwritable_switch_never_advertises_a_working_offer() {
|
||||
let mut fake = Fake::new();
|
||||
fake.forwarding = "0\n";
|
||||
fake.forwarding.set("0\n");
|
||||
fake.deny_forwarding = true;
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||
assert_eq!(report.forwarding, Some(false));
|
||||
fake.forwarding = "junk";
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_needs_authorization(why))
|
||||
);
|
||||
assert_eq!(report.client, Some(RuleOutcome::Applied));
|
||||
fake.forwarding.set("junk");
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, false));
|
||||
assert_eq!(report.forwarding, None);
|
||||
assert!(matches!(&report.offer[0].1, RuleOutcome::Failed(_)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_denied_native_pf_uses_only_a_previously_authorized_offer_helper() {
|
||||
let mut fake = Fake::new();
|
||||
fake.deny_pf = true;
|
||||
fake.forwarding.set("0\n");
|
||||
let state = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan(true, false));
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_needs_authorization(why))
|
||||
);
|
||||
assert!(
|
||||
matches!(&report.offer[0].1, RuleOutcome::Failed(why) if macos_exit_authorization_uid(why) == Some(501))
|
||||
);
|
||||
for suffix in ["0", "", "501: denied", "+501", "4294967296"] {
|
||||
assert_eq!(
|
||||
macos_exit_authorization_uid(&format!("{NEEDS_AUTHORIZATION} for UID {suffix}")),
|
||||
None
|
||||
);
|
||||
}
|
||||
assert!(fake.position("Pfctl -E").unwrap() < fake.position("OfferHelper").unwrap());
|
||||
fake.helper = true;
|
||||
let run = |t, a: &[String], s: Option<&str>| fake.run(t, a, s);
|
||||
let report = apply_plan(&run, &state, &plan(true, false));
|
||||
assert_eq!(report.offer[0].1, RuleOutcome::Applied);
|
||||
assert_eq!(report.forwarding, Some(true));
|
||||
clear_all(&run, &state, "utun5");
|
||||
assert!(fake.position("OfferHelper clear utun5").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1304,10 +1579,26 @@ destination: default\n\
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serving_without_an_upstream_moves_nat_when_the_physical_interface_changes() {
|
||||
let mut fake = Fake::new();
|
||||
let state = HostState::default();
|
||||
let plan = plan(true, false);
|
||||
let first = apply_plan(&|t, a, s| fake.run(t, a, s), &state, &plan);
|
||||
assert_eq!(first.offer[0].1, RuleOutcome::Applied);
|
||||
fake.default_route = Some(DEFAULT_ROUTE.replace("en0", "en7"));
|
||||
let moved = refresh_offer(&|t, a, s| fake.run(t, a, s), &state, &plan).unwrap();
|
||||
assert_eq!(moved.offer[0].1, RuleOutcome::Applied);
|
||||
assert!(fake.stdins.borrow().last().unwrap().contains("nat on en7"));
|
||||
assert_eq!(moved.client, None);
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_routes_are_added_when_the_rules_did_not_load() {
|
||||
let mut fake = Fake::new();
|
||||
fake.pf_load_fails = true;
|
||||
fake.forwarding.set("0\n");
|
||||
let token = HostState::default();
|
||||
let report = apply_plan(&|t, a, s| fake.run(t, a, s), &token, &plan(true, true));
|
||||
let Some(RuleOutcome::Failed(why)) = report.client else {
|
||||
@@ -1319,6 +1610,8 @@ destination: default\n\
|
||||
// Nothing sent the host's traffic into a tunnel it could not exempt
|
||||
// the agent from.
|
||||
assert_eq!(fake.count(" add "), 0);
|
||||
assert_eq!(fake.count("Sysctl -w"), 0);
|
||||
assert_eq!(fake.count("OfferHelper"), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
//! 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 an_update_replaces_the_old_helper_and_preserves_existing_subnet_grants() {
|
||||
let host = Host::new();
|
||||
let helper = host.0.path().join("grants/offer-v1");
|
||||
assert!(!super::offer_helper_available(&helper, "clear"));
|
||||
host.grant("501", "10.13.37.0_24");
|
||||
fs::write(&helper, "#!/bin/sh\n# previous release\n").unwrap();
|
||||
assert!(!super::offer_helper_available(&helper, "apply"));
|
||||
assert!(super::offer_helper_available(&helper, "clear"));
|
||||
host.grant("501", "10.99.0.0_16");
|
||||
assert!(super::offer_helper_available(&helper, "apply"));
|
||||
assert!(
|
||||
host.0
|
||||
.path()
|
||||
.join("grants/grant_501_10.13.37.0_24")
|
||||
.is_file()
|
||||
);
|
||||
}
|
||||
|
||||
#[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");
|
||||
}
|
||||
@@ -66,14 +66,14 @@ impl Drop for Capture<'_> {
|
||||
}
|
||||
|
||||
impl Capture<'_> {
|
||||
fn enable(&mut self) {
|
||||
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,
|
||||
&[],
|
||||
Some(&ClientRules {
|
||||
&ranges[..1],
|
||||
use_upstream.then_some(&ClientRules {
|
||||
uid: 0,
|
||||
overlay: &ranges,
|
||||
}),
|
||||
@@ -86,6 +86,10 @@ impl Capture<'_> {
|
||||
Some(&rules),
|
||||
)
|
||||
.unwrap();
|
||||
enable_forwarding(&run_tool).unwrap();
|
||||
}
|
||||
fn enable(&mut self) {
|
||||
self.offer(true);
|
||||
run_ok(
|
||||
&run_tool,
|
||||
Tool::Route,
|
||||
@@ -250,6 +254,45 @@ async fn udp_round_trip(uplink: &dyn TunDevice, socket: &UdpSocket, stage: &str)
|
||||
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() {
|
||||
@@ -272,7 +315,16 @@ async fn exit_preserves_underlay_and_both_meshes() {
|
||||
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;
|
||||
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -159,6 +159,19 @@ async fn step(what: &'static str, script: String) -> RuleOutcome {
|
||||
#[derive(Debug, Default)]
|
||||
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 {
|
||||
@@ -233,6 +246,10 @@ fn resolve_host(host: &str) -> Vec<std::net::Ipv4Addr> {
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
@@ -241,17 +258,20 @@ impl ExitHostRules for WindowsHostRules {
|
||||
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 || {
|
||||
let hosts = cache.lock().unwrap_or_else(|p| p.into_inner()).lookup(
|
||||
&job.bypass_hosts,
|
||||
Instant::now(),
|
||||
&resolve_host,
|
||||
);
|
||||
windows_exit::apply_plan(
|
||||
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| {
|
||||
@@ -271,11 +291,12 @@ impl ExitHostRules for WindowsHostRules {
|
||||
|
||||
fn refresh<'a>(&'a self, plan: &'a ExitHostPlan) -> BoxFuture<'a, Option<RuleOutcome>> {
|
||||
Box::pin(async move {
|
||||
if !plan.client {
|
||||
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());
|
||||
@@ -287,6 +308,16 @@ impl ExitHostRules for WindowsHostRules {
|
||||
}
|
||||
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,
|
||||
@@ -307,7 +338,9 @@ impl ExitHostRules for WindowsHostRules {
|
||||
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)
|
||||
})
|
||||
@@ -355,6 +388,22 @@ mod tests {
|
||||
|
||||
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};
|
||||
|
||||
@@ -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,64 +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 the physical default and the more specific routes that already
|
||||
/// outrank the split defaults. Ignore our own host routes when refreshing.
|
||||
/// 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-Object -ExpandProperty DestinationPrefix\n",
|
||||
select_gateway(interface)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -269,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 {
|
||||
@@ -310,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)) {
|
||||
@@ -357,84 +336,51 @@ 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> {
|
||||
@@ -764,7 +710,7 @@ exit 0"#
|
||||
};
|
||||
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:'"));
|
||||
}
|
||||
}
|
||||
@@ -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::{
|
||||
@@ -147,6 +148,8 @@ 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,
|
||||
@@ -224,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
|
||||
@@ -235,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);
|
||||
@@ -247,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)));
|
||||
@@ -273,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);
|
||||
@@ -282,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();
|
||||
@@ -301,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 {
|
||||
@@ -320,16 +393,36 @@ impl Interface {
|
||||
tally.multicast.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let selected = match destination {
|
||||
IpAddr::V4(address) => routes.packet_route(address),
|
||||
IpAddr::V6(_) => None,
|
||||
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);
|
||||
}
|
||||
@@ -342,6 +435,8 @@ impl Interface {
|
||||
};
|
||||
|
||||
Ok(Self {
|
||||
#[cfg(any(windows, target_os = "macos"))]
|
||||
forwarding,
|
||||
device,
|
||||
factory,
|
||||
name,
|
||||
@@ -464,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();
|
||||
@@ -474,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");
|
||||
@@ -482,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!(
|
||||
@@ -509,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"
|
||||
@@ -532,6 +641,22 @@ 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
|
||||
@@ -641,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"),
|
||||
}
|
||||
@@ -677,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;
|
||||
@@ -781,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 {
|
||||
@@ -848,14 +988,14 @@ impl Interface {
|
||||
self.tally.wrong_source.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::WrongSource);
|
||||
};
|
||||
let (broadcast, exit) = match (origin, header.destination()) {
|
||||
let (broadcast, exit, forwarded) = match (origin, header.destination()) {
|
||||
(
|
||||
PacketSource::ExitReply {
|
||||
local: Some(local),
|
||||
exit,
|
||||
},
|
||||
IpAddr::V4(destination),
|
||||
) if destination == local => (false, Some(exit)),
|
||||
) if destination == local => (false, Some(exit), false),
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_broadcast(destination) =>
|
||||
{
|
||||
@@ -865,13 +1005,17 @@ impl Interface {
|
||||
self.tally.broadcast_dropped.fetch_add(1, Ordering::Relaxed);
|
||||
return Err(Rejected::BroadcastDenied);
|
||||
}
|
||||
(true, None)
|
||||
(true, None, false)
|
||||
}
|
||||
(PacketSource::Member, IpAddr::V4(destination))
|
||||
if self.routes.is_local_destination(network, destination)
|
||||
|| self.routes.accepts_exit_traffic(network, destination) =>
|
||||
if self.routes.is_local_destination(network, destination) =>
|
||||
{
|
||||
(false, None)
|
||||
(false, None, 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);
|
||||
@@ -880,25 +1024,112 @@ 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);
|
||||
}
|
||||
@@ -909,7 +1140,6 @@ impl Interface {
|
||||
}
|
||||
self.tally.received.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The addresses the interface should be carrying, from the table.
|
||||
|
||||
@@ -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,7 +44,10 @@ 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;
|
||||
|
||||
@@ -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::{
|
||||
@@ -671,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;
|
||||
@@ -704,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
|
||||
@@ -865,11 +875,11 @@ async fn replace_exit_default(
|
||||
/// 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
|
||||
@@ -886,7 +896,24 @@ async fn set_exit_client(
|
||||
};
|
||||
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()
|
||||
@@ -930,6 +957,7 @@ async fn set_exit_client(
|
||||
.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))?;
|
||||
@@ -960,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()
|
||||
@@ -1008,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 {
|
||||
@@ -1023,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}"
|
||||
))
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -477,6 +477,11 @@ async fn run(program: &'static str, args: Vec<String>) -> Result<String, Overlay
|
||||
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}"
|
||||
)))
|
||||
|
||||
@@ -85,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 {
|
||||
@@ -109,10 +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 {
|
||||
@@ -121,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,
|
||||
@@ -185,7 +244,20 @@ 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)));
|
||||
@@ -196,7 +268,10 @@ 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)));
|
||||
@@ -226,7 +301,11 @@ impl RoutingTable {
|
||||
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);
|
||||
}
|
||||
@@ -248,6 +327,10 @@ impl RoutingTable {
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -292,11 +375,12 @@ 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(destination).map(|(route, _)| 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();
|
||||
@@ -324,6 +408,14 @@ impl RoutingTable {
|
||||
return None;
|
||||
}
|
||||
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)))
|
||||
}
|
||||
|
||||
@@ -383,7 +475,10 @@ impl RoutingTable {
|
||||
///
|
||||
/// 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.
|
||||
@@ -584,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();
|
||||
@@ -857,6 +1006,32 @@ 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();
|
||||
|
||||
@@ -509,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 \
|
||||
@@ -516,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."
|
||||
};
|
||||
@@ -549,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")))]
|
||||
{
|
||||
|
||||
@@ -91,9 +91,17 @@ pub struct Announcement {
|
||||
/// Announced IP plugin capabilities. Opaque to the core.
|
||||
pub capabilities: Vec<PluginCapability>,
|
||||
/// Software release reported by this peer for display after authentication.
|
||||
/// Keep this trailer last: original v8 readers stop after the capabilities.
|
||||
/// 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> {
|
||||
@@ -433,6 +441,10 @@ mod tests {
|
||||
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()),
|
||||
@@ -440,6 +452,16 @@ mod tests {
|
||||
.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();
|
||||
|
||||
@@ -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;
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
description = "Built-in mesh transports and status reporting for native tsunagi agents."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,13 +8,21 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.4" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.4" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.4" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.11" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.11" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.11" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.11" }
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes", version = "1.0.0" }
|
||||
tsunagi-vless-xhttp = { path = "../tsunagi-vless-xhttp", version = "1.0.0" }
|
||||
tsunagi-ss2022 = { path = "../tsunagi-ss2022", version = "1.0.0" }
|
||||
tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile.workspace = true
|
||||
data-encoding.workspace = true
|
||||
hex.workspace = true
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -10,7 +10,11 @@ use tsunagi::{
|
||||
iroh_types::EndpointAddr,
|
||||
};
|
||||
use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport};
|
||||
use tsunagi_tcp_tls::{TCP_TLS_PROTOCOL, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport};
|
||||
use tsunagi_shoes::ShoesTransport;
|
||||
use tsunagi_tcp_tls::{
|
||||
TCP_TLS_PROTOCOL, TcpCarrier, TcpTlsCarrier, TcpTlsConfig, TcpTlsTransport,
|
||||
candidates::TcpEndpoint,
|
||||
};
|
||||
use tsunagi_wireguard::WG_PROTOCOL;
|
||||
|
||||
pub mod report;
|
||||
@@ -23,6 +27,10 @@ pub mod report;
|
||||
pub struct ProtocolSpec {
|
||||
/// The name on the wire, which is what peers compare.
|
||||
pub name: &'static str,
|
||||
/// Display family; selection is still saved per protocol.
|
||||
pub group: &'static str,
|
||||
/// Compact user-facing name.
|
||||
pub label: &'static str,
|
||||
/// The wire version. Not the software version: two peers on different
|
||||
/// builds carry traffic for each other as long as this matches.
|
||||
pub version: u16,
|
||||
@@ -32,6 +40,27 @@ pub struct ProtocolSpec {
|
||||
pub options: &'static [tsunagi::dataplane::ProtocolOption],
|
||||
}
|
||||
|
||||
impl ProtocolSpec {
|
||||
/// UI metadata for the current local build.
|
||||
pub fn report(&self) -> tsunagi::ipc::ProtocolReport {
|
||||
tsunagi::ipc::ProtocolReport {
|
||||
name: self.name.into(),
|
||||
label: self.label.into(),
|
||||
group: self.group.into(),
|
||||
summary: self.summary.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const fn tcp_port_option(port: &'static str) -> tsunagi::dataplane::ProtocolOption {
|
||||
tsunagi::dataplane::ProtocolOption {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
help: "local TCP listener port (0 for an available port)",
|
||||
default: Some(port),
|
||||
}
|
||||
}
|
||||
|
||||
const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
@@ -43,34 +72,59 @@ const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::
|
||||
pub const PROTOCOLS: &[ProtocolSpec] = &[
|
||||
ProtocolSpec {
|
||||
name: WG_PROTOCOL,
|
||||
group: "WireGuard",
|
||||
label: "WireGuard",
|
||||
version: tsunagi_wireguard::WG_WIRE_VERSION,
|
||||
summary: "Pure WireGuard direct UDP transport",
|
||||
options: WG_OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: AWG_PROTOCOL,
|
||||
group: "WireGuard",
|
||||
label: "AmneziaWG",
|
||||
version: AWG_WIRE_VERSION,
|
||||
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
|
||||
options: AwgPlugin::OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: "wg-quic",
|
||||
group: "iroh",
|
||||
label: "WG over QUIC",
|
||||
version: 1,
|
||||
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
|
||||
options: &[],
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: TCP_TLS_PROTOCOL,
|
||||
group: "Native",
|
||||
label: "TCP + TLS",
|
||||
version: tsunagi_tcp_tls::TCP_TLS_VERSION,
|
||||
summary: "TCP TLS 1.3 carrier",
|
||||
summary: "Direct TCP with TLS 1.3 pinned to the peer identity. Either peer can initiate the connection.",
|
||||
options: TcpTlsConfig::OPTIONS,
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: tsunagi_vless_xhttp::PROTOCOL,
|
||||
group: "Shoes",
|
||||
label: "VLESS + XHTTP",
|
||||
version: tsunagi_vless_xhttp::WIRE_VERSION,
|
||||
summary: "VLESS over XHTTP stream-one, HTTP/2 and TLS 1.3. Each attempt gets a fresh UUID and request path.",
|
||||
options: &[tcp_port_option("9443")],
|
||||
},
|
||||
ProtocolSpec {
|
||||
name: tsunagi_ss2022::PROTOCOL,
|
||||
group: "Shoes",
|
||||
label: "Shadowsocks 2022",
|
||||
version: tsunagi_ss2022::WIRE_VERSION,
|
||||
summary: "Shadowsocks 2022 over TCP. Each attempt gets a fresh private key, salts, padding and a choice of AES-128-GCM or AES-256-GCM.",
|
||||
options: &[tcp_port_option("9444")],
|
||||
},
|
||||
];
|
||||
|
||||
/// Incoming direct connections to attach after the agent has acquired its identity.
|
||||
pub struct Carriers {
|
||||
udp: [Arc<AwgTransport>; 2],
|
||||
tls: Arc<TcpTlsTransport>,
|
||||
shoes: Vec<Arc<ShoesTransport>>,
|
||||
}
|
||||
|
||||
impl Carriers {
|
||||
@@ -142,20 +196,52 @@ impl Carriers {
|
||||
.await
|
||||
.map_err(|error| -> Box<dyn std::error::Error> { error })?,
|
||||
);
|
||||
for address in bootstrap {
|
||||
for ip in address.ip_addrs() {
|
||||
tls.set_peer_addr(address.id, *ip);
|
||||
}
|
||||
}
|
||||
let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone());
|
||||
if let Some(source) = underlay {
|
||||
carrier.set_underlay(source);
|
||||
carrier.set_bootstrap(bootstrap);
|
||||
if let Some(source) = &underlay {
|
||||
carrier.set_underlay(source.clone());
|
||||
}
|
||||
config = config
|
||||
.with_carrier(Arc::new(IrohCarrier))
|
||||
.with_carrier(carrier)
|
||||
.with_custom_transport(TCP_TLS_PROTOCOL, tls.clone());
|
||||
Ok((config, Self { udp, tls }))
|
||||
let vless = tsunagi_vless_xhttp::VlessXhttp::new(&identity)
|
||||
.map_err(|e| -> Box<dyn std::error::Error> { e })?;
|
||||
let wires: [(Arc<dyn tsunagi_shoes::ShoesWire>, u16); 2] = [
|
||||
(Arc::new(vless), tsunagi_vless_xhttp::PORT),
|
||||
(
|
||||
Arc::new(tsunagi_ss2022::Shadowsocks2022),
|
||||
tsunagi_ss2022::PORT,
|
||||
),
|
||||
];
|
||||
let mut shoes = Vec::new();
|
||||
for (wire, default_port) in wires {
|
||||
let name = wire.name();
|
||||
let mut port = None;
|
||||
for (key, value) in options_for(name) {
|
||||
if key != "port" {
|
||||
return Err(format!("unknown {name} option {key}").into());
|
||||
}
|
||||
port = Some(value.parse::<u16>()?);
|
||||
}
|
||||
let transport = ShoesTransport::bind(wire, port, default_port).await?;
|
||||
let carrier =
|
||||
TcpCarrier::with_interface(transport.clone(), config.interface_name.clone());
|
||||
carrier.set_bootstrap(bootstrap);
|
||||
if let Some(source) = &underlay {
|
||||
carrier.set_underlay(source.clone());
|
||||
}
|
||||
tracing::debug!(
|
||||
protocol = name,
|
||||
port = transport.bound_port(),
|
||||
"TCP listener ready"
|
||||
);
|
||||
config = config
|
||||
.with_carrier(carrier)
|
||||
.with_custom_transport(name, transport.clone());
|
||||
shoes.push(transport);
|
||||
}
|
||||
Ok((config, Self { udp, tls, shoes }))
|
||||
}
|
||||
|
||||
/// Accept incoming authenticated links until the caller drops the returned task set.
|
||||
@@ -172,6 +258,9 @@ impl Carriers {
|
||||
}
|
||||
});
|
||||
}
|
||||
for transport in self.shoes {
|
||||
tasks.spawn(transport.listen(agent.clone()));
|
||||
}
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
self.tls
|
||||
|
||||
@@ -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,
|
||||
@@ -111,6 +113,7 @@ pub fn networks(
|
||||
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(),
|
||||
|
||||
@@ -0,0 +1,126 @@
|
||||
//! Optional interoperability against an independently built upstream Shoes server.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
use std::{
|
||||
fs,
|
||||
process::{Child, Command, Stdio},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::{TcpListener, TcpStream},
|
||||
};
|
||||
use tsunagi::identity::DeviceIdentity;
|
||||
use tsunagi_shoes::{Profile, ShoesWire};
|
||||
use tsunagi_tcp_tls::cert::generate_self_signed_cert;
|
||||
|
||||
struct Reference(Child);
|
||||
impl Drop for Reference {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.0.kill();
|
||||
let _ = self.0.wait();
|
||||
}
|
||||
}
|
||||
fn pem(label: &str, bytes: &[u8]) -> String {
|
||||
format!(
|
||||
"-----BEGIN {label}-----\n{}\n-----END {label}-----\n",
|
||||
data_encoding::BASE64.encode(bytes)
|
||||
)
|
||||
}
|
||||
#[tokio::test]
|
||||
#[ignore = "set TSUNAGI_SHOES_BIN to the upstream Shoes executable (v0.3.8)"]
|
||||
async fn upstream_server_accepts_stream_one_and_both_ss2022_methods() {
|
||||
let bin = std::env::var_os("TSUNAGI_SHOES_BIN").expect("upstream Shoes path");
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let endpoint = DeviceIdentity::generate();
|
||||
let (cert, key) = generate_self_signed_cert(&endpoint.secret_bytes(), "localhost").unwrap();
|
||||
fs::write(
|
||||
dir.path().join("cert.pem"),
|
||||
pem("CERTIFICATE", cert.as_ref()),
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.path().join("key.pem"),
|
||||
pem("PRIVATE KEY", key.secret_der()),
|
||||
)
|
||||
.unwrap();
|
||||
for (is_vless, use_256) in [(true, false), (false, false), (false, true)] {
|
||||
let profile = Profile {
|
||||
tag: [0x34; 32],
|
||||
secret: [0x53; 32],
|
||||
variant: use_256,
|
||||
};
|
||||
let (wire, protocol): (Box<dyn ShoesWire>, String) = if is_vless {
|
||||
let path = hex::encode(profile.tag);
|
||||
(
|
||||
Box::new(tsunagi_vless_xhttp::VlessXhttp::new(&endpoint).unwrap()),
|
||||
format!(
|
||||
"type: tls\n default_target:\n cert: cert.pem\n key: key.pem\n alpn_protocols: [h2]\n protocol:\n type: xhttp\n path: /{path}/\n mode: stream-one\n protocol:\n type: vless\n user_id: 53535353-5353-4353-9353-535353535353"
|
||||
),
|
||||
)
|
||||
} else {
|
||||
let size = if use_256 { 32 } else { 16 };
|
||||
let key = data_encoding::BASE64.encode(&profile.secret[..size]);
|
||||
(
|
||||
Box::new(tsunagi_ss2022::Shadowsocks2022),
|
||||
format!(
|
||||
"type: shadowsocks\n cipher: 2022-blake3-aes-{}-gcm\n password: '{key}'",
|
||||
size * 8
|
||||
),
|
||||
)
|
||||
};
|
||||
let backend = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let backend_address = backend.local_addr().unwrap();
|
||||
let reservation = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let address = reservation.local_addr().unwrap();
|
||||
fs::write(dir.path().join("reference.yaml"), format!("- address: {address}\n protocol:\n {protocol}\n rules:\n - mask: 127.0.0.1:1\n action: allow\n override_address: {backend_address}\n client_chain: direct\n")).unwrap();
|
||||
drop(reservation);
|
||||
let mut server = Reference(
|
||||
Command::new(&bin)
|
||||
.current_dir(dir.path())
|
||||
.args(["-t", "1", "--no-reload", "reference.yaml"])
|
||||
.stdout(Stdio::null())
|
||||
.spawn()
|
||||
.unwrap(),
|
||||
);
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
let tcp = loop {
|
||||
assert!(
|
||||
server.0.try_wait().unwrap().is_none(),
|
||||
"reference server exited at startup"
|
||||
);
|
||||
if let Ok(tcp) = TcpStream::connect(address).await {
|
||||
break tcp;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||
};
|
||||
let payload = vec![0x8c; 96 * 1024];
|
||||
let exchange = async {
|
||||
let mut stream = wire
|
||||
.connect(tcp, endpoint.endpoint_id(), &profile)
|
||||
.await
|
||||
.unwrap();
|
||||
if !is_vless {
|
||||
let mut first = [0; 4];
|
||||
stream.read_exact(&mut first).await.unwrap();
|
||||
assert_eq!(&first, b"mesh");
|
||||
}
|
||||
stream.write_all(&payload).await.unwrap();
|
||||
let mut returned = vec![0; payload.len()];
|
||||
stream.read_exact(&mut returned).await.unwrap();
|
||||
assert_eq!(payload, returned);
|
||||
};
|
||||
let service = async {
|
||||
let (mut socket, _) = backend.accept().await.unwrap();
|
||||
if !is_vless {
|
||||
socket.write_all(b"\0mesh").await.unwrap();
|
||||
}
|
||||
let mut bytes = vec![0; payload.len()];
|
||||
socket.read_exact(&mut bytes).await.unwrap();
|
||||
socket.write_all(&bytes).await.unwrap();
|
||||
};
|
||||
tokio::join!(service, exchange);
|
||||
})
|
||||
.await
|
||||
.expect("reference wire exchange timed out");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[package]
|
||||
name = "tsunagi-shoes"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "WTFPL"
|
||||
repository.workspace = true
|
||||
description = "Private per-attempt negotiation for Shoes mesh carriers."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
rand = "0.10"
|
||||
zeroize = { version = "1.9", features = ["derive"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,281 @@
|
||||
//! Embedded peer-only TCP profiles. Control is supplied by the running mesh agent.
|
||||
mod profile;
|
||||
mod stream;
|
||||
use iroh::EndpointId;
|
||||
use profile::{Pair, rejected};
|
||||
pub use profile::{Profile, Profiles, Ticket};
|
||||
use std::{
|
||||
io,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, OnceLock},
|
||||
time::Duration,
|
||||
};
|
||||
pub use stream::driven;
|
||||
use tokio::{
|
||||
io::{AsyncRead, AsyncWrite},
|
||||
net::{TcpListener, TcpStream},
|
||||
sync::{Semaphore, oneshot},
|
||||
task::JoinSet,
|
||||
time::timeout,
|
||||
};
|
||||
use tsunagi::{
|
||||
BoxFuture, NetworkId,
|
||||
dataplane::transport::{
|
||||
ControlSender, InboundLink, PacketTransport, SharedLink, TransportError, TransportPayload,
|
||||
},
|
||||
};
|
||||
use tsunagi_tcp_tls::{
|
||||
candidates::{TcpEndpoint, dial_candidates},
|
||||
transport::TcpTlsLink,
|
||||
};
|
||||
|
||||
/// A negotiated byte stream carrying length-prefixed mesh datagrams.
|
||||
pub trait ByteStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
impl<T: AsyncRead + AsyncWrite + Unpin + Send> ByteStream for T {}
|
||||
/// Owned stream returned by either side.
|
||||
pub type Stream = Box<dyn ByteStream>;
|
||||
/// A wire profile knows its own handshake and bytes, independent of reachability.
|
||||
pub trait ShoesWire: Send + Sync + 'static {
|
||||
/// Stable protocol identifier.
|
||||
fn name(&self) -> &'static str;
|
||||
/// Version compared between peers.
|
||||
fn version(&self) -> u16;
|
||||
/// Perform the client handshake.
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
peer: EndpointId,
|
||||
profile: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>>;
|
||||
/// Authenticate and consume an authorized incoming attempt.
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>>;
|
||||
}
|
||||
|
||||
/// A listening TCP carrier with private one-time, per-pair credentials.
|
||||
pub struct ShoesTransport {
|
||||
wire: Arc<dyn ShoesWire>,
|
||||
listener: TcpListener,
|
||||
port: u16,
|
||||
profiles: Profiles,
|
||||
control: OnceLock<Arc<dyn ControlSender>>,
|
||||
replies: Arc<Semaphore>,
|
||||
}
|
||||
impl std::fmt::Debug for ShoesTransport {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("ShoesTransport")
|
||||
.field("name", &self.name())
|
||||
.field("port", &self.port)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
impl ShoesTransport {
|
||||
/// An explicitly requested port must bind; an occupied default can use a dynamic port.
|
||||
pub async fn bind(
|
||||
wire: Arc<dyn ShoesWire>,
|
||||
port: Option<u16>,
|
||||
default_port: u16,
|
||||
) -> io::Result<Arc<Self>> {
|
||||
let listener = match tsunagi_tcp_tls::candidates::listen(port.unwrap_or(default_port)) {
|
||||
Ok(l) => l,
|
||||
Err(e) if port.is_none() && e.kind() == io::ErrorKind::AddrInUse => {
|
||||
tsunagi_tcp_tls::candidates::listen(0)?
|
||||
}
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let port = listener.local_addr()?.port();
|
||||
Ok(Arc::new(Self {
|
||||
wire,
|
||||
listener,
|
||||
port,
|
||||
profiles: Default::default(),
|
||||
control: OnceLock::new(),
|
||||
replies: Arc::new(Semaphore::new(64)),
|
||||
}))
|
||||
}
|
||||
|
||||
/// Drives incoming sockets and their installation, bounded by one task set.
|
||||
pub async fn listen(self: Arc<Self>, agent: tsunagi::Agent) {
|
||||
let mut tasks = JoinSet::new();
|
||||
let mut expire = tokio::time::interval(profile::LIFETIME);
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = expire.tick() => self.profiles.expire(),
|
||||
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
||||
accepted = self.listener.accept(), if tasks.len() < 64 => {
|
||||
let Ok((tcp, address)) = accepted else { break; };
|
||||
let owner = self.clone();
|
||||
let agent = agent.clone();
|
||||
tasks.spawn(async move {
|
||||
let _ = tcp.set_nodelay(true);
|
||||
if let Ok(Ok((ticket, stream))) = timeout(Duration::from_secs(8), owner.wire.accept(tcp, &owner.profiles)).await {
|
||||
let (network, peer) = ticket.pair;
|
||||
let protocol = owner.wire.name();
|
||||
let link = Arc::new(TcpTlsLink::framed(protocol, network, peer, stream, address.to_string()));
|
||||
let _ = agent.install_inbound_link(InboundLink { network, peer, protocol: protocol.into(), link }).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn authorize(&self, pair: Pair) -> Result<Profile, TransportError> {
|
||||
let control = self.control.get().ok_or(TransportError::Closed)?;
|
||||
let profile = Profile::fresh();
|
||||
let (tx, rx) = oneshot::channel();
|
||||
self.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get_mut(&pair)
|
||||
.ok_or(TransportError::Closed)?
|
||||
.waiting = Some((profile.tag, tx));
|
||||
// Fixed lengths distinguish an offer (tag + secret + variant) from its receipt (tag).
|
||||
let mut bytes = Vec::with_capacity(65);
|
||||
bytes.extend_from_slice(&profile.tag);
|
||||
bytes.extend_from_slice(&profile.secret);
|
||||
bytes.push(u8::from(profile.variant));
|
||||
control
|
||||
.send(pair.0, pair.1, self.name(), TransportPayload::new(bytes))
|
||||
.await?;
|
||||
rx.await.map_err(|_| TransportError::Closed)?;
|
||||
Ok(profile)
|
||||
}
|
||||
}
|
||||
impl TcpEndpoint for ShoesTransport {
|
||||
fn wire_version(&self) -> u16 {
|
||||
self.wire.version()
|
||||
}
|
||||
fn bound_port(&self) -> u16 {
|
||||
self.port
|
||||
}
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
) {
|
||||
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
match addresses {
|
||||
Some(addresses) => slots.entry((network, peer)).or_default().addresses = addresses,
|
||||
None => {
|
||||
slots.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn clear_network(&self, network: NetworkId) {
|
||||
self.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.retain(|(n, _), _| *n != network);
|
||||
}
|
||||
}
|
||||
impl PacketTransport for ShoesTransport {
|
||||
fn name(&self) -> &str {
|
||||
self.wire.name()
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
}
|
||||
fn attach_control(&self, control: Arc<dyn ControlSender>) {
|
||||
let _ = self.control.set(control);
|
||||
}
|
||||
fn on_control(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
bytes: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
let bad = || TransportError::Declined("invalid Shoes negotiation".into());
|
||||
if protocol != self.name() {
|
||||
return Err(bad());
|
||||
}
|
||||
let pair = (network, peer);
|
||||
let tag: [u8; 32] = bytes
|
||||
.get(..32)
|
||||
.ok_or_else(bad)?
|
||||
.try_into()
|
||||
.map_err(|_| bad())?;
|
||||
match bytes.len() {
|
||||
32 => {
|
||||
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let slot = slots.get_mut(&pair).ok_or_else(bad)?;
|
||||
let (_, ack) = slot.waiting.take_if(|(id, _)| *id == tag).ok_or_else(bad)?;
|
||||
let _ = ack.send(());
|
||||
}
|
||||
65 if bytes[64] <= 1 => {
|
||||
let secret = bytes[32..64].try_into().map_err(|_| bad())?;
|
||||
let permit = self
|
||||
.replies
|
||||
.clone()
|
||||
.try_acquire_owned()
|
||||
.map_err(|_| bad())?;
|
||||
let sender = self.control.get().ok_or_else(bad)?.clone();
|
||||
let name = self.wire.name();
|
||||
self.profiles
|
||||
.offer(
|
||||
pair,
|
||||
Profile {
|
||||
tag,
|
||||
secret,
|
||||
variant: bytes[64] == 1,
|
||||
},
|
||||
)
|
||||
.map_err(|_| bad())?;
|
||||
tokio::spawn(async move {
|
||||
let _permit = permit;
|
||||
let _ = timeout(
|
||||
Duration::from_secs(4),
|
||||
sender.send(network, peer, name, TransportPayload::new(tag.to_vec())),
|
||||
)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
_ => return Err(bad()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn open<'a>(
|
||||
&'a self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &'a str,
|
||||
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
||||
Box::pin(async move {
|
||||
if protocol != self.name() {
|
||||
return Err(TransportError::Declined(protocol.into()));
|
||||
}
|
||||
let pair = (network, peer);
|
||||
let addresses = self
|
||||
.profiles
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&pair)
|
||||
.map(|s| s.addresses.clone())
|
||||
.ok_or_else(|| TransportError::Unreachable(rejected().to_string()))?;
|
||||
dial_candidates(addresses, |tcp, addr| async move {
|
||||
let profile = self.authorize(pair).await?;
|
||||
let stream = self
|
||||
.wire
|
||||
.connect(tcp, peer, &profile)
|
||||
.await
|
||||
.map_err(|_| TransportError::Declined("Shoes handshake failed".into()))?;
|
||||
Ok(Arc::new(TcpTlsLink::framed(
|
||||
self.wire.name(),
|
||||
network,
|
||||
peer,
|
||||
stream,
|
||||
addr.to_string(),
|
||||
)) as SharedLink)
|
||||
})
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
//! Single-use credentials scoped to an authenticated pair.
|
||||
use iroh::EndpointId;
|
||||
use std::{
|
||||
collections::HashMap,
|
||||
io,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
use tokio::sync::oneshot;
|
||||
use tsunagi::NetworkId;
|
||||
use zeroize::ZeroizeOnDrop;
|
||||
|
||||
pub(crate) type Pair = (NetworkId, EndpointId);
|
||||
pub(crate) const LIFETIME: Duration = Duration::from_secs(12);
|
||||
|
||||
/// An independently random public lookup value and private credential.
|
||||
#[derive(ZeroizeOnDrop)]
|
||||
pub struct Profile {
|
||||
/// Random request salt or XHTTP path component.
|
||||
pub tag: [u8; 32],
|
||||
/// Secret material, sent only on the already authenticated control session.
|
||||
pub secret: [u8; 32],
|
||||
/// Independent random selector for a wire profile with two supported methods.
|
||||
pub variant: bool,
|
||||
}
|
||||
impl Profile {
|
||||
pub(crate) fn fresh() -> Self {
|
||||
Self {
|
||||
tag: rand::random(),
|
||||
secret: rand::random(),
|
||||
variant: rand::random(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pair is supplied by authenticated control, never by the TCP client.
|
||||
#[derive(Clone)]
|
||||
pub struct Ticket {
|
||||
pub(crate) pair: Pair,
|
||||
/// Parameters of this connection attempt.
|
||||
pub profile: Arc<Profile>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Slot {
|
||||
pub(crate) addresses: Vec<SocketAddr>,
|
||||
incoming: Option<(Arc<Profile>, Instant)>,
|
||||
// A repeated private offer cannot reauthorize a previously accepted salt.
|
||||
recent: std::collections::VecDeque<([u8; 16], Instant)>,
|
||||
pub(crate) waiting: Option<([u8; 32], oneshot::Sender<()>)>,
|
||||
}
|
||||
|
||||
/// Bounded by enabled, authenticated memberships. At most one offer per pair.
|
||||
#[derive(Default)]
|
||||
pub struct Profiles(pub(crate) Mutex<HashMap<Pair, Slot>>);
|
||||
|
||||
impl Profiles {
|
||||
pub(crate) fn offer(&self, pair: Pair, profile: Profile) -> io::Result<()> {
|
||||
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
if slots.iter().any(|(other, slot)| {
|
||||
*other != pair
|
||||
&& slot.incoming.as_ref().is_some_and(|(p, until)| {
|
||||
*until > Instant::now() && p.tag[..16] == profile.tag[..16]
|
||||
})
|
||||
}) {
|
||||
return Err(rejected());
|
||||
}
|
||||
let slot = slots.get_mut(&pair).ok_or_else(rejected)?;
|
||||
let now = Instant::now();
|
||||
let prefix = profile.tag[..16].try_into().map_err(|_| rejected())?;
|
||||
slot.recent.retain(|(_, until)| *until > now);
|
||||
if slot.recent.len() >= 64 || slot.recent.iter().any(|(tag, _)| tag == &prefix) {
|
||||
return Err(rejected());
|
||||
}
|
||||
slot.recent
|
||||
.push_back((prefix, now + Duration::from_secs(60)));
|
||||
slot.incoming = Some((Arc::new(profile), now + LIFETIME));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Resolve a bounded, public identifier before verifying the private credential.
|
||||
pub fn lookup(&self, tag: &[u8]) -> io::Result<Ticket> {
|
||||
if !matches!(tag.len(), 16 | 32) {
|
||||
return Err(rejected());
|
||||
}
|
||||
let slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
slots
|
||||
.iter()
|
||||
.find_map(|(pair, slot)| {
|
||||
let (p, expiry) = slot.incoming.as_ref()?;
|
||||
(p.tag.starts_with(tag) && *expiry > Instant::now()).then(|| Ticket {
|
||||
pair: *pair,
|
||||
profile: p.clone(),
|
||||
})
|
||||
})
|
||||
.ok_or_else(rejected)
|
||||
}
|
||||
/// Consume only after successful wire authentication and before acknowledging the client.
|
||||
pub fn claim(&self, ticket: &Ticket) -> io::Result<()> {
|
||||
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||
let slot = slots.get_mut(&ticket.pair).ok_or_else(rejected)?;
|
||||
slot.incoming
|
||||
.take_if(|(p, until)| Arc::ptr_eq(p, &ticket.profile) && *until > Instant::now())
|
||||
.map(|_| ())
|
||||
.ok_or_else(rejected)
|
||||
}
|
||||
pub(crate) fn expire(&self) {
|
||||
for slot in self
|
||||
.0
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.values_mut()
|
||||
{
|
||||
slot.incoming.take_if(|(_, until)| *until <= Instant::now());
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(crate) fn rejected() -> io::Error {
|
||||
io::Error::new(
|
||||
io::ErrorKind::PermissionDenied,
|
||||
"unknown or expired connection attempt",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn attempts_rotate_and_a_delayed_claim_cannot_consume_a_replacement() {
|
||||
let registry = Profiles::default();
|
||||
let pair = (
|
||||
NetworkId::from_bytes([12; 32]),
|
||||
tsunagi::identity::DeviceIdentity::generate().endpoint_id(),
|
||||
);
|
||||
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||
let a = Profile::fresh();
|
||||
let tag = a.tag;
|
||||
registry.offer(pair, a).unwrap();
|
||||
let old = registry.lookup(&tag).unwrap();
|
||||
let b = Profile::fresh();
|
||||
assert_ne!(old.profile.tag, b.tag);
|
||||
assert_ne!(old.profile.secret, b.secret);
|
||||
let tag = b.tag;
|
||||
registry.offer(pair, b).unwrap();
|
||||
assert!(registry.claim(&old).is_err());
|
||||
let current = registry.lookup(&tag).unwrap();
|
||||
registry.claim(¤t).unwrap();
|
||||
assert!(registry.claim(¤t).is_err());
|
||||
assert!(registry.lookup(&tag).is_err());
|
||||
let duplicate = Profile {
|
||||
tag,
|
||||
secret: current.profile.secret,
|
||||
variant: current.profile.variant,
|
||||
};
|
||||
assert!(registry.offer(pair, duplicate).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wrong_network_expiry_and_retirement_reject_existing_tickets() {
|
||||
let registry = Profiles::default();
|
||||
let peer = tsunagi::identity::DeviceIdentity::generate().endpoint_id();
|
||||
let pair = (NetworkId::from_bytes([7; 32]), peer);
|
||||
let other = (NetworkId::from_bytes([8; 32]), peer);
|
||||
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||
assert!(registry.offer(other, Profile::fresh()).is_err());
|
||||
let offered = Profile::fresh();
|
||||
let tag = offered.tag;
|
||||
registry.offer(pair, offered).unwrap();
|
||||
let ticket = registry.lookup(&tag).unwrap();
|
||||
registry
|
||||
.0
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&pair)
|
||||
.unwrap()
|
||||
.incoming
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.1 = Instant::now();
|
||||
assert!(registry.lookup(&tag).is_err());
|
||||
assert!(registry.claim(&ticket).is_err());
|
||||
registry.expire();
|
||||
registry.0.lock().unwrap().remove(&pair);
|
||||
assert!(registry.claim(&ticket).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Tie an HTTP/2 connection or record driver to its negotiated stream.
|
||||
use crate::{ByteStream, Stream};
|
||||
use std::{
|
||||
future::Future,
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
struct Driven<S> {
|
||||
inner: S,
|
||||
driver: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
impl<S> Drop for Driven<S> {
|
||||
fn drop(&mut self) {
|
||||
self.driver.abort();
|
||||
}
|
||||
}
|
||||
/// Closing a link cancels its driver even when the peer has stopped reading.
|
||||
pub fn driven<S: ByteStream + 'static>(
|
||||
inner: S,
|
||||
driver: impl Future<Output = ()> + Send + 'static,
|
||||
) -> Stream {
|
||||
Box::new(Driven {
|
||||
inner,
|
||||
driver: tokio::spawn(driver),
|
||||
})
|
||||
}
|
||||
impl<S: ByteStream> AsyncRead for Driven<S> {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
impl<S: ByteStream> AsyncWrite for Driven<S> {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||
}
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_flush(cx)
|
||||
}
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
[package]
|
||||
name = "tsunagi-speedtest"
|
||||
version = "0.1.0"
|
||||
description = "Bounded, adaptive goodput measurements over an authenticated mesh tunnel"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
bytes.workspace = true
|
||||
postcard.workspace = true
|
||||
serde.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { workspace = true, features = ["test-util"] }
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,477 @@
|
||||
use crate::measurement::{Pacer, Receiver, Search};
|
||||
use crate::packet::{MAX_MTU, MIN_MTU, PacketBuilder};
|
||||
use crate::{
|
||||
Control, Datagram, Direction, Feedback, NORMAL_BYTES, Progress, Quality, Reading, Start, State,
|
||||
};
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio::time::{Instant, MissedTickBehavior, interval_at, sleep_until, timeout_at};
|
||||
|
||||
const TOTAL_TIME: Duration = Duration::from_secs(5);
|
||||
const DIRECTION_TIME: Duration = Duration::from_millis(1900);
|
||||
const FEEDBACK_TICK: Duration = Duration::from_millis(25);
|
||||
const PACE_TICK: Duration = Duration::from_millis(1);
|
||||
|
||||
/// Parameters for one locally admitted, authenticated peer.
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Config {
|
||||
/// Fresh random identifier for the exchange. A responder uses the identifier from the request.
|
||||
pub id: u64,
|
||||
/// Local overlay IPv4 address on this network.
|
||||
pub local: Ipv4Addr,
|
||||
/// Authenticated peer's overlay address on this network.
|
||||
pub remote: Ipv4Addr,
|
||||
/// Maximum complete diagnostic datagram size supported by this route.
|
||||
pub mtu: u16,
|
||||
/// Local policy's maximum diagnostic IPv4 bytes in each direction.
|
||||
pub byte_limit: u32,
|
||||
/// Recent peer RTT, used to select the feedback interval and bound the final drain.
|
||||
pub rtt: Duration,
|
||||
}
|
||||
|
||||
/// Delivery for exactly one network and peer. The host uses its usual network
|
||||
/// authentication for control and its ordinary encrypted packet path for probes.
|
||||
pub trait Io: Send + Sync {
|
||||
/// Enqueue or send one reliable authenticated control record.
|
||||
fn control(&self, message: Control) -> impl Future<Output = bool> + Send;
|
||||
/// Attempt to send one packet without blocking the tunnel or buffering unbounded data.
|
||||
fn packet(&self, packet: Bytes) -> bool;
|
||||
/// Publish a live observation or terminal state.
|
||||
fn progress(&self, update: Progress);
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Ingress(Mutex<Option<Receiver>>);
|
||||
|
||||
impl Ingress {
|
||||
fn with<T>(&self, f: impl FnOnce(&mut Option<Receiver>) -> T) -> T {
|
||||
let mut guard = self.0.lock().unwrap_or_else(|poison| poison.into_inner());
|
||||
f(&mut guard)
|
||||
}
|
||||
}
|
||||
|
||||
/// Cloneable, nonblocking ingress for a single test. Data is counted in place;
|
||||
/// it is never put on the reliable message queue.
|
||||
#[derive(Clone)]
|
||||
pub struct Handle {
|
||||
id: u64,
|
||||
local: Ipv4Addr,
|
||||
remote: Ipv4Addr,
|
||||
events: mpsc::Sender<Control>,
|
||||
cancel: watch::Sender<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
}
|
||||
|
||||
impl Handle {
|
||||
/// Deliver an authenticated control record for an existing test.
|
||||
pub fn control(&self, message: Control) {
|
||||
if message.id() == self.id && message.valid() {
|
||||
if matches!(message, Control::Cancel { .. }) {
|
||||
self.cancel();
|
||||
} else {
|
||||
let _ = self.events.try_send(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Count a validated probe from the bound peer in the current receiving direction.
|
||||
pub fn data(&self, packet: Datagram) {
|
||||
if packet.id == self.id && packet.source == self.remote && packet.destination == self.local
|
||||
{
|
||||
self.ingress.with(|rx| {
|
||||
if let Some(rx) = rx {
|
||||
rx.put(packet, Instant::now());
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Interrupt local work, including outstanding control sends.
|
||||
pub fn cancel(&self) {
|
||||
self.cancel.send_replace(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// A single, bounded two-direction exchange. Nothing runs until the host calls `run`.
|
||||
pub struct Session {
|
||||
cfg: Config,
|
||||
request: Option<Start>,
|
||||
events: mpsc::Receiver<Control>,
|
||||
cancel: watch::Receiver<bool>,
|
||||
ingress: Arc<Ingress>,
|
||||
progress: Progress,
|
||||
}
|
||||
|
||||
/// Prepare an outgoing session. The test begins when its runner sends its Start record.
|
||||
pub fn initiate(config: Config) -> (Handle, Session) {
|
||||
new_session(config, None)
|
||||
}
|
||||
|
||||
/// Prepare the response to a verified Start. Local and requested traffic limits are intersected.
|
||||
pub fn respond(mut config: Config, request: Start) -> (Handle, Session) {
|
||||
config.id = request.id;
|
||||
new_session(config, Some(request))
|
||||
}
|
||||
|
||||
fn new_session(config: Config, request: Option<Start>) -> (Handle, Session) {
|
||||
let (tx, events) = mpsc::channel(32);
|
||||
let (cancel_tx, cancel) = watch::channel(false);
|
||||
let ingress = Arc::new(Ingress::default());
|
||||
let handle = Handle {
|
||||
id: config.id,
|
||||
local: config.local,
|
||||
remote: config.remote,
|
||||
events: tx,
|
||||
cancel: cancel_tx,
|
||||
ingress: ingress.clone(),
|
||||
};
|
||||
let session = Session {
|
||||
cfg: config,
|
||||
request,
|
||||
events,
|
||||
cancel,
|
||||
ingress,
|
||||
progress: Progress::default(),
|
||||
};
|
||||
(handle, session)
|
||||
}
|
||||
|
||||
fn open_control(control: Option<Control>) -> Result<Control, State> {
|
||||
match control {
|
||||
Some(Control::Busy { .. }) => Err(State::Busy),
|
||||
Some(Control::Cancel { .. }) => Err(State::Cancelled),
|
||||
Some(control) => Ok(control),
|
||||
None => Err(State::Cancelled),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send(io: &impl Io, message: Control) -> Result<(), State> {
|
||||
if io.control(message).await {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(State::Failed)
|
||||
}
|
||||
}
|
||||
|
||||
impl Session {
|
||||
/// Run both directions under one five-second deadline and return the same final
|
||||
/// snapshot that is published to the host. Dropping the future stops packet generation.
|
||||
pub async fn run(mut self, io: impl Io) -> Progress {
|
||||
let deadline = Instant::now() + TOTAL_TIME;
|
||||
let mut cancellation = self.cancel.clone();
|
||||
io.progress(self.progress);
|
||||
let state = tokio::select! {
|
||||
biased;
|
||||
_ = cancellation.wait_for(|v| *v) => State::Cancelled,
|
||||
result = timeout_at(deadline, self.exchange(&io, deadline)) => {
|
||||
match result { Ok(Ok(())) => State::Complete, Ok(Err(state)) => state, Err(_) => State::TimedOut }
|
||||
}
|
||||
};
|
||||
self.ingress.with(|rx| *rx = None);
|
||||
self.progress.state = state;
|
||||
io.progress(self.progress);
|
||||
if matches!(state, State::Cancelled | State::Failed | State::TimedOut) {
|
||||
// A blocked control stream must never delay local release or shutdown.
|
||||
let _ = timeout_at(
|
||||
deadline.min(Instant::now() + Duration::from_millis(20)),
|
||||
io.control(Control::Cancel { id: self.cfg.id }),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
self.progress
|
||||
}
|
||||
|
||||
async fn exchange(&mut self, io: &impl Io, deadline: Instant) -> Result<(), State> {
|
||||
let id = self.cfg.id;
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(NORMAL_BYTES);
|
||||
self.cfg.mtu = self.cfg.mtu.min(MAX_MTU);
|
||||
if self.cfg.mtu < MIN_MTU || self.cfg.byte_limit == 0 || self.cfg.local == self.cfg.remote {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
if let Some(start) = self.request {
|
||||
if !Control::Start(start).valid() {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = self.cfg.mtu.min(start.mtu);
|
||||
self.cfg.byte_limit = self.cfg.byte_limit.min(start.byte_limit);
|
||||
send(
|
||||
io,
|
||||
Control::Accepted {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
} else {
|
||||
send(
|
||||
io,
|
||||
Control::Start(Start {
|
||||
id,
|
||||
mtu: self.cfg.mtu,
|
||||
byte_limit: self.cfg.byte_limit,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Accepted {
|
||||
mtu, byte_limit, ..
|
||||
} = open_control(self.events.recv().await)?
|
||||
{
|
||||
if mtu > self.cfg.mtu || byte_limit > self.cfg.byte_limit {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
self.cfg.mtu = mtu;
|
||||
self.cfg.byte_limit = byte_limit;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for direction in [Direction::Download, Direction::Upload] {
|
||||
self.progress.state = match direction {
|
||||
Direction::Download => State::Download,
|
||||
Direction::Upload => State::Upload,
|
||||
};
|
||||
io.progress(self.progress);
|
||||
let sender = (direction == Direction::Download) == self.request.is_some();
|
||||
let result = if sender {
|
||||
self.send_probes(io, direction, deadline).await?
|
||||
} else {
|
||||
self.receive_probes(io, direction).await?
|
||||
};
|
||||
*self.progress.at(direction) = result;
|
||||
io.progress(self.progress);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
deadline: Instant,
|
||||
) -> Result<Reading, State> {
|
||||
loop {
|
||||
if matches!(open_control(self.events.recv().await)?, Control::Ready { direction: d, .. } if d == direction)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
let start = Instant::now();
|
||||
// Leave room for the opposite direction and the final reliable report.
|
||||
let remaining = deadline
|
||||
.saturating_duration_since(start)
|
||||
.saturating_sub(Duration::from_millis(200));
|
||||
let phase = if direction == Direction::Download {
|
||||
remaining / 2
|
||||
} else {
|
||||
remaining
|
||||
};
|
||||
let end = start + phase.min(DIRECTION_TIME);
|
||||
let mut tick = interval_at(start + PACE_TICK, PACE_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let mut search = Search::default();
|
||||
let mut pacer = Pacer::new(start, self.cfg.mtu);
|
||||
let builder = PacketBuilder::new(
|
||||
self.cfg.local,
|
||||
self.cfg.remote,
|
||||
self.cfg.id,
|
||||
direction,
|
||||
self.cfg.mtu,
|
||||
);
|
||||
let limit = self.cfg.byte_limit / u32::from(self.cfg.mtu);
|
||||
let mut packets = 0;
|
||||
let mut last_bytes = 0;
|
||||
let mut last_feedback = start;
|
||||
let max_silence = (self
|
||||
.cfg
|
||||
.rtt
|
||||
.saturating_mul(3)
|
||||
.saturating_add(Duration::from_millis(200)))
|
||||
.clamp(Duration::from_millis(700), Duration::from_millis(950));
|
||||
while packets < limit && !search.done() && Instant::now() < end {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::Feedback { direction: d, sample, .. } = open_control(control)?
|
||||
&& d == direction && sample.bytes >= last_bytes && sample.bytes <= self.cfg.byte_limit
|
||||
{
|
||||
if sample.bytes > last_bytes {
|
||||
last_feedback = Instant::now();
|
||||
last_bytes = sample.bytes;
|
||||
}
|
||||
if sample.bps > 0 {
|
||||
*self.progress.at(direction) = Reading { bps: Some(sample.bps), bytes: last_bytes, quality: Quality::Measuring };
|
||||
io.progress(self.progress);
|
||||
}
|
||||
search.observe(sample, start.elapsed().as_micros() as u32);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let now = Instant::now();
|
||||
let silence = if last_bytes == 0 { max_silence.max(Duration::from_millis(1100)) } else { max_silence };
|
||||
if now.duration_since(last_feedback) > silence {
|
||||
break;
|
||||
}
|
||||
let emit = pacer.packets(now, search.target).min(limit - packets);
|
||||
for index in 0..emit {
|
||||
if index > 0 && index.is_multiple_of(64) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
let elapsed_us = start.elapsed().as_micros() as u32;
|
||||
let packet = builder.packet(search.stage, packets, elapsed_us);
|
||||
// A tunnel waiting for a handshake can retain a submitted
|
||||
// packet. Charge that attempt, then release the unissued
|
||||
// part of this batch for a later tick if the tunnel is full.
|
||||
packets += 1;
|
||||
if !io.packet(packet) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
send(
|
||||
io,
|
||||
Control::End {
|
||||
id: self.cfg.id,
|
||||
direction,
|
||||
packets,
|
||||
reading: search.result(last_bytes),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
loop {
|
||||
if let Control::Report {
|
||||
direction: d,
|
||||
reading,
|
||||
..
|
||||
} = open_control(self.events.recv().await)?
|
||||
&& d == direction
|
||||
{
|
||||
if reading.bytes > packets * u32::from(self.cfg.mtu - crate::packet::HEADER) {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
return Ok(reading);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn receive_probes(
|
||||
&mut self,
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
) -> Result<Reading, State> {
|
||||
let id = self.cfg.id;
|
||||
self.ingress
|
||||
.with(|rx| *rx = Some(Receiver::new(direction, self.cfg.mtu, self.cfg.byte_limit)));
|
||||
send(io, Control::Ready { id, direction }).await?;
|
||||
let mut tick = interval_at(Instant::now() + FEEDBACK_TICK, FEEDBACK_TICK);
|
||||
tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
|
||||
let window = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(100), Duration::from_millis(220));
|
||||
let (packets, estimate) = loop {
|
||||
tokio::select! {
|
||||
control = self.events.recv() => {
|
||||
if let Control::End { direction: d, packets, reading, .. } = open_control(control)?
|
||||
&& d == direction
|
||||
{
|
||||
if packets > self.cfg.byte_limit / u32::from(self.cfg.mtu) { return Err(State::Failed); }
|
||||
break (packets, reading);
|
||||
}
|
||||
}
|
||||
_ = tick.tick() => {
|
||||
let sample = self.ingress.with(|rx| rx.as_mut().and_then(|r| r.sample(Instant::now(), window)));
|
||||
if let Some(sample) = sample {
|
||||
self.update_receiver(io, direction, sample);
|
||||
send(io, Control::Feedback { id, direction, sample }).await?;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
let received = self.ingress.with(|rx| rx.as_ref().map_or(0, |r| r.count));
|
||||
if received < packets {
|
||||
// Reliable End and encrypted probes may take different paths.
|
||||
let drain = self
|
||||
.cfg
|
||||
.rtt
|
||||
.clamp(Duration::from_millis(25), Duration::from_millis(120));
|
||||
sleep_until(Instant::now() + drain).await;
|
||||
}
|
||||
let rx = self.ingress.with(Option::take).ok_or(State::Failed)?;
|
||||
if rx.count > packets {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
let reading = rx.finish(estimate);
|
||||
send(
|
||||
io,
|
||||
Control::Report {
|
||||
id,
|
||||
direction,
|
||||
reading,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(reading)
|
||||
}
|
||||
|
||||
fn update_receiver(&mut self, io: &impl Io, direction: Direction, sample: Feedback) {
|
||||
let reading = self.progress.at(direction);
|
||||
reading.bytes = sample.bytes;
|
||||
if sample.bps > 0 {
|
||||
reading.bps = Some(sample.bps);
|
||||
}
|
||||
io.progress(self.progress);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn data_ingress_is_bound_to_the_session_id_and_both_assigned_addresses() {
|
||||
let local = Ipv4Addr::new(10, 1, 2, 3);
|
||||
let remote = Ipv4Addr::new(10, 1, 2, 4);
|
||||
let conf = Config {
|
||||
id: 42,
|
||||
local,
|
||||
remote,
|
||||
mtu: 1280,
|
||||
byte_limit: 32_000,
|
||||
rtt: Duration::ZERO,
|
||||
};
|
||||
let (handle, _) = initiate(conf);
|
||||
handle.ingress.with(|rx| {
|
||||
*rx = Some(Receiver::new(
|
||||
Direction::Download,
|
||||
conf.mtu,
|
||||
conf.byte_limit,
|
||||
))
|
||||
});
|
||||
let make = |src, dst, id, seq| {
|
||||
let raw = PacketBuilder::new(src, dst, id, Direction::Download, 1280).packet(0, seq, 7);
|
||||
crate::decode_packet(&raw).unwrap()
|
||||
};
|
||||
for (ipfrom, ipto, id, seq) in [
|
||||
(remote, local, 41, 0),
|
||||
(local, remote, 42, 1),
|
||||
(Ipv4Addr::LOCALHOST, local, 42, 2),
|
||||
(remote, Ipv4Addr::LOCALHOST, 42, 3),
|
||||
(remote, local, 42, 4),
|
||||
] {
|
||||
handle.data(make(ipfrom, ipto, id, seq));
|
||||
}
|
||||
assert_eq!(
|
||||
handle.ingress.with(|rx| rx.as_ref().map(|r| r.count)),
|
||||
Some(1)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Directional goodput measurements for an authenticated peer on its existing IPv4 tunnel.
|
||||
//!
|
||||
//! The host advertises and negotiates this crate's wire version, admits at most one
|
||||
//! test at a time, and delivers control messages over its reliable authenticated
|
||||
//! channel. Probe packets take the same encrypted IPv4 path as application traffic.
|
||||
|
||||
mod engine;
|
||||
mod measurement;
|
||||
mod packet;
|
||||
mod wire;
|
||||
|
||||
pub use engine::{Config, Handle, Io, Session, initiate, respond};
|
||||
pub use packet::{Datagram, decode_packet, is_test_packet};
|
||||
pub use wire::{Control, Direction, Feedback, Progress, Quality, Reading, Start, State};
|
||||
|
||||
/// Capability negotiated by peers for this protocol.
|
||||
pub const PROTOCOL: &str = "speedtest";
|
||||
/// Wire version of the control records and IPv4 payload, independent of software versions.
|
||||
pub const VERSION: u16 = 1;
|
||||
/// Absolute per-direction diagnostic IPv4 traffic budget.
|
||||
pub const NORMAL_BYTES: u32 = 96 * 1024 * 1024;
|
||||
/// Suggested per-direction budget on metered paths.
|
||||
pub const METERED_BYTES: u32 = 8 * 1024 * 1024;
|
||||
@@ -0,0 +1,483 @@
|
||||
use crate::packet::HEADER;
|
||||
use crate::wire::MAX_BPS;
|
||||
use crate::{Datagram, Direction, Feedback, Quality, Reading};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
const INITIAL_BPS: u64 = 8_000_000;
|
||||
// A tail shorter than a regular feedback period may still contain a sustained
|
||||
// train. Require both clocks to span this interval and multiple arrival groups.
|
||||
const MIN_TRAIN: Duration = Duration::from_millis(60);
|
||||
const MIN_BPS: u64 = 32_000;
|
||||
|
||||
pub(crate) struct Receiver {
|
||||
pub(crate) direction: Direction,
|
||||
mtu: u16,
|
||||
packets: u32,
|
||||
seen: Vec<u64>,
|
||||
stage: u8,
|
||||
window: Option<Window>,
|
||||
pub(crate) count: u32,
|
||||
best: u64,
|
||||
}
|
||||
|
||||
struct Window {
|
||||
received: u32,
|
||||
opening_group: u32,
|
||||
arrival_groups: u8,
|
||||
last_group: Instant,
|
||||
first_arrival: Instant,
|
||||
last_arrival: Instant,
|
||||
first: u32,
|
||||
highest: u32,
|
||||
first_send_us: u32,
|
||||
last_send_us: u32,
|
||||
}
|
||||
|
||||
impl Window {
|
||||
fn new(probe: Datagram, now: Instant) -> Self {
|
||||
Self {
|
||||
received: 1,
|
||||
opening_group: 1,
|
||||
arrival_groups: 1,
|
||||
last_group: now,
|
||||
first_arrival: now,
|
||||
last_arrival: now,
|
||||
first: probe.sequence,
|
||||
highest: probe.sequence,
|
||||
first_send_us: probe.sent_us,
|
||||
last_send_us: probe.sent_us,
|
||||
}
|
||||
}
|
||||
|
||||
fn push(&mut self, probe: Datagram, now: Instant) {
|
||||
if self.arrival_groups < 3
|
||||
&& now.duration_since(self.last_group) >= Duration::from_millis(20)
|
||||
{
|
||||
self.arrival_groups += 1;
|
||||
self.last_group = now;
|
||||
}
|
||||
self.first = self.first.min(probe.sequence);
|
||||
self.highest = self.highest.max(probe.sequence);
|
||||
self.first_send_us = self.first_send_us.min(probe.sent_us);
|
||||
self.last_send_us = self.last_send_us.max(probe.sent_us);
|
||||
// Packets already in the first arrival batch did not traverse the measured interval.
|
||||
if now.duration_since(self.first_arrival) < Duration::from_millis(1) {
|
||||
self.opening_group += 1;
|
||||
}
|
||||
self.received += 1;
|
||||
self.last_arrival = now;
|
||||
}
|
||||
|
||||
fn rate(&self, mtu: u16) -> Option<u64> {
|
||||
let arrivals = self.last_arrival.duration_since(self.first_arrival);
|
||||
let sends = Duration::from_micros(u64::from(self.last_send_us - self.first_send_us));
|
||||
let packets = self.received.saturating_sub(self.opening_group);
|
||||
if packets < 3 || self.arrival_groups < 3 || arrivals < MIN_TRAIN || sends < MIN_TRAIN {
|
||||
return None;
|
||||
}
|
||||
// Feedback and End may arrive late, or queued packets may arrive together.
|
||||
// Use the slower of the sender's and receiver's independent train clocks.
|
||||
let elapsed = arrivals.max(sends).as_micros() as u64;
|
||||
Some((u64::from(packets) * u64::from(mtu - HEADER) * 8_000_000 / elapsed).min(MAX_BPS))
|
||||
}
|
||||
}
|
||||
|
||||
impl Receiver {
|
||||
pub(crate) fn new(direction: Direction, mtu: u16, budget: u32) -> Self {
|
||||
let packets = budget / u32::from(mtu);
|
||||
Self {
|
||||
direction,
|
||||
mtu,
|
||||
packets,
|
||||
seen: vec![0; packets.div_ceil(64) as usize],
|
||||
stage: 0,
|
||||
window: None,
|
||||
count: 0,
|
||||
best: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn put(&mut self, probe: Datagram, now: Instant) {
|
||||
if probe.direction != self.direction
|
||||
|| probe.size != self.mtu
|
||||
|| probe.sequence >= self.packets
|
||||
{
|
||||
return;
|
||||
}
|
||||
let word = &mut self.seen[(probe.sequence / 64) as usize];
|
||||
let bit = 1u64 << (probe.sequence % 64);
|
||||
if *word & bit != 0 {
|
||||
return;
|
||||
}
|
||||
*word |= bit;
|
||||
self.count += 1;
|
||||
if probe.stage < self.stage {
|
||||
return;
|
||||
}
|
||||
if probe.stage > self.stage {
|
||||
self.finish_window();
|
||||
self.stage = probe.stage;
|
||||
}
|
||||
match &mut self.window {
|
||||
Some(window) => window.push(probe, now),
|
||||
None => self.window = Some(Window::new(probe, now)),
|
||||
}
|
||||
}
|
||||
|
||||
fn finish_window(&mut self) {
|
||||
if let Some(rate) = self.window.take().and_then(|w| w.rate(self.mtu)) {
|
||||
self.best = self.best.max(rate);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn finish(mut self, estimate: Reading) -> Reading {
|
||||
self.finish_window();
|
||||
// Final delivery belongs to the receiver. A sender may have stopped on its
|
||||
// byte limit before receiving feedback for a faster, fully observed train.
|
||||
if self.best == 0 {
|
||||
return Reading {
|
||||
bps: None,
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Insufficient,
|
||||
};
|
||||
}
|
||||
if estimate.quality == Quality::Measured
|
||||
&& let Some(rate) = estimate.bps
|
||||
&& self.best.abs_diff(rate) <= rate / 5
|
||||
{
|
||||
return Reading {
|
||||
bps: Some(rate.min(self.best)),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::Measured,
|
||||
};
|
||||
}
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes: self.bytes(),
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn bytes(&self) -> u32 {
|
||||
self.count * u32::from(self.mtu - HEADER)
|
||||
}
|
||||
|
||||
// A rate needs observations spread over a real interval. A queued burst
|
||||
// followed by silence must never turn into a capacity estimate.
|
||||
pub(crate) fn sample(&mut self, now: Instant, minimum: Duration) -> Option<Feedback> {
|
||||
let bytes = self.bytes();
|
||||
let w = self.window.as_ref()?;
|
||||
let elapsed = now.duration_since(w.first_arrival);
|
||||
if elapsed < minimum {
|
||||
return None;
|
||||
}
|
||||
let span = w.highest - w.first + 1;
|
||||
let loss = (u64::from(span.saturating_sub(w.received)) * 1000 / u64::from(span)) as u16;
|
||||
let rate = w.rate(self.mtu);
|
||||
if rate.is_none() && elapsed < Duration::from_millis(600) {
|
||||
return None;
|
||||
}
|
||||
let bps = rate.unwrap_or(0);
|
||||
let feedback = Feedback {
|
||||
stage: self.stage,
|
||||
bps,
|
||||
lost_per_mille: loss,
|
||||
bytes,
|
||||
echo_us: w.last_send_us,
|
||||
};
|
||||
self.window = None;
|
||||
self.best = self.best.max(bps);
|
||||
Some(feedback)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Phase {
|
||||
Ramp,
|
||||
// A rate backed off from congestion needs another, higher offer to test it.
|
||||
Settle { verified: bool },
|
||||
Challenge { previous_rate: u64 },
|
||||
}
|
||||
|
||||
pub(crate) struct Search {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) target: u64,
|
||||
best: u64,
|
||||
baseline_delay: Option<u32>,
|
||||
initial_loss: Option<u16>,
|
||||
last_echo: Option<u32>,
|
||||
phase: Phase,
|
||||
previous: Option<u64>,
|
||||
measured: Option<u64>,
|
||||
}
|
||||
|
||||
impl Default for Search {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
stage: 0,
|
||||
target: INITIAL_BPS,
|
||||
best: 0,
|
||||
baseline_delay: None,
|
||||
initial_loss: None,
|
||||
last_echo: None,
|
||||
phase: Phase::Ramp,
|
||||
previous: None,
|
||||
measured: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Search {
|
||||
pub(crate) fn observe(&mut self, sample: Feedback, elapsed_us: u32) {
|
||||
if sample.stage != self.stage
|
||||
|| self.measured.is_some()
|
||||
|| sample.echo_us > elapsed_us
|
||||
|| self.last_echo.is_some_and(|echo| echo >= sample.echo_us)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.last_echo = Some(sample.echo_us);
|
||||
let bps = sample.bps;
|
||||
self.best = self.best.max(bps);
|
||||
let delay = elapsed_us - sample.echo_us;
|
||||
let base = *self.baseline_delay.get_or_insert(delay);
|
||||
self.baseline_delay = Some(base.min(delay));
|
||||
let queuing = delay > base.saturating_add(45_000).max(base.saturating_mul(2));
|
||||
// Loss present at the first offer also reduces the payload rate that
|
||||
// can arrive at higher offers. Look for additional loss or queuing.
|
||||
// A very lossy first sample may already be an overloaded slow path.
|
||||
let baseline_loss = *self
|
||||
.initial_loss
|
||||
.get_or_insert(sample.lost_per_mille.min(400));
|
||||
let expected = self.target * u64::from(1000 - baseline_loss) / 1000;
|
||||
let congested =
|
||||
sample.lost_per_mille > baseline_loss + 30 || bps < expected * 4 / 5 || queuing;
|
||||
if congested {
|
||||
let verified = match self.phase {
|
||||
Phase::Challenge { previous_rate } => {
|
||||
bps.abs_diff(previous_rate) <= previous_rate / 5
|
||||
}
|
||||
Phase::Settle { verified } => verified && bps >= self.target * 4 / 5,
|
||||
Phase::Ramp => false,
|
||||
};
|
||||
self.phase = Phase::Settle { verified };
|
||||
self.previous = None;
|
||||
self.offer(if bps == 0 {
|
||||
self.target / 2
|
||||
} else {
|
||||
bps * 97 / 100
|
||||
});
|
||||
} else if let Phase::Settle { verified } = self.phase {
|
||||
if sample.lost_per_mille > 100 {
|
||||
self.previous = None;
|
||||
return;
|
||||
}
|
||||
if let Some(prev) = self.previous.replace(bps)
|
||||
&& prev.abs_diff(bps) <= bps / 6
|
||||
{
|
||||
let steady = (prev + bps) / 2;
|
||||
if verified {
|
||||
self.measured = Some(steady);
|
||||
} else if elapsed_us >= 850_000 {
|
||||
// A cold tunnel or one busy scheduler slice can look like a bottleneck.
|
||||
// Two samples at our own reduced rate prove only that we can sustain it.
|
||||
self.phase = Phase::Challenge {
|
||||
previous_rate: steady,
|
||||
};
|
||||
self.offer(steady * 2);
|
||||
self.previous = None;
|
||||
}
|
||||
}
|
||||
} else if self.target < MAX_BPS {
|
||||
self.phase = Phase::Ramp;
|
||||
self.offer(self.target.saturating_mul(4));
|
||||
}
|
||||
}
|
||||
|
||||
fn offer(&mut self, bps: u64) {
|
||||
self.target = bps.clamp(MIN_BPS, MAX_BPS);
|
||||
self.stage = self.stage.saturating_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn done(&self) -> bool {
|
||||
self.measured.is_some()
|
||||
}
|
||||
|
||||
pub(crate) fn result(&self, bytes: u32) -> Reading {
|
||||
if let Some(bps) = self.measured {
|
||||
Reading {
|
||||
bps: Some(bps),
|
||||
bytes,
|
||||
quality: Quality::Measured,
|
||||
}
|
||||
} else if self.best > 0 {
|
||||
Reading {
|
||||
bps: Some(self.best),
|
||||
bytes,
|
||||
quality: Quality::AtLeast,
|
||||
}
|
||||
} else {
|
||||
Reading {
|
||||
bps: None,
|
||||
bytes,
|
||||
quality: Quality::Insufficient,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct Pacer {
|
||||
last_tick: Instant,
|
||||
// Fractional packet credit in payload bit-nanoseconds.
|
||||
credit: u64,
|
||||
cost: u64,
|
||||
}
|
||||
|
||||
impl Pacer {
|
||||
pub(crate) fn new(start: Instant, mtu: u16) -> Self {
|
||||
Self {
|
||||
last_tick: start,
|
||||
credit: 0,
|
||||
cost: u64::from(mtu - HEADER) * 8_000_000_000,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn packets(&mut self, now: Instant, bps: u64) -> u32 {
|
||||
// The event loop may have been descheduled. Never catch up with a long burst.
|
||||
let elapsed = now
|
||||
.duration_since(self.last_tick)
|
||||
.as_nanos()
|
||||
.min(12_000_000) as u64;
|
||||
self.last_tick = now;
|
||||
self.credit += elapsed * bps;
|
||||
let packets = self.credit / self.cost;
|
||||
self.credit %= self.cost;
|
||||
packets.min(512) as u32
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
fn packet(sequence: u32, stage: u8, sent_us: u32) -> Datagram {
|
||||
Datagram {
|
||||
id: 7,
|
||||
source: Ipv4Addr::LOCALHOST,
|
||||
destination: Ipv4Addr::BROADCAST,
|
||||
direction: Direction::Download,
|
||||
stage,
|
||||
sequence,
|
||||
sent_us,
|
||||
size: 1280,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bounded_reordered_packets_are_counted_once_and_do_not_reopen_earlier_stages() {
|
||||
let t = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, 1280 * 8);
|
||||
for (i, s) in [(7, 1), (1, 0), (3, 1), (3, 1), (8, 1), (u32::MAX, 1)] {
|
||||
rx.put(packet(i, s, 0), t);
|
||||
}
|
||||
rx.put(
|
||||
Datagram {
|
||||
direction: Direction::Upload,
|
||||
..packet(4, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
rx.put(
|
||||
Datagram {
|
||||
size: 1500,
|
||||
..packet(5, 1, 0)
|
||||
},
|
||||
t,
|
||||
);
|
||||
assert_eq!(rx.count, 3);
|
||||
assert_eq!(rx.bytes(), 3 * u32::from(1280 - HEADER));
|
||||
assert_eq!(rx.stage, 1);
|
||||
assert!(rx.window.as_ref().is_some_and(|w| w.received == 2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_short_burst_or_compressed_catchup_cannot_establish_throughput() {
|
||||
let start = Instant::now();
|
||||
let mut receiver = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
for i in 0..500 {
|
||||
receiver.put(packet(i, 0, i), start);
|
||||
}
|
||||
let window = Duration::from_millis(120);
|
||||
for i in 500..520 {
|
||||
receiver.put(packet(i, 0, i), start + window);
|
||||
}
|
||||
assert!(receiver.sample(start + window, window).is_none());
|
||||
let feedback = receiver
|
||||
.sample(start + Duration::from_millis(650), window)
|
||||
.unwrap();
|
||||
assert_eq!(feedback.bps, 0);
|
||||
assert_eq!(receiver.best, 0);
|
||||
}
|
||||
|
||||
const NORMAL_BYTES_FOR_TEST: u32 = 1024 * 1024;
|
||||
|
||||
#[test]
|
||||
fn final_rate_uses_delivered_payload_even_when_end_overtakes_feedback() {
|
||||
let start = Instant::now();
|
||||
let mut rx = Receiver::new(Direction::Download, 1280, NORMAL_BYTES_FOR_TEST);
|
||||
// The first train takes twice as long to arrive as to send. The faster
|
||||
// second train ends before the next feedback tick.
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(i, 0, i * 1_000),
|
||||
start + Duration::from_millis(u64::from(i) * 2),
|
||||
);
|
||||
}
|
||||
let tick = Duration::from_millis(220);
|
||||
let initial = rx.sample(start + tick, tick).unwrap();
|
||||
let payload_bits = u64::from(1280 - HEADER) * 8;
|
||||
assert_eq!(initial.bps, payload_bits * 500);
|
||||
for i in 0..=100 {
|
||||
rx.put(
|
||||
packet(101 + i, 1, 250_000 + i * 1_000),
|
||||
start + Duration::from_millis(250 + u64::from(i)),
|
||||
);
|
||||
}
|
||||
let result = rx.finish(Reading {
|
||||
bytes: initial.bytes,
|
||||
bps: Some(initial.bps),
|
||||
quality: Quality::AtLeast,
|
||||
});
|
||||
assert_eq!(result.bps, Some(payload_bits * 1000));
|
||||
assert_eq!(result.quality, Quality::AtLeast);
|
||||
assert_eq!(result.bytes, 202 * u32::from(1280 - HEADER));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retransmitted_feedback_does_not_supply_two_confirmation_windows() {
|
||||
let mut search = Search::default();
|
||||
let f = |stage, bps, lost_per_mille, bytes, echo_us| Feedback {
|
||||
stage,
|
||||
bps,
|
||||
lost_per_mille,
|
||||
bytes,
|
||||
echo_us,
|
||||
};
|
||||
search.observe(f(0, 1_000_000, 700, 15000, 120_000), 121_000);
|
||||
let observed = f(1, 970_000, 0, 30000, 241_000);
|
||||
search.observe(observed, 242_000);
|
||||
search.observe(observed, 243_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 45000, 360_000), 361_000);
|
||||
assert!(!search.done());
|
||||
search.observe(f(1, 970_000, 0, 100_000, 900_000), 901_000);
|
||||
assert_eq!(search.stage, 2);
|
||||
search.observe(f(2, 1_000_000, 450, 120_000, 1_060_000), 1_061_000);
|
||||
search.observe(f(3, 970_000, 0, 150_000, 1_220_000), 1_221_000);
|
||||
search.observe(f(3, 970_000, 0, 180_000, 1_380_000), 1_381_000);
|
||||
assert!(search.done());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
use crate::Direction;
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
pub(crate) const MIN_MTU: u16 = 576;
|
||||
pub(crate) const MAX_MTU: u16 = 1500;
|
||||
pub(crate) const HEADER: u16 = 46;
|
||||
const MAGIC: &[u8; 8] = b"TSNGSP01";
|
||||
const IP_PROTOCOL: u8 = 253; // RFC 3692 local experiment, disambiguated by MAGIC.
|
||||
|
||||
/// Fields from a validated version-one diagnostic IPv4 packet. Probes carry no arbitrary stream data.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Datagram {
|
||||
/// Measurement identifier from the authenticated control exchange.
|
||||
pub id: u64,
|
||||
/// Source address of the inner IPv4 datagram.
|
||||
pub source: Ipv4Addr,
|
||||
/// Destination address of the inner IPv4 datagram.
|
||||
pub destination: Ipv4Addr,
|
||||
pub(crate) direction: Direction,
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) sequence: u32,
|
||||
pub(crate) sent_us: u32,
|
||||
pub(crate) size: u16,
|
||||
}
|
||||
|
||||
impl Datagram {
|
||||
/// Number of delivered diagnostic payload bytes, excluding both headers.
|
||||
pub fn payload_len(self) -> u16 {
|
||||
self.size - HEADER
|
||||
}
|
||||
}
|
||||
|
||||
/// Identify this crate's reserved IPv4 payload, including malformed records that should be dropped.
|
||||
pub fn is_test_packet(bytes: &[u8]) -> bool {
|
||||
if bytes.len() < 20 || bytes[0] >> 4 != 4 || bytes[9] != IP_PROTOCOL {
|
||||
return false;
|
||||
}
|
||||
let offset = usize::from(bytes[0] & 0x0f) * 4;
|
||||
offset >= 20 && bytes.get(offset..offset + MAGIC.len()) == Some(MAGIC)
|
||||
}
|
||||
|
||||
/// Validate an entire diagnostic datagram before handing its fixed-size metadata to the receiver.
|
||||
pub fn decode_packet(bytes: &[u8]) -> Option<Datagram> {
|
||||
let size = u16::try_from(bytes.len()).ok()?;
|
||||
if !(MIN_MTU..=MAX_MTU).contains(&size)
|
||||
|| bytes[0] != 0x45
|
||||
|| bytes[9] != IP_PROTOCOL
|
||||
|| bytes[20..28] != *MAGIC
|
||||
|| u16::from_be_bytes([bytes[2], bytes[3]]) != size
|
||||
|| u16::from_be_bytes([bytes[6], bytes[7]]) & !0x4000 != 0
|
||||
|| checksum(&bytes[..20]) != 0
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let direction = match bytes[36] {
|
||||
0 => Direction::Download,
|
||||
1 => Direction::Upload,
|
||||
_ => return None,
|
||||
};
|
||||
let sent_us = u32::from_be_bytes(bytes[42..46].try_into().ok()?);
|
||||
if sent_us > 5_000_000 {
|
||||
return None;
|
||||
}
|
||||
Some(Datagram {
|
||||
source: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[12..16]).ok()?),
|
||||
destination: Ipv4Addr::from(<[u8; 4]>::try_from(&bytes[16..20]).ok()?),
|
||||
id: u64::from_be_bytes(bytes[28..36].try_into().ok()?),
|
||||
direction,
|
||||
stage: bytes[37],
|
||||
sequence: u32::from_be_bytes(bytes[38..42].try_into().ok()?),
|
||||
sent_us,
|
||||
size,
|
||||
})
|
||||
}
|
||||
|
||||
// Build the immutable header and deterministic padding once per direction. The
|
||||
// underlying data tunnel encrypts the packet before it goes on the wire.
|
||||
pub(crate) struct PacketBuilder(Bytes);
|
||||
|
||||
impl PacketBuilder {
|
||||
pub(crate) fn new(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
id: u64,
|
||||
direction: Direction,
|
||||
mtu: u16,
|
||||
) -> Self {
|
||||
let mut bytes = BytesMut::zeroed(usize::from(mtu));
|
||||
bytes[0] = 0x45;
|
||||
bytes[2..4].copy_from_slice(&mtu.to_be_bytes());
|
||||
bytes[6] = 0x40;
|
||||
bytes[8] = 64;
|
||||
bytes[9] = IP_PROTOCOL;
|
||||
bytes[12..16].copy_from_slice(&source.octets());
|
||||
bytes[16..20].copy_from_slice(&destination.octets());
|
||||
let check = checksum(&bytes[..20]);
|
||||
bytes[10..12].copy_from_slice(&check.to_be_bytes());
|
||||
bytes[20..28].copy_from_slice(MAGIC);
|
||||
bytes[28..36].copy_from_slice(&id.to_be_bytes());
|
||||
bytes[36] = match direction {
|
||||
Direction::Download => 0,
|
||||
Direction::Upload => 1,
|
||||
};
|
||||
Self(bytes.freeze())
|
||||
}
|
||||
|
||||
pub(crate) fn packet(&self, stage: u8, sequence: u32, sent_us: u32) -> Bytes {
|
||||
let mut bytes = BytesMut::from(self.0.as_ref());
|
||||
bytes[37] = stage;
|
||||
bytes[38..42].copy_from_slice(&sequence.to_be_bytes());
|
||||
bytes[42..46].copy_from_slice(&sent_us.to_be_bytes());
|
||||
bytes.freeze()
|
||||
}
|
||||
}
|
||||
|
||||
fn checksum(bytes: &[u8]) -> u16 {
|
||||
let mut sum: u32 = bytes
|
||||
.as_chunks::<2>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|&word| u32::from(u16::from_be_bytes(word)))
|
||||
.sum();
|
||||
while sum > u32::from(u16::MAX) {
|
||||
sum = (sum & 0xffff) + (sum >> 16);
|
||||
}
|
||||
!(sum as u16)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
fn probe() -> Bytes {
|
||||
PacketBuilder::new(
|
||||
Ipv4Addr::new(10, 1, 10, 1),
|
||||
Ipv4Addr::new(10, 1, 10, 2),
|
||||
42,
|
||||
Direction::Upload,
|
||||
1280,
|
||||
)
|
||||
.packet(3, 908, 12_000)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn routeable_ip_header_and_test_metadata_round_trip() {
|
||||
let bytes = probe();
|
||||
assert!(is_test_packet(&bytes));
|
||||
let data = decode_packet(&bytes).unwrap();
|
||||
assert_eq!(data.source, Ipv4Addr::new(10, 1, 10, 1));
|
||||
assert_eq!(data.destination, Ipv4Addr::new(10, 1, 10, 2));
|
||||
assert_eq!(
|
||||
(
|
||||
data.id,
|
||||
data.direction,
|
||||
data.stage,
|
||||
data.sequence,
|
||||
data.sent_us
|
||||
),
|
||||
(42, Direction::Upload, 3, 908, 12_000)
|
||||
);
|
||||
assert_eq!(data.payload_len(), 1280 - HEADER);
|
||||
for n in [0, 1, 19, 27, 45, 100, 1279] {
|
||||
assert!(decode_packet(&bytes[..n]).is_none());
|
||||
}
|
||||
for (byte, value) in [
|
||||
(0, 0x65),
|
||||
(2, 0x04),
|
||||
(6, 0x20),
|
||||
(9, 17),
|
||||
(10, 0),
|
||||
(20, b'z'),
|
||||
(36, 3),
|
||||
(42, 255),
|
||||
] {
|
||||
let mut bad = bytes.to_vec();
|
||||
bad[byte] = value;
|
||||
assert!(decode_packet(&bad).is_none(), "corrupted {byte}");
|
||||
}
|
||||
let mut broken = bytes.to_vec();
|
||||
broken[36] = 123;
|
||||
assert!(is_test_packet(&broken));
|
||||
broken[20] = 0;
|
||||
assert!(!is_test_packet(&broken));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,228 @@
|
||||
use crate::NORMAL_BYTES;
|
||||
use crate::packet::{MAX_MTU, MIN_MTU};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Both endpoints name directions from the initiating user's point of view.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Direction {
|
||||
/// From the responding peer to the initiator.
|
||||
Download,
|
||||
/// From the initiator to the responding peer.
|
||||
Upload,
|
||||
}
|
||||
|
||||
/// What the received samples establish about the path.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Quality {
|
||||
/// Measurement in progress.
|
||||
#[default]
|
||||
Measuring,
|
||||
/// The receiver confirmed a stable rate after the probe reached the path's limit.
|
||||
Measured,
|
||||
/// Sustained delivery at this rate was established before the time or byte budget ended.
|
||||
AtLeast,
|
||||
/// No full observation window was available.
|
||||
Insufficient,
|
||||
}
|
||||
|
||||
/// Useful probe payload received in one direction.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Reading {
|
||||
/// Delivered bits per second, if there was enough evidence to calculate a rate.
|
||||
pub bps: Option<u64>,
|
||||
/// Unique, received probe payload bytes, excluding IPv4 and diagnostic headers.
|
||||
pub bytes: u32,
|
||||
/// Meaning of the reported rate.
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
/// Lifecycle of a single bidirectional test.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum State {
|
||||
/// Negotiating a test.
|
||||
#[default]
|
||||
Starting,
|
||||
/// Receiving from the peer.
|
||||
Download,
|
||||
/// Sending to the peer.
|
||||
Upload,
|
||||
/// Both direction reports were exchanged.
|
||||
Complete,
|
||||
/// A participant cancelled this test.
|
||||
Cancelled,
|
||||
/// The other endpoint is already testing.
|
||||
Busy,
|
||||
/// A participant failed to finish before the deadline.
|
||||
TimedOut,
|
||||
/// The transport failed, configuration was invalid, or a peer sent inconsistent results.
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// A snapshot suitable for status or a live display.
|
||||
#[derive(Default, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Progress {
|
||||
/// Current phase or final outcome.
|
||||
pub state: State,
|
||||
/// Peer to initiator.
|
||||
pub down: Reading,
|
||||
/// Initiator to peer.
|
||||
pub up: Reading,
|
||||
}
|
||||
|
||||
impl Progress {
|
||||
pub(crate) fn at(&mut self, direction: Direction) -> &mut Reading {
|
||||
match direction {
|
||||
Direction::Download => &mut self.down,
|
||||
Direction::Upload => &mut self.up,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Request to start one measurement under both peers' local limits.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Start {
|
||||
/// Fresh random identifier selected by the initiator.
|
||||
pub id: u64,
|
||||
/// Maximum diagnostic IPv4 bytes to send per direction.
|
||||
pub byte_limit: u32,
|
||||
/// Maximum complete IPv4 datagram size supported by the initiating endpoint.
|
||||
pub mtu: u16,
|
||||
}
|
||||
|
||||
/// Receiver-clock observation at one offered rate.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct Feedback {
|
||||
pub(crate) stage: u8,
|
||||
pub(crate) bps: u64,
|
||||
pub(crate) lost_per_mille: u16,
|
||||
pub(crate) bytes: u32,
|
||||
pub(crate) echo_us: u32,
|
||||
}
|
||||
|
||||
/// Bounded records carried by the authenticated, reliable control connection.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Control {
|
||||
/// Request a test between these two peers.
|
||||
Start(Start),
|
||||
/// Negotiated maximum datagram size and per-direction budget.
|
||||
Accepted {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Per-direction budget in IPv4 bytes.
|
||||
byte_limit: u32,
|
||||
/// Size of every probe datagram.
|
||||
mtu: u16,
|
||||
},
|
||||
/// The responder already has an active test.
|
||||
Busy {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
/// Receiver has installed its data sink before the sender begins.
|
||||
Ready {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction about to start.
|
||||
direction: Direction,
|
||||
},
|
||||
/// Observed goodput and loss over a full interval of the receiver's clock.
|
||||
Feedback {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction being measured.
|
||||
direction: Direction,
|
||||
/// Receiver's observation.
|
||||
sample: Feedback,
|
||||
},
|
||||
/// The sender has stopped issuing probes and shares the result of its rate search.
|
||||
End {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction ending.
|
||||
direction: Direction,
|
||||
/// Number of IPv4 datagrams issued by the sender.
|
||||
packets: u32,
|
||||
/// Rate search result based on receiver feedback.
|
||||
reading: Reading,
|
||||
},
|
||||
/// Final delivery numbers after draining late probes.
|
||||
Report {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
/// Direction completed.
|
||||
direction: Direction,
|
||||
/// Agreed result for this direction.
|
||||
reading: Reading,
|
||||
},
|
||||
/// End the exchange early in either direction.
|
||||
Cancel {
|
||||
/// Test identifier.
|
||||
id: u64,
|
||||
},
|
||||
}
|
||||
|
||||
pub(crate) const MAX_BPS: u64 = 8_000_000_000;
|
||||
const MAX_RECORD: usize = 64;
|
||||
|
||||
impl Control {
|
||||
/// Identifier used to bind the record to an already authenticated peer and session.
|
||||
pub fn id(&self) -> u64 {
|
||||
match *self {
|
||||
Self::Start(start) => start.id,
|
||||
Self::Accepted { id, .. }
|
||||
| Self::Busy { id }
|
||||
| Self::Ready { id, .. }
|
||||
| Self::Feedback { id, .. }
|
||||
| Self::End { id, .. }
|
||||
| Self::Report { id, .. }
|
||||
| Self::Cancel { id } => id,
|
||||
}
|
||||
}
|
||||
|
||||
/// Encode a control record into its compact version-one representation.
|
||||
pub fn encode(&self) -> Result<Vec<u8>, postcard::Error> {
|
||||
postcard::to_stdvec(self)
|
||||
}
|
||||
|
||||
/// Parse exactly one version-one record. Trailing bytes and values outside the protocol limits are rejected.
|
||||
pub fn decode(bytes: &[u8]) -> Option<Self> {
|
||||
if bytes.len() > MAX_RECORD {
|
||||
return None;
|
||||
}
|
||||
let (control, rest) = postcard::take_from_bytes::<Self>(bytes).ok()?;
|
||||
(rest.is_empty() && control.valid()).then_some(control)
|
||||
}
|
||||
|
||||
pub(crate) fn valid(self) -> bool {
|
||||
match self {
|
||||
Self::Start(Start {
|
||||
byte_limit, mtu, ..
|
||||
})
|
||||
| Self::Accepted {
|
||||
byte_limit, mtu, ..
|
||||
} => (1..=NORMAL_BYTES).contains(&byte_limit) && (MIN_MTU..=MAX_MTU).contains(&mtu),
|
||||
Self::Feedback { sample, .. } => {
|
||||
sample.bps <= MAX_BPS
|
||||
&& sample.lost_per_mille <= 1000
|
||||
&& sample.bytes <= NORMAL_BYTES
|
||||
&& sample.echo_us <= 5_000_000
|
||||
}
|
||||
Self::End {
|
||||
packets, reading, ..
|
||||
} => packets <= NORMAL_BYTES / u32::from(MIN_MTU) && valid_result(reading),
|
||||
Self::Report { reading, .. } => valid_result(reading),
|
||||
Self::Busy { .. } | Self::Ready { .. } | Self::Cancel { .. } => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_result(reading: Reading) -> bool {
|
||||
reading.bytes <= NORMAL_BYTES
|
||||
&& match reading.quality {
|
||||
Quality::Insufficient => reading.bps.is_none(),
|
||||
Quality::Measured | Quality::AtLeast => {
|
||||
reading.bytes > 0 && reading.bps.is_some_and(|v| (1..=MAX_BPS).contains(&v))
|
||||
}
|
||||
Quality::Measuring => false,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
//! Independently clocked sessions exchange real control records and shaped IPv4 probes.
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use bytes::Bytes;
|
||||
use std::future::Future;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
use tsunagi_speedtest::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Link {
|
||||
remote: Handle,
|
||||
start: Instant,
|
||||
rate: u64,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
state: Arc<Mutex<Delivery>>,
|
||||
samples: Arc<Mutex<Vec<Progress>>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Delivery {
|
||||
// Tokens represent one millisecond of useful payload on this shaped path.
|
||||
tick: u64,
|
||||
credit: u64,
|
||||
bytes: u64,
|
||||
packets: u32,
|
||||
}
|
||||
|
||||
impl Io for Link {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
// The harness creates the responding session with the real Start record.
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
if !self.control_delay.is_zero() {
|
||||
tokio::time::sleep(self.control_delay).await;
|
||||
}
|
||||
self.remote
|
||||
.control(Control::decode(&message.encode().unwrap()).unwrap());
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let probe = decode_packet(&packet).unwrap();
|
||||
let tick = self.start.elapsed().as_millis() as u64;
|
||||
let rate = self
|
||||
.warmup
|
||||
.filter(|(until, _)| self.start.elapsed() < *until)
|
||||
.map_or(self.rate, |(_, rate)| rate);
|
||||
let mut state = self.state.lock().unwrap();
|
||||
if state.tick != tick {
|
||||
let elapsed = tick - state.tick;
|
||||
state.credit = (state.credit + rate * elapsed / 8000).min(rate * 4 / 8000 + 1300);
|
||||
state.tick = tick;
|
||||
}
|
||||
state.bytes += packet.len() as u64;
|
||||
if state.credit >= probe.payload_len() as u64 {
|
||||
state.credit -= probe.payload_len() as u64;
|
||||
state.packets += 1;
|
||||
if self.drop_every != 0 && state.packets.is_multiple_of(self.drop_every) {
|
||||
return true;
|
||||
}
|
||||
self.remote.data(probe);
|
||||
// Duplicates must never add more bytes or improve the reported rate.
|
||||
self.remote.data(probe);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn progress(&self, update: Progress) {
|
||||
self.samples.lock().unwrap().push(update);
|
||||
}
|
||||
}
|
||||
|
||||
fn config(local: u8, remote: u8, bytes: u32) -> Config {
|
||||
Config {
|
||||
id: 7,
|
||||
local: Ipv4Addr::new(10, 11, 12, local),
|
||||
remote: Ipv4Addr::new(10, 11, 12, remote),
|
||||
mtu: 1280,
|
||||
byte_limit: bytes,
|
||||
rtt: Duration::from_millis(20),
|
||||
}
|
||||
}
|
||||
|
||||
async fn measure(down: u64, up: u64, budget: u32) -> (Progress, Progress, Link, Link) {
|
||||
shaped(down, up, budget, Duration::ZERO, 0, None).await
|
||||
}
|
||||
|
||||
async fn shaped(
|
||||
down: u64,
|
||||
up: u64,
|
||||
budget: u32,
|
||||
control_delay: Duration,
|
||||
drop_every: u32,
|
||||
warmup: Option<(Duration, u64)>,
|
||||
) -> (Progress, Progress, Link, Link) {
|
||||
let cfg = |a, b| Config {
|
||||
rtt: control_delay.max(Duration::from_millis(20)),
|
||||
..config(a, b, budget)
|
||||
};
|
||||
let (a, initiator) = initiate(cfg(1, 2));
|
||||
let start = Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
};
|
||||
let (b, responder) = respond(cfg(2, 1), start);
|
||||
let now = Instant::now();
|
||||
let link = |remote, rate, warmup| Link {
|
||||
warmup,
|
||||
remote,
|
||||
start: now,
|
||||
rate,
|
||||
control_delay,
|
||||
drop_every,
|
||||
state: Default::default(),
|
||||
samples: Default::default(),
|
||||
};
|
||||
let ab = link(b, up, None);
|
||||
let ba = link(a, down, warmup);
|
||||
let (a, b) = tokio::join!(initiator.run(ab.clone()), responder.run(ba.clone()));
|
||||
println!(
|
||||
"Shaped path {down}/{up} bit/s, receiver readings {:?}/{:?}",
|
||||
a.down.bps, a.up.bps
|
||||
);
|
||||
assert!(now.elapsed() <= Duration::from_secs(5));
|
||||
assert!(ab.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
assert!(ba.state.lock().unwrap().bytes <= u64::from(budget));
|
||||
(a, b, ab, ba)
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn both_directions_measure_delivery_and_show_it_before_completion() {
|
||||
let (a, b, ab, _) = measure(10_000_000, 40_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (sample, expected) in [(a.down, 10_000_000), (a.up, 40_000_000)] {
|
||||
let bps = sample.bps.unwrap();
|
||||
assert!(
|
||||
(expected * 8 / 10..=expected * 12 / 10).contains(&bps),
|
||||
"{sample:?}"
|
||||
);
|
||||
assert_eq!(sample.quality, Quality::Measured, "{sample:?}");
|
||||
}
|
||||
let updates = ab.samples.lock().unwrap();
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Download && p.down.bps.is_some())
|
||||
);
|
||||
assert!(
|
||||
updates
|
||||
.iter()
|
||||
.any(|p| p.state == State::Upload && p.up.bps.is_some())
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_fast_path_extends_the_probe_but_never_turns_a_short_burst_into_a_peak() {
|
||||
let (a, _, _, _) = measure(1_000_000_000, 1_000_000_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(a.down.bytes > 16 * 1024 * 1024);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (700_000_000..=1_150_000_000).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
let (short, _, _, _) = measure(1_000_000_000, 1_000_000_000, 4096).await;
|
||||
assert_eq!(short.down.quality, Quality::Insufficient);
|
||||
assert_eq!(short.down.bps, None);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_random_loss_does_not_masquerade_as_a_slow_link() {
|
||||
let (a, _, _, _) = shaped(
|
||||
20_000_000,
|
||||
45_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(45),
|
||||
20,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (reading, rate) in [(a.down, 20_000_000), (a.up, 45_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (rate * 7 / 10..=rate * 11 / 10).contains(&v)),
|
||||
"{a:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn fast_metered_path_returns_a_sustained_lower_bound_within_its_budget() {
|
||||
let (a, _, _, _) = measure(4_000_000_000, 4_000_000_000, METERED_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::AtLeast);
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|v| (50_000_000..1_000_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn unreachable_data_path_cannot_synthesize_a_rate_or_keep_the_exchange_open() {
|
||||
let (a, _, _, _) = measure(0, 0, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for reading in [a.down, a.up] {
|
||||
assert_eq!(reading.quality, Quality::Insufficient);
|
||||
assert_eq!(reading.bps, None);
|
||||
}
|
||||
}
|
||||
|
||||
struct Silent;
|
||||
impl Io for Silent {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::pending()
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_blocked_control_stream_cannot_hold_up_cancellation_or_the_deadline() {
|
||||
let (handle, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let task = tokio::spawn(runner.run(Silent));
|
||||
tokio::task::yield_now().await;
|
||||
handle.cancel();
|
||||
let before = Instant::now();
|
||||
assert_eq!(task.await.unwrap().state, State::Cancelled);
|
||||
assert!(before.elapsed() <= Duration::from_millis(25));
|
||||
|
||||
let (_keep_ingress, runner) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
let before = Instant::now();
|
||||
assert_eq!(runner.run(Silent).await.state, State::TimedOut);
|
||||
assert!(before.elapsed() <= Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn control_records_have_finite_limits_and_exact_framing() {
|
||||
let message = Control::Start(Start {
|
||||
id: 42,
|
||||
byte_limit: NORMAL_BYTES,
|
||||
mtu: 1280,
|
||||
});
|
||||
let mut wire = message.encode().unwrap();
|
||||
assert_eq!(Control::decode(&wire), Some(message));
|
||||
for n in 0..wire.len() {
|
||||
assert_eq!(Control::decode(&wire[..n]), None);
|
||||
}
|
||||
wire.push(0);
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
assert_eq!(Control::decode(&[255; 65]), None);
|
||||
for (byte_limit, mtu) in [
|
||||
(0, 1280),
|
||||
(NORMAL_BYTES + 1, 1280),
|
||||
(1000, 4),
|
||||
(1000, u16::MAX),
|
||||
] {
|
||||
let wire = Control::Start(Start {
|
||||
id: 1,
|
||||
byte_limit,
|
||||
mtu,
|
||||
})
|
||||
.encode()
|
||||
.unwrap();
|
||||
assert_eq!(Control::decode(&wire), None);
|
||||
}
|
||||
}
|
||||
|
||||
struct OpenControl;
|
||||
impl Io for OpenControl {
|
||||
fn control(&self, _: Control) -> impl Future<Output = bool> + Send {
|
||||
std::future::ready(true)
|
||||
}
|
||||
fn packet(&self, _: Bytes) -> bool {
|
||||
false
|
||||
}
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn an_unrelated_busy_reply_does_not_cancel_the_active_request() {
|
||||
let (handle, session) = initiate(config(1, 2, NORMAL_BYTES));
|
||||
handle.control(Control::Busy { id: 8 });
|
||||
let task = tokio::spawn(session.run(OpenControl));
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!task.is_finished());
|
||||
handle.control(Control::Busy { id: 7 });
|
||||
assert_eq!(task.await.unwrap().state, State::Busy);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slower_control_feedback_leaves_time_for_both_directions() {
|
||||
let (a, b, _, _) = shaped(
|
||||
12_000_000,
|
||||
25_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(130),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a, b);
|
||||
assert_eq!(a.state, State::Complete);
|
||||
assert!(
|
||||
a.down
|
||||
.bps
|
||||
.is_some_and(|v| (9_000_000..=14_000_000).contains(&v))
|
||||
);
|
||||
assert!(
|
||||
a.up.bps
|
||||
.is_some_and(|v| (17_000_000..=28_000_000).contains(&v))
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slow_links_accumulate_enough_arrivals_for_a_rate() {
|
||||
let (a, _, _, _) = measure(100_000, 256_000, NORMAL_BYTES).await;
|
||||
assert_eq!(a.state, State::Complete);
|
||||
for (r, rate) in [(a.down, 100_000), (a.up, 256_000)] {
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (rate * 65 / 100..=rate * 125 / 100).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn persistent_heavy_loss_reports_only_sustained_lower_bounds() {
|
||||
let (a, _, _, _) = shaped(
|
||||
50_000_000,
|
||||
50_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
3,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for r in [a.down, a.up] {
|
||||
assert_eq!(r.quality, Quality::AtLeast, "{r:?}");
|
||||
assert!(
|
||||
r.bps
|
||||
.is_some_and(|v| (28_000_000..=36_000_000).contains(&v)),
|
||||
"{r:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_rate_requires_evidence_of_delivered_payload() {
|
||||
for quality in [Quality::AtLeast, Quality::Measured] {
|
||||
let message = Control::Report {
|
||||
id: 1,
|
||||
direction: Direction::Download,
|
||||
reading: Reading {
|
||||
bps: Some(8_000_000_000),
|
||||
bytes: 0,
|
||||
quality,
|
||||
},
|
||||
};
|
||||
assert!(Control::decode(&message.encode().unwrap()).is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_cold_download_reprobes_after_the_path_warms_up() {
|
||||
let (result, _, _, _) = shaped(
|
||||
300_000_000,
|
||||
250_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::ZERO,
|
||||
0,
|
||||
Some((Duration::from_millis(850), 60_000_000)),
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 300_000_000), (result.up, 250_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 8 / 10..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn delayed_feedback_does_not_hide_the_metered_receivers_last_sustained_rate() {
|
||||
let (result, _, _, _) = shaped(
|
||||
350_000_000,
|
||||
200_000_000,
|
||||
METERED_BYTES,
|
||||
Duration::from_millis(95),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
for (reading, expected) in [(result.down, 350_000_000), (result.up, 200_000_000)] {
|
||||
assert!(
|
||||
reading
|
||||
.bps
|
||||
.is_some_and(|rate| (expected * 75 / 100..=expected * 11 / 10).contains(&rate)),
|
||||
"{result:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_full_tunnel_charges_only_packets_actually_submitted_to_it() {
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
|
||||
struct BusyQueue {
|
||||
other: Handle,
|
||||
start: Instant,
|
||||
stalled: AtomicBool,
|
||||
submitted: AtomicU32,
|
||||
}
|
||||
|
||||
impl Io for BusyQueue {
|
||||
async fn control(&self, message: Control) -> bool {
|
||||
if let Control::End { packets, .. } = message {
|
||||
assert!(self.stalled.load(Ordering::Relaxed));
|
||||
assert_eq!(packets, self.submitted.load(Ordering::Relaxed));
|
||||
}
|
||||
if !matches!(message, Control::Start(_)) {
|
||||
self.other.control(message);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn packet(&self, packet: Bytes) -> bool {
|
||||
let count = self.submitted.fetch_add(1, Ordering::Relaxed);
|
||||
let full = self.start.elapsed() > Duration::from_millis(180) && count.is_multiple_of(3);
|
||||
if full {
|
||||
self.stalled.store(true, Ordering::Relaxed);
|
||||
}
|
||||
// A backpressured tunnel may drop the packet or retain it for a
|
||||
// pending handshake. Either outcome must respect the byte budget.
|
||||
if !full || count.is_multiple_of(2) {
|
||||
self.other.data(decode_packet(&packet).unwrap());
|
||||
}
|
||||
!full
|
||||
}
|
||||
|
||||
fn progress(&self, _: Progress) {}
|
||||
}
|
||||
|
||||
let budget = 2 * 1024 * 1024;
|
||||
let (a, outgoing) = initiate(config(1, 2, budget));
|
||||
let (b, incoming) = respond(
|
||||
config(2, 1, budget),
|
||||
Start {
|
||||
id: 7,
|
||||
byte_limit: budget,
|
||||
mtu: 1280,
|
||||
},
|
||||
);
|
||||
let queue = |other| BusyQueue {
|
||||
other,
|
||||
start: Instant::now(),
|
||||
stalled: AtomicBool::new(false),
|
||||
submitted: AtomicU32::new(0),
|
||||
};
|
||||
let (initiator, responder) = tokio::join!(
|
||||
outgoing.run(queue(b.clone())),
|
||||
incoming.run(queue(a.clone()))
|
||||
);
|
||||
assert_eq!(initiator.state, State::Complete);
|
||||
assert_eq!(initiator, responder);
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "tsunagi-ss2022"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "MIT"
|
||||
repository.workspace = true
|
||||
description = "Shadowsocks 2022 TCP transport for peer-to-peer mesh links."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
rand = "0.10"
|
||||
ring = "0.17"
|
||||
blake3 = { version = "1.8", features = ["zeroize"] }
|
||||
zeroize = "1.9"
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2021-2023 Alex Lau <github@alau.ca>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of this software and associated documentation files (the
|
||||
"Software"), to deal in the Software without restriction, including
|
||||
without limitation the rights to use, copy, modify, merge, publish,
|
||||
distribute, sublicense, and/or sell copies of the Software, and to
|
||||
permit persons to whom the Software is furnished to do so, subject to
|
||||
the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,219 @@
|
||||
//! Peer-only Shoes Shadowsocks 2022 TCP profile, adapted from cfal/shoes v0.3.8
|
||||
//! shadowsocks/{blake3_key,shadowsocks_stream,shadowsocks_tcp_handler}.rs (MIT).
|
||||
mod records;
|
||||
use iroh::EndpointId;
|
||||
use rand::Rng;
|
||||
use records::Records;
|
||||
use std::{
|
||||
io,
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tsunagi::BoxFuture;
|
||||
use tsunagi_shoes::{Profile, Profiles, ShoesWire, Stream, Ticket, driven};
|
||||
|
||||
/// Fixed identity of the external carrier.
|
||||
pub const PROTOCOL: &str = "ss2022";
|
||||
/// Initial compatible wire format.
|
||||
pub const WIRE_VERSION: u16 = 1;
|
||||
/// Preferred physical port.
|
||||
pub const PORT: u16 = 9444;
|
||||
/// Both SIP022 AES-GCM methods are available.
|
||||
pub struct Shadowsocks2022;
|
||||
|
||||
// A service selector inside the encrypted request. No OS connection is opened.
|
||||
const TARGET: [u8; 7] = [1, 127, 0, 0, 1, 0, 1];
|
||||
const MAX_PADDING: usize = 900;
|
||||
const TAG: usize = 16;
|
||||
fn invalid() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid Shadowsocks record")
|
||||
}
|
||||
fn now() -> io::Result<u64> {
|
||||
Ok(SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map_err(io::Error::other)?
|
||||
.as_secs())
|
||||
}
|
||||
fn key_len(profile: &Profile) -> usize {
|
||||
// Independent of the secret; the private offer tells both endpoints which method to use.
|
||||
if profile.variant { 32 } else { 16 }
|
||||
}
|
||||
fn fixed(kind: u8, request_salt: &[u8], len: usize) -> io::Result<Vec<u8>> {
|
||||
let mut header = vec![kind];
|
||||
header.extend_from_slice(&now()?.to_be_bytes());
|
||||
header.extend_from_slice(request_salt);
|
||||
header.extend_from_slice(&u16::try_from(len).map_err(|_| invalid())?.to_be_bytes());
|
||||
Ok(header)
|
||||
}
|
||||
fn parse_fixed(header: &[u8], kind: u8, salt: &[u8], time: u64) -> io::Result<usize> {
|
||||
if header.len() != 11 + salt.len() || header[0] != kind || &header[9..9 + salt.len()] != salt {
|
||||
return Err(invalid());
|
||||
}
|
||||
let timestamp = u64::from_be_bytes(header[1..9].try_into().map_err(|_| invalid())?);
|
||||
if timestamp.abs_diff(time) > 30 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let n = 9 + salt.len();
|
||||
Ok(u16::from_be_bytes([header[n], header[n + 1]]) as usize)
|
||||
}
|
||||
fn record_stream(tcp: TcpStream, mut seal: Records, mut open: Records, early: Vec<u8>) -> Stream {
|
||||
let (stream, bridge) = tokio::io::duplex(64 * 1024);
|
||||
driven(stream, async move {
|
||||
let (mut net_in, mut net_out) = tcp.into_split();
|
||||
let (mut app_in, mut app_out) = tokio::io::split(bridge);
|
||||
let upload = async {
|
||||
let mut buf = vec![0; 16 * 1024];
|
||||
loop {
|
||||
let n = app_in.read(&mut buf).await?;
|
||||
if n == 0 {
|
||||
return Ok::<_, io::Error>(());
|
||||
}
|
||||
let mut frame = seal.seal(&(n as u16).to_be_bytes())?;
|
||||
frame.extend(seal.seal(&buf[..n])?);
|
||||
net_out.write_all(&frame).await?;
|
||||
}
|
||||
};
|
||||
let download = async {
|
||||
app_out.write_all(&early).await?;
|
||||
loop {
|
||||
let len = open.read(&mut net_in, 2).await?;
|
||||
let n = u16::from_be_bytes([len[0], len[1]]) as usize;
|
||||
if n == 0 {
|
||||
return Err::<(), _>(invalid());
|
||||
}
|
||||
app_out.write_all(&open.read(&mut net_in, n).await?).await?;
|
||||
}
|
||||
};
|
||||
tokio::select! { _ = upload => {}, _ = download => {} }
|
||||
})
|
||||
}
|
||||
|
||||
impl ShoesWire for Shadowsocks2022 {
|
||||
fn name(&self) -> &'static str {
|
||||
PROTOCOL
|
||||
}
|
||||
fn version(&self) -> u16 {
|
||||
WIRE_VERSION
|
||||
}
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
mut tcp: TcpStream,
|
||||
_: EndpointId,
|
||||
p: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>> {
|
||||
Box::pin(async move {
|
||||
let n = key_len(p);
|
||||
let salt = &p.tag[..n];
|
||||
let mut seal = Records::new(&p.secret[..n], salt)?;
|
||||
let pad: u16 = rand::random_range(1..=MAX_PADDING as u16);
|
||||
let mut body = TARGET.to_vec();
|
||||
body.extend_from_slice(&pad.to_be_bytes());
|
||||
body.resize(body.len() + usize::from(pad), 0);
|
||||
rand::rng().fill_bytes(&mut body[9..]);
|
||||
let mut first = salt.to_vec();
|
||||
first.extend(seal.seal(&fixed(0, &[], body.len())?)?);
|
||||
first.extend(seal.seal(&body)?);
|
||||
tcp.write_all(&first).await?;
|
||||
let mut response = vec![0; n + 11 + n + TAG];
|
||||
if tcp.read(&mut response).await? != response.len() {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut open = Records::new(&p.secret[..n], &response[..n])?;
|
||||
let header = open.open(response[n..].to_vec())?;
|
||||
let size = parse_fixed(&header, 1, salt, now()?)?;
|
||||
if size == 0 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let initial = open.read(&mut tcp, size).await?;
|
||||
let early = initial.strip_prefix(&[0]).ok_or_else(invalid)?;
|
||||
Ok(record_stream(tcp, seal, open, early.to_vec()))
|
||||
})
|
||||
}
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
mut tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>> {
|
||||
Box::pin(async move {
|
||||
// Use a consistent reset on rejected or truncated first records (SIP022 §3.1.4).
|
||||
tcp.set_zero_linger()?;
|
||||
// SIP022 reads the salt and complete fixed header in one socket read.
|
||||
let mut prefix = [0u8; 32 + 11 + TAG];
|
||||
let used = tcp.read(&mut prefix).await?;
|
||||
if used < 16 + 11 + TAG {
|
||||
return Err(invalid());
|
||||
}
|
||||
let ticket = profiles.lookup(&prefix[..16])?;
|
||||
let p = &ticket.profile;
|
||||
let n = key_len(p);
|
||||
let end = n + 11 + TAG;
|
||||
if used < end || prefix[..n] != p.tag[..n] {
|
||||
return Err(invalid());
|
||||
}
|
||||
let salt = &prefix[..n];
|
||||
let key = &p.secret[..n];
|
||||
let mut open = Records::new(key, salt)?;
|
||||
let header = open.open(prefix[n..end].to_vec())?;
|
||||
let size = parse_fixed(&header, 0, &[], now()?)?;
|
||||
if size < 9 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut body = vec![0; size + TAG];
|
||||
let buffered = used - end;
|
||||
body[..buffered].copy_from_slice(&prefix[end..used]);
|
||||
tcp.read_exact(&mut body[buffered..]).await?;
|
||||
let body = open.open(body)?;
|
||||
let early = parse_target(&body)?;
|
||||
profiles.claim(&ticket)?;
|
||||
// Tokio deprecates positive linger times because they block on close.
|
||||
// Clearing the rejection-only reset restores the normal nonblocking close.
|
||||
#[allow(deprecated)]
|
||||
tcp.set_linger(None)?;
|
||||
let response_salt: [u8; 32] = rand::random();
|
||||
let mut seal = Records::new(key, &response_salt[..n])?;
|
||||
let mut response = response_salt[..n].to_vec();
|
||||
response.extend(seal.seal(&fixed(1, salt, 1)?)?);
|
||||
response.extend(seal.seal(&[0])?);
|
||||
tcp.write_all(&response).await?;
|
||||
Ok((ticket, record_stream(tcp, seal, open, early.to_vec())))
|
||||
})
|
||||
}
|
||||
}
|
||||
fn parse_target(body: &[u8]) -> io::Result<&[u8]> {
|
||||
if body.len() < 9 || body[..7] != TARGET {
|
||||
return Err(invalid());
|
||||
}
|
||||
let pad = u16::from_be_bytes([body[7], body[8]]) as usize;
|
||||
if pad > MAX_PADDING || body.len() == 9 {
|
||||
return Err(invalid());
|
||||
}
|
||||
body.get(9 + pad..).ok_or_else(invalid)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn reject_clock_skew_reflection_wrong_salt_and_wrong_service() {
|
||||
let header = fixed(1, &[8; 16], 512).unwrap();
|
||||
let time = now().unwrap();
|
||||
assert_eq!(parse_fixed(&header, 1, &[8; 16], time).unwrap(), 512);
|
||||
assert!(parse_fixed(&header, 0, &[8; 16], time).is_err());
|
||||
assert!(parse_fixed(&header, 1, &[7; 16], time).is_err());
|
||||
assert!(parse_fixed(&header, 1, &[8; 16], time + 31).is_err());
|
||||
let mut body = TARGET.to_vec();
|
||||
body.extend([0, 0]);
|
||||
assert!(parse_target(&body).is_err());
|
||||
body.extend([9]);
|
||||
assert_eq!(parse_target(&body).unwrap(), &[9]);
|
||||
body[8] = 2;
|
||||
assert!(parse_target(&body).is_err());
|
||||
body[8] = 1;
|
||||
body[4] = 2;
|
||||
assert!(parse_target(&body).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
//! The SIP022 record construction used by Shoes (MIT).
|
||||
use super::{TAG, invalid};
|
||||
use ring::aead::{self, Aad, LessSafeKey, Nonce, UnboundKey};
|
||||
use std::io;
|
||||
use tokio::io::{AsyncRead, AsyncReadExt};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
|
||||
pub(super) struct Records {
|
||||
key: LessSafeKey,
|
||||
counter: u128,
|
||||
}
|
||||
impl Records {
|
||||
pub(super) fn new(key: &[u8], salt: &[u8]) -> io::Result<Self> {
|
||||
let algorithm = match (key.len(), salt.len()) {
|
||||
(16, 16) => &aead::AES_128_GCM,
|
||||
(32, 32) => &aead::AES_256_GCM,
|
||||
_ => return Err(invalid()),
|
||||
};
|
||||
let mut hasher = blake3::Hasher::new_derive_key("shadowsocks 2022 session subkey");
|
||||
hasher.update(key).update(salt);
|
||||
let mut subkey = Zeroizing::new([0; 32]);
|
||||
hasher.finalize_xof().fill(&mut subkey[..key.len()]);
|
||||
hasher.zeroize();
|
||||
let key = UnboundKey::new(algorithm, &subkey[..key.len()]).map_err(|_| invalid())?;
|
||||
Ok(Self {
|
||||
key: LessSafeKey::new(key),
|
||||
counter: 0,
|
||||
})
|
||||
}
|
||||
fn nonce(&mut self) -> io::Result<Nonce> {
|
||||
if self.counter >= 1 << 96 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut nonce = [0; 12];
|
||||
nonce.copy_from_slice(&self.counter.to_le_bytes()[..12]);
|
||||
self.counter += 1;
|
||||
Ok(Nonce::assume_unique_for_key(nonce))
|
||||
}
|
||||
pub(super) fn seal(&mut self, plaintext: &[u8]) -> io::Result<Vec<u8>> {
|
||||
let nonce = self.nonce()?;
|
||||
let mut buf = plaintext.to_vec();
|
||||
self.key
|
||||
.seal_in_place_append_tag(nonce, Aad::empty(), &mut buf)
|
||||
.map_err(|_| invalid())?;
|
||||
Ok(buf)
|
||||
}
|
||||
pub(super) fn open(&mut self, mut buf: Vec<u8>) -> io::Result<Vec<u8>> {
|
||||
let nonce = self.nonce()?;
|
||||
let size = self
|
||||
.key
|
||||
.open_in_place(nonce, Aad::empty(), &mut buf)
|
||||
.map_err(|_| invalid())?
|
||||
.len();
|
||||
buf.truncate(size);
|
||||
Ok(buf)
|
||||
}
|
||||
pub(super) async fn read(
|
||||
&mut self,
|
||||
r: &mut (impl AsyncRead + Unpin),
|
||||
len: usize,
|
||||
) -> io::Result<Vec<u8>> {
|
||||
let mut buf = vec![0; len + TAG];
|
||||
r.read_exact(&mut buf).await?;
|
||||
self.open(buf)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn both_methods_authenticate_each_record_and_enforce_nonce_order() {
|
||||
for n in [16, 32] {
|
||||
let key = &[0x33; 32][..n];
|
||||
let salt = &[0x44; 32][..n];
|
||||
let mut tx = Records::new(key, salt).unwrap();
|
||||
let mut rx = Records::new(key, salt).unwrap();
|
||||
let a = tx.seal(b"ab").unwrap();
|
||||
let b = tx.seal(b"ab").unwrap();
|
||||
assert_ne!(a, b);
|
||||
assert_eq!(rx.open(a.clone()).unwrap(), b"ab");
|
||||
assert_eq!(rx.open(b).unwrap(), b"ab");
|
||||
assert!(rx.open(a.clone()).is_err());
|
||||
let mut corrupt = a;
|
||||
corrupt[1] ^= 0x40;
|
||||
assert!(Records::new(key, salt).unwrap().open(corrupt).is_err());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tcp-tls"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,16 +8,18 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
x509-parser = "0.18"
|
||||
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
||||
bytes.workspace = true
|
||||
serde.workspace = true
|
||||
postcard.workspace = true
|
||||
tracing.workspace = true
|
||||
socket2 = "0.6"
|
||||
netdev = "0.46"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
//! Bounded address selection shared by native TCP carriers.
|
||||
use iroh::EndpointId;
|
||||
use std::{collections::HashMap, net::SocketAddr, sync::Mutex, time::Duration};
|
||||
use tokio::{
|
||||
net::TcpStream,
|
||||
task::JoinSet,
|
||||
time::{sleep, timeout},
|
||||
};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
dataplane::transport::{PacketTransport, SharedLink, TransportError},
|
||||
};
|
||||
|
||||
/// TCP service registered on its own port, using authenticated, per-network announcements.
|
||||
pub trait TcpEndpoint: PacketTransport {
|
||||
/// Independent version of the data carrier.
|
||||
fn wire_version(&self) -> u16;
|
||||
/// Actual bound TCP port.
|
||||
fn bound_port(&self) -> u16;
|
||||
/// Replace reachability for one membership; an empty list still permits reverse dialing.
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
);
|
||||
/// Retire candidates and negotiations belonging to this network.
|
||||
fn clear_network(&self, network: NetworkId);
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct Candidates {
|
||||
pub(crate) pairs: Mutex<HashMap<(NetworkId, EndpointId), Vec<SocketAddr>>>,
|
||||
pub(crate) manual: Mutex<HashMap<EndpointId, Vec<SocketAddr>>>,
|
||||
}
|
||||
|
||||
/// Stagger TCP connects so a stale LAN address cannot hide a reachable candidate.
|
||||
/// Only one connected socket at a time negotiates a link with the remote peer.
|
||||
pub async fn dial_candidates<F, Fut>(
|
||||
addresses: Vec<SocketAddr>,
|
||||
mut authenticate: F,
|
||||
) -> Result<SharedLink, TransportError>
|
||||
where
|
||||
F: FnMut(TcpStream, SocketAddr) -> Fut,
|
||||
Fut: Future<Output = Result<SharedLink, TransportError>>,
|
||||
{
|
||||
timeout(Duration::from_secs(8), async {
|
||||
let mut connects = JoinSet::new();
|
||||
for (i, addr) in addresses.into_iter().take(32).enumerate() {
|
||||
connects.spawn(async move {
|
||||
sleep(Duration::from_millis(60 * i as u64)).await;
|
||||
let socket = timeout(Duration::from_secs(3), TcpStream::connect(addr))
|
||||
.await
|
||||
.ok()?
|
||||
.ok()?;
|
||||
Some((socket, addr))
|
||||
});
|
||||
}
|
||||
let mut error = TransportError::Unreachable("no reachable TCP listener for peer".into());
|
||||
while let Some(result) = connects.join_next().await {
|
||||
if let Ok(Some((socket, addr))) = result {
|
||||
let _ = socket.set_nodelay(true);
|
||||
match timeout(Duration::from_secs(4), authenticate(socket, addr)).await {
|
||||
Ok(Ok(link)) => return Ok(link),
|
||||
Ok(Err(err)) => error = err,
|
||||
Err(_) => error = TransportError::Unreachable("TCP handshake timed out".into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error)
|
||||
})
|
||||
.await
|
||||
.map_err(|_| TransportError::Unreachable("TCP dial timed out".into()))?
|
||||
}
|
||||
|
||||
/// Bind one port for both address families where the host supports dual-stack TCP.
|
||||
pub fn listen(port: u16) -> std::io::Result<tokio::net::TcpListener> {
|
||||
use socket2::{Domain, Socket, Type};
|
||||
let ipv6 = || -> std::io::Result<std::net::TcpListener> {
|
||||
let socket = Socket::new(Domain::IPV6, Type::STREAM, None)?;
|
||||
socket.set_only_v6(false)?;
|
||||
socket.bind(&SocketAddr::from((std::net::Ipv6Addr::UNSPECIFIED, port)).into())?;
|
||||
socket.listen(128)?;
|
||||
Ok(socket.into())
|
||||
};
|
||||
let socket =
|
||||
ipv6().or_else(|_| std::net::TcpListener::bind((std::net::Ipv4Addr::UNSPECIFIED, port)))?;
|
||||
socket.set_nonblocking(true)?;
|
||||
tokio::net::TcpListener::from_std(socket)
|
||||
}
|
||||
@@ -33,14 +33,15 @@ impl ServerCertVerifier for PinnedEndpointVerifier {
|
||||
_ocsp_response: &[u8],
|
||||
_now: UnixTime,
|
||||
) -> Result<ServerCertVerified, RustlsError> {
|
||||
// Parse the certificate's SPKI / public key
|
||||
let cert_bytes = end_entity.as_ref();
|
||||
let expected_bytes = self.expected.as_bytes();
|
||||
|
||||
// Check if the expected 32-byte Ed25519 public key is in the certificate
|
||||
if cert_bytes
|
||||
.windows(32)
|
||||
.any(|window| window == expected_bytes)
|
||||
use x509_parser::prelude::{FromDer, X509Certificate};
|
||||
let (rest, cert) = X509Certificate::from_der(end_entity.as_ref())
|
||||
.map_err(|_| RustlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
|
||||
let key = cert.public_key();
|
||||
if rest.is_empty()
|
||||
&& key.algorithm.algorithm == x509_parser::oid_registry::OID_SIG_ED25519
|
||||
&& key.algorithm.parameters.is_none()
|
||||
&& key.subject_public_key.unused_bits == 0
|
||||
&& key.subject_public_key.data.as_ref() == self.expected.as_bytes()
|
||||
{
|
||||
Ok(ServerCertVerified::assertion())
|
||||
} else {
|
||||
@@ -126,7 +127,7 @@ pub fn make_server_config(
|
||||
) -> Result<Arc<ServerConfig>, rustls::Error> {
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let mut config = ServerConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(vec![cert], key)?;
|
||||
config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
||||
@@ -138,7 +139,7 @@ pub fn make_client_config(expected_peer: EndpointId) -> Result<Arc<ClientConfig>
|
||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||
let verifier = Arc::new(PinnedEndpointVerifier::new(expected_peer));
|
||||
let mut config = ClientConfig::builder_with_provider(provider)
|
||||
.with_safe_default_protocol_versions()?
|
||||
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(verifier)
|
||||
.with_no_client_auth();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
//! TCP TLS 1.3 carrier for opaque, independently encrypted mesh datagrams.
|
||||
pub mod candidates;
|
||||
pub mod cert;
|
||||
pub mod plugin;
|
||||
pub mod transport;
|
||||
pub use plugin::{
|
||||
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpTlsCarrier, TcpTlsConfig, local_ip_candidates,
|
||||
TCP_TLS_PROTOCOL, TCP_TLS_VERSION, TcpCarrier, TcpTlsCarrier, TcpTlsConfig, local_ip_candidates,
|
||||
};
|
||||
pub use transport::TcpTlsTransport;
|
||||
@@ -1,5 +1,5 @@
|
||||
//! TLS carrier options and bounded reachability announcements. No IP cipher lives here.
|
||||
use crate::transport::TcpTlsTransport;
|
||||
use crate::{candidates::TcpEndpoint, transport::TcpTlsTransport};
|
||||
use iroh::EndpointId;
|
||||
use serde::Deserialize;
|
||||
use std::sync::Arc;
|
||||
@@ -138,7 +138,12 @@ pub(crate) fn is_candidate_interface(iface: &netdev::Interface) -> bool {
|
||||
}
|
||||
|
||||
pub(crate) fn is_candidate_ipv4(addr: std::net::Ipv4Addr) -> bool {
|
||||
if addr.is_loopback() || addr.is_unspecified() || addr.is_link_local() || addr.is_broadcast() {
|
||||
if addr.is_multicast()
|
||||
|| addr.is_loopback()
|
||||
|| addr.is_unspecified()
|
||||
|| addr.is_link_local()
|
||||
|| addr.is_broadcast()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
if addr.is_documentation() {
|
||||
@@ -151,7 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool {
|
||||
match addr {
|
||||
std::net::IpAddr::V4(v4) => is_candidate_ipv4(v4),
|
||||
std::net::IpAddr::V6(v6) => {
|
||||
if v6.is_loopback() || v6.is_unspecified() {
|
||||
if v6.is_multicast() || v6.is_loopback() || v6.is_unspecified() {
|
||||
return false;
|
||||
}
|
||||
let segments = v6.segments();
|
||||
@@ -230,71 +235,65 @@ impl TcpTlsConfig {
|
||||
Ok(config)
|
||||
}
|
||||
}
|
||||
/// TLS carrier announcements and lifecycle, independent of IP encryption.
|
||||
/// Native TLS carrier, retaining the original registration API.
|
||||
pub type TcpTlsCarrier = TcpCarrier<TcpTlsTransport>;
|
||||
|
||||
/// Bounded TCP address announcements shared by carriers with independent listeners.
|
||||
#[derive(Debug)]
|
||||
pub struct TcpTlsCarrier {
|
||||
transport: Arc<TcpTlsTransport>,
|
||||
pub struct TcpCarrier<T> {
|
||||
transport: Arc<T>,
|
||||
excluded_interface: std::sync::Mutex<Option<String>>,
|
||||
bootstrap: std::sync::OnceLock<std::collections::HashMap<EndpointId, Vec<std::net::IpAddr>>>,
|
||||
underlay: std::sync::OnceLock<tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>>,
|
||||
peers: std::sync::Mutex<
|
||||
std::collections::HashMap<(NetworkId, EndpointId), Vec<std::net::SocketAddr>>,
|
||||
>,
|
||||
}
|
||||
impl TcpTlsCarrier {
|
||||
/// Shares the transport's listener; creates no end-to-end cipher.
|
||||
pub fn new(transport: Arc<TcpTlsTransport>) -> Arc<Self> {
|
||||
impl<T: TcpEndpoint> TcpCarrier<T> {
|
||||
/// Announces the actual listener's port.
|
||||
pub fn new(transport: Arc<T>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(None),
|
||||
excluded_interface: Default::default(),
|
||||
bootstrap: Default::default(),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
/// Registers a carrier while excluding the agent's own, possibly custom-named interface.
|
||||
pub fn with_interface(transport: Arc<TcpTlsTransport>, interface: String) -> Arc<Self> {
|
||||
/// Excludes the agent's own interface from physical addresses.
|
||||
pub fn with_interface(transport: Arc<T>, interface: String) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
transport,
|
||||
excluded_interface: std::sync::Mutex::new(Some(interface)),
|
||||
bootstrap: Default::default(),
|
||||
underlay: Default::default(),
|
||||
peers: Default::default(),
|
||||
})
|
||||
}
|
||||
/// Bootstrap IPs can be candidates for this peer's separately announced TCP port.
|
||||
pub fn set_bootstrap(&self, endpoints: &[iroh::EndpointAddr]) {
|
||||
let _ = self.bootstrap.set(
|
||||
endpoints
|
||||
.iter()
|
||||
.map(|endpoint| {
|
||||
(
|
||||
endpoint.id,
|
||||
endpoint.ip_addrs().take(32).map(|a| a.ip()).collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
/// Use only the addresses assigned to the OS-selected physical network.
|
||||
pub fn set_underlay(&self, source: tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>) {
|
||||
let _ = self.underlay.set(source);
|
||||
}
|
||||
fn update_peer(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addrs: Option<Vec<std::net::SocketAddr>>,
|
||||
) {
|
||||
let mut peers = self.peers.lock().unwrap_or_else(|p| p.into_inner());
|
||||
match addrs {
|
||||
Some(addrs) => {
|
||||
peers.insert((network, peer), addrs);
|
||||
}
|
||||
None => {
|
||||
peers.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
let mut combined = peers
|
||||
.iter()
|
||||
.filter(|((_, id), _)| *id == peer)
|
||||
.flat_map(|(_, addrs)| addrs.iter().copied())
|
||||
.collect::<Vec<_>>();
|
||||
combined.sort_unstable();
|
||||
combined.dedup();
|
||||
combined.truncate(32);
|
||||
self.transport.replace_peer_addrs(peer, combined);
|
||||
}
|
||||
}
|
||||
impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
|
||||
impl<T: TcpEndpoint> tsunagi::dataplane::transport::DataCarrier for TcpCarrier<T> {
|
||||
fn protocol_id(&self) -> &str {
|
||||
TCP_TLS_PROTOCOL
|
||||
self.transport.name()
|
||||
}
|
||||
fn protocol_version(&self) -> u16 {
|
||||
2
|
||||
self.transport.wire_version()
|
||||
}
|
||||
fn supports_reverse_dial(&self) -> bool {
|
||||
true
|
||||
}
|
||||
fn on_interface_ready(&self, name: &str) {
|
||||
*self
|
||||
@@ -324,10 +323,10 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
self.transport.bound_port(),
|
||||
ips.into_iter().take(32).collect::<Vec<_>>(),
|
||||
))
|
||||
.map_err(|_| PluginError::Other("cannot encode TLS addresses".into()))?;
|
||||
.map_err(|_| PluginError::Other("cannot encode TCP addresses".into()))?;
|
||||
Ok(Some(tsunagi::dataplane::PluginCapability {
|
||||
protocol: TCP_TLS_PROTOCOL.into(),
|
||||
version: 2,
|
||||
protocol: self.protocol_id().into(),
|
||||
version: self.protocol_version(),
|
||||
enabled: true,
|
||||
data,
|
||||
}))
|
||||
@@ -338,8 +337,20 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
peer: EndpointId,
|
||||
cap: &tsunagi::dataplane::PluginCapability,
|
||||
) -> Result<(), PluginError> {
|
||||
if !cap.enabled || cap.protocol != TCP_TLS_PROTOCOL || cap.version != 2 {
|
||||
return Err(PluginError::Rejected("unsupported TLS carrier".into()));
|
||||
self.on_peer_capability_at(network, peer, cap, &[])
|
||||
}
|
||||
fn on_peer_capability_at(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
cap: &tsunagi::dataplane::PluginCapability,
|
||||
observed: &[std::net::IpAddr],
|
||||
) -> Result<(), PluginError> {
|
||||
if !cap.enabled
|
||||
|| cap.protocol != self.protocol_id()
|
||||
|| cap.version != self.protocol_version()
|
||||
{
|
||||
return Err(PluginError::Rejected("unsupported TCP carrier".into()));
|
||||
}
|
||||
// Decode a fixed bounded array through the existing common announcement limit.
|
||||
#[derive(Deserialize)]
|
||||
@@ -348,37 +359,36 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
||||
#[serde(deserialize_with = "bounded_ips")] Vec<std::net::IpAddr>,
|
||||
);
|
||||
let Addresses(port, ips) = postcard::from_bytes(&cap.data)
|
||||
.map_err(|_| PluginError::Rejected("invalid TLS carrier addresses".into()))?;
|
||||
.map_err(|_| PluginError::Rejected("invalid TCP carrier addresses".into()))?;
|
||||
if port == 0 {
|
||||
return Err(PluginError::Rejected("invalid TLS carrier port".into()));
|
||||
return Err(PluginError::Rejected("invalid TCP carrier port".into()));
|
||||
}
|
||||
self.update_peer(
|
||||
network,
|
||||
peer,
|
||||
Some(
|
||||
ips.into_iter()
|
||||
.filter(|ip| is_candidate_ip(*ip))
|
||||
.map(|ip| std::net::SocketAddr::new(ip, port))
|
||||
.collect(),
|
||||
),
|
||||
);
|
||||
let configured = self.bootstrap.get().and_then(|peers| peers.get(&peer));
|
||||
let mut addresses = Vec::new();
|
||||
for ip in observed
|
||||
.iter()
|
||||
.copied()
|
||||
.chain(configured.into_iter().flatten().copied())
|
||||
.chain(ips)
|
||||
{
|
||||
let ip = ip.to_canonical();
|
||||
let addr = std::net::SocketAddr::new(ip, port);
|
||||
if is_candidate_ip(ip) && !addresses.contains(&addr) {
|
||||
addresses.push(addr);
|
||||
}
|
||||
if addresses.len() == 32 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.transport
|
||||
.set_pair_addresses(network, peer, Some(addresses));
|
||||
Ok(())
|
||||
}
|
||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
||||
self.update_peer(network, peer, None);
|
||||
self.transport.set_pair_addresses(network, peer, None);
|
||||
}
|
||||
fn on_network_deactivated(&self, network: NetworkId) {
|
||||
let peers: Vec<_> = self
|
||||
.peers
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.keys()
|
||||
.filter(|(id, _)| *id == network)
|
||||
.map(|(_, peer)| *peer)
|
||||
.collect();
|
||||
for peer in peers {
|
||||
self.update_peer(network, peer, None);
|
||||
}
|
||||
self.transport.clear_network(network);
|
||||
}
|
||||
}
|
||||
fn bounded_ips<'de, D: serde::Deserializer<'de>>(
|
||||
|
||||
@@ -3,17 +3,16 @@
|
||||
//! Provides [`TcpTlsTransport`] implementing [`PacketTransport`]
|
||||
//! and [`TcpTlsLink`] implementing [`PacketLink`].
|
||||
|
||||
use std::collections::HashMap;
|
||||
use crate::candidates::{Candidates, TcpEndpoint, dial_candidates};
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use iroh::{EndpointId, Signature};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tokio::sync::{Notify, mpsc};
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::sync::{mpsc, watch};
|
||||
use tokio_rustls::TlsConnector;
|
||||
|
||||
use tsunagi::BoxFuture;
|
||||
@@ -116,14 +115,27 @@ pub struct TcpTlsLink {
|
||||
tx: mpsc::Sender<Bytes>,
|
||||
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||
tasks: [tokio::task::AbortHandle; 2],
|
||||
closed_notify: Arc<Notify>,
|
||||
is_closed: Arc<AtomicBool>,
|
||||
closed: watch::Sender<bool>,
|
||||
remote_addr: String,
|
||||
protocol: &'static str,
|
||||
}
|
||||
|
||||
impl TcpTlsLink {
|
||||
/// Creates a new `TcpTlsLink` from a stream that has already passed the TLS handshake.
|
||||
pub fn new<S>(network: NetworkId, peer: EndpointId, stream: S, remote_addr: String) -> Self
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
|
||||
{
|
||||
Self::framed("tcp-tls", network, peer, stream, remote_addr)
|
||||
}
|
||||
/// Frames opaque mesh datagrams on a mutually authenticated carrier stream.
|
||||
pub fn framed<S>(
|
||||
protocol: &'static str,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
stream: S,
|
||||
remote_addr: String,
|
||||
) -> Self
|
||||
where
|
||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
|
||||
{
|
||||
@@ -132,11 +144,8 @@ impl TcpTlsLink {
|
||||
let (tx_out, mut rx_out) = mpsc::channel::<Bytes>(256);
|
||||
let (tx_in, rx_in) = mpsc::channel::<Bytes>(256);
|
||||
|
||||
let is_closed = Arc::new(AtomicBool::new(false));
|
||||
let closed_notify = Arc::new(Notify::new());
|
||||
|
||||
let closed_flag_w = Arc::clone(&is_closed);
|
||||
let closed_notify_w = Arc::clone(&closed_notify);
|
||||
let (closed, _) = watch::channel(false);
|
||||
let writer_closed = closed.clone();
|
||||
let writer_task = tokio::spawn(async move {
|
||||
while let Some(msg) = rx_out.recv().await {
|
||||
if msg.len() > MAX_FRAME_SIZE {
|
||||
@@ -153,12 +162,10 @@ impl TcpTlsLink {
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed_flag_w.store(true, Ordering::Release);
|
||||
closed_notify_w.notify_waiters();
|
||||
writer_closed.send_replace(true);
|
||||
});
|
||||
|
||||
let closed_flag_r = Arc::clone(&is_closed);
|
||||
let closed_notify_r = Arc::clone(&closed_notify);
|
||||
let reader_closed = closed.clone();
|
||||
let reader_task = tokio::spawn(async move {
|
||||
let mut len_buf = [0u8; 2];
|
||||
loop {
|
||||
@@ -177,8 +184,7 @@ impl TcpTlsLink {
|
||||
break;
|
||||
}
|
||||
}
|
||||
closed_flag_r.store(true, Ordering::Release);
|
||||
closed_notify_r.notify_waiters();
|
||||
reader_closed.send_replace(true);
|
||||
});
|
||||
|
||||
Self {
|
||||
@@ -187,9 +193,9 @@ impl TcpTlsLink {
|
||||
tx: tx_out,
|
||||
rx: tokio::sync::Mutex::new(rx_in),
|
||||
tasks: [writer_task.abort_handle(), reader_task.abort_handle()],
|
||||
closed_notify,
|
||||
is_closed,
|
||||
closed,
|
||||
remote_addr,
|
||||
protocol,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -201,8 +207,7 @@ impl Drop for TcpTlsLink {
|
||||
}
|
||||
impl PacketLink for TcpTlsLink {
|
||||
fn close(&self) {
|
||||
self.is_closed.store(true, Ordering::Release);
|
||||
self.closed_notify.notify_waiters();
|
||||
self.closed.send_replace(true);
|
||||
for task in &self.tasks {
|
||||
task.abort();
|
||||
}
|
||||
@@ -226,7 +231,7 @@ impl PacketLink for TcpTlsLink {
|
||||
limit: MAX_FRAME_SIZE,
|
||||
});
|
||||
}
|
||||
if self.is_closed.load(Ordering::Acquire) {
|
||||
if *self.closed.borrow() {
|
||||
return Err(TransportError::Closed);
|
||||
}
|
||||
self.tx
|
||||
@@ -243,19 +248,16 @@ impl PacketLink for TcpTlsLink {
|
||||
|
||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||
Box::pin(async move {
|
||||
if self.is_closed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
self.closed_notify.notified().await;
|
||||
let _ = self.closed.subscribe().wait_for(|closed| *closed).await;
|
||||
})
|
||||
}
|
||||
|
||||
fn is_closed(&self) -> bool {
|
||||
self.is_closed.load(Ordering::Acquire)
|
||||
*self.closed.borrow()
|
||||
}
|
||||
|
||||
fn path_description(&self) -> String {
|
||||
format!("tcp-tls via {}", self.remote_addr)
|
||||
format!("{} via {}", self.protocol, self.remote_addr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -265,7 +267,7 @@ pub struct TcpTlsTransport {
|
||||
local_id: EndpointId,
|
||||
listen_port: u16,
|
||||
sni: String,
|
||||
peer_addresses: std::sync::RwLock<HashMap<EndpointId, Vec<SocketAddr>>>,
|
||||
peer_addresses: Candidates,
|
||||
server_config: Arc<rustls::ServerConfig>,
|
||||
listener: Option<Arc<TcpListener>>,
|
||||
}
|
||||
@@ -348,7 +350,6 @@ impl TcpTlsTransport {
|
||||
let server_config = make_server_config(cert, key)?;
|
||||
|
||||
let target_port = requested_port.unwrap_or(DEFAULT_PORT);
|
||||
let bind_addr = SocketAddr::from(([0, 0, 0, 0], target_port));
|
||||
|
||||
let bind_result = {
|
||||
#[cfg(target_os = "linux")]
|
||||
@@ -358,13 +359,11 @@ impl TcpTlsTransport {
|
||||
None
|
||||
};
|
||||
|
||||
std::net::TcpListener::bind(bind_addr)
|
||||
crate::candidates::listen(target_port)
|
||||
};
|
||||
|
||||
let listener = match bind_result {
|
||||
Ok(std_listener) => {
|
||||
std_listener.set_nonblocking(true)?;
|
||||
let l = TcpListener::from_std(std_listener)?;
|
||||
Ok(l) => {
|
||||
tracing::info!(port = target_port, "TCP TLS listening");
|
||||
Some(Arc::new(l))
|
||||
}
|
||||
@@ -391,8 +390,7 @@ impl TcpTlsTransport {
|
||||
);
|
||||
}
|
||||
|
||||
let fallback_addr = SocketAddr::from(([0, 0, 0, 0], FALLBACK_PORT));
|
||||
match TcpListener::bind(fallback_addr).await {
|
||||
match crate::candidates::listen(FALLBACK_PORT) {
|
||||
Ok(l) => {
|
||||
tracing::info!(port = FALLBACK_PORT, "TCP TLS listening on fallback port");
|
||||
Some(Arc::new(l))
|
||||
@@ -404,8 +402,7 @@ impl TcpTlsTransport {
|
||||
"Cannot bind to fallback port {FALLBACK_PORT}: {fallback_err}. \
|
||||
Falling back to ephemeral port."
|
||||
);
|
||||
let ephemeral_addr = SocketAddr::from(([0, 0, 0, 0], 0));
|
||||
let l = TcpListener::bind(ephemeral_addr).await?;
|
||||
let l = crate::candidates::listen(0)?;
|
||||
let bound = l.local_addr()?.port();
|
||||
tracing::info!(port = bound, "TCP TLS listening on ephemeral port");
|
||||
Some(Arc::new(l))
|
||||
@@ -438,7 +435,7 @@ impl TcpTlsTransport {
|
||||
local_id: identity.endpoint_id(),
|
||||
listen_port: bound_port,
|
||||
sni,
|
||||
peer_addresses: std::sync::RwLock::new(HashMap::new()),
|
||||
peer_addresses: Candidates::default(),
|
||||
server_config,
|
||||
listener,
|
||||
})
|
||||
@@ -456,7 +453,7 @@ impl TcpTlsTransport {
|
||||
|
||||
/// Records an observed TCP target address for a peer.
|
||||
pub fn set_peer_addr(&self, peer: EndpointId, addr: SocketAddr) {
|
||||
if let Ok(mut guard) = self.peer_addresses.write() {
|
||||
if let Ok(mut guard) = self.peer_addresses.manual.lock() {
|
||||
let addrs = guard.entry(peer).or_default();
|
||||
if !addrs.contains(&addr) {
|
||||
addrs.push(addr);
|
||||
@@ -466,7 +463,7 @@ impl TcpTlsTransport {
|
||||
|
||||
/// Replaces a bounded candidate set learned through an authenticated session.
|
||||
pub fn replace_peer_addrs(&self, peer: EndpointId, addresses: Vec<SocketAddr>) {
|
||||
if let Ok(mut peers) = self.peer_addresses.write() {
|
||||
if let Ok(mut peers) = self.peer_addresses.manual.lock() {
|
||||
if addresses.is_empty() {
|
||||
peers.remove(&peer);
|
||||
} else {
|
||||
@@ -487,11 +484,19 @@ impl TcpTlsTransport {
|
||||
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::clone(&self.server_config));
|
||||
let local_id = self.local_id;
|
||||
|
||||
while let Ok((socket, remote_addr)) = listener.accept().await {
|
||||
let mut handshakes = tokio::task::JoinSet::new();
|
||||
loop {
|
||||
let accepted = tokio::select! {
|
||||
_ = handshakes.join_next(), if !handshakes.is_empty() => continue,
|
||||
result = listener.accept(), if handshakes.len() < 64 => result,
|
||||
};
|
||||
let Ok((socket, remote_addr)) = accepted else {
|
||||
break;
|
||||
};
|
||||
let _ = socket.set_nodelay(true);
|
||||
let acceptor = acceptor.clone();
|
||||
let on_inbound = on_inbound.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
handshakes.spawn(tokio::time::timeout(Duration::from_secs(8), async move {
|
||||
let mut tls_stream = match acceptor.accept(socket).await {
|
||||
Ok(s) => s,
|
||||
Err(err) => {
|
||||
@@ -536,7 +541,7 @@ impl TcpTlsTransport {
|
||||
protocol: "tcp-tls".into(),
|
||||
link: Arc::new(link),
|
||||
});
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,92 +566,107 @@ impl PacketTransport for TcpTlsTransport {
|
||||
return Err(TransportError::Declined(protocol.to_string()));
|
||||
}
|
||||
|
||||
let target_addrs = {
|
||||
let guard = self
|
||||
.peer_addresses
|
||||
.read()
|
||||
.map_err(|_| TransportError::Other("lock poisoned".into()))?;
|
||||
guard.get(&peer).cloned().unwrap_or_default()
|
||||
};
|
||||
let addresses = self
|
||||
.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&(network, peer))
|
||||
.cloned()
|
||||
.unwrap_or_else(|| {
|
||||
self.peer_addresses
|
||||
.manual
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.get(&peer)
|
||||
.cloned()
|
||||
.unwrap_or_default()
|
||||
});
|
||||
dial_candidates(addresses, |socket, addr| async move {
|
||||
let client_config = make_client_config(peer)
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let connector = TlsConnector::from(client_config);
|
||||
|
||||
if target_addrs.is_empty() {
|
||||
return Err(TransportError::Unreachable(
|
||||
"no known TCP address for peer".into(),
|
||||
));
|
||||
}
|
||||
let server_name = rustls::pki_types::ServerName::try_from(self.sni.as_str())
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?
|
||||
.to_owned();
|
||||
|
||||
let mut connected_socket = None;
|
||||
let mut connected_addr = None;
|
||||
for addr in &target_addrs {
|
||||
if addr.ip().is_loopback() && addr.port() == self.listen_port {
|
||||
continue;
|
||||
let mut tls_stream = connector
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(format!("TLS handshake failed: {err}")))?;
|
||||
|
||||
// Send LinkHandshake (fixed 128 bytes)
|
||||
let msg = link_handshake_bytes(network, peer);
|
||||
let sig = self.identity.sign(&msg);
|
||||
let hello = LinkHandshake {
|
||||
network,
|
||||
client_id: self.local_id,
|
||||
signature: sig.to_bytes(),
|
||||
};
|
||||
let hello_bytes = hello.to_bytes();
|
||||
tls_stream
|
||||
.write_all(&hello_bytes)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
tls_stream
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
|
||||
// Read LinkAck (fixed 1 byte)
|
||||
let mut ack_buf = [0u8; LinkAck::LEN];
|
||||
tls_stream
|
||||
.read_exact(&mut ack_buf)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let ack = LinkAck::from_bytes(&ack_buf)
|
||||
.ok_or_else(|| TransportError::Other("invalid link ack".into()))?;
|
||||
|
||||
if !ack.accepted {
|
||||
return Err(TransportError::Declined("link declined".into()));
|
||||
}
|
||||
match tokio::time::timeout(Duration::from_secs(3), TcpStream::connect(*addr)).await
|
||||
{
|
||||
Ok(Ok(socket)) => {
|
||||
connected_socket = Some(socket);
|
||||
connected_addr = Some(*addr);
|
||||
break;
|
||||
}
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
|
||||
let (socket, addr) = match (connected_socket, connected_addr) {
|
||||
(Some(s), Some(a)) => (s, a),
|
||||
_ => {
|
||||
return Err(TransportError::Unreachable(
|
||||
"cannot connect to any TCP address for peer".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
|
||||
let client_config =
|
||||
make_client_config(peer).map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let connector = TlsConnector::from(client_config);
|
||||
|
||||
let server_name = rustls::pki_types::ServerName::try_from(self.sni.as_str())
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?
|
||||
.to_owned();
|
||||
|
||||
let mut tls_stream = connector
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(format!("TLS handshake failed: {err}")))?;
|
||||
|
||||
// Send LinkHandshake (fixed 128 bytes)
|
||||
let msg = link_handshake_bytes(network, peer);
|
||||
let sig = self.identity.sign(&msg);
|
||||
let hello = LinkHandshake {
|
||||
network,
|
||||
client_id: self.local_id,
|
||||
signature: sig.to_bytes(),
|
||||
};
|
||||
let hello_bytes = hello.to_bytes();
|
||||
tls_stream
|
||||
.write_all(&hello_bytes)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
tls_stream
|
||||
.flush()
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
|
||||
// Read LinkAck (fixed 1 byte)
|
||||
let mut ack_buf = [0u8; LinkAck::LEN];
|
||||
tls_stream
|
||||
.read_exact(&mut ack_buf)
|
||||
.await
|
||||
.map_err(|err| TransportError::Other(err.to_string()))?;
|
||||
let ack = LinkAck::from_bytes(&ack_buf)
|
||||
.ok_or_else(|| TransportError::Other("invalid link ack".into()))?;
|
||||
|
||||
if !ack.accepted {
|
||||
return Err(TransportError::Declined("link declined".into()));
|
||||
}
|
||||
|
||||
let link = TcpTlsLink::new(network, peer, tls_stream, addr.to_string());
|
||||
Ok(Arc::new(link) as SharedLink)
|
||||
let link = TcpTlsLink::new(network, peer, tls_stream, addr.to_string());
|
||||
Ok(Arc::new(link) as SharedLink)
|
||||
})
|
||||
.await
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl TcpEndpoint for TcpTlsTransport {
|
||||
fn wire_version(&self) -> u16 {
|
||||
crate::TCP_TLS_VERSION
|
||||
}
|
||||
fn bound_port(&self) -> u16 {
|
||||
self.listen_port
|
||||
}
|
||||
fn set_pair_addresses(
|
||||
&self,
|
||||
network: NetworkId,
|
||||
peer: EndpointId,
|
||||
addresses: Option<Vec<SocketAddr>>,
|
||||
) {
|
||||
let mut pairs = self
|
||||
.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner());
|
||||
match addresses {
|
||||
Some(addresses) => {
|
||||
pairs.insert((network, peer), addresses);
|
||||
}
|
||||
None => {
|
||||
pairs.remove(&(network, peer));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn clear_network(&self, network: NetworkId) {
|
||||
self.peer_addresses
|
||||
.pairs
|
||||
.lock()
|
||||
.unwrap_or_else(|p| p.into_inner())
|
||||
.retain(|(n, _), _| *n != network);
|
||||
}
|
||||
}
|
||||
@@ -51,3 +51,28 @@ fn test_make_client_and_server_config() {
|
||||
let client_config = tsunagi_tcp_tls::cert::make_client_config(peer_id);
|
||||
assert!(client_config.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrelated_certificate_fields_cannot_satisfy_the_identity_pin() {
|
||||
let expected = DeviceIdentity::generate().endpoint_id();
|
||||
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap();
|
||||
let mut params = rcgen::CertificateParams::new(vec!["peer.invalid".into()]).unwrap();
|
||||
params
|
||||
.custom_extensions
|
||||
.push(rcgen::CustomExtension::from_oid_content(
|
||||
&[1, 3, 6, 1, 4, 1, 55555, 1],
|
||||
expected.as_bytes().to_vec(),
|
||||
));
|
||||
let cert = params.self_signed(&key).unwrap();
|
||||
assert!(
|
||||
PinnedEndpointVerifier::new(expected)
|
||||
.verify_server_cert(
|
||||
cert.der(),
|
||||
&[],
|
||||
&ServerName::try_from("peer.invalid").unwrap(),
|
||||
&[],
|
||||
UnixTime::now()
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.4"
|
||||
version = "1.0.11"
|
||||
description = "Tray application to manage a running tsunagi agent."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -16,7 +16,7 @@ tsunagi-ui = { path = "../tsunagi-ui" }
|
||||
# The agent control client and the report types: the GUI is a thin client over
|
||||
# the same local control interface the CLI uses, so it reuses these directly
|
||||
# and never re-implements the protocol.
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.4" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
||||
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
|
||||
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
|
||||
|
||||
@@ -9,16 +9,13 @@
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
use std::time::Instant;
|
||||
|
||||
use eframe::egui;
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use tsunagi::ipc;
|
||||
|
||||
/// How often the worker refreshes status while idle.
|
||||
const POLL_INTERVAL: Duration = Duration::from_secs(2);
|
||||
|
||||
use tsunagi_ui::client::Client;
|
||||
pub(crate) use tsunagi_ui::client::{Command, Snapshot, VipSaveResult};
|
||||
|
||||
@@ -32,6 +29,7 @@ impl Client for AgentClient {
|
||||
}
|
||||
|
||||
/// Handle the UI holds: send commands, read the latest snapshot.
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct AgentClient {
|
||||
tx: mpsc::UnboundedSender<Command>,
|
||||
shared: Arc<Mutex<Snapshot>>,
|
||||
@@ -105,12 +103,19 @@ async fn worker(
|
||||
ctx: egui::Context,
|
||||
) {
|
||||
refresh(&shared, &ctx).await;
|
||||
let mut tick = tokio::time::interval(POLL_INTERVAL);
|
||||
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
|
||||
|
||||
loop {
|
||||
let interval = {
|
||||
let snapshot = lock(&shared);
|
||||
tsunagi_ui::client::status_poll_interval(
|
||||
snapshot
|
||||
.status
|
||||
.as_ref()
|
||||
.and_then(|s| s.as_ref().ok())
|
||||
.map(Arc::as_ref),
|
||||
)
|
||||
};
|
||||
tokio::select! {
|
||||
_ = tick.tick() => {
|
||||
_ = tokio::time::sleep(interval) => {
|
||||
refresh(&shared, &ctx).await;
|
||||
}
|
||||
command = rx.recv() => {
|
||||
@@ -118,7 +123,7 @@ async fn worker(
|
||||
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
|
||||
refresh(&shared, &ctx).await;
|
||||
lock(&shared).busy = false;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -141,7 +146,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
|
||||
guard.at = Some(Instant::now());
|
||||
guard.socket = socket;
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Runs one command and records its outcome.
|
||||
@@ -153,7 +158,7 @@ async fn run(
|
||||
ctx: &egui::Context,
|
||||
) {
|
||||
lock(shared).busy = true;
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
|
||||
let outcome: Result<String, String> = match command {
|
||||
Command::SaveVip {
|
||||
@@ -245,6 +250,16 @@ async fn run(
|
||||
})
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StartSpeedTest { network_id, peer } => {
|
||||
ipc::start_speed_test(socket, &network_id, peer.as_deref(), false)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string())
|
||||
}
|
||||
Command::StopSpeedTest { network_id } => ipc::stop_speed_test(socket, &network_id)
|
||||
.await
|
||||
.map(|_| String::new())
|
||||
.map_err(|err| err.to_string()),
|
||||
Command::Join { name, secret } => ipc::join_network(socket, &name, &secret)
|
||||
.await
|
||||
.map(|report| {
|
||||
@@ -288,7 +303,7 @@ async fn run(
|
||||
Some(outcome)
|
||||
};
|
||||
}
|
||||
ctx.request_repaint();
|
||||
ctx.request_repaint_of(egui::ViewportId::ROOT);
|
||||
}
|
||||
|
||||
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
|
||||
|
||||
Loaded 100 of 151 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user