Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f60c11fc20 | ||
|
|
87fa83e482 | ||
|
|
a966152143 | ||
|
|
6e71d8cf8c | ||
|
|
16d7f82af5 | ||
|
|
68f19d1758 | ||
|
|
8e0cfc97ac | ||
|
|
7b83aec3be | ||
|
|
21de427c62 | ||
|
|
a1da4bf498 | ||
|
|
9920d4c10f |
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
|
||||
@@ -65,7 +65,8 @@ jobs:
|
||||
- name: Verify separate forwarding and local egress in Linux namespaces
|
||||
if: runner.os == 'Linux'
|
||||
shell: bash
|
||||
run: sudo -n -- "$TEST_BINARY" --ignored --exact "$TEST_NAME" --nocapture
|
||||
# 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
|
||||
|
||||
Generated
+71
-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.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"anstream",
|
||||
"anstyle",
|
||||
@@ -6320,7 +6324,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"egui",
|
||||
@@ -6344,7 +6348,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"iroh",
|
||||
@@ -6359,7 +6363,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-core"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"arc-swap",
|
||||
"bytes",
|
||||
@@ -6404,17 +6408,35 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
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"
|
||||
@@ -6425,9 +6447,23 @@ dependencies = [
|
||||
"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.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"caps",
|
||||
@@ -6437,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.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"eframe",
|
||||
"egui-phosphor",
|
||||
@@ -6463,7 +6501,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"egui",
|
||||
"egui-phosphor",
|
||||
@@ -6474,9 +6512,29 @@ dependencies = [
|
||||
"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.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
@@ -6496,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.9"
|
||||
version = "1.0.12"
|
||||
dependencies = [
|
||||
"boringtun",
|
||||
"bytes",
|
||||
|
||||
@@ -127,11 +127,26 @@ status and recent traffic. Expand it to see who is using this device for interne
|
||||
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 native `tcp-tls` listener prefers TCP 9442. To use all three
|
||||
on a public server, allow inbound TCP 9442–9444. For a second agent on the
|
||||
same host, set its listeners explicitly, for example
|
||||
`tsng up -o tcp-tls:port=10442 -o vless-xhttp:port=10443 -o ss2022:port=10444`,
|
||||
and allow TCP 10442–10444 for that instance.
|
||||
|
||||
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
|
||||
@@ -144,12 +159,17 @@ 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.
|
||||
through its current encrypted mesh path. A test becomes available after a
|
||||
round trip to the peer succeeds over that path, directly or through relay
|
||||
members. The control connection coordinates the test and returns its results.
|
||||
Only packets received over the data path count towards the rate 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
|
||||
@@ -168,9 +188,12 @@ initiator. These ceilings count probe IP packets before tunnel overhead.
|
||||
Adjacent peers need a common external transport at the same wire version.
|
||||
Peers that both support link comparison probe another mutually enabled transport
|
||||
while traffic continues on the current one. They can switch to a faster healthy link.
|
||||
`tsng status` and the tray show the direct data link's measured RTT separately
|
||||
from the control connection's RTT. A mesh relay's first-hop RTT cannot measure
|
||||
the round trip to the destination.
|
||||
`tsng status` and Devices show the round trip of an encrypted probe to the
|
||||
destination, including any mesh relay hops. The previous measurement stays
|
||||
visible while the next probe is in flight. Losing the route or missing two
|
||||
consecutive probes clears the measurement. Devices shows **Ready** or **Idle**
|
||||
only while the data path is confirmed and the tunnel has a usable session key.
|
||||
Control RTT is shown separately.
|
||||
Selection applies to this device's incoming and outgoing data links; control and
|
||||
discovery are independent. A relay's next hop may use a different transport.
|
||||
Every pair uses one internal WireGuard cipher, hidden from these controls.
|
||||
@@ -206,10 +229,15 @@ address/port pair and repeated ICMP echoes for an address pair into one row. Sel
|
||||
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. Select a row
|
||||
to see its packet counts. The monitor records header metadata and counters only.
|
||||
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
|
||||
|
||||
@@ -30,6 +30,8 @@ Rotate the phone to select a network on the left and see its settings on the rig
|
||||
|
||||
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.
|
||||
|
||||
## Check two networks on an emulator
|
||||
|
||||
@@ -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.9')
|
||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.12')
|
||||
ndk { abiFilters abi }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-android"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
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.9" }
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.12" }
|
||||
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,
|
||||
@@ -81,7 +82,7 @@ extern "system" fn Java_cy_hexor_tsunagi_Native_surface(
|
||||
ctx,
|
||||
ui,
|
||||
events: Vec::new(),
|
||||
primary: None,
|
||||
touch: TouchInput::default(),
|
||||
start: Instant::now(),
|
||||
ime: -1,
|
||||
exit_active: false,
|
||||
@@ -104,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()
|
||||
};
|
||||
@@ -122,6 +123,9 @@ 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));
|
||||
@@ -201,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)]
|
||||
|
||||
@@ -9,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;
|
||||
@@ -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;
|
||||
@@ -302,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()
|
||||
|
||||
@@ -449,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()
|
||||
@@ -487,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;
|
||||
}
|
||||
|
||||
@@ -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]
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -493,7 +493,7 @@ impl Phone {
|
||||
if ui.button(format!("{} Paste secret", icon::CLIPBOARD)).clicked() {system = Some(SystemAction::PasteSecret);}
|
||||
}
|
||||
Page::Exits => {
|
||||
if let Some(choice) = devices::choose_exit_from_networks(ui, &report.networks, &report.endpoint_id) {
|
||||
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() {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-awg"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
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.9"
|
||||
version = "1.0.12"
|
||||
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"]
|
||||
|
||||
@@ -40,6 +40,7 @@ use super::status::{
|
||||
};
|
||||
use sync::{Changes, SyncKey};
|
||||
|
||||
mod reverse;
|
||||
mod selection;
|
||||
mod sync;
|
||||
|
||||
@@ -354,6 +355,14 @@ fn data_link_backoff(failures: u32) -> Duration {
|
||||
Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct PendingSpeedStart {
|
||||
peer: EndpointId,
|
||||
session: u64,
|
||||
request: tsunagi_speedtest::Start,
|
||||
received: Instant,
|
||||
}
|
||||
|
||||
struct Runtime {
|
||||
discovery_worker: Option<DiscoveryWorker>,
|
||||
discovery_candidates: mpsc::Receiver<Candidate>,
|
||||
@@ -379,6 +388,8 @@ struct Runtime {
|
||||
/// peer, which outlives any particular path.
|
||||
links: HashMap<(EndpointId, String), Arc<HealthLink>>,
|
||||
pending_health: HashMap<(EndpointId, String), HealthSettings>,
|
||||
// The initiator can finish its first data echo just before our own.
|
||||
pending_speed: Option<PendingSpeedStart>,
|
||||
comparisons: HashMap<EndpointId, selection::Schedule>,
|
||||
last_failed_protocol: HashMap<EndpointId, String>,
|
||||
/// Every data link of this network, and what is reached through what.
|
||||
@@ -407,6 +418,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>,
|
||||
@@ -507,6 +519,7 @@ impl Runtime {
|
||||
dial_results_rx,
|
||||
links: HashMap::new(),
|
||||
pending_health: HashMap::new(),
|
||||
pending_speed: None,
|
||||
comparisons: HashMap::new(),
|
||||
last_failed_protocol: HashMap::new(),
|
||||
hub,
|
||||
@@ -515,6 +528,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,
|
||||
@@ -556,10 +570,13 @@ impl Runtime {
|
||||
// Long discovery intervals must not let live transit edges expire.
|
||||
let mut reach_refresh = tokio::time::interval(REACH_EXPIRY / 3);
|
||||
reach_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
let mut speed_refresh = tokio::time::interval(Duration::from_millis(50));
|
||||
speed_refresh.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.shutdown.wait() => break,
|
||||
_ = speed_refresh.tick(), if self.pending_speed.is_some() => self.retry_speed_start(),
|
||||
_ = roster.changed() => self.sync_exit_use(),
|
||||
_ = reach_refresh.tick(), if self.params.discovery_interval > REACH_EXPIRY / 3 => self.announce_reach(false),
|
||||
_ = self.hub.changed() => {
|
||||
@@ -2086,12 +2103,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;
|
||||
@@ -2157,8 +2174,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;
|
||||
}
|
||||
@@ -2206,6 +2222,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();
|
||||
}
|
||||
@@ -2214,49 +2231,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
|
||||
@@ -2529,6 +2554,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);
|
||||
@@ -2586,6 +2622,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();
|
||||
@@ -2675,6 +2726,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| {
|
||||
@@ -2832,6 +2884,14 @@ 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());
|
||||
}
|
||||
@@ -3011,19 +3071,36 @@ impl Runtime {
|
||||
&& 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);
|
||||
match message {
|
||||
tsunagi_speedtest::Control::Start(start)
|
||||
if self.pending_speed.is_none()
|
||||
&& self.overlay_rtt(peer).is_none()
|
||||
&& self.data_error(session).is_none() =>
|
||||
{
|
||||
self.pending_speed = Some(PendingSpeedStart {
|
||||
peer,
|
||||
session: session.id,
|
||||
request: start,
|
||||
received: Instant::now(),
|
||||
});
|
||||
}
|
||||
tsunagi_speedtest::Control::Cancel { id }
|
||||
if self
|
||||
.pending_speed
|
||||
.is_some_and(|p| p.peer == peer && p.request.id == id) =>
|
||||
{
|
||||
self.pending_speed = None;
|
||||
}
|
||||
_ => self.deliver_speed_control(peer, message),
|
||||
}
|
||||
}
|
||||
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;
|
||||
@@ -3152,6 +3229,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
|
||||
@@ -3162,7 +3247,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(())
|
||||
},
|
||||
@@ -3281,6 +3366,50 @@ impl Runtime {
|
||||
})
|
||||
}
|
||||
|
||||
fn retry_speed_start(&mut self) {
|
||||
let Some(pending) = self.pending_speed else {
|
||||
return;
|
||||
};
|
||||
let Some(session) = self.sessions.get(&pending.peer).filter(|s| {
|
||||
s.id == pending.session
|
||||
&& super::speed::supported(&s.capabilities)
|
||||
&& super::speed::supported(&self.local_capabilities)
|
||||
}) else {
|
||||
self.pending_speed = None;
|
||||
return;
|
||||
};
|
||||
// Allow one ordinary three-second echo timeout and the next probe tick.
|
||||
if pending.received.elapsed() < Duration::from_millis(3500)
|
||||
&& self.data_error(session).is_none()
|
||||
&& self.overlay_rtt(pending.peer).is_none()
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.pending_speed = None;
|
||||
self.deliver_speed_control(
|
||||
pending.peer,
|
||||
tsunagi_speedtest::Control::Start(pending.request),
|
||||
);
|
||||
}
|
||||
|
||||
fn deliver_speed_control(&mut self, peer: EndpointId, message: tsunagi_speedtest::Control) {
|
||||
if let Some(inner) = self.params.agent.upgrade()
|
||||
&& let Some(reply) =
|
||||
super::speed::receive_control(&inner, self.network_id, peer, message, || {
|
||||
self.overlay_rtt(peer)
|
||||
})
|
||||
{
|
||||
let _ = self.send_to(peer, reply);
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay_rtt(&self, peer: EndpointId) -> Option<Duration> {
|
||||
if self.tunnel_errors.contains_key(&peer) || !self.hub.reachable(peer) {
|
||||
return None;
|
||||
}
|
||||
self.params.routes.vips.peer_rtt(self.network_id, peer)
|
||||
}
|
||||
|
||||
fn data_error(&self, session: &Session) -> Option<String> {
|
||||
if self.params.carriers.is_empty() {
|
||||
return Some(super::DATA_DISABLED.into());
|
||||
@@ -3318,6 +3447,7 @@ impl Runtime {
|
||||
.iter()
|
||||
.filter(|cap| {
|
||||
cap.enabled
|
||||
&& cap.protocol != reverse::PROTOCOL
|
||||
&& cap.protocol != selection::PROTOCOL
|
||||
&& self
|
||||
.params
|
||||
@@ -3354,9 +3484,11 @@ impl Runtime {
|
||||
.next()
|
||||
.and_then(|kind| self.links.get(&(session.peer, kind)));
|
||||
PeerStatus {
|
||||
data_rtt: selected
|
||||
.and_then(|link| link.quality())
|
||||
.map(|quality| quality.rtt),
|
||||
data_rtt: if self.params.interface.is_some() && self.params.tunnel.is_some() {
|
||||
self.overlay_rtt(session.peer)
|
||||
} else {
|
||||
selected.and_then(|link| link.quality()).map(|q| q.rtt)
|
||||
},
|
||||
data_transport_detail: selected.map(|link| link.path_description()),
|
||||
broadcast: session.broadcast,
|
||||
exit_node: session.exit_node,
|
||||
|
||||
@@ -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()),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -126,7 +126,7 @@ impl SpeedTests {
|
||||
.collect(),
|
||||
capable: peers
|
||||
.iter()
|
||||
.filter(|p| enabled && supported(&p.capabilities))
|
||||
.filter(|p| enabled && p.has_confirmed_data_path() && supported(&p.capabilities))
|
||||
.map(|p| p.endpoint_id.to_string())
|
||||
.collect(),
|
||||
}
|
||||
@@ -221,7 +221,7 @@ fn config(
|
||||
key: Key,
|
||||
id: u64,
|
||||
bytes: u32,
|
||||
rtt: Option<Duration>,
|
||||
rtt: Duration,
|
||||
) -> Option<(wire::Config, DiagnosticPeer)> {
|
||||
let addresses = inner.routes.diagnostic_peer(key.0, key.1)?;
|
||||
let ceiling = if inner.speed.metered.load(Ordering::Relaxed) {
|
||||
@@ -235,7 +235,7 @@ fn config(
|
||||
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)),
|
||||
rtt,
|
||||
};
|
||||
Some((cfg, addresses))
|
||||
}
|
||||
@@ -257,7 +257,11 @@ pub(super) fn receive_control(
|
||||
{
|
||||
return envelope(&wire::Control::Busy { id });
|
||||
}
|
||||
let (cfg, addresses) = config(inner, key, id, request.byte_limit, rtt())?;
|
||||
let Some((cfg, addresses)) =
|
||||
rtt().and_then(|rtt| config(inner, key, id, request.byte_limit, rtt))
|
||||
else {
|
||||
return envelope(&wire::Control::Cancel { id });
|
||||
};
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::respond(cfg, request);
|
||||
inner.speed.active.store(Some(Arc::new(Channel {
|
||||
@@ -430,10 +434,18 @@ impl Agent {
|
||||
.collect();
|
||||
if targets.is_empty() {
|
||||
return Err(Error::SpeedTest(
|
||||
if peer.is_some() {
|
||||
"Peer is offline or does not support this speed-test version"
|
||||
if let Some(target) = peer {
|
||||
if status
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.endpoint_id == target && supported(&p.capabilities))
|
||||
{
|
||||
"No confirmed data path to this peer"
|
||||
} else {
|
||||
"Peer is offline or does not support this speed-test version"
|
||||
}
|
||||
} else {
|
||||
"No online exit nodes support speed tests in this network"
|
||||
"No compatible exit nodes with a confirmed data path in this network"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
@@ -522,7 +534,7 @@ impl Agent {
|
||||
Some((_, update, started)) => update_report(report, update, started),
|
||||
None => {
|
||||
report.phase = SpeedPhase::Failed(
|
||||
"Peer is no longer eligible or its overlay address is unavailable"
|
||||
"Peer no longer has a confirmed data path or is no longer eligible"
|
||||
.into(),
|
||||
)
|
||||
}
|
||||
@@ -577,10 +589,12 @@ async fn run_outgoing(
|
||||
};
|
||||
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)
|
||||
p.endpoint_id == key.1
|
||||
&& (!exits_only || p.exit_node)
|
||||
&& status.speed.capable.contains(&p.endpoint_id.to_string())
|
||||
})?;
|
||||
let id = rand::random();
|
||||
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt.or(peer.rtt))?;
|
||||
let (cfg, addresses) = config(inner, key, id, limit, peer.data_rtt?)?;
|
||||
let limit = cfg.byte_limit;
|
||||
let (handle, session) = wire::initiate(cfg);
|
||||
let io = TestIo::new(inner, key, Some(generation));
|
||||
|
||||
@@ -179,7 +179,8 @@ pub struct PeerStatus {
|
||||
pub transport: TransportKind,
|
||||
/// RTT of the selected path, when iroh reported one.
|
||||
pub rtt: Option<Duration>,
|
||||
/// Recent RTT of the selected direct data link, measured by authenticated probes.
|
||||
/// Round trip to this peer over encrypted overlay data, including relay hops.
|
||||
/// Carrier-only agents report their selected physical link's round trip.
|
||||
pub data_rtt: Option<Duration>,
|
||||
/// The selected direct data carrier's own description of its underlying path.
|
||||
pub data_transport_detail: Option<String>,
|
||||
@@ -197,6 +198,15 @@ pub struct PeerStatus {
|
||||
pub data_path: DataPath,
|
||||
}
|
||||
|
||||
impl PeerStatus {
|
||||
/// A usable route with a successful data round trip to this peer.
|
||||
pub fn has_confirmed_data_path(&self) -> bool {
|
||||
!matches!(self.data_path, DataPath::None)
|
||||
&& self.data_rtt.is_some()
|
||||
&& self.data_error.is_none()
|
||||
}
|
||||
}
|
||||
|
||||
/// Counters scoped to one logical network.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct NetworkMetrics {
|
||||
|
||||
@@ -11,6 +11,8 @@
|
||||
//! the encrypted inner bytes without entering an IP plugin or the TUN.
|
||||
//! Data-plane failure never stops control sessions or discovery.
|
||||
|
||||
pub use crate::vip::router::is_path_probe;
|
||||
|
||||
pub mod relay;
|
||||
pub mod routing;
|
||||
pub mod transport;
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -739,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.
|
||||
@@ -886,7 +890,7 @@ pub struct PeerReport {
|
||||
pub transport: String,
|
||||
/// Round-trip time of the control connection in milliseconds.
|
||||
pub rtt_ms: Option<u64>,
|
||||
/// Fresh median RTT of the selected direct data link, in milliseconds.
|
||||
/// Measured round trip to the peer over its data path, in milliseconds.
|
||||
pub data_rtt_ms: Option<u64>,
|
||||
/// Underlying path reported by the selected direct data carrier.
|
||||
pub data_transport_detail: Option<String>,
|
||||
@@ -985,8 +989,7 @@ pub struct OverlayPeerReport {
|
||||
pub address: Option<String>,
|
||||
/// 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.
|
||||
/// An established tunnel has no recent or pending application traffic.
|
||||
#[serde(default)]
|
||||
pub idle: bool,
|
||||
/// Packets encrypted and sent to this peer.
|
||||
@@ -1214,7 +1217,7 @@ 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', 29]);
|
||||
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.
|
||||
///
|
||||
|
||||
@@ -10,7 +10,7 @@ pub struct SpeedReport {
|
||||
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.
|
||||
/// Compatible peers with a confirmed encrypted data path for a test.
|
||||
pub capable: Vec<String>,
|
||||
}
|
||||
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -669,6 +669,8 @@ fn serving_an_established_flow_while_switching_the_local_exit() {
|
||||
.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!(
|
||||
|
||||
@@ -66,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.
|
||||
|
||||
@@ -14,7 +14,7 @@ helper="$directory/offer-v1"
|
||||
/bin/chmod 0755 "$directory"
|
||||
tmp=$(/usr/bin/mktemp -d "$directory/.install.XXXXXXXX")
|
||||
trap '/bin/rm -rf "$tmp"' EXIT
|
||||
printf '%s\n' "$helper_body" > "$tmp/offer"
|
||||
printf '%s' "$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"
|
||||
|
||||
@@ -125,7 +125,7 @@ if [ ! -f "$record" ]; then
|
||||
fi
|
||||
if ! /sbin/pfctl -q -a "$anchor" -f - <<RULES
|
||||
nat on $out inet from $range to any tagged $tag -> ($out)
|
||||
pass out quick on $iface route-to $via inet from any to any tagged $tag no state
|
||||
pass 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
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
//! ```text
|
||||
//! 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 any tagged <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)
|
||||
//! ```
|
||||
//!
|
||||
@@ -88,6 +88,15 @@ use super::macos_authorization::{macos_exit_authorization_uid, macos_exit_needs_
|
||||
|
||||
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 {
|
||||
@@ -133,7 +142,11 @@ pub(super) fn run_tool(tool: Tool, args: &[String], stdin: Option<&str>) -> Ran
|
||||
use std::process::{Command, Stdio};
|
||||
|
||||
let mut command = if tool == Tool::OfferHelper {
|
||||
if !std::path::Path::new(OFFER_HELPER).is_file() {
|
||||
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");
|
||||
@@ -415,23 +428,30 @@ fn pf_rules(
|
||||
from any to any flags any tagged {tag} keep state (if-bound)"
|
||||
));
|
||||
}
|
||||
for range in offer {
|
||||
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 {range} to any tagged {tag} -> ({out})"
|
||||
"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} tag {tag} no state"
|
||||
"pass in quick on {interface} inet from {members} to ! {members} tag {tag} no state"
|
||||
));
|
||||
}
|
||||
if !offer.is_empty() {
|
||||
let tag = format!("tsng_forward_{interface}");
|
||||
// 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 any to any tagged {tag} no state"
|
||||
"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.
|
||||
@@ -1166,7 +1186,7 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
text,
|
||||
"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 any to any tagged tsng_forward_utun5 no state\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"
|
||||
);
|
||||
@@ -1174,6 +1194,32 @@ destination: default\n\
|
||||
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()];
|
||||
@@ -1289,7 +1335,7 @@ destination: default\n\
|
||||
assert_eq!(
|
||||
fake.stdins.borrow()[0],
|
||||
"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 any to any tagged tsng_forward_utun5 no state\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"
|
||||
);
|
||||
|
||||
@@ -146,6 +146,25 @@ fn privileged_helper_accepts_only_a_granted_subnet_configured_on_the_utun() {
|
||||
);
|
||||
}
|
||||
|
||||
#[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();
|
||||
|
||||
@@ -295,8 +295,7 @@ impl Interface {
|
||||
_=interval.tick()=>{
|
||||
let (probes,jobs)=routes.vips.tick(routes.vips.check_capacity().saturating_sub(checks.len()));
|
||||
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();}
|
||||
carrier.carry(route,packet);
|
||||
}
|
||||
for job in jobs {
|
||||
let factory = Arc::clone(&factory);
|
||||
@@ -1025,22 +1024,8 @@ 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, 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.
|
||||
let tx = self.routes.traffic.packet(
|
||||
route.network,
|
||||
route.peer,
|
||||
Direction::Tx,
|
||||
&packet,
|
||||
|| Role::Vip,
|
||||
);
|
||||
if self.carrier.carry(route, packet) {
|
||||
tx.record();
|
||||
}
|
||||
// Only an authenticated RTT request generates an immediate peer reply here.
|
||||
self.carrier.carry(route, reply);
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::Local(translated) => {
|
||||
@@ -1064,14 +1049,9 @@ impl Interface {
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
crate::vip::router::Decision::ProbeReceived => {
|
||||
self.routes
|
||||
.traffic
|
||||
.packet(network, peer, Direction::Rx, &packet, || Role::Vip)
|
||||
.record();
|
||||
crate::vip::router::Decision::ProbeReceived | crate::vip::router::Decision::Drop => {
|
||||
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)
|
||||
|
||||
@@ -144,30 +144,30 @@ impl VipRouter {
|
||||
) {
|
||||
let mut s = self.lock();
|
||||
s.limits = limits.clone();
|
||||
let source_changed = s
|
||||
.networks
|
||||
.get(&network)
|
||||
.is_none_or(|n| n.address != address);
|
||||
let mut present = HashSet::new();
|
||||
for (peer, address, available) in peers {
|
||||
present.insert(peer);
|
||||
let p = s.paths.entry((network, peer)).or_default();
|
||||
if p.address != Some(address) {
|
||||
p.rtt = None;
|
||||
p.heard = None;
|
||||
p.pending = None;
|
||||
if source_changed || p.address != Some(address) || p.available != available {
|
||||
*p = Path::default();
|
||||
}
|
||||
p.address = Some(address);
|
||||
p.available = available;
|
||||
}
|
||||
for ((n, peer), p) in &mut s.paths {
|
||||
if *n == network && !present.contains(peer) {
|
||||
p.available = false;
|
||||
}
|
||||
}
|
||||
if let Some(address) = address {
|
||||
present.insert(local);
|
||||
let p = s.paths.entry((network, local)).or_default();
|
||||
p.address = Some(address);
|
||||
p.available = true;
|
||||
p.rtt = Some(0);
|
||||
p.heard = Some(Instant::now());
|
||||
}
|
||||
s.paths
|
||||
.retain(|(n, peer), _| *n != network || present.contains(peer));
|
||||
s.networks.insert(
|
||||
network,
|
||||
Network {
|
||||
@@ -177,6 +177,16 @@ impl VipRouter {
|
||||
},
|
||||
);
|
||||
}
|
||||
/// Last confirmed round trip through both endpoints' encrypted packet channels.
|
||||
pub fn peer_rtt(&self, network: NetworkId, peer: EndpointId) -> Option<Duration> {
|
||||
let s = self.lock();
|
||||
s.paths
|
||||
.get(&(network, peer))
|
||||
.filter(|p| p.available)?
|
||||
.rtt
|
||||
.map(Duration::from_micros)
|
||||
}
|
||||
|
||||
pub fn remove_network(&self, network: NetworkId) {
|
||||
let mut s = self.lock();
|
||||
s.networks.remove(&network);
|
||||
@@ -342,6 +352,47 @@ impl VipRouter {
|
||||
let live: HashSet<_> = s.flows.keys().copied().collect();
|
||||
s.reverse.retain(|_, t| live.contains(t));
|
||||
let mut probes = Vec::new();
|
||||
let State {
|
||||
paths,
|
||||
networks,
|
||||
sequence,
|
||||
..
|
||||
} = &mut *s;
|
||||
for (&(network, peer), path) in paths {
|
||||
let Some(net) = networks.get(&network) else {
|
||||
continue;
|
||||
};
|
||||
let (Some(source), Some(address)) = (net.address, path.address) else {
|
||||
continue;
|
||||
};
|
||||
if !path.available || peer == net.local {
|
||||
continue;
|
||||
}
|
||||
if path
|
||||
.pending
|
||||
.is_some_and(|(_, at)| now.duration_since(at) >= Duration::from_secs(3))
|
||||
{
|
||||
path.pending = None;
|
||||
path.misses = path.misses.saturating_add(1);
|
||||
if path.misses >= 2 {
|
||||
path.rtt = None;
|
||||
path.heard = None;
|
||||
}
|
||||
}
|
||||
if path.pending.is_none()
|
||||
&& path
|
||||
.last_probe
|
||||
.is_none_or(|at| now.duration_since(at) >= Duration::from_secs(1))
|
||||
{
|
||||
*sequence = sequence.wrapping_add(1);
|
||||
path.pending = Some((*sequence, now));
|
||||
path.last_probe = Some(now);
|
||||
probes.push((
|
||||
Route { network, peer },
|
||||
probe(source, address, 1, *sequence),
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut jobs = Vec::new();
|
||||
let mut targets = BTreeMap::new();
|
||||
for (n, net) in &s.networks {
|
||||
@@ -366,37 +417,10 @@ impl VipRouter {
|
||||
let Some(net) = s.networks.get(&network) else {
|
||||
continue;
|
||||
};
|
||||
let (local, source) = (net.local, net.address);
|
||||
let sequence = s.sequence.wrapping_add(1);
|
||||
s.sequence = sequence;
|
||||
let Some(path) = s.paths.get_mut(&(network, peer)) else {
|
||||
let source = net.address;
|
||||
let Some(address) = s.paths.get(&(network, peer)).and_then(|p| p.address) else {
|
||||
continue;
|
||||
};
|
||||
let Some(address) = path.address else {
|
||||
continue;
|
||||
};
|
||||
if peer == local {
|
||||
path.rtt = Some(0);
|
||||
path.heard = Some(now);
|
||||
} else if path.available {
|
||||
if path
|
||||
.pending
|
||||
.is_some_and(|(_, at)| now.duration_since(at) >= Duration::from_secs(3))
|
||||
{
|
||||
path.pending = None;
|
||||
path.misses = path.misses.saturating_add(1);
|
||||
}
|
||||
if path.pending.is_none()
|
||||
&& path
|
||||
.last_probe
|
||||
.is_none_or(|at| now.duration_since(at) >= Duration::from_secs(1))
|
||||
&& let Some(source) = source
|
||||
{
|
||||
path.pending = Some((sequence, now));
|
||||
path.last_probe = Some(now);
|
||||
probes.push((Route { network, peer }, probe(source, address, 1, sequence)));
|
||||
}
|
||||
}
|
||||
for (l, b) in listeners {
|
||||
let key = (network, peer, address, l.protocol, b.port);
|
||||
wanted_checks.insert(key);
|
||||
@@ -759,28 +783,32 @@ impl VipRouter {
|
||||
let Some(source) = net.address else {
|
||||
return Decision::Drop;
|
||||
};
|
||||
let Some(path) = s.paths.get_mut(&(network, peer)) else {
|
||||
return Decision::Drop;
|
||||
};
|
||||
let Some(remote) = path.address else {
|
||||
return Decision::Drop;
|
||||
};
|
||||
if packet::addresses(&packet) != Some((remote, source)) {
|
||||
return Decision::Drop;
|
||||
}
|
||||
if kind == 1 {
|
||||
let Some((_, destination)) = packet::addresses(&packet).map(|(a, b)| (b, a)) else {
|
||||
return Decision::Drop;
|
||||
};
|
||||
return Decision::Send(
|
||||
Route { network, peer },
|
||||
probe(source, destination, 2, sequence),
|
||||
);
|
||||
return Decision::Send(Route { network, peer }, probe(source, remote, 2, sequence));
|
||||
}
|
||||
if kind == 2
|
||||
&& let Some(p) = s.paths.get_mut(&(network, peer))
|
||||
&& let Some((expected, at)) = p.pending
|
||||
&& path.available
|
||||
&& let Some((expected, at)) = path.pending
|
||||
&& expected == sequence
|
||||
&& at.elapsed() < Duration::from_secs(3)
|
||||
{
|
||||
let rtt = at.elapsed().as_micros().min(u128::from(u64::MAX)) as u64;
|
||||
p.rtt = Some(
|
||||
p.rtt
|
||||
path.rtt = Some(
|
||||
path.rtt
|
||||
.map_or(rtt, |old| old.saturating_mul(7).saturating_add(rtt) / 8),
|
||||
);
|
||||
p.heard = Some(Instant::now());
|
||||
p.pending = None;
|
||||
p.misses = 0;
|
||||
path.heard = Some(Instant::now());
|
||||
path.pending = None;
|
||||
path.misses = 0;
|
||||
return Decision::ProbeReceived;
|
||||
}
|
||||
return Decision::Drop;
|
||||
@@ -981,15 +1009,18 @@ fn probe(src: Ipv4Addr, dst: Ipv4Addr, kind: u8, sequence: u64) -> Bytes {
|
||||
p[10..12].copy_from_slice(&c.to_be_bytes());
|
||||
Bytes::from(p)
|
||||
}
|
||||
/// Recognizes the reserved encrypted overlay echo used to measure peer RTT.
|
||||
pub fn is_path_probe(p: &[u8]) -> bool {
|
||||
p.len() == 45 && p[9] == 253 && &p[20..36] == PROBE && packet::header(p) == Some(20)
|
||||
}
|
||||
|
||||
fn parse_probe(p: &[u8]) -> Option<(u8, u64)> {
|
||||
(packet::header(p) == Some(20) && p.len() == 45 && p[9] == 253 && &p[20..36] == PROBE).then(
|
||||
|| {
|
||||
(
|
||||
p[36],
|
||||
u64::from_be_bytes([p[37], p[38], p[39], p[40], p[41], p[42], p[43], p[44]]),
|
||||
)
|
||||
},
|
||||
)
|
||||
is_path_probe(p).then(|| {
|
||||
(
|
||||
p[36],
|
||||
u64::from_be_bytes([p[37], p[38], p[39], p[40], p[41], p[42], p[43], p[44]]),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -1258,6 +1289,66 @@ mod tests {
|
||||
}
|
||||
assert!(r.statuses(n)[0].listeners[0].selected.is_some());
|
||||
}
|
||||
#[test]
|
||||
fn peer_rtt_survives_one_miss_and_expires_on_loss_or_new_membership() {
|
||||
let (router, network, local, peer, other, t) = fixture(Protocol::Udp);
|
||||
let remote = Ipv4Addr::new(10, 0, 0, 2);
|
||||
let configure = |available| {
|
||||
router.configure(
|
||||
network,
|
||||
local,
|
||||
Some(t.src),
|
||||
vec![],
|
||||
vec![(peer, remote, available)],
|
||||
&Limits::default(),
|
||||
)
|
||||
};
|
||||
configure(false);
|
||||
configure(true);
|
||||
assert!(router.peer_rtt(network, peer).is_none());
|
||||
let (probes, _) = router.tick(0);
|
||||
let (_, request) = probes.iter().find(|(route, _)| route.peer == peer).unwrap();
|
||||
let (_, seq) = parse_probe(request).unwrap();
|
||||
let reply = probe(remote, t.src, 2, seq);
|
||||
assert!(matches!(
|
||||
router.incoming(network, other, reply.clone()),
|
||||
Decision::Drop
|
||||
));
|
||||
assert!(router.peer_rtt(network, peer).is_none());
|
||||
assert!(matches!(
|
||||
router.incoming(network, peer, reply.clone()),
|
||||
Decision::ProbeReceived
|
||||
));
|
||||
let measured = router.peer_rtt(network, peer).unwrap();
|
||||
configure(true);
|
||||
assert_eq!(router.peer_rtt(network, peer), Some(measured));
|
||||
assert!(matches!(
|
||||
router.incoming(network, peer, reply.clone()),
|
||||
Decision::Drop
|
||||
));
|
||||
for missed in 1..=2 {
|
||||
{
|
||||
let mut state = router.lock();
|
||||
let p = state.paths.get_mut(&(network, peer)).unwrap();
|
||||
let sent = Instant::now() - Duration::from_secs(4);
|
||||
p.last_probe = Some(sent);
|
||||
p.pending = Some((seq + missed, sent));
|
||||
}
|
||||
router.tick(0);
|
||||
assert_eq!(
|
||||
router.peer_rtt(network, peer),
|
||||
(missed == 1).then_some(measured)
|
||||
);
|
||||
}
|
||||
configure(false);
|
||||
configure(true);
|
||||
assert!(matches!(
|
||||
router.incoming(network, peer, reply),
|
||||
Decision::Drop
|
||||
));
|
||||
assert!(router.peer_rtt(network, peer).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unknown_rtt_is_not_selected_and_reflected_probes_do_not_forge_measurements() {
|
||||
let (r, n, _, a, _, _) = fixture(Protocol::Udp);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-runtime"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
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.9" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.9" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.9" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.9" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.12" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.12" }
|
||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.12" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.12" }
|
||||
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
|
||||
|
||||
@@ -25,6 +25,12 @@ pub fn networks(
|
||||
let mut peers: Vec<OverlayPeerReport> = Vec::new();
|
||||
|
||||
if let Some(view) = &wg_view {
|
||||
let confirmed: std::collections::HashSet<_> = network
|
||||
.peers
|
||||
.iter()
|
||||
.filter(|p| p.has_confirmed_data_path())
|
||||
.map(|p| p.endpoint_id)
|
||||
.collect();
|
||||
for peer in &view.peers {
|
||||
let tunnel = peer.tunnel.as_ref();
|
||||
peers.push(OverlayPeerReport {
|
||||
@@ -35,7 +41,8 @@ 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),
|
||||
idle: tunnel.is_some_and(|t| t.health.idle)
|
||||
&& confirmed.contains(&peer.endpoint_id),
|
||||
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),
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -192,6 +192,7 @@ impl Session {
|
||||
if self.cfg.mtu < MIN_MTU || self.cfg.byte_limit == 0 || self.cfg.local == self.cfg.remote {
|
||||
return Err(State::Failed);
|
||||
}
|
||||
let negotiation_started = Instant::now();
|
||||
if let Some(start) = self.request {
|
||||
if !Control::Start(start).valid() {
|
||||
return Err(State::Failed);
|
||||
@@ -232,6 +233,7 @@ impl Session {
|
||||
}
|
||||
}
|
||||
|
||||
let negotiation_time = negotiation_started.elapsed();
|
||||
for direction in [Direction::Download, Direction::Upload] {
|
||||
self.progress.state = match direction {
|
||||
Direction::Download => State::Download,
|
||||
@@ -240,7 +242,8 @@ impl Session {
|
||||
io.progress(self.progress);
|
||||
let sender = (direction == Direction::Download) == self.request.is_some();
|
||||
let result = if sender {
|
||||
self.send_probes(io, direction, deadline).await?
|
||||
self.send_probes(io, direction, deadline, negotiation_time)
|
||||
.await?
|
||||
} else {
|
||||
self.receive_probes(io, direction).await?
|
||||
};
|
||||
@@ -255,7 +258,9 @@ impl Session {
|
||||
io: &impl Io,
|
||||
direction: Direction,
|
||||
deadline: Instant,
|
||||
negotiation_time: Duration,
|
||||
) -> Result<Reading, State> {
|
||||
let waiting = Instant::now();
|
||||
loop {
|
||||
if matches!(open_control(self.events.recv().await)?, Control::Ready { direction: d, .. } if d == direction)
|
||||
{
|
||||
@@ -263,10 +268,17 @@ impl Session {
|
||||
}
|
||||
}
|
||||
let start = Instant::now();
|
||||
// Leave room for the opposite direction and the final reliable report.
|
||||
// End and Report travel on reliable control. Leave room for their
|
||||
// exchange and a queued feedback message even on a slow control path.
|
||||
// Only the receiver's data packets contribute to the measured rate.
|
||||
let report_time = negotiation_time
|
||||
.max(waiting.elapsed())
|
||||
.saturating_mul(3)
|
||||
.saturating_add(Duration::from_millis(200))
|
||||
.min(Duration::from_millis(1600));
|
||||
let remaining = deadline
|
||||
.saturating_duration_since(start)
|
||||
.saturating_sub(Duration::from_millis(200));
|
||||
.saturating_sub(report_time);
|
||||
let phase = if direction == Direction::Download {
|
||||
remaining / 2
|
||||
} else {
|
||||
|
||||
@@ -302,6 +302,22 @@ async fn an_unrelated_busy_reply_does_not_cancel_the_active_request() {
|
||||
assert_eq!(task.await.unwrap().state, State::Busy);
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn a_half_second_control_round_trip_can_return_both_data_measurements() {
|
||||
let (a, b, _, _) = shaped(
|
||||
12_000_000,
|
||||
25_000_000,
|
||||
NORMAL_BYTES,
|
||||
Duration::from_millis(260),
|
||||
0,
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(a.state, State::Complete, "{a:?}");
|
||||
assert_eq!(b.state, State::Complete, "{b:?}");
|
||||
assert!(a.down.bps.is_some() && a.up.bps.is_some(), "{a:?}");
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn slower_control_feedback_leaves_time_for_both_directions() {
|
||||
let (a, b, _, _) = shaped(
|
||||
|
||||
@@ -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.9"
|
||||
version = "1.0.12"
|
||||
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.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12" }
|
||||
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();
|
||||
@@ -194,7 +199,7 @@ impl TcpTlsConfig {
|
||||
key: "port",
|
||||
value: "PORT",
|
||||
help: "TCP port to listen on for TLS 1.3 connections",
|
||||
default: Some("443"),
|
||||
default: Some("9442"),
|
||||
},
|
||||
ProtocolOption {
|
||||
key: "sni",
|
||||
@@ -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;
|
||||
@@ -25,9 +24,9 @@ use tsunagi::identity::{DeviceIdentity, NetworkId};
|
||||
use crate::cert::{generate_self_signed_cert, make_client_config, make_server_config};
|
||||
|
||||
/// Default TCP port to bind and listen on.
|
||||
pub const DEFAULT_PORT: u16 = 443;
|
||||
pub const DEFAULT_PORT: u16 = 9442;
|
||||
|
||||
/// Fallback port if 443 is unprivileged on Linux and denied.
|
||||
/// Second unprivileged port when the preferred listener cannot bind.
|
||||
pub const FALLBACK_PORT: u16 = 8443;
|
||||
|
||||
/// Maximum payload length for a single framed datagram over TLS.
|
||||
@@ -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,9 +267,9 @@ 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>>,
|
||||
listener: TcpListener,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for TcpTlsTransport {
|
||||
@@ -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,87 +359,32 @@ 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)?;
|
||||
tracing::info!(port = target_port, "TCP TLS listening");
|
||||
Some(Arc::new(l))
|
||||
}
|
||||
Ok(listener) => listener,
|
||||
Err(err) if requested_port.is_none() => {
|
||||
let exe = std::env::current_exe()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_else(|_| "tsunagi".into());
|
||||
|
||||
if err.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
tracing::warn!(
|
||||
port = target_port,
|
||||
%err,
|
||||
"Cannot bind to default port {target_port} without privileges. \
|
||||
To allow port 443 and TUN on Linux, grant capabilities once with:\n \
|
||||
sudo setcap cap_net_admin,cap_net_bind_service+p {exe}\n\
|
||||
Falling back to port {FALLBACK_PORT}."
|
||||
);
|
||||
} else {
|
||||
tracing::warn!(
|
||||
port = target_port,
|
||||
%err,
|
||||
"Cannot bind to default port {target_port}: {err}. \
|
||||
Falling back to port {FALLBACK_PORT}."
|
||||
);
|
||||
}
|
||||
|
||||
let fallback_addr = SocketAddr::from(([0, 0, 0, 0], FALLBACK_PORT));
|
||||
match TcpListener::bind(fallback_addr).await {
|
||||
Ok(l) => {
|
||||
tracing::info!(port = FALLBACK_PORT, "TCP TLS listening on fallback port");
|
||||
Some(Arc::new(l))
|
||||
}
|
||||
Err(fallback_err) => {
|
||||
tracing::warn!(
|
||||
port = FALLBACK_PORT,
|
||||
err = %fallback_err,
|
||||
"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 bound = l.local_addr()?.port();
|
||||
tracing::info!(port = bound, "TCP TLS listening on ephemeral port");
|
||||
Some(Arc::new(l))
|
||||
}
|
||||
}
|
||||
tracing::warn!(port = target_port, %err, "TCP TLS default port unavailable");
|
||||
crate::candidates::listen(FALLBACK_PORT).or_else(|err| {
|
||||
tracing::warn!(port = FALLBACK_PORT, %err, "TCP TLS fallback port unavailable");
|
||||
crate::candidates::listen(0)
|
||||
})?
|
||||
}
|
||||
Err(err) => {
|
||||
let exe = std::env::current_exe()
|
||||
.map(|p| p.display().to_string())
|
||||
.unwrap_or_else(|_| "tsunagi".into());
|
||||
tracing::warn!(
|
||||
port = target_port,
|
||||
%err,
|
||||
"Cannot bind to requested port {target_port}: {err}. \
|
||||
To allow port {target_port} and TUN on Linux, grant capabilities once with:\n \
|
||||
sudo setcap cap_net_admin,cap_net_bind_service+p {exe}"
|
||||
);
|
||||
tracing::warn!(port = target_port, %err, "Cannot bind requested TCP TLS port");
|
||||
return Err(Box::new(err));
|
||||
}
|
||||
};
|
||||
|
||||
let bound_port = listener
|
||||
.as_ref()
|
||||
.and_then(|l| l.local_addr().ok())
|
||||
.map(|a| a.port())
|
||||
.unwrap_or(target_port);
|
||||
let bound_port = listener.local_addr()?.port();
|
||||
tracing::info!(port = bound_port, "TCP TLS listening");
|
||||
|
||||
Ok(Self {
|
||||
identity: identity.clone(),
|
||||
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 +402,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 +412,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 {
|
||||
@@ -480,18 +426,22 @@ impl TcpTlsTransport {
|
||||
where
|
||||
F: Fn(InboundLink) + Send + Sync + Clone + 'static,
|
||||
{
|
||||
let Some(listener) = self.listener.as_ref().cloned() else {
|
||||
return;
|
||||
};
|
||||
|
||||
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 = self.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 +486,7 @@ impl TcpTlsTransport {
|
||||
protocol: "tcp-tls".into(),
|
||||
link: Arc::new(link),
|
||||
});
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -561,92 +511,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()
|
||||
);
|
||||
}
|
||||
@@ -11,6 +11,38 @@ use tsunagi::dataplane::transport::{InboundLink, PacketTransport};
|
||||
use tsunagi::identity::{DeviceIdentity, NetworkId};
|
||||
use tsunagi_tcp_tls::TcpTlsTransport;
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_listeners_use_high_ports_and_report_the_actual_bound_port() {
|
||||
use tsunagi::dataplane::transport::DataCarrier;
|
||||
use tsunagi_tcp_tls::{TcpTlsCarrier, TcpTlsConfig, transport::DEFAULT_PORT};
|
||||
|
||||
assert_eq!(DEFAULT_PORT, 9442);
|
||||
let option = TcpTlsConfig::OPTIONS
|
||||
.iter()
|
||||
.find(|o| o.key == "port")
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
option.default.unwrap().parse::<u16>().unwrap(),
|
||||
DEFAULT_PORT
|
||||
);
|
||||
let identity = DeviceIdentity::generate();
|
||||
let first = TcpTlsTransport::bind(&identity, None, None).await.unwrap();
|
||||
let second = Arc::new(TcpTlsTransport::bind(&identity, None, None).await.unwrap());
|
||||
assert!(first.bound_port() >= 1024 && second.bound_port() >= 1024);
|
||||
assert_ne!(first.bound_port(), second.bound_port());
|
||||
assert!(
|
||||
TcpTlsTransport::bind(&identity, Some(first.bound_port()), None)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
let cap = TcpTlsCarrier::new(second.clone())
|
||||
.local_capability(NetworkId::from_bytes([3; 32]))
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (port, _): (u16, Vec<std::net::IpAddr>) = postcard::from_bytes(&cap.data).unwrap();
|
||||
assert_eq!(port, second.bound_port());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_tcp_tls_transport_loopback() {
|
||||
let identity_a = DeviceIdentity::generate();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-tray"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
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.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12" }
|
||||
# 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).
|
||||
|
||||
@@ -34,6 +34,17 @@ pub(crate) struct App {
|
||||
sampled: u64,
|
||||
}
|
||||
|
||||
const MIN_DEVICES_SIZE: egui::Vec2 = egui::vec2(560., 260.);
|
||||
|
||||
fn initial_devices_size(rows: usize, monitor: Option<egui::Vec2>, row_pitch: f32) -> egui::Vec2 {
|
||||
// The collapsed header, the roster header and the totals row are visible on open.
|
||||
let height = (110. + (rows as f32 + 2.) * row_pitch).clamp(MIN_DEVICES_SIZE.y, 780.);
|
||||
let preferred = egui::vec2(1240., height);
|
||||
monitor.map_or(preferred, |screen| {
|
||||
preferred.min((screen - egui::vec2(48., 80.)).max(MIN_DEVICES_SIZE))
|
||||
})
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Builds the app: resolves the socket and starts the worker.
|
||||
pub(crate) fn new(
|
||||
@@ -195,18 +206,27 @@ impl App {
|
||||
continue;
|
||||
};
|
||||
let viewport = egui::ViewportId::from_hash_of(("devices", id));
|
||||
let preferred = egui::vec2(1240., 740.);
|
||||
let size = ctx
|
||||
.input(|i| i.viewport().monitor_size)
|
||||
.map_or(preferred, |monitor| {
|
||||
preferred.min((monitor - egui::vec2(48., 80.)).max(egui::vec2(560., 400.)))
|
||||
});
|
||||
let builder = egui::ViewportBuilder::default()
|
||||
let mut builder = egui::ViewportBuilder::default()
|
||||
.with_title(devices::title(&report.networks[index]))
|
||||
.with_app_id(crate::icon::APP_ID)
|
||||
.with_icon(crate::icon::window())
|
||||
.with_inner_size(size)
|
||||
.with_min_inner_size([560., 400.]);
|
||||
.with_min_inner_size(MIN_DEVICES_SIZE);
|
||||
// Apply the roster estimate only when creating a native window.
|
||||
// Subsequent frames leave the user's own height and width in place.
|
||||
let (opened, monitor) = ctx.input(|i| {
|
||||
(
|
||||
i.raw.viewports.contains_key(&viewport),
|
||||
i.viewport().monitor_size,
|
||||
)
|
||||
});
|
||||
if !opened {
|
||||
let rows = devices::known_count(&report.networks[index], &report.endpoint_id);
|
||||
builder = builder.with_inner_size(initial_devices_size(
|
||||
rows,
|
||||
monitor,
|
||||
devices::row_pitch(ctx),
|
||||
));
|
||||
}
|
||||
let views = self.views.clone();
|
||||
let agent = self.agent.clone();
|
||||
let report = report.clone();
|
||||
@@ -245,6 +265,17 @@ mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn devices_window_opens_to_fit_the_roster_within_the_screen() {
|
||||
let size = |rows| initial_devices_size(rows, None, 34.);
|
||||
assert_eq!(size(0).y, size(1).y);
|
||||
assert!(size(6).y < size(16).y);
|
||||
assert!(size(16).y < size(80).y);
|
||||
assert_eq!(size(80), size(2000));
|
||||
let on_small_screen = initial_devices_size(80, Some(egui::vec2(950., 670.)), 34.);
|
||||
assert!(on_small_screen.x < 950. && on_small_screen.y < 670.);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn device_frames_are_scheduled_independently_of_the_main_window() {
|
||||
let runtime = tokio::runtime::Builder::new_current_thread()
|
||||
@@ -277,6 +308,28 @@ mod tests {
|
||||
app.show_devices_windows(ctx, &report, &["test-id".to_string()], true);
|
||||
});
|
||||
assert!(out.viewport_output[&id].class == egui::ViewportClass::Deferred);
|
||||
assert_eq!(
|
||||
out.viewport_output[&id].builder.inner_size.unwrap().y,
|
||||
MIN_DEVICES_SIZE.y
|
||||
);
|
||||
|
||||
let mut resized = egui::RawInput::default();
|
||||
resized.viewports.entry(id).or_default().inner_rect = Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(1300., 900.),
|
||||
));
|
||||
let mut larger = Arc::clone(&report);
|
||||
Arc::make_mut(&mut larger).networks[0].members = (0..60)
|
||||
.map(|i| tsunagi::ipc::MemberReport {
|
||||
endpoint_id: i.to_string(),
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
let out = ctx.run(resized, |ctx| {
|
||||
app.show_devices_windows(ctx, &larger, &["test-id".to_string()], true);
|
||||
});
|
||||
let builder = &out.viewport_output[&id].builder;
|
||||
assert!(builder.inner_size.is_none() && builder.max_inner_size.is_none());
|
||||
let draw = out.viewport_output[&id].viewport_ui_cb.as_ref().unwrap();
|
||||
let mut input = egui::RawInput {
|
||||
viewport_id: id,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-ui"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
description = "Shared egui widgets for the tray and Android clients."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
@@ -13,7 +13,9 @@ mod speed;
|
||||
mod speed_tests;
|
||||
mod status;
|
||||
pub use crate::exit::name_of;
|
||||
pub use exit_picker::{choose_exit, choose_exit_from_networks, exit_action_colors};
|
||||
pub use exit_picker::{
|
||||
choose_exit, choose_exit_from_networks, choose_exit_with_tests, exit_action_colors,
|
||||
};
|
||||
|
||||
use egui_phosphor::regular as icon;
|
||||
|
||||
@@ -208,6 +210,12 @@ fn short_name_cell(ui: &mut egui::Ui, device: &Device<'_>) {
|
||||
));
|
||||
}
|
||||
|
||||
/// Height of one desktop roster row, including the gap to its neighbour.
|
||||
pub fn row_pitch(ctx: &egui::Context) -> f32 {
|
||||
let style = ctx.style();
|
||||
crate::table::row_height(ctx, &style) + style.spacing.item_spacing.y
|
||||
}
|
||||
|
||||
/// Draws the window body into its viewport.
|
||||
pub fn show(
|
||||
ctx: &egui::Context,
|
||||
@@ -244,7 +252,7 @@ pub fn show(
|
||||
"devices ({online} online / {} known)",
|
||||
devices.len()
|
||||
));
|
||||
speed.toolbar(ui);
|
||||
speed.batch_button(ui, false);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -278,11 +286,7 @@ pub fn show(
|
||||
columns[0].collapsing("Network details", |ui| summary(ui, network));
|
||||
let plot = &mut columns[1];
|
||||
plot.label("Network traffic");
|
||||
let width = plot.available_width().min(440.0);
|
||||
plot.scope(|ui| {
|
||||
ui.set_max_width(width);
|
||||
format::sparkline(ui, traffic.network(&network.network_id), unit, 48.0);
|
||||
});
|
||||
format::sparkline(plot, traffic.network(&network.network_id), unit, 48.0);
|
||||
});
|
||||
ui.add_space(8.0);
|
||||
egui::ScrollArea::vertical()
|
||||
@@ -767,7 +771,7 @@ const MIN_PLOT_WIDTH: f32 = 100.;
|
||||
|
||||
fn stretch_columns(mut widths: [f32; 9], available: f32) -> [f32; 9] {
|
||||
let gaps = crate::table::GAP * (widths.len() - 1) as f32;
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).clamp(MIN_PLOT_WIDTH, 180.0);
|
||||
widths[8] = (available - gaps - widths[..8].iter().sum::<f32>()).max(MIN_PLOT_WIDTH);
|
||||
widths
|
||||
}
|
||||
|
||||
@@ -995,7 +999,7 @@ fn device_table(
|
||||
2 => tunnel_cell(ui, device),
|
||||
3 => {
|
||||
ui.label(rtt_pair(device)).on_hover_text(
|
||||
"Median authenticated direct data-link RTT / selected control-connection RTT. A dash means there is no current measurement.",
|
||||
"Round trip to the device over the encrypted data path, including relay hops / round trip over the control connection.",
|
||||
);
|
||||
}
|
||||
4 => match &device.address {
|
||||
@@ -1434,10 +1438,10 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wider_windows_keep_a_compact_plot_and_narrow_windows_preserve_column_floors() {
|
||||
fn plots_fill_wide_windows_and_narrow_windows_preserve_column_floors() {
|
||||
let minimum = [100.0; 9];
|
||||
let wide = stretch_columns(minimum, 1440.0);
|
||||
assert!((100.0..=190.0).contains(&wide[8]));
|
||||
assert!((wide.iter().sum::<f32>() + 8. * crate::table::GAP - 1440.).abs() < 0.1);
|
||||
assert_eq!(&wide[..8], &minimum[..8]);
|
||||
let narrow = stretch_columns(minimum, 800.0);
|
||||
assert_eq!(
|
||||
@@ -1451,6 +1455,20 @@ mod tests {
|
||||
);
|
||||
|
||||
let ctx = egui::Context::default();
|
||||
let network = NetworkReport {
|
||||
peers: vec![tsunagi::ipc::PeerReport {
|
||||
endpoint_id: "peer".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
overlay: Some(tsunagi::ipc::OverlayReport {
|
||||
peers: vec![OverlayPeerReport {
|
||||
endpoint_id: "peer".into(),
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
for window_width in [800.0, 1000.0, 1440.0] {
|
||||
let frame = ctx.run(
|
||||
egui::RawInput {
|
||||
@@ -1466,21 +1484,27 @@ mod tests {
|
||||
&ReadOnly,
|
||||
&mut Unit::Bytes,
|
||||
(&mut None, &mut None),
|
||||
&NetworkReport::default(),
|
||||
&network,
|
||||
"self",
|
||||
&Traffic::default(),
|
||||
);
|
||||
},
|
||||
);
|
||||
let chart = frame
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Rect(r) if r.rect.height() == 48.0 => Some(r.rect),
|
||||
let chart = |height| {
|
||||
frame.shapes.iter().find_map(|s| match &s.shape {
|
||||
egui::Shape::Rect(r) if r.rect.height() == height => Some(r.rect),
|
||||
_ => None,
|
||||
})
|
||||
.expect("network traffic chart");
|
||||
assert!((300.0..=440.0).contains(&chart.width()), "{chart:?}");
|
||||
};
|
||||
let total = chart(48.).expect("network traffic chart");
|
||||
assert!((window_width - total.right()).abs() < 12., "{total:?}");
|
||||
if window_width == 1440. {
|
||||
let peer = chart(24.).expect("desktop peer traffic chart");
|
||||
assert!(
|
||||
(peer.right() - total.right()).abs() < 2.,
|
||||
"{peer:?} {total:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! One touch target per exit, grouped by the network that will carry the traffic.
|
||||
use super::{ExitConfirm, devices};
|
||||
use super::{Client, ExitConfirm, devices, speed};
|
||||
use crate::{exit, format, widgets};
|
||||
use egui::{Align, Align2, Color32, FontFamily, FontId, Rect, Sense, Ui, pos2, vec2};
|
||||
use egui_phosphor::regular as icon;
|
||||
@@ -15,6 +15,25 @@ pub fn choose_exit_from_networks(
|
||||
ui: &mut Ui,
|
||||
networks: &[NetworkReport],
|
||||
own: &str,
|
||||
) -> Option<ExitConfirm> {
|
||||
chooser(ui, networks, own, None)
|
||||
}
|
||||
|
||||
/// The interactive Android picker can also measure every eligible exit in one network.
|
||||
pub fn choose_exit_with_tests(
|
||||
ui: &mut Ui,
|
||||
networks: &[NetworkReport],
|
||||
own: &str,
|
||||
client: &dyn Client,
|
||||
) -> Option<ExitConfirm> {
|
||||
chooser(ui, networks, own, Some(client))
|
||||
}
|
||||
|
||||
fn chooser(
|
||||
ui: &mut Ui,
|
||||
networks: &[NetworkReport],
|
||||
own: &str,
|
||||
client: Option<&dyn Client>,
|
||||
) -> Option<ExitConfirm> {
|
||||
let current = networks
|
||||
.iter()
|
||||
@@ -28,7 +47,7 @@ pub fn choose_exit_from_networks(
|
||||
glyph: icon::GLOBE,
|
||||
};
|
||||
let mut choice = None;
|
||||
if local.draw(ui, "local internet")
|
||||
if local.draw(ui, "local internet", None)
|
||||
&& let Some((network, id)) = current
|
||||
{
|
||||
choice = Some(ExitConfirm::stop_from_tile(network, id));
|
||||
@@ -64,17 +83,30 @@ pub fn choose_exit_from_networks(
|
||||
network.name.clone()
|
||||
};
|
||||
ui.add_space(10.);
|
||||
let (header, hint) =
|
||||
ui.allocate_exact_size(vec2(ui.available_width(), 30.), Sense::hover());
|
||||
widgets::single_line(
|
||||
ui.painter(),
|
||||
header,
|
||||
Align::Min,
|
||||
&title,
|
||||
bold(19.),
|
||||
ui.visuals().strong_text_color(),
|
||||
);
|
||||
widgets::hint(hint, &network.network_id);
|
||||
ui.push_id(&network.network_id, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
let (height, button_space) = if client.is_some() {
|
||||
(44., 44. + ui.spacing().item_spacing.x)
|
||||
} else {
|
||||
(30., 0.)
|
||||
};
|
||||
let title_width = (ui.available_width() - button_space).max(0.);
|
||||
let (header, hint) =
|
||||
ui.allocate_exact_size(vec2(title_width, height), Sense::hover());
|
||||
widgets::single_line(
|
||||
ui.painter(),
|
||||
header,
|
||||
Align::Min,
|
||||
&title,
|
||||
bold(19.),
|
||||
ui.visuals().strong_text_color(),
|
||||
);
|
||||
widgets::hint(hint, &network.network_id);
|
||||
if let Some(client) = client {
|
||||
speed::Controls::new(network, client).batch_button(ui, true);
|
||||
}
|
||||
});
|
||||
});
|
||||
if let Some(rules) = &network.exit.client_rules
|
||||
&& !rules.ok
|
||||
{
|
||||
@@ -94,7 +126,7 @@ pub fn choose_exit_from_networks(
|
||||
selected: true,
|
||||
glyph: icon::SIGN_OUT,
|
||||
}
|
||||
.draw(ui, (&network.network_id, id));
|
||||
.draw(ui, (&network.network_id, id), None);
|
||||
}
|
||||
for d in candidates {
|
||||
let name = d.name();
|
||||
@@ -112,15 +144,17 @@ pub fn choose_exit_from_networks(
|
||||
}
|
||||
};
|
||||
let latency = d.data_rtt_ms.map(|ms| format!("{ms} ms"));
|
||||
let speed = network.speed.peers.get(d.id).map(speed::exit_caption);
|
||||
let address = d.address.as_deref();
|
||||
let row = Row {
|
||||
name: &name,
|
||||
caption: d.address.as_deref().unwrap_or(""),
|
||||
caption: speed.as_deref().or(address).unwrap_or(""),
|
||||
latency: latency.as_deref(),
|
||||
path: Some(&path),
|
||||
selected: d.in_use,
|
||||
glyph: icon::SIGN_OUT,
|
||||
};
|
||||
if row.draw(ui, (&network.network_id, d.id)) && !d.in_use {
|
||||
if row.draw(ui, (&network.network_id, d.id), address) && !d.in_use {
|
||||
choice = Some(ExitConfirm {
|
||||
network_id: network.network_id.clone(),
|
||||
peer_id: d.id.into(),
|
||||
@@ -159,7 +193,7 @@ struct Row<'a> {
|
||||
glyph: &'static str,
|
||||
}
|
||||
impl Row<'_> {
|
||||
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash) -> bool {
|
||||
fn draw(&self, ui: &mut Ui, id: impl std::hash::Hash, hint: Option<&str>) -> bool {
|
||||
let (rect, _) = ui.allocate_exact_size(vec2(ui.available_width(), 58.), Sense::hover());
|
||||
let response = ui.interact(
|
||||
rect,
|
||||
@@ -273,9 +307,12 @@ impl Row<'_> {
|
||||
detail,
|
||||
);
|
||||
}
|
||||
response
|
||||
.on_hover_cursor(egui::CursorIcon::PointingHand)
|
||||
.clicked()
|
||||
let response = response.on_hover_cursor(egui::CursorIcon::PointingHand);
|
||||
match hint {
|
||||
Some(hint) => widgets::hint(response, hint),
|
||||
None => response,
|
||||
}
|
||||
.clicked()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! The same speed control occupies one fixed cell throughout a measurement.
|
||||
use super::{Client, Command, Device, NetworkReport, format, icon, widgets};
|
||||
use super::{Client, Command, Device, NetworkReport, format, icon, status, widgets};
|
||||
use crate::client::speed_running;
|
||||
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, pos2, vec2};
|
||||
use std::time::{Duration, SystemTime, UNIX_EPOCH};
|
||||
@@ -29,58 +29,67 @@ impl<'a> Controls<'a> {
|
||||
self.network.speed.capable.iter().any(|peer| peer == id)
|
||||
}
|
||||
|
||||
pub(super) fn toolbar(&self, ui: &mut Ui) {
|
||||
let (label, help, available) = if self.running {
|
||||
pub(super) fn batch_button(&self, ui: &mut Ui, icon_only: bool) {
|
||||
let (glyph, label, help, available) = if self.running {
|
||||
ui.ctx().request_repaint_after(Duration::from_millis(250));
|
||||
let label = self.network.speed.batch.map_or_else(
|
||||
|| format!("{} Stop test", icon::STOP_CIRCLE),
|
||||
|batch| {
|
||||
format!(
|
||||
"{} Stop {}/{}",
|
||||
icon::STOP_CIRCLE,
|
||||
batch.done,
|
||||
batch.total
|
||||
)
|
||||
},
|
||||
|| "Stop test".to_owned(),
|
||||
|batch| format!("Stop {}/{}", batch.done, batch.total),
|
||||
);
|
||||
(
|
||||
icon::STOP_CIRCLE,
|
||||
label,
|
||||
"Stop this speed test and skip any queued exits.",
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let available = self.network.active
|
||||
&& self
|
||||
.network
|
||||
.peers
|
||||
.iter()
|
||||
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
|
||||
&& self.network.peers.iter().any(|p| {
|
||||
p.exit_node
|
||||
&& self.capable(&p.endpoint_id)
|
||||
&& p.data_error.is_none()
|
||||
&& status::confirmed(
|
||||
Some(&p.path),
|
||||
p.data_rtt_ms,
|
||||
self.network.overlay.as_ref().and_then(|overlay| {
|
||||
overlay
|
||||
.peers
|
||||
.iter()
|
||||
.find(|t| t.endpoint_id == p.endpoint_id)
|
||||
}),
|
||||
)
|
||||
});
|
||||
(
|
||||
format!("{} Test exits", icon::GAUGE),
|
||||
icon::GAUGE,
|
||||
"Test exits".to_owned(),
|
||||
if available {
|
||||
"Test each compatible online exit node in this network, one at a time."
|
||||
} else {
|
||||
"No online exit in this network supports peer speed tests."
|
||||
"No compatible exit has a confirmed data path."
|
||||
},
|
||||
available,
|
||||
)
|
||||
};
|
||||
// Leave room for the batch count before starting. A wrapping toolbar
|
||||
// must keep the same height when the button becomes Stop.
|
||||
let width = ui
|
||||
.painter()
|
||||
.layout_no_wrap(
|
||||
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
|
||||
egui::TextStyle::Button.resolve(ui.style()),
|
||||
ui.visuals().text_color(),
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
+ 2. * ui.spacing().button_padding.x;
|
||||
let button = ui.add_enabled(
|
||||
available && !self.client.busy(),
|
||||
egui::Button::new(label).min_size(vec2(width, 0.)),
|
||||
);
|
||||
let button = if icon_only {
|
||||
egui::Button::new(egui::RichText::new(glyph).size(22.)).min_size(vec2(44., 44.))
|
||||
} else {
|
||||
// Switching to Stop must not wrap a toolbar onto a second line.
|
||||
let width = ui
|
||||
.painter()
|
||||
.layout_no_wrap(
|
||||
format!("{} Stop 9999/9999", icon::STOP_CIRCLE),
|
||||
egui::TextStyle::Button.resolve(ui.style()),
|
||||
ui.visuals().text_color(),
|
||||
)
|
||||
.size()
|
||||
.x
|
||||
+ 2. * ui.spacing().button_padding.x;
|
||||
egui::Button::new(format!("{glyph} {label}")).min_size(vec2(width, 0.))
|
||||
};
|
||||
let button = ui.add_enabled(available && !self.client.busy(), button);
|
||||
button.widget_info(|| {
|
||||
egui::WidgetInfo::labeled(egui::WidgetType::Button, button.enabled(), &label)
|
||||
});
|
||||
if widgets::hint(button, help).clicked() {
|
||||
let network_id = self.network.network_id.clone();
|
||||
let command = if self.running {
|
||||
@@ -101,7 +110,12 @@ impl<'a> Controls<'a> {
|
||||
}
|
||||
let reading = self.network.speed.peers.get(peer.id);
|
||||
let supported = self.capable(peer.id);
|
||||
let ready = self.network.active && peer.online && supported;
|
||||
let ready = self.network.active
|
||||
&& supported
|
||||
&& matches!(
|
||||
peer.channel(),
|
||||
status::Channel::Ready | status::Channel::Idle
|
||||
);
|
||||
let can_start = ready && !self.running && !self.client.busy();
|
||||
let id = ui.make_persistent_id(("test peer speed", &self.network.network_id, peer.id));
|
||||
let r = ui.interact(rect, id, Sense::click());
|
||||
@@ -132,6 +146,30 @@ impl<'a> Controls<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn exit_caption(test: &SpeedPeerReport) -> String {
|
||||
match test.phase {
|
||||
SpeedPhase::Queued => "Queued".into(),
|
||||
SpeedPhase::Preparing => "Starting…".into(),
|
||||
SpeedPhase::Cancelled => "Stopped".into(),
|
||||
SpeedPhase::Failed(_) => "Test failed".into(),
|
||||
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
|
||||
let rate = |value: Option<SpeedRate>, phase| {
|
||||
value.map_or_else(
|
||||
|| if test.phase == phase { "…" } else { "—" }.into(),
|
||||
compact_rate,
|
||||
)
|
||||
};
|
||||
format!(
|
||||
"{} {} {} {} Mbit/s",
|
||||
icon::ARROW_DOWN,
|
||||
rate(test.down, SpeedPhase::Download),
|
||||
icon::ARROW_UP,
|
||||
rate(test.up, SpeedPhase::Upload)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_reading(
|
||||
ui: &Ui,
|
||||
rect: Rect,
|
||||
@@ -162,7 +200,9 @@ fn paint_reading(
|
||||
label("Starting", color);
|
||||
activity(ui, rect, color);
|
||||
}
|
||||
SpeedPhase::Failed(_) if !ready => label("Failed", v.weak_text_color()),
|
||||
SpeedPhase::Failed(_) => label(&format!("{} Retry", icon::WARNING), v.error_fg_color),
|
||||
SpeedPhase::Cancelled if !ready => label("Stopped", v.weak_text_color()),
|
||||
SpeedPhase::Cancelled => label(&format!("{} Retry", icon::ARROW_CLOCKWISE), color),
|
||||
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
|
||||
// Reserve the same two slots for idle, live and completed readings.
|
||||
@@ -306,6 +346,11 @@ fn tooltip(
|
||||
}
|
||||
if !peer.online {
|
||||
hint.push_str("\nPeer is offline.");
|
||||
} else if !matches!(
|
||||
peer.channel(),
|
||||
status::Channel::Ready | status::Channel::Idle
|
||||
) {
|
||||
hint.push_str("\nWaiting for a confirmed data path.");
|
||||
} else if !supported {
|
||||
hint.push_str("\nNo compatible speed-test session with this peer.");
|
||||
} else if !running {
|
||||
|
||||
@@ -27,8 +27,20 @@ fn network() -> NetworkReport {
|
||||
endpoint_id: id.into(),
|
||||
hostname: Some(id.into()),
|
||||
exit_node: offers_exit,
|
||||
path: DataPathReport::Direct {
|
||||
transport: "wg".into(),
|
||||
},
|
||||
data_rtt_ms: Some(12),
|
||||
..Default::default()
|
||||
});
|
||||
n.overlay
|
||||
.get_or_insert_with(Default::default)
|
||||
.peers
|
||||
.push(OverlayPeerReport {
|
||||
endpoint_id: id.into(),
|
||||
handshake_secs_ago: Some(1),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
n.speed.capable = vec!["alice".into(), "ben".into()];
|
||||
n
|
||||
@@ -52,6 +64,76 @@ fn reading(phase: SpeedPhase) -> SpeedPeerReport {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_picker_tests_only_the_tapped_network_and_keeps_the_route_selection() {
|
||||
let screen = Screen::new(320., true);
|
||||
let a = network();
|
||||
let mut b = network();
|
||||
b.name = "office".into();
|
||||
b.network_id = "office-id".into();
|
||||
b.exit.via = Some("alice".into());
|
||||
let mut nets = [a, b];
|
||||
let draw = |nets: &[NetworkReport], events| {
|
||||
screen.ctx.run(
|
||||
egui::RawInput {
|
||||
screen_rect: Some(egui::Rect::from_min_size(
|
||||
egui::Pos2::ZERO,
|
||||
egui::vec2(320., 650.),
|
||||
)),
|
||||
events,
|
||||
..Default::default()
|
||||
},
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
assert!(choose_exit_with_tests(ui, nets, "self", &screen.log).is_none());
|
||||
assert!(ui.min_rect().right() <= 320.);
|
||||
});
|
||||
},
|
||||
)
|
||||
};
|
||||
let tap = |nets: &[NetworkReport], pos| {
|
||||
for pressed in [true, false] {
|
||||
draw(
|
||||
nets,
|
||||
vec![
|
||||
egui::Event::PointerMoved(pos),
|
||||
egui::Event::PointerButton {
|
||||
pos,
|
||||
button: egui::PointerButton::Primary,
|
||||
pressed,
|
||||
modifiers: Default::default(),
|
||||
},
|
||||
],
|
||||
);
|
||||
}
|
||||
};
|
||||
let first = draw(&nets, vec![]);
|
||||
let gauges = positions(&first, |s| s == icon::GAUGE);
|
||||
assert_eq!(gauges.len(), 2);
|
||||
let office = positions(&first, |s| s == "office")[0];
|
||||
let button = *gauges.iter().find(|p| (p.y - office.y).abs() < 4.).unwrap();
|
||||
tap(&nets, button);
|
||||
assert!(
|
||||
matches!(screen.log.0.borrow().as_slice(), [Command::StartSpeedTest { network_id, peer: None }] if network_id == "office-id")
|
||||
);
|
||||
nets[1].speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
|
||||
nets[1]
|
||||
.speed
|
||||
.peers
|
||||
.insert("alice".into(), reading(SpeedPhase::Upload));
|
||||
let live = draw(&nets, vec![]);
|
||||
assert!(!positions(&live, |s| s.contains("125") && s.contains("Mbit/s")).is_empty());
|
||||
let stop = positions(&live, |s| s == icon::STOP_CIRCLE)[0];
|
||||
tap(&nets, stop);
|
||||
assert!(
|
||||
matches!(screen.log.0.borrow().last(), Some(Command::StopSpeedTest { network_id }) if network_id == "office-id")
|
||||
);
|
||||
nets[1].speed = Default::default();
|
||||
draw(&nets, vec![]);
|
||||
tap(&nets, button);
|
||||
assert_eq!(screen.log.0.borrow().len(), 2);
|
||||
}
|
||||
|
||||
struct Screen {
|
||||
ctx: egui::Context,
|
||||
width: f32,
|
||||
@@ -258,6 +340,26 @@ fn long_press_explains_a_partial_result_without_requesting_another_test() {
|
||||
assert!(s.log.0.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_control_only_peer_cannot_look_idle_or_start_a_speed_test() {
|
||||
let mut n = network();
|
||||
n.peers[0].data_rtt_ms = None;
|
||||
n.peers[0].rtt_ms = Some(12);
|
||||
n.overlay.as_mut().unwrap().peers[0].idle = true;
|
||||
let row = devices(&n, "self");
|
||||
assert!(matches!(
|
||||
row.iter().find(|p| p.id == "alice").unwrap().channel(),
|
||||
status::Channel::Waiting
|
||||
));
|
||||
let screen = Screen::new(360., true);
|
||||
screen.frame(&n, vec![]);
|
||||
let output = screen.frame(&n, vec![]);
|
||||
assert_eq!(positions(&output, |s| s == icon::GAUGE).len(), 1);
|
||||
let start = positions(&output, |s| s.contains("Test exits"))[0];
|
||||
screen.click(&n, start);
|
||||
assert!(screen.log.0.borrow().is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
|
||||
let mut n = network();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::{DataPathReport, Device, icon};
|
||||
use super::{DataPathReport, Device, OverlayPeerReport, icon};
|
||||
use tsunagi::agent::{DATA_CONNECTING, DATA_DISABLED};
|
||||
|
||||
#[derive(Copy, Clone, PartialEq, Eq)]
|
||||
@@ -11,6 +11,16 @@ pub(super) enum Channel {
|
||||
Disabled,
|
||||
}
|
||||
|
||||
pub(super) fn confirmed(
|
||||
path: Option<&DataPathReport>,
|
||||
rtt: Option<u64>,
|
||||
tunnel: Option<&OverlayPeerReport>,
|
||||
) -> bool {
|
||||
!matches!(path, None | Some(DataPathReport::None))
|
||||
&& rtt.is_some()
|
||||
&& tunnel.is_some_and(OverlayPeerReport::is_up)
|
||||
}
|
||||
|
||||
impl Device<'_> {
|
||||
pub(super) fn channel(&self) -> Channel {
|
||||
if !self.online {
|
||||
@@ -20,10 +30,9 @@ impl Device<'_> {
|
||||
Some(DATA_DISABLED) => Channel::Disabled,
|
||||
Some(DATA_CONNECTING) => Channel::Waiting,
|
||||
Some(_) => Channel::Error,
|
||||
None if matches!(self.path, None | Some(DataPathReport::None)) => Channel::Waiting,
|
||||
None if !confirmed(self.path, self.data_rtt_ms, self.overlay) => Channel::Waiting,
|
||||
None if self.overlay.is_some_and(|p| p.idle) => Channel::Idle,
|
||||
None if self.overlay.is_some_and(|p| p.is_up()) => Channel::Ready,
|
||||
None => Channel::Waiting,
|
||||
None => Channel::Ready,
|
||||
}
|
||||
}
|
||||
pub(super) fn channel_hint(&self) -> &str {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
//! Shared compact network tiles, device header and join form.
|
||||
mod card;
|
||||
mod protocols;
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
devices, exit, format,
|
||||
@@ -7,6 +8,7 @@ use crate::{
|
||||
widgets,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use protocols::draw_protocols;
|
||||
use std::collections::BTreeSet;
|
||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||
use zeroize::{Zeroize, Zeroizing};
|
||||
@@ -422,81 +424,6 @@ fn draw_selected_exit(ui: &mut egui::Ui, network: &NetworkReport, via: &str, sta
|
||||
});
|
||||
}
|
||||
|
||||
fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[tsunagi::ipc::ProtocolReport],
|
||||
) {
|
||||
let summary = if network.protocols.is_empty() {
|
||||
"none".into()
|
||||
} else {
|
||||
network.protocols.join(", ")
|
||||
};
|
||||
egui::CollapsingHeader::new(format!("data transports {summary}"))
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
ui.weak("Order sets the first choice. Peers that support link comparison can switch to a faster enabled transport.");
|
||||
let mut selected = network.protocols.clone();
|
||||
let mut changed = false;
|
||||
ui.add_enabled_ui(!agent.busy(), |ui| {
|
||||
// Enabled items follow the user's preference; unchecked items
|
||||
// follow the agent's catalog. The worker refreshes after edits.
|
||||
let ordered: Vec<_> = network
|
||||
.protocols
|
||||
.iter()
|
||||
.filter_map(|name| available.iter().find(|p| &p.name == name))
|
||||
.chain(
|
||||
available
|
||||
.iter()
|
||||
.filter(|p| !network.protocols.contains(&p.name)),
|
||||
)
|
||||
.collect();
|
||||
for protocol in ordered {
|
||||
ui.horizontal(|ui| {
|
||||
let mut on = selected.contains(&protocol.name);
|
||||
if ui.checkbox(&mut on, &protocol.name).changed() {
|
||||
if on {
|
||||
selected.push(protocol.name.clone());
|
||||
} else {
|
||||
selected.retain(|p| p != &protocol.name);
|
||||
}
|
||||
changed = true;
|
||||
}
|
||||
if let Some(index) = selected.iter().position(|p| p == &protocol.name) {
|
||||
if widgets::hint(ui.add_enabled(index > 0, egui::Button::new(icon::ARROW_UP)),
|
||||
"Move transport up in preference order").clicked()
|
||||
{
|
||||
selected.swap(index, index - 1);
|
||||
changed = true;
|
||||
}
|
||||
if widgets::hint(ui.add_enabled(
|
||||
index + 1 < selected.len(),
|
||||
egui::Button::new(icon::ARROW_DOWN),
|
||||
), "Move transport down in preference order").clicked()
|
||||
{
|
||||
selected.swap(index, index + 1);
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
});
|
||||
ui.indent(("description", &network.network_id, &protocol.name), |ui| {
|
||||
ui.weak(&protocol.summary);
|
||||
});
|
||||
}
|
||||
});
|
||||
if selected.is_empty() {
|
||||
ui.weak("Control only; no IP traffic in this network.");
|
||||
}
|
||||
if changed {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// A prominent line about an exit node. One that carries a command copies it
|
||||
/// when clicked.
|
||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||
|
||||
@@ -88,39 +88,52 @@ pub(super) fn header(
|
||||
let left = dot.x + 9.;
|
||||
let mut right = rect.right() - 2.;
|
||||
let quiet = ui.visuals().weak_text_color();
|
||||
// Preserve a useful piece of the name even on the narrow landscape selector.
|
||||
if right - left > 98. {
|
||||
let width = (rect.width() * 0.15).clamp(26., 64.);
|
||||
let title_font = FontId::new(font.size + 4., egui::FontFamily::Name("Bold".into()));
|
||||
let strong = ui.visuals().strong_text_color();
|
||||
let title = painter.layout_no_wrap(net.name.clone(), title_font.clone(), strong);
|
||||
let mut spare = right - left - title.size().x.min(64.);
|
||||
const GAP: f32 = 8.;
|
||||
let mut reserve = |text| {
|
||||
let galley = painter.layout_no_wrap(text, font.clone(), ink);
|
||||
let width = galley.size().x + GAP;
|
||||
if width > spare {
|
||||
return None;
|
||||
}
|
||||
spare -= width;
|
||||
Some(galley)
|
||||
};
|
||||
// Reserve the address first. Peer counts grow as sessions reconnect.
|
||||
let address = net.overlay.as_ref().and_then(|o| o.address.as_deref());
|
||||
let ip = address.and_then(|s| reserve(s.to_owned()));
|
||||
let peers = reserve(format!("{} {online}/{known}", icon::DEVICES));
|
||||
let clients = if users > 0 {
|
||||
reserve(format!("{} {users}", icon::SIGN_IN))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let width = (rect.width() * 0.15).min(64.).min(spare - GAP);
|
||||
if width >= 26. {
|
||||
let plot = Rect::from_center_size(pos2(right - width / 2., center), vec2(width, 14.));
|
||||
format::mini_traffic(&painter, plot, series, unit, quiet, net.active);
|
||||
right = plot.left() - 7.;
|
||||
right = plot.left() - GAP;
|
||||
}
|
||||
let mut field = |text: String, reserved: f32| {
|
||||
let galley = painter.layout_no_wrap(text, font.clone(), ink);
|
||||
if right - left - galley.size().x >= reserved {
|
||||
right -= galley.size().x;
|
||||
painter.galley(pos2(right, center - galley.size().y / 2.), galley, ink);
|
||||
right -= 8.;
|
||||
}
|
||||
};
|
||||
field(format!("{} {online}/{known}", icon::DEVICES), 45.);
|
||||
if users > 0 {
|
||||
field(format!("{} {users}", icon::SIGN_IN), 60.);
|
||||
for galley in [peers, clients, ip].into_iter().flatten() {
|
||||
right -= galley.size().x;
|
||||
painter.galley(pos2(right, center - galley.size().y / 2.), galley, ink);
|
||||
right -= GAP;
|
||||
}
|
||||
if let Some(addr) = net.overlay.as_ref().and_then(|o| o.address.as_deref()) {
|
||||
field(addr.to_owned(), 110.);
|
||||
}
|
||||
let mut job = egui::text::LayoutJob::simple_singleline(
|
||||
net.name.clone(),
|
||||
FontId::new(font.size + 4., egui::FontFamily::Name("Bold".into())),
|
||||
ui.visuals().strong_text_color(),
|
||||
widgets::single_line(
|
||||
&painter,
|
||||
Rect::from_min_max(pos2(left, rect.top()), pos2(right.max(left), rect.bottom())),
|
||||
Align::Min,
|
||||
&net.name,
|
||||
title_font,
|
||||
strong,
|
||||
);
|
||||
job.wrap.max_width = (right - left).max(1.);
|
||||
job.wrap.max_rows = 1;
|
||||
job.wrap.break_anywhere = true;
|
||||
let name = painter.layout_job(job);
|
||||
painter.galley(pos2(left, center - name.size().y / 2.), name, ink);
|
||||
let mut hint = format!("{} · {status}\n{online} online · {known} known", net.name);
|
||||
if let Some(address) = address {
|
||||
hint.push_str(&format!("\n{address}"));
|
||||
}
|
||||
if users > 0 {
|
||||
hint.push_str(&format!("\n{}", user_count(users)));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,147 @@
|
||||
use crate::{
|
||||
client::{Client, Command},
|
||||
widgets,
|
||||
};
|
||||
use egui_phosphor::regular as icon;
|
||||
use tsunagi::ipc::{NetworkReport, ProtocolReport};
|
||||
|
||||
fn set_members(selected: &mut Vec<String>, members: &[&ProtocolReport], on: bool) {
|
||||
if on {
|
||||
for p in members {
|
||||
if !selected.contains(&p.name) {
|
||||
selected.push(p.name.clone());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
selected.retain(|name| !members.iter().any(|p| p.name == *name));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn draw_protocols(
|
||||
ui: &mut egui::Ui,
|
||||
agent: &dyn Client,
|
||||
network: &NetworkReport,
|
||||
available: &[ProtocolReport],
|
||||
) {
|
||||
let mut selected = network.protocols.clone();
|
||||
let caption = if selected.is_empty() {
|
||||
"Data transports · control only".into()
|
||||
} else {
|
||||
format!("Data transports {}/{}", selected.len(), available.len())
|
||||
};
|
||||
egui::CollapsingHeader::new(caption)
|
||||
.id_salt(("protocols", &network.network_id))
|
||||
.show(ui, |ui| {
|
||||
let mut groups = Vec::new();
|
||||
for p in available {
|
||||
if !groups.contains(&p.group.as_str()) {
|
||||
groups.push(p.group.as_str());
|
||||
}
|
||||
}
|
||||
for group in groups {
|
||||
let members: Vec<_> = available.iter().filter(|p| p.group == group).collect();
|
||||
let enabled = members
|
||||
.iter()
|
||||
.filter(|p| selected.contains(&p.name))
|
||||
.count();
|
||||
let all = enabled == members.len();
|
||||
let id = ui.make_persistent_id((&network.network_id, "transport group", group));
|
||||
egui::collapsing_header::CollapsingState::load_with_default_open(
|
||||
ui.ctx(),
|
||||
id,
|
||||
false,
|
||||
)
|
||||
.show_header(ui, |ui| {
|
||||
let mut checked = all;
|
||||
let checkbox =
|
||||
egui::Checkbox::new(&mut checked, egui::RichText::new(group).strong())
|
||||
.indeterminate(enabled != 0 && !all);
|
||||
if ui.add_enabled(!agent.busy(), checkbox).changed() {
|
||||
set_members(&mut selected, &members, !all);
|
||||
}
|
||||
ui.weak(format!("{enabled}/{}", members.len()));
|
||||
})
|
||||
.body(|ui| {
|
||||
for p in &members {
|
||||
ui.push_id(&p.name, |ui| {
|
||||
ui.horizontal(|ui| {
|
||||
ui.spacing_mut().item_spacing.x = 4.;
|
||||
let position = selected.iter().position(|n| n == &p.name);
|
||||
let mut enabled = position.is_some();
|
||||
if ui
|
||||
.add_enabled(
|
||||
!agent.busy(),
|
||||
egui::Checkbox::new(&mut enabled, &p.label),
|
||||
)
|
||||
.changed()
|
||||
{
|
||||
set_members(&mut selected, &[p], enabled);
|
||||
}
|
||||
widgets::info(ui, &p.summary);
|
||||
if let Some(i) = position {
|
||||
widgets::hint(
|
||||
ui.weak(format!("#{}", i + 1)),
|
||||
"Priority across all enabled transports",
|
||||
);
|
||||
for (glyph, next, help) in [
|
||||
(
|
||||
icon::CARET_UP,
|
||||
i.checked_sub(1),
|
||||
"Increase priority across all groups",
|
||||
),
|
||||
(
|
||||
icon::CARET_DOWN,
|
||||
(i + 1 < selected.len()).then_some(i + 1),
|
||||
"Decrease priority across all groups",
|
||||
),
|
||||
] {
|
||||
let r = ui.add_enabled(
|
||||
next.is_some() && !agent.busy(),
|
||||
egui::Button::new(glyph).small().frame(false),
|
||||
);
|
||||
if widgets::hint(r, help).clicked()
|
||||
&& let Some(j) = next
|
||||
{
|
||||
selected.swap(i, j);
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
if selected != network.protocols {
|
||||
agent.send(Command::SetProtocols {
|
||||
network_id: network.network_id.clone(),
|
||||
protocols: selected,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn mixed_and_unchecked_groups_enable_every_child_and_keep_global_order() {
|
||||
let wg = ProtocolReport {
|
||||
name: "wg".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let awg = ProtocolReport {
|
||||
name: "awg".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let members = [&wg, &awg];
|
||||
let mut selected = vec!["ss2022".into(), "awg".into(), "tcp-tls".into()];
|
||||
set_members(&mut selected, &members, true);
|
||||
assert_eq!(selected, ["ss2022", "awg", "tcp-tls", "wg"]);
|
||||
set_members(&mut selected, &members, false);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls"]);
|
||||
set_members(&mut selected, &members, true);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls", "wg", "awg"]);
|
||||
set_members(&mut selected, &[&wg], false);
|
||||
assert_eq!(selected, ["ss2022", "tcp-tls", "awg"]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Fields shared by the table, its column chooser and the history ordering.
|
||||
use super::{Names, endpoints, role_name};
|
||||
use rusqlite::types::Value;
|
||||
use std::net::Ipv4Addr;
|
||||
use tsunagi::traffic::{Flow, FlowKey, IpDetail};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
@@ -86,21 +87,30 @@ impl Column {
|
||||
pub fn uses_names(self) -> bool {
|
||||
matches!(self, Self::Peer | Self::Network | Self::Near | Self::Far)
|
||||
}
|
||||
pub fn ip_endpoint(self, key: &FlowKey) -> Option<(Ipv4Addr, Option<u16>)> {
|
||||
let Flow::Ip {
|
||||
near, far, detail, ..
|
||||
} = key.flow
|
||||
else {
|
||||
return None;
|
||||
};
|
||||
let ip = match self {
|
||||
Self::Near => near,
|
||||
Self::Far => far,
|
||||
_ => return None,
|
||||
};
|
||||
let port = match detail {
|
||||
IpDetail::Ports(a, b) => Some(if self == Self::Near { a } else { b }),
|
||||
_ => None,
|
||||
};
|
||||
Some((ip.into(), port))
|
||||
}
|
||||
// SQLite indexes this value only while sorting by a descriptive column.
|
||||
// Numeric IPv4 address and port order is independent of their spelling.
|
||||
pub fn label_key(self, key: &FlowKey, names: &Names) -> Value {
|
||||
if let Flow::Ip {
|
||||
near, far, detail, ..
|
||||
} = key.flow
|
||||
&& matches!(self, Self::Near | Self::Far)
|
||||
{
|
||||
let near_side = self == Self::Near;
|
||||
let ip = u32::from_be_bytes(if near_side { near } else { far });
|
||||
let port = match detail {
|
||||
IpDetail::Ports(a, b) => 1 + i64::from(if near_side { a } else { b }),
|
||||
_ => 0,
|
||||
};
|
||||
return Value::Integer((i64::from(ip) << 17) + port);
|
||||
if let Some((ip, port)) = self.ip_endpoint(key) {
|
||||
let port = port.map_or(0, |p| i64::from(p) + 1);
|
||||
return Value::Integer((i64::from(u32::from(ip)) << 17) + port);
|
||||
}
|
||||
let label = match self {
|
||||
Self::Peer => names.peer(&key.network, &key.peer),
|
||||
|
||||
@@ -14,7 +14,8 @@ use history::{Cursor, Filter};
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
|
||||
use tsunagi::{
|
||||
NetworkId,
|
||||
ipc::StatusReport,
|
||||
dns::ZoneName,
|
||||
ipc::{NetworkReport, StatusReport},
|
||||
iroh_types::EndpointId,
|
||||
traffic::{Flow, FlowKey, IpDetail, Role},
|
||||
};
|
||||
@@ -31,6 +32,8 @@ struct Network {
|
||||
struct Names {
|
||||
networks: BTreeMap<Id, Network>,
|
||||
generation: Option<u64>,
|
||||
addresses: BTreeMap<(Id, Ipv4Addr), String>,
|
||||
resolve_addresses: bool,
|
||||
}
|
||||
|
||||
fn public_id(id: &Id) -> String {
|
||||
@@ -43,11 +46,13 @@ impl Names {
|
||||
return false;
|
||||
}
|
||||
self.generation = Some(generation);
|
||||
self.addresses.clear();
|
||||
let mut changed = false;
|
||||
for n in &report.networks {
|
||||
let Ok(id) = n.network_id.parse::<NetworkId>() else {
|
||||
continue;
|
||||
};
|
||||
self.index_addresses(*id.as_bytes(), n, &report.hostname);
|
||||
let entry = self.networks.entry(*id.as_bytes()).or_default();
|
||||
if entry.name != n.name {
|
||||
entry.name.clone_from(&n.name);
|
||||
@@ -97,6 +102,53 @@ impl Names {
|
||||
}
|
||||
changed
|
||||
}
|
||||
fn index_addresses(&mut self, id: Id, network: &NetworkReport, hostname: &str) {
|
||||
let Ok(zone) = ZoneName::new(&network.name) else {
|
||||
return;
|
||||
};
|
||||
let mut add = |address: Option<Ipv4Addr>, name: Option<&str>| {
|
||||
if let (Some(ip), Some(name)) = (
|
||||
address,
|
||||
name.map(|s| s.trim_matches('.')).filter(|s| !s.is_empty()),
|
||||
) {
|
||||
self.addresses
|
||||
.entry((id, ip))
|
||||
.or_insert_with(|| format!("{}.{}", name.to_ascii_lowercase(), zone.as_str()));
|
||||
}
|
||||
};
|
||||
if network.hostname_conflict.is_none()
|
||||
&& let Some(own) = &network.overlay
|
||||
{
|
||||
add(
|
||||
own.address.as_deref().and_then(|s| s.parse().ok()),
|
||||
Some(hostname),
|
||||
);
|
||||
}
|
||||
for member in &network.members {
|
||||
if member.hostname_conflict.is_none() {
|
||||
add(
|
||||
member
|
||||
.overlay_address_v4
|
||||
.as_deref()
|
||||
.and_then(|s| s.parse().ok()),
|
||||
member.hostname.as_deref(),
|
||||
);
|
||||
}
|
||||
}
|
||||
for vip in &network.vips {
|
||||
if vip.error.is_none() {
|
||||
add(vip.address, Some(&vip.config.name));
|
||||
}
|
||||
}
|
||||
}
|
||||
fn resolved_endpoint(&self, key: &FlowKey, column: Column) -> Option<String> {
|
||||
let (ip, port) = column.ip_endpoint(key)?;
|
||||
let name = self.addresses.get(&(key.network, ip))?;
|
||||
Some(match port {
|
||||
Some(port) => format!("{name}:{port}"),
|
||||
None => name.clone(),
|
||||
})
|
||||
}
|
||||
fn network(&self, id: &Id) -> String {
|
||||
let Some(n) = self.networks.get(id) else {
|
||||
return short(&NetworkId::from_bytes(*id).to_string());
|
||||
@@ -207,7 +259,10 @@ impl Window {
|
||||
pub fn new(directory: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
worker: Worker::new(directory),
|
||||
names: Names::default(),
|
||||
names: Names {
|
||||
resolve_addresses: true,
|
||||
..Names::default()
|
||||
},
|
||||
filter: Filter::default(),
|
||||
keep: false,
|
||||
previous: Vec::new(),
|
||||
@@ -220,12 +275,16 @@ impl Window {
|
||||
}
|
||||
|
||||
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
|
||||
if ui.available_width() < 540. {
|
||||
ui.horizontal(|ui| self.layers(ui));
|
||||
if ui.available_width() < 620. {
|
||||
ui.horizontal_wrapped(|ui| {
|
||||
self.layers(ui);
|
||||
self.resolve_option(ui);
|
||||
});
|
||||
ui.horizontal(|ui| self.history_controls(ui, grid));
|
||||
} else {
|
||||
ui.horizontal(|ui| {
|
||||
self.layers(ui);
|
||||
self.resolve_option(ui);
|
||||
self.history_controls(ui, grid);
|
||||
});
|
||||
}
|
||||
@@ -262,6 +321,15 @@ impl Window {
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_option(&mut self, ui: &mut Ui) {
|
||||
if !self.filter.transport {
|
||||
widgets::hint(
|
||||
ui.checkbox(&mut self.names.resolve_addresses, "Resolve names"),
|
||||
"Show this network’s peer and VIP names. Hover or hold a name to see its IP address.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn history_controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
|
||||
widgets::hint(
|
||||
ui.checkbox(&mut self.keep, "Keep until close"),
|
||||
|
||||
@@ -328,7 +328,19 @@ impl Grid {
|
||||
_ => &self.body,
|
||||
};
|
||||
let bounds = slot.rect(row);
|
||||
let response = cell(ui, bounds, &label, font, self.ink(col), numeric(col));
|
||||
let resolved = if names.resolve_addresses {
|
||||
names.resolved_endpoint(key, col)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let response = cell(
|
||||
ui,
|
||||
bounds,
|
||||
resolved.as_deref().unwrap_or(&label),
|
||||
font,
|
||||
self.ink(col),
|
||||
numeric(col),
|
||||
);
|
||||
if col == PeerId {
|
||||
let full = public_id(&key.peer);
|
||||
let button = ui
|
||||
@@ -344,6 +356,9 @@ impl Grid {
|
||||
if widgets::hint(button, &format!("Copy peer ID\n{full}")).clicked() {
|
||||
ui.ctx().copy_text(full);
|
||||
}
|
||||
} else if resolved.is_some() {
|
||||
// A click sense also gives Android long presses a target.
|
||||
widgets::hint(response.interact(Sense::click()), &label);
|
||||
} else {
|
||||
widgets::hint(response, &label);
|
||||
}
|
||||
|
||||
@@ -207,6 +207,76 @@ fn a_stale_member_name_does_not_reindex_the_capture_every_refresh() {
|
||||
assert_eq!(names.peer(network.as_bytes(), peer.as_bytes()), "old");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn endpoint_names_use_the_rows_network_and_current_peer_and_vip_records() {
|
||||
use super::{Column, Names};
|
||||
use tsunagi::ipc::{MemberReport, NetworkReport, OverlayReport, StatusReport};
|
||||
use tsunagi::vip::{VipConfig, VipStatus};
|
||||
|
||||
let network = |id, name: &str, host: &str| NetworkReport {
|
||||
network_id: tsunagi::NetworkId::from_bytes([id; 32]).to_string(),
|
||||
name: name.into(),
|
||||
members: vec![MemberReport {
|
||||
hostname: Some(host.into()),
|
||||
overlay_address_v4: Some("10.0.0.2".into()),
|
||||
..Default::default()
|
||||
}],
|
||||
overlay: Some(OverlayReport {
|
||||
address: Some("10.0.0.1".into()),
|
||||
..Default::default()
|
||||
}),
|
||||
..Default::default()
|
||||
};
|
||||
let mut report = StatusReport {
|
||||
hostname: "laptop".into(),
|
||||
networks: vec![network(1, "tsng", "music"), network(2, "vpn", "home")],
|
||||
..Default::default()
|
||||
};
|
||||
report.networks[0].vips.push(VipStatus {
|
||||
config: VipConfig::new("radio"),
|
||||
revision: String::new(),
|
||||
address: Some("10.0.0.3".parse().unwrap()),
|
||||
error: None,
|
||||
listeners: vec![],
|
||||
});
|
||||
let mut names = Names::default();
|
||||
names.refresh(Some(&report), 1);
|
||||
let mut key = sample(55201, true).key;
|
||||
assert_eq!(
|
||||
names.resolved_endpoint(&key, Column::Near).as_deref(),
|
||||
Some("laptop.tsng:55201")
|
||||
);
|
||||
assert_eq!(
|
||||
names.resolved_endpoint(&key, Column::Far).as_deref(),
|
||||
Some("music.tsng:443")
|
||||
);
|
||||
key.network = [2; 32];
|
||||
assert_eq!(
|
||||
names.resolved_endpoint(&key, Column::Far).as_deref(),
|
||||
Some("home.vpn:443")
|
||||
);
|
||||
key.network = [1; 32];
|
||||
key.flow = Flow::Ip {
|
||||
near: [10, 0, 0, 3],
|
||||
far: [1, 1, 1, 1],
|
||||
protocol: 1,
|
||||
detail: IpDetail::Echo,
|
||||
};
|
||||
assert_eq!(
|
||||
names.resolved_endpoint(&key, Column::Near).as_deref(),
|
||||
Some("radio.tsng")
|
||||
);
|
||||
assert_eq!(names.resolved_endpoint(&key, Column::Far), None);
|
||||
report.networks[0].vips[0].error = Some("address conflict".into());
|
||||
report.networks[0].members.clear();
|
||||
names.refresh(Some(&report), 2);
|
||||
assert_eq!(names.resolved_endpoint(&key, Column::Near), None);
|
||||
assert_eq!(
|
||||
names.resolved_endpoint(&sample(1, true).key, Column::Far),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sorting_uses_display_names_numeric_endpoints_and_live_rates() {
|
||||
use super::{Column, Names, Network, Sort};
|
||||
@@ -280,7 +350,14 @@ fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
|
||||
let ctx = Context::default();
|
||||
ctx.set_theme(theme);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| {
|
||||
s.interaction.tooltip_delay = 0.;
|
||||
s.interaction.show_tooltips_only_when_still = false;
|
||||
});
|
||||
let mut win = Window::new(None);
|
||||
win.names
|
||||
.addresses
|
||||
.insert(([1; 32], [10, 0, 0, 2].into()), "music.lab".into());
|
||||
win.names.networks.insert(
|
||||
[1; 32],
|
||||
Network {
|
||||
@@ -366,6 +443,29 @@ fn monitor_rows_stay_on_one_line_and_headers_sort_in_both_themes() {
|
||||
wait(win);
|
||||
};
|
||||
let mut frame = draw(&mut win, vec![]);
|
||||
let checkbox = label(&frame, "Resolve names").0.center();
|
||||
if width > 900. {
|
||||
let name = label(&frame, "music.lab:443").0.center();
|
||||
draw(&mut win, vec![Event::PointerMoved(name)]);
|
||||
frame = draw(&mut win, vec![]);
|
||||
assert!(
|
||||
frame.shapes.iter().any(
|
||||
|s| matches!(&s.shape, Shape::Text(t) if t.galley.text() == "10.0.0.2:443")
|
||||
),
|
||||
"hovering a resolved name reveals the numeric endpoint"
|
||||
);
|
||||
click(&mut win, checkbox);
|
||||
frame = draw(&mut win, vec![]);
|
||||
label(&frame, "10.0.0.2:443");
|
||||
assert!(
|
||||
!frame.shapes.iter().any(
|
||||
|s| matches!(&s.shape, Shape::Text(t) if t.galley.text() == "music.lab:443")
|
||||
)
|
||||
);
|
||||
click(&mut win, checkbox);
|
||||
frame = draw(&mut win, vec![]);
|
||||
label(&frame, "music.lab:443");
|
||||
}
|
||||
let chooser = frame
|
||||
.shapes
|
||||
.iter()
|
||||
|
||||
@@ -54,6 +54,58 @@ fn keyboard_focus_explains_an_icon_and_the_shared_font_contains_the_status_glyph
|
||||
assert!(label(&draw(0.2), "Show secret").is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn long_protocol_hints_wrap_inside_narrow_windows_on_hover_and_focus() {
|
||||
const DETAIL: &str =
|
||||
"Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt";
|
||||
for (width, enabled, focus) in [
|
||||
(360., true, false),
|
||||
(320., false, false),
|
||||
(240., true, true),
|
||||
] {
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Mac);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| s.interaction.tooltip_delay = 0.);
|
||||
let size = egui::vec2(width, 400.);
|
||||
let draw = |time, events| {
|
||||
frame(&ctx, size, time, events, |ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
ui.with_layout(egui::Layout::right_to_left(egui::Align::TOP), |ui| {
|
||||
let button = ui.add_enabled(enabled, egui::Button::new(icon::INFO));
|
||||
if focus {
|
||||
button.request_focus();
|
||||
}
|
||||
crate::widgets::hint(button, DETAIL);
|
||||
});
|
||||
});
|
||||
})
|
||||
};
|
||||
let first = draw(0., vec![]);
|
||||
let pos = label(&first, icon::INFO).unwrap().center();
|
||||
draw(0.1, vec![Event::PointerMoved(pos)]);
|
||||
draw(0.8, vec![]);
|
||||
let out = draw(1., vec![]);
|
||||
let (text, clip) = out
|
||||
.shapes
|
||||
.iter()
|
||||
.find_map(|s| match &s.shape {
|
||||
egui::Shape::Text(t) if t.galley.text() == DETAIL => Some((t, s.clip_rect)),
|
||||
_ => None,
|
||||
})
|
||||
.expect("the full tooltip should be shown");
|
||||
let ink = text.visual_bounding_rect();
|
||||
assert!(
|
||||
text.galley.rows.len() > 1,
|
||||
"the tooltip stayed on one line at width {width}"
|
||||
);
|
||||
assert!(
|
||||
Rect::from_min_size(Pos2::ZERO, size).contains_rect(ink) && clip.contains_rect(ink),
|
||||
"window {width}, clip {clip:?}, text {ink:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
struct ReadOnly;
|
||||
impl Client for ReadOnly {
|
||||
fn busy(&self) -> bool {
|
||||
@@ -180,6 +232,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
hops: 2,
|
||||
via: "another".into(),
|
||||
},
|
||||
data_rtt_ms: matches!(state, "ready" | "idle").then_some(37),
|
||||
data_error: match state {
|
||||
"waiting" => Some(tsunagi::agent::DATA_CONNECTING.into()),
|
||||
"error" => Some("Carrier unavailable".into()),
|
||||
@@ -204,6 +257,7 @@ fn rotating_the_devices_view_keeps_the_peer_and_fits_traffic_and_states_on_scree
|
||||
OverlayPeerReport {
|
||||
endpoint_id: id.into(),
|
||||
idle: true,
|
||||
handshake_secs_ago: Some(8),
|
||||
..Default::default()
|
||||
}
|
||||
}));
|
||||
@@ -441,6 +495,61 @@ fn desktop_full_table_survives_long_names_and_compact_exit_icon_starts_and_stops
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collapsed_vpn_keeps_its_address_as_peers_reconnect() {
|
||||
let ctx = Context::default();
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
let mut state = home::UiState::default();
|
||||
let report = tsunagi::ipc::StatusReport::default();
|
||||
let address = "10.78.107.201";
|
||||
let mut network = NetworkReport {
|
||||
name: "vpn".into(),
|
||||
active: true,
|
||||
overlay: Some(OverlayReport {
|
||||
address: Some(address.into()),
|
||||
..Default::default()
|
||||
}),
|
||||
members: (0..14)
|
||||
.map(|i| MemberReport {
|
||||
endpoint_id: format!("peer-{i}"),
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..Default::default()
|
||||
};
|
||||
for width in [320., 359.] {
|
||||
for online in [1, 9, 10, 12, 14] {
|
||||
for (i, member) in network.members.iter_mut().enumerate() {
|
||||
member.online = i < online;
|
||||
}
|
||||
let out = frame(
|
||||
&ctx,
|
||||
egui::vec2(width, 240.),
|
||||
online as f64,
|
||||
vec![],
|
||||
|ctx| {
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
home::draw_network(
|
||||
ui,
|
||||
&ReadOnly,
|
||||
&mut state,
|
||||
&Traffic::default(),
|
||||
&network,
|
||||
&report,
|
||||
true,
|
||||
);
|
||||
});
|
||||
},
|
||||
);
|
||||
let name = label(&out, "vpn").unwrap();
|
||||
let address = label(&out, address).expect("the local address stays visible");
|
||||
let count = label(&out, &format!("{} {online}/14", icon::DEVICES)).unwrap();
|
||||
assert!(name.right() < address.left() && address.right() < count.left());
|
||||
assert!(count.right() <= width);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_users_scroll_a_row_inside_the_existing_card_and_disappear_on_deselection() {
|
||||
for (width, os) in [
|
||||
@@ -589,3 +698,105 @@ fn exit_users_scroll_a_row_inside_the_existing_card_and_disappear_on_deselection
|
||||
assert!((h - baseline).abs() < 1.);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn protocol_groups_toggle_in_one_command_and_fit_on_a_phone() {
|
||||
use std::cell::RefCell;
|
||||
use tsunagi::ipc::{ProtocolReport, StatusReport};
|
||||
#[derive(Default)]
|
||||
struct Edits(RefCell<Vec<Vec<String>>>);
|
||||
impl Client for Edits {
|
||||
fn busy(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn send(&self, command: Command) {
|
||||
let Command::SetProtocols {
|
||||
network_id,
|
||||
protocols,
|
||||
} = command
|
||||
else {
|
||||
panic!("unexpected action")
|
||||
};
|
||||
assert_eq!(network_id, "lab");
|
||||
self.0.borrow_mut().push(protocols);
|
||||
}
|
||||
}
|
||||
let edits = Edits::default();
|
||||
let ctx = Context::default();
|
||||
ctx.set_os(egui::os::OperatingSystem::Android);
|
||||
ctx.set_fonts(crate::app_fonts());
|
||||
ctx.style_mut(|s| s.animation_time = 0.);
|
||||
let mut state = home::UiState::default();
|
||||
let report = StatusReport {
|
||||
available_protocols: [
|
||||
("Native", "tcp-tls", "TCP + TLS"),
|
||||
("Shoes", "vless-xhttp", "VLESS + XHTTP"),
|
||||
("Shoes", "ss2022", "Shadowsocks 2022"),
|
||||
]
|
||||
.map(|(group, name, label)| ProtocolReport {
|
||||
group: group.into(),
|
||||
name: name.into(),
|
||||
label: label.into(),
|
||||
summary: format!("Details for {label}"),
|
||||
})
|
||||
.into(),
|
||||
..Default::default()
|
||||
};
|
||||
let selected = RefCell::new(vec!["tcp-tls".into(), "ss2022".into()]);
|
||||
let mut draw = |time, events| {
|
||||
frame(&ctx, egui::vec2(320., 700.), time, events, |ctx| {
|
||||
let network = NetworkReport {
|
||||
network_id: "lab".into(),
|
||||
protocols: selected.borrow().clone(),
|
||||
..Default::default()
|
||||
};
|
||||
egui::CentralPanel::default().show(ctx, |ui| {
|
||||
home::draw_network_details(
|
||||
ui,
|
||||
&edits,
|
||||
&mut state,
|
||||
&Traffic::default(),
|
||||
&network,
|
||||
&report,
|
||||
false,
|
||||
)
|
||||
});
|
||||
})
|
||||
};
|
||||
draw(0., vec![]);
|
||||
let out = draw(0.1, vec![]);
|
||||
let at = label(&out, "Data transports 2/3").unwrap().center();
|
||||
draw(0.2, vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(0.3, vec![press(at, false)]);
|
||||
let out = draw(0.4, vec![]);
|
||||
let group = label(&out, "Shoes").unwrap();
|
||||
for (step, expected) in [
|
||||
vec!["tcp-tls", "ss2022", "vless-xhttp"],
|
||||
vec!["tcp-tls"],
|
||||
vec!["tcp-tls", "vless-xhttp", "ss2022"],
|
||||
]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
{
|
||||
let at = group.center();
|
||||
let t = 1. + step as f64;
|
||||
draw(t, vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(t + 0.1, vec![press(at, false)]);
|
||||
let received = std::mem::take(&mut *edits.0.borrow_mut());
|
||||
assert_eq!(received, [expected]);
|
||||
*selected.borrow_mut() = received[0].clone();
|
||||
draw(t + 0.2, vec![]);
|
||||
}
|
||||
// The disclosure arrow is before the checkbox and label. Expanding keeps the selection.
|
||||
let at = egui::pos2(group.left() - 37., group.center().y);
|
||||
draw(5., vec![Event::PointerMoved(at), press(at, true)]);
|
||||
draw(5.1, vec![press(at, false)]);
|
||||
let out = draw(5.2, vec![]);
|
||||
assert!(label(&out, "Shadowsocks 2022").unwrap().right() < 320.);
|
||||
assert!(label(&out, "Details for VLESS + XHTTP").is_none());
|
||||
let info = label(&out, icon::INFO).unwrap().center();
|
||||
draw(5.3, vec![Event::PointerMoved(info), press(info, true)]);
|
||||
draw(5.4, vec![press(info, false)]);
|
||||
assert!(label(&draw(5.5, vec![]), "Details for VLESS + XHTTP").is_some());
|
||||
assert!(edits.0.borrow().is_empty());
|
||||
}
|
||||
@@ -3,6 +3,16 @@
|
||||
|
||||
pub(crate) const GAP: f32 = 10.0;
|
||||
|
||||
pub(crate) fn row_height(ctx: &egui::Context, style: &egui::Style) -> f32 {
|
||||
let font = egui::FontSelection::Default.resolve(style);
|
||||
style
|
||||
.spacing
|
||||
.interact_size
|
||||
.y
|
||||
.max(ctx.fonts(|fonts| fonts.row_height(&font)))
|
||||
+ 10.
|
||||
}
|
||||
|
||||
pub(crate) fn row(
|
||||
ui: &mut egui::Ui,
|
||||
id: impl std::hash::Hash,
|
||||
@@ -10,9 +20,7 @@ pub(crate) fn row(
|
||||
stripe: bool,
|
||||
mut cell: impl FnMut(usize, &mut egui::Ui),
|
||||
) {
|
||||
let font = egui::FontSelection::Default.resolve(ui.style());
|
||||
let text_height = ui.fonts(|fonts| fonts.row_height(&font));
|
||||
let height = ui.spacing().interact_size.y.max(text_height) + 10.0;
|
||||
let height = row_height(ui.ctx(), ui.style());
|
||||
let width = widths.iter().sum::<f32>() + GAP * widths.len().saturating_sub(1) as f32;
|
||||
let (rect, _) = ui.allocate_exact_size(egui::vec2(width, height), egui::Sense::hover());
|
||||
if stripe {
|
||||
|
||||
@@ -26,26 +26,43 @@ pub fn hint(response: Response, description: &str) -> Response {
|
||||
let held = ctx
|
||||
.data(|d| d.get_temp::<(egui::Id, f64)>(key))
|
||||
.filter(|(id, until)| touch && *id == response.id && now < *until);
|
||||
let contents = |ui: &mut Ui| {
|
||||
let padding = egui::Frame::popup(ui.style()).total_margin().sum().x;
|
||||
let available = (ui.ctx().screen_rect().width() - padding).max(1.);
|
||||
ui.set_max_width(ui.spacing().tooltip_width.min(available));
|
||||
ui.add(egui::Label::new(description).wrap());
|
||||
};
|
||||
if held.is_some() || (!touch && response.has_focus()) {
|
||||
egui::show_tooltip_for(ctx, response.layer_id, response.id, &response.rect, |ui| {
|
||||
ui.set_max_width(
|
||||
ui.spacing()
|
||||
.tooltip_width
|
||||
.min(ctx.screen_rect().width() - 16.),
|
||||
);
|
||||
ui.label(description);
|
||||
});
|
||||
egui::show_tooltip_for(
|
||||
ctx,
|
||||
response.layer_id,
|
||||
response.id,
|
||||
&response.rect,
|
||||
contents,
|
||||
);
|
||||
if let Some((_, until)) = held {
|
||||
ctx.request_repaint_after_secs((until - now) as f32);
|
||||
}
|
||||
response
|
||||
} else {
|
||||
response
|
||||
.on_hover_text(description)
|
||||
.on_disabled_hover_text(description)
|
||||
.on_hover_ui(contents)
|
||||
.on_disabled_hover_ui(contents)
|
||||
}
|
||||
}
|
||||
|
||||
/// A compact help button. Tapping reveals the same detail as desktop hover.
|
||||
pub(crate) fn info(ui: &mut Ui, description: &str) {
|
||||
let r = ui.add(egui::Button::new(egui::RichText::new(icon::INFO).weak()).frame(false));
|
||||
r.widget_info(|| WidgetInfo::labeled(WidgetType::Button, true, description));
|
||||
if r.clicked() && ui.ctx().os() == egui::os::OperatingSystem::Android {
|
||||
let until = ui.input(|i| i.time) + 2.5;
|
||||
let key = egui::Id::new(("touch explanation", ui.ctx().viewport_id()));
|
||||
ui.ctx().data_mut(|d| d.insert_temp(key, (r.id, until)));
|
||||
}
|
||||
hint(r, description);
|
||||
}
|
||||
|
||||
/// A glyph-only button with its action exposed to assistive technology.
|
||||
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
|
||||
let r = ui.button(glyph);
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
[package]
|
||||
name = "tsunagi-vless-xhttp"
|
||||
version = "1.0.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
license = "MIT"
|
||||
repository.workspace = true
|
||||
description = "VLESS over XHTTP, HTTP/2 and TLS for peer-to-peer mesh links."
|
||||
|
||||
[dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||
http = "1"
|
||||
h2 = "0.4"
|
||||
rustls = "0.23"
|
||||
tokio-rustls = "0.26"
|
||||
bytes.workspace = true
|
||||
hex.workspace = true
|
||||
rand = "0.10"
|
||||
subtle = "2.6"
|
||||
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,104 @@
|
||||
//! Adapted from Shoes v0.3.8, src/http2/stream.rs (MIT).
|
||||
use bytes::Bytes;
|
||||
use std::{
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
pub(crate) struct H2MultiStream {
|
||||
send: h2::SendStream<Bytes>,
|
||||
recv: h2::RecvStream,
|
||||
recv_buf: Bytes,
|
||||
shutdown_sent: bool,
|
||||
}
|
||||
impl H2MultiStream {
|
||||
pub(crate) fn new(send: h2::SendStream<Bytes>, recv: h2::RecvStream) -> Self {
|
||||
Self {
|
||||
send,
|
||||
recv,
|
||||
recv_buf: Bytes::new(),
|
||||
shutdown_sent: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl AsyncRead for H2MultiStream {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
if buf.remaining() == 0 {
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
// Empty DATA is not EOF. Bound work per poll even for a padding-only peer.
|
||||
for _ in 0..32 {
|
||||
if !self.recv_buf.is_empty() {
|
||||
let count = self.recv_buf.len().min(buf.remaining());
|
||||
buf.put_slice(&self.recv_buf.split_to(count));
|
||||
self.recv
|
||||
.flow_control()
|
||||
.release_capacity(count)
|
||||
.map_err(io::Error::other)?;
|
||||
return Poll::Ready(Ok(()));
|
||||
}
|
||||
match std::task::ready!(self.recv.poll_data(cx)) {
|
||||
Some(Ok(data)) => self.recv_buf = data,
|
||||
Some(Err(e)) => return Poll::Ready(Err(io::Error::other(e))),
|
||||
None => return Poll::Ready(Ok(())),
|
||||
}
|
||||
}
|
||||
cx.waker().wake_by_ref();
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for H2MultiStream {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
if buf.is_empty() {
|
||||
return Poll::Ready(Ok(0));
|
||||
}
|
||||
if self.shutdown_sent {
|
||||
return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into()));
|
||||
}
|
||||
let wanted = buf.len().min(16 * 1024);
|
||||
let send = &mut self.send;
|
||||
send.reserve_capacity(wanted);
|
||||
loop {
|
||||
let capacity = send.capacity();
|
||||
if capacity != 0 {
|
||||
let count = wanted.min(capacity);
|
||||
send.send_data(Bytes::copy_from_slice(&buf[..count]), false)
|
||||
.map_err(io::Error::other)?;
|
||||
return Poll::Ready(Ok(count));
|
||||
}
|
||||
match std::task::ready!(send.poll_capacity(cx)) {
|
||||
Some(Ok(_)) => continue,
|
||||
Some(Err(e)) => return Poll::Ready(Err(io::Error::other(e))),
|
||||
None => return Poll::Ready(Err(io::ErrorKind::BrokenPipe.into())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
// h2 has no per-stream flush; the connection driver handles transmission
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
if !self.shutdown_sent {
|
||||
self.send
|
||||
.send_data(Bytes::new(), true)
|
||||
.map_err(io::Error::other)?;
|
||||
self.shutdown_sent = true;
|
||||
}
|
||||
|
||||
// Don't wait for peer ACK; the connection driver transmits END_STREAM reliably
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
//! Shoes' XHTTP stream-one and VLESS TCP profile over HTTP/2 and pinned TLS 1.3.
|
||||
//! Wire formats adapted from cfal/shoes v0.3.8 (MIT), xhttp/wire.rs and vless/.
|
||||
mod h2_stream;
|
||||
use bytes::Bytes;
|
||||
use h2_stream::H2MultiStream;
|
||||
use iroh::EndpointId;
|
||||
use rustls::pki_types::ServerName;
|
||||
use std::{io, sync::Arc};
|
||||
use subtle::ConstantTimeEq;
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt},
|
||||
net::TcpStream,
|
||||
};
|
||||
use tsunagi::{BoxFuture, identity::DeviceIdentity};
|
||||
use tsunagi_shoes::{Profile, Profiles, ShoesWire, Stream, Ticket, driven};
|
||||
use tsunagi_tcp_tls::cert::{generate_self_signed_cert, make_client_config, make_server_config};
|
||||
use zeroize::Zeroizing;
|
||||
|
||||
/// Catalog identifier, independent of Tsunagi's software version.
|
||||
pub const PROTOCOL: &str = "vless-xhttp";
|
||||
/// Initial compatible wire format.
|
||||
pub const WIRE_VERSION: u16 = 1;
|
||||
/// Preferred physical port.
|
||||
pub const PORT: u16 = 9443;
|
||||
|
||||
const TARGET: [u8; 9] = [0, 1, 0, 1, 1, 127, 0, 0, 1]; // no addons, TCP, port 1, IPv4
|
||||
const HEADER_LIMIT: u32 = 8192;
|
||||
|
||||
/// One HTTP/2 endpoint identified by its persistent mesh public key.
|
||||
pub struct VlessXhttp {
|
||||
tls: tokio_rustls::TlsAcceptor,
|
||||
}
|
||||
impl VlessXhttp {
|
||||
/// Construct a server without DNS, public certificates or web ingress.
|
||||
pub fn new(
|
||||
identity: &DeviceIdentity,
|
||||
) -> Result<Self, Box<dyn std::error::Error + Send + Sync>> {
|
||||
let (cert, key) = generate_self_signed_cert(&identity.secret_bytes(), "localhost")?;
|
||||
let mut tls = make_server_config(cert, key)?;
|
||||
Arc::make_mut(&mut tls).alpn_protocols = vec![b"h2".to_vec()];
|
||||
Ok(Self { tls: tls.into() })
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid() -> io::Error {
|
||||
io::Error::new(io::ErrorKind::InvalidData, "invalid VLESS/XHTTP handshake")
|
||||
}
|
||||
fn header(p: &Profile) -> Zeroizing<[u8; 26]> {
|
||||
let mut bytes = Zeroizing::new([0; 26]);
|
||||
bytes[1..17].copy_from_slice(&p.secret[..16]);
|
||||
// RFC 9562 UUIDv4 version and variant.
|
||||
bytes[7] = (bytes[7] & 0x0f) | 0x40;
|
||||
bytes[9] = (bytes[9] & 0x3f) | 0x80;
|
||||
bytes[17..].copy_from_slice(&TARGET);
|
||||
bytes
|
||||
}
|
||||
fn request(p: &Profile, authority: std::net::SocketAddr) -> io::Result<http::Request<()>> {
|
||||
let path = format!("/{}/", hex::encode(p.tag));
|
||||
let uri = format!("https://{authority}{path}");
|
||||
let padding = "X".repeat(rand::random_range(100..=1000));
|
||||
http::Request::post(&uri)
|
||||
.header("referer", format!("{uri}?x_padding={padding}"))
|
||||
.header("content-type", "application/grpc")
|
||||
.body(())
|
||||
.map_err(io::Error::other)
|
||||
}
|
||||
fn request_tag<T>(req: &http::Request<T>) -> io::Result<[u8; 32]> {
|
||||
if req.method() != http::Method::POST || req.uri().scheme_str() != Some("https") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let path = req
|
||||
.uri()
|
||||
.path()
|
||||
.strip_prefix('/')
|
||||
.and_then(|p| p.strip_suffix('/'))
|
||||
.ok_or_else(invalid)?;
|
||||
let referer: http::Uri = req
|
||||
.headers()
|
||||
.get("referer")
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.and_then(|s| s.parse().ok())
|
||||
.ok_or_else(invalid)?;
|
||||
let padding = referer
|
||||
.query()
|
||||
.and_then(|q| q.strip_prefix("x_padding="))
|
||||
.ok_or_else(invalid)?;
|
||||
if !(100..=1000).contains(&padding.len()) || path.len() != 64 {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut tag = [0; 32];
|
||||
hex::decode_to_slice(path, &mut tag).map_err(|_| invalid())?;
|
||||
Ok(tag)
|
||||
}
|
||||
|
||||
impl ShoesWire for VlessXhttp {
|
||||
fn name(&self) -> &'static str {
|
||||
PROTOCOL
|
||||
}
|
||||
fn version(&self) -> u16 {
|
||||
WIRE_VERSION
|
||||
}
|
||||
fn connect<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
peer: EndpointId,
|
||||
profile: &'a Profile,
|
||||
) -> BoxFuture<'a, io::Result<Stream>> {
|
||||
Box::pin(async move {
|
||||
let mut config = make_client_config(peer).map_err(io::Error::other)?;
|
||||
Arc::make_mut(&mut config).alpn_protocols = vec![b"h2".to_vec()];
|
||||
let address = tcp.peer_addr()?;
|
||||
let tls = tokio_rustls::TlsConnector::from(config)
|
||||
.connect(ServerName::IpAddress(address.ip().into()), tcp)
|
||||
.await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let (sender, mut connection) = h2::client::Builder::new()
|
||||
.max_header_list_size(HEADER_LIMIT)
|
||||
.enable_push(false)
|
||||
.handshake::<_, Bytes>(tls)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let open = async {
|
||||
let mut sender = sender.ready().await.map_err(io::Error::other)?;
|
||||
let (response, mut send) = sender
|
||||
.send_request(request(profile, address)?, false)
|
||||
.map_err(io::Error::other)?;
|
||||
send.send_data(Bytes::copy_from_slice(&header(profile)[..]), false)
|
||||
.map_err(io::Error::other)?;
|
||||
let response = response.await.map_err(io::Error::other)?;
|
||||
if response.status() != http::StatusCode::OK {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(H2MultiStream::new(send, response.into_body()))
|
||||
};
|
||||
let stream = tokio::select! { _ = &mut connection => return Err(invalid()), result = open => result? };
|
||||
let mut stream = driven(stream, async move {
|
||||
let _ = connection.await;
|
||||
});
|
||||
let mut response = [0; 2];
|
||||
stream.read_exact(&mut response).await?;
|
||||
if response != [0, 0] {
|
||||
return Err(invalid());
|
||||
}
|
||||
Ok(stream)
|
||||
})
|
||||
}
|
||||
fn accept<'a>(
|
||||
&'a self,
|
||||
tcp: TcpStream,
|
||||
profiles: &'a Profiles,
|
||||
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>> {
|
||||
Box::pin(async move {
|
||||
let tls = self.tls.accept(tcp).await?;
|
||||
if tls.get_ref().1.alpn_protocol() != Some(b"h2") {
|
||||
return Err(invalid());
|
||||
}
|
||||
let mut conn = h2::server::Builder::new()
|
||||
.max_header_list_size(HEADER_LIMIT)
|
||||
.max_concurrent_streams(1)
|
||||
.handshake::<_, Bytes>(tls)
|
||||
.await
|
||||
.map_err(io::Error::other)?;
|
||||
let (req, mut respond) = conn
|
||||
.accept()
|
||||
.await
|
||||
.ok_or_else(invalid)?
|
||||
.map_err(io::Error::other)?;
|
||||
let ticket = profiles.lookup(&request_tag(&req)?)?;
|
||||
let response = http::Response::builder()
|
||||
.header("content-type", "application/grpc")
|
||||
.header("cache-control", "no-store")
|
||||
.body(())
|
||||
.map_err(io::Error::other)?;
|
||||
let send = respond
|
||||
.send_response(response, false)
|
||||
.map_err(io::Error::other)?;
|
||||
let mut stream = driven(H2MultiStream::new(send, req.into_body()), async move {
|
||||
while let Some(Ok((_, mut response))) = conn.accept().await {
|
||||
response.send_reset(h2::Reason::REFUSED_STREAM);
|
||||
}
|
||||
});
|
||||
let mut received = Zeroizing::new([0u8; 26]);
|
||||
stream.read_exact(&mut received[..]).await?;
|
||||
if !bool::from(received[..].ct_eq(&header(&ticket.profile)[..])) {
|
||||
return Err(invalid());
|
||||
}
|
||||
profiles.claim(&ticket)?;
|
||||
stream.write_all(&[0, 0]).await?;
|
||||
Ok((ticket, stream))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#![allow(clippy::unwrap_used)]
|
||||
use super::*;
|
||||
#[test]
|
||||
fn stream_one_and_vless_use_the_standard_post_path_uuid_and_tcp_destination() {
|
||||
let p = Profile {
|
||||
tag: [0xda; 32],
|
||||
secret: [0xaa; 32],
|
||||
variant: false,
|
||||
};
|
||||
let req = request(&p, "127.0.0.1:9443".parse().unwrap()).unwrap();
|
||||
assert_eq!(req.headers()["content-type"], "application/grpc");
|
||||
assert_eq!(request_tag(&req).unwrap(), p.tag);
|
||||
assert_eq!(
|
||||
hex::encode(&header(&p)[..]),
|
||||
"00aaaaaaaaaaaa4aaaaaaaaaaaaaaaaaaa00010001017f000001"
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn bad_methods_and_paths_are_rejected_before_allocating_a_stream() {
|
||||
let p = Profile {
|
||||
tag: [7; 32],
|
||||
secret: [4; 32],
|
||||
variant: true,
|
||||
};
|
||||
let mut req = request(&p, "127.0.0.1:9443".parse().unwrap()).unwrap();
|
||||
*req.method_mut() = http::Method::GET;
|
||||
assert!(request_tag(&req).is_err());
|
||||
*req.method_mut() = http::Method::POST;
|
||||
*req.uri_mut() = http::Uri::from_static("https://peer.invalid/missing/");
|
||||
assert!(request_tag(&req).is_err());
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@ name = "tsunagi-wg-quic"
|
||||
# Its own version, and deliberately separate from the wire version it
|
||||
# negotiates: a release here does not stop it talking to a peer on an older
|
||||
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -11,7 +11,7 @@ license.workspace = true
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12" }
|
||||
iroh.workspace = true
|
||||
tokio.workspace = true
|
||||
serde.workspace = true
|
||||
@@ -30,6 +30,9 @@ rand = "0.10"
|
||||
boringtun = { version = "0.7.1", default-features = false }
|
||||
|
||||
[dev-dependencies]
|
||||
tsunagi-shoes = { path = "../tsunagi-shoes" }
|
||||
tsunagi-vless-xhttp = { path = "../tsunagi-vless-xhttp" }
|
||||
tsunagi-ss2022 = { path = "../tsunagi-ss2022" }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||
|
||||
@@ -41,7 +41,7 @@ use tokio::task::JoinHandle;
|
||||
|
||||
use tsunagi::dataplane::routing::{FlowId, flow::ip_flow};
|
||||
use tsunagi::dataplane::transport::{SharedLink, TransportError};
|
||||
use tsunagi::dataplane::{PacketSink, PluginContext, PluginError};
|
||||
use tsunagi::dataplane::{PacketSink, PluginContext, PluginError, is_path_probe};
|
||||
use tsunagi::identity::NetworkId;
|
||||
|
||||
use crate::keys::{WgPublicKey, WgSecretKey};
|
||||
@@ -65,8 +65,8 @@ const SCRATCH: usize = 4096;
|
||||
struct FlowTunnel {
|
||||
tunn: Tunn,
|
||||
queued: VecDeque<(FlowId, usize)>,
|
||||
/// First usable session or most recent IP payload. Keepalives and later
|
||||
/// handshakes leave this alone, including when the current key expires.
|
||||
/// First usable session or most recent application payload. RTT probes,
|
||||
/// keepalives and later handshakes leave this alone.
|
||||
last_activity: Option<Instant>,
|
||||
}
|
||||
|
||||
@@ -81,17 +81,26 @@ impl FlowTunnel {
|
||||
scratch: &'a mut [u8],
|
||||
flow: FlowId,
|
||||
) -> (TunnResult<'a>, FlowId) {
|
||||
let probe = is_path_probe(packet);
|
||||
// A stale health check must never wait in the pending application FIFO.
|
||||
// Ask for a key and let the next scheduled probe use it.
|
||||
if probe && self.tunn.time_since_last_handshake().is_none() {
|
||||
return (self.tunn.format_handshake_initiation(scratch, false), flow);
|
||||
}
|
||||
let result = self.tunn.encapsulate(packet, scratch);
|
||||
if packet.is_empty() {
|
||||
return (result, 0);
|
||||
}
|
||||
if matches!(&result, TunnResult::WriteToNetwork(out) if carries_ip(out)) {
|
||||
self.last_activity = Some(Instant::now());
|
||||
if !probe {
|
||||
self.last_activity = Some(Instant::now());
|
||||
}
|
||||
return (result, flow);
|
||||
}
|
||||
// MAX_QUEUE_DEPTH in boringtun 0.7: the newest packet is dropped at 256.
|
||||
if self.queued.len() < 256 {
|
||||
self.queued.push_back((flow, packet.len()));
|
||||
self.queued
|
||||
.push_back((flow, if probe { 0 } else { packet.len() }));
|
||||
}
|
||||
(result, 0)
|
||||
}
|
||||
@@ -113,7 +122,7 @@ impl FlowTunnel {
|
||||
TunnResult::WriteToNetwork(out) if carries_ip(out) => {
|
||||
if let Some((tag, len)) = self.queued.pop_front() {
|
||||
flow = tag;
|
||||
plaintext_len = Some(len);
|
||||
plaintext_len = (len > 0).then_some(len);
|
||||
}
|
||||
}
|
||||
// An internal keepalive may occupy a slot in the bounded
|
||||
@@ -122,10 +131,13 @@ impl FlowTunnel {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
result,
|
||||
TunnResult::WriteToTunnelV4(..) | TunnResult::WriteToTunnelV6(..)
|
||||
) || plaintext_len.is_some()
|
||||
let application_data = match &result {
|
||||
TunnResult::WriteToTunnelV4(out, _) => !is_path_probe(out),
|
||||
TunnResult::WriteToTunnelV6(..) => true,
|
||||
_ => false,
|
||||
};
|
||||
if application_data
|
||||
|| plaintext_len.is_some()
|
||||
|| (self.last_activity.is_none() && self.tunn.time_since_last_handshake().is_some())
|
||||
{
|
||||
self.last_activity = Some(Instant::now());
|
||||
@@ -133,10 +145,10 @@ impl FlowTunnel {
|
||||
(result, flow, plaintext_len)
|
||||
}
|
||||
|
||||
fn health(&self, now: Instant, keep_warm: bool) -> PeerHealth {
|
||||
fn health(&self, now: Instant) -> PeerHealth {
|
||||
let since_handshake = self.tunn.time_since_last_handshake();
|
||||
let idle = self.queued.is_empty()
|
||||
&& (!keep_warm || since_handshake.is_some())
|
||||
&& since_handshake.is_some()
|
||||
&& self
|
||||
.last_activity
|
||||
.is_some_and(|at| now.duration_since(at) >= IDLE_AFTER);
|
||||
@@ -229,7 +241,7 @@ pub struct PeerStats {
|
||||
pub struct PeerHealth {
|
||||
/// Age of the last handshake while a usable WireGuard session exists.
|
||||
pub since_handshake: Option<Duration>,
|
||||
/// A previously established tunnel with no recent or queued IP traffic.
|
||||
/// A currently usable session with no recent or queued application traffic.
|
||||
pub idle: bool,
|
||||
}
|
||||
|
||||
@@ -290,12 +302,12 @@ impl Peer {
|
||||
}
|
||||
}
|
||||
|
||||
fn health(&self, keep_warm: bool) -> PeerHealth {
|
||||
fn health(&self) -> PeerHealth {
|
||||
let guard = match self.tunn.lock() {
|
||||
Ok(guard) => guard,
|
||||
Err(poisoned) => poisoned.into_inner(),
|
||||
};
|
||||
guard.health(Instant::now(), keep_warm)
|
||||
guard.health(Instant::now())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -416,14 +428,16 @@ impl WireguardDevice {
|
||||
}
|
||||
};
|
||||
let Some((len, selected_flow, data)) = result else {
|
||||
peer.counters
|
||||
.dropped_no_session
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
if !is_path_probe(packet) {
|
||||
peer.counters
|
||||
.dropped_no_session
|
||||
.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
let sent = send_to_peer_flow(&peer, &scratch[..len], selected_flow);
|
||||
if sent && data {
|
||||
if sent && data && !is_path_probe(packet) {
|
||||
count_sent(&peer, packet.len());
|
||||
}
|
||||
sent
|
||||
@@ -523,7 +537,6 @@ impl WireguardDevice {
|
||||
|
||||
/// A snapshot of every peer.
|
||||
pub fn peers(&self) -> Vec<PeerSummary> {
|
||||
let warm_peer = self.inner.context.warm_peer(self.inner.network);
|
||||
let mut peers: Vec<PeerSummary> = read_lock(&self.inner.peers)
|
||||
.values()
|
||||
.map(|peer| {
|
||||
@@ -535,7 +548,7 @@ impl WireguardDevice {
|
||||
endpoint_id: peer.endpoint_id,
|
||||
public_key: peer.public_key,
|
||||
overlay_address_v4: overlay_v4,
|
||||
health: peer.health(warm_peer == Some(peer.endpoint_id)),
|
||||
health: peer.health(),
|
||||
stats: peer.stats(),
|
||||
path: peer.link.path_description(),
|
||||
max_datagram: peer.link.max_datagram_size(),
|
||||
@@ -675,10 +688,12 @@ async fn read_from_link(inner: Arc<Inner>, peer: Arc<Peer>) {
|
||||
.sink
|
||||
.deliver(inner.network, peer.endpoint_id, payload)
|
||||
.await;
|
||||
peer.counters.rx_packets.fetch_add(1, Ordering::Relaxed);
|
||||
peer.counters
|
||||
.rx_bytes
|
||||
.fetch_add(len as u64, Ordering::Relaxed);
|
||||
if !is_path_probe(&scratch[..len]) {
|
||||
peer.counters.rx_packets.fetch_add(1, Ordering::Relaxed);
|
||||
peer.counters
|
||||
.rx_bytes
|
||||
.fetch_add(len as u64, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
Outcome::Failed => {
|
||||
peer.counters
|
||||
@@ -809,24 +824,24 @@ mod flow_tests {
|
||||
let bk = WgSecretKey::from_bytes(&[2; 32]);
|
||||
let (mut a, mut b) = (tunnel(&ak, &bk), tunnel(&bk, &ak));
|
||||
let mut scratch = [0u8; SCRATCH];
|
||||
assert!(!a.health(Instant::now() + IDLE_AFTER, false).idle);
|
||||
assert!(!a.health(Instant::now() + IDLE_AFTER).idle);
|
||||
establish(&mut a, &mut b, &mut scratch);
|
||||
assert!(!a.health(Instant::now(), false).idle);
|
||||
assert!(!a.health(Instant::now()).idle);
|
||||
let activity = (a.last_activity, b.last_activity);
|
||||
let idle_at = Instant::now() + IDLE_AFTER;
|
||||
assert!(a.health(idle_at, true).idle);
|
||||
assert!(a.health(idle_at).idle);
|
||||
establish(&mut a, &mut b, &mut scratch);
|
||||
assert_eq!((a.last_activity, b.last_activity), activity);
|
||||
assert!(a.health(idle_at, true).idle);
|
||||
assert!(b.health(idle_at, false).idle);
|
||||
assert!(a.health(idle_at).idle);
|
||||
assert!(b.health(idle_at).idle);
|
||||
|
||||
let mut ip = [0u8; 20];
|
||||
ip[0] = 0x45;
|
||||
ip[2..4].copy_from_slice(&20u16.to_be_bytes());
|
||||
let ciphertext = wire(a.encapsulate(&ip, &mut scratch, 7).0);
|
||||
let _ = b.decapsulate(&ciphertext, &mut scratch);
|
||||
assert!(!a.health(Instant::now(), false).idle);
|
||||
assert!(!b.health(Instant::now(), false).idle);
|
||||
assert!(!a.health(Instant::now()).idle);
|
||||
assert!(!b.health(Instant::now()).idle);
|
||||
assert!(a.last_activity > activity.0 && b.last_activity > activity.1);
|
||||
|
||||
// Discard BoringTun's session keys to exercise an idle tunnel with no
|
||||
@@ -834,10 +849,9 @@ mod flow_tests {
|
||||
a.tunn
|
||||
.set_static_private(ak.to_static_secret(), ak.public().into_x25519(), None);
|
||||
let idle_at = Instant::now() + IDLE_AFTER;
|
||||
assert!(a.health(idle_at, false).idle);
|
||||
assert!(!a.health(idle_at, true).idle);
|
||||
assert!(!a.health(idle_at).idle);
|
||||
let _ = a.encapsulate(&ip, &mut scratch, 7);
|
||||
assert!(!a.health(idle_at, false).idle);
|
||||
assert!(!a.health(idle_at).idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -871,7 +885,7 @@ mod flow_tests {
|
||||
a.decapsulate(&[], &mut scratch).0,
|
||||
TunnResult::Done
|
||||
));
|
||||
assert!(a.health(Instant::now() + IDLE_AFTER, false).idle);
|
||||
assert!(a.health(Instant::now() + IDLE_AFTER).idle);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -10,25 +10,39 @@ use std::{
|
||||
use tempfile::TempDir;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::{TcpListener, TcpStream};
|
||||
use tsunagi::dataplane::transport::ControlSender;
|
||||
use tsunagi::dataplane::transport::{PacketTransport, SharedLink, TransportError};
|
||||
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
|
||||
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
|
||||
use tsunagi::{Agent, BoxFuture, NetworkId};
|
||||
use tsunagi_tcp_tls::{TcpTlsCarrier, TcpTlsTransport};
|
||||
use tsunagi_shoes::{ShoesTransport, ShoesWire};
|
||||
use tsunagi_tcp_tls::{TcpCarrier, TcpTlsCarrier, TcpTlsTransport, candidates::TcpEndpoint};
|
||||
use tsunagi_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||
use tsunagi_wireguard::{UdpCarrier, UdpTransport};
|
||||
|
||||
// Only address selection is constrained to loopback. TLS sockets, identity
|
||||
// verification, framing, membership and both encryption layers remain real.
|
||||
#[derive(Debug)]
|
||||
struct LoopbackTls {
|
||||
inner: Arc<TcpTlsTransport>,
|
||||
struct LoopbackTcp {
|
||||
inner: Arc<dyn TcpEndpoint>,
|
||||
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
|
||||
}
|
||||
impl PacketTransport for LoopbackTls {
|
||||
impl PacketTransport for LoopbackTcp {
|
||||
fn name(&self) -> &str {
|
||||
"tcp-tls"
|
||||
self.inner.name()
|
||||
}
|
||||
fn attach_control(&self, sender: Arc<dyn ControlSender>) {
|
||||
self.inner.attach_control(sender);
|
||||
}
|
||||
fn on_control(
|
||||
&self,
|
||||
net: NetworkId,
|
||||
peer: EndpointId,
|
||||
protocol: &str,
|
||||
payload: &[u8],
|
||||
) -> Result<(), TransportError> {
|
||||
self.inner.on_control(net, peer, protocol, payload)
|
||||
}
|
||||
fn as_any(&self) -> &dyn std::any::Any {
|
||||
self
|
||||
@@ -47,8 +61,15 @@ impl PacketTransport for LoopbackTls {
|
||||
.find(|(id, _)| *id == peer)
|
||||
.unwrap()
|
||||
.1;
|
||||
self.inner
|
||||
.replace_peer_addrs(peer, vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]);
|
||||
self.inner.set_pair_addresses(
|
||||
network,
|
||||
peer,
|
||||
Some(if port == 0 {
|
||||
vec![]
|
||||
} else {
|
||||
vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]
|
||||
}),
|
||||
);
|
||||
self.inner.open(network, peer, protocol)
|
||||
}
|
||||
}
|
||||
@@ -95,6 +116,7 @@ impl Node {
|
||||
.with_tunnel(tunnel.clone());
|
||||
let mut wireguard = None;
|
||||
let mut tls = None;
|
||||
let mut shoes = Vec::new();
|
||||
for &protocol in protocols {
|
||||
match protocol {
|
||||
"wg" => {
|
||||
@@ -120,13 +142,35 @@ impl Node {
|
||||
.with_carrier(TcpTlsCarrier::new(transport.clone()))
|
||||
.with_custom_transport(
|
||||
protocol,
|
||||
Arc::new(LoopbackTls {
|
||||
Arc::new(LoopbackTcp {
|
||||
inner: transport.clone(),
|
||||
ports: ports.clone(),
|
||||
}),
|
||||
);
|
||||
tls = Some(transport);
|
||||
}
|
||||
"vless-xhttp" | "ss2022" => {
|
||||
let wire: Arc<dyn ShoesWire> = if protocol == "vless-xhttp" {
|
||||
Arc::new(tsunagi_vless_xhttp::VlessXhttp::new(&identity).unwrap())
|
||||
} else {
|
||||
Arc::new(tsunagi_ss2022::Shadowsocks2022)
|
||||
};
|
||||
let transport = ShoesTransport::bind(wire, Some(0), 0).await.unwrap();
|
||||
ports
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((identity.endpoint_id(), transport.bound_port()));
|
||||
config = config
|
||||
.with_carrier(TcpCarrier::new(transport.clone()))
|
||||
.with_custom_transport(
|
||||
protocol,
|
||||
Arc::new(LoopbackTcp {
|
||||
inner: transport.clone(),
|
||||
ports: ports.clone(),
|
||||
}),
|
||||
);
|
||||
shoes.push(transport);
|
||||
}
|
||||
"wg-quic" => {
|
||||
config = config.with_carrier(Arc::new(
|
||||
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
||||
@@ -137,6 +181,9 @@ impl Node {
|
||||
}
|
||||
let agent = Agent::spawn(config).await.unwrap();
|
||||
let mut listeners = tokio::task::JoinSet::new();
|
||||
for transport in shoes {
|
||||
listeners.spawn(transport.listen(agent.clone()));
|
||||
}
|
||||
if let Some(transport) = wireguard.clone() {
|
||||
let incoming = agent.clone();
|
||||
listeners.spawn(async move {
|
||||
@@ -418,9 +465,8 @@ async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exact_plaintext_counters()
|
||||
{
|
||||
for protocol in ["wg", "tcp-tls"] {
|
||||
async fn direct_carriers_share_the_internal_cipher_and_count_exact_plaintext() {
|
||||
for protocol in ["wg", "tcp-tls", "vless-xhttp", "ss2022"] {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let ports = Arc::default();
|
||||
let a = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
@@ -501,3 +547,42 @@ async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exac
|
||||
b.agent.shutdown().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn each_tcp_carrier_reverses_when_the_elected_dialler_cannot_reach_the_listener() {
|
||||
for protocol in ["tcp-tls", "vless-xhttp", "ss2022"] {
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let ports = Arc::default();
|
||||
let a = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
let b = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
||||
// Only the smaller identity accepts a connection from its peer.
|
||||
ports
|
||||
.lock()
|
||||
.unwrap()
|
||||
.iter_mut()
|
||||
.max_by_key(|(id, _)| *id)
|
||||
.unwrap()
|
||||
.1 = 0;
|
||||
let (name, secret) = network(protocol);
|
||||
let id = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_until(
|
||||
"both endpoints have an established cipher over the reverse socket",
|
||||
|| async {
|
||||
[&a, &b]
|
||||
.iter()
|
||||
.all(|n| {
|
||||
n.tunnel.overview(id).and_then(|o| {
|
||||
o.peers.first()?.tunnel.as_ref().map(|t| t.health.is_up())
|
||||
}) == Some(true)
|
||||
})
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
deliver(&a, &b, id, 41).await;
|
||||
deliver(&b, &a, id, 42).await;
|
||||
a.agent.shutdown().await;
|
||||
b.agent.shutdown().await;
|
||||
}
|
||||
}
|
||||
@@ -441,8 +441,8 @@ async fn shared_networks<'a>(client: &Node, peer: &'a Node) -> [ExitNetwork<'a>;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "observes a full 180-second WireGuard key lifetime on real clocks"]
|
||||
async fn only_the_selected_exit_stays_keyed_through_idle_expiry() {
|
||||
#[ignore = "observes WireGuard's 120-second rekey timer on real clocks"]
|
||||
async fn confirmed_idle_paths_remain_usable_through_wireguard_rekeying() {
|
||||
let (client, peer) = shared_nodes().await;
|
||||
let [chosen, other] = shared_networks(&client, &peer).await;
|
||||
client
|
||||
@@ -463,39 +463,30 @@ async fn only_the_selected_exit_stays_keyed_through_idle_expiry() {
|
||||
.unwrap()
|
||||
};
|
||||
let epoch = tunnel(chosen.id).stats.counter_epoch;
|
||||
let mut old_key_seen = false;
|
||||
let mut old_keys_seen = false;
|
||||
tokio::time::timeout(Duration::from_secs(210), async {
|
||||
let mut poll = tokio::time::interval(Duration::from_millis(500));
|
||||
loop {
|
||||
poll.tick().await;
|
||||
let warm = tunnel(chosen.id);
|
||||
let cold = tunnel(other.id);
|
||||
let ordinary = tunnel(other.id);
|
||||
assert_eq!(warm.stats.counter_epoch, epoch);
|
||||
let warm_age = warm
|
||||
.health
|
||||
.since_handshake
|
||||
.expect("usable exit key throughout idle");
|
||||
assert_eq!((warm.stats.tx_bytes, warm.stats.rx_bytes), (0, 0));
|
||||
assert_eq!((cold.stats.tx_bytes, cold.stats.rx_bytes), (0, 0));
|
||||
if cold
|
||||
.health
|
||||
.since_handshake
|
||||
.is_some_and(|age| age >= Duration::from_secs(150))
|
||||
{
|
||||
old_key_seen = true;
|
||||
}
|
||||
if old_key_seen && !cold.health.is_up() {
|
||||
assert!(
|
||||
warm_age < Duration::from_secs(90),
|
||||
"exit key renewed before expiry"
|
||||
);
|
||||
assert!(warm.health.idle && cold.health.idle);
|
||||
assert_eq!((ordinary.stats.tx_bytes, ordinary.stats.rx_bytes), (0, 0));
|
||||
let ordinary_age = ordinary.health.since_handshake.expect("usable peer key");
|
||||
old_keys_seen |= warm_age.min(ordinary_age) >= Duration::from_secs(90);
|
||||
if old_keys_seen && warm_age.max(ordinary_age) < Duration::from_secs(60) {
|
||||
assert!(warm.health.idle && ordinary.health.idle);
|
||||
break;
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("unselected peer's unused session expired");
|
||||
.expect("both confirmed data paths renewed their keys without application traffic");
|
||||
|
||||
let packet = ipv4_packet(chosen.client_addr, INTERNET, b"first IP packet after idle");
|
||||
client.tun().await.push_from_os(packet.clone());
|
||||
|
||||
@@ -2119,6 +2119,101 @@ async fn vip_udp_reaches_another_backend_after_the_selected_agent_stops() {
|
||||
alive.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn peer_speed_requires_a_bidirectional_data_path_and_can_measure_through_a_relay() {
|
||||
use tsunagi::agent::DataPath;
|
||||
use tsunagi::ipc::SpeedPhase;
|
||||
|
||||
let discovery = SharedMemoryDiscovery::new();
|
||||
let (name, secret) = network("speed-relayed");
|
||||
let blocked = Arc::new(std::sync::Mutex::new(std::collections::HashSet::new()));
|
||||
let a = WgAgent::spawn_cut_off(&discovery, "client", blocked.clone()).await;
|
||||
let b = WgAgent::spawn(&discovery, "server").await;
|
||||
let peer = b.endpoint_id();
|
||||
let key = peer.to_string();
|
||||
blocked.lock().unwrap().insert(peer);
|
||||
let net = a.agent.join_network(&name, &secret).await.unwrap();
|
||||
b.agent.join_network(&name, &secret).await.unwrap();
|
||||
wait_until(
|
||||
"authenticated control-only peer has advertised speed tests",
|
||||
|| async {
|
||||
let status = a.agent.network_status(net).await.ok()?;
|
||||
status
|
||||
.peers
|
||||
.iter()
|
||||
.find(|p| {
|
||||
p.endpoint_id == peer
|
||||
&& p.capabilities
|
||||
.iter()
|
||||
.any(|c| c.protocol == "speedtest" && c.enabled)
|
||||
})
|
||||
.map(|_| ())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let status = a.agent.network_status(net).await.unwrap();
|
||||
assert!(matches!(status.peers[0].data_path, DataPath::None));
|
||||
assert!(status.peers[0].data_rtt.is_none());
|
||||
assert!(!status.speed.capable.contains(&key));
|
||||
assert!(
|
||||
a.agent
|
||||
.start_speed_test(net, Some(peer), true)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(
|
||||
a.agent
|
||||
.network_status(net)
|
||||
.await
|
||||
.unwrap()
|
||||
.speed
|
||||
.peers
|
||||
.is_empty()
|
||||
);
|
||||
|
||||
let relay = WgAgent::spawn(&discovery, "relay").await;
|
||||
relay.agent.join_network(&name, &secret).await.unwrap();
|
||||
for (node, target) in [(&a, peer), (&b, a.endpoint_id())] {
|
||||
wait_until("end-to-end data RTT without a direct link", || async {
|
||||
let status = node.agent.network_status(net).await.ok()?;
|
||||
let p = status.peers.iter().find(|p| p.endpoint_id == target)?;
|
||||
(matches!(p.data_path, DataPath::Relayed { hops: 2, via } if via == relay.endpoint_id())
|
||||
&& p.data_rtt.is_some()
|
||||
&& status.speed.capable.contains(&target.to_string()))
|
||||
.then_some(())
|
||||
})
|
||||
.await;
|
||||
}
|
||||
a.agent
|
||||
.start_speed_test(net, Some(peer), true)
|
||||
.await
|
||||
.unwrap();
|
||||
let report = wait_until("both test directions carried over the relay", || async {
|
||||
let s = a.agent.network_status(net).await.ok()?.speed;
|
||||
let p = s.peers.get(&key)?;
|
||||
matches!(p.phase, SpeedPhase::Done | SpeedPhase::Failed(_)).then(|| p.clone())
|
||||
})
|
||||
.await;
|
||||
assert_eq!(report.phase, SpeedPhase::Done, "{report:?}");
|
||||
assert!(report.down.is_some() && report.up.is_some() && report.bytes > 0);
|
||||
assert!(report.path.unwrap().contains("2 hops"));
|
||||
relay.shutdown().await;
|
||||
wait_until(
|
||||
"losing only the relay clears data RTT and speed admission",
|
||||
|| async {
|
||||
let status = a.agent.network_status(net).await.ok()?;
|
||||
let p = status.peers.iter().find(|p| p.endpoint_id == peer)?;
|
||||
(matches!(p.data_path, DataPath::None)
|
||||
&& p.data_rtt.is_none()
|
||||
&& !status.speed.capable.contains(&key))
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
a.shutdown().await;
|
||||
b.shutdown().await;
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn peer_speed_measures_both_wireguard_directions_and_can_be_repeated() {
|
||||
use tsunagi::ipc::SpeedPhase;
|
||||
@@ -2155,6 +2250,20 @@ async fn peer_speed_measures_both_wireguard_directions_and_can_be_repeated() {
|
||||
.is_err()
|
||||
);
|
||||
b.agent.set_speed_test_metered(true);
|
||||
wait_until(
|
||||
"the initiator has confirmed the peer's data path",
|
||||
|| async {
|
||||
a.agent
|
||||
.network_status(net)
|
||||
.await
|
||||
.ok()?
|
||||
.speed
|
||||
.capable
|
||||
.contains(&key)
|
||||
.then_some(())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
a.agent
|
||||
.start_speed_test(net, Some(remote), false)
|
||||
.await
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi-wireguard"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
|
||||
repository.workspace = true
|
||||
|
||||
[dependencies]
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12" }
|
||||
iroh.workspace = true
|
||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||
serde.workspace = true
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "tsunagi"
|
||||
version = "1.0.9"
|
||||
version = "1.0.12"
|
||||
description = "The tsunagi command line agent."
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
@@ -12,11 +12,11 @@ name = "tsng"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.9" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.9", features = ["tun-device", "dns-publish"] }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.9" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.9" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.9" }
|
||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.12" }
|
||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.12", features = ["tun-device", "dns-publish"] }
|
||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.12" }
|
||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.12" }
|
||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.12" }
|
||||
iroh.workspace = true
|
||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||
tracing.workspace = true
|
||||
|
||||
+81
-27
@@ -498,7 +498,7 @@ struct UpArgs {
|
||||
long = "protocol",
|
||||
value_name = "LIST",
|
||||
value_delimiter = ',',
|
||||
default_value = "wg,awg,wg-quic,tcp-tls",
|
||||
default_values = PROTOCOLS.iter().map(|p| p.name),
|
||||
help_heading = "Transport"
|
||||
)]
|
||||
protocols: Vec<String>,
|
||||
@@ -1475,7 +1475,11 @@ fn take_tunnel_settings(settings: &mut Vec<Setting>) -> Result<Vec<(String, Stri
|
||||
}
|
||||
|
||||
/// The settings meant for one protocol, refusing any that fit nowhere.
|
||||
fn settings_for(spec: &ProtocolSpec, settings: &[Setting]) -> Vec<(String, String)> {
|
||||
fn settings_for(
|
||||
spec: &ProtocolSpec,
|
||||
settings: &[Setting],
|
||||
selected: &[&ProtocolSpec],
|
||||
) -> Vec<(String, String)> {
|
||||
let mut taken = Vec::new();
|
||||
for setting in settings {
|
||||
let aimed_here = match &setting.protocol {
|
||||
@@ -1485,7 +1489,19 @@ fn settings_for(spec: &ProtocolSpec, settings: &[Setting]) -> Vec<(String, Strin
|
||||
// Unqualified settings go to whichever protocol declares the
|
||||
// key. With one selected that is the obvious reading; with
|
||||
// several, write `protocol:key=value`.
|
||||
None => spec.options.iter().any(|option| option.key == setting.key),
|
||||
None => {
|
||||
// Existing unqualified ports configure the original listeners.
|
||||
// A Shoes listener can inherit one when it is the sole TCP choice.
|
||||
let shoes_port =
|
||||
setting.key == "port" && matches!(spec.name, "vless-xhttp" | "ss2022");
|
||||
let eligible = !shoes_port
|
||||
|| selected
|
||||
.iter()
|
||||
.filter(|p| matches!(p.name, "tcp-tls" | "vless-xhttp" | "ss2022"))
|
||||
.count()
|
||||
== 1;
|
||||
eligible && spec.options.iter().any(|option| option.key == setting.key)
|
||||
}
|
||||
};
|
||||
if aimed_here {
|
||||
taken.push((setting.key.clone(), setting.value.clone()));
|
||||
@@ -1501,6 +1517,7 @@ fn show_protocols() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let mut out = Report::new();
|
||||
for spec in PROTOCOLS {
|
||||
let mut section = Section::new(format!("{} (wire version {})", spec.name, spec.version));
|
||||
section.push(Row::new(Health::Info, "group", spec.group));
|
||||
section.push(Row::new(Health::Info, "what", spec.summary));
|
||||
if spec.options.is_empty() {
|
||||
section.push(Row::new(Health::Info, "settings", "none"));
|
||||
@@ -2033,7 +2050,7 @@ fn parse_protocol_list(text: &str) -> Result<Vec<String>, String> {
|
||||
};
|
||||
if !PROTOCOLS.iter().any(|spec| spec.name == name) {
|
||||
return Err(format!(
|
||||
"unknown protocol `{name}`; use wg,awg,wg-quic,tcp-tls or `none` alone. Run `tsng protocols` for details"
|
||||
"unknown protocol `{name}`; run `tsng protocols` to list available transports, or use `none` alone"
|
||||
));
|
||||
}
|
||||
if names.iter().any(|n| n == name) {
|
||||
@@ -3948,7 +3965,6 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
}
|
||||
|
||||
use tsunagi::ipc::DataPathReport;
|
||||
let tunnel_up = row.tunnel.is_some_and(|tunnel| tunnel.is_up());
|
||||
let has_overlay = row.tunnel.is_some();
|
||||
// Online is online: a member reached through others is as much here as
|
||||
// one reached directly, and is said to be reached that way.
|
||||
@@ -3965,8 +3981,9 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
),
|
||||
Some(DataPathReport::None) | None => ("connected · no data path yet".to_string(), false),
|
||||
};
|
||||
let idle = data_path_good && row.data_error.is_none() && row.tunnel.is_some_and(|t| t.idle);
|
||||
let show_counters = tunnel_up || idle;
|
||||
let confirmed = data_path_good && row.data_error.is_none() && row.data_rtt_ms.is_some();
|
||||
let show_counters = confirmed && row.tunnel.is_some_and(|t| t.is_up());
|
||||
let idle = show_counters && row.tunnel.is_some_and(|t| t.idle);
|
||||
|
||||
let mut detail = String::new();
|
||||
if let Some(v4) = row.overlay_address_v4 {
|
||||
@@ -3992,7 +4009,7 @@ fn member_row(row: &MemberRow<'_>) -> report::Row {
|
||||
}
|
||||
detail.extend(taken);
|
||||
|
||||
let health = if !data_path_good || row.data_error.is_some() || (has_overlay && !show_counters) {
|
||||
let health = if !confirmed || (has_overlay && !show_counters) {
|
||||
Health::Degraded
|
||||
} else {
|
||||
Health::Good
|
||||
@@ -4729,10 +4746,10 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
if !PROTOCOLS
|
||||
.iter()
|
||||
.filter(|spec| setting.protocol.is_some() || wanted.iter().any(|p| p.name == spec.name))
|
||||
.any(|spec| !settings_for(spec, std::slice::from_ref(setting)).is_empty())
|
||||
.any(|spec| !settings_for(spec, std::slice::from_ref(setting), &wanted).is_empty())
|
||||
{
|
||||
return Err(format!(
|
||||
"no configured protocol takes `{}`; qualify disabled protocol settings as protocol:key=value. Run `tsng protocols` for details",
|
||||
"no configured protocol takes `{}`; use protocol:key=value to select a specific listener or configure a disabled transport. Run `tsng protocols` for details",
|
||||
setting.key
|
||||
)
|
||||
.into());
|
||||
@@ -4772,7 +4789,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
settings_for(spec, &scoped)
|
||||
settings_for(spec, &scoped, &wanted)
|
||||
})
|
||||
.await?;
|
||||
|
||||
@@ -4950,13 +4967,7 @@ async fn build_report(
|
||||
|
||||
StatusReport {
|
||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||
available_protocols: PROTOCOLS
|
||||
.iter()
|
||||
.map(|p| tsunagi::ipc::ProtocolReport {
|
||||
name: p.name.into(),
|
||||
summary: p.summary.into(),
|
||||
})
|
||||
.collect(),
|
||||
available_protocols: PROTOCOLS.iter().map(|p| p.report()).collect(),
|
||||
endpoint_id: status.endpoint_id.to_string(),
|
||||
hostname: status.hostname.clone(),
|
||||
bound_sockets: status
|
||||
@@ -5305,7 +5316,7 @@ mod status_tests {
|
||||
hostname: Some("music".into()),
|
||||
transport: "direct".into(),
|
||||
rtt_ms: Some(24),
|
||||
data_rtt_ms: None,
|
||||
data_rtt_ms: Some(16),
|
||||
data_transport_detail: None,
|
||||
exit_node: false,
|
||||
path: tsunagi::ipc::DataPathReport::Direct {
|
||||
@@ -5764,8 +5775,8 @@ mod status_tests {
|
||||
|
||||
#[test]
|
||||
fn a_member_reached_through_another_is_online_and_says_through_whom() {
|
||||
// No direct link, a path through somebody else: online all the same,
|
||||
// and said to be, rather than being shown as away or as a fault.
|
||||
// The member is online via the mesh. Reachability alone hasn't
|
||||
// confirmed an encrypted round trip to it.
|
||||
let mut network = network_after_a_peer_returned();
|
||||
network.members.push(MemberReport {
|
||||
record_version: 1,
|
||||
@@ -5793,7 +5804,7 @@ mod status_tests {
|
||||
"names the member it goes through: {text}"
|
||||
);
|
||||
assert!(!text.contains("offline"), "{text}");
|
||||
assert_eq!(out.worst(), Health::Good, "{text}");
|
||||
assert_eq!(out.worst(), Health::Degraded, "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -5869,7 +5880,7 @@ mod status_tests {
|
||||
#[test]
|
||||
fn an_idle_peer_keeps_its_counters_and_a_missing_route_is_still_degraded() {
|
||||
let mut network = network_after_a_peer_returned();
|
||||
let mut quiet = tunnel(ONLINE, None);
|
||||
let mut quiet = tunnel(ONLINE, Some(29));
|
||||
quiet.idle = true;
|
||||
network.overlay = Some(overlay(vec![quiet]));
|
||||
for (path, health) in [
|
||||
@@ -5896,6 +5907,25 @@ mod status_tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_key_and_a_control_rtt_cannot_make_an_unverified_data_path_idle() {
|
||||
let mut network = network_after_a_peer_returned();
|
||||
network.peers[0].data_rtt_ms = None;
|
||||
let mut quiet = tunnel(ONLINE, Some(29));
|
||||
quiet.idle = true;
|
||||
network.overlay = Some(overlay(vec![quiet]));
|
||||
let mut out = report::Report::new();
|
||||
out.push(network_section(&network, OWN, false));
|
||||
let text = out.render(false);
|
||||
assert_eq!(out.worst(), Health::Degraded, "{text}");
|
||||
assert!(text.contains("control RTT 24ms"), "{text}");
|
||||
assert!(
|
||||
text.contains("encrypted data channel is not ready yet"),
|
||||
"{text}"
|
||||
);
|
||||
assert!(!text.contains("· idle"), "{text}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_failures_with_nobody_connected_point_at_the_secret() {
|
||||
// The classic symptom of one member being given a different secret.
|
||||
@@ -5988,10 +6018,31 @@ mod network_tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_carriers_include_awg_and_explicit_order_is_preserved() {
|
||||
fn separate_tcp_listeners_preserve_historic_unqualified_ports() {
|
||||
let all: Vec<_> = super::PROTOCOLS.iter().collect();
|
||||
let spec = |name| *all.iter().find(|p| p.name == name).unwrap();
|
||||
let settings = super::parse_settings(&["port=8765".into()]).unwrap();
|
||||
assert_eq!(
|
||||
super::settings_for(spec("tcp-tls"), &settings, &all)[0].1,
|
||||
"8765"
|
||||
);
|
||||
assert!(super::settings_for(spec("vless-xhttp"), &settings, &all).is_empty());
|
||||
for name in ["vless-xhttp", "ss2022"] {
|
||||
let only = [spec(name)];
|
||||
assert_eq!(super::settings_for(only[0], &settings, &only)[0].1, "8765");
|
||||
let qualified = super::parse_settings(&[format!("{name}:port=9876")]).unwrap();
|
||||
assert_eq!(super::settings_for(only[0], &qualified, &all)[0].1, "9876");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_carriers_default_on_and_explicit_order_is_preserved() {
|
||||
use clap::Parser;
|
||||
for (words, expected) in [
|
||||
(vec!["tsng", "up"], vec!["wg", "awg", "wg-quic", "tcp-tls"]),
|
||||
(
|
||||
vec!["tsng", "up"],
|
||||
vec!["wg", "awg", "wg-quic", "tcp-tls", "vless-xhttp", "ss2022"],
|
||||
),
|
||||
(
|
||||
vec![
|
||||
"tsng",
|
||||
@@ -6357,14 +6408,17 @@ mod service_log_tests {
|
||||
);
|
||||
|
||||
let big = std::fs::File::options()
|
||||
.append(true)
|
||||
.write(true)
|
||||
.open(logs.join("tsng.log"))
|
||||
.unwrap();
|
||||
big.set_len(SERVICE_LOG_LIMIT + 1).unwrap();
|
||||
drop(big);
|
||||
let file = open_log_in(&logs).unwrap();
|
||||
assert_eq!(file.metadata().unwrap().len(), 0);
|
||||
assert!(logs.join("tsng.log.old").exists());
|
||||
assert_eq!(
|
||||
std::fs::metadata(logs.join("tsng.log.old")).unwrap().len(),
|
||||
SERVICE_LOG_LIMIT + 1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+3
-3
@@ -1,11 +1,11 @@
|
||||
# Pairwise Amnezia transport
|
||||
|
||||
The CLI's default carrier preference is `wg,awg,wg-quic,tcp-tls`. To select
|
||||
The CLI's default carrier preference is `wg,awg,wg-quic,tcp-tls,vless-xhttp,ss2022`. To select
|
||||
AWG explicitly:
|
||||
|
||||
```sh
|
||||
tsng up --protocol awg
|
||||
tsng up --protocol wg,awg,wg-quic,tcp-tls
|
||||
tsng up --protocol wg,awg,wg-quic,tcp-tls,vless-xhttp,ss2022
|
||||
```
|
||||
|
||||
The startup list is the initial per-network preference. A saved network choice
|
||||
@@ -127,7 +127,7 @@ The internal capability is `wireguard-e2e` v4; external `wg` and `awg` use v2,
|
||||
`wg-quic` v1 and `tcp-tls` v2, as in 1.0.1. Control ALPN
|
||||
`tsunagi/ctrl/8`, discovery, membership and signed state are unchanged. The data
|
||||
ALPN is `tsunagi/data/6`; the relay envelope format is unchanged. Automatic
|
||||
carrier comparisons are optional on the mesh wire. Local IPC is v29,
|
||||
carrier comparisons are optional on the mesh wire. Local IPC is v30,
|
||||
so agent, CLI and tray must match. Historical `wg-quic/wireguard.sqlite` is the
|
||||
canonical internal key store. Missing keys are imported transactionally from
|
||||
`wg` then `awg`, without replacing an existing canonical key or modifying a
|
||||
|
||||
@@ -76,6 +76,9 @@ And in crates of their own:
|
||||
|---|---|
|
||||
| `tsunagi-wireguard` | independent ordinary WG and masked UDP hop engines, private pair negotiation and local candidates |
|
||||
| `tsunagi-tcp-tls` | TLS hop encryption and bounded reachability announcements; no inner IP cipher |
|
||||
| `tsunagi-shoes` | ephemeral credentials negotiated privately for each TCP attempt |
|
||||
| `tsunagi-vless-xhttp` | VLESS over XHTTP stream-one, HTTP/2 and TLS 1.3 |
|
||||
| `tsunagi-ss2022` | Shadowsocks 2022 TCP wire profile and authenticated records |
|
||||
| `tsunagi-awg` | ephemeral pairwise Amnezia masking, private negotiation and independently encrypted UDP carriers; shares the independent UDP hop engine with `wg` |
|
||||
| `tsunagi-wg-quic` | the single internal WireGuard cipher, keys and opaque announcement (historical crate name) |
|
||||
| `tsunagi` | the command line agent, built as the `tsng` executable: the only place that owns a runtime, a logger and signals |
|
||||
|
||||
+7
-4
@@ -116,9 +116,10 @@ and configured networks.
|
||||
|
||||
- **Offering:** a `pf` anchor `com.apple/tsunagi-exit-<interface>` (the stock
|
||||
`/etc/pf.conf` already evaluates `com.apple/*`) holds
|
||||
NAT for traffic tagged on entry from an offered range. A tagged packet that the
|
||||
kernel would forward back to the utun gets a PF `route-to` through the
|
||||
physical gateway. The physical NAT state is interface-bound.
|
||||
NAT for traffic tagged on entry from an offered range. If the kernel chooses
|
||||
the utun for a member's outbound internet packet, PF steers it through the
|
||||
physical gateway. Replies keep the tag after reverse NAT and return to the
|
||||
member over the utun. The physical NAT state is interface-bound.
|
||||
`pf` is enabled if it was off, and that reference is released when the rules
|
||||
go. After installing the rules the agent enables IPv4 forwarding and checks
|
||||
the kernel's answer before advertising the exit. Stopping the offer removes
|
||||
@@ -133,7 +134,9 @@ and configured networks.
|
||||
a separate grant. The helper checks the live utun address and mask, selects
|
||||
the uplink from the kernel, and manages its own PF anchor and enable token.
|
||||
It accepts only sharing operations. The agent can subsequently reconcile and
|
||||
remove these rules without prompting. At startup it reclaims orphaned helper
|
||||
remove these rules without prompting. When an update changes the helper,
|
||||
enabling sharing again prompts once to replace it and keeps existing subnet
|
||||
grants. At startup the agent reclaims orphaned helper
|
||||
anchors for the account by checking the owning process and its start time.
|
||||
For a system agent with the necessary
|
||||
rights, the initial enable completes directly.
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
# Embedded Shoes transports
|
||||
|
||||
Both profiles carry the usual length-prefixed, encrypted mesh datagrams over a
|
||||
direct TCP stream. Each listener has a preferred port, 9443 for `vless-xhttp`
|
||||
and 9444 for `ss2022`. If a default is occupied, the agent announces an
|
||||
available port. An explicitly configured port must bind successfully.
|
||||
|
||||
The wire implementations adapt the stream-one request format, HTTP/2 stream
|
||||
flow control, VLESS TCP handshake and Shadowsocks TCP record format from
|
||||
[Shoes v0.3.8](https://github.com/cfal/shoes/tree/7680938b96a245a21d9e481ad009205b956e4436).
|
||||
The protocol crates include the upstream MIT license. Both run inside the agent.
|
||||
|
||||
For each new TCP handshake the dialler generates an independent 32-byte
|
||||
identifier, 32 bytes of secret material and a method selector. It sends the offer
|
||||
to the destination member on the encrypted control connection for that network.
|
||||
The receiver acknowledges the identifier before data authentication starts.
|
||||
Only the two peers see the offer. The receiver accepts one successful claim
|
||||
within 12 seconds. A replacement, a disabled transport or the end of membership
|
||||
invalidates pending credentials. The TCP ports and device identities are stable
|
||||
across these attempts. No per-attempt secret enters SQLite or status output.
|
||||
|
||||
* **VLESS + XHTTP** uses a single bidirectional HTTP/2 POST with the XHTTP
|
||||
stream-one path and standard Referer padding. The path and VLESS UUIDv4
|
||||
change per attempt. TLS 1.3 authenticates the server using the Ed25519 SPKI
|
||||
of the expected mesh member. The client uses the peer's IP for the request
|
||||
authority, so this profile can run without a domain, public PKI or ingress.
|
||||
* **Shadowsocks 2022** selects AES-128-GCM or AES-256-GCM independently of the
|
||||
key and salt. The TCP request carries a random salt and padding. The receiver
|
||||
authenticates the fixed and variable headers, the service selector and the
|
||||
time window. The response authenticates the request salt. The first payload
|
||||
byte acknowledges the mesh service. Subsequent data uses standard encrypted
|
||||
length and payload records. [SIP022](https://shadowsocks.org/doc/sip022.html)
|
||||
|
||||
The destination encoded inside either protocol is the mesh service selector
|
||||
`127.0.0.1:1`. Each endpoint terminates that service in memory and hands the
|
||||
resulting link to the mesh. The inner WireGuard tunnel authenticates the source
|
||||
and destination of the overlay traffic.
|
||||
|
||||
The elected peer tries advertised TCP listeners first. Candidates can include
|
||||
verified direct control-path IPs and configured bootstrap IPs paired with the
|
||||
peer's advertised TCP port. Peers that advertise `link-reverse` v1 can request
|
||||
one reverse attempt after the forward attempt fails. The first successful
|
||||
direction carries traffic both ways. If both fail the mesh applies its usual
|
||||
carrier selection and relay routing. Ports forwarded through a router must
|
||||
reach the announced TCP listener. Network filtering and NAT determine which
|
||||
paths can actually be established.
|
||||
+8
-3
@@ -273,10 +273,15 @@ observations, counter resets, recreated listeners and removal of cached
|
||||
histories. These are headless egui checks, not native desktop screenshots.
|
||||
|
||||
`tsunagi-wg-quic/tests/carriers.rs` uses the same internal WireGuard plugin over
|
||||
real ordinary WG UDP and TCP/TLS, with loopback address selection and memory
|
||||
TUNs. Exact original IP byte/packet counts exclude health probes and encryption
|
||||
real ordinary WG UDP, native TCP/TLS, VLESS/XHTTP and Shadowsocks 2022 with
|
||||
loopback address selection and memory TUNs. For each TCP carrier a second test
|
||||
removes every candidate in the elected direction and exchanges IP packets in
|
||||
both directions over the reverse socket. Exact original IP byte/packet counts exclude health probes and encryption
|
||||
overhead. An artificial delay on a real TCP/TLS link exercises automatic
|
||||
selection of a faster QUIC carrier. Both endpoints exchange packets across the
|
||||
selection of a faster QUIC carrier. An optional reference test runs the upstream
|
||||
Shoes v0.3.8 executable against the embedded VLESS/XHTTP client and both
|
||||
Shadowsocks methods. Set `TSUNAGI_SHOES_BIN` and run
|
||||
`cargo test --locked -p tsunagi-runtime --test shoes_reference -- --ignored`. Both endpoints exchange packets across the
|
||||
transition and retain their original encrypted tunnels. The AWG suite connects
|
||||
AWG-only and QUIC-only endpoints through a
|
||||
mixed relay. One real smoltcp TCP connection stays established through relay →
|
||||
|
||||
+8
-5
@@ -47,7 +47,8 @@ peer by the agent and runs a WireGuard tunnel over it:
|
||||
```
|
||||
|
||||
Reachability belongs to external carriers: ordinary WireGuard UDP (`wg`),
|
||||
Amnezia-masked UDP (`awg`), iroh QUIC (`wg-quic`), or TCP/TLS (`tcp-tls`). The
|
||||
Amnezia-masked UDP (`awg`), iroh QUIC (`wg-quic`), TCP/TLS (`tcp-tls`),
|
||||
VLESS/XHTTP (`vless-xhttp`) or Shadowsocks 2022 (`ss2022`). The
|
||||
user's ordered choice applies only to those physical data links. The internal
|
||||
capability `wireguard-e2e` v4 is fixed and hidden from the CLI/tray controls.
|
||||
All carriers move the same inner encrypted bytes, including through relays.
|
||||
@@ -242,10 +243,12 @@ The client renews the selected exit peer's session key at 120 seconds, even
|
||||
when no IP traffic is flowing. The current key can carry packets during the
|
||||
exchange. Changing the exit moves this behavior to the new network and peer.
|
||||
|
||||
The device list shows **Idle** after an established tunnel has had 30 seconds
|
||||
without IP traffic. Handshakes and keepalives do not restart this interval.
|
||||
Pending IP packets, a missing path, or a selected exit waiting for a usable
|
||||
key still show **Waiting**. A reported transport failure shows **Error**.
|
||||
The device list shows **Idle** after 30 seconds without application traffic
|
||||
on a confirmed path with a usable key and an empty packet queue. Encrypted
|
||||
round-trip probes keep measuring an idle path all the way to the destination.
|
||||
Probes, handshakes and keepalives leave the idle timer and application counters
|
||||
unchanged. A missing key or an unconfirmed path shows **Waiting**. A reported
|
||||
transport failure shows **Error**.
|
||||
|
||||
User traffic counters count original IP bytes once when the encrypted frame is
|
||||
accepted by the logical transport, and once when decrypted on receipt. They do
|
||||
|
||||
+1
-1
@@ -34,7 +34,7 @@ let
|
||||
in
|
||||
rustPlatform.buildRustPackage {
|
||||
pname = if withTray then "tsunagi" else "tsunagi-cli";
|
||||
version = "1.0.9";
|
||||
version = "1.0.12";
|
||||
|
||||
src = lib.cleanSource ../.;
|
||||
cargoLock.lockFile = ../Cargo.lock;
|
||||
|
||||
Reference in new issue
Block a user