Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a966152143 | ||
|
|
6e71d8cf8c | ||
|
|
16d7f82af5 |
No files matched your search
Generated
+71
-10
@@ -211,6 +211,9 @@ name = "arrayvec"
|
|||||||
version = "0.7.8"
|
version = "0.7.8"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"
|
||||||
|
dependencies = [
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "as-raw-xcb-connection"
|
name = "as-raw-xcb-connection"
|
||||||
@@ -493,6 +496,7 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
"constant_time_eq",
|
"constant_time_eq",
|
||||||
"cpufeatures 0.3.1",
|
"cpufeatures 0.3.1",
|
||||||
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -6296,7 +6300,7 @@ checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi"
|
name = "tsunagi"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"anstream",
|
"anstream",
|
||||||
"anstyle",
|
"anstyle",
|
||||||
@@ -6320,7 +6324,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-android"
|
name = "tsunagi-android"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"egui",
|
"egui",
|
||||||
@@ -6344,7 +6348,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-awg"
|
name = "tsunagi-awg"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"iroh",
|
"iroh",
|
||||||
@@ -6359,7 +6363,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-core"
|
name = "tsunagi-core"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"arc-swap",
|
"arc-swap",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -6404,17 +6408,35 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-runtime"
|
name = "tsunagi-runtime"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
|
"data-encoding",
|
||||||
|
"hex",
|
||||||
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tsunagi-awg",
|
"tsunagi-awg",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-shoes",
|
||||||
|
"tsunagi-ss2022",
|
||||||
"tsunagi-tcp-tls",
|
"tsunagi-tcp-tls",
|
||||||
|
"tsunagi-vless-xhttp",
|
||||||
"tsunagi-wg-quic",
|
"tsunagi-wg-quic",
|
||||||
"tsunagi-wireguard",
|
"tsunagi-wireguard",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tsunagi-shoes"
|
||||||
|
version = "1.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"iroh",
|
||||||
|
"rand 0.10.3",
|
||||||
|
"tokio",
|
||||||
|
"tsunagi-core",
|
||||||
|
"tsunagi-tcp-tls",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-speedtest"
|
name = "tsunagi-speedtest"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
@@ -6425,9 +6447,23 @@ dependencies = [
|
|||||||
"tokio",
|
"tokio",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tsunagi-ss2022"
|
||||||
|
version = "1.0.0"
|
||||||
|
dependencies = [
|
||||||
|
"blake3",
|
||||||
|
"iroh",
|
||||||
|
"rand 0.10.3",
|
||||||
|
"ring",
|
||||||
|
"tokio",
|
||||||
|
"tsunagi-core",
|
||||||
|
"tsunagi-shoes",
|
||||||
|
"zeroize",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-tcp-tls"
|
name = "tsunagi-tcp-tls"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"bytes",
|
"bytes",
|
||||||
"caps",
|
"caps",
|
||||||
@@ -6437,17 +6473,19 @@ dependencies = [
|
|||||||
"rcgen",
|
"rcgen",
|
||||||
"rustls",
|
"rustls",
|
||||||
"serde",
|
"serde",
|
||||||
|
"socket2",
|
||||||
"tempfile",
|
"tempfile",
|
||||||
"tokio",
|
"tokio",
|
||||||
"tokio-rustls",
|
"tokio-rustls",
|
||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"x509-parser",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-tray"
|
name = "tsunagi-tray"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"eframe",
|
"eframe",
|
||||||
"egui-phosphor",
|
"egui-phosphor",
|
||||||
@@ -6463,7 +6501,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-ui"
|
name = "tsunagi-ui"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"egui",
|
"egui",
|
||||||
"egui-phosphor",
|
"egui-phosphor",
|
||||||
@@ -6474,9 +6512,29 @@ dependencies = [
|
|||||||
"zeroize",
|
"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]]
|
[[package]]
|
||||||
name = "tsunagi-wg-quic"
|
name = "tsunagi-wg-quic"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"boringtun",
|
"boringtun",
|
||||||
"bytes",
|
"bytes",
|
||||||
@@ -6496,14 +6554,17 @@ dependencies = [
|
|||||||
"tracing",
|
"tracing",
|
||||||
"tracing-subscriber",
|
"tracing-subscriber",
|
||||||
"tsunagi-core",
|
"tsunagi-core",
|
||||||
|
"tsunagi-shoes",
|
||||||
|
"tsunagi-ss2022",
|
||||||
"tsunagi-tcp-tls",
|
"tsunagi-tcp-tls",
|
||||||
|
"tsunagi-vless-xhttp",
|
||||||
"tsunagi-wireguard",
|
"tsunagi-wireguard",
|
||||||
"zeroize",
|
"zeroize",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "tsunagi-wireguard"
|
name = "tsunagi-wireguard"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"boringtun",
|
"boringtun",
|
||||||
"bytes",
|
"bytes",
|
||||||
|
|||||||
@@ -127,11 +127,23 @@ status and recent traffic. Expand it to see who is using this device for interne
|
|||||||
access.
|
access.
|
||||||
[Details and per-OS notes](docs/exit-node.md).
|
[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
|
fresh masking profile and outer keys for each pair connection attempt, including
|
||||||
reentry after fallback. Sustained data loss triggers switching independently of
|
reentry after fallback. Sustained data loss triggers switching independently of
|
||||||
the iroh control connection. [Configuration and limits](docs/amnezia.md).
|
the iroh control connection. [Configuration and limits](docs/amnezia.md).
|
||||||
|
|
||||||
|
The **Shoes** family adds two embedded TCP carriers. `vless-xhttp` uses VLESS
|
||||||
|
over XHTTP stream-one with HTTP/2 and pinned TLS 1.3 (preferred port 9443).
|
||||||
|
`ss2022` uses Shadowsocks 2022 with AES-128-GCM or AES-256-GCM (9444).
|
||||||
|
Peers agree fresh credentials over their authenticated control connection on
|
||||||
|
every attempt. The agent runs both listeners itself. Override their ports with
|
||||||
|
`tsng up -o vless-xhttp:port=10443 -o ss2022:port=10444`.
|
||||||
|
|
||||||
|
With two updated peers, `tcp-tls` and both Shoes carriers try the opposite dial
|
||||||
|
direction if the first fails. One reachable TCP listener suffices. If neither
|
||||||
|
side accepts TCP, the mesh can use another enabled carrier or an available
|
||||||
|
relay route. [Wire profiles and compatibility](docs/shoes.md).
|
||||||
|
|
||||||
Change a network's protocol selection without editing its service or restarting:
|
Change a network's protocol selection without editing its service or restarting:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
@@ -144,8 +156,10 @@ tsng protocols home none # control plane only
|
|||||||
Exact network names, full ids and unique id prefixes work here. The choice is
|
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
|
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
|
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
|
name to expand its card. Open **Data transports** to toggle a family or expand it to select individual
|
||||||
their initial preference order. **Show devices** lists peers and their reported
|
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.
|
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
|
Select a peer’s speedometer in **Devices** to measure download and upload
|
||||||
|
|||||||
@@ -24,7 +24,7 @@ android {
|
|||||||
targetSdk 35
|
targetSdk 35
|
||||||
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
|
||||||
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
versionCode providers.gradleProperty('tsunagiVersionCode').getOrElse('1').toInteger()
|
||||||
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.10')
|
versionName providers.gradleProperty('tsunagiVersionName').getOrElse('1.0.11')
|
||||||
ndk { abiFilters abi }
|
ndk { abiFilters abi }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-android"
|
name = "tsunagi-android"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Android VPN client and egui views for tsunagi."
|
description = "Android VPN client and egui views for tsunagi."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -16,7 +16,7 @@ name = "vpn_source_probe"
|
|||||||
crate-type = ["cdylib"]
|
crate-type = ["cdylib"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.10" }
|
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.11" }
|
||||||
tsunagi-ui = { path = "../tsunagi-ui" }
|
tsunagi-ui = { path = "../tsunagi-ui" }
|
||||||
tsunagi-core = { path = "../tsunagi-core" }
|
tsunagi-core = { path = "../tsunagi-core" }
|
||||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic" }
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ use std::{sync::Arc, time::Instant};
|
|||||||
use tokio::sync::{mpsc, watch};
|
use tokio::sync::{mpsc, watch};
|
||||||
use tsunagi::{
|
use tsunagi::{
|
||||||
Agent, NetworkName, NetworkSecret,
|
Agent, NetworkName, NetworkSecret,
|
||||||
ipc::{DnsReport, PrivilegeReport, ProtocolReport, StatusReport},
|
ipc::{DnsReport, PrivilegeReport, StatusReport},
|
||||||
vip::VipStatus,
|
vip::VipStatus,
|
||||||
};
|
};
|
||||||
use tsunagi_ui::client::Command;
|
use tsunagi_ui::client::Command;
|
||||||
@@ -302,10 +302,7 @@ async fn snapshot(
|
|||||||
cache_healthy: status.cache_healthy,
|
cache_healthy: status.cache_healthy,
|
||||||
available_protocols: tsunagi_runtime::PROTOCOLS
|
available_protocols: tsunagi_runtime::PROTOCOLS
|
||||||
.iter()
|
.iter()
|
||||||
.map(|spec| ProtocolReport {
|
.map(|spec| spec.report())
|
||||||
name: spec.name.into(),
|
|
||||||
summary: spec.summary.into(),
|
|
||||||
})
|
|
||||||
.collect(),
|
.collect(),
|
||||||
protocols: tsunagi_runtime::PROTOCOLS
|
protocols: tsunagi_runtime::PROTOCOLS
|
||||||
.iter()
|
.iter()
|
||||||
|
|||||||
@@ -449,16 +449,21 @@ fn broadcast_route_is_only_present_when_requested() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[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::{Agent, testing};
|
||||||
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
use tsunagi_runtime::{Carriers, PROTOCOLS};
|
||||||
let dir = tempfile::tempdir().unwrap();
|
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 (network, secret) = testing::network("carriers");
|
||||||
|
let (other, other_secret) = testing::network("other");
|
||||||
for restart in [false, true] {
|
for restart in [false, true] {
|
||||||
let config = testing::local_config(dir.path());
|
let config = testing::local_config(dir.path());
|
||||||
let (config, carriers) = Carriers::configure(config, &[], None, |spec| {
|
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())]
|
vec![("port".into(), "0".into())]
|
||||||
} else {
|
} else {
|
||||||
Vec::new()
|
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;
|
let saved = agent.network_status(id).await.unwrap().protocols;
|
||||||
if restart {
|
if restart {
|
||||||
assert_eq!(saved, ["tcp-tls", "wg"]);
|
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 {
|
} else {
|
||||||
assert_eq!(saved, names);
|
assert_eq!(saved, names);
|
||||||
agent
|
agent
|
||||||
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
.set_protocols(id, vec!["tcp-tls".into(), "wg".into()])
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
let (other, secret) = testing::network("other");
|
let second = agent.join_network(&other, &other_secret).await.unwrap();
|
||||||
let second = agent.join_network(&other, &secret).await.unwrap();
|
|
||||||
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
assert_eq!(agent.network_status(second).await.unwrap().protocols, names);
|
||||||
|
agent.set_protocols(second, vec![]).await.unwrap();
|
||||||
}
|
}
|
||||||
agent.shutdown().await;
|
agent.shutdown().await;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-awg"
|
name = "tsunagi-awg"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
description = "Ephemeral pairwise Amnezia transport for Tsunagi."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-core"
|
name = "tsunagi-core"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Small private mesh networks: persistent agent identity, deterministic network spaces, an iroh control plane, signed state and a local DNS view."
|
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"
|
readme = "../../README.md"
|
||||||
keywords = ["mesh", "p2p", "iroh", "networking"]
|
keywords = ["mesh", "p2p", "iroh", "networking"]
|
||||||
|
|||||||
@@ -40,6 +40,7 @@ use super::status::{
|
|||||||
};
|
};
|
||||||
use sync::{Changes, SyncKey};
|
use sync::{Changes, SyncKey};
|
||||||
|
|
||||||
|
mod reverse;
|
||||||
mod selection;
|
mod selection;
|
||||||
mod sync;
|
mod sync;
|
||||||
|
|
||||||
@@ -407,6 +408,7 @@ struct Runtime {
|
|||||||
/// Links currently being opened, so we do not start two.
|
/// Links currently being opened, so we do not start two.
|
||||||
opening: HashSet<(EndpointId, String)>,
|
opening: HashSet<(EndpointId, String)>,
|
||||||
link_tasks: HashMap<(EndpointId, String), tokio::task::AbortHandle>,
|
link_tasks: HashMap<(EndpointId, String), tokio::task::AbortHandle>,
|
||||||
|
reverse_dials: HashMap<(EndpointId, String), u64>,
|
||||||
link_attempts: HashMap<(EndpointId, String), u64>,
|
link_attempts: HashMap<(EndpointId, String), u64>,
|
||||||
next_link_attempt: u64,
|
next_link_attempt: u64,
|
||||||
link_results_tx: mpsc::Sender<LinkOutcome>,
|
link_results_tx: mpsc::Sender<LinkOutcome>,
|
||||||
@@ -515,6 +517,7 @@ impl Runtime {
|
|||||||
announced_reach: HashSet::new(),
|
announced_reach: HashSet::new(),
|
||||||
opening: HashSet::new(),
|
opening: HashSet::new(),
|
||||||
link_tasks: HashMap::new(),
|
link_tasks: HashMap::new(),
|
||||||
|
reverse_dials: HashMap::new(),
|
||||||
link_attempts: HashMap::new(),
|
link_attempts: HashMap::new(),
|
||||||
next_link_attempt: 0,
|
next_link_attempt: 0,
|
||||||
link_results_tx,
|
link_results_tx,
|
||||||
@@ -2086,12 +2089,12 @@ impl Runtime {
|
|||||||
|
|
||||||
/// Opens whatever data plane links are missing, and forgets dead ones.
|
/// 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,
|
/// The smaller endpoint coordinates each attempt, including a reverse
|
||||||
/// so two agents never open two links for the same thing.
|
/// TCP dial if the negotiated carrier supports it.
|
||||||
fn ensure_links(&mut self) {
|
fn ensure_links(&mut self) {
|
||||||
let Some(transport) = self.params.transport.clone() else {
|
if self.params.transport.is_none() {
|
||||||
return;
|
return;
|
||||||
};
|
}
|
||||||
let served = self.served_protocols();
|
let served = self.served_protocols();
|
||||||
if served.is_empty() {
|
if served.is_empty() {
|
||||||
return;
|
return;
|
||||||
@@ -2157,8 +2160,7 @@ impl Runtime {
|
|||||||
if self.no_direct_data(peer) {
|
if self.no_direct_data(peer) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
// The smaller endpoint id dials; the other side accepts. Both
|
// The smaller endpoint tries first and can invite a peer to dial back.
|
||||||
// compute this identically, so exactly one link is created.
|
|
||||||
if self.local_id.as_bytes() >= peer.as_bytes() {
|
if self.local_id.as_bytes() >= peer.as_bytes() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -2206,6 +2208,7 @@ impl Runtime {
|
|||||||
for key in interrupted {
|
for key in interrupted {
|
||||||
self.opening.remove(&key);
|
self.opening.remove(&key);
|
||||||
self.link_attempts.remove(&key);
|
self.link_attempts.remove(&key);
|
||||||
|
self.reverse_dials.remove(&key);
|
||||||
if let Some(task) = self.link_tasks.remove(&key) {
|
if let Some(task) = self.link_tasks.remove(&key) {
|
||||||
task.abort();
|
task.abort();
|
||||||
}
|
}
|
||||||
@@ -2214,49 +2217,57 @@ impl Runtime {
|
|||||||
let trial = self.next_comparison(&served, now);
|
let trial = self.next_comparison(&served, now);
|
||||||
wanted.extend(trial.iter().cloned());
|
wanted.extend(trial.iter().cloned());
|
||||||
for (peer, protocol) in wanted {
|
for (peer, protocol) in wanted {
|
||||||
let key = (peer, protocol.clone());
|
let background = trial.as_ref() == Some(&(peer, protocol.clone()));
|
||||||
if self.links.contains_key(&key) || self.opening.contains(&key) {
|
self.start_link_attempt(peer, protocol, background);
|
||||||
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());
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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.
|
/// Takes in what another member knows about the rest.
|
||||||
///
|
///
|
||||||
/// Returns how many of them were new here, which is the only reason to
|
/// Returns how many of them were new here, which is the only reason to
|
||||||
@@ -2529,6 +2540,17 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
return;
|
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.link_attempts.remove(&key);
|
||||||
self.opening.remove(&key);
|
self.opening.remove(&key);
|
||||||
self.link_tasks.remove(&key);
|
self.link_tasks.remove(&key);
|
||||||
@@ -2586,6 +2608,21 @@ impl Runtime {
|
|||||||
inbound.link.close();
|
inbound.link.close();
|
||||||
return;
|
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.record_protocol_success(inbound.peer, &inbound.protocol);
|
||||||
self.adopt_link(inbound.peer, inbound.protocol, inbound.link);
|
self.adopt_link(inbound.peer, inbound.protocol, inbound.link);
|
||||||
self.update_paths();
|
self.update_paths();
|
||||||
@@ -2675,6 +2712,7 @@ impl Runtime {
|
|||||||
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
fn reset_peer_data(&mut self, peer: EndpointId, reason: &str) {
|
||||||
self.comparisons.remove(&peer);
|
self.comparisons.remove(&peer);
|
||||||
self.data_errors.remove(&peer);
|
self.data_errors.remove(&peer);
|
||||||
|
self.reverse_dials.retain(|(id, _), _| *id != peer);
|
||||||
self.link_attempts.retain(|(id, _), _| *id != peer);
|
self.link_attempts.retain(|(id, _), _| *id != peer);
|
||||||
self.opening.retain(|(id, _)| *id != peer);
|
self.opening.retain(|(id, _)| *id != peer);
|
||||||
self.link_tasks.retain(|(id, _), task| {
|
self.link_tasks.retain(|(id, _), task| {
|
||||||
@@ -2832,6 +2870,14 @@ impl Runtime {
|
|||||||
reason,
|
reason,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
if self
|
||||||
|
.params
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.supports_reverse_dial())
|
||||||
|
{
|
||||||
|
capabilities.push(reverse::capability());
|
||||||
|
}
|
||||||
if self.params.carriers.len() > 1 {
|
if self.params.carriers.len() > 1 {
|
||||||
capabilities.push(selection::capability());
|
capabilities.push(selection::capability());
|
||||||
}
|
}
|
||||||
@@ -3024,6 +3070,10 @@ impl Runtime {
|
|||||||
}
|
}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if protocol == reverse::PROTOCOL {
|
||||||
|
self.receive_reverse(peer, payload.as_bytes());
|
||||||
|
return;
|
||||||
|
}
|
||||||
if protocol == selection::PROTOCOL {
|
if protocol == selection::PROTOCOL {
|
||||||
self.receive_choice(peer, payload.as_bytes());
|
self.receive_choice(peer, payload.as_bytes());
|
||||||
return;
|
return;
|
||||||
@@ -3152,6 +3202,14 @@ impl Runtime {
|
|||||||
|
|
||||||
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
fn dispatch_capabilities(&mut self, peer: EndpointId, capabilities: &[PluginCapability]) {
|
||||||
let mut errors = Vec::new();
|
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 {
|
for cap in capabilities {
|
||||||
let carriers = self
|
let carriers = self
|
||||||
.params
|
.params
|
||||||
@@ -3162,7 +3220,7 @@ impl Runtime {
|
|||||||
(
|
(
|
||||||
carrier.protocol_version(),
|
carrier.protocol_version(),
|
||||||
if carrier.protocol_version() == cap.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 {
|
} else {
|
||||||
Ok(())
|
Ok(())
|
||||||
},
|
},
|
||||||
@@ -3318,6 +3376,7 @@ impl Runtime {
|
|||||||
.iter()
|
.iter()
|
||||||
.filter(|cap| {
|
.filter(|cap| {
|
||||||
cap.enabled
|
cap.enabled
|
||||||
|
&& cap.protocol != reverse::PROTOCOL
|
||||||
&& cap.protocol != selection::PROTOCOL
|
&& cap.protocol != selection::PROTOCOL
|
||||||
&& self
|
&& self
|
||||||
.params
|
.params
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
//! The elected opener grants one bounded reverse dial over authenticated control.
|
||||||
|
use super::{ControlMessage, EndpointId, LinkOutcome, PluginCapability, Runtime};
|
||||||
|
use crate::dataplane::transport::{DataCarrier, PacketLink, TransportPayload};
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
pub(super) const PROTOCOL: &str = "link-reverse";
|
||||||
|
|
||||||
|
pub(super) fn capability() -> PluginCapability {
|
||||||
|
PluginCapability {
|
||||||
|
protocol: PROTOCOL.into(),
|
||||||
|
version: 1,
|
||||||
|
enabled: true,
|
||||||
|
data: Vec::new(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Runtime {
|
||||||
|
fn mutual_carrier(&self, peer: EndpointId, name: &str) -> Option<&dyn DataCarrier> {
|
||||||
|
let caps = &self.sessions.get(&peer)?.capabilities;
|
||||||
|
self.params
|
||||||
|
.carriers
|
||||||
|
.iter()
|
||||||
|
.find(|c| {
|
||||||
|
c.protocol_id() == name
|
||||||
|
&& caps.iter().any(|cap| {
|
||||||
|
cap.enabled && cap.protocol == name && cap.version == c.protocol_version()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.map(|c| c.as_ref())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn can_reverse(&self, peer: EndpointId, protocol: &str) -> bool {
|
||||||
|
self.mutual_carrier(peer, protocol)
|
||||||
|
.is_some_and(|c| c.supports_reverse_dial())
|
||||||
|
&& self.sessions.get(&peer).is_some_and(|s| {
|
||||||
|
s.capabilities
|
||||||
|
.iter()
|
||||||
|
.any(|c| c.enabled && c.protocol == PROTOCOL && c.version == 1)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn send_reverse(
|
||||||
|
&mut self,
|
||||||
|
peer: EndpointId,
|
||||||
|
protocol: &str,
|
||||||
|
token: u64,
|
||||||
|
request: bool,
|
||||||
|
) -> bool {
|
||||||
|
let Ok(bytes) = postcard::to_stdvec(&(request, token, protocol)) else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
self.send_to(
|
||||||
|
peer,
|
||||||
|
ControlMessage::Transport {
|
||||||
|
protocol: PROTOCOL.into(),
|
||||||
|
payload: TransportPayload::new(bytes),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.is_ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn ask_for_reverse(&mut self, attempt: &LinkOutcome) -> bool {
|
||||||
|
let peer = attempt.peer;
|
||||||
|
let protocol = &attempt.protocol;
|
||||||
|
let generation = attempt.generation;
|
||||||
|
if self.local_id >= peer
|
||||||
|
|| !self.can_reverse(peer, protocol)
|
||||||
|
|| !self.send_reverse(peer, protocol, generation, true)
|
||||||
|
{
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
let key = (peer, protocol.clone());
|
||||||
|
self.reverse_dials.insert(key.clone(), generation);
|
||||||
|
let tx = self.link_results_tx.clone();
|
||||||
|
let protocol = protocol.clone();
|
||||||
|
let task = tokio::spawn(async move {
|
||||||
|
tokio::time::sleep(Duration::from_secs(12)).await;
|
||||||
|
let _ = tx
|
||||||
|
.send(LinkOutcome {
|
||||||
|
generation,
|
||||||
|
peer,
|
||||||
|
protocol,
|
||||||
|
result: Err("reverse TCP dial timed out".into()),
|
||||||
|
})
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
self.link_tasks.insert(key, task.abort_handle());
|
||||||
|
true
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(super) fn receive_reverse(&mut self, peer: EndpointId, payload: &[u8]) {
|
||||||
|
let Ok((request, generation, protocol)) =
|
||||||
|
postcard::from_bytes::<(bool, u64, &str)>(payload)
|
||||||
|
else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
if protocol.len() > crate::dataplane::MAX_PROTOCOL_ID_LEN
|
||||||
|
|| !self.can_reverse(peer, protocol)
|
||||||
|
{
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let key = (peer, protocol.to_owned());
|
||||||
|
if request && peer < self.local_id {
|
||||||
|
if self.opening.contains(&key) || self.links.get(&key).is_some_and(|l| !l.is_closed()) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if self.no_direct_data(peer)
|
||||||
|
|| self
|
||||||
|
.protocol_dial_states
|
||||||
|
.get(&key)
|
||||||
|
.is_some_and(|s| s.cooldown_until > Instant::now())
|
||||||
|
{
|
||||||
|
self.send_reverse(peer, protocol, generation, false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
self.reverse_dials.insert(key, generation);
|
||||||
|
self.start_link_attempt(peer, protocol.to_owned(), false);
|
||||||
|
} else if !request
|
||||||
|
&& self.local_id < peer
|
||||||
|
&& self.reverse_dials.get(&key) == Some(&generation)
|
||||||
|
{
|
||||||
|
if let Some(task) = self.link_tasks.remove(&key) {
|
||||||
|
task.abort();
|
||||||
|
}
|
||||||
|
self.handle_link_result(LinkOutcome {
|
||||||
|
generation,
|
||||||
|
peer,
|
||||||
|
protocol: protocol.into(),
|
||||||
|
result: Err("neither TCP dial direction succeeded".into()),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -11,6 +11,10 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
fn protocol_id(&self) -> &str;
|
fn protocol_id(&self) -> &str;
|
||||||
/// Wire version, independent of software releases and the internal tunnel.
|
/// Wire version, independent of software releases and the internal tunnel.
|
||||||
fn protocol_version(&self) -> u16;
|
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.
|
/// Supported carrier settings.
|
||||||
fn options(&self) -> &'static [ProtocolOption] {
|
fn options(&self) -> &'static [ProtocolOption] {
|
||||||
&[]
|
&[]
|
||||||
@@ -25,6 +29,17 @@ pub trait DataCarrier: Send + Sync + std::fmt::Debug + 'static {
|
|||||||
peer: EndpointId,
|
peer: EndpointId,
|
||||||
capability: &PluginCapability,
|
capability: &PluginCapability,
|
||||||
) -> Result<(), PluginError>;
|
) -> 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.
|
/// Supplies the actual owned interface name, including kernel-assigned names.
|
||||||
fn on_interface_ready(&self, _name: &str) {}
|
fn on_interface_ready(&self, _name: &str) {}
|
||||||
/// Activates this carrier for one local network.
|
/// Activates this carrier for one local network.
|
||||||
|
|||||||
@@ -739,6 +739,10 @@ pub struct RangeConflictReport {
|
|||||||
/// A data-plane protocol available in the running agent.
|
/// A data-plane protocol available in the running agent.
|
||||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct ProtocolReport {
|
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.
|
/// Stable protocol name used by the CLI and network negotiation.
|
||||||
pub name: String,
|
pub name: String,
|
||||||
/// A short description of encryption and transport.
|
/// A short description of encryption and transport.
|
||||||
@@ -1214,7 +1218,7 @@ pub const EXCHANGE_TIMEOUT: Duration = Duration::from_secs(5);
|
|||||||
///
|
///
|
||||||
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
/// Bump it whenever [`Request`], [`Response`] or anything they contain
|
||||||
/// changes shape.
|
/// 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.
|
/// Reads one request off an accepted stream, answers it, writes the response.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-runtime"
|
name = "tsunagi-runtime"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Built-in mesh transports and status reporting for native tsunagi agents."
|
description = "Built-in mesh transports and status reporting for native tsunagi agents."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -8,13 +8,21 @@ license.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.10" }
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.11" }
|
||||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.10" }
|
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.11" }
|
||||||
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.10" }
|
tsunagi-awg = { path = "../tsunagi-awg", version = "1.0.11" }
|
||||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.10" }
|
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.11" }
|
||||||
|
tsunagi-shoes = { path = "../tsunagi-shoes", version = "1.0.0" }
|
||||||
|
tsunagi-vless-xhttp = { path = "../tsunagi-vless-xhttp", version = "1.0.0" }
|
||||||
|
tsunagi-ss2022 = { path = "../tsunagi-ss2022", version = "1.0.0" }
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
tempfile.workspace = true
|
||||||
|
data-encoding.workspace = true
|
||||||
|
hex.workspace = true
|
||||||
|
|
||||||
[lints]
|
[lints]
|
||||||
workspace = true
|
workspace = true
|
||||||
@@ -10,7 +10,11 @@ use tsunagi::{
|
|||||||
iroh_types::EndpointAddr,
|
iroh_types::EndpointAddr,
|
||||||
};
|
};
|
||||||
use tsunagi_awg::{AWG_PROTOCOL, AWG_WIRE_VERSION, AwgPlugin, AwgTransport};
|
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;
|
use tsunagi_wireguard::WG_PROTOCOL;
|
||||||
|
|
||||||
pub mod report;
|
pub mod report;
|
||||||
@@ -23,6 +27,10 @@ pub mod report;
|
|||||||
pub struct ProtocolSpec {
|
pub struct ProtocolSpec {
|
||||||
/// The name on the wire, which is what peers compare.
|
/// The name on the wire, which is what peers compare.
|
||||||
pub name: &'static str,
|
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
|
/// The wire version. Not the software version: two peers on different
|
||||||
/// builds carry traffic for each other as long as this matches.
|
/// builds carry traffic for each other as long as this matches.
|
||||||
pub version: u16,
|
pub version: u16,
|
||||||
@@ -32,6 +40,27 @@ pub struct ProtocolSpec {
|
|||||||
pub options: &'static [tsunagi::dataplane::ProtocolOption],
|
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 {
|
const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::ProtocolOption {
|
||||||
key: "port",
|
key: "port",
|
||||||
value: "PORT",
|
value: "PORT",
|
||||||
@@ -43,34 +72,59 @@ const WG_OPTIONS: &[tsunagi::dataplane::ProtocolOption] = &[tsunagi::dataplane::
|
|||||||
pub const PROTOCOLS: &[ProtocolSpec] = &[
|
pub const PROTOCOLS: &[ProtocolSpec] = &[
|
||||||
ProtocolSpec {
|
ProtocolSpec {
|
||||||
name: WG_PROTOCOL,
|
name: WG_PROTOCOL,
|
||||||
|
group: "WireGuard",
|
||||||
|
label: "WireGuard",
|
||||||
version: tsunagi_wireguard::WG_WIRE_VERSION,
|
version: tsunagi_wireguard::WG_WIRE_VERSION,
|
||||||
summary: "Pure WireGuard direct UDP transport",
|
summary: "Pure WireGuard direct UDP transport",
|
||||||
options: WG_OPTIONS,
|
options: WG_OPTIONS,
|
||||||
},
|
},
|
||||||
ProtocolSpec {
|
ProtocolSpec {
|
||||||
name: AWG_PROTOCOL,
|
name: AWG_PROTOCOL,
|
||||||
|
group: "WireGuard",
|
||||||
|
label: "AmneziaWG",
|
||||||
version: AWG_WIRE_VERSION,
|
version: AWG_WIRE_VERSION,
|
||||||
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
|
summary: "Pairwise Amnezia-masked UDP with fresh private profiles on every connection attempt",
|
||||||
options: AwgPlugin::OPTIONS,
|
options: AwgPlugin::OPTIONS,
|
||||||
},
|
},
|
||||||
ProtocolSpec {
|
ProtocolSpec {
|
||||||
name: "wg-quic",
|
name: "wg-quic",
|
||||||
|
group: "iroh",
|
||||||
|
label: "WG over QUIC",
|
||||||
version: 1,
|
version: 1,
|
||||||
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
|
summary: "iroh QUIC datagram carrier with NAT traversal and relays",
|
||||||
options: &[],
|
options: &[],
|
||||||
},
|
},
|
||||||
ProtocolSpec {
|
ProtocolSpec {
|
||||||
name: TCP_TLS_PROTOCOL,
|
name: TCP_TLS_PROTOCOL,
|
||||||
|
group: "Native",
|
||||||
|
label: "TCP + TLS",
|
||||||
version: tsunagi_tcp_tls::TCP_TLS_VERSION,
|
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,
|
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.
|
/// Incoming direct connections to attach after the agent has acquired its identity.
|
||||||
pub struct Carriers {
|
pub struct Carriers {
|
||||||
udp: [Arc<AwgTransport>; 2],
|
udp: [Arc<AwgTransport>; 2],
|
||||||
tls: Arc<TcpTlsTransport>,
|
tls: Arc<TcpTlsTransport>,
|
||||||
|
shoes: Vec<Arc<ShoesTransport>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Carriers {
|
impl Carriers {
|
||||||
@@ -142,20 +196,52 @@ impl Carriers {
|
|||||||
.await
|
.await
|
||||||
.map_err(|error| -> Box<dyn std::error::Error> { error })?,
|
.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());
|
let carrier = TcpTlsCarrier::with_interface(tls.clone(), config.interface_name.clone());
|
||||||
if let Some(source) = underlay {
|
carrier.set_bootstrap(bootstrap);
|
||||||
carrier.set_underlay(source);
|
if let Some(source) = &underlay {
|
||||||
|
carrier.set_underlay(source.clone());
|
||||||
}
|
}
|
||||||
config = config
|
config = config
|
||||||
.with_carrier(Arc::new(IrohCarrier))
|
.with_carrier(Arc::new(IrohCarrier))
|
||||||
.with_carrier(carrier)
|
.with_carrier(carrier)
|
||||||
.with_custom_transport(TCP_TLS_PROTOCOL, tls.clone());
|
.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.
|
/// 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();
|
let agent = agent.clone();
|
||||||
tasks.spawn(async move {
|
tasks.spawn(async move {
|
||||||
self.tls
|
self.tls
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
//! Optional interoperability against an independently built upstream Shoes server.
|
||||||
|
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||||
|
use std::{
|
||||||
|
fs,
|
||||||
|
process::{Child, Command, Stdio},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncReadExt, AsyncWriteExt},
|
||||||
|
net::{TcpListener, TcpStream},
|
||||||
|
};
|
||||||
|
use tsunagi::identity::DeviceIdentity;
|
||||||
|
use tsunagi_shoes::{Profile, ShoesWire};
|
||||||
|
use tsunagi_tcp_tls::cert::generate_self_signed_cert;
|
||||||
|
|
||||||
|
struct Reference(Child);
|
||||||
|
impl Drop for Reference {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = self.0.kill();
|
||||||
|
let _ = self.0.wait();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn pem(label: &str, bytes: &[u8]) -> String {
|
||||||
|
format!(
|
||||||
|
"-----BEGIN {label}-----\n{}\n-----END {label}-----\n",
|
||||||
|
data_encoding::BASE64.encode(bytes)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
#[ignore = "set TSUNAGI_SHOES_BIN to the upstream Shoes executable (v0.3.8)"]
|
||||||
|
async fn upstream_server_accepts_stream_one_and_both_ss2022_methods() {
|
||||||
|
let bin = std::env::var_os("TSUNAGI_SHOES_BIN").expect("upstream Shoes path");
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let endpoint = DeviceIdentity::generate();
|
||||||
|
let (cert, key) = generate_self_signed_cert(&endpoint.secret_bytes(), "localhost").unwrap();
|
||||||
|
fs::write(
|
||||||
|
dir.path().join("cert.pem"),
|
||||||
|
pem("CERTIFICATE", cert.as_ref()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
fs::write(
|
||||||
|
dir.path().join("key.pem"),
|
||||||
|
pem("PRIVATE KEY", key.secret_der()),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
for (is_vless, use_256) in [(true, false), (false, false), (false, true)] {
|
||||||
|
let profile = Profile {
|
||||||
|
tag: [0x34; 32],
|
||||||
|
secret: [0x53; 32],
|
||||||
|
variant: use_256,
|
||||||
|
};
|
||||||
|
let (wire, protocol): (Box<dyn ShoesWire>, String) = if is_vless {
|
||||||
|
let path = hex::encode(profile.tag);
|
||||||
|
(
|
||||||
|
Box::new(tsunagi_vless_xhttp::VlessXhttp::new(&endpoint).unwrap()),
|
||||||
|
format!(
|
||||||
|
"type: tls\n default_target:\n cert: cert.pem\n key: key.pem\n alpn_protocols: [h2]\n protocol:\n type: xhttp\n path: /{path}/\n mode: stream-one\n protocol:\n type: vless\n user_id: 53535353-5353-4353-9353-535353535353"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
let size = if use_256 { 32 } else { 16 };
|
||||||
|
let key = data_encoding::BASE64.encode(&profile.secret[..size]);
|
||||||
|
(
|
||||||
|
Box::new(tsunagi_ss2022::Shadowsocks2022),
|
||||||
|
format!(
|
||||||
|
"type: shadowsocks\n cipher: 2022-blake3-aes-{}-gcm\n password: '{key}'",
|
||||||
|
size * 8
|
||||||
|
),
|
||||||
|
)
|
||||||
|
};
|
||||||
|
let backend = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let backend_address = backend.local_addr().unwrap();
|
||||||
|
let reservation = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||||
|
let address = reservation.local_addr().unwrap();
|
||||||
|
fs::write(dir.path().join("reference.yaml"), format!("- address: {address}\n protocol:\n {protocol}\n rules:\n - mask: 127.0.0.1:1\n action: allow\n override_address: {backend_address}\n client_chain: direct\n")).unwrap();
|
||||||
|
drop(reservation);
|
||||||
|
let mut server = Reference(
|
||||||
|
Command::new(&bin)
|
||||||
|
.current_dir(dir.path())
|
||||||
|
.args(["-t", "1", "--no-reload", "reference.yaml"])
|
||||||
|
.stdout(Stdio::null())
|
||||||
|
.spawn()
|
||||||
|
.unwrap(),
|
||||||
|
);
|
||||||
|
tokio::time::timeout(Duration::from_secs(15), async {
|
||||||
|
let tcp = loop {
|
||||||
|
assert!(
|
||||||
|
server.0.try_wait().unwrap().is_none(),
|
||||||
|
"reference server exited at startup"
|
||||||
|
);
|
||||||
|
if let Ok(tcp) = TcpStream::connect(address).await {
|
||||||
|
break tcp;
|
||||||
|
}
|
||||||
|
tokio::time::sleep(Duration::from_millis(15)).await;
|
||||||
|
};
|
||||||
|
let payload = vec![0x8c; 96 * 1024];
|
||||||
|
let exchange = async {
|
||||||
|
let mut stream = wire
|
||||||
|
.connect(tcp, endpoint.endpoint_id(), &profile)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
if !is_vless {
|
||||||
|
let mut first = [0; 4];
|
||||||
|
stream.read_exact(&mut first).await.unwrap();
|
||||||
|
assert_eq!(&first, b"mesh");
|
||||||
|
}
|
||||||
|
stream.write_all(&payload).await.unwrap();
|
||||||
|
let mut returned = vec![0; payload.len()];
|
||||||
|
stream.read_exact(&mut returned).await.unwrap();
|
||||||
|
assert_eq!(payload, returned);
|
||||||
|
};
|
||||||
|
let service = async {
|
||||||
|
let (mut socket, _) = backend.accept().await.unwrap();
|
||||||
|
if !is_vless {
|
||||||
|
socket.write_all(b"\0mesh").await.unwrap();
|
||||||
|
}
|
||||||
|
let mut bytes = vec![0; payload.len()];
|
||||||
|
socket.read_exact(&mut bytes).await.unwrap();
|
||||||
|
socket.write_all(&bytes).await.unwrap();
|
||||||
|
};
|
||||||
|
tokio::join!(service, exchange);
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
.expect("reference wire exchange timed out");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
[package]
|
||||||
|
name = "tsunagi-shoes"
|
||||||
|
version = "1.0.0"
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
license = "WTFPL"
|
||||||
|
repository.workspace = true
|
||||||
|
description = "Private per-attempt negotiation for Shoes mesh carriers."
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||||
|
tsunagi-core = { path = "../tsunagi-core" }
|
||||||
|
iroh.workspace = true
|
||||||
|
tokio = { workspace = true, features = ["net", "io-util"] }
|
||||||
|
rand = "0.10"
|
||||||
|
zeroize = { version = "1.9", features = ["derive"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
//! Embedded peer-only TCP profiles. Control is supplied by the running mesh agent.
|
||||||
|
mod profile;
|
||||||
|
mod stream;
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use profile::{Pair, rejected};
|
||||||
|
pub use profile::{Profile, Profiles, Ticket};
|
||||||
|
use std::{
|
||||||
|
io,
|
||||||
|
net::SocketAddr,
|
||||||
|
sync::{Arc, OnceLock},
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
pub use stream::driven;
|
||||||
|
use tokio::{
|
||||||
|
io::{AsyncRead, AsyncWrite},
|
||||||
|
net::{TcpListener, TcpStream},
|
||||||
|
sync::{Semaphore, oneshot},
|
||||||
|
task::JoinSet,
|
||||||
|
time::timeout,
|
||||||
|
};
|
||||||
|
use tsunagi::{
|
||||||
|
BoxFuture, NetworkId,
|
||||||
|
dataplane::transport::{
|
||||||
|
ControlSender, InboundLink, PacketTransport, SharedLink, TransportError, TransportPayload,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use tsunagi_tcp_tls::{
|
||||||
|
candidates::{TcpEndpoint, dial_candidates},
|
||||||
|
transport::TcpTlsLink,
|
||||||
|
};
|
||||||
|
|
||||||
|
/// A negotiated byte stream carrying length-prefixed mesh datagrams.
|
||||||
|
pub trait ByteStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||||
|
impl<T: AsyncRead + AsyncWrite + Unpin + Send> ByteStream for T {}
|
||||||
|
/// Owned stream returned by either side.
|
||||||
|
pub type Stream = Box<dyn ByteStream>;
|
||||||
|
/// A wire profile knows its own handshake and bytes, independent of reachability.
|
||||||
|
pub trait ShoesWire: Send + Sync + 'static {
|
||||||
|
/// Stable protocol identifier.
|
||||||
|
fn name(&self) -> &'static str;
|
||||||
|
/// Version compared between peers.
|
||||||
|
fn version(&self) -> u16;
|
||||||
|
/// Perform the client handshake.
|
||||||
|
fn connect<'a>(
|
||||||
|
&'a self,
|
||||||
|
tcp: TcpStream,
|
||||||
|
peer: EndpointId,
|
||||||
|
profile: &'a Profile,
|
||||||
|
) -> BoxFuture<'a, io::Result<Stream>>;
|
||||||
|
/// Authenticate and consume an authorized incoming attempt.
|
||||||
|
fn accept<'a>(
|
||||||
|
&'a self,
|
||||||
|
tcp: TcpStream,
|
||||||
|
profiles: &'a Profiles,
|
||||||
|
) -> BoxFuture<'a, io::Result<(Ticket, Stream)>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A listening TCP carrier with private one-time, per-pair credentials.
|
||||||
|
pub struct ShoesTransport {
|
||||||
|
wire: Arc<dyn ShoesWire>,
|
||||||
|
listener: TcpListener,
|
||||||
|
port: u16,
|
||||||
|
profiles: Profiles,
|
||||||
|
control: OnceLock<Arc<dyn ControlSender>>,
|
||||||
|
replies: Arc<Semaphore>,
|
||||||
|
}
|
||||||
|
impl std::fmt::Debug for ShoesTransport {
|
||||||
|
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||||
|
f.debug_struct("ShoesTransport")
|
||||||
|
.field("name", &self.name())
|
||||||
|
.field("port", &self.port)
|
||||||
|
.finish_non_exhaustive()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl ShoesTransport {
|
||||||
|
/// An explicitly requested port must bind; an occupied default can use a dynamic port.
|
||||||
|
pub async fn bind(
|
||||||
|
wire: Arc<dyn ShoesWire>,
|
||||||
|
port: Option<u16>,
|
||||||
|
default_port: u16,
|
||||||
|
) -> io::Result<Arc<Self>> {
|
||||||
|
let listener = match tsunagi_tcp_tls::candidates::listen(port.unwrap_or(default_port)) {
|
||||||
|
Ok(l) => l,
|
||||||
|
Err(e) if port.is_none() && e.kind() == io::ErrorKind::AddrInUse => {
|
||||||
|
tsunagi_tcp_tls::candidates::listen(0)?
|
||||||
|
}
|
||||||
|
Err(e) => return Err(e),
|
||||||
|
};
|
||||||
|
let port = listener.local_addr()?.port();
|
||||||
|
Ok(Arc::new(Self {
|
||||||
|
wire,
|
||||||
|
listener,
|
||||||
|
port,
|
||||||
|
profiles: Default::default(),
|
||||||
|
control: OnceLock::new(),
|
||||||
|
replies: Arc::new(Semaphore::new(64)),
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drives incoming sockets and their installation, bounded by one task set.
|
||||||
|
pub async fn listen(self: Arc<Self>, agent: tsunagi::Agent) {
|
||||||
|
let mut tasks = JoinSet::new();
|
||||||
|
let mut expire = tokio::time::interval(profile::LIFETIME);
|
||||||
|
loop {
|
||||||
|
tokio::select! {
|
||||||
|
_ = expire.tick() => self.profiles.expire(),
|
||||||
|
_ = tasks.join_next(), if !tasks.is_empty() => {},
|
||||||
|
accepted = self.listener.accept(), if tasks.len() < 64 => {
|
||||||
|
let Ok((tcp, address)) = accepted else { break; };
|
||||||
|
let owner = self.clone();
|
||||||
|
let agent = agent.clone();
|
||||||
|
tasks.spawn(async move {
|
||||||
|
let _ = tcp.set_nodelay(true);
|
||||||
|
if let Ok(Ok((ticket, stream))) = timeout(Duration::from_secs(8), owner.wire.accept(tcp, &owner.profiles)).await {
|
||||||
|
let (network, peer) = ticket.pair;
|
||||||
|
let protocol = owner.wire.name();
|
||||||
|
let link = Arc::new(TcpTlsLink::framed(protocol, network, peer, stream, address.to_string()));
|
||||||
|
let _ = agent.install_inbound_link(InboundLink { network, peer, protocol: protocol.into(), link }).await;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn authorize(&self, pair: Pair) -> Result<Profile, TransportError> {
|
||||||
|
let control = self.control.get().ok_or(TransportError::Closed)?;
|
||||||
|
let profile = Profile::fresh();
|
||||||
|
let (tx, rx) = oneshot::channel();
|
||||||
|
self.profiles
|
||||||
|
.0
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.get_mut(&pair)
|
||||||
|
.ok_or(TransportError::Closed)?
|
||||||
|
.waiting = Some((profile.tag, tx));
|
||||||
|
// Fixed lengths distinguish an offer (tag + secret + variant) from its receipt (tag).
|
||||||
|
let mut bytes = Vec::with_capacity(65);
|
||||||
|
bytes.extend_from_slice(&profile.tag);
|
||||||
|
bytes.extend_from_slice(&profile.secret);
|
||||||
|
bytes.push(u8::from(profile.variant));
|
||||||
|
control
|
||||||
|
.send(pair.0, pair.1, self.name(), TransportPayload::new(bytes))
|
||||||
|
.await?;
|
||||||
|
rx.await.map_err(|_| TransportError::Closed)?;
|
||||||
|
Ok(profile)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl TcpEndpoint for ShoesTransport {
|
||||||
|
fn wire_version(&self) -> u16 {
|
||||||
|
self.wire.version()
|
||||||
|
}
|
||||||
|
fn bound_port(&self) -> u16 {
|
||||||
|
self.port
|
||||||
|
}
|
||||||
|
fn set_pair_addresses(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
addresses: Option<Vec<SocketAddr>>,
|
||||||
|
) {
|
||||||
|
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
match addresses {
|
||||||
|
Some(addresses) => slots.entry((network, peer)).or_default().addresses = addresses,
|
||||||
|
None => {
|
||||||
|
slots.remove(&(network, peer));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fn clear_network(&self, network: NetworkId) {
|
||||||
|
self.profiles
|
||||||
|
.0
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.retain(|(n, _), _| *n != network);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl PacketTransport for ShoesTransport {
|
||||||
|
fn name(&self) -> &str {
|
||||||
|
self.wire.name()
|
||||||
|
}
|
||||||
|
fn as_any(&self) -> &dyn std::any::Any {
|
||||||
|
self
|
||||||
|
}
|
||||||
|
fn attach_control(&self, control: Arc<dyn ControlSender>) {
|
||||||
|
let _ = self.control.set(control);
|
||||||
|
}
|
||||||
|
fn on_control(
|
||||||
|
&self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
protocol: &str,
|
||||||
|
bytes: &[u8],
|
||||||
|
) -> Result<(), TransportError> {
|
||||||
|
let bad = || TransportError::Declined("invalid Shoes negotiation".into());
|
||||||
|
if protocol != self.name() {
|
||||||
|
return Err(bad());
|
||||||
|
}
|
||||||
|
let pair = (network, peer);
|
||||||
|
let tag: [u8; 32] = bytes
|
||||||
|
.get(..32)
|
||||||
|
.ok_or_else(bad)?
|
||||||
|
.try_into()
|
||||||
|
.map_err(|_| bad())?;
|
||||||
|
match bytes.len() {
|
||||||
|
32 => {
|
||||||
|
let mut slots = self.profiles.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
let slot = slots.get_mut(&pair).ok_or_else(bad)?;
|
||||||
|
let (_, ack) = slot.waiting.take_if(|(id, _)| *id == tag).ok_or_else(bad)?;
|
||||||
|
let _ = ack.send(());
|
||||||
|
}
|
||||||
|
65 if bytes[64] <= 1 => {
|
||||||
|
let secret = bytes[32..64].try_into().map_err(|_| bad())?;
|
||||||
|
let permit = self
|
||||||
|
.replies
|
||||||
|
.clone()
|
||||||
|
.try_acquire_owned()
|
||||||
|
.map_err(|_| bad())?;
|
||||||
|
let sender = self.control.get().ok_or_else(bad)?.clone();
|
||||||
|
let name = self.wire.name();
|
||||||
|
self.profiles
|
||||||
|
.offer(
|
||||||
|
pair,
|
||||||
|
Profile {
|
||||||
|
tag,
|
||||||
|
secret,
|
||||||
|
variant: bytes[64] == 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|_| bad())?;
|
||||||
|
tokio::spawn(async move {
|
||||||
|
let _permit = permit;
|
||||||
|
let _ = timeout(
|
||||||
|
Duration::from_secs(4),
|
||||||
|
sender.send(network, peer, name, TransportPayload::new(tag.to_vec())),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
_ => return Err(bad()),
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
fn open<'a>(
|
||||||
|
&'a self,
|
||||||
|
network: NetworkId,
|
||||||
|
peer: EndpointId,
|
||||||
|
protocol: &'a str,
|
||||||
|
) -> BoxFuture<'a, Result<SharedLink, TransportError>> {
|
||||||
|
Box::pin(async move {
|
||||||
|
if protocol != self.name() {
|
||||||
|
return Err(TransportError::Declined(protocol.into()));
|
||||||
|
}
|
||||||
|
let pair = (network, peer);
|
||||||
|
let addresses = self
|
||||||
|
.profiles
|
||||||
|
.0
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.get(&pair)
|
||||||
|
.map(|s| s.addresses.clone())
|
||||||
|
.ok_or_else(|| TransportError::Unreachable(rejected().to_string()))?;
|
||||||
|
dial_candidates(addresses, |tcp, addr| async move {
|
||||||
|
let profile = self.authorize(pair).await?;
|
||||||
|
let stream = self
|
||||||
|
.wire
|
||||||
|
.connect(tcp, peer, &profile)
|
||||||
|
.await
|
||||||
|
.map_err(|_| TransportError::Declined("Shoes handshake failed".into()))?;
|
||||||
|
Ok(Arc::new(TcpTlsLink::framed(
|
||||||
|
self.wire.name(),
|
||||||
|
network,
|
||||||
|
peer,
|
||||||
|
stream,
|
||||||
|
addr.to_string(),
|
||||||
|
)) as SharedLink)
|
||||||
|
})
|
||||||
|
.await
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,188 @@
|
|||||||
|
//! Single-use credentials scoped to an authenticated pair.
|
||||||
|
use iroh::EndpointId;
|
||||||
|
use std::{
|
||||||
|
collections::HashMap,
|
||||||
|
io,
|
||||||
|
net::SocketAddr,
|
||||||
|
sync::{Arc, Mutex},
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
|
use tokio::sync::oneshot;
|
||||||
|
use tsunagi::NetworkId;
|
||||||
|
use zeroize::ZeroizeOnDrop;
|
||||||
|
|
||||||
|
pub(crate) type Pair = (NetworkId, EndpointId);
|
||||||
|
pub(crate) const LIFETIME: Duration = Duration::from_secs(12);
|
||||||
|
|
||||||
|
/// An independently random public lookup value and private credential.
|
||||||
|
#[derive(ZeroizeOnDrop)]
|
||||||
|
pub struct Profile {
|
||||||
|
/// Random request salt or XHTTP path component.
|
||||||
|
pub tag: [u8; 32],
|
||||||
|
/// Secret material, sent only on the already authenticated control session.
|
||||||
|
pub secret: [u8; 32],
|
||||||
|
/// Independent random selector for a wire profile with two supported methods.
|
||||||
|
pub variant: bool,
|
||||||
|
}
|
||||||
|
impl Profile {
|
||||||
|
pub(crate) fn fresh() -> Self {
|
||||||
|
Self {
|
||||||
|
tag: rand::random(),
|
||||||
|
secret: rand::random(),
|
||||||
|
variant: rand::random(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The pair is supplied by authenticated control, never by the TCP client.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct Ticket {
|
||||||
|
pub(crate) pair: Pair,
|
||||||
|
/// Parameters of this connection attempt.
|
||||||
|
pub profile: Arc<Profile>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct Slot {
|
||||||
|
pub(crate) addresses: Vec<SocketAddr>,
|
||||||
|
incoming: Option<(Arc<Profile>, Instant)>,
|
||||||
|
// A repeated private offer cannot reauthorize a previously accepted salt.
|
||||||
|
recent: std::collections::VecDeque<([u8; 16], Instant)>,
|
||||||
|
pub(crate) waiting: Option<([u8; 32], oneshot::Sender<()>)>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bounded by enabled, authenticated memberships. At most one offer per pair.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub struct Profiles(pub(crate) Mutex<HashMap<Pair, Slot>>);
|
||||||
|
|
||||||
|
impl Profiles {
|
||||||
|
pub(crate) fn offer(&self, pair: Pair, profile: Profile) -> io::Result<()> {
|
||||||
|
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
if slots.iter().any(|(other, slot)| {
|
||||||
|
*other != pair
|
||||||
|
&& slot.incoming.as_ref().is_some_and(|(p, until)| {
|
||||||
|
*until > Instant::now() && p.tag[..16] == profile.tag[..16]
|
||||||
|
})
|
||||||
|
}) {
|
||||||
|
return Err(rejected());
|
||||||
|
}
|
||||||
|
let slot = slots.get_mut(&pair).ok_or_else(rejected)?;
|
||||||
|
let now = Instant::now();
|
||||||
|
let prefix = profile.tag[..16].try_into().map_err(|_| rejected())?;
|
||||||
|
slot.recent.retain(|(_, until)| *until > now);
|
||||||
|
if slot.recent.len() >= 64 || slot.recent.iter().any(|(tag, _)| tag == &prefix) {
|
||||||
|
return Err(rejected());
|
||||||
|
}
|
||||||
|
slot.recent
|
||||||
|
.push_back((prefix, now + Duration::from_secs(60)));
|
||||||
|
slot.incoming = Some((Arc::new(profile), now + LIFETIME));
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve a bounded, public identifier before verifying the private credential.
|
||||||
|
pub fn lookup(&self, tag: &[u8]) -> io::Result<Ticket> {
|
||||||
|
if !matches!(tag.len(), 16 | 32) {
|
||||||
|
return Err(rejected());
|
||||||
|
}
|
||||||
|
let slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
slots
|
||||||
|
.iter()
|
||||||
|
.find_map(|(pair, slot)| {
|
||||||
|
let (p, expiry) = slot.incoming.as_ref()?;
|
||||||
|
(p.tag.starts_with(tag) && *expiry > Instant::now()).then(|| Ticket {
|
||||||
|
pair: *pair,
|
||||||
|
profile: p.clone(),
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.ok_or_else(rejected)
|
||||||
|
}
|
||||||
|
/// Consume only after successful wire authentication and before acknowledging the client.
|
||||||
|
pub fn claim(&self, ticket: &Ticket) -> io::Result<()> {
|
||||||
|
let mut slots = self.0.lock().unwrap_or_else(|p| p.into_inner());
|
||||||
|
let slot = slots.get_mut(&ticket.pair).ok_or_else(rejected)?;
|
||||||
|
slot.incoming
|
||||||
|
.take_if(|(p, until)| Arc::ptr_eq(p, &ticket.profile) && *until > Instant::now())
|
||||||
|
.map(|_| ())
|
||||||
|
.ok_or_else(rejected)
|
||||||
|
}
|
||||||
|
pub(crate) fn expire(&self) {
|
||||||
|
for slot in self
|
||||||
|
.0
|
||||||
|
.lock()
|
||||||
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
|
.values_mut()
|
||||||
|
{
|
||||||
|
slot.incoming.take_if(|(_, until)| *until <= Instant::now());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub(crate) fn rejected() -> io::Error {
|
||||||
|
io::Error::new(
|
||||||
|
io::ErrorKind::PermissionDenied,
|
||||||
|
"unknown or expired connection attempt",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
#![allow(clippy::unwrap_used)]
|
||||||
|
use super::*;
|
||||||
|
#[test]
|
||||||
|
fn attempts_rotate_and_a_delayed_claim_cannot_consume_a_replacement() {
|
||||||
|
let registry = Profiles::default();
|
||||||
|
let pair = (
|
||||||
|
NetworkId::from_bytes([12; 32]),
|
||||||
|
tsunagi::identity::DeviceIdentity::generate().endpoint_id(),
|
||||||
|
);
|
||||||
|
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||||
|
let a = Profile::fresh();
|
||||||
|
let tag = a.tag;
|
||||||
|
registry.offer(pair, a).unwrap();
|
||||||
|
let old = registry.lookup(&tag).unwrap();
|
||||||
|
let b = Profile::fresh();
|
||||||
|
assert_ne!(old.profile.tag, b.tag);
|
||||||
|
assert_ne!(old.profile.secret, b.secret);
|
||||||
|
let tag = b.tag;
|
||||||
|
registry.offer(pair, b).unwrap();
|
||||||
|
assert!(registry.claim(&old).is_err());
|
||||||
|
let current = registry.lookup(&tag).unwrap();
|
||||||
|
registry.claim(¤t).unwrap();
|
||||||
|
assert!(registry.claim(¤t).is_err());
|
||||||
|
assert!(registry.lookup(&tag).is_err());
|
||||||
|
let duplicate = Profile {
|
||||||
|
tag,
|
||||||
|
secret: current.profile.secret,
|
||||||
|
variant: current.profile.variant,
|
||||||
|
};
|
||||||
|
assert!(registry.offer(pair, duplicate).is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn wrong_network_expiry_and_retirement_reject_existing_tickets() {
|
||||||
|
let registry = Profiles::default();
|
||||||
|
let peer = tsunagi::identity::DeviceIdentity::generate().endpoint_id();
|
||||||
|
let pair = (NetworkId::from_bytes([7; 32]), peer);
|
||||||
|
let other = (NetworkId::from_bytes([8; 32]), peer);
|
||||||
|
registry.0.lock().unwrap().insert(pair, Slot::default());
|
||||||
|
assert!(registry.offer(other, Profile::fresh()).is_err());
|
||||||
|
let offered = Profile::fresh();
|
||||||
|
let tag = offered.tag;
|
||||||
|
registry.offer(pair, offered).unwrap();
|
||||||
|
let ticket = registry.lookup(&tag).unwrap();
|
||||||
|
registry
|
||||||
|
.0
|
||||||
|
.lock()
|
||||||
|
.unwrap()
|
||||||
|
.get_mut(&pair)
|
||||||
|
.unwrap()
|
||||||
|
.incoming
|
||||||
|
.as_mut()
|
||||||
|
.unwrap()
|
||||||
|
.1 = Instant::now();
|
||||||
|
assert!(registry.lookup(&tag).is_err());
|
||||||
|
assert!(registry.claim(&ticket).is_err());
|
||||||
|
registry.expire();
|
||||||
|
registry.0.lock().unwrap().remove(&pair);
|
||||||
|
assert!(registry.claim(&ticket).is_err());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
//! Tie an HTTP/2 connection or record driver to its negotiated stream.
|
||||||
|
use crate::{ByteStream, Stream};
|
||||||
|
use std::{
|
||||||
|
future::Future,
|
||||||
|
io,
|
||||||
|
pin::Pin,
|
||||||
|
task::{Context, Poll},
|
||||||
|
};
|
||||||
|
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||||
|
|
||||||
|
struct Driven<S> {
|
||||||
|
inner: S,
|
||||||
|
driver: tokio::task::JoinHandle<()>,
|
||||||
|
}
|
||||||
|
impl<S> Drop for Driven<S> {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.driver.abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Closing a link cancels its driver even when the peer has stopped reading.
|
||||||
|
pub fn driven<S: ByteStream + 'static>(
|
||||||
|
inner: S,
|
||||||
|
driver: impl Future<Output = ()> + Send + 'static,
|
||||||
|
) -> Stream {
|
||||||
|
Box::new(Driven {
|
||||||
|
inner,
|
||||||
|
driver: tokio::spawn(driver),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
impl<S: ByteStream> AsyncRead for Driven<S> {
|
||||||
|
fn poll_read(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &mut ReadBuf<'_>,
|
||||||
|
) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut self.inner).poll_read(cx, buf)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<S: ByteStream> AsyncWrite for Driven<S> {
|
||||||
|
fn poll_write(
|
||||||
|
mut self: Pin<&mut Self>,
|
||||||
|
cx: &mut Context<'_>,
|
||||||
|
buf: &[u8],
|
||||||
|
) -> Poll<io::Result<usize>> {
|
||||||
|
Pin::new(&mut self.inner).poll_write(cx, buf)
|
||||||
|
}
|
||||||
|
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut self.inner).poll_flush(cx)
|
||||||
|
}
|
||||||
|
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||||
|
Pin::new(&mut self.inner).poll_shutdown(cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,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]
|
[package]
|
||||||
name = "tsunagi-tcp-tls"
|
name = "tsunagi-tcp-tls"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
description = "TCP TLS carrier for independently encrypted tsunagi mesh traffic."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -8,16 +8,18 @@ license.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||||
iroh.workspace = true
|
iroh.workspace = true
|
||||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||||
rustls = "0.23"
|
rustls = "0.23"
|
||||||
tokio-rustls = "0.26"
|
tokio-rustls = "0.26"
|
||||||
|
x509-parser = "0.18"
|
||||||
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
rcgen = { version = "0.14", default-features = false, features = ["ring"] }
|
||||||
bytes.workspace = true
|
bytes.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
postcard.workspace = true
|
postcard.workspace = true
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
socket2 = "0.6"
|
||||||
netdev = "0.46"
|
netdev = "0.46"
|
||||||
|
|
||||||
[target.'cfg(target_os = "linux")'.dependencies]
|
[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],
|
_ocsp_response: &[u8],
|
||||||
_now: UnixTime,
|
_now: UnixTime,
|
||||||
) -> Result<ServerCertVerified, RustlsError> {
|
) -> Result<ServerCertVerified, RustlsError> {
|
||||||
// Parse the certificate's SPKI / public key
|
use x509_parser::prelude::{FromDer, X509Certificate};
|
||||||
let cert_bytes = end_entity.as_ref();
|
let (rest, cert) = X509Certificate::from_der(end_entity.as_ref())
|
||||||
let expected_bytes = self.expected.as_bytes();
|
.map_err(|_| RustlsError::InvalidCertificate(rustls::CertificateError::BadEncoding))?;
|
||||||
|
let key = cert.public_key();
|
||||||
// Check if the expected 32-byte Ed25519 public key is in the certificate
|
if rest.is_empty()
|
||||||
if cert_bytes
|
&& key.algorithm.algorithm == x509_parser::oid_registry::OID_SIG_ED25519
|
||||||
.windows(32)
|
&& key.algorithm.parameters.is_none()
|
||||||
.any(|window| window == expected_bytes)
|
&& key.subject_public_key.unused_bits == 0
|
||||||
|
&& key.subject_public_key.data.as_ref() == self.expected.as_bytes()
|
||||||
{
|
{
|
||||||
Ok(ServerCertVerified::assertion())
|
Ok(ServerCertVerified::assertion())
|
||||||
} else {
|
} else {
|
||||||
@@ -126,7 +127,7 @@ pub fn make_server_config(
|
|||||||
) -> Result<Arc<ServerConfig>, rustls::Error> {
|
) -> Result<Arc<ServerConfig>, rustls::Error> {
|
||||||
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
let provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
let mut config = ServerConfig::builder_with_provider(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_no_client_auth()
|
||||||
.with_single_cert(vec![cert], key)?;
|
.with_single_cert(vec![cert], key)?;
|
||||||
config.alpn_protocols = vec![b"http/1.1".to_vec()];
|
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 provider = Arc::new(rustls::crypto::ring::default_provider());
|
||||||
let verifier = Arc::new(PinnedEndpointVerifier::new(expected_peer));
|
let verifier = Arc::new(PinnedEndpointVerifier::new(expected_peer));
|
||||||
let mut config = ClientConfig::builder_with_provider(provider)
|
let mut config = ClientConfig::builder_with_provider(provider)
|
||||||
.with_safe_default_protocol_versions()?
|
.with_protocol_versions(&[&rustls::version::TLS13])?
|
||||||
.dangerous()
|
.dangerous()
|
||||||
.with_custom_certificate_verifier(verifier)
|
.with_custom_certificate_verifier(verifier)
|
||||||
.with_no_client_auth();
|
.with_no_client_auth();
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
//! TCP TLS 1.3 carrier for opaque, independently encrypted mesh datagrams.
|
//! TCP TLS 1.3 carrier for opaque, independently encrypted mesh datagrams.
|
||||||
|
pub mod candidates;
|
||||||
pub mod cert;
|
pub mod cert;
|
||||||
pub mod plugin;
|
pub mod plugin;
|
||||||
pub mod transport;
|
pub mod transport;
|
||||||
pub use plugin::{
|
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;
|
pub use transport::TcpTlsTransport;
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
//! TLS carrier options and bounded reachability announcements. No IP cipher lives here.
|
//! 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 iroh::EndpointId;
|
||||||
use serde::Deserialize;
|
use serde::Deserialize;
|
||||||
use std::sync::Arc;
|
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 {
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
if addr.is_documentation() {
|
if addr.is_documentation() {
|
||||||
@@ -151,7 +156,7 @@ pub(crate) fn is_candidate_ip(addr: std::net::IpAddr) -> bool {
|
|||||||
match addr {
|
match addr {
|
||||||
std::net::IpAddr::V4(v4) => is_candidate_ipv4(v4),
|
std::net::IpAddr::V4(v4) => is_candidate_ipv4(v4),
|
||||||
std::net::IpAddr::V6(v6) => {
|
std::net::IpAddr::V6(v6) => {
|
||||||
if v6.is_loopback() || v6.is_unspecified() {
|
if v6.is_multicast() || v6.is_loopback() || v6.is_unspecified() {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
let segments = v6.segments();
|
let segments = v6.segments();
|
||||||
@@ -230,71 +235,65 @@ impl TcpTlsConfig {
|
|||||||
Ok(config)
|
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)]
|
#[derive(Debug)]
|
||||||
pub struct TcpTlsCarrier {
|
pub struct TcpCarrier<T> {
|
||||||
transport: Arc<TcpTlsTransport>,
|
transport: Arc<T>,
|
||||||
excluded_interface: std::sync::Mutex<Option<String>>,
|
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>>>,
|
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 {
|
impl<T: TcpEndpoint> TcpCarrier<T> {
|
||||||
/// Shares the transport's listener; creates no end-to-end cipher.
|
/// Announces the actual listener's port.
|
||||||
pub fn new(transport: Arc<TcpTlsTransport>) -> Arc<Self> {
|
pub fn new(transport: Arc<T>) -> Arc<Self> {
|
||||||
Arc::new(Self {
|
Arc::new(Self {
|
||||||
transport,
|
transport,
|
||||||
excluded_interface: std::sync::Mutex::new(None),
|
excluded_interface: Default::default(),
|
||||||
|
bootstrap: Default::default(),
|
||||||
underlay: Default::default(),
|
underlay: Default::default(),
|
||||||
peers: Default::default(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
/// Registers a carrier while excluding the agent's own, possibly custom-named interface.
|
/// Excludes the agent's own interface from physical addresses.
|
||||||
pub fn with_interface(transport: Arc<TcpTlsTransport>, interface: String) -> Arc<Self> {
|
pub fn with_interface(transport: Arc<T>, interface: String) -> Arc<Self> {
|
||||||
Arc::new(Self {
|
Arc::new(Self {
|
||||||
transport,
|
transport,
|
||||||
excluded_interface: std::sync::Mutex::new(Some(interface)),
|
excluded_interface: std::sync::Mutex::new(Some(interface)),
|
||||||
|
bootstrap: Default::default(),
|
||||||
underlay: 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.
|
/// 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>>) {
|
pub fn set_underlay(&self, source: tokio::sync::watch::Receiver<Vec<std::net::IpAddr>>) {
|
||||||
let _ = self.underlay.set(source);
|
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 {
|
fn protocol_id(&self) -> &str {
|
||||||
TCP_TLS_PROTOCOL
|
self.transport.name()
|
||||||
}
|
}
|
||||||
fn protocol_version(&self) -> u16 {
|
fn protocol_version(&self) -> u16 {
|
||||||
2
|
self.transport.wire_version()
|
||||||
|
}
|
||||||
|
fn supports_reverse_dial(&self) -> bool {
|
||||||
|
true
|
||||||
}
|
}
|
||||||
fn on_interface_ready(&self, name: &str) {
|
fn on_interface_ready(&self, name: &str) {
|
||||||
*self
|
*self
|
||||||
@@ -324,10 +323,10 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
|||||||
self.transport.bound_port(),
|
self.transport.bound_port(),
|
||||||
ips.into_iter().take(32).collect::<Vec<_>>(),
|
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 {
|
Ok(Some(tsunagi::dataplane::PluginCapability {
|
||||||
protocol: TCP_TLS_PROTOCOL.into(),
|
protocol: self.protocol_id().into(),
|
||||||
version: 2,
|
version: self.protocol_version(),
|
||||||
enabled: true,
|
enabled: true,
|
||||||
data,
|
data,
|
||||||
}))
|
}))
|
||||||
@@ -338,8 +337,20 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
|||||||
peer: EndpointId,
|
peer: EndpointId,
|
||||||
cap: &tsunagi::dataplane::PluginCapability,
|
cap: &tsunagi::dataplane::PluginCapability,
|
||||||
) -> Result<(), PluginError> {
|
) -> Result<(), PluginError> {
|
||||||
if !cap.enabled || cap.protocol != TCP_TLS_PROTOCOL || cap.version != 2 {
|
self.on_peer_capability_at(network, peer, cap, &[])
|
||||||
return Err(PluginError::Rejected("unsupported TLS carrier".into()));
|
}
|
||||||
|
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.
|
// Decode a fixed bounded array through the existing common announcement limit.
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
@@ -348,37 +359,36 @@ impl tsunagi::dataplane::transport::DataCarrier for TcpTlsCarrier {
|
|||||||
#[serde(deserialize_with = "bounded_ips")] Vec<std::net::IpAddr>,
|
#[serde(deserialize_with = "bounded_ips")] Vec<std::net::IpAddr>,
|
||||||
);
|
);
|
||||||
let Addresses(port, ips) = postcard::from_bytes(&cap.data)
|
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 {
|
if port == 0 {
|
||||||
return Err(PluginError::Rejected("invalid TLS carrier port".into()));
|
return Err(PluginError::Rejected("invalid TCP carrier port".into()));
|
||||||
}
|
}
|
||||||
self.update_peer(
|
let configured = self.bootstrap.get().and_then(|peers| peers.get(&peer));
|
||||||
network,
|
let mut addresses = Vec::new();
|
||||||
peer,
|
for ip in observed
|
||||||
Some(
|
.iter()
|
||||||
ips.into_iter()
|
.copied()
|
||||||
.filter(|ip| is_candidate_ip(*ip))
|
.chain(configured.into_iter().flatten().copied())
|
||||||
.map(|ip| std::net::SocketAddr::new(ip, port))
|
.chain(ips)
|
||||||
.collect(),
|
{
|
||||||
),
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
fn on_peer_gone(&self, network: NetworkId, peer: EndpointId) {
|
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) {
|
fn on_network_deactivated(&self, network: NetworkId) {
|
||||||
let peers: Vec<_> = self
|
self.transport.clear_network(network);
|
||||||
.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);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
fn bounded_ips<'de, D: serde::Deserializer<'de>>(
|
fn bounded_ips<'de, D: serde::Deserializer<'de>>(
|
||||||
|
|||||||
@@ -3,17 +3,16 @@
|
|||||||
//! Provides [`TcpTlsTransport`] implementing [`PacketTransport`]
|
//! Provides [`TcpTlsTransport`] implementing [`PacketTransport`]
|
||||||
//! and [`TcpTlsLink`] implementing [`PacketLink`].
|
//! and [`TcpTlsLink`] implementing [`PacketLink`].
|
||||||
|
|
||||||
use std::collections::HashMap;
|
use crate::candidates::{Candidates, TcpEndpoint, dial_candidates};
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
|
|
||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use iroh::{EndpointId, Signature};
|
use iroh::{EndpointId, Signature};
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net::{TcpListener, TcpStream};
|
use tokio::net::TcpListener;
|
||||||
use tokio::sync::{Notify, mpsc};
|
use tokio::sync::{mpsc, watch};
|
||||||
use tokio_rustls::TlsConnector;
|
use tokio_rustls::TlsConnector;
|
||||||
|
|
||||||
use tsunagi::BoxFuture;
|
use tsunagi::BoxFuture;
|
||||||
@@ -116,14 +115,27 @@ pub struct TcpTlsLink {
|
|||||||
tx: mpsc::Sender<Bytes>,
|
tx: mpsc::Sender<Bytes>,
|
||||||
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
rx: tokio::sync::Mutex<mpsc::Receiver<Bytes>>,
|
||||||
tasks: [tokio::task::AbortHandle; 2],
|
tasks: [tokio::task::AbortHandle; 2],
|
||||||
closed_notify: Arc<Notify>,
|
closed: watch::Sender<bool>,
|
||||||
is_closed: Arc<AtomicBool>,
|
|
||||||
remote_addr: String,
|
remote_addr: String,
|
||||||
|
protocol: &'static str,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TcpTlsLink {
|
impl TcpTlsLink {
|
||||||
/// Creates a new `TcpTlsLink` from a stream that has already passed the TLS handshake.
|
/// 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
|
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
|
where
|
||||||
S: tokio::io::AsyncRead + tokio::io::AsyncWrite + Send + 'static,
|
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_out, mut rx_out) = mpsc::channel::<Bytes>(256);
|
||||||
let (tx_in, rx_in) = mpsc::channel::<Bytes>(256);
|
let (tx_in, rx_in) = mpsc::channel::<Bytes>(256);
|
||||||
|
|
||||||
let is_closed = Arc::new(AtomicBool::new(false));
|
let (closed, _) = watch::channel(false);
|
||||||
let closed_notify = Arc::new(Notify::new());
|
let writer_closed = closed.clone();
|
||||||
|
|
||||||
let closed_flag_w = Arc::clone(&is_closed);
|
|
||||||
let closed_notify_w = Arc::clone(&closed_notify);
|
|
||||||
let writer_task = tokio::spawn(async move {
|
let writer_task = tokio::spawn(async move {
|
||||||
while let Some(msg) = rx_out.recv().await {
|
while let Some(msg) = rx_out.recv().await {
|
||||||
if msg.len() > MAX_FRAME_SIZE {
|
if msg.len() > MAX_FRAME_SIZE {
|
||||||
@@ -153,12 +162,10 @@ impl TcpTlsLink {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
closed_flag_w.store(true, Ordering::Release);
|
writer_closed.send_replace(true);
|
||||||
closed_notify_w.notify_waiters();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
let closed_flag_r = Arc::clone(&is_closed);
|
let reader_closed = closed.clone();
|
||||||
let closed_notify_r = Arc::clone(&closed_notify);
|
|
||||||
let reader_task = tokio::spawn(async move {
|
let reader_task = tokio::spawn(async move {
|
||||||
let mut len_buf = [0u8; 2];
|
let mut len_buf = [0u8; 2];
|
||||||
loop {
|
loop {
|
||||||
@@ -177,8 +184,7 @@ impl TcpTlsLink {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
closed_flag_r.store(true, Ordering::Release);
|
reader_closed.send_replace(true);
|
||||||
closed_notify_r.notify_waiters();
|
|
||||||
});
|
});
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
@@ -187,9 +193,9 @@ impl TcpTlsLink {
|
|||||||
tx: tx_out,
|
tx: tx_out,
|
||||||
rx: tokio::sync::Mutex::new(rx_in),
|
rx: tokio::sync::Mutex::new(rx_in),
|
||||||
tasks: [writer_task.abort_handle(), reader_task.abort_handle()],
|
tasks: [writer_task.abort_handle(), reader_task.abort_handle()],
|
||||||
closed_notify,
|
closed,
|
||||||
is_closed,
|
|
||||||
remote_addr,
|
remote_addr,
|
||||||
|
protocol,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -201,8 +207,7 @@ impl Drop for TcpTlsLink {
|
|||||||
}
|
}
|
||||||
impl PacketLink for TcpTlsLink {
|
impl PacketLink for TcpTlsLink {
|
||||||
fn close(&self) {
|
fn close(&self) {
|
||||||
self.is_closed.store(true, Ordering::Release);
|
self.closed.send_replace(true);
|
||||||
self.closed_notify.notify_waiters();
|
|
||||||
for task in &self.tasks {
|
for task in &self.tasks {
|
||||||
task.abort();
|
task.abort();
|
||||||
}
|
}
|
||||||
@@ -226,7 +231,7 @@ impl PacketLink for TcpTlsLink {
|
|||||||
limit: MAX_FRAME_SIZE,
|
limit: MAX_FRAME_SIZE,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
if self.is_closed.load(Ordering::Acquire) {
|
if *self.closed.borrow() {
|
||||||
return Err(TransportError::Closed);
|
return Err(TransportError::Closed);
|
||||||
}
|
}
|
||||||
self.tx
|
self.tx
|
||||||
@@ -243,19 +248,16 @@ impl PacketLink for TcpTlsLink {
|
|||||||
|
|
||||||
fn closed(&self) -> BoxFuture<'_, ()> {
|
fn closed(&self) -> BoxFuture<'_, ()> {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
if self.is_closed.load(Ordering::Acquire) {
|
let _ = self.closed.subscribe().wait_for(|closed| *closed).await;
|
||||||
return;
|
|
||||||
}
|
|
||||||
self.closed_notify.notified().await;
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
fn is_closed(&self) -> bool {
|
fn is_closed(&self) -> bool {
|
||||||
self.is_closed.load(Ordering::Acquire)
|
*self.closed.borrow()
|
||||||
}
|
}
|
||||||
|
|
||||||
fn path_description(&self) -> String {
|
fn path_description(&self) -> String {
|
||||||
format!("tcp-tls via {}", self.remote_addr)
|
format!("{} via {}", self.protocol, self.remote_addr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -265,7 +267,7 @@ pub struct TcpTlsTransport {
|
|||||||
local_id: EndpointId,
|
local_id: EndpointId,
|
||||||
listen_port: u16,
|
listen_port: u16,
|
||||||
sni: String,
|
sni: String,
|
||||||
peer_addresses: std::sync::RwLock<HashMap<EndpointId, Vec<SocketAddr>>>,
|
peer_addresses: Candidates,
|
||||||
server_config: Arc<rustls::ServerConfig>,
|
server_config: Arc<rustls::ServerConfig>,
|
||||||
listener: Option<Arc<TcpListener>>,
|
listener: Option<Arc<TcpListener>>,
|
||||||
}
|
}
|
||||||
@@ -348,7 +350,6 @@ impl TcpTlsTransport {
|
|||||||
let server_config = make_server_config(cert, key)?;
|
let server_config = make_server_config(cert, key)?;
|
||||||
|
|
||||||
let target_port = requested_port.unwrap_or(DEFAULT_PORT);
|
let target_port = requested_port.unwrap_or(DEFAULT_PORT);
|
||||||
let bind_addr = SocketAddr::from(([0, 0, 0, 0], target_port));
|
|
||||||
|
|
||||||
let bind_result = {
|
let bind_result = {
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
@@ -358,13 +359,11 @@ impl TcpTlsTransport {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
std::net::TcpListener::bind(bind_addr)
|
crate::candidates::listen(target_port)
|
||||||
};
|
};
|
||||||
|
|
||||||
let listener = match bind_result {
|
let listener = match bind_result {
|
||||||
Ok(std_listener) => {
|
Ok(l) => {
|
||||||
std_listener.set_nonblocking(true)?;
|
|
||||||
let l = TcpListener::from_std(std_listener)?;
|
|
||||||
tracing::info!(port = target_port, "TCP TLS listening");
|
tracing::info!(port = target_port, "TCP TLS listening");
|
||||||
Some(Arc::new(l))
|
Some(Arc::new(l))
|
||||||
}
|
}
|
||||||
@@ -391,8 +390,7 @@ impl TcpTlsTransport {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let fallback_addr = SocketAddr::from(([0, 0, 0, 0], FALLBACK_PORT));
|
match crate::candidates::listen(FALLBACK_PORT) {
|
||||||
match TcpListener::bind(fallback_addr).await {
|
|
||||||
Ok(l) => {
|
Ok(l) => {
|
||||||
tracing::info!(port = FALLBACK_PORT, "TCP TLS listening on fallback port");
|
tracing::info!(port = FALLBACK_PORT, "TCP TLS listening on fallback port");
|
||||||
Some(Arc::new(l))
|
Some(Arc::new(l))
|
||||||
@@ -404,8 +402,7 @@ impl TcpTlsTransport {
|
|||||||
"Cannot bind to fallback port {FALLBACK_PORT}: {fallback_err}. \
|
"Cannot bind to fallback port {FALLBACK_PORT}: {fallback_err}. \
|
||||||
Falling back to ephemeral port."
|
Falling back to ephemeral port."
|
||||||
);
|
);
|
||||||
let ephemeral_addr = SocketAddr::from(([0, 0, 0, 0], 0));
|
let l = crate::candidates::listen(0)?;
|
||||||
let l = TcpListener::bind(ephemeral_addr).await?;
|
|
||||||
let bound = l.local_addr()?.port();
|
let bound = l.local_addr()?.port();
|
||||||
tracing::info!(port = bound, "TCP TLS listening on ephemeral port");
|
tracing::info!(port = bound, "TCP TLS listening on ephemeral port");
|
||||||
Some(Arc::new(l))
|
Some(Arc::new(l))
|
||||||
@@ -438,7 +435,7 @@ impl TcpTlsTransport {
|
|||||||
local_id: identity.endpoint_id(),
|
local_id: identity.endpoint_id(),
|
||||||
listen_port: bound_port,
|
listen_port: bound_port,
|
||||||
sni,
|
sni,
|
||||||
peer_addresses: std::sync::RwLock::new(HashMap::new()),
|
peer_addresses: Candidates::default(),
|
||||||
server_config,
|
server_config,
|
||||||
listener,
|
listener,
|
||||||
})
|
})
|
||||||
@@ -456,7 +453,7 @@ impl TcpTlsTransport {
|
|||||||
|
|
||||||
/// Records an observed TCP target address for a peer.
|
/// Records an observed TCP target address for a peer.
|
||||||
pub fn set_peer_addr(&self, peer: EndpointId, addr: SocketAddr) {
|
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();
|
let addrs = guard.entry(peer).or_default();
|
||||||
if !addrs.contains(&addr) {
|
if !addrs.contains(&addr) {
|
||||||
addrs.push(addr);
|
addrs.push(addr);
|
||||||
@@ -466,7 +463,7 @@ impl TcpTlsTransport {
|
|||||||
|
|
||||||
/// Replaces a bounded candidate set learned through an authenticated session.
|
/// Replaces a bounded candidate set learned through an authenticated session.
|
||||||
pub fn replace_peer_addrs(&self, peer: EndpointId, addresses: Vec<SocketAddr>) {
|
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() {
|
if addresses.is_empty() {
|
||||||
peers.remove(&peer);
|
peers.remove(&peer);
|
||||||
} else {
|
} else {
|
||||||
@@ -487,11 +484,19 @@ impl TcpTlsTransport {
|
|||||||
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::clone(&self.server_config));
|
let acceptor = tokio_rustls::TlsAcceptor::from(Arc::clone(&self.server_config));
|
||||||
let local_id = self.local_id;
|
let local_id = self.local_id;
|
||||||
|
|
||||||
while let Ok((socket, remote_addr)) = listener.accept().await {
|
let mut handshakes = tokio::task::JoinSet::new();
|
||||||
|
loop {
|
||||||
|
let accepted = tokio::select! {
|
||||||
|
_ = handshakes.join_next(), if !handshakes.is_empty() => continue,
|
||||||
|
result = listener.accept(), if handshakes.len() < 64 => result,
|
||||||
|
};
|
||||||
|
let Ok((socket, remote_addr)) = accepted else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let _ = socket.set_nodelay(true);
|
||||||
let acceptor = acceptor.clone();
|
let acceptor = acceptor.clone();
|
||||||
let on_inbound = on_inbound.clone();
|
let on_inbound = on_inbound.clone();
|
||||||
|
handshakes.spawn(tokio::time::timeout(Duration::from_secs(8), async move {
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut tls_stream = match acceptor.accept(socket).await {
|
let mut tls_stream = match acceptor.accept(socket).await {
|
||||||
Ok(s) => s,
|
Ok(s) => s,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
@@ -536,7 +541,7 @@ impl TcpTlsTransport {
|
|||||||
protocol: "tcp-tls".into(),
|
protocol: "tcp-tls".into(),
|
||||||
link: Arc::new(link),
|
link: Arc::new(link),
|
||||||
});
|
});
|
||||||
});
|
}));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -561,92 +566,107 @@ impl PacketTransport for TcpTlsTransport {
|
|||||||
return Err(TransportError::Declined(protocol.to_string()));
|
return Err(TransportError::Declined(protocol.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let target_addrs = {
|
let addresses = self
|
||||||
let guard = self
|
.peer_addresses
|
||||||
.peer_addresses
|
.pairs
|
||||||
.read()
|
.lock()
|
||||||
.map_err(|_| TransportError::Other("lock poisoned".into()))?;
|
.unwrap_or_else(|p| p.into_inner())
|
||||||
guard.get(&peer).cloned().unwrap_or_default()
|
.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() {
|
let server_name = rustls::pki_types::ServerName::try_from(self.sni.as_str())
|
||||||
return Err(TransportError::Unreachable(
|
.map_err(|err| TransportError::Other(err.to_string()))?
|
||||||
"no known TCP address for peer".into(),
|
.to_owned();
|
||||||
));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut connected_socket = None;
|
let mut tls_stream = connector
|
||||||
let mut connected_addr = None;
|
.connect(server_name, socket)
|
||||||
for addr in &target_addrs {
|
.await
|
||||||
if addr.ip().is_loopback() && addr.port() == self.listen_port {
|
.map_err(|err| TransportError::Other(format!("TLS handshake failed: {err}")))?;
|
||||||
continue;
|
|
||||||
|
// 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) {
|
let link = TcpTlsLink::new(network, peer, tls_stream, addr.to_string());
|
||||||
(Some(s), Some(a)) => (s, a),
|
Ok(Arc::new(link) as SharedLink)
|
||||||
_ => {
|
})
|
||||||
return Err(TransportError::Unreachable(
|
.await
|
||||||
"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)
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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);
|
let client_config = tsunagi_tcp_tls::cert::make_client_config(peer_id);
|
||||||
assert!(client_config.is_ok());
|
assert!(client_config.is_ok());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn unrelated_certificate_fields_cannot_satisfy_the_identity_pin() {
|
||||||
|
let expected = DeviceIdentity::generate().endpoint_id();
|
||||||
|
let key = rcgen::KeyPair::generate_for(&rcgen::PKCS_ED25519).unwrap();
|
||||||
|
let mut params = rcgen::CertificateParams::new(vec!["peer.invalid".into()]).unwrap();
|
||||||
|
params
|
||||||
|
.custom_extensions
|
||||||
|
.push(rcgen::CustomExtension::from_oid_content(
|
||||||
|
&[1, 3, 6, 1, 4, 1, 55555, 1],
|
||||||
|
expected.as_bytes().to_vec(),
|
||||||
|
));
|
||||||
|
let cert = params.self_signed(&key).unwrap();
|
||||||
|
assert!(
|
||||||
|
PinnedEndpointVerifier::new(expected)
|
||||||
|
.verify_server_cert(
|
||||||
|
cert.der(),
|
||||||
|
&[],
|
||||||
|
&ServerName::try_from("peer.invalid").unwrap(),
|
||||||
|
&[],
|
||||||
|
UnixTime::now()
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-tray"
|
name = "tsunagi-tray"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Tray application to manage a running tsunagi agent."
|
description = "Tray application to manage a running tsunagi agent."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.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 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
|
# the same local control interface the CLI uses, so it reuses these directly
|
||||||
# and never re-implements the protocol.
|
# and never re-implements the protocol.
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||||
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
# Native, lightweight GUI — no web engine. eframe re-exports egui.
|
||||||
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow", "wayland", "x11"] }
|
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).
|
# Cross-platform tray icon + menu (Windows tray, macOS menu bar, Linux SNI).
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-ui"
|
name = "tsunagi-ui"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Shared egui widgets for the tray and Android clients."
|
description = "Shared egui widgets for the tray and Android clients."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
//! Shared compact network tiles, device header and join form.
|
//! Shared compact network tiles, device header and join form.
|
||||||
mod card;
|
mod card;
|
||||||
|
mod protocols;
|
||||||
use crate::{
|
use crate::{
|
||||||
client::{Client, Command},
|
client::{Client, Command},
|
||||||
devices, exit, format,
|
devices, exit, format,
|
||||||
@@ -7,6 +8,7 @@ use crate::{
|
|||||||
widgets,
|
widgets,
|
||||||
};
|
};
|
||||||
use egui_phosphor::regular as icon;
|
use egui_phosphor::regular as icon;
|
||||||
|
use protocols::draw_protocols;
|
||||||
use std::collections::BTreeSet;
|
use std::collections::BTreeSet;
|
||||||
use tsunagi::ipc::{NetworkReport, StatusReport};
|
use tsunagi::ipc::{NetworkReport, StatusReport};
|
||||||
use zeroize::{Zeroize, Zeroizing};
|
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
|
/// A prominent line about an exit node. One that carries a command copies it
|
||||||
/// when clicked.
|
/// when clicked.
|
||||||
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
fn draw_exit_warning(ui: &mut egui::Ui, warning: &exit::Warning) {
|
||||||
|
|||||||
@@ -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"]);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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());
|
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;
|
struct ReadOnly;
|
||||||
impl Client for ReadOnly {
|
impl Client for ReadOnly {
|
||||||
fn busy(&self) -> bool {
|
fn busy(&self) -> bool {
|
||||||
@@ -644,3 +696,105 @@ fn exit_users_scroll_a_row_inside_the_existing_card_and_disappear_on_deselection
|
|||||||
assert!((h - baseline).abs() < 1.);
|
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());
|
||||||
|
}
|
||||||
@@ -26,26 +26,43 @@ pub fn hint(response: Response, description: &str) -> Response {
|
|||||||
let held = ctx
|
let held = ctx
|
||||||
.data(|d| d.get_temp::<(egui::Id, f64)>(key))
|
.data(|d| d.get_temp::<(egui::Id, f64)>(key))
|
||||||
.filter(|(id, until)| touch && *id == response.id && now < *until);
|
.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()) {
|
if held.is_some() || (!touch && response.has_focus()) {
|
||||||
egui::show_tooltip_for(ctx, response.layer_id, response.id, &response.rect, |ui| {
|
egui::show_tooltip_for(
|
||||||
ui.set_max_width(
|
ctx,
|
||||||
ui.spacing()
|
response.layer_id,
|
||||||
.tooltip_width
|
response.id,
|
||||||
.min(ctx.screen_rect().width() - 16.),
|
&response.rect,
|
||||||
);
|
contents,
|
||||||
ui.label(description);
|
);
|
||||||
});
|
|
||||||
if let Some((_, until)) = held {
|
if let Some((_, until)) = held {
|
||||||
ctx.request_repaint_after_secs((until - now) as f32);
|
ctx.request_repaint_after_secs((until - now) as f32);
|
||||||
}
|
}
|
||||||
response
|
response
|
||||||
} else {
|
} else {
|
||||||
response
|
response
|
||||||
.on_hover_text(description)
|
.on_hover_ui(contents)
|
||||||
.on_disabled_hover_text(description)
|
.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.
|
/// A glyph-only button with its action exposed to assistive technology.
|
||||||
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
|
pub fn icon_button(ui: &mut Ui, glyph: &str, description: &str) -> Response {
|
||||||
let r = ui.button(glyph);
|
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
|
# 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
|
# negotiates: a release here does not stop it talking to a peer on an older
|
||||||
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
|
# build, because what peers compare is `ANNOUNCEMENT_VERSION`.
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
|
description = "The single internal WireGuard tunnel for tsunagi, independent of external carriers."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -11,7 +11,7 @@ license.workspace = true
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||||
iroh.workspace = true
|
iroh.workspace = true
|
||||||
tokio.workspace = true
|
tokio.workspace = true
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
@@ -30,6 +30,9 @@ rand = "0.10"
|
|||||||
boringtun = { version = "0.7.1", default-features = false }
|
boringtun = { version = "0.7.1", default-features = false }
|
||||||
|
|
||||||
[dev-dependencies]
|
[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-wireguard = { path = "../tsunagi-wireguard" }
|
||||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls" }
|
||||||
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
tsunagi-core = { path = "../tsunagi-core", features = ["testing"] }
|
||||||
|
|||||||
@@ -10,25 +10,39 @@ use std::{
|
|||||||
use tempfile::TempDir;
|
use tempfile::TempDir;
|
||||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||||
use tokio::net::{TcpListener, TcpStream};
|
use tokio::net::{TcpListener, TcpStream};
|
||||||
|
use tsunagi::dataplane::transport::ControlSender;
|
||||||
use tsunagi::dataplane::transport::{PacketTransport, SharedLink, TransportError};
|
use tsunagi::dataplane::transport::{PacketTransport, SharedLink, TransportError};
|
||||||
use tsunagi::discovery::SharedMemoryDiscovery;
|
use tsunagi::discovery::SharedMemoryDiscovery;
|
||||||
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
|
use tsunagi::overlay::{MemoryTun, MemoryTunFactory};
|
||||||
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
|
use tsunagi::testing::{config_with, network, wait_for_peers, wait_until};
|
||||||
use tsunagi::{Agent, BoxFuture, NetworkId};
|
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_wg_quic::{WireguardConfig, WireguardPlugin};
|
||||||
use tsunagi_wireguard::{UdpCarrier, UdpTransport};
|
use tsunagi_wireguard::{UdpCarrier, UdpTransport};
|
||||||
|
|
||||||
// Only address selection is constrained to loopback. TLS sockets, identity
|
// Only address selection is constrained to loopback. TLS sockets, identity
|
||||||
// verification, framing, membership and both encryption layers remain real.
|
// verification, framing, membership and both encryption layers remain real.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
struct LoopbackTls {
|
struct LoopbackTcp {
|
||||||
inner: Arc<TcpTlsTransport>,
|
inner: Arc<dyn TcpEndpoint>,
|
||||||
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
|
ports: Arc<std::sync::Mutex<Vec<(EndpointId, u16)>>>,
|
||||||
}
|
}
|
||||||
impl PacketTransport for LoopbackTls {
|
impl PacketTransport for LoopbackTcp {
|
||||||
fn name(&self) -> &str {
|
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 {
|
fn as_any(&self) -> &dyn std::any::Any {
|
||||||
self
|
self
|
||||||
@@ -47,8 +61,15 @@ impl PacketTransport for LoopbackTls {
|
|||||||
.find(|(id, _)| *id == peer)
|
.find(|(id, _)| *id == peer)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.1;
|
.1;
|
||||||
self.inner
|
self.inner.set_pair_addresses(
|
||||||
.replace_peer_addrs(peer, vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]);
|
network,
|
||||||
|
peer,
|
||||||
|
Some(if port == 0 {
|
||||||
|
vec![]
|
||||||
|
} else {
|
||||||
|
vec![SocketAddr::from((Ipv4Addr::LOCALHOST, port))]
|
||||||
|
}),
|
||||||
|
);
|
||||||
self.inner.open(network, peer, protocol)
|
self.inner.open(network, peer, protocol)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -95,6 +116,7 @@ impl Node {
|
|||||||
.with_tunnel(tunnel.clone());
|
.with_tunnel(tunnel.clone());
|
||||||
let mut wireguard = None;
|
let mut wireguard = None;
|
||||||
let mut tls = None;
|
let mut tls = None;
|
||||||
|
let mut shoes = Vec::new();
|
||||||
for &protocol in protocols {
|
for &protocol in protocols {
|
||||||
match protocol {
|
match protocol {
|
||||||
"wg" => {
|
"wg" => {
|
||||||
@@ -120,13 +142,35 @@ impl Node {
|
|||||||
.with_carrier(TcpTlsCarrier::new(transport.clone()))
|
.with_carrier(TcpTlsCarrier::new(transport.clone()))
|
||||||
.with_custom_transport(
|
.with_custom_transport(
|
||||||
protocol,
|
protocol,
|
||||||
Arc::new(LoopbackTls {
|
Arc::new(LoopbackTcp {
|
||||||
inner: transport.clone(),
|
inner: transport.clone(),
|
||||||
ports: ports.clone(),
|
ports: ports.clone(),
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
tls = Some(transport);
|
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" => {
|
"wg-quic" => {
|
||||||
config = config.with_carrier(Arc::new(
|
config = config.with_carrier(Arc::new(
|
||||||
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
tsunagi::dataplane::transport::iroh_link::IrohCarrier,
|
||||||
@@ -137,6 +181,9 @@ impl Node {
|
|||||||
}
|
}
|
||||||
let agent = Agent::spawn(config).await.unwrap();
|
let agent = Agent::spawn(config).await.unwrap();
|
||||||
let mut listeners = tokio::task::JoinSet::new();
|
let mut listeners = tokio::task::JoinSet::new();
|
||||||
|
for transport in shoes {
|
||||||
|
listeners.spawn(transport.listen(agent.clone()));
|
||||||
|
}
|
||||||
if let Some(transport) = wireguard.clone() {
|
if let Some(transport) = wireguard.clone() {
|
||||||
let incoming = agent.clone();
|
let incoming = agent.clone();
|
||||||
listeners.spawn(async move {
|
listeners.spawn(async move {
|
||||||
@@ -418,9 +465,8 @@ async fn missing_native_transport_cannot_silently_turn_wireguard_into_quic() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn wireguard_and_tls_carriers_both_carry_the_same_internal_cipher_and_exact_plaintext_counters()
|
async fn direct_carriers_share_the_internal_cipher_and_count_exact_plaintext() {
|
||||||
{
|
for protocol in ["wg", "tcp-tls", "vless-xhttp", "ss2022"] {
|
||||||
for protocol in ["wg", "tcp-tls"] {
|
|
||||||
let discovery = SharedMemoryDiscovery::new();
|
let discovery = SharedMemoryDiscovery::new();
|
||||||
let ports = Arc::default();
|
let ports = Arc::default();
|
||||||
let a = Node::new(&discovery, protocol, Arc::clone(&ports)).await;
|
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;
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi-wireguard"
|
name = "tsunagi-wireguard"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
|
description = "Independent authenticated WireGuard and Amnezia UDP carriers for tsunagi."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -8,7 +8,7 @@ license = "WTFPL AND Apache-2.0"
|
|||||||
repository.workspace = true
|
repository.workspace = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10" }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11" }
|
||||||
iroh.workspace = true
|
iroh.workspace = true
|
||||||
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
tokio = { workspace = true, features = ["net", "io-util", "time", "sync", "macros"] }
|
||||||
serde.workspace = true
|
serde.workspace = true
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "tsunagi"
|
name = "tsunagi"
|
||||||
version = "1.0.10"
|
version = "1.0.11"
|
||||||
description = "The tsunagi command line agent."
|
description = "The tsunagi command line agent."
|
||||||
edition.workspace = true
|
edition.workspace = true
|
||||||
rust-version.workspace = true
|
rust-version.workspace = true
|
||||||
@@ -12,11 +12,11 @@ name = "tsng"
|
|||||||
path = "src/main.rs"
|
path = "src/main.rs"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.10" }
|
tsunagi-runtime = { path = "../tsunagi-runtime", version = "1.0.11" }
|
||||||
tsunagi-core = { path = "../tsunagi-core", version = "1.0.10", features = ["tun-device", "dns-publish"] }
|
tsunagi-core = { path = "../tsunagi-core", version = "1.0.11", features = ["tun-device", "dns-publish"] }
|
||||||
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.10" }
|
tsunagi-wireguard = { path = "../tsunagi-wireguard", version = "1.0.11" }
|
||||||
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.10" }
|
tsunagi-wg-quic = { path = "../tsunagi-wg-quic", version = "1.0.11" }
|
||||||
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.10" }
|
tsunagi-tcp-tls = { path = "../tsunagi-tcp-tls", version = "1.0.11" }
|
||||||
iroh.workspace = true
|
iroh.workspace = true
|
||||||
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
tokio = { version = "1.53", features = ["rt", "rt-multi-thread", "sync", "time", "macros", "signal"] }
|
||||||
tracing.workspace = true
|
tracing.workspace = true
|
||||||
|
|||||||
+48
-16
@@ -498,7 +498,7 @@ struct UpArgs {
|
|||||||
long = "protocol",
|
long = "protocol",
|
||||||
value_name = "LIST",
|
value_name = "LIST",
|
||||||
value_delimiter = ',',
|
value_delimiter = ',',
|
||||||
default_value = "wg,awg,wg-quic,tcp-tls",
|
default_values = PROTOCOLS.iter().map(|p| p.name),
|
||||||
help_heading = "Transport"
|
help_heading = "Transport"
|
||||||
)]
|
)]
|
||||||
protocols: Vec<String>,
|
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.
|
/// 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();
|
let mut taken = Vec::new();
|
||||||
for setting in settings {
|
for setting in settings {
|
||||||
let aimed_here = match &setting.protocol {
|
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
|
// Unqualified settings go to whichever protocol declares the
|
||||||
// key. With one selected that is the obvious reading; with
|
// key. With one selected that is the obvious reading; with
|
||||||
// several, write `protocol:key=value`.
|
// 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 {
|
if aimed_here {
|
||||||
taken.push((setting.key.clone(), setting.value.clone()));
|
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();
|
let mut out = Report::new();
|
||||||
for spec in PROTOCOLS {
|
for spec in PROTOCOLS {
|
||||||
let mut section = Section::new(format!("{} (wire version {})", spec.name, spec.version));
|
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));
|
section.push(Row::new(Health::Info, "what", spec.summary));
|
||||||
if spec.options.is_empty() {
|
if spec.options.is_empty() {
|
||||||
section.push(Row::new(Health::Info, "settings", "none"));
|
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) {
|
if !PROTOCOLS.iter().any(|spec| spec.name == name) {
|
||||||
return Err(format!(
|
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) {
|
if names.iter().any(|n| n == name) {
|
||||||
@@ -4729,10 +4746,10 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
if !PROTOCOLS
|
if !PROTOCOLS
|
||||||
.iter()
|
.iter()
|
||||||
.filter(|spec| setting.protocol.is_some() || wanted.iter().any(|p| p.name == spec.name))
|
.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!(
|
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
|
setting.key
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
@@ -4772,7 +4789,7 @@ async fn up(args: UpArgs) -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
})
|
})
|
||||||
.cloned()
|
.cloned()
|
||||||
.collect();
|
.collect();
|
||||||
settings_for(spec, &scoped)
|
settings_for(spec, &scoped, &wanted)
|
||||||
})
|
})
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
@@ -4950,13 +4967,7 @@ async fn build_report(
|
|||||||
|
|
||||||
StatusReport {
|
StatusReport {
|
||||||
overlay_config_error: overlay.and_then(|state| state.address_error),
|
overlay_config_error: overlay.and_then(|state| state.address_error),
|
||||||
available_protocols: PROTOCOLS
|
available_protocols: PROTOCOLS.iter().map(|p| p.report()).collect(),
|
||||||
.iter()
|
|
||||||
.map(|p| tsunagi::ipc::ProtocolReport {
|
|
||||||
name: p.name.into(),
|
|
||||||
summary: p.summary.into(),
|
|
||||||
})
|
|
||||||
.collect(),
|
|
||||||
endpoint_id: status.endpoint_id.to_string(),
|
endpoint_id: status.endpoint_id.to_string(),
|
||||||
hostname: status.hostname.clone(),
|
hostname: status.hostname.clone(),
|
||||||
bound_sockets: status
|
bound_sockets: status
|
||||||
@@ -5988,10 +5999,31 @@ mod network_tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[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;
|
use clap::Parser;
|
||||||
for (words, expected) in [
|
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.
|
||||||
|
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.
|
histories. These are headless egui checks, not native desktop screenshots.
|
||||||
|
|
||||||
`tsunagi-wg-quic/tests/carriers.rs` uses the same internal WireGuard plugin over
|
`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
|
real ordinary WG UDP, native TCP/TLS, VLESS/XHTTP and Shadowsocks 2022 with
|
||||||
TUNs. Exact original IP byte/packet counts exclude health probes and encryption
|
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
|
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
|
transition and retain their original encrypted tunnels. The AWG suite connects
|
||||||
AWG-only and QUIC-only endpoints through a
|
AWG-only and QUIC-only endpoints through a
|
||||||
mixed relay. One real smoltcp TCP connection stays established through relay →
|
mixed relay. One real smoltcp TCP connection stays established through relay →
|
||||||
|
|||||||
+2
-1
@@ -47,7 +47,8 @@ peer by the agent and runs a WireGuard tunnel over it:
|
|||||||
```
|
```
|
||||||
|
|
||||||
Reachability belongs to external carriers: ordinary WireGuard UDP (`wg`),
|
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
|
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.
|
capability `wireguard-e2e` v4 is fixed and hidden from the CLI/tray controls.
|
||||||
All carriers move the same inner encrypted bytes, including through relays.
|
All carriers move the same inner encrypted bytes, including through relays.
|
||||||
|
|||||||
+1
-1
@@ -34,7 +34,7 @@ let
|
|||||||
in
|
in
|
||||||
rustPlatform.buildRustPackage {
|
rustPlatform.buildRustPackage {
|
||||||
pname = if withTray then "tsunagi" else "tsunagi-cli";
|
pname = if withTray then "tsunagi" else "tsunagi-cli";
|
||||||
version = "1.0.10";
|
version = "1.0.11";
|
||||||
|
|
||||||
src = lib.cleanSource ../.;
|
src = lib.cleanSource ../.;
|
||||||
cargoLock.lockFile = ../Cargo.lock;
|
cargoLock.lockFile = ../Cargo.lock;
|
||||||
|
|||||||
Reference in new issue
Block a user