Initial MeshPort SDK and cross-platform client
This commit is contained in:
+12521
File diff suppressed because it is too large
Load Diff
Vendored
+105
@@ -0,0 +1,105 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["easytier", "easytier-core", "easytier-proto"]
|
||||
default-members = ["easytier"]
|
||||
exclude = []
|
||||
|
||||
[workspace.package]
|
||||
edition = "2024"
|
||||
rust-version = "1.95"
|
||||
|
||||
[workspace.dependencies]
|
||||
# Shared versions and sources; members select features and optional dependencies.
|
||||
anyhow = "1.0"
|
||||
arc-swap = "1.9"
|
||||
async-trait = "0.1.92"
|
||||
atomic-shim = "0.2.0"
|
||||
auto_impl = "1.3.0"
|
||||
axum = "0.8"
|
||||
# Match pbjson 0.9's base64 dependency; upgrade together to avoid two codecs.
|
||||
base64 = "0.22.1"
|
||||
bon = "3.10.1"
|
||||
bytecodec = "0.5.0"
|
||||
bytes = "1.12.1"
|
||||
chrono = "0.4.45"
|
||||
cidr = "0.3.2"
|
||||
clap = "4.6.7"
|
||||
crossbeam = "0.8.5"
|
||||
crossbeam-utils = "0.8.23"
|
||||
dashmap = "6.2.1"
|
||||
easytier = { version = "2.7.0", path = "easytier", default-features = false }
|
||||
easytier-core = { version = "2.7.0", path = "easytier-core", default-features = false }
|
||||
easytier-ffi = { version = "0.1.0", path = "easytier-contrib/easytier-ffi", default-features = false }
|
||||
easytier-ohos-core = { version = "0.1.0", path = "easytier-contrib/easytier-ohrs/crates/easytier-ohos-core", default-features = false }
|
||||
easytier-ohos-features = { version = "0.1.0", path = "easytier-contrib/easytier-ohrs/crates/easytier-ohos-features", default-features = false }
|
||||
easytier-proto = { version = "2.7.0", path = "easytier-proto", default-features = false }
|
||||
futures = { version = "0.3", default-features = false }
|
||||
gethostname = "1.1"
|
||||
guarden = "0.3"
|
||||
# Keep HMAC/SHA2 on digest 0.10, shared by stun_codec 0.4 and snow 0.10.
|
||||
# Upgrade this crypto family together when those upstream constraints move.
|
||||
hmac = "0.12.1"
|
||||
http-body-util = "0.1"
|
||||
hyper = { version = "1", default-features = false }
|
||||
hyper-util = { version = "0.1", default-features = false }
|
||||
indoc = "2.0.7"
|
||||
log = "0.4"
|
||||
mimalloc = "*"
|
||||
once_cell = "1.21"
|
||||
parking_lot = "0.12.5"
|
||||
percent-encoding = "2.3.2"
|
||||
pin-project-lite = "0.2.17"
|
||||
prost = "0.14.4"
|
||||
prost-types = "0.14.4"
|
||||
quanta = "0.12"
|
||||
# rand 0.10 / x25519-dalek 3 require a coordinated RNG trait migration.
|
||||
rand = "0.8.8"
|
||||
reqwest = { version = "0.13.5", default-features = false }
|
||||
rust-i18n = "4"
|
||||
rustls = { version = "0.23.45", default-features = false }
|
||||
# tower-sessions-sqlx-store 0.15 requires SQLx 0.8; SeaORM 2 requires SQLx 0.9.
|
||||
sea-orm = "1.1.20"
|
||||
sea-orm-migration = "1.1.20"
|
||||
serde = "1.0.229"
|
||||
serde_json = "1.0"
|
||||
# See the HMAC constraint above; SHA2 must use the same digest generation.
|
||||
sha2 = "0.10.9"
|
||||
smoltcp = { version = "0.14.0", default-features = false }
|
||||
sqlx = "0.8.6"
|
||||
strum = "0.28.0"
|
||||
stun_codec = "0.4.0"
|
||||
sys-locale = "0.3"
|
||||
tauri = "2.11.5"
|
||||
tempfile = "3.27.0"
|
||||
thiserror = "2.0"
|
||||
thunk-rs = { git = "https://github.com/EasyTier/thunk.git", default-features = false }
|
||||
tokio = { version = "1.53", default-features = false }
|
||||
tokio-rustls = { version = "0.26", default-features = false }
|
||||
tokio-util = "0.7.19"
|
||||
toml = "1.1.6"
|
||||
tower-http = "0.7"
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", default-features = false }
|
||||
url = "2.5"
|
||||
uuid = "1.26.1"
|
||||
winapi = "0.3.9"
|
||||
windows = "0.62"
|
||||
x25519-dalek = "2.0.1"
|
||||
# zerocopy 0.8 requires migrating the packet layout and casting APIs.
|
||||
zerocopy = "0.7.35"
|
||||
|
||||
[profile.dev]
|
||||
panic = "unwind"
|
||||
debug = 2
|
||||
|
||||
[profile.release]
|
||||
panic = "abort"
|
||||
lto = true
|
||||
codegen-units = 1
|
||||
opt-level = 3
|
||||
strip = true
|
||||
|
||||
[profile.mini]
|
||||
inherits = "release"
|
||||
opt-level = "z"
|
||||
strip = "symbols"
|
||||
Vendored
+165
@@ -0,0 +1,165 @@
|
||||
GNU LESSER GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
|
||||
This version of the GNU Lesser General Public License incorporates
|
||||
the terms and conditions of version 3 of the GNU General Public
|
||||
License, supplemented by the additional permissions listed below.
|
||||
|
||||
0. Additional Definitions.
|
||||
|
||||
As used herein, "this License" refers to version 3 of the GNU Lesser
|
||||
General Public License, and the "GNU GPL" refers to version 3 of the GNU
|
||||
General Public License.
|
||||
|
||||
"The Library" refers to a covered work governed by this License,
|
||||
other than an Application or a Combined Work as defined below.
|
||||
|
||||
An "Application" is any work that makes use of an interface provided
|
||||
by the Library, but which is not otherwise based on the Library.
|
||||
Defining a subclass of a class defined by the Library is deemed a mode
|
||||
of using an interface provided by the Library.
|
||||
|
||||
A "Combined Work" is a work produced by combining or linking an
|
||||
Application with the Library. The particular version of the Library
|
||||
with which the Combined Work was made is also called the "Linked
|
||||
Version".
|
||||
|
||||
The "Minimal Corresponding Source" for a Combined Work means the
|
||||
Corresponding Source for the Combined Work, excluding any source code
|
||||
for portions of the Combined Work that, considered in isolation, are
|
||||
based on the Application, and not on the Linked Version.
|
||||
|
||||
The "Corresponding Application Code" for a Combined Work means the
|
||||
object code and/or source code for the Application, including any data
|
||||
and utility programs needed for reproducing the Combined Work from the
|
||||
Application, but excluding the System Libraries of the Combined Work.
|
||||
|
||||
1. Exception to Section 3 of the GNU GPL.
|
||||
|
||||
You may convey a covered work under sections 3 and 4 of this License
|
||||
without being bound by section 3 of the GNU GPL.
|
||||
|
||||
2. Conveying Modified Versions.
|
||||
|
||||
If you modify a copy of the Library, and, in your modifications, a
|
||||
facility refers to a function or data to be supplied by an Application
|
||||
that uses the facility (other than as an argument passed when the
|
||||
facility is invoked), then you may convey a copy of the modified
|
||||
version:
|
||||
|
||||
a) under this License, provided that you make a good faith effort to
|
||||
ensure that, in the event an Application does not supply the
|
||||
function or data, the facility still operates, and performs
|
||||
whatever part of its purpose remains meaningful, or
|
||||
|
||||
b) under the GNU GPL, with none of the additional permissions of
|
||||
this License applicable to that copy.
|
||||
|
||||
3. Object Code Incorporating Material from Library Header Files.
|
||||
|
||||
The object code form of an Application may incorporate material from
|
||||
a header file that is part of the Library. You may convey such object
|
||||
code under terms of your choice, provided that, if the incorporated
|
||||
material is not limited to numerical parameters, data structure
|
||||
layouts and accessors, or small macros, inline functions and templates
|
||||
(ten or fewer lines in length), you do both of the following:
|
||||
|
||||
a) Give prominent notice with each copy of the object code that the
|
||||
Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the object code with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
4. Combined Works.
|
||||
|
||||
You may convey a Combined Work under terms of your choice that,
|
||||
taken together, effectively do not restrict modification of the
|
||||
portions of the Library contained in the Combined Work and reverse
|
||||
engineering for debugging such modifications, if you also do each of
|
||||
the following:
|
||||
|
||||
a) Give prominent notice with each copy of the Combined Work that
|
||||
the Library is used in it and that the Library and its use are
|
||||
covered by this License.
|
||||
|
||||
b) Accompany the Combined Work with a copy of the GNU GPL and this license
|
||||
document.
|
||||
|
||||
c) For a Combined Work that displays copyright notices during
|
||||
execution, include the copyright notice for the Library among
|
||||
these notices, as well as a reference directing the user to the
|
||||
copies of the GNU GPL and this license document.
|
||||
|
||||
d) Do one of the following:
|
||||
|
||||
0) Convey the Minimal Corresponding Source under the terms of this
|
||||
License, and the Corresponding Application Code in a form
|
||||
suitable for, and under terms that permit, the user to
|
||||
recombine or relink the Application with a modified version of
|
||||
the Linked Version to produce a modified Combined Work, in the
|
||||
manner specified by section 6 of the GNU GPL for conveying
|
||||
Corresponding Source.
|
||||
|
||||
1) Use a suitable shared library mechanism for linking with the
|
||||
Library. A suitable mechanism is one that (a) uses at run time
|
||||
a copy of the Library already present on the user's computer
|
||||
system, and (b) will operate properly with a modified version
|
||||
of the Library that is interface-compatible with the Linked
|
||||
Version.
|
||||
|
||||
e) Provide Installation Information, but only if you would otherwise
|
||||
be required to provide such information under section 6 of the
|
||||
GNU GPL, and only to the extent that such information is
|
||||
necessary to install and execute a modified version of the
|
||||
Combined Work produced by recombining or relinking the
|
||||
Application with a modified version of the Linked Version. (If
|
||||
you use option 4d0, the Installation Information must accompany
|
||||
the Minimal Corresponding Source and Corresponding Application
|
||||
Code. If you use option 4d1, you must provide the Installation
|
||||
Information in the manner specified by section 6 of the GNU GPL
|
||||
for conveying Corresponding Source.)
|
||||
|
||||
5. Combined Libraries.
|
||||
|
||||
You may place library facilities that are a work based on the
|
||||
Library side by side in a single library together with other library
|
||||
facilities that are not Applications and are not covered by this
|
||||
License, and convey such a combined library under terms of your
|
||||
choice, if you do both of the following:
|
||||
|
||||
a) Accompany the combined library with a copy of the same work based
|
||||
on the Library, uncombined with any other library facilities,
|
||||
conveyed under the terms of this License.
|
||||
|
||||
b) Give prominent notice with the combined library that part of it
|
||||
is a work based on the Library, and explaining where to find the
|
||||
accompanying uncombined form of the same work.
|
||||
|
||||
6. Revised Versions of the GNU Lesser General Public License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions
|
||||
of the GNU Lesser General Public License from time to time. Such new
|
||||
versions will be similar in spirit to the present version, but may
|
||||
differ in detail to address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Library as you received it specifies that a certain numbered version
|
||||
of the GNU Lesser General Public License "or any later version"
|
||||
applies to it, you have the option of following the terms and
|
||||
conditions either of that published version or of any later version
|
||||
published by the Free Software Foundation. If the Library as you
|
||||
received it does not specify a version number of the GNU Lesser
|
||||
General Public License, you may choose any version of the GNU Lesser
|
||||
General Public License ever published by the Free Software Foundation.
|
||||
|
||||
If the Library as you received it specifies that a proxy can decide
|
||||
whether future versions of the GNU Lesser General Public License shall
|
||||
apply, that proxy's public statement of acceptance of any version is
|
||||
permanent authorization for you to choose that version for the
|
||||
Library.
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
# MeshPort vendored EasyTier
|
||||
|
||||
Source: https://github.com/EasyTier/EasyTier
|
||||
Upstream revision: 7af7bdc16a41d64d58743d15023a63b3eed2102c
|
||||
Imported using git archive. Retained LGPL-3.0 LICENSE and upstream crate sources.
|
||||
|
||||
This is a local source customization, not a published GitHub fork. Root workspace members were limited to easytier, easytier-core and easytier-proto for the SDK build. MeshPort root uses path dependencies and its own Cargo.lock.
|
||||
|
||||
Local modifications:
|
||||
- easytier/src/common/network.rs: macOS hardware enumeration uses blocking subprocess waits; physical connection candidates exclude route-probe addresses and nonphysical IPv6 interfaces so another VPN's TUN is not reintroduced. Hardware device names match exactly.
|
||||
- easytier-core/src/peers/meshport_optimization.rs: direct preference, improvement thresholds, hold/cooldown and candidate first-hop filter.
|
||||
- easytier-core/src/peers/mod.rs: exposes policy module.
|
||||
- easytier-core/src/peers/conn/peer_map.rs: local policy and bounded decision caches.
|
||||
- easytier-core/src/peers/conn/peer.rs: optional UDP preference, skip closed connections, resolve default selection for status/fallback.
|
||||
- easytier-core/src/peers/peer_manager.rs: policy configuration and effective next-hop inspection.
|
||||
- easytier/src/common/ifcfg/mod.rs: macOS interface commands use blocking-pool subprocess waits rather than Tokio SIGCHLD-driven waits, for embedded runtime compatibility.
|
||||
- easytier-core/src/instance/packet_plane.rs: optional host subnet filter for route projection.
|
||||
- easytier-core/src/peers/peer_manager.rs: apply the same host filter to application TCP/UDP packet destinations.
|
||||
- easytier/src/instance/virtual_nic.rs: recompute filtered route deltas on events and periodic refresh, retry failed route additions.
|
||||
- easytier/Cargo.toml and easytier/src/instance/config.rs: expose the existing core packet proxy as an independent native host capability for subnet-gateway tests, without requiring KCP/QUIC. SDK production builds do not enable it.
|
||||
- Cargo.toml: reduced workspace member list.
|
||||
|
||||
No packet/protobuf wire-format modification. Do not assume mixed-version interoperability from local tests alone. Before upstream updates, compare these files against the pinned revision and rerun MeshPort real overlay and transport fallback tests. See ../../docs/optimization.md for policy limits.
|
||||
+178
@@ -0,0 +1,178 @@
|
||||
[package]
|
||||
name = "easytier-core"
|
||||
description = "EasyTier OS-free control-plane core primitives."
|
||||
homepage = "https://github.com/EasyTier/EasyTier"
|
||||
repository = "https://github.com/EasyTier/EasyTier"
|
||||
version = "2.7.0"
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
authors = ["kkrainbow"]
|
||||
keywords = ["vpn", "p2p", "network", "easytier"]
|
||||
categories = ["network-programming"]
|
||||
license-file = "../LICENSE"
|
||||
|
||||
[lib]
|
||||
crate-type = ["rlib", "cdylib"]
|
||||
|
||||
[package.metadata.wasm-pack.profile.release]
|
||||
wasm-opt = ["-Oz", "--enable-bulk-memory", "--enable-nontrapping-float-to-int"]
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
ariadne = { version = "0.6", optional = true }
|
||||
arc-swap.workspace = true
|
||||
async-ringbuf = "0.3.9"
|
||||
async-trait.workspace = true
|
||||
auto_impl.workspace = true
|
||||
base64.workspace = true
|
||||
bitflags = "2.13"
|
||||
bytecodec.workspace = true
|
||||
bytes.workspace = true
|
||||
chrono = { workspace = true, features = ["clock"] }
|
||||
cidr = { workspace = true, features = ["serde"] }
|
||||
crossbeam-utils.workspace = true
|
||||
dashmap.workspace = true
|
||||
bon.workspace = true
|
||||
easytier-proto = { workspace = true, features = ["core"] }
|
||||
futures = { workspace = true, features = ["std", "async-await"] }
|
||||
guarden.workspace = true
|
||||
hmac.workspace = true
|
||||
http-body-util = { workspace = true, optional = true }
|
||||
hyper = { workspace = true, features = ["client", "http1"], optional = true }
|
||||
hyper-util = { workspace = true, features = ["tokio"], optional = true }
|
||||
idna = "1.1"
|
||||
atomic-shim.workspace = true
|
||||
ordered_hash_map = "0.6.1"
|
||||
parking_lot.workspace = true
|
||||
percent-encoding.workspace = true
|
||||
petgraph = "0.8.3"
|
||||
pin-project-lite.workspace = true
|
||||
prefix-trie = { version = "0.10.1", features = ["cidr"] }
|
||||
prost.workspace = true
|
||||
prost-types.workspace = true
|
||||
rand.workspace = true
|
||||
quanta.workspace = true
|
||||
ring = { version = "0.17", optional = true }
|
||||
rustls = { workspace = true, features = ["ring", "std", "tls12"], optional = true }
|
||||
serde = { workspace = true, features = ["derive"] }
|
||||
serde_json.workspace = true
|
||||
sha2.workspace = true
|
||||
smoltcp = { workspace = true, optional = true }
|
||||
# All core Noise handshakes use 25519_ChaChaPoly_SHA256. Snow's std feature
|
||||
# also enables unused ring and BLAKE2 dependencies, so use its alloc support.
|
||||
snow = { version = "0.10.0", default-features = false, features = [
|
||||
"use-chacha20poly1305",
|
||||
"use-sha2",
|
||||
"use-curve25519",
|
||||
"use-getrandom",
|
||||
] }
|
||||
stun_codec.workspace = true
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
strum = { workspace = true, features = ["derive"] }
|
||||
toml.workspace = true
|
||||
tokio = { workspace = true, features = [
|
||||
"rt",
|
||||
"time",
|
||||
"sync",
|
||||
"macros",
|
||||
"io-util",
|
||||
] }
|
||||
tokio-util = { workspace = true, features = ["io", "rt"] }
|
||||
tokio-rustls = { workspace = true, optional = true }
|
||||
url = { workspace = true, features = ["serde"] }
|
||||
wildmatch = "2.6.1"
|
||||
uuid = { workspace = true, features = ["v4", "serde"] }
|
||||
webpki-roots = { version = "1.0", optional = true }
|
||||
x25519-dalek = { workspace = true, features = ["static_secrets"] }
|
||||
zerocopy = { workspace = true, features = ["derive", "simd"] }
|
||||
zstd = { version = "0.14", optional = true }
|
||||
# Match snow 0.10's AEAD generation to share aead, cipher and crypto-common.
|
||||
# Upgrade together with snow rather than pulling in a second crypto stack.
|
||||
aes-gcm = { version = "0.10.3", optional = true }
|
||||
chacha20poly1305 = { version = "0.10.1", optional = true }
|
||||
openssl = { version = "0.10", optional = true, features = ["vendored"] }
|
||||
|
||||
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
|
||||
getrandom-02 = { package = "getrandom", version = "0.2.17", features = ["js"] }
|
||||
getrandom-03 = { package = "getrandom", version = "0.3.4", features = ["wasm_js"] }
|
||||
ring = { version = "0.17", features = ["wasm32_unknown_unknown_js"], optional = true }
|
||||
rustls-pki-types = { version = "1.15.1", features = ["web"], optional = true }
|
||||
uuid = { workspace = true, features = ["js"] }
|
||||
wasm-bindgen = "0.2"
|
||||
|
||||
[features]
|
||||
default = ["aes-gcm", "endpoint-discovery", "extended-services", "management", "tcp-hole-punch"]
|
||||
aes-gcm = ["dep:aes-gcm"]
|
||||
browser-config = ["config-write", "easytier-proto/api", "easytier-proto/json-rpc"]
|
||||
chacha20 = ["dep:chacha20poly1305"]
|
||||
openssl-crypto = ["dep:openssl"]
|
||||
ring-crypto = ["dep:ring"]
|
||||
wasi-crypto-offload = ["ring-crypto"]
|
||||
config-write = []
|
||||
endpoint-discovery = [
|
||||
"dep:http-body-util",
|
||||
"dep:hyper",
|
||||
"dep:hyper-util",
|
||||
"dep:ring",
|
||||
"dep:rustls",
|
||||
"dep:rustls-pki-types",
|
||||
"dep:tokio-rustls",
|
||||
"dep:webpki-roots",
|
||||
]
|
||||
dhcp-ipv4 = []
|
||||
public-ipv6-provider = []
|
||||
vpn-portal = []
|
||||
wrapped-transport = []
|
||||
extended-services = [
|
||||
"dhcp-ipv4",
|
||||
"public-ipv6-provider",
|
||||
"vpn-portal",
|
||||
"wrapped-transport",
|
||||
"proxy-cidr-monitor",
|
||||
]
|
||||
web-client = ["management-rpc", "config-write"]
|
||||
management = ["web-client", "extended-services", "rich-config-errors", "easytier-proto/json-rpc"]
|
||||
management-rpc = ["easytier-proto/api"]
|
||||
proxy-cidr-monitor = []
|
||||
rich-config-errors = ["dep:ariadne"]
|
||||
tcp-hole-punch = []
|
||||
proxy-packet = [
|
||||
"wrapped-transport",
|
||||
"dep:smoltcp",
|
||||
"smoltcp/std",
|
||||
"smoltcp/proto-ipv4",
|
||||
"smoltcp/proto-ipv4-fragmentation",
|
||||
"smoltcp/fragmentation-buffer-size-65536",
|
||||
"smoltcp/assembler-max-segment-count-16",
|
||||
"smoltcp/reassembly-buffer-size-65536",
|
||||
"smoltcp/reassembly-buffer-count-16",
|
||||
]
|
||||
proxy-smoltcp-stack = [
|
||||
"proxy-packet",
|
||||
"smoltcp/medium-ip",
|
||||
"smoltcp/socket-tcp",
|
||||
"smoltcp/socket-udp",
|
||||
"smoltcp/proto-ipv6",
|
||||
"smoltcp/async",
|
||||
]
|
||||
wasm-host-tunnel = []
|
||||
wasm-host-tunnel-outbound = ["wasm-host-tunnel"]
|
||||
test-utils = []
|
||||
tracing-log = ["tracing/log"]
|
||||
zstd = ["dep:zstd"]
|
||||
|
||||
[dev-dependencies]
|
||||
futures = { workspace = true, features = ["executor"] }
|
||||
|
||||
[target.'cfg(not(target_os = "wasi"))'.dev-dependencies]
|
||||
tokio = { workspace = true, features = ["rt-multi-thread", "test-util"] }
|
||||
|
||||
[package.metadata.cargo-machete]
|
||||
ignored = [
|
||||
# Enable browser entropy backends for transitive rand/snow/AEAD dependencies.
|
||||
"getrandom-02",
|
||||
"getrandom-03",
|
||||
# Enable browser time for rustls certificate validation.
|
||||
"rustls-pki-types",
|
||||
]
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
//! Portable conversion between the shared TOML model and management schema.
|
||||
|
||||
use easytier_proto::api::manage::{
|
||||
self, NetworkConfig, NetworkingMethod, PortForwardConfig as ApiPortForwardConfig,
|
||||
};
|
||||
|
||||
use super::{
|
||||
api_input::managed_credential_to_proto,
|
||||
toml::{ConfigLoader as _, TomlConfig},
|
||||
};
|
||||
|
||||
pub fn network_config_from_toml(config: &TomlConfig) -> NetworkConfig {
|
||||
let default_config = TomlConfig::default();
|
||||
let mut result = NetworkConfig {
|
||||
instance_id: Some(config.get_id().to_string()),
|
||||
dhcp: Some(config.get_dhcp()),
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
if config.get_hostname() != default_config.get_hostname() {
|
||||
result.hostname = Some(config.get_hostname());
|
||||
}
|
||||
|
||||
let network_identity = config.get_network_identity();
|
||||
result.network_name = Some(network_identity.network_name);
|
||||
result.network_secret = network_identity.network_secret;
|
||||
|
||||
if let Some(ipv4) = config.get_ipv4() {
|
||||
result.virtual_ipv4 = Some(ipv4.address().to_string());
|
||||
result.network_length = Some(ipv4.network_length() as i32);
|
||||
}
|
||||
|
||||
if config.get_ipv6_public_addr_provider() != default_config.get_ipv6_public_addr_provider() {
|
||||
result.ipv6_public_addr_provider = Some(config.get_ipv6_public_addr_provider());
|
||||
}
|
||||
if config.get_ipv6_public_addr_auto() != default_config.get_ipv6_public_addr_auto() {
|
||||
result.ipv6_public_addr_auto = Some(config.get_ipv6_public_addr_auto());
|
||||
}
|
||||
result.ipv6_public_addr_prefix = config
|
||||
.get_ipv6_public_addr_prefix()
|
||||
.map(|prefix| prefix.to_string());
|
||||
|
||||
let peers = config.get_peers();
|
||||
result.networking_method = Some(NetworkingMethod::Manual as i32);
|
||||
if !peers.is_empty() {
|
||||
result.peer_urls = peers.iter().map(|peer| peer.uri.to_string()).collect();
|
||||
result.peers = peers
|
||||
.iter()
|
||||
.map(|peer| manage::NetworkPeerConfig {
|
||||
uri: peer.uri.to_string(),
|
||||
peer_public_key: peer.peer_public_key.clone(),
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
result.listener_urls = config
|
||||
.get_listeners()
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect();
|
||||
result.proxy_cidrs = config
|
||||
.get_proxy_cidrs()
|
||||
.iter()
|
||||
.map(|proxy| match proxy.mapped_cidr {
|
||||
Some(mapped) => format!("{}->{}", proxy.cidr, mapped),
|
||||
None => proxy.cidr.to_string(),
|
||||
})
|
||||
.collect();
|
||||
|
||||
let port_forwards = config.get_port_forwards();
|
||||
if !port_forwards.is_empty() {
|
||||
result.port_forwards = port_forwards
|
||||
.iter()
|
||||
.map(|forward| ApiPortForwardConfig {
|
||||
proto: forward.proto.clone(),
|
||||
bind_ip: forward.bind_addr.ip().to_string(),
|
||||
bind_port: forward.bind_addr.port() as u32,
|
||||
dst_ip: forward.dst_addr.ip().to_string(),
|
||||
dst_port: forward.dst_addr.port() as u32,
|
||||
})
|
||||
.collect();
|
||||
}
|
||||
|
||||
if let Some(vpn_config) = config.get_vpn_portal_config() {
|
||||
result.vpn_portal_config = Some(manage::VpnPortalConfig {
|
||||
enabled: vpn_config.enabled,
|
||||
wireguard_listen: vpn_config.wireguard_listen.to_string(),
|
||||
wireguard_private_key: vpn_config.wireguard_private_key,
|
||||
clients: vpn_config
|
||||
.clients
|
||||
.into_iter()
|
||||
.map(|client| manage::VpnPortalClientConfig {
|
||||
name: client.name,
|
||||
virtual_ip: client.virtual_ip.to_string(),
|
||||
groups: client.groups,
|
||||
})
|
||||
.collect(),
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(routes) = config.get_routes()
|
||||
&& !routes.is_empty()
|
||||
{
|
||||
result.enable_manual_routes = Some(true);
|
||||
result.routes = routes.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
let exit_nodes = config.get_exit_nodes();
|
||||
if !exit_nodes.is_empty() {
|
||||
result.exit_nodes = exit_nodes.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
if let Some(socks5_portal) = config.get_socks5_portal() {
|
||||
result.enable_socks5 = Some(true);
|
||||
result.socks5_port = socks5_portal.port().map(|port| port as i32);
|
||||
}
|
||||
let mapped_listeners = config.get_mapped_listeners();
|
||||
if !mapped_listeners.is_empty() {
|
||||
result.mapped_listeners = mapped_listeners.iter().map(ToString::to_string).collect();
|
||||
}
|
||||
|
||||
result.secure_mode = config.get_secure_mode();
|
||||
result.credential_file = config
|
||||
.get_credential_file()
|
||||
.map(|path| path.to_string_lossy().into_owned());
|
||||
result.managed_credentials = config
|
||||
.get_managed_credentials()
|
||||
.into_iter()
|
||||
.map(managed_credential_to_proto)
|
||||
.collect();
|
||||
|
||||
let flags = config.get_flags();
|
||||
let default_flags = default_config.get_flags();
|
||||
result.latency_first = Some(flags.latency_first);
|
||||
result.dev_name = Some(flags.dev_name.clone());
|
||||
result.use_smoltcp = Some(flags.use_smoltcp);
|
||||
result.disable_ipv6 = Some(!flags.enable_ipv6);
|
||||
result.enable_kcp_proxy = Some(flags.enable_kcp_proxy);
|
||||
result.disable_kcp_input = Some(flags.disable_kcp_input);
|
||||
result.enable_quic_proxy = Some(flags.enable_quic_proxy);
|
||||
result.disable_quic_input = Some(flags.disable_quic_input);
|
||||
result.disable_p2p = Some(flags.disable_p2p);
|
||||
result.p2p_only = Some(flags.p2p_only);
|
||||
result.lazy_p2p = Some(flags.lazy_p2p);
|
||||
result.bind_device = Some(flags.bind_device);
|
||||
result.socket_mark = flags.socket_mark;
|
||||
result.no_tun = Some(flags.no_tun);
|
||||
result.enable_exit_node = Some(flags.enable_exit_node);
|
||||
result.relay_all_peer_rpc = Some(flags.relay_all_peer_rpc);
|
||||
result.need_p2p = Some(flags.need_p2p);
|
||||
result.multi_thread = Some(flags.multi_thread);
|
||||
result.proxy_forward_by_system = Some(flags.proxy_forward_by_system);
|
||||
result.disable_encryption = Some(!flags.enable_encryption);
|
||||
result.disable_tcp_hole_punching = Some(flags.disable_tcp_hole_punching);
|
||||
result.disable_udp_hole_punching = Some(flags.disable_udp_hole_punching);
|
||||
result.disable_upnp = Some(flags.disable_upnp);
|
||||
result.disable_relay_data = Some(flags.disable_relay_data);
|
||||
result.prefer_peer_relay = Some(flags.prefer_peer_relay);
|
||||
result.enable_udp_broadcast_relay = Some(flags.enable_udp_broadcast_relay);
|
||||
result.disable_sym_hole_punching = Some(flags.disable_sym_hole_punching);
|
||||
result.enable_magic_dns = Some(flags.accept_dns);
|
||||
result.mtu = Some(flags.mtu as i32);
|
||||
result.data_compress_algo = (flags.data_compress_algo != default_flags.data_compress_algo)
|
||||
.then_some(flags.data_compress_algo);
|
||||
result.encryption_algorithm = (flags.encryption_algorithm
|
||||
!= default_flags.encryption_algorithm)
|
||||
.then_some(flags.encryption_algorithm);
|
||||
result.instance_recv_bps_limit =
|
||||
(flags.instance_recv_bps_limit != u64::MAX).then_some(flags.instance_recv_bps_limit);
|
||||
result.enable_private_mode = Some(flags.private_mode);
|
||||
result.acl = config.get_acl();
|
||||
|
||||
if flags.relay_network_whitelist == "*" {
|
||||
result.enable_relay_network_whitelist = Some(false);
|
||||
} else {
|
||||
result.enable_relay_network_whitelist = Some(true);
|
||||
result.relay_network_whitelist = flags
|
||||
.relay_network_whitelist
|
||||
.split_whitespace()
|
||||
.map(ToOwned::to_owned)
|
||||
.collect();
|
||||
}
|
||||
|
||||
result
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::config::toml::ManagedCredentialConfig;
|
||||
|
||||
#[test]
|
||||
fn includes_managed_credentials() {
|
||||
let config = TomlConfig::default();
|
||||
config.set_managed_credentials(vec![ManagedCredentialConfig {
|
||||
credential_id: "managed-a".to_owned(),
|
||||
credential_secret: "credential-secret".to_owned(),
|
||||
groups: vec!["ops".to_owned()],
|
||||
allow_relay: true,
|
||||
allowed_proxy_cidrs: vec!["10.0.0.0/24".to_owned()],
|
||||
expiry_unix: 2_000_000_000,
|
||||
reusable: false,
|
||||
}]);
|
||||
|
||||
let projected = network_config_from_toml(&config);
|
||||
|
||||
assert_eq!(
|
||||
projected.managed_credentials,
|
||||
vec![manage::ManagedCredentialConfig {
|
||||
credential_id: "managed-a".to_owned(),
|
||||
credential_secret: "credential-secret".to_owned(),
|
||||
groups: vec!["ops".to_owned()],
|
||||
allow_relay: true,
|
||||
allowed_proxy_cidrs: vec!["10.0.0.0/24".to_owned()],
|
||||
expiry_unix: 2_000_000_000,
|
||||
reusable: Some(false),
|
||||
}]
|
||||
);
|
||||
}
|
||||
}
|
||||
+1016
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,33 @@
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
use super::{
|
||||
api_input::{NetworkConfig, NetworkConfigExt, merge_network_config_toml},
|
||||
toml::{ConfigLoader, TomlConfig},
|
||||
};
|
||||
|
||||
fn js_error(error: impl std::fmt::Debug) -> JsValue {
|
||||
JsValue::from_str(&format!("{error:?}"))
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn generate_config(config_json: &str) -> Result<String, JsValue> {
|
||||
let config: NetworkConfig = serde_json::from_str(config_json).map_err(js_error)?;
|
||||
config
|
||||
.gen_config()
|
||||
.map(|config| config.dump())
|
||||
.map_err(js_error)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn merge_config(original_toml: &str, config_json: &str) -> Result<String, JsValue> {
|
||||
let config: NetworkConfig = serde_json::from_str(config_json).map_err(js_error)?;
|
||||
merge_network_config_toml(original_toml, &config).map_err(js_error)
|
||||
}
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn parse_config(toml_config: &str) -> Result<String, JsValue> {
|
||||
let config = TomlConfig::new_from_str(toml_config)
|
||||
.and_then(|config| NetworkConfig::new_from_config(&config))
|
||||
.map_err(js_error)?;
|
||||
serde_json::to_string(&config).map_err(js_error)
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use std::{fmt, str::FromStr};
|
||||
|
||||
use strum::VariantArray;
|
||||
|
||||
/// Stable configuration vocabulary for every known encryption algorithm.
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, VariantArray)]
|
||||
pub enum EncryptionAlgorithm {
|
||||
Xor,
|
||||
#[default]
|
||||
AesGcm,
|
||||
Aes256Gcm,
|
||||
ChaCha20,
|
||||
}
|
||||
|
||||
impl EncryptionAlgorithm {
|
||||
pub const fn as_str(self) -> &'static str {
|
||||
match self {
|
||||
Self::Xor => "xor",
|
||||
Self::AesGcm => "aes-gcm",
|
||||
Self::Aes256Gcm => "aes-256-gcm",
|
||||
Self::ChaCha20 => "chacha20",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for EncryptionAlgorithm {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter.write_str(self.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for EncryptionAlgorithm {
|
||||
type Err = ();
|
||||
|
||||
fn from_str(value: &str) -> Result<Self, Self::Err> {
|
||||
match value.to_ascii_lowercase().as_str() {
|
||||
"xor" => Ok(Self::Xor),
|
||||
"aes-gcm" | "openssl-aes-gcm" => Ok(Self::AesGcm),
|
||||
"aes-256-gcm" | "openssl-aes-256-gcm" => Ok(Self::Aes256Gcm),
|
||||
"chacha20" | "chacha20-poly1305" | "openssl-chacha20" => Ok(Self::ChaCha20),
|
||||
_ => Err(()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn known_algorithm_names_are_stable() {
|
||||
let cases = [
|
||||
("xor", EncryptionAlgorithm::Xor),
|
||||
("aes-gcm", EncryptionAlgorithm::AesGcm),
|
||||
("aes-256-gcm", EncryptionAlgorithm::Aes256Gcm),
|
||||
("chacha20", EncryptionAlgorithm::ChaCha20),
|
||||
("chacha20-poly1305", EncryptionAlgorithm::ChaCha20),
|
||||
("openssl-aes-gcm", EncryptionAlgorithm::AesGcm),
|
||||
("openssl-aes-256-gcm", EncryptionAlgorithm::Aes256Gcm),
|
||||
("openssl-chacha20", EncryptionAlgorithm::ChaCha20),
|
||||
];
|
||||
|
||||
for (name, expected) in cases {
|
||||
assert_eq!(name.parse(), Ok(expected));
|
||||
}
|
||||
assert_eq!(EncryptionAlgorithm::ChaCha20.to_string(), "chacha20");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn aes_is_the_stable_default() {
|
||||
assert_eq!(EncryptionAlgorithm::default(), EncryptionAlgorithm::AesGcm);
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use easytier_proto::common::{PortForwardConfigPb, SocketType};
|
||||
|
||||
/// Runtime configuration for the core-owned SOCKS and port-forward gateway.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct GatewayRuntimeConfig {
|
||||
pub socks5_bind: Option<SocketAddr>,
|
||||
pub port_forwards: Vec<PortForwardConfig>,
|
||||
}
|
||||
|
||||
/// One TCP or UDP port-forward rule.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct PortForwardConfig {
|
||||
pub bind_addr: SocketAddr,
|
||||
pub dst_addr: SocketAddr,
|
||||
pub proto: String,
|
||||
}
|
||||
|
||||
impl From<PortForwardConfigPb> for PortForwardConfig {
|
||||
fn from(config: PortForwardConfigPb) -> Self {
|
||||
Self {
|
||||
bind_addr: config.bind_addr.unwrap_or_default().into(),
|
||||
dst_addr: config.dst_addr.unwrap_or_default().into(),
|
||||
proto: match SocketType::try_from(config.socket_type) {
|
||||
Ok(SocketType::Tcp) => "tcp".to_string(),
|
||||
Ok(SocketType::Udp) => "udp".to_string(),
|
||||
_ => "tcp".to_string(),
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PortForwardConfig> for PortForwardConfigPb {
|
||||
fn from(config: PortForwardConfig) -> Self {
|
||||
Self {
|
||||
bind_addr: Some(config.bind_addr.into()),
|
||||
dst_addr: Some(config.dst_addr.into()),
|
||||
socket_type: match config.proto.to_lowercase().as_str() {
|
||||
"tcp" => SocketType::Tcp as i32,
|
||||
"udp" => SocketType::Udp as i32,
|
||||
_ => SocketType::Tcp as i32,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProxyRuntimeConfig {
|
||||
pub enable_exit_node: bool,
|
||||
pub no_tun: bool,
|
||||
pub forward_by_system: bool,
|
||||
pub force_smoltcp: bool,
|
||||
pub icmp_failure_is_fatal: bool,
|
||||
pub udp_response_ipv4_mtu: usize,
|
||||
}
|
||||
|
||||
impl ProxyRuntimeConfig {
|
||||
pub fn should_start(self, has_proxy_networks: bool) -> bool {
|
||||
if !has_proxy_networks && !self.enable_exit_node && !self.no_tun {
|
||||
return false;
|
||||
}
|
||||
|
||||
!self.forward_by_system || self.no_tun
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ProxyRuntimeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
enable_exit_node: false,
|
||||
no_tun: false,
|
||||
forward_by_system: false,
|
||||
force_smoltcp: false,
|
||||
icmp_failure_is_fatal: false,
|
||||
udp_response_ipv4_mtu: 1280,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ProxyRuntimeConfig;
|
||||
|
||||
#[test]
|
||||
fn proxy_startup_policy_preserves_runtime_modes() {
|
||||
assert!(!ProxyRuntimeConfig::default().should_start(false));
|
||||
assert!(ProxyRuntimeConfig::default().should_start(true));
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
enable_exit_node: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_startup_policy_preserves_system_forwarding_rules() {
|
||||
assert!(
|
||||
!ProxyRuntimeConfig {
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(true)
|
||||
);
|
||||
assert!(
|
||||
!ProxyRuntimeConfig {
|
||||
enable_exit_node: true,
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
assert!(
|
||||
ProxyRuntimeConfig {
|
||||
no_tun: true,
|
||||
forward_by_system: true,
|
||||
..Default::default()
|
||||
}
|
||||
.should_start(false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn proxy_runtime_defaults_preserve_udp_mtu() {
|
||||
assert_eq!(ProxyRuntimeConfig::default().udp_response_ipv4_mtu, 1280);
|
||||
}
|
||||
}
|
||||
+827
@@ -0,0 +1,827 @@
|
||||
//! Static configuration schema plus the live runtime configuration store.
|
||||
|
||||
#[cfg(feature = "web-client")]
|
||||
pub mod api;
|
||||
#[cfg(any(feature = "web-client", feature = "browser-config"))]
|
||||
pub mod api_input;
|
||||
#[cfg(all(
|
||||
feature = "browser-config",
|
||||
target_arch = "wasm32",
|
||||
target_os = "unknown"
|
||||
))]
|
||||
mod browser;
|
||||
mod encryption;
|
||||
pub mod gateway;
|
||||
pub mod peers;
|
||||
pub mod runtime;
|
||||
pub mod toml;
|
||||
|
||||
pub use encryption::EncryptionAlgorithm;
|
||||
|
||||
pub(crate) const DEFAULT_UDP_STUN_SERVERS: &[&str] = &[
|
||||
"txt:stun.easytier.cn",
|
||||
"stun.miwifi.com",
|
||||
"stun.chat.bilibili.com",
|
||||
"stun.hitv.com",
|
||||
];
|
||||
pub(crate) const DEFAULT_TCP_STUN_SERVERS: &[&str] = &[
|
||||
"stun.hot-chilli.net",
|
||||
"stun.fitauto.ru",
|
||||
"fwa.lifesizecloud.com",
|
||||
"global.turn.twilio.com",
|
||||
"turn.cloudflare.com",
|
||||
"stun.voip.blackberry.com",
|
||||
"stun.radiojar.com",
|
||||
];
|
||||
pub(crate) const DEFAULT_UDP_V6_STUN_SERVERS: &[&str] = &["txt:stun-v6.easytier.cn"];
|
||||
|
||||
pub(crate) fn default_stun_servers(servers: &[&str]) -> Vec<String> {
|
||||
servers.iter().map(ToString::to_string).collect()
|
||||
}
|
||||
|
||||
use std::{
|
||||
collections::{BTreeSet, hash_map::DefaultHasher},
|
||||
hash::{Hash, Hasher},
|
||||
net::IpAddr,
|
||||
};
|
||||
|
||||
use anyhow::Context as _;
|
||||
use base64::{Engine as _, prelude::BASE64_STANDARD};
|
||||
use easytier_proto::{common as common_pb, core_config as pb};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
pub type PeerId = u32;
|
||||
|
||||
pub type NetworkSecretDigest = [u8; 32];
|
||||
|
||||
/// Host capabilities used by the portable mapped-listener validation rule.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct MappedListenerPolicy {
|
||||
implicit_port_schemes: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl MappedListenerPolicy {
|
||||
pub fn new<I, S>(implicit_port_schemes: I) -> Self
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: Into<String>,
|
||||
{
|
||||
Self {
|
||||
implicit_port_schemes: implicit_port_schemes
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.map(|scheme: String| scheme.to_ascii_lowercase())
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate(&self, url: &Url) -> anyhow::Result<()> {
|
||||
if url.port().is_none() && !self.implicit_port_schemes.contains(url.scheme()) {
|
||||
anyhow::bail!("mapped listener port is missing: {}", url);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn parse_urls(&self, mapped_listeners: &[String]) -> anyhow::Result<Vec<Url>> {
|
||||
mapped_listeners
|
||||
.iter()
|
||||
.map(|value| {
|
||||
let url: Url = value
|
||||
.parse()
|
||||
.with_context(|| format!("mapped listener is not a valid url: {}", value))?;
|
||||
self.validate(&url)?;
|
||||
Ok(url)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// Completes and validates the portable secure-mode key configuration.
|
||||
pub fn normalize_secure_mode_config(
|
||||
mut config: common_pb::SecureModeConfig,
|
||||
) -> anyhow::Result<common_pb::SecureModeConfig> {
|
||||
if !config.enabled {
|
||||
return Ok(config);
|
||||
}
|
||||
|
||||
let private_key = if config.local_private_key.is_none() {
|
||||
let private = x25519_dalek::StaticSecret::random_from_rng(rand::rngs::OsRng);
|
||||
config.local_private_key = Some(BASE64_STANDARD.encode(private.as_bytes()));
|
||||
private
|
||||
} else {
|
||||
config.private_key()?
|
||||
};
|
||||
let generated_public_key = x25519_dalek::PublicKey::from(&private_key);
|
||||
let generated_public_key = BASE64_STANDARD.encode(generated_public_key.as_bytes());
|
||||
|
||||
match config.local_public_key.as_ref() {
|
||||
None => config.local_public_key = Some(generated_public_key),
|
||||
Some(configured_public_key) => {
|
||||
config.public_key()?;
|
||||
if configured_public_key != &generated_public_key {
|
||||
anyhow::bail!(
|
||||
"local public key {} does not match generated public key {}",
|
||||
configured_public_key,
|
||||
generated_public_key
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct NetworkIdentity {
|
||||
pub network_name: String,
|
||||
pub network_secret: Option<String>,
|
||||
pub network_secret_digest: Option<NetworkSecretDigest>,
|
||||
}
|
||||
|
||||
impl NetworkIdentity {
|
||||
pub fn new(network_name: String, network_secret: String) -> Self {
|
||||
Self {
|
||||
network_secret_digest: Some(network_secret_digest(&network_name, &network_secret)),
|
||||
network_name,
|
||||
network_secret: Some(network_secret),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_credential(network_name: String) -> Self {
|
||||
Self {
|
||||
network_name,
|
||||
network_secret: None,
|
||||
network_secret_digest: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn secret_digest(&self) -> Option<NetworkSecretDigest> {
|
||||
if self.network_secret_digest.is_some() {
|
||||
self.network_secret_digest
|
||||
} else if let Some(network_secret) = &self.network_secret {
|
||||
let mut network_secret_digest = [0u8; 32];
|
||||
generate_digest_from_str(
|
||||
&self.network_name,
|
||||
network_secret,
|
||||
&mut network_secret_digest,
|
||||
);
|
||||
Some(network_secret_digest)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_secret_digest(mut self) -> Self {
|
||||
self.network_secret_digest = self.secret_digest();
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Eq, PartialEq, Hash)]
|
||||
struct NetworkIdentityWithOnlyDigest {
|
||||
network_name: String,
|
||||
network_secret_digest: Option<NetworkSecretDigest>,
|
||||
}
|
||||
|
||||
fn generate_digest_from_str(str1: &str, str2: &str, digest: &mut [u8]) {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
hasher.write(str1.as_bytes());
|
||||
hasher.write(str2.as_bytes());
|
||||
|
||||
assert_eq!(digest.len() % 8, 0, "digest length must be multiple of 8");
|
||||
|
||||
let shard_count = digest.len() / 8;
|
||||
for i in 0..shard_count {
|
||||
digest[i * 8..(i + 1) * 8].copy_from_slice(&hasher.finish().to_be_bytes());
|
||||
hasher.write(&digest[..(i + 1) * 8]);
|
||||
}
|
||||
}
|
||||
|
||||
fn network_secret_digest(network_name: &str, network_secret: &str) -> NetworkSecretDigest {
|
||||
let mut digest = [0u8; 32];
|
||||
generate_digest_from_str(network_name, network_secret, &mut digest);
|
||||
digest
|
||||
}
|
||||
|
||||
impl From<NetworkIdentity> for NetworkIdentityWithOnlyDigest {
|
||||
fn from(identity: NetworkIdentity) -> Self {
|
||||
Self {
|
||||
network_secret_digest: identity.secret_digest(),
|
||||
network_name: identity.network_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for NetworkIdentity {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let self_with_digest = NetworkIdentityWithOnlyDigest::from(self.clone());
|
||||
let other_with_digest = NetworkIdentityWithOnlyDigest::from(other.clone());
|
||||
self_with_digest == other_with_digest
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for NetworkIdentity {}
|
||||
|
||||
impl Hash for NetworkIdentity {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
let self_with_digest = NetworkIdentityWithOnlyDigest::from(self.clone());
|
||||
self_with_digest.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for NetworkIdentity {
|
||||
fn default() -> Self {
|
||||
Self::new("default".to_string(), "".to_string())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct CoreConfig {
|
||||
pub node: NodeConfig,
|
||||
pub routes: RouteConfig,
|
||||
pub peer_policy: PeerPolicyConfig,
|
||||
pub traffic: TrafficConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct NodeConfig {
|
||||
pub peer_id: Option<PeerId>,
|
||||
pub instance_id: Option<[u8; 16]>,
|
||||
pub hostname: Option<String>,
|
||||
pub network_name: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct RouteConfig {
|
||||
pub ipv4: Option<IpPrefix>,
|
||||
pub ipv6: Option<IpPrefix>,
|
||||
pub advertised_routes: Vec<IpPrefix>,
|
||||
pub proxy_networks: Vec<ProxyNetworkConfig>,
|
||||
pub foreign_networks: Vec<ForeignNetworkConfig>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct IpPrefix {
|
||||
pub address: IpAddr,
|
||||
pub prefix_len: u8,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ProxyNetworkConfig {
|
||||
pub real: IpPrefix,
|
||||
pub mapped: Option<IpPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct ForeignNetworkConfig {
|
||||
pub name: String,
|
||||
pub cidrs: Vec<IpPrefix>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerPolicyConfig {
|
||||
pub p2p_enabled: bool,
|
||||
pub relay_peer_rpc: bool,
|
||||
pub relay_data: bool,
|
||||
pub latency_first: bool,
|
||||
pub encryption_required: bool,
|
||||
}
|
||||
|
||||
impl Default for PeerPolicyConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
p2p_enabled: true,
|
||||
relay_peer_rpc: false,
|
||||
relay_data: true,
|
||||
latency_first: false,
|
||||
encryption_required: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct P2pPolicyFlags {
|
||||
pub disable_udp_hole_punching: bool,
|
||||
pub disable_sym_hole_punching: bool,
|
||||
pub disable_upnp: bool,
|
||||
pub lazy_p2p: bool,
|
||||
pub disable_p2p: bool,
|
||||
pub need_p2p: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
|
||||
pub struct TrafficConfig {
|
||||
pub mtu: Option<u16>,
|
||||
pub instance_recv_bps_limit: Option<u64>,
|
||||
pub foreign_relay_bps_limit: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum ConfigError {
|
||||
#[error("missing required field: {0}")]
|
||||
MissingField(&'static str),
|
||||
#[error("invalid IPv4 prefix length: {0}")]
|
||||
InvalidIpv4Prefix(u8),
|
||||
#[error("invalid IPv6 prefix length: {0}")]
|
||||
InvalidIpv6Prefix(u8),
|
||||
#[error("invalid MTU: {0}")]
|
||||
InvalidMtu(u32),
|
||||
}
|
||||
|
||||
impl IpPrefix {
|
||||
pub fn new(address: IpAddr, prefix_len: u8) -> Result<Self, ConfigError> {
|
||||
match address {
|
||||
IpAddr::V4(_) if prefix_len <= 32 => Ok(Self {
|
||||
address,
|
||||
prefix_len,
|
||||
}),
|
||||
IpAddr::V4(_) => Err(ConfigError::InvalidIpv4Prefix(prefix_len)),
|
||||
IpAddr::V6(_) if prefix_len <= 128 => Ok(Self {
|
||||
address,
|
||||
prefix_len,
|
||||
}),
|
||||
IpAddr::V6(_) => Err(ConfigError::InvalidIpv6Prefix(prefix_len)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::CoreConfig> for CoreConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::CoreConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
node: value
|
||||
.node
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
routes: value
|
||||
.routes
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
peer_policy: value.peer_policy.map(Into::into).unwrap_or_default(),
|
||||
traffic: value
|
||||
.traffic
|
||||
.map(TryInto::try_into)
|
||||
.transpose()?
|
||||
.unwrap_or_default(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<CoreConfig> for pb::CoreConfig {
|
||||
fn from(value: CoreConfig) -> Self {
|
||||
Self {
|
||||
node: Some(value.node.into()),
|
||||
routes: Some(value.routes.into()),
|
||||
peer_policy: Some(value.peer_policy.into()),
|
||||
traffic: Some(value.traffic.into()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::NodeConfig> for NodeConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::NodeConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
peer_id: value.peer_id,
|
||||
instance_id: value.instance_id.map(uuid_to_bytes),
|
||||
hostname: value.hostname,
|
||||
network_name: value.network_name,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<NodeConfig> for pb::NodeConfig {
|
||||
fn from(value: NodeConfig) -> Self {
|
||||
Self {
|
||||
peer_id: value.peer_id,
|
||||
instance_id: value.instance_id.map(uuid_from_bytes),
|
||||
hostname: value.hostname,
|
||||
network_name: value.network_name,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::RouteConfig> for RouteConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::RouteConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
ipv4: value.ipv4.map(TryInto::try_into).transpose()?,
|
||||
ipv6: value.ipv6.map(TryInto::try_into).transpose()?,
|
||||
advertised_routes: value
|
||||
.advertised_routes
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
proxy_networks: value
|
||||
.proxy_networks
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
foreign_networks: value
|
||||
.foreign_networks
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<RouteConfig> for pb::RouteConfig {
|
||||
fn from(value: RouteConfig) -> Self {
|
||||
Self {
|
||||
ipv4: value.ipv4.map(Into::into),
|
||||
ipv6: value.ipv6.map(Into::into),
|
||||
advertised_routes: value
|
||||
.advertised_routes
|
||||
.into_iter()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
proxy_networks: value.proxy_networks.into_iter().map(Into::into).collect(),
|
||||
foreign_networks: value.foreign_networks.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::IpPrefix> for IpPrefix {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::IpPrefix) -> Result<Self, Self::Error> {
|
||||
let address = pb_ip_addr_to_std(
|
||||
value
|
||||
.address
|
||||
.ok_or(ConfigError::MissingField("IpPrefix.address"))?,
|
||||
)?;
|
||||
let prefix_len = u8::try_from(value.prefix_len)
|
||||
.map_err(|_| invalid_prefix_for_address(address, value.prefix_len))?;
|
||||
Self::new(address, prefix_len)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<IpPrefix> for pb::IpPrefix {
|
||||
fn from(value: IpPrefix) -> Self {
|
||||
Self {
|
||||
address: Some(value.address.into()),
|
||||
prefix_len: value.prefix_len.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::ProxyNetworkConfig> for ProxyNetworkConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::ProxyNetworkConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
real: value
|
||||
.real
|
||||
.ok_or(ConfigError::MissingField("ProxyNetworkConfig.real"))?
|
||||
.try_into()?,
|
||||
mapped: value.mapped.map(TryInto::try_into).transpose()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ProxyNetworkConfig> for pb::ProxyNetworkConfig {
|
||||
fn from(value: ProxyNetworkConfig) -> Self {
|
||||
Self {
|
||||
real: Some(value.real.into()),
|
||||
mapped: value.mapped.map(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::ForeignNetworkConfig> for ForeignNetworkConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::ForeignNetworkConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
name: value.name,
|
||||
cidrs: value
|
||||
.cidrs
|
||||
.into_iter()
|
||||
.map(TryInto::try_into)
|
||||
.collect::<Result<_, _>>()?,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<ForeignNetworkConfig> for pb::ForeignNetworkConfig {
|
||||
fn from(value: ForeignNetworkConfig) -> Self {
|
||||
Self {
|
||||
name: value.name,
|
||||
cidrs: value.cidrs.into_iter().map(Into::into).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<pb::PeerPolicyConfig> for PeerPolicyConfig {
|
||||
fn from(value: pb::PeerPolicyConfig) -> Self {
|
||||
let default = Self::default();
|
||||
Self {
|
||||
p2p_enabled: value.p2p_enabled.unwrap_or(default.p2p_enabled),
|
||||
relay_peer_rpc: value.relay_peer_rpc.unwrap_or(default.relay_peer_rpc),
|
||||
relay_data: value.relay_data.unwrap_or(default.relay_data),
|
||||
latency_first: value.latency_first.unwrap_or(default.latency_first),
|
||||
encryption_required: value
|
||||
.encryption_required
|
||||
.unwrap_or(default.encryption_required),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<PeerPolicyConfig> for pb::PeerPolicyConfig {
|
||||
fn from(value: PeerPolicyConfig) -> Self {
|
||||
Self {
|
||||
p2p_enabled: Some(value.p2p_enabled),
|
||||
relay_peer_rpc: Some(value.relay_peer_rpc),
|
||||
relay_data: Some(value.relay_data),
|
||||
latency_first: Some(value.latency_first),
|
||||
encryption_required: Some(value.encryption_required),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<pb::TrafficConfig> for TrafficConfig {
|
||||
type Error = ConfigError;
|
||||
|
||||
fn try_from(value: pb::TrafficConfig) -> Result<Self, Self::Error> {
|
||||
Ok(Self {
|
||||
mtu: value
|
||||
.mtu
|
||||
.map(|mtu| u16::try_from(mtu).map_err(|_| ConfigError::InvalidMtu(mtu)))
|
||||
.transpose()?,
|
||||
instance_recv_bps_limit: value.instance_recv_bps_limit,
|
||||
foreign_relay_bps_limit: value.foreign_relay_bps_limit,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TrafficConfig> for pb::TrafficConfig {
|
||||
fn from(value: TrafficConfig) -> Self {
|
||||
Self {
|
||||
mtu: value.mtu.map(Into::into),
|
||||
instance_recv_bps_limit: value.instance_recv_bps_limit,
|
||||
foreign_relay_bps_limit: value.foreign_relay_bps_limit,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn pb_ip_addr_to_std(value: common_pb::IpAddr) -> Result<IpAddr, ConfigError> {
|
||||
match value.ip.ok_or(ConfigError::MissingField("IpAddr.ip"))? {
|
||||
common_pb::ip_addr::Ip::Ipv4(addr) => Ok(IpAddr::V4(addr.into())),
|
||||
common_pb::ip_addr::Ip::Ipv6(addr) => Ok(IpAddr::V6(addr.into())),
|
||||
}
|
||||
}
|
||||
|
||||
fn invalid_prefix_for_address(address: IpAddr, prefix_len: u32) -> ConfigError {
|
||||
let prefix_len = u8::try_from(prefix_len).unwrap_or(u8::MAX);
|
||||
match address {
|
||||
IpAddr::V4(_) => ConfigError::InvalidIpv4Prefix(prefix_len),
|
||||
IpAddr::V6(_) => ConfigError::InvalidIpv6Prefix(prefix_len),
|
||||
}
|
||||
}
|
||||
|
||||
fn uuid_to_bytes(value: common_pb::Uuid) -> [u8; 16] {
|
||||
let mut bytes = [0; 16];
|
||||
bytes[0..4].copy_from_slice(&value.part1.to_be_bytes());
|
||||
bytes[4..8].copy_from_slice(&value.part2.to_be_bytes());
|
||||
bytes[8..12].copy_from_slice(&value.part3.to_be_bytes());
|
||||
bytes[12..16].copy_from_slice(&value.part4.to_be_bytes());
|
||||
bytes
|
||||
}
|
||||
|
||||
fn uuid_from_bytes(bytes: [u8; 16]) -> common_pb::Uuid {
|
||||
common_pb::Uuid {
|
||||
part1: u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
|
||||
part2: u32::from_be_bytes([bytes[4], bytes[5], bytes[6], bytes[7]]),
|
||||
part3: u32::from_be_bytes([bytes[8], bytes[9], bytes[10], bytes[11]]),
|
||||
part4: u32::from_be_bytes([bytes[12], bytes[13], bytes[14], bytes[15]]),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use base64::prelude::BASE64_STANDARD;
|
||||
use x25519_dalek::{PublicKey, StaticSecret};
|
||||
|
||||
fn digest(network_name: &str, network_secret: &str) -> NetworkSecretDigest {
|
||||
let mut digest = [0u8; 32];
|
||||
generate_digest_from_str(network_name, network_secret, &mut digest);
|
||||
digest
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_matches_secret_to_digest_identity() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "secret")),
|
||||
};
|
||||
|
||||
assert_eq!(local, remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_rejects_different_digest() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "other")),
|
||||
};
|
||||
|
||||
assert_ne!(local, remote);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_equal_values_have_equal_hash() {
|
||||
let local = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let remote = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: None,
|
||||
network_secret_digest: Some(digest("net", "secret")),
|
||||
};
|
||||
let mut local_hasher = DefaultHasher::new();
|
||||
let mut remote_hasher = DefaultHasher::new();
|
||||
|
||||
local.hash(&mut local_hasher);
|
||||
remote.hash(&mut remote_hasher);
|
||||
|
||||
assert_eq!(local_hasher.finish(), remote_hasher.finish());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_derives_digest_from_plaintext_secret() {
|
||||
let identity = NetworkIdentity {
|
||||
network_name: "net".to_string(),
|
||||
network_secret: Some("secret".to_string()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
|
||||
assert_eq!(identity.secret_digest(), Some(digest("net", "secret")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn network_identity_default_matches_native_default_network() {
|
||||
assert_eq!(
|
||||
NetworkIdentity::default(),
|
||||
NetworkIdentity::new("default".to_string(), "".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_listener_policy_uses_explicit_host_capabilities() {
|
||||
let policy = MappedListenerPolicy::new(["tcp", "ws", "wss"]);
|
||||
let parsed = policy
|
||||
.parse_urls(&[
|
||||
"tcp://127.0.0.1".to_string(),
|
||||
"ws://example.com".to_string(),
|
||||
"wss://example.com/path".to_string(),
|
||||
"ring://peer-id:1000".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(parsed.len(), 4);
|
||||
assert_eq!(parsed[0].scheme(), "tcp");
|
||||
assert_eq!(parsed[1].scheme(), "ws");
|
||||
assert_eq!(parsed[2].scheme(), "wss");
|
||||
assert_eq!(parsed[3].port(), Some(1000));
|
||||
|
||||
let error = policy
|
||||
.parse_urls(&["ring://peer-id".to_string()])
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
error
|
||||
.to_string()
|
||||
.contains("mapped listener port is missing")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_generates_missing_key_pair() {
|
||||
let normalized = normalize_secure_mode_config(common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: None,
|
||||
local_public_key: None,
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
let private_key = normalized.private_key().unwrap();
|
||||
let public_key = normalized.public_key().unwrap();
|
||||
assert_eq!(public_key, PublicKey::from(&private_key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_preserves_existing_key_configuration() {
|
||||
let private_key = StaticSecret::from([7; 32]);
|
||||
let public_key = PublicKey::from(&private_key);
|
||||
let config = common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: Some(BASE64_STANDARD.encode(private_key.as_bytes())),
|
||||
local_public_key: Some(BASE64_STANDARD.encode(public_key.as_bytes())),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_secure_mode_config(config.clone()).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn secure_mode_normalization_rejects_mismatched_public_key() {
|
||||
let private_key = StaticSecret::from([7; 32]);
|
||||
let other_public_key = PublicKey::from(&StaticSecret::from([9; 32]));
|
||||
let error = normalize_secure_mode_config(common_pb::SecureModeConfig {
|
||||
enabled: true,
|
||||
local_private_key: Some(BASE64_STANDARD.encode(private_key.as_bytes())),
|
||||
local_public_key: Some(BASE64_STANDARD.encode(other_public_key.as_bytes())),
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
|
||||
assert!(
|
||||
error.contains("does not match generated public key"),
|
||||
"{error}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_secure_mode_does_not_validate_keys() {
|
||||
let config = common_pb::SecureModeConfig {
|
||||
enabled: false,
|
||||
local_private_key: Some("not-base64".to_string()),
|
||||
local_public_key: Some("not-base64".to_string()),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
normalize_secure_mode_config(config.clone()).unwrap(),
|
||||
config
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validates_ip_prefix_lengths() {
|
||||
assert!(IpPrefix::new("10.0.0.1".parse().unwrap(), 24).is_ok());
|
||||
assert_eq!(
|
||||
IpPrefix::new("10.0.0.1".parse().unwrap(), 33),
|
||||
Err(ConfigError::InvalidIpv4Prefix(33))
|
||||
);
|
||||
assert!(IpPrefix::new("2001:db8::1".parse().unwrap(), 64).is_ok());
|
||||
assert_eq!(
|
||||
IpPrefix::new("2001:db8::1".parse().unwrap(), 129),
|
||||
Err(ConfigError::InvalidIpv6Prefix(129))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_core_config_from_proto_defaults() {
|
||||
let config = CoreConfig::try_from(pb::CoreConfig {
|
||||
node: Some(pb::NodeConfig {
|
||||
peer_id: Some(7),
|
||||
instance_id: None,
|
||||
hostname: Some("node-a".to_string()),
|
||||
network_name: "net".to_string(),
|
||||
}),
|
||||
routes: None,
|
||||
peer_policy: None,
|
||||
traffic: Some(pb::TrafficConfig {
|
||||
mtu: Some(1380),
|
||||
instance_recv_bps_limit: Some(100),
|
||||
foreign_relay_bps_limit: None,
|
||||
}),
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(config.node.peer_id, Some(7));
|
||||
assert_eq!(config.node.hostname.as_deref(), Some("node-a"));
|
||||
assert!(config.peer_policy.p2p_enabled);
|
||||
assert_eq!(config.traffic.mtu, Some(1380));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn converts_ip_prefix_round_trip() {
|
||||
let prefix = IpPrefix::new("10.1.0.1".parse().unwrap(), 16).unwrap();
|
||||
let pb: pb::IpPrefix = prefix.clone().into();
|
||||
assert_eq!(IpPrefix::try_from(pb).unwrap(), prefix);
|
||||
}
|
||||
}
|
||||
+359
@@ -0,0 +1,359 @@
|
||||
//! Peer-flavored configuration data owned by the config layer.
|
||||
//!
|
||||
//! These types are pure serializable configuration snapshots. Normalization
|
||||
//! and derivation behavior that depends on peer-domain logic stays in
|
||||
//! `crate::peers`.
|
||||
|
||||
use anyhow::Context as _;
|
||||
use cidr::Ipv6Cidr;
|
||||
use easytier_proto::common::{FlagsInConfig, PeerFeatureFlag, SecureModeConfig, StunInfo};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::proto::acl::{Acl, AclV1, Action, Chain, ChainType, GroupInfo, Protocol, Rule};
|
||||
|
||||
use super::{CoreConfig, NetworkIdentity};
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct AclRuleConfig {
|
||||
pub acl: Option<Acl>,
|
||||
pub tcp_whitelist: Vec<String>,
|
||||
pub udp_whitelist: Vec<String>,
|
||||
pub whitelist_priority: Option<u32>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct AclWhitelistSnapshot {
|
||||
pub tcp_ports: Vec<String>,
|
||||
pub udp_ports: Vec<String>,
|
||||
}
|
||||
|
||||
impl From<&AclRuleConfig> for AclWhitelistSnapshot {
|
||||
fn from(config: &AclRuleConfig) -> Self {
|
||||
Self {
|
||||
tcp_ports: config.tcp_whitelist.clone(),
|
||||
udp_ports: config.udp_whitelist.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AclRuleConfig {
|
||||
fn parse_port_list(port_list: &[String]) -> anyhow::Result<Vec<String>> {
|
||||
let mut ports = Vec::new();
|
||||
|
||||
for port_spec in port_list {
|
||||
if port_spec.contains('-') {
|
||||
let parts: Vec<&str> = port_spec.split('-').collect();
|
||||
if parts.len() != 2 {
|
||||
return Err(anyhow::anyhow!("Invalid port range format: {}", port_spec));
|
||||
}
|
||||
|
||||
let start: u16 = parts[0]
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid start port in range: {}", port_spec))?;
|
||||
let end: u16 = parts[1]
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid end port in range: {}", port_spec))?;
|
||||
|
||||
if start > end {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Start port must be <= end port in range: {}",
|
||||
port_spec
|
||||
));
|
||||
}
|
||||
ports.push(port_spec.clone());
|
||||
} else {
|
||||
let port: u16 = port_spec
|
||||
.parse()
|
||||
.with_context(|| format!("Invalid port number: {}", port_spec))?;
|
||||
ports.push(port.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ports)
|
||||
}
|
||||
|
||||
fn generate_acl_from_whitelists(&mut self) -> anyhow::Result<()> {
|
||||
if self.tcp_whitelist.is_empty() && self.udp_whitelist.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let mut inbound_chain = Chain {
|
||||
name: "inbound_whitelist".to_string(),
|
||||
chain_type: ChainType::Inbound as i32,
|
||||
description: "Auto-generated inbound whitelist from CLI".to_string(),
|
||||
enabled: true,
|
||||
rules: vec![],
|
||||
default_action: Action::Allow as i32,
|
||||
};
|
||||
|
||||
let mut rule_priority = self.whitelist_priority.unwrap_or(1000u32);
|
||||
|
||||
if !self.tcp_whitelist.is_empty() {
|
||||
let tcp_ports = Self::parse_port_list(&self.tcp_whitelist)?;
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "tcp_whitelist".to_string(),
|
||||
description: "Auto-generated TCP whitelist rule".to_string(),
|
||||
priority: rule_priority,
|
||||
enabled: true,
|
||||
protocol: Protocol::Tcp as i32,
|
||||
ports: tcp_ports,
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Allow as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: true,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "tcp_whitelist_deny_other".to_string(),
|
||||
description: "Auto-generated TCP whitelist rule to deny other ports".to_string(),
|
||||
priority: 0,
|
||||
enabled: true,
|
||||
protocol: Protocol::Tcp as i32,
|
||||
ports: vec!["0-65535".to_string()],
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Drop as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
rule_priority -= 1;
|
||||
}
|
||||
|
||||
if !self.udp_whitelist.is_empty() {
|
||||
let udp_ports = Self::parse_port_list(&self.udp_whitelist)?;
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "udp_whitelist".to_string(),
|
||||
description: "Auto-generated UDP whitelist rule".to_string(),
|
||||
priority: rule_priority,
|
||||
enabled: true,
|
||||
protocol: Protocol::Udp as i32,
|
||||
ports: udp_ports,
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Allow as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
inbound_chain.rules.push(Rule {
|
||||
name: "udp_whitelist_deny_other".to_string(),
|
||||
description: "Auto-generated UDP whitelist rule to deny other ports".to_string(),
|
||||
priority: 0,
|
||||
enabled: true,
|
||||
protocol: Protocol::Udp as i32,
|
||||
ports: vec!["0-65535".to_string()],
|
||||
source_ips: vec![],
|
||||
destination_ips: vec![],
|
||||
source_ports: vec![],
|
||||
action: Action::Drop as i32,
|
||||
rate_limit: 0,
|
||||
burst_limit: 0,
|
||||
stateful: false,
|
||||
source_groups: vec![],
|
||||
destination_groups: vec![],
|
||||
});
|
||||
}
|
||||
|
||||
if self.acl.is_none() {
|
||||
self.acl = Some(Acl::default());
|
||||
}
|
||||
|
||||
let acl = self.acl.as_mut().expect("ACL was initialized above");
|
||||
if let Some(acl_v1) = acl.acl_v1.as_mut() {
|
||||
acl_v1.chains.push(inbound_chain);
|
||||
} else {
|
||||
acl.acl_v1 = Some(AclV1 {
|
||||
chains: vec![inbound_chain],
|
||||
group: Some(GroupInfo {
|
||||
declares: vec![],
|
||||
members: vec![],
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn for_credential_peer(&self) -> Self {
|
||||
let mut config = self.clone();
|
||||
if let Some(acl) = config.acl.as_mut().and_then(|acl| acl.acl_v1.as_mut()) {
|
||||
acl.group = None;
|
||||
}
|
||||
config
|
||||
}
|
||||
|
||||
pub fn build(&self) -> anyhow::Result<Option<Acl>> {
|
||||
let mut config = self.clone();
|
||||
config.generate_acl_from_whitelists()?;
|
||||
Ok(config.acl)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PublicIpv6ProviderConfig {
|
||||
pub provider_enabled: bool,
|
||||
pub configured_prefix: Option<Ipv6Cidr>,
|
||||
pub provider_supported: bool,
|
||||
}
|
||||
|
||||
impl PublicIpv6ProviderConfig {
|
||||
pub fn should_run_reconcile(self) -> bool {
|
||||
self.provider_enabled
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PeerRuntimeConfig {
|
||||
pub core: CoreConfig,
|
||||
pub network_identity: NetworkIdentity,
|
||||
pub stun_info: StunInfo,
|
||||
pub feature_flags: PeerFeatureFlag,
|
||||
pub secure_mode: Option<SecureModeConfig>,
|
||||
pub host_routing: HostRoutingPolicy,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HostRoutingPolicy {
|
||||
/// Route otherwise-unreachable external IPv4 traffic through this node and
|
||||
/// keep self-delivered packets eligible for the host TUN/proxy path.
|
||||
pub local_exit_node_fallback: bool,
|
||||
}
|
||||
|
||||
/// One normalized peer configuration version submitted by a host.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct PeerRuntimeSnapshot {
|
||||
pub runtime: PeerRuntimeConfig,
|
||||
pub easytier_version: String,
|
||||
pub avoid_relay_data_preference: bool,
|
||||
pub flags: FlagsInConfig,
|
||||
pub pinned_peers: Vec<(url::Url, Option<String>)>,
|
||||
pub peer_group_memberships: Vec<PeerGroupIdentity>,
|
||||
pub acl_group_declarations: Vec<PeerGroupIdentity>,
|
||||
pub ospf_update_my_foreign_network_interval_sec: u64,
|
||||
pub max_direct_conns_per_peer_in_foreign_network: usize,
|
||||
pub hmac_secret_digest: bool,
|
||||
}
|
||||
|
||||
impl PeerRuntimeSnapshot {
|
||||
pub fn new(runtime: PeerRuntimeConfig, flags: FlagsInConfig) -> Self {
|
||||
let avoid_relay_data_preference = runtime.feature_flags.avoid_relay_data;
|
||||
Self {
|
||||
runtime,
|
||||
easytier_version: env!("CARGO_PKG_VERSION").to_owned(),
|
||||
avoid_relay_data_preference,
|
||||
flags,
|
||||
pinned_peers: Vec::new(),
|
||||
peer_group_memberships: Vec::new(),
|
||||
acl_group_declarations: Vec::new(),
|
||||
ospf_update_my_foreign_network_interval_sec: 10,
|
||||
max_direct_conns_per_peer_in_foreign_network: 3,
|
||||
hmac_secret_digest: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PeerRuntimeSnapshot {
|
||||
fn default() -> Self {
|
||||
Self::new(
|
||||
PeerRuntimeConfig {
|
||||
core: CoreConfig::default(),
|
||||
network_identity: NetworkIdentity::default(),
|
||||
stun_info: StunInfo::default(),
|
||||
feature_flags: PeerFeatureFlag::default(),
|
||||
secure_mode: None,
|
||||
host_routing: HostRoutingPolicy::default(),
|
||||
},
|
||||
FlagsInConfig::default(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PeerGroupIdentity {
|
||||
pub group_name: String,
|
||||
pub group_secret: String,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn whitelist_rules_are_built_in_core() {
|
||||
let acl = AclRuleConfig {
|
||||
tcp_whitelist: vec!["80".to_string(), "8000-9000".to_string()],
|
||||
udp_whitelist: vec!["53".to_string()],
|
||||
..Default::default()
|
||||
}
|
||||
.build()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let chain = &acl.acl_v1.unwrap().chains[0];
|
||||
assert_eq!(chain.name, "inbound_whitelist");
|
||||
assert_eq!(chain.rules.len(), 4);
|
||||
assert_eq!(chain.rules[0].ports, ["80", "8000-9000"]);
|
||||
assert_eq!(chain.rules[2].ports, ["53"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_whitelist_range_is_rejected() {
|
||||
let error = AclRuleConfig {
|
||||
tcp_whitelist: vec!["9000-8000".to_string()],
|
||||
..Default::default()
|
||||
}
|
||||
.build()
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("Start port must be <= end port"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn credential_peer_acl_preserves_chains_without_group_secrets() {
|
||||
let config = AclRuleConfig {
|
||||
acl: Some(Acl {
|
||||
acl_v1: Some(AclV1 {
|
||||
chains: vec![Chain {
|
||||
name: "forward".to_owned(),
|
||||
chain_type: ChainType::Forward as i32,
|
||||
rules: vec![Rule {
|
||||
action: Action::Drop as i32,
|
||||
..Default::default()
|
||||
}],
|
||||
..Default::default()
|
||||
}],
|
||||
group: Some(GroupInfo {
|
||||
declares: vec![crate::proto::acl::GroupIdentity {
|
||||
group_name: "ops".to_owned(),
|
||||
group_secret: "secret".to_owned(),
|
||||
}],
|
||||
members: vec!["ops".to_owned()],
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
tcp_whitelist: vec!["22".to_owned()],
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
let sanitized = config.for_credential_peer();
|
||||
|
||||
let acl = sanitized.acl.unwrap().acl_v1.unwrap();
|
||||
assert_eq!(acl.chains.len(), 1);
|
||||
assert_eq!(acl.chains[0].name, "forward");
|
||||
assert_eq!(acl.chains[0].rules[0].action, Action::Drop as i32);
|
||||
assert!(acl.group.is_none());
|
||||
assert_eq!(sanitized.tcp_whitelist, ["22"]);
|
||||
assert!(config.acl.unwrap().acl_v1.unwrap().group.is_some());
|
||||
}
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
//! Atomic runtime configuration owned by one core instance.
|
||||
|
||||
use std::{collections::BTreeSet, sync::Arc};
|
||||
|
||||
use arc_swap::ArcSwap;
|
||||
use cidr::Ipv4Cidr;
|
||||
use parking_lot::Mutex;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use super::{
|
||||
gateway::{GatewayRuntimeConfig, ProxyRuntimeConfig},
|
||||
peers::{AclRuleConfig, PeerRuntimeSnapshot, PublicIpv6ProviderConfig},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct CoreRuntimeConfig {
|
||||
pub acl: AclRuleConfig,
|
||||
pub dhcp_ipv4: bool,
|
||||
pub gateway: GatewayRuntimeConfig,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pub manual_routes: Option<BTreeSet<Ipv4Cidr>>,
|
||||
pub proxy: ProxyRuntimeConfig,
|
||||
#[serde(default)]
|
||||
pub public_ipv6_auto: bool,
|
||||
pub public_ipv6_provider: PublicIpv6ProviderConfig,
|
||||
}
|
||||
|
||||
impl Default for CoreRuntimeConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
acl: AclRuleConfig::default(),
|
||||
dhcp_ipv4: false,
|
||||
gateway: GatewayRuntimeConfig::default(),
|
||||
manual_routes: None,
|
||||
proxy: ProxyRuntimeConfig::default(),
|
||||
public_ipv6_auto: false,
|
||||
public_ipv6_provider: PublicIpv6ProviderConfig {
|
||||
provider_enabled: false,
|
||||
configured_prefix: None,
|
||||
provider_supported: false,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CoreInstanceRuntimeConfig {
|
||||
pub services: CoreRuntimeConfig,
|
||||
pub peer: Arc<PeerRuntimeSnapshot>,
|
||||
}
|
||||
|
||||
struct CoreRuntimeConfigStoreInner {
|
||||
snapshot: ArcSwap<CoreInstanceRuntimeConfig>,
|
||||
update: Mutex<()>,
|
||||
peer_changes: tokio::sync::watch::Sender<u64>,
|
||||
service_changes: tokio::sync::watch::Sender<u64>,
|
||||
}
|
||||
|
||||
/// Atomic configuration authority shared by one core instance and its peer
|
||||
/// context. Readers always observe a complete submitted version.
|
||||
#[derive(Clone)]
|
||||
pub struct CoreRuntimeConfigStore {
|
||||
inner: Arc<CoreRuntimeConfigStoreInner>,
|
||||
}
|
||||
|
||||
impl CoreRuntimeConfigStore {
|
||||
pub fn new(services: CoreRuntimeConfig, peer: Arc<PeerRuntimeSnapshot>) -> Self {
|
||||
let (peer_changes, _) = tokio::sync::watch::channel(0);
|
||||
let (service_changes, _) = tokio::sync::watch::channel(0);
|
||||
Self {
|
||||
inner: Arc::new(CoreRuntimeConfigStoreInner {
|
||||
snapshot: ArcSwap::from_pointee(CoreInstanceRuntimeConfig { services, peer }),
|
||||
update: Mutex::new(()),
|
||||
peer_changes,
|
||||
service_changes,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Arc<CoreInstanceRuntimeConfig> {
|
||||
self.inner.snapshot.load_full()
|
||||
}
|
||||
|
||||
pub(crate) fn with_snapshot<T>(&self, read: impl FnOnce(&CoreInstanceRuntimeConfig) -> T) -> T {
|
||||
let snapshot = self.inner.snapshot.load();
|
||||
read(&snapshot)
|
||||
}
|
||||
|
||||
pub fn replace(&self, config: CoreInstanceRuntimeConfig) {
|
||||
let _update = self.inner.update.lock();
|
||||
self.inner.snapshot.store(Arc::new(config));
|
||||
self.inner.peer_changes.send_modify(|version| *version += 1);
|
||||
self.inner
|
||||
.service_changes
|
||||
.send_modify(|version| *version += 1);
|
||||
}
|
||||
|
||||
pub(crate) fn replace_with_current(
|
||||
&self,
|
||||
mut config: CoreInstanceRuntimeConfig,
|
||||
merge: impl FnOnce(&CoreInstanceRuntimeConfig, &mut CoreInstanceRuntimeConfig),
|
||||
) -> Arc<CoreInstanceRuntimeConfig> {
|
||||
let _update = self.inner.update.lock();
|
||||
let current = self.inner.snapshot.load_full();
|
||||
merge(¤t, &mut config);
|
||||
let config = Arc::new(config);
|
||||
self.inner.snapshot.store(config.clone());
|
||||
self.inner.peer_changes.send_modify(|version| *version += 1);
|
||||
self.inner
|
||||
.service_changes
|
||||
.send_modify(|version| *version += 1);
|
||||
config
|
||||
}
|
||||
|
||||
pub fn update_services(&self, update: impl FnOnce(&mut CoreRuntimeConfig)) {
|
||||
let _update = self.inner.update.lock();
|
||||
let mut config = self.inner.snapshot.load_full().as_ref().clone();
|
||||
update(&mut config.services);
|
||||
self.inner.snapshot.store(Arc::new(config));
|
||||
self.inner
|
||||
.service_changes
|
||||
.send_modify(|version| *version += 1);
|
||||
}
|
||||
|
||||
pub fn update_peer(&self, peer: Arc<PeerRuntimeSnapshot>) {
|
||||
let _update = self.inner.update.lock();
|
||||
let mut config = self.inner.snapshot.load_full().as_ref().clone();
|
||||
config.peer = peer;
|
||||
self.inner.snapshot.store(Arc::new(config));
|
||||
self.inner.peer_changes.send_modify(|version| *version += 1);
|
||||
}
|
||||
|
||||
pub(crate) fn update_peer_with(&self, update: impl FnOnce(&mut PeerRuntimeSnapshot)) {
|
||||
let _update = self.inner.update.lock();
|
||||
let mut config = self.inner.snapshot.load_full().as_ref().clone();
|
||||
update(Arc::make_mut(&mut config.peer));
|
||||
self.inner.snapshot.store(Arc::new(config));
|
||||
self.inner.peer_changes.send_modify(|version| *version += 1);
|
||||
}
|
||||
|
||||
pub fn subscribe_peer_runtime_changes(&self) -> tokio::sync::watch::Receiver<u64> {
|
||||
self.inner.peer_changes.subscribe()
|
||||
}
|
||||
|
||||
pub fn subscribe_service_runtime_changes(&self) -> tokio::sync::watch::Receiver<u64> {
|
||||
self.inner.service_changes.subscribe()
|
||||
}
|
||||
#[cfg(test)]
|
||||
pub(crate) fn peer_change_subscriber_count(&self) -> usize {
|
||||
self.inner.peer_changes.receiver_count()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn service_change_subscriber_count(&self) -> usize {
|
||||
self.inner.service_changes.receiver_count()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn replaces_service_and_peer_as_one_version() {
|
||||
let mut before_peer = PeerRuntimeSnapshot::default();
|
||||
before_peer.runtime.core.node.hostname = Some("before".to_owned());
|
||||
let store =
|
||||
CoreRuntimeConfigStore::new(CoreRuntimeConfig::default(), Arc::new(before_peer));
|
||||
let before = store.snapshot();
|
||||
|
||||
let after_services = CoreRuntimeConfig {
|
||||
dhcp_ipv4: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut after_peer = PeerRuntimeSnapshot::default();
|
||||
after_peer.runtime.core.node.hostname = Some("after".to_owned());
|
||||
store.replace(CoreInstanceRuntimeConfig {
|
||||
services: after_services,
|
||||
peer: Arc::new(after_peer),
|
||||
});
|
||||
|
||||
assert!(!before.services.dhcp_ipv4);
|
||||
assert_eq!(
|
||||
before.peer.runtime.core.node.hostname.as_deref(),
|
||||
Some("before")
|
||||
);
|
||||
let after = store.snapshot();
|
||||
assert!(after.services.dhcp_ipv4);
|
||||
assert_eq!(
|
||||
after.peer.runtime.core.node.hostname.as_deref(),
|
||||
Some("after")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notifies_peer_snapshot_changes() {
|
||||
let store = CoreRuntimeConfigStore::new(
|
||||
CoreRuntimeConfig::default(),
|
||||
Arc::new(PeerRuntimeSnapshot::default()),
|
||||
);
|
||||
let mut changes = store.subscribe_peer_runtime_changes();
|
||||
let mut peer = PeerRuntimeSnapshot::default();
|
||||
peer.runtime.core.node.hostname = Some("updated".to_owned());
|
||||
|
||||
store.update_peer(Arc::new(peer));
|
||||
|
||||
assert!(changes.changed().await.is_ok());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn notifies_service_snapshot_changes() {
|
||||
let store = CoreRuntimeConfigStore::new(
|
||||
CoreRuntimeConfig::default(),
|
||||
Arc::new(PeerRuntimeSnapshot::default()),
|
||||
);
|
||||
let mut changes = store.subscribe_service_runtime_changes();
|
||||
|
||||
store.update_services(|services| services.dhcp_ipv4 = true);
|
||||
|
||||
assert!(changes.changed().await.is_ok());
|
||||
assert!(store.snapshot().services.dhcp_ipv4);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_update_does_not_notify_service_watchers() {
|
||||
let store = CoreRuntimeConfigStore::new(
|
||||
CoreRuntimeConfig::default(),
|
||||
Arc::new(PeerRuntimeSnapshot::default()),
|
||||
);
|
||||
let changes = store.subscribe_service_runtime_changes();
|
||||
let mut peer = PeerRuntimeSnapshot::default();
|
||||
peer.runtime.core.node.hostname = Some("updated".to_owned());
|
||||
|
||||
store.update_peer(Arc::new(peer));
|
||||
|
||||
assert!(!changes.has_changed().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_in_place_update_preserves_the_rest_of_the_atomic_snapshot() {
|
||||
let services = CoreRuntimeConfig {
|
||||
dhcp_ipv4: true,
|
||||
..Default::default()
|
||||
};
|
||||
let mut peer = PeerRuntimeSnapshot::default();
|
||||
peer.runtime.core.node.hostname = Some("preserved".to_owned());
|
||||
let store = CoreRuntimeConfigStore::new(services, Arc::new(peer));
|
||||
|
||||
store.update_peer_with(|peer| {
|
||||
peer.runtime.core.routes.ipv4 = Some(crate::config::IpPrefix {
|
||||
address: "10.20.30.7".parse().unwrap(),
|
||||
prefix_len: 24,
|
||||
});
|
||||
});
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(snapshot.services.dhcp_ipv4);
|
||||
assert_eq!(
|
||||
snapshot.peer.runtime.core.node.hostname.as_deref(),
|
||||
Some("preserved")
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot
|
||||
.peer
|
||||
.runtime
|
||||
.core
|
||||
.routes
|
||||
.ipv4
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.address,
|
||||
"10.20.30.7".parse::<std::net::IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_manual_routes_preserves_portable_config_compatibility() {
|
||||
let encoded = serde_json::to_value(CoreRuntimeConfig::default()).unwrap();
|
||||
assert!(encoded.get("manual_routes").is_none());
|
||||
|
||||
let decoded: CoreRuntimeConfig = serde_json::from_value(encoded).unwrap();
|
||||
assert_eq!(decoded.manual_routes, None);
|
||||
}
|
||||
}
|
||||
+2016
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,15 @@
|
||||
use super::{Arc, Mutex, TomlConfig};
|
||||
|
||||
impl TomlConfig {
|
||||
pub(crate) fn detached_snapshot(&self) -> Self {
|
||||
let config = self.config.lock().unwrap().clone();
|
||||
Self {
|
||||
config: Arc::new(Mutex::new(config)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn replace_from_snapshot(&self, snapshot: &Self) {
|
||||
let config = snapshot.config.lock().unwrap().clone();
|
||||
*self.config.lock().unwrap() = config;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,496 @@
|
||||
//! Composes process-wide socket capabilities with instance-scoped network facts.
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
net::{IpAddr, Ipv6Addr, SocketAddr},
|
||||
sync::Arc,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
connectivity::{
|
||||
direct::DirectConnectorHost,
|
||||
manual::{ManualConnectorHost, ManualInterfaceAddrs},
|
||||
transport::ConnectedByteStream,
|
||||
},
|
||||
proto::peer_rpc::GetIpListResponse,
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{
|
||||
TcpConnectOptions, TcpListenOptions, VirtualTcpListenerFactory, VirtualTcpSocketFactory,
|
||||
},
|
||||
udp::{PreferredIpv6Source, UdpBindOptions, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
const INTERFACE_ADDR_CACHE_TTL: Duration = Duration::from_secs(60);
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedInterfaceAddrs {
|
||||
collected_at: Instant,
|
||||
response: GetIpListResponse,
|
||||
}
|
||||
|
||||
struct InterfaceAddrCacheEntry {
|
||||
context: SocketContext,
|
||||
value: Arc<tokio::sync::Mutex<Option<CachedInterfaceAddrs>>>,
|
||||
}
|
||||
|
||||
struct InterfaceAddrCache {
|
||||
entries: tokio::sync::Mutex<Vec<InterfaceAddrCacheEntry>>,
|
||||
ttl: Duration,
|
||||
}
|
||||
|
||||
impl InterfaceAddrCache {
|
||||
fn new(ttl: Duration) -> Self {
|
||||
Self {
|
||||
entries: tokio::sync::Mutex::new(Vec::new()),
|
||||
ttl,
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_or_collect<F, Fut>(&self, context: &SocketContext, collect: F) -> GetIpListResponse
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = GetIpListResponse>,
|
||||
{
|
||||
let value = {
|
||||
let mut entries = self.entries.lock().await;
|
||||
entries.retain(|entry| {
|
||||
if Arc::strong_count(&entry.value) > 1 {
|
||||
return true;
|
||||
}
|
||||
entry.value.try_lock().map_or(true, |cached| {
|
||||
cached
|
||||
.as_ref()
|
||||
.is_some_and(|cached| cached.collected_at.elapsed() < self.ttl)
|
||||
})
|
||||
});
|
||||
if let Some(entry) = entries.iter().find(|entry| &entry.context == context) {
|
||||
entry.value.clone()
|
||||
} else {
|
||||
let value = Arc::new(tokio::sync::Mutex::new(None));
|
||||
entries.push(InterfaceAddrCacheEntry {
|
||||
context: context.clone(),
|
||||
value: value.clone(),
|
||||
});
|
||||
value
|
||||
}
|
||||
};
|
||||
|
||||
// Only collectors for the same socket context share this lock. A slow
|
||||
// namespace observation cannot block fresh hits or refreshes elsewhere.
|
||||
let mut cached = value.lock().await;
|
||||
if let Some(cached) = cached
|
||||
.as_ref()
|
||||
.filter(|cached| cached.collected_at.elapsed() < self.ttl)
|
||||
{
|
||||
return cached.response.clone();
|
||||
}
|
||||
|
||||
let response = collect().await;
|
||||
*cached = Some(CachedInterfaceAddrs {
|
||||
collected_at: Instant::now(),
|
||||
response: response.clone(),
|
||||
});
|
||||
response
|
||||
}
|
||||
}
|
||||
|
||||
/// Mechanical connector operations supplied by one process-wide runtime.
|
||||
#[async_trait]
|
||||
pub trait ConnectorRuntime: VirtualTcpSocketFactory + Send + Sync + 'static {
|
||||
fn supports_external_tunnel(&self, _scheme: &str) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
async fn connect_external_tunnel(
|
||||
&self,
|
||||
_url: &Url,
|
||||
) -> anyhow::Result<Option<Box<dyn crate::tunnel::Tunnel>>> {
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn connect_byte_stream(
|
||||
&self,
|
||||
url: &Url,
|
||||
) -> anyhow::Result<ConnectedByteStream<Self::Socket>>;
|
||||
|
||||
async fn local_addr_for_remote(
|
||||
&self,
|
||||
remote_addr: SocketAddr,
|
||||
context: SocketContext,
|
||||
) -> anyhow::Result<SocketAddr>;
|
||||
|
||||
async fn collect_ip_addrs(&self, context: &SocketContext) -> GetIpListResponse;
|
||||
|
||||
async fn preferred_ipv6_source(
|
||||
&self,
|
||||
ip: Ipv6Addr,
|
||||
context: SocketContext,
|
||||
) -> Option<PreferredIpv6Source>;
|
||||
}
|
||||
|
||||
/// Instance facts consumed by portable connector policy.
|
||||
///
|
||||
/// Socket creation, route probing and host interface I/O are deliberately
|
||||
/// absent; those belong to the process-wide [`ConnectorRuntime`].
|
||||
pub trait ConnectorEnvironment: Send + Sync + 'static {
|
||||
fn socket_context(&self) -> SocketContext;
|
||||
|
||||
fn mapped_listeners(&self) -> Vec<Url>;
|
||||
fn is_local_ip(&self, ip: &IpAddr) -> bool;
|
||||
}
|
||||
|
||||
/// Deep adapter that combines one socket runtime with one instance environment.
|
||||
pub struct ConnectorHostAdapter<S, E> {
|
||||
sockets: Arc<S>,
|
||||
environment: Arc<E>,
|
||||
interface_addrs: InterfaceAddrCache,
|
||||
}
|
||||
|
||||
impl<S, E> ConnectorHostAdapter<S, E> {
|
||||
pub fn new(sockets: Arc<S>, environment: Arc<E>) -> Self {
|
||||
Self {
|
||||
sockets,
|
||||
environment,
|
||||
interface_addrs: InterfaceAddrCache::new(INTERFACE_ADDR_CACHE_TTL),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<S, E> ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: ConnectorRuntime,
|
||||
{
|
||||
async fn cached_ip_addrs(&self, context: &SocketContext) -> GetIpListResponse {
|
||||
self.interface_addrs
|
||||
.get_or_collect(context, || self.sockets.collect_ip_addrs(context))
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S, E> VirtualTcpSocketFactory for ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: VirtualTcpSocketFactory,
|
||||
E: Send + Sync + 'static,
|
||||
{
|
||||
type Socket = S::Socket;
|
||||
|
||||
async fn connect_tcp(&self, options: TcpConnectOptions) -> anyhow::Result<Self::Socket> {
|
||||
self.sockets.connect_tcp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S, E> VirtualTcpListenerFactory for ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: VirtualTcpListenerFactory,
|
||||
E: Send + Sync + 'static,
|
||||
{
|
||||
type Listener = S::Listener;
|
||||
|
||||
async fn bind_tcp(&self, options: TcpListenOptions) -> anyhow::Result<Arc<Self::Listener>> {
|
||||
self.sockets.bind_tcp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S, E> VirtualUdpSocketFactory for ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: VirtualUdpSocketFactory,
|
||||
E: Send + Sync + 'static,
|
||||
{
|
||||
type Socket = S::Socket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.sockets.bind_udp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S, E> ManualConnectorHost for ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: ConnectorRuntime + VirtualUdpSocketFactory,
|
||||
E: ConnectorEnvironment,
|
||||
{
|
||||
fn supports_external_tunnel(&self, scheme: &str) -> bool {
|
||||
self.sockets.supports_external_tunnel(scheme)
|
||||
}
|
||||
|
||||
async fn connect_external_tunnel(
|
||||
&self,
|
||||
url: &Url,
|
||||
) -> anyhow::Result<Option<Box<dyn crate::tunnel::Tunnel>>> {
|
||||
self.sockets.connect_external_tunnel(url).await
|
||||
}
|
||||
|
||||
async fn local_addr_for_remote(
|
||||
&self,
|
||||
remote_addr: SocketAddr,
|
||||
context: SocketContext,
|
||||
) -> anyhow::Result<SocketAddr> {
|
||||
self.sockets
|
||||
.local_addr_for_remote(remote_addr, context)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn interface_addrs(&self) -> anyhow::Result<ManualInterfaceAddrs> {
|
||||
let addrs = self
|
||||
.cached_ip_addrs(&self.environment.socket_context())
|
||||
.await;
|
||||
Ok(ManualInterfaceAddrs {
|
||||
interface_ipv4s: addrs
|
||||
.interface_ipv4s
|
||||
.into_iter()
|
||||
.map(std::net::Ipv4Addr::from)
|
||||
.collect(),
|
||||
interface_ipv6s: addrs
|
||||
.interface_ipv6s
|
||||
.into_iter()
|
||||
.map(std::net::Ipv6Addr::from)
|
||||
.collect(),
|
||||
public_ipv6: addrs.public_ipv6.map(std::net::Ipv6Addr::from),
|
||||
})
|
||||
}
|
||||
|
||||
async fn connect_byte_stream(
|
||||
&self,
|
||||
url: &Url,
|
||||
) -> anyhow::Result<ConnectedByteStream<<Self as VirtualTcpSocketFactory>::Socket>> {
|
||||
self.sockets.connect_byte_stream(url).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<S, E> DirectConnectorHost for ConnectorHostAdapter<S, E>
|
||||
where
|
||||
S: ConnectorRuntime + VirtualUdpSocketFactory,
|
||||
E: ConnectorEnvironment,
|
||||
{
|
||||
async fn collect_ip_addrs(&self, context: &SocketContext) -> GetIpListResponse {
|
||||
self.cached_ip_addrs(context).await
|
||||
}
|
||||
|
||||
async fn collect_foreign_ip_addrs(&self, context: &SocketContext) -> GetIpListResponse {
|
||||
self.cached_ip_addrs(context).await
|
||||
}
|
||||
|
||||
fn mapped_listeners(&self) -> Vec<Url> {
|
||||
self.environment.mapped_listeners()
|
||||
}
|
||||
|
||||
fn is_local_ip(&self, ip: &IpAddr) -> bool {
|
||||
self.environment.is_local_ip(ip)
|
||||
}
|
||||
|
||||
async fn preferred_ipv6_source(
|
||||
&self,
|
||||
ip: Ipv6Addr,
|
||||
context: SocketContext,
|
||||
) -> Option<PreferredIpv6Source> {
|
||||
if !valid_public_ipv6_candidate(ip) {
|
||||
return None;
|
||||
}
|
||||
self.sockets.preferred_ipv6_source(ip, context).await
|
||||
}
|
||||
|
||||
async fn preferred_foreign_ipv6_source(
|
||||
&self,
|
||||
ip: Ipv6Addr,
|
||||
context: SocketContext,
|
||||
) -> Option<PreferredIpv6Source> {
|
||||
if !valid_public_ipv6_candidate(ip) {
|
||||
return None;
|
||||
}
|
||||
self.sockets.preferred_ipv6_source(ip, context).await
|
||||
}
|
||||
}
|
||||
|
||||
fn valid_public_ipv6_candidate(ip: Ipv6Addr) -> bool {
|
||||
!(ip.is_loopback()
|
||||
|| ip.is_unspecified()
|
||||
|| ip.is_unique_local()
|
||||
|| ip.is_unicast_link_local()
|
||||
|| ip.is_multicast())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use super::*;
|
||||
use crate::socket::{IpVersion, NetNamespace};
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_cache_misses_share_one_collection() {
|
||||
let cache = Arc::new(InterfaceAddrCache::new(Duration::from_secs(60)));
|
||||
let context = SocketContext::default();
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel();
|
||||
|
||||
let first = tokio::spawn({
|
||||
let cache = cache.clone();
|
||||
let context = context.clone();
|
||||
let calls = calls.clone();
|
||||
async move {
|
||||
cache
|
||||
.get_or_collect(&context, || async move {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
let _ = started_tx.send(());
|
||||
let _ = release_rx.await;
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
|
||||
let (second_started_tx, second_started_rx) = oneshot::channel();
|
||||
let second = tokio::spawn({
|
||||
let cache = cache.clone();
|
||||
let context = context.clone();
|
||||
let calls = calls.clone();
|
||||
async move {
|
||||
let _ = second_started_tx.send(());
|
||||
cache
|
||||
.get_or_collect(&context, || async move {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
second_started_rx.await.unwrap();
|
||||
tokio::task::yield_now().await;
|
||||
let _ = release_tx.send(());
|
||||
|
||||
first.await.unwrap();
|
||||
second.await.unwrap();
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cache_keys_include_the_complete_socket_context() {
|
||||
let cache = InterfaceAddrCache::new(Duration::from_secs(60));
|
||||
let calls = AtomicUsize::new(0);
|
||||
let contexts = [
|
||||
SocketContext::default(),
|
||||
SocketContext::default().with_ip_version(IpVersion::V4),
|
||||
SocketContext::default().with_socket_mark(Some(7)),
|
||||
SocketContext::default().with_netns(Some(NetNamespace::new("foreign-a"))),
|
||||
];
|
||||
|
||||
for context in &contexts {
|
||||
cache
|
||||
.get_or_collect(context, || async {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await;
|
||||
}
|
||||
cache
|
||||
.get_or_collect(&contexts[0], || async {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(calls.load(Ordering::SeqCst), contexts.len());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slow_collection_does_not_block_a_different_context() {
|
||||
let cache = Arc::new(InterfaceAddrCache::new(Duration::from_secs(60)));
|
||||
let slow_context = SocketContext::default().with_socket_mark(Some(1));
|
||||
let other_context = SocketContext::default().with_socket_mark(Some(2));
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel();
|
||||
let slow = tokio::spawn({
|
||||
let cache = cache.clone();
|
||||
async move {
|
||||
cache
|
||||
.get_or_collect(&slow_context, || async move {
|
||||
let _ = started_tx.send(());
|
||||
let _ = release_rx.await;
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(100),
|
||||
cache.get_or_collect(&other_context, || async { GetIpListResponse::default() }),
|
||||
)
|
||||
.await
|
||||
.expect("different socket contexts must collect independently");
|
||||
|
||||
let _ = release_tx.send(());
|
||||
slow.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn slow_collection_does_not_block_a_fresh_hit() {
|
||||
let cache = Arc::new(InterfaceAddrCache::new(Duration::from_secs(60)));
|
||||
let cached_context = SocketContext::default().with_socket_mark(Some(1));
|
||||
let slow_context = SocketContext::default().with_socket_mark(Some(2));
|
||||
cache
|
||||
.get_or_collect(&cached_context, || async { GetIpListResponse::default() })
|
||||
.await;
|
||||
|
||||
let (started_tx, started_rx) = oneshot::channel();
|
||||
let (release_tx, release_rx) = oneshot::channel();
|
||||
let slow = tokio::spawn({
|
||||
let cache = cache.clone();
|
||||
async move {
|
||||
cache
|
||||
.get_or_collect(&slow_context, || async move {
|
||||
let _ = started_tx.send(());
|
||||
let _ = release_rx.await;
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await
|
||||
}
|
||||
});
|
||||
started_rx.await.unwrap();
|
||||
|
||||
tokio::time::timeout(
|
||||
Duration::from_millis(100),
|
||||
cache.get_or_collect(&cached_context, || async {
|
||||
panic!("fresh cache hit must not recollect")
|
||||
}),
|
||||
)
|
||||
.await
|
||||
.expect("fresh hit must not wait for another socket context");
|
||||
|
||||
let _ = release_tx.send(());
|
||||
slow.await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn expired_entries_are_recollected() {
|
||||
let cache = InterfaceAddrCache::new(Duration::ZERO);
|
||||
let calls = AtomicUsize::new(0);
|
||||
let context = SocketContext::default();
|
||||
|
||||
for _ in 0..2 {
|
||||
cache
|
||||
.get_or_collect(&context, || async {
|
||||
calls.fetch_add(1, Ordering::SeqCst);
|
||||
GetIpListResponse::default()
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
assert_eq!(calls.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,797 @@
|
||||
//! Host-operation Adapter for the shared connector composition.
|
||||
//!
|
||||
//! This module was previously named `host`, which collided with the
|
||||
//! top-level [`crate::host`] layer, and one concept was split across two
|
||||
//! same-named `environment.rs` files. The ownership split is:
|
||||
//!
|
||||
//! - Mechanical environment queries implement
|
||||
//! [`crate::host::environment::HostConnectorEnvironmentIo`].
|
||||
//! - [`HostConnectorRuntime`] adapts host socket/listener factories and an
|
||||
//! injected environment snapshot to the shared connector runtime and
|
||||
//! environment traits.
|
||||
//! - [`HostConnectorEnvironmentSnapshot`] is connectivity's captured view of
|
||||
//! the host environment.
|
||||
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
connectivity::{
|
||||
composite::{ConnectorEnvironment, ConnectorHostAdapter, ConnectorRuntime},
|
||||
manual::ExternalTunnelConnector,
|
||||
transport::ConnectedByteStream,
|
||||
},
|
||||
host::environment::{HostConnectorEnvironmentIo, local_addr_for_remote},
|
||||
host::socket::{
|
||||
HostSocketRuntime, HostTcpStream,
|
||||
factory::{HostSocketBackend, HostSocketFactory},
|
||||
listener::{HostTcpListener, HostTcpListenerBackend, HostTcpListenerFactory},
|
||||
udp::HostUdpSocket,
|
||||
},
|
||||
proto::peer_rpc::GetIpListResponse,
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{
|
||||
TcpConnectOptions, TcpListenOptions, VirtualTcpListenerFactory, VirtualTcpSocketFactory,
|
||||
},
|
||||
udp::{PreferredIpv6Source, UdpBindOptions, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
/// Host-observed facts consumed by core connector policy.
|
||||
///
|
||||
/// The host normalizes this snapshot before constructing an instance. Core
|
||||
/// owns all selection and connection policy applied to these facts.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct HostConnectorEnvironmentSnapshot {
|
||||
pub public_ipv4: Option<Ipv4Addr>,
|
||||
pub interface_ipv4s: Vec<Ipv4Addr>,
|
||||
pub public_ipv6: Option<Ipv6Addr>,
|
||||
pub interface_ipv6s: Vec<Ipv6Addr>,
|
||||
pub mapped_listeners: Vec<Url>,
|
||||
pub local_ips: Vec<IpAddr>,
|
||||
pub protected_tcp_ports: Vec<u16>,
|
||||
pub preferred_ipv6_sources: Vec<PreferredIpv6Source>,
|
||||
}
|
||||
|
||||
impl HostConnectorEnvironmentSnapshot {
|
||||
fn ip_list(&self) -> GetIpListResponse {
|
||||
GetIpListResponse {
|
||||
public_ipv4: self.public_ipv4.map(Into::into),
|
||||
interface_ipv4s: self
|
||||
.interface_ipv4s
|
||||
.iter()
|
||||
.copied()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
public_ipv6: self.public_ipv6.map(Into::into),
|
||||
interface_ipv6s: self
|
||||
.interface_ipv6s
|
||||
.iter()
|
||||
.copied()
|
||||
.map(Into::into)
|
||||
.collect(),
|
||||
listeners: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn preferred_ipv6_source(&self, ip: Ipv6Addr) -> Option<PreferredIpv6Source> {
|
||||
if ip.is_loopback()
|
||||
|| ip.is_unspecified()
|
||||
|| ip.is_unique_local()
|
||||
|| ip.is_unicast_link_local()
|
||||
|| ip.is_multicast()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.preferred_ipv6_sources
|
||||
.iter()
|
||||
.find(|source| source.ip == ip)
|
||||
.copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// One host handle domain capable of creating and operating connector sockets.
|
||||
pub trait ConnectorHostSocketBackend: HostSocketBackend + HostTcpListenerBackend {}
|
||||
|
||||
impl<T> ConnectorHostSocketBackend for T where T: HostSocketBackend + HostTcpListenerBackend {}
|
||||
|
||||
/// Adapts mechanical host sockets and captured environment state to the
|
||||
/// shared connector composition.
|
||||
pub struct HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
socket_runtime: HostSocketRuntime,
|
||||
sockets: HostSocketFactory<B>,
|
||||
listeners: HostTcpListenerFactory<B>,
|
||||
environment: Arc<HostConnectorEnvironmentSnapshot>,
|
||||
environment_io: Arc<E>,
|
||||
external_tunnel_connector: Option<Arc<dyn ExternalTunnelConnector>>,
|
||||
}
|
||||
|
||||
impl<B, E> HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
pub fn new(
|
||||
runtime: HostSocketRuntime,
|
||||
backend: Arc<B>,
|
||||
environment: HostConnectorEnvironmentSnapshot,
|
||||
environment_io: Arc<E>,
|
||||
) -> Self {
|
||||
Self {
|
||||
socket_runtime: runtime.clone(),
|
||||
sockets: HostSocketFactory::new(runtime.clone(), backend.clone()),
|
||||
listeners: HostTcpListenerFactory::new(runtime, backend),
|
||||
environment: Arc::new(environment),
|
||||
environment_io,
|
||||
external_tunnel_connector: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_external_tunnel_connector(
|
||||
mut self,
|
||||
connector: Arc<dyn ExternalTunnelConnector>,
|
||||
) -> Self {
|
||||
self.external_tunnel_connector = Some(connector);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B, E> VirtualTcpSocketFactory for HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
type Socket = HostTcpStream;
|
||||
|
||||
async fn connect_tcp(&self, options: TcpConnectOptions) -> anyhow::Result<Self::Socket> {
|
||||
self.sockets.connect_tcp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B, E> VirtualUdpSocketFactory for HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
type Socket = HostUdpSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.sockets.bind_udp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B, E> VirtualTcpListenerFactory for HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
type Listener = HostTcpListener<B>;
|
||||
|
||||
async fn bind_tcp(&self, options: TcpListenOptions) -> anyhow::Result<Arc<Self::Listener>> {
|
||||
self.listeners.bind_tcp(options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<B, E> ConnectorRuntime for HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
fn supports_external_tunnel(&self, scheme: &str) -> bool {
|
||||
self.external_tunnel_connector
|
||||
.as_ref()
|
||||
.is_some_and(|connector| connector.supports_scheme(scheme))
|
||||
}
|
||||
|
||||
async fn connect_external_tunnel(
|
||||
&self,
|
||||
url: &Url,
|
||||
) -> anyhow::Result<Option<Box<dyn crate::tunnel::Tunnel>>> {
|
||||
let Some(connector) = &self.external_tunnel_connector else {
|
||||
return Ok(None);
|
||||
};
|
||||
if !connector.supports_scheme(url.scheme()) {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some(connector.connect(url).await?))
|
||||
}
|
||||
|
||||
async fn connect_byte_stream(
|
||||
&self,
|
||||
url: &Url,
|
||||
) -> anyhow::Result<ConnectedByteStream<Self::Socket>> {
|
||||
anyhow::bail!("host does not support external byte stream: {url}")
|
||||
}
|
||||
|
||||
async fn local_addr_for_remote(
|
||||
&self,
|
||||
remote_addr: SocketAddr,
|
||||
context: SocketContext,
|
||||
) -> anyhow::Result<SocketAddr> {
|
||||
local_addr_for_remote(
|
||||
&self.socket_runtime,
|
||||
self.environment_io.clone(),
|
||||
remote_addr,
|
||||
context,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn collect_ip_addrs(&self, _context: &SocketContext) -> GetIpListResponse {
|
||||
self.environment.ip_list()
|
||||
}
|
||||
|
||||
async fn preferred_ipv6_source(
|
||||
&self,
|
||||
ip: Ipv6Addr,
|
||||
_context: SocketContext,
|
||||
) -> Option<PreferredIpv6Source> {
|
||||
self.environment.preferred_ipv6_source(ip)
|
||||
}
|
||||
}
|
||||
|
||||
impl<B, E> ConnectorEnvironment for HostConnectorRuntime<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
fn socket_context(&self) -> SocketContext {
|
||||
SocketContext::default()
|
||||
}
|
||||
|
||||
fn mapped_listeners(&self) -> Vec<Url> {
|
||||
self.environment.mapped_listeners.clone()
|
||||
}
|
||||
|
||||
fn is_local_ip(&self, ip: &IpAddr) -> bool {
|
||||
self.environment.local_ips.contains(ip)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shared connector policy composed with a host-operation runtime.
|
||||
pub type ConnectorHost<B, E> =
|
||||
ConnectorHostAdapter<HostConnectorRuntime<B, E>, HostConnectorRuntime<B, E>>;
|
||||
|
||||
/// Builds the shared connector host over one host-operation backend.
|
||||
pub fn new_connector_host<B, E>(
|
||||
socket_runtime: HostSocketRuntime,
|
||||
backend: Arc<B>,
|
||||
environment: HostConnectorEnvironmentSnapshot,
|
||||
environment_io: Arc<E>,
|
||||
) -> ConnectorHost<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
let runtime = Arc::new(HostConnectorRuntime::new(
|
||||
socket_runtime,
|
||||
backend,
|
||||
environment,
|
||||
environment_io,
|
||||
));
|
||||
ConnectorHostAdapter::new(runtime.clone(), runtime)
|
||||
}
|
||||
|
||||
pub fn new_connector_host_with_external_tunnel<B, E>(
|
||||
socket_runtime: HostSocketRuntime,
|
||||
backend: Arc<B>,
|
||||
environment: HostConnectorEnvironmentSnapshot,
|
||||
environment_io: Arc<E>,
|
||||
connector: Arc<dyn ExternalTunnelConnector>,
|
||||
) -> ConnectorHost<B, E>
|
||||
where
|
||||
B: ConnectorHostSocketBackend,
|
||||
E: HostConnectorEnvironmentIo,
|
||||
{
|
||||
let runtime = Arc::new(
|
||||
HostConnectorRuntime::new(socket_runtime, backend, environment, environment_io)
|
||||
.with_external_tunnel_connector(connector),
|
||||
);
|
||||
ConnectorHostAdapter::new(runtime.clone(), runtime)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
task::Poll,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
connectivity::{
|
||||
direct::{DirectConnectorHost, DirectConnectorRpcHandler},
|
||||
hole_punch::tcp::TcpHolePunchHost,
|
||||
manual::ManualConnectorHost,
|
||||
stun::StunInfoProvider,
|
||||
},
|
||||
host::socket::{
|
||||
HostOperationId, HostSocketHandle, HostSocketIo, HostTcpIo,
|
||||
factory::{HostSocketFactoryIo, HostTcpConnectResult, HostUdpBindResult},
|
||||
listener::{HostTcpBindResult, HostTcpListenerIo},
|
||||
udp::{HostUdpDatagram, HostUdpIo},
|
||||
},
|
||||
proto::{
|
||||
common::StunInfo,
|
||||
peer_rpc::{DirectConnectorRpc as _, GetIpListRequest},
|
||||
rpc_types::controller::BaseController,
|
||||
},
|
||||
socket::udp::UdpSocketSendMeta,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
struct UnsupportedBackend {
|
||||
udp_send_attempts: Mutex<Vec<(Vec<u8>, SocketAddr, UdpSocketSendMeta)>>,
|
||||
reject_preferred_source: AtomicBool,
|
||||
}
|
||||
|
||||
struct FixedStunProvider;
|
||||
|
||||
struct ExternalFailingConnector;
|
||||
|
||||
#[async_trait]
|
||||
impl ExternalTunnelConnector for ExternalFailingConnector {
|
||||
fn supports_scheme(&self, scheme: &str) -> bool {
|
||||
scheme == "ws"
|
||||
}
|
||||
|
||||
async fn connect(&self, _url: &Url) -> anyhow::Result<Box<dyn crate::tunnel::Tunnel>> {
|
||||
anyhow::bail!("external connector called")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StunInfoProvider for FixedStunProvider {
|
||||
fn get_stun_info(&self) -> StunInfo {
|
||||
StunInfo {
|
||||
public_ip: vec!["198.51.100.7".to_owned(), "2001:db8::1".to_owned()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_udp_port_mapping(&self, _local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
anyhow::bail!("unused by direct RPC projection test")
|
||||
}
|
||||
|
||||
async fn get_tcp_port_mapping(&self, _local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
anyhow::bail!("unused by direct RPC projection test")
|
||||
}
|
||||
|
||||
fn update_stun_info(&self) {}
|
||||
}
|
||||
|
||||
fn unsupported<T>() -> io::Result<T> {
|
||||
Err(io::ErrorKind::Unsupported.into())
|
||||
}
|
||||
|
||||
impl HostSocketIo for UnsupportedBackend {
|
||||
fn cancel_operation(&self, _operation: HostOperationId) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close(&self, _handle: HostSocketHandle) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl HostTcpIo for UnsupportedBackend {
|
||||
fn submit_read(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
_operation: HostOperationId,
|
||||
_capacity: usize,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_read(&self, _operation: HostOperationId) -> Poll<io::Result<Vec<u8>>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
|
||||
fn submit_write(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
_operation: HostOperationId,
|
||||
_source: &[u8],
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_write(&self, _operation: HostOperationId) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
impl HostUdpIo for UnsupportedBackend {
|
||||
fn submit_recv(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
_operation: HostOperationId,
|
||||
_capacity: usize,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_recv(&self, _operation: HostOperationId) -> Poll<io::Result<HostUdpDatagram>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
|
||||
fn try_send(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
source: &[u8],
|
||||
peer_addr: SocketAddr,
|
||||
meta: UdpSocketSendMeta,
|
||||
) -> io::Result<()> {
|
||||
self.udp_send_attempts
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((source.to_vec(), peer_addr, meta));
|
||||
if self.reject_preferred_source.load(Ordering::Relaxed) && meta.src_ip.is_some() {
|
||||
return Err(io::ErrorKind::AddrNotAvailable.into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn submit_send_ready(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
_operation: HostOperationId,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_send_ready(&self, _operation: HostOperationId) -> Poll<io::Result<()>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
impl HostSocketFactoryIo for UnsupportedBackend {
|
||||
fn submit_tcp_connect(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
_options: &TcpConnectOptions,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_tcp_connect(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
) -> Poll<io::Result<HostTcpConnectResult>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
|
||||
fn submit_udp_bind(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
_options: &UdpBindOptions,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_udp_bind(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
) -> Poll<io::Result<HostUdpBindResult>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
impl HostTcpListenerIo for UnsupportedBackend {
|
||||
fn submit_tcp_bind(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
_options: &TcpListenOptions,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_tcp_bind(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
) -> Poll<io::Result<HostTcpBindResult>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
|
||||
fn submit_tcp_accept(
|
||||
&self,
|
||||
_handle: HostSocketHandle,
|
||||
_operation: HostOperationId,
|
||||
) -> io::Result<()> {
|
||||
unsupported()
|
||||
}
|
||||
|
||||
fn take_tcp_accept(
|
||||
&self,
|
||||
_operation: HostOperationId,
|
||||
) -> Poll<io::Result<HostTcpConnectResult>> {
|
||||
Poll::Ready(unsupported())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct TestEnvironmentIo {
|
||||
local_requests: Mutex<Vec<(SocketAddr, SocketContext)>>,
|
||||
ready: Mutex<Vec<HostOperationId>>,
|
||||
}
|
||||
|
||||
impl HostConnectorEnvironmentIo for TestEnvironmentIo {
|
||||
fn submit_local_addr_for_remote(
|
||||
&self,
|
||||
operation: HostOperationId,
|
||||
remote_addr: SocketAddr,
|
||||
context: &SocketContext,
|
||||
) -> io::Result<()> {
|
||||
self.local_requests
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((remote_addr, context.clone()));
|
||||
self.ready.lock().unwrap().push(operation);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn take_local_addr_for_remote(
|
||||
&self,
|
||||
operation: HostOperationId,
|
||||
) -> Poll<io::Result<SocketAddr>> {
|
||||
let mut ready = self.ready.lock().unwrap();
|
||||
let Some(index) = ready.iter().position(|candidate| *candidate == operation) else {
|
||||
return Poll::Pending;
|
||||
};
|
||||
ready.swap_remove(index);
|
||||
Poll::Ready(Ok("192.0.2.1:40100".parse().unwrap()))
|
||||
}
|
||||
|
||||
fn cancel_operation(&self, operation: HostOperationId) -> io::Result<()> {
|
||||
self.ready
|
||||
.lock()
|
||||
.unwrap()
|
||||
.retain(|candidate| *candidate != operation);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_environment_snapshot() -> HostConnectorEnvironmentSnapshot {
|
||||
HostConnectorEnvironmentSnapshot {
|
||||
interface_ipv4s: vec!["192.0.2.1".parse().unwrap()],
|
||||
public_ipv6: Some("2001:db8::1".parse().unwrap()),
|
||||
interface_ipv6s: vec!["2001:db8::1".parse().unwrap()],
|
||||
mapped_listeners: vec!["tcp://192.0.2.1:11010".parse().unwrap()],
|
||||
local_ips: vec!["192.0.2.1".parse().unwrap()],
|
||||
protected_tcp_ports: vec![11010],
|
||||
preferred_ipv6_sources: vec![PreferredIpv6Source {
|
||||
ip: "2001:db8::1".parse().unwrap(),
|
||||
ifindex: 7,
|
||||
}],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_core_host<H>()
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegates_connector_environment_without_owning_policy() {
|
||||
type TestHost = ConnectorHost<UnsupportedBackend, TestEnvironmentIo>;
|
||||
assert_core_host::<TestHost>();
|
||||
|
||||
let environment_io = Arc::new(TestEnvironmentIo::default());
|
||||
let host = new_connector_host(
|
||||
HostSocketRuntime::new(),
|
||||
Arc::new(UnsupportedBackend::default()),
|
||||
test_environment_snapshot(),
|
||||
environment_io.clone(),
|
||||
);
|
||||
let remote = "203.0.113.1:11010".parse().unwrap();
|
||||
let context = SocketContext::default().with_socket_mark(Some(7));
|
||||
let local = ManualConnectorHost::local_addr_for_remote(&host, remote, context.clone())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(local, "192.0.2.1:40100".parse().unwrap());
|
||||
assert_eq!(
|
||||
*environment_io.local_requests.lock().unwrap(),
|
||||
vec![(remote, context)]
|
||||
);
|
||||
assert_eq!(
|
||||
ManualConnectorHost::interface_addrs(&host)
|
||||
.await
|
||||
.unwrap()
|
||||
.public_ipv6,
|
||||
Some("2001:db8::1".parse().unwrap())
|
||||
);
|
||||
let byte_stream_error =
|
||||
match ManualConnectorHost::connect_byte_stream(&host, &"ring://42".parse().unwrap())
|
||||
.await
|
||||
{
|
||||
Ok(_) => panic!("test environment should reject byte streams"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert_eq!(
|
||||
byte_stream_error.to_string(),
|
||||
"host does not support external byte stream: ring://42"
|
||||
);
|
||||
assert_eq!(
|
||||
DirectConnectorHost::mapped_listeners(&host),
|
||||
vec!["tcp://192.0.2.1:11010".parse::<Url>().unwrap()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delegates_external_tunnel_connections() {
|
||||
let host = new_connector_host_with_external_tunnel(
|
||||
HostSocketRuntime::new(),
|
||||
Arc::new(UnsupportedBackend::default()),
|
||||
test_environment_snapshot(),
|
||||
Arc::new(TestEnvironmentIo::default()),
|
||||
Arc::new(ExternalFailingConnector),
|
||||
);
|
||||
|
||||
let error = ManualConnectorHost::connect_external_tunnel(
|
||||
&host,
|
||||
&"ws://relay.example/".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(error.to_string(), "external connector called");
|
||||
assert!(
|
||||
ManualConnectorHost::connect_external_tunnel(
|
||||
&host,
|
||||
&"tcp://relay.example:11010".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn direct_rpc_projects_host_observations_without_instance_policy() {
|
||||
let host = Arc::new(new_connector_host(
|
||||
HostSocketRuntime::new(),
|
||||
Arc::new(UnsupportedBackend::default()),
|
||||
test_environment_snapshot(),
|
||||
Arc::new(TestEnvironmentIo::default()),
|
||||
));
|
||||
let handler = DirectConnectorRpcHandler::new_with_stun(
|
||||
host,
|
||||
SocketContext::default().with_socket_mark(Some(7)),
|
||||
Some(Arc::new(FixedStunProvider)),
|
||||
);
|
||||
|
||||
let response = handler
|
||||
.get_ip_list(BaseController::default(), GetIpListRequest {})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.interface_ipv4s,
|
||||
vec![std::net::Ipv4Addr::new(192, 0, 2, 1).into()]
|
||||
);
|
||||
assert_eq!(
|
||||
response.interface_ipv6s,
|
||||
vec!["2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap().into()]
|
||||
);
|
||||
assert_eq!(
|
||||
response.public_ipv4,
|
||||
Some("198.51.100.7".parse::<std::net::Ipv4Addr>().unwrap().into())
|
||||
);
|
||||
assert_eq!(
|
||||
response.public_ipv6,
|
||||
Some("2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap().into())
|
||||
);
|
||||
assert_eq!(
|
||||
response
|
||||
.listeners
|
||||
.into_iter()
|
||||
.map(Url::from)
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["tcp://192.0.2.1:11010".parse::<Url>().unwrap()]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn foreign_direct_rpc_preserves_parent_managed_ipv6_addresses() {
|
||||
let host = Arc::new(new_connector_host(
|
||||
HostSocketRuntime::new(),
|
||||
Arc::new(UnsupportedBackend::default()),
|
||||
test_environment_snapshot(),
|
||||
Arc::new(TestEnvironmentIo::default()),
|
||||
));
|
||||
let handler = DirectConnectorRpcHandler::new_for_foreign_network_with_stun(
|
||||
host,
|
||||
SocketContext::default().with_socket_mark(Some(7)),
|
||||
Some(Arc::new(FixedStunProvider)),
|
||||
);
|
||||
|
||||
let response = handler
|
||||
.get_ip_list(BaseController::default(), GetIpListRequest {})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
response.interface_ipv6s,
|
||||
vec!["2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap().into()]
|
||||
);
|
||||
assert_eq!(
|
||||
response.public_ipv6,
|
||||
Some("2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap().into())
|
||||
);
|
||||
assert_eq!(
|
||||
response.public_ipv4,
|
||||
Some("198.51.100.7".parse::<std::net::Ipv4Addr>().unwrap().into())
|
||||
);
|
||||
}
|
||||
|
||||
fn snapshot() -> HostConnectorEnvironmentSnapshot {
|
||||
HostConnectorEnvironmentSnapshot {
|
||||
public_ipv4: Some("198.51.100.1".parse().unwrap()),
|
||||
interface_ipv4s: vec!["192.0.2.1".parse().unwrap()],
|
||||
public_ipv6: Some("2001:db8::1".parse().unwrap()),
|
||||
interface_ipv6s: vec!["2001:db8::2".parse().unwrap()],
|
||||
mapped_listeners: vec!["tcp://198.51.100.1:11010".parse().unwrap()],
|
||||
local_ips: vec!["192.0.2.1".parse().unwrap()],
|
||||
protected_tcp_ports: vec![11010],
|
||||
preferred_ipv6_sources: vec![
|
||||
PreferredIpv6Source {
|
||||
ip: "2001:db8::2".parse().unwrap(),
|
||||
ifindex: 7,
|
||||
},
|
||||
PreferredIpv6Source {
|
||||
ip: "fd00::1".parse().unwrap(),
|
||||
ifindex: 8,
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn projects_normalized_snapshot() {
|
||||
let snapshot = snapshot();
|
||||
assert_eq!(
|
||||
serde_json::from_slice::<HostConnectorEnvironmentSnapshot>(
|
||||
&serde_json::to_vec(&snapshot).unwrap()
|
||||
)
|
||||
.unwrap(),
|
||||
snapshot
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.ip_list().interface_ipv4s,
|
||||
vec![Ipv4Addr::new(192, 0, 2, 1).into()]
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.preferred_ipv6_source("2001:db8::2".parse().unwrap()),
|
||||
Some(PreferredIpv6Source {
|
||||
ip: "2001:db8::2".parse().unwrap(),
|
||||
ifindex: 7,
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
snapshot.preferred_ipv6_source("fd00::1".parse().unwrap()),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,21 @@
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
|
||||
use crate::{
|
||||
connectivity::transport::ConnectedUdpSession,
|
||||
socket::udp::{UdpSessionLayer, VirtualUdpSocketFactory},
|
||||
};
|
||||
|
||||
use super::DirectConnectorHost;
|
||||
|
||||
pub(super) async fn connect_with_socket<H>(
|
||||
host: Arc<H>,
|
||||
socket: Arc<<H as VirtualUdpSocketFactory>::Socket>,
|
||||
remote_addr: SocketAddr,
|
||||
) -> anyhow::Result<ConnectedUdpSession>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
let layer = Arc::new(UdpSessionLayer::new_with_stun_responder(socket, host));
|
||||
let session = layer.connect(remote_addr).await?;
|
||||
Ok(ConnectedUdpSession::new(session, layer))
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::peers::PeerConnectionOrigin;
|
||||
use crate::proto::rpc_types::{controller::BaseController, handler::Handler};
|
||||
use crate::tunnel::Tunnel;
|
||||
|
||||
mod peer_adapters;
|
||||
pub(crate) mod policy;
|
||||
pub mod port_mapping;
|
||||
pub(crate) mod tcp;
|
||||
pub(crate) mod udp;
|
||||
|
||||
/// Registration seam for hole-punch RPC services.
|
||||
///
|
||||
/// The engines build the proto-generated server wrapper around their RPC
|
||||
/// endpoint; the implementation owns the peer RPC registry and the network
|
||||
/// domain the service is registered under. Implemented only by the sealed
|
||||
/// peer adapter in `peer_adapters.rs`.
|
||||
pub(crate) trait HolePunchRpcRegistry: Send + Sync + 'static {
|
||||
fn register_rpc_service<H>(&self, service: H)
|
||||
where
|
||||
H: Handler<Controller = BaseController>;
|
||||
|
||||
fn unregister_rpc_service<H>(&self, service: H)
|
||||
where
|
||||
H: Handler<Controller = BaseController>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub(crate) trait HolePunchTunnelSink: Send + Sync + 'static {
|
||||
async fn add_client_tunnel(
|
||||
&self,
|
||||
tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()>;
|
||||
|
||||
async fn add_server_tunnel(
|
||||
&self,
|
||||
tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv6Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use quanta::Instant;
|
||||
|
||||
use crate::{
|
||||
config::{P2pPolicyFlags, PeerId},
|
||||
foundation::task::ExternalTaskSignal,
|
||||
peers::{PeerConnectionOrigin, peer_manager::PeerManagerCore},
|
||||
proto::{
|
||||
common::NatType,
|
||||
peer_rpc::{
|
||||
TcpHolePunchRpc, TcpHolePunchRpcClientFactory, UdpHolePunchRpc,
|
||||
UdpHolePunchRpcClientFactory,
|
||||
},
|
||||
rpc_types::{controller::BaseController, handler::Handler},
|
||||
},
|
||||
tunnel::Tunnel,
|
||||
};
|
||||
|
||||
use super::{
|
||||
HolePunchRpcRegistry, HolePunchTunnelSink,
|
||||
tcp::{TcpHolePunchPeerSource, TcpPunchCandidate},
|
||||
udp::{UdpHolePunchPeerSource, UdpHolePunchRpcSource, UdpPunchCandidate},
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
impl UdpHolePunchPeerSource for PeerManagerCore {
|
||||
fn local_peer_id(&self) -> PeerId {
|
||||
PeerManagerCore::my_peer_id(self)
|
||||
}
|
||||
|
||||
fn p2p_policy_flags(&self) -> P2pPolicyFlags {
|
||||
PeerManagerCore::p2p_policy_flags(self)
|
||||
}
|
||||
|
||||
async fn candidates(&self) -> Vec<UdpPunchCandidate> {
|
||||
let now = Instant::now();
|
||||
let peer_map = self.get_peer_map();
|
||||
self.list_route_snapshots()
|
||||
.await
|
||||
.into_iter()
|
||||
.filter_map(|route| {
|
||||
let udp_nat_type = route
|
||||
.stun_info
|
||||
.as_ref()
|
||||
.map(|info| info.udp_nat_type)
|
||||
.unwrap_or_default();
|
||||
let Ok(udp_nat_type) = crate::proto::common::NatType::try_from(udp_nat_type) else {
|
||||
return None;
|
||||
};
|
||||
Some(UdpPunchCandidate {
|
||||
peer_id: route.peer_id,
|
||||
udp_nat_type,
|
||||
feature_flag: route.feature_flag,
|
||||
has_direct_connection: peer_map.has_peer(route.peer_id),
|
||||
has_recent_traffic: self.has_recent_traffic(route.peer_id, now),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn p2p_demand_notify(&self) -> Arc<ExternalTaskSignal> {
|
||||
PeerManagerCore::p2p_demand_notify(self)
|
||||
}
|
||||
|
||||
fn is_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
PeerManagerCore::is_local_virtual_ip(self, ip)
|
||||
}
|
||||
|
||||
async fn is_easytier_managed_ipv6(&self, ip: &Ipv6Addr) -> bool {
|
||||
PeerManagerCore::is_easytier_managed_ipv6(self, ip).await
|
||||
}
|
||||
}
|
||||
|
||||
impl UdpHolePunchRpcSource for PeerManagerCore {
|
||||
fn local_peer_id(&self) -> PeerId {
|
||||
PeerManagerCore::my_peer_id(self)
|
||||
}
|
||||
|
||||
fn rpc_stub(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
) -> Box<dyn UdpHolePunchRpc<Controller = BaseController> + Send + Sync + 'static> {
|
||||
PeerManagerCore::get_peer_rpc_mgr(self)
|
||||
.rpc_client()
|
||||
.scoped_client::<UdpHolePunchRpcClientFactory<BaseController>>(
|
||||
PeerManagerCore::my_peer_id(self),
|
||||
dst_peer_id,
|
||||
PeerManagerCore::network_name(self).to_owned(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HolePunchTunnelSink for PeerManagerCore {
|
||||
async fn add_client_tunnel(
|
||||
&self,
|
||||
tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()> {
|
||||
self.add_client_tunnel_with_peer_id_hint(tunnel, origin, None)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(anyhow::Error::from)
|
||||
}
|
||||
|
||||
async fn add_server_tunnel(
|
||||
&self,
|
||||
tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()> {
|
||||
self.add_tunnel_as_server_with_origin(tunnel, origin)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(anyhow::Error::from)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TcpHolePunchPeerSource for PeerManagerCore {
|
||||
fn local_peer_id(&self) -> PeerId {
|
||||
PeerManagerCore::my_peer_id(self)
|
||||
}
|
||||
|
||||
fn p2p_policy_flags(&self) -> P2pPolicyFlags {
|
||||
PeerManagerCore::p2p_policy_flags(self)
|
||||
}
|
||||
|
||||
fn tcp_hole_punching_disabled(&self) -> bool {
|
||||
PeerManagerCore::tcp_hole_punching_disabled(self)
|
||||
}
|
||||
|
||||
fn p2p_demand_notify(&self) -> Arc<ExternalTaskSignal> {
|
||||
PeerManagerCore::p2p_demand_notify(self)
|
||||
}
|
||||
|
||||
async fn candidates(&self) -> Vec<TcpPunchCandidate> {
|
||||
let now = Instant::now();
|
||||
let peer_map = self.get_peer_map();
|
||||
self.list_route_snapshots()
|
||||
.await
|
||||
.into_iter()
|
||||
.map(|route| TcpPunchCandidate {
|
||||
peer_id: route.peer_id,
|
||||
tcp_nat_type: route
|
||||
.stun_info
|
||||
.as_ref()
|
||||
.map(|info| info.tcp_nat_type)
|
||||
.and_then(|nat_type| NatType::try_from(nat_type).ok())
|
||||
.unwrap_or(NatType::Unknown),
|
||||
feature_flag: route.feature_flag,
|
||||
has_direct_connection: peer_map.has_peer(route.peer_id),
|
||||
has_recent_traffic: self.has_recent_traffic(route.peer_id, now),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn rpc_stub(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
) -> Box<dyn TcpHolePunchRpc<Controller = BaseController> + Send + Sync + 'static> {
|
||||
PeerManagerCore::get_peer_rpc_mgr(self)
|
||||
.rpc_client()
|
||||
.scoped_client::<TcpHolePunchRpcClientFactory<BaseController>>(
|
||||
PeerManagerCore::my_peer_id(self),
|
||||
dst_peer_id,
|
||||
PeerManagerCore::network_name(self).to_owned(),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HolePunchRpcRegistry for PeerManagerCore {
|
||||
fn register_rpc_service<H>(&self, service: H)
|
||||
where
|
||||
H: Handler<Controller = BaseController>,
|
||||
{
|
||||
PeerManagerCore::get_peer_rpc_mgr(self)
|
||||
.rpc_server()
|
||||
.registry()
|
||||
.register(service, PeerManagerCore::network_name(self));
|
||||
}
|
||||
|
||||
fn unregister_rpc_service<H>(&self, service: H)
|
||||
where
|
||||
H: Handler<Controller = BaseController>,
|
||||
{
|
||||
PeerManagerCore::get_peer_rpc_mgr(self)
|
||||
.rpc_server()
|
||||
.registry()
|
||||
.unregister(service, PeerManagerCore::network_name(self));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
use crate::proto::common::PeerFeatureFlag;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct BackOff {
|
||||
backoffs_ms: Vec<u64>,
|
||||
current_idx: usize,
|
||||
}
|
||||
|
||||
impl BackOff {
|
||||
pub fn new(backoffs_ms: Vec<u64>) -> Self {
|
||||
Self {
|
||||
backoffs_ms,
|
||||
current_idx: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn next_backoff(&mut self) -> u64 {
|
||||
let backoff = self.backoffs_ms[self.current_idx];
|
||||
self.current_idx = (self.current_idx + 1).min(self.backoffs_ms.len() - 1);
|
||||
backoff
|
||||
}
|
||||
|
||||
pub fn rollback(&mut self) {
|
||||
self.current_idx = self.current_idx.saturating_sub(1);
|
||||
}
|
||||
|
||||
pub async fn sleep_for_next_backoff(&mut self) {
|
||||
let backoff = self.next_backoff();
|
||||
if backoff > 0 {
|
||||
crate::foundation::time::sleep(crate::foundation::time::Duration::from_millis(backoff))
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn should_try_p2p_with_peer(
|
||||
feature_flag: Option<&PeerFeatureFlag>,
|
||||
allow_public_server: bool,
|
||||
local_disable_p2p: bool,
|
||||
local_need_p2p: bool,
|
||||
) -> bool {
|
||||
feature_flag
|
||||
.map(|flag| {
|
||||
(allow_public_server || !flag.is_public_server)
|
||||
&& (!local_disable_p2p || flag.need_p2p)
|
||||
&& (!flag.disable_p2p || local_need_p2p)
|
||||
})
|
||||
.unwrap_or(!local_disable_p2p)
|
||||
}
|
||||
|
||||
pub fn should_background_p2p_with_peer(
|
||||
feature_flag: Option<&PeerFeatureFlag>,
|
||||
allow_public_server: bool,
|
||||
lazy_p2p: bool,
|
||||
local_disable_p2p: bool,
|
||||
local_need_p2p: bool,
|
||||
) -> bool {
|
||||
should_try_p2p_with_peer(
|
||||
feature_flag,
|
||||
allow_public_server,
|
||||
local_disable_p2p,
|
||||
local_need_p2p,
|
||||
) && (!lazy_p2p || feature_flag.map(|flag| flag.need_p2p).unwrap_or(false))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn backoff_saturates_and_can_rollback() {
|
||||
let mut backoff = BackOff::new(vec![10, 20]);
|
||||
|
||||
assert_eq!(backoff.next_backoff(), 10);
|
||||
assert_eq!(backoff.next_backoff(), 20);
|
||||
assert_eq!(backoff.next_backoff(), 20);
|
||||
backoff.rollback();
|
||||
assert_eq!(backoff.next_backoff(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_background_p2p_requires_need_p2p() {
|
||||
let no_need_p2p = PeerFeatureFlag {
|
||||
need_p2p: false,
|
||||
..Default::default()
|
||||
};
|
||||
let need_p2p = PeerFeatureFlag {
|
||||
need_p2p: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(should_background_p2p_with_peer(
|
||||
Some(&no_need_p2p),
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(!should_background_p2p_with_peer(
|
||||
Some(&no_need_p2p),
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(should_background_p2p_with_peer(
|
||||
Some(&need_p2p),
|
||||
false,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn p2p_policy_respects_public_server_setting() {
|
||||
let public_server = PeerFeatureFlag {
|
||||
is_public_server: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(!should_try_p2p_with_peer(
|
||||
Some(&public_server),
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(should_try_p2p_with_peer(
|
||||
Some(&public_server),
|
||||
true,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(!should_background_p2p_with_peer(
|
||||
Some(&public_server),
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(should_background_p2p_with_peer(
|
||||
Some(&public_server),
|
||||
true,
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disable_p2p_only_allows_need_p2p_exceptions() {
|
||||
let normal_peer = PeerFeatureFlag::default();
|
||||
let need_peer = PeerFeatureFlag {
|
||||
need_p2p: true,
|
||||
..Default::default()
|
||||
};
|
||||
let disable_peer = PeerFeatureFlag {
|
||||
disable_p2p: true,
|
||||
..Default::default()
|
||||
};
|
||||
let disable_need_peer = PeerFeatureFlag {
|
||||
disable_p2p: true,
|
||||
need_p2p: true,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
assert!(should_try_p2p_with_peer(
|
||||
Some(&normal_peer),
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(should_try_p2p_with_peer(None, false, false, false));
|
||||
assert!(!should_try_p2p_with_peer(None, false, true, false));
|
||||
assert!(!should_try_p2p_with_peer(
|
||||
Some(&normal_peer),
|
||||
false,
|
||||
true,
|
||||
false
|
||||
));
|
||||
assert!(should_try_p2p_with_peer(
|
||||
Some(&need_peer),
|
||||
false,
|
||||
true,
|
||||
false
|
||||
));
|
||||
assert!(!should_try_p2p_with_peer(
|
||||
Some(&disable_peer),
|
||||
false,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(should_try_p2p_with_peer(
|
||||
Some(&disable_peer),
|
||||
false,
|
||||
false,
|
||||
true
|
||||
));
|
||||
assert!(should_try_p2p_with_peer(
|
||||
Some(&disable_need_peer),
|
||||
false,
|
||||
true,
|
||||
true
|
||||
));
|
||||
assert!(!should_try_p2p_with_peer(
|
||||
Some(&disable_need_peer),
|
||||
false,
|
||||
true,
|
||||
false
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
use std::{
|
||||
fmt,
|
||||
future::Future,
|
||||
net::{Ipv4Addr, SocketAddr},
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
use crate::events::{CoreEvent, CoreEventSink};
|
||||
|
||||
const UPNP_RENEW_INTERVAL: Duration = Duration::from_secs(240);
|
||||
|
||||
pub(crate) trait UdpPortMappingLease: Send + Sync + fmt::Debug {
|
||||
fn public_addr_resolved(&self, _mapped_addr: SocketAddr) {}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UdpPortMappingBackend {
|
||||
Igd,
|
||||
NatPmp,
|
||||
}
|
||||
|
||||
impl UdpPortMappingBackend {
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
Self::Igd => "igd",
|
||||
Self::NatPmp => "nat-pmp",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UdpPortMappingAttemptPhase {
|
||||
Discovery,
|
||||
Establishment,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UdpPortMappingAttemptError {
|
||||
phase: UdpPortMappingAttemptPhase,
|
||||
source: anyhow::Error,
|
||||
}
|
||||
|
||||
impl UdpPortMappingAttemptError {
|
||||
pub fn discovery(source: impl Into<anyhow::Error>) -> Self {
|
||||
Self {
|
||||
phase: UdpPortMappingAttemptPhase::Discovery,
|
||||
source: source.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn establishment(source: impl Into<anyhow::Error>) -> Self {
|
||||
Self {
|
||||
phase: UdpPortMappingAttemptPhase::Establishment,
|
||||
source: source.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn phase(&self) -> UdpPortMappingAttemptPhase {
|
||||
self.phase
|
||||
}
|
||||
|
||||
pub(crate) fn source(&self) -> &anyhow::Error {
|
||||
&self.source
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for UdpPortMappingAttemptError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.source.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for UdpPortMappingAttemptError {
|
||||
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
|
||||
Some(self.source.as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ActiveUdpPortMapping: Send + Sync + fmt::Debug {
|
||||
fn backend(&self) -> UdpPortMappingBackend;
|
||||
|
||||
fn local_addr(&self) -> SocketAddr;
|
||||
|
||||
fn gateway_external_port(&self) -> u16;
|
||||
|
||||
async fn renew(&self) -> anyhow::Result<()>;
|
||||
|
||||
async fn remove(&self) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
pub type UdpPortMappingLifecycle = Pin<Box<dyn Future<Output = ()> + Send + 'static>>;
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpPortMappingPlatform: Send + Sync + 'static {
|
||||
async fn establish_udp_port_mapping(
|
||||
&self,
|
||||
backend: UdpPortMappingBackend,
|
||||
local_listener: &url::Url,
|
||||
) -> Result<Box<dyn ActiveUdpPortMapping>, UdpPortMappingAttemptError>;
|
||||
|
||||
fn spawn_udp_port_mapping_lifecycle(
|
||||
&self,
|
||||
_local_listener: url::Url,
|
||||
lifecycle: UdpPortMappingLifecycle,
|
||||
) {
|
||||
tokio::spawn(lifecycle);
|
||||
}
|
||||
}
|
||||
|
||||
struct ManagedUdpPortMappingLease {
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
local_listener: url::Url,
|
||||
backend: UdpPortMappingBackend,
|
||||
gateway_external_port: u16,
|
||||
stop_tx: Option<oneshot::Sender<()>>,
|
||||
}
|
||||
|
||||
impl fmt::Debug for ManagedUdpPortMappingLease {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.debug_struct("UdpPortMappingLease")
|
||||
.field("backend", &self.backend.name())
|
||||
.field("gateway_external_port", &self.gateway_external_port)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ManagedUdpPortMappingLease {
|
||||
fn drop(&mut self) {
|
||||
if let Some(stop_tx) = self.stop_tx.take() {
|
||||
let _ = stop_tx.send(());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UdpPortMappingLease for ManagedUdpPortMappingLease {
|
||||
fn public_addr_resolved(&self, mapped_addr: SocketAddr) {
|
||||
self.events.emit(CoreEvent::UdpPortMappingEstablished {
|
||||
local_listener: self.local_listener.clone(),
|
||||
mapped_listener: udp_url(mapped_addr),
|
||||
backend: self.backend.name().to_owned(),
|
||||
});
|
||||
tracing::info!(
|
||||
local_listener = %self.local_listener,
|
||||
backend = self.backend.name(),
|
||||
gateway_external_port = self.gateway_external_port,
|
||||
stun_mapped_addr = %mapped_addr,
|
||||
"udp public addr resolved after port mapping"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start_udp_port_mapping(
|
||||
platform: Arc<dyn UdpPortMappingPlatform>,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
local_listener: &url::Url,
|
||||
) -> anyhow::Result<Option<Box<dyn UdpPortMappingLease>>> {
|
||||
if !should_map_udp_listener(local_listener) {
|
||||
return Ok(None);
|
||||
}
|
||||
|
||||
let mapping = discover_udp_port_mapping(platform.as_ref(), local_listener).await?;
|
||||
let backend = mapping.backend();
|
||||
let gateway_external_port = mapping.gateway_external_port();
|
||||
tracing::info!(
|
||||
%local_listener,
|
||||
backend = backend.name(),
|
||||
local_addr = %mapping.local_addr(),
|
||||
gateway_external_port,
|
||||
"udp port mapping established"
|
||||
);
|
||||
|
||||
let (stop_tx, stop_rx) = oneshot::channel();
|
||||
platform.spawn_udp_port_mapping_lifecycle(
|
||||
local_listener.clone(),
|
||||
Box::pin(run_udp_port_mapping_lifecycle(
|
||||
local_listener.clone(),
|
||||
mapping,
|
||||
stop_rx,
|
||||
)),
|
||||
);
|
||||
|
||||
Ok(Some(Box::new(ManagedUdpPortMappingLease {
|
||||
events,
|
||||
local_listener: local_listener.clone(),
|
||||
backend,
|
||||
gateway_external_port,
|
||||
stop_tx: Some(stop_tx),
|
||||
})))
|
||||
}
|
||||
|
||||
async fn discover_udp_port_mapping(
|
||||
platform: &dyn UdpPortMappingPlatform,
|
||||
local_listener: &url::Url,
|
||||
) -> anyhow::Result<Box<dyn ActiveUdpPortMapping>> {
|
||||
let igd_error = match platform
|
||||
.establish_udp_port_mapping(UdpPortMappingBackend::Igd, local_listener)
|
||||
.await
|
||||
{
|
||||
Ok(mapping) => return Ok(mapping),
|
||||
Err(error) => error,
|
||||
};
|
||||
match igd_error.phase() {
|
||||
UdpPortMappingAttemptPhase::Discovery => tracing::debug!(
|
||||
igd_err = ?igd_error.source(),
|
||||
%local_listener,
|
||||
"igd gateway discovery failed, retry with nat-pmp"
|
||||
),
|
||||
UdpPortMappingAttemptPhase::Establishment => tracing::debug!(
|
||||
igd_err = ?igd_error.source(),
|
||||
%local_listener,
|
||||
"igd udp port mapping failed, retry with nat-pmp"
|
||||
),
|
||||
}
|
||||
|
||||
match platform
|
||||
.establish_udp_port_mapping(UdpPortMappingBackend::NatPmp, local_listener)
|
||||
.await
|
||||
{
|
||||
Ok(mapping) => Ok(mapping),
|
||||
Err(nat_pmp_error) => Err(combined_mapping_error(
|
||||
local_listener,
|
||||
igd_error,
|
||||
nat_pmp_error,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn combined_mapping_error(
|
||||
local_listener: &url::Url,
|
||||
igd_error: UdpPortMappingAttemptError,
|
||||
nat_pmp_error: UdpPortMappingAttemptError,
|
||||
) -> anyhow::Error {
|
||||
let igd_label = match igd_error.phase() {
|
||||
UdpPortMappingAttemptPhase::Discovery => "igd discovery error",
|
||||
UdpPortMappingAttemptPhase::Establishment => "igd error",
|
||||
};
|
||||
let nat_pmp_label = match nat_pmp_error.phase() {
|
||||
UdpPortMappingAttemptPhase::Discovery => "nat-pmp discovery error",
|
||||
UdpPortMappingAttemptPhase::Establishment => "nat-pmp error",
|
||||
};
|
||||
anyhow::anyhow!(
|
||||
"udp port mapping failed for {local_listener}: {igd_label}: {}; {nat_pmp_label}: {}",
|
||||
igd_error.source(),
|
||||
nat_pmp_error.source(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn run_udp_port_mapping_lifecycle(
|
||||
local_listener: url::Url,
|
||||
mapping: Box<dyn ActiveUdpPortMapping>,
|
||||
mut stop_rx: oneshot::Receiver<()>,
|
||||
) {
|
||||
loop {
|
||||
tokio::select! {
|
||||
_ = crate::foundation::time::sleep(UPNP_RENEW_INTERVAL) => {
|
||||
if let Err(error) = mapping.renew().await {
|
||||
tracing::warn!(
|
||||
err = ?error,
|
||||
%local_listener,
|
||||
backend = mapping.backend().name(),
|
||||
gateway_external_port = mapping.gateway_external_port(),
|
||||
"failed to renew udp port mapping"
|
||||
);
|
||||
}
|
||||
}
|
||||
_ = &mut stop_rx => break,
|
||||
}
|
||||
}
|
||||
|
||||
if let Err(error) = mapping.remove().await {
|
||||
tracing::debug!(
|
||||
err = ?error,
|
||||
%local_listener,
|
||||
backend = mapping.backend().name(),
|
||||
gateway_external_port = mapping.gateway_external_port(),
|
||||
"failed to remove udp port mapping"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn should_map_udp_listener(local_listener: &url::Url) -> bool {
|
||||
if local_listener.scheme() != "udp" {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Some(host) = listener_ipv4_host(local_listener) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if host.is_loopback() || host.is_broadcast() {
|
||||
return false;
|
||||
}
|
||||
|
||||
host.is_unspecified() || host.is_private() || host.is_link_local()
|
||||
}
|
||||
|
||||
fn listener_ipv4_host(local_listener: &url::Url) -> Option<Ipv4Addr> {
|
||||
local_listener.host_str()?.parse().ok()
|
||||
}
|
||||
|
||||
fn udp_url(addr: SocketAddr) -> url::Url {
|
||||
let mut url = url::Url::parse("udp://0.0.0.0").expect("static UDP URL should be valid");
|
||||
url.set_ip_host(addr.ip())
|
||||
.expect("socket IP should be a valid URL host");
|
||||
url.set_port(Some(addr.port()))
|
||||
.expect("UDP URL should accept a port");
|
||||
url
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MockMapping {
|
||||
backend: UdpPortMappingBackend,
|
||||
removals: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ActiveUdpPortMapping for MockMapping {
|
||||
fn backend(&self) -> UdpPortMappingBackend {
|
||||
self.backend
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> SocketAddr {
|
||||
"192.168.1.5:11010".parse().unwrap()
|
||||
}
|
||||
|
||||
fn gateway_external_port(&self) -> u16 {
|
||||
41010
|
||||
}
|
||||
|
||||
async fn renew(&self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove(&self) -> anyhow::Result<()> {
|
||||
self.removals.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct MockPlatform {
|
||||
attempts: Mutex<Vec<UdpPortMappingBackend>>,
|
||||
igd_phase: Option<UdpPortMappingAttemptPhase>,
|
||||
removals: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UdpPortMappingPlatform for MockPlatform {
|
||||
async fn establish_udp_port_mapping(
|
||||
&self,
|
||||
backend: UdpPortMappingBackend,
|
||||
_local_listener: &url::Url,
|
||||
) -> Result<Box<dyn ActiveUdpPortMapping>, UdpPortMappingAttemptError> {
|
||||
self.attempts.lock().unwrap().push(backend);
|
||||
if backend == UdpPortMappingBackend::Igd
|
||||
&& let Some(phase) = self.igd_phase
|
||||
{
|
||||
return Err(match phase {
|
||||
UdpPortMappingAttemptPhase::Discovery => {
|
||||
UdpPortMappingAttemptError::discovery(anyhow::anyhow!("no igd"))
|
||||
}
|
||||
UdpPortMappingAttemptPhase::Establishment => {
|
||||
UdpPortMappingAttemptError::establishment(anyhow::anyhow!("igd denied"))
|
||||
}
|
||||
});
|
||||
}
|
||||
Ok(Box::new(MockMapping {
|
||||
backend,
|
||||
removals: self.removals.clone(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapping_requires_private_or_unspecified_ipv4_listener() {
|
||||
assert!(should_map_udp_listener(
|
||||
&"udp://0.0.0.0:11010".parse().unwrap()
|
||||
));
|
||||
assert!(should_map_udp_listener(
|
||||
&"udp://192.168.1.10:11010".parse().unwrap()
|
||||
));
|
||||
assert!(!should_map_udp_listener(
|
||||
&"udp://127.0.0.1:11010".parse().unwrap()
|
||||
));
|
||||
assert!(!should_map_udp_listener(
|
||||
&"udp://8.8.8.8:11010".parse().unwrap()
|
||||
));
|
||||
assert!(!should_map_udp_listener(
|
||||
&"tcp://0.0.0.0:11010".parse().unwrap()
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_from_igd_to_nat_pmp_and_removes_on_drop() {
|
||||
let removals = Arc::new(AtomicUsize::new(0));
|
||||
let platform = Arc::new(MockPlatform {
|
||||
attempts: Mutex::new(Vec::new()),
|
||||
igd_phase: Some(UdpPortMappingAttemptPhase::Discovery),
|
||||
removals: removals.clone(),
|
||||
});
|
||||
|
||||
let lease = start_udp_port_mapping(
|
||||
platform.clone(),
|
||||
Arc::new(()),
|
||||
&"udp://0.0.0.0:11010".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
*platform.attempts.lock().unwrap(),
|
||||
vec![UdpPortMappingBackend::Igd, UdpPortMappingBackend::NatPmp]
|
||||
);
|
||||
|
||||
drop(lease);
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while removals.load(Ordering::SeqCst) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(removals.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,802 @@
|
||||
//! Core-owned UDP hole-punch socket/session runtime.
|
||||
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
use anyhow::Context as _;
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{
|
||||
connectivity::{
|
||||
direct::DirectConnectorHost,
|
||||
hole_punch::port_mapping::{UdpPortMappingPlatform, start_udp_port_mapping},
|
||||
hole_punch::{HolePunchRpcRegistry, HolePunchTunnelSink},
|
||||
protocol::ClientProtocolUpgrader,
|
||||
stun::{StunInfoProvider, StunSocketMapper},
|
||||
},
|
||||
proto::peer_rpc::UdpHolePunchRpcServer,
|
||||
socket::{
|
||||
IpVersion, ListenerConnectionCounter, SocketContext,
|
||||
tcp::VirtualTcpSocketFactory,
|
||||
udp::{
|
||||
UdpBindOptions, UdpSessionLayer, UdpSessionSocket, UdpSessionStunResponder,
|
||||
VirtualUdpSocket, VirtualUdpSocketFactory,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
ProtocolUdpHolePunchTransportSink, UdpHolePunchConnector, UdpHolePunchPeerSource,
|
||||
UdpHolePunchRuntime, UdpPunchAcceptor, UdpPunchListener, UdpPunchSocket, UdpResolvedPublicAddr,
|
||||
UdpSymPunchLock,
|
||||
rpc::{PeerRpcUdpHolePunchSignaling, UdpHolePunchRpcEndpoint, UdpHolePunchRpcSource},
|
||||
};
|
||||
|
||||
async fn resolve_public_addr_with_policy<S>(
|
||||
stun: &dyn StunSocketMapper<S>,
|
||||
platform: Option<Arc<dyn UdpPortMappingPlatform>>,
|
||||
events: Arc<dyn crate::events::CoreEventSink>,
|
||||
socket: Arc<S>,
|
||||
local_listener: &url::Url,
|
||||
disable_upnp: bool,
|
||||
) -> anyhow::Result<UdpResolvedPublicAddr>
|
||||
where
|
||||
S: VirtualUdpSocket + 'static,
|
||||
{
|
||||
let port_mapping_lease = if disable_upnp {
|
||||
None
|
||||
} else if let Some(platform) = platform {
|
||||
match start_udp_port_mapping(platform, events, local_listener).await {
|
||||
Ok(lease) => lease,
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
?error,
|
||||
%local_listener,
|
||||
"failed to establish udp port mapping, fallback to stun-only public addr resolution"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let mapped_addr = stun
|
||||
.get_udp_port_mapping_with_socket(socket)
|
||||
.await
|
||||
.with_context(|| format!("resolve udp public addr for {local_listener}"))?;
|
||||
if let Some(lease) = &port_mapping_lease {
|
||||
lease.public_addr_resolved(mapped_addr);
|
||||
} else {
|
||||
tracing::debug!(
|
||||
%local_listener,
|
||||
stun_mapped_addr = %mapped_addr,
|
||||
"udp public addr resolved without port mapping"
|
||||
);
|
||||
}
|
||||
|
||||
Ok(UdpResolvedPublicAddr {
|
||||
mapped_addr,
|
||||
port_mapping_lease,
|
||||
})
|
||||
}
|
||||
|
||||
fn managed_local_addr_error(
|
||||
local_addr: SocketAddr,
|
||||
is_local_virtual_ipv4: bool,
|
||||
is_easytier_managed_ipv6: bool,
|
||||
) -> Option<&'static str> {
|
||||
match local_addr.ip() {
|
||||
IpAddr::V4(_) if is_local_virtual_ipv4 => Some("local address is virtual ipv4"),
|
||||
IpAddr::V6(_) if is_easytier_managed_ipv6 => Some("local address is easytier-managed ipv6"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
type HostUdpSocket<H> = <H as VirtualUdpSocketFactory>::Socket;
|
||||
type HostTcpSocket<H> = <H as VirtualTcpSocketFactory>::Socket;
|
||||
type CoreUdpSessionLayer<H> = UdpSessionLayer<HostUdpSocket<H>, H>;
|
||||
type CoreUdpHolePunchTransportSink<H, P> = ProtocolUdpHolePunchTransportSink<HostTcpSocket<H>, P>;
|
||||
type CoreUdpHolePunchConnector<H, P> = UdpHolePunchConnector<
|
||||
P,
|
||||
PeerRpcUdpHolePunchSignaling<P>,
|
||||
CoreUdpHolePunchTransportSink<H, P>,
|
||||
CoreUdpHolePunchRuntime<H, P>,
|
||||
>;
|
||||
type CoreUdpHolePunchEndpoint<H, P> =
|
||||
UdpHolePunchRpcEndpoint<CoreUdpHolePunchRuntime<H, P>, CoreUdpHolePunchTransportSink<H, P>>;
|
||||
|
||||
pub(crate) struct CoreUdpHolePunchService<H, P>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
P: UdpHolePunchPeerSource
|
||||
+ HolePunchTunnelSink
|
||||
+ UdpHolePunchRpcSource
|
||||
+ HolePunchRpcRegistry
|
||||
+ 'static,
|
||||
{
|
||||
server: Arc<CoreUdpHolePunchEndpoint<H, P>>,
|
||||
client: CoreUdpHolePunchConnector<H, P>,
|
||||
peer_source: Arc<P>,
|
||||
}
|
||||
|
||||
impl<H, P> CoreUdpHolePunchService<H, P>
|
||||
where
|
||||
H: DirectConnectorHost + Send + Sync + 'static,
|
||||
HostUdpSocket<H>: VirtualUdpSocket + 'static,
|
||||
P: UdpHolePunchPeerSource
|
||||
+ HolePunchTunnelSink
|
||||
+ UdpHolePunchRpcSource
|
||||
+ HolePunchRpcRegistry
|
||||
+ 'static,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
peer_source: Arc<P>,
|
||||
host: Arc<H>,
|
||||
stun: Arc<dyn StunSocketMapper<HostUdpSocket<H>>>,
|
||||
platform: Option<Arc<dyn UdpPortMappingPlatform>>,
|
||||
events: Arc<dyn crate::events::CoreEventSink>,
|
||||
socket_context: SocketContext,
|
||||
protocol: Arc<dyn ClientProtocolUpgrader<HostTcpSocket<H>>>,
|
||||
) -> Self {
|
||||
let stun_mapper = stun.clone();
|
||||
let stun_info: Arc<dyn StunInfoProvider> = stun;
|
||||
let transport_sink = Arc::new(ProtocolUdpHolePunchTransportSink::new(
|
||||
protocol,
|
||||
peer_source.clone(),
|
||||
));
|
||||
let runtime = Arc::new(CoreUdpHolePunchRuntime::new(
|
||||
host,
|
||||
peer_source.clone(),
|
||||
stun_mapper,
|
||||
platform,
|
||||
events,
|
||||
socket_context,
|
||||
));
|
||||
let sym_punch_lock = UdpSymPunchLock::default();
|
||||
let client = UdpHolePunchConnector::new(
|
||||
peer_source.clone(),
|
||||
Arc::new(PeerRpcUdpHolePunchSignaling::new(peer_source.clone())),
|
||||
transport_sink.clone(),
|
||||
runtime.clone(),
|
||||
stun_info.clone(),
|
||||
sym_punch_lock.clone(),
|
||||
Some(peer_source.p2p_demand_notify()),
|
||||
);
|
||||
|
||||
Self {
|
||||
server: UdpHolePunchRpcEndpoint::new(
|
||||
stun_info,
|
||||
transport_sink,
|
||||
sym_punch_lock,
|
||||
runtime,
|
||||
),
|
||||
client,
|
||||
peer_source,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self) -> anyhow::Result<()> {
|
||||
if self
|
||||
.peer_source
|
||||
.p2p_policy_flags()
|
||||
.disable_udp_hole_punching
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.server.start().await;
|
||||
self.peer_source
|
||||
.register_rpc_service(UdpHolePunchRpcServer::new(Arc::downgrade(&self.server)));
|
||||
self.client.run_as_client();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
self.client.stop().await;
|
||||
self.server.begin_stop();
|
||||
self.peer_source
|
||||
.unregister_rpc_service(UdpHolePunchRpcServer::new(Arc::downgrade(&self.server)));
|
||||
self.server.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreUdpPunchAcceptor<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
HostUdpSocket<H>: VirtualUdpSocket,
|
||||
{
|
||||
layer: Arc<CoreUdpSessionLayer<H>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<H> UdpPunchAcceptor for CoreUdpPunchAcceptor<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory + UdpSessionStunResponder<HostUdpSocket<H>> + Send + Sync + 'static,
|
||||
HostUdpSocket<H>: VirtualUdpSocket + 'static,
|
||||
{
|
||||
async fn accept(&mut self) -> anyhow::Result<UdpPunchSocket> {
|
||||
let session = self.layer.accept().await?;
|
||||
let remote_addr = session.peer_addr()?;
|
||||
Ok(UdpPunchSocket::new(
|
||||
session,
|
||||
remote_addr,
|
||||
self.layer.clone(),
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreUdpPunchConnCounter<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
HostUdpSocket<H>: VirtualUdpSocket,
|
||||
{
|
||||
layer: Weak<CoreUdpSessionLayer<H>>,
|
||||
}
|
||||
|
||||
impl<H> std::fmt::Debug for CoreUdpPunchConnCounter<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
HostUdpSocket<H>: VirtualUdpSocket,
|
||||
{
|
||||
fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
formatter
|
||||
.debug_struct("CoreUdpPunchConnCounter")
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> ListenerConnectionCounter for CoreUdpPunchConnCounter<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory + UdpSessionStunResponder<HostUdpSocket<H>> + Send + Sync + 'static,
|
||||
HostUdpSocket<H>: VirtualUdpSocket + 'static,
|
||||
{
|
||||
fn get(&self) -> Option<u32> {
|
||||
Some(
|
||||
self.layer
|
||||
.upgrade()
|
||||
.map(|layer| layer.active_session_count() as u32)
|
||||
.unwrap_or(0),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct CoreUdpHolePunchRuntime<H, P>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
{
|
||||
host: Arc<H>,
|
||||
peer_source: Arc<P>,
|
||||
stun: Arc<dyn StunSocketMapper<HostUdpSocket<H>>>,
|
||||
platform: Option<Arc<dyn UdpPortMappingPlatform>>,
|
||||
events: Arc<dyn crate::events::CoreEventSink>,
|
||||
socket_context: SocketContext,
|
||||
}
|
||||
|
||||
impl<H, P> CoreUdpHolePunchRuntime<H, P>
|
||||
where
|
||||
H: DirectConnectorHost + Send + Sync + 'static,
|
||||
HostUdpSocket<H>: VirtualUdpSocket + 'static,
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
{
|
||||
pub fn new(
|
||||
host: Arc<H>,
|
||||
peer_source: Arc<P>,
|
||||
stun: Arc<dyn StunSocketMapper<HostUdpSocket<H>>>,
|
||||
platform: Option<Arc<dyn UdpPortMappingPlatform>>,
|
||||
events: Arc<dyn crate::events::CoreEventSink>,
|
||||
socket_context: SocketContext,
|
||||
) -> Self {
|
||||
Self {
|
||||
host,
|
||||
peer_source,
|
||||
stun,
|
||||
platform,
|
||||
events,
|
||||
socket_context,
|
||||
}
|
||||
}
|
||||
|
||||
fn session_layer(&self, socket: Arc<HostUdpSocket<H>>) -> Arc<CoreUdpSessionLayer<H>> {
|
||||
Arc::new(UdpSessionLayer::new_with_stun_responder(
|
||||
socket,
|
||||
self.host.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn create_listener_with_mapping(
|
||||
&self,
|
||||
resolve_public_addr: bool,
|
||||
port: Option<u16>,
|
||||
) -> anyhow::Result<UdpPunchListener<HostUdpSocket<H>>> {
|
||||
let bind = match port {
|
||||
Some(port) => UdpBindOptions::hole_punch_candidate().with_local_addr(Some(
|
||||
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, port)),
|
||||
)),
|
||||
None => UdpBindOptions::hole_punch_control(),
|
||||
}
|
||||
.with_context(self.socket_context.clone().with_ip_version(IpVersion::V4));
|
||||
let socket = self.host.bind_udp(bind).await?;
|
||||
let local_port = socket.local_addr()?.port();
|
||||
let resolved = if resolve_public_addr {
|
||||
self.resolve_public_addr(socket.clone()).await?
|
||||
} else {
|
||||
UdpResolvedPublicAddr {
|
||||
mapped_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, local_port)),
|
||||
port_mapping_lease: None,
|
||||
}
|
||||
};
|
||||
|
||||
let layer = self.session_layer(socket.clone());
|
||||
let conn_counter = Arc::new(CoreUdpPunchConnCounter {
|
||||
layer: Arc::downgrade(&layer),
|
||||
});
|
||||
let acceptor = Box::new(CoreUdpPunchAcceptor { layer });
|
||||
|
||||
Ok(UdpPunchListener {
|
||||
socket,
|
||||
mapped_addr: resolved.mapped_addr,
|
||||
conn_counter,
|
||||
acceptor,
|
||||
port_mapping_lease: resolved.port_mapping_lease,
|
||||
})
|
||||
}
|
||||
|
||||
async fn resolve_public_addr(
|
||||
&self,
|
||||
socket: Arc<HostUdpSocket<H>>,
|
||||
) -> anyhow::Result<UdpResolvedPublicAddr> {
|
||||
let local_port = socket.local_addr()?.port();
|
||||
let local_listener: url::Url = format!("udp://0.0.0.0:{local_port}").parse()?;
|
||||
resolve_public_addr_with_policy(
|
||||
self.stun.as_ref(),
|
||||
self.platform.clone(),
|
||||
self.events.clone(),
|
||||
socket,
|
||||
&local_listener,
|
||||
self.peer_source.p2p_policy_flags().disable_upnp,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn validate_socket_route(
|
||||
&self,
|
||||
context: SocketContext,
|
||||
remote_addr: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
let local_addr = self
|
||||
.host
|
||||
.local_addr_for_remote(remote_addr, context)
|
||||
.await?;
|
||||
let is_local_virtual_ipv4 = match local_addr.ip() {
|
||||
IpAddr::V4(ip) => self.peer_source.is_local_virtual_ip(&IpAddr::V4(ip)),
|
||||
IpAddr::V6(_) => false,
|
||||
};
|
||||
let is_easytier_managed_ipv6 = match local_addr.ip() {
|
||||
IpAddr::V4(_) => false,
|
||||
IpAddr::V6(ip) => self.peer_source.is_easytier_managed_ipv6(&ip).await,
|
||||
};
|
||||
if let Some(error) =
|
||||
managed_local_addr_error(local_addr, is_local_virtual_ipv4, is_easytier_managed_ipv6)
|
||||
{
|
||||
anyhow::bail!(error);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<H, P> UdpHolePunchRuntime for CoreUdpHolePunchRuntime<H, P>
|
||||
where
|
||||
H: DirectConnectorHost + Send + Sync + 'static,
|
||||
HostUdpSocket<H>: VirtualUdpSocket + 'static,
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
{
|
||||
type Socket = HostUdpSocket<H>;
|
||||
|
||||
fn socket_context(&self) -> SocketContext {
|
||||
self.socket_context.clone()
|
||||
}
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.host.bind_udp(options).await
|
||||
}
|
||||
|
||||
async fn bind_direct_connect_udp(&self) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.host
|
||||
.bind_udp(
|
||||
UdpBindOptions::hole_punch_candidate()
|
||||
.with_context(self.socket_context.clone().with_ip_version(IpVersion::V4)),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_udp_public_addr(
|
||||
&self,
|
||||
socket: Arc<Self::Socket>,
|
||||
) -> anyhow::Result<UdpResolvedPublicAddr> {
|
||||
self.resolve_public_addr(socket).await
|
||||
}
|
||||
|
||||
async fn create_listener(
|
||||
&self,
|
||||
_prefer_port_mapping: bool,
|
||||
) -> anyhow::Result<UdpPunchListener<Self::Socket>> {
|
||||
self.create_listener_with_mapping(true, None).await
|
||||
}
|
||||
|
||||
async fn create_port_bound_listener(
|
||||
&self,
|
||||
port: u16,
|
||||
) -> anyhow::Result<UdpPunchListener<Self::Socket>> {
|
||||
self.create_listener_with_mapping(false, Some(port)).await
|
||||
}
|
||||
|
||||
async fn connect_with_socket(
|
||||
&self,
|
||||
socket: Arc<Self::Socket>,
|
||||
remote: SocketAddr,
|
||||
) -> anyhow::Result<UdpPunchSocket> {
|
||||
self.validate_socket_route(socket.socket_context(), remote)
|
||||
.await?;
|
||||
let layer = self.session_layer(socket);
|
||||
let session = layer.connect(remote).await?;
|
||||
if session.peer_addr()? != remote {
|
||||
tracing::debug!(
|
||||
recv_addr = ?session.peer_addr()?,
|
||||
?remote,
|
||||
"udp connect addr not match"
|
||||
);
|
||||
}
|
||||
Ok(UdpPunchSocket::new(session, remote, layer))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
net::{Ipv6Addr, SocketAddrV6},
|
||||
sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use crate::{connectivity::stun::StunInfoProvider, proto::common::StunInfo};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MockSocket {
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], _addr: SocketAddr) -> io::Result<usize> {
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
struct MockStun {
|
||||
mapped_addr: SocketAddr,
|
||||
fail: bool,
|
||||
calls: AtomicUsize,
|
||||
}
|
||||
|
||||
impl MockStun {
|
||||
fn succeeds_with(mapped_addr: SocketAddr) -> Self {
|
||||
Self {
|
||||
mapped_addr,
|
||||
fail: false,
|
||||
calls: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
|
||||
fn failing() -> Self {
|
||||
Self {
|
||||
mapped_addr: "0.0.0.0:0".parse().unwrap(),
|
||||
fail: true,
|
||||
calls: AtomicUsize::new(0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StunInfoProvider for MockStun {
|
||||
fn get_stun_info(&self) -> StunInfo {
|
||||
StunInfo::default()
|
||||
}
|
||||
|
||||
async fn get_udp_port_mapping(&self, _local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
Ok(self.mapped_addr)
|
||||
}
|
||||
|
||||
async fn get_tcp_port_mapping(&self, _local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
Ok(self.mapped_addr)
|
||||
}
|
||||
|
||||
fn update_stun_info(&self) {}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StunSocketMapper<MockSocket> for MockStun {
|
||||
async fn get_udp_port_mapping_with_socket(
|
||||
&self,
|
||||
_socket: Arc<MockSocket>,
|
||||
) -> anyhow::Result<SocketAddr> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
if self.fail {
|
||||
anyhow::bail!("mock STUN failure");
|
||||
}
|
||||
Ok(self.mapped_addr)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct LeaseState {
|
||||
drops: AtomicUsize,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockEvents {
|
||||
established: Mutex<Vec<crate::events::CoreEvent>>,
|
||||
}
|
||||
|
||||
impl crate::events::CoreEventSink for MockEvents {
|
||||
fn emit(&self, event: crate::events::CoreEvent) {
|
||||
self.established.lock().unwrap().push(event);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct MockMapping {
|
||||
state: Arc<LeaseState>,
|
||||
backend: crate::connectivity::hole_punch::port_mapping::UdpPortMappingBackend,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl crate::connectivity::hole_punch::port_mapping::ActiveUdpPortMapping for MockMapping {
|
||||
fn backend(&self) -> crate::connectivity::hole_punch::port_mapping::UdpPortMappingBackend {
|
||||
self.backend
|
||||
}
|
||||
|
||||
fn local_addr(&self) -> SocketAddr {
|
||||
"192.168.1.5:30123".parse().unwrap()
|
||||
}
|
||||
|
||||
fn gateway_external_port(&self) -> u16 {
|
||||
40123
|
||||
}
|
||||
|
||||
async fn renew(&self) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn remove(&self) -> anyhow::Result<()> {
|
||||
self.state.drops.fetch_add(1, Ordering::SeqCst);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct MockPlatform {
|
||||
calls: AtomicUsize,
|
||||
fail: bool,
|
||||
lease_state: Arc<LeaseState>,
|
||||
}
|
||||
|
||||
impl MockPlatform {
|
||||
fn failing() -> Self {
|
||||
Self {
|
||||
calls: AtomicUsize::new(0),
|
||||
fail: true,
|
||||
lease_state: Arc::default(),
|
||||
}
|
||||
}
|
||||
|
||||
fn with_lease(lease_state: Arc<LeaseState>) -> Self {
|
||||
Self {
|
||||
calls: AtomicUsize::new(0),
|
||||
fail: false,
|
||||
lease_state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UdpPortMappingPlatform for MockPlatform {
|
||||
async fn establish_udp_port_mapping(
|
||||
&self,
|
||||
backend: crate::connectivity::hole_punch::port_mapping::UdpPortMappingBackend,
|
||||
_local_listener: &url::Url,
|
||||
) -> Result<
|
||||
Box<dyn crate::connectivity::hole_punch::port_mapping::ActiveUdpPortMapping>,
|
||||
crate::connectivity::hole_punch::port_mapping::UdpPortMappingAttemptError,
|
||||
> {
|
||||
self.calls.fetch_add(1, Ordering::SeqCst);
|
||||
if self.fail {
|
||||
return Err(
|
||||
crate::connectivity::hole_punch::port_mapping::UdpPortMappingAttemptError::establishment(
|
||||
anyhow::anyhow!("mock port-mapping failure"),
|
||||
),
|
||||
);
|
||||
}
|
||||
Ok(Box::new(MockMapping {
|
||||
state: self.lease_state.clone(),
|
||||
backend,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
fn socket() -> Arc<MockSocket> {
|
||||
Arc::new(MockSocket {
|
||||
local_addr: "0.0.0.0:30123".parse().unwrap(),
|
||||
})
|
||||
}
|
||||
|
||||
fn listener_url() -> url::Url {
|
||||
"udp://0.0.0.0:30123".parse().unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn port_mapping_failure_falls_back_to_stun() {
|
||||
let mapped_addr = "198.51.100.8:40123".parse().unwrap();
|
||||
let stun = MockStun::succeeds_with(mapped_addr);
|
||||
let platform = Arc::new(MockPlatform::failing());
|
||||
|
||||
let resolved = resolve_public_addr_with_policy(
|
||||
&stun,
|
||||
Some(platform.clone()),
|
||||
Arc::new(()),
|
||||
socket(),
|
||||
&listener_url(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(resolved.mapped_addr, mapped_addr);
|
||||
assert!(resolved.port_mapping_lease.is_none());
|
||||
assert_eq!(platform.calls.load(Ordering::SeqCst), 2);
|
||||
assert_eq!(stun.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stun_failure_releases_mapping_without_notification() {
|
||||
let lease_state = Arc::new(LeaseState::default());
|
||||
let platform = Arc::new(MockPlatform::with_lease(lease_state.clone()));
|
||||
let events = Arc::new(MockEvents::default());
|
||||
|
||||
let result = resolve_public_addr_with_policy(
|
||||
&MockStun::failing(),
|
||||
Some(platform),
|
||||
events.clone(),
|
||||
socket(),
|
||||
&listener_url(),
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(result.is_err());
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while lease_state.drops.load(Ordering::SeqCst) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(lease_state.drops.load(Ordering::SeqCst), 1);
|
||||
assert!(events.established.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn disable_upnp_is_applied_per_resolution() {
|
||||
let mapped_addr = "198.51.100.9:40124".parse().unwrap();
|
||||
let stun = MockStun::succeeds_with(mapped_addr);
|
||||
let lease_state = Arc::new(LeaseState::default());
|
||||
let platform = Arc::new(MockPlatform::with_lease(lease_state));
|
||||
|
||||
let disabled = resolve_public_addr_with_policy(
|
||||
&stun,
|
||||
Some(platform.clone()),
|
||||
Arc::new(()),
|
||||
socket(),
|
||||
&listener_url(),
|
||||
true,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(disabled.port_mapping_lease.is_none());
|
||||
assert_eq!(platform.calls.load(Ordering::SeqCst), 0);
|
||||
|
||||
let enabled = resolve_public_addr_with_policy(
|
||||
&stun,
|
||||
Some(platform.clone()),
|
||||
Arc::new(()),
|
||||
socket(),
|
||||
&listener_url(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(enabled.port_mapping_lease.is_some());
|
||||
assert_eq!(platform.calls.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn successful_mapping_is_notified_and_held_with_result() {
|
||||
let mapped_addr = "198.51.100.10:40125".parse().unwrap();
|
||||
let lease_state = Arc::new(LeaseState::default());
|
||||
let platform = Arc::new(MockPlatform::with_lease(lease_state.clone()));
|
||||
let events = Arc::new(MockEvents::default());
|
||||
|
||||
let resolved = resolve_public_addr_with_policy(
|
||||
&MockStun::succeeds_with(mapped_addr),
|
||||
Some(platform),
|
||||
events.clone(),
|
||||
socket(),
|
||||
&listener_url(),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
{
|
||||
let established = events.established.lock().unwrap();
|
||||
assert!(matches!(
|
||||
established.as_slice(),
|
||||
[crate::events::CoreEvent::UdpPortMappingEstablished {
|
||||
local_listener,
|
||||
mapped_listener,
|
||||
backend,
|
||||
}] if local_listener == &listener_url()
|
||||
&& mapped_listener.as_str() == "udp://198.51.100.10:40125"
|
||||
&& backend == "igd"
|
||||
));
|
||||
}
|
||||
assert_eq!(lease_state.drops.load(Ordering::SeqCst), 0);
|
||||
drop(resolved);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while lease_state.drops.load(Ordering::SeqCst) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(lease_state.drops.load(Ordering::SeqCst), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn managed_local_addresses_are_rejected() {
|
||||
let virtual_ipv4 = "10.144.0.2:1234".parse().unwrap();
|
||||
assert_eq!(
|
||||
managed_local_addr_error(virtual_ipv4, true, false),
|
||||
Some("local address is virtual ipv4")
|
||||
);
|
||||
assert_eq!(managed_local_addr_error(virtual_ipv4, false, false), None);
|
||||
|
||||
let managed_ipv6 = SocketAddr::V6(SocketAddrV6::new(
|
||||
"fd00::1".parse::<Ipv6Addr>().unwrap(),
|
||||
1234,
|
||||
0,
|
||||
0,
|
||||
));
|
||||
assert_eq!(
|
||||
managed_local_addr_error(managed_ipv6, false, true),
|
||||
Some("local address is easytier-managed ipv6")
|
||||
);
|
||||
assert_eq!(managed_local_addr_error(managed_ipv6, false, false), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,995 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use guarden::defer;
|
||||
use quanta::Instant;
|
||||
use rand::Rng;
|
||||
use tokio::sync::RwLock;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::{
|
||||
config::PeerId,
|
||||
connectivity::stun::StunInfoProvider,
|
||||
packet::{HOLE_PUNCH_PACKET_BODY_LEN, new_hole_punch_packet},
|
||||
socket::udp::{UdpBindOptions, VirtualUdpSocketFactory},
|
||||
};
|
||||
|
||||
use super::{
|
||||
SelectPunchListener, SendPunchPacketBothEasySym, SendPunchPacketCone, SendPunchPacketEasySym,
|
||||
SendPunchPacketHardSym, UdpHolePunchRuntime, UdpHolePunchSignalError, UdpHolePunchSignaling,
|
||||
UdpNatType, UdpPunchSocket, UdpSocketArray,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum UdpHolePunchClientError {
|
||||
#[error("signaling: {0}")]
|
||||
Signaling(#[from] UdpHolePunchSignalError),
|
||||
#[error(transparent)]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
pub type UdpHolePunchClientResult<T> = Result<T, UdpHolePunchClientError>;
|
||||
|
||||
const UDP_ARRAY_SIZE_FOR_HARD_SYM: usize = 84;
|
||||
const UDP_ARRAY_SIZE_FOR_BOTH_EASY_SYM: usize = 25;
|
||||
const DST_PORT_OFFSET: u16 = 20;
|
||||
const REMOTE_WAIT_TIME_MS: u64 = 5000;
|
||||
|
||||
pub fn apply_peer_easy_sym_port_offset(base_port: u16, peer_is_incremental: bool) -> u16 {
|
||||
let port = if peer_is_incremental {
|
||||
(base_port as u32).saturating_add(DST_PORT_OFFSET as u32)
|
||||
} else {
|
||||
(base_port as u32).saturating_sub(DST_PORT_OFFSET as u32)
|
||||
};
|
||||
port as u16
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(runtime, signaling), fields(dst_peer_id), err)]
|
||||
pub async fn punch_cone_to_cone<R, S>(
|
||||
runtime: Arc<R>,
|
||||
signaling: Arc<S>,
|
||||
dst_peer_id: PeerId,
|
||||
) -> UdpHolePunchClientResult<Option<UdpPunchSocket>>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
tracing::info!(?dst_peer_id, "start hole punching");
|
||||
let tid = rand::random();
|
||||
|
||||
let udp_array = UdpSocketArray::new_with_context(1, runtime.clone(), runtime.socket_context());
|
||||
|
||||
let resp = signaling
|
||||
.select_punch_listener(
|
||||
dst_peer_id,
|
||||
SelectPunchListener {
|
||||
force_new: false,
|
||||
prefer_port_mapping: true,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
let remote_mapped_addr = resp.listener_mapped_addr;
|
||||
|
||||
let local_socket = UdpHolePunchRuntime::bind_udp(
|
||||
runtime.as_ref(),
|
||||
UdpBindOptions::hole_punch_control().with_context(
|
||||
runtime
|
||||
.socket_context()
|
||||
.with_ip_version(crate::socket::IpVersion::V4),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let resolved = runtime
|
||||
.resolve_udp_public_addr(local_socket.clone())
|
||||
.await?;
|
||||
let local_mapped_addr = resolved.mapped_addr;
|
||||
let _local_port_mapping_lease = resolved.port_mapping_lease;
|
||||
|
||||
tracing::debug!(
|
||||
?local_mapped_addr,
|
||||
?remote_mapped_addr,
|
||||
"hole punch got remote listener"
|
||||
);
|
||||
|
||||
udp_array.add_new_socket(local_socket).await?;
|
||||
udp_array.add_intreast_tid(tid);
|
||||
let punch_packet = new_hole_punch_packet(tid, HOLE_PUNCH_PACKET_BODY_LEN).into_bytes();
|
||||
|
||||
send_from_local(&udp_array, &punch_packet, remote_mapped_addr).await?;
|
||||
|
||||
let signaling_for_task = signaling.clone();
|
||||
let punch_task = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
if let Err(e) = signaling_for_task
|
||||
.send_punch_packet_cone(
|
||||
dst_peer_id,
|
||||
SendPunchPacketCone {
|
||||
listener_mapped_addr: remote_mapped_addr,
|
||||
dest_addr: local_mapped_addr,
|
||||
transaction_id: tid,
|
||||
packet_count_per_batch: 2,
|
||||
packet_batch_count: 5,
|
||||
packet_interval_ms: 400,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!(?e, "failed to call remote send punch packet");
|
||||
}
|
||||
}));
|
||||
|
||||
let mut finish_time: Option<Instant> = None;
|
||||
while finish_time.is_none() || finish_time.as_ref().unwrap().elapsed().as_millis() < 1000 {
|
||||
crate::foundation::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
|
||||
if finish_time.is_none() && punch_task.is_finished() {
|
||||
finish_time = Some(Instant::now());
|
||||
}
|
||||
|
||||
let Some(socket) = udp_array.try_fetch_punched_socket(tid) else {
|
||||
tracing::debug!("no punched socket found, send some more hole punch packets");
|
||||
send_from_local(&udp_array, &punch_packet, remote_mapped_addr).await?;
|
||||
continue;
|
||||
};
|
||||
|
||||
tracing::debug!(?socket, ?tid, "punched socket found, try connect with it");
|
||||
|
||||
for _ in 0..2 {
|
||||
match runtime
|
||||
.connect_with_socket(socket.socket.clone(), remote_mapped_addr)
|
||||
.await
|
||||
{
|
||||
Ok(socket) => {
|
||||
tracing::info!(?socket, "hole punched");
|
||||
return Ok(Some(socket));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(?e, "failed to connect with socket");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
async fn send_from_local<R>(
|
||||
udp_array: &UdpSocketArray<R>,
|
||||
punch_packet: &[u8],
|
||||
remote_mapped_addr: SocketAddr,
|
||||
) -> UdpHolePunchClientResult<()>
|
||||
where
|
||||
R: VirtualUdpSocketFactory,
|
||||
{
|
||||
udp_array
|
||||
.send_with_all(punch_packet, remote_mapped_addr)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub struct UdpSymToConePunchClient<R, S>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
runtime: Arc<R>,
|
||||
signaling: Arc<S>,
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
udp_array: RwLock<Option<Arc<UdpSocketArray<R>>>>,
|
||||
try_direct_connect: AtomicBool,
|
||||
punch_predictably: AtomicBool,
|
||||
}
|
||||
|
||||
impl<R, S> UdpSymToConePunchClient<R, S>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
pub fn new(runtime: Arc<R>, signaling: Arc<S>, stun: Arc<dyn StunInfoProvider>) -> Self {
|
||||
Self {
|
||||
runtime,
|
||||
signaling,
|
||||
stun,
|
||||
udp_array: RwLock::new(None),
|
||||
try_direct_connect: AtomicBool::new(true),
|
||||
punch_predictably: AtomicBool::new(true),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn clear_udp_array(&self) {
|
||||
let mut wlocked = self.udp_array.write().await;
|
||||
wlocked.take();
|
||||
}
|
||||
|
||||
async fn prepare_udp_array(&self) -> anyhow::Result<Arc<UdpSocketArray<R>>> {
|
||||
let rlocked = self.udp_array.read().await;
|
||||
if let Some(udp_array) = rlocked.clone() {
|
||||
return Ok(udp_array);
|
||||
}
|
||||
|
||||
drop(rlocked);
|
||||
let mut wlocked = self.udp_array.write().await;
|
||||
if let Some(udp_array) = wlocked.clone() {
|
||||
return Ok(udp_array);
|
||||
}
|
||||
|
||||
let udp_array = Arc::new(UdpSocketArray::new_with_context(
|
||||
UDP_ARRAY_SIZE_FOR_HARD_SYM,
|
||||
self.runtime.clone(),
|
||||
self.runtime.socket_context(),
|
||||
));
|
||||
udp_array.start().await?;
|
||||
wlocked.replace(udp_array.clone());
|
||||
Ok(udp_array)
|
||||
}
|
||||
|
||||
async fn get_base_port_for_easy_sym(&self, my_nat_info: UdpNatType) -> Option<u16> {
|
||||
if my_nat_info.is_easy_sym() {
|
||||
match self.stun.get_udp_port_mapping(0).await {
|
||||
Ok(addr) => Some(addr.port()),
|
||||
ret => {
|
||||
tracing::warn!(?ret, "failed to get udp port mapping for easy sym");
|
||||
None
|
||||
}
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
async fn remote_send_hole_punch_packet_predictable(
|
||||
signaling: Arc<S>,
|
||||
dst_peer_id: PeerId,
|
||||
base_port_for_easy_sym: Option<u16>,
|
||||
my_nat_info: UdpNatType,
|
||||
remote_mapped_addr: SocketAddr,
|
||||
public_ips: Vec<Ipv4Addr>,
|
||||
tid: u32,
|
||||
) {
|
||||
let Some(inc) = my_nat_info.get_inc_of_easy_sym() else {
|
||||
return;
|
||||
};
|
||||
let req = SendPunchPacketEasySym {
|
||||
listener_mapped_addr: remote_mapped_addr,
|
||||
public_ips,
|
||||
transaction_id: tid,
|
||||
base_port_num: base_port_for_easy_sym.unwrap() as u32,
|
||||
max_port_num: 50,
|
||||
is_incremental: inc,
|
||||
};
|
||||
tracing::debug!(?req, "send punch packet for easy sym start");
|
||||
let ret = signaling.send_punch_packet_easy_sym(dst_peer_id, req).await;
|
||||
tracing::debug!(?ret, "send punch packet for easy sym return");
|
||||
}
|
||||
|
||||
async fn remote_send_hole_punch_packet_random(
|
||||
signaling: Arc<S>,
|
||||
dst_peer_id: PeerId,
|
||||
remote_mapped_addr: SocketAddr,
|
||||
public_ips: Vec<Ipv4Addr>,
|
||||
tid: u32,
|
||||
round: u32,
|
||||
port_index: u32,
|
||||
) -> Option<u32> {
|
||||
let req = SendPunchPacketHardSym {
|
||||
listener_mapped_addr: remote_mapped_addr,
|
||||
public_ips,
|
||||
transaction_id: tid,
|
||||
round,
|
||||
port_index,
|
||||
};
|
||||
tracing::debug!(?req, "send punch packet for hard sym start");
|
||||
match signaling.send_punch_packet_hard_sym(dst_peer_id, req).await {
|
||||
Err(e) => {
|
||||
tracing::error!(?e, "failed to send punch packet for hard sym");
|
||||
None
|
||||
}
|
||||
Ok(resp) => Some(resp.next_port_index),
|
||||
}
|
||||
}
|
||||
|
||||
async fn check_hole_punch_result<T>(
|
||||
&self,
|
||||
udp_array: &Arc<UdpSocketArray<R>>,
|
||||
packet: &[u8],
|
||||
tid: u32,
|
||||
remote_mapped_addr: SocketAddr,
|
||||
punch_task: &AbortOnDropHandle<T>,
|
||||
) -> anyhow::Result<Option<UdpPunchSocket>> {
|
||||
let mut ret_socket = None;
|
||||
let mut finish_time: Option<Instant> = None;
|
||||
while finish_time.is_none() || finish_time.as_ref().unwrap().elapsed().as_millis() < 1000 {
|
||||
udp_array.send_with_all(packet, remote_mapped_addr).await?;
|
||||
|
||||
crate::foundation::time::sleep(std::time::Duration::from_millis(200)).await;
|
||||
|
||||
if finish_time.is_none() && punch_task.is_finished() {
|
||||
finish_time = Some(Instant::now());
|
||||
}
|
||||
|
||||
let Some(socket) = udp_array.try_fetch_punched_socket(tid) else {
|
||||
tracing::debug!("no punched socket found, wait for more time");
|
||||
continue;
|
||||
};
|
||||
|
||||
match self
|
||||
.runtime
|
||||
.connect_with_socket(socket.socket.clone(), remote_mapped_addr)
|
||||
.await
|
||||
{
|
||||
Ok(socket) => {
|
||||
ret_socket.replace(socket);
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(?e, "failed to connect with socket");
|
||||
udp_array.add_new_socket(socket.socket).await?;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(ret_socket)
|
||||
}
|
||||
|
||||
#[tracing::instrument(err(level = tracing::Level::ERROR), skip(self))]
|
||||
pub async fn do_hole_punching(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
round: u32,
|
||||
last_port_idx: &mut usize,
|
||||
my_nat_info: UdpNatType,
|
||||
) -> UdpHolePunchClientResult<Option<UdpPunchSocket>> {
|
||||
let udp_array = self.prepare_udp_array().await?;
|
||||
|
||||
let resp = self
|
||||
.signaling
|
||||
.select_punch_listener(
|
||||
dst_peer_id,
|
||||
SelectPunchListener {
|
||||
force_new: false,
|
||||
prefer_port_mapping: true,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
let remote_mapped_addr = resp.listener_mapped_addr;
|
||||
|
||||
if self.try_direct_connect.load(Ordering::Relaxed) {
|
||||
let socket = self.runtime.bind_direct_connect_udp().await?;
|
||||
if let Ok(socket) = self
|
||||
.runtime
|
||||
.connect_with_socket(socket, remote_mapped_addr)
|
||||
.await
|
||||
{
|
||||
return Ok(Some(socket));
|
||||
}
|
||||
}
|
||||
|
||||
let stun_info = self.stun.get_stun_info();
|
||||
let public_ips: Vec<Ipv4Addr> = stun_info
|
||||
.public_ip
|
||||
.iter()
|
||||
.filter_map(|x| x.parse().ok())
|
||||
.collect();
|
||||
if public_ips.is_empty() {
|
||||
return Err(anyhow::anyhow!("failed to get public ips").into());
|
||||
}
|
||||
|
||||
let tid = rand::thread_rng().r#gen();
|
||||
let packet = new_hole_punch_packet(tid, HOLE_PUNCH_PACKET_BODY_LEN).into_bytes();
|
||||
udp_array.add_intreast_tid(tid);
|
||||
defer! { udp_array.remove_intreast_tid(tid); }
|
||||
|
||||
let port_index = *last_port_idx as u32;
|
||||
let base_port_for_easy_sym = self.get_base_port_for_easy_sym(my_nat_info).await;
|
||||
udp_array.send_with_all(&packet, remote_mapped_addr).await?;
|
||||
|
||||
if self.punch_predictably.load(Ordering::Relaxed) && base_port_for_easy_sym.is_some() {
|
||||
let signaling = self.signaling.clone();
|
||||
let punch_task = AbortOnDropHandle::new(tokio::spawn(
|
||||
Self::remote_send_hole_punch_packet_predictable(
|
||||
signaling,
|
||||
dst_peer_id,
|
||||
base_port_for_easy_sym,
|
||||
my_nat_info,
|
||||
remote_mapped_addr,
|
||||
public_ips.clone(),
|
||||
tid,
|
||||
),
|
||||
));
|
||||
let ret_socket = self
|
||||
.check_hole_punch_result(&udp_array, &packet, tid, remote_mapped_addr, &punch_task)
|
||||
.await?;
|
||||
|
||||
let task_ret = punch_task.await;
|
||||
tracing::debug!(?ret_socket, ?task_ret, "predictable punch task got result");
|
||||
if let Some(socket) = ret_socket {
|
||||
return Ok(Some(socket));
|
||||
}
|
||||
}
|
||||
|
||||
let signaling = self.signaling.clone();
|
||||
let punch_task =
|
||||
AbortOnDropHandle::new(tokio::spawn(Self::remote_send_hole_punch_packet_random(
|
||||
signaling,
|
||||
dst_peer_id,
|
||||
remote_mapped_addr,
|
||||
public_ips.clone(),
|
||||
tid,
|
||||
round,
|
||||
port_index,
|
||||
)));
|
||||
let ret_socket = self
|
||||
.check_hole_punch_result(&udp_array, &packet, tid, remote_mapped_addr, &punch_task)
|
||||
.await?;
|
||||
|
||||
let punch_task_result = punch_task.await;
|
||||
tracing::debug!(?punch_task_result, ?ret_socket, "punch task got result");
|
||||
|
||||
if let Ok(Some(next_port_idx)) = punch_task_result {
|
||||
*last_port_idx = next_port_idx as usize;
|
||||
} else {
|
||||
*last_port_idx = rand::random();
|
||||
}
|
||||
|
||||
Ok(ret_socket)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UdpBothEasySymPunchClient<R, S>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
runtime: Arc<R>,
|
||||
signaling: Arc<S>,
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
}
|
||||
|
||||
impl<R, S> UdpBothEasySymPunchClient<R, S>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
pub fn new(runtime: Arc<R>, signaling: Arc<S>, stun: Arc<dyn StunInfoProvider>) -> Self {
|
||||
Self {
|
||||
runtime,
|
||||
signaling,
|
||||
stun,
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(ret, skip(self))]
|
||||
pub async fn do_hole_punching(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
my_nat_info: UdpNatType,
|
||||
peer_nat_info: UdpNatType,
|
||||
is_busy: &mut bool,
|
||||
) -> UdpHolePunchClientResult<Option<UdpPunchSocket>> {
|
||||
*is_busy = false;
|
||||
|
||||
let udp_array = UdpSocketArray::new_with_context(
|
||||
UDP_ARRAY_SIZE_FOR_BOTH_EASY_SYM,
|
||||
self.runtime.clone(),
|
||||
self.runtime.socket_context(),
|
||||
);
|
||||
udp_array.start().await?;
|
||||
|
||||
let cur_mapped_addr = self.stun.get_udp_port_mapping(0).await?;
|
||||
let my_public_ip = match cur_mapped_addr.ip() {
|
||||
IpAddr::V4(v4) => v4,
|
||||
_ => {
|
||||
return Err(anyhow::anyhow!("ipv6 is not supported").into());
|
||||
}
|
||||
};
|
||||
let me_is_incremental = my_nat_info
|
||||
.get_inc_of_easy_sym()
|
||||
.ok_or(anyhow::anyhow!("me_is_incremental is required"))?;
|
||||
let peer_is_incremental = peer_nat_info
|
||||
.get_inc_of_easy_sym()
|
||||
.ok_or(anyhow::anyhow!("peer_is_incremental is required"))?;
|
||||
|
||||
let tid = rand::random();
|
||||
udp_array.add_intreast_tid(tid);
|
||||
|
||||
let remote_ret = self
|
||||
.signaling
|
||||
.send_punch_packet_both_easy_sym(
|
||||
dst_peer_id,
|
||||
SendPunchPacketBothEasySym {
|
||||
transaction_id: tid,
|
||||
public_ip: my_public_ip,
|
||||
dst_port_num: if me_is_incremental {
|
||||
cur_mapped_addr.port().saturating_add(DST_PORT_OFFSET)
|
||||
} else {
|
||||
cur_mapped_addr.port().saturating_sub(DST_PORT_OFFSET)
|
||||
} as u32,
|
||||
udp_socket_count: UDP_ARRAY_SIZE_FOR_BOTH_EASY_SYM as u32,
|
||||
wait_time_ms: REMOTE_WAIT_TIME_MS as u32,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
if remote_ret.is_busy {
|
||||
*is_busy = true;
|
||||
return Err(anyhow::anyhow!("remote is busy").into());
|
||||
}
|
||||
|
||||
let mut remote_mapped_addr = remote_ret
|
||||
.base_mapped_addr
|
||||
.ok_or(anyhow::anyhow!("remote_mapped_addr is required"))?;
|
||||
|
||||
let now = Instant::now();
|
||||
remote_mapped_addr.set_port(apply_peer_easy_sym_port_offset(
|
||||
remote_mapped_addr.port(),
|
||||
peer_is_incremental,
|
||||
));
|
||||
tracing::debug!(
|
||||
?remote_mapped_addr,
|
||||
?remote_ret,
|
||||
"start send hole punch packet for both easy sym"
|
||||
);
|
||||
|
||||
while now.elapsed().as_millis() < (REMOTE_WAIT_TIME_MS + 1000).into() {
|
||||
udp_array
|
||||
.send_with_all(
|
||||
&new_hole_punch_packet(tid, HOLE_PUNCH_PACKET_BODY_LEN).into_bytes(),
|
||||
remote_mapped_addr,
|
||||
)
|
||||
.await?;
|
||||
|
||||
crate::foundation::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
|
||||
let Some(socket) = udp_array.try_fetch_punched_socket(tid) else {
|
||||
tracing::trace!(
|
||||
?remote_mapped_addr,
|
||||
?tid,
|
||||
"no punched socket found, send some more hole punch packets"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
|
||||
tracing::info!(
|
||||
?socket,
|
||||
?remote_mapped_addr,
|
||||
?tid,
|
||||
"got punched socket in both easy sym"
|
||||
);
|
||||
|
||||
for _ in 0..2 {
|
||||
match self
|
||||
.runtime
|
||||
.connect_with_socket(socket.socket.clone(), remote_mapped_addr)
|
||||
.await
|
||||
{
|
||||
Ok(socket) => {
|
||||
return Ok(Some(socket));
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(?e, "failed to connect with socket");
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
udp_array.add_new_socket(socket.socket).await?;
|
||||
}
|
||||
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
proto::common::{NatType, StunInfo},
|
||||
socket::udp::VirtualUdpSocket,
|
||||
};
|
||||
|
||||
impl<R, S> UdpSymToConePunchClient<R, S>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
{
|
||||
fn set_try_direct_connect(&self, enabled: bool) {
|
||||
self.try_direct_connect.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
struct MockSocket {
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, _data: &[u8], _addr: SocketAddr) -> io::Result<usize> {
|
||||
Ok(0)
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
struct MockRuntime {
|
||||
bind_count: AtomicUsize,
|
||||
resolve_count: AtomicUsize,
|
||||
bind_options: tokio::sync::Mutex<Vec<UdpBindOptions>>,
|
||||
}
|
||||
|
||||
impl MockRuntime {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
bind_count: AtomicUsize::new(0),
|
||||
resolve_count: AtomicUsize::new(0),
|
||||
bind_options: tokio::sync::Mutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UdpHolePunchRuntime for MockRuntime {
|
||||
type Socket = MockSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.bind_options.lock().await.push(options);
|
||||
let bind_idx = self.bind_count.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(Arc::new(MockSocket {
|
||||
local_addr: SocketAddr::from(([127, 0, 0, 1], 10000 + bind_idx as u16)),
|
||||
}))
|
||||
}
|
||||
|
||||
async fn resolve_udp_public_addr(
|
||||
&self,
|
||||
_socket: Arc<Self::Socket>,
|
||||
) -> anyhow::Result<super::super::UdpResolvedPublicAddr> {
|
||||
self.resolve_count.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(super::super::UdpResolvedPublicAddr {
|
||||
mapped_addr: SocketAddr::from(([203, 0, 113, 1], 10000)),
|
||||
port_mapping_lease: None,
|
||||
})
|
||||
}
|
||||
|
||||
async fn create_listener(
|
||||
&self,
|
||||
_prefer_port_mapping: bool,
|
||||
) -> anyhow::Result<super::super::UdpPunchListener<Self::Socket>> {
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
|
||||
async fn create_port_bound_listener(
|
||||
&self,
|
||||
_port: u16,
|
||||
) -> anyhow::Result<super::super::UdpPunchListener<Self::Socket>> {
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
|
||||
async fn connect_with_socket(
|
||||
&self,
|
||||
_socket: Arc<Self::Socket>,
|
||||
_remote: SocketAddr,
|
||||
) -> anyhow::Result<UdpPunchSocket> {
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockStunInfoProvider {
|
||||
port_mapping_count: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl StunInfoProvider for MockStunInfoProvider {
|
||||
fn get_stun_info(&self) -> StunInfo {
|
||||
StunInfo {
|
||||
public_ip: vec!["127.0.0.1".to_string()],
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_udp_port_mapping(&self, _port: u16) -> anyhow::Result<SocketAddr> {
|
||||
self.port_mapping_count.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(SocketAddr::from(([203, 0, 113, 1], 10000)))
|
||||
}
|
||||
|
||||
async fn get_tcp_port_mapping(&self, _port: u16) -> anyhow::Result<SocketAddr> {
|
||||
unreachable!("TCP mapping is not used by UDP hole-punch tests")
|
||||
}
|
||||
|
||||
fn update_stun_info(&self) {}
|
||||
}
|
||||
|
||||
struct RejectingSignaling;
|
||||
|
||||
#[async_trait]
|
||||
impl UdpHolePunchSignaling for RejectingSignaling {
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: SelectPunchListener,
|
||||
) -> Result<super::super::SelectPunchListenerResponse, UdpHolePunchSignalError> {
|
||||
Err(UdpHolePunchSignalError::InvalidServiceKey)
|
||||
}
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: super::super::SendPunchPacketHardSym,
|
||||
) -> Result<super::super::SendPunchPacketHardSymResponse, UdpHolePunchSignalError> {
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: super::super::SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: super::super::SendPunchPacketBothEasySym,
|
||||
) -> Result<super::super::SendPunchPacketBothEasySymResponse, UdpHolePunchSignalError>
|
||||
{
|
||||
unimplemented!("not used by cone client tests")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cone_punch_does_not_bind_or_resolve_before_listener_rpc_succeeds() {
|
||||
let runtime = Arc::new(MockRuntime::new());
|
||||
let signaling = Arc::new(RejectingSignaling);
|
||||
|
||||
let err = punch_cone_to_cone(runtime.clone(), signaling, 2)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(matches!(
|
||||
err,
|
||||
UdpHolePunchClientError::Signaling(UdpHolePunchSignalError::InvalidServiceKey)
|
||||
));
|
||||
assert_eq!(runtime.bind_count.load(Ordering::Relaxed), 0);
|
||||
assert_eq!(runtime.resolve_count.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_direct_connect_bind_uses_direct_connect_purpose() {
|
||||
let runtime = MockRuntime::new();
|
||||
|
||||
let socket = runtime.bind_direct_connect_udp().await.unwrap();
|
||||
|
||||
assert_eq!(socket.local_addr().unwrap().port(), 10000);
|
||||
let bind_options = runtime.bind_options.lock().await;
|
||||
assert_eq!(
|
||||
bind_options.as_slice(),
|
||||
&[UdpBindOptions::direct_connect().with_ip_version(crate::socket::IpVersion::V4)]
|
||||
);
|
||||
}
|
||||
|
||||
struct RecordingSignaling {
|
||||
easy_requests: tokio::sync::Mutex<Vec<SendPunchPacketEasySym>>,
|
||||
hard_requests: tokio::sync::Mutex<Vec<SendPunchPacketHardSym>>,
|
||||
both_requests: tokio::sync::Mutex<Vec<SendPunchPacketBothEasySym>>,
|
||||
both_response: super::super::SendPunchPacketBothEasySymResponse,
|
||||
next_port_index: u32,
|
||||
}
|
||||
|
||||
impl RecordingSignaling {
|
||||
fn new(next_port_index: u32) -> Self {
|
||||
Self {
|
||||
easy_requests: tokio::sync::Mutex::new(Vec::new()),
|
||||
hard_requests: tokio::sync::Mutex::new(Vec::new()),
|
||||
both_requests: tokio::sync::Mutex::new(Vec::new()),
|
||||
both_response: super::super::SendPunchPacketBothEasySymResponse {
|
||||
is_busy: false,
|
||||
base_mapped_addr: Some(SocketAddr::from(([127, 0, 0, 1], 40144))),
|
||||
},
|
||||
next_port_index,
|
||||
}
|
||||
}
|
||||
|
||||
fn with_both_response(
|
||||
mut self,
|
||||
both_response: super::super::SendPunchPacketBothEasySymResponse,
|
||||
) -> Self {
|
||||
self.both_response = both_response;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl UdpHolePunchSignaling for RecordingSignaling {
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: SelectPunchListener,
|
||||
) -> Result<super::super::SelectPunchListenerResponse, UdpHolePunchSignalError> {
|
||||
Ok(super::super::SelectPunchListenerResponse {
|
||||
listener_mapped_addr: SocketAddr::from(([127, 0, 0, 1], 30000)),
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
_request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
request: SendPunchPacketHardSym,
|
||||
) -> Result<super::super::SendPunchPacketHardSymResponse, UdpHolePunchSignalError> {
|
||||
self.hard_requests.lock().await.push(request);
|
||||
Ok(super::super::SendPunchPacketHardSymResponse {
|
||||
next_port_index: self.next_port_index,
|
||||
})
|
||||
}
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
request: SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
self.easy_requests.lock().await.push(request);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
_dst_peer_id: PeerId,
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> Result<super::super::SendPunchPacketBothEasySymResponse, UdpHolePunchSignalError>
|
||||
{
|
||||
self.both_requests.lock().await.push(request);
|
||||
Ok(self.both_response.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sym_to_cone_easy_sym_uses_port_mapping_in_predictable_request() {
|
||||
let runtime = Arc::new(MockRuntime::new());
|
||||
let signaling = Arc::new(RecordingSignaling::new(42));
|
||||
let stun = Arc::new(MockStunInfoProvider::default());
|
||||
let client = UdpSymToConePunchClient::new(runtime.clone(), signaling.clone(), stun.clone());
|
||||
client.set_try_direct_connect(false);
|
||||
|
||||
let mut last_port_idx = 7;
|
||||
let ret = client
|
||||
.do_hole_punching(2, 3, &mut last_port_idx, NatType::SymmetricEasyInc.into())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(ret.is_none());
|
||||
assert_eq!(stun.port_mapping_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
let easy_requests = signaling.easy_requests.lock().await;
|
||||
assert_eq!(easy_requests.len(), 1);
|
||||
let req = &easy_requests[0];
|
||||
assert_eq!(
|
||||
req.listener_mapped_addr,
|
||||
SocketAddr::from(([127, 0, 0, 1], 30000))
|
||||
);
|
||||
assert_eq!(req.public_ips, vec![Ipv4Addr::new(127, 0, 0, 1)]);
|
||||
assert_eq!(req.base_port_num, 10000);
|
||||
assert_eq!(req.max_port_num, 50);
|
||||
assert!(req.is_incremental);
|
||||
|
||||
let hard_requests = signaling.hard_requests.lock().await;
|
||||
assert_eq!(hard_requests.len(), 1);
|
||||
assert_eq!(last_port_idx, 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sym_to_cone_hard_sym_sends_random_request_and_updates_port_index() {
|
||||
let runtime = Arc::new(MockRuntime::new());
|
||||
let signaling = Arc::new(RecordingSignaling::new(321));
|
||||
let stun = Arc::new(MockStunInfoProvider::default());
|
||||
let client = UdpSymToConePunchClient::new(runtime.clone(), signaling.clone(), stun.clone());
|
||||
client.set_try_direct_connect(false);
|
||||
|
||||
let mut last_port_idx = 123;
|
||||
let ret = client
|
||||
.do_hole_punching(2, 4, &mut last_port_idx, NatType::Symmetric.into())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(ret.is_none());
|
||||
assert_eq!(stun.port_mapping_count.load(Ordering::Relaxed), 0);
|
||||
assert!(signaling.easy_requests.lock().await.is_empty());
|
||||
|
||||
let hard_requests = signaling.hard_requests.lock().await;
|
||||
assert_eq!(hard_requests.len(), 1);
|
||||
let req = &hard_requests[0];
|
||||
assert_eq!(
|
||||
req.listener_mapped_addr,
|
||||
SocketAddr::from(([127, 0, 0, 1], 30000))
|
||||
);
|
||||
assert_eq!(req.public_ips, vec![Ipv4Addr::new(127, 0, 0, 1)]);
|
||||
assert_eq!(req.round, 4);
|
||||
assert_eq!(req.port_index, 123);
|
||||
assert_eq!(last_port_idx, 321);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_easy_sym_port_offset_preserves_old_proto_cast_semantics() {
|
||||
assert_eq!(apply_peer_easy_sym_port_offset(65530, true), 14);
|
||||
assert_eq!(apply_peer_easy_sym_port_offset(10, false), 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn both_easy_sym_sends_remote_request_and_reports_busy() {
|
||||
let runtime = Arc::new(MockRuntime::new());
|
||||
let stun = Arc::new(MockStunInfoProvider::default());
|
||||
let signaling = Arc::new(RecordingSignaling::new(0).with_both_response(
|
||||
super::super::SendPunchPacketBothEasySymResponse {
|
||||
is_busy: true,
|
||||
base_mapped_addr: None,
|
||||
},
|
||||
));
|
||||
let client =
|
||||
UdpBothEasySymPunchClient::new(runtime.clone(), signaling.clone(), stun.clone());
|
||||
|
||||
let mut is_busy = false;
|
||||
let err = client
|
||||
.do_hole_punching(
|
||||
2,
|
||||
NatType::SymmetricEasyInc.into(),
|
||||
NatType::SymmetricEasyDec.into(),
|
||||
&mut is_busy,
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(is_busy);
|
||||
assert!(err.to_string().contains("remote is busy"));
|
||||
assert_eq!(stun.port_mapping_count.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(
|
||||
runtime.bind_count.load(Ordering::Relaxed),
|
||||
UDP_ARRAY_SIZE_FOR_BOTH_EASY_SYM
|
||||
);
|
||||
|
||||
let both_requests = signaling.both_requests.lock().await;
|
||||
assert_eq!(both_requests.len(), 1);
|
||||
let req = &both_requests[0];
|
||||
assert_eq!(req.public_ip, Ipv4Addr::new(203, 0, 113, 1));
|
||||
assert_eq!(req.dst_port_num, 10020);
|
||||
assert_eq!(
|
||||
req.udp_socket_count,
|
||||
UDP_ARRAY_SIZE_FOR_BOTH_EASY_SYM as u32
|
||||
);
|
||||
assert_eq!(req.wait_time_ms, REMOTE_WAIT_TIME_MS as u32);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
use crate::{config::PeerId, proto::common::NatType};
|
||||
|
||||
pub const BLACKLIST_TIMEOUT_SEC: u64 = 3600;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum UdpPunchClientMethod {
|
||||
None,
|
||||
ConeToCone,
|
||||
SymToCone,
|
||||
EasySymToEasySym,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum UdpNatType {
|
||||
Unknown,
|
||||
Open(NatType),
|
||||
Cone(NatType),
|
||||
EasySymmetric(NatType, bool),
|
||||
HardSymmetric(NatType),
|
||||
}
|
||||
|
||||
impl From<NatType> for UdpNatType {
|
||||
fn from(nat_type: NatType) -> Self {
|
||||
match nat_type {
|
||||
NatType::Unknown => UdpNatType::Unknown,
|
||||
NatType::OpenInternet => UdpNatType::Open(nat_type),
|
||||
NatType::NoPat | NatType::FullCone | NatType::Restricted | NatType::PortRestricted => {
|
||||
UdpNatType::Cone(nat_type)
|
||||
}
|
||||
NatType::Symmetric | NatType::SymUdpFirewall => UdpNatType::HardSymmetric(nat_type),
|
||||
NatType::SymmetricEasyInc => UdpNatType::EasySymmetric(nat_type, true),
|
||||
NatType::SymmetricEasyDec => UdpNatType::EasySymmetric(nat_type, false),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<UdpNatType> for NatType {
|
||||
fn from(val: UdpNatType) -> Self {
|
||||
match val {
|
||||
UdpNatType::Unknown => NatType::Unknown,
|
||||
UdpNatType::Open(nat_type) => nat_type,
|
||||
UdpNatType::Cone(nat_type) => nat_type,
|
||||
UdpNatType::EasySymmetric(nat_type, _) => nat_type,
|
||||
UdpNatType::HardSymmetric(nat_type) => nat_type,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl UdpNatType {
|
||||
pub fn is_open(&self) -> bool {
|
||||
matches!(self, UdpNatType::Open(_))
|
||||
}
|
||||
|
||||
pub fn is_unknown(&self) -> bool {
|
||||
matches!(self, UdpNatType::Unknown)
|
||||
}
|
||||
|
||||
pub fn is_sym(&self) -> bool {
|
||||
self.is_hard_sym() || self.is_easy_sym()
|
||||
}
|
||||
|
||||
pub fn is_hard_sym(&self) -> bool {
|
||||
matches!(self, UdpNatType::HardSymmetric(_))
|
||||
}
|
||||
|
||||
pub fn is_easy_sym(&self) -> bool {
|
||||
matches!(self, UdpNatType::EasySymmetric(_, _))
|
||||
}
|
||||
|
||||
pub fn is_cone(&self) -> bool {
|
||||
matches!(self, UdpNatType::Cone(_))
|
||||
}
|
||||
|
||||
pub fn get_inc_of_easy_sym(&self) -> Option<bool> {
|
||||
match self {
|
||||
UdpNatType::EasySymmetric(_, inc) => Some(*inc),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_punch_hole_method(
|
||||
&self,
|
||||
other: Self,
|
||||
disable_sym_hole_punching: bool,
|
||||
) -> UdpPunchClientMethod {
|
||||
if disable_sym_hole_punching && self.is_sym() {
|
||||
if other.is_sym() {
|
||||
return UdpPunchClientMethod::None;
|
||||
} else {
|
||||
return UdpPunchClientMethod::ConeToCone;
|
||||
}
|
||||
}
|
||||
|
||||
if other.is_unknown() {
|
||||
if self.is_sym() {
|
||||
return UdpPunchClientMethod::SymToCone;
|
||||
} else {
|
||||
return UdpPunchClientMethod::ConeToCone;
|
||||
}
|
||||
}
|
||||
|
||||
if self.is_unknown() {
|
||||
if other.is_sym() {
|
||||
return UdpPunchClientMethod::None;
|
||||
} else {
|
||||
return UdpPunchClientMethod::ConeToCone;
|
||||
}
|
||||
}
|
||||
|
||||
if self.is_open() || other.is_open() {
|
||||
return UdpPunchClientMethod::None;
|
||||
}
|
||||
|
||||
if self.is_cone() {
|
||||
if other.is_sym() {
|
||||
UdpPunchClientMethod::None
|
||||
} else {
|
||||
UdpPunchClientMethod::ConeToCone
|
||||
}
|
||||
} else if self.is_easy_sym() {
|
||||
if other.is_hard_sym() {
|
||||
UdpPunchClientMethod::None
|
||||
} else if other.is_easy_sym() {
|
||||
UdpPunchClientMethod::EasySymToEasySym
|
||||
} else {
|
||||
UdpPunchClientMethod::SymToCone
|
||||
}
|
||||
} else if self.is_hard_sym() {
|
||||
if other.is_sym() {
|
||||
UdpPunchClientMethod::None
|
||||
} else {
|
||||
UdpPunchClientMethod::SymToCone
|
||||
}
|
||||
} else {
|
||||
unreachable!("invalid nat type");
|
||||
}
|
||||
}
|
||||
|
||||
pub fn can_punch_hole_as_client(
|
||||
&self,
|
||||
other: Self,
|
||||
my_peer_id: PeerId,
|
||||
dst_peer_id: PeerId,
|
||||
disable_sym_hole_punching: bool,
|
||||
) -> bool {
|
||||
match self.get_punch_hole_method(other, disable_sym_hole_punching) {
|
||||
UdpPunchClientMethod::None => false,
|
||||
UdpPunchClientMethod::ConeToCone | UdpPunchClientMethod::SymToCone => true,
|
||||
UdpPunchClientMethod::EasySymToEasySym => my_peer_id < dst_peer_id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn nat(nat_type: NatType) -> UdpNatType {
|
||||
nat_type.into()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nat_type_classification_matches_proto_values() {
|
||||
assert_eq!(nat(NatType::Unknown), UdpNatType::Unknown);
|
||||
assert_eq!(
|
||||
nat(NatType::OpenInternet),
|
||||
UdpNatType::Open(NatType::OpenInternet)
|
||||
);
|
||||
assert_eq!(nat(NatType::FullCone), UdpNatType::Cone(NatType::FullCone));
|
||||
assert_eq!(
|
||||
nat(NatType::Symmetric),
|
||||
UdpNatType::HardSymmetric(NatType::Symmetric)
|
||||
);
|
||||
assert_eq!(
|
||||
nat(NatType::SymmetricEasyInc),
|
||||
UdpNatType::EasySymmetric(NatType::SymmetricEasyInc, true)
|
||||
);
|
||||
assert_eq!(
|
||||
nat(NatType::SymmetricEasyDec),
|
||||
UdpNatType::EasySymmetric(NatType::SymmetricEasyDec, false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn punch_method_preserves_current_nat_matrix() {
|
||||
let cone = nat(NatType::FullCone);
|
||||
let hard_sym = nat(NatType::Symmetric);
|
||||
let easy_sym = nat(NatType::SymmetricEasyInc);
|
||||
let open = nat(NatType::OpenInternet);
|
||||
let unknown = nat(NatType::Unknown);
|
||||
|
||||
assert_eq!(
|
||||
cone.get_punch_hole_method(cone, false),
|
||||
UdpPunchClientMethod::ConeToCone
|
||||
);
|
||||
assert_eq!(
|
||||
hard_sym.get_punch_hole_method(cone, false),
|
||||
UdpPunchClientMethod::SymToCone
|
||||
);
|
||||
assert_eq!(
|
||||
cone.get_punch_hole_method(hard_sym, false),
|
||||
UdpPunchClientMethod::None
|
||||
);
|
||||
assert_eq!(
|
||||
easy_sym.get_punch_hole_method(easy_sym, false),
|
||||
UdpPunchClientMethod::EasySymToEasySym
|
||||
);
|
||||
assert_eq!(
|
||||
easy_sym.get_punch_hole_method(hard_sym, false),
|
||||
UdpPunchClientMethod::None
|
||||
);
|
||||
assert_eq!(
|
||||
hard_sym.get_punch_hole_method(unknown, false),
|
||||
UdpPunchClientMethod::SymToCone
|
||||
);
|
||||
assert_eq!(
|
||||
unknown.get_punch_hole_method(hard_sym, false),
|
||||
UdpPunchClientMethod::None
|
||||
);
|
||||
assert_eq!(
|
||||
open.get_punch_hole_method(cone, false),
|
||||
UdpPunchClientMethod::None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabled_symmetric_punching_keeps_existing_fallback() {
|
||||
let cone = nat(NatType::FullCone);
|
||||
let hard_sym = nat(NatType::Symmetric);
|
||||
let easy_sym = nat(NatType::SymmetricEasyInc);
|
||||
|
||||
assert_eq!(
|
||||
hard_sym.get_punch_hole_method(cone, true),
|
||||
UdpPunchClientMethod::ConeToCone
|
||||
);
|
||||
assert_eq!(
|
||||
hard_sym.get_punch_hole_method(easy_sym, true),
|
||||
UdpPunchClientMethod::None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easy_sym_to_easy_sym_uses_lower_peer_id_as_client() {
|
||||
let easy_sym = nat(NatType::SymmetricEasyInc);
|
||||
|
||||
assert!(easy_sym.can_punch_hole_as_client(easy_sym, 1, 2, false));
|
||||
assert!(!easy_sym.can_punch_hole_as_client(easy_sym, 2, 1, false));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use anyhow::Error;
|
||||
use dashmap::DashMap;
|
||||
use quanta::Instant;
|
||||
use tokio::{
|
||||
sync::{Mutex, OwnedMutexGuard, TryLockError},
|
||||
task::JoinHandle,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::PeerId,
|
||||
connectivity::stun::StunInfoProvider,
|
||||
foundation::task::{ExternalTaskSignal, PeerTaskLauncher, PeerTaskManager},
|
||||
proto::common::NatType,
|
||||
};
|
||||
|
||||
use crate::connectivity::hole_punch::policy::BackOff;
|
||||
|
||||
use super::{
|
||||
BLACKLIST_TIMEOUT_SEC, UdpBothEasySymPunchClient, UdpHolePunchClientError,
|
||||
UdpHolePunchPeerSource, UdpHolePunchRuntime, UdpHolePunchSignaling, UdpHolePunchTransportSink,
|
||||
UdpNatType, UdpPunchClientMethod, UdpPunchSocket, UdpPunchTaskInfo, UdpSymToConePunchClient,
|
||||
collect_udp_punch_tasks, punch_cone_to_cone, should_blacklist_signal_error,
|
||||
};
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub struct UdpSymPunchLock {
|
||||
inner: Arc<Mutex<()>>,
|
||||
}
|
||||
|
||||
impl UdpSymPunchLock {
|
||||
pub(crate) async fn lock(&self) -> OwnedMutexGuard<()> {
|
||||
self.inner.clone().lock_owned().await
|
||||
}
|
||||
|
||||
pub(crate) fn try_lock(&self) -> Result<OwnedMutexGuard<()>, TryLockError> {
|
||||
self.inner.clone().try_lock_owned()
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpHolePunchBlacklist {
|
||||
items: DashMap<PeerId, Instant>,
|
||||
}
|
||||
|
||||
impl UdpHolePunchBlacklist {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
items: DashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn contains(&self, peer_id: PeerId) -> bool {
|
||||
let Some(insert_time) = self.items.get(&peer_id) else {
|
||||
return false;
|
||||
};
|
||||
let expired = insert_time.elapsed().as_secs() >= BLACKLIST_TIMEOUT_SEC;
|
||||
drop(insert_time);
|
||||
|
||||
if expired {
|
||||
self.items.remove(&peer_id);
|
||||
false
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(&self, peer_id: PeerId) {
|
||||
self.items.insert(peer_id, Instant::now());
|
||||
}
|
||||
|
||||
fn cleanup(&self) {
|
||||
self.items
|
||||
.retain(|_, insert_time| insert_time.elapsed().as_secs() < BLACKLIST_TIMEOUT_SEC);
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpHolePunchConnectorParts<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
peer_source: Arc<P>,
|
||||
signaling: Arc<S>,
|
||||
transport_sink: Arc<T>,
|
||||
runtime: Arc<R>,
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
sym_punch_lock: UdpSymPunchLock,
|
||||
try_cone_before_sym: AtomicBool,
|
||||
}
|
||||
|
||||
pub struct UdpHolePunchConnectorData<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
peer_source: Arc<P>,
|
||||
signaling: Arc<S>,
|
||||
transport_sink: Arc<T>,
|
||||
runtime: Arc<R>,
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
sym_punch_lock: UdpSymPunchLock,
|
||||
blacklist: UdpHolePunchBlacklist,
|
||||
try_cone_before_sym: Arc<AtomicBool>,
|
||||
pub sym_to_cone_client: UdpSymToConePunchClient<R, S>,
|
||||
pub both_easy_sym_client: UdpBothEasySymPunchClient<R, S>,
|
||||
}
|
||||
|
||||
impl<P, S, T, R> UdpHolePunchConnectorData<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
fn new(parts: Arc<UdpHolePunchConnectorParts<P, S, T, R>>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
peer_source: parts.peer_source.clone(),
|
||||
signaling: parts.signaling.clone(),
|
||||
transport_sink: parts.transport_sink.clone(),
|
||||
runtime: parts.runtime.clone(),
|
||||
stun: parts.stun.clone(),
|
||||
sym_punch_lock: parts.sym_punch_lock.clone(),
|
||||
blacklist: UdpHolePunchBlacklist::new(),
|
||||
try_cone_before_sym: Arc::new(AtomicBool::new(
|
||||
parts.try_cone_before_sym.load(Ordering::Relaxed),
|
||||
)),
|
||||
sym_to_cone_client: UdpSymToConePunchClient::new(
|
||||
parts.runtime.clone(),
|
||||
parts.signaling.clone(),
|
||||
parts.stun.clone(),
|
||||
),
|
||||
both_easy_sym_client: UdpBothEasySymPunchClient::new(
|
||||
parts.runtime.clone(),
|
||||
parts.signaling.clone(),
|
||||
parts.stun.clone(),
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn should_skip_blacklisted(&self, peer_id: PeerId) -> bool {
|
||||
if self.blacklist.contains(peer_id) {
|
||||
tracing::debug!(
|
||||
dst_peer_id = peer_id,
|
||||
"peer is blacklisted, skipping hole punching"
|
||||
);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
fn map_client_result(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
ret: Result<Option<UdpPunchSocket>, UdpHolePunchClientError>,
|
||||
) -> Result<Option<UdpPunchSocket>, Error> {
|
||||
match ret {
|
||||
Ok(ret) => Ok(ret),
|
||||
Err(UdpHolePunchClientError::Signaling(err)) => {
|
||||
if should_blacklist_signal_error(&err) {
|
||||
self.blacklist.insert(dst_peer_id);
|
||||
}
|
||||
Err(err.into())
|
||||
}
|
||||
Err(err) => Err(err.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn handle_punch_result(
|
||||
&self,
|
||||
ret: Result<Option<UdpPunchSocket>, Error>,
|
||||
backoff: Option<&mut BackOff>,
|
||||
round: Option<&mut u32>,
|
||||
) -> bool {
|
||||
let op = |rollback: bool| {
|
||||
if rollback {
|
||||
if let Some(backoff) = backoff {
|
||||
backoff.rollback();
|
||||
}
|
||||
if let Some(round) = round {
|
||||
*round = round.saturating_sub(1);
|
||||
}
|
||||
} else if let Some(round) = round {
|
||||
*round += 1;
|
||||
}
|
||||
};
|
||||
|
||||
match ret {
|
||||
Ok(Some(socket)) => {
|
||||
let (connected, requested_url) = socket.into_connected();
|
||||
if let Err(err) = self
|
||||
.transport_sink
|
||||
.add_client_transport(connected, requested_url)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(?err, "upgrade or add UDP hole-punch transport failed");
|
||||
op(true);
|
||||
false
|
||||
} else {
|
||||
tracing::info!(
|
||||
"hole punching transport admitted; awaiting liveness measurement"
|
||||
);
|
||||
true
|
||||
}
|
||||
}
|
||||
Ok(None) => {
|
||||
tracing::info!("hole punching failed, no punched socket");
|
||||
op(false);
|
||||
false
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::info!(?err, "hole punching failed");
|
||||
op(true);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn cone_to_cone(self: Arc<Self>, task_info: UdpPunchTaskInfo) -> Result<(), Error> {
|
||||
let mut backoff = BackOff::new(vec![1000, 1000, 2000, 4000, 4000, 8000, 8000, 16000]);
|
||||
|
||||
loop {
|
||||
backoff.sleep_for_next_backoff().await;
|
||||
|
||||
if self.should_skip_blacklisted(task_info.dst_peer_id) {
|
||||
break;
|
||||
}
|
||||
|
||||
let ret = punch_cone_to_cone(
|
||||
self.runtime.clone(),
|
||||
self.signaling.clone(),
|
||||
task_info.dst_peer_id,
|
||||
)
|
||||
.await;
|
||||
let ret = self.map_client_result(task_info.dst_peer_id, ret);
|
||||
|
||||
if self
|
||||
.handle_punch_result(ret, Some(&mut backoff), None)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn sym_to_cone(self: Arc<Self>, task_info: UdpPunchTaskInfo) -> Result<(), Error> {
|
||||
let mut backoff =
|
||||
BackOff::new(vec![1000, 1000, 2000, 4000, 4000, 8000, 8000, 16000, 64000]);
|
||||
let mut round = 0;
|
||||
let mut port_idx = rand::random();
|
||||
|
||||
loop {
|
||||
backoff.sleep_for_next_backoff().await;
|
||||
|
||||
if self.should_skip_blacklisted(task_info.dst_peer_id) {
|
||||
break;
|
||||
}
|
||||
|
||||
if self.try_cone_before_sym.load(Ordering::Relaxed) {
|
||||
let ret = punch_cone_to_cone(
|
||||
self.runtime.clone(),
|
||||
self.signaling.clone(),
|
||||
task_info.dst_peer_id,
|
||||
)
|
||||
.await;
|
||||
let ret = self.map_client_result(task_info.dst_peer_id, ret);
|
||||
if self.handle_punch_result(ret, None, None).await {
|
||||
break;
|
||||
}
|
||||
if self.should_skip_blacklisted(task_info.dst_peer_id) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let ret = {
|
||||
let _lock = self.sym_punch_lock.lock().await;
|
||||
self.sym_to_cone_client
|
||||
.do_hole_punching(
|
||||
task_info.dst_peer_id,
|
||||
round,
|
||||
&mut port_idx,
|
||||
task_info.my_nat_type,
|
||||
)
|
||||
.await
|
||||
};
|
||||
let ret = self.map_client_result(task_info.dst_peer_id, ret);
|
||||
|
||||
if self
|
||||
.handle_punch_result(ret, Some(&mut backoff), Some(&mut round))
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tracing::instrument(skip(self))]
|
||||
async fn both_easy_sym(self: Arc<Self>, task_info: UdpPunchTaskInfo) -> Result<(), Error> {
|
||||
let mut backoff =
|
||||
BackOff::new(vec![1000, 1000, 2000, 4000, 4000, 8000, 8000, 16000, 64000]);
|
||||
|
||||
loop {
|
||||
backoff.sleep_for_next_backoff().await;
|
||||
|
||||
if self.should_skip_blacklisted(task_info.dst_peer_id) {
|
||||
break;
|
||||
}
|
||||
|
||||
if self.try_cone_before_sym.load(Ordering::Relaxed) {
|
||||
let ret = punch_cone_to_cone(
|
||||
self.runtime.clone(),
|
||||
self.signaling.clone(),
|
||||
task_info.dst_peer_id,
|
||||
)
|
||||
.await;
|
||||
let ret = self.map_client_result(task_info.dst_peer_id, ret);
|
||||
if self.handle_punch_result(ret, None, None).await {
|
||||
break;
|
||||
}
|
||||
if self.should_skip_blacklisted(task_info.dst_peer_id) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
let mut is_busy = false;
|
||||
let ret = {
|
||||
let _lock = self.sym_punch_lock.lock().await;
|
||||
self.both_easy_sym_client
|
||||
.do_hole_punching(
|
||||
task_info.dst_peer_id,
|
||||
task_info.my_nat_type,
|
||||
task_info.dst_nat_type,
|
||||
&mut is_busy,
|
||||
)
|
||||
.await
|
||||
};
|
||||
let ret = self.map_client_result(task_info.dst_peer_id, ret);
|
||||
|
||||
if is_busy {
|
||||
backoff.rollback();
|
||||
} else if self
|
||||
.handle_punch_result(ret, Some(&mut backoff), None)
|
||||
.await
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpHolePunchPeerTaskLauncher<P, S, T, R>(Arc<UdpHolePunchConnectorData<P, S, T, R>>)
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime;
|
||||
|
||||
impl<P, S, T, R> Clone for UdpHolePunchPeerTaskLauncher<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
Self(self.0.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<P, S, T, R> PeerTaskLauncher for UdpHolePunchPeerTaskLauncher<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
type CollectPeerItem = UdpPunchTaskInfo;
|
||||
type TaskRet = ();
|
||||
|
||||
async fn collect_peers_need_task(&self) -> Vec<Self::CollectPeerItem> {
|
||||
let data = &self.0;
|
||||
let my_nat_type = data.stun.get_stun_info().udp_nat_type;
|
||||
let my_nat_type: UdpNatType = NatType::try_from(my_nat_type)
|
||||
.unwrap_or(NatType::Unknown)
|
||||
.into();
|
||||
if !my_nat_type.is_sym() {
|
||||
data.sym_to_cone_client.clear_udp_array().await;
|
||||
}
|
||||
|
||||
if my_nat_type.is_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
data.blacklist.cleanup();
|
||||
|
||||
let my_peer_id = data.peer_source.local_peer_id();
|
||||
let policy = data.peer_source.p2p_policy_flags();
|
||||
let candidates = data.peer_source.candidates().await;
|
||||
let peers_to_connect =
|
||||
collect_udp_punch_tasks(my_peer_id, my_nat_type, policy, candidates, |peer_id| {
|
||||
data.blacklist.contains(peer_id)
|
||||
});
|
||||
for task in &peers_to_connect {
|
||||
tracing::info!(
|
||||
peer_id = task.dst_peer_id,
|
||||
peer_nat_type = ?task.dst_nat_type,
|
||||
?my_nat_type,
|
||||
"found peer to do hole punching"
|
||||
);
|
||||
}
|
||||
|
||||
peers_to_connect
|
||||
}
|
||||
|
||||
async fn launch_task(
|
||||
&self,
|
||||
item: Self::CollectPeerItem,
|
||||
) -> JoinHandle<Result<Self::TaskRet, Error>> {
|
||||
let data = self.0.clone();
|
||||
let disable_sym_hole_punching = data
|
||||
.peer_source
|
||||
.p2p_policy_flags()
|
||||
.disable_sym_hole_punching;
|
||||
let punch_method = item
|
||||
.my_nat_type
|
||||
.get_punch_hole_method(item.dst_nat_type, disable_sym_hole_punching);
|
||||
match punch_method {
|
||||
UdpPunchClientMethod::ConeToCone => tokio::spawn(data.cone_to_cone(item)),
|
||||
UdpPunchClientMethod::SymToCone => tokio::spawn(data.sym_to_cone(item)),
|
||||
UdpPunchClientMethod::EasySymToEasySym => tokio::spawn(data.both_easy_sym(item)),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn all_task_done(&self) {
|
||||
self.0.sym_to_cone_client.clear_udp_array().await;
|
||||
}
|
||||
|
||||
fn loop_interval_ms(&self) -> u64 {
|
||||
5000
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UdpHolePunchConnector<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
client: PeerTaskManager<UdpHolePunchPeerTaskLauncher<P, S, T, R>>,
|
||||
}
|
||||
|
||||
impl<P, S, T, R> UdpHolePunchConnector<P, S, T, R>
|
||||
where
|
||||
P: UdpHolePunchPeerSource + 'static,
|
||||
S: UdpHolePunchSignaling + 'static,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
R: UdpHolePunchRuntime,
|
||||
{
|
||||
pub fn new(
|
||||
peer_source: Arc<P>,
|
||||
signaling: Arc<S>,
|
||||
transport_sink: Arc<T>,
|
||||
runtime: Arc<R>,
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
sym_punch_lock: UdpSymPunchLock,
|
||||
external_signal: Option<Arc<ExternalTaskSignal>>,
|
||||
) -> Self {
|
||||
let parts = Arc::new(UdpHolePunchConnectorParts {
|
||||
peer_source,
|
||||
signaling,
|
||||
transport_sink,
|
||||
runtime,
|
||||
stun,
|
||||
sym_punch_lock,
|
||||
try_cone_before_sym: AtomicBool::new(true),
|
||||
});
|
||||
let data = UdpHolePunchConnectorData::new(parts);
|
||||
Self {
|
||||
client: PeerTaskManager::new_with_external_signal(
|
||||
UdpHolePunchPeerTaskLauncher(data),
|
||||
external_signal,
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_as_client(&self) {
|
||||
self.client.start();
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
self.client.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::UdpSymPunchLock;
|
||||
|
||||
#[test]
|
||||
fn symmetric_punch_locks_are_scoped_per_instance() {
|
||||
let first = UdpSymPunchLock::default();
|
||||
let first_clone = first.clone();
|
||||
let second = UdpSymPunchLock::default();
|
||||
|
||||
let _first_guard = first.try_lock().unwrap();
|
||||
assert!(first_clone.try_lock().is_err());
|
||||
assert!(second.try_lock().is_ok());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
mod binding;
|
||||
mod client;
|
||||
mod common;
|
||||
mod connector;
|
||||
mod punch_listener;
|
||||
mod rpc;
|
||||
mod runtime;
|
||||
mod server;
|
||||
mod socket_array;
|
||||
mod task;
|
||||
|
||||
pub(crate) use binding::CoreUdpHolePunchService;
|
||||
pub(crate) use client::{
|
||||
UdpBothEasySymPunchClient, UdpHolePunchClientError, UdpSymToConePunchClient, punch_cone_to_cone,
|
||||
};
|
||||
pub(crate) use common::{BLACKLIST_TIMEOUT_SEC, UdpNatType, UdpPunchClientMethod};
|
||||
pub(crate) use connector::{UdpHolePunchConnector, UdpSymPunchLock};
|
||||
pub(crate) use punch_listener::{
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS, ReusableUdpPunchListener, can_reuse_port_mapping_listener,
|
||||
can_reuse_public_listener, select_reusable_port_mapping_listener_idx,
|
||||
select_reusable_public_listener_idx, should_create_public_listener,
|
||||
should_retry_public_listener_selection,
|
||||
};
|
||||
pub(crate) use rpc::UdpHolePunchRpcSource;
|
||||
pub(crate) use runtime::{
|
||||
ProtocolUdpHolePunchTransportSink, SelectPunchListener, SelectPunchListenerResponse,
|
||||
SendPunchPacketBothEasySym, SendPunchPacketBothEasySymResponse, SendPunchPacketCone,
|
||||
SendPunchPacketEasySym, SendPunchPacketHardSym, SendPunchPacketHardSymResponse,
|
||||
UdpHolePunchInbound, UdpHolePunchPeerSource, UdpHolePunchRuntime, UdpHolePunchSignalError,
|
||||
UdpHolePunchSignaling, UdpHolePunchTransportSink, UdpPunchAcceptor, UdpPunchListener,
|
||||
UdpPunchSocket, UdpResolvedPublicAddr, should_blacklist_signal_error,
|
||||
};
|
||||
pub(crate) use server::UdpHolePunchServer;
|
||||
pub(crate) use socket_array::UdpSocketArray;
|
||||
pub(crate) use task::{UdpPunchCandidate, UdpPunchTaskInfo, collect_udp_punch_tasks};
|
||||
|
||||
const fn udp_packet_len(body_len: u16) -> usize {
|
||||
crate::packet::UDP_TUNNEL_HEADER_SIZE + body_len as usize
|
||||
}
|
||||
+195
@@ -0,0 +1,195 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use quanta::Instant;
|
||||
|
||||
pub const MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS: usize = 4;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct ReusableUdpPunchListener {
|
||||
pub running: bool,
|
||||
pub mapped_addr: SocketAddr,
|
||||
pub has_port_mapping_lease: bool,
|
||||
pub last_active_time: Instant,
|
||||
}
|
||||
|
||||
pub fn can_reuse_public_listener(listener: &ReusableUdpPunchListener) -> bool {
|
||||
listener.running && !listener.mapped_addr.ip().is_unspecified()
|
||||
}
|
||||
|
||||
pub fn can_reuse_port_mapping_listener(listener: &ReusableUdpPunchListener) -> bool {
|
||||
can_reuse_public_listener(listener) && listener.has_port_mapping_lease
|
||||
}
|
||||
|
||||
pub fn select_reusable_public_listener_idx(
|
||||
listeners: &[ReusableUdpPunchListener],
|
||||
) -> Option<usize> {
|
||||
listeners
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, listener)| can_reuse_public_listener(listener))
|
||||
.max_by_key(|(_, listener)| listener.last_active_time)
|
||||
.map(|(idx, _)| idx)
|
||||
}
|
||||
|
||||
pub fn select_reusable_port_mapping_listener_idx(
|
||||
listeners: &[ReusableUdpPunchListener],
|
||||
) -> Option<usize> {
|
||||
listeners
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, listener)| can_reuse_port_mapping_listener(listener))
|
||||
.max_by_key(|(_, listener)| listener.last_active_time)
|
||||
.map(|(idx, _)| idx)
|
||||
}
|
||||
|
||||
pub fn should_create_public_listener(
|
||||
current_listener_count: usize,
|
||||
has_reusable_listener: bool,
|
||||
has_port_mapping_listener: bool,
|
||||
force_new_listener: bool,
|
||||
prefer_port_mapping: bool,
|
||||
) -> bool {
|
||||
if current_listener_count >= MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS {
|
||||
return false;
|
||||
}
|
||||
|
||||
if current_listener_count == 0 {
|
||||
return true;
|
||||
}
|
||||
|
||||
if force_new_listener {
|
||||
return true;
|
||||
}
|
||||
|
||||
if prefer_port_mapping && !has_port_mapping_listener {
|
||||
return true;
|
||||
}
|
||||
|
||||
!has_reusable_listener
|
||||
}
|
||||
|
||||
pub fn should_retry_public_listener_selection(
|
||||
force_new_listener: bool,
|
||||
current_listener_count: usize,
|
||||
prefer_port_mapping: bool,
|
||||
has_port_mapping_listener: bool,
|
||||
) -> bool {
|
||||
if prefer_port_mapping && has_port_mapping_listener {
|
||||
return false;
|
||||
}
|
||||
|
||||
!force_new_listener && current_listener_count < MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn listener(
|
||||
port: u16,
|
||||
running: bool,
|
||||
has_port_mapping_lease: bool,
|
||||
active_age: Duration,
|
||||
) -> ReusableUdpPunchListener {
|
||||
ReusableUdpPunchListener {
|
||||
running,
|
||||
mapped_addr: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
|
||||
has_port_mapping_lease,
|
||||
last_active_time: Instant::now() - active_age,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_prefers_reuse_before_cap() {
|
||||
assert!(!should_create_public_listener(1, true, true, false, false));
|
||||
assert!(!should_create_public_listener(
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS,
|
||||
true,
|
||||
true,
|
||||
false,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_creates_when_empty_or_no_reusable_listener() {
|
||||
assert!(should_create_public_listener(0, false, false, false, false));
|
||||
assert!(should_create_public_listener(1, false, false, false, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_force_new_respects_cap() {
|
||||
assert!(should_create_public_listener(1, true, true, true, false));
|
||||
assert!(!should_create_public_listener(
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS,
|
||||
true,
|
||||
true,
|
||||
true,
|
||||
false
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_prefers_port_mapping_until_available() {
|
||||
assert!(should_create_public_listener(1, true, false, false, true));
|
||||
assert!(!should_create_public_listener(1, true, true, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_selection_retry_respects_cap() {
|
||||
assert!(should_retry_public_listener_selection(
|
||||
false, 1, false, false
|
||||
));
|
||||
assert!(!should_retry_public_listener_selection(
|
||||
false,
|
||||
MAX_PUBLIC_UDP_HOLE_PUNCH_LISTENERS,
|
||||
false,
|
||||
false
|
||||
));
|
||||
assert!(!should_retry_public_listener_selection(
|
||||
true, 1, false, false
|
||||
));
|
||||
assert!(!should_retry_public_listener_selection(
|
||||
false, 1, true, true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_most_recent_reusable_public_listener() {
|
||||
let listeners = vec![
|
||||
listener(1000, true, false, Duration::from_secs(10)),
|
||||
listener(1001, false, false, Duration::from_secs(1)),
|
||||
listener(1002, true, false, Duration::from_secs(2)),
|
||||
];
|
||||
|
||||
assert_eq!(select_reusable_public_listener_idx(&listeners), Some(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_most_recent_reusable_port_mapping_listener() {
|
||||
let listeners = vec![
|
||||
listener(1000, true, false, Duration::from_secs(1)),
|
||||
listener(1001, true, true, Duration::from_secs(10)),
|
||||
listener(1002, true, true, Duration::from_secs(2)),
|
||||
];
|
||||
|
||||
assert_eq!(
|
||||
select_reusable_port_mapping_listener_idx(&listeners),
|
||||
Some(2)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unspecified_addr_is_not_reusable() {
|
||||
let mut listener = listener(1000, true, true, Duration::ZERO);
|
||||
listener.mapped_addr = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 1000));
|
||||
|
||||
assert!(!can_reuse_public_listener(&listener));
|
||||
assert!(!can_reuse_port_mapping_listener(&listener));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,828 @@
|
||||
use std::{fmt, net::SocketAddr, sync::Arc};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{
|
||||
config::PeerId,
|
||||
connectivity::hole_punch::udp::{
|
||||
SelectPunchListener, SelectPunchListenerResponse as CoreSelectPunchListenerResponse,
|
||||
SendPunchPacketBothEasySym,
|
||||
SendPunchPacketBothEasySymResponse as CoreSendPunchPacketBothEasySymResponse,
|
||||
SendPunchPacketCone, SendPunchPacketEasySym, SendPunchPacketHardSym,
|
||||
SendPunchPacketHardSymResponse as CoreSendPunchPacketHardSymResponse, UdpHolePunchInbound,
|
||||
UdpHolePunchRuntime, UdpHolePunchServer as CoreUdpHolePunchServer, UdpHolePunchSignalError,
|
||||
UdpHolePunchSignaling, UdpHolePunchTransportSink, UdpSymPunchLock,
|
||||
},
|
||||
connectivity::stun::StunInfoProvider,
|
||||
proto::{
|
||||
common::Void,
|
||||
peer_rpc::{
|
||||
SelectPunchListenerRequest, SelectPunchListenerResponse,
|
||||
SendPunchPacketBothEasySymRequest, SendPunchPacketBothEasySymResponse,
|
||||
SendPunchPacketConeRequest, SendPunchPacketEasySymRequest,
|
||||
SendPunchPacketHardSymRequest, SendPunchPacketHardSymResponse, UdpHolePunchRpc,
|
||||
},
|
||||
rpc_types::{self, controller::BaseController},
|
||||
},
|
||||
};
|
||||
|
||||
const CONE_RPC_TIMEOUT_MS: i32 = 4000;
|
||||
const SYMMETRIC_RPC_TIMEOUT_MS: i32 = 4000;
|
||||
const BOTH_EASY_SYMMETRIC_RPC_TIMEOUT_MS: i32 = 2000;
|
||||
|
||||
fn cone_controller() -> BaseController {
|
||||
BaseController {
|
||||
timeout_ms: CONE_RPC_TIMEOUT_MS,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn symmetric_controller() -> BaseController {
|
||||
BaseController {
|
||||
timeout_ms: SYMMETRIC_RPC_TIMEOUT_MS,
|
||||
trace_id: 0,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn both_easy_symmetric_controller() -> BaseController {
|
||||
BaseController {
|
||||
timeout_ms: BOTH_EASY_SYMMETRIC_RPC_TIMEOUT_MS,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn select_listener_request_to_rpc(request: SelectPunchListener) -> SelectPunchListenerRequest {
|
||||
SelectPunchListenerRequest {
|
||||
force_new: request.force_new,
|
||||
prefer_port_mapping: request.prefer_port_mapping,
|
||||
}
|
||||
}
|
||||
|
||||
fn select_listener_request_from_rpc(input: SelectPunchListenerRequest) -> SelectPunchListener {
|
||||
SelectPunchListener {
|
||||
force_new: input.force_new,
|
||||
prefer_port_mapping: input.prefer_port_mapping,
|
||||
}
|
||||
}
|
||||
|
||||
fn select_listener_response_from_rpc(
|
||||
response: SelectPunchListenerResponse,
|
||||
) -> Result<CoreSelectPunchListenerResponse, UdpHolePunchSignalError> {
|
||||
Ok(CoreSelectPunchListenerResponse {
|
||||
listener_mapped_addr: SocketAddr::from(
|
||||
response
|
||||
.listener_mapped_addr
|
||||
.ok_or_else(|| missing_field("listener_mapped_addr"))?,
|
||||
),
|
||||
})
|
||||
}
|
||||
|
||||
fn select_listener_response_to_rpc(
|
||||
response: CoreSelectPunchListenerResponse,
|
||||
) -> SelectPunchListenerResponse {
|
||||
SelectPunchListenerResponse {
|
||||
listener_mapped_addr: Some(response.listener_mapped_addr.into()),
|
||||
}
|
||||
}
|
||||
|
||||
fn cone_request_to_rpc(request: SendPunchPacketCone) -> SendPunchPacketConeRequest {
|
||||
SendPunchPacketConeRequest {
|
||||
listener_mapped_addr: Some(request.listener_mapped_addr.into()),
|
||||
dest_addr: Some(request.dest_addr.into()),
|
||||
transaction_id: request.transaction_id,
|
||||
packet_count_per_batch: request.packet_count_per_batch,
|
||||
packet_batch_count: request.packet_batch_count,
|
||||
packet_interval_ms: request.packet_interval_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn hard_symmetric_request_to_rpc(request: SendPunchPacketHardSym) -> SendPunchPacketHardSymRequest {
|
||||
SendPunchPacketHardSymRequest {
|
||||
listener_mapped_addr: Some(request.listener_mapped_addr.into()),
|
||||
public_ips: request.public_ips.into_iter().map(Into::into).collect(),
|
||||
transaction_id: request.transaction_id,
|
||||
port_index: request.port_index,
|
||||
round: request.round,
|
||||
}
|
||||
}
|
||||
|
||||
fn easy_symmetric_request_to_rpc(request: SendPunchPacketEasySym) -> SendPunchPacketEasySymRequest {
|
||||
SendPunchPacketEasySymRequest {
|
||||
listener_mapped_addr: Some(request.listener_mapped_addr.into()),
|
||||
public_ips: request.public_ips.into_iter().map(Into::into).collect(),
|
||||
transaction_id: request.transaction_id,
|
||||
base_port_num: request.base_port_num,
|
||||
max_port_num: request.max_port_num,
|
||||
is_incremental: request.is_incremental,
|
||||
}
|
||||
}
|
||||
|
||||
fn both_easy_symmetric_request_to_rpc(
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> SendPunchPacketBothEasySymRequest {
|
||||
SendPunchPacketBothEasySymRequest {
|
||||
transaction_id: request.transaction_id,
|
||||
public_ip: Some(request.public_ip.into()),
|
||||
dst_port_num: request.dst_port_num,
|
||||
udp_socket_count: request.udp_socket_count,
|
||||
wait_time_ms: request.wait_time_ms,
|
||||
}
|
||||
}
|
||||
|
||||
fn hard_symmetric_response_from_rpc(
|
||||
response: SendPunchPacketHardSymResponse,
|
||||
) -> CoreSendPunchPacketHardSymResponse {
|
||||
CoreSendPunchPacketHardSymResponse {
|
||||
next_port_index: response.next_port_index,
|
||||
}
|
||||
}
|
||||
|
||||
fn hard_symmetric_response_to_rpc(
|
||||
response: CoreSendPunchPacketHardSymResponse,
|
||||
) -> SendPunchPacketHardSymResponse {
|
||||
SendPunchPacketHardSymResponse {
|
||||
next_port_index: response.next_port_index,
|
||||
}
|
||||
}
|
||||
|
||||
fn both_easy_symmetric_response_from_rpc(
|
||||
response: SendPunchPacketBothEasySymResponse,
|
||||
) -> CoreSendPunchPacketBothEasySymResponse {
|
||||
CoreSendPunchPacketBothEasySymResponse {
|
||||
is_busy: response.is_busy,
|
||||
base_mapped_addr: response.base_mapped_addr.map(SocketAddr::from),
|
||||
}
|
||||
}
|
||||
|
||||
fn both_easy_symmetric_response_to_rpc(
|
||||
response: CoreSendPunchPacketBothEasySymResponse,
|
||||
) -> SendPunchPacketBothEasySymResponse {
|
||||
SendPunchPacketBothEasySymResponse {
|
||||
is_busy: response.is_busy,
|
||||
base_mapped_addr: response.base_mapped_addr.map(Into::into),
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrow source of peer-scoped UDP hole-punch RPC stubs.
|
||||
///
|
||||
/// Implemented only by the sealed peer adapter in `super::peer_adapters`.
|
||||
pub trait UdpHolePunchRpcSource: Send + Sync + 'static {
|
||||
fn local_peer_id(&self) -> PeerId;
|
||||
|
||||
fn rpc_stub(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
) -> Box<dyn UdpHolePunchRpc<Controller = BaseController> + Send + Sync + 'static>;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct PeerRpcUdpHolePunchSignaling<P>
|
||||
where
|
||||
P: UdpHolePunchRpcSource,
|
||||
{
|
||||
rpc_source: Arc<P>,
|
||||
}
|
||||
|
||||
impl<P> fmt::Debug for PeerRpcUdpHolePunchSignaling<P>
|
||||
where
|
||||
P: UdpHolePunchRpcSource,
|
||||
{
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
formatter
|
||||
.debug_struct("PeerRpcUdpHolePunchSignaling")
|
||||
.field("my_peer_id", &self.rpc_source.local_peer_id())
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
impl<P> PeerRpcUdpHolePunchSignaling<P>
|
||||
where
|
||||
P: UdpHolePunchRpcSource,
|
||||
{
|
||||
pub(super) fn new(rpc_source: Arc<P>) -> Self {
|
||||
Self { rpc_source }
|
||||
}
|
||||
|
||||
fn rpc_stub(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
) -> Box<dyn UdpHolePunchRpc<Controller = BaseController> + Send + Sync + 'static> {
|
||||
self.rpc_source.rpc_stub(dst_peer_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn map_rpc_error(error: rpc_types::error::Error) -> UdpHolePunchSignalError {
|
||||
match error {
|
||||
rpc_types::error::Error::InvalidServiceKey(_, _) => {
|
||||
UdpHolePunchSignalError::InvalidServiceKey
|
||||
}
|
||||
rpc_types::error::Error::Timeout(_) => UdpHolePunchSignalError::Timeout,
|
||||
rpc_types::error::Error::ExecutionError(error) => {
|
||||
UdpHolePunchSignalError::RemoteRejected(error.to_string())
|
||||
}
|
||||
other => UdpHolePunchSignalError::Transport(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn missing_field(field: &str) -> UdpHolePunchSignalError {
|
||||
UdpHolePunchSignalError::RemoteRejected(format!("missing {field}"))
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<P> UdpHolePunchSignaling for PeerRpcUdpHolePunchSignaling<P>
|
||||
where
|
||||
P: UdpHolePunchRpcSource,
|
||||
{
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
request: SelectPunchListener,
|
||||
) -> Result<CoreSelectPunchListenerResponse, UdpHolePunchSignalError> {
|
||||
let response = self
|
||||
.rpc_stub(dst_peer_id)
|
||||
.select_punch_listener(
|
||||
BaseController::default(),
|
||||
select_listener_request_to_rpc(request),
|
||||
)
|
||||
.await
|
||||
.map_err(map_rpc_error)?;
|
||||
|
||||
select_listener_response_from_rpc(response)
|
||||
}
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
self.rpc_stub(dst_peer_id)
|
||||
.send_punch_packet_cone(cone_controller(), cone_request_to_rpc(request))
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(map_rpc_error)
|
||||
}
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
request: SendPunchPacketHardSym,
|
||||
) -> Result<CoreSendPunchPacketHardSymResponse, UdpHolePunchSignalError> {
|
||||
let response = self
|
||||
.rpc_stub(dst_peer_id)
|
||||
.send_punch_packet_hard_sym(
|
||||
symmetric_controller(),
|
||||
hard_symmetric_request_to_rpc(request),
|
||||
)
|
||||
.await
|
||||
.map_err(map_rpc_error)?;
|
||||
|
||||
Ok(hard_symmetric_response_from_rpc(response))
|
||||
}
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
request: SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
self.rpc_stub(dst_peer_id)
|
||||
.send_punch_packet_easy_sym(
|
||||
symmetric_controller(),
|
||||
easy_symmetric_request_to_rpc(request),
|
||||
)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(map_rpc_error)
|
||||
}
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
dst_peer_id: PeerId,
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> Result<CoreSendPunchPacketBothEasySymResponse, UdpHolePunchSignalError> {
|
||||
let response = self
|
||||
.rpc_stub(dst_peer_id)
|
||||
.send_punch_packet_both_easy_sym(
|
||||
both_easy_symmetric_controller(),
|
||||
both_easy_symmetric_request_to_rpc(request),
|
||||
)
|
||||
.await
|
||||
.map_err(map_rpc_error)?;
|
||||
|
||||
Ok(both_easy_symmetric_response_from_rpc(response))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct UdpHolePunchRpcEndpoint<R, T>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
{
|
||||
inner: CoreUdpHolePunchServer<R, T>,
|
||||
}
|
||||
|
||||
impl<R, T> UdpHolePunchRpcEndpoint<R, T>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
{
|
||||
pub(super) fn new(
|
||||
stun: Arc<dyn StunInfoProvider>,
|
||||
transport_sink: Arc<T>,
|
||||
sym_punch_lock: UdpSymPunchLock,
|
||||
runtime: Arc<R>,
|
||||
) -> Arc<Self> {
|
||||
let inner = CoreUdpHolePunchServer::new(runtime, stun, transport_sink, sym_punch_lock);
|
||||
Arc::new(Self { inner })
|
||||
}
|
||||
|
||||
pub(super) async fn start(&self) {
|
||||
self.inner.start().await;
|
||||
}
|
||||
|
||||
pub(super) fn begin_stop(&self) {
|
||||
self.inner.begin_stop();
|
||||
}
|
||||
|
||||
pub(super) async fn stop(&self) {
|
||||
self.inner.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn signal_error_to_rpc_error(error: UdpHolePunchSignalError) -> rpc_types::error::Error {
|
||||
match error {
|
||||
UdpHolePunchSignalError::InvalidServiceKey => rpc_types::error::Error::InvalidServiceKey(
|
||||
"UdpHolePunchRpc".to_owned(),
|
||||
"UdpHolePunchRpc".to_owned(),
|
||||
),
|
||||
UdpHolePunchSignalError::Timeout => anyhow::anyhow!("timeout").into(),
|
||||
UdpHolePunchSignalError::RemoteRejected(message)
|
||||
| UdpHolePunchSignalError::Transport(message) => anyhow::anyhow!(message).into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn cone_request_from_rpc(
|
||||
input: SendPunchPacketConeRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketCone> {
|
||||
let listener_addr = input.listener_mapped_addr.ok_or(anyhow::anyhow!(
|
||||
"send_punch_packet_for_cone request missing listener_mapped_addr"
|
||||
))?;
|
||||
let dest_addr = input.dest_addr.ok_or(anyhow::anyhow!(
|
||||
"send_punch_packet_for_cone request missing dest_addr"
|
||||
))?;
|
||||
Ok(SendPunchPacketCone {
|
||||
listener_mapped_addr: listener_addr.into(),
|
||||
dest_addr: dest_addr.into(),
|
||||
transaction_id: input.transaction_id,
|
||||
packet_count_per_batch: input.packet_count_per_batch,
|
||||
packet_batch_count: input.packet_batch_count,
|
||||
packet_interval_ms: input.packet_interval_ms,
|
||||
})
|
||||
}
|
||||
|
||||
fn hard_symmetric_request_from_rpc(
|
||||
input: SendPunchPacketHardSymRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketHardSym> {
|
||||
let listener_addr = input.listener_mapped_addr.ok_or(anyhow::anyhow!(
|
||||
"try_punch_symmetric request missing listener_addr"
|
||||
))?;
|
||||
Ok(SendPunchPacketHardSym {
|
||||
listener_mapped_addr: listener_addr.into(),
|
||||
public_ips: input.public_ips.into_iter().map(Into::into).collect(),
|
||||
transaction_id: input.transaction_id,
|
||||
port_index: input.port_index,
|
||||
round: input.round,
|
||||
})
|
||||
}
|
||||
|
||||
fn easy_symmetric_request_from_rpc(
|
||||
input: SendPunchPacketEasySymRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketEasySym> {
|
||||
let listener_addr = input.listener_mapped_addr.ok_or(anyhow::anyhow!(
|
||||
"send_punch_packet_easy_sym request missing listener_addr"
|
||||
))?;
|
||||
Ok(SendPunchPacketEasySym {
|
||||
listener_mapped_addr: listener_addr.into(),
|
||||
public_ips: input.public_ips.into_iter().map(Into::into).collect(),
|
||||
transaction_id: input.transaction_id,
|
||||
base_port_num: input.base_port_num,
|
||||
max_port_num: input.max_port_num,
|
||||
is_incremental: input.is_incremental,
|
||||
})
|
||||
}
|
||||
|
||||
fn both_easy_symmetric_request_from_rpc(
|
||||
input: SendPunchPacketBothEasySymRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketBothEasySym> {
|
||||
let public_ip = input
|
||||
.public_ip
|
||||
.ok_or(anyhow::anyhow!("public_ip is required"))?;
|
||||
Ok(SendPunchPacketBothEasySym {
|
||||
transaction_id: input.transaction_id,
|
||||
public_ip: public_ip.into(),
|
||||
dst_port_num: input.dst_port_num,
|
||||
udp_socket_count: input.udp_socket_count,
|
||||
wait_time_ms: input.wait_time_ms,
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<R, T> UdpHolePunchInbound for UdpHolePunchRpcEndpoint<R, T>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
{
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
request: SelectPunchListener,
|
||||
) -> Result<CoreSelectPunchListenerResponse, UdpHolePunchSignalError> {
|
||||
self.inner.select_punch_listener(request).await
|
||||
}
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
self.inner.send_punch_packet_cone(request).await
|
||||
}
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
request: SendPunchPacketHardSym,
|
||||
) -> Result<CoreSendPunchPacketHardSymResponse, UdpHolePunchSignalError> {
|
||||
self.inner.send_punch_packet_hard_sym(request).await
|
||||
}
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
request: SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError> {
|
||||
self.inner.send_punch_packet_easy_sym(request).await
|
||||
}
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> Result<CoreSendPunchPacketBothEasySymResponse, UdpHolePunchSignalError> {
|
||||
self.inner.send_punch_packet_both_easy_sym(request).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<R, T> UdpHolePunchRpc for UdpHolePunchRpcEndpoint<R, T>
|
||||
where
|
||||
R: UdpHolePunchRuntime,
|
||||
T: UdpHolePunchTransportSink + 'static,
|
||||
{
|
||||
type Controller = BaseController;
|
||||
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
_controller: Self::Controller,
|
||||
input: SelectPunchListenerRequest,
|
||||
) -> rpc_types::error::Result<SelectPunchListenerResponse> {
|
||||
let response = UdpHolePunchInbound::select_punch_listener(
|
||||
self,
|
||||
select_listener_request_from_rpc(input),
|
||||
)
|
||||
.await
|
||||
.map_err(signal_error_to_rpc_error)?;
|
||||
|
||||
Ok(select_listener_response_to_rpc(response))
|
||||
}
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
_controller: Self::Controller,
|
||||
input: SendPunchPacketConeRequest,
|
||||
) -> rpc_types::error::Result<Void> {
|
||||
UdpHolePunchInbound::send_punch_packet_cone(self, cone_request_from_rpc(input)?)
|
||||
.await
|
||||
.map_err(signal_error_to_rpc_error)?;
|
||||
|
||||
Ok(Void::default())
|
||||
}
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
_controller: Self::Controller,
|
||||
input: SendPunchPacketHardSymRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketHardSymResponse> {
|
||||
let response = UdpHolePunchInbound::send_punch_packet_hard_sym(
|
||||
self,
|
||||
hard_symmetric_request_from_rpc(input)?,
|
||||
)
|
||||
.await
|
||||
.map_err(signal_error_to_rpc_error)?;
|
||||
|
||||
Ok(hard_symmetric_response_to_rpc(response))
|
||||
}
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
_controller: Self::Controller,
|
||||
input: SendPunchPacketEasySymRequest,
|
||||
) -> rpc_types::error::Result<Void> {
|
||||
UdpHolePunchInbound::send_punch_packet_easy_sym(
|
||||
self,
|
||||
easy_symmetric_request_from_rpc(input)?,
|
||||
)
|
||||
.await
|
||||
.map_err(signal_error_to_rpc_error)?;
|
||||
|
||||
Ok(Void::default())
|
||||
}
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
_controller: Self::Controller,
|
||||
input: SendPunchPacketBothEasySymRequest,
|
||||
) -> rpc_types::error::Result<SendPunchPacketBothEasySymResponse> {
|
||||
let response = UdpHolePunchInbound::send_punch_packet_both_easy_sym(
|
||||
self,
|
||||
both_easy_symmetric_request_from_rpc(input)?,
|
||||
)
|
||||
.await
|
||||
.map_err(signal_error_to_rpc_error)?;
|
||||
|
||||
Ok(both_easy_symmetric_response_to_rpc(response))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{future, net::Ipv4Addr, time::Duration};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn outbound_rpc_controllers_preserve_timeouts() {
|
||||
assert_eq!(cone_controller().timeout_ms, 4000);
|
||||
assert_eq!(symmetric_controller().timeout_ms, 4000);
|
||||
assert_eq!(symmetric_controller().trace_id, 0);
|
||||
assert_eq!(both_easy_symmetric_controller().timeout_ms, 2000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn select_listener_dto_preserves_fields_and_requires_response_addr() {
|
||||
let domain_request = SelectPunchListener {
|
||||
force_new: true,
|
||||
prefer_port_mapping: false,
|
||||
};
|
||||
let rpc_request = select_listener_request_to_rpc(domain_request.clone());
|
||||
assert!(rpc_request.force_new);
|
||||
assert!(!rpc_request.prefer_port_mapping);
|
||||
assert_eq!(
|
||||
select_listener_request_from_rpc(SelectPunchListenerRequest {
|
||||
force_new: true,
|
||||
prefer_port_mapping: false,
|
||||
}),
|
||||
domain_request
|
||||
);
|
||||
|
||||
let mapped_addr: SocketAddr = "198.51.100.1:31001".parse().unwrap();
|
||||
let core_response = CoreSelectPunchListenerResponse {
|
||||
listener_mapped_addr: mapped_addr,
|
||||
};
|
||||
let rpc_response = select_listener_response_to_rpc(core_response.clone());
|
||||
assert_eq!(
|
||||
SocketAddr::from(rpc_response.listener_mapped_addr.unwrap()),
|
||||
mapped_addr
|
||||
);
|
||||
assert_eq!(
|
||||
select_listener_response_from_rpc(rpc_response).unwrap(),
|
||||
core_response
|
||||
);
|
||||
|
||||
let error =
|
||||
select_listener_response_from_rpc(SelectPunchListenerResponse::default()).unwrap_err();
|
||||
assert_eq!(
|
||||
error,
|
||||
UdpHolePunchSignalError::RemoteRejected("missing listener_mapped_addr".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cone_dto_round_trip_preserves_all_fields() {
|
||||
let request = SendPunchPacketCone {
|
||||
listener_mapped_addr: "198.51.100.2:31002".parse().unwrap(),
|
||||
dest_addr: "203.0.113.2:32002".parse().unwrap(),
|
||||
transaction_id: 12,
|
||||
packet_count_per_batch: 3,
|
||||
packet_batch_count: 4,
|
||||
packet_interval_ms: 500,
|
||||
};
|
||||
|
||||
let rpc = cone_request_to_rpc(request.clone());
|
||||
assert_eq!(
|
||||
SocketAddr::from(rpc.listener_mapped_addr.unwrap()),
|
||||
request.listener_mapped_addr
|
||||
);
|
||||
assert_eq!(SocketAddr::from(rpc.dest_addr.unwrap()), request.dest_addr);
|
||||
assert_eq!(rpc.transaction_id, 12);
|
||||
assert_eq!(rpc.packet_count_per_batch, 3);
|
||||
assert_eq!(rpc.packet_batch_count, 4);
|
||||
assert_eq!(rpc.packet_interval_ms, 500);
|
||||
assert_eq!(cone_request_from_rpc(rpc).unwrap(), request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hard_symmetric_dto_round_trip_preserves_all_fields() {
|
||||
let request = SendPunchPacketHardSym {
|
||||
listener_mapped_addr: "198.51.100.3:31003".parse().unwrap(),
|
||||
public_ips: vec![Ipv4Addr::new(203, 0, 113, 3), Ipv4Addr::new(203, 0, 113, 4)],
|
||||
transaction_id: 13,
|
||||
port_index: 17,
|
||||
round: 19,
|
||||
};
|
||||
|
||||
let rpc = hard_symmetric_request_to_rpc(request.clone());
|
||||
assert_eq!(
|
||||
SocketAddr::from(rpc.listener_mapped_addr.unwrap()),
|
||||
request.listener_mapped_addr
|
||||
);
|
||||
assert_eq!(
|
||||
rpc.public_ips
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(Ipv4Addr::from)
|
||||
.collect::<Vec<_>>(),
|
||||
request.public_ips
|
||||
);
|
||||
assert_eq!(rpc.transaction_id, 13);
|
||||
assert_eq!(rpc.port_index, 17);
|
||||
assert_eq!(rpc.round, 19);
|
||||
assert_eq!(hard_symmetric_request_from_rpc(rpc).unwrap(), request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easy_symmetric_dto_round_trip_preserves_all_fields() {
|
||||
let request = SendPunchPacketEasySym {
|
||||
listener_mapped_addr: "198.51.100.5:31005".parse().unwrap(),
|
||||
public_ips: vec![Ipv4Addr::new(203, 0, 113, 5)],
|
||||
transaction_id: 15,
|
||||
base_port_num: 33000,
|
||||
max_port_num: 51,
|
||||
is_incremental: true,
|
||||
};
|
||||
|
||||
let rpc = easy_symmetric_request_to_rpc(request.clone());
|
||||
assert_eq!(
|
||||
SocketAddr::from(rpc.listener_mapped_addr.unwrap()),
|
||||
request.listener_mapped_addr
|
||||
);
|
||||
assert_eq!(
|
||||
rpc.public_ips
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(Ipv4Addr::from)
|
||||
.collect::<Vec<_>>(),
|
||||
request.public_ips
|
||||
);
|
||||
assert_eq!(rpc.transaction_id, 15);
|
||||
assert_eq!(rpc.base_port_num, 33000);
|
||||
assert_eq!(rpc.max_port_num, 51);
|
||||
assert!(rpc.is_incremental);
|
||||
assert_eq!(easy_symmetric_request_from_rpc(rpc).unwrap(), request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_easy_symmetric_dto_round_trip_preserves_all_fields() {
|
||||
let request = SendPunchPacketBothEasySym {
|
||||
udp_socket_count: 25,
|
||||
public_ip: Ipv4Addr::new(203, 0, 113, 6),
|
||||
transaction_id: 16,
|
||||
dst_port_num: 34000,
|
||||
wait_time_ms: 2500,
|
||||
};
|
||||
|
||||
let rpc = both_easy_symmetric_request_to_rpc(request.clone());
|
||||
assert_eq!(rpc.udp_socket_count, 25);
|
||||
assert_eq!(Ipv4Addr::from(rpc.public_ip.unwrap()), request.public_ip);
|
||||
assert_eq!(rpc.transaction_id, 16);
|
||||
assert_eq!(rpc.dst_port_num, 34000);
|
||||
assert_eq!(rpc.wait_time_ms, 2500);
|
||||
assert_eq!(both_easy_symmetric_request_from_rpc(rpc).unwrap(), request);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rpc_response_dtos_preserve_all_fields() {
|
||||
let hard_response = CoreSendPunchPacketHardSymResponse {
|
||||
next_port_index: 41,
|
||||
};
|
||||
let hard_rpc = hard_symmetric_response_to_rpc(hard_response.clone());
|
||||
assert_eq!(hard_rpc.next_port_index, 41);
|
||||
assert_eq!(hard_symmetric_response_from_rpc(hard_rpc), hard_response);
|
||||
|
||||
let both_response = CoreSendPunchPacketBothEasySymResponse {
|
||||
is_busy: true,
|
||||
base_mapped_addr: Some("198.51.100.8:31008".parse().unwrap()),
|
||||
};
|
||||
let both_rpc = both_easy_symmetric_response_to_rpc(both_response.clone());
|
||||
assert!(both_rpc.is_busy);
|
||||
assert_eq!(
|
||||
SocketAddr::from(both_rpc.base_mapped_addr.unwrap()),
|
||||
both_response.base_mapped_addr.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
both_easy_symmetric_response_from_rpc(both_rpc),
|
||||
both_response
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inbound_rpc_dtos_reject_missing_required_fields() {
|
||||
let cone_listener_error = cone_request_from_rpc(SendPunchPacketConeRequest::default())
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
cone_listener_error,
|
||||
"Rust error: send_punch_packet_for_cone request missing listener_mapped_addr"
|
||||
);
|
||||
|
||||
let cone_dest_error = cone_request_from_rpc(SendPunchPacketConeRequest {
|
||||
listener_mapped_addr: Some("198.51.100.7:31007".parse::<SocketAddr>().unwrap().into()),
|
||||
..Default::default()
|
||||
})
|
||||
.unwrap_err()
|
||||
.to_string();
|
||||
assert_eq!(
|
||||
cone_dest_error,
|
||||
"Rust error: send_punch_packet_for_cone request missing dest_addr"
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
hard_symmetric_request_from_rpc(SendPunchPacketHardSymRequest::default())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Rust error: try_punch_symmetric request missing listener_addr"
|
||||
);
|
||||
assert_eq!(
|
||||
easy_symmetric_request_from_rpc(SendPunchPacketEasySymRequest::default())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Rust error: send_punch_packet_easy_sym request missing listener_addr"
|
||||
);
|
||||
assert_eq!(
|
||||
both_easy_symmetric_request_from_rpc(SendPunchPacketBothEasySymRequest::default())
|
||||
.unwrap_err()
|
||||
.to_string(),
|
||||
"Rust error: public_ip is required"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rpc_errors_keep_domain_classification() {
|
||||
assert_eq!(
|
||||
map_rpc_error(rpc_types::error::Error::InvalidServiceKey(
|
||||
"service".to_owned(),
|
||||
"proto".to_owned()
|
||||
)),
|
||||
UdpHolePunchSignalError::InvalidServiceKey
|
||||
);
|
||||
assert_eq!(
|
||||
map_rpc_error(rpc_types::error::Error::ExecutionError(anyhow::anyhow!(
|
||||
"rejected"
|
||||
))),
|
||||
UdpHolePunchSignalError::RemoteRejected("rejected".to_owned())
|
||||
);
|
||||
assert_eq!(
|
||||
map_rpc_error(rpc_types::error::Error::TunnelError("closed".to_owned())),
|
||||
UdpHolePunchSignalError::Transport("Tunnel error: closed".to_owned())
|
||||
);
|
||||
|
||||
let elapsed = tokio::time::timeout(Duration::ZERO, future::pending::<()>())
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
map_rpc_error(rpc_types::error::Error::Timeout(elapsed)),
|
||||
UdpHolePunchSignalError::Timeout
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn domain_errors_keep_rpc_classification() {
|
||||
assert!(matches!(
|
||||
signal_error_to_rpc_error(UdpHolePunchSignalError::InvalidServiceKey),
|
||||
rpc_types::error::Error::InvalidServiceKey(_, _)
|
||||
));
|
||||
for (domain_error, expected_message) in [
|
||||
(UdpHolePunchSignalError::Timeout, "timeout"),
|
||||
(
|
||||
UdpHolePunchSignalError::RemoteRejected("rejected".to_owned()),
|
||||
"rejected",
|
||||
),
|
||||
(
|
||||
UdpHolePunchSignalError::Transport("closed".to_owned()),
|
||||
"closed",
|
||||
),
|
||||
] {
|
||||
let rpc_types::error::Error::ExecutionError(error) =
|
||||
signal_error_to_rpc_error(domain_error)
|
||||
else {
|
||||
panic!("domain error should map to execution error");
|
||||
};
|
||||
assert_eq!(error.to_string(), expected_message);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,524 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use super::super::{HolePunchTunnelSink, port_mapping::UdpPortMappingLease};
|
||||
|
||||
use crate::{
|
||||
config::P2pPolicyFlags,
|
||||
connectivity::{
|
||||
protocol::ClientProtocolUpgrader,
|
||||
transport::{ConnectedTransport, ConnectedUdpSession},
|
||||
},
|
||||
foundation::task::ExternalTaskSignal,
|
||||
peers::PeerConnectionOrigin,
|
||||
socket::{
|
||||
ListenerConnectionCounter, SocketContext,
|
||||
udp::{UdpBindOptions, UdpSession, VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
},
|
||||
tunnel::Tunnel,
|
||||
};
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpPunchAcceptor: Send {
|
||||
async fn accept(&mut self) -> anyhow::Result<UdpPunchSocket>;
|
||||
}
|
||||
|
||||
pub struct UdpPunchSocket {
|
||||
session: UdpSession,
|
||||
requested_remote_addr: SocketAddr,
|
||||
lifetime_guard: Box<dyn Send + Sync>,
|
||||
}
|
||||
|
||||
impl UdpPunchSocket {
|
||||
pub fn new<G>(session: UdpSession, requested_remote_addr: SocketAddr, lifetime_guard: G) -> Self
|
||||
where
|
||||
G: Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
session,
|
||||
requested_remote_addr,
|
||||
lifetime_guard: Box::new(lifetime_guard),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn into_connected(self) -> (ConnectedUdpSession, url::Url) {
|
||||
(
|
||||
ConnectedUdpSession::new(self.session, self.lifetime_guard),
|
||||
udp_url(self.requested_remote_addr),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for UdpPunchSocket {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("UdpPunchSocket")
|
||||
.field("session", &self.session)
|
||||
.field("requested_remote_addr", &self.requested_remote_addr)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
fn udp_url(addr: SocketAddr) -> url::Url {
|
||||
let mut url = url::Url::parse("udp://0.0.0.0").expect("static UDP URL should be valid");
|
||||
url.set_ip_host(addr.ip())
|
||||
.expect("socket IP should be a valid URL host");
|
||||
url.set_port(Some(addr.port()))
|
||||
.expect("UDP URL should accept a port");
|
||||
url
|
||||
}
|
||||
|
||||
pub struct UdpPunchListener<S> {
|
||||
pub socket: Arc<S>,
|
||||
pub mapped_addr: SocketAddr,
|
||||
pub conn_counter: Arc<dyn ListenerConnectionCounter>,
|
||||
pub acceptor: Box<dyn UdpPunchAcceptor>,
|
||||
pub(crate) port_mapping_lease: Option<Box<dyn UdpPortMappingLease>>,
|
||||
}
|
||||
|
||||
pub struct UdpResolvedPublicAddr {
|
||||
pub mapped_addr: SocketAddr,
|
||||
pub(crate) port_mapping_lease: Option<Box<dyn UdpPortMappingLease>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SelectPunchListener {
|
||||
pub force_new: bool,
|
||||
pub prefer_port_mapping: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SelectPunchListenerResponse {
|
||||
pub listener_mapped_addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketCone {
|
||||
pub listener_mapped_addr: SocketAddr,
|
||||
pub dest_addr: SocketAddr,
|
||||
pub transaction_id: u32,
|
||||
pub packet_count_per_batch: u32,
|
||||
pub packet_batch_count: u32,
|
||||
pub packet_interval_ms: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketHardSym {
|
||||
pub listener_mapped_addr: SocketAddr,
|
||||
pub public_ips: Vec<Ipv4Addr>,
|
||||
pub transaction_id: u32,
|
||||
pub port_index: u32,
|
||||
pub round: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketHardSymResponse {
|
||||
pub next_port_index: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketEasySym {
|
||||
pub listener_mapped_addr: SocketAddr,
|
||||
pub public_ips: Vec<Ipv4Addr>,
|
||||
pub transaction_id: u32,
|
||||
pub base_port_num: u32,
|
||||
pub max_port_num: u32,
|
||||
pub is_incremental: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketBothEasySym {
|
||||
pub udp_socket_count: u32,
|
||||
pub public_ip: Ipv4Addr,
|
||||
pub transaction_id: u32,
|
||||
pub dst_port_num: u32,
|
||||
pub wait_time_ms: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SendPunchPacketBothEasySymResponse {
|
||||
pub is_busy: bool,
|
||||
pub base_mapped_addr: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
|
||||
pub enum UdpHolePunchSignalError {
|
||||
#[error("invalid service key")]
|
||||
InvalidServiceKey,
|
||||
#[error("timeout")]
|
||||
Timeout,
|
||||
#[error("remote rejected: {0}")]
|
||||
RemoteRejected(String),
|
||||
#[error("transport: {0}")]
|
||||
Transport(String),
|
||||
}
|
||||
|
||||
pub fn should_blacklist_signal_error(error: &UdpHolePunchSignalError) -> bool {
|
||||
matches!(error, UdpHolePunchSignalError::InvalidServiceKey)
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpHolePunchSignaling: Send + Sync {
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
dst_peer_id: crate::config::PeerId,
|
||||
request: SelectPunchListener,
|
||||
) -> Result<SelectPunchListenerResponse, UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
dst_peer_id: crate::config::PeerId,
|
||||
request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
dst_peer_id: crate::config::PeerId,
|
||||
request: SendPunchPacketHardSym,
|
||||
) -> Result<SendPunchPacketHardSymResponse, UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
dst_peer_id: crate::config::PeerId,
|
||||
request: SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
dst_peer_id: crate::config::PeerId,
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> Result<SendPunchPacketBothEasySymResponse, UdpHolePunchSignalError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpHolePunchInbound: Send + Sync {
|
||||
async fn select_punch_listener(
|
||||
&self,
|
||||
request: SelectPunchListener,
|
||||
) -> Result<SelectPunchListenerResponse, UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_cone(
|
||||
&self,
|
||||
request: SendPunchPacketCone,
|
||||
) -> Result<(), UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_hard_sym(
|
||||
&self,
|
||||
request: SendPunchPacketHardSym,
|
||||
) -> Result<SendPunchPacketHardSymResponse, UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_easy_sym(
|
||||
&self,
|
||||
request: SendPunchPacketEasySym,
|
||||
) -> Result<(), UdpHolePunchSignalError>;
|
||||
|
||||
async fn send_punch_packet_both_easy_sym(
|
||||
&self,
|
||||
request: SendPunchPacketBothEasySym,
|
||||
) -> Result<SendPunchPacketBothEasySymResponse, UdpHolePunchSignalError>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpHolePunchTransportSink: Send + Sync {
|
||||
async fn add_client_transport(
|
||||
&self,
|
||||
connected: ConnectedUdpSession,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<()>;
|
||||
|
||||
async fn add_server_transport(
|
||||
&self,
|
||||
connected: ConnectedUdpSession,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
pub struct ProtocolUdpHolePunchTransportSink<TcpSocket, T> {
|
||||
protocol: Arc<dyn ClientProtocolUpgrader<TcpSocket>>,
|
||||
tunnel_sink: Arc<T>,
|
||||
}
|
||||
|
||||
impl<TcpSocket: 'static, T> ProtocolUdpHolePunchTransportSink<TcpSocket, T> {
|
||||
pub fn new(protocol: Arc<dyn ClientProtocolUpgrader<TcpSocket>>, tunnel_sink: Arc<T>) -> Self {
|
||||
Self {
|
||||
protocol,
|
||||
tunnel_sink,
|
||||
}
|
||||
}
|
||||
|
||||
async fn upgrade(
|
||||
&self,
|
||||
connected: ConnectedUdpSession,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>> {
|
||||
self.protocol
|
||||
.upgrade_client(ConnectedTransport::Udp(connected), requested_url)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<TcpSocket, T> UdpHolePunchTransportSink for ProtocolUdpHolePunchTransportSink<TcpSocket, T>
|
||||
where
|
||||
TcpSocket: 'static,
|
||||
T: HolePunchTunnelSink,
|
||||
{
|
||||
async fn add_client_transport(
|
||||
&self,
|
||||
connected: ConnectedUdpSession,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<()> {
|
||||
let tunnel = self.upgrade(connected, requested_url).await?;
|
||||
self.tunnel_sink
|
||||
.add_client_tunnel(tunnel, PeerConnectionOrigin::UdpHolePunch)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn add_server_transport(
|
||||
&self,
|
||||
connected: ConnectedUdpSession,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<()> {
|
||||
let tunnel = self.upgrade(connected, requested_url).await?;
|
||||
self.tunnel_sink
|
||||
.add_server_tunnel(tunnel, PeerConnectionOrigin::UdpHolePunch)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpHolePunchPeerSource: Send + Sync {
|
||||
fn local_peer_id(&self) -> crate::config::PeerId;
|
||||
fn p2p_policy_flags(&self) -> P2pPolicyFlags;
|
||||
|
||||
async fn candidates(&self) -> Vec<super::UdpPunchCandidate>;
|
||||
|
||||
fn p2p_demand_notify(&self) -> Arc<ExternalTaskSignal>;
|
||||
|
||||
fn is_local_virtual_ip(&self, ip: &IpAddr) -> bool;
|
||||
|
||||
async fn is_easytier_managed_ipv6(&self, ip: &Ipv6Addr) -> bool;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait UdpHolePunchRuntime: Send + Sync + 'static {
|
||||
type Socket: VirtualUdpSocket + 'static;
|
||||
|
||||
fn socket_context(&self) -> SocketContext {
|
||||
SocketContext::default()
|
||||
}
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>>;
|
||||
|
||||
async fn bind_direct_connect_udp(&self) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
UdpHolePunchRuntime::bind_udp(
|
||||
self,
|
||||
UdpBindOptions::direct_connect().with_context(
|
||||
self.socket_context()
|
||||
.with_ip_version(crate::socket::IpVersion::V4),
|
||||
),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn resolve_udp_public_addr(
|
||||
&self,
|
||||
socket: Arc<Self::Socket>,
|
||||
) -> anyhow::Result<UdpResolvedPublicAddr>;
|
||||
|
||||
async fn create_listener(
|
||||
&self,
|
||||
prefer_port_mapping: bool,
|
||||
) -> anyhow::Result<UdpPunchListener<Self::Socket>>;
|
||||
|
||||
async fn create_port_bound_listener(
|
||||
&self,
|
||||
port: u16,
|
||||
) -> anyhow::Result<UdpPunchListener<Self::Socket>>;
|
||||
|
||||
async fn connect_with_socket(
|
||||
&self,
|
||||
socket: Arc<Self::Socket>,
|
||||
remote: SocketAddr,
|
||||
) -> anyhow::Result<UdpPunchSocket>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<T> VirtualUdpSocketFactory for T
|
||||
where
|
||||
T: UdpHolePunchRuntime + Send + Sync + 'static,
|
||||
{
|
||||
type Socket = T::Socket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
UdpHolePunchRuntime::bind_udp(self, options).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::socket::udp::UdpSessionKind;
|
||||
|
||||
struct MockSocket {
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], _addr: SocketAddr) -> io::Result<usize> {
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
struct DropSignal(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for DropSignal {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockProtocol {
|
||||
upgrades: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ClientProtocolUpgrader<()> for MockProtocol {
|
||||
fn supports_scheme(&self, scheme: &str) -> bool {
|
||||
scheme == "udp"
|
||||
}
|
||||
|
||||
async fn upgrade_client(
|
||||
&self,
|
||||
connected: ConnectedTransport<()>,
|
||||
requested_url: url::Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>> {
|
||||
self.upgrades.fetch_add(1, Ordering::Relaxed);
|
||||
let ConnectedTransport::Udp(connected) = connected else {
|
||||
anyhow::bail!("expected UDP transport");
|
||||
};
|
||||
Ok(crate::connectivity::protocol::raw::upgrade_connected_udp(
|
||||
connected,
|
||||
requested_url,
|
||||
)?)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockTunnelSink {
|
||||
clients: AtomicUsize,
|
||||
servers: AtomicUsize,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl HolePunchTunnelSink for MockTunnelSink {
|
||||
async fn add_client_tunnel(
|
||||
&self,
|
||||
_tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()> {
|
||||
assert_eq!(origin, PeerConnectionOrigin::UdpHolePunch);
|
||||
self.clients.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_server_tunnel(
|
||||
&self,
|
||||
_tunnel: Box<dyn Tunnel>,
|
||||
origin: PeerConnectionOrigin,
|
||||
) -> anyhow::Result<()> {
|
||||
assert_eq!(origin, PeerConnectionOrigin::UdpHolePunch);
|
||||
self.servers.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn punched_socket(local_port: u16, remote_port: u16) -> UdpPunchSocket {
|
||||
let remote_addr = SocketAddr::from(([203, 0, 113, 1], remote_port));
|
||||
let session = UdpSession::identity_standalone(
|
||||
Arc::new(MockSocket {
|
||||
local_addr: SocketAddr::from(([127, 0, 0, 1], local_port)),
|
||||
}),
|
||||
remote_addr,
|
||||
UdpSessionKind::EasyTierMux,
|
||||
)
|
||||
.unwrap();
|
||||
UdpPunchSocket::new(session, remote_addr, ())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn protocol_sink_upgrades_before_role_specific_admission() {
|
||||
let protocol = Arc::new(MockProtocol::default());
|
||||
let tunnel_sink = Arc::new(MockTunnelSink::default());
|
||||
let sink =
|
||||
ProtocolUdpHolePunchTransportSink::<(), _>::new(protocol.clone(), tunnel_sink.clone());
|
||||
|
||||
let (client, client_url) = punched_socket(1000, 2000).into_connected();
|
||||
sink.add_client_transport(client, client_url).await.unwrap();
|
||||
let (server, server_url) = punched_socket(1001, 2001).into_connected();
|
||||
sink.add_server_transport(server, server_url).await.unwrap();
|
||||
|
||||
assert_eq!(protocol.upgrades.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(tunnel_sink.clients.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(tunnel_sink.servers.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn punched_socket_preserves_requested_and_resolved_addresses() {
|
||||
let local_addr = SocketAddr::from(([127, 0, 0, 1], 1000));
|
||||
let requested_remote_addr = SocketAddr::from(([198, 51, 100, 1], 2000));
|
||||
let resolved_remote_addr = SocketAddr::from(([203, 0, 113, 1], 3000));
|
||||
let session = UdpSession::identity_standalone(
|
||||
Arc::new(MockSocket { local_addr }),
|
||||
resolved_remote_addr,
|
||||
UdpSessionKind::EasyTierMux,
|
||||
)
|
||||
.unwrap();
|
||||
let guard_dropped = Arc::new(AtomicBool::new(false));
|
||||
let socket = UdpPunchSocket::new(
|
||||
session,
|
||||
requested_remote_addr,
|
||||
DropSignal(guard_dropped.clone()),
|
||||
);
|
||||
|
||||
let (connected, requested_url) = socket.into_connected();
|
||||
let tunnel =
|
||||
crate::connectivity::protocol::raw::upgrade_connected_udp(connected, requested_url)
|
||||
.unwrap();
|
||||
let info = tunnel.info().unwrap();
|
||||
let local_url: url::Url = info.local_addr.unwrap().into();
|
||||
let remote_url: url::Url = info.remote_addr.unwrap().into();
|
||||
let resolved_url: url::Url = info.resolved_remote_addr.unwrap().into();
|
||||
|
||||
assert_eq!(local_url.host_str(), Some("127.0.0.1"));
|
||||
assert_eq!(local_url.port(), Some(local_addr.port()));
|
||||
assert_eq!(remote_url.host_str(), Some("198.51.100.1"));
|
||||
assert_eq!(remote_url.port(), Some(requested_remote_addr.port()));
|
||||
assert_eq!(resolved_url.host_str(), Some("203.0.113.1"));
|
||||
assert_eq!(resolved_url.port(), Some(resolved_remote_addr.port()));
|
||||
assert!(!guard_dropped.load(Ordering::Relaxed));
|
||||
drop(tunnel);
|
||||
assert!(guard_dropped.load(Ordering::Relaxed));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+379
@@ -0,0 +1,379 @@
|
||||
use std::{
|
||||
fmt::Debug,
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use dashmap::{DashMap, DashSet};
|
||||
use tokio::task::JoinSet;
|
||||
use tracing::{Instrument, Level, instrument};
|
||||
|
||||
use crate::{
|
||||
foundation::task::reap_joinset_background,
|
||||
packet::{HOLE_PUNCH_PACKET_BODY_LEN, hole_punch_packet_tid},
|
||||
socket::{
|
||||
IpVersion, SocketContext,
|
||||
udp::{UdpBindOptions, VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
pub struct PunchedUdpSocket<S> {
|
||||
pub socket: Arc<S>,
|
||||
pub tid: u32,
|
||||
pub remote_addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl<S> Debug for PunchedUdpSocket<S> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("PunchedUdpSocket")
|
||||
.field("tid", &self.tid)
|
||||
.field("remote_addr", &self.remote_addr)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UdpSocketArray<R>
|
||||
where
|
||||
R: VirtualUdpSocketFactory,
|
||||
{
|
||||
sockets: Arc<DashMap<SocketAddr, Arc<R::Socket>>>,
|
||||
max_socket_count: usize,
|
||||
socket_factory: Arc<R>,
|
||||
socket_context: SocketContext,
|
||||
tasks: Arc<Mutex<JoinSet<()>>>,
|
||||
|
||||
interest_tids: Arc<DashSet<u32>>,
|
||||
tid_to_socket: Arc<DashMap<u32, Vec<PunchedUdpSocket<R::Socket>>>>,
|
||||
}
|
||||
|
||||
impl<R> UdpSocketArray<R>
|
||||
where
|
||||
R: VirtualUdpSocketFactory,
|
||||
{
|
||||
pub fn new_with_context(
|
||||
max_socket_count: usize,
|
||||
socket_factory: Arc<R>,
|
||||
socket_context: SocketContext,
|
||||
) -> Self {
|
||||
let tasks = Arc::new(Mutex::new(JoinSet::new()));
|
||||
tokio::spawn(reap_joinset_background(
|
||||
Arc::downgrade(&tasks),
|
||||
"UdpSocketArray",
|
||||
));
|
||||
|
||||
Self {
|
||||
sockets: Arc::new(DashMap::new()),
|
||||
max_socket_count,
|
||||
socket_factory,
|
||||
socket_context,
|
||||
tasks,
|
||||
|
||||
interest_tids: Arc::new(DashSet::new()),
|
||||
tid_to_socket: Arc::new(DashMap::new()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn started(&self) -> bool {
|
||||
!self.sockets.is_empty()
|
||||
}
|
||||
|
||||
pub async fn add_new_socket(&self, socket: Arc<R::Socket>) -> anyhow::Result<()> {
|
||||
let socket_map = self.sockets.clone();
|
||||
let local_addr = socket.local_addr()?;
|
||||
let interest_tids = self.interest_tids.clone();
|
||||
let tid_to_socket = self.tid_to_socket.clone();
|
||||
socket_map.insert(local_addr, socket.clone());
|
||||
self.tasks.lock().unwrap().spawn(
|
||||
async move {
|
||||
let _socket_map_guard = RemoveSocketOnDrop {
|
||||
sockets: socket_map,
|
||||
local_addr,
|
||||
};
|
||||
let mut buf = [0u8; super::udp_packet_len(HOLE_PUNCH_PACKET_BODY_LEN)];
|
||||
tracing::trace!(?local_addr, "udp socket added");
|
||||
loop {
|
||||
let Ok((len, addr)) = socket.recv_from(&mut buf).await else {
|
||||
break;
|
||||
};
|
||||
|
||||
tracing::debug!(?len, ?addr, "got raw packet");
|
||||
|
||||
let packet = &buf[..len];
|
||||
let Some(tid) = hole_punch_packet_tid(packet, HOLE_PUNCH_PACKET_BODY_LEN)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
tracing::debug!(?addr, ?tid, "got udp hole punch packet");
|
||||
|
||||
if interest_tids.contains(&tid) {
|
||||
tracing::info!(?addr, ?tid, "got hole punching packet with interest tid");
|
||||
tid_to_socket
|
||||
.entry(tid)
|
||||
.or_default()
|
||||
.push(PunchedUdpSocket {
|
||||
socket: socket.clone(),
|
||||
tid,
|
||||
remote_addr: addr,
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
tracing::debug!(?local_addr, "udp socket recv loop end");
|
||||
}
|
||||
.instrument(tracing::info_span!("udp array socket recv loop")),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(err)]
|
||||
pub async fn start(&self) -> anyhow::Result<()> {
|
||||
tracing::info!("starting udp socket array");
|
||||
|
||||
while self.sockets.len() < self.max_socket_count {
|
||||
let socket = self
|
||||
.socket_factory
|
||||
.bind_udp(
|
||||
UdpBindOptions::hole_punch_candidate()
|
||||
.with_context(self.socket_context.clone().with_ip_version(IpVersion::V4)),
|
||||
)
|
||||
.await?;
|
||||
self.add_new_socket(socket).await?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(err)]
|
||||
pub async fn send_with_all(&self, data: &[u8], addr: SocketAddr) -> anyhow::Result<()> {
|
||||
tracing::info!(?addr, "sending hole punching packet");
|
||||
|
||||
let sockets = self
|
||||
.sockets
|
||||
.iter()
|
||||
.map(|s| s.value().clone())
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
for socket in sockets.iter() {
|
||||
for _ in 0..3 {
|
||||
socket.send_to(data, addr).await?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[instrument(ret(level = Level::DEBUG))]
|
||||
pub fn try_fetch_punched_socket(&self, tid: u32) -> Option<PunchedUdpSocket<R::Socket>> {
|
||||
tracing::debug!(?tid, "try fetch punched socket");
|
||||
self.tid_to_socket.get_mut(&tid)?.value_mut().pop()
|
||||
}
|
||||
|
||||
pub fn add_interest_tid(&self, tid: u32) {
|
||||
self.interest_tids.insert(tid);
|
||||
}
|
||||
|
||||
pub fn add_intreast_tid(&self, tid: u32) {
|
||||
self.add_interest_tid(tid);
|
||||
}
|
||||
|
||||
pub fn remove_interest_tid(&self, tid: u32) {
|
||||
self.interest_tids.remove(&tid);
|
||||
self.tid_to_socket.remove(&tid);
|
||||
}
|
||||
|
||||
pub fn remove_intreast_tid(&self, tid: u32) {
|
||||
self.remove_interest_tid(tid);
|
||||
}
|
||||
}
|
||||
|
||||
impl<R> Debug for UdpSocketArray<R>
|
||||
where
|
||||
R: VirtualUdpSocketFactory,
|
||||
{
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("UdpSocketArray")
|
||||
.field("sockets", &self.sockets.len())
|
||||
.field("max_socket_count", &self.max_socket_count)
|
||||
.field("started", &self.started())
|
||||
.field("interest_tids", &self.interest_tids.len())
|
||||
.field("tid_to_socket", &self.tid_to_socket.len())
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
struct RemoveSocketOnDrop<S> {
|
||||
sockets: Arc<DashMap<SocketAddr, Arc<S>>>,
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl<S> Drop for RemoveSocketOnDrop<S> {
|
||||
fn drop(&mut self) {
|
||||
self.sockets.remove(&self.local_addr);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io,
|
||||
sync::atomic::{AtomicU16, Ordering},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::Mutex as TokioMutex;
|
||||
|
||||
use super::*;
|
||||
use crate::{packet::new_hole_punch_packet, socket::NetNamespace};
|
||||
|
||||
impl<R> UdpSocketArray<R>
|
||||
where
|
||||
R: VirtualUdpSocketFactory,
|
||||
{
|
||||
fn new(max_socket_count: usize, socket_factory: Arc<R>) -> Self {
|
||||
Self::new_with_context(max_socket_count, socket_factory, SocketContext::default())
|
||||
}
|
||||
}
|
||||
|
||||
struct MockSocket {
|
||||
local_addr: SocketAddr,
|
||||
incoming: TokioMutex<VecDeque<(Vec<u8>, SocketAddr)>>,
|
||||
sent: TokioMutex<Vec<(Vec<u8>, SocketAddr)>>,
|
||||
}
|
||||
|
||||
impl MockSocket {
|
||||
fn new(local_addr: SocketAddr, incoming: Vec<(Vec<u8>, SocketAddr)>) -> Self {
|
||||
Self {
|
||||
local_addr,
|
||||
incoming: TokioMutex::new(incoming.into()),
|
||||
sent: TokioMutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], addr: SocketAddr) -> io::Result<usize> {
|
||||
self.sent.lock().await.push((data.to_vec(), addr));
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
let packet = self.incoming.lock().await.pop_front();
|
||||
let Some((packet, addr)) = packet else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
buf[..packet.len()].copy_from_slice(&packet);
|
||||
Ok((packet.len(), addr))
|
||||
}
|
||||
}
|
||||
|
||||
struct MockFactory {
|
||||
next_port: AtomicU16,
|
||||
bind_options: TokioMutex<Vec<UdpBindOptions>>,
|
||||
}
|
||||
|
||||
impl MockFactory {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
next_port: AtomicU16::new(10000),
|
||||
bind_options: TokioMutex::new(Vec::new()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocketFactory for MockFactory {
|
||||
type Socket = MockSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.bind_options.lock().await.push(options);
|
||||
let port = self.next_port.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(Arc::new(MockSocket::new(
|
||||
SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
Vec::new(),
|
||||
)))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fetches_socket_when_interested_tid_is_received() {
|
||||
let runtime = Arc::new(MockFactory::new());
|
||||
let array = UdpSocketArray::new(0, runtime);
|
||||
let tid = 7;
|
||||
let remote_addr = SocketAddr::from(([10, 0, 0, 1], 1234));
|
||||
let packet = new_hole_punch_packet(tid, HOLE_PUNCH_PACKET_BODY_LEN)
|
||||
.into_bytes()
|
||||
.to_vec();
|
||||
let socket = Arc::new(MockSocket::new(
|
||||
SocketAddr::from(([127, 0, 0, 1], 20000)),
|
||||
vec![(packet, remote_addr)],
|
||||
));
|
||||
|
||||
array.add_interest_tid(tid);
|
||||
array.add_new_socket(socket.clone()).await.unwrap();
|
||||
|
||||
for _ in 0..10 {
|
||||
if let Some(punched) = array.try_fetch_punched_socket(tid) {
|
||||
assert_eq!(punched.tid, tid);
|
||||
assert_eq!(punched.remote_addr, remote_addr);
|
||||
assert!(Arc::ptr_eq(&punched.socket, &socket));
|
||||
return;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
|
||||
panic!("punched socket was not recorded");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn send_with_all_sends_three_packets_per_socket() {
|
||||
let runtime = Arc::new(MockFactory::new());
|
||||
let array = UdpSocketArray::new(0, runtime);
|
||||
let socket = Arc::new(MockSocket::new(
|
||||
SocketAddr::from(([127, 0, 0, 1], 20001)),
|
||||
Vec::new(),
|
||||
));
|
||||
let remote_addr = SocketAddr::from(([10, 0, 0, 2], 1235));
|
||||
|
||||
array.add_new_socket(socket.clone()).await.unwrap();
|
||||
array.send_with_all(b"abc", remote_addr).await.unwrap();
|
||||
|
||||
let sent = socket.sent.lock().await;
|
||||
assert_eq!(sent.len(), 3);
|
||||
assert!(
|
||||
sent.iter()
|
||||
.all(|(data, addr)| data == b"abc" && *addr == remote_addr)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn start_binds_up_to_max_socket_count() {
|
||||
let runtime = Arc::new(MockFactory::new());
|
||||
let context = SocketContext::default()
|
||||
.with_socket_mark(Some(0))
|
||||
.with_netns(Some(NetNamespace::new("instance-a")));
|
||||
let array = UdpSocketArray::new_with_context(2, runtime.clone(), context.clone());
|
||||
|
||||
array.start().await.unwrap();
|
||||
|
||||
assert!(array.started());
|
||||
assert_eq!(array.sockets.len(), 2);
|
||||
|
||||
let bind_options = runtime.bind_options.lock().await;
|
||||
assert_eq!(
|
||||
bind_options.as_slice(),
|
||||
&[
|
||||
UdpBindOptions::hole_punch_candidate()
|
||||
.with_context(context.clone().with_ip_version(IpVersion::V4)),
|
||||
UdpBindOptions::hole_punch_candidate()
|
||||
.with_context(context.with_ip_version(IpVersion::V4)),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
use crate::{
|
||||
config::{P2pPolicyFlags, PeerId},
|
||||
proto::common::{NatType, PeerFeatureFlag},
|
||||
};
|
||||
|
||||
use super::{
|
||||
super::policy::{should_background_p2p_with_peer, should_try_p2p_with_peer},
|
||||
UdpNatType,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct UdpPunchCandidate {
|
||||
pub peer_id: PeerId,
|
||||
pub udp_nat_type: NatType,
|
||||
pub feature_flag: Option<PeerFeatureFlag>,
|
||||
pub has_direct_connection: bool,
|
||||
pub has_recent_traffic: bool,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Hash, Eq, PartialEq)]
|
||||
pub struct UdpPunchTaskInfo {
|
||||
pub dst_peer_id: PeerId,
|
||||
pub dst_nat_type: UdpNatType,
|
||||
pub my_nat_type: UdpNatType,
|
||||
}
|
||||
|
||||
pub fn collect_udp_punch_tasks<I, F>(
|
||||
my_peer_id: PeerId,
|
||||
my_nat_type: UdpNatType,
|
||||
policy: P2pPolicyFlags,
|
||||
candidates: I,
|
||||
is_blacklisted: F,
|
||||
) -> Vec<UdpPunchTaskInfo>
|
||||
where
|
||||
I: IntoIterator<Item = UdpPunchCandidate>,
|
||||
F: Fn(PeerId) -> bool,
|
||||
{
|
||||
if my_nat_type.is_open() {
|
||||
return Vec::new();
|
||||
}
|
||||
|
||||
candidates
|
||||
.into_iter()
|
||||
.filter_map(|candidate| {
|
||||
let static_allowed = should_background_p2p_with_peer(
|
||||
candidate.feature_flag.as_ref(),
|
||||
false,
|
||||
policy.lazy_p2p,
|
||||
policy.disable_p2p,
|
||||
policy.need_p2p,
|
||||
);
|
||||
let dynamic_allowed = should_try_p2p_with_peer(
|
||||
candidate.feature_flag.as_ref(),
|
||||
false,
|
||||
policy.disable_p2p,
|
||||
policy.need_p2p,
|
||||
) && candidate.has_recent_traffic;
|
||||
if !static_allowed && !dynamic_allowed {
|
||||
return None;
|
||||
}
|
||||
|
||||
let peer_id = candidate.peer_id;
|
||||
if is_blacklisted(peer_id) || candidate.has_direct_connection {
|
||||
return None;
|
||||
}
|
||||
|
||||
let peer_nat_type = candidate.udp_nat_type.into();
|
||||
if !my_nat_type.can_punch_hole_as_client(
|
||||
peer_nat_type,
|
||||
my_peer_id,
|
||||
peer_id,
|
||||
policy.disable_sym_hole_punching,
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(UdpPunchTaskInfo {
|
||||
dst_peer_id: peer_id,
|
||||
dst_nat_type: peer_nat_type,
|
||||
my_nat_type,
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::proto::common::PeerFeatureFlag;
|
||||
|
||||
fn candidate(peer_id: PeerId, udp_nat_type: NatType) -> UdpPunchCandidate {
|
||||
UdpPunchCandidate {
|
||||
peer_id,
|
||||
udp_nat_type,
|
||||
feature_flag: Some(PeerFeatureFlag::default()),
|
||||
has_direct_connection: false,
|
||||
has_recent_traffic: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn collect(
|
||||
my_peer_id: PeerId,
|
||||
my_nat_type: NatType,
|
||||
policy: P2pPolicyFlags,
|
||||
candidates: Vec<UdpPunchCandidate>,
|
||||
) -> Vec<UdpPunchTaskInfo> {
|
||||
collect_udp_punch_tasks(my_peer_id, my_nat_type.into(), policy, candidates, |_| {
|
||||
false
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn open_nat_does_not_start_udp_punch_tasks() {
|
||||
let tasks = collect(
|
||||
1,
|
||||
NatType::OpenInternet,
|
||||
P2pPolicyFlags::default(),
|
||||
vec![candidate(2, NatType::PortRestricted)],
|
||||
);
|
||||
|
||||
assert!(tasks.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lazy_p2p_allows_recent_traffic_without_need_p2p_flag() {
|
||||
let mut idle = candidate(2, NatType::PortRestricted);
|
||||
idle.feature_flag = Some(PeerFeatureFlag {
|
||||
need_p2p: false,
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
let mut active = idle.clone();
|
||||
active.peer_id = 3;
|
||||
active.has_recent_traffic = true;
|
||||
|
||||
let tasks = collect(
|
||||
1,
|
||||
NatType::PortRestricted,
|
||||
P2pPolicyFlags {
|
||||
lazy_p2p: true,
|
||||
..Default::default()
|
||||
},
|
||||
vec![idle, active],
|
||||
);
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].dst_peer_id, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skips_blacklisted_and_directly_connected_candidates() {
|
||||
let mut direct = candidate(2, NatType::PortRestricted);
|
||||
direct.has_direct_connection = true;
|
||||
|
||||
let tasks = collect_udp_punch_tasks(
|
||||
1,
|
||||
NatType::PortRestricted.into(),
|
||||
P2pPolicyFlags::default(),
|
||||
vec![direct, candidate(3, NatType::PortRestricted)],
|
||||
|peer_id| peer_id == 3,
|
||||
);
|
||||
|
||||
assert!(tasks.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn filters_candidates_by_udp_nat_method() {
|
||||
let tasks = collect(
|
||||
1,
|
||||
NatType::PortRestricted,
|
||||
P2pPolicyFlags::default(),
|
||||
vec![
|
||||
candidate(2, NatType::Symmetric),
|
||||
candidate(3, NatType::PortRestricted),
|
||||
],
|
||||
);
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].dst_peer_id, 3);
|
||||
assert_eq!(tasks[0].dst_nat_type, NatType::PortRestricted.into());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn easy_symmetric_pair_uses_lower_peer_id_as_initiator() {
|
||||
let tasks = collect(
|
||||
1,
|
||||
NatType::SymmetricEasyInc,
|
||||
P2pPolicyFlags::default(),
|
||||
vec![candidate(2, NatType::SymmetricEasyDec)],
|
||||
);
|
||||
assert_eq!(tasks.len(), 1);
|
||||
|
||||
let tasks = collect(
|
||||
2,
|
||||
NatType::SymmetricEasyInc,
|
||||
P2pPolicyFlags::default(),
|
||||
vec![candidate(1, NatType::SymmetricEasyDec)],
|
||||
);
|
||||
assert!(tasks.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disabling_symmetric_hole_punch_keeps_sym_to_cone_as_cone_method() {
|
||||
let tasks = collect(
|
||||
1,
|
||||
NatType::Symmetric,
|
||||
P2pPolicyFlags {
|
||||
disable_sym_hole_punching: true,
|
||||
..Default::default()
|
||||
},
|
||||
vec![candidate(2, NatType::PortRestricted)],
|
||||
);
|
||||
|
||||
assert_eq!(tasks.len(), 1);
|
||||
assert_eq!(tasks[0].dst_peer_id, 2);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::socket::{IpVersion, SocketContext, tcp::TcpBindOptions};
|
||||
|
||||
#[cfg(feature = "endpoint-discovery")]
|
||||
mod implementation;
|
||||
|
||||
#[cfg(feature = "endpoint-discovery")]
|
||||
pub(crate) use implementation::CoreManualEndpointResolver;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ManualEndpointDiscoveryConfig {
|
||||
pub user_agent: String,
|
||||
pub network_name: String,
|
||||
pub http_timeout: Duration,
|
||||
pub http_ip_version: IpVersion,
|
||||
pub http_tcp_bind: TcpBindOptions,
|
||||
pub dns_record_context: SocketContext,
|
||||
pub srv_protocols: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for ManualEndpointDiscoveryConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
user_agent: "easytier-core".to_owned(),
|
||||
network_name: String::new(),
|
||||
http_timeout: Duration::from_secs(20),
|
||||
http_ip_version: IpVersion::Both,
|
||||
http_tcp_bind: TcpBindOptions::default(),
|
||||
dns_record_context: SocketContext::default(),
|
||||
srv_protocols: vec!["tcp".to_owned(), "udp".to_owned()],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "endpoint-discovery"))]
|
||||
pub(crate) struct CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: crate::socket::tcp::VirtualTcpSocketFactory,
|
||||
{
|
||||
_host: std::marker::PhantomData<fn() -> H>,
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "endpoint-discovery"))]
|
||||
impl<H> CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: crate::socket::tcp::VirtualTcpSocketFactory,
|
||||
{
|
||||
pub fn new(
|
||||
host: std::sync::Arc<H>,
|
||||
dns: std::sync::Arc<dyn crate::host::dns::DnsResolver>,
|
||||
dns_records: std::sync::Arc<dyn crate::host::dns::DnsRecordResolver>,
|
||||
config: ManualEndpointDiscoveryConfig,
|
||||
) -> Self {
|
||||
let _ = (host, dns, dns_records, config);
|
||||
Self {
|
||||
_host: std::marker::PhantomData,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "endpoint-discovery"))]
|
||||
#[async_trait::async_trait]
|
||||
impl<H> super::ManualEndpointResolver for CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: crate::socket::tcp::VirtualTcpSocketFactory,
|
||||
{
|
||||
async fn resolve_endpoint(&self, url: &url::Url) -> anyhow::Result<url::Url> {
|
||||
anyhow::bail!("endpoint discovery is disabled for {url}")
|
||||
}
|
||||
}
|
||||
+969
@@ -0,0 +1,969 @@
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context as _;
|
||||
use bytes::Bytes;
|
||||
use http_body_util::{BodyExt as _, Empty};
|
||||
use hyper::{Request, header};
|
||||
use hyper_util::rt::TokioIo;
|
||||
use rand::{Rng as _, seq::SliceRandom};
|
||||
use rustls::pki_types::ServerName;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
use tokio_rustls::TlsConnector;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
connectivity::transport,
|
||||
host::dns::{DnsQuery, DnsRecordResolver, DnsResolver, DnsSrvRecord},
|
||||
socket::{
|
||||
IpVersion, SocketContext,
|
||||
tcp::{TcpBindOptions, TcpSocketPurpose, VirtualTcpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
use super::super::{ManualEndpointResolver, resolve_url_addrs};
|
||||
use super::ManualEndpointDiscoveryConfig;
|
||||
|
||||
const HTTP_DEFAULT_PORT: u16 = 80;
|
||||
const HTTPS_DEFAULT_PORT: u16 = 443;
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct HttpDiscoveryRequest {
|
||||
pub url: Url,
|
||||
pub user_agent: String,
|
||||
pub network_name: String,
|
||||
pub timeout: Duration,
|
||||
pub ip_version: IpVersion,
|
||||
pub tcp_bind: TcpBindOptions,
|
||||
}
|
||||
|
||||
pub(crate) struct CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
host: Arc<H>,
|
||||
dns: Arc<dyn DnsResolver>,
|
||||
dns_records: Arc<dyn DnsRecordResolver>,
|
||||
config: ManualEndpointDiscoveryConfig,
|
||||
}
|
||||
|
||||
impl<H> CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
pub fn new(
|
||||
host: Arc<H>,
|
||||
dns: Arc<dyn DnsResolver>,
|
||||
dns_records: Arc<dyn DnsRecordResolver>,
|
||||
config: ManualEndpointDiscoveryConfig,
|
||||
) -> Self {
|
||||
Self {
|
||||
host,
|
||||
dns,
|
||||
dns_records,
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<H> ManualEndpointResolver for CoreManualEndpointResolver<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
async fn resolve_endpoint(&self, url: &Url) -> anyhow::Result<Url> {
|
||||
match url.scheme() {
|
||||
"http" | "https" => {
|
||||
let response = fetch_http_discovery(
|
||||
self.host.clone(),
|
||||
self.dns.as_ref(),
|
||||
HttpDiscoveryRequest {
|
||||
url: url.clone(),
|
||||
user_agent: self.config.user_agent.clone(),
|
||||
network_name: self.config.network_name.clone(),
|
||||
timeout: self.config.http_timeout,
|
||||
ip_version: self.config.http_ip_version,
|
||||
tcp_bind: self.config.http_tcp_bind.clone(),
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
resolve_http_endpoint(response)
|
||||
.map(|endpoint| endpoint.url)
|
||||
.map_err(|error| anyhow::anyhow!("Invalid Url: {error}"))
|
||||
}
|
||||
"txt" => {
|
||||
let host = endpoint_host(url)?;
|
||||
resolve_txt_endpoint(
|
||||
self.dns_records.as_ref(),
|
||||
host,
|
||||
self.config.dns_record_context.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
"srv" => {
|
||||
let host = endpoint_host(url)?;
|
||||
resolve_srv_endpoint(
|
||||
self.dns_records.as_ref(),
|
||||
host,
|
||||
&self.config.srv_protocols,
|
||||
self.config.dns_record_context.clone(),
|
||||
)
|
||||
.await
|
||||
}
|
||||
scheme => anyhow::bail!("unsupported manual endpoint resolver scheme: {scheme}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn endpoint_host(url: &Url) -> anyhow::Result<&str> {
|
||||
url.host_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("host should not be empty in {url}"))
|
||||
}
|
||||
|
||||
pub(crate) async fn fetch_http_discovery<H>(
|
||||
host: Arc<H>,
|
||||
dns: &dyn DnsResolver,
|
||||
request: HttpDiscoveryRequest,
|
||||
) -> anyhow::Result<HttpDiscoveryResponse>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
let timeout = request.timeout;
|
||||
crate::foundation::time::timeout(timeout, fetch_http_discovery_inner(host, dns, request))
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("HTTP discovery timed out after {timeout:?}"))?
|
||||
}
|
||||
|
||||
async fn fetch_http_discovery_inner<H>(
|
||||
host: Arc<H>,
|
||||
dns: &dyn DnsResolver,
|
||||
request: HttpDiscoveryRequest,
|
||||
) -> anyhow::Result<HttpDiscoveryResponse>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
let default_port = match request.url.scheme() {
|
||||
"http" => HTTP_DEFAULT_PORT,
|
||||
"https" => HTTPS_DEFAULT_PORT,
|
||||
scheme => anyhow::bail!("unsupported HTTP discovery scheme: {scheme}"),
|
||||
};
|
||||
let addrs = resolve_url_addrs(
|
||||
&request.url,
|
||||
default_port,
|
||||
request
|
||||
.tcp_bind
|
||||
.context
|
||||
.clone()
|
||||
.with_ip_version(request.ip_version),
|
||||
dns,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let mut last_error = None;
|
||||
let mut socket = None;
|
||||
for addr in addrs {
|
||||
match transport::connect_tcp(
|
||||
host.clone(),
|
||||
addr,
|
||||
Vec::new(),
|
||||
request.tcp_bind.clone(),
|
||||
TcpSocketPurpose::ManualConnect,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(connected) => {
|
||||
socket = Some(connected);
|
||||
break;
|
||||
}
|
||||
Err(error) => last_error = Some(error),
|
||||
}
|
||||
}
|
||||
let socket = socket.ok_or_else(|| {
|
||||
last_error.unwrap_or_else(|| anyhow::anyhow!("no HTTP discovery address candidates"))
|
||||
})?;
|
||||
|
||||
if request.url.scheme() == "https" {
|
||||
let server_name = tls_server_name(&request.url)?;
|
||||
let root_store = rustls::RootCertStore {
|
||||
roots: webpki_roots::TLS_SERVER_ROOTS.to_vec(),
|
||||
};
|
||||
// A host application can enable another rustls backend through Cargo
|
||||
// feature unification. Select ring explicitly instead of requiring a
|
||||
// process-wide provider to have been initialized first (#2607).
|
||||
let tls_config = rustls::ClientConfig::builder_with_provider(Arc::new(
|
||||
rustls::crypto::ring::default_provider(),
|
||||
))
|
||||
.with_safe_default_protocol_versions()
|
||||
.context("selecting HTTPS protocol versions failed")?
|
||||
.with_root_certificates(root_store)
|
||||
.with_no_client_auth();
|
||||
let stream = TlsConnector::from(Arc::new(tls_config))
|
||||
.connect(server_name, socket)
|
||||
.await
|
||||
.with_context(|| format!("HTTPS handshake failed for {}", request.url))?;
|
||||
send_http_discovery_request(stream, request).await
|
||||
} else {
|
||||
send_http_discovery_request(socket, request).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tls_server_name(url: &Url) -> anyhow::Result<ServerName<'static>> {
|
||||
match url.host() {
|
||||
Some(url::Host::Domain(host)) => ServerName::try_from(host.to_owned())
|
||||
.with_context(|| format!("invalid HTTPS server name in {url}")),
|
||||
Some(url::Host::Ipv4(ip)) => Ok(ServerName::IpAddress(ip.into())),
|
||||
Some(url::Host::Ipv6(ip)) => Ok(ServerName::IpAddress(ip.into())),
|
||||
None => anyhow::bail!("HTTP discovery URL has no host: {url}"),
|
||||
}
|
||||
}
|
||||
|
||||
async fn send_http_discovery_request<S>(
|
||||
stream: S,
|
||||
request: HttpDiscoveryRequest,
|
||||
) -> anyhow::Result<HttpDiscoveryResponse>
|
||||
where
|
||||
S: AsyncRead + AsyncWrite + Unpin + Send + 'static,
|
||||
{
|
||||
let io = TokioIo::new(stream);
|
||||
let (mut sender, connection) = hyper::client::conn::http1::handshake(io)
|
||||
.await
|
||||
.with_context(|| format!("starting HTTP connection failed for {}", request.url))?;
|
||||
let connection_task = AbortOnDropHandle::new(tokio::spawn(connection));
|
||||
|
||||
let request_target = match request.url.query() {
|
||||
Some(query) => format!("{}?{query}", request.url.path()),
|
||||
None => request.url.path().to_owned(),
|
||||
};
|
||||
let host_header = &request.url[url::Position::BeforeHost..url::Position::AfterPort];
|
||||
let outgoing = Request::builder()
|
||||
.method("GET")
|
||||
.uri(request_target)
|
||||
.header(header::HOST, host_header)
|
||||
.header(header::USER_AGENT, request.user_agent)
|
||||
.header("X-Network-Name", request.network_name)
|
||||
.header(header::CONNECTION, "close")
|
||||
.body(Empty::<Bytes>::new())?;
|
||||
let response = sender
|
||||
.send_request(outgoing)
|
||||
.await
|
||||
.with_context(|| format!("sending HTTP request failed for {}", request.url))?;
|
||||
let status_code = response.status().as_u16();
|
||||
let location = response
|
||||
.headers()
|
||||
.get(header::LOCATION)
|
||||
.map(|value| String::from_utf8_lossy(value.as_bytes()).into_owned());
|
||||
let body = response
|
||||
.into_body()
|
||||
.collect()
|
||||
.await
|
||||
.with_context(|| format!("reading HTTP response failed for {}", request.url))?
|
||||
.to_bytes();
|
||||
drop(sender);
|
||||
connection_task
|
||||
.await
|
||||
.context("HTTP connection task failed")?
|
||||
.with_context(|| format!("HTTP connection failed for {}", request.url))?;
|
||||
|
||||
Ok(HttpDiscoveryResponse {
|
||||
status_code,
|
||||
location,
|
||||
body: String::from_utf8_lossy(&body).into_owned(),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum HttpEndpointSource {
|
||||
RedirectQuery,
|
||||
RedirectUrl,
|
||||
ResponseBody,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct HttpDiscoveryResponse {
|
||||
pub status_code: u16,
|
||||
pub location: Option<String>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct ResolvedHttpEndpoint {
|
||||
pub url: Url,
|
||||
pub source: HttpEndpointSource,
|
||||
}
|
||||
|
||||
fn resolve_http_redirect(location: &str) -> anyhow::Result<ResolvedHttpEndpoint> {
|
||||
let url = Url::parse(location)
|
||||
.with_context(|| format!("parsing redirect URL failed. url: {location}"))?;
|
||||
if !matches!(url.scheme(), "http" | "https") {
|
||||
return Ok(ResolvedHttpEndpoint {
|
||||
url,
|
||||
source: HttpEndpointSource::RedirectUrl,
|
||||
});
|
||||
}
|
||||
|
||||
let candidates = url
|
||||
.query_pairs()
|
||||
.filter_map(|(_, value)| Url::parse(&value).ok())
|
||||
.collect::<Vec<_>>();
|
||||
if let Some(url) = candidates.choose(&mut rand::thread_rng()).cloned() {
|
||||
return Ok(ResolvedHttpEndpoint {
|
||||
url,
|
||||
source: HttpEndpointSource::RedirectQuery,
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(url) = location
|
||||
.strip_prefix(&format!("{}://", url.scheme()))
|
||||
.and_then(|value| Url::parse(value).ok())
|
||||
{
|
||||
return Ok(ResolvedHttpEndpoint {
|
||||
url,
|
||||
source: HttpEndpointSource::RedirectUrl,
|
||||
});
|
||||
}
|
||||
|
||||
anyhow::bail!("no valid connector URL found in redirect location {location:?}")
|
||||
}
|
||||
|
||||
fn resolve_http_body(body: &str) -> anyhow::Result<ResolvedHttpEndpoint> {
|
||||
let mut candidates = body
|
||||
.lines()
|
||||
.map(str::trim)
|
||||
.filter(|line| !line.is_empty())
|
||||
.collect::<Vec<_>>();
|
||||
candidates.shuffle(&mut rand::thread_rng());
|
||||
for candidate in candidates {
|
||||
if let Ok(url) = Url::parse(candidate) {
|
||||
return Ok(ResolvedHttpEndpoint {
|
||||
url,
|
||||
source: HttpEndpointSource::ResponseBody,
|
||||
});
|
||||
}
|
||||
}
|
||||
anyhow::bail!("no valid connector URL found in response body {body:?}")
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_http_endpoint(
|
||||
response: HttpDiscoveryResponse,
|
||||
) -> anyhow::Result<ResolvedHttpEndpoint> {
|
||||
match response.status_code {
|
||||
300..=399 => resolve_http_redirect(
|
||||
response
|
||||
.location
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow::anyhow!("HTTP redirect has no Location header"))?,
|
||||
),
|
||||
200..=299 => resolve_http_body(&response.body),
|
||||
status_code => anyhow::bail!(
|
||||
"unexpected HTTP discovery status {status_code}, body: {:?}",
|
||||
response.body
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
fn choose_weighted<T>(options: &[(T, u64)]) -> Option<&T> {
|
||||
let total_weight = options.iter().map(|(_, weight)| *weight).sum();
|
||||
let mut rng = rand::thread_rng();
|
||||
let selected = rng.gen_range(0..total_weight);
|
||||
let mut accumulated = 0;
|
||||
|
||||
for (item, weight) in options {
|
||||
accumulated += *weight;
|
||||
if selected < accumulated {
|
||||
return Some(item);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_txt_endpoint(
|
||||
resolver: &dyn DnsRecordResolver,
|
||||
domain_name: &str,
|
||||
context: SocketContext,
|
||||
) -> anyhow::Result<Url> {
|
||||
let txt_data = resolver
|
||||
.resolve_txt(DnsQuery::new(domain_name, context))
|
||||
.await
|
||||
.with_context(|| format!("resolve TXT record failed for {domain_name}"))?;
|
||||
let candidates = txt_data
|
||||
.split(' ')
|
||||
.filter_map(|candidate| Url::parse(candidate).ok())
|
||||
.collect::<Vec<_>>();
|
||||
candidates
|
||||
.choose(&mut rand::thread_rng())
|
||||
.cloned()
|
||||
.ok_or_else(|| {
|
||||
anyhow::anyhow!(
|
||||
"no valid URL found in TXT data {txt_data:?}; expected a space-separated URL list"
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn srv_record_url(protocol: &str, record: DnsSrvRecord) -> anyhow::Result<(Url, u64)> {
|
||||
if record.port == 0 {
|
||||
anyhow::bail!("SRV port must be non-zero");
|
||||
}
|
||||
let url = format!("{protocol}://{}:{}", record.target, record.port);
|
||||
// Preserve the existing EasyTier selection rule, which treats SRV priority
|
||||
// as the candidate weight.
|
||||
Ok((Url::parse(&url)?, u64::from(record.priority)))
|
||||
}
|
||||
|
||||
pub(super) fn deduplicate_srv_candidates(candidates: Vec<(Url, u64)>) -> Vec<(Url, u64)> {
|
||||
candidates
|
||||
.into_iter()
|
||||
.collect::<HashSet<_>>()
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) async fn resolve_srv_endpoint(
|
||||
resolver: &dyn DnsRecordResolver,
|
||||
domain_name: &str,
|
||||
supported_protocols: &[String],
|
||||
context: SocketContext,
|
||||
) -> anyhow::Result<Url> {
|
||||
let lookups = supported_protocols.iter().map(|protocol| {
|
||||
let protocol = protocol.clone();
|
||||
let query = DnsQuery::new(
|
||||
format!("_easytier._{protocol}.{domain_name}"),
|
||||
context.clone(),
|
||||
);
|
||||
async move { (protocol, resolver.resolve_srv(query).await) }
|
||||
});
|
||||
|
||||
let mut candidates = Vec::new();
|
||||
for (protocol, result) in futures::future::join_all(lookups).await {
|
||||
let Ok(records) = result else {
|
||||
continue;
|
||||
};
|
||||
candidates.extend(records.into_iter().filter_map(|record| {
|
||||
match srv_record_url(&protocol, record) {
|
||||
Ok(candidate) => Some(candidate),
|
||||
Err(error) => {
|
||||
tracing::warn!(
|
||||
?error,
|
||||
srv_domain = %format!("_easytier._{protocol}.{domain_name}"),
|
||||
"ignore invalid SRV endpoint record"
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}));
|
||||
}
|
||||
if candidates.is_empty() {
|
||||
anyhow::bail!("no SRV endpoint found for {domain_name}");
|
||||
}
|
||||
let candidates = deduplicate_srv_candidates(candidates);
|
||||
|
||||
choose_weighted(&candidates)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("failed to choose an SRV endpoint for {domain_name}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
pin::Pin,
|
||||
sync::Mutex,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _, DuplexStream, ReadBuf};
|
||||
|
||||
use crate::socket::tcp::{TcpConnectOptions, VirtualTcpSocket, VirtualTcpSocketFactory};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct HttpTestSocket {
|
||||
stream: DuplexStream,
|
||||
local_addr: SocketAddr,
|
||||
peer_addr: SocketAddr,
|
||||
}
|
||||
|
||||
impl AsyncRead for HttpTestSocket {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.stream).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for HttpTestSocket {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.stream).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.stream).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.stream).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl VirtualTcpSocket for HttpTestSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
fn peer_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.peer_addr)
|
||||
}
|
||||
}
|
||||
|
||||
struct HttpTestHost {
|
||||
stream: Mutex<Option<DuplexStream>>,
|
||||
connects: Mutex<Vec<TcpConnectOptions>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualTcpSocketFactory for HttpTestHost {
|
||||
type Socket = HttpTestSocket;
|
||||
|
||||
async fn connect_tcp(&self, options: TcpConnectOptions) -> anyhow::Result<Self::Socket> {
|
||||
self.connects.lock().unwrap().push(options.clone());
|
||||
let stream = self
|
||||
.stream
|
||||
.lock()
|
||||
.unwrap()
|
||||
.take()
|
||||
.ok_or_else(|| anyhow::anyhow!("test socket already connected"))?;
|
||||
Ok(HttpTestSocket {
|
||||
stream,
|
||||
local_addr: "192.0.2.2:40000".parse().unwrap(),
|
||||
peer_addr: options.remote_addr,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
struct HttpTestDns {
|
||||
queries: Mutex<Vec<DnsQuery>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DnsResolver for HttpTestDns {
|
||||
async fn resolve(&self, query: DnsQuery) -> anyhow::Result<Vec<IpAddr>> {
|
||||
self.queries.lock().unwrap().push(query);
|
||||
Ok(vec![IpAddr::V4(Ipv4Addr::new(192, 0, 2, 1))])
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn http_fetch_uses_host_dns_and_socket_while_core_drives_io() {
|
||||
let (client, mut server) = tokio::io::duplex(8192);
|
||||
let host = Arc::new(HttpTestHost {
|
||||
stream: Mutex::new(Some(client)),
|
||||
connects: Mutex::new(Vec::new()),
|
||||
});
|
||||
let dns = HttpTestDns {
|
||||
queries: Mutex::new(Vec::new()),
|
||||
};
|
||||
let server_task = tokio::spawn(async move {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let len = server.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(len, 0, "HTTP request ended before its headers");
|
||||
request.extend_from_slice(&chunk[..len]);
|
||||
if request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let request = String::from_utf8(request).unwrap().to_ascii_lowercase();
|
||||
assert!(request.starts_with("get /lookup?kind=peer http/1.1\r\n"));
|
||||
assert!(request.contains("host: discovery.example:18080\r\n"));
|
||||
assert!(request.contains("user-agent: easytier/test\r\n"));
|
||||
assert!(request.contains("x-network-name: test-network\r\n"));
|
||||
assert!(request.contains("connection: close\r\n"));
|
||||
|
||||
server
|
||||
.write_all(
|
||||
b"HTTP/1.1 302 Found\r\nLocation: tcp://192.0.2.10:11010\r\nTransfer-Encoding: chunked\r\nConnection: close\r\n\r\n5\r\nhello\r\n0\r\n\r\n",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
server.shutdown().await.unwrap();
|
||||
});
|
||||
|
||||
let response = fetch_http_discovery(
|
||||
host.clone(),
|
||||
&dns,
|
||||
HttpDiscoveryRequest {
|
||||
url: "http://discovery.example:18080/lookup?kind=peer"
|
||||
.parse()
|
||||
.unwrap(),
|
||||
user_agent: "easytier/test".to_owned(),
|
||||
network_name: "test-network".to_owned(),
|
||||
timeout: Duration::from_secs(1),
|
||||
ip_version: IpVersion::V4,
|
||||
tcp_bind: TcpBindOptions::default().with_socket_mark(Some(9)),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
crate::foundation::time::timeout(Duration::from_secs(1), server_task)
|
||||
.await
|
||||
.expect("HTTP fetch test server did not finish")
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(response.status_code, 302);
|
||||
assert_eq!(response.location.as_deref(), Some("tcp://192.0.2.10:11010"));
|
||||
assert_eq!(response.body, "hello");
|
||||
assert_eq!(
|
||||
*dns.queries.lock().unwrap(),
|
||||
[DnsQuery::new(
|
||||
"discovery.example",
|
||||
SocketContext {
|
||||
ip_version: IpVersion::V4,
|
||||
socket_mark: Some(9),
|
||||
netns: None,
|
||||
}
|
||||
)]
|
||||
);
|
||||
assert_eq!(host.connects.lock().unwrap().len(), 1);
|
||||
let options = &host.connects.lock().unwrap()[0];
|
||||
assert_eq!(options.remote_addr, "192.0.2.1:18080".parse().unwrap());
|
||||
assert_eq!(options.purpose, TcpSocketPurpose::ManualConnect);
|
||||
assert_eq!(options.bind.context.socket_mark, Some(9));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn https_fetch_reaches_tls_handshake_without_global_provider() {
|
||||
// Also run with rustls/aws_lc_rs enabled: feature unification must not
|
||||
// make HTTPS discovery panic before it can send a ClientHello (#2607).
|
||||
let (client, mut server) = tokio::io::duplex(8192);
|
||||
let host = Arc::new(HttpTestHost {
|
||||
stream: Mutex::new(Some(client)),
|
||||
connects: Mutex::new(Vec::new()),
|
||||
});
|
||||
let dns = HttpTestDns {
|
||||
queries: Mutex::new(Vec::new()),
|
||||
};
|
||||
let server_task = tokio::spawn(async move {
|
||||
let mut record_header = [0; 5];
|
||||
server.read_exact(&mut record_header).await.unwrap();
|
||||
assert_eq!(record_header[0], 22, "expected a TLS handshake record");
|
||||
// Close without replying; discovery should report a handshake
|
||||
// error rather than panic while selecting a crypto provider.
|
||||
});
|
||||
|
||||
let error = fetch_http_discovery(
|
||||
host,
|
||||
&dns,
|
||||
HttpDiscoveryRequest {
|
||||
url: "https://discovery.example/lookup".parse().unwrap(),
|
||||
user_agent: "easytier/test".to_owned(),
|
||||
network_name: "test-network".to_owned(),
|
||||
timeout: Duration::from_secs(5),
|
||||
ip_version: IpVersion::V4,
|
||||
tcp_bind: TcpBindOptions::default(),
|
||||
},
|
||||
)
|
||||
.await
|
||||
.expect_err("server closed during the TLS handshake");
|
||||
assert!(format!("{error:#}").contains("HTTPS handshake failed"));
|
||||
server_task.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_discovery_interprets_redirect_and_body_forms() {
|
||||
let query = resolve_http_endpoint(HttpDiscoveryResponse {
|
||||
status_code: 302,
|
||||
location: Some("https://discovery.example/?url=tcp://127.0.0.1:11010".to_owned()),
|
||||
body: String::new(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(query.url.as_str(), "tcp://127.0.0.1:11010");
|
||||
assert_eq!(query.source, HttpEndpointSource::RedirectQuery);
|
||||
|
||||
let nested = resolve_http_endpoint(HttpDiscoveryResponse {
|
||||
status_code: 302,
|
||||
location: Some("https://udp://127.0.0.1:11010".to_owned()),
|
||||
body: String::new(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(nested.url.as_str(), "udp://127.0.0.1:11010");
|
||||
assert_eq!(nested.source, HttpEndpointSource::RedirectUrl);
|
||||
|
||||
let direct = resolve_http_endpoint(HttpDiscoveryResponse {
|
||||
status_code: 307,
|
||||
location: Some("quic://127.0.0.1:11012".to_owned()),
|
||||
body: String::new(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(direct.url.as_str(), "quic://127.0.0.1:11012");
|
||||
assert_eq!(direct.source, HttpEndpointSource::RedirectUrl);
|
||||
|
||||
let body = resolve_http_endpoint(HttpDiscoveryResponse {
|
||||
status_code: 200,
|
||||
location: None,
|
||||
body: "invalid\nwg://127.0.0.1:11011\n".to_owned(),
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(body.url.as_str(), "wg://127.0.0.1:11011");
|
||||
assert_eq!(body.source, HttpEndpointSource::ResponseBody);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn http_discovery_reports_malformed_redirect_location() {
|
||||
let error = resolve_http_endpoint(HttpDiscoveryResponse {
|
||||
status_code: 302,
|
||||
location: Some("not a URL".to_owned()),
|
||||
body: String::new(),
|
||||
})
|
||||
.unwrap_err();
|
||||
|
||||
let message = error.to_string();
|
||||
assert!(message.contains("parsing redirect URL failed"));
|
||||
assert!(message.contains("not a URL"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn https_server_name_accepts_ip_literals_without_url_brackets() {
|
||||
let ipv4: Url = "https://192.0.2.1/".parse().unwrap();
|
||||
let ipv6: Url = "https://[2001:db8::1]/".parse().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
tls_server_name(&ipv4).unwrap(),
|
||||
ServerName::IpAddress(Ipv4Addr::new(192, 0, 2, 1).into())
|
||||
);
|
||||
assert_eq!(
|
||||
tls_server_name(&ipv6).unwrap(),
|
||||
ServerName::IpAddress("2001:db8::1".parse::<std::net::Ipv6Addr>().unwrap().into())
|
||||
);
|
||||
}
|
||||
|
||||
struct TestResolver {
|
||||
txt: String,
|
||||
srv: Vec<DnsSrvRecord>,
|
||||
queries: Mutex<Vec<DnsQuery>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DnsRecordResolver for TestResolver {
|
||||
async fn resolve_txt(&self, query: DnsQuery) -> anyhow::Result<String> {
|
||||
self.queries.lock().unwrap().push(query);
|
||||
Ok(self.txt.clone())
|
||||
}
|
||||
|
||||
async fn resolve_srv(&self, query: DnsQuery) -> anyhow::Result<Vec<DnsSrvRecord>> {
|
||||
self.queries.lock().unwrap().push(query);
|
||||
Ok(self.srv.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_endpoint_resolver_owns_record_scheme_dispatch() {
|
||||
let host = Arc::new(HttpTestHost {
|
||||
stream: Mutex::new(None),
|
||||
connects: Mutex::new(Vec::new()),
|
||||
});
|
||||
let dns: Arc<dyn DnsResolver> = Arc::new(HttpTestDns {
|
||||
queries: Mutex::new(Vec::new()),
|
||||
});
|
||||
let records = Arc::new(TestResolver {
|
||||
txt: "tcp://192.0.2.10:11010".to_owned(),
|
||||
srv: vec![DnsSrvRecord {
|
||||
priority: 1,
|
||||
weight: 10,
|
||||
port: 11012,
|
||||
target: "peer.example.com.".to_owned(),
|
||||
}],
|
||||
queries: Mutex::new(Vec::new()),
|
||||
});
|
||||
let record_context = SocketContext {
|
||||
ip_version: IpVersion::V6,
|
||||
socket_mark: Some(17),
|
||||
netns: None,
|
||||
};
|
||||
let resolver = CoreManualEndpointResolver::new(
|
||||
host,
|
||||
dns,
|
||||
records.clone(),
|
||||
ManualEndpointDiscoveryConfig {
|
||||
user_agent: "easytier/test".to_owned(),
|
||||
network_name: "test-network".to_owned(),
|
||||
http_timeout: Duration::from_secs(1),
|
||||
http_ip_version: IpVersion::Both,
|
||||
http_tcp_bind: TcpBindOptions::default(),
|
||||
dns_record_context: record_context.clone(),
|
||||
srv_protocols: vec!["quic".to_owned()],
|
||||
},
|
||||
);
|
||||
|
||||
let txt = resolver
|
||||
.resolve_endpoint(&"txt://discovery.example".parse().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let srv = resolver
|
||||
.resolve_endpoint(&"srv://discovery.example".parse().unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(txt.as_str(), "tcp://192.0.2.10:11010");
|
||||
assert_eq!(srv.as_str(), "quic://peer.example.com.:11012");
|
||||
assert_eq!(
|
||||
*records.queries.lock().unwrap(),
|
||||
[
|
||||
DnsQuery::new("discovery.example", record_context.clone()),
|
||||
DnsQuery::new("_easytier._quic.discovery.example", record_context)
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_endpoint_resolver_passes_http_config_and_error_classification() {
|
||||
let (client, mut server) = tokio::io::duplex(8192);
|
||||
let host = Arc::new(HttpTestHost {
|
||||
stream: Mutex::new(Some(client)),
|
||||
connects: Mutex::new(Vec::new()),
|
||||
});
|
||||
let dns = Arc::new(HttpTestDns {
|
||||
queries: Mutex::new(Vec::new()),
|
||||
});
|
||||
let records = Arc::new(TestResolver {
|
||||
txt: String::new(),
|
||||
srv: Vec::new(),
|
||||
queries: Mutex::new(Vec::new()),
|
||||
});
|
||||
let server_task = tokio::spawn(async move {
|
||||
let mut request = Vec::new();
|
||||
loop {
|
||||
let mut chunk = [0; 1024];
|
||||
let len = server.read(&mut chunk).await.unwrap();
|
||||
assert_ne!(len, 0, "HTTP request ended before its headers");
|
||||
request.extend_from_slice(&chunk[..len]);
|
||||
if request.windows(4).any(|window| window == b"\r\n\r\n") {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let request = String::from_utf8(request).unwrap().to_ascii_lowercase();
|
||||
assert!(request.contains("user-agent: easytier/facade-test\r\n"));
|
||||
assert!(request.contains("x-network-name: facade-network\r\n"));
|
||||
server
|
||||
.write_all(
|
||||
b"HTTP/1.1 200 OK\r\nContent-Length: 9\r\nConnection: close\r\n\r\nnot a URL",
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
server.shutdown().await.unwrap();
|
||||
});
|
||||
let resolver = CoreManualEndpointResolver::new(
|
||||
host.clone(),
|
||||
dns.clone(),
|
||||
records,
|
||||
ManualEndpointDiscoveryConfig {
|
||||
user_agent: "easytier/facade-test".to_owned(),
|
||||
network_name: "facade-network".to_owned(),
|
||||
http_timeout: Duration::from_secs(1),
|
||||
http_ip_version: IpVersion::V4,
|
||||
http_tcp_bind: TcpBindOptions::default().with_socket_mark(Some(23)),
|
||||
dns_record_context: SocketContext::default(),
|
||||
srv_protocols: Vec::new(),
|
||||
},
|
||||
);
|
||||
|
||||
let error = resolver
|
||||
.resolve_endpoint(&"http://discovery.example:18081/endpoint".parse().unwrap())
|
||||
.await
|
||||
.unwrap_err();
|
||||
crate::foundation::time::timeout(Duration::from_secs(1), server_task)
|
||||
.await
|
||||
.expect("HTTP facade test server did not finish")
|
||||
.unwrap();
|
||||
|
||||
assert!(error.to_string().starts_with("Invalid Url:"));
|
||||
assert_eq!(
|
||||
*dns.queries.lock().unwrap(),
|
||||
[DnsQuery::new(
|
||||
"discovery.example",
|
||||
SocketContext {
|
||||
ip_version: IpVersion::V4,
|
||||
socket_mark: Some(23),
|
||||
netns: None,
|
||||
}
|
||||
)]
|
||||
);
|
||||
let connects = host.connects.lock().unwrap();
|
||||
assert_eq!(connects.len(), 1);
|
||||
assert_eq!(connects[0].remote_addr, "192.0.2.1:18081".parse().unwrap());
|
||||
assert_eq!(connects[0].bind.context.socket_mark, Some(23));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn txt_discovery_parses_easy_tier_url_candidates() {
|
||||
let resolver = TestResolver {
|
||||
txt: "invalid tcp://127.0.0.1:11010".to_owned(),
|
||||
srv: Vec::new(),
|
||||
queries: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let endpoint =
|
||||
resolve_txt_endpoint(&resolver, "discovery.example", SocketContext::default())
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(endpoint.as_str(), "tcp://127.0.0.1:11010");
|
||||
assert_eq!(
|
||||
*resolver.queries.lock().unwrap(),
|
||||
[DnsQuery::new("discovery.example", SocketContext::default())]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn srv_discovery_builds_protocol_specific_endpoint() {
|
||||
let resolver = TestResolver {
|
||||
txt: String::new(),
|
||||
srv: vec![DnsSrvRecord {
|
||||
priority: 1,
|
||||
weight: 10,
|
||||
port: 11012,
|
||||
target: "peer.example.com.".to_owned(),
|
||||
}],
|
||||
queries: Mutex::new(Vec::new()),
|
||||
};
|
||||
|
||||
let endpoint = resolve_srv_endpoint(
|
||||
&resolver,
|
||||
"discovery.example",
|
||||
&["quic".to_owned()],
|
||||
SocketContext::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(endpoint.as_str(), "quic://peer.example.com.:11012");
|
||||
assert_eq!(
|
||||
*resolver.queries.lock().unwrap(),
|
||||
[DnsQuery::new(
|
||||
"_easytier._quic.discovery.example",
|
||||
SocketContext::default()
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn srv_discovery_deduplicates_url_and_priority() {
|
||||
let endpoint: Url = "tcp://peer.example.com:11010".parse().unwrap();
|
||||
let candidates = deduplicate_srv_candidates(vec![
|
||||
(endpoint.clone(), 10),
|
||||
(endpoint.clone(), 10),
|
||||
(endpoint.clone(), 20),
|
||||
]);
|
||||
|
||||
assert_eq!(candidates.len(), 2);
|
||||
assert!(candidates.contains(&(endpoint.clone(), 10)));
|
||||
assert!(candidates.contains(&(endpoint, 20)));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,37 @@
|
||||
//! Portable connection orchestration.
|
||||
|
||||
use std::fmt::Debug;
|
||||
|
||||
use url::Url;
|
||||
|
||||
pub mod composite;
|
||||
pub mod direct;
|
||||
pub mod hole_punch;
|
||||
// Kept public: the host-driven adapter chain is WASI-only production code
|
||||
// (cfg(target_os = "wasi")), so crate-private visibility would surface
|
||||
// dead-code warnings on host builds for code that is live on WASI.
|
||||
pub mod connector_host;
|
||||
pub mod manual;
|
||||
pub mod protocol;
|
||||
pub mod stun;
|
||||
pub mod transport;
|
||||
|
||||
/// Supplies the URLs of the instance's currently running listeners.
|
||||
///
|
||||
/// The listener layer's running-listener registry implements this seam.
|
||||
/// Connectors use it to avoid dialing addresses that would hairpin back
|
||||
/// into one of their own listeners, so connectivity depends on this narrow
|
||||
/// query rather than on the listener module's concrete registry type.
|
||||
pub trait LocalListenerUrls: Debug + Send + Sync + 'static {
|
||||
fn local_listener_urls(&self) -> Vec<Url>;
|
||||
}
|
||||
|
||||
/// Empty [`LocalListenerUrls`] for connectors that track no listeners.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct NoLocalListeners;
|
||||
|
||||
impl LocalListenerUrls for NoLocalListeners {
|
||||
fn local_listener_urls(&self) -> Vec<Url> {
|
||||
Vec::new()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,811 @@
|
||||
use std::{marker::PhantomData, num::NonZeroUsize, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
socket::{tcp::VirtualTcpSocket, udp::UdpSession},
|
||||
tunnel::Tunnel,
|
||||
};
|
||||
|
||||
use super::transport::{ConnectedTransport, UdpSessionMode};
|
||||
|
||||
pub mod raw;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum ProtocolTransport {
|
||||
Tcp,
|
||||
FakeTcp,
|
||||
Udp(UdpSessionMode),
|
||||
}
|
||||
|
||||
pub(crate) const fn protocol_transport(scheme: &str) -> Option<ProtocolTransport> {
|
||||
match scheme.as_bytes() {
|
||||
b"tcp" | b"ws" | b"wss" => Some(ProtocolTransport::Tcp),
|
||||
b"faketcp" => Some(ProtocolTransport::FakeTcp),
|
||||
b"udp" => Some(ProtocolTransport::Udp(UdpSessionMode::EasyTierMux)),
|
||||
b"wg" => Some(ProtocolTransport::Udp(UdpSessionMode::Classified(
|
||||
crate::socket::udp::UdpSessionProtocol::WireGuard,
|
||||
))),
|
||||
b"quic" => Some(ProtocolTransport::Udp(UdpSessionMode::Classified(
|
||||
crate::socket::udp::UdpSessionProtocol::Quic,
|
||||
))),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) const fn protocol_uses_udp(scheme: &str) -> bool {
|
||||
matches!(protocol_transport(scheme), Some(ProtocolTransport::Udp(_)))
|
||||
}
|
||||
|
||||
/// Returns the listener-port offset used when expanding a single base port
|
||||
/// into EasyTier's protocol-specific listener set.
|
||||
pub const fn protocol_port_offset(scheme: &str) -> Option<u16> {
|
||||
match scheme.as_bytes() {
|
||||
b"tcp" | b"udp" => Some(0),
|
||||
b"wg" | b"ws" => Some(1),
|
||||
b"quic" | b"wss" => Some(2),
|
||||
b"faketcp" => Some(3),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the default port for a concrete EasyTier IP protocol.
|
||||
pub const fn protocol_default_port(scheme: &str) -> Option<u16> {
|
||||
match scheme.as_bytes() {
|
||||
b"ws" => Some(80),
|
||||
b"wss" => Some(443),
|
||||
_ => match protocol_port_offset(scheme) {
|
||||
Some(offset) => Some(11010 + offset),
|
||||
None => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ClientProtocolUpgrader<TcpSocket>: Send + Sync + 'static {
|
||||
fn supports_scheme(&self, scheme: &str) -> bool;
|
||||
|
||||
fn connect_timeout(&self, _scheme: &str) -> Option<Duration> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn upgrade_client(
|
||||
&self,
|
||||
connected: ConnectedTransport<TcpSocket>,
|
||||
requested_url: Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>>;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ServerTunnelAcceptor: Send + 'static {
|
||||
async fn accept(&mut self) -> anyhow::Result<Box<dyn Tunnel>>;
|
||||
}
|
||||
|
||||
pub enum ServerProtocolUpgrade {
|
||||
Tunnel(Box<dyn Tunnel>),
|
||||
Acceptor(Box<dyn ServerTunnelAcceptor>),
|
||||
}
|
||||
|
||||
pub struct ServerProtocolAdmission {
|
||||
active_session: OwnedSemaphorePermit,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl ServerProtocolAdmission {
|
||||
pub fn into_parts(self) -> (OwnedSemaphorePermit, Arc<Semaphore>) {
|
||||
(self.active_session, self.handshake_slots)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ServerProtocolAdmissionController {
|
||||
active_sessions: Arc<Semaphore>,
|
||||
handshake_slots: Arc<Semaphore>,
|
||||
}
|
||||
|
||||
impl ServerProtocolAdmissionController {
|
||||
pub fn new(max_active_sessions: usize, max_in_flight_handshakes: usize) -> Self {
|
||||
Self {
|
||||
active_sessions: Arc::new(Semaphore::new(max_active_sessions)),
|
||||
handshake_slots: Arc::new(Semaphore::new(max_in_flight_handshakes)),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn try_admit(&self) -> Option<ServerProtocolAdmission> {
|
||||
Some(ServerProtocolAdmission {
|
||||
active_session: self.active_sessions.clone().try_acquire_owned().ok()?,
|
||||
handshake_slots: self.handshake_slots.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn quic() -> Self {
|
||||
Self::new(1024, 128)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait ServerProtocolUpgrader<TcpSocket>: Send + Sync + 'static {
|
||||
fn supports_scheme(&self, scheme: &str) -> bool;
|
||||
|
||||
fn max_pending_tcp_upgrades(&self, _scheme: &str) -> Option<NonZeroUsize> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn upgrade_tcp(
|
||||
&self,
|
||||
socket: TcpSocket,
|
||||
local_url: Url,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade>;
|
||||
|
||||
async fn upgrade_udp(
|
||||
&self,
|
||||
session: UdpSession,
|
||||
local_url: Url,
|
||||
admission: Option<ServerProtocolAdmission>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade>;
|
||||
|
||||
async fn upgrade_byte_stream(
|
||||
&self,
|
||||
socket: TcpSocket,
|
||||
local_url: Url,
|
||||
remote_url: Option<Url>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade>;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub struct CoreClientProtocolConfig {
|
||||
pub unix: bool,
|
||||
pub faketcp: bool,
|
||||
}
|
||||
|
||||
/// Owns portable client protocol dispatch and delegates only protocol engines
|
||||
/// that are not yet available in core.
|
||||
pub struct CoreClientProtocolUpgrader<TcpSocket> {
|
||||
config: CoreClientProtocolConfig,
|
||||
external: Option<Arc<dyn ClientProtocolUpgrader<TcpSocket>>>,
|
||||
}
|
||||
|
||||
impl<TcpSocket> CoreClientProtocolUpgrader<TcpSocket> {
|
||||
pub fn new(config: CoreClientProtocolConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
external: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_external(
|
||||
config: CoreClientProtocolConfig,
|
||||
external: Arc<dyn ClientProtocolUpgrader<TcpSocket>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
external: Some(external),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<TcpSocket> ClientProtocolUpgrader<TcpSocket> for CoreClientProtocolUpgrader<TcpSocket>
|
||||
where
|
||||
TcpSocket: VirtualTcpSocket,
|
||||
{
|
||||
fn supports_scheme(&self, scheme: &str) -> bool {
|
||||
match scheme {
|
||||
"tcp" | "udp" | "ring" => true,
|
||||
"unix" => self.config.unix,
|
||||
"faketcp" => self.config.faketcp,
|
||||
_ => self
|
||||
.external
|
||||
.as_ref()
|
||||
.is_some_and(|external| external.supports_scheme(scheme)),
|
||||
}
|
||||
}
|
||||
|
||||
fn connect_timeout(&self, scheme: &str) -> Option<Duration> {
|
||||
self.external
|
||||
.as_ref()
|
||||
.filter(|external| external.supports_scheme(scheme))
|
||||
.and_then(|external| external.connect_timeout(scheme))
|
||||
}
|
||||
|
||||
async fn upgrade_client(
|
||||
&self,
|
||||
connected: ConnectedTransport<TcpSocket>,
|
||||
requested_url: Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>> {
|
||||
match requested_url.scheme() {
|
||||
"tcp" => match connected {
|
||||
ConnectedTransport::Tcp(socket) => {
|
||||
Ok(raw::upgrade_connected_tcp(socket, requested_url)?)
|
||||
}
|
||||
ConnectedTransport::Udp(_) | ConnectedTransport::ByteStream(_) => {
|
||||
anyhow::bail!("TCP protocol requires a TCP transport")
|
||||
}
|
||||
},
|
||||
"udp" => match connected {
|
||||
ConnectedTransport::Udp(session) => {
|
||||
Ok(raw::upgrade_connected_udp(session, requested_url)?)
|
||||
}
|
||||
ConnectedTransport::Tcp(_) | ConnectedTransport::ByteStream(_) => {
|
||||
anyhow::bail!("UDP protocol requires a UDP session")
|
||||
}
|
||||
},
|
||||
"ring" => upgrade_byte_stream(connected),
|
||||
"unix" if self.config.unix => upgrade_byte_stream(connected),
|
||||
"faketcp" if self.config.faketcp => match connected {
|
||||
ConnectedTransport::Tcp(socket) => {
|
||||
Ok(raw::upgrade_connected_tcp(socket, requested_url)?)
|
||||
}
|
||||
ConnectedTransport::Udp(_) | ConnectedTransport::ByteStream(_) => {
|
||||
anyhow::bail!("FakeTCP protocol requires a TCP transport")
|
||||
}
|
||||
},
|
||||
"unix" | "faketcp" => anyhow::bail!(
|
||||
"unsupported client protocol upgrader: {}",
|
||||
requested_url.scheme()
|
||||
),
|
||||
scheme => {
|
||||
let Some(external) = &self.external else {
|
||||
anyhow::bail!("unsupported client protocol upgrader: {scheme}");
|
||||
};
|
||||
if !external.supports_scheme(scheme) {
|
||||
anyhow::bail!("unsupported client protocol upgrader: {scheme}");
|
||||
}
|
||||
external.upgrade_client(connected, requested_url).await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn upgrade_byte_stream<TcpSocket>(
|
||||
connected: ConnectedTransport<TcpSocket>,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>>
|
||||
where
|
||||
TcpSocket: VirtualTcpSocket,
|
||||
{
|
||||
match connected {
|
||||
ConnectedTransport::ByteStream(stream) => Ok(raw::upgrade_connected_byte_stream(stream)?),
|
||||
ConnectedTransport::Tcp(_) | ConnectedTransport::Udp(_) => {
|
||||
anyhow::bail!("external protocol requires a host-created byte stream")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
|
||||
pub struct CoreServerProtocolConfig {
|
||||
pub unix: bool,
|
||||
pub faketcp: bool,
|
||||
}
|
||||
|
||||
/// Owns portable server protocol dispatch and delegates only protocol engines
|
||||
/// that are not available in core.
|
||||
pub struct CoreServerProtocolUpgrader<TcpSocket> {
|
||||
config: CoreServerProtocolConfig,
|
||||
external: Option<Arc<dyn ServerProtocolUpgrader<TcpSocket>>>,
|
||||
tcp_socket: PhantomData<fn() -> TcpSocket>,
|
||||
}
|
||||
|
||||
impl<TcpSocket: 'static> CoreServerProtocolUpgrader<TcpSocket> {
|
||||
pub fn new(config: CoreServerProtocolConfig) -> Self {
|
||||
Self {
|
||||
config,
|
||||
external: None,
|
||||
tcp_socket: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_external(
|
||||
config: CoreServerProtocolConfig,
|
||||
external: Arc<dyn ServerProtocolUpgrader<TcpSocket>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
config,
|
||||
external: Some(external),
|
||||
tcp_socket: PhantomData,
|
||||
}
|
||||
}
|
||||
|
||||
fn supports_core_scheme(&self, scheme: &str) -> Option<bool> {
|
||||
match scheme {
|
||||
"tcp" | "udp" | "ring" => Some(true),
|
||||
"unix" => Some(self.config.unix),
|
||||
"faketcp" => Some(self.config.faketcp),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn external(&self, scheme: &str) -> anyhow::Result<&dyn ServerProtocolUpgrader<TcpSocket>> {
|
||||
let external = self
|
||||
.external
|
||||
.as_deref()
|
||||
.ok_or_else(|| anyhow::anyhow!("unsupported server protocol upgrader: {scheme}"))?;
|
||||
if !external.supports_scheme(scheme) {
|
||||
anyhow::bail!("unsupported server protocol upgrader: {scheme}");
|
||||
}
|
||||
Ok(external)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<TcpSocket> ServerProtocolUpgrader<TcpSocket> for CoreServerProtocolUpgrader<TcpSocket>
|
||||
where
|
||||
TcpSocket: VirtualTcpSocket,
|
||||
{
|
||||
fn supports_scheme(&self, scheme: &str) -> bool {
|
||||
self.supports_core_scheme(scheme).unwrap_or_else(|| {
|
||||
self.external
|
||||
.as_ref()
|
||||
.is_some_and(|external| external.supports_scheme(scheme))
|
||||
})
|
||||
}
|
||||
|
||||
fn max_pending_tcp_upgrades(&self, scheme: &str) -> Option<NonZeroUsize> {
|
||||
self.external
|
||||
.as_ref()
|
||||
.filter(|external| external.supports_scheme(scheme))
|
||||
.and_then(|external| external.max_pending_tcp_upgrades(scheme))
|
||||
}
|
||||
|
||||
async fn upgrade_tcp(
|
||||
&self,
|
||||
socket: TcpSocket,
|
||||
local_url: Url,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
match local_url.scheme() {
|
||||
"tcp" | "faketcp" => Ok(ServerProtocolUpgrade::Tunnel(
|
||||
upgrade_accepted_tcp(socket, local_url, self.config).await?,
|
||||
)),
|
||||
"udp" | "wg" | "quic" => {
|
||||
anyhow::bail!("{} protocol requires a UDP session", local_url.scheme())
|
||||
}
|
||||
"ring" | "unix" => {
|
||||
anyhow::bail!("{} protocol requires a byte stream", local_url.scheme())
|
||||
}
|
||||
scheme => self.external(scheme)?.upgrade_tcp(socket, local_url).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn upgrade_udp(
|
||||
&self,
|
||||
session: UdpSession,
|
||||
local_url: Url,
|
||||
admission: Option<ServerProtocolAdmission>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
match local_url.scheme() {
|
||||
"udp" => Ok(ServerProtocolUpgrade::Tunnel(upgrade_accepted_udp(
|
||||
session, &local_url,
|
||||
)?)),
|
||||
"tcp" | "faketcp" => {
|
||||
anyhow::bail!("{} protocol requires a TCP transport", local_url.scheme())
|
||||
}
|
||||
"ring" | "unix" => {
|
||||
anyhow::bail!("{} protocol requires a byte stream", local_url.scheme())
|
||||
}
|
||||
scheme => {
|
||||
self.external(scheme)?
|
||||
.upgrade_udp(session, local_url, admission)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn upgrade_byte_stream(
|
||||
&self,
|
||||
socket: TcpSocket,
|
||||
local_url: Url,
|
||||
remote_url: Option<Url>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
match local_url.scheme() {
|
||||
"ring" => Ok(ServerProtocolUpgrade::Tunnel(
|
||||
raw::upgrade_accepted_byte_stream(socket, local_url, remote_url)?,
|
||||
)),
|
||||
"unix" if self.config.unix => Ok(ServerProtocolUpgrade::Tunnel(
|
||||
raw::upgrade_accepted_byte_stream(socket, local_url, remote_url)?,
|
||||
)),
|
||||
"tcp" | "faketcp" => {
|
||||
anyhow::bail!("{} protocol requires a TCP transport", local_url.scheme())
|
||||
}
|
||||
"udp" | "wg" | "quic" => {
|
||||
anyhow::bail!("{} protocol requires a UDP session", local_url.scheme())
|
||||
}
|
||||
"unix" => anyhow::bail!("unsupported server protocol upgrader: unix"),
|
||||
scheme => {
|
||||
self.external(scheme)?
|
||||
.upgrade_byte_stream(socket, local_url, remote_url)
|
||||
.await
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn upgrade_accepted_tcp<TcpSocket>(
|
||||
socket: TcpSocket,
|
||||
local_url: Url,
|
||||
config: CoreServerProtocolConfig,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>>
|
||||
where
|
||||
TcpSocket: VirtualTcpSocket,
|
||||
{
|
||||
match local_url.scheme() {
|
||||
"tcp" => Ok(raw::upgrade_accepted_tcp_with_local_url(socket, local_url)?),
|
||||
"faketcp" if config.faketcp => {
|
||||
Ok(raw::upgrade_accepted_tcp_with_local_url(socket, local_url)?)
|
||||
}
|
||||
scheme => anyhow::bail!("unsupported TCP listener protocol: {scheme}"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn upgrade_accepted_udp(
|
||||
session: UdpSession,
|
||||
local_url: &Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>> {
|
||||
match local_url.scheme() {
|
||||
"udp" => Ok(raw::upgrade_accepted_udp_with_local_url(
|
||||
session,
|
||||
local_url.clone(),
|
||||
)?),
|
||||
scheme => anyhow::bail!("unsupported UDP listener protocol: {scheme}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
net::SocketAddr,
|
||||
pin::Pin,
|
||||
sync::Arc,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
use super::*;
|
||||
use crate::socket::udp::{UdpSessionKind, VirtualUdpSocket};
|
||||
|
||||
#[test]
|
||||
fn protocol_port_metadata_is_authoritative_for_all_ip_protocols() {
|
||||
let cases = [
|
||||
("tcp", 0, 11010),
|
||||
("udp", 0, 11010),
|
||||
("wg", 1, 11011),
|
||||
("quic", 2, 11012),
|
||||
("ws", 1, 80),
|
||||
("wss", 2, 443),
|
||||
("faketcp", 3, 11013),
|
||||
];
|
||||
|
||||
for (scheme, offset, port) in cases {
|
||||
assert_eq!(protocol_port_offset(scheme), Some(offset));
|
||||
assert_eq!(protocol_default_port(scheme), Some(port));
|
||||
}
|
||||
assert_eq!(protocol_default_port("ring"), None);
|
||||
}
|
||||
|
||||
struct MockTcpSocket;
|
||||
|
||||
impl AsyncRead for MockTcpSocket {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
_buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Poll::Pending
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for MockTcpSocket {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
_buf: &[u8],
|
||||
) -> Poll<Result<usize, io::Error>> {
|
||||
Poll::Pending
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, _cx: &mut Context<'_>) -> Poll<Result<(), io::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
|
||||
fn poll_shutdown(
|
||||
self: Pin<&mut Self>,
|
||||
_cx: &mut Context<'_>,
|
||||
) -> Poll<Result<(), io::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
}
|
||||
|
||||
impl VirtualTcpSocket for MockTcpSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:1000".parse().unwrap())
|
||||
}
|
||||
|
||||
fn peer_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:2000".parse().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
struct MockUdpSocket {
|
||||
local_addr: SocketAddr,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockUdpSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], _addr: SocketAddr) -> io::Result<usize> {
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
struct MockExternalUpgrader;
|
||||
|
||||
#[async_trait]
|
||||
impl ClientProtocolUpgrader<MockTcpSocket> for MockExternalUpgrader {
|
||||
fn supports_scheme(&self, _scheme: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
async fn upgrade_client(
|
||||
&self,
|
||||
_connected: ConnectedTransport<MockTcpSocket>,
|
||||
_requested_url: Url,
|
||||
) -> anyhow::Result<Box<dyn Tunnel>> {
|
||||
anyhow::bail!("external protocol invoked")
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl ServerProtocolUpgrader<MockTcpSocket> for MockExternalUpgrader {
|
||||
fn supports_scheme(&self, scheme: &str) -> bool {
|
||||
matches!(scheme, "external" | "ring" | "unix")
|
||||
}
|
||||
|
||||
async fn upgrade_tcp(
|
||||
&self,
|
||||
_socket: MockTcpSocket,
|
||||
_local_url: Url,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
anyhow::bail!("external server protocol invoked")
|
||||
}
|
||||
|
||||
async fn upgrade_udp(
|
||||
&self,
|
||||
_session: UdpSession,
|
||||
_local_url: Url,
|
||||
_admission: Option<ServerProtocolAdmission>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
anyhow::bail!("external server UDP protocol invoked")
|
||||
}
|
||||
|
||||
async fn upgrade_byte_stream(
|
||||
&self,
|
||||
_socket: MockTcpSocket,
|
||||
_local_url: Url,
|
||||
_remote_url: Option<Url>,
|
||||
) -> anyhow::Result<ServerProtocolUpgrade> {
|
||||
anyhow::bail!("external server byte-stream protocol invoked")
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn default_core_upgrader_rejects_external_and_mismatched_protocols() {
|
||||
let upgrader =
|
||||
CoreClientProtocolUpgrader::<MockTcpSocket>::new(CoreClientProtocolConfig::default());
|
||||
|
||||
assert!(upgrader.supports_scheme("ring"));
|
||||
assert!(!upgrader.supports_scheme("unix"));
|
||||
|
||||
let unsupported = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::Tcp(MockTcpSocket),
|
||||
"ws://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert!(unsupported.is_err());
|
||||
|
||||
let mismatched = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::Tcp(MockTcpSocket),
|
||||
"udp://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert!(mismatched.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_upgrader_owns_builtin_capabilities_and_delegates_external_protocols() {
|
||||
let upgrader = CoreClientProtocolUpgrader::with_external(
|
||||
CoreClientProtocolConfig {
|
||||
unix: false,
|
||||
faketcp: false,
|
||||
},
|
||||
Arc::new(MockExternalUpgrader),
|
||||
);
|
||||
|
||||
assert!(upgrader.supports_scheme("tcp"));
|
||||
assert!(upgrader.supports_scheme("ring"));
|
||||
assert!(upgrader.supports_scheme("ws"));
|
||||
assert!(!upgrader.supports_scheme("unix"));
|
||||
assert!(!upgrader.supports_scheme("faketcp"));
|
||||
|
||||
let external = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::Tcp(MockTcpSocket),
|
||||
"ws://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(external.to_string(), "external protocol invoked");
|
||||
|
||||
let disabled_builtin = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::Tcp(MockTcpSocket),
|
||||
"faketcp://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
disabled_builtin
|
||||
.to_string()
|
||||
.contains("unsupported client protocol upgrader")
|
||||
);
|
||||
|
||||
let mismatched_udp = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::Tcp(MockTcpSocket),
|
||||
"udp://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
mismatched_udp.to_string(),
|
||||
"UDP protocol requires a UDP session"
|
||||
);
|
||||
|
||||
let mismatched_tcp = upgrader
|
||||
.upgrade_client(
|
||||
ConnectedTransport::ByteStream(super::super::transport::ConnectedByteStream::new(
|
||||
MockTcpSocket,
|
||||
None,
|
||||
"ring://remote".parse().unwrap(),
|
||||
None,
|
||||
)),
|
||||
"tcp://127.0.0.1:2000".parse().unwrap(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
mismatched_tcp.to_string(),
|
||||
"TCP protocol requires a TCP transport"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_server_dispatches_raw_tcp_and_enforces_host_capabilities() {
|
||||
let tunnel = upgrade_accepted_tcp(
|
||||
MockTcpSocket,
|
||||
"tcp://0.0.0.0:2000".parse().unwrap(),
|
||||
CoreServerProtocolConfig::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
tunnel.info().unwrap().local_addr.unwrap().url,
|
||||
"tcp://0.0.0.0:2000"
|
||||
);
|
||||
|
||||
let disabled = upgrade_accepted_tcp(
|
||||
MockTcpSocket,
|
||||
"ws://0.0.0.0:2000".parse().unwrap(),
|
||||
CoreServerProtocolConfig::default(),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
disabled.to_string(),
|
||||
"unsupported TCP listener protocol: ws"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_server_raw_udp_preserves_explicit_listener_url() {
|
||||
let local_url: Url = "udp://listener.example:1000/path?bind_device=eth0"
|
||||
.parse()
|
||||
.unwrap();
|
||||
let session = UdpSession::identity_standalone(
|
||||
Arc::new(MockUdpSocket {
|
||||
local_addr: "127.0.0.1:1000".parse().unwrap(),
|
||||
}),
|
||||
"127.0.0.1:2000".parse().unwrap(),
|
||||
UdpSessionKind::EasyTierMux,
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let tunnel = upgrade_accepted_udp(session, &local_url).unwrap();
|
||||
|
||||
assert_eq!(
|
||||
tunnel.info().unwrap().local_addr.unwrap().url,
|
||||
local_url.as_str()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn core_server_upgrader_owns_builtin_dispatch_and_delegates_external_protocols() {
|
||||
let upgrader = CoreServerProtocolUpgrader::with_external(
|
||||
CoreServerProtocolConfig::default(),
|
||||
Arc::new(MockExternalUpgrader),
|
||||
);
|
||||
|
||||
assert!(upgrader.supports_scheme("tcp"));
|
||||
assert!(upgrader.supports_scheme("udp"));
|
||||
assert!(!upgrader.supports_scheme("ws"));
|
||||
assert!(!upgrader.supports_scheme("quic"));
|
||||
assert!(upgrader.supports_scheme("ring"));
|
||||
assert!(!upgrader.supports_scheme("unix"));
|
||||
assert!(upgrader.supports_scheme("external"));
|
||||
|
||||
let external = upgrader
|
||||
.upgrade_tcp(MockTcpSocket, "external://0.0.0.0:2000".parse().unwrap())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(external.to_string(), "external server protocol invoked");
|
||||
|
||||
let mismatched = upgrader
|
||||
.upgrade_tcp(MockTcpSocket, "quic://0.0.0.0:2000".parse().unwrap())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
mismatched.to_string(),
|
||||
"quic protocol requires a UDP session"
|
||||
);
|
||||
|
||||
let wrong_ring_transport = upgrader
|
||||
.upgrade_tcp(MockTcpSocket, "ring://local".parse().unwrap())
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
wrong_ring_transport.to_string(),
|
||||
"ring protocol requires a byte stream"
|
||||
);
|
||||
|
||||
let disabled_unix = upgrader
|
||||
.upgrade_byte_stream(
|
||||
MockTcpSocket,
|
||||
"unix:///tmp/easytier.sock".parse().unwrap(),
|
||||
None,
|
||||
)
|
||||
.await
|
||||
.err()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
disabled_unix.to_string(),
|
||||
"unsupported server protocol upgrader: unix"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn server_protocol_admission_is_scoped_to_its_controller() {
|
||||
let controller = ServerProtocolAdmissionController::new(1, 2);
|
||||
let admission = controller.try_admit().unwrap();
|
||||
assert!(controller.try_admit().is_none());
|
||||
|
||||
let (active_session, handshake_slots) = admission.into_parts();
|
||||
assert_eq!(handshake_slots.available_permits(), 2);
|
||||
drop(active_session);
|
||||
assert!(controller.try_admit().is_some());
|
||||
|
||||
let other = ServerProtocolAdmissionController::new(1, 1);
|
||||
assert!(other.try_admit().is_some());
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,768 @@
|
||||
//! Per-instance STUN state and background detection lifecycle.
|
||||
|
||||
use std::{
|
||||
collections::BTreeSet,
|
||||
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
|
||||
sync::{
|
||||
Arc, Mutex, RwLock,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::{Duration, SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use rand::seq::IteratorRandom as _;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use crate::{
|
||||
config::{
|
||||
DEFAULT_TCP_STUN_SERVERS, DEFAULT_UDP_STUN_SERVERS, DEFAULT_UDP_V6_STUN_SERVERS,
|
||||
default_stun_servers,
|
||||
},
|
||||
proto::common::{NatType, StunInfo},
|
||||
socket::{
|
||||
IpVersion, SocketContext,
|
||||
udp::{VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
use super::client::{
|
||||
HostResolverIter, StunDnsRuntime, StunNatTypeDetectResult, StunSocketRuntime,
|
||||
TcpNatTypeDetector, UdpNatTypeDetector, stun_udp_bind_options, tcp_bind_request,
|
||||
udp_bind_request,
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct StunServerConfig {
|
||||
pub udp_servers: Vec<String>,
|
||||
pub tcp_servers: Vec<String>,
|
||||
pub udp_v6_servers: Vec<String>,
|
||||
}
|
||||
|
||||
impl Default for StunServerConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
udp_servers: default_stun_servers(DEFAULT_UDP_STUN_SERVERS),
|
||||
tcp_servers: default_stun_servers(DEFAULT_TCP_STUN_SERVERS),
|
||||
udp_v6_servers: default_stun_servers(DEFAULT_UDP_V6_STUN_SERVERS),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
#[auto_impl::auto_impl(&, Arc, Box)]
|
||||
pub trait StunInfoProvider: Send + Sync {
|
||||
fn get_stun_info(&self) -> StunInfo;
|
||||
|
||||
async fn get_udp_port_mapping(&self, local_port: u16) -> anyhow::Result<SocketAddr>;
|
||||
|
||||
async fn get_tcp_port_mapping(&self, local_port: u16) -> anyhow::Result<SocketAddr>;
|
||||
|
||||
fn update_stun_info(&self);
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
#[auto_impl::auto_impl(&, Arc, Box)]
|
||||
pub trait StunSocketMapper<S>: StunInfoProvider + Send + Sync
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
async fn get_udp_port_mapping_with_socket(&self, socket: Arc<S>) -> anyhow::Result<SocketAddr>;
|
||||
}
|
||||
|
||||
pub struct StunInfoCollector<R, D: ?Sized>
|
||||
where
|
||||
R: StunSocketRuntime,
|
||||
D: StunDnsRuntime,
|
||||
{
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
udp_socket_context: SocketContext,
|
||||
tcp_socket_context: SocketContext,
|
||||
stun_servers: Arc<RwLock<Vec<String>>>,
|
||||
tcp_stun_servers: Arc<RwLock<Vec<String>>>,
|
||||
stun_servers_v6: Arc<RwLock<Vec<String>>>,
|
||||
udp_nat_test_result: Arc<RwLock<Option<StunNatTypeDetectResult>>>,
|
||||
tcp_nat_test_result: Arc<RwLock<Option<StunNatTypeDetectResult>>>,
|
||||
public_ipv6: Arc<RwLock<Option<Ipv6Addr>>>,
|
||||
nat_test_result_time: Arc<RwLock<i64>>,
|
||||
redetect_notify: Arc<tokio::sync::Notify>,
|
||||
tasks: Mutex<JoinSet<()>>,
|
||||
started: AtomicBool,
|
||||
}
|
||||
|
||||
impl<R, D> StunInfoCollector<R, D>
|
||||
where
|
||||
R: StunSocketRuntime,
|
||||
D: StunDnsRuntime + ?Sized,
|
||||
{
|
||||
pub fn new(
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
socket_context: SocketContext,
|
||||
udp_stun_servers: Vec<String>,
|
||||
tcp_stun_servers: Vec<String>,
|
||||
stun_servers_v6: Vec<String>,
|
||||
) -> Self {
|
||||
Self::new_with_socket_contexts(
|
||||
runtime,
|
||||
dns,
|
||||
socket_context.clone(),
|
||||
socket_context,
|
||||
udp_stun_servers,
|
||||
tcp_stun_servers,
|
||||
stun_servers_v6,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_with_socket_contexts(
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
udp_socket_context: SocketContext,
|
||||
tcp_socket_context: SocketContext,
|
||||
udp_stun_servers: Vec<String>,
|
||||
tcp_stun_servers: Vec<String>,
|
||||
stun_servers_v6: Vec<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
runtime,
|
||||
dns,
|
||||
udp_socket_context,
|
||||
tcp_socket_context,
|
||||
stun_servers: Arc::new(RwLock::new(udp_stun_servers)),
|
||||
tcp_stun_servers: Arc::new(RwLock::new(tcp_stun_servers)),
|
||||
stun_servers_v6: Arc::new(RwLock::new(stun_servers_v6)),
|
||||
udp_nat_test_result: Arc::new(RwLock::new(None)),
|
||||
tcp_nat_test_result: Arc::new(RwLock::new(None)),
|
||||
public_ipv6: Arc::new(RwLock::new(None)),
|
||||
nat_test_result_time: Arc::new(RwLock::new(unix_timestamp())),
|
||||
redetect_notify: Arc::new(tokio::sync::Notify::new()),
|
||||
tasks: Mutex::new(JoinSet::new()),
|
||||
started: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn new_with_default_servers(
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
socket_context: SocketContext,
|
||||
) -> Self {
|
||||
Self::new(
|
||||
runtime,
|
||||
dns,
|
||||
socket_context,
|
||||
Self::get_default_servers(),
|
||||
Self::get_default_tcp_servers(),
|
||||
Self::get_default_servers_v6(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn new_with_default_servers_and_socket_contexts(
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
udp_socket_context: SocketContext,
|
||||
tcp_socket_context: SocketContext,
|
||||
) -> Self {
|
||||
Self::new_with_socket_contexts(
|
||||
runtime,
|
||||
dns,
|
||||
udp_socket_context,
|
||||
tcp_socket_context,
|
||||
Self::get_default_servers(),
|
||||
Self::get_default_tcp_servers(),
|
||||
Self::get_default_servers_v6(),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn set_stun_servers(&self, stun_servers: Vec<String>) {
|
||||
*self.stun_servers.write().unwrap() = stun_servers;
|
||||
}
|
||||
|
||||
pub fn set_stun_servers_v6(&self, stun_servers_v6: Vec<String>) {
|
||||
*self.stun_servers_v6.write().unwrap() = stun_servers_v6;
|
||||
}
|
||||
|
||||
pub fn set_tcp_stun_servers(&self, stun_servers: Vec<String>) {
|
||||
*self.tcp_stun_servers.write().unwrap() = stun_servers;
|
||||
}
|
||||
|
||||
pub fn get_default_servers() -> Vec<String> {
|
||||
StunServerConfig::default().udp_servers
|
||||
}
|
||||
|
||||
pub fn get_default_tcp_servers() -> Vec<String> {
|
||||
StunServerConfig::default().tcp_servers
|
||||
}
|
||||
|
||||
pub fn get_default_servers_v6() -> Vec<String> {
|
||||
StunServerConfig::default().udp_v6_servers
|
||||
}
|
||||
|
||||
async fn get_public_ipv6(
|
||||
runtime: Arc<R>,
|
||||
dns: Arc<D>,
|
||||
socket_context: SocketContext,
|
||||
servers: &[String],
|
||||
) -> Option<Ipv6Addr> {
|
||||
let mut resolver = HostResolverIter::new(
|
||||
dns,
|
||||
socket_context.clone().with_ip_version(IpVersion::V6),
|
||||
servers.to_vec(),
|
||||
10,
|
||||
true,
|
||||
);
|
||||
while let Some(server) = resolver.next().await {
|
||||
let socket = runtime
|
||||
.bind_udp(stun_udp_bind_options(
|
||||
socket_context.clone(),
|
||||
IpVersion::V6,
|
||||
SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), 0),
|
||||
))
|
||||
.await
|
||||
.ok()?;
|
||||
let response = udp_bind_request(socket, server).await;
|
||||
tracing::debug!(?response, "finish ipv6 udp nat type detect");
|
||||
if let Ok(Some(IpAddr::V6(ip))) =
|
||||
response.map(|response| response.mapped_socket_addr.map(|addr| addr.ip()))
|
||||
{
|
||||
return Some(ip);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn start_stun_routine(&self) {
|
||||
if self.started.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let runtime = self.runtime.clone();
|
||||
let dns = self.dns.clone();
|
||||
let socket_context = self.udp_socket_context.clone();
|
||||
let stun_servers = self.stun_servers.clone();
|
||||
let udp_nat_test_result = self.udp_nat_test_result.clone();
|
||||
let nat_test_time = self.nat_test_result_time.clone();
|
||||
let redetect_notify = self.redetect_notify.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
let servers = sampled_servers(&stun_servers.read().unwrap());
|
||||
let detector = UdpNatTypeDetector::new(
|
||||
runtime.clone(),
|
||||
dns.clone(),
|
||||
socket_context.clone(),
|
||||
servers,
|
||||
1,
|
||||
);
|
||||
let mut result = detector.detect_nat_type(0).await;
|
||||
tracing::debug!(?result, "finish udp nat type detect");
|
||||
|
||||
let nat_type = result
|
||||
.as_ref()
|
||||
.map(StunNatTypeDetectResult::nat_type)
|
||||
.unwrap_or(NatType::Unknown);
|
||||
if nat_type == NatType::Symmetric {
|
||||
let old_result = result.as_mut().unwrap();
|
||||
tracing::debug!(?old_result, "start get extra bind result");
|
||||
for server in old_result.collect_available_stun_server() {
|
||||
let extra = detector.get_extra_bind_result(0, server).await;
|
||||
tracing::debug!(?extra, "finish udp nat type detect with another port");
|
||||
if let Ok(response) = extra {
|
||||
old_result.extra_bind_test = Some(response);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut sleep_sec = 10;
|
||||
if let Ok(result) = result {
|
||||
*nat_test_time.write().unwrap() = unix_timestamp();
|
||||
let completed_extra_test = result.extra_bind_test.is_some();
|
||||
*udp_nat_test_result.write().unwrap() = Some(result);
|
||||
if nat_type != NatType::Unknown
|
||||
&& (nat_type != NatType::Symmetric || completed_extra_test)
|
||||
{
|
||||
sleep_sec = 600;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = redetect_notify.notified() => {}
|
||||
_ = crate::foundation::time::sleep(Duration::from_secs(sleep_sec)) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let runtime = self.runtime.clone();
|
||||
let dns = self.dns.clone();
|
||||
let socket_context = self.tcp_socket_context.clone();
|
||||
let tcp_stun_servers = self.tcp_stun_servers.clone();
|
||||
let tcp_nat_test_result = self.tcp_nat_test_result.clone();
|
||||
let nat_test_time = self.nat_test_result_time.clone();
|
||||
let redetect_notify = self.redetect_notify.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
let servers = sampled_servers(&tcp_stun_servers.read().unwrap());
|
||||
let detector = TcpNatTypeDetector::new(
|
||||
runtime.clone(),
|
||||
dns.clone(),
|
||||
socket_context.clone(),
|
||||
servers,
|
||||
1,
|
||||
);
|
||||
let result = detector.detect_nat_type(0).await;
|
||||
tracing::debug!(?result, "finish tcp nat type detect");
|
||||
|
||||
let mut sleep_sec = 10;
|
||||
if let Ok(result) = result {
|
||||
*nat_test_time.write().unwrap() = unix_timestamp();
|
||||
let nat_type = result.nat_type();
|
||||
*tcp_nat_test_result.write().unwrap() = Some(result);
|
||||
if nat_type != NatType::Unknown {
|
||||
sleep_sec = 600;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = redetect_notify.notified() => {}
|
||||
_ = crate::foundation::time::sleep(Duration::from_secs(sleep_sec)) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let runtime = self.runtime.clone();
|
||||
let dns = self.dns.clone();
|
||||
let socket_context = self.udp_socket_context.clone();
|
||||
let stun_servers_v6 = self.stun_servers_v6.clone();
|
||||
let public_ipv6 = self.public_ipv6.clone();
|
||||
let redetect_notify = self.redetect_notify.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
let servers = stun_servers_v6.read().unwrap().clone();
|
||||
if let Some(ip) = Self::get_public_ipv6(
|
||||
runtime.clone(),
|
||||
dns.clone(),
|
||||
socket_context.clone(),
|
||||
&servers,
|
||||
)
|
||||
.await
|
||||
{
|
||||
*public_ipv6.write().unwrap() = Some(ip);
|
||||
}
|
||||
|
||||
let sleep_sec = if public_ipv6.read().unwrap().is_none() {
|
||||
60
|
||||
} else {
|
||||
360
|
||||
};
|
||||
tokio::select! {
|
||||
_ = redetect_notify.notified() => {}
|
||||
_ = crate::foundation::time::sleep(Duration::from_secs(sleep_sec)) => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<R, D> StunInfoProvider for StunInfoCollector<R, D>
|
||||
where
|
||||
R: StunSocketRuntime,
|
||||
D: StunDnsRuntime + ?Sized,
|
||||
{
|
||||
fn get_stun_info(&self) -> StunInfo {
|
||||
self.start_stun_routine();
|
||||
let udp_result = self.udp_nat_test_result.read().unwrap().clone();
|
||||
let tcp_result = self.tcp_nat_test_result.read().unwrap().clone();
|
||||
if udp_result.is_none() && tcp_result.is_none() {
|
||||
return StunInfo::default();
|
||||
}
|
||||
|
||||
let mut public_ip = BTreeSet::<String>::new();
|
||||
if let Some(result) = &udp_result {
|
||||
public_ip.extend(result.public_ips().into_iter().map(|ip| ip.to_string()));
|
||||
}
|
||||
if let Some(result) = &tcp_result {
|
||||
public_ip.extend(result.public_ips().into_iter().map(|ip| ip.to_string()));
|
||||
}
|
||||
if let Some(ip) = *self.public_ipv6.read().unwrap() {
|
||||
public_ip.insert(ip.to_string());
|
||||
}
|
||||
|
||||
StunInfo {
|
||||
udp_nat_type: udp_result
|
||||
.as_ref()
|
||||
.map(|result| result.nat_type() as i32)
|
||||
.unwrap_or(NatType::Unknown as i32),
|
||||
tcp_nat_type: tcp_result
|
||||
.as_ref()
|
||||
.map(|result| result.nat_type() as i32)
|
||||
.unwrap_or(NatType::Unknown as i32),
|
||||
last_update_time: *self.nat_test_result_time.read().unwrap(),
|
||||
public_ip: public_ip.into_iter().collect(),
|
||||
min_port: udp_result
|
||||
.as_ref()
|
||||
.map(|result| result.min_port() as u32)
|
||||
.or_else(|| tcp_result.as_ref().map(|result| result.min_port() as u32))
|
||||
.unwrap_or(0),
|
||||
max_port: udp_result
|
||||
.as_ref()
|
||||
.map(|result| result.max_port() as u32)
|
||||
.or_else(|| tcp_result.as_ref().map(|result| result.max_port() as u32))
|
||||
.unwrap_or(0),
|
||||
}
|
||||
}
|
||||
|
||||
async fn get_udp_port_mapping(&self, local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
let socket = self
|
||||
.runtime
|
||||
.bind_udp(stun_udp_bind_options(
|
||||
self.udp_socket_context.clone(),
|
||||
IpVersion::V4,
|
||||
SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), local_port),
|
||||
))
|
||||
.await?;
|
||||
StunSocketMapper::get_udp_port_mapping_with_socket(self, socket).await
|
||||
}
|
||||
|
||||
async fn get_tcp_port_mapping(&self, local_port: u16) -> anyhow::Result<SocketAddr> {
|
||||
self.start_stun_routine();
|
||||
let mut servers = self
|
||||
.tcp_nat_test_result
|
||||
.read()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.map(|result| result.collect_available_stun_server())
|
||||
.unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
let mut resolver = HostResolverIter::new(
|
||||
self.dns.clone(),
|
||||
self.tcp_socket_context
|
||||
.clone()
|
||||
.with_ip_version(IpVersion::V4),
|
||||
self.tcp_stun_servers.read().unwrap().clone(),
|
||||
2,
|
||||
false,
|
||||
);
|
||||
while let Some(addr) = resolver.next().await {
|
||||
servers.push(addr);
|
||||
if servers.len() >= 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for server in servers {
|
||||
match tcp_bind_request(
|
||||
self.runtime.clone(),
|
||||
self.tcp_socket_context.clone(),
|
||||
server,
|
||||
local_port,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
if let Some(mapped_addr) = response.mapped_socket_addr {
|
||||
return Ok(mapped_addr);
|
||||
}
|
||||
}
|
||||
Err(error) => tracing::warn!(?server, ?error, "tcp stun bind request failed"),
|
||||
}
|
||||
}
|
||||
anyhow::bail!("no TCP STUN mapping found")
|
||||
}
|
||||
|
||||
fn update_stun_info(&self) {
|
||||
self.redetect_notify.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<R, D> StunSocketMapper<<R as VirtualUdpSocketFactory>::Socket> for StunInfoCollector<R, D>
|
||||
where
|
||||
R: StunSocketRuntime,
|
||||
D: StunDnsRuntime + ?Sized,
|
||||
{
|
||||
async fn get_udp_port_mapping_with_socket(
|
||||
&self,
|
||||
socket: Arc<<R as VirtualUdpSocketFactory>::Socket>,
|
||||
) -> anyhow::Result<SocketAddr> {
|
||||
self.start_stun_routine();
|
||||
let mut servers = self
|
||||
.udp_nat_test_result
|
||||
.read()
|
||||
.unwrap()
|
||||
.clone()
|
||||
.map(|result| result.collect_available_stun_server())
|
||||
.unwrap_or_default();
|
||||
if servers.is_empty() {
|
||||
let mut resolver = HostResolverIter::new(
|
||||
self.dns.clone(),
|
||||
self.udp_socket_context
|
||||
.clone()
|
||||
.with_ip_version(IpVersion::V4),
|
||||
self.stun_servers.read().unwrap().clone(),
|
||||
2,
|
||||
false,
|
||||
);
|
||||
while let Some(addr) = resolver.next().await {
|
||||
servers.push(addr);
|
||||
if servers.len() >= 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for server in servers {
|
||||
match udp_bind_request(socket.clone(), server).await {
|
||||
Ok(response) => {
|
||||
if let Some(mapped_addr) = response.mapped_socket_addr {
|
||||
return Ok(mapped_addr);
|
||||
}
|
||||
}
|
||||
Err(error) => tracing::warn!(?server, ?error, "stun bind request failed"),
|
||||
}
|
||||
}
|
||||
anyhow::bail!("no UDP STUN mapping found")
|
||||
}
|
||||
}
|
||||
|
||||
fn sampled_servers(servers: &[String]) -> Vec<String> {
|
||||
servers
|
||||
.iter()
|
||||
.take(2)
|
||||
.chain(servers.iter().skip(2).choose(&mut rand::thread_rng()))
|
||||
.cloned()
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn unix_timestamp() -> i64 {
|
||||
SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap_or_default()
|
||||
.as_secs() as i64
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
collections::VecDeque,
|
||||
io,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use bytecodec::{DecodeExt as _, EncodeExt as _};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, ReadBuf};
|
||||
|
||||
use crate::host::dns::{DnsQuery, DnsRecordResolver, DnsResolver, DnsSrvRecord};
|
||||
use crate::socket::{
|
||||
NetNamespace,
|
||||
tcp::{TcpConnectOptions, VirtualTcpSocket, VirtualTcpSocketFactory},
|
||||
udp::{UdpBindOptions, UdpSocketPurpose},
|
||||
};
|
||||
|
||||
use crate::packet::stun::Attribute;
|
||||
use stun_codec::rfc5389::{attributes::XorMappedAddress, methods::BINDING};
|
||||
use stun_codec::{Message, MessageClass, MessageDecoder, MessageEncoder};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct MockUdpSocket {
|
||||
local_addr: SocketAddr,
|
||||
mapped_addr: SocketAddr,
|
||||
responses: Mutex<VecDeque<(Vec<u8>, SocketAddr)>>,
|
||||
response_ready: tokio::sync::Notify,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockUdpSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.local_addr)
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], addr: SocketAddr) -> io::Result<usize> {
|
||||
let request = MessageDecoder::<Attribute>::new()
|
||||
.decode_from_bytes(data)
|
||||
.map_err(|error| io::Error::other(format!("{error:?}")))?
|
||||
.map_err(|error| io::Error::other(format!("{error:?}")))?;
|
||||
let mut response = Message::<Attribute>::new(
|
||||
MessageClass::SuccessResponse,
|
||||
BINDING,
|
||||
request.transaction_id(),
|
||||
);
|
||||
response.add_attribute(Attribute::XorMappedAddress(XorMappedAddress::new(
|
||||
self.mapped_addr,
|
||||
)));
|
||||
let bytes = MessageEncoder::new()
|
||||
.encode_into_bytes(response)
|
||||
.map_err(io::Error::other)?;
|
||||
self.responses.lock().unwrap().push_back((bytes, addr));
|
||||
self.response_ready.notify_one();
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
loop {
|
||||
if let Some((bytes, addr)) = self.responses.lock().unwrap().pop_front() {
|
||||
buf[..bytes.len()].copy_from_slice(&bytes);
|
||||
return Ok((bytes.len(), addr));
|
||||
}
|
||||
self.response_ready.notified().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct MockTcpSocket(tokio::io::DuplexStream);
|
||||
|
||||
impl AsyncRead for MockTcpSocket {
|
||||
fn poll_read(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut ReadBuf<'_>,
|
||||
) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.0).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for MockTcpSocket {
|
||||
fn poll_write(
|
||||
mut self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<io::Result<usize>> {
|
||||
Pin::new(&mut self.0).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.0).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
|
||||
Pin::new(&mut self.0).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
|
||||
impl VirtualTcpSocket for MockTcpSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:40000".parse().unwrap())
|
||||
}
|
||||
|
||||
fn peer_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:3478".parse().unwrap())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct MockRuntime {
|
||||
udp_binds: Mutex<Vec<UdpBindOptions>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocketFactory for MockRuntime {
|
||||
type Socket = MockUdpSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.udp_binds.lock().unwrap().push(options);
|
||||
Ok(Arc::new(MockUdpSocket {
|
||||
local_addr: "0.0.0.0:40000".parse().unwrap(),
|
||||
mapped_addr: "198.51.100.10:40123".parse().unwrap(),
|
||||
responses: Mutex::new(VecDeque::new()),
|
||||
response_ready: tokio::sync::Notify::new(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualTcpSocketFactory for MockRuntime {
|
||||
type Socket = MockTcpSocket;
|
||||
|
||||
async fn connect_tcp(&self, _options: TcpConnectOptions) -> anyhow::Result<Self::Socket> {
|
||||
anyhow::bail!("TCP is not used by this test")
|
||||
}
|
||||
}
|
||||
|
||||
struct MockDns;
|
||||
|
||||
#[async_trait]
|
||||
impl DnsResolver for MockDns {
|
||||
async fn resolve(&self, _query: DnsQuery) -> anyhow::Result<Vec<IpAddr>> {
|
||||
Ok(vec!["192.0.2.1".parse().unwrap()])
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DnsRecordResolver for MockDns {
|
||||
async fn resolve_txt(&self, _query: DnsQuery) -> anyhow::Result<String> {
|
||||
Ok(String::new())
|
||||
}
|
||||
|
||||
async fn resolve_srv(&self, _query: DnsQuery) -> anyhow::Result<Vec<DnsSrvRecord>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sampled_servers_keep_first_two_and_at_most_one_extra() {
|
||||
let servers = ["a", "b", "c", "d"]
|
||||
.into_iter()
|
||||
.map(str::to_owned)
|
||||
.collect::<Vec<_>>();
|
||||
let sampled = sampled_servers(&servers);
|
||||
assert_eq!(&sampled[..2], &["a", "b"]);
|
||||
assert_eq!(sampled.len(), 3);
|
||||
assert!(matches!(sampled[2].as_str(), "c" | "d"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn collector_keeps_udp_and_tcp_socket_contexts_separate() {
|
||||
let udp_context = SocketContext::default()
|
||||
.with_socket_mark(Some(11))
|
||||
.with_netns(Some(NetNamespace::new("udp-instance")));
|
||||
let tcp_context = SocketContext::default()
|
||||
.with_socket_mark(Some(22))
|
||||
.with_netns(Some(NetNamespace::new("tcp-instance")));
|
||||
let collector = StunInfoCollector::new_with_socket_contexts(
|
||||
Arc::new(MockRuntime::default()),
|
||||
Arc::new(MockDns),
|
||||
udp_context.clone(),
|
||||
tcp_context.clone(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
assert_eq!(collector.udp_socket_context, udp_context);
|
||||
assert_eq!(collector.tcp_socket_context, tcp_context);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn udp_mapping_uses_portable_runtime_and_instance_context() {
|
||||
let runtime = Arc::new(MockRuntime::default());
|
||||
let context = SocketContext::default()
|
||||
.with_socket_mark(Some(0))
|
||||
.with_netns(Some(NetNamespace::new("instance-a")));
|
||||
let collector = StunInfoCollector::new(
|
||||
runtime.clone(),
|
||||
Arc::new(MockDns),
|
||||
context,
|
||||
vec!["stun.example".to_owned()],
|
||||
Vec::new(),
|
||||
Vec::new(),
|
||||
);
|
||||
|
||||
let mapped = collector.get_udp_port_mapping(0).await.unwrap();
|
||||
|
||||
assert_eq!(mapped, "198.51.100.10:40123".parse().unwrap());
|
||||
let binds = runtime.udp_binds.lock().unwrap();
|
||||
assert!(!binds.is_empty());
|
||||
assert_eq!(binds[0].purpose, UdpSocketPurpose::StunProbe);
|
||||
assert_eq!(binds[0].local_addr, Some("0.0.0.0:0".parse().unwrap()));
|
||||
assert_eq!(binds[0].context.ip_version, IpVersion::V4);
|
||||
assert_eq!(binds[0].context.socket_mark, Some(0));
|
||||
assert_eq!(
|
||||
binds[0].context.netns.as_ref().map(|netns| netns.token()),
|
||||
Some("instance-a")
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
mod client;
|
||||
mod collector;
|
||||
mod responder;
|
||||
|
||||
pub use client::{
|
||||
StunDnsRuntime, StunNatTypeDetectResult, StunSocketRuntime, TcpNatTypeDetector,
|
||||
UdpNatTypeDetector,
|
||||
};
|
||||
pub use collector::{StunInfoCollector, StunInfoProvider, StunServerConfig, StunSocketMapper};
|
||||
@@ -0,0 +1,247 @@
|
||||
//! STUN binding-response support over UDP sockets.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::Context as _;
|
||||
use bytecodec::{DecodeExt as _, EncodeExt as _};
|
||||
use stun_codec::rfc5389::attributes::XorMappedAddress;
|
||||
use stun_codec::rfc5389::methods::BINDING;
|
||||
use stun_codec::{Message, MessageClass, MessageDecoder, MessageEncoder};
|
||||
|
||||
use crate::packet::stun::{Attribute, ChangeRequest, tid_to_u32, u32_to_tid};
|
||||
use crate::socket::udp::{UdpBindOptions, VirtualUdpSocket, VirtualUdpSocketFactory};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum StunResponseSendSource {
|
||||
SameSocket,
|
||||
NewSocket,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct StunResponse {
|
||||
pub bytes: Vec<u8>,
|
||||
pub send_source: StunResponseSendSource,
|
||||
}
|
||||
|
||||
pub fn build_stun_response(addr: SocketAddr, req_buf: &[u8]) -> anyhow::Result<StunResponse> {
|
||||
let mut decoder = MessageDecoder::<Attribute>::new();
|
||||
let req_msg = decoder
|
||||
.decode_from_bytes(req_buf)
|
||||
.map_err(|e| anyhow::anyhow!("stun decode error: {:?}", e))?
|
||||
.map_err(|e| anyhow::anyhow!("stun decode broken message error: {:?}", e))?;
|
||||
|
||||
let tid = req_msg.transaction_id();
|
||||
// we only respond easytier stun req, whose tid has 0xdeadbeef prefix
|
||||
if tid.as_bytes()[0..4] != [0xde, 0xad, 0xbe, 0xef] {
|
||||
anyhow::bail!("stun req tid not from easytier");
|
||||
}
|
||||
|
||||
let mut resp_msg = Message::<Attribute>::new(
|
||||
MessageClass::SuccessResponse,
|
||||
BINDING,
|
||||
// we discard the prefix, make sure our implementation is not compatible with other stun client
|
||||
u32_to_tid(tid_to_u32(&tid)),
|
||||
);
|
||||
resp_msg.add_attribute(Attribute::XorMappedAddress(XorMappedAddress::new(addr)));
|
||||
|
||||
let mut encoder = MessageEncoder::new();
|
||||
let bytes = encoder
|
||||
.encode_into_bytes(resp_msg.clone())
|
||||
.map_err(|e| anyhow::anyhow!("stun encode error: {:?}", e))?;
|
||||
|
||||
let change_req = req_msg
|
||||
.get_attribute::<ChangeRequest>()
|
||||
.map(|r| r.ip() || r.port())
|
||||
.unwrap_or(false);
|
||||
|
||||
Ok(StunResponse {
|
||||
bytes,
|
||||
send_source: if change_req {
|
||||
StunResponseSendSource::NewSocket
|
||||
} else {
|
||||
StunResponseSendSource::SameSocket
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
async fn respond_stun_packet<S, F>(
|
||||
socket: Arc<S>,
|
||||
factory: &F,
|
||||
addr: SocketAddr,
|
||||
req_buf: &[u8],
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
F: VirtualUdpSocketFactory<Socket = S> + ?Sized,
|
||||
{
|
||||
let response = build_stun_response(addr, req_buf)?;
|
||||
match response.send_source {
|
||||
StunResponseSendSource::SameSocket => {
|
||||
socket
|
||||
.send_to(&response.bytes, addr)
|
||||
.await
|
||||
.with_context(|| "send stun response error")?;
|
||||
}
|
||||
StunResponseSendSource::NewSocket => {
|
||||
let bind_addr = if addr.is_ipv4() {
|
||||
"0.0.0.0:0".parse().unwrap()
|
||||
} else {
|
||||
"[::]:0".parse().unwrap()
|
||||
};
|
||||
let socket = factory
|
||||
.bind_udp(
|
||||
UdpBindOptions::hole_punch_control()
|
||||
.with_context(socket.socket_context())
|
||||
.with_local_addr(Some(bind_addr)),
|
||||
)
|
||||
.await?;
|
||||
socket.send_to(&response.bytes, addr).await?;
|
||||
}
|
||||
}
|
||||
|
||||
tracing::debug!(?addr, "udp respond stun packet done");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<S, F> crate::socket::udp::UdpSessionStunResponder<S> for F
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
F: VirtualUdpSocketFactory<Socket = S>,
|
||||
{
|
||||
async fn respond_stun(
|
||||
&self,
|
||||
socket: Arc<S>,
|
||||
datagram: &[u8],
|
||||
remote_addr: SocketAddr,
|
||||
) -> std::io::Result<()> {
|
||||
respond_stun_packet(socket, self, remote_addr, datagram)
|
||||
.await
|
||||
.map_err(|error| std::io::Error::other(error.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{io, sync::Mutex};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use stun_codec::TransactionId;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct MockSocket {
|
||||
sent: Mutex<Vec<(Vec<u8>, SocketAddr)>>,
|
||||
}
|
||||
|
||||
impl MockSocket {
|
||||
fn sent(&self) -> Vec<(Vec<u8>, SocketAddr)> {
|
||||
self.sent.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocket for MockSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:0".parse().unwrap())
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], addr: SocketAddr) -> io::Result<usize> {
|
||||
self.sent.lock().unwrap().push((data.to_vec(), addr));
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct MockFactory {
|
||||
bind_options: Mutex<Vec<UdpBindOptions>>,
|
||||
sockets: Mutex<Vec<Arc<MockSocket>>>,
|
||||
}
|
||||
|
||||
impl MockFactory {
|
||||
fn bind_options(&self) -> Vec<UdpBindOptions> {
|
||||
self.bind_options.lock().unwrap().clone()
|
||||
}
|
||||
|
||||
fn sockets(&self) -> Vec<Arc<MockSocket>> {
|
||||
self.sockets.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl VirtualUdpSocketFactory for MockFactory {
|
||||
type Socket = MockSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.bind_options.lock().unwrap().push(options);
|
||||
let socket = Arc::new(MockSocket::default());
|
||||
self.sockets.lock().unwrap().push(socket.clone());
|
||||
Ok(socket)
|
||||
}
|
||||
}
|
||||
|
||||
fn stun_request(change_ip: bool, change_port: bool) -> Vec<u8> {
|
||||
let mut request = Message::<Attribute>::new(MessageClass::Request, BINDING, u32_to_tid(7));
|
||||
if change_ip || change_port {
|
||||
request.add_attribute(Attribute::ChangeRequest(ChangeRequest::new(
|
||||
change_ip,
|
||||
change_port,
|
||||
)));
|
||||
}
|
||||
MessageEncoder::new().encode_into_bytes(request).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_stun_response_rejects_non_easytier_tid() {
|
||||
let request =
|
||||
Message::<Attribute>::new(MessageClass::Request, BINDING, TransactionId::new([0; 12]));
|
||||
let mut encoder = MessageEncoder::new();
|
||||
let request = encoder.encode_into_bytes(request).unwrap();
|
||||
|
||||
assert!(build_stun_response("127.0.0.1:1234".parse().unwrap(), &request).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn build_stun_response_detects_change_request() {
|
||||
let request = stun_request(true, false);
|
||||
|
||||
let response = build_stun_response("127.0.0.1:1234".parse().unwrap(), &request).unwrap();
|
||||
|
||||
assert_eq!(response.send_source, StunResponseSendSource::NewSocket);
|
||||
assert!(!response.bytes.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn respond_stun_packet_uses_ipv6_unspecified_socket_for_ipv6_change_request() {
|
||||
let listener_socket = Arc::new(MockSocket::default());
|
||||
let factory = MockFactory::default();
|
||||
let remote_addr = "[::1]:1234".parse().unwrap();
|
||||
|
||||
respond_stun_packet(
|
||||
listener_socket.clone(),
|
||||
&factory,
|
||||
remote_addr,
|
||||
&stun_request(true, false),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(listener_socket.sent().is_empty());
|
||||
assert_eq!(
|
||||
factory.bind_options(),
|
||||
vec![
|
||||
UdpBindOptions::hole_punch_control()
|
||||
.with_local_addr(Some("[::]:0".parse().unwrap()))
|
||||
]
|
||||
);
|
||||
let sockets = factory.sockets();
|
||||
assert_eq!(sockets.len(), 1);
|
||||
assert_eq!(sockets[0].sent()[0].1, remote_addr);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
use std::future::Future;
|
||||
|
||||
use futures::{StreamExt, stream::FuturesUnordered};
|
||||
use url::Url;
|
||||
|
||||
mod tcp;
|
||||
mod udp;
|
||||
|
||||
pub(crate) use tcp::connect_tcp;
|
||||
pub use udp::{ConnectedUdpSession, UdpSessionMode, connect_udp};
|
||||
|
||||
/// A host-created non-IP byte stream with host-provided endpoint metadata.
|
||||
///
|
||||
/// Unix and in-process transports use the same stream framing boundary as TCP,
|
||||
/// but their endpoints cannot be represented by `SocketAddr`.
|
||||
pub struct ConnectedByteStream<S> {
|
||||
socket: S,
|
||||
local_url: Option<Url>,
|
||||
remote_url: Url,
|
||||
resolved_remote_url: Option<Url>,
|
||||
}
|
||||
|
||||
impl<S> ConnectedByteStream<S> {
|
||||
pub fn new(
|
||||
socket: S,
|
||||
local_url: Option<Url>,
|
||||
remote_url: Url,
|
||||
resolved_remote_url: Option<Url>,
|
||||
) -> Self {
|
||||
Self {
|
||||
socket,
|
||||
local_url,
|
||||
remote_url,
|
||||
resolved_remote_url,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_parts(self) -> (S, Option<Url>, Url, Option<Url>) {
|
||||
(
|
||||
self.socket,
|
||||
self.local_url,
|
||||
self.remote_url,
|
||||
self.resolved_remote_url,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A transport endpoint established by a connectivity strategy.
|
||||
///
|
||||
/// Manual, direct, and hole-punch strategies stop at this boundary. Protocol
|
||||
/// code consumes the endpoint and upgrades it into an EasyTier tunnel.
|
||||
pub enum ConnectedTransport<TcpSocket> {
|
||||
Tcp(TcpSocket),
|
||||
Udp(ConnectedUdpSession),
|
||||
ByteStream(ConnectedByteStream<TcpSocket>),
|
||||
}
|
||||
|
||||
async fn first_success<F, T>(mut futures: FuturesUnordered<F>) -> anyhow::Result<T>
|
||||
where
|
||||
F: Future<Output = anyhow::Result<T>> + Send,
|
||||
{
|
||||
let mut last_error = None;
|
||||
while let Some(result) = futures.next().await {
|
||||
match result {
|
||||
Ok(value) => return Ok(value),
|
||||
Err(error) => last_error = Some(error),
|
||||
}
|
||||
}
|
||||
Err(last_error.unwrap_or_else(|| anyhow::anyhow!("no transport candidates")))
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
|
||||
use futures::stream::FuturesUnordered;
|
||||
|
||||
use crate::socket::{
|
||||
IpVersion,
|
||||
tcp::{TcpBindOptions, TcpConnectOptions, TcpSocketPurpose, VirtualTcpSocketFactory},
|
||||
};
|
||||
|
||||
use super::first_success;
|
||||
|
||||
pub async fn connect_tcp<H>(
|
||||
host: Arc<H>,
|
||||
remote_addr: SocketAddr,
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
default_bind: TcpBindOptions,
|
||||
purpose: TcpSocketPurpose,
|
||||
) -> anyhow::Result<H::Socket>
|
||||
where
|
||||
H: VirtualTcpSocketFactory,
|
||||
{
|
||||
let ip_version = if remote_addr.is_ipv4() {
|
||||
IpVersion::V4
|
||||
} else {
|
||||
IpVersion::V6
|
||||
};
|
||||
let default_bind = default_bind.with_ip_version(ip_version);
|
||||
let futures = FuturesUnordered::new();
|
||||
if bind_addrs.is_empty() {
|
||||
futures.push(
|
||||
host.connect_tcp(
|
||||
TcpConnectOptions::direct_connect(remote_addr)
|
||||
.with_purpose(purpose)
|
||||
.with_bind(default_bind),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
for bind_addr in bind_addrs {
|
||||
let bind = default_bind
|
||||
.clone()
|
||||
.with_local_addr(Some(bind_addr))
|
||||
.with_only_v6(true);
|
||||
futures.push(
|
||||
host.connect_tcp(
|
||||
TcpConnectOptions::direct_connect(remote_addr)
|
||||
.with_purpose(purpose)
|
||||
.with_bind(bind),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
first_success(futures).await
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use std::{net::SocketAddr, sync::Arc};
|
||||
|
||||
use futures::stream::FuturesUnordered;
|
||||
|
||||
use crate::socket::{
|
||||
IpVersion,
|
||||
udp::{
|
||||
UdpBindOptions, UdpSession, UdpSessionLayer, UdpSessionProtocol, VirtualUdpSocketFactory,
|
||||
},
|
||||
};
|
||||
|
||||
use super::first_success;
|
||||
|
||||
pub struct ConnectedUdpSession {
|
||||
session: UdpSession,
|
||||
keep_alive: Box<dyn Send + Sync>,
|
||||
}
|
||||
|
||||
impl ConnectedUdpSession {
|
||||
pub fn new<T>(session: UdpSession, keep_alive: T) -> Self
|
||||
where
|
||||
T: Send + Sync + 'static,
|
||||
{
|
||||
Self {
|
||||
session,
|
||||
keep_alive: Box::new(keep_alive),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn session(&self) -> &UdpSession {
|
||||
&self.session
|
||||
}
|
||||
|
||||
pub fn into_parts(self) -> (UdpSession, Box<dyn Send + Sync>) {
|
||||
(self.session, self.keep_alive)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum UdpSessionMode {
|
||||
EasyTierMux,
|
||||
Classified(UdpSessionProtocol),
|
||||
}
|
||||
|
||||
pub async fn connect_udp<H>(
|
||||
host: Arc<H>,
|
||||
remote_addr: SocketAddr,
|
||||
bind_addrs: Vec<SocketAddr>,
|
||||
default_bind: UdpBindOptions,
|
||||
mode: UdpSessionMode,
|
||||
) -> anyhow::Result<ConnectedUdpSession>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
let ip_version = if remote_addr.is_ipv4() {
|
||||
IpVersion::V4
|
||||
} else {
|
||||
IpVersion::V6
|
||||
};
|
||||
let default_bind = default_bind.with_ip_version(ip_version);
|
||||
let futures = FuturesUnordered::new();
|
||||
if bind_addrs.is_empty() {
|
||||
let local_addr = if remote_addr.is_ipv4() {
|
||||
"0.0.0.0:0".parse().expect("static IPv4 bind address")
|
||||
} else {
|
||||
"[::]:0".parse().expect("static IPv6 bind address")
|
||||
};
|
||||
let bind = default_bind
|
||||
.with_local_addr(Some(local_addr))
|
||||
.with_only_v6(true);
|
||||
futures.push(bind_and_connect(host.clone(), bind, remote_addr, mode));
|
||||
} else {
|
||||
for bind_addr in bind_addrs {
|
||||
let bind = default_bind
|
||||
.clone()
|
||||
.with_local_addr(Some(bind_addr))
|
||||
.with_only_v6(true);
|
||||
futures.push(bind_and_connect(host.clone(), bind, remote_addr, mode));
|
||||
}
|
||||
}
|
||||
first_success(futures).await
|
||||
}
|
||||
|
||||
async fn bind_and_connect<H>(
|
||||
host: Arc<H>,
|
||||
bind: UdpBindOptions,
|
||||
remote_addr: SocketAddr,
|
||||
mode: UdpSessionMode,
|
||||
) -> anyhow::Result<ConnectedUdpSession>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
let socket = host.bind_udp(bind).await?;
|
||||
let layer = Arc::new(UdpSessionLayer::new_with_stun_responder(socket, host));
|
||||
let session = match mode {
|
||||
UdpSessionMode::EasyTierMux => layer.connect(remote_addr).await?,
|
||||
UdpSessionMode::Classified(protocol) => {
|
||||
layer.open_classified_session(protocol, remote_addr)?
|
||||
}
|
||||
};
|
||||
Ok(ConnectedUdpSession::new(session, layer))
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use cidr::{Ipv4Cidr, Ipv6Inet};
|
||||
use url::Url;
|
||||
|
||||
use crate::{
|
||||
config::{PeerId, gateway::PortForwardConfig},
|
||||
socket::{IpVersion, ListenerConnectionCounter},
|
||||
};
|
||||
|
||||
/// Notifications emitted by the portable core runtime to its host.
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum CoreEvent {
|
||||
PeerAdded(PeerId),
|
||||
PeerRemoved(PeerId),
|
||||
PeerConnAdded(easytier_proto::core_peer::peer::PeerConnInfo),
|
||||
PeerConnRemoved(easytier_proto::core_peer::peer::PeerConnInfo),
|
||||
CredentialChanged,
|
||||
|
||||
ManualConnecting {
|
||||
url: Url,
|
||||
},
|
||||
ManualConnectError {
|
||||
url: Url,
|
||||
ip_version: IpVersion,
|
||||
error: String,
|
||||
},
|
||||
|
||||
ListenerPlanFailed {
|
||||
url: Url,
|
||||
error: String,
|
||||
},
|
||||
ListenerAdded {
|
||||
url: Url,
|
||||
connection_counter: Arc<dyn ListenerConnectionCounter>,
|
||||
},
|
||||
ListenerRemoved {
|
||||
url: Url,
|
||||
},
|
||||
ListenerAddFailed {
|
||||
url: Url,
|
||||
error: String,
|
||||
retry_count: usize,
|
||||
will_retry: bool,
|
||||
},
|
||||
ListenerAcceptFailed {
|
||||
url: Url,
|
||||
error: String,
|
||||
},
|
||||
ListenerSocketAccepted {
|
||||
url: Url,
|
||||
},
|
||||
ListenerAcceptedSocketHandleFailed {
|
||||
url: Url,
|
||||
error: String,
|
||||
},
|
||||
|
||||
TunnelAccepted {
|
||||
local_url: String,
|
||||
remote_url: String,
|
||||
},
|
||||
TunnelAdmissionFailed {
|
||||
local_url: String,
|
||||
remote_url: String,
|
||||
error: String,
|
||||
},
|
||||
UdpPortMappingEstablished {
|
||||
local_listener: Url,
|
||||
mapped_listener: Url,
|
||||
backend: String,
|
||||
},
|
||||
|
||||
ProxyCidrsUpdated {
|
||||
added: Vec<Ipv4Cidr>,
|
||||
removed: Vec<Ipv4Cidr>,
|
||||
},
|
||||
PublicIpv6LeaseChanged {
|
||||
old: Option<Ipv6Inet>,
|
||||
new: Option<Ipv6Inet>,
|
||||
},
|
||||
PublicIpv6RoutesChanged {
|
||||
added: Vec<Ipv6Inet>,
|
||||
removed: Vec<Ipv6Inet>,
|
||||
},
|
||||
|
||||
VpnPortalStarted(String),
|
||||
VpnPortalClientConnected {
|
||||
portal: String,
|
||||
client: String,
|
||||
},
|
||||
VpnPortalClientDisconnected {
|
||||
portal: String,
|
||||
client: String,
|
||||
},
|
||||
GatewayPortForwardAdded(PortForwardConfig),
|
||||
}
|
||||
|
||||
pub trait CoreEventSink: Send + Sync + 'static {
|
||||
fn emit(&self, event: CoreEvent);
|
||||
}
|
||||
|
||||
impl CoreEventSink for () {
|
||||
fn emit(&self, _event: CoreEvent) {}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
use std::{hash::Hash, time::Duration, time::Instant};
|
||||
|
||||
use dashmap::DashMap;
|
||||
|
||||
/// A thread-safe set whose entries expire after a per-insert TTL.
|
||||
///
|
||||
/// `contains` lazily removes expired entries, so periodic `cleanup` calls
|
||||
/// are only needed to reclaim memory for keys that stop being read.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExpiringSet<K>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
entries: DashMap<K, Instant>,
|
||||
}
|
||||
|
||||
impl<K> Default for ExpiringSet<K>
|
||||
where
|
||||
K: Eq + Hash,
|
||||
{
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
entries: DashMap::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K> ExpiringSet<K>
|
||||
where
|
||||
K: Eq + Hash + Clone,
|
||||
{
|
||||
pub fn insert(&self, key: K, ttl: Duration) {
|
||||
self.entries.insert(key, Instant::now() + ttl);
|
||||
}
|
||||
|
||||
pub fn contains(&self, key: &K) -> bool {
|
||||
match self
|
||||
.entries
|
||||
.remove_if(key, |_, expires_at| *expires_at <= Instant::now())
|
||||
{
|
||||
// Existed and expired: removed while holding the shard lock, so a
|
||||
// concurrent insert of the same key cannot be dropped by us.
|
||||
Some(_) => false,
|
||||
// Not removed: either absent, or still fresh.
|
||||
None => self.entries.contains_key(key),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn cleanup(&self) {
|
||||
let now = Instant::now();
|
||||
self.entries.retain(|_, expires_at| *expires_at > now);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::time::Duration;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn expired_entries_are_reported_absent() {
|
||||
let set: ExpiringSet<u32> = ExpiringSet::default();
|
||||
set.insert(1, Duration::ZERO);
|
||||
set.insert(2, Duration::from_secs(3600));
|
||||
assert!(!set.contains(&1));
|
||||
assert!(set.contains(&2));
|
||||
set.cleanup();
|
||||
assert!(!set.entries.contains_key(&1));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Infrastructure Modules with no domain dependency.
|
||||
//!
|
||||
//! Everything in `foundation` may be used by any layer, and nothing here may
|
||||
//! depend on a domain Module. See `CONTEXT.md` "Module layers".
|
||||
|
||||
pub mod expiring_set;
|
||||
#[cfg(any(
|
||||
feature = "proxy-smoltcp-stack",
|
||||
test,
|
||||
all(feature = "management-rpc", target_os = "wasi")
|
||||
))]
|
||||
pub(crate) mod operation_broker;
|
||||
pub mod stats;
|
||||
pub(crate) mod task;
|
||||
pub(crate) mod time;
|
||||
pub(crate) mod token_bucket;
|
||||
@@ -0,0 +1,503 @@
|
||||
//! Domain-neutral lifecycle and completion storage for externally submitted
|
||||
//! asynchronous operations.
|
||||
|
||||
use std::{
|
||||
collections::{HashMap, VecDeque},
|
||||
hash::Hash,
|
||||
};
|
||||
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[repr(transparent)]
|
||||
pub(crate) struct OperationId(u64);
|
||||
|
||||
impl OperationId {
|
||||
pub(crate) fn from_raw(value: u64) -> Option<Self> {
|
||||
(value != 0).then_some(Self(value))
|
||||
}
|
||||
|
||||
pub(crate) fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum AdmissionError {
|
||||
AtCapacity,
|
||||
IdExhausted,
|
||||
}
|
||||
|
||||
pub(crate) struct Admission {
|
||||
pub(crate) id: OperationId,
|
||||
pub(crate) cancellation: CancellationToken,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum AccessError {
|
||||
Missing,
|
||||
NotDrained,
|
||||
}
|
||||
|
||||
pub(crate) struct Completion<K, S> {
|
||||
pub(crate) operation_id: OperationId,
|
||||
pub(crate) kind: K,
|
||||
pub(crate) status: S,
|
||||
}
|
||||
|
||||
pub(crate) struct ReleasedOperation<M, O> {
|
||||
pub(crate) metadata: M,
|
||||
pub(crate) outcome: Option<O>,
|
||||
}
|
||||
|
||||
pub(crate) struct TakenOperation<M, T> {
|
||||
pub(crate) metadata: M,
|
||||
pub(crate) value: T,
|
||||
}
|
||||
|
||||
enum OperationState<O> {
|
||||
Pending,
|
||||
Queued(O),
|
||||
Drained(O),
|
||||
Discarding,
|
||||
}
|
||||
|
||||
struct Operation<K, O, M> {
|
||||
kind: K,
|
||||
metadata: Option<M>,
|
||||
cancellation: CancellationToken,
|
||||
state: OperationState<O>,
|
||||
}
|
||||
|
||||
pub(crate) struct OperationBroker<K, O, M> {
|
||||
max_operations: usize,
|
||||
next_operation_id: u64,
|
||||
operations: HashMap<OperationId, Operation<K, O, M>>,
|
||||
completions: VecDeque<OperationId>,
|
||||
wake_generation: u64,
|
||||
}
|
||||
|
||||
impl<K, O, M> OperationBroker<K, O, M>
|
||||
where
|
||||
K: Copy,
|
||||
{
|
||||
pub(crate) fn new(max_operations: usize) -> Self {
|
||||
Self {
|
||||
max_operations,
|
||||
next_operation_id: 1,
|
||||
operations: HashMap::new(),
|
||||
completions: VecDeque::new(),
|
||||
wake_generation: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn admit(&mut self, kind: K, metadata: M) -> Result<Admission, AdmissionError> {
|
||||
if self.operations.len() >= self.max_operations {
|
||||
return Err(AdmissionError::AtCapacity);
|
||||
}
|
||||
let id =
|
||||
OperationId::from_raw(self.next_operation_id).ok_or(AdmissionError::IdExhausted)?;
|
||||
self.next_operation_id = self
|
||||
.next_operation_id
|
||||
.checked_add(1)
|
||||
.ok_or(AdmissionError::IdExhausted)?;
|
||||
let cancellation = CancellationToken::new();
|
||||
let replaced = self.operations.insert(
|
||||
id,
|
||||
Operation {
|
||||
kind,
|
||||
metadata: Some(metadata),
|
||||
cancellation: cancellation.clone(),
|
||||
state: OperationState::Pending,
|
||||
},
|
||||
);
|
||||
debug_assert!(replaced.is_none());
|
||||
Ok(Admission { id, cancellation })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn len(&self) -> usize {
|
||||
self.operations.len()
|
||||
}
|
||||
|
||||
pub(crate) fn complete_with(
|
||||
&mut self,
|
||||
operation_id: OperationId,
|
||||
complete: impl FnOnce(K, &mut M) -> O,
|
||||
) -> bool {
|
||||
self.resolve_pending_with(operation_id, false, complete)
|
||||
}
|
||||
|
||||
pub(crate) fn cancel_with(
|
||||
&mut self,
|
||||
operation_id: OperationId,
|
||||
complete: impl FnOnce(K, &mut M) -> O,
|
||||
) -> bool {
|
||||
self.resolve_pending_with(operation_id, true, complete)
|
||||
}
|
||||
|
||||
fn resolve_pending_with(
|
||||
&mut self,
|
||||
operation_id: OperationId,
|
||||
cancel: bool,
|
||||
complete: impl FnOnce(K, &mut M) -> O,
|
||||
) -> bool {
|
||||
let Some(mut operation) = self.operations.remove(&operation_id) else {
|
||||
return false;
|
||||
};
|
||||
match operation.state {
|
||||
OperationState::Pending => {
|
||||
if cancel {
|
||||
operation.cancellation.cancel();
|
||||
}
|
||||
let outcome = complete(
|
||||
operation.kind,
|
||||
operation
|
||||
.metadata
|
||||
.as_mut()
|
||||
.expect("pending operation metadata is present"),
|
||||
);
|
||||
let notify = self.completions.is_empty();
|
||||
operation.state = OperationState::Queued(outcome);
|
||||
self.operations.insert(operation_id, operation);
|
||||
self.completions.push_back(operation_id);
|
||||
notify
|
||||
}
|
||||
OperationState::Discarding => {
|
||||
if cancel {
|
||||
self.operations.insert(operation_id, operation);
|
||||
}
|
||||
false
|
||||
}
|
||||
OperationState::Queued(_) | OperationState::Drained(_) => {
|
||||
self.operations.insert(operation_id, operation);
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn free(&mut self, operation_id: OperationId) -> Option<ReleasedOperation<M, O>> {
|
||||
let mut operation = self.operations.remove(&operation_id)?;
|
||||
let state = std::mem::replace(&mut operation.state, OperationState::Discarding);
|
||||
match state {
|
||||
OperationState::Pending => {
|
||||
operation.cancellation.cancel();
|
||||
let released = ReleasedOperation {
|
||||
metadata: operation
|
||||
.metadata
|
||||
.take()
|
||||
.expect("pending operation metadata is present"),
|
||||
outcome: None,
|
||||
};
|
||||
self.operations.insert(operation_id, operation);
|
||||
Some(released)
|
||||
}
|
||||
OperationState::Queued(outcome) => {
|
||||
self.completions
|
||||
.retain(|completion| *completion != operation_id);
|
||||
Some(ReleasedOperation {
|
||||
metadata: operation
|
||||
.metadata
|
||||
.take()
|
||||
.expect("queued operation metadata is present"),
|
||||
outcome: Some(outcome),
|
||||
})
|
||||
}
|
||||
OperationState::Drained(outcome) => Some(ReleasedOperation {
|
||||
metadata: operation
|
||||
.metadata
|
||||
.take()
|
||||
.expect("drained operation metadata is present"),
|
||||
outcome: Some(outcome),
|
||||
}),
|
||||
OperationState::Discarding => {
|
||||
operation.state = OperationState::Discarding;
|
||||
self.operations.insert(operation_id, operation);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn drain<S>(
|
||||
&mut self,
|
||||
max_count: usize,
|
||||
mut status: impl FnMut(&O) -> S,
|
||||
) -> Vec<Completion<K, S>> {
|
||||
let mut completions = Vec::with_capacity(max_count.min(self.completions.len()));
|
||||
while completions.len() < max_count {
|
||||
let Some(operation_id) = self.completions.pop_front() else {
|
||||
break;
|
||||
};
|
||||
let Some(operation) = self.operations.get_mut(&operation_id) else {
|
||||
continue;
|
||||
};
|
||||
let old_state = std::mem::replace(&mut operation.state, OperationState::Discarding);
|
||||
match old_state {
|
||||
OperationState::Queued(outcome) => {
|
||||
completions.push(Completion {
|
||||
operation_id,
|
||||
kind: operation.kind,
|
||||
status: status(&outcome),
|
||||
});
|
||||
operation.state = OperationState::Drained(outcome);
|
||||
}
|
||||
other => operation.state = other,
|
||||
}
|
||||
}
|
||||
completions
|
||||
}
|
||||
|
||||
pub(crate) fn has_completions(&self) -> bool {
|
||||
!self.completions.is_empty()
|
||||
}
|
||||
|
||||
pub(crate) fn pending_kind(&self, operation_id: OperationId) -> Option<K> {
|
||||
self.operations.get(&operation_id).and_then(|operation| {
|
||||
matches!(operation.state, OperationState::Pending).then_some(operation.kind)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn request_cancellation(&self, operation_id: OperationId) -> bool {
|
||||
let Some(operation) = self.operations.get(&operation_id) else {
|
||||
return false;
|
||||
};
|
||||
if !matches!(operation.state, OperationState::Pending) {
|
||||
return false;
|
||||
}
|
||||
operation.cancellation.cancel();
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn with_drained<T>(
|
||||
&self,
|
||||
operation_id: OperationId,
|
||||
inspect: impl FnOnce(K, &M, &O) -> T,
|
||||
) -> Result<T, AccessError> {
|
||||
let operation = self
|
||||
.operations
|
||||
.get(&operation_id)
|
||||
.ok_or(AccessError::Missing)?;
|
||||
match &operation.state {
|
||||
OperationState::Drained(outcome) => Ok(inspect(
|
||||
operation.kind,
|
||||
operation
|
||||
.metadata
|
||||
.as_ref()
|
||||
.expect("drained operation metadata is present"),
|
||||
outcome,
|
||||
)),
|
||||
OperationState::Pending | OperationState::Queued(_) | OperationState::Discarding => {
|
||||
Err(AccessError::NotDrained)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn take_with<T>(
|
||||
&mut self,
|
||||
operation_id: OperationId,
|
||||
take: impl FnOnce(&O) -> Option<T>,
|
||||
) -> Result<Option<TakenOperation<M, T>>, AccessError> {
|
||||
let Some(mut operation) = self.operations.remove(&operation_id) else {
|
||||
return Err(AccessError::Missing);
|
||||
};
|
||||
let old_state = std::mem::replace(&mut operation.state, OperationState::Discarding);
|
||||
let outcome = match old_state {
|
||||
OperationState::Drained(outcome) => outcome,
|
||||
other => {
|
||||
operation.state = other;
|
||||
self.operations.insert(operation_id, operation);
|
||||
return Err(AccessError::NotDrained);
|
||||
}
|
||||
};
|
||||
let Some(value) = take(&outcome) else {
|
||||
operation.state = OperationState::Drained(outcome);
|
||||
self.operations.insert(operation_id, operation);
|
||||
return Ok(None);
|
||||
};
|
||||
Ok(Some(TakenOperation {
|
||||
metadata: operation
|
||||
.metadata
|
||||
.take()
|
||||
.expect("drained operation metadata is present"),
|
||||
value,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(crate) fn pending_ids(&self) -> Vec<OperationId> {
|
||||
self.operations
|
||||
.iter()
|
||||
.filter_map(|(operation_id, operation)| {
|
||||
matches!(operation.state, OperationState::Pending).then_some(*operation_id)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn wake_generation(&self) -> u64 {
|
||||
self.wake_generation
|
||||
}
|
||||
|
||||
pub(crate) fn invalidate_waiters(&mut self) {
|
||||
self.wake_generation = self.wake_generation.wrapping_add(1);
|
||||
}
|
||||
|
||||
pub(crate) fn discard_all(&mut self) {
|
||||
for operation in self.operations.values() {
|
||||
operation.cancellation.cancel();
|
||||
}
|
||||
self.operations.clear();
|
||||
self.completions.clear();
|
||||
self.invalidate_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Kind {
|
||||
Read,
|
||||
Write,
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_is_drained_and_taken_once() {
|
||||
let mut broker = OperationBroker::new(4);
|
||||
let admission = broker.admit(Kind::Read, "metadata").unwrap();
|
||||
|
||||
assert!(broker.complete_with(admission.id, |_, _| Ok::<_, u8>(7)));
|
||||
let completions = broker.drain(4, |outcome| outcome.is_ok());
|
||||
assert_eq!(completions.len(), 1);
|
||||
assert_eq!(completions[0].operation_id, admission.id);
|
||||
assert_eq!(completions[0].kind, Kind::Read);
|
||||
assert!(completions[0].status);
|
||||
assert!(broker.drain(4, |_| true).is_empty());
|
||||
|
||||
assert!(
|
||||
broker
|
||||
.take_with(admission.id, |_| None::<u8>)
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
let taken = broker
|
||||
.take_with(admission.id, |outcome| outcome.as_ref().ok().copied())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(taken.metadata, "metadata");
|
||||
assert_eq!(taken.value, 7);
|
||||
assert!(matches!(
|
||||
broker.take_with(admission.id, |_| Some(())),
|
||||
Err(AccessError::Missing)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn free_pending_absorbs_late_completion() {
|
||||
let mut broker = OperationBroker::new(4);
|
||||
let admission = broker.admit(Kind::Write, 9).unwrap();
|
||||
|
||||
let released = broker.free(admission.id).unwrap();
|
||||
assert_eq!(released.metadata, 9);
|
||||
assert!(released.outcome.is_none());
|
||||
assert!(admission.cancellation.is_cancelled());
|
||||
assert!(!broker.complete_with(admission.id, |_, _| 3));
|
||||
|
||||
assert_eq!(broker.len(), 0);
|
||||
assert!(!broker.has_completions());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_and_completion_have_one_terminal_outcome() {
|
||||
let mut cancelled_first = OperationBroker::new(4);
|
||||
let cancelled = cancelled_first.admit(Kind::Read, ()).unwrap();
|
||||
assert!(cancelled_first.cancel_with(cancelled.id, |_, _| Err::<u8, _>("cancelled")));
|
||||
assert!(!cancelled_first.complete_with(cancelled.id, |_, _| Ok(1)));
|
||||
let completions = cancelled_first.drain(4, |outcome| outcome.is_ok());
|
||||
assert_eq!(completions.len(), 1);
|
||||
assert!(!completions[0].status);
|
||||
|
||||
let mut completed_first = OperationBroker::new(4);
|
||||
let completed = completed_first.admit(Kind::Read, ()).unwrap();
|
||||
assert!(completed_first.complete_with(completed.id, |_, _| Ok::<_, &str>(1)));
|
||||
assert!(!completed_first.cancel_with(completed.id, |_, _| Err("cancelled")));
|
||||
let completions = completed_first.drain(4, |outcome| outcome.is_ok());
|
||||
assert_eq!(completions.len(), 1);
|
||||
assert!(completions[0].status);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn requested_cancellation_stays_pending_until_operation_completes() {
|
||||
let mut broker = OperationBroker::new(4);
|
||||
let admission = broker.admit(Kind::Write, "metadata").unwrap();
|
||||
|
||||
assert_eq!(broker.pending_kind(admission.id), Some(Kind::Write));
|
||||
assert!(broker.request_cancellation(admission.id));
|
||||
assert!(admission.cancellation.is_cancelled());
|
||||
assert!(!broker.has_completions());
|
||||
|
||||
assert!(broker.complete_with(admission.id, |_, _| Ok::<_, &'static str>(7)));
|
||||
assert!(broker.has_completions());
|
||||
assert_eq!(broker.pending_kind(admission.id), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn completion_notification_is_an_empty_to_nonempty_edge() {
|
||||
let mut broker = OperationBroker::new(4);
|
||||
let first = broker.admit(Kind::Read, ()).unwrap();
|
||||
let second = broker.admit(Kind::Write, ()).unwrap();
|
||||
|
||||
assert!(broker.complete_with(first.id, |_, _| ()));
|
||||
assert!(!broker.complete_with(second.id, |_, _| ()));
|
||||
assert_eq!(broker.drain(2, |_| ()).len(), 2);
|
||||
assert!(!broker.has_completions());
|
||||
|
||||
let third = broker.admit(Kind::Read, ()).unwrap();
|
||||
assert!(broker.complete_with(third.id, |_, _| ()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn admission_limit_counts_discarding_tombstones() {
|
||||
let mut broker = OperationBroker::new(1);
|
||||
let admission = broker.admit(Kind::Read, ()).unwrap();
|
||||
broker.free(admission.id);
|
||||
|
||||
assert!(matches!(
|
||||
broker.admit(Kind::Write, ()),
|
||||
Err(AdmissionError::AtCapacity)
|
||||
));
|
||||
|
||||
broker.complete_with(admission.id, |_, _| ());
|
||||
broker.admit(Kind::Write, ()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cancellation_keeps_discarding_tombstone_until_completion() {
|
||||
let mut broker: OperationBroker<Kind, (), ()> = OperationBroker::new(1);
|
||||
let admission = broker.admit(Kind::Read, ()).unwrap();
|
||||
broker.free(admission.id);
|
||||
|
||||
assert!(!broker.cancel_with(admission.id, |_, _| ()));
|
||||
assert_eq!(broker.len(), 1);
|
||||
assert!(matches!(
|
||||
broker.admit(Kind::Write, ()),
|
||||
Err(AdmissionError::AtCapacity)
|
||||
));
|
||||
|
||||
assert!(!broker.complete_with(admission.id, |_, _| ()));
|
||||
assert_eq!(broker.len(), 0);
|
||||
broker.admit(Kind::Write, ()).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn discard_invalidates_waiters_and_cancels_operations() {
|
||||
let mut broker: OperationBroker<Kind, (), ()> = OperationBroker::new(1);
|
||||
let admission = broker.admit(Kind::Read, ()).unwrap();
|
||||
let generation = broker.wake_generation();
|
||||
|
||||
broker.discard_all();
|
||||
|
||||
assert!(admission.cancellation.is_cancelled());
|
||||
assert_ne!(broker.wake_generation(), generation);
|
||||
assert_eq!(broker.len(), 0);
|
||||
}
|
||||
}
|
||||
+1332
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,323 @@
|
||||
use std::{
|
||||
result::Result,
|
||||
sync::{Arc, Mutex, Weak, atomic::Ordering},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use anyhow::Error;
|
||||
use async_trait::async_trait;
|
||||
use atomic_shim::AtomicU64;
|
||||
use dashmap::DashMap;
|
||||
use tokio::{
|
||||
select,
|
||||
sync::Notify,
|
||||
task::{JoinHandle, JoinSet},
|
||||
};
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
pub(crate) async fn reap_joinset_background<T>(tasks: Weak<Mutex<JoinSet<T>>>, origin: &'static str)
|
||||
where
|
||||
T: Send + 'static,
|
||||
{
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(1)).await;
|
||||
let Some(tasks) = tasks.upgrade() else {
|
||||
break;
|
||||
};
|
||||
while tasks.lock().unwrap().try_join_next().is_some() {}
|
||||
}
|
||||
tracing::debug!(origin, "joinset task reaper exited");
|
||||
}
|
||||
|
||||
pub struct ExternalTaskSignal {
|
||||
version: AtomicU64,
|
||||
notify: Notify,
|
||||
}
|
||||
|
||||
impl Default for ExternalTaskSignal {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl ExternalTaskSignal {
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
version: AtomicU64::new(0),
|
||||
notify: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn notify(&self) {
|
||||
self.version.fetch_add(1, Ordering::Relaxed);
|
||||
self.notify.notify_waiters();
|
||||
}
|
||||
|
||||
pub fn version(&self) -> u64 {
|
||||
self.version.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
pub fn notified(&self) -> impl std::future::Future<Output = ()> + '_ {
|
||||
self.notify.notified()
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait PeerTaskLauncher: Send + Sync + Clone + 'static {
|
||||
type CollectPeerItem;
|
||||
type TaskRet;
|
||||
|
||||
async fn collect_peers_need_task(&self) -> Vec<Self::CollectPeerItem>;
|
||||
async fn launch_task(
|
||||
&self,
|
||||
item: Self::CollectPeerItem,
|
||||
) -> JoinHandle<Result<Self::TaskRet, Error>>;
|
||||
|
||||
async fn all_task_done(&self) {}
|
||||
|
||||
fn loop_interval_ms(&self) -> u64 {
|
||||
5000
|
||||
}
|
||||
}
|
||||
|
||||
type PeerTaskMap<Launcher> = DashMap<
|
||||
<Launcher as PeerTaskLauncher>::CollectPeerItem,
|
||||
AbortOnDropHandle<Result<<Launcher as PeerTaskLauncher>::TaskRet, Error>>,
|
||||
>;
|
||||
|
||||
pub struct PeerTaskManager<Launcher: PeerTaskLauncher> {
|
||||
launcher: Launcher,
|
||||
main_loop_task: Mutex<Option<AbortOnDropHandle<()>>>,
|
||||
peer_tasks: Arc<PeerTaskMap<Launcher>>,
|
||||
run_signal: Arc<Notify>,
|
||||
external_signal: Option<Arc<ExternalTaskSignal>>,
|
||||
}
|
||||
|
||||
impl<C, T, L> PeerTaskManager<L>
|
||||
where
|
||||
C: std::fmt::Debug + Send + Sync + Clone + core::hash::Hash + Eq + 'static,
|
||||
T: Send + 'static,
|
||||
L: PeerTaskLauncher<CollectPeerItem = C, TaskRet = T> + 'static,
|
||||
{
|
||||
pub fn new_with_external_signal(
|
||||
launcher: L,
|
||||
external_signal: Option<Arc<ExternalTaskSignal>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
launcher,
|
||||
main_loop_task: Mutex::new(None),
|
||||
peer_tasks: Arc::new(DashMap::new()),
|
||||
run_signal: Arc::new(Notify::new()),
|
||||
external_signal,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&self) {
|
||||
let mut task_slot = self.main_loop_task.lock().unwrap();
|
||||
if task_slot.as_ref().is_some_and(|task| !task.is_finished()) {
|
||||
return;
|
||||
}
|
||||
let task = AbortOnDropHandle::new(tokio::spawn(Self::main_loop(
|
||||
self.launcher.clone(),
|
||||
self.run_signal.clone(),
|
||||
self.external_signal.clone(),
|
||||
self.peer_tasks.clone(),
|
||||
)));
|
||||
task_slot.replace(task);
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
let task = self.main_loop_task.lock().unwrap().take();
|
||||
if let Some(task) = task {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
let keys = self
|
||||
.peer_tasks
|
||||
.iter()
|
||||
.map(|entry| entry.key().clone())
|
||||
.collect::<Vec<_>>();
|
||||
for key in keys {
|
||||
if let Some((_, task)) = self.peer_tasks.remove(&key) {
|
||||
task.abort();
|
||||
let _ = task.await;
|
||||
}
|
||||
}
|
||||
self.peer_tasks.shrink_to_fit();
|
||||
self.launcher.all_task_done().await;
|
||||
}
|
||||
|
||||
async fn main_loop(
|
||||
launcher: L,
|
||||
signal: Arc<Notify>,
|
||||
external_signal: Option<Arc<ExternalTaskSignal>>,
|
||||
peer_task_map: Arc<DashMap<C, AbortOnDropHandle<Result<T, Error>>>>,
|
||||
) {
|
||||
let mut external_signal_version = external_signal.as_ref().map(|signal| signal.version());
|
||||
|
||||
loop {
|
||||
let peers_to_connect = launcher.collect_peers_need_task().await;
|
||||
|
||||
let mut to_remove = vec![];
|
||||
for item in peer_task_map.iter() {
|
||||
if !peers_to_connect.contains(item.key()) || item.value().is_finished() {
|
||||
to_remove.push(item.key().clone());
|
||||
}
|
||||
}
|
||||
|
||||
for key in to_remove {
|
||||
if let Some((_, task)) = peer_task_map.remove(&key) {
|
||||
task.abort();
|
||||
match task.await {
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(task_ret)) => {
|
||||
tracing::error!(
|
||||
target: "easytier_core::peers::peer_task",
|
||||
?task_ret,
|
||||
"hole punching task failed"
|
||||
);
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::error!(
|
||||
target: "easytier_core::peers::peer_task",
|
||||
?e,
|
||||
"hole punching task aborted"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
peer_task_map.shrink_to_fit();
|
||||
}
|
||||
|
||||
if !peers_to_connect.is_empty() {
|
||||
for item in peers_to_connect {
|
||||
if peer_task_map.contains_key(&item) {
|
||||
continue;
|
||||
}
|
||||
|
||||
tracing::debug!(
|
||||
target: "easytier_core::peers::peer_task",
|
||||
?item,
|
||||
"launch hole punching task"
|
||||
);
|
||||
peer_task_map.insert(
|
||||
item.clone(),
|
||||
AbortOnDropHandle::new(launcher.launch_task(item).await),
|
||||
);
|
||||
}
|
||||
} else if peer_task_map.is_empty() {
|
||||
launcher.all_task_done().await;
|
||||
}
|
||||
|
||||
if let Some(external_signal) = external_signal.as_ref() {
|
||||
let notified = external_signal.notified();
|
||||
tokio::pin!(notified);
|
||||
let cur_version = external_signal.version();
|
||||
if external_signal_version != Some(cur_version) {
|
||||
external_signal_version = Some(cur_version);
|
||||
continue;
|
||||
}
|
||||
|
||||
select! {
|
||||
_ = crate::foundation::time::sleep(std::time::Duration::from_millis(
|
||||
launcher.loop_interval_ms(),
|
||||
)) => {},
|
||||
_ = signal.notified() => {},
|
||||
_ = &mut notified => {
|
||||
external_signal_version = Some(external_signal.version());
|
||||
}
|
||||
}
|
||||
} else {
|
||||
select! {
|
||||
_ = crate::foundation::time::sleep(std::time::Duration::from_millis(
|
||||
launcher.loop_interval_ms(),
|
||||
)) => {},
|
||||
_ = signal.notified() => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct TestLauncher {
|
||||
active_tasks: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
struct ActiveTaskGuard(Arc<AtomicUsize>);
|
||||
|
||||
impl Drop for ActiveTaskGuard {
|
||||
fn drop(&mut self) {
|
||||
self.0.fetch_sub(1, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl PeerTaskLauncher for TestLauncher {
|
||||
type CollectPeerItem = u8;
|
||||
type TaskRet = ();
|
||||
|
||||
async fn collect_peers_need_task(&self) -> Vec<u8> {
|
||||
vec![1]
|
||||
}
|
||||
|
||||
async fn launch_task(&self, _item: u8) -> JoinHandle<Result<(), Error>> {
|
||||
let active_tasks = self.active_tasks.clone();
|
||||
tokio::spawn(async move {
|
||||
active_tasks.fetch_add(1, Ordering::SeqCst);
|
||||
let _guard = ActiveTaskGuard(active_tasks);
|
||||
std::future::pending::<()>().await;
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn joinset_reaper_does_not_keep_task_set_alive() {
|
||||
let tasks = Arc::new(Mutex::new(JoinSet::new()));
|
||||
let weak_tasks = Arc::downgrade(&tasks);
|
||||
tasks
|
||||
.lock()
|
||||
.unwrap()
|
||||
.spawn(reap_joinset_background(weak_tasks.clone(), "test"));
|
||||
|
||||
drop(tasks);
|
||||
|
||||
assert!(weak_tasks.upgrade().is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn peer_task_manager_is_cold_and_joins_children_on_stop() {
|
||||
let active_tasks = Arc::new(AtomicUsize::new(0));
|
||||
let manager = PeerTaskManager::new_with_external_signal(
|
||||
TestLauncher {
|
||||
active_tasks: active_tasks.clone(),
|
||||
},
|
||||
None,
|
||||
);
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(active_tasks.load(Ordering::SeqCst), 0);
|
||||
|
||||
manager.start();
|
||||
crate::foundation::time::timeout(std::time::Duration::from_secs(1), async {
|
||||
while active_tasks.load(Ordering::SeqCst) == 0 {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
manager.stop().await;
|
||||
assert_eq!(active_tasks.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! Tokio time facade.
|
||||
//!
|
||||
//! Native builds use Tokio directly. WASI builds use the deadline-tracking
|
||||
//! implementation in [`crate::wasi::time`] so an external runtime can drive
|
||||
//! the guest without polling.
|
||||
|
||||
#[cfg(not(any(test, target_os = "wasi")))]
|
||||
pub use tokio::time::{Duration, Instant, Interval, error, interval, sleep, sleep_until, timeout};
|
||||
|
||||
#[cfg(any(test, target_os = "wasi"))]
|
||||
pub use crate::wasi::time::{
|
||||
Duration, Instant, Interval, error, interval, sleep, sleep_until, timeout,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "wasi")]
|
||||
pub(crate) use crate::wasi::time::{clear_domain, enter_domain, next_deadline_millis};
|
||||
@@ -0,0 +1,510 @@
|
||||
use dashmap::DashMap;
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::{
|
||||
Arc, Mutex as StdMutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::foundation::time;
|
||||
|
||||
pub(crate) trait ByteLimiter: Send + Sync {
|
||||
fn try_consume(&self, bytes: u64) -> bool;
|
||||
}
|
||||
|
||||
impl ByteLimiter for () {
|
||||
fn try_consume(&self, _bytes: u64) -> bool {
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) type ArcByteLimiter = Arc<dyn ByteLimiter>;
|
||||
|
||||
const MIN_FILL_RATE: u64 = 8_196;
|
||||
const NANOS_PER_SECOND: u128 = 1_000_000_000;
|
||||
|
||||
/// Token Bucket rate limiter with on-demand refill.
|
||||
pub struct TokenBucket {
|
||||
state: Mutex<BucketState>,
|
||||
config: BucketConfig,
|
||||
stop_notifier: Notify,
|
||||
stopped: AtomicBool,
|
||||
}
|
||||
|
||||
struct BucketState {
|
||||
available_tokens: u64,
|
||||
last_refill: Instant,
|
||||
refill_remainder: u64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct BucketConfig {
|
||||
capacity: u64,
|
||||
fill_rate: u64,
|
||||
}
|
||||
|
||||
impl BucketConfig {
|
||||
pub fn new(capacity: u64, fill_rate: u64) -> Self {
|
||||
Self {
|
||||
capacity,
|
||||
fill_rate,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_default_capacity(fill_rate: u64) -> Self {
|
||||
let fill_rate = fill_rate.max(MIN_FILL_RATE);
|
||||
Self::new(fill_rate, fill_rate)
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenBucket {
|
||||
pub fn new(capacity: u64, bps: u64) -> Arc<Self> {
|
||||
Self::new_from_cfg(BucketConfig::new(capacity, bps))
|
||||
}
|
||||
|
||||
/// Creates a new Token Bucket rate limiter
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `capacity` - Bucket capacity in bytes
|
||||
/// * `bps` - Bandwidth limit in bytes per second
|
||||
pub fn new_from_cfg(mut config: BucketConfig) -> Arc<Self> {
|
||||
config.capacity = config.capacity.max(1);
|
||||
config.fill_rate = config.fill_rate.max(1);
|
||||
|
||||
Arc::new(Self {
|
||||
state: Mutex::new(BucketState {
|
||||
available_tokens: config.capacity,
|
||||
last_refill: Instant::now(),
|
||||
refill_remainder: 0,
|
||||
}),
|
||||
config,
|
||||
stop_notifier: Notify::new(),
|
||||
stopped: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
/// Refill tokens based on elapsed time since last refill.
|
||||
/// Called while holding the bucket state lock.
|
||||
fn refill(&self, state: &mut BucketState, now: Instant) {
|
||||
let elapsed_nanos = now.saturating_duration_since(state.last_refill).as_nanos();
|
||||
if elapsed_nanos == 0 {
|
||||
return;
|
||||
}
|
||||
|
||||
state.last_refill = now;
|
||||
if state.available_tokens == self.config.capacity {
|
||||
state.refill_remainder = 0;
|
||||
return;
|
||||
}
|
||||
|
||||
let generated = (self.config.fill_rate as u128)
|
||||
.saturating_mul(elapsed_nanos)
|
||||
.saturating_add(state.refill_remainder as u128);
|
||||
let tokens_to_add = generated / NANOS_PER_SECOND;
|
||||
let refill_remainder = generated % NANOS_PER_SECOND;
|
||||
let available_capacity = self.config.capacity - state.available_tokens;
|
||||
|
||||
if tokens_to_add >= available_capacity as u128 {
|
||||
state.available_tokens = self.config.capacity;
|
||||
state.refill_remainder = 0;
|
||||
} else {
|
||||
state.available_tokens += tokens_to_add as u64;
|
||||
state.refill_remainder = refill_remainder as u64;
|
||||
}
|
||||
}
|
||||
|
||||
/// Attempt to consume tokens without blocking
|
||||
///
|
||||
/// Requests larger than the bucket capacity are charged one full
|
||||
/// bucket instead of being rejected, so oversized packets can still
|
||||
/// pass whenever the bucket holds a full burst; traffic consisting
|
||||
/// only of oversized packets can therefore sustain up to
|
||||
/// packet-size/capacity times the nominal rate.
|
||||
///
|
||||
/// # Returns
|
||||
/// `true` if tokens were consumed, `false` if insufficient tokens
|
||||
pub fn try_consume(&self, tokens: u64) -> bool {
|
||||
if self.stopped.load(Ordering::Acquire) {
|
||||
return true;
|
||||
}
|
||||
let tokens = tokens.min(self.config.capacity);
|
||||
|
||||
let mut state = self.state.lock();
|
||||
self.refill(&mut state, Instant::now());
|
||||
if state.available_tokens < tokens {
|
||||
return false;
|
||||
}
|
||||
|
||||
state.available_tokens -= tokens;
|
||||
true
|
||||
}
|
||||
|
||||
/// Consume tokens, sleeping until they become available.
|
||||
pub async fn consume(&self, tokens: u64) {
|
||||
let mut remaining = tokens;
|
||||
while remaining > 0 {
|
||||
if self.stopped.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
let chunk = remaining.min(self.config.capacity);
|
||||
self.consume_chunk(chunk).await;
|
||||
remaining -= chunk;
|
||||
}
|
||||
}
|
||||
|
||||
async fn consume_chunk(&self, tokens: u64) {
|
||||
loop {
|
||||
let stopped = self.stop_notifier.notified();
|
||||
if self.stopped.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
|
||||
let sleep_dur = {
|
||||
let mut state = self.state.lock();
|
||||
self.refill(&mut state, Instant::now());
|
||||
if state.available_tokens >= tokens {
|
||||
state.available_tokens -= tokens;
|
||||
return;
|
||||
}
|
||||
|
||||
let deficit = tokens - state.available_tokens;
|
||||
let required = deficit as u128 * NANOS_PER_SECOND;
|
||||
let remaining = required - state.refill_remainder as u128;
|
||||
let sleep_nanos = remaining
|
||||
.div_ceil(self.config.fill_rate as u128)
|
||||
.min(u64::MAX as u128) as u64;
|
||||
Duration::from_nanos(sleep_nanos.max(1_000_000))
|
||||
};
|
||||
|
||||
tokio::select! {
|
||||
_ = time::sleep(sleep_dur) => {}
|
||||
_ = stopped => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn stop(&self) {
|
||||
self.stopped.store(true, Ordering::Release);
|
||||
self.stop_notifier.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
impl ByteLimiter for TokenBucket {
|
||||
fn try_consume(&self, bytes: u64) -> bool {
|
||||
TokenBucket::try_consume(self, bytes)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct TokenBucketManager {
|
||||
buckets: Arc<DashMap<String, Arc<TokenBucket>>>,
|
||||
retain_task: StdMutex<Option<AbortOnDropHandle<()>>>,
|
||||
}
|
||||
|
||||
impl Default for TokenBucketManager {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl TokenBucketManager {
|
||||
/// Creates a new TokenBucketManager
|
||||
pub fn new() -> Self {
|
||||
let buckets = Arc::new(DashMap::new());
|
||||
|
||||
let buckets_clone = buckets.clone();
|
||||
let retain_task = tokio::spawn(async move {
|
||||
loop {
|
||||
// Retain only buckets that are still in use
|
||||
let old_len = buckets_clone.len();
|
||||
buckets_clone.retain(|_, bucket| Arc::<TokenBucket>::strong_count(bucket) > 1);
|
||||
buckets_clone.shrink_to_fit();
|
||||
// Sleep for a while before next retention check
|
||||
time::sleep(Duration::from_secs(5)).await;
|
||||
tracing::info!(
|
||||
"Retained buckets: {} ({} dropped)",
|
||||
buckets_clone.len(),
|
||||
old_len.saturating_sub(buckets_clone.len())
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
Self {
|
||||
buckets,
|
||||
retain_task: StdMutex::new(Some(AbortOnDropHandle::new(retain_task))),
|
||||
}
|
||||
}
|
||||
|
||||
/// Get or create a token bucket for the given key
|
||||
pub fn get_or_create(&self, key: &str, cfg: BucketConfig) -> Arc<TokenBucket> {
|
||||
self.buckets
|
||||
.entry(key.to_string())
|
||||
.or_insert_with(|| TokenBucket::new_from_cfg(cfg))
|
||||
.clone()
|
||||
}
|
||||
|
||||
pub async fn stop(&self) {
|
||||
let retain_task = self.retain_task.lock().unwrap().take();
|
||||
if let Some(retain_task) = retain_task {
|
||||
retain_task.abort();
|
||||
let _ = retain_task.await;
|
||||
}
|
||||
let buckets = self
|
||||
.buckets
|
||||
.iter()
|
||||
.map(|entry| entry.value().clone())
|
||||
.collect::<Vec<_>>();
|
||||
for bucket in buckets {
|
||||
bucket.stop().await;
|
||||
}
|
||||
self.buckets.clear();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::time::{Duration, sleep, timeout};
|
||||
|
||||
#[test]
|
||||
fn bucket_config_uses_one_second_default_capacity() {
|
||||
let config = BucketConfig::with_default_capacity(100_000);
|
||||
|
||||
assert_eq!(config.capacity, 100_000);
|
||||
assert_eq!(config.fill_rate, 100_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_config_default_capacity_fits_regular_packets() {
|
||||
let config = BucketConfig::with_default_capacity(8_196);
|
||||
|
||||
assert_eq!(config.capacity, 8_196);
|
||||
assert_eq!(config.fill_rate, 8_196);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bucket_config_preserves_explicit_capacity() {
|
||||
let config = BucketConfig::new(200_000, 100_000);
|
||||
|
||||
assert_eq!(config.capacity, 200_000);
|
||||
assert_eq!(config.fill_rate, 100_000);
|
||||
}
|
||||
|
||||
/// Test initial state after creation
|
||||
#[tokio::test]
|
||||
async fn test_initial_state() {
|
||||
let bucket = TokenBucket::new(1000, 1000);
|
||||
|
||||
// Should have full capacity initially
|
||||
assert!(bucket.try_consume(1000));
|
||||
assert!(!bucket.try_consume(1)); // Should be empty now
|
||||
}
|
||||
|
||||
/// Test token consumption behavior
|
||||
#[tokio::test]
|
||||
async fn test_consumption() {
|
||||
let bucket = TokenBucket::new(1500, 1000);
|
||||
|
||||
// First packet should succeed
|
||||
assert!(bucket.try_consume(1000));
|
||||
|
||||
// Second packet should fail (only 500 left)
|
||||
assert!(!bucket.try_consume(600));
|
||||
|
||||
// Should be able to take remaining tokens
|
||||
assert!(bucket.try_consume(500));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_releases_waiting_consumers() {
|
||||
let bucket = TokenBucket::new(1, 1);
|
||||
assert!(bucket.try_consume(1));
|
||||
let waiting = tokio::spawn({
|
||||
let bucket = bucket.clone();
|
||||
async move { bucket.consume(1).await }
|
||||
});
|
||||
tokio::task::yield_now().await;
|
||||
assert!(!waiting.is_finished());
|
||||
|
||||
bucket.stop().await;
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(1), waiting)
|
||||
.await
|
||||
.expect("stopped limiter should release consumers")
|
||||
.unwrap();
|
||||
assert!(bucket.try_consume(u64::MAX));
|
||||
}
|
||||
|
||||
/// Test lazy refill functionality
|
||||
#[tokio::test]
|
||||
async fn test_refill() {
|
||||
let bucket = TokenBucket::new(1_000_000, 10_000);
|
||||
|
||||
// Drain the bucket
|
||||
assert!(bucket.try_consume(1_000_000));
|
||||
|
||||
// Wait for time to pass (tokens accumulate lazily on next consume)
|
||||
sleep(Duration::from_millis(25)).await;
|
||||
let tokens = {
|
||||
let mut state = bucket.state.lock();
|
||||
bucket.refill(&mut state, Instant::now());
|
||||
state.available_tokens
|
||||
};
|
||||
assert!(tokens > 0, "Expected some refilled tokens");
|
||||
assert!(
|
||||
tokens < bucket.config.capacity,
|
||||
"Bucket unexpectedly refilled to capacity: {}",
|
||||
tokens
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_refill_preserves_fractional_tokens() {
|
||||
let bucket = TokenBucket::new(100, 100);
|
||||
let start = Instant::now();
|
||||
let mut state = bucket.state.lock();
|
||||
state.available_tokens = 0;
|
||||
state.last_refill = start;
|
||||
state.refill_remainder = 0;
|
||||
|
||||
for step in 1..=10 {
|
||||
bucket.refill(&mut state, start + Duration::from_millis(step * 15));
|
||||
}
|
||||
|
||||
assert_eq!(state.available_tokens, 15);
|
||||
assert_eq!(state.refill_remainder, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_refill_preserves_submicrosecond_time() {
|
||||
let bucket = TokenBucket::new(100, 1_000_000);
|
||||
let start = Instant::now();
|
||||
let mut state = bucket.state.lock();
|
||||
state.available_tokens = 0;
|
||||
state.last_refill = start;
|
||||
state.refill_remainder = 0;
|
||||
|
||||
for step in 1..=10 {
|
||||
bucket.refill(&mut state, start + Duration::from_nanos(step * 1_500));
|
||||
}
|
||||
|
||||
assert_eq!(state.available_tokens, 15);
|
||||
assert_eq!(state.refill_remainder, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_refill_discards_excess_credit_at_capacity() {
|
||||
let bucket = TokenBucket::new(10, 10);
|
||||
let start = Instant::now();
|
||||
let mut state = bucket.state.lock();
|
||||
state.available_tokens = 0;
|
||||
state.last_refill = start;
|
||||
|
||||
let refill_time = start + Duration::from_secs(2);
|
||||
bucket.refill(&mut state, refill_time);
|
||||
assert_eq!(state.available_tokens, 10);
|
||||
assert_eq!(state.refill_remainder, 0);
|
||||
|
||||
state.available_tokens = 0;
|
||||
bucket.refill(&mut state, refill_time);
|
||||
assert_eq!(state.available_tokens, 0);
|
||||
}
|
||||
|
||||
/// Test capacity enforcement
|
||||
#[tokio::test]
|
||||
async fn test_capacity_limit() {
|
||||
let bucket = TokenBucket::new(500, 1000);
|
||||
|
||||
// Wait longer than refill interval
|
||||
sleep(Duration::from_millis(50)).await;
|
||||
|
||||
// Should not exceed capacity despite time passed
|
||||
assert!(bucket.try_consume(500));
|
||||
assert!(!bucket.try_consume(1));
|
||||
}
|
||||
|
||||
/// Test high load with concurrent access
|
||||
#[cfg_attr(
|
||||
not(target_os = "wasi"),
|
||||
tokio::test(flavor = "multi_thread", worker_threads = 4)
|
||||
)]
|
||||
#[cfg_attr(target_os = "wasi", tokio::test)]
|
||||
async fn test_concurrent_access() {
|
||||
let bucket = TokenBucket::new(10_000, 1);
|
||||
let mut handles = vec![];
|
||||
|
||||
// Spawn 100 tasks to consume tokens concurrently
|
||||
for _ in 0..100 {
|
||||
let bucket = bucket.clone();
|
||||
handles.push(tokio::spawn(async move {
|
||||
let mut consumed = 0;
|
||||
for _ in 0..100 {
|
||||
if bucket.try_consume(10) {
|
||||
consumed += 10;
|
||||
}
|
||||
}
|
||||
consumed
|
||||
}));
|
||||
}
|
||||
|
||||
// Wait for all tasks to complete
|
||||
let mut consumed = 0;
|
||||
for handle in handles {
|
||||
consumed += handle.await.unwrap();
|
||||
}
|
||||
|
||||
assert_eq!(consumed, 10_000);
|
||||
assert_eq!(bucket.state.lock().available_tokens, 0);
|
||||
}
|
||||
|
||||
/// Test behavior when packet size exceeds capacity
|
||||
#[tokio::test]
|
||||
async fn test_oversized_packet() {
|
||||
// Fill rate of 1 token/s keeps the test independent of timing:
|
||||
// even a long scheduling stall cannot refill a meaningful amount.
|
||||
let bucket = TokenBucket::new(1500, 1);
|
||||
|
||||
// Oversized packets are charged one full bucket instead of
|
||||
// being rejected, so a full bucket always admits them.
|
||||
assert!(bucket.try_consume(1600));
|
||||
assert_eq!(bucket.state.lock().available_tokens, 0);
|
||||
|
||||
// A partially drained bucket still rejects them.
|
||||
let bucket = TokenBucket::new(1500, 1);
|
||||
assert!(bucket.try_consume(1000));
|
||||
assert!(!bucket.try_consume(1600));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_zero_fill_rate_is_normalized() {
|
||||
let bucket = TokenBucket::new(1000, 0);
|
||||
|
||||
assert_eq!(bucket.config.fill_rate, 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_consume_oversized_packet_in_chunks() {
|
||||
let bucket = TokenBucket::new(10, 1_000_000);
|
||||
|
||||
timeout(Duration::from_millis(100), bucket.consume(25))
|
||||
.await
|
||||
.expect("oversized consume should be split into capacity-sized chunks");
|
||||
}
|
||||
|
||||
/// Test refill precision after elapsed time.
|
||||
#[test]
|
||||
fn test_refill_precision() {
|
||||
let bucket = TokenBucket::new(10_000, 10_000);
|
||||
let start = Instant::now();
|
||||
let mut state = bucket.state.lock();
|
||||
state.available_tokens = 100;
|
||||
state.last_refill = start;
|
||||
state.refill_remainder = 0;
|
||||
|
||||
bucket.refill(&mut state, start + Duration::from_micros(1_234));
|
||||
|
||||
assert_eq!(state.available_tokens, 112);
|
||||
assert_eq!(state.refill_remainder, 340_000_000);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
//! Deadlines for data-plane control operations and persistent I/O resources.
|
||||
|
||||
use std::{future::Future, sync::Mutex, time::Duration};
|
||||
|
||||
use quanta::Instant;
|
||||
use tokio::{sync::watch, task::JoinHandle};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::foundation::time;
|
||||
|
||||
use super::{DataPlaneError, DataPlaneResult};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct DataPlaneDeadline(Option<Instant>);
|
||||
|
||||
impl DataPlaneDeadline {
|
||||
pub(super) fn from_timeout(timeout: Duration) -> Self {
|
||||
Self(Instant::now().checked_add(timeout))
|
||||
}
|
||||
|
||||
pub(super) fn from_optional_timeout(timeout: Option<Duration>) -> Self {
|
||||
match timeout {
|
||||
Some(timeout) => Self::from_timeout(timeout),
|
||||
None => Self(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn remaining(self) -> DataPlaneResult<Option<Duration>> {
|
||||
let Some(deadline) = self.0 else {
|
||||
return Ok(None);
|
||||
};
|
||||
let now = Instant::now();
|
||||
if now >= deadline {
|
||||
return Err(DataPlaneError::deadline_exceeded());
|
||||
}
|
||||
Ok(Some(deadline - now))
|
||||
}
|
||||
|
||||
pub(super) async fn run<T, E>(
|
||||
self,
|
||||
future: impl Future<Output = Result<T, E>>,
|
||||
) -> DataPlaneResult<T>
|
||||
where
|
||||
E: Into<DataPlaneError>,
|
||||
{
|
||||
match self.remaining()? {
|
||||
Some(remaining) => time::timeout(remaining, future)
|
||||
.await
|
||||
.map_err(|_| DataPlaneError::deadline_exceeded())?
|
||||
.map_err(Into::into),
|
||||
None => future.await.map_err(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct DataPlaneIoDeadline {
|
||||
generation: watch::Sender<CancellationToken>,
|
||||
timer: Mutex<Option<JoinHandle<()>>>,
|
||||
}
|
||||
|
||||
impl Default for DataPlaneIoDeadline {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
generation: watch::channel(CancellationToken::new()).0,
|
||||
timer: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DataPlaneIoDeadline {
|
||||
pub(super) fn set_timeout(&self, timeout: Option<Duration>) {
|
||||
let mut timer = self.timer.lock().unwrap_or_else(|error| error.into_inner());
|
||||
if let Some(timer) = timer.take() {
|
||||
timer.abort();
|
||||
}
|
||||
|
||||
let expired = CancellationToken::new();
|
||||
if let Some(timeout) = timeout {
|
||||
if timeout.is_zero() {
|
||||
expired.cancel();
|
||||
} else {
|
||||
if let Some(deadline) = time::Instant::now().checked_add(timeout) {
|
||||
let sleep = time::sleep_until(deadline);
|
||||
let expiration = expired.clone();
|
||||
*timer = Some(tokio::spawn(async move {
|
||||
sleep.await;
|
||||
expiration.cancel();
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
self.generation.send_replace(expired);
|
||||
}
|
||||
|
||||
pub(super) async fn run<T, E>(
|
||||
&self,
|
||||
cancel: CancellationToken,
|
||||
future: impl Future<Output = Result<T, E>>,
|
||||
) -> DataPlaneResult<T>
|
||||
where
|
||||
E: Into<DataPlaneError>,
|
||||
{
|
||||
let mut deadline = self.generation.subscribe();
|
||||
tokio::pin!(future);
|
||||
loop {
|
||||
let expired = deadline.borrow_and_update().clone();
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => {
|
||||
return Err(DataPlaneError::new(
|
||||
super::DataPlaneErrorKind::Cancelled,
|
||||
"data-plane operation cancelled",
|
||||
));
|
||||
}
|
||||
changed = deadline.changed() => {
|
||||
if changed.is_err() {
|
||||
return Err(DataPlaneError::new(
|
||||
super::DataPlaneErrorKind::HandleClosed,
|
||||
"data-plane resource is closed",
|
||||
));
|
||||
}
|
||||
}
|
||||
_ = expired.cancelled() => {
|
||||
return Err(DataPlaneError::deadline_exceeded());
|
||||
}
|
||||
result = &mut future => return result.map_err(Into::into),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DataPlaneIoDeadline {
|
||||
fn drop(&mut self) {
|
||||
if let Some(timer) = self
|
||||
.timer
|
||||
.get_mut()
|
||||
.unwrap_or_else(|error| error.into_inner())
|
||||
.take()
|
||||
{
|
||||
timer.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{future, sync::Arc};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn io_deadline_updates_an_active_operation() {
|
||||
let deadline = Arc::new(DataPlaneIoDeadline::default());
|
||||
let operation = {
|
||||
let deadline = deadline.clone();
|
||||
tokio::spawn(async move {
|
||||
deadline
|
||||
.run(
|
||||
CancellationToken::new(),
|
||||
future::pending::<Result<(), DataPlaneError>>(),
|
||||
)
|
||||
.await
|
||||
})
|
||||
};
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
deadline.set_timeout(Some(Duration::ZERO));
|
||||
|
||||
assert_eq!(
|
||||
operation.await.unwrap().unwrap_err().kind(),
|
||||
super::super::DataPlaneErrorKind::DeadlineExceeded
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn io_deadline_expires_future_operations_until_cleared() {
|
||||
let deadline = DataPlaneIoDeadline::default();
|
||||
deadline.set_timeout(Some(Duration::ZERO));
|
||||
|
||||
assert_eq!(
|
||||
deadline
|
||||
.run(
|
||||
CancellationToken::new(),
|
||||
future::ready(Ok::<_, DataPlaneError>(())),
|
||||
)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.kind(),
|
||||
super::super::DataPlaneErrorKind::DeadlineExceeded
|
||||
);
|
||||
|
||||
deadline.set_timeout(None);
|
||||
deadline
|
||||
.run(
|
||||
CancellationToken::new(),
|
||||
future::ready(Ok::<_, DataPlaneError>(())),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn io_deadline_treats_unrepresentable_timeout_as_unbounded() {
|
||||
let deadline = DataPlaneIoDeadline::default();
|
||||
deadline.set_timeout(Some(Duration::from_millis(u64::MAX - 1)));
|
||||
|
||||
deadline
|
||||
.run(
|
||||
CancellationToken::new(),
|
||||
future::ready(Ok::<_, DataPlaneError>(())),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! Stable errors returned by the public data-plane interface.
|
||||
|
||||
use std::{fmt, io};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
#[repr(u16)]
|
||||
pub enum DataPlaneErrorKind {
|
||||
Cancelled = 1,
|
||||
DeadlineExceeded = 2,
|
||||
InstanceStopped = 3,
|
||||
HandleClosed = 4,
|
||||
NoOverlayRoute = 5,
|
||||
PathNotReady = 6,
|
||||
AddressFamilyUnsupported = 7,
|
||||
AddressInUse = 8,
|
||||
ConnectionRefused = 9,
|
||||
NetworkChanged = 10,
|
||||
ResourceLimit = 11,
|
||||
Io = 12,
|
||||
BufferTooSmall = 13,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct DataPlaneError {
|
||||
kind: DataPlaneErrorKind,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl DataPlaneError {
|
||||
pub(crate) fn new(kind: DataPlaneErrorKind, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn deadline_exceeded() -> Self {
|
||||
Self::new(
|
||||
DataPlaneErrorKind::DeadlineExceeded,
|
||||
"data-plane deadline exceeded",
|
||||
)
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> DataPlaneErrorKind {
|
||||
self.kind
|
||||
}
|
||||
|
||||
pub fn message(&self) -> &str {
|
||||
&self.message
|
||||
}
|
||||
|
||||
pub(crate) fn into_io_error(self) -> io::Error {
|
||||
let kind = match self.kind {
|
||||
DataPlaneErrorKind::Cancelled => io::ErrorKind::Interrupted,
|
||||
DataPlaneErrorKind::DeadlineExceeded => io::ErrorKind::TimedOut,
|
||||
DataPlaneErrorKind::AddressFamilyUnsupported => io::ErrorKind::Unsupported,
|
||||
DataPlaneErrorKind::AddressInUse => io::ErrorKind::AddrInUse,
|
||||
DataPlaneErrorKind::ConnectionRefused => io::ErrorKind::ConnectionRefused,
|
||||
DataPlaneErrorKind::ResourceLimit => io::ErrorKind::OutOfMemory,
|
||||
DataPlaneErrorKind::BufferTooSmall => io::ErrorKind::InvalidInput,
|
||||
DataPlaneErrorKind::InstanceStopped
|
||||
| DataPlaneErrorKind::HandleClosed
|
||||
| DataPlaneErrorKind::NetworkChanged => io::ErrorKind::BrokenPipe,
|
||||
DataPlaneErrorKind::NoOverlayRoute | DataPlaneErrorKind::PathNotReady => {
|
||||
io::ErrorKind::NotConnected
|
||||
}
|
||||
DataPlaneErrorKind::Io => io::ErrorKind::Other,
|
||||
};
|
||||
io::Error::new(kind, self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for DataPlaneError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str(&self.message)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for DataPlaneError {}
|
||||
|
||||
impl From<io::Error> for DataPlaneError {
|
||||
fn from(error: io::Error) -> Self {
|
||||
if let Some(error) = error
|
||||
.get_ref()
|
||||
.and_then(|error| error.downcast_ref::<Self>())
|
||||
{
|
||||
return Self::new(error.kind, error.message.clone());
|
||||
}
|
||||
let kind = match error.kind() {
|
||||
io::ErrorKind::TimedOut => DataPlaneErrorKind::DeadlineExceeded,
|
||||
io::ErrorKind::AddrInUse => DataPlaneErrorKind::AddressInUse,
|
||||
io::ErrorKind::ConnectionRefused => DataPlaneErrorKind::ConnectionRefused,
|
||||
io::ErrorKind::Interrupted => DataPlaneErrorKind::Cancelled,
|
||||
io::ErrorKind::Unsupported => DataPlaneErrorKind::AddressFamilyUnsupported,
|
||||
io::ErrorKind::NotConnected => DataPlaneErrorKind::PathNotReady,
|
||||
io::ErrorKind::BrokenPipe => DataPlaneErrorKind::HandleClosed,
|
||||
io::ErrorKind::OutOfMemory => DataPlaneErrorKind::ResourceLimit,
|
||||
_ => DataPlaneErrorKind::Io,
|
||||
};
|
||||
Self::new(kind, error.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for DataPlaneError {
|
||||
fn from(error: anyhow::Error) -> Self {
|
||||
if let Some(error) = error.downcast_ref::<Self>() {
|
||||
return Self::new(error.kind, error.message.clone());
|
||||
}
|
||||
if let Some(error) = error.downcast_ref::<io::Error>() {
|
||||
return Self::from(io::Error::new(error.kind(), error.to_string()));
|
||||
}
|
||||
Self::new(DataPlaneErrorKind::Io, format!("{error:#}"))
|
||||
}
|
||||
}
|
||||
|
||||
pub type DataPlaneResult<T> = Result<T, DataPlaneError>;
|
||||
@@ -0,0 +1,428 @@
|
||||
//! Shared data-plane flow registration and ownership.
|
||||
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use atomic_shim::AtomicU64;
|
||||
use dashmap::{DashMap, mapref::entry::Entry};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
|
||||
#[repr(u8)]
|
||||
pub(crate) enum FlowKind {
|
||||
Udp = 1,
|
||||
Tcp = 2,
|
||||
TcpListen = 3,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub(crate) struct FlowKey {
|
||||
pub src: SocketAddr,
|
||||
pub dst: SocketAddr,
|
||||
pub kind: FlowKind,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct FlowCountChange {
|
||||
pub previous: usize,
|
||||
pub current: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct FlowInsert {
|
||||
pub replaced: bool,
|
||||
pub count: FlowCountChange,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct FlowRemoval {
|
||||
pub removed: bool,
|
||||
pub count: FlowCountChange,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) struct FlowRetain {
|
||||
pub removed: usize,
|
||||
pub count: FlowCountChange,
|
||||
}
|
||||
|
||||
pub(crate) struct FlowTable<V> {
|
||||
entries: DashMap<FlowKey, RegisteredFlow<V>>,
|
||||
count: AtomicUsize,
|
||||
next_registration: AtomicU64,
|
||||
}
|
||||
|
||||
struct RegisteredFlow<V> {
|
||||
registration: u64,
|
||||
value: V,
|
||||
}
|
||||
|
||||
pub(crate) struct FlowLease<V> {
|
||||
table: Arc<FlowTable<V>>,
|
||||
entry: FlowKey,
|
||||
registration: u64,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl<V> FlowLease<V> {
|
||||
pub fn register(table: Arc<FlowTable<V>>, entry: FlowKey, value: V) -> (Self, FlowInsert) {
|
||||
let (registration, insert) = table.insert_registered(entry.clone(), value);
|
||||
(
|
||||
Self {
|
||||
table,
|
||||
entry,
|
||||
registration,
|
||||
active: true,
|
||||
},
|
||||
insert,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn try_register(table: Arc<FlowTable<V>>, entry: FlowKey, value: V) -> Option<Self> {
|
||||
let registration = table.try_insert_registered(entry.clone(), value)?;
|
||||
Some(Self {
|
||||
table,
|
||||
entry,
|
||||
registration,
|
||||
active: true,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Drop for FlowLease<V> {
|
||||
fn drop(&mut self) {
|
||||
if self.active {
|
||||
self.table
|
||||
.remove_registration(&self.entry, self.registration);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> Default for FlowTable<V> {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
entries: DashMap::new(),
|
||||
count: AtomicUsize::new(0),
|
||||
next_registration: AtomicU64::new(1),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<V> FlowTable<V> {
|
||||
pub fn count(&self) -> usize {
|
||||
self.count.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
/// Returns whether no flow is visible or being published.
|
||||
///
|
||||
/// New entries reserve their count before they become visible, while
|
||||
/// removals release their count after the entry is gone. Consequently a
|
||||
/// zero observed here is a safe fast-path signal without inspecting every
|
||||
/// DashMap shard.
|
||||
pub fn is_idle(&self) -> bool {
|
||||
self.count.load(Ordering::Acquire) == 0
|
||||
}
|
||||
|
||||
pub fn len(&self) -> usize {
|
||||
self.entries.len()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.is_empty()
|
||||
}
|
||||
|
||||
pub fn contains_key(&self, entry: &FlowKey) -> bool {
|
||||
self.entries.contains_key(entry)
|
||||
}
|
||||
|
||||
pub fn contains_destination_ip(&self, destination: IpAddr) -> bool {
|
||||
self.entries
|
||||
.iter()
|
||||
.any(|entry| entry.key().dst.ip() == destination)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn with_entry<R>(&self, entry: &FlowKey, f: impl FnOnce(&V) -> R) -> Option<R> {
|
||||
self.entries.get(entry).map(|value| f(&value.value().value))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn insert(&self, entry: FlowKey, value: V) -> FlowInsert {
|
||||
self.insert_registered(entry, value).1
|
||||
}
|
||||
|
||||
fn insert_registered(&self, entry: FlowKey, value: V) -> (u64, FlowInsert) {
|
||||
let registration = self.next_registration();
|
||||
match self.entries.entry(entry) {
|
||||
Entry::Occupied(mut occupied) => {
|
||||
occupied.insert(RegisteredFlow {
|
||||
registration,
|
||||
value,
|
||||
});
|
||||
let count = self.count();
|
||||
(
|
||||
registration,
|
||||
FlowInsert {
|
||||
replaced: true,
|
||||
count: FlowCountChange {
|
||||
previous: count,
|
||||
current: count,
|
||||
},
|
||||
},
|
||||
)
|
||||
}
|
||||
Entry::Vacant(vacant) => {
|
||||
// Reserve the count while holding the shard lock so retain cannot
|
||||
// observe the entry before its count is accounted for.
|
||||
let count = self.increment_count();
|
||||
vacant.insert(RegisteredFlow {
|
||||
registration,
|
||||
value,
|
||||
});
|
||||
(
|
||||
registration,
|
||||
FlowInsert {
|
||||
replaced: false,
|
||||
count,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn try_insert(&self, entry: FlowKey, value: V) -> bool {
|
||||
self.try_insert_registered(entry, value).is_some()
|
||||
}
|
||||
|
||||
fn try_insert_registered(&self, entry: FlowKey, value: V) -> Option<u64> {
|
||||
match self.entries.entry(entry) {
|
||||
Entry::Occupied(_) => None,
|
||||
Entry::Vacant(vacant) => {
|
||||
let registration = self.next_registration();
|
||||
self.increment_count();
|
||||
vacant.insert(RegisteredFlow {
|
||||
registration,
|
||||
value,
|
||||
});
|
||||
Some(registration)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn remove(&self, entry: &FlowKey) -> FlowRemoval {
|
||||
let removed = self.entries.remove(entry).is_some();
|
||||
let count = if removed {
|
||||
self.decrement_count_by(1)
|
||||
} else {
|
||||
let count = self.count();
|
||||
FlowCountChange {
|
||||
previous: count,
|
||||
current: count,
|
||||
}
|
||||
};
|
||||
FlowRemoval { removed, count }
|
||||
}
|
||||
|
||||
pub fn retain(&self, mut f: impl FnMut(&FlowKey, &mut V) -> bool) -> FlowRetain {
|
||||
let mut removed = 0;
|
||||
self.entries.retain(|entry, value| {
|
||||
let keep = f(entry, &mut value.value);
|
||||
if !keep {
|
||||
removed += 1;
|
||||
}
|
||||
keep
|
||||
});
|
||||
FlowRetain {
|
||||
removed,
|
||||
count: self.decrement_count_by(removed),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn clear(&self) -> FlowRetain {
|
||||
self.retain(|_, _| false)
|
||||
}
|
||||
|
||||
fn increment_count(&self) -> FlowCountChange {
|
||||
let previous = self
|
||||
.count
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| {
|
||||
count.checked_add(1)
|
||||
})
|
||||
.expect("flow count overflow");
|
||||
FlowCountChange {
|
||||
previous,
|
||||
current: previous + 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn next_registration(&self) -> u64 {
|
||||
self.next_registration.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn remove_registration(&self, entry: &FlowKey, registration: u64) -> FlowRemoval {
|
||||
let removed = self
|
||||
.entries
|
||||
.remove_if(entry, |_, flow| flow.registration == registration)
|
||||
.is_some();
|
||||
let count = if removed {
|
||||
self.decrement_count_by(1)
|
||||
} else {
|
||||
let count = self.count();
|
||||
FlowCountChange {
|
||||
previous: count,
|
||||
current: count,
|
||||
}
|
||||
};
|
||||
FlowRemoval { removed, count }
|
||||
}
|
||||
|
||||
fn decrement_count_by(&self, delta: usize) -> FlowCountChange {
|
||||
if delta == 0 {
|
||||
let count = self.count();
|
||||
return FlowCountChange {
|
||||
previous: count,
|
||||
current: count,
|
||||
};
|
||||
}
|
||||
|
||||
let previous = self
|
||||
.count
|
||||
.fetch_update(Ordering::AcqRel, Ordering::Acquire, |count| {
|
||||
count.checked_sub(delta)
|
||||
})
|
||||
.expect("flow count underflow");
|
||||
FlowCountChange {
|
||||
previous,
|
||||
current: previous - delta,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{FlowKey, FlowKind, FlowLease, FlowTable};
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
impl<V> FlowLease<V> {
|
||||
fn remove(mut self) -> super::FlowRemoval {
|
||||
self.active = false;
|
||||
self.table
|
||||
.remove_registration(&self.entry, self.registration)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_kind_values_preserve_native_table_identity() {
|
||||
assert_eq!(FlowKind::Udp as u8, 1);
|
||||
assert_eq!(FlowKind::Tcp as u8, 2);
|
||||
assert_eq!(FlowKind::TcpListen as u8, 3);
|
||||
}
|
||||
|
||||
fn table_entry(port: u16) -> FlowKey {
|
||||
FlowKey {
|
||||
src: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 42, 0, 2)), port),
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 42, 0, 1)), 22),
|
||||
kind: FlowKind::Tcp,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flow_table_tracks_insert_replace_and_remove() {
|
||||
let table = FlowTable::default();
|
||||
let entry = table_entry(40000);
|
||||
|
||||
let inserted = table.insert(entry.clone(), "first");
|
||||
assert!(!inserted.replaced);
|
||||
assert_eq!(inserted.count.previous, 0);
|
||||
assert_eq!(inserted.count.current, 1);
|
||||
assert!(!table.is_idle());
|
||||
assert_eq!(table.with_entry(&entry, |value| *value), Some("first"));
|
||||
|
||||
let replaced = table.insert(entry.clone(), "second");
|
||||
assert!(replaced.replaced);
|
||||
assert_eq!(replaced.count.previous, 1);
|
||||
assert_eq!(replaced.count.current, 1);
|
||||
assert_eq!(table.with_entry(&entry, |value| *value), Some("second"));
|
||||
|
||||
let removed = table.remove(&entry);
|
||||
assert!(removed.removed);
|
||||
assert_eq!(removed.count.previous, 1);
|
||||
assert_eq!(removed.count.current, 0);
|
||||
assert!(table.is_idle());
|
||||
|
||||
let missing = table.remove(&entry);
|
||||
assert!(!missing.removed);
|
||||
assert_eq!(missing.count.previous, 0);
|
||||
assert_eq!(missing.count.current, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flow_table_try_insert_and_retain_keep_count_consistent() {
|
||||
let table = FlowTable::default();
|
||||
let first = table_entry(40000);
|
||||
let second = table_entry(40001);
|
||||
|
||||
assert!(table.try_insert(first.clone(), 1));
|
||||
assert!(!table.try_insert(first.clone(), 2));
|
||||
assert!(table.try_insert(second.clone(), 3));
|
||||
assert_eq!(table.count(), 2);
|
||||
assert!(table.contains_destination_ip(first.dst.ip()));
|
||||
|
||||
let retained = table.retain(|entry, _| entry == &second);
|
||||
assert_eq!(retained.removed, 1);
|
||||
assert_eq!(retained.count.previous, 2);
|
||||
assert_eq!(retained.count.current, 1);
|
||||
assert!(!table.contains_key(&first));
|
||||
assert!(table.contains_key(&second));
|
||||
|
||||
let cleared = table.clear();
|
||||
assert_eq!(cleared.removed, 1);
|
||||
assert_eq!(cleared.count.current, 0);
|
||||
assert!(table.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_guard_owns_registration_lifetime() {
|
||||
let table = Arc::new(FlowTable::default());
|
||||
let entry = table_entry(40000);
|
||||
|
||||
let (guard, insert) = FlowLease::register(table.clone(), entry.clone(), "first");
|
||||
assert!(!insert.replaced);
|
||||
assert!(table.contains_key(&entry));
|
||||
assert!(FlowLease::try_register(table.clone(), entry.clone(), "second").is_none());
|
||||
assert_eq!(table.with_entry(&entry, |value| *value), Some("first"));
|
||||
|
||||
drop(guard);
|
||||
assert!(!table.contains_key(&entry));
|
||||
|
||||
let guard = FlowLease::try_register(table.clone(), entry.clone(), "third").unwrap();
|
||||
let removal = guard.remove();
|
||||
assert!(removal.removed);
|
||||
assert_eq!(table.count(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaced_lease_cannot_remove_new_registration() {
|
||||
let table = Arc::new(FlowTable::default());
|
||||
let entry = table_entry(40000);
|
||||
let (old, _) = FlowLease::register(table.clone(), entry.clone(), "old");
|
||||
let (new, replaced) = FlowLease::register(table.clone(), entry.clone(), "new");
|
||||
assert!(replaced.replaced);
|
||||
|
||||
drop(old);
|
||||
assert_eq!(table.with_entry(&entry, |value| *value), Some("new"));
|
||||
|
||||
drop(new);
|
||||
assert!(!table.contains_key(&entry));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,976 @@
|
||||
//! Data-plane access built on top of the core gateway smoltcp stack.
|
||||
//!
|
||||
//! This module exposes TCP streams and UDP sockets (mainly for FFI callers that
|
||||
//! send traffic through EasyTier without creating OS-level proxy listeners).
|
||||
//!
|
||||
//! Typical usage:
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let instance = CoreInstance::new(...);
|
||||
//! instance.start().await?;
|
||||
//!
|
||||
//! let socket = instance.data_plane_udp_bind(local_port, timeout).await?;
|
||||
//! socket.send_to(buf, peer_addr).await?;
|
||||
//! ```
|
||||
|
||||
use std::{
|
||||
any::Any,
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::{
|
||||
Arc, Weak,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use smoltcp::wire::{IpProtocol, Ipv4Packet, TcpPacket};
|
||||
use tokio::{
|
||||
select,
|
||||
sync::{Mutex, mpsc},
|
||||
task::JoinSet,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::runtime::CoreRuntimeConfigStore,
|
||||
foundation::task::reap_joinset_background,
|
||||
gateway::{
|
||||
proxy::{
|
||||
traits::TcpProxyStream,
|
||||
wrapped_transport::{WrappedTransportKind, WrappedTransportProxyModule},
|
||||
},
|
||||
smoltcp::{Net, UdpSocket},
|
||||
},
|
||||
packet::{PacketType, ZCPacket},
|
||||
peers::{
|
||||
PeerPacketFilter,
|
||||
peer_manager::{PeerManagerCore, PipelineRegistrationGuard},
|
||||
},
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{
|
||||
TcpBindOptions, TcpConnectOptions, TcpListenOptions, TcpSocketPurpose,
|
||||
VirtualTcpListener, VirtualTcpListenerFactory, VirtualTcpSocket,
|
||||
VirtualTcpSocketFactory,
|
||||
},
|
||||
udp::{UdpBindOptions, VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
mod deadline;
|
||||
mod error;
|
||||
mod flow;
|
||||
mod operation;
|
||||
mod packet;
|
||||
mod resource;
|
||||
mod route;
|
||||
mod session;
|
||||
mod stack;
|
||||
mod tcp;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod udp;
|
||||
|
||||
use self::{
|
||||
deadline::{DataPlaneDeadline, DataPlaneIoDeadline},
|
||||
error::DataPlaneResult,
|
||||
flow::{FlowKey, FlowKind, FlowLease, FlowTable},
|
||||
packet::{PeerPacketRoute, tcp_flags},
|
||||
resource::{DataPlaneConsumers, DataPlaneIoGuard, DataPlaneLease},
|
||||
route::{
|
||||
DataPlaneRoutePolicy, DataPlaneTcpRoute, DataPlaneTcpRouteInput,
|
||||
DataPlaneTransportPreference,
|
||||
},
|
||||
stack::SmoltcpPlane,
|
||||
};
|
||||
|
||||
pub(crate) use self::resource::DataPlaneConsumerLease;
|
||||
use self::tcp::DataPlaneTcpStreamRoute;
|
||||
pub use self::{
|
||||
error::{DataPlaneError, DataPlaneErrorKind},
|
||||
operation::{
|
||||
DataPlaneCompletionDescriptor, DataPlaneCompletionStatus, DataPlaneOperationId,
|
||||
DataPlaneOperationKind, DataPlaneOperationOutcome, DataPlaneOperationResult,
|
||||
DataPlaneResourceId,
|
||||
},
|
||||
session::{DataPlaneSession, DataPlaneSessionLimits},
|
||||
tcp::{DataPlaneTcpListener, DataPlaneTcpStream},
|
||||
udp::DataPlaneUdpSocket,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct DataPlaneTcpConnectOptions {
|
||||
policy: DataPlaneRoutePolicy,
|
||||
transport: DataPlaneTransportPreference,
|
||||
purpose: TcpSocketPurpose,
|
||||
source_hint: Option<SocketAddr>,
|
||||
deadline: DataPlaneDeadline,
|
||||
}
|
||||
|
||||
impl DataPlaneTcpConnectOptions {
|
||||
fn public(timeout: Duration) -> Self {
|
||||
Self::public_with_timeout(Some(timeout))
|
||||
}
|
||||
|
||||
fn public_with_timeout(timeout: Option<Duration>) -> Self {
|
||||
Self::public_with_deadline(DataPlaneDeadline::from_optional_timeout(timeout))
|
||||
}
|
||||
|
||||
fn public_with_deadline(deadline: DataPlaneDeadline) -> Self {
|
||||
Self {
|
||||
policy: DataPlaneRoutePolicy::OverlayOnly,
|
||||
transport: DataPlaneTransportPreference::SmoltcpOnly,
|
||||
purpose: TcpSocketPurpose::DataPlane,
|
||||
source_hint: None,
|
||||
deadline,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn gateway(
|
||||
timeout: Duration,
|
||||
purpose: TcpSocketPurpose,
|
||||
source_hint: SocketAddr,
|
||||
) -> Self {
|
||||
Self {
|
||||
policy: DataPlaneRoutePolicy::OverlayOrDirect,
|
||||
transport: DataPlaneTransportPreference::PreferKcp,
|
||||
purpose,
|
||||
source_hint: Some(source_hint),
|
||||
deadline: DataPlaneDeadline::from_timeout(timeout),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct DataPlaneUdpIo(UdpSocket);
|
||||
|
||||
impl DataPlaneUdpIo {
|
||||
pub async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> Result<usize, std::io::Error> {
|
||||
self.0.send_to(buf, addr).await
|
||||
}
|
||||
|
||||
pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr), std::io::Error> {
|
||||
self.0.recv_from(buf).await
|
||||
}
|
||||
|
||||
pub async fn recv_from_limited(
|
||||
&self,
|
||||
max_len: usize,
|
||||
) -> Result<(Vec<u8>, SocketAddr, bool), std::io::Error> {
|
||||
self.0.recv_from_limited(max_len).await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) enum FlowData {
|
||||
Tcp {
|
||||
_reservation: Arc<dyn Any + Send + Sync>,
|
||||
},
|
||||
// a data-plane routing entry that owns no resource. the entry_type in the
|
||||
// key distinguishes a listen route from an actively outbound route.
|
||||
DataPlaneRoute,
|
||||
Udp,
|
||||
}
|
||||
|
||||
const UDP_ENTRY: FlowKind = FlowKind::Udp;
|
||||
const TCP_ENTRY: FlowKind = FlowKind::Tcp;
|
||||
const TCP_LISTEN_ENTRY: FlowKind = FlowKind::TcpListen;
|
||||
|
||||
type FlowSet = Arc<FlowTable<FlowData>>;
|
||||
type DataPlaneTcpIo = Box<dyn TcpProxyStream>;
|
||||
|
||||
pub(crate) struct DataPlaneRuntime<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
operation: Mutex<()>,
|
||||
pub(super) runtime_started: AtomicBool,
|
||||
runtime_guard: DataPlaneIoGuard,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
pub(super) peer_manager: Weak<PeerManagerCore>,
|
||||
pub(super) transport_proxy: Option<Weak<WrappedTransportProxyModule>>,
|
||||
pub(super) host: Arc<H>,
|
||||
pub(super) socket_context: SocketContext,
|
||||
|
||||
pub(super) runtime_tasks: Arc<std::sync::Mutex<JoinSet<()>>>,
|
||||
packet_sender: mpsc::Sender<ZCPacket>,
|
||||
packet_recv: Arc<Mutex<mpsc::Receiver<ZCPacket>>>,
|
||||
|
||||
net: Arc<Mutex<Option<SmoltcpPlane>>>,
|
||||
pub(super) entries: FlowSet,
|
||||
|
||||
data_plane_consumers: Arc<DataPlaneConsumers>,
|
||||
// Tracks whether the smoltcp `net` is ready for data-plane callers.
|
||||
data_plane_net_ready: tokio::sync::watch::Sender<bool>,
|
||||
pipeline_guard: Mutex<Option<PipelineRegistrationGuard>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<H> PeerPacketFilter for DataPlaneRuntime<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
async fn try_process_packet_from_peer(&self, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
if self.entries.is_idle() {
|
||||
if tracing::enabled!(tracing::Level::TRACE)
|
||||
&& let Some(hdr) = packet.peer_manager_header()
|
||||
&& matches!(
|
||||
hdr.packet_type,
|
||||
x if x == PacketType::Data as u8
|
||||
|| x == PacketType::DataWithKcpSrcModified as u8
|
||||
|| x == PacketType::DataWithQuicSrcModified as u8
|
||||
)
|
||||
{
|
||||
if let Ok(ipv4) = Ipv4Packet::new_checked(packet.payload()) {
|
||||
let (tcp_src_port, tcp_dst_port, tcp_flags) =
|
||||
if ipv4.next_header() == IpProtocol::Tcp {
|
||||
TcpPacket::new_checked(ipv4.payload())
|
||||
.ok()
|
||||
.map(|tcp| {
|
||||
(
|
||||
Some(tcp.src_port()),
|
||||
Some(tcp.dst_port()),
|
||||
Some(tcp_flags(&tcp)),
|
||||
)
|
||||
})
|
||||
.unwrap_or((None, None, None))
|
||||
} else {
|
||||
(None, None, None)
|
||||
};
|
||||
tracing::trace!(
|
||||
packet_type = hdr.packet_type,
|
||||
from_peer_id = hdr.from_peer_id.get(),
|
||||
to_peer_id = hdr.to_peer_id.get(),
|
||||
ipv4_src = %ipv4.src_addr(),
|
||||
ipv4_dst = %ipv4.dst_addr(),
|
||||
next_protocol = ?ipv4.next_header(),
|
||||
?tcp_src_port,
|
||||
?tcp_dst_port,
|
||||
?tcp_flags,
|
||||
entry_count = 0,
|
||||
"data plane fast gate passed packet from peer"
|
||||
);
|
||||
} else {
|
||||
tracing::trace!(
|
||||
packet_type = hdr.packet_type,
|
||||
from_peer_id = hdr.from_peer_id.get(),
|
||||
to_peer_id = hdr.to_peer_id.get(),
|
||||
entry_count = 0,
|
||||
"data plane fast gate passed non-ipv4 packet from peer"
|
||||
);
|
||||
}
|
||||
}
|
||||
return Some(packet);
|
||||
}
|
||||
let route = self.entries.route_peer_packet(&packet, true);
|
||||
let (entry_key, tcp_flags) = match route {
|
||||
PeerPacketRoute::Pass => return Some(packet),
|
||||
PeerPacketRoute::Unmatched { entry, tcp_flags } => {
|
||||
tracing::trace!(
|
||||
entry_key = ?entry,
|
||||
?tcp_flags,
|
||||
ipv4_src = %entry.dst.ip(),
|
||||
ipv4_dst = %entry.src.ip(),
|
||||
entry_count = self.entries.count(),
|
||||
"data plane has no flow for packet from peer"
|
||||
);
|
||||
return Some(packet);
|
||||
}
|
||||
PeerPacketRoute::Deliver { entry, tcp_flags } => (entry, tcp_flags),
|
||||
PeerPacketRoute::FragmentedUdp { source, mirror } => {
|
||||
let source: IpAddr = source.into();
|
||||
tracing::trace!(
|
||||
is_in_entries = mirror,
|
||||
"ipv4 src = {:?}, check need send both smoltcp and kernel tun",
|
||||
source
|
||||
);
|
||||
if mirror {
|
||||
// if the packet is fragmented, no matther what the payload is, need send it to both smoltcp and kernel tun. because
|
||||
// we cannot determine the udp port of the packet.
|
||||
match self.packet_sender.try_send(packet.clone()) {
|
||||
Ok(()) => tracing::trace!(
|
||||
?source,
|
||||
entry_count = self.entries.count(),
|
||||
"data plane delivered fragmented packet from peer to smoltcp"
|
||||
),
|
||||
Err(err) => tracing::trace!(
|
||||
?source,
|
||||
?err,
|
||||
entry_count = self.entries.count(),
|
||||
"data plane failed to deliver fragmented packet from peer to smoltcp"
|
||||
),
|
||||
}
|
||||
}
|
||||
return Some(packet);
|
||||
}
|
||||
};
|
||||
|
||||
tracing::trace!(
|
||||
?entry_key,
|
||||
?tcp_flags,
|
||||
ipv4_src = %entry_key.dst.ip(),
|
||||
ipv4_dst = %entry_key.src.ip(),
|
||||
entry_count = self.entries.count(),
|
||||
"data plane found entry for packet from peer"
|
||||
);
|
||||
|
||||
match self.packet_sender.try_send(packet) {
|
||||
Ok(()) => tracing::trace!(
|
||||
?entry_key,
|
||||
?tcp_flags,
|
||||
entry_count = self.entries.count(),
|
||||
"data plane delivered packet from peer to smoltcp"
|
||||
),
|
||||
Err(err) => tracing::trace!(
|
||||
?entry_key,
|
||||
?tcp_flags,
|
||||
?err,
|
||||
entry_count = self.entries.count(),
|
||||
"data plane failed to deliver packet from peer to smoltcp"
|
||||
),
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> DataPlaneRuntime<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
transport_proxy: Option<&Arc<WrappedTransportProxyModule>>,
|
||||
host: Arc<H>,
|
||||
socket_context: SocketContext,
|
||||
) -> Arc<Self> {
|
||||
let (packet_sender, packet_recv) = mpsc::channel(1024);
|
||||
Arc::new(Self {
|
||||
operation: Mutex::new(()),
|
||||
runtime_started: AtomicBool::new(false),
|
||||
runtime_guard: DataPlaneIoGuard::new(),
|
||||
runtime_config,
|
||||
peer_manager: Arc::downgrade(&peer_manager),
|
||||
transport_proxy: transport_proxy.map(Arc::downgrade),
|
||||
host,
|
||||
socket_context,
|
||||
|
||||
runtime_tasks: Arc::new(std::sync::Mutex::new(JoinSet::new())),
|
||||
packet_recv: Arc::new(Mutex::new(packet_recv)),
|
||||
packet_sender,
|
||||
|
||||
net: Arc::new(Mutex::new(None)),
|
||||
entries: Arc::new(FlowTable::default()),
|
||||
|
||||
data_plane_consumers: Arc::new(DataPlaneConsumers::new()),
|
||||
data_plane_net_ready: tokio::sync::watch::channel(false).0,
|
||||
pipeline_guard: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
fn runtime_ipv4(runtime_config: &CoreRuntimeConfigStore) -> Option<cidr::Ipv4Inet> {
|
||||
let prefix = runtime_config
|
||||
.snapshot()
|
||||
.peer
|
||||
.runtime
|
||||
.core
|
||||
.routes
|
||||
.ipv4
|
||||
.clone()?;
|
||||
let IpAddr::V4(address) = prefix.address else {
|
||||
return None;
|
||||
};
|
||||
cidr::Ipv4Inet::new(address, prefix.prefix_len).ok()
|
||||
}
|
||||
|
||||
pub(crate) fn is_local_virtual_ip(&self, ip: IpAddr) -> bool {
|
||||
Self::runtime_ipv4(&self.runtime_config)
|
||||
.is_some_and(|inet| IpAddr::V4(inet.address()) == ip)
|
||||
}
|
||||
|
||||
async fn run_net_update_task(self: &Arc<Self>) {
|
||||
let net = self.net.clone();
|
||||
let runtime_config = self.runtime_config.clone();
|
||||
let peer_manager = self.peer_manager.clone();
|
||||
let packet_recv = self.packet_recv.clone();
|
||||
let entries = self.entries.clone();
|
||||
let data_plane_consumers = self.data_plane_consumers.clone();
|
||||
let data_plane_net_ready = self.data_plane_net_ready.clone();
|
||||
self.runtime_tasks.lock().unwrap().spawn(async move {
|
||||
let mut prev_ipv4 = None;
|
||||
let mut peer_changes = runtime_config.subscribe_peer_runtime_changes();
|
||||
loop {
|
||||
let data_plane_active = data_plane_consumers.has_consumers();
|
||||
|
||||
if !data_plane_active {
|
||||
let old_net = {
|
||||
let mut net_guard = net.lock().await;
|
||||
// New leases and the zero-consumer teardown decision
|
||||
// are serialized while this net slot is held. A bind
|
||||
// can retain this generation or wait for its
|
||||
// replacement, but cannot receive a stale generation.
|
||||
if data_plane_consumers.has_consumers() {
|
||||
continue;
|
||||
}
|
||||
net_guard.take()
|
||||
};
|
||||
if let Some(old_net) = &old_net {
|
||||
old_net.close(DataPlaneErrorKind::HandleClosed);
|
||||
}
|
||||
let had_net = old_net.is_some();
|
||||
prev_ipv4 = None;
|
||||
let cleared = entries.clear();
|
||||
tracing::trace!(
|
||||
had_net,
|
||||
data_plane_active,
|
||||
removed_entries = cleared.removed,
|
||||
entry_count = cleared.count.current,
|
||||
entries_len = entries.len(),
|
||||
"data plane waiting for consumers"
|
||||
);
|
||||
let _ = data_plane_net_ready.send_replace(false);
|
||||
select! {
|
||||
_ = peer_changes.changed() => {}
|
||||
_ = data_plane_consumers.changed() => {}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
let cur_ipv4 = Self::runtime_ipv4(&runtime_config);
|
||||
if prev_ipv4 != cur_ipv4 {
|
||||
let old_ipv4 = prev_ipv4;
|
||||
prev_ipv4 = cur_ipv4;
|
||||
|
||||
tracing::trace!(
|
||||
?old_ipv4,
|
||||
?cur_ipv4,
|
||||
old_entry_count = entries.count(),
|
||||
old_entries_len = entries.len(),
|
||||
"data plane resetting flows for ipv4 change"
|
||||
);
|
||||
let _ = data_plane_net_ready.send_replace(false);
|
||||
let old_net = net.lock().await.take();
|
||||
if let Some(old_net) = old_net {
|
||||
old_net.close(DataPlaneErrorKind::NetworkChanged);
|
||||
}
|
||||
let cleared = entries.clear();
|
||||
tracing::trace!(
|
||||
?old_ipv4,
|
||||
?cur_ipv4,
|
||||
removed_entries = cleared.removed,
|
||||
new_entry_count = cleared.count.current,
|
||||
new_entries_len = entries.len(),
|
||||
"data plane reset flows complete"
|
||||
);
|
||||
|
||||
if let Some(cur_ipv4) = cur_ipv4 {
|
||||
net.lock().await.replace(SmoltcpPlane::new(
|
||||
cur_ipv4,
|
||||
peer_manager.clone(),
|
||||
packet_recv.clone(),
|
||||
));
|
||||
tracing::trace!(
|
||||
?cur_ipv4,
|
||||
entry_count = entries.count(),
|
||||
entries_len = entries.len(),
|
||||
"data plane installed smoltcp net"
|
||||
);
|
||||
// Wake any data-plane callers waiting in
|
||||
// `wait_data_plane_net` for the smoltcp net to appear.
|
||||
let _ = data_plane_net_ready.send_replace(true);
|
||||
} else {
|
||||
tracing::trace!(
|
||||
entry_count = entries.count(),
|
||||
entries_len = entries.len(),
|
||||
"data plane removed smoltcp net"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
select! {
|
||||
_ = peer_changes.changed() => {}
|
||||
_ = data_plane_consumers.changed() => {}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn start_runtime_inner(self: &Arc<Self>) -> anyhow::Result<()> {
|
||||
let Some(peer_manager) = self.peer_manager.upgrade() else {
|
||||
return Err(anyhow::anyhow!("peer manager is gone"));
|
||||
};
|
||||
let guard = peer_manager
|
||||
.add_managed_packet_process_pipeline(Box::new(self.clone()))
|
||||
.await;
|
||||
self.pipeline_guard.lock().await.replace(guard);
|
||||
|
||||
self.runtime_tasks
|
||||
.lock()
|
||||
.unwrap()
|
||||
.spawn(reap_joinset_background(
|
||||
Arc::downgrade(&self.runtime_tasks),
|
||||
"data plane runtime",
|
||||
));
|
||||
self.run_net_update_task().await;
|
||||
|
||||
tracing::trace!("data plane peer packet pipeline registered");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn start_runtime(self: &Arc<Self>) -> anyhow::Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
if self.runtime_started.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
if let Err(error) = self.start_runtime_inner().await {
|
||||
self.stop_runtime_inner().await;
|
||||
return Err(error);
|
||||
}
|
||||
self.runtime_started.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn shutdown_tasks(tasks: &Arc<std::sync::Mutex<JoinSet<()>>>) {
|
||||
let mut tasks = {
|
||||
let mut guard = tasks.lock().unwrap();
|
||||
std::mem::replace(&mut *guard, JoinSet::new())
|
||||
};
|
||||
tasks.shutdown().await;
|
||||
}
|
||||
|
||||
async fn stop_runtime_inner(&self) {
|
||||
self.runtime_started.store(false, Ordering::Release);
|
||||
self.runtime_guard
|
||||
.close(DataPlaneErrorKind::InstanceStopped);
|
||||
if let Some(guard) = self.pipeline_guard.lock().await.take() {
|
||||
guard.close();
|
||||
}
|
||||
if let Some(net) = self.net.lock().await.take() {
|
||||
net.close(DataPlaneErrorKind::InstanceStopped);
|
||||
}
|
||||
let _ = self.data_plane_net_ready.send_replace(false);
|
||||
self.entries.clear();
|
||||
Self::shutdown_tasks(&self.runtime_tasks).await;
|
||||
}
|
||||
|
||||
pub(crate) async fn stop_runtime(&self) {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.stop_runtime_inner().await;
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> DataPlaneRuntime<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
async fn tcp_route_input(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
options: DataPlaneTcpConnectOptions,
|
||||
) -> DataPlaneResult<DataPlaneTcpRouteInput> {
|
||||
let IpAddr::V4(dst_ip) = dst_addr.ip() else {
|
||||
return Err(DataPlaneError::new(
|
||||
DataPlaneErrorKind::AddressFamilyUnsupported,
|
||||
"the EasyTier data plane currently supports IPv4 destinations only",
|
||||
));
|
||||
};
|
||||
self.runtime_guard.ensure_open()?;
|
||||
let local_virtual_ip = Self::runtime_ipv4(&self.runtime_config).map(|inet| inet.address());
|
||||
let local_virtual_destination = local_virtual_ip == Some(dst_ip);
|
||||
let local_endpoint = local_virtual_destination
|
||||
&& self.entries.contains_key(&FlowKey {
|
||||
src: dst_addr,
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||
kind: TCP_LISTEN_ENTRY,
|
||||
});
|
||||
|
||||
let peer_manager = self.peer_manager.upgrade().ok_or_else(|| {
|
||||
DataPlaneError::new(
|
||||
DataPlaneErrorKind::InstanceStopped,
|
||||
"peer manager is no longer available",
|
||||
)
|
||||
})?;
|
||||
let overlay_destination = if local_virtual_destination {
|
||||
true
|
||||
} else {
|
||||
let (peers, _) = options
|
||||
.deadline
|
||||
.run(async {
|
||||
Ok::<_, DataPlaneError>(peer_manager.get_msg_dst_peer(&dst_addr.ip()).await)
|
||||
})
|
||||
.await?;
|
||||
!peers.is_empty()
|
||||
};
|
||||
|
||||
let prefer_kcp = options.transport == DataPlaneTransportPreference::PreferKcp;
|
||||
let transport_proxy = self.transport_proxy.as_ref().and_then(Weak::upgrade);
|
||||
let kcp_ready = if prefer_kcp && overlay_destination {
|
||||
match &transport_proxy {
|
||||
Some(proxy) => {
|
||||
options
|
||||
.deadline
|
||||
.run(async {
|
||||
Ok::<_, DataPlaneError>(
|
||||
proxy.source_connect_ready(WrappedTransportKind::Kcp).await,
|
||||
)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
None => false,
|
||||
}
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let kcp_allowed = if prefer_kcp && kcp_ready {
|
||||
options
|
||||
.deadline
|
||||
.run(async {
|
||||
Ok::<_, DataPlaneError>(
|
||||
peer_manager.check_allow_kcp_to_dst(&dst_addr.ip()).await,
|
||||
)
|
||||
})
|
||||
.await?
|
||||
} else {
|
||||
false
|
||||
};
|
||||
|
||||
Ok(DataPlaneTcpRouteInput {
|
||||
policy: options.policy,
|
||||
transport: options.transport,
|
||||
local_endpoint,
|
||||
local_virtual_destination,
|
||||
overlay_destination,
|
||||
smoltcp_ready: self.net.lock().await.is_some(),
|
||||
kcp_ready,
|
||||
kcp_allowed,
|
||||
})
|
||||
}
|
||||
|
||||
async fn connect_smoltcp_tcp(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
deadline: DataPlaneDeadline,
|
||||
data_plane_ref: DataPlaneLease,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
let (ipv4_addr, smoltcp_net, generation) = self.wait_data_plane_net(deadline).await?;
|
||||
let listen_options = TcpListenOptions::port_lease("0.0.0.0:0".parse().unwrap());
|
||||
let reservation = generation
|
||||
.while_open(
|
||||
deadline.run(
|
||||
self.host.bind_tcp(
|
||||
listen_options.clone().with_bind(
|
||||
listen_options
|
||||
.bind
|
||||
.with_context(self.socket_context.clone()),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
let local_port = reservation
|
||||
.local_addr()
|
||||
.map_err(DataPlaneError::from)?
|
||||
.port();
|
||||
let local_addr = SocketAddr::new(IpAddr::V4(ipv4_addr.address()), local_port);
|
||||
let (flow, _) = FlowLease::register(
|
||||
self.entries.clone(),
|
||||
FlowKey {
|
||||
src: local_addr,
|
||||
dst: dst_addr,
|
||||
kind: TCP_ENTRY,
|
||||
},
|
||||
FlowData::Tcp {
|
||||
_reservation: reservation,
|
||||
},
|
||||
);
|
||||
let stream = generation
|
||||
.while_open(deadline.run(smoltcp_net.tcp_connect(dst_addr, local_port)))
|
||||
.await?;
|
||||
generation.ensure_open()?;
|
||||
|
||||
Ok(DataPlaneTcpStream::new(
|
||||
Box::new(stream),
|
||||
local_addr,
|
||||
Some(data_plane_ref),
|
||||
DataPlaneTcpStreamRoute::Outbound { _flow: flow },
|
||||
generation,
|
||||
))
|
||||
}
|
||||
|
||||
async fn connect_host_tcp(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
options: DataPlaneTcpConnectOptions,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
let connect_options = TcpConnectOptions::direct_connect(dst_addr)
|
||||
.with_purpose(options.purpose)
|
||||
.with_bind(TcpBindOptions::default().with_context(self.socket_context.clone()));
|
||||
let socket = self
|
||||
.runtime_guard
|
||||
.while_open(options.deadline.run(self.host.connect_tcp(connect_options)))
|
||||
.await?;
|
||||
let local_addr = socket.local_addr().map_err(DataPlaneError::from)?;
|
||||
Ok(DataPlaneTcpStream::new(
|
||||
Box::new(socket),
|
||||
local_addr,
|
||||
None,
|
||||
DataPlaneTcpStreamRoute::External,
|
||||
self.runtime_guard.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
async fn connect_kcp_tcp(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
options: DataPlaneTcpConnectOptions,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
let source_addr = options.source_hint.ok_or_else(|| {
|
||||
DataPlaneError::new(
|
||||
DataPlaneErrorKind::PathNotReady,
|
||||
"KCP gateway route requires a logical source address",
|
||||
)
|
||||
})?;
|
||||
let transport_proxy = self
|
||||
.transport_proxy
|
||||
.as_ref()
|
||||
.and_then(Weak::upgrade)
|
||||
.ok_or_else(|| {
|
||||
DataPlaneError::new(
|
||||
DataPlaneErrorKind::PathNotReady,
|
||||
"KCP source transport is not ready",
|
||||
)
|
||||
})?;
|
||||
let stream = self
|
||||
.runtime_guard
|
||||
.while_open(options.deadline.run(transport_proxy.connect_source(
|
||||
WrappedTransportKind::Kcp,
|
||||
source_addr,
|
||||
dst_addr,
|
||||
)))
|
||||
.await?;
|
||||
Ok(DataPlaneTcpStream::new(
|
||||
stream,
|
||||
source_addr,
|
||||
None,
|
||||
DataPlaneTcpStreamRoute::External,
|
||||
self.runtime_guard.clone(),
|
||||
))
|
||||
}
|
||||
|
||||
pub(crate) async fn connect_tcp(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
options: DataPlaneTcpConnectOptions,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
let mut route_input = self.tcp_route_input(dst_addr, options).await?;
|
||||
let route = match route_input.select() {
|
||||
Ok(route) => route,
|
||||
Err(error) if error.kind() == DataPlaneErrorKind::PathNotReady => {
|
||||
let data_plane_ref = self.acquire_data_plane_ref()?;
|
||||
let _ = self.wait_data_plane_net(options.deadline).await?;
|
||||
route_input.smoltcp_ready = true;
|
||||
let route = route_input.select()?;
|
||||
return self
|
||||
.connect_selected_tcp(dst_addr, options, route, Some(data_plane_ref))
|
||||
.await;
|
||||
}
|
||||
Err(error) => return Err(error),
|
||||
};
|
||||
self.connect_selected_tcp(dst_addr, options, route, None)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn connect_selected_tcp(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
options: DataPlaneTcpConnectOptions,
|
||||
route: DataPlaneTcpRoute,
|
||||
data_plane_ref: Option<DataPlaneLease>,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
tracing::debug!(?dst_addr, ?route, "selected data-plane TCP route");
|
||||
match route {
|
||||
DataPlaneTcpRoute::LocalEndpoint | DataPlaneTcpRoute::Smoltcp => {
|
||||
let data_plane_ref = match data_plane_ref {
|
||||
Some(lease) => lease,
|
||||
None => self.acquire_data_plane_ref()?,
|
||||
};
|
||||
self.connect_smoltcp_tcp(dst_addr, options.deadline, data_plane_ref)
|
||||
.await
|
||||
}
|
||||
DataPlaneTcpRoute::LocalHost => {
|
||||
self.connect_host_tcp(
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), dst_addr.port()),
|
||||
options,
|
||||
)
|
||||
.await
|
||||
}
|
||||
DataPlaneTcpRoute::Kcp => self.connect_kcp_tcp(dst_addr, options).await,
|
||||
DataPlaneTcpRoute::Direct => self.connect_host_tcp(dst_addr, options).await,
|
||||
}
|
||||
}
|
||||
|
||||
fn acquire_data_plane_ref(&self) -> DataPlaneResult<DataPlaneLease> {
|
||||
if !self.runtime_started.load(Ordering::Acquire) || self.runtime_guard.is_closed() {
|
||||
return Err(DataPlaneError::new(
|
||||
DataPlaneErrorKind::InstanceStopped,
|
||||
"data-plane runtime is not running",
|
||||
));
|
||||
}
|
||||
let lease = DataPlaneLease::acquire(self.data_plane_consumers.clone());
|
||||
if !self.runtime_started.load(Ordering::Acquire) || self.runtime_guard.is_closed() {
|
||||
drop(lease);
|
||||
return Err(DataPlaneError::new(
|
||||
DataPlaneErrorKind::InstanceStopped,
|
||||
"data-plane runtime stopped while acquiring a resource",
|
||||
));
|
||||
}
|
||||
Ok(lease)
|
||||
}
|
||||
|
||||
pub(crate) fn acquire_consumer_lease(&self) -> DataPlaneResult<DataPlaneConsumerLease> {
|
||||
self.acquire_data_plane_ref()
|
||||
.map(DataPlaneConsumerLease::new)
|
||||
}
|
||||
|
||||
async fn wait_data_plane_net(
|
||||
&self,
|
||||
deadline: DataPlaneDeadline,
|
||||
) -> DataPlaneResult<(cidr::Ipv4Inet, Arc<Net>, DataPlaneIoGuard)> {
|
||||
let mut ready = self.data_plane_net_ready.subscribe();
|
||||
loop {
|
||||
if let Some(net) = self
|
||||
.net
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.map(|plane| (plane.ipv4_addr, plane.net.clone(), plane.lease()))
|
||||
{
|
||||
net.2.ensure_open()?;
|
||||
return Ok(net);
|
||||
}
|
||||
|
||||
tokio::select! {
|
||||
_ = self.runtime_guard.closed() => {
|
||||
return Err(DataPlaneError::new(
|
||||
DataPlaneErrorKind::InstanceStopped,
|
||||
"data-plane runtime stopped while waiting for the stack",
|
||||
));
|
||||
}
|
||||
result = deadline.run(async {
|
||||
ready
|
||||
.wait_for(|ready| *ready)
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|_| DataPlaneError::new(
|
||||
DataPlaneErrorKind::InstanceStopped,
|
||||
"data-plane readiness channel closed",
|
||||
))
|
||||
}) => {
|
||||
result?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn data_plane_tcp_connect(
|
||||
&self,
|
||||
dst_addr: SocketAddr,
|
||||
timeout: Duration,
|
||||
) -> DataPlaneResult<DataPlaneTcpStream> {
|
||||
self.connect_tcp(dst_addr, DataPlaneTcpConnectOptions::public(timeout))
|
||||
.await
|
||||
}
|
||||
|
||||
pub async fn data_plane_tcp_bind(
|
||||
&self,
|
||||
local_port: u16,
|
||||
timeout: Duration,
|
||||
) -> DataPlaneResult<DataPlaneTcpListener> {
|
||||
self.data_plane_tcp_bind_with_deadline(local_port, DataPlaneDeadline::from_timeout(timeout))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn data_plane_tcp_bind_with_deadline(
|
||||
&self,
|
||||
local_port: u16,
|
||||
deadline: DataPlaneDeadline,
|
||||
) -> DataPlaneResult<DataPlaneTcpListener> {
|
||||
let data_plane_ref = self.acquire_data_plane_ref()?;
|
||||
let (ipv4_addr, smoltcp_net, generation) = self.wait_data_plane_net(deadline).await?;
|
||||
let bind_addr = SocketAddr::new(IpAddr::V4(ipv4_addr.address()), local_port);
|
||||
let listener = generation
|
||||
.while_open(deadline.run(smoltcp_net.tcp_bind(bind_addr)))
|
||||
.await?;
|
||||
generation.ensure_open()?;
|
||||
let local_addr = listener.local_addr().map_err(DataPlaneError::from)?;
|
||||
let listen_route = FlowLease::try_register(
|
||||
self.entries.clone(),
|
||||
FlowKey {
|
||||
src: local_addr,
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||
kind: TCP_LISTEN_ENTRY,
|
||||
},
|
||||
FlowData::DataPlaneRoute,
|
||||
)
|
||||
.ok_or_else(|| {
|
||||
DataPlaneError::new(
|
||||
DataPlaneErrorKind::AddressInUse,
|
||||
"data-plane TCP listener already exists",
|
||||
)
|
||||
})?;
|
||||
|
||||
Ok(DataPlaneTcpListener {
|
||||
listener,
|
||||
local_addr,
|
||||
flows: self.entries.clone(),
|
||||
_listen_flow: listen_route,
|
||||
data_plane_lease: data_plane_ref,
|
||||
generation,
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn data_plane_udp_bind(
|
||||
&self,
|
||||
local_port: u16,
|
||||
timeout: Duration,
|
||||
) -> DataPlaneResult<DataPlaneUdpSocket> {
|
||||
self.data_plane_udp_bind_with_deadline(local_port, DataPlaneDeadline::from_timeout(timeout))
|
||||
.await
|
||||
}
|
||||
|
||||
async fn data_plane_udp_bind_with_deadline(
|
||||
&self,
|
||||
local_port: u16,
|
||||
deadline: DataPlaneDeadline,
|
||||
) -> DataPlaneResult<DataPlaneUdpSocket> {
|
||||
let data_plane_ref = self.acquire_data_plane_ref()?;
|
||||
let (ipv4_addr, smoltcp_net, generation) = self.wait_data_plane_net(deadline).await?;
|
||||
let reservation_options = UdpBindOptions::port_lease(SocketAddr::new(
|
||||
IpAddr::V4(Ipv4Addr::UNSPECIFIED),
|
||||
local_port,
|
||||
))
|
||||
.with_context(self.socket_context.clone());
|
||||
let reservation = generation
|
||||
.while_open(deadline.run(self.host.bind_udp(reservation_options)))
|
||||
.await?;
|
||||
let reserved_port = reservation
|
||||
.local_addr()
|
||||
.map_err(DataPlaneError::from)?
|
||||
.port();
|
||||
let bind_addr = SocketAddr::new(IpAddr::V4(ipv4_addr.address()), reserved_port);
|
||||
let smol = generation
|
||||
.while_open(deadline.run(smoltcp_net.udp_bind(bind_addr)))
|
||||
.await?;
|
||||
generation.ensure_open()?;
|
||||
let local_addr = smol.local_addr().map_err(DataPlaneError::from)?;
|
||||
let socket = Arc::new(DataPlaneUdpIo(smol));
|
||||
|
||||
Ok(DataPlaneUdpSocket {
|
||||
socket,
|
||||
flows: self.entries.clone(),
|
||||
routes: std::sync::Mutex::new(std::collections::HashMap::new()),
|
||||
local_addr,
|
||||
_reservation: reservation,
|
||||
_data_plane_lease: data_plane_ref,
|
||||
generation,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
//! Stable operation, completion, and result types for one data-plane session.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use crate::foundation::operation_broker::OperationId;
|
||||
|
||||
use super::DataPlaneErrorKind;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[repr(transparent)]
|
||||
pub struct DataPlaneOperationId(OperationId);
|
||||
|
||||
impl DataPlaneOperationId {
|
||||
pub fn from_raw(value: u64) -> Option<Self> {
|
||||
OperationId::from_raw(value).map(Self)
|
||||
}
|
||||
|
||||
pub fn get(self) -> u64 {
|
||||
self.0.get()
|
||||
}
|
||||
|
||||
pub(super) fn from_broker(operation_id: OperationId) -> Self {
|
||||
Self(operation_id)
|
||||
}
|
||||
|
||||
pub(super) fn broker_id(self) -> OperationId {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
|
||||
#[repr(transparent)]
|
||||
pub struct DataPlaneResourceId(u64);
|
||||
|
||||
impl DataPlaneResourceId {
|
||||
pub fn from_raw(value: u64) -> Option<Self> {
|
||||
(value != 0).then_some(Self(value))
|
||||
}
|
||||
|
||||
pub fn get(self) -> u64 {
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
#[repr(u16)]
|
||||
pub enum DataPlaneOperationKind {
|
||||
TcpConnect = 1,
|
||||
TcpBind = 2,
|
||||
TcpAccept = 3,
|
||||
TcpRead = 4,
|
||||
TcpWrite = 5,
|
||||
UdpBind = 6,
|
||||
UdpReceive = 7,
|
||||
UdpSend = 8,
|
||||
TcpShutdownWrite = 9,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum DataPlaneCompletionStatus {
|
||||
Success,
|
||||
Error(DataPlaneErrorKind),
|
||||
}
|
||||
|
||||
impl DataPlaneCompletionStatus {
|
||||
pub fn code(self) -> u16 {
|
||||
match self {
|
||||
Self::Success => 0,
|
||||
Self::Error(kind) => kind as u16,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct DataPlaneCompletionDescriptor {
|
||||
pub operation_id: DataPlaneOperationId,
|
||||
pub kind: DataPlaneOperationKind,
|
||||
pub status: DataPlaneCompletionStatus,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum DataPlaneOperationResult {
|
||||
TcpConnected {
|
||||
stream: DataPlaneResourceId,
|
||||
local_addr: SocketAddr,
|
||||
peer_addr: SocketAddr,
|
||||
},
|
||||
TcpBound {
|
||||
listener: DataPlaneResourceId,
|
||||
local_addr: SocketAddr,
|
||||
},
|
||||
TcpAccepted {
|
||||
stream: DataPlaneResourceId,
|
||||
local_addr: SocketAddr,
|
||||
peer_addr: SocketAddr,
|
||||
},
|
||||
TcpRead {
|
||||
data: Vec<u8>,
|
||||
eof: bool,
|
||||
},
|
||||
TcpWritten {
|
||||
len: usize,
|
||||
},
|
||||
TcpWriteShutdown,
|
||||
UdpBound {
|
||||
socket: DataPlaneResourceId,
|
||||
local_addr: SocketAddr,
|
||||
},
|
||||
UdpReceived {
|
||||
data: Vec<u8>,
|
||||
peer_addr: SocketAddr,
|
||||
truncated: bool,
|
||||
},
|
||||
UdpSent {
|
||||
len: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl DataPlaneOperationResult {
|
||||
pub(super) fn retained_bytes(&self) -> usize {
|
||||
match self {
|
||||
Self::TcpRead { data, .. } | Self::UdpReceived { data, .. } => data.capacity(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn payload_bytes(&self) -> usize {
|
||||
match self {
|
||||
Self::TcpRead { data, .. } | Self::UdpReceived { data, .. } => data.len(),
|
||||
_ => 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn created_resource(&self) -> Option<DataPlaneResourceId> {
|
||||
match self {
|
||||
Self::TcpConnected { stream, .. } | Self::TcpAccepted { stream, .. } => Some(*stream),
|
||||
Self::TcpBound { listener, .. } => Some(*listener),
|
||||
Self::UdpBound { socket, .. } => Some(*socket),
|
||||
Self::TcpRead { .. }
|
||||
| Self::TcpWritten { .. }
|
||||
| Self::TcpWriteShutdown
|
||||
| Self::UdpReceived { .. }
|
||||
| Self::UdpSent { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type DataPlaneOperationOutcome = Result<DataPlaneOperationResult, DataPlaneErrorKind>;
|
||||
@@ -0,0 +1,394 @@
|
||||
//! Peer-packet classification for registered data-plane flows.
|
||||
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
use smoltcp::wire::{IPV4_HEADER_LEN, IpProtocol, Ipv4Packet, TcpPacket, UdpPacket};
|
||||
|
||||
use crate::{
|
||||
gateway::proxy::ip_reassembler::IpReassembler,
|
||||
packet::{PacketType, ZCPacket},
|
||||
};
|
||||
|
||||
use super::flow::{FlowKey, FlowKind, FlowTable};
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
enum ClassifiedPeerPacket {
|
||||
Tcp {
|
||||
entry: FlowKey,
|
||||
listen_entry: FlowKey,
|
||||
flags: u8,
|
||||
},
|
||||
Udp {
|
||||
entry: FlowKey,
|
||||
},
|
||||
FragmentedUdp {
|
||||
source: Ipv4Addr,
|
||||
},
|
||||
Unsupported,
|
||||
}
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum PeerPacketRoute {
|
||||
Pass,
|
||||
Unmatched {
|
||||
entry: FlowKey,
|
||||
tcp_flags: Option<u8>,
|
||||
},
|
||||
Deliver {
|
||||
entry: FlowKey,
|
||||
tcp_flags: Option<u8>,
|
||||
},
|
||||
FragmentedUdp {
|
||||
source: Ipv4Addr,
|
||||
mirror: bool,
|
||||
},
|
||||
}
|
||||
fn classify_peer_ipv4_payload(payload: &[u8]) -> ClassifiedPeerPacket {
|
||||
let Ok(ipv4) = Ipv4Packet::new_checked(payload) else {
|
||||
return ClassifiedPeerPacket::Unsupported;
|
||||
};
|
||||
if ipv4.version() != 4 || usize::from(ipv4.header_len()) < IPV4_HEADER_LEN {
|
||||
return ClassifiedPeerPacket::Unsupported;
|
||||
}
|
||||
|
||||
match ipv4.next_header() {
|
||||
IpProtocol::Tcp => {
|
||||
let Ok(tcp) = TcpPacket::new_checked(ipv4.payload()) else {
|
||||
return ClassifiedPeerPacket::Unsupported;
|
||||
};
|
||||
let entry = FlowKey {
|
||||
dst: SocketAddr::new(ipv4.src_addr().into(), tcp.src_port()),
|
||||
src: SocketAddr::new(ipv4.dst_addr().into(), tcp.dst_port()),
|
||||
kind: FlowKind::Tcp,
|
||||
};
|
||||
let listen_entry = FlowKey {
|
||||
src: entry.src,
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||
kind: FlowKind::TcpListen,
|
||||
};
|
||||
ClassifiedPeerPacket::Tcp {
|
||||
entry,
|
||||
listen_entry,
|
||||
flags: tcp_flags(&tcp),
|
||||
}
|
||||
}
|
||||
IpProtocol::Udp => {
|
||||
if IpReassembler::is_packet_fragmented(&ipv4) {
|
||||
return ClassifiedPeerPacket::FragmentedUdp {
|
||||
source: ipv4.src_addr(),
|
||||
};
|
||||
}
|
||||
let Ok(udp) = UdpPacket::new_checked(ipv4.payload()) else {
|
||||
return ClassifiedPeerPacket::Unsupported;
|
||||
};
|
||||
ClassifiedPeerPacket::Udp {
|
||||
entry: FlowKey {
|
||||
dst: SocketAddr::new(ipv4.src_addr().into(), udp.src_port()),
|
||||
src: SocketAddr::new(ipv4.dst_addr().into(), udp.dst_port()),
|
||||
kind: FlowKind::Udp,
|
||||
},
|
||||
}
|
||||
}
|
||||
_ => ClassifiedPeerPacket::Unsupported,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn tcp_flags<T: AsRef<[u8]>>(tcp: &TcpPacket<T>) -> u8 {
|
||||
u8::from(tcp.fin())
|
||||
| (u8::from(tcp.syn()) << 1)
|
||||
| (u8::from(tcp.rst()) << 2)
|
||||
| (u8::from(tcp.psh()) << 3)
|
||||
| (u8::from(tcp.ack()) << 4)
|
||||
| (u8::from(tcp.urg()) << 5)
|
||||
| (u8::from(tcp.ece()) << 6)
|
||||
| (u8::from(tcp.cwr()) << 7)
|
||||
}
|
||||
impl<V> FlowTable<V> {
|
||||
pub fn route_peer_packet(
|
||||
&self,
|
||||
packet: &ZCPacket,
|
||||
allow_tcp_listen_fallback: bool,
|
||||
) -> PeerPacketRoute {
|
||||
let Some(header) = packet.peer_manager_header() else {
|
||||
return PeerPacketRoute::Pass;
|
||||
};
|
||||
let is_modified_source = matches!(
|
||||
header.packet_type,
|
||||
x if x == PacketType::DataWithKcpSrcModified as u8
|
||||
|| x == PacketType::DataWithQuicSrcModified as u8
|
||||
);
|
||||
if header.packet_type != PacketType::Data as u8 && !is_modified_source {
|
||||
return PeerPacketRoute::Pass;
|
||||
}
|
||||
if is_modified_source && header.from_peer_id != header.to_peer_id {
|
||||
return PeerPacketRoute::Pass;
|
||||
}
|
||||
|
||||
self.route_peer_ipv4_payload(packet.payload(), allow_tcp_listen_fallback)
|
||||
}
|
||||
|
||||
pub fn route_peer_ipv4_payload(
|
||||
&self,
|
||||
payload: &[u8],
|
||||
allow_tcp_listen_fallback: bool,
|
||||
) -> PeerPacketRoute {
|
||||
let (entry, tcp_flags) = match classify_peer_ipv4_payload(payload) {
|
||||
ClassifiedPeerPacket::Tcp {
|
||||
entry,
|
||||
listen_entry,
|
||||
flags,
|
||||
} => {
|
||||
let entry = if allow_tcp_listen_fallback && !self.contains_key(&entry) {
|
||||
listen_entry
|
||||
} else {
|
||||
entry
|
||||
};
|
||||
(entry, Some(flags))
|
||||
}
|
||||
ClassifiedPeerPacket::Udp { entry } => (entry, None),
|
||||
ClassifiedPeerPacket::FragmentedUdp { source } => {
|
||||
return PeerPacketRoute::FragmentedUdp {
|
||||
source,
|
||||
mirror: self.contains_destination_ip(source.into()),
|
||||
};
|
||||
}
|
||||
ClassifiedPeerPacket::Unsupported => return PeerPacketRoute::Pass,
|
||||
};
|
||||
|
||||
if self.contains_key(&entry) {
|
||||
PeerPacketRoute::Deliver { entry, tcp_flags }
|
||||
} else {
|
||||
PeerPacketRoute::Unmatched { entry, tcp_flags }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
use super::*;
|
||||
use crate::packet::{PacketType, ZCPacket};
|
||||
|
||||
const TCP_SYN: u8 = 0x02;
|
||||
|
||||
fn ipv4_packet(protocol: IpProtocol, payload_len: usize) -> Vec<u8> {
|
||||
let mut packet = vec![0; 20 + payload_len];
|
||||
let packet_len = packet.len() as u16;
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut packet);
|
||||
ipv4.set_version(4);
|
||||
ipv4.set_header_len(20);
|
||||
ipv4.set_total_len(packet_len);
|
||||
ipv4.set_src_addr(Ipv4Addr::new(10, 1, 1, 2));
|
||||
ipv4.set_dst_addr(Ipv4Addr::new(10, 2, 2, 3));
|
||||
ipv4.set_next_header(protocol);
|
||||
packet
|
||||
}
|
||||
#[test]
|
||||
fn classifies_tcp_and_listen_keys() {
|
||||
let mut packet = ipv4_packet(IpProtocol::Tcp, 20);
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut packet);
|
||||
let mut tcp = TcpPacket::new_unchecked(ipv4.payload_mut());
|
||||
tcp.set_src_port(1234);
|
||||
tcp.set_dst_port(4321);
|
||||
tcp.set_header_len(20);
|
||||
tcp.set_syn(true);
|
||||
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&packet),
|
||||
ClassifiedPeerPacket::Tcp {
|
||||
entry: FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: "10.1.1.2:1234".parse().unwrap(),
|
||||
kind: FlowKind::Tcp,
|
||||
},
|
||||
listen_entry: FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||
kind: FlowKind::TcpListen,
|
||||
},
|
||||
flags: TCP_SYN,
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn classifies_udp_and_fragmented_udp() {
|
||||
let mut packet = ipv4_packet(IpProtocol::Udp, 8);
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut packet);
|
||||
let mut udp = UdpPacket::new_unchecked(ipv4.payload_mut());
|
||||
udp.set_src_port(1234);
|
||||
udp.set_dst_port(4321);
|
||||
udp.set_len(8);
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&packet),
|
||||
ClassifiedPeerPacket::Udp {
|
||||
entry: FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: "10.1.1.2:1234".parse().unwrap(),
|
||||
kind: FlowKind::Udp,
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
let mut fragmented = ipv4_packet(IpProtocol::Udp, 8);
|
||||
Ipv4Packet::new_unchecked(&mut fragmented).set_frag_offset(8);
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&fragmented),
|
||||
ClassifiedPeerPacket::FragmentedUdp {
|
||||
source: Ipv4Addr::new(10, 1, 1, 2),
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn rejects_malformed_and_unsupported_packets() {
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&[]),
|
||||
ClassifiedPeerPacket::Unsupported
|
||||
);
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&ipv4_packet(IpProtocol::Icmp, 8)),
|
||||
ClassifiedPeerPacket::Unsupported
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_ipv4_header_shorter_than_minimum() {
|
||||
let mut packet = ipv4_packet(IpProtocol::Tcp, 20);
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut packet);
|
||||
ipv4.set_header_len(16);
|
||||
let mut tcp = TcpPacket::new_unchecked(ipv4.payload_mut());
|
||||
tcp.set_src_port(1234);
|
||||
tcp.set_dst_port(4321);
|
||||
tcp.set_header_len(20);
|
||||
|
||||
assert_eq!(
|
||||
classify_peer_ipv4_payload(&packet),
|
||||
ClassifiedPeerPacket::Unsupported
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn flow_table_routes_tcp_exact_and_listen_fallback() {
|
||||
let mut packet = ipv4_packet(IpProtocol::Tcp, 20);
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut packet);
|
||||
let mut tcp = TcpPacket::new_unchecked(ipv4.payload_mut());
|
||||
tcp.set_src_port(1234);
|
||||
tcp.set_dst_port(4321);
|
||||
tcp.set_header_len(20);
|
||||
tcp.set_syn(true);
|
||||
|
||||
let exact = FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: "10.1.1.2:1234".parse().unwrap(),
|
||||
kind: FlowKind::Tcp,
|
||||
};
|
||||
let listen = FlowKey {
|
||||
src: exact.src,
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||
kind: FlowKind::TcpListen,
|
||||
};
|
||||
let table = FlowTable::default();
|
||||
|
||||
assert_eq!(
|
||||
table.route_peer_ipv4_payload(&packet, false),
|
||||
PeerPacketRoute::Unmatched {
|
||||
entry: exact.clone(),
|
||||
tcp_flags: Some(TCP_SYN),
|
||||
}
|
||||
);
|
||||
|
||||
table.insert(listen.clone(), ());
|
||||
assert_eq!(
|
||||
table.route_peer_ipv4_payload(&packet, true),
|
||||
PeerPacketRoute::Deliver {
|
||||
entry: listen,
|
||||
tcp_flags: Some(TCP_SYN),
|
||||
}
|
||||
);
|
||||
|
||||
table.insert(exact.clone(), ());
|
||||
assert_eq!(
|
||||
table.route_peer_ipv4_payload(&packet, true),
|
||||
PeerPacketRoute::Deliver {
|
||||
entry: exact,
|
||||
tcp_flags: Some(TCP_SYN),
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn flow_table_routes_fragmented_udp_by_source_ip() {
|
||||
let mut packet = ipv4_packet(IpProtocol::Udp, 8);
|
||||
Ipv4Packet::new_unchecked(&mut packet).set_frag_offset(8);
|
||||
let table = FlowTable::default();
|
||||
|
||||
assert_eq!(
|
||||
table.route_peer_ipv4_payload(&packet, false),
|
||||
PeerPacketRoute::FragmentedUdp {
|
||||
source: Ipv4Addr::new(10, 1, 1, 2),
|
||||
mirror: false,
|
||||
}
|
||||
);
|
||||
|
||||
table.insert(
|
||||
FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: "10.1.1.2:1234".parse().unwrap(),
|
||||
kind: FlowKind::Udp,
|
||||
},
|
||||
(),
|
||||
);
|
||||
assert_eq!(
|
||||
table.route_peer_ipv4_payload(&packet, false),
|
||||
PeerPacketRoute::FragmentedUdp {
|
||||
source: Ipv4Addr::new(10, 1, 1, 2),
|
||||
mirror: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn flow_table_routes_loopback_modified_source_packets() {
|
||||
let mut payload = ipv4_packet(IpProtocol::Tcp, 20);
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut payload);
|
||||
let mut tcp = TcpPacket::new_unchecked(ipv4.payload_mut());
|
||||
tcp.set_src_port(1234);
|
||||
tcp.set_dst_port(4321);
|
||||
tcp.set_header_len(20);
|
||||
let entry = FlowKey {
|
||||
src: "10.2.2.3:4321".parse().unwrap(),
|
||||
dst: "10.1.1.2:1234".parse().unwrap(),
|
||||
kind: FlowKind::Tcp,
|
||||
};
|
||||
let table = FlowTable::default();
|
||||
table.insert(entry.clone(), ());
|
||||
|
||||
for packet_type in [
|
||||
PacketType::DataWithKcpSrcModified,
|
||||
PacketType::DataWithQuicSrcModified,
|
||||
] {
|
||||
let mut packet = ZCPacket::new_with_payload(&payload);
|
||||
packet.fill_peer_manager_hdr(7, 7, packet_type as u8);
|
||||
assert_eq!(
|
||||
table.route_peer_packet(&packet, false),
|
||||
PeerPacketRoute::Deliver {
|
||||
entry: entry.clone(),
|
||||
tcp_flags: Some(0),
|
||||
}
|
||||
);
|
||||
}
|
||||
}
|
||||
#[test]
|
||||
fn flow_table_passes_non_loopback_or_malformed_modified_source_packets() {
|
||||
let table = FlowTable::<()>::default();
|
||||
let mut non_loopback = ZCPacket::new_with_payload(&ipv4_packet(IpProtocol::Tcp, 20));
|
||||
non_loopback.fill_peer_manager_hdr(7, 8, PacketType::DataWithKcpSrcModified as u8);
|
||||
assert_eq!(
|
||||
table.route_peer_packet(&non_loopback, false),
|
||||
PeerPacketRoute::Pass
|
||||
);
|
||||
|
||||
let mut malformed = ZCPacket::new_with_payload(&[0u8; 8]);
|
||||
malformed.fill_peer_manager_hdr(7, 7, PacketType::DataWithQuicSrcModified as u8);
|
||||
assert_eq!(
|
||||
table.route_peer_packet(&malformed, false),
|
||||
PeerPacketRoute::Pass
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
//! Shared lifetime and close guards held by data-plane resources.
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use super::{DataPlaneError, DataPlaneErrorKind, DataPlaneResult};
|
||||
|
||||
pub(super) struct DataPlaneLease {
|
||||
consumers: Arc<DataPlaneConsumers>,
|
||||
}
|
||||
|
||||
pub(super) struct DataPlaneConsumers {
|
||||
refs: Mutex<usize>,
|
||||
notifier: Notify,
|
||||
}
|
||||
|
||||
pub(crate) struct DataPlaneConsumerLease {
|
||||
_lease: DataPlaneLease,
|
||||
}
|
||||
|
||||
impl DataPlaneConsumerLease {
|
||||
pub(super) fn new(lease: DataPlaneLease) -> Self {
|
||||
Self { _lease: lease }
|
||||
}
|
||||
}
|
||||
|
||||
impl DataPlaneLease {
|
||||
pub(super) fn acquire(consumers: Arc<DataPlaneConsumers>) -> Self {
|
||||
consumers.acquire();
|
||||
Self { consumers }
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for DataPlaneLease {
|
||||
fn clone(&self) -> Self {
|
||||
self.consumers.clone_ref();
|
||||
Self {
|
||||
consumers: self.consumers.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DataPlaneLease {
|
||||
fn drop(&mut self) {
|
||||
self.consumers.release();
|
||||
}
|
||||
}
|
||||
|
||||
impl DataPlaneConsumers {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
refs: Mutex::new(0),
|
||||
notifier: Notify::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn has_consumers(&self) -> bool {
|
||||
*self.refs.lock().unwrap() != 0
|
||||
}
|
||||
|
||||
pub(super) async fn changed(&self) {
|
||||
self.notifier.notified().await;
|
||||
}
|
||||
|
||||
fn acquire(&self) {
|
||||
let mut refs = self.refs.lock().unwrap();
|
||||
*refs = refs
|
||||
.checked_add(1)
|
||||
.expect("data-plane consumer reference count overflow");
|
||||
drop(refs);
|
||||
self.notifier.notify_one();
|
||||
}
|
||||
|
||||
fn clone_ref(&self) {
|
||||
let mut refs = self.refs.lock().unwrap();
|
||||
*refs = refs
|
||||
.checked_add(1)
|
||||
.expect("data-plane consumer reference count overflow");
|
||||
}
|
||||
|
||||
fn release(&self) {
|
||||
let mut refs = self.refs.lock().unwrap();
|
||||
debug_assert_ne!(*refs, 0);
|
||||
*refs -= 1;
|
||||
let final_ref = *refs == 0;
|
||||
drop(refs);
|
||||
if final_ref {
|
||||
self.notifier.notify_one();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct DataPlaneIoGuard {
|
||||
closed: CancellationToken,
|
||||
close_kind: Arc<AtomicCell<Option<DataPlaneErrorKind>>>,
|
||||
}
|
||||
|
||||
impl DataPlaneIoGuard {
|
||||
pub(super) fn new() -> Self {
|
||||
Self {
|
||||
closed: CancellationToken::new(),
|
||||
close_kind: Arc::new(AtomicCell::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn ensure_open(&self) -> DataPlaneResult<()> {
|
||||
if self.closed.is_cancelled() {
|
||||
return Err(self.closed_error());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn is_closed(&self) -> bool {
|
||||
self.closed.is_cancelled()
|
||||
}
|
||||
|
||||
pub(super) async fn closed(&self) {
|
||||
self.closed.cancelled().await;
|
||||
}
|
||||
|
||||
pub(super) async fn while_open<T>(
|
||||
&self,
|
||||
future: impl Future<Output = DataPlaneResult<T>>,
|
||||
) -> DataPlaneResult<T> {
|
||||
self.ensure_open()?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.closed() => Err(self.closed_error()),
|
||||
result = future => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn closed_future(&self) -> Pin<Box<dyn Future<Output = ()> + Send>> {
|
||||
let closed = self.closed.clone();
|
||||
Box::pin(async move {
|
||||
closed.cancelled().await;
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn close(&self, kind: DataPlaneErrorKind) {
|
||||
if self.close_kind.compare_exchange(None, Some(kind)).is_ok() {
|
||||
self.closed.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn closed_error(&self) -> DataPlaneError {
|
||||
let kind = self
|
||||
.close_kind
|
||||
.load()
|
||||
.unwrap_or(DataPlaneErrorKind::HandleClosed);
|
||||
DataPlaneError::new(kind, "data-plane I/O resource closed")
|
||||
}
|
||||
|
||||
pub(super) fn closed_io_error(&self) -> std::io::Error {
|
||||
self.closed_error().into_io_error()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
//! Pure route selection for TCP data-plane connections.
|
||||
|
||||
use super::{DataPlaneError, DataPlaneErrorKind, DataPlaneResult};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum DataPlaneRoutePolicy {
|
||||
OverlayOnly,
|
||||
OverlayOrDirect,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum DataPlaneTransportPreference {
|
||||
SmoltcpOnly,
|
||||
PreferKcp,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(super) enum DataPlaneTcpRoute {
|
||||
LocalEndpoint,
|
||||
LocalHost,
|
||||
Smoltcp,
|
||||
Kcp,
|
||||
Direct,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct DataPlaneTcpRouteInput {
|
||||
pub policy: DataPlaneRoutePolicy,
|
||||
pub transport: DataPlaneTransportPreference,
|
||||
pub local_endpoint: bool,
|
||||
pub local_virtual_destination: bool,
|
||||
pub overlay_destination: bool,
|
||||
pub smoltcp_ready: bool,
|
||||
pub kcp_ready: bool,
|
||||
pub kcp_allowed: bool,
|
||||
}
|
||||
|
||||
impl DataPlaneTcpRouteInput {
|
||||
pub(super) fn select(self) -> DataPlaneResult<DataPlaneTcpRoute> {
|
||||
if self.local_endpoint {
|
||||
return self
|
||||
.smoltcp_ready
|
||||
.then_some(DataPlaneTcpRoute::LocalEndpoint)
|
||||
.ok_or_else(path_not_ready);
|
||||
}
|
||||
if self.local_virtual_destination {
|
||||
return Ok(DataPlaneTcpRoute::LocalHost);
|
||||
}
|
||||
if self.overlay_destination {
|
||||
if self.transport == DataPlaneTransportPreference::PreferKcp
|
||||
&& self.kcp_ready
|
||||
&& self.kcp_allowed
|
||||
{
|
||||
return Ok(DataPlaneTcpRoute::Kcp);
|
||||
}
|
||||
return self
|
||||
.smoltcp_ready
|
||||
.then_some(DataPlaneTcpRoute::Smoltcp)
|
||||
.ok_or_else(path_not_ready);
|
||||
}
|
||||
if self.policy == DataPlaneRoutePolicy::OverlayOrDirect {
|
||||
return Ok(DataPlaneTcpRoute::Direct);
|
||||
}
|
||||
Err(DataPlaneError::new(
|
||||
DataPlaneErrorKind::NoOverlayRoute,
|
||||
"destination has no EasyTier overlay route",
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
fn path_not_ready() -> DataPlaneError {
|
||||
DataPlaneError::new(
|
||||
DataPlaneErrorKind::PathNotReady,
|
||||
"selected EasyTier data-plane path is not ready",
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn overlay() -> DataPlaneTcpRouteInput {
|
||||
DataPlaneTcpRouteInput {
|
||||
policy: DataPlaneRoutePolicy::OverlayOnly,
|
||||
transport: DataPlaneTransportPreference::SmoltcpOnly,
|
||||
local_endpoint: false,
|
||||
local_virtual_destination: false,
|
||||
overlay_destination: true,
|
||||
smoltcp_ready: true,
|
||||
kcp_ready: false,
|
||||
kcp_allowed: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlay_only_rejects_unrelated_destination() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
overlay_destination: false,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
input.select().unwrap_err().kind(),
|
||||
DataPlaneErrorKind::NoOverlayRoute
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_policy_can_select_direct_host_route() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
policy: DataPlaneRoutePolicy::OverlayOrDirect,
|
||||
overlay_destination: false,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(input.select().unwrap(), DataPlaneTcpRoute::Direct);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn smoltcp_only_ignores_available_kcp() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
kcp_ready: true,
|
||||
kcp_allowed: true,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(input.select().unwrap(), DataPlaneTcpRoute::Smoltcp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gateway_preference_selects_allowed_ready_kcp() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
transport: DataPlaneTransportPreference::PreferKcp,
|
||||
kcp_ready: true,
|
||||
kcp_allowed: true,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(input.select().unwrap(), DataPlaneTcpRoute::Kcp);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn known_overlay_without_a_ready_path_is_not_direct() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
policy: DataPlaneRoutePolicy::OverlayOrDirect,
|
||||
smoltcp_ready: false,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
input.select().unwrap_err().kind(),
|
||||
DataPlaneErrorKind::PathNotReady
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn local_endpoint_precedes_local_host_mapping() {
|
||||
let input = DataPlaneTcpRouteInput {
|
||||
local_endpoint: true,
|
||||
local_virtual_destination: true,
|
||||
..overlay()
|
||||
};
|
||||
|
||||
assert_eq!(input.select().unwrap(), DataPlaneTcpRoute::LocalEndpoint);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
//! smoltcp stack generation and its peer-packet bridge.
|
||||
|
||||
use std::{
|
||||
net::IpAddr,
|
||||
sync::{Arc, Weak},
|
||||
};
|
||||
|
||||
use smoltcp::wire::Ipv4Packet;
|
||||
use tokio::{
|
||||
sync::{Mutex, mpsc},
|
||||
task::JoinSet,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
foundation::task::reap_joinset_background,
|
||||
gateway::smoltcp::{BufferSize, Net, NetConfig, channel_device},
|
||||
packet::ZCPacket,
|
||||
peers::peer_manager::PeerManagerCore,
|
||||
};
|
||||
|
||||
use super::{DataPlaneErrorKind, DataPlaneIoGuard};
|
||||
|
||||
pub(super) struct SmoltcpPlane {
|
||||
pub(super) ipv4_addr: cidr::Ipv4Inet,
|
||||
pub(super) net: Arc<Net>,
|
||||
generation: DataPlaneIoGuard,
|
||||
_forward_tasks: Arc<std::sync::Mutex<JoinSet<()>>>,
|
||||
}
|
||||
|
||||
impl SmoltcpPlane {
|
||||
pub(super) fn new(
|
||||
ipv4_addr: cidr::Ipv4Inet,
|
||||
peer_manager: Weak<PeerManagerCore>,
|
||||
packet_recv: Arc<Mutex<mpsc::Receiver<ZCPacket>>>,
|
||||
) -> Self {
|
||||
let mut forward_tasks = JoinSet::new();
|
||||
let mut capabilities = smoltcp::phy::DeviceCapabilities::default();
|
||||
// Fragment offsets are expressed in eight-byte units.
|
||||
capabilities.max_transmission_unit = 1284;
|
||||
capabilities.medium = smoltcp::phy::Medium::Ip;
|
||||
let (device, stack_sink, mut stack_stream) =
|
||||
channel_device::ChannelDevice::new(capabilities);
|
||||
|
||||
forward_tasks.spawn(async move {
|
||||
let mut packet_recv = packet_recv.lock().await;
|
||||
while let Some(packet) = packet_recv.recv().await {
|
||||
tracing::trace!(?packet, "deliver peer packet to smoltcp");
|
||||
if let Err(error) = stack_sink.send(Ok(packet.payload().to_vec())).await {
|
||||
tracing::error!(?error, "deliver peer packet to smoltcp failed");
|
||||
}
|
||||
}
|
||||
tracing::debug!("peer-to-smoltcp bridge stopped");
|
||||
});
|
||||
|
||||
forward_tasks.spawn(async move {
|
||||
while let Some(data) = stack_stream.recv().await {
|
||||
let Ok(ipv4) = Ipv4Packet::new_checked(&data) else {
|
||||
tracing::error!(?data, "smoltcp emitted a non-IPv4 packet");
|
||||
continue;
|
||||
};
|
||||
let destination = ipv4.dst_addr();
|
||||
let Some(peer_manager) = peer_manager.upgrade() else {
|
||||
tracing::debug!("smoltcp-to-peer bridge lost PeerManager");
|
||||
return;
|
||||
};
|
||||
if let Err(error) = peer_manager
|
||||
.send_msg_by_ip(
|
||||
ZCPacket::new_with_payload(&data),
|
||||
IpAddr::V4(destination),
|
||||
false,
|
||||
)
|
||||
.await
|
||||
{
|
||||
tracing::error!(?error, "deliver smoltcp packet to peer failed");
|
||||
}
|
||||
}
|
||||
tracing::debug!("smoltcp-to-peer bridge stopped");
|
||||
});
|
||||
|
||||
let interface_config = smoltcp::iface::Config::new(smoltcp::wire::HardwareAddress::Ip);
|
||||
let net = Net::new(
|
||||
device,
|
||||
NetConfig::new(
|
||||
interface_config,
|
||||
format!("{}/{}", ipv4_addr.address(), ipv4_addr.network_length())
|
||||
.parse()
|
||||
.expect("validated IPv4 prefix"),
|
||||
vec![
|
||||
ipv4_addr
|
||||
.address()
|
||||
.to_string()
|
||||
.parse()
|
||||
.expect("validated IPv4 address"),
|
||||
],
|
||||
Some(BufferSize {
|
||||
tcp_rx_size: 1024 * 128,
|
||||
tcp_tx_size: 1024 * 128,
|
||||
udp_rx_size: 1024 * 128,
|
||||
udp_tx_size: 1024 * 128,
|
||||
udp_rx_meta_size: 128,
|
||||
udp_tx_meta_size: 128,
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
let forward_tasks = Arc::new(std::sync::Mutex::new(forward_tasks));
|
||||
forward_tasks.lock().unwrap().spawn(reap_joinset_background(
|
||||
Arc::downgrade(&forward_tasks),
|
||||
"SmoltcpPlane",
|
||||
));
|
||||
|
||||
Self {
|
||||
ipv4_addr,
|
||||
net: Arc::new(net),
|
||||
generation: DataPlaneIoGuard::new(),
|
||||
_forward_tasks: forward_tasks,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn lease(&self) -> DataPlaneIoGuard {
|
||||
self.generation.clone()
|
||||
}
|
||||
|
||||
pub(super) fn close(&self, kind: DataPlaneErrorKind) {
|
||||
self.generation.close(kind);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SmoltcpPlane {
|
||||
fn drop(&mut self) {
|
||||
self.close(DataPlaneErrorKind::HandleClosed);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
//! TCP stream and listener resources exposed by the data plane.
|
||||
|
||||
use std::{
|
||||
future::Future,
|
||||
net::SocketAddr,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use crate::gateway::smoltcp::TcpListener;
|
||||
|
||||
use super::{
|
||||
DataPlaneIoGuard, DataPlaneLease, DataPlaneTcpIo, FlowData, FlowKey, FlowLease, FlowSet,
|
||||
TCP_ENTRY,
|
||||
};
|
||||
|
||||
/// Tracks how an established stream keeps its inbound flow alive.
|
||||
pub(super) enum DataPlaneTcpStreamRoute {
|
||||
Outbound { _flow: FlowLease<FlowData> },
|
||||
Accepted { _flow: FlowLease<FlowData> },
|
||||
External,
|
||||
}
|
||||
|
||||
/// A TCP stream created by the data-plane API.
|
||||
pub struct DataPlaneTcpStream {
|
||||
pub(super) stream: DataPlaneTcpIo,
|
||||
pub(super) local_addr: SocketAddr,
|
||||
pub(super) _route: DataPlaneTcpStreamRoute,
|
||||
pub(super) _data_plane_lease: Option<DataPlaneLease>,
|
||||
generation: DataPlaneIoGuard,
|
||||
read_closed: Pin<Box<dyn Future<Output = ()> + Send>>,
|
||||
write_closed: Pin<Box<dyn Future<Output = ()> + Send>>,
|
||||
}
|
||||
|
||||
/// A TCP listener created by the data-plane API.
|
||||
pub struct DataPlaneTcpListener {
|
||||
pub(super) listener: TcpListener,
|
||||
pub(super) local_addr: SocketAddr,
|
||||
pub(super) flows: FlowSet,
|
||||
pub(super) _listen_flow: FlowLease<FlowData>,
|
||||
pub(super) data_plane_lease: DataPlaneLease,
|
||||
pub(super) generation: DataPlaneIoGuard,
|
||||
}
|
||||
|
||||
impl DataPlaneTcpStream {
|
||||
pub(super) fn new(
|
||||
stream: DataPlaneTcpIo,
|
||||
local_addr: SocketAddr,
|
||||
data_plane_lease: Option<DataPlaneLease>,
|
||||
route: DataPlaneTcpStreamRoute,
|
||||
generation: DataPlaneIoGuard,
|
||||
) -> Self {
|
||||
Self {
|
||||
stream,
|
||||
local_addr,
|
||||
_data_plane_lease: data_plane_lease,
|
||||
_route: route,
|
||||
read_closed: generation.closed_future(),
|
||||
write_closed: generation.closed_future(),
|
||||
generation,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.local_addr
|
||||
}
|
||||
}
|
||||
|
||||
impl DataPlaneTcpListener {
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.local_addr
|
||||
}
|
||||
|
||||
pub async fn accept(&mut self) -> Result<(DataPlaneTcpStream, SocketAddr), std::io::Error> {
|
||||
self.generation
|
||||
.ensure_open()
|
||||
.map_err(|error| error.into_io_error())?;
|
||||
let generation = self.generation.clone();
|
||||
let (stream, peer_addr) = tokio::select! {
|
||||
biased;
|
||||
_ = generation.closed() => {
|
||||
return Err(generation.closed_io_error());
|
||||
}
|
||||
result = self.listener.accept() => result?,
|
||||
};
|
||||
generation
|
||||
.ensure_open()
|
||||
.map_err(|error| error.into_io_error())?;
|
||||
let local_addr = stream.local_addr()?;
|
||||
let (flow, _) = FlowLease::register(
|
||||
self.flows.clone(),
|
||||
FlowKey {
|
||||
src: local_addr,
|
||||
dst: peer_addr,
|
||||
kind: TCP_ENTRY,
|
||||
},
|
||||
FlowData::DataPlaneRoute,
|
||||
);
|
||||
let accepted = DataPlaneTcpStream::new(
|
||||
Box::new(stream),
|
||||
local_addr,
|
||||
Some(self.data_plane_lease.clone()),
|
||||
DataPlaneTcpStreamRoute::Accepted { _flow: flow },
|
||||
generation,
|
||||
);
|
||||
Ok((accepted, peer_addr))
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncRead for DataPlaneTcpStream {
|
||||
fn poll_read(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &mut tokio::io::ReadBuf<'_>,
|
||||
) -> Poll<std::io::Result<()>> {
|
||||
let this = self.get_mut();
|
||||
if this.generation.ensure_open().is_err() || this.read_closed.as_mut().poll(cx).is_ready() {
|
||||
return Poll::Ready(Err(this.generation.closed_io_error()));
|
||||
}
|
||||
Pin::new(&mut this.stream).poll_read(cx, buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl AsyncWrite for DataPlaneTcpStream {
|
||||
fn poll_write(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
buf: &[u8],
|
||||
) -> Poll<Result<usize, std::io::Error>> {
|
||||
let this = self.get_mut();
|
||||
if this.generation.ensure_open().is_err() || this.write_closed.as_mut().poll(cx).is_ready()
|
||||
{
|
||||
return Poll::Ready(Err(this.generation.closed_io_error()));
|
||||
}
|
||||
Pin::new(&mut this.stream).poll_write(cx, buf)
|
||||
}
|
||||
|
||||
fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), std::io::Error>> {
|
||||
let this = self.get_mut();
|
||||
if this.generation.ensure_open().is_err() || this.write_closed.as_mut().poll(cx).is_ready()
|
||||
{
|
||||
return Poll::Ready(Err(this.generation.closed_io_error()));
|
||||
}
|
||||
Pin::new(&mut this.stream).poll_flush(cx)
|
||||
}
|
||||
|
||||
fn poll_shutdown(
|
||||
self: Pin<&mut Self>,
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Result<(), std::io::Error>> {
|
||||
let this = self.get_mut();
|
||||
if this.generation.ensure_open().is_err() || this.write_closed.as_mut().poll(cx).is_ready()
|
||||
{
|
||||
return Poll::Ready(Err(this.generation.closed_io_error()));
|
||||
}
|
||||
Pin::new(&mut this.stream).poll_shutdown(cx)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,943 @@
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
|
||||
use smoltcp::wire::{IpAddress, IpProtocol, Ipv4Packet, TcpPacket};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
|
||||
use super::*;
|
||||
use crate::{
|
||||
config::peers::PeerRuntimeSnapshot,
|
||||
config::{IpPrefix, NetworkIdentity},
|
||||
host::{
|
||||
packet::{HostPacketReceiver, host_packet_channel},
|
||||
testkit::TestHost,
|
||||
},
|
||||
peers::peer_manager::PortablePeerManagerConfig,
|
||||
tunnel::ring::RingTunnelRegistry,
|
||||
};
|
||||
|
||||
fn test_gateway() -> Arc<DataPlaneRuntime<TestHost>> {
|
||||
let runtime_config = CoreRuntimeConfigStore::new(
|
||||
crate::config::runtime::CoreRuntimeConfig::default(),
|
||||
Arc::new(PeerRuntimeSnapshot::default()),
|
||||
);
|
||||
let host = Arc::new(TestHost::default());
|
||||
let (packet_sender, packet_recv) = mpsc::channel(16);
|
||||
Arc::new(DataPlaneRuntime {
|
||||
operation: Mutex::new(()),
|
||||
runtime_started: AtomicBool::new(false),
|
||||
runtime_guard: DataPlaneIoGuard::new(),
|
||||
runtime_config,
|
||||
peer_manager: Weak::new(),
|
||||
transport_proxy: None,
|
||||
host: host.clone(),
|
||||
socket_context: SocketContext::default(),
|
||||
runtime_tasks: Arc::new(std::sync::Mutex::new(JoinSet::new())),
|
||||
packet_sender,
|
||||
packet_recv: Arc::new(Mutex::new(packet_recv)),
|
||||
net: Arc::new(Mutex::new(None)),
|
||||
entries: Arc::new(FlowTable::default()),
|
||||
data_plane_consumers: Arc::new(DataPlaneConsumers::new()),
|
||||
data_plane_net_ready: tokio::sync::watch::channel(false).0,
|
||||
pipeline_guard: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
struct DataPlaneEndpoint {
|
||||
gateway: Arc<DataPlaneRuntime<TestHost>>,
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
_packet_receiver: HostPacketReceiver,
|
||||
ip: cidr::Ipv4Inet,
|
||||
}
|
||||
|
||||
fn data_plane_endpoint(host: Arc<TestHost>, ip: cidr::Ipv4Inet) -> DataPlaneEndpoint {
|
||||
const NETWORK_NAME: &str = "gateway-data-plane";
|
||||
|
||||
let mut runtime = PeerRuntimeSnapshot::default().runtime;
|
||||
runtime.core.node.peer_id = None;
|
||||
runtime.core.node.network_name = NETWORK_NAME.to_owned();
|
||||
runtime.core.routes.ipv4 = Some(
|
||||
IpPrefix::new(IpAddr::V4(ip.address()), ip.network_length())
|
||||
.expect("test IPv4 prefix should be valid"),
|
||||
);
|
||||
runtime.network_identity = NetworkIdentity {
|
||||
network_name: NETWORK_NAME.to_owned(),
|
||||
network_secret: Some("shared-secret".to_owned()),
|
||||
network_secret_digest: None,
|
||||
};
|
||||
let peer_config = PortablePeerManagerConfig::new(runtime);
|
||||
let runtime_config = CoreRuntimeConfigStore::new(
|
||||
crate::config::runtime::CoreRuntimeConfig::default(),
|
||||
Arc::new(peer_config.snapshot.clone()),
|
||||
);
|
||||
let (packet_sender, packet_receiver) = host_packet_channel();
|
||||
let peer_manager = Arc::new(
|
||||
PeerManagerCore::new_portable_for_test(peer_config, packet_sender)
|
||||
.expect("build portable peer manager"),
|
||||
);
|
||||
let gateway = DataPlaneRuntime::new(
|
||||
runtime_config,
|
||||
peer_manager.clone(),
|
||||
None,
|
||||
host,
|
||||
SocketContext::default(),
|
||||
);
|
||||
|
||||
DataPlaneEndpoint {
|
||||
gateway,
|
||||
peer_manager,
|
||||
_packet_receiver: packet_receiver,
|
||||
ip,
|
||||
}
|
||||
}
|
||||
|
||||
async fn setup_data_plane_pair() -> (DataPlaneEndpoint, DataPlaneEndpoint) {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let a = data_plane_endpoint(host.clone(), "10.126.126.1/24".parse().unwrap());
|
||||
let b = loop {
|
||||
let b = data_plane_endpoint(host.clone(), "10.126.126.2/24".parse().unwrap());
|
||||
if b.peer_manager.my_peer_id() != a.peer_manager.my_peer_id() {
|
||||
break b;
|
||||
}
|
||||
};
|
||||
|
||||
let (run_a, run_b) = tokio::join!(a.peer_manager.run(), b.peer_manager.run());
|
||||
run_a.unwrap();
|
||||
run_b.unwrap();
|
||||
let (start_a, start_b) = tokio::join!(a.gateway.start_runtime(), b.gateway.start_runtime());
|
||||
start_a.unwrap();
|
||||
start_b.unwrap();
|
||||
|
||||
let registry = Arc::new(RingTunnelRegistry::default());
|
||||
let listener_id = uuid::Uuid::new_v4();
|
||||
let mut listener = registry.bind(listener_id).unwrap();
|
||||
let client_tunnel = registry.connect(listener_id).unwrap().into_tunnel();
|
||||
let server_tunnel = listener.accept().await.unwrap().into_tunnel();
|
||||
let (client, server) = tokio::join!(
|
||||
b.peer_manager.add_client_tunnel(client_tunnel),
|
||||
a.peer_manager.add_tunnel_as_server(server_tunnel),
|
||||
);
|
||||
client.unwrap();
|
||||
server.unwrap();
|
||||
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if a.peer_manager
|
||||
.list_route_snapshots()
|
||||
.await
|
||||
.iter()
|
||||
.any(|route| {
|
||||
route.peer_id == b.peer_manager.my_peer_id()
|
||||
&& route.ipv4_addr == Some(b.ip.into())
|
||||
})
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("Ring peers did not exchange routes");
|
||||
|
||||
(a, b)
|
||||
}
|
||||
|
||||
async fn stop_data_plane_pair(a: &DataPlaneEndpoint, b: &DataPlaneEndpoint) {
|
||||
tokio::join!(a.gateway.stop_runtime(), b.gateway.stop_runtime());
|
||||
tokio::join!(
|
||||
a.peer_manager.clear_resources(),
|
||||
b.peer_manager.clear_resources()
|
||||
);
|
||||
}
|
||||
|
||||
async fn wait_for_session_completion(
|
||||
session: &DataPlaneSession<TestHost>,
|
||||
) -> DataPlaneCompletionDescriptor {
|
||||
tokio::time::timeout(Duration::from_secs(10), session.completion_notified())
|
||||
.await
|
||||
.expect("data-plane session completion timed out");
|
||||
let completions = session.drain_completions(1);
|
||||
assert_eq!(completions.len(), 1);
|
||||
completions[0]
|
||||
}
|
||||
|
||||
fn build_tcp_packet(src: SocketAddr, dst: SocketAddr) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; 40];
|
||||
let src_ip = match src.ip() {
|
||||
IpAddr::V4(ip) => ip,
|
||||
IpAddr::V6(_) => panic!("test only supports ipv4"),
|
||||
};
|
||||
let dst_ip = match dst.ip() {
|
||||
IpAddr::V4(ip) => ip,
|
||||
IpAddr::V6(_) => panic!("test only supports ipv4"),
|
||||
};
|
||||
|
||||
{
|
||||
let mut ip_packet = Ipv4Packet::new_unchecked(&mut buf);
|
||||
ip_packet.set_version(4);
|
||||
ip_packet.set_header_len(20);
|
||||
ip_packet.set_total_len(40);
|
||||
ip_packet.set_hop_limit(64);
|
||||
ip_packet.set_next_header(IpProtocol::Tcp);
|
||||
ip_packet.set_src_addr(src_ip);
|
||||
ip_packet.set_dst_addr(dst_ip);
|
||||
|
||||
let mut tcp_packet = TcpPacket::new_unchecked(ip_packet.payload_mut());
|
||||
tcp_packet.set_src_port(src.port());
|
||||
tcp_packet.set_dst_port(dst.port());
|
||||
tcp_packet.set_header_len(20);
|
||||
tcp_packet.set_syn(true);
|
||||
tcp_packet.set_ack(true);
|
||||
tcp_packet.set_window_len(65535);
|
||||
tcp_packet.fill_checksum(&IpAddress::Ipv4(src_ip), &IpAddress::Ipv4(dst_ip));
|
||||
|
||||
ip_packet.fill_checksum();
|
||||
}
|
||||
|
||||
buf
|
||||
}
|
||||
|
||||
fn build_udp_followup_fragment(src: Ipv4Addr, dst: Ipv4Addr) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; 28];
|
||||
{
|
||||
let mut ip_packet = Ipv4Packet::new_unchecked(&mut buf);
|
||||
ip_packet.set_version(4);
|
||||
ip_packet.set_header_len(20);
|
||||
ip_packet.set_total_len(28);
|
||||
ip_packet.set_hop_limit(64);
|
||||
ip_packet.set_next_header(IpProtocol::Udp);
|
||||
ip_packet.set_frag_offset(8);
|
||||
ip_packet.set_src_addr(src);
|
||||
ip_packet.set_dst_addr(dst);
|
||||
ip_packet
|
||||
.payload_mut()
|
||||
.copy_from_slice(&[0xde, 0xad, 0xbe, 0xef, 0xca, 0xfe, 0xba, 0xbe]);
|
||||
|
||||
ip_packet.fill_checksum();
|
||||
}
|
||||
|
||||
buf
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_tcp_pingpong() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let timeout = Duration::from_secs(10);
|
||||
let mut listener = b.gateway.data_plane_tcp_bind(0, timeout).await.unwrap();
|
||||
let listen_addr = SocketAddr::new(b.ip.address().into(), listener.local_addr().port());
|
||||
|
||||
let accept = tokio::spawn(async move {
|
||||
let (mut stream, _peer) = listener.accept().await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
stream.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
stream.write_all(b"pong").await.unwrap();
|
||||
stream.flush().await.unwrap();
|
||||
});
|
||||
|
||||
let mut client = a
|
||||
.gateway
|
||||
.data_plane_tcp_connect(listen_addr, timeout)
|
||||
.await
|
||||
.unwrap();
|
||||
client.write_all(b"ping").await.unwrap();
|
||||
client.flush().await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
client.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"pong");
|
||||
accept.await.unwrap();
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_sessions_complete_tcp_operations_end_to_end() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let session_a = DataPlaneSession::new(&a.gateway);
|
||||
let session_b = DataPlaneSession::new(&b.gateway);
|
||||
session_a.start().unwrap();
|
||||
session_b.start().unwrap();
|
||||
|
||||
let bind = session_b
|
||||
.submit_tcp_bind(0, Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
let completion = wait_for_session_completion(&session_b).await;
|
||||
assert_eq!(completion.operation_id, bind);
|
||||
let (listener, listen_addr) = session_b
|
||||
.take_result_with(bind, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpBound {
|
||||
listener,
|
||||
local_addr,
|
||||
}) => Some((*listener, *local_addr)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let accept = session_b
|
||||
.submit_tcp_accept(listener, Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
let connect = session_a
|
||||
.submit_tcp_connect(listen_addr, Some(Duration::from_secs(10)))
|
||||
.unwrap();
|
||||
let (connect_completion, accept_completion) = tokio::join!(
|
||||
wait_for_session_completion(&session_a),
|
||||
wait_for_session_completion(&session_b),
|
||||
);
|
||||
assert_eq!(connect_completion.operation_id, connect);
|
||||
assert_eq!(accept_completion.operation_id, accept);
|
||||
let client = session_a
|
||||
.take_result_with(connect, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpConnected { stream, .. }) => Some(*stream),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let server = session_b
|
||||
.take_result_with(accept, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpAccepted { stream, .. }) => Some(*stream),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let read = session_b.submit_tcp_read(server, 16).unwrap();
|
||||
let write = session_a
|
||||
.submit_tcp_write(client, b"ping".to_vec())
|
||||
.unwrap();
|
||||
let (write_completion, read_completion) = tokio::join!(
|
||||
wait_for_session_completion(&session_a),
|
||||
wait_for_session_completion(&session_b),
|
||||
);
|
||||
assert_eq!(write_completion.operation_id, write);
|
||||
assert_eq!(read_completion.operation_id, read);
|
||||
let written = session_a
|
||||
.take_result_with(write, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpWritten { len }) => Some(*len),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let received = session_b
|
||||
.take_result_with(read, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpRead { data, eof }) if !eof => Some(data.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(written, 4);
|
||||
assert_eq!(received, b"ping");
|
||||
|
||||
let eof_read = session_b.submit_tcp_read(server, 16).unwrap();
|
||||
let shutdown = session_a.submit_tcp_shutdown_write(client).unwrap();
|
||||
let shutdown_completion = wait_for_session_completion(&session_a).await;
|
||||
let eof_completion = wait_for_session_completion(&session_b).await;
|
||||
assert_eq!(shutdown_completion.operation_id, shutdown);
|
||||
assert_eq!(eof_completion.operation_id, eof_read);
|
||||
session_a
|
||||
.take_result_with(shutdown, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpWriteShutdown) => Some(()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let eof = session_b
|
||||
.take_result_with(eof_read, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpRead { data, eof }) => Some((data.clone(), *eof)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(eof, (Vec::new(), true));
|
||||
|
||||
let response_read = session_a.submit_tcp_read(client, 16).unwrap();
|
||||
let response_write = session_b
|
||||
.submit_tcp_write(server, b"pong".to_vec())
|
||||
.unwrap();
|
||||
let (response_read_completion, response_write_completion) = tokio::join!(
|
||||
wait_for_session_completion(&session_a),
|
||||
wait_for_session_completion(&session_b),
|
||||
);
|
||||
assert_eq!(response_read_completion.operation_id, response_read);
|
||||
assert_eq!(response_write_completion.operation_id, response_write);
|
||||
let response = session_a
|
||||
.take_result_with(response_read, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpRead { data, eof }) if !eof => Some(data.clone()),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let response_len = session_b
|
||||
.take_result_with(response_write, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::TcpWritten { len }) => Some(*len),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(response, b"pong");
|
||||
assert_eq!(response_len, 4);
|
||||
|
||||
let blocked_read = session_b.submit_tcp_read(server, 16).unwrap();
|
||||
session_b.close_resource(server);
|
||||
let close_completion = wait_for_session_completion(&session_b).await;
|
||||
assert_eq!(close_completion.operation_id, blocked_read);
|
||||
assert_eq!(
|
||||
close_completion.status,
|
||||
DataPlaneCompletionStatus::Error(DataPlaneErrorKind::HandleClosed)
|
||||
);
|
||||
let close_error = session_b
|
||||
.take_result_with(blocked_read, |outcome| outcome.as_ref().err().copied())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(close_error, DataPlaneErrorKind::HandleClosed);
|
||||
|
||||
let stopped_read = session_a.submit_tcp_read(client, 16).unwrap();
|
||||
session_a.stop();
|
||||
let stop_completion = wait_for_session_completion(&session_a).await;
|
||||
assert_eq!(stop_completion.operation_id, stopped_read);
|
||||
assert_eq!(
|
||||
stop_completion.status,
|
||||
DataPlaneCompletionStatus::Error(DataPlaneErrorKind::InstanceStopped)
|
||||
);
|
||||
|
||||
session_a.close_resource(client);
|
||||
session_b.close_resource(listener);
|
||||
session_b.stop();
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_sessions_report_udp_truncation() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let session_a = DataPlaneSession::new(&a.gateway);
|
||||
let session_b = DataPlaneSession::new(&b.gateway);
|
||||
session_a.start().unwrap();
|
||||
session_b.start().unwrap();
|
||||
|
||||
let bind_a = session_a.submit_udp_bind(0, None).unwrap();
|
||||
let bind_b = session_b.submit_udp_bind(0, None).unwrap();
|
||||
let (completion_a, completion_b) = tokio::join!(
|
||||
wait_for_session_completion(&session_a),
|
||||
wait_for_session_completion(&session_b),
|
||||
);
|
||||
assert_eq!(completion_a.operation_id, bind_a);
|
||||
assert_eq!(completion_b.operation_id, bind_b);
|
||||
let (socket_a, addr_a) = session_a
|
||||
.take_result_with(bind_a, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::UdpBound { socket, local_addr }) => {
|
||||
Some((*socket, *local_addr))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let (socket_b, addr_b) = session_b
|
||||
.take_result_with(bind_b, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::UdpBound { socket, local_addr }) => {
|
||||
Some((*socket, *local_addr))
|
||||
}
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let warmup = session_b
|
||||
.submit_udp_send(socket_b, addr_a, b"warmup".to_vec())
|
||||
.unwrap();
|
||||
wait_for_session_completion(&session_b).await;
|
||||
session_b
|
||||
.take_result_with(warmup, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::UdpSent { len }) => Some(*len),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
let receive = session_b.submit_udp_receive(socket_b, 2).unwrap();
|
||||
let send = session_a
|
||||
.submit_udp_send(socket_a, addr_b, b"ping".to_vec())
|
||||
.unwrap();
|
||||
let (send_completion, receive_completion) = tokio::join!(
|
||||
wait_for_session_completion(&session_a),
|
||||
wait_for_session_completion(&session_b),
|
||||
);
|
||||
assert_eq!(send_completion.operation_id, send);
|
||||
assert_eq!(receive_completion.operation_id, receive);
|
||||
let (data, peer_addr, truncated) = session_b
|
||||
.take_result_with(receive, |outcome| match outcome {
|
||||
Ok(DataPlaneOperationResult::UdpReceived {
|
||||
data,
|
||||
peer_addr,
|
||||
truncated,
|
||||
}) => Some((data.clone(), *peer_addr, *truncated)),
|
||||
_ => None,
|
||||
})
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(data, b"pi");
|
||||
assert_eq!(peer_addr, addr_a);
|
||||
assert!(truncated);
|
||||
|
||||
session_a.close_resource(socket_a);
|
||||
session_b.close_resource(socket_b);
|
||||
session_a.stop();
|
||||
session_b.stop();
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn public_tcp_connect_never_falls_back_to_an_unrelated_host() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host, "10.126.131.1/24".parse().unwrap());
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
|
||||
let error = match endpoint
|
||||
.gateway
|
||||
.data_plane_tcp_connect("192.0.2.10:443".parse().unwrap(), Duration::from_secs(1))
|
||||
.await
|
||||
{
|
||||
Ok(_) => panic!("public data plane unexpectedly used a Host TCP route"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert_eq!(error.kind(), DataPlaneErrorKind::NoOverlayRoute);
|
||||
assert_eq!(endpoint.gateway.host.tcp_binds.load(Ordering::Relaxed), 0);
|
||||
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn listener_and_accepted_stream_own_independent_flow_lifetimes() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let timeout = Duration::from_secs(10);
|
||||
let mut listener = b.gateway.data_plane_tcp_bind(0, timeout).await.unwrap();
|
||||
let listen_addr = SocketAddr::new(b.ip.address().into(), listener.local_addr().port());
|
||||
|
||||
let (accepted, client) = tokio::join!(
|
||||
listener.accept(),
|
||||
a.gateway.data_plane_tcp_connect(listen_addr, timeout),
|
||||
);
|
||||
let (mut server, peer_addr) = accepted.unwrap();
|
||||
let mut client = client.unwrap();
|
||||
|
||||
assert_eq!(client.local_addr(), peer_addr);
|
||||
assert_eq!(a.gateway.entries.count(), 1);
|
||||
assert_eq!(b.gateway.entries.count(), 2);
|
||||
|
||||
drop(listener);
|
||||
assert_eq!(b.gateway.entries.count(), 1);
|
||||
|
||||
client.write_all(b"after-listener-drop").await.unwrap();
|
||||
client.flush().await.unwrap();
|
||||
let mut buf = [0u8; 19];
|
||||
server.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"after-listener-drop");
|
||||
|
||||
drop(client);
|
||||
assert_eq!(a.gateway.entries.count(), 0);
|
||||
drop(server);
|
||||
assert_eq!(b.gateway.entries.count(), 0);
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_udp_pingpong() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let timeout = Duration::from_secs(10);
|
||||
let socket_a = a.gateway.data_plane_udp_bind(0, timeout).await.unwrap();
|
||||
let socket_b = b.gateway.data_plane_udp_bind(0, timeout).await.unwrap();
|
||||
let addr_a = SocketAddr::new(a.ip.address().into(), socket_a.local_addr().port());
|
||||
let addr_b = SocketAddr::new(b.ip.address().into(), socket_b.local_addr().port());
|
||||
|
||||
socket_b.send_to(b"warmup", addr_a).await.unwrap();
|
||||
socket_a.send_to(b"ping", addr_b).await.unwrap();
|
||||
let mut buf = [0u8; 16];
|
||||
let (len, from) = tokio::time::timeout(timeout, socket_b.recv_from(&mut buf))
|
||||
.await
|
||||
.expect("receive ping timed out")
|
||||
.unwrap();
|
||||
assert_eq!(&buf[..len], b"ping");
|
||||
assert_eq!(from, addr_a);
|
||||
|
||||
socket_b.send_to(b"pong", addr_a).await.unwrap();
|
||||
loop {
|
||||
let (len, from) = tokio::time::timeout(timeout, socket_a.recv_from(&mut buf))
|
||||
.await
|
||||
.expect("receive pong timed out")
|
||||
.unwrap();
|
||||
if &buf[..len] == b"pong" {
|
||||
assert_eq!(from, addr_b);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_udp_carries_maximum_ipv4_payload() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let timeout = Duration::from_secs(10);
|
||||
let socket_a = a.gateway.data_plane_udp_bind(0, timeout).await.unwrap();
|
||||
let socket_b = b.gateway.data_plane_udp_bind(0, timeout).await.unwrap();
|
||||
let addr_a = SocketAddr::new(a.ip.address().into(), socket_a.local_addr().port());
|
||||
let addr_b = SocketAddr::new(b.ip.address().into(), socket_b.local_addr().port());
|
||||
|
||||
socket_b.send_to(b"warmup", addr_a).await.unwrap();
|
||||
let payload = vec![0x5a; 65_507];
|
||||
socket_a.send_to(&payload, addr_b).await.unwrap();
|
||||
let mut received = vec![0; payload.len()];
|
||||
let (len, from) = tokio::time::timeout(timeout, socket_b.recv_from(&mut received))
|
||||
.await
|
||||
.expect("receive maximum UDP payload timed out")
|
||||
.unwrap();
|
||||
assert_eq!(from, addr_a);
|
||||
assert_eq!(len, payload.len());
|
||||
assert_eq!(received, payload);
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn udp_socket_drop_releases_every_destination_flow() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let timeout = Duration::from_secs(10);
|
||||
let socket = a.gateway.data_plane_udp_bind(0, timeout).await.unwrap();
|
||||
let first = SocketAddr::new(b.ip.address().into(), 31001);
|
||||
let second = SocketAddr::new(b.ip.address().into(), 31002);
|
||||
|
||||
socket.send_to(b"one", first).await.unwrap();
|
||||
socket.send_to(b"two", second).await.unwrap();
|
||||
assert_eq!(a.gateway.entries.count(), 2);
|
||||
|
||||
drop(socket);
|
||||
assert_eq!(a.gateway.entries.count(), 0);
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn udp_socket_owns_a_host_port_reservation() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host.clone(), "10.126.132.1/24".parse().unwrap());
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
|
||||
let socket = endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(socket.local_addr().port(), 20002);
|
||||
assert_eq!(host.udp_binds.load(Ordering::Relaxed), 1);
|
||||
|
||||
drop(socket);
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn final_data_plane_lease_releases_net_and_same_ipv4_reacquires_it() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host, "10.126.127.1/24".parse().unwrap());
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
|
||||
let socket = endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(endpoint.gateway.net.lock().await.is_some());
|
||||
|
||||
drop(socket);
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
if endpoint.gateway.net.lock().await.is_none() {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("final data-plane lease did not release smoltcp net");
|
||||
|
||||
let socket = endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_secs(1))
|
||||
.await
|
||||
.expect("same IPv4 generation should be recreated");
|
||||
assert!(endpoint.gateway.net.lock().await.is_some());
|
||||
|
||||
drop(socket);
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn immediate_consumer_reacquire_never_leases_closing_generation() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host, "10.126.133.1/24".parse().unwrap());
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
let destination: SocketAddr = "10.126.133.2:31001".parse().unwrap();
|
||||
|
||||
for _ in 0..20 {
|
||||
let socket = endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_secs(1))
|
||||
.await
|
||||
.expect("consumer should acquire the current smoltcp generation");
|
||||
socket
|
||||
.send_to(b"generation-probe", destination)
|
||||
.await
|
||||
.expect("new consumer must not inherit a closing generation");
|
||||
drop(socket);
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_connect_survives_ipv4_generation_replacement() {
|
||||
let (a, b) = setup_data_plane_pair().await;
|
||||
let _consumer = b.gateway.acquire_consumer_lease().unwrap();
|
||||
|
||||
for ip in ["10.126.127.2", "10.126.126.2"] {
|
||||
let ip: IpAddr = ip.parse().unwrap();
|
||||
b.gateway.runtime_config.update_peer_with(|peer| {
|
||||
peer.runtime.core.routes.ipv4 = Some(IpPrefix::new(ip, 24).unwrap());
|
||||
});
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
loop {
|
||||
if b.gateway
|
||||
.net
|
||||
.lock()
|
||||
.await
|
||||
.as_ref()
|
||||
.is_some_and(|plane| IpAddr::V4(plane.ipv4_addr.address()) == ip)
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("data-plane IPv4 generation did not update");
|
||||
}
|
||||
|
||||
let timeout = Duration::from_secs(10);
|
||||
let mut listener = b.gateway.data_plane_tcp_bind(0, timeout).await.unwrap();
|
||||
let listen_addr = SocketAddr::new(b.ip.address().into(), listener.local_addr().port());
|
||||
let (accepted, client) = tokio::join!(
|
||||
listener.accept(),
|
||||
a.gateway.data_plane_tcp_connect(listen_addr, timeout),
|
||||
);
|
||||
let (mut server, _) = accepted.unwrap();
|
||||
let mut client = client.unwrap();
|
||||
|
||||
client.write_all(b"ping").await.unwrap();
|
||||
client.flush().await.unwrap();
|
||||
let mut buf = [0u8; 4];
|
||||
server.read_exact(&mut buf).await.unwrap();
|
||||
assert_eq!(&buf, b"ping");
|
||||
|
||||
stop_data_plane_pair(&a, &b).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ipv4_change_closes_existing_generation_with_typed_error() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host, "10.126.128.1/24".parse().unwrap());
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
let socket = endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_secs(1))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
endpoint.gateway.runtime_config.update_peer_with(|peer| {
|
||||
peer.runtime.core.routes.ipv4 =
|
||||
Some(IpPrefix::new("10.126.129.1".parse().unwrap(), 24).unwrap());
|
||||
});
|
||||
|
||||
let mut buf = [0u8; 1];
|
||||
let error = tokio::time::timeout(Duration::from_secs(1), socket.recv_from(&mut buf))
|
||||
.await
|
||||
.expect("old generation receive did not wake")
|
||||
.unwrap_err();
|
||||
let data_plane_error = error
|
||||
.get_ref()
|
||||
.and_then(|error| error.downcast_ref::<DataPlaneError>())
|
||||
.expect("generation close must preserve the typed data-plane error");
|
||||
assert_eq!(data_plane_error.kind(), DataPlaneErrorKind::NetworkChanged);
|
||||
|
||||
drop(socket);
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn readiness_timeout_has_stable_error_kind() {
|
||||
let host = Arc::new(TestHost::default());
|
||||
let endpoint = data_plane_endpoint(host, "10.126.130.1/24".parse().unwrap());
|
||||
endpoint
|
||||
.gateway
|
||||
.runtime_config
|
||||
.update_peer_with(|peer| peer.runtime.core.routes.ipv4 = None);
|
||||
endpoint.peer_manager.run().await.unwrap();
|
||||
endpoint.gateway.start_runtime().await.unwrap();
|
||||
|
||||
let error = match endpoint
|
||||
.gateway
|
||||
.data_plane_udp_bind(0, Duration::from_millis(1))
|
||||
.await
|
||||
{
|
||||
Ok(_) => panic!("data-plane bind unexpectedly succeeded without an IPv4 address"),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert_eq!(error.kind(), DataPlaneErrorKind::DeadlineExceeded);
|
||||
|
||||
endpoint.gateway.stop_runtime().await;
|
||||
endpoint.peer_manager.clear_resources().await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_consumes_modified_data_when_entry_matches() {
|
||||
let gateway = test_gateway();
|
||||
|
||||
let local = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 1)), 40000);
|
||||
let remote = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 3)), 22);
|
||||
let entry = FlowKey {
|
||||
src: local,
|
||||
dst: remote,
|
||||
kind: TCP_ENTRY,
|
||||
};
|
||||
gateway.entries.insert(
|
||||
entry,
|
||||
FlowData::Tcp {
|
||||
_reservation: Arc::new(()),
|
||||
},
|
||||
);
|
||||
|
||||
for packet_type in [
|
||||
PacketType::DataWithKcpSrcModified,
|
||||
PacketType::DataWithQuicSrcModified,
|
||||
] {
|
||||
let mut packet = ZCPacket::new_with_payload(&build_tcp_packet(remote, local));
|
||||
packet.fill_peer_manager_hdr(1, 1, packet_type as u8);
|
||||
|
||||
let result = gateway.try_process_packet_from_peer(packet).await;
|
||||
assert!(result.is_none());
|
||||
|
||||
let mut receiver = gateway.packet_recv.lock().await;
|
||||
let received = receiver.try_recv().unwrap();
|
||||
assert_eq!(
|
||||
received.peer_manager_header().unwrap().packet_type,
|
||||
packet_type as u8
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_passes_through_unmatched_or_malformed_modified_data() {
|
||||
let gateway = test_gateway();
|
||||
gateway.entries.insert(
|
||||
FlowKey {
|
||||
src: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 1)), 40000),
|
||||
dst: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 3)), 22),
|
||||
kind: TCP_ENTRY,
|
||||
},
|
||||
FlowData::Tcp {
|
||||
_reservation: Arc::new(()),
|
||||
},
|
||||
);
|
||||
|
||||
let unmatched_local = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 1)), 40001);
|
||||
let remote = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 3)), 22);
|
||||
let mut unmatched_packet =
|
||||
ZCPacket::new_with_payload(&build_tcp_packet(remote, unmatched_local));
|
||||
unmatched_packet.fill_peer_manager_hdr(1, 2, PacketType::DataWithKcpSrcModified as u8);
|
||||
let result = gateway.try_process_packet_from_peer(unmatched_packet).await;
|
||||
assert!(result.is_some());
|
||||
|
||||
let mut malformed_packet = ZCPacket::new_with_payload(&[0u8; 8]);
|
||||
malformed_packet.fill_peer_manager_hdr(1, 2, PacketType::DataWithQuicSrcModified as u8);
|
||||
let result = gateway.try_process_packet_from_peer(malformed_packet).await;
|
||||
assert!(result.is_some());
|
||||
|
||||
let mut receiver = gateway.packet_recv.lock().await;
|
||||
assert!(receiver.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_passes_through_non_loopback_modified_data_when_entry_matches() {
|
||||
let gateway = test_gateway();
|
||||
|
||||
let local = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 1)), 40000);
|
||||
let remote = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 3)), 22);
|
||||
let entry = FlowKey {
|
||||
src: local,
|
||||
dst: remote,
|
||||
kind: TCP_ENTRY,
|
||||
};
|
||||
gateway.entries.insert(
|
||||
entry,
|
||||
FlowData::Tcp {
|
||||
_reservation: Arc::new(()),
|
||||
},
|
||||
);
|
||||
|
||||
let mut packet = ZCPacket::new_with_payload(&build_tcp_packet(remote, local));
|
||||
packet.fill_peer_manager_hdr(1, 2, PacketType::DataWithKcpSrcModified as u8);
|
||||
|
||||
let result = gateway.try_process_packet_from_peer(packet).await;
|
||||
assert!(result.is_some());
|
||||
|
||||
let mut receiver = gateway.packet_recv.lock().await;
|
||||
assert!(receiver.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn data_plane_mirrors_fragmented_udp_when_entry_matches() {
|
||||
let gateway = test_gateway();
|
||||
|
||||
let local = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 1)), 40000);
|
||||
let remote = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(10, 144, 144, 3)), 53);
|
||||
gateway.entries.insert(
|
||||
FlowKey {
|
||||
src: local,
|
||||
dst: remote,
|
||||
kind: UDP_ENTRY,
|
||||
},
|
||||
FlowData::Udp,
|
||||
);
|
||||
assert_eq!(gateway.entries.count(), 1);
|
||||
|
||||
let mut packet = ZCPacket::new_with_payload(&build_udp_followup_fragment(
|
||||
match remote.ip() {
|
||||
IpAddr::V4(ip) => ip,
|
||||
IpAddr::V6(_) => unreachable!(),
|
||||
},
|
||||
match local.ip() {
|
||||
IpAddr::V4(ip) => ip,
|
||||
IpAddr::V6(_) => unreachable!(),
|
||||
},
|
||||
));
|
||||
packet.fill_peer_manager_hdr(1, 2, PacketType::Data as u8);
|
||||
|
||||
let result = gateway.try_process_packet_from_peer(packet).await;
|
||||
assert!(result.is_some());
|
||||
|
||||
let mut receiver = gateway.packet_recv.lock().await;
|
||||
let received = receiver.try_recv().unwrap();
|
||||
assert_eq!(
|
||||
received.peer_manager_header().unwrap().packet_type,
|
||||
PacketType::Data as u8
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! UDP socket resources exposed by the data plane.
|
||||
|
||||
use std::{
|
||||
any::Any,
|
||||
collections::{HashMap, hash_map::Entry},
|
||||
net::SocketAddr,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use super::{
|
||||
DataPlaneIoGuard, DataPlaneLease, DataPlaneUdpIo, FlowData, FlowKey, FlowLease, FlowSet,
|
||||
UDP_ENTRY,
|
||||
};
|
||||
|
||||
pub struct DataPlaneUdpSocket {
|
||||
pub(super) socket: Arc<DataPlaneUdpIo>,
|
||||
pub(super) flows: FlowSet,
|
||||
pub(super) routes: Mutex<HashMap<SocketAddr, FlowLease<FlowData>>>,
|
||||
pub(super) local_addr: SocketAddr,
|
||||
pub(super) _reservation: Arc<dyn Any + Send + Sync>,
|
||||
pub(super) _data_plane_lease: DataPlaneLease,
|
||||
pub(super) generation: DataPlaneIoGuard,
|
||||
}
|
||||
|
||||
impl DataPlaneUdpSocket {
|
||||
pub fn local_addr(&self) -> SocketAddr {
|
||||
self.local_addr
|
||||
}
|
||||
|
||||
pub async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> Result<usize, std::io::Error> {
|
||||
self.generation
|
||||
.ensure_open()
|
||||
.map_err(|error| error.into_io_error())?;
|
||||
let key = FlowKey {
|
||||
src: self.local_addr,
|
||||
dst: addr,
|
||||
kind: UDP_ENTRY,
|
||||
};
|
||||
if let Entry::Vacant(route) = self.routes.lock().unwrap().entry(addr) {
|
||||
let lease = FlowLease::try_register(self.flows.clone(), key, FlowData::Udp)
|
||||
.ok_or_else(|| {
|
||||
std::io::Error::new(
|
||||
std::io::ErrorKind::AddrInUse,
|
||||
"data-plane UDP flow already exists",
|
||||
)
|
||||
})?;
|
||||
route.insert(lease);
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.generation.closed() => Err(self.generation.closed_io_error()),
|
||||
result = self.socket.send_to(buf, addr) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn recv_from(&self, buf: &mut [u8]) -> Result<(usize, SocketAddr), std::io::Error> {
|
||||
self.generation
|
||||
.ensure_open()
|
||||
.map_err(|error| error.into_io_error())?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.generation.closed() => Err(self.generation.closed_io_error()),
|
||||
result = self.socket.recv_from(buf) => result,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn recv_from_limited(
|
||||
&self,
|
||||
max_len: usize,
|
||||
) -> Result<(Vec<u8>, SocketAddr, bool), std::io::Error> {
|
||||
self.generation
|
||||
.ensure_open()
|
||||
.map_err(|error| error.into_io_error())?;
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = self.generation.closed() => Err(self.generation.closed_io_error()),
|
||||
result = self.socket.recv_from_limited(max_len) => result,
|
||||
}
|
||||
}
|
||||
}
|
||||
+792
@@ -0,0 +1,792 @@
|
||||
use std::{collections::HashSet, sync::Arc, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use cidr::Ipv4Inet;
|
||||
use rand::Rng;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::{
|
||||
config::IpPrefix, config::runtime::CoreRuntimeConfigStore, peers::peer_manager::PeerManagerCore,
|
||||
};
|
||||
|
||||
#[cfg(feature = "dhcp-ipv4")]
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DhcpIpv4Decision {
|
||||
WaitForPeers,
|
||||
Unchanged,
|
||||
Change {
|
||||
previous: Option<Ipv4Inet>,
|
||||
next: Option<Ipv4Inet>,
|
||||
},
|
||||
}
|
||||
|
||||
// Give an already-addressed peer time to announce its subnet before a fresh
|
||||
// network's first node falls back to the bootstrap subnet.
|
||||
const BOOTSTRAP_WAIT_ROUNDS: u32 = 2;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct DhcpIpv4Allocator {
|
||||
default_subnet: Option<Ipv4Inet>,
|
||||
current: Option<Ipv4Inet>,
|
||||
no_ipv4_rounds: u32,
|
||||
}
|
||||
|
||||
impl DhcpIpv4Allocator {
|
||||
pub fn new(default_subnet: Ipv4Inet) -> Self {
|
||||
Self {
|
||||
default_subnet: Some(default_subnet),
|
||||
current: None,
|
||||
no_ipv4_rounds: 0,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn current(&self) -> Option<Ipv4Inet> {
|
||||
self.current
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.current = None;
|
||||
self.no_ipv4_rounds = 0;
|
||||
}
|
||||
|
||||
pub fn commit(&mut self, next: Option<Ipv4Inet>) {
|
||||
self.current = next;
|
||||
}
|
||||
|
||||
pub fn evaluate(
|
||||
&mut self,
|
||||
has_routes: bool,
|
||||
used_ipv4: &HashSet<Ipv4Inet>,
|
||||
) -> DhcpIpv4Decision {
|
||||
self.evaluate_with_rng(has_routes, used_ipv4, &mut rand::thread_rng())
|
||||
}
|
||||
|
||||
fn evaluate_with_rng(
|
||||
&mut self,
|
||||
has_routes: bool,
|
||||
used_ipv4: &HashSet<Ipv4Inet>,
|
||||
rng: &mut impl Rng,
|
||||
) -> DhcpIpv4Decision {
|
||||
if !has_routes && self.default_subnet.is_none() {
|
||||
return DhcpIpv4Decision::WaitForPeers;
|
||||
}
|
||||
|
||||
let preferred = used_ipv4
|
||||
.iter()
|
||||
.filter(|subnet| {
|
||||
self.current
|
||||
.is_some_and(|current| current.network() == subnet.network())
|
||||
})
|
||||
.min_by_key(|subnet| (subnet.first_address(), subnet.network_length()));
|
||||
let advertised = preferred.or_else(|| {
|
||||
used_ipv4
|
||||
.iter()
|
||||
.min_by_key(|subnet| (subnet.first_address(), subnet.network_length()))
|
||||
});
|
||||
let subnet = if let Some(subnet) = advertised {
|
||||
self.no_ipv4_rounds = 0;
|
||||
*subnet
|
||||
} else if self.current.is_some() {
|
||||
return DhcpIpv4Decision::Unchanged;
|
||||
} else {
|
||||
let Some(default_subnet) = self.default_subnet else {
|
||||
return DhcpIpv4Decision::WaitForPeers;
|
||||
};
|
||||
self.no_ipv4_rounds = self.no_ipv4_rounds.saturating_add(1);
|
||||
if self.no_ipv4_rounds <= BOOTSTRAP_WAIT_ROUNDS {
|
||||
return DhcpIpv4Decision::WaitForPeers;
|
||||
}
|
||||
default_subnet
|
||||
};
|
||||
if let Some(current) = self.current
|
||||
&& current.network() == subnet.network()
|
||||
&& !used_ipv4.contains(¤t)
|
||||
{
|
||||
return DhcpIpv4Decision::Unchanged;
|
||||
}
|
||||
|
||||
let first = u32::from(subnet.first_address());
|
||||
let span = u32::from(subnet.last_address()) - first;
|
||||
// Spread simultaneous bootstrap allocations and conflict retries across
|
||||
// the subnet. Existing route announcements still detect collisions.
|
||||
let offset = if span > 1 && (used_ipv4.is_empty() || self.current.is_some()) {
|
||||
rng.gen_range(1..span)
|
||||
} else {
|
||||
1
|
||||
};
|
||||
let next = (offset..span).chain(1..offset).find_map(|offset| {
|
||||
let candidate = Ipv4Inet::new((first + offset).into(), subnet.network_length()).ok()?;
|
||||
(!used_ipv4.contains(&candidate)).then_some(candidate)
|
||||
});
|
||||
if self.current == next {
|
||||
return DhcpIpv4Decision::Unchanged;
|
||||
}
|
||||
|
||||
DhcpIpv4Decision::Change {
|
||||
previous: self.current,
|
||||
next,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DhcpIpv4RouteSnapshot {
|
||||
pub has_routes: bool,
|
||||
pub used_ipv4: HashSet<Ipv4Inet>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait DhcpIpv4RouteSource: Send + Sync + 'static {
|
||||
async fn dhcp_ipv4_route_snapshot(&self) -> DhcpIpv4RouteSnapshot;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpIpv4RouteSource for PeerManagerCore {
|
||||
async fn dhcp_ipv4_route_snapshot(&self) -> DhcpIpv4RouteSnapshot {
|
||||
let routes = self.get_route().list_routes().await;
|
||||
let has_routes = !routes.is_empty();
|
||||
let used_ipv4 = routes
|
||||
.into_iter()
|
||||
.filter_map(|route| route.ipv4_addr.map(Into::into))
|
||||
.collect();
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes,
|
||||
used_ipv4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait DhcpIpv4Host: Send + Sync + 'static {
|
||||
fn take_interface_closed(&self) -> bool;
|
||||
|
||||
async fn apply_dhcp_ipv4(
|
||||
&self,
|
||||
previous: Option<Ipv4Inet>,
|
||||
next: Option<Ipv4Inet>,
|
||||
) -> DhcpIpv4ApplyOutcome;
|
||||
|
||||
fn publish_dhcp_ipv4(
|
||||
&self,
|
||||
_previous: Option<Ipv4Inet>,
|
||||
_requested: Option<Ipv4Inet>,
|
||||
_actual: Option<Ipv4Inet>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "dhcp-ipv4")]
|
||||
pub(crate) struct DhcpIpv4Runtime {
|
||||
task: Mutex<Option<AbortOnDropHandle<()>>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "dhcp-ipv4")]
|
||||
impl DhcpIpv4Runtime {
|
||||
pub(crate) fn new() -> Self {
|
||||
Self {
|
||||
task: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
&self,
|
||||
route_source: Arc<dyn DhcpIpv4RouteSource>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
host: Arc<dyn DhcpIpv4Host>,
|
||||
) {
|
||||
let mut task = self.task.lock().await;
|
||||
if task.is_none() {
|
||||
task.replace(DhcpIpv4Service::new(route_source, runtime_config, host).start());
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
self.task.lock().await.take();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DhcpIpv4ApplyPermit {
|
||||
_guard: Box<dyn Send>,
|
||||
}
|
||||
|
||||
impl DhcpIpv4ApplyPermit {
|
||||
pub fn new(guard: impl Send + 'static) -> Self {
|
||||
Self {
|
||||
_guard: Box::new(guard),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DhcpIpv4ApplyOutcome {
|
||||
pub actual: Option<Ipv4Inet>,
|
||||
pub result: anyhow::Result<()>,
|
||||
permit: Option<DhcpIpv4ApplyPermit>,
|
||||
}
|
||||
|
||||
impl DhcpIpv4ApplyOutcome {
|
||||
pub fn applied(actual: Option<Ipv4Inet>) -> Self {
|
||||
Self {
|
||||
actual,
|
||||
result: Ok(()),
|
||||
permit: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn failed(actual: Option<Ipv4Inet>, error: impl Into<anyhow::Error>) -> Self {
|
||||
Self {
|
||||
actual,
|
||||
result: Err(error.into()),
|
||||
permit: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_permit(mut self, permit: DhcpIpv4ApplyPermit) -> Self {
|
||||
self.permit = Some(permit);
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
pub struct DhcpIpv4Service {
|
||||
operation: tokio::sync::Mutex<()>,
|
||||
allocator: std::sync::Mutex<DhcpIpv4Allocator>,
|
||||
route_source: Arc<dyn DhcpIpv4RouteSource>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
host: Arc<dyn DhcpIpv4Host>,
|
||||
}
|
||||
|
||||
impl DhcpIpv4Service {
|
||||
pub fn new(
|
||||
route_source: Arc<dyn DhcpIpv4RouteSource>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
host: Arc<dyn DhcpIpv4Host>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
operation: tokio::sync::Mutex::new(()),
|
||||
allocator: std::sync::Mutex::new(DhcpIpv4Allocator::new(
|
||||
Ipv4Inet::new(std::net::Ipv4Addr::new(10, 126, 126, 0), 24)
|
||||
.expect("valid bootstrap subnet"),
|
||||
)),
|
||||
route_source,
|
||||
runtime_config,
|
||||
host,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn current(&self) -> Option<Ipv4Inet> {
|
||||
self.allocator.lock().unwrap().current()
|
||||
}
|
||||
|
||||
pub async fn reconcile_once(&self) -> bool {
|
||||
let _operation = self.operation.lock().await;
|
||||
if self.host.take_interface_closed() {
|
||||
self.allocator.lock().unwrap().reset();
|
||||
}
|
||||
let snapshot = self.route_source.dhcp_ipv4_route_snapshot().await;
|
||||
let decision = self
|
||||
.allocator
|
||||
.lock()
|
||||
.unwrap()
|
||||
.evaluate(snapshot.has_routes, &snapshot.used_ipv4);
|
||||
|
||||
let DhcpIpv4Decision::Change { previous, next } = decision else {
|
||||
return snapshot.has_routes;
|
||||
};
|
||||
tracing::debug!(?previous, ?next, "DHCP IPv4 reconciliation applying change");
|
||||
let outcome = self.host.apply_dhcp_ipv4(previous, next).await;
|
||||
let DhcpIpv4ApplyOutcome {
|
||||
actual,
|
||||
result,
|
||||
permit,
|
||||
} = outcome;
|
||||
self.runtime_config.update_peer_with(|peer| {
|
||||
peer.runtime.core.routes.ipv4 = actual.map(|actual| IpPrefix {
|
||||
address: actual.address().into(),
|
||||
prefix_len: actual.network_length(),
|
||||
});
|
||||
});
|
||||
match result {
|
||||
Ok(()) => {
|
||||
self.allocator.lock().unwrap().commit(actual);
|
||||
self.host.publish_dhcp_ipv4(previous, next, actual);
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::error!(?previous, ?next, ?actual, ?err, "DHCP IPv4 apply failed");
|
||||
}
|
||||
}
|
||||
drop(permit);
|
||||
snapshot.has_routes
|
||||
}
|
||||
|
||||
pub fn start(self: &Arc<Self>) -> AbortOnDropHandle<()> {
|
||||
let service = self.clone();
|
||||
AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let mut next_sleep = Duration::ZERO;
|
||||
loop {
|
||||
crate::foundation::time::sleep(next_sleep).await;
|
||||
next_sleep = if service.reconcile_once().await {
|
||||
Duration::from_secs(rand::thread_rng().gen_range(5..10))
|
||||
} else {
|
||||
Duration::from_secs(1)
|
||||
};
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::{
|
||||
Mutex,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
struct StaticRouteSource {
|
||||
snapshot: Mutex<DhcpIpv4RouteSnapshot>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpIpv4RouteSource for StaticRouteSource {
|
||||
async fn dhcp_ipv4_route_snapshot(&self) -> DhcpIpv4RouteSnapshot {
|
||||
self.snapshot.lock().unwrap().clone()
|
||||
}
|
||||
}
|
||||
|
||||
type PublishedIpv4Route = (Option<Ipv4Inet>, Option<Ipv4Inet>, Option<Ipv4Inet>);
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingHost {
|
||||
interface_closed: AtomicBool,
|
||||
fail_apply: AtomicBool,
|
||||
hold_apply_permit: AtomicBool,
|
||||
permit_held: Arc<AtomicBool>,
|
||||
published_with_permit: AtomicBool,
|
||||
runtime_config: Mutex<Option<CoreRuntimeConfigStore>>,
|
||||
published_runtime_ipv4: Mutex<Vec<Option<IpPrefix>>>,
|
||||
changes: Mutex<Vec<(Option<Ipv4Inet>, Option<Ipv4Inet>)>>,
|
||||
published: Mutex<Vec<PublishedIpv4Route>>,
|
||||
}
|
||||
|
||||
struct RecordingPermit(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for RecordingPermit {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(false, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl DhcpIpv4Host for RecordingHost {
|
||||
fn take_interface_closed(&self) -> bool {
|
||||
self.interface_closed.swap(false, Ordering::AcqRel)
|
||||
}
|
||||
|
||||
async fn apply_dhcp_ipv4(
|
||||
&self,
|
||||
previous: Option<Ipv4Inet>,
|
||||
next: Option<Ipv4Inet>,
|
||||
) -> DhcpIpv4ApplyOutcome {
|
||||
self.changes.lock().unwrap().push((previous, next));
|
||||
let mut outcome = if self.fail_apply.load(Ordering::Acquire) {
|
||||
DhcpIpv4ApplyOutcome::failed(None, anyhow::anyhow!("apply failed"))
|
||||
} else {
|
||||
DhcpIpv4ApplyOutcome::applied(next)
|
||||
};
|
||||
if self.hold_apply_permit.load(Ordering::Acquire) {
|
||||
assert!(!self.permit_held.swap(true, Ordering::AcqRel));
|
||||
outcome = outcome.with_permit(DhcpIpv4ApplyPermit::new(RecordingPermit(
|
||||
self.permit_held.clone(),
|
||||
)));
|
||||
}
|
||||
outcome
|
||||
}
|
||||
|
||||
fn publish_dhcp_ipv4(
|
||||
&self,
|
||||
previous: Option<Ipv4Inet>,
|
||||
requested: Option<Ipv4Inet>,
|
||||
actual: Option<Ipv4Inet>,
|
||||
) {
|
||||
self.published_with_permit
|
||||
.store(self.permit_held.load(Ordering::Acquire), Ordering::Release);
|
||||
if let Some(runtime_config) = self.runtime_config.lock().unwrap().as_ref() {
|
||||
self.published_runtime_ipv4.lock().unwrap().push(
|
||||
runtime_config
|
||||
.snapshot()
|
||||
.peer
|
||||
.runtime
|
||||
.core
|
||||
.routes
|
||||
.ipv4
|
||||
.clone(),
|
||||
);
|
||||
}
|
||||
self.published
|
||||
.lock()
|
||||
.unwrap()
|
||||
.push((previous, requested, actual));
|
||||
}
|
||||
}
|
||||
|
||||
fn service(
|
||||
snapshot: DhcpIpv4RouteSnapshot,
|
||||
host: Arc<RecordingHost>,
|
||||
) -> (Arc<DhcpIpv4Service>, CoreRuntimeConfigStore) {
|
||||
let runtime_config = CoreRuntimeConfigStore::new(
|
||||
crate::config::runtime::CoreRuntimeConfig::default(),
|
||||
Arc::new(crate::config::peers::PeerRuntimeSnapshot::default()),
|
||||
);
|
||||
*host.runtime_config.lock().unwrap() = Some(runtime_config.clone());
|
||||
let service = DhcpIpv4Service::new(
|
||||
Arc::new(StaticRouteSource {
|
||||
snapshot: Mutex::new(snapshot),
|
||||
}),
|
||||
runtime_config.clone(),
|
||||
host,
|
||||
);
|
||||
(service, runtime_config)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn waits_until_at_least_one_route_exists() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
|
||||
assert_eq!(
|
||||
allocator.evaluate(false, &HashSet::new()),
|
||||
DhcpIpv4Decision::WaitForPeers
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn does_not_fall_back_to_a_builtin_subnet_without_assigned_ipv4() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
|
||||
assert_eq!(
|
||||
allocator.evaluate(true, &HashSet::new()),
|
||||
DhcpIpv4Decision::WaitForPeers
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bootstraps_default_subnet_after_bounded_wait() {
|
||||
let mut allocator = DhcpIpv4Allocator::new("10.126.126.0/24".parse().unwrap());
|
||||
|
||||
for _ in 0..2 {
|
||||
assert_eq!(
|
||||
allocator.evaluate(true, &HashSet::new()),
|
||||
DhcpIpv4Decision::WaitForPeers
|
||||
);
|
||||
}
|
||||
let DhcpIpv4Decision::Change {
|
||||
previous: None,
|
||||
next: Some(address),
|
||||
} = allocator.evaluate(true, &HashSet::new())
|
||||
else {
|
||||
panic!("expected bootstrap address")
|
||||
};
|
||||
assert_eq!(
|
||||
address.network(),
|
||||
"10.126.126.0/24".parse::<Ipv4Inet>().unwrap().network()
|
||||
);
|
||||
assert_ne!(address.address(), address.first_address());
|
||||
assert_ne!(address.address(), address.last_address());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn announced_peer_subnet_takes_priority_over_bootstrap_subnet() {
|
||||
let mut allocator = DhcpIpv4Allocator::new("10.126.126.0/24".parse().unwrap());
|
||||
let used = HashSet::from(["198.18.106.5/24".parse().unwrap()]);
|
||||
|
||||
assert_eq!(
|
||||
allocator.evaluate(true, &used),
|
||||
DhcpIpv4Decision::Change {
|
||||
previous: None,
|
||||
next: Some("198.18.106.1/24".parse().unwrap()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_current_address_when_peers_stop_announcing_ipv4() {
|
||||
let mut allocator = DhcpIpv4Allocator::new("10.126.126.0/24".parse().unwrap());
|
||||
let current = "198.18.106.1/24".parse().unwrap();
|
||||
allocator.commit(Some(current));
|
||||
|
||||
for _ in 0..BOOTSTRAP_WAIT_ROUNDS + 2 {
|
||||
assert_eq!(
|
||||
allocator.evaluate(true, &HashSet::new()),
|
||||
DhcpIpv4Decision::Unchanged
|
||||
);
|
||||
assert_eq!(allocator.current(), Some(current));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_dhcp_only_peers_resolve_conflicts() {
|
||||
use rand::SeedableRng;
|
||||
let subnet = "10.126.126.0/24".parse().unwrap();
|
||||
let mut allocators = (0..32)
|
||||
.map(|_| DhcpIpv4Allocator::new(subnet))
|
||||
.collect::<Vec<_>>();
|
||||
let mut rng = rand::rngs::StdRng::seed_from_u64(42);
|
||||
for round in 0..30 {
|
||||
// All peers evaluate the same previous-round snapshot before any
|
||||
// candidate is published, including simultaneous empty startup.
|
||||
let current = allocators
|
||||
.iter()
|
||||
.map(|allocator| allocator.current())
|
||||
.collect::<Vec<_>>();
|
||||
let decisions = allocators
|
||||
.iter_mut()
|
||||
.enumerate()
|
||||
.map(|(index, allocator)| {
|
||||
let used = current
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(peer, address)| (peer != index).then_some(*address).flatten())
|
||||
.collect();
|
||||
allocator.evaluate_with_rng(true, &used, &mut rng)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
for (allocator, decision) in allocators.iter_mut().zip(decisions) {
|
||||
if let DhcpIpv4Decision::Change { next, .. } = decision {
|
||||
allocator.commit(next);
|
||||
}
|
||||
}
|
||||
if round > BOOTSTRAP_WAIT_ROUNDS {
|
||||
let addresses = allocators
|
||||
.iter()
|
||||
.filter_map(|allocator| allocator.current())
|
||||
.collect::<HashSet<_>>();
|
||||
if addresses.len() == allocators.len() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
panic!("simultaneous allocations did not converge");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_advertised_current_subnet_and_uses_deterministic_fallback() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
allocator.commit(Some("10.2.0.8/24".parse().unwrap()));
|
||||
let used = HashSet::from([
|
||||
"10.1.0.2/24".parse().unwrap(),
|
||||
"10.2.0.2/24".parse().unwrap(),
|
||||
]);
|
||||
for _ in 0..20 {
|
||||
assert_eq!(allocator.evaluate(true, &used), DhcpIpv4Decision::Unchanged);
|
||||
}
|
||||
allocator.reset();
|
||||
assert_eq!(
|
||||
allocator.evaluate(true, &used),
|
||||
DhcpIpv4Decision::Change {
|
||||
previous: None,
|
||||
next: Some("10.1.0.1/24".parse().unwrap()),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn keeps_current_address_when_it_is_free_in_the_selected_subnet() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
allocator.commit(Some("10.1.2.8/24".parse().unwrap()));
|
||||
let used = HashSet::from(["10.1.2.2/24".parse().unwrap()]);
|
||||
|
||||
assert_eq!(allocator.evaluate(true, &used), DhcpIpv4Decision::Unchanged);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn selects_an_unused_host_after_a_conflict() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
allocator.commit(Some("10.1.2.1/24".parse().unwrap()));
|
||||
let used = HashSet::from([
|
||||
"10.1.2.1/24".parse().unwrap(),
|
||||
"10.1.2.2/24".parse().unwrap(),
|
||||
]);
|
||||
|
||||
let DhcpIpv4Decision::Change {
|
||||
previous,
|
||||
next: Some(next),
|
||||
} = allocator.evaluate(true, &used)
|
||||
else {
|
||||
panic!("expected conflict resolution");
|
||||
};
|
||||
assert_eq!(previous, Some("10.1.2.1/24".parse().unwrap()));
|
||||
assert!(!used.contains(&next));
|
||||
assert_eq!(next.network(), previous.unwrap().network());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_forgets_the_previous_interface_address() {
|
||||
let mut allocator = DhcpIpv4Allocator::default();
|
||||
allocator.commit(Some("10.1.2.8/24".parse().unwrap()));
|
||||
|
||||
allocator.reset();
|
||||
|
||||
assert_eq!(allocator.current(), None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_bootstraps_ipv4_when_no_peer_has_one() {
|
||||
check_service_bootstrap(true).await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_bootstraps_ipv4_without_other_peers() {
|
||||
check_service_bootstrap(false).await;
|
||||
}
|
||||
|
||||
async fn check_service_bootstrap(has_routes: bool) {
|
||||
let host = Arc::new(RecordingHost::default());
|
||||
let (service, runtime_config) = service(
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes,
|
||||
used_ipv4: HashSet::new(),
|
||||
},
|
||||
host.clone(),
|
||||
);
|
||||
|
||||
for _ in 0..BOOTSTRAP_WAIT_ROUNDS {
|
||||
assert_eq!(service.reconcile_once().await, has_routes);
|
||||
}
|
||||
|
||||
assert_eq!(service.current(), None);
|
||||
assert!(host.changes.lock().unwrap().is_empty());
|
||||
assert!(host.published.lock().unwrap().is_empty());
|
||||
assert!(
|
||||
runtime_config
|
||||
.snapshot()
|
||||
.peer
|
||||
.runtime
|
||||
.core
|
||||
.routes
|
||||
.ipv4
|
||||
.is_none()
|
||||
);
|
||||
|
||||
assert_eq!(service.reconcile_once().await, has_routes);
|
||||
let address = service.current().expect("bootstrap address");
|
||||
assert_eq!(
|
||||
address.network(),
|
||||
"10.126.126.0/24".parse::<Ipv4Inet>().unwrap().network()
|
||||
);
|
||||
assert_eq!(*host.changes.lock().unwrap(), [(None, Some(address))]);
|
||||
assert_eq!(
|
||||
runtime_config.snapshot().peer.runtime.core.routes.ipv4,
|
||||
Some(IpPrefix {
|
||||
address: address.address().into(),
|
||||
prefix_len: address.network_length(),
|
||||
})
|
||||
);
|
||||
assert_eq!(service.reconcile_once().await, has_routes);
|
||||
assert_eq!(service.current(), Some(address));
|
||||
assert_eq!(host.changes.lock().unwrap().len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_commits_only_after_host_apply_succeeds() {
|
||||
let host = Arc::new(RecordingHost::default());
|
||||
let (service, runtime_config) = service(
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes: true,
|
||||
used_ipv4: HashSet::from(["198.18.0.2/24".parse().unwrap()]),
|
||||
},
|
||||
host.clone(),
|
||||
);
|
||||
|
||||
assert!(service.reconcile_once().await);
|
||||
|
||||
assert_eq!(service.current(), Some("198.18.0.1/24".parse().unwrap()));
|
||||
assert_eq!(
|
||||
*host.changes.lock().unwrap(),
|
||||
[(None, Some("198.18.0.1/24".parse().unwrap()))]
|
||||
);
|
||||
assert_eq!(
|
||||
runtime_config.snapshot().peer.runtime.core.routes.ipv4,
|
||||
Some(IpPrefix::new("198.18.0.1".parse().unwrap(), 24).unwrap())
|
||||
);
|
||||
assert_eq!(
|
||||
*host.published.lock().unwrap(),
|
||||
[(
|
||||
None,
|
||||
Some("198.18.0.1/24".parse().unwrap()),
|
||||
Some("198.18.0.1/24".parse().unwrap())
|
||||
)]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_holds_host_permit_through_store_and_event_commit() {
|
||||
let host = Arc::new(RecordingHost::default());
|
||||
host.hold_apply_permit.store(true, Ordering::Release);
|
||||
let (service, _runtime_config) = service(
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes: true,
|
||||
used_ipv4: HashSet::from(["198.18.0.2/24".parse().unwrap()]),
|
||||
},
|
||||
host.clone(),
|
||||
);
|
||||
|
||||
service.reconcile_once().await;
|
||||
|
||||
let expected = Some(IpPrefix::new("198.18.0.1".parse().unwrap(), 24).unwrap());
|
||||
assert!(host.published_with_permit.load(Ordering::Acquire));
|
||||
assert_eq!(
|
||||
host.published_runtime_ipv4.lock().unwrap().as_slice(),
|
||||
&[expected]
|
||||
);
|
||||
assert!(!host.permit_held.load(Ordering::Acquire));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn service_retries_change_when_host_apply_fails() {
|
||||
let host = Arc::new(RecordingHost::default());
|
||||
host.fail_apply.store(true, Ordering::Release);
|
||||
let (service, runtime_config) = service(
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes: true,
|
||||
used_ipv4: HashSet::from(["198.18.0.2/24".parse().unwrap()]),
|
||||
},
|
||||
host.clone(),
|
||||
);
|
||||
|
||||
service.reconcile_once().await;
|
||||
service.reconcile_once().await;
|
||||
|
||||
assert_eq!(service.current(), None);
|
||||
assert_eq!(host.changes.lock().unwrap().len(), 2);
|
||||
assert_eq!(
|
||||
runtime_config.snapshot().peer.runtime.core.routes.ipv4,
|
||||
None
|
||||
);
|
||||
assert!(host.published.lock().unwrap().is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interface_close_resets_previous_allocation_before_reapply() {
|
||||
let host = Arc::new(RecordingHost::default());
|
||||
let (service, _runtime_config) = service(
|
||||
DhcpIpv4RouteSnapshot {
|
||||
has_routes: true,
|
||||
used_ipv4: HashSet::from(["198.18.0.2/24".parse().unwrap()]),
|
||||
},
|
||||
host.clone(),
|
||||
);
|
||||
service.reconcile_once().await;
|
||||
host.interface_closed.store(true, Ordering::Release);
|
||||
|
||||
service.reconcile_once().await;
|
||||
|
||||
assert_eq!(
|
||||
host.changes.lock().unwrap().as_slice(),
|
||||
[
|
||||
(None, Some("198.18.0.1/24".parse().unwrap())),
|
||||
(None, Some("198.18.0.1/24".parse().unwrap())),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
mod records;
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
mod packet;
|
||||
|
||||
pub use records::{
|
||||
MagicDnsRecordSnapshot, MagicDnsRecordStore, MagicDnsRoute, MagicDnsRouteAdvertisement,
|
||||
MagicDnsRoutePublisher, MagicDnsRouteSnapshot, MagicDnsRouteSource,
|
||||
run_magic_dns_route_publisher,
|
||||
};
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) use packet::magic_dns_packet_filter;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub use packet::{
|
||||
MagicDnsQuery, MagicDnsQueryResolver, MagicDnsResolverRegistration, process_magic_dns_packet,
|
||||
};
|
||||
@@ -0,0 +1,449 @@
|
||||
use std::{future::Future, net::Ipv4Addr};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use smoltcp::wire::{
|
||||
IPV4_HEADER_LEN, Icmpv4Message, Icmpv4Packet, IpAddress, IpProtocol, Ipv4Packet,
|
||||
UDP_HEADER_LEN, UdpPacket,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::PeerId,
|
||||
packet::ZCPacket,
|
||||
peers::{BoxNicPacketFilter, NicPacketFilter},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MagicDnsQuery {
|
||||
pub source: std::net::SocketAddr,
|
||||
pub payload: Vec<u8>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait MagicDnsQueryResolver: Send + Sync + 'static {
|
||||
async fn resolve(&self, query: MagicDnsQuery) -> Option<Vec<u8>>;
|
||||
}
|
||||
|
||||
/// Owns one Magic DNS resolver installed in the core NIC pipeline.
|
||||
///
|
||||
/// `close` waits until readers that may already be invoking the resolver have
|
||||
/// finished, then removes the entry so the resolver can be dropped promptly.
|
||||
pub struct MagicDnsResolverRegistration {
|
||||
peer_manager: std::sync::Weak<crate::peers::peer_manager::PeerManagerCore>,
|
||||
pipeline: crate::peers::peer_manager::PipelineRegistrationGuard,
|
||||
runtime: tokio::runtime::Handle,
|
||||
}
|
||||
|
||||
impl MagicDnsResolverRegistration {
|
||||
pub(crate) fn new(
|
||||
peer_manager: std::sync::Weak<crate::peers::peer_manager::PeerManagerCore>,
|
||||
pipeline: crate::peers::peer_manager::PipelineRegistrationGuard,
|
||||
runtime: tokio::runtime::Handle,
|
||||
) -> Self {
|
||||
Self {
|
||||
peer_manager,
|
||||
pipeline,
|
||||
runtime,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn close(&self) {
|
||||
self.pipeline.close();
|
||||
if let Some(peer_manager) = self.peer_manager.upgrade() {
|
||||
peer_manager
|
||||
.remove_managed_nic_packet_process_pipeline(&self.pipeline)
|
||||
.await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for MagicDnsResolverRegistration {
|
||||
fn drop(&mut self) {
|
||||
self.pipeline.close();
|
||||
let Some(peer_manager) = self.peer_manager.upgrade() else {
|
||||
return;
|
||||
};
|
||||
let pipeline = self.pipeline.clone();
|
||||
self.runtime.spawn(async move {
|
||||
peer_manager
|
||||
.remove_managed_nic_packet_process_pipeline(&pipeline)
|
||||
.await;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct MagicDnsPacketFilter {
|
||||
fake_ip: Ipv4Addr,
|
||||
my_peer_id: PeerId,
|
||||
resolver: std::sync::Arc<dyn MagicDnsQueryResolver>,
|
||||
}
|
||||
|
||||
pub(crate) fn magic_dns_packet_filter(
|
||||
fake_ip: Ipv4Addr,
|
||||
my_peer_id: PeerId,
|
||||
resolver: std::sync::Arc<dyn MagicDnsQueryResolver>,
|
||||
) -> BoxNicPacketFilter {
|
||||
Box::new(MagicDnsPacketFilter {
|
||||
fake_ip,
|
||||
my_peer_id,
|
||||
resolver,
|
||||
})
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl NicPacketFilter for MagicDnsPacketFilter {
|
||||
async fn try_process_packet_from_nic(&self, packet: &mut ZCPacket) -> bool {
|
||||
process_magic_dns_packet(packet, self.fake_ip, self.my_peer_id, |query| {
|
||||
self.resolver.resolve(query)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn id(&self) -> String {
|
||||
"magic_dns_server".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn process_magic_dns_packet<F, Fut>(
|
||||
packet: &mut ZCPacket,
|
||||
fake_ip: Ipv4Addr,
|
||||
my_peer_id: PeerId,
|
||||
resolve: F,
|
||||
) -> bool
|
||||
where
|
||||
F: FnOnce(MagicDnsQuery) -> Fut,
|
||||
Fut: Future<Output = Option<Vec<u8>>>,
|
||||
{
|
||||
if packet.peer_manager_header().is_none() {
|
||||
return false;
|
||||
}
|
||||
if packet.payload().len() < IPV4_HEADER_LEN {
|
||||
return false;
|
||||
}
|
||||
let ip_packet = Ipv4Packet::new_unchecked(packet.payload());
|
||||
if ip_packet.version() != 4 || ip_packet.dst_addr() != fake_ip {
|
||||
return false;
|
||||
}
|
||||
|
||||
let ip_header_length = ip_packet.header_len() as usize;
|
||||
let ip_total_length = ip_packet.total_len() as usize;
|
||||
if ip_header_length < IPV4_HEADER_LEN
|
||||
|| ip_header_length > ip_total_length
|
||||
|| ip_total_length != packet.payload().len()
|
||||
|| ip_packet.frag_offset() != 0
|
||||
|| ip_packet.more_frags()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
let protocol = ip_packet.next_header();
|
||||
let source_ip = ip_packet.src_addr();
|
||||
let destination_ip = ip_packet.dst_addr();
|
||||
|
||||
match protocol {
|
||||
IpProtocol::Udp => {
|
||||
let ip_payload = &packet.payload()[ip_header_length..ip_total_length];
|
||||
if ip_payload.len() < UDP_HEADER_LEN {
|
||||
return false;
|
||||
}
|
||||
let udp_packet = UdpPacket::new_unchecked(ip_payload);
|
||||
let udp_length = udp_packet.len() as usize;
|
||||
if udp_length != ip_payload.len() || udp_length < UDP_HEADER_LEN {
|
||||
return false;
|
||||
}
|
||||
if udp_packet.dst_port() != 53 {
|
||||
return false;
|
||||
}
|
||||
let source_port = udp_packet.src_port();
|
||||
let destination_port = udp_packet.dst_port();
|
||||
let query = MagicDnsQuery {
|
||||
source: std::net::SocketAddr::from((source_ip, source_port)),
|
||||
payload: udp_packet.payload().to_vec(),
|
||||
};
|
||||
let Some(response) = resolve(query).await else {
|
||||
return false;
|
||||
};
|
||||
if !apply_udp_response(
|
||||
packet,
|
||||
source_ip,
|
||||
destination_ip,
|
||||
source_port,
|
||||
destination_port,
|
||||
ip_header_length,
|
||||
&response,
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
IpProtocol::Icmp => {
|
||||
let Ok(icmp_packet) = Icmpv4Packet::new_checked(&packet.payload()[ip_header_length..])
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
if icmp_packet.msg_type() != Icmpv4Message::EchoRequest {
|
||||
return false;
|
||||
}
|
||||
let mut icmp_packet =
|
||||
Icmpv4Packet::new_unchecked(&mut packet.mut_payload()[ip_header_length..]);
|
||||
icmp_packet.set_msg_type(Icmpv4Message::EchoReply);
|
||||
icmp_packet.fill_checksum();
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
|
||||
let mut ip_packet = Ipv4Packet::new_unchecked(packet.mut_payload());
|
||||
ip_packet.set_src_addr(destination_ip);
|
||||
ip_packet.set_dst_addr(source_ip);
|
||||
ip_packet.fill_checksum();
|
||||
let payload_length = packet.payload().len() as u32;
|
||||
let Some(header) = packet.mut_peer_manager_header() else {
|
||||
return false;
|
||||
};
|
||||
header.to_peer_id = my_peer_id.into();
|
||||
header.len.set(payload_length);
|
||||
true
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn apply_udp_response(
|
||||
packet: &mut ZCPacket,
|
||||
source_ip: Ipv4Addr,
|
||||
destination_ip: Ipv4Addr,
|
||||
source_port: u16,
|
||||
destination_port: u16,
|
||||
ip_header_length: usize,
|
||||
response: &[u8],
|
||||
) -> bool {
|
||||
let Some(udp_length) = UDP_HEADER_LEN.checked_add(response.len()) else {
|
||||
return false;
|
||||
};
|
||||
let Some(ip_length) = ip_header_length.checked_add(udp_length) else {
|
||||
return false;
|
||||
};
|
||||
if ip_length > u16::MAX as usize {
|
||||
return false;
|
||||
}
|
||||
let Some(header_length) = packet.buf_len().checked_sub(packet.payload().len()) else {
|
||||
return false;
|
||||
};
|
||||
let Some(inner_length) = header_length.checked_add(ip_length) else {
|
||||
return false;
|
||||
};
|
||||
|
||||
if packet.mut_inner().capacity() < inner_length {
|
||||
packet
|
||||
.mut_inner()
|
||||
.truncate(header_length + ip_header_length + UDP_HEADER_LEN);
|
||||
}
|
||||
packet.mut_inner().resize(inner_length, 0);
|
||||
|
||||
let mut ip_packet = Ipv4Packet::new_unchecked(packet.mut_payload());
|
||||
ip_packet.set_total_len(ip_length as u16);
|
||||
let mut udp_packet = UdpPacket::new_unchecked(ip_packet.payload_mut());
|
||||
udp_packet.set_len(udp_length as u16);
|
||||
udp_packet.set_src_port(destination_port);
|
||||
udp_packet.set_dst_port(source_port);
|
||||
udp_packet.payload_mut().copy_from_slice(response);
|
||||
udp_packet.fill_checksum(
|
||||
&IpAddress::Ipv4(destination_ip),
|
||||
&IpAddress::Ipv4(source_ip),
|
||||
);
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn udp_query(payload: &[u8], destination_port: u16) -> ZCPacket {
|
||||
let mut bytes = vec![0; 20 + 8 + payload.len()];
|
||||
{
|
||||
let mut ip = Ipv4Packet::new_unchecked(&mut bytes);
|
||||
ip.set_version(4);
|
||||
ip.set_header_len(20);
|
||||
ip.set_total_len((20 + 8 + payload.len()) as u16);
|
||||
ip.set_next_header(IpProtocol::Udp);
|
||||
ip.set_src_addr("10.0.0.2".parse().unwrap());
|
||||
ip.set_dst_addr("100.100.100.101".parse().unwrap());
|
||||
let mut udp = UdpPacket::new_unchecked(ip.payload_mut());
|
||||
udp.set_src_port(53000);
|
||||
udp.set_dst_port(destination_port);
|
||||
udp.set_len((8 + payload.len()) as u16);
|
||||
udp.payload_mut().copy_from_slice(payload);
|
||||
}
|
||||
ZCPacket::new_with_payload(&bytes)
|
||||
}
|
||||
|
||||
fn icmp_echo_request() -> ZCPacket {
|
||||
let mut bytes = vec![0; 20 + 8];
|
||||
{
|
||||
let mut ip = Ipv4Packet::new_unchecked(&mut bytes);
|
||||
ip.set_version(4);
|
||||
ip.set_header_len(20);
|
||||
ip.set_total_len(28);
|
||||
ip.set_next_header(IpProtocol::Icmp);
|
||||
ip.set_src_addr("10.0.0.2".parse().unwrap());
|
||||
ip.set_dst_addr("100.100.100.101".parse().unwrap());
|
||||
let mut icmp = Icmpv4Packet::new_unchecked(ip.payload_mut());
|
||||
icmp.set_msg_type(Icmpv4Message::EchoRequest);
|
||||
}
|
||||
ZCPacket::new_with_payload(&bytes)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rewrites_dns_query_response() {
|
||||
let mut packet = udp_query(b"query", 53);
|
||||
let handled = process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|query| async move {
|
||||
assert_eq!(query.source, "10.0.0.2:53000".parse().unwrap());
|
||||
assert_eq!(query.payload, b"query");
|
||||
Some(b"response".to_vec())
|
||||
},
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(handled);
|
||||
let ip = Ipv4Packet::new_checked(packet.payload()).unwrap();
|
||||
assert_eq!(
|
||||
ip.src_addr(),
|
||||
"100.100.100.101".parse::<Ipv4Addr>().unwrap()
|
||||
);
|
||||
assert_eq!(ip.dst_addr(), "10.0.0.2".parse::<Ipv4Addr>().unwrap());
|
||||
let udp = UdpPacket::new_checked(ip.payload()).unwrap();
|
||||
assert_eq!(udp.src_port(), 53);
|
||||
assert_eq!(udp.dst_port(), 53000);
|
||||
assert_eq!(udp.payload(), b"response");
|
||||
assert_eq!(packet.get_dst_peer_id(), Some(42));
|
||||
assert_eq!(
|
||||
packet.peer_manager_header().unwrap().len.get() as usize,
|
||||
packet.payload().len()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rejects_invalid_ipv4_header_without_mutation() {
|
||||
let mut packet = udp_query(b"query", 53);
|
||||
Ipv4Packet::new_unchecked(packet.mut_payload()).set_header_len(60);
|
||||
let original = packet.payload().to_vec();
|
||||
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { panic!("invalid IPv4 header must not invoke DNS") },
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert_eq!(packet.payload(), original);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rejects_short_zc_packet_without_panicking() {
|
||||
let mut packet =
|
||||
ZCPacket::new_from_buf(Default::default(), crate::packet::ZCPacketType::NIC);
|
||||
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { panic!("short packet must not invoke DNS") },
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rejects_inconsistent_udp_length_without_mutation() {
|
||||
let mut packet = udp_query(b"query", 53);
|
||||
let mut ip = Ipv4Packet::new_unchecked(packet.mut_payload());
|
||||
UdpPacket::new_unchecked(ip.payload_mut()).set_len(8);
|
||||
let original = packet.payload().to_vec();
|
||||
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { panic!("invalid UDP length must not invoke DNS") },
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert_eq!(packet.payload(), original);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rejects_fragmented_packets_without_mutation() {
|
||||
let mut packet = udp_query(b"query", 53);
|
||||
Ipv4Packet::new_unchecked(packet.mut_payload()).set_more_frags(true);
|
||||
let original = packet.payload().to_vec();
|
||||
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { panic!("fragmented packet must not invoke DNS") },
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert_eq!(packet.payload(), original);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_rejects_oversized_response_without_mutation() {
|
||||
let mut packet = udp_query(b"query", 53);
|
||||
let original = packet.payload().to_vec();
|
||||
let original_length = packet.buf_len();
|
||||
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { Some(vec![0; u16::MAX as usize]) },
|
||||
)
|
||||
.await
|
||||
);
|
||||
assert_eq!(packet.buf_len(), original_length);
|
||||
assert_eq!(packet.payload(), original);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_replies_to_icmp_without_calling_dns() {
|
||||
let mut packet = icmp_echo_request();
|
||||
let handled = process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
7,
|
||||
|_| async { panic!("ICMP must not invoke DNS") },
|
||||
)
|
||||
.await;
|
||||
|
||||
assert!(handled);
|
||||
let ip = Ipv4Packet::new_checked(packet.payload()).unwrap();
|
||||
assert_eq!(
|
||||
ip.src_addr(),
|
||||
"100.100.100.101".parse::<Ipv4Addr>().unwrap()
|
||||
);
|
||||
let icmp = Icmpv4Packet::new_checked(ip.payload()).unwrap();
|
||||
assert_eq!(icmp.msg_type(), Icmpv4Message::EchoReply);
|
||||
assert_eq!(packet.get_dst_peer_id(), Some(7));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn packet_engine_ignores_non_dns_udp() {
|
||||
let mut packet = udp_query(b"query", 5353);
|
||||
assert!(
|
||||
!process_magic_dns_packet(
|
||||
&mut packet,
|
||||
"100.100.100.101".parse().unwrap(),
|
||||
42,
|
||||
|_| async { Some(Vec::new()) },
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
use std::{collections::BTreeMap, net::Ipv4Addr, sync::Mutex, time::Duration};
|
||||
|
||||
use async_trait::async_trait;
|
||||
use quanta::Instant;
|
||||
|
||||
use crate::peers::peer_manager::PeerManagerCore;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MagicDnsRoute {
|
||||
pub hostname: String,
|
||||
pub ipv4_addr: Option<Ipv4Addr>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MagicDnsRouteSnapshot {
|
||||
pub revision: Instant,
|
||||
pub routes: Vec<MagicDnsRouteAdvertisement>,
|
||||
pub zone: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MagicDnsRouteAdvertisement {
|
||||
pub hostname: String,
|
||||
pub ipv4_addr: Option<crate::proto::common::Ipv4Inet>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait MagicDnsRouteSource: Send + Sync {
|
||||
async fn snapshot(&self) -> MagicDnsRouteSnapshot;
|
||||
async fn revision(&self) -> Instant;
|
||||
}
|
||||
|
||||
fn magic_dns_route_advertisement(
|
||||
route: crate::proto::core_peer::peer::Route,
|
||||
) -> MagicDnsRouteAdvertisement {
|
||||
MagicDnsRouteAdvertisement {
|
||||
hostname: route.hostname,
|
||||
ipv4_addr: route.ipv4_addr,
|
||||
}
|
||||
}
|
||||
|
||||
fn magic_dns_route_snapshot(
|
||||
revision: Instant,
|
||||
routes: Vec<crate::proto::core_peer::peer::Route>,
|
||||
local_identity: (String, Option<crate::proto::common::Ipv4Inet>, String),
|
||||
) -> MagicDnsRouteSnapshot {
|
||||
let mut routes = routes
|
||||
.into_iter()
|
||||
.map(magic_dns_route_advertisement)
|
||||
.collect::<Vec<_>>();
|
||||
let (hostname, ipv4_addr, zone) = local_identity;
|
||||
routes.push(MagicDnsRouteAdvertisement {
|
||||
hostname,
|
||||
ipv4_addr,
|
||||
});
|
||||
MagicDnsRouteSnapshot {
|
||||
revision,
|
||||
routes,
|
||||
zone,
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MagicDnsRouteSource for PeerManagerCore {
|
||||
async fn snapshot(&self) -> MagicDnsRouteSnapshot {
|
||||
let revision = self.get_route().get_peer_info_last_update_time().await;
|
||||
magic_dns_route_snapshot(
|
||||
revision,
|
||||
self.list_route_snapshots().await,
|
||||
self.dns_route_identity(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn revision(&self) -> Instant {
|
||||
self.get_route().get_peer_info_last_update_time().await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait MagicDnsRoutePublisher: Send {
|
||||
async fn handshake(&mut self) -> anyhow::Result<()>;
|
||||
async fn heartbeat(&mut self) -> anyhow::Result<()>;
|
||||
async fn publish(&mut self, snapshot: &MagicDnsRouteSnapshot) -> anyhow::Result<()>;
|
||||
}
|
||||
|
||||
pub async fn run_magic_dns_route_publisher<S, P>(
|
||||
source: &S,
|
||||
publisher: &mut P,
|
||||
unchanged_interval: Duration,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
S: MagicDnsRouteSource + ?Sized,
|
||||
P: MagicDnsRoutePublisher + ?Sized,
|
||||
{
|
||||
let mut published_revision = None;
|
||||
publisher.handshake().await?;
|
||||
loop {
|
||||
publisher.heartbeat().await?;
|
||||
|
||||
let snapshot = source.snapshot().await;
|
||||
if published_revision == Some(snapshot.revision) {
|
||||
crate::foundation::time::sleep(unchanged_interval).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
publisher.publish(&snapshot).await?;
|
||||
if source.revision().await == snapshot.revision {
|
||||
published_revision = Some(snapshot.revision);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MagicDnsRecordSnapshot {
|
||||
pub zones: BTreeMap<String, Vec<MagicDnsRoute>>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct MagicDnsRecordStore {
|
||||
zones: Mutex<BTreeMap<String, BTreeMap<String, Vec<MagicDnsRoute>>>>,
|
||||
}
|
||||
|
||||
impl MagicDnsRecordStore {
|
||||
/// Replaces one client's routes within a zone.
|
||||
///
|
||||
/// Returns `true` when the update removed the final client from an
|
||||
/// existing zone. The host can use that signal to keep an empty zone
|
||||
/// authoritative.
|
||||
pub fn replace_client_routes(
|
||||
&self,
|
||||
zone: String,
|
||||
client: String,
|
||||
routes: Vec<MagicDnsRoute>,
|
||||
) -> bool {
|
||||
let mut zones = self.zones.lock().unwrap();
|
||||
let Some(routes_by_client) = zones.get_mut(&zone) else {
|
||||
if !routes.is_empty() {
|
||||
zones.entry(zone).or_default().insert(client, routes);
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
routes_by_client.remove(&client);
|
||||
if !routes.is_empty() {
|
||||
routes_by_client.insert(client, routes);
|
||||
}
|
||||
if !routes_by_client.is_empty() {
|
||||
return false;
|
||||
}
|
||||
zones.remove(&zone);
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes a disconnected client from every zone and returns the zones
|
||||
/// that became empty.
|
||||
pub fn remove_client(&self, client: &str) -> Vec<String> {
|
||||
let mut zones = self.zones.lock().unwrap();
|
||||
let mut removed_zones = Vec::new();
|
||||
zones.retain(|zone, routes_by_client| {
|
||||
routes_by_client.remove(client);
|
||||
let retain = !routes_by_client.is_empty();
|
||||
if !retain {
|
||||
removed_zones.push(zone.clone());
|
||||
}
|
||||
retain
|
||||
});
|
||||
removed_zones
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> MagicDnsRecordSnapshot {
|
||||
let zones = self.zones.lock().unwrap();
|
||||
MagicDnsRecordSnapshot {
|
||||
zones: zones
|
||||
.iter()
|
||||
.map(|(zone, routes_by_client)| {
|
||||
(
|
||||
zone.clone(),
|
||||
routes_by_client
|
||||
.values()
|
||||
.flat_map(|routes| routes.iter().cloned())
|
||||
.collect(),
|
||||
)
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn route_advertisement_preserves_untrusted_prefix_without_parsing() {
|
||||
let ipv4_addr = crate::proto::common::Ipv4Inet {
|
||||
address: Some("192.0.2.1".parse::<std::net::Ipv4Addr>().unwrap().into()),
|
||||
network_length: 33,
|
||||
};
|
||||
|
||||
let advertisement = magic_dns_route_advertisement(crate::proto::core_peer::peer::Route {
|
||||
hostname: "remote".to_owned(),
|
||||
ipv4_addr: Some(ipv4_addr),
|
||||
..Default::default()
|
||||
});
|
||||
|
||||
assert_eq!(advertisement.ipv4_addr, Some(ipv4_addr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn route_snapshot_appends_local_identity() {
|
||||
let ipv4_addr: crate::proto::common::Ipv4Inet =
|
||||
"10.20.0.91/16".parse::<cidr::Ipv4Inet>().unwrap().into();
|
||||
let snapshot = magic_dns_route_snapshot(
|
||||
Instant::now(),
|
||||
Vec::new(),
|
||||
(
|
||||
"portable-node".to_owned(),
|
||||
Some(ipv4_addr),
|
||||
"et.net.".to_owned(),
|
||||
),
|
||||
);
|
||||
|
||||
assert_eq!(snapshot.zone, "et.net.");
|
||||
assert_eq!(
|
||||
snapshot.routes,
|
||||
[MagicDnsRouteAdvertisement {
|
||||
hostname: "portable-node".to_owned(),
|
||||
ipv4_addr: Some(ipv4_addr),
|
||||
}]
|
||||
);
|
||||
}
|
||||
|
||||
struct TestRouteSource {
|
||||
revision: Mutex<Instant>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MagicDnsRouteSource for TestRouteSource {
|
||||
async fn snapshot(&self) -> MagicDnsRouteSnapshot {
|
||||
MagicDnsRouteSnapshot {
|
||||
revision: *self.revision.lock().unwrap(),
|
||||
routes: vec![MagicDnsRouteAdvertisement {
|
||||
hostname: "node-a".to_owned(),
|
||||
ipv4_addr: Some("10.1.0.1/24".parse::<cidr::Ipv4Inet>().unwrap().into()),
|
||||
}],
|
||||
zone: "et.net.".to_owned(),
|
||||
}
|
||||
}
|
||||
|
||||
async fn revision(&self) -> Instant {
|
||||
*self.revision.lock().unwrap()
|
||||
}
|
||||
}
|
||||
|
||||
struct TestRoutePublisher {
|
||||
source: Arc<TestRouteSource>,
|
||||
heartbeat_calls: usize,
|
||||
fail_heartbeat_at: usize,
|
||||
change_revision_on_first_publish: bool,
|
||||
handshake_calls: usize,
|
||||
snapshots: Vec<MagicDnsRouteSnapshot>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl MagicDnsRoutePublisher for TestRoutePublisher {
|
||||
async fn handshake(&mut self) -> anyhow::Result<()> {
|
||||
self.handshake_calls += 1;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn heartbeat(&mut self) -> anyhow::Result<()> {
|
||||
self.heartbeat_calls += 1;
|
||||
if self.heartbeat_calls == self.fail_heartbeat_at {
|
||||
anyhow::bail!("stop test publisher");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn publish(&mut self, snapshot: &MagicDnsRouteSnapshot) -> anyhow::Result<()> {
|
||||
self.snapshots.push(snapshot.clone());
|
||||
if self.change_revision_on_first_publish && self.snapshots.len() == 1 {
|
||||
*self.source.revision.lock().unwrap() = snapshot.revision + Duration::from_secs(1);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn test_publisher(source: Arc<TestRouteSource>) -> TestRoutePublisher {
|
||||
TestRoutePublisher {
|
||||
source,
|
||||
heartbeat_calls: 0,
|
||||
fail_heartbeat_at: 3,
|
||||
change_revision_on_first_publish: false,
|
||||
handshake_calls: 0,
|
||||
snapshots: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn route_publisher_skips_unchanged_snapshot() {
|
||||
let source = Arc::new(TestRouteSource {
|
||||
revision: Mutex::new(Instant::now()),
|
||||
});
|
||||
let mut publisher = test_publisher(source.clone());
|
||||
|
||||
let error = run_magic_dns_route_publisher(
|
||||
source.as_ref(),
|
||||
&mut publisher,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("stop test publisher"));
|
||||
assert_eq!(publisher.handshake_calls, 1);
|
||||
assert_eq!(publisher.snapshots.len(), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn route_publisher_retries_change_during_publish() {
|
||||
let source = Arc::new(TestRouteSource {
|
||||
revision: Mutex::new(Instant::now()),
|
||||
});
|
||||
let mut publisher = test_publisher(source.clone());
|
||||
publisher.change_revision_on_first_publish = true;
|
||||
|
||||
let error = run_magic_dns_route_publisher(
|
||||
source.as_ref(),
|
||||
&mut publisher,
|
||||
Duration::from_millis(1),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
|
||||
assert!(error.to_string().contains("stop test publisher"));
|
||||
assert_eq!(publisher.snapshots.len(), 2);
|
||||
assert_ne!(
|
||||
publisher.snapshots[0].revision,
|
||||
publisher.snapshots[1].revision
|
||||
);
|
||||
}
|
||||
|
||||
fn route(hostname: &str, addr: [u8; 4]) -> MagicDnsRoute {
|
||||
MagicDnsRoute {
|
||||
hostname: hostname.to_owned(),
|
||||
ipv4_addr: Some(addr.into()),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaces_routes_for_the_same_client_without_touching_other_clients() {
|
||||
let store = MagicDnsRecordStore::default();
|
||||
assert!(!store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-a".to_owned(),
|
||||
vec![route("old-a", [10, 0, 0, 1])],
|
||||
));
|
||||
assert!(!store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-b".to_owned(),
|
||||
vec![route("peer-b", [10, 0, 0, 2])],
|
||||
));
|
||||
assert!(!store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-a".to_owned(),
|
||||
vec![route("new-a", [10, 0, 0, 3])],
|
||||
));
|
||||
|
||||
let routes = &store.snapshot().zones["et.net."];
|
||||
assert_eq!(routes.len(), 2);
|
||||
assert!(routes.iter().any(|route| route.hostname == "new-a"));
|
||||
assert!(routes.iter().any(|route| route.hostname == "peer-b"));
|
||||
assert!(!routes.iter().any(|route| route.hostname == "old-a"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_update_removes_only_the_target_client_and_reports_empty_zone() {
|
||||
let store = MagicDnsRecordStore::default();
|
||||
store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-a".to_owned(),
|
||||
vec![route("peer-a", [10, 0, 0, 1])],
|
||||
);
|
||||
store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-b".to_owned(),
|
||||
vec![route("peer-b", [10, 0, 0, 2])],
|
||||
);
|
||||
|
||||
assert!(!store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-a".to_owned(),
|
||||
Vec::new(),
|
||||
));
|
||||
assert!(store.replace_client_routes(
|
||||
"et.net.".to_owned(),
|
||||
"tcp://client-b".to_owned(),
|
||||
Vec::new(),
|
||||
));
|
||||
assert!(store.snapshot().zones.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disconnect_removes_client_from_all_zones() {
|
||||
let store = MagicDnsRecordStore::default();
|
||||
for zone in ["a.et.net.", "b.et.net."] {
|
||||
store.replace_client_routes(
|
||||
zone.to_owned(),
|
||||
"tcp://client-a".to_owned(),
|
||||
vec![route("peer-a", [10, 0, 0, 1])],
|
||||
);
|
||||
}
|
||||
store.replace_client_routes(
|
||||
"b.et.net.".to_owned(),
|
||||
"tcp://client-b".to_owned(),
|
||||
vec![route("peer-b", [10, 0, 0, 2])],
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
store.remove_client("tcp://client-a"),
|
||||
vec!["a.et.net.".to_owned()]
|
||||
);
|
||||
let snapshot = store.snapshot();
|
||||
assert_eq!(snapshot.zones.len(), 1);
|
||||
assert_eq!(snapshot.zones["b.et.net."][0].hostname, "peer-b");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
//! Packet-plane features: the gateway dataplane, proxy services, and the
|
||||
//! instance-level network services. See `CONTEXT.md` "Gateway dataplane"
|
||||
//! and "Module layers".
|
||||
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
mod dataplane;
|
||||
pub mod dhcp;
|
||||
pub mod magic_dns;
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
mod port_forward;
|
||||
pub mod proxy;
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
mod smoltcp;
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
mod socks5;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub mod udp_broadcast;
|
||||
pub mod vpn_portal;
|
||||
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
pub(crate) use dataplane::DataPlaneRuntime;
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
pub use dataplane::{
|
||||
DataPlaneCompletionDescriptor, DataPlaneCompletionStatus, DataPlaneError, DataPlaneErrorKind,
|
||||
DataPlaneOperationId, DataPlaneOperationKind, DataPlaneOperationOutcome,
|
||||
DataPlaneOperationResult, DataPlaneResourceId, DataPlaneSession, DataPlaneSessionLimits,
|
||||
DataPlaneTcpListener, DataPlaneTcpStream, DataPlaneUdpSocket,
|
||||
};
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
pub(crate) use port_forward::PortForwardAdapter;
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
pub(crate) use socks5::Socks5GatewayAdapter;
|
||||
@@ -0,0 +1,911 @@
|
||||
//! Host port-forward adapter backed by the data-plane runtime.
|
||||
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use crossbeam_utils::atomic::AtomicCell;
|
||||
use dashmap::DashMap;
|
||||
use quanta::Instant;
|
||||
use tokio::{
|
||||
select,
|
||||
sync::{Mutex, OwnedMutexGuard, OwnedSemaphorePermit, Semaphore},
|
||||
task::JoinSet,
|
||||
};
|
||||
use tokio_util::{
|
||||
sync::{CancellationToken, DropGuard},
|
||||
task::AbortOnDropHandle,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
config::{gateway::PortForwardConfig, runtime::CoreRuntimeConfigStore},
|
||||
events::{CoreEvent, CoreEventSink},
|
||||
foundation::task::reap_joinset_background,
|
||||
gateway::dataplane::{
|
||||
DataPlaneConsumerLease, DataPlaneRuntime, DataPlaneTcpConnectOptions, DataPlaneTcpStream,
|
||||
DataPlaneUdpSocket,
|
||||
},
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{
|
||||
TcpListenOptions, TcpSocketPurpose, VirtualTcpListener, VirtualTcpListenerFactory,
|
||||
VirtualTcpSocket, VirtualTcpSocketFactory,
|
||||
},
|
||||
udp::{UdpBindOptions, VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
const MAX_UDP_PAYLOAD_SIZE: usize = 65_507;
|
||||
const TCP_PORT_FORWARD_REBIND_DELAY: Duration = Duration::from_millis(100);
|
||||
// A remote flow owns roughly 320 KiB of smoltcp and response buffers.
|
||||
// Keep the per-instance worst case near 80 MiB instead of allowing a
|
||||
// source-port flood to grow the WASM heap without bound.
|
||||
const MAX_ACTIVE_UDP_CLIENTS: usize = 256;
|
||||
|
||||
#[derive(Debug, Eq, PartialEq, Hash, Clone)]
|
||||
struct UdpClientKey {
|
||||
client_addr: SocketAddr,
|
||||
forward: PortForwardConfig,
|
||||
}
|
||||
|
||||
enum PortForwardUdpFlow<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
Host(Arc<H::Socket>),
|
||||
DataPlane(Arc<DataPlaneUdpSocket>),
|
||||
}
|
||||
|
||||
impl<H> PortForwardUdpFlow<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
async fn send_to(&self, buf: &[u8], addr: SocketAddr) -> std::io::Result<usize> {
|
||||
match self {
|
||||
Self::Host(socket) => socket.send_to(buf, addr).await,
|
||||
Self::DataPlane(socket) => socket.send_to(buf, addr).await,
|
||||
}
|
||||
}
|
||||
|
||||
async fn recv_from(&self, buf: &mut [u8]) -> std::io::Result<(usize, SocketAddr)> {
|
||||
match self {
|
||||
Self::Host(socket) => socket.recv_from(buf).await,
|
||||
Self::DataPlane(socket) => socket.recv_from(buf).await,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpClientInfo<H>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
flow: Arc<PortForwardUdpFlow<H>>,
|
||||
last_active: AtomicCell<Instant>,
|
||||
_slot: Arc<OwnedSemaphorePermit>,
|
||||
}
|
||||
|
||||
struct UdpClientReservation {
|
||||
slot: OwnedSemaphorePermit,
|
||||
admission: OwnedMutexGuard<()>,
|
||||
}
|
||||
|
||||
pub(crate) struct PortForwardAdapter<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
operation: Mutex<()>,
|
||||
started: AtomicBool,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
data_plane: Arc<DataPlaneRuntime<H>>,
|
||||
host: Arc<H>,
|
||||
socket_context: SocketContext,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
tasks: Arc<std::sync::Mutex<JoinSet<()>>>,
|
||||
cancel_tokens: Arc<DashMap<PortForwardConfig, DropGuard>>,
|
||||
udp_clients: Arc<DashMap<UdpClientKey, Arc<UdpClientInfo<H>>>>,
|
||||
udp_response_tasks: Arc<DashMap<UdpClientKey, AbortOnDropHandle<()>>>,
|
||||
udp_client_admission: Arc<Mutex<()>>,
|
||||
udp_client_slots: Arc<Semaphore>,
|
||||
consumer_lease: Mutex<Option<DataPlaneConsumerLease>>,
|
||||
}
|
||||
|
||||
impl<H> PortForwardAdapter<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
pub(crate) fn new(
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
data_plane: Arc<DataPlaneRuntime<H>>,
|
||||
host: Arc<H>,
|
||||
socket_context: SocketContext,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
operation: Mutex::new(()),
|
||||
started: AtomicBool::new(false),
|
||||
runtime_config,
|
||||
data_plane,
|
||||
host,
|
||||
socket_context,
|
||||
events,
|
||||
tasks: Arc::new(std::sync::Mutex::new(JoinSet::new())),
|
||||
cancel_tokens: Arc::new(DashMap::new()),
|
||||
udp_clients: Arc::new(DashMap::new()),
|
||||
udp_response_tasks: Arc::new(DashMap::new()),
|
||||
udp_client_admission: Arc::new(Mutex::new(())),
|
||||
udp_client_slots: Arc::new(Semaphore::new(MAX_ACTIVE_UDP_CLIENTS)),
|
||||
consumer_lease: Mutex::new(None),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self) -> anyhow::Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
if self.started.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
self.tasks.lock().unwrap().spawn(reap_joinset_background(
|
||||
Arc::downgrade(&self.tasks),
|
||||
"port-forward adapter",
|
||||
));
|
||||
self.start_udp_reaper();
|
||||
let cfgs = self
|
||||
.runtime_config
|
||||
.snapshot()
|
||||
.services
|
||||
.gateway
|
||||
.port_forwards
|
||||
.clone();
|
||||
if let Err(error) = self.apply_port_forwards(&cfgs).await {
|
||||
self.stop_inner().await;
|
||||
return Err(error);
|
||||
}
|
||||
self.started.store(true, Ordering::Release);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn reload(&self, cfgs: &[PortForwardConfig]) -> anyhow::Result<()> {
|
||||
let _operation = self.operation.lock().await;
|
||||
if !self.started.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
self.apply_port_forwards(cfgs).await
|
||||
}
|
||||
|
||||
async fn apply_port_forwards(&self, cfgs: &[PortForwardConfig]) -> anyhow::Result<()> {
|
||||
for cfg in cfgs {
|
||||
if !matches!(cfg.proto.to_lowercase().as_str(), "tcp" | "udp") {
|
||||
anyhow::bail!(
|
||||
"unsupported protocol: {}, only support udp / tcp",
|
||||
cfg.proto
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if !cfgs.is_empty() {
|
||||
let mut consumer_lease = self.consumer_lease.lock().await;
|
||||
if consumer_lease.is_none() {
|
||||
consumer_lease.replace(self.data_plane.acquire_consumer_lease()?);
|
||||
}
|
||||
}
|
||||
|
||||
self.cancel_tokens.retain(|current, _| {
|
||||
let keep = cfgs.iter().any(|next| {
|
||||
if next.dst_addr.ip().is_unspecified() {
|
||||
current.bind_addr == next.bind_addr && current.proto == next.proto
|
||||
} else {
|
||||
current == next
|
||||
}
|
||||
});
|
||||
if !keep {
|
||||
tracing::info!(?current, "port-forward removed by runtime config reload");
|
||||
}
|
||||
keep
|
||||
});
|
||||
self.udp_clients
|
||||
.retain(|key, _| self.cancel_tokens.contains_key(&key.forward));
|
||||
self.udp_response_tasks
|
||||
.retain(|key, _| self.udp_clients.contains_key(key));
|
||||
for cfg in cfgs {
|
||||
if !self.cancel_tokens.contains_key(cfg) {
|
||||
self.add_port_forward(cfg.clone()).await?;
|
||||
}
|
||||
}
|
||||
if cfgs.is_empty() {
|
||||
self.consumer_lease.lock().await.take();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_port_forward(&self, cfg: PortForwardConfig) -> anyhow::Result<()> {
|
||||
match cfg.proto.to_lowercase().as_str() {
|
||||
"tcp" => self.add_tcp_port_forward(&cfg).await?,
|
||||
"udp" => self.add_udp_port_forward(&cfg).await?,
|
||||
_ => {
|
||||
anyhow::bail!(
|
||||
"unsupported protocol: {}, only support udp / tcp",
|
||||
cfg.proto
|
||||
)
|
||||
}
|
||||
}
|
||||
self.events.emit(CoreEvent::GatewayPortForwardAdded(cfg));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_tcp_port_forward(&self, cfg: &PortForwardConfig) -> anyhow::Result<()> {
|
||||
let (bind_addr, dst_addr) = (cfg.bind_addr, cfg.dst_addr);
|
||||
let options = TcpListenOptions::port_forward(bind_addr);
|
||||
let bind = options
|
||||
.bind
|
||||
.clone()
|
||||
.with_context(self.socket_context.clone());
|
||||
let options = options.with_bind(bind);
|
||||
let listener = self.host.bind_tcp(options.clone()).await?;
|
||||
tracing::info!(?bind_addr, ?dst_addr, "TCP port-forward listener bound");
|
||||
let cancel = CancellationToken::new();
|
||||
self.cancel_tokens
|
||||
.insert(cfg.clone(), cancel.clone().drop_guard());
|
||||
|
||||
let data_plane = self.data_plane.clone();
|
||||
let connections = Arc::new(std::sync::Mutex::new(JoinSet::new()));
|
||||
connections.lock().unwrap().spawn(reap_joinset_background(
|
||||
Arc::downgrade(&connections),
|
||||
"TCP port-forward connections",
|
||||
));
|
||||
let host = self.host.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
let mut listener = Some(listener);
|
||||
loop {
|
||||
let Some((incoming, source_addr)) =
|
||||
accept_tcp_port_forward(&host, &options, &mut listener, &cancel).await
|
||||
else {
|
||||
break;
|
||||
};
|
||||
tracing::info!(
|
||||
?bind_addr,
|
||||
?source_addr,
|
||||
?dst_addr,
|
||||
"port-forward accepted local connection"
|
||||
);
|
||||
let data_plane = data_plane.clone();
|
||||
connections.lock().unwrap().spawn(async move {
|
||||
tracing::info!(
|
||||
?source_addr,
|
||||
?dst_addr,
|
||||
"port-forward data-plane connect started"
|
||||
);
|
||||
let options = DataPlaneTcpConnectOptions::gateway(
|
||||
Duration::from_secs(10),
|
||||
TcpSocketPurpose::PortForward,
|
||||
source_addr,
|
||||
);
|
||||
let outgoing = match data_plane.connect_tcp(dst_addr, options).await {
|
||||
Ok(stream) => stream,
|
||||
Err(error) => {
|
||||
tracing::error!(?error, ?dst_addr, "port-forward connect failed");
|
||||
return;
|
||||
}
|
||||
};
|
||||
tracing::info!(?source_addr, ?dst_addr, "port-forward data-plane connected");
|
||||
copy_tcp(incoming, outgoing, dst_addr).await;
|
||||
});
|
||||
}
|
||||
tracing::info!(
|
||||
?bind_addr,
|
||||
?dst_addr,
|
||||
"TCP port-forward listener task stopped"
|
||||
);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn add_udp_port_forward(&self, cfg: &PortForwardConfig) -> anyhow::Result<()> {
|
||||
let (bind_addr, dst_addr) = (cfg.bind_addr, cfg.dst_addr);
|
||||
let forward = cfg.clone();
|
||||
let socket = self
|
||||
.host
|
||||
.bind_udp(
|
||||
UdpBindOptions::port_forward(bind_addr).with_context(self.socket_context.clone()),
|
||||
)
|
||||
.await?;
|
||||
let cancel = CancellationToken::new();
|
||||
self.cancel_tokens
|
||||
.insert(cfg.clone(), cancel.clone().drop_guard());
|
||||
|
||||
let data_plane = self.data_plane.clone();
|
||||
let host = self.host.clone();
|
||||
let socket_context = self.socket_context.clone();
|
||||
let udp_clients = self.udp_clients.clone();
|
||||
let response_tasks = self.udp_response_tasks.clone();
|
||||
let client_admission = self.udp_client_admission.clone();
|
||||
let client_slots = self.udp_client_slots.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
let adapter = UdpFlowFactory {
|
||||
data_plane,
|
||||
host,
|
||||
socket_context,
|
||||
};
|
||||
let mut buf = vec![0u8; MAX_UDP_PAYLOAD_SIZE];
|
||||
loop {
|
||||
let (len, client_addr) = select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => break,
|
||||
result = socket.recv_from(&mut buf) => match result {
|
||||
Ok(packet) => packet,
|
||||
Err(error) => {
|
||||
tracing::error!(?error, ?bind_addr, "UDP port-forward receive failed");
|
||||
continue;
|
||||
}
|
||||
},
|
||||
};
|
||||
let key = UdpClientKey {
|
||||
client_addr,
|
||||
forward: forward.clone(),
|
||||
};
|
||||
let flow = match udp_clients.get(&key) {
|
||||
Some(client) => client.clone(),
|
||||
None => {
|
||||
let flow = match adapter.open(dst_addr).await {
|
||||
Ok(flow) => flow,
|
||||
Err(error) => {
|
||||
tracing::error!(
|
||||
?error,
|
||||
?dst_addr,
|
||||
"open UDP data-plane flow failed"
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(reservation) = reserve_udp_client_slot(
|
||||
&cancel,
|
||||
&client_admission,
|
||||
&client_slots,
|
||||
&udp_clients,
|
||||
&response_tasks,
|
||||
)
|
||||
.await
|
||||
else {
|
||||
tracing::trace!(
|
||||
?client_addr,
|
||||
"UDP port-forward client limit remains full"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let UdpClientReservation { slot, admission } = reservation;
|
||||
let slot = Arc::new(slot);
|
||||
let client = Arc::new(UdpClientInfo {
|
||||
flow: flow.clone(),
|
||||
last_active: AtomicCell::new(Instant::now()),
|
||||
_slot: slot.clone(),
|
||||
});
|
||||
udp_clients.insert(key.clone(), client.clone());
|
||||
|
||||
let inbound = socket.clone();
|
||||
let response_flow = flow.clone();
|
||||
let response_client = client_addr;
|
||||
let response_slot = slot;
|
||||
response_tasks.insert(
|
||||
key.clone(),
|
||||
AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let _slot = response_slot;
|
||||
let mut buf = vec![0u8; MAX_UDP_PAYLOAD_SIZE];
|
||||
loop {
|
||||
match response_flow.recv_from(&mut buf).await {
|
||||
Ok((len, remote)) => {
|
||||
tracing::trace!(
|
||||
?remote,
|
||||
?response_client,
|
||||
len,
|
||||
"forwarding UDP data-plane response"
|
||||
);
|
||||
if let Err(error) =
|
||||
inbound.send_to(&buf[..len], response_client).await
|
||||
{
|
||||
tracing::error!(?error, "send UDP response failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(?error, "receive UDP response failed");
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
})),
|
||||
);
|
||||
drop(admission);
|
||||
client
|
||||
}
|
||||
};
|
||||
flow.last_active.store(Instant::now());
|
||||
if let Err(error) = flow.flow.send_to(&buf[..len], dst_addr).await {
|
||||
tracing::error!(?error, ?dst_addr, "send UDP data-plane packet failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn start_udp_reaper(&self) {
|
||||
let udp_clients = self.udp_clients.clone();
|
||||
let response_tasks = self.udp_response_tasks.clone();
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(30)).await;
|
||||
let now = Instant::now();
|
||||
udp_clients.retain(|_, client| {
|
||||
now.duration_since(client.last_active.load()).as_secs() < 600
|
||||
});
|
||||
response_tasks.retain(|key, _| udp_clients.contains_key(key));
|
||||
udp_clients.shrink_to_fit();
|
||||
response_tasks.shrink_to_fit();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn stop_inner(&self) {
|
||||
self.started.store(false, Ordering::Release);
|
||||
tracing::info!(
|
||||
forward_count = self.cancel_tokens.len(),
|
||||
"port-forward adapter stopping"
|
||||
);
|
||||
self.cancel_tokens.clear();
|
||||
self.udp_response_tasks.clear();
|
||||
self.udp_clients.clear();
|
||||
self.consumer_lease.lock().await.take();
|
||||
let mut tasks = {
|
||||
let mut tasks = self.tasks.lock().unwrap();
|
||||
std::mem::replace(&mut *tasks, JoinSet::new())
|
||||
};
|
||||
tasks.shutdown().await;
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.stop_inner().await;
|
||||
}
|
||||
}
|
||||
|
||||
async fn accept_tcp_port_forward<H>(
|
||||
host: &Arc<H>,
|
||||
options: &TcpListenOptions,
|
||||
listener: &mut Option<Arc<H::Listener>>,
|
||||
cancel: &CancellationToken,
|
||||
) -> Option<(<H::Listener as VirtualTcpListener>::Socket, SocketAddr)>
|
||||
where
|
||||
H: VirtualTcpListenerFactory,
|
||||
{
|
||||
loop {
|
||||
let current = listener
|
||||
.take()
|
||||
.expect("TCP port-forward listener must be bound before accepting");
|
||||
let accepted = select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!(?options, "port-forward listener cancelled while accepting");
|
||||
return None;
|
||||
},
|
||||
result = current.accept() => result,
|
||||
};
|
||||
match accepted {
|
||||
Ok(accepted) => {
|
||||
listener.replace(current);
|
||||
return Some(accepted);
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(?error, ?options, "port-forward accept failed; rebinding");
|
||||
}
|
||||
}
|
||||
drop(current);
|
||||
|
||||
loop {
|
||||
select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!(?options, "port-forward listener cancelled during rebind delay");
|
||||
return None;
|
||||
},
|
||||
_ = crate::foundation::time::sleep(TCP_PORT_FORWARD_REBIND_DELAY) => {}
|
||||
}
|
||||
let rebound = select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => {
|
||||
tracing::info!(?options, "port-forward listener cancelled while rebinding");
|
||||
return None;
|
||||
},
|
||||
result = host.bind_tcp(options.clone()) => result,
|
||||
};
|
||||
match rebound {
|
||||
Ok(rebound) => {
|
||||
tracing::info!(?options, "port-forward listener rebound");
|
||||
listener.replace(rebound);
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(?error, ?options, "port-forward listener rebind failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn reserve_udp_client_slot<H>(
|
||||
cancel: &CancellationToken,
|
||||
admission: &Arc<Mutex<()>>,
|
||||
slots: &Arc<Semaphore>,
|
||||
clients: &DashMap<UdpClientKey, Arc<UdpClientInfo<H>>>,
|
||||
response_tasks: &DashMap<UdpClientKey, AbortOnDropHandle<()>>,
|
||||
) -> Option<UdpClientReservation>
|
||||
where
|
||||
H: VirtualUdpSocketFactory,
|
||||
{
|
||||
// Keep eviction, permit handoff, and publication in one critical section.
|
||||
let admission = select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return None,
|
||||
admission = admission.clone().lock_owned() => admission,
|
||||
};
|
||||
loop {
|
||||
if let Ok(slot) = slots.clone().try_acquire_owned() {
|
||||
return Some(UdpClientReservation { slot, admission });
|
||||
}
|
||||
|
||||
let oldest = clients
|
||||
.iter()
|
||||
.min_by_key(|entry| entry.value().last_active.load())
|
||||
.map(|entry| entry.key().clone())?;
|
||||
let Some(evicted) = clients.remove(&oldest) else {
|
||||
continue;
|
||||
};
|
||||
drop(response_tasks.remove(&oldest));
|
||||
drop(evicted);
|
||||
let slot = select! {
|
||||
biased;
|
||||
_ = cancel.cancelled() => return None,
|
||||
slot = slots.clone().acquire_owned() => slot.ok()?,
|
||||
};
|
||||
return Some(UdpClientReservation { slot, admission });
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpFlowFactory<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
data_plane: Arc<DataPlaneRuntime<H>>,
|
||||
host: Arc<H>,
|
||||
socket_context: SocketContext,
|
||||
}
|
||||
|
||||
impl<H> UdpFlowFactory<H>
|
||||
where
|
||||
H: VirtualTcpSocketFactory + VirtualTcpListenerFactory + VirtualUdpSocketFactory,
|
||||
{
|
||||
async fn open(&self, dst_addr: SocketAddr) -> anyhow::Result<Arc<PortForwardUdpFlow<H>>> {
|
||||
if self.data_plane.is_local_virtual_ip(dst_addr.ip()) {
|
||||
let socket = self
|
||||
.host
|
||||
.bind_udp(
|
||||
UdpBindOptions::port_lease("0.0.0.0:0".parse().unwrap())
|
||||
.with_context(self.socket_context.clone()),
|
||||
)
|
||||
.await?;
|
||||
Ok(Arc::new(PortForwardUdpFlow::Host(socket)))
|
||||
} else {
|
||||
let socket = self
|
||||
.data_plane
|
||||
.data_plane_udp_bind(0, Duration::from_secs(10))
|
||||
.await?;
|
||||
Ok(Arc::new(PortForwardUdpFlow::DataPlane(Arc::new(socket))))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn copy_tcp<S>(mut incoming: S, mut outgoing: DataPlaneTcpStream, dst_addr: SocketAddr)
|
||||
where
|
||||
S: VirtualTcpSocket,
|
||||
{
|
||||
match tokio::io::copy_bidirectional(&mut incoming, &mut outgoing).await {
|
||||
Ok((from_client, from_server)) => tracing::info!(
|
||||
?dst_addr,
|
||||
from_client,
|
||||
from_server,
|
||||
"port-forward connection finished"
|
||||
),
|
||||
Err(error) => tracing::error!(?error, ?dst_addr, "port-forward connection failed"),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{io, sync::atomic::AtomicUsize};
|
||||
|
||||
use super::*;
|
||||
use crate::host::testkit::{TestHost, TestTcpSocket, TestUdpSocket};
|
||||
|
||||
struct RecoveringTcpListener {
|
||||
accept_error: bool,
|
||||
active: Arc<AtomicUsize>,
|
||||
address: SocketAddr,
|
||||
}
|
||||
|
||||
impl Drop for RecoveringTcpListener {
|
||||
fn drop(&mut self) {
|
||||
self.active.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl VirtualTcpListener for RecoveringTcpListener {
|
||||
type Socket = TestTcpSocket;
|
||||
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok(self.address)
|
||||
}
|
||||
|
||||
async fn accept(&self) -> io::Result<(Self::Socket, SocketAddr)> {
|
||||
if self.accept_error {
|
||||
return Err(io::Error::other("listener is no longer usable"));
|
||||
}
|
||||
let (socket, _) = tokio::io::duplex(64);
|
||||
Ok((TestTcpSocket(socket), "127.0.0.1:40000".parse().unwrap()))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecoveringTcpHost {
|
||||
binds: AtomicUsize,
|
||||
active: Arc<AtomicUsize>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl VirtualTcpListenerFactory for RecoveringTcpHost {
|
||||
type Listener = RecoveringTcpListener;
|
||||
|
||||
async fn bind_tcp(&self, options: TcpListenOptions) -> anyhow::Result<Arc<Self::Listener>> {
|
||||
let bind_index = self.binds.fetch_add(1, Ordering::Relaxed);
|
||||
if bind_index > 0 && self.active.load(Ordering::Relaxed) != 0 {
|
||||
anyhow::bail!("previous listener is still active");
|
||||
}
|
||||
self.active.fetch_add(1, Ordering::Relaxed);
|
||||
Ok(Arc::new(RecoveringTcpListener {
|
||||
accept_error: bind_index == 0,
|
||||
active: self.active.clone(),
|
||||
address: options.bind.local_addr.unwrap(),
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_rebinds_after_accept_error() {
|
||||
let host = Arc::new(RecoveringTcpHost::default());
|
||||
let options = TcpListenOptions::port_forward("127.0.0.1:5202".parse().unwrap());
|
||||
let mut listener = Some(host.bind_tcp(options.clone()).await.unwrap());
|
||||
|
||||
let accepted = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
accept_tcp_port_forward(&host, &options, &mut listener, &CancellationToken::new()),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(accepted.is_some());
|
||||
assert_eq!(host.binds.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(host.active.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_listener_rebind_stops_when_cancelled() {
|
||||
let host = Arc::new(RecoveringTcpHost::default());
|
||||
let options = TcpListenOptions::port_forward("127.0.0.1:5202".parse().unwrap());
|
||||
let mut listener = Some(host.bind_tcp(options.clone()).await.unwrap());
|
||||
let cancel = CancellationToken::new();
|
||||
let cancel_after_error = cancel.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(Duration::from_millis(10)).await;
|
||||
cancel_after_error.cancel();
|
||||
});
|
||||
|
||||
let accepted = tokio::time::timeout(
|
||||
Duration::from_secs(1),
|
||||
accept_tcp_port_forward(&host, &options, &mut listener, &cancel),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(accepted.is_none());
|
||||
assert_eq!(host.binds.load(Ordering::Relaxed), 1);
|
||||
assert_eq!(host.active.load(Ordering::Relaxed), 0);
|
||||
}
|
||||
|
||||
fn udp_client_key(port: u16) -> UdpClientKey {
|
||||
UdpClientKey {
|
||||
client_addr: SocketAddr::from(([127, 0, 0, 1], port)),
|
||||
forward: PortForwardConfig {
|
||||
bind_addr: "127.0.0.1:5202".parse().unwrap(),
|
||||
dst_addr: "10.144.0.20:5201".parse().unwrap(),
|
||||
proto: "udp".to_owned(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn udp_client(slots: &Arc<Semaphore>, last_active: Instant) -> Arc<UdpClientInfo<TestHost>> {
|
||||
udp_client_with_slot(
|
||||
Arc::new(slots.clone().try_acquire_owned().unwrap()),
|
||||
last_active,
|
||||
)
|
||||
}
|
||||
|
||||
fn udp_client_with_slot(
|
||||
slot: Arc<OwnedSemaphorePermit>,
|
||||
last_active: Instant,
|
||||
) -> Arc<UdpClientInfo<TestHost>> {
|
||||
let flow: Arc<PortForwardUdpFlow<TestHost>> = Arc::new(PortForwardUdpFlow::Host(Arc::new(
|
||||
TestUdpSocket("127.0.0.1:20002".parse().unwrap()),
|
||||
)));
|
||||
Arc::new(UdpClientInfo {
|
||||
flow,
|
||||
last_active: AtomicCell::new(last_active),
|
||||
_slot: slot,
|
||||
})
|
||||
}
|
||||
|
||||
fn pending_response_task(slot: Arc<OwnedSemaphorePermit>) -> AbortOnDropHandle<()> {
|
||||
AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let _slot = slot;
|
||||
std::future::pending().await
|
||||
}))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn udp_client_capacity_evicts_least_recently_active_flow() {
|
||||
let slots = Arc::new(Semaphore::new(2));
|
||||
let admission = Arc::new(Mutex::new(()));
|
||||
let clients: DashMap<UdpClientKey, Arc<UdpClientInfo<TestHost>>> = DashMap::new();
|
||||
let response_tasks: DashMap<UdpClientKey, AbortOnDropHandle<()>> = DashMap::new();
|
||||
let oldest = udp_client_key(40001);
|
||||
let newest = udp_client_key(40002);
|
||||
let now = Instant::now();
|
||||
let oldest_client = udp_client(&slots, now - Duration::from_secs(2));
|
||||
let newest_client = udp_client(&slots, now - Duration::from_secs(1));
|
||||
response_tasks.insert(
|
||||
oldest.clone(),
|
||||
pending_response_task(oldest_client._slot.clone()),
|
||||
);
|
||||
response_tasks.insert(
|
||||
newest.clone(),
|
||||
pending_response_task(newest_client._slot.clone()),
|
||||
);
|
||||
clients.insert(oldest.clone(), oldest_client);
|
||||
clients.insert(newest.clone(), newest_client);
|
||||
assert_eq!(slots.available_permits(), 0);
|
||||
|
||||
let replacement = reserve_udp_client_slot(
|
||||
&CancellationToken::new(),
|
||||
&admission,
|
||||
&slots,
|
||||
&clients,
|
||||
&response_tasks,
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert!(!clients.contains_key(&oldest));
|
||||
assert!(!response_tasks.contains_key(&oldest));
|
||||
assert!(clients.contains_key(&newest));
|
||||
assert!(response_tasks.contains_key(&newest));
|
||||
assert_eq!(slots.available_permits(), 0);
|
||||
|
||||
drop(replacement);
|
||||
response_tasks.clear();
|
||||
clients.clear();
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(slots.available_permits(), 2);
|
||||
}
|
||||
|
||||
#[cfg_attr(
|
||||
not(target_os = "wasi"),
|
||||
tokio::test(flavor = "multi_thread", worker_threads = 2)
|
||||
)]
|
||||
#[cfg_attr(target_os = "wasi", tokio::test)]
|
||||
async fn udp_client_admission_covers_client_and_response_task_publication() {
|
||||
let slots = Arc::new(Semaphore::new(1));
|
||||
let admission = Arc::new(Mutex::new(()));
|
||||
let clients: Arc<DashMap<UdpClientKey, Arc<UdpClientInfo<TestHost>>>> =
|
||||
Arc::new(DashMap::new());
|
||||
let response_tasks: Arc<DashMap<UdpClientKey, AbortOnDropHandle<()>>> =
|
||||
Arc::new(DashMap::new());
|
||||
let oldest = udp_client_key(40001);
|
||||
let oldest_client = udp_client(&slots, Instant::now());
|
||||
response_tasks.insert(
|
||||
oldest.clone(),
|
||||
pending_response_task(oldest_client._slot.clone()),
|
||||
);
|
||||
clients.insert(oldest.clone(), oldest_client.clone());
|
||||
|
||||
let reserve = || {
|
||||
let admission = admission.clone();
|
||||
let slots = slots.clone();
|
||||
let clients = clients.clone();
|
||||
let response_tasks = response_tasks.clone();
|
||||
tokio::spawn(async move {
|
||||
reserve_udp_client_slot(
|
||||
&CancellationToken::new(),
|
||||
&admission,
|
||||
&slots,
|
||||
&clients,
|
||||
&response_tasks,
|
||||
)
|
||||
.await
|
||||
})
|
||||
};
|
||||
let first = reserve();
|
||||
tokio::time::timeout(Duration::from_secs(1), async {
|
||||
while clients.contains_key(&oldest) {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let mut second = reserve();
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), &mut second)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
drop(oldest_client);
|
||||
let first_slot = tokio::time::timeout(Duration::from_secs(1), first)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), &mut second)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
|
||||
let UdpClientReservation {
|
||||
slot,
|
||||
admission: admission_guard,
|
||||
} = first_slot;
|
||||
let replacement = udp_client_key(40002);
|
||||
let replacement_slot = Arc::new(slot);
|
||||
let replacement_client = udp_client_with_slot(replacement_slot.clone(), Instant::now());
|
||||
clients.insert(replacement.clone(), replacement_client.clone());
|
||||
|
||||
assert!(
|
||||
tokio::time::timeout(Duration::from_millis(50), &mut second)
|
||||
.await
|
||||
.is_err()
|
||||
);
|
||||
assert!(clients.contains_key(&replacement));
|
||||
|
||||
response_tasks.insert(replacement.clone(), pending_response_task(replacement_slot));
|
||||
drop(admission_guard);
|
||||
|
||||
// Release the test's permit reference and wait for the full eviction;
|
||||
// the client and response-task entries are removed separately.
|
||||
drop(replacement_client);
|
||||
let second_slot = tokio::time::timeout(Duration::from_secs(1), second)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
|
||||
assert!(!clients.contains_key(&replacement));
|
||||
assert!(!response_tasks.contains_key(&replacement));
|
||||
|
||||
drop(second_slot);
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(slots.available_permits(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
use std::{collections::BTreeSet, sync::Arc, time::Duration};
|
||||
|
||||
use cidr::Ipv4Cidr;
|
||||
#[cfg(feature = "proxy-cidr-monitor")]
|
||||
use tokio::sync::Mutex;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::{
|
||||
config::runtime::{CoreInstanceRuntimeConfig, CoreRuntimeConfigStore},
|
||||
events::{CoreEvent, CoreEventSink},
|
||||
peers::peer_manager::PeerManagerCore,
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub(crate) struct ProxyCidrConfigSnapshot {
|
||||
pub manual_routes: Option<BTreeSet<Ipv4Cidr>>,
|
||||
}
|
||||
|
||||
impl From<&CoreInstanceRuntimeConfig> for ProxyCidrConfigSnapshot {
|
||||
fn from(config: &CoreInstanceRuntimeConfig) -> Self {
|
||||
Self {
|
||||
manual_routes: config.services.manual_routes.clone(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-cidr-monitor")]
|
||||
pub(crate) struct ProxyCidrMonitorRuntime {
|
||||
enabled: bool,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
task: Mutex<Option<AbortOnDropHandle<()>>>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-cidr-monitor")]
|
||||
impl ProxyCidrMonitorRuntime {
|
||||
pub(crate) fn new(enabled: bool, events: Arc<dyn CoreEventSink>) -> Self {
|
||||
Self {
|
||||
enabled,
|
||||
events,
|
||||
task: Mutex::new(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn is_enabled(&self) -> bool {
|
||||
self.enabled
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
&self,
|
||||
peer_manager: &Arc<PeerManagerCore>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
) {
|
||||
if !self.enabled {
|
||||
return;
|
||||
}
|
||||
let mut task = self.task.lock().await;
|
||||
if task.is_none() {
|
||||
task.replace(
|
||||
ProxyCidrMonitor::new(peer_manager, runtime_config, self.events.clone()).start(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
self.task.lock().await.take();
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct ProxyCidrDiff {
|
||||
pub current: BTreeSet<Ipv4Cidr>,
|
||||
pub added: Vec<Ipv4Cidr>,
|
||||
pub removed: Vec<Ipv4Cidr>,
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_proxy_cidrs(
|
||||
peer_routes: BTreeSet<Ipv4Cidr>,
|
||||
config: ProxyCidrConfigSnapshot,
|
||||
) -> BTreeSet<Ipv4Cidr> {
|
||||
if let Some(manual_routes) = config.manual_routes {
|
||||
return manual_routes;
|
||||
}
|
||||
peer_routes
|
||||
}
|
||||
|
||||
pub(crate) fn diff_proxy_cidrs(
|
||||
previous: &BTreeSet<Ipv4Cidr>,
|
||||
current: BTreeSet<Ipv4Cidr>,
|
||||
) -> ProxyCidrDiff {
|
||||
let added = current.difference(previous).copied().collect();
|
||||
let removed = previous.difference(¤t).copied().collect();
|
||||
ProxyCidrDiff {
|
||||
current,
|
||||
added,
|
||||
removed,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_proxy_cidrs(
|
||||
peer_manager: &PeerManagerCore,
|
||||
config: &CoreInstanceRuntimeConfig,
|
||||
) -> BTreeSet<Ipv4Cidr> {
|
||||
let peer_routes = peer_manager.get_route().list_proxy_cidrs().await;
|
||||
resolve_proxy_cidrs_from_runtime(peer_routes, config)
|
||||
}
|
||||
|
||||
fn resolve_proxy_cidrs_from_runtime(
|
||||
peer_routes: BTreeSet<Ipv4Cidr>,
|
||||
config: &CoreInstanceRuntimeConfig,
|
||||
) -> BTreeSet<Ipv4Cidr> {
|
||||
resolve_proxy_cidrs(peer_routes, config.into())
|
||||
}
|
||||
|
||||
pub(crate) async fn collect_proxy_cidr_diff(
|
||||
peer_manager: &PeerManagerCore,
|
||||
runtime_config: &CoreRuntimeConfigStore,
|
||||
previous: &BTreeSet<Ipv4Cidr>,
|
||||
) -> ProxyCidrDiff {
|
||||
let config = runtime_config.snapshot();
|
||||
collect_proxy_cidr_diff_from_snapshot(peer_manager, config.as_ref(), previous).await
|
||||
}
|
||||
|
||||
async fn collect_proxy_cidr_diff_from_snapshot(
|
||||
peer_manager: &PeerManagerCore,
|
||||
config: &CoreInstanceRuntimeConfig,
|
||||
previous: &BTreeSet<Ipv4Cidr>,
|
||||
) -> ProxyCidrDiff {
|
||||
let current = collect_proxy_cidrs(peer_manager, config).await;
|
||||
diff_proxy_cidrs(previous, current)
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "proxy-cidr-monitor"), allow(dead_code))]
|
||||
pub(crate) struct ProxyCidrMonitor {
|
||||
peer_manager: std::sync::Weak<PeerManagerCore>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
}
|
||||
|
||||
#[cfg_attr(not(feature = "proxy-cidr-monitor"), allow(dead_code))]
|
||||
impl ProxyCidrMonitor {
|
||||
pub(crate) fn new(
|
||||
peer_manager: &Arc<PeerManagerCore>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
events: Arc<dyn CoreEventSink>,
|
||||
) -> Self {
|
||||
Self {
|
||||
peer_manager: Arc::downgrade(peer_manager),
|
||||
runtime_config,
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn start(self) -> AbortOnDropHandle<()> {
|
||||
AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
let mut current = BTreeSet::new();
|
||||
let mut last_update = None;
|
||||
let mut last_runtime_config: Option<Arc<CoreInstanceRuntimeConfig>> = None;
|
||||
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(1)).await;
|
||||
let Some(peer_manager) = self.peer_manager.upgrade() else {
|
||||
break;
|
||||
};
|
||||
let update = peer_manager
|
||||
.get_route()
|
||||
.get_peer_info_last_update_time()
|
||||
.await;
|
||||
let runtime_config = self.runtime_config.snapshot();
|
||||
let runtime_config_changed = last_runtime_config
|
||||
.as_ref()
|
||||
.map(|previous| !Arc::ptr_eq(previous, &runtime_config))
|
||||
.unwrap_or(true);
|
||||
if last_update == Some(update) && !runtime_config_changed {
|
||||
continue;
|
||||
}
|
||||
last_update = Some(update);
|
||||
last_runtime_config = Some(runtime_config.clone());
|
||||
|
||||
let diff = collect_proxy_cidr_diff_from_snapshot(
|
||||
peer_manager.as_ref(),
|
||||
runtime_config.as_ref(),
|
||||
¤t,
|
||||
)
|
||||
.await;
|
||||
current = diff.current;
|
||||
if !diff.added.is_empty() || !diff.removed.is_empty() {
|
||||
self.events.emit(CoreEvent::ProxyCidrsUpdated {
|
||||
added: diff.added,
|
||||
removed: diff.removed,
|
||||
});
|
||||
}
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
config::peers::PeerRuntimeSnapshot,
|
||||
config::runtime::{CoreInstanceRuntimeConfig, CoreRuntimeConfig},
|
||||
};
|
||||
|
||||
fn cidrs(values: &[&str]) -> BTreeSet<Ipv4Cidr> {
|
||||
values.iter().map(|value| value.parse().unwrap()).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn manual_routes_override_peer_routes() {
|
||||
let resolved = resolve_proxy_cidrs(
|
||||
cidrs(&["10.0.0.0/8"]),
|
||||
ProxyCidrConfigSnapshot {
|
||||
manual_routes: Some(cidrs(&["192.0.2.0/24"])),
|
||||
},
|
||||
);
|
||||
assert_eq!(resolved, cidrs(&["192.0.2.0/24"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_routes_report_ordered_diff() {
|
||||
let current = resolve_proxy_cidrs(
|
||||
cidrs(&["10.0.0.0/8"]),
|
||||
ProxyCidrConfigSnapshot {
|
||||
manual_routes: None,
|
||||
},
|
||||
);
|
||||
let diff = diff_proxy_cidrs(&cidrs(&["10.0.0.0/8", "172.16.0.0/12"]), current);
|
||||
|
||||
assert_eq!(diff.current, cidrs(&["10.0.0.0/8"]));
|
||||
assert!(diff.added.is_empty());
|
||||
assert_eq!(diff.removed, vec!["172.16.0.0/12".parse().unwrap()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_store_update_changes_the_monitor_config_snapshot() {
|
||||
let initial_peer = PeerRuntimeSnapshot::default();
|
||||
let store = CoreRuntimeConfigStore::new(
|
||||
CoreRuntimeConfig {
|
||||
manual_routes: Some(cidrs(&["192.0.2.0/24"])),
|
||||
..Default::default()
|
||||
},
|
||||
Arc::new(initial_peer),
|
||||
);
|
||||
let initial = store.snapshot();
|
||||
|
||||
let updated_peer = PeerRuntimeSnapshot::default();
|
||||
store.replace(CoreInstanceRuntimeConfig {
|
||||
services: CoreRuntimeConfig::default(),
|
||||
peer: Arc::new(updated_peer),
|
||||
});
|
||||
let updated = store.snapshot();
|
||||
|
||||
assert_eq!(
|
||||
resolve_proxy_cidrs_from_runtime(cidrs(&["10.0.0.0/8"]), initial.as_ref()),
|
||||
cidrs(&["192.0.2.0/24"])
|
||||
);
|
||||
assert_eq!(
|
||||
resolve_proxy_cidrs_from_runtime(cidrs(&["10.0.0.0/8"]), updated.as_ref()),
|
||||
cidrs(&["10.0.0.0/8"])
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
use std::net::IpAddr;
|
||||
#[cfg(any(test, feature = "proxy-packet"))]
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
use parking_lot::RwLock;
|
||||
|
||||
use crate::config::{IpPrefix, ProxyNetworkConfig};
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
pub struct ProxyCidrRule {
|
||||
pub cidr: cidr::Ipv4Cidr,
|
||||
pub mapped_cidr: Option<cidr::Ipv4Cidr>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, PartialEq)]
|
||||
pub struct ProxyCidrSnapshot {
|
||||
pub rules: Vec<ProxyCidrRule>,
|
||||
}
|
||||
|
||||
impl ProxyCidrSnapshot {
|
||||
pub fn from_proxy_networks(networks: &[ProxyNetworkConfig]) -> Self {
|
||||
Self {
|
||||
rules: networks.iter().filter_map(proxy_cidr_rule).collect(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn ipv4_cidr(prefix: &IpPrefix) -> Option<cidr::Ipv4Cidr> {
|
||||
let IpAddr::V4(address) = prefix.address else {
|
||||
return None;
|
||||
};
|
||||
cidr::Ipv4Cidr::new(address, prefix.prefix_len).ok()
|
||||
}
|
||||
|
||||
fn proxy_cidr_rule(config: &ProxyNetworkConfig) -> Option<ProxyCidrRule> {
|
||||
Some(ProxyCidrRule {
|
||||
cidr: ipv4_cidr(&config.real)?,
|
||||
mapped_cidr: config.mapped.as_ref().and_then(ipv4_cidr),
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct ProxyCidrEntry {
|
||||
real_cidr: cidr::Ipv4Cidr,
|
||||
mapped_cidr: cidr::Ipv4Cidr,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ProxyCidrTable {
|
||||
entries: RwLock<Vec<ProxyCidrEntry>>,
|
||||
}
|
||||
|
||||
impl ProxyCidrTable {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub fn from_snapshot(snapshot: ProxyCidrSnapshot) -> Self {
|
||||
let table = Self::new();
|
||||
table.update_snapshot(snapshot);
|
||||
table
|
||||
}
|
||||
|
||||
pub fn update_snapshot(&self, snapshot: ProxyCidrSnapshot) {
|
||||
let entries = snapshot
|
||||
.rules
|
||||
.into_iter()
|
||||
.map(|rule| ProxyCidrEntry {
|
||||
real_cidr: rule.cidr,
|
||||
mapped_cidr: rule.mapped_cidr.unwrap_or(rule.cidr),
|
||||
})
|
||||
.collect();
|
||||
*self.entries.write() = entries;
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.entries.read().is_empty()
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "proxy-packet"))]
|
||||
pub fn lookup_v4(&self, ipv4: Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
self.entries
|
||||
.read()
|
||||
.iter()
|
||||
.find_map(|entry| entry.lookup_v4(ipv4))
|
||||
}
|
||||
}
|
||||
|
||||
impl ProxyCidrEntry {
|
||||
#[cfg(any(test, feature = "proxy-packet"))]
|
||||
fn lookup_v4(&self, ipv4: Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
if !self.mapped_cidr.contains(&ipv4) {
|
||||
return None;
|
||||
}
|
||||
|
||||
if self.mapped_cidr == self.real_cidr {
|
||||
return Some(ipv4);
|
||||
}
|
||||
|
||||
let origin_network_bits = self.real_cidr.first().address().to_bits();
|
||||
let network_mask = self.mapped_cidr.mask().to_bits();
|
||||
let converted_ip = (ipv4.to_bits() & !network_mask) | origin_network_bits;
|
||||
Some(Ipv4Addr::from(converted_ip))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::config::{IpPrefix, ProxyNetworkConfig};
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn lookup_returns_original_ip_for_unmapped_cidr() {
|
||||
let table = ProxyCidrTable::from_snapshot(ProxyCidrSnapshot {
|
||||
rules: vec![ProxyCidrRule {
|
||||
cidr: "127.0.0.0/24".parse().unwrap(),
|
||||
mapped_cidr: None,
|
||||
}],
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
table.lookup_v4("127.0.0.42".parse().unwrap()),
|
||||
Some("127.0.0.42".parse().unwrap())
|
||||
);
|
||||
assert_eq!(table.lookup_v4("127.0.1.42".parse().unwrap()), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_converts_mapped_cidr_to_real_cidr() {
|
||||
let table = ProxyCidrTable::from_snapshot(ProxyCidrSnapshot {
|
||||
rules: vec![ProxyCidrRule {
|
||||
cidr: "127.0.0.0/24".parse().unwrap(),
|
||||
mapped_cidr: Some("10.10.10.0/24".parse().unwrap()),
|
||||
}],
|
||||
});
|
||||
|
||||
assert_eq!(
|
||||
table.lookup_v4("10.10.10.42".parse().unwrap()),
|
||||
Some("127.0.0.42".parse().unwrap())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn snapshot_normalizes_proxy_network_config() {
|
||||
let snapshot = ProxyCidrSnapshot::from_proxy_networks(&[ProxyNetworkConfig {
|
||||
real: IpPrefix {
|
||||
address: "192.0.2.0".parse().unwrap(),
|
||||
prefix_len: 24,
|
||||
},
|
||||
mapped: Some(IpPrefix {
|
||||
address: "198.51.100.0".parse().unwrap(),
|
||||
prefix_len: 24,
|
||||
}),
|
||||
}]);
|
||||
let table = ProxyCidrTable::from_snapshot(snapshot);
|
||||
|
||||
assert_eq!(
|
||||
table.lookup_v4("198.51.100.42".parse().unwrap()),
|
||||
Some("192.0.2.42".parse().unwrap())
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum ProxyRuntimeError {
|
||||
#[error(transparent)]
|
||||
Other(#[from] anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<std::io::Error> for ProxyRuntimeError {
|
||||
fn from(value: std::io::Error) -> Self {
|
||||
Self::Other(value.into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait IcmpProxySocket: Send + Sync + 'static {
|
||||
async fn send(&self, destination: Ipv4Addr, packet: &[u8]) -> Result<(), ProxyRuntimeError>;
|
||||
|
||||
async fn recv(&self) -> Result<(IpAddr, Vec<u8>), ProxyRuntimeError>;
|
||||
|
||||
fn close(&self) {}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait IcmpProxyHost: Send + Sync + 'static {
|
||||
async fn open_icmp_v4(
|
||||
&self,
|
||||
context: crate::socket::SocketContext,
|
||||
) -> Result<Arc<dyn IcmpProxySocket>, ProxyRuntimeError>;
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
use std::{net::Ipv4Addr, sync::Arc, time::Duration};
|
||||
|
||||
use dashmap::DashMap;
|
||||
use quanta::Instant;
|
||||
use smoltcp::wire::{IPV4_HEADER_LEN, Icmpv4Message, Icmpv4Packet, Ipv4Packet};
|
||||
|
||||
use crate::packet::{PacketType, ZCPacket};
|
||||
|
||||
use super::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
ip_reassembler::{ComposeIpv4PacketArgs, IpProtocol, IpReassembler, compose_ipv4_packet},
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct IcmpProxyContext {
|
||||
pub virtual_ipv4: Option<Ipv4Addr>,
|
||||
pub enable_exit_node: bool,
|
||||
pub no_tun: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum IcmpProxyAction {
|
||||
Pass,
|
||||
SendToSocket {
|
||||
destination: Ipv4Addr,
|
||||
packet: Vec<u8>,
|
||||
},
|
||||
SendToPeer(Vec<ZCPacket>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
struct IcmpNatKey {
|
||||
real_destination: Ipv4Addr,
|
||||
identifier: u16,
|
||||
sequence: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IcmpNatEntry {
|
||||
source_peer_id: u32,
|
||||
local_peer_id: u32,
|
||||
source_ip: Ipv4Addr,
|
||||
mapped_destination: Ipv4Addr,
|
||||
started_at: Instant,
|
||||
}
|
||||
|
||||
const ICMP_ECHO_HEADER_LEN: usize = 8;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct IcmpProxyEngine {
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
nat_table: DashMap<IcmpNatKey, IcmpNatEntry>,
|
||||
reassembler: IpReassembler,
|
||||
}
|
||||
|
||||
impl IcmpProxyEngine {
|
||||
pub fn new(cidr_table: Arc<ProxyCidrTable>, fragment_timeout: Duration) -> Self {
|
||||
Self {
|
||||
cidr_table,
|
||||
nat_table: DashMap::new(),
|
||||
reassembler: IpReassembler::new(fragment_timeout),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_peer_packet(
|
||||
&self,
|
||||
packet: &ZCPacket,
|
||||
context: IcmpProxyContext,
|
||||
) -> IcmpProxyAction {
|
||||
if self.cidr_table.is_empty() && !context.enable_exit_node && !context.no_tun {
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
let Some(virtual_ipv4) = context.virtual_ipv4 else {
|
||||
return IcmpProxyAction::Pass;
|
||||
};
|
||||
let Some(header) = packet.peer_manager_header() else {
|
||||
return IcmpProxyAction::Pass;
|
||||
};
|
||||
if header.packet_type != PacketType::Data as u8 || header.is_no_proxy() {
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
let Ok(ipv4) = Ipv4Packet::new_checked(packet.payload()) else {
|
||||
return IcmpProxyAction::Pass;
|
||||
};
|
||||
if ipv4.version() != 4
|
||||
|| usize::from(ipv4.header_len()) < IPV4_HEADER_LEN
|
||||
|| ipv4.next_header() != IpProtocol::Icmp
|
||||
{
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
|
||||
let mapped_destination = ipv4.dst_addr();
|
||||
let real_destination = self.cidr_table.lookup_v4(mapped_destination);
|
||||
let is_local_no_tun = context.no_tun && mapped_destination == virtual_ipv4;
|
||||
if real_destination.is_none() && !header.is_exit_node() && !is_local_no_tun {
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
|
||||
let reassembled;
|
||||
let request_bytes = if IpReassembler::is_packet_fragmented(&ipv4) {
|
||||
reassembled = self.reassembler.add_fragment(&ipv4);
|
||||
let Some(reassembled) = reassembled.as_ref() else {
|
||||
return IcmpProxyAction::Pass;
|
||||
};
|
||||
reassembled.as_slice()
|
||||
} else {
|
||||
ipv4.payload()
|
||||
};
|
||||
if request_bytes.len() < ICMP_ECHO_HEADER_LEN {
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
let request = Icmpv4Packet::new_unchecked(request_bytes);
|
||||
if request.msg_type() != Icmpv4Message::EchoRequest {
|
||||
return IcmpProxyAction::Pass;
|
||||
}
|
||||
|
||||
if is_local_no_tun {
|
||||
return self.local_reply(
|
||||
mapped_destination,
|
||||
ipv4.src_addr(),
|
||||
header.to_peer_id.get(),
|
||||
header.from_peer_id.get(),
|
||||
&request,
|
||||
);
|
||||
}
|
||||
|
||||
let real_destination = real_destination.unwrap_or(mapped_destination);
|
||||
let key = IcmpNatKey {
|
||||
real_destination,
|
||||
identifier: request.echo_ident(),
|
||||
sequence: request.echo_seq_no(),
|
||||
};
|
||||
self.nat_table.insert(
|
||||
key,
|
||||
IcmpNatEntry {
|
||||
source_peer_id: header.from_peer_id.get(),
|
||||
local_peer_id: header.to_peer_id.get(),
|
||||
source_ip: ipv4.src_addr(),
|
||||
mapped_destination,
|
||||
started_at: Instant::now(),
|
||||
},
|
||||
);
|
||||
|
||||
IcmpProxyAction::SendToSocket {
|
||||
destination: real_destination,
|
||||
packet: request.as_ref().to_vec(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_socket_response(&self, peer_ip: Ipv4Addr, packet: &mut [u8]) -> Vec<ZCPacket> {
|
||||
let Ok(ipv4) = Ipv4Packet::new_checked(&*packet) else {
|
||||
return Vec::new();
|
||||
};
|
||||
if usize::from(ipv4.header_len()) < IPV4_HEADER_LEN
|
||||
|| ipv4.payload().len() < ICMP_ECHO_HEADER_LEN
|
||||
{
|
||||
return Vec::new();
|
||||
}
|
||||
let reply = Icmpv4Packet::new_unchecked(ipv4.payload());
|
||||
if reply.msg_type() != Icmpv4Message::EchoReply {
|
||||
return Vec::new();
|
||||
}
|
||||
let key = IcmpNatKey {
|
||||
real_destination: peer_ip,
|
||||
identifier: reply.echo_ident(),
|
||||
sequence: reply.echo_seq_no(),
|
||||
};
|
||||
let Some((_, entry)) = self.nat_table.remove(&key) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let Some(payload_len) = packet.len().checked_sub(ipv4.header_len() as usize) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let ip_id = ipv4.ident();
|
||||
let mut responses = Vec::new();
|
||||
let _ = compose_ipv4_packet(
|
||||
ComposeIpv4PacketArgs {
|
||||
buf: packet,
|
||||
src_v4: &entry.mapped_destination,
|
||||
dst_v4: &entry.source_ip,
|
||||
next_protocol: IpProtocol::Icmp,
|
||||
payload_len,
|
||||
payload_mtu: 1200,
|
||||
ip_id,
|
||||
},
|
||||
|buf| {
|
||||
let mut packet = ZCPacket::new_with_payload(buf);
|
||||
packet.fill_peer_manager_hdr(
|
||||
entry.local_peer_id,
|
||||
entry.source_peer_id,
|
||||
PacketType::Data as u8,
|
||||
);
|
||||
packet
|
||||
.mut_peer_manager_header()
|
||||
.expect("peer manager header")
|
||||
.set_no_proxy(true);
|
||||
responses.push(packet);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
responses
|
||||
}
|
||||
|
||||
pub fn remove_expired_entries(&self, max_age: Duration) {
|
||||
self.nat_table
|
||||
.retain(|_, entry| entry.started_at.elapsed() < max_age);
|
||||
self.nat_table.shrink_to_fit();
|
||||
}
|
||||
|
||||
pub fn remove_expired_fragments(&self) {
|
||||
self.reassembler.remove_expired_packets();
|
||||
}
|
||||
|
||||
fn local_reply(
|
||||
&self,
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
source_peer_id: u32,
|
||||
destination_peer_id: u32,
|
||||
request: &Icmpv4Packet<&[u8]>,
|
||||
) -> IcmpProxyAction {
|
||||
let mut buffer = vec![0_u8; request.as_ref().len() + 20];
|
||||
let mut reply = Icmpv4Packet::new_unchecked(&mut buffer[20..]);
|
||||
reply.set_msg_type(Icmpv4Message::EchoReply);
|
||||
reply.set_msg_code(0);
|
||||
reply.set_echo_ident(request.echo_ident());
|
||||
reply.set_echo_seq_no(request.echo_seq_no());
|
||||
reply.data_mut().copy_from_slice(request.data());
|
||||
reply.fill_checksum();
|
||||
|
||||
let payload_len = buffer.len() - 20;
|
||||
let mut responses = Vec::new();
|
||||
let _ = compose_ipv4_packet(
|
||||
ComposeIpv4PacketArgs {
|
||||
buf: &mut buffer,
|
||||
src_v4: &source,
|
||||
dst_v4: &destination,
|
||||
next_protocol: IpProtocol::Icmp,
|
||||
payload_len,
|
||||
payload_mtu: 1200,
|
||||
ip_id: rand::random(),
|
||||
},
|
||||
|buf| {
|
||||
let mut packet = ZCPacket::new_with_payload(buf);
|
||||
packet.fill_peer_manager_hdr(
|
||||
source_peer_id,
|
||||
destination_peer_id,
|
||||
PacketType::Data as u8,
|
||||
);
|
||||
responses.push(packet);
|
||||
Ok(())
|
||||
},
|
||||
);
|
||||
IcmpProxyAction::SendToPeer(responses)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gateway::proxy::cidr_table::{ProxyCidrRule, ProxyCidrSnapshot};
|
||||
|
||||
fn echo_request_with_payload(
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
payload: &[u8],
|
||||
) -> ZCPacket {
|
||||
let mut bytes = vec![0_u8; 20 + 8 + payload.len()];
|
||||
{
|
||||
let mut request = Icmpv4Packet::new_unchecked(&mut bytes[20..]);
|
||||
request.set_msg_type(Icmpv4Message::EchoRequest);
|
||||
request.set_echo_ident(7);
|
||||
request.set_echo_seq_no(11);
|
||||
request.data_mut().copy_from_slice(payload);
|
||||
request.fill_checksum();
|
||||
}
|
||||
{
|
||||
let packet_len = bytes.len() as u16;
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut bytes);
|
||||
ipv4.set_version(4);
|
||||
ipv4.set_header_len(20);
|
||||
ipv4.set_total_len(packet_len);
|
||||
ipv4.set_hop_limit(64);
|
||||
ipv4.set_next_header(IpProtocol::Icmp);
|
||||
ipv4.set_src_addr(source);
|
||||
ipv4.set_dst_addr(destination);
|
||||
ipv4.fill_checksum();
|
||||
}
|
||||
let mut packet = ZCPacket::new_with_payload(&bytes);
|
||||
packet.fill_peer_manager_hdr(101, 202, PacketType::Data as u8);
|
||||
packet
|
||||
}
|
||||
|
||||
fn echo_request(source: Ipv4Addr, destination: Ipv4Addr) -> ZCPacket {
|
||||
echo_request_with_payload(source, destination, b"ping")
|
||||
}
|
||||
|
||||
fn engine(rule: Option<ProxyCidrRule>) -> IcmpProxyEngine {
|
||||
let table = ProxyCidrTable::from_snapshot(ProxyCidrSnapshot {
|
||||
rules: rule.into_iter().collect(),
|
||||
});
|
||||
IcmpProxyEngine::new(Arc::new(table), Duration::from_secs(10))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inactive_proxy_passes_echo_request() {
|
||||
let engine = engine(None);
|
||||
let packet = echo_request("10.0.0.2".parse().unwrap(), "192.0.2.2".parse().unwrap());
|
||||
|
||||
assert!(matches!(
|
||||
engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
IcmpProxyAction::Pass
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_tun_local_request_returns_echo_reply_to_origin_peer() {
|
||||
let engine = engine(None);
|
||||
let packet = echo_request("10.0.0.2".parse().unwrap(), "10.0.0.1".parse().unwrap());
|
||||
|
||||
let IcmpProxyAction::SendToPeer(replies) = engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
},
|
||||
) else {
|
||||
panic!("expected local reply");
|
||||
};
|
||||
let [reply] = replies.as_slice() else {
|
||||
panic!("expected one local reply");
|
||||
};
|
||||
let header = reply.peer_manager_header().unwrap();
|
||||
assert_eq!(header.from_peer_id.get(), 202);
|
||||
assert_eq!(header.to_peer_id.get(), 101);
|
||||
let ipv4 = Ipv4Packet::new_checked(reply.payload()).unwrap();
|
||||
assert_eq!(ipv4.src_addr(), "10.0.0.1".parse::<Ipv4Addr>().unwrap());
|
||||
assert_eq!(ipv4.dst_addr(), "10.0.0.2".parse::<Ipv4Addr>().unwrap());
|
||||
let reply = Icmpv4Packet::new_checked(ipv4.payload()).unwrap();
|
||||
assert_eq!(reply.echo_ident(), 7);
|
||||
assert_eq!(reply.echo_seq_no(), 11);
|
||||
assert_eq!(reply.data(), b"ping");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn peer_packet_rejects_ipv4_header_shorter_than_minimum() {
|
||||
let engine = engine(None);
|
||||
let mut packet = echo_request("10.0.0.2".parse().unwrap(), "8.0.0.1".parse().unwrap());
|
||||
Ipv4Packet::new_unchecked(packet.mut_payload()).set_header_len(16);
|
||||
|
||||
assert!(matches!(
|
||||
engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("8.0.0.1".parse().unwrap()),
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
}
|
||||
),
|
||||
IcmpProxyAction::Pass
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mapped_request_and_socket_reply_round_trip() {
|
||||
let engine = engine(Some(ProxyCidrRule {
|
||||
cidr: "127.0.0.0/24".parse().unwrap(),
|
||||
mapped_cidr: Some("10.10.10.0/24".parse().unwrap()),
|
||||
}));
|
||||
let packet = echo_request("10.0.0.2".parse().unwrap(), "10.10.10.42".parse().unwrap());
|
||||
|
||||
let IcmpProxyAction::SendToSocket {
|
||||
destination,
|
||||
packet: request,
|
||||
} = engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
else {
|
||||
panic!("expected socket request");
|
||||
};
|
||||
assert_eq!(destination, "127.0.0.42".parse::<Ipv4Addr>().unwrap());
|
||||
let request = Icmpv4Packet::new_checked(&request).unwrap();
|
||||
assert_eq!(request.data(), b"ping");
|
||||
|
||||
let mut response = echo_request(destination, "10.0.0.1".parse().unwrap())
|
||||
.payload()
|
||||
.to_vec();
|
||||
{
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut response);
|
||||
let mut reply = Icmpv4Packet::new_unchecked(ipv4.payload_mut());
|
||||
reply.set_msg_type(Icmpv4Message::EchoReply);
|
||||
reply.fill_checksum();
|
||||
ipv4.set_src_addr(destination);
|
||||
ipv4.fill_checksum();
|
||||
}
|
||||
let replies = engine.handle_socket_response(destination, &mut response);
|
||||
let [reply] = replies.as_slice() else {
|
||||
panic!("expected one socket reply");
|
||||
};
|
||||
let header = reply.peer_manager_header().unwrap();
|
||||
assert_eq!(header.from_peer_id.get(), 202);
|
||||
assert_eq!(header.to_peer_id.get(), 101);
|
||||
assert!(header.is_no_proxy());
|
||||
let ipv4 = Ipv4Packet::new_checked(reply.payload()).unwrap();
|
||||
assert_eq!(ipv4.src_addr(), "10.10.10.42".parse::<Ipv4Addr>().unwrap());
|
||||
assert_eq!(ipv4.dst_addr(), "10.0.0.2".parse::<Ipv4Addr>().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socket_response_rejects_ipv4_header_shorter_than_minimum() {
|
||||
let engine = engine(Some(ProxyCidrRule {
|
||||
cidr: "127.0.0.0/24".parse().unwrap(),
|
||||
mapped_cidr: Some("10.10.10.0/24".parse().unwrap()),
|
||||
}));
|
||||
let destination = "127.0.0.42".parse().unwrap();
|
||||
let request = echo_request("10.0.0.2".parse().unwrap(), "10.10.10.42".parse().unwrap());
|
||||
assert!(matches!(
|
||||
engine.handle_peer_packet(
|
||||
&request,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
IcmpProxyAction::SendToSocket { .. }
|
||||
));
|
||||
|
||||
let key = IcmpNatKey {
|
||||
real_destination: destination,
|
||||
identifier: 7,
|
||||
sequence: 11,
|
||||
};
|
||||
let mut response = echo_request(destination, "10.0.0.1".parse().unwrap())
|
||||
.payload()
|
||||
.to_vec();
|
||||
{
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut response);
|
||||
ipv4.set_header_len(16);
|
||||
let mut reply = Icmpv4Packet::new_unchecked(ipv4.payload_mut());
|
||||
reply.set_msg_type(Icmpv4Message::EchoReply);
|
||||
reply.set_msg_code(0);
|
||||
reply.set_echo_ident(7);
|
||||
reply.set_echo_seq_no(11);
|
||||
}
|
||||
|
||||
assert!(
|
||||
engine
|
||||
.handle_socket_response(destination, &mut response)
|
||||
.is_empty()
|
||||
);
|
||||
assert!(engine.nat_table.contains_key(&key));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_local_reply_preserves_all_ipv4_fragments() {
|
||||
let engine = engine(None);
|
||||
let packet = echo_request_with_payload(
|
||||
"10.0.0.2".parse().unwrap(),
|
||||
"10.0.0.1".parse().unwrap(),
|
||||
&[0; 2400],
|
||||
);
|
||||
|
||||
let IcmpProxyAction::SendToPeer(replies) = engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
},
|
||||
) else {
|
||||
panic!("expected local replies");
|
||||
};
|
||||
|
||||
assert_eq!(replies.len(), 3);
|
||||
assert!(replies.iter().all(|packet| {
|
||||
let header = packet.peer_manager_header().unwrap();
|
||||
header.from_peer_id.get() == 202 && header.to_peer_id.get() == 101
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn large_socket_reply_preserves_all_ipv4_fragments() {
|
||||
let engine = engine(Some(ProxyCidrRule {
|
||||
cidr: "127.0.0.0/24".parse().unwrap(),
|
||||
mapped_cidr: Some("10.10.10.0/24".parse().unwrap()),
|
||||
}));
|
||||
let destination = "127.0.0.42".parse().unwrap();
|
||||
let packet = echo_request_with_payload(
|
||||
"10.0.0.2".parse().unwrap(),
|
||||
"10.10.10.42".parse().unwrap(),
|
||||
&[0; 2400],
|
||||
);
|
||||
assert!(matches!(
|
||||
engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: Some("10.0.0.1".parse().unwrap()),
|
||||
..Default::default()
|
||||
},
|
||||
),
|
||||
IcmpProxyAction::SendToSocket { .. }
|
||||
));
|
||||
assert!(engine.nat_table.contains_key(&IcmpNatKey {
|
||||
real_destination: destination,
|
||||
identifier: 7,
|
||||
sequence: 11,
|
||||
}));
|
||||
|
||||
let mut response =
|
||||
echo_request_with_payload(destination, "10.0.0.1".parse().unwrap(), &[0; 2400])
|
||||
.payload()
|
||||
.to_vec();
|
||||
{
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut response);
|
||||
let mut reply = Icmpv4Packet::new_unchecked(ipv4.payload_mut());
|
||||
reply.set_msg_type(Icmpv4Message::EchoReply);
|
||||
reply.fill_checksum();
|
||||
ipv4.set_src_addr(destination);
|
||||
// Raw sockets may return a buffer with bytes beyond the IPv4 total
|
||||
// length. The native implementation composes from the received
|
||||
// buffer length, so keep that case covered without changing the
|
||||
// existing in-place composer in this refactor.
|
||||
ipv4.set_total_len(1220);
|
||||
ipv4.fill_checksum();
|
||||
}
|
||||
let ipv4 = Ipv4Packet::new_checked(&response).unwrap();
|
||||
let echo_reply = Icmpv4Packet::new_checked(ipv4.payload()).unwrap();
|
||||
assert_eq!(echo_reply.msg_type(), Icmpv4Message::EchoReply);
|
||||
assert_eq!(echo_reply.echo_ident(), 7);
|
||||
assert_eq!(echo_reply.echo_seq_no(), 11);
|
||||
|
||||
let replies = engine.handle_socket_response(destination, &mut response);
|
||||
assert_eq!(replies.len(), 3);
|
||||
assert!(replies.iter().all(|packet| {
|
||||
let header = packet.peer_manager_header().unwrap();
|
||||
header.from_peer_id.get() == 202
|
||||
&& header.to_peer_id.get() == 101
|
||||
&& header.is_no_proxy()
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,337 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::{
|
||||
Arc, Weak,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use tokio::{
|
||||
sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel},
|
||||
task::JoinSet,
|
||||
};
|
||||
|
||||
use crate::{
|
||||
packet::ZCPacket,
|
||||
peers::{
|
||||
PeerPacketFilter,
|
||||
peer_manager::{PeerManagerCore, PipelineRegistrationGuard},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
icmp_proxy_engine::{IcmpProxyAction, IcmpProxyContext, IcmpProxyEngine},
|
||||
traits::{IcmpProxyRuntime, IcmpProxySocket, ProxyRuntimeError},
|
||||
};
|
||||
|
||||
async fn start_icmp_runtime<R: IcmpProxyRuntime + 'static>(
|
||||
runtime: &R,
|
||||
no_tun: bool,
|
||||
) -> Result<Option<Arc<R::Socket>>, ProxyRuntimeError> {
|
||||
match runtime.start_icmp().await {
|
||||
Ok(socket) => Ok(Some(socket)),
|
||||
Err(err) => {
|
||||
runtime.stop_icmp();
|
||||
if !no_tun {
|
||||
return Err(err);
|
||||
}
|
||||
tracing::warn!(?err, "start ICMP runtime failed without TUN");
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub struct IcmpProxyService<R: IcmpProxyRuntime + 'static> {
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
engine: Arc<IcmpProxyEngine>,
|
||||
response_tx: UnboundedSender<ZCPacket>,
|
||||
response_rx: std::sync::Mutex<Option<UnboundedReceiver<ZCPacket>>>,
|
||||
pipeline_guard: std::sync::Mutex<Option<PipelineRegistrationGuard>>,
|
||||
tasks: std::sync::Mutex<JoinSet<()>>,
|
||||
socket: std::sync::Mutex<Option<Arc<R::Socket>>>,
|
||||
runtime_started: AtomicBool,
|
||||
started: AtomicBool,
|
||||
}
|
||||
|
||||
impl<R: IcmpProxyRuntime + 'static> IcmpProxyService<R> {
|
||||
pub fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
fragment_timeout: Duration,
|
||||
) -> Arc<Self> {
|
||||
let (response_tx, response_rx) = unbounded_channel();
|
||||
Arc::new(Self {
|
||||
peer_manager,
|
||||
runtime,
|
||||
engine: Arc::new(IcmpProxyEngine::new(cidr_table, fragment_timeout)),
|
||||
response_tx,
|
||||
response_rx: std::sync::Mutex::new(Some(response_rx)),
|
||||
pipeline_guard: std::sync::Mutex::new(None),
|
||||
tasks: std::sync::Mutex::new(JoinSet::new()),
|
||||
socket: std::sync::Mutex::new(None),
|
||||
runtime_started: AtomicBool::new(false),
|
||||
started: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn start(self: &Arc<Self>) -> Result<(), ProxyRuntimeError> {
|
||||
if self.started.swap(true, Ordering::AcqRel) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let socket = match start_icmp_runtime(self.runtime.as_ref(), snapshot.no_tun).await {
|
||||
Ok(socket) => socket,
|
||||
Err(err) => {
|
||||
self.started.store(false, Ordering::Release);
|
||||
return Err(err);
|
||||
}
|
||||
};
|
||||
let runtime_started = socket.is_some();
|
||||
self.runtime_started
|
||||
.store(runtime_started, Ordering::Release);
|
||||
self.socket.lock().unwrap().clone_from(&socket);
|
||||
|
||||
if let Some(mut response_rx) = self.response_rx.lock().unwrap().take() {
|
||||
let peer_manager = self.peer_manager.clone();
|
||||
let latency_first = snapshot.latency_first;
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
while let Some(mut packet) = response_rx.recv().await {
|
||||
let Some(header) = packet.mut_peer_manager_header() else {
|
||||
continue;
|
||||
};
|
||||
header.set_latency_first(latency_first);
|
||||
let to_peer_id = header.to_peer_id.into();
|
||||
if let Err(err) = peer_manager.send_msg_for_proxy(packet, to_peer_id).await {
|
||||
tracing::error!(?err, "send ICMP proxy response to peer failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if let Some(socket) = socket {
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
let recv_result = socket.recv().await;
|
||||
let (peer_ip, mut packet) = match recv_result {
|
||||
Ok(packet) => packet,
|
||||
Err(err) => {
|
||||
tracing::error!(?err, "receive ICMP packet failed");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
if packet.is_empty() {
|
||||
tracing::error!("received empty ICMP packet");
|
||||
break;
|
||||
}
|
||||
let IpAddr::V4(peer_ip) = peer_ip else {
|
||||
continue;
|
||||
};
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service.handle_socket_response(peer_ip, &mut packet);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(1)).await;
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service.engine.remove_expired_fragments();
|
||||
}
|
||||
});
|
||||
|
||||
let guard = self
|
||||
.peer_manager
|
||||
.add_managed_packet_process_pipeline(Box::new(IcmpProxyServiceFilter {
|
||||
service: Arc::downgrade(self),
|
||||
}))
|
||||
.await;
|
||||
self.pipeline_guard.lock().unwrap().replace(guard);
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(1)).await;
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service
|
||||
.engine
|
||||
.remove_expired_entries(Duration::from_secs(20));
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
if !self.started.swap(false, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
if let Some(guard) = self.pipeline_guard.lock().unwrap().take() {
|
||||
guard.close();
|
||||
}
|
||||
self.tasks.lock().unwrap().abort_all();
|
||||
if self.runtime_started.swap(false, Ordering::AcqRel) {
|
||||
self.runtime.stop_icmp();
|
||||
}
|
||||
self.socket.lock().unwrap().take();
|
||||
}
|
||||
|
||||
async fn handle_peer_packet(self: Arc<Self>, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
match self.engine.handle_peer_packet(
|
||||
&packet,
|
||||
IcmpProxyContext {
|
||||
virtual_ipv4: snapshot.virtual_ipv4,
|
||||
enable_exit_node: snapshot.enable_exit_node,
|
||||
no_tun: snapshot.no_tun,
|
||||
},
|
||||
) {
|
||||
IcmpProxyAction::Pass => Some(packet),
|
||||
IcmpProxyAction::SendToSocket {
|
||||
destination,
|
||||
packet: request,
|
||||
} => {
|
||||
let socket = self.socket.lock().unwrap().clone();
|
||||
match socket {
|
||||
Some(socket) => {
|
||||
if let Err(err) = socket.send(destination, &request).await {
|
||||
tracing::error!(?err, "send ICMP packet through runtime failed");
|
||||
}
|
||||
}
|
||||
None => tracing::error!("send ICMP packet without a runtime socket"),
|
||||
}
|
||||
None
|
||||
}
|
||||
IcmpProxyAction::SendToPeer(packets) => {
|
||||
for packet in packets {
|
||||
if let Err(err) = self.response_tx.send(packet) {
|
||||
tracing::error!(?err, "queue local ICMP response failed");
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: IcmpProxyRuntime + 'static> IcmpProxyService<R> {
|
||||
fn handle_socket_response(&self, peer_ip: Ipv4Addr, packet: &mut [u8]) {
|
||||
for response in self.engine.handle_socket_response(peer_ip, packet) {
|
||||
if let Err(err) = self.response_tx.send(response) {
|
||||
tracing::error!(?err, "queue ICMP socket response failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: IcmpProxyRuntime + 'static> Drop for IcmpProxyService<R> {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
struct IcmpProxyServiceFilter<R: IcmpProxyRuntime + 'static> {
|
||||
service: Weak<IcmpProxyService<R>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<R: IcmpProxyRuntime + 'static> PeerPacketFilter for IcmpProxyServiceFilter<R> {
|
||||
async fn try_process_packet_from_peer(&self, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let Some(service) = self.service.upgrade() else {
|
||||
return Some(packet);
|
||||
};
|
||||
service.handle_peer_packet(packet).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicUsize, Ordering},
|
||||
},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::gateway::proxy::traits::{IcmpProxySocket, ProxyRuntimeInfo, ProxyRuntimeSnapshot};
|
||||
|
||||
#[derive(Default)]
|
||||
struct PartialStartRuntime {
|
||||
stop_count: AtomicUsize,
|
||||
}
|
||||
|
||||
impl ProxyRuntimeInfo for PartialStartRuntime {
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
ProxyRuntimeSnapshot::default()
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, _ip: &IpAddr) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
struct NoopIcmpSocket;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl IcmpProxySocket for NoopIcmpSocket {
|
||||
async fn send(
|
||||
&self,
|
||||
_destination: Ipv4Addr,
|
||||
_packet: &[u8],
|
||||
) -> Result<(), ProxyRuntimeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn recv(&self) -> Result<(IpAddr, Vec<u8>), ProxyRuntimeError> {
|
||||
Err(std::io::Error::other("unused test socket").into())
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl IcmpProxyRuntime for PartialStartRuntime {
|
||||
type Socket = NoopIcmpSocket;
|
||||
|
||||
async fn start_icmp(&self) -> Result<Arc<Self::Socket>, ProxyRuntimeError> {
|
||||
Err(std::io::Error::other("partial start").into())
|
||||
}
|
||||
|
||||
fn stop_icmp(&self) {
|
||||
self.stop_count.fetch_add(1, Ordering::AcqRel);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_runtime_start_rolls_back_partial_resources() {
|
||||
let runtime = PartialStartRuntime::default();
|
||||
|
||||
assert!(start_icmp_runtime(&runtime, false).await.is_err());
|
||||
assert_eq!(runtime.stop_count.load(Ordering::Acquire), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn no_tun_suppresses_start_error_after_rollback() {
|
||||
let runtime = PartialStartRuntime::default();
|
||||
|
||||
let socket = start_icmp_runtime(&runtime, true).await.unwrap();
|
||||
assert!(socket.is_none());
|
||||
if socket.is_some() {
|
||||
runtime.stop_icmp();
|
||||
}
|
||||
assert_eq!(runtime.stop_count.load(Ordering::Acquire), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,321 @@
|
||||
use std::{
|
||||
net::Ipv4Addr,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use dashmap::DashMap;
|
||||
pub use smoltcp::wire::IpProtocol;
|
||||
use smoltcp::wire::Ipv4Packet;
|
||||
|
||||
#[derive(Debug, Hash, PartialEq, Eq, Clone)]
|
||||
struct IpReassemblerKey {
|
||||
source: Ipv4Addr,
|
||||
destination: Ipv4Addr,
|
||||
id: u16,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct IpFragment {
|
||||
offset: u16,
|
||||
data: Vec<u8>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IpPacket {
|
||||
total_length: Option<u16>,
|
||||
fragments: Vec<IpFragment>,
|
||||
}
|
||||
|
||||
impl IpPacket {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
total_length: None,
|
||||
fragments: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn add_fragment(&mut self, fragment: IpFragment) {
|
||||
for existing in &self.fragments {
|
||||
let existing_end = existing.offset + existing.data.len() as u16;
|
||||
let fragment_end = fragment.offset + fragment.data.len() as u16;
|
||||
if existing.offset <= fragment.offset && fragment.offset < existing_end {
|
||||
tracing::trace!(
|
||||
existing_offset = existing.offset,
|
||||
fragment_offset = fragment.offset,
|
||||
existing_len = existing.data.len(),
|
||||
fragment_len = fragment.data.len(),
|
||||
"fragment overlap"
|
||||
);
|
||||
return;
|
||||
}
|
||||
if fragment.offset <= existing.offset && existing.offset < fragment_end {
|
||||
tracing::trace!(
|
||||
existing_offset = existing.offset,
|
||||
fragment_offset = fragment.offset,
|
||||
existing_len = existing.data.len(),
|
||||
fragment_len = fragment.data.len(),
|
||||
"fragment overlap"
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
self.fragments.push(fragment);
|
||||
}
|
||||
|
||||
fn set_total_length(&mut self, total_length: u16) {
|
||||
self.total_length = Some(total_length);
|
||||
}
|
||||
|
||||
fn assemble(&mut self) -> Option<Vec<u8>> {
|
||||
let total_length = self.total_length?;
|
||||
self.fragments.sort_by_key(|fragment| fragment.offset);
|
||||
|
||||
let mut offset = 0;
|
||||
let mut ret = Vec::with_capacity(total_length as usize);
|
||||
for fragment in &self.fragments {
|
||||
if fragment.offset != offset {
|
||||
return None;
|
||||
}
|
||||
ret.extend_from_slice(&fragment.data);
|
||||
offset += fragment.data.len() as u16;
|
||||
}
|
||||
|
||||
(offset == total_length).then_some(ret)
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: AsRef<[u8]> + ?Sized> From<&Ipv4Packet<&T>> for IpFragment {
|
||||
fn from(packet: &Ipv4Packet<&T>) -> Self {
|
||||
Self {
|
||||
offset: packet.frag_offset(),
|
||||
data: packet.payload().to_vec(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct IpReassemblerValue {
|
||||
packet: IpPacket,
|
||||
timestamp: Instant,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct IpReassembler {
|
||||
packets: DashMap<IpReassemblerKey, IpReassemblerValue>,
|
||||
timeout: Duration,
|
||||
}
|
||||
|
||||
impl IpReassembler {
|
||||
pub fn new(timeout: Duration) -> Self {
|
||||
Self {
|
||||
packets: DashMap::new(),
|
||||
timeout,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_packet_fragmented<T: AsRef<[u8]>>(packet: &Ipv4Packet<T>) -> bool {
|
||||
packet.frag_offset() != 0 || packet.more_frags()
|
||||
}
|
||||
|
||||
pub fn is_last_fragment<T: AsRef<[u8]>>(packet: &Ipv4Packet<T>) -> bool {
|
||||
!packet.more_frags()
|
||||
}
|
||||
|
||||
pub fn add_fragment<T: AsRef<[u8]> + ?Sized>(
|
||||
&self,
|
||||
packet: &Ipv4Packet<&T>,
|
||||
) -> Option<Vec<u8>> {
|
||||
let total_length = packet.total_len() - packet.header_len() as u16;
|
||||
if total_length != packet.payload().len() as u16 {
|
||||
tracing::trace!(
|
||||
?total_length,
|
||||
payload_len = ?packet.payload().len(),
|
||||
"unexpected total length",
|
||||
);
|
||||
return None;
|
||||
}
|
||||
|
||||
let key = IpReassemblerKey {
|
||||
source: packet.src_addr(),
|
||||
destination: packet.dst_addr(),
|
||||
id: packet.ident(),
|
||||
};
|
||||
let fragment: IpFragment = packet.into();
|
||||
|
||||
tracing::trace!(?key, offset = fragment.offset, total_length, "add fragment");
|
||||
|
||||
let mut entry = self.packets.entry(key.clone()).or_insert_with(|| {
|
||||
let packet = IpPacket::new();
|
||||
let timestamp = Instant::now();
|
||||
IpReassemblerValue { packet, timestamp }
|
||||
});
|
||||
let value_mut = entry.value_mut();
|
||||
|
||||
if Self::is_last_fragment(packet) {
|
||||
value_mut
|
||||
.packet
|
||||
.set_total_length(total_length + fragment.offset);
|
||||
}
|
||||
|
||||
value_mut.packet.add_fragment(fragment);
|
||||
if let Some(data) = value_mut.packet.assemble() {
|
||||
drop(entry);
|
||||
self.packets.remove(&key);
|
||||
Some(data)
|
||||
} else {
|
||||
value_mut.timestamp = Instant::now();
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_expired_packets(&self) {
|
||||
let timeout = self.timeout;
|
||||
self.packets
|
||||
.retain(|_, value| value.timestamp.elapsed() <= timeout);
|
||||
self.packets.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct ComposeIpv4PacketArgs<'a> {
|
||||
pub buf: &'a mut [u8],
|
||||
pub src_v4: &'a Ipv4Addr,
|
||||
pub dst_v4: &'a Ipv4Addr,
|
||||
pub next_protocol: IpProtocol,
|
||||
pub payload_len: usize,
|
||||
pub payload_mtu: usize,
|
||||
pub ip_id: u16,
|
||||
}
|
||||
|
||||
pub fn compose_ipv4_packet<F>(args: ComposeIpv4PacketArgs, mut cb: F) -> anyhow::Result<()>
|
||||
where
|
||||
F: FnMut(&[u8]) -> anyhow::Result<()>,
|
||||
{
|
||||
let total_pieces = args.payload_len.div_ceil(args.payload_mtu);
|
||||
let mut buf_offset = 0;
|
||||
let mut fragment_offset = 0;
|
||||
let mut cur_piece = 0;
|
||||
while fragment_offset < args.payload_len {
|
||||
let next_fragment_offset =
|
||||
std::cmp::min(fragment_offset + args.payload_mtu, args.payload_len);
|
||||
let fragment_len = next_fragment_offset - fragment_offset;
|
||||
let packet_len = fragment_len + smoltcp::wire::IPV4_HEADER_LEN;
|
||||
let mut ipv4_packet =
|
||||
Ipv4Packet::new_unchecked(&mut args.buf[buf_offset..buf_offset + packet_len]);
|
||||
ipv4_packet.set_version(4);
|
||||
ipv4_packet.set_header_len(smoltcp::wire::IPV4_HEADER_LEN as u8);
|
||||
ipv4_packet.set_total_len(packet_len as u16);
|
||||
ipv4_packet.set_ident(args.ip_id);
|
||||
ipv4_packet.clear_flags();
|
||||
if total_pieces > 1 {
|
||||
ipv4_packet.set_more_frags(cur_piece != total_pieces - 1);
|
||||
ipv4_packet.set_frag_offset(fragment_offset as u16);
|
||||
} else {
|
||||
ipv4_packet.set_dont_frag(true);
|
||||
ipv4_packet.set_frag_offset(0);
|
||||
}
|
||||
ipv4_packet.set_dscp(0);
|
||||
ipv4_packet.set_ecn(0);
|
||||
ipv4_packet.set_hop_limit(32);
|
||||
ipv4_packet.set_src_addr(*args.src_v4);
|
||||
ipv4_packet.set_dst_addr(*args.dst_v4);
|
||||
ipv4_packet.set_next_header(args.next_protocol);
|
||||
ipv4_packet.fill_checksum();
|
||||
|
||||
tracing::trace!(?ipv4_packet, "proxy ipv4 packet composed");
|
||||
|
||||
cb(ipv4_packet.as_ref())?;
|
||||
|
||||
buf_offset += next_fragment_offset - fragment_offset;
|
||||
fragment_offset = next_fragment_offset;
|
||||
cur_piece += 1;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn compose_ipv4_packet_fragments_arbitrary_payload() {
|
||||
let payload_len = 1932;
|
||||
let payload_mtu = 1256;
|
||||
let mut buffer = vec![0xff; smoltcp::wire::IPV4_HEADER_LEN + payload_len];
|
||||
let expected_payload = buffer[smoltcp::wire::IPV4_HEADER_LEN..].to_vec();
|
||||
let mut fragments = Vec::new();
|
||||
|
||||
compose_ipv4_packet(
|
||||
ComposeIpv4PacketArgs {
|
||||
buf: &mut buffer,
|
||||
src_v4: &Ipv4Addr::new(10, 1, 2, 3),
|
||||
dst_v4: &Ipv4Addr::new(10, 1, 2, 4),
|
||||
next_protocol: IpProtocol::Udp,
|
||||
payload_len,
|
||||
payload_mtu,
|
||||
ip_id: 42,
|
||||
},
|
||||
|fragment| {
|
||||
fragments.push(fragment.to_vec());
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(fragments.len(), 2);
|
||||
let first = Ipv4Packet::new_checked(fragments[0].as_slice()).unwrap();
|
||||
let second = Ipv4Packet::new_checked(fragments[1].as_slice()).unwrap();
|
||||
assert!(first.more_frags());
|
||||
assert_eq!(first.frag_offset(), 0);
|
||||
assert!(!second.more_frags());
|
||||
assert_eq!(second.frag_offset(), payload_mtu as u16);
|
||||
|
||||
let reassembled = first
|
||||
.payload()
|
||||
.iter()
|
||||
.chain(second.payload())
|
||||
.copied()
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(reassembled, expected_payload);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reassembler() {
|
||||
let raw_packets = [
|
||||
vec![
|
||||
0x45, 0x00, 0x00, 0x1c, 0x1c, 0x46, 0x20, 0x01, 0x40, 0x06, 0xb1, 0xe6, 0xc0, 0xa8,
|
||||
0x00, 0x01, 0xc0, 0xa8, 0x00, 0x02, 0x04, 0x05, 0x06, 0x07, 0x04, 0x05, 0x06, 0x07,
|
||||
],
|
||||
vec![
|
||||
0x45, 0x00, 0x00, 0x1c, 0x1c, 0x46, 0x00, 0x02, 0x40, 0x06, 0xb1, 0xe6, 0xc0, 0xa8,
|
||||
0x00, 0x01, 0xc0, 0xa8, 0x00, 0x02, 0x08, 0x09, 0x0a, 0x0b, 0x04, 0x05, 0x06, 0x07,
|
||||
],
|
||||
vec![
|
||||
0x45, 0x00, 0x00, 0x1c, 0x1c, 0x46, 0x20, 0x00, 0x40, 0x06, 0xb1, 0xe6, 0xc0, 0xa8,
|
||||
0x00, 0x01, 0xc0, 0xa8, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
|
||||
],
|
||||
vec![
|
||||
0x45, 0x00, 0x00, 0x1c, 0x1c, 0x47, 0x20, 0x00, 0x40, 0x06, 0xb1, 0xe6, 0xc0, 0xa8,
|
||||
0x00, 0x01, 0xc0, 0xa8, 0x00, 0x02, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
|
||||
],
|
||||
];
|
||||
|
||||
let reassembler = IpReassembler::new(Duration::from_secs(1));
|
||||
|
||||
for (idx, raw_packet) in raw_packets.iter().enumerate() {
|
||||
let packet = Ipv4Packet::new_checked(raw_packet.as_slice()).unwrap();
|
||||
let ret = reassembler.add_fragment(&packet);
|
||||
if idx != 2 {
|
||||
assert!(ret.is_none());
|
||||
} else {
|
||||
assert!(ret.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
reassembler.remove_expired_packets();
|
||||
assert_eq!(1, reassembler.packets.len());
|
||||
|
||||
std::thread::sleep(Duration::from_secs(2));
|
||||
reassembler.remove_expired_packets();
|
||||
assert_eq!(0, reassembler.packets.len());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
pub mod cidr_monitor;
|
||||
pub(crate) mod cidr_table;
|
||||
pub mod icmp_host;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod proxy_acl;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod service;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub mod traits;
|
||||
#[cfg_attr(not(feature = "wrapped-transport"), allow(dead_code))]
|
||||
pub mod wrapped_transport;
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod icmp_proxy_engine;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod icmp_proxy_service;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod ip_reassembler;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub mod tcp_proxy_engine;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod tcp_proxy_service;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod tcp_socket_connector;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod udp_proxy_engine;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod udp_proxy_service;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod udp_socket_runtime;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod wrapped_tcp_proxy;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub(crate) mod wrapped_transport_destination;
|
||||
@@ -0,0 +1,49 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use easytier_proto::acl::{Action, ChainType};
|
||||
use tokio::io::{AsyncRead, AsyncWrite, copy_bidirectional};
|
||||
use tokio_util::io::InspectReader;
|
||||
|
||||
use crate::peers::acl::{filter::AclFilter, processor::PacketInfo};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProxyAclHandler {
|
||||
pub acl_filter: Arc<AclFilter>,
|
||||
pub packet_info: PacketInfo,
|
||||
pub chain_type: ChainType,
|
||||
}
|
||||
|
||||
impl ProxyAclHandler {
|
||||
pub fn handle_packet(&self, buf: &[u8]) -> anyhow::Result<()> {
|
||||
self.handle_packet_size(buf.len())
|
||||
}
|
||||
|
||||
pub fn handle_packet_size(&self, packet_size: usize) -> anyhow::Result<()> {
|
||||
let mut packet_info = self.packet_info.clone();
|
||||
packet_info.packet_size = packet_size;
|
||||
let processor = self.acl_filter.get_processor();
|
||||
let ret = processor.process_packet(&packet_info, self.chain_type);
|
||||
self.acl_filter
|
||||
.handle_acl_result(&ret, &packet_info, self.chain_type, &processor);
|
||||
if !matches!(ret.action, Action::Allow) {
|
||||
anyhow::bail!("acl denied");
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn copy_bidirection_with_acl(
|
||||
&self,
|
||||
src: impl AsyncRead + AsyncWrite + Unpin,
|
||||
mut dst: impl AsyncRead + AsyncWrite + Unpin,
|
||||
) -> anyhow::Result<()> {
|
||||
let (src_reader, src_writer) = tokio::io::split(src);
|
||||
let src_reader = InspectReader::new(src_reader, |buf| {
|
||||
let _ = self.handle_packet(buf);
|
||||
});
|
||||
let mut src = tokio::io::join(src_reader, src_writer);
|
||||
|
||||
copy_bidirectional(&mut src, &mut dst).await?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use cidr::Ipv4Inet;
|
||||
use tokio::sync::Mutex;
|
||||
|
||||
use crate::{
|
||||
config::IpPrefix,
|
||||
config::runtime::{CoreInstanceRuntimeConfig, CoreRuntimeConfigStore},
|
||||
connectivity::{
|
||||
direct::DirectConnectorHost, hole_punch::tcp::TcpHolePunchHost, protocol::protocol_uses_udp,
|
||||
},
|
||||
foundation::stats::{LabelSet, LabelType, MetricName, StatsManager},
|
||||
listener::RunningListenerRegistry,
|
||||
peers::peer_manager::PeerManagerCore,
|
||||
process_runtime::ProtectedTcpPortRegistry,
|
||||
socket::{IpVersion, SocketContext, udp::UdpBindOptions},
|
||||
};
|
||||
|
||||
use super::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
icmp_proxy_service::IcmpProxyService,
|
||||
tcp_proxy_engine::TcpNatEntrySnapshot,
|
||||
tcp_proxy_service::TcpProxyService,
|
||||
tcp_socket_connector::TcpSocketProxyConnector,
|
||||
traits::{
|
||||
IcmpProxyHost, IcmpProxyRuntime, IcmpProxySocket, ProxyRuntimeError, ProxyRuntimeInfo,
|
||||
ProxyRuntimeSnapshot, TcpProxyConnectContext, TcpProxyRuntime, UdpProxyPolicy,
|
||||
WrappedTcpDestinationRuntime,
|
||||
},
|
||||
udp_proxy_service::UdpProxyService,
|
||||
udp_socket_runtime::UdpSocketProxyRuntime,
|
||||
};
|
||||
|
||||
const UDP_PROXY_SOCKET_IDLE_TIMEOUT: Duration = Duration::from_secs(120);
|
||||
const PROXY_FRAGMENT_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
fn udp_proxy_bind_options(context: SocketContext) -> UdpBindOptions {
|
||||
UdpBindOptions::proxy_nat().with_context(context.with_ip_version(IpVersion::V4))
|
||||
}
|
||||
|
||||
fn ipv4_inet(prefix: &IpPrefix) -> Option<Ipv4Inet> {
|
||||
let IpAddr::V4(address) = prefix.address else {
|
||||
return None;
|
||||
};
|
||||
Ipv4Inet::new(address, prefix.prefix_len).ok()
|
||||
}
|
||||
|
||||
fn smoltcp_proxy_inet() -> Ipv4Inet {
|
||||
Ipv4Inet::new(Ipv4Addr::new(192, 88, 99, 254), 24)
|
||||
.expect("smoltcp proxy address must be a valid IPv4 interface")
|
||||
}
|
||||
|
||||
fn runtime_snapshot(
|
||||
config: &CoreInstanceRuntimeConfig,
|
||||
smoltcp_enabled: bool,
|
||||
) -> ProxyRuntimeSnapshot {
|
||||
let virtual_inet = config
|
||||
.peer
|
||||
.runtime
|
||||
.core
|
||||
.routes
|
||||
.ipv4
|
||||
.as_ref()
|
||||
.and_then(ipv4_inet);
|
||||
ProxyRuntimeSnapshot {
|
||||
local_inet: smoltcp_enabled.then(smoltcp_proxy_inet).or(virtual_inet),
|
||||
virtual_ipv4: virtual_inet.map(|inet| inet.address()),
|
||||
no_tun: config.services.proxy.no_tun,
|
||||
enable_exit_node: config.services.proxy.enable_exit_node,
|
||||
smoltcp_enabled,
|
||||
latency_first: config.peer.flags.latency_first && !config.peer.flags.p2p_only,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
config: CoreRuntimeConfigStore,
|
||||
stats: Arc<StatsManager>,
|
||||
protocol_label: &'static str,
|
||||
smoltcp_enabled: AtomicBool,
|
||||
}
|
||||
|
||||
impl<H> CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
config: CoreRuntimeConfigStore,
|
||||
protocol_label: &'static str,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
stats: peer_manager.stats_manager(),
|
||||
peer_manager,
|
||||
host,
|
||||
protected_tcp_ports,
|
||||
running_listeners,
|
||||
config,
|
||||
protocol_label,
|
||||
smoltcp_enabled: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn latch_smoltcp(&self) {
|
||||
self.smoltcp_enabled.store(
|
||||
self.config.snapshot().services.proxy.force_smoltcp,
|
||||
Ordering::Release,
|
||||
);
|
||||
}
|
||||
|
||||
fn should_deny_proxy(&self, destination: SocketAddr, is_udp: bool) -> bool {
|
||||
let destination_is_local = self.host.is_local_ip(&destination.ip())
|
||||
|| self.peer_manager.is_local_virtual_ip(&destination.ip());
|
||||
if !destination_is_local {
|
||||
return false;
|
||||
}
|
||||
|
||||
self.running_listeners
|
||||
.running_listeners()
|
||||
.iter()
|
||||
.any(|listener| {
|
||||
listener.port() == Some(destination.port())
|
||||
&& protocol_uses_udp(listener.scheme()) == is_udp
|
||||
})
|
||||
|| (!is_udp && self.protected_tcp_ports.contains(destination.port()))
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> ProxyRuntimeInfo for CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
runtime_snapshot(
|
||||
self.config.snapshot().as_ref(),
|
||||
self.smoltcp_enabled.load(Ordering::Acquire),
|
||||
)
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
self.peer_manager.is_local_virtual_ip(ip)
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> TcpProxyRuntime for CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
fn should_deny_tcp_proxy(&self, destination: SocketAddr) -> bool {
|
||||
self.should_deny_proxy(destination, false)
|
||||
}
|
||||
|
||||
fn record_tcp_proxy_connect(&self, context: TcpProxyConnectContext, socket_dst: SocketAddr) {
|
||||
self.stats
|
||||
.get_counter(
|
||||
MetricName::TcpProxyConnect,
|
||||
LabelSet::new()
|
||||
.with_label_type(LabelType::Protocol(self.protocol_label.to_owned()))
|
||||
.with_label_type(LabelType::DstIp(socket_dst.ip().to_string()))
|
||||
.with_label_type(LabelType::MappedDstIp(context.mapped_dst.ip().to_string())),
|
||||
)
|
||||
.inc();
|
||||
}
|
||||
}
|
||||
|
||||
impl<H> WrappedTcpDestinationRuntime for CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
ProxyRuntimeInfo::is_ip_local_virtual_ip(self, ip)
|
||||
}
|
||||
|
||||
fn no_tun(&self) -> bool {
|
||||
self.proxy_runtime_snapshot().no_tun
|
||||
}
|
||||
|
||||
fn should_deny_tcp_proxy(&self, dst: SocketAddr) -> bool {
|
||||
TcpProxyRuntime::should_deny_tcp_proxy(self, dst)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<H> UdpProxyPolicy for CoreProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
fn should_deny_udp_proxy(&self, destination: SocketAddr) -> bool {
|
||||
self.should_deny_proxy(destination, true)
|
||||
}
|
||||
|
||||
fn udp_response_ipv4_mtu(&self) -> usize {
|
||||
self.config.snapshot().services.proxy.udp_response_ipv4_mtu
|
||||
}
|
||||
}
|
||||
|
||||
struct CoreIcmpProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
policy: Arc<CoreProxyRuntime<H>>,
|
||||
host: Arc<dyn IcmpProxyHost>,
|
||||
socket: std::sync::Mutex<Option<Arc<dyn IcmpProxySocket>>>,
|
||||
context: SocketContext,
|
||||
}
|
||||
|
||||
impl<H> ProxyRuntimeInfo for CoreIcmpProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
self.policy.proxy_runtime_snapshot()
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
ProxyRuntimeInfo::is_ip_local_virtual_ip(self.policy.as_ref(), ip)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<H> IcmpProxyRuntime for CoreIcmpProxyRuntime<H>
|
||||
where
|
||||
H: DirectConnectorHost,
|
||||
{
|
||||
type Socket = dyn IcmpProxySocket;
|
||||
|
||||
async fn start_icmp(&self) -> Result<Arc<Self::Socket>, ProxyRuntimeError> {
|
||||
let socket = self.host.open_icmp_v4(self.context.clone()).await?;
|
||||
self.socket.lock().unwrap().replace(socket.clone());
|
||||
Ok(socket)
|
||||
}
|
||||
|
||||
fn stop_icmp(&self) {
|
||||
if let Some(socket) = self.socket.lock().unwrap().take() {
|
||||
socket.close();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type CoreTcpProxy<H> = TcpProxyService<CoreProxyRuntime<H>, H, TcpSocketProxyConnector<H>>;
|
||||
type CoreUdpProxyRuntime<H> = UdpSocketProxyRuntime<H, CoreProxyRuntime<H>>;
|
||||
type CoreUdpProxy<H> = UdpProxyService<CoreUdpProxyRuntime<H>>;
|
||||
type CoreIcmpProxy<H> = IcmpProxyService<CoreIcmpProxyRuntime<H>>;
|
||||
|
||||
/// Deep portable proxy Module owned by one `CoreInstance`.
|
||||
///
|
||||
/// The Host supplies socket creation and an optional raw-ICMP capability. Core
|
||||
/// owns policy, CIDR authority, packet pipelines, NAT entries, and lifecycle.
|
||||
pub(crate) struct CoreProxyModule<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
operation: Mutex<()>,
|
||||
runtime: Arc<CoreProxyRuntime<H>>,
|
||||
tcp: Arc<CoreTcpProxy<H>>,
|
||||
icmp: Option<Arc<CoreIcmpProxy<H>>>,
|
||||
udp_runtime: Arc<CoreUdpProxyRuntime<H>>,
|
||||
udp: Arc<CoreUdpProxy<H>>,
|
||||
tcp_started: AtomicBool,
|
||||
icmp_started: AtomicBool,
|
||||
udp_started: AtomicBool,
|
||||
}
|
||||
|
||||
impl<H> CoreProxyModule<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(crate) fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
config: CoreRuntimeConfigStore,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
tcp_socket_context: SocketContext,
|
||||
udp_socket_context: SocketContext,
|
||||
icmp_socket_context: SocketContext,
|
||||
icmp_host: Option<Arc<dyn IcmpProxyHost>>,
|
||||
) -> Arc<Self> {
|
||||
let runtime = CoreProxyRuntime::new(
|
||||
peer_manager.clone(),
|
||||
host.clone(),
|
||||
protected_tcp_ports,
|
||||
running_listeners,
|
||||
config.clone(),
|
||||
"TCP",
|
||||
);
|
||||
let tcp_connector = Arc::new(
|
||||
TcpSocketProxyConnector::new(host.clone())
|
||||
.with_socket_context(tcp_socket_context.clone()),
|
||||
);
|
||||
let tcp = TcpProxyService::new_with_socket_context(
|
||||
peer_manager.clone(),
|
||||
runtime.clone(),
|
||||
host.clone(),
|
||||
tcp_connector,
|
||||
cidr_table.clone(),
|
||||
tcp_socket_context,
|
||||
);
|
||||
let icmp = icmp_host.map(|host| {
|
||||
IcmpProxyService::new(
|
||||
peer_manager.clone(),
|
||||
Arc::new(CoreIcmpProxyRuntime {
|
||||
policy: runtime.clone(),
|
||||
host,
|
||||
socket: std::sync::Mutex::new(None),
|
||||
context: icmp_socket_context.with_ip_version(IpVersion::V4),
|
||||
}),
|
||||
cidr_table.clone(),
|
||||
PROXY_FRAGMENT_TIMEOUT,
|
||||
)
|
||||
});
|
||||
let udp_runtime = Arc::new(UdpSocketProxyRuntime::new(
|
||||
host,
|
||||
runtime.clone(),
|
||||
udp_proxy_bind_options(udp_socket_context),
|
||||
UDP_PROXY_SOCKET_IDLE_TIMEOUT,
|
||||
));
|
||||
let udp = UdpProxyService::new(
|
||||
peer_manager,
|
||||
udp_runtime.clone(),
|
||||
cidr_table.clone(),
|
||||
PROXY_FRAGMENT_TIMEOUT,
|
||||
);
|
||||
|
||||
Arc::new(Self {
|
||||
operation: Mutex::new(()),
|
||||
runtime,
|
||||
tcp,
|
||||
icmp,
|
||||
udp_runtime,
|
||||
udp,
|
||||
tcp_started: AtomicBool::new(false),
|
||||
icmp_started: AtomicBool::new(false),
|
||||
udp_started: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn tcp_entry_snapshots(&self) -> Vec<TcpNatEntrySnapshot> {
|
||||
self.tcp.engine().list_entries()
|
||||
}
|
||||
|
||||
fn stop_started(&self) {
|
||||
if self.udp_started.swap(false, Ordering::AcqRel) {
|
||||
self.udp.stop();
|
||||
self.udp_runtime.close_all();
|
||||
}
|
||||
if self.icmp_started.swap(false, Ordering::AcqRel)
|
||||
&& let Some(icmp) = &self.icmp
|
||||
{
|
||||
icmp.stop();
|
||||
}
|
||||
if self.tcp_started.swap(false, Ordering::AcqRel) {
|
||||
self.tcp.stop();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn start(&self) -> Result<(), ProxyRuntimeError> {
|
||||
let _operation = self.operation.lock().await;
|
||||
if self.tcp_started.load(Ordering::Acquire) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
self.runtime.latch_smoltcp();
|
||||
self.tcp_started.store(true, Ordering::Release);
|
||||
if let Err(error) = self.tcp.start(true).await {
|
||||
self.stop_started();
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
if let Some(icmp) = &self.icmp {
|
||||
self.icmp_started.store(true, Ordering::Release);
|
||||
if let Err(error) = icmp.start().await {
|
||||
self.icmp_started.store(false, Ordering::Release);
|
||||
if self
|
||||
.runtime
|
||||
.config
|
||||
.snapshot()
|
||||
.services
|
||||
.proxy
|
||||
.icmp_failure_is_fatal
|
||||
{
|
||||
self.stop_started();
|
||||
return Err(error);
|
||||
}
|
||||
tracing::warn!(?error, "optional ICMP proxy runtime failed to start");
|
||||
}
|
||||
}
|
||||
|
||||
self.udp_started.store(true, Ordering::Release);
|
||||
self.udp.start().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
let _operation = self.operation.lock().await;
|
||||
self.stop_started();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
|
||||
use crate::{
|
||||
config::gateway::ProxyRuntimeConfig,
|
||||
config::peers::{PeerRuntimeConfig, PeerRuntimeSnapshot},
|
||||
config::runtime::{CoreInstanceRuntimeConfig, CoreRuntimeConfig},
|
||||
config::{CoreConfig, IpPrefix, PeerPolicyConfig, ProxyNetworkConfig, RouteConfig},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
fn test_config() -> CoreInstanceRuntimeConfig {
|
||||
let mut peer = PeerRuntimeSnapshot::new(
|
||||
PeerRuntimeConfig {
|
||||
core: CoreConfig {
|
||||
routes: RouteConfig {
|
||||
ipv4: Some(IpPrefix {
|
||||
address: IpAddr::V4(Ipv4Addr::new(10, 1, 2, 3)),
|
||||
prefix_len: 24,
|
||||
}),
|
||||
proxy_networks: vec![ProxyNetworkConfig {
|
||||
real: IpPrefix {
|
||||
address: IpAddr::V4(Ipv4Addr::new(192, 0, 2, 0)),
|
||||
prefix_len: 24,
|
||||
},
|
||||
mapped: Some(IpPrefix {
|
||||
address: IpAddr::V4(Ipv4Addr::new(198, 51, 100, 0)),
|
||||
prefix_len: 24,
|
||||
}),
|
||||
}],
|
||||
..Default::default()
|
||||
},
|
||||
peer_policy: PeerPolicyConfig {
|
||||
latency_first: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
network_identity: Default::default(),
|
||||
stun_info: Default::default(),
|
||||
feature_flags: Default::default(),
|
||||
secure_mode: None,
|
||||
host_routing: Default::default(),
|
||||
},
|
||||
Default::default(),
|
||||
);
|
||||
peer.flags.latency_first = true;
|
||||
CoreInstanceRuntimeConfig {
|
||||
services: CoreRuntimeConfig {
|
||||
proxy: ProxyRuntimeConfig {
|
||||
enable_exit_node: true,
|
||||
no_tun: true,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
peer: Arc::new(peer),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn runtime_snapshot_uses_submitted_policy_and_latched_smoltcp() {
|
||||
let config = test_config();
|
||||
|
||||
let kernel = runtime_snapshot(&config, false);
|
||||
assert_eq!(kernel.local_inet.unwrap().to_string(), "10.1.2.3/24");
|
||||
assert_eq!(kernel.virtual_ipv4, Some(Ipv4Addr::new(10, 1, 2, 3)));
|
||||
assert!(kernel.enable_exit_node);
|
||||
assert!(kernel.no_tun);
|
||||
assert!(kernel.latency_first);
|
||||
|
||||
let smoltcp = runtime_snapshot(&config, true);
|
||||
assert_eq!(smoltcp.local_inet, Some(smoltcp_proxy_inet()));
|
||||
assert_eq!(smoltcp.virtual_ipv4, kernel.virtual_ipv4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn listener_protocol_classification_matches_native_proxy_guard() {
|
||||
for scheme in ["udp", "wg", "quic"] {
|
||||
assert!(protocol_uses_udp(scheme));
|
||||
}
|
||||
for scheme in ["tcp", "ws", "wss", "faketcp"] {
|
||||
assert!(!protocol_uses_udp(scheme));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn udp_proxy_bind_options_preserve_the_datagram_context() {
|
||||
let context = SocketContext::default()
|
||||
.with_socket_mark(Some(73))
|
||||
.with_netns(Some(crate::socket::NetNamespace::new("udp-proxy")));
|
||||
|
||||
let options = udp_proxy_bind_options(context);
|
||||
|
||||
assert_eq!(options.context.ip_version, IpVersion::V4);
|
||||
assert_eq!(options.context.socket_mark, Some(73));
|
||||
assert_eq!(
|
||||
options.context.netns.as_ref().map(|netns| netns.token()),
|
||||
Some("udp-proxy")
|
||||
);
|
||||
assert_eq!(
|
||||
options.purpose,
|
||||
crate::socket::udp::UdpSocketPurpose::ProxyNat
|
||||
);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,678 @@
|
||||
use std::future::Future;
|
||||
use std::sync::{Arc, Weak, atomic::Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
use atomic_shim::AtomicU64;
|
||||
use parking_lot::Mutex;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use crate::{
|
||||
foundation::time::timeout,
|
||||
packet::ZCPacket,
|
||||
peers::{
|
||||
NicPacketFilter, PeerPacketFilter,
|
||||
peer_manager::{PeerManagerCore, PipelineRegistrationGuard},
|
||||
},
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{TcpBindOptions, TcpListenOptions, VirtualTcpListener, VirtualTcpListenerFactory},
|
||||
},
|
||||
};
|
||||
|
||||
use super::cidr_table::ProxyCidrTable;
|
||||
use super::tcp_proxy_engine::{
|
||||
TcpNatEntry, TcpNatEntryState, TcpProxyEngine, TcpProxyMode, TcpProxyNicContext,
|
||||
TcpProxyPacketAction, TcpProxyPeerContext,
|
||||
};
|
||||
use super::traits::{
|
||||
ProxyRuntimeError, TcpProxyConnectContext, TcpProxyDestinationConnector, TcpProxyRuntime,
|
||||
TcpProxyStream,
|
||||
};
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
use crate::gateway::smoltcp::{SmolTcpStack, output_dst_ip};
|
||||
|
||||
fn spawn_tcp_proxy_task(
|
||||
lifecycle: &AtomicU64,
|
||||
expected_generation: u64,
|
||||
tasks: &Mutex<JoinSet<()>>,
|
||||
task: impl Future<Output = ()> + Send + 'static,
|
||||
) -> bool {
|
||||
let mut tasks = tasks.lock();
|
||||
if lifecycle.load(Ordering::Acquire) != expected_generation {
|
||||
return false;
|
||||
}
|
||||
tasks.spawn(task);
|
||||
true
|
||||
}
|
||||
|
||||
pub struct TcpProxyService<
|
||||
R: TcpProxyRuntime + 'static,
|
||||
F: VirtualTcpListenerFactory,
|
||||
C: TcpProxyDestinationConnector,
|
||||
> {
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
listener_factory: Arc<F>,
|
||||
socket_context: SocketContext,
|
||||
connector: Arc<C>,
|
||||
engine: Arc<TcpProxyEngine>,
|
||||
mode: TcpProxyMode,
|
||||
peer_pipeline_guard: Mutex<Option<PipelineRegistrationGuard>>,
|
||||
nic_pipeline_guard: Mutex<Option<PipelineRegistrationGuard>>,
|
||||
kernel_listener: Mutex<Option<Arc<F::Listener>>>,
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
smoltcp_stack: Mutex<Option<Arc<SmolTcpStack>>>,
|
||||
tasks: Mutex<JoinSet<()>>,
|
||||
lifecycle: AtomicU64,
|
||||
}
|
||||
|
||||
impl<R: TcpProxyRuntime + 'static, F: VirtualTcpListenerFactory, C: TcpProxyDestinationConnector>
|
||||
TcpProxyService<R, F, C>
|
||||
{
|
||||
pub fn new_with_socket_context(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
listener_factory: Arc<F>,
|
||||
connector: Arc<C>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
socket_context: SocketContext,
|
||||
) -> Arc<Self> {
|
||||
let mode = connector.proxy_mode();
|
||||
Arc::new(Self {
|
||||
peer_manager,
|
||||
runtime,
|
||||
listener_factory,
|
||||
socket_context,
|
||||
connector,
|
||||
engine: Arc::new(TcpProxyEngine::new(cidr_table)),
|
||||
mode,
|
||||
peer_pipeline_guard: Mutex::new(None),
|
||||
nic_pipeline_guard: Mutex::new(None),
|
||||
kernel_listener: Mutex::new(None),
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
smoltcp_stack: Mutex::new(None),
|
||||
tasks: Mutex::new(JoinSet::new()),
|
||||
lifecycle: AtomicU64::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn engine(&self) -> Arc<TcpProxyEngine> {
|
||||
self.engine.clone()
|
||||
}
|
||||
|
||||
pub fn is_started(&self) -> bool {
|
||||
self.lifecycle.load(Ordering::Acquire) & 1 != 0
|
||||
}
|
||||
|
||||
pub async fn start(self: &Arc<Self>, register_pipeline: bool) -> Result<(), ProxyRuntimeError> {
|
||||
let generation = loop {
|
||||
let stopped = self.lifecycle.load(Ordering::Acquire);
|
||||
if stopped & 1 != 0 {
|
||||
return Ok(());
|
||||
}
|
||||
let active = stopped.wrapping_add(1);
|
||||
if self
|
||||
.lifecycle
|
||||
.compare_exchange(stopped, active, Ordering::AcqRel, Ordering::Acquire)
|
||||
.is_ok()
|
||||
{
|
||||
break active;
|
||||
}
|
||||
};
|
||||
|
||||
self.engine.clear();
|
||||
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let start_result = if snapshot.smoltcp_enabled {
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
{
|
||||
self.start_smoltcp(generation).await
|
||||
}
|
||||
|
||||
#[cfg(not(feature = "proxy-smoltcp-stack"))]
|
||||
{
|
||||
Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"smoltcp proxy stack feature is disabled"
|
||||
)))
|
||||
}
|
||||
} else {
|
||||
self.start_kernel_listener(generation).await
|
||||
};
|
||||
|
||||
if let Err(err) = start_result {
|
||||
let _ = self.lifecycle.compare_exchange(
|
||||
generation,
|
||||
generation.wrapping_add(1),
|
||||
Ordering::AcqRel,
|
||||
Ordering::Acquire,
|
||||
);
|
||||
return Err(err);
|
||||
}
|
||||
|
||||
if register_pipeline {
|
||||
self.register_pipeline().await;
|
||||
}
|
||||
self.spawn_syn_cleanup(generation);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
self.stop_resources();
|
||||
self.tasks.lock().abort_all();
|
||||
self.engine.clear();
|
||||
}
|
||||
|
||||
pub(crate) async fn stop_and_wait(&self) {
|
||||
self.stop_resources();
|
||||
let mut tasks = std::mem::take(&mut *self.tasks.lock());
|
||||
tasks.shutdown().await;
|
||||
self.engine.clear();
|
||||
}
|
||||
|
||||
fn stop_resources(&self) {
|
||||
loop {
|
||||
let generation = self.lifecycle.load(Ordering::Acquire);
|
||||
if generation & 1 == 0
|
||||
|| self
|
||||
.lifecycle
|
||||
.compare_exchange(
|
||||
generation,
|
||||
generation.wrapping_add(1),
|
||||
Ordering::AcqRel,
|
||||
Ordering::Acquire,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
if let Some(guard) = self.peer_pipeline_guard.lock().take() {
|
||||
guard.close();
|
||||
}
|
||||
if let Some(guard) = self.nic_pipeline_guard.lock().take() {
|
||||
guard.close();
|
||||
}
|
||||
if let Some(listener) = self.kernel_listener.lock().take() {
|
||||
drop(listener);
|
||||
}
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
if let Some(stack) = self.smoltcp_stack.lock().take() {
|
||||
drop(stack);
|
||||
}
|
||||
}
|
||||
|
||||
async fn register_pipeline(self: &Arc<Self>) {
|
||||
self.register_peer_pipeline().await;
|
||||
self.register_nic_pipeline().await;
|
||||
}
|
||||
|
||||
pub async fn register_peer_pipeline(self: &Arc<Self>) {
|
||||
if self.peer_pipeline_guard.lock().is_some() {
|
||||
return;
|
||||
}
|
||||
let peer_guard = self
|
||||
.peer_manager
|
||||
.add_managed_packet_process_pipeline(Box::new(TcpProxyServiceFilter {
|
||||
service: Arc::downgrade(self),
|
||||
}))
|
||||
.await;
|
||||
self.peer_pipeline_guard.lock().replace(peer_guard);
|
||||
}
|
||||
|
||||
pub async fn register_nic_pipeline(self: &Arc<Self>) {
|
||||
if self.nic_pipeline_guard.lock().is_some() {
|
||||
return;
|
||||
}
|
||||
let nic_guard = self
|
||||
.peer_manager
|
||||
.add_managed_nic_packet_process_pipeline(Box::new(TcpProxyServiceFilter {
|
||||
service: Arc::downgrade(self),
|
||||
}))
|
||||
.await;
|
||||
self.nic_pipeline_guard.lock().replace(nic_guard);
|
||||
}
|
||||
|
||||
fn spawn_syn_cleanup(self: &Arc<Self>, generation: u64) {
|
||||
let service = Arc::downgrade(self);
|
||||
let _ = spawn_tcp_proxy_task(&self.lifecycle, generation, &self.tasks, async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(10)).await;
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service.engine.cleanup_expired_syn(Duration::from_secs(30));
|
||||
service.drain_completed_tasks();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn drain_completed_tasks(&self) {
|
||||
let mut tasks = self.tasks.lock();
|
||||
while let Some(result) = tasks.try_join_next() {
|
||||
if let Err(err) = result {
|
||||
tracing::warn!(?err, "tcp proxy task finished with error");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn start_kernel_listener(
|
||||
self: &Arc<Self>,
|
||||
generation: u64,
|
||||
) -> Result<(), ProxyRuntimeError> {
|
||||
let listen_addr = std::net::SocketAddr::new(std::net::Ipv4Addr::UNSPECIFIED.into(), 0);
|
||||
let listener = self
|
||||
.listener_factory
|
||||
.bind_tcp(
|
||||
TcpListenOptions::proxy_nat(listen_addr).with_bind(
|
||||
TcpBindOptions::default()
|
||||
.with_need_protect(false)
|
||||
.with_context(
|
||||
self.socket_context
|
||||
.clone()
|
||||
.with_ip_version(crate::socket::IpVersion::V4),
|
||||
)
|
||||
.with_local_addr(Some(listen_addr)),
|
||||
),
|
||||
)
|
||||
.await?;
|
||||
self.engine.set_local_port(listener.local_addr()?.port());
|
||||
self.kernel_listener.lock().replace(listener.clone());
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
let _ = spawn_tcp_proxy_task(&self.lifecycle, generation, &self.tasks, async move {
|
||||
loop {
|
||||
let accept_ret = listener.accept().await;
|
||||
let Ok((src_stream, socket_addr)) = accept_ret else {
|
||||
tracing::error!(
|
||||
error = ?accept_ret.err(),
|
||||
"nat tcp listener accept failed"
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service
|
||||
.handle_accept(generation, socket_addr, Box::new(src_stream))
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
async fn start_smoltcp(self: &Arc<Self>, generation: u64) -> Result<(), ProxyRuntimeError> {
|
||||
let local_ip = self
|
||||
.runtime
|
||||
.proxy_runtime_snapshot()
|
||||
.local_inet
|
||||
.map(|inet| inet.address())
|
||||
.unwrap_or(std::net::Ipv4Addr::new(192, 88, 99, 254));
|
||||
let stack = SmolTcpStack::new(local_ip, self.mode.smoltcp_listener_port()).await?;
|
||||
self.engine.set_local_port(stack.local_port());
|
||||
|
||||
let mut output_rx = stack.take_output_rx().await?;
|
||||
let peer_manager = self.peer_manager.clone();
|
||||
let _ = spawn_tcp_proxy_task(&self.lifecycle, generation, &self.tasks, async move {
|
||||
while let Some(data) = output_rx.recv().await {
|
||||
tracing::trace!(?data, "receive from smoltcp stack and send to peer manager");
|
||||
let dst = match output_dst_ip(&data) {
|
||||
Ok(dst) => dst,
|
||||
Err(err) => {
|
||||
tracing::error!(?err, ?data, "invalid smoltcp output packet");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let packet = ZCPacket::new_with_payload(&data);
|
||||
if let Err(err) = peer_manager.send_msg_by_ip(packet, dst, false).await {
|
||||
tracing::error!(?err, "send to peer failed in smoltcp sender");
|
||||
}
|
||||
}
|
||||
tracing::error!("smoltcp stack stream exited");
|
||||
});
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
let accept_stack = stack.clone();
|
||||
let _ = spawn_tcp_proxy_task(&self.lifecycle, generation, &self.tasks, async move {
|
||||
loop {
|
||||
let accept_ret = accept_stack.accept().await;
|
||||
let Ok((socket_addr, src_stream)) = accept_ret else {
|
||||
tracing::error!(error = ?accept_ret.err(), "smoltcp accept failed");
|
||||
continue;
|
||||
};
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service
|
||||
.handle_accept(generation, socket_addr, src_stream)
|
||||
.await;
|
||||
}
|
||||
});
|
||||
|
||||
self.smoltcp_stack.lock().replace(stack);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle_accept(
|
||||
self: Arc<Self>,
|
||||
generation: u64,
|
||||
socket_addr: std::net::SocketAddr,
|
||||
src_stream: Box<dyn TcpProxyStream>,
|
||||
) {
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let Some(entry) = self
|
||||
.engine
|
||||
.accept_connection(socket_addr, snapshot.local_inet)
|
||||
else {
|
||||
tracing::error!(
|
||||
?socket_addr,
|
||||
"tcp connection from unknown source, ignore it"
|
||||
);
|
||||
return;
|
||||
};
|
||||
tracing::info!(
|
||||
?socket_addr,
|
||||
"tcp connection accepted for proxy, nat dst: {:?}",
|
||||
entry.real_dst()
|
||||
);
|
||||
|
||||
if !spawn_tcp_proxy_task(
|
||||
&self.lifecycle,
|
||||
generation,
|
||||
&self.tasks,
|
||||
Self::connect_to_nat_dst(self.clone(), src_stream, entry.clone()),
|
||||
) {
|
||||
entry.set_state(TcpNatEntryState::Closed);
|
||||
self.engine.remove_entry(entry.id());
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect_to_nat_dst(
|
||||
service: Arc<Self>,
|
||||
mut src_stream: Box<dyn TcpProxyStream>,
|
||||
entry: Arc<TcpNatEntry>,
|
||||
) {
|
||||
if service.runtime.should_deny_tcp_proxy(entry.real_dst()) {
|
||||
tracing::error!(
|
||||
?entry,
|
||||
"nat dst port {} is in running listeners, ignore it",
|
||||
entry.real_dst().port()
|
||||
);
|
||||
entry.set_state(TcpNatEntryState::Closed);
|
||||
service.engine.remove_entry(entry.id());
|
||||
return;
|
||||
}
|
||||
|
||||
let ctx = TcpProxyConnectContext {
|
||||
src: entry.src(),
|
||||
real_dst: entry.real_dst(),
|
||||
mapped_dst: entry.mapped_dst(),
|
||||
};
|
||||
let socket_dst = if service.runtime.is_ip_local_virtual_ip(&ctx.real_dst.ip()) {
|
||||
std::net::SocketAddr::new(std::net::Ipv4Addr::LOCALHOST.into(), ctx.real_dst.port())
|
||||
} else {
|
||||
ctx.real_dst
|
||||
};
|
||||
service.runtime.record_tcp_proxy_connect(ctx, socket_dst);
|
||||
|
||||
let Ok(dst_stream) = service.connector.connect(ctx.src, socket_dst).await else {
|
||||
tracing::error!("connect to dst failed: {:?}", entry);
|
||||
entry.set_state(TcpNatEntryState::Closed);
|
||||
service.engine.remove_entry(entry.id());
|
||||
return;
|
||||
};
|
||||
let mut dst_stream: Box<dyn TcpProxyStream> = Box::new(dst_stream);
|
||||
|
||||
tracing::info!(?entry, "tcp connection to dst established");
|
||||
if entry.state() == TcpNatEntryState::ConnectingDst {
|
||||
entry.set_state(TcpNatEntryState::Connected);
|
||||
}
|
||||
|
||||
let ret = copy_bidirectional(src_stream.as_mut(), dst_stream.as_mut()).await;
|
||||
tracing::info!(nat_entry = ?entry, ret = ?ret, "nat tcp connection closed");
|
||||
|
||||
entry.set_state(TcpNatEntryState::ClosingSrc);
|
||||
let ret = timeout(Duration::from_secs(10), src_stream.shutdown()).await;
|
||||
tracing::info!(nat_entry = ?entry, ret = ?ret, "src tcp stream shutdown");
|
||||
|
||||
entry.set_state(TcpNatEntryState::ClosingDst);
|
||||
let ret = timeout(Duration::from_secs(10), dst_stream.shutdown()).await;
|
||||
tracing::info!(nat_entry = ?entry, ret = ?ret, "dst tcp stream shutdown");
|
||||
|
||||
drop(src_stream);
|
||||
drop(dst_stream);
|
||||
|
||||
entry.set_state(TcpNatEntryState::Closed);
|
||||
crate::foundation::time::sleep(Duration::from_secs(10)).await;
|
||||
service.engine.remove_entry(entry.id());
|
||||
}
|
||||
|
||||
async fn handle_peer_packet(self: Arc<Self>, mut packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let action = self.engine.try_handle_peer_packet(
|
||||
self.mode,
|
||||
&mut packet,
|
||||
TcpProxyPeerContext {
|
||||
local_inet: snapshot.local_inet,
|
||||
virtual_ipv4: snapshot.virtual_ipv4,
|
||||
local_port: self.engine.local_port(),
|
||||
enable_exit_node: snapshot.enable_exit_node,
|
||||
no_tun: snapshot.no_tun,
|
||||
smoltcp_enabled: snapshot.smoltcp_enabled,
|
||||
},
|
||||
);
|
||||
match action {
|
||||
TcpProxyPacketAction::Handled { new_syn: _ } => {}
|
||||
TcpProxyPacketAction::Drop => return None,
|
||||
TcpProxyPacketAction::Pass => return Some(packet),
|
||||
}
|
||||
|
||||
if snapshot.smoltcp_enabled {
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
self.handle_smoltcp_packet(packet).await;
|
||||
|
||||
#[cfg(not(feature = "proxy-smoltcp-stack"))]
|
||||
tracing::error!("smoltcp packet received but proxy-smoltcp-stack is disabled");
|
||||
} else if let Err(err) = self
|
||||
.peer_manager
|
||||
.get_nic_channel()
|
||||
.send(crate::host::packet::HostPacket::from_core_packet(packet))
|
||||
.await
|
||||
{
|
||||
tracing::error!(?err, "send to nic failed");
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-smoltcp-stack")]
|
||||
async fn handle_smoltcp_packet(&self, packet: ZCPacket) {
|
||||
let stack = self.smoltcp_stack.lock().clone();
|
||||
let Some(stack) = stack else {
|
||||
tracing::error!("smoltcp stack is not started");
|
||||
return;
|
||||
};
|
||||
if let Err(err) = stack.send_ingress(packet).await {
|
||||
tracing::error!(?err, "send to smoltcp stack failed");
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_nic_packet(&self, packet: &mut ZCPacket) -> bool {
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
self.engine.try_process_packet_from_nic(
|
||||
packet,
|
||||
TcpProxyNicContext {
|
||||
local_inet: snapshot.local_inet,
|
||||
local_port: self.engine.local_port(),
|
||||
my_peer_id: self.peer_manager.my_peer_id(),
|
||||
smoltcp_enabled: snapshot.smoltcp_enabled,
|
||||
},
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
async fn copy_bidirectional(
|
||||
src: &mut dyn TcpProxyStream,
|
||||
dst: &mut dyn TcpProxyStream,
|
||||
) -> Result<(), ProxyRuntimeError> {
|
||||
// Forward EOF to the opposite writer while continuing to relay its reply.
|
||||
// Returning on the first EOF would discard responses to half-closed requests.
|
||||
tokio::io::copy_bidirectional(src, dst).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl<R: TcpProxyRuntime + 'static, F: VirtualTcpListenerFactory, C: TcpProxyDestinationConnector>
|
||||
Drop for TcpProxyService<R, F, C>
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
struct TcpProxyServiceFilter<
|
||||
R: TcpProxyRuntime + 'static,
|
||||
F: VirtualTcpListenerFactory,
|
||||
C: TcpProxyDestinationConnector,
|
||||
> {
|
||||
service: Weak<TcpProxyService<R, F, C>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<R: TcpProxyRuntime + 'static, F: VirtualTcpListenerFactory, C: TcpProxyDestinationConnector>
|
||||
PeerPacketFilter for TcpProxyServiceFilter<R, F, C>
|
||||
{
|
||||
async fn try_process_packet_from_peer(&self, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let Some(service) = self.service.upgrade() else {
|
||||
return Some(packet);
|
||||
};
|
||||
service.handle_peer_packet(packet).await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<R: TcpProxyRuntime + 'static, F: VirtualTcpListenerFactory, C: TcpProxyDestinationConnector>
|
||||
NicPacketFilter for TcpProxyServiceFilter<R, F, C>
|
||||
{
|
||||
async fn try_process_packet_from_nic(&self, packet: &mut ZCPacket) -> bool {
|
||||
let Some(service) = self.service.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
service.handle_nic_packet(packet).await
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use tokio::io::AsyncReadExt;
|
||||
|
||||
async fn response_after_half_close(source_closes_first: bool, request_size: usize) {
|
||||
// Small buffers force the relay to make progress in both directions;
|
||||
// the response is deliberately larger than either relay buffer.
|
||||
let (mut client, mut src) = tokio::io::duplex(64);
|
||||
let (mut dst, mut server) = tokio::io::duplex(64);
|
||||
let request = vec![0x35; request_size];
|
||||
let response = vec![0xa7; 64 * 1024];
|
||||
let relay = async {
|
||||
if source_closes_first {
|
||||
copy_bidirectional(&mut src, &mut dst).await
|
||||
} else {
|
||||
copy_bidirectional(&mut dst, &mut src).await
|
||||
}
|
||||
.unwrap();
|
||||
};
|
||||
let requester = async {
|
||||
client.write_all(&request).await.unwrap();
|
||||
client.shutdown().await.unwrap();
|
||||
let mut received = Vec::new();
|
||||
client.read_to_end(&mut received).await.unwrap();
|
||||
assert_eq!(received, response);
|
||||
};
|
||||
let responder = async {
|
||||
let mut received = Vec::new();
|
||||
server.read_to_end(&mut received).await.unwrap();
|
||||
assert_eq!(received, request);
|
||||
server.write_all(&response).await.unwrap();
|
||||
server.shutdown().await.unwrap();
|
||||
};
|
||||
timeout(Duration::from_secs(5), async {
|
||||
tokio::join!(relay, requester, responder);
|
||||
})
|
||||
.await
|
||||
.expect("half-closed relay did not finish");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn source_half_close_preserves_response() {
|
||||
for request_size in [0, 32 * 1024] {
|
||||
response_after_half_close(true, request_size).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destination_half_close_preserves_response() {
|
||||
for request_size in [0, 32 * 1024] {
|
||||
response_after_half_close(false, request_size).await;
|
||||
}
|
||||
}
|
||||
|
||||
struct DropSignal(Arc<AtomicBool>);
|
||||
|
||||
impl Drop for DropSignal {
|
||||
fn drop(&mut self) {
|
||||
self.0.store(true, Ordering::Release);
|
||||
}
|
||||
}
|
||||
|
||||
fn pending_task(dropped: Arc<AtomicBool>) -> impl Future<Output = ()> + Send + 'static {
|
||||
let signal = DropSignal(dropped);
|
||||
async move {
|
||||
let _signal = signal;
|
||||
std::future::pending::<()>().await;
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stop_fence_linearizes_task_registration() {
|
||||
let lifecycle = AtomicU64::new(1);
|
||||
let tasks = Mutex::new(JoinSet::new());
|
||||
let accepted_dropped = Arc::new(AtomicBool::new(false));
|
||||
|
||||
assert!(spawn_tcp_proxy_task(
|
||||
&lifecycle,
|
||||
1,
|
||||
&tasks,
|
||||
pending_task(accepted_dropped.clone()),
|
||||
));
|
||||
lifecycle.store(2, Ordering::Release);
|
||||
let mut stopping = std::mem::take(&mut *tasks.lock());
|
||||
stopping.shutdown().await;
|
||||
assert!(accepted_dropped.load(Ordering::Acquire));
|
||||
|
||||
lifecycle.store(3, Ordering::Release);
|
||||
|
||||
let rejected_dropped = Arc::new(AtomicBool::new(false));
|
||||
assert!(!spawn_tcp_proxy_task(
|
||||
&lifecycle,
|
||||
1,
|
||||
&tasks,
|
||||
pending_task(rejected_dropped.clone()),
|
||||
));
|
||||
assert!(rejected_dropped.load(Ordering::Acquire));
|
||||
|
||||
let current_dropped = Arc::new(AtomicBool::new(false));
|
||||
assert!(spawn_tcp_proxy_task(
|
||||
&lifecycle,
|
||||
3,
|
||||
&tasks,
|
||||
pending_task(current_dropped.clone()),
|
||||
));
|
||||
let mut current = std::mem::take(&mut *tasks.lock());
|
||||
current.shutdown().await;
|
||||
assert!(current_dropped.load(Ordering::Acquire));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
use std::{net::SocketAddr, sync::Arc, time::Duration};
|
||||
|
||||
use anyhow::Context;
|
||||
|
||||
use crate::{
|
||||
foundation::time::timeout,
|
||||
socket::{
|
||||
SocketContext,
|
||||
tcp::{TcpConnectOptions, VirtualTcpSocketFactory},
|
||||
},
|
||||
};
|
||||
|
||||
use super::{tcp_proxy_engine::TcpProxyMode, traits::TcpProxyDestinationConnector};
|
||||
|
||||
pub struct TcpSocketProxyConnector<F: VirtualTcpSocketFactory> {
|
||||
socket_factory: Arc<F>,
|
||||
socket_context: SocketContext,
|
||||
}
|
||||
|
||||
impl<F: VirtualTcpSocketFactory> TcpSocketProxyConnector<F> {
|
||||
pub fn new(socket_factory: Arc<F>) -> Self {
|
||||
Self {
|
||||
socket_factory,
|
||||
socket_context: SocketContext::default(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn with_socket_context(mut self, socket_context: SocketContext) -> Self {
|
||||
self.socket_context = socket_context;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<F: VirtualTcpSocketFactory> TcpProxyDestinationConnector for TcpSocketProxyConnector<F> {
|
||||
type DstStream = F::Socket;
|
||||
|
||||
async fn connect(&self, _src: SocketAddr, dst: SocketAddr) -> anyhow::Result<Self::DstStream> {
|
||||
timeout(
|
||||
Duration::from_secs(10),
|
||||
self.socket_factory.connect_tcp(
|
||||
TcpConnectOptions::proxy_nat(dst).with_bind(
|
||||
crate::socket::tcp::TcpBindOptions::default().with_context(
|
||||
self.socket_context
|
||||
.clone()
|
||||
.with_ip_version(if dst.is_ipv4() {
|
||||
crate::socket::IpVersion::V4
|
||||
} else {
|
||||
crate::socket::IpVersion::V6
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.await?
|
||||
.with_context(|| format!("connect to nat dst failed: {dst:?}"))
|
||||
}
|
||||
|
||||
fn proxy_mode(&self) -> TcpProxyMode {
|
||||
TcpProxyMode::Tcp
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use std::sync::{Arc, Weak};
|
||||
|
||||
use bytes::Bytes;
|
||||
use cidr::Ipv4Inet;
|
||||
use tokio::io::{AsyncRead, AsyncWrite};
|
||||
|
||||
use super::tcp_proxy_engine::TcpProxyMode;
|
||||
use super::udp_proxy_engine::UdpNatEntryId;
|
||||
|
||||
pub use super::icmp_host::{IcmpProxyHost, IcmpProxySocket, ProxyRuntimeError};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default)]
|
||||
pub(crate) struct ProxyRuntimeSnapshot {
|
||||
pub local_inet: Option<Ipv4Inet>,
|
||||
pub virtual_ipv4: Option<Ipv4Addr>,
|
||||
pub no_tun: bool,
|
||||
pub enable_exit_node: bool,
|
||||
pub smoltcp_enabled: bool,
|
||||
pub latency_first: bool,
|
||||
}
|
||||
|
||||
pub(crate) trait ProxyRuntimeInfo: Send + Sync {
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot;
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool;
|
||||
}
|
||||
|
||||
pub(crate) trait WrappedTcpDestinationRuntime: Send + Sync {
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool;
|
||||
fn no_tun(&self) -> bool;
|
||||
fn should_deny_tcp_proxy(&self, dst: SocketAddr) -> bool;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait IcmpProxyRuntime: ProxyRuntimeInfo {
|
||||
type Socket: IcmpProxySocket + ?Sized;
|
||||
|
||||
async fn start_icmp(&self) -> Result<Arc<Self::Socket>, ProxyRuntimeError>;
|
||||
|
||||
fn stop_icmp(&self);
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait UdpProxyResponseSink: Send + Sync {
|
||||
async fn handle_socket_response(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
src: SocketAddr,
|
||||
payload: Bytes,
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) trait UdpProxyPolicy: ProxyRuntimeInfo {
|
||||
fn should_deny_udp_proxy(&self, dst: SocketAddr) -> bool;
|
||||
fn udp_response_ipv4_mtu(&self) -> usize;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait UdpProxyRuntime: ProxyRuntimeInfo {
|
||||
fn should_deny_udp_proxy(&self, dst: SocketAddr) -> bool;
|
||||
fn udp_response_ipv4_mtu(&self) -> usize;
|
||||
|
||||
async fn send_udp_to_socket(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
dst: SocketAddr,
|
||||
payload: Bytes,
|
||||
response_sink: Weak<dyn UdpProxyResponseSink>,
|
||||
) -> Result<(), ProxyRuntimeError>;
|
||||
|
||||
fn close_udp_socket(&self, entry_id: UdpNatEntryId);
|
||||
}
|
||||
|
||||
pub trait TcpProxyStream: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
|
||||
impl<T> TcpProxyStream for T where T: AsyncRead + AsyncWrite + Unpin + Send {}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(crate) struct TcpProxyConnectContext {
|
||||
pub src: SocketAddr,
|
||||
pub real_dst: SocketAddr,
|
||||
pub mapped_dst: SocketAddr,
|
||||
}
|
||||
|
||||
pub(crate) trait TcpProxyRuntime: ProxyRuntimeInfo {
|
||||
fn should_deny_tcp_proxy(&self, dst: SocketAddr) -> bool;
|
||||
|
||||
fn record_tcp_proxy_connect(&self, ctx: TcpProxyConnectContext, socket_dst: SocketAddr);
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait TcpProxyDestinationConnector: Send + Sync + 'static {
|
||||
type DstStream: TcpProxyStream + 'static;
|
||||
|
||||
async fn connect(&self, src: SocketAddr, dst: SocketAddr) -> anyhow::Result<Self::DstStream>;
|
||||
|
||||
fn proxy_mode(&self) -> TcpProxyMode;
|
||||
}
|
||||
@@ -0,0 +1,507 @@
|
||||
use std::{
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU16, Ordering},
|
||||
},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use dashmap::{DashMap, mapref::entry::Entry};
|
||||
use smoltcp::wire::{IpAddress, IpProtocol, Ipv4Packet, UdpPacket};
|
||||
|
||||
use crate::{
|
||||
config::PeerId,
|
||||
packet::{PacketType, ZCPacket},
|
||||
};
|
||||
|
||||
use super::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
ip_reassembler::{ComposeIpv4PacketArgs, IpReassembler, compose_ipv4_packet},
|
||||
traits::UdpProxyRuntime,
|
||||
};
|
||||
|
||||
#[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)]
|
||||
pub struct UdpNatKey {
|
||||
pub src_socket: SocketAddr,
|
||||
pub dst_socket: SocketAddr,
|
||||
}
|
||||
|
||||
impl UdpNatKey {
|
||||
pub fn new(src_socket: SocketAddr, dst_socket: SocketAddr) -> Self {
|
||||
Self {
|
||||
src_socket,
|
||||
dst_socket,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Hash, Eq, PartialEq)]
|
||||
pub struct UdpNatEntryId(uuid::Uuid);
|
||||
|
||||
impl UdpNatEntryId {
|
||||
pub fn new() -> Self {
|
||||
Self(uuid::Uuid::new_v4())
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for UdpNatEntryId {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UdpNatEntry {
|
||||
id: UdpNatEntryId,
|
||||
src_peer_id: PeerId,
|
||||
my_peer_id: PeerId,
|
||||
src_socket: SocketAddr,
|
||||
real_dst_ip: Ipv4Addr,
|
||||
mapped_dst_ip: Ipv4Addr,
|
||||
virtual_ipv4: Ipv4Addr,
|
||||
last_active_time: parking_lot::Mutex<Instant>,
|
||||
stopped: AtomicBool,
|
||||
denied: bool,
|
||||
}
|
||||
|
||||
impl UdpNatEntry {
|
||||
fn new(
|
||||
src_peer_id: PeerId,
|
||||
my_peer_id: PeerId,
|
||||
src_socket: SocketAddr,
|
||||
real_dst_ip: Ipv4Addr,
|
||||
mapped_dst_ip: Ipv4Addr,
|
||||
virtual_ipv4: Ipv4Addr,
|
||||
denied: bool,
|
||||
) -> Self {
|
||||
Self {
|
||||
id: UdpNatEntryId::new(),
|
||||
src_peer_id,
|
||||
my_peer_id,
|
||||
src_socket,
|
||||
real_dst_ip,
|
||||
mapped_dst_ip,
|
||||
virtual_ipv4,
|
||||
last_active_time: parking_lot::Mutex::new(Instant::now()),
|
||||
stopped: AtomicBool::new(false),
|
||||
denied,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn id(&self) -> UdpNatEntryId {
|
||||
self.id
|
||||
}
|
||||
|
||||
pub fn is_denied(&self) -> bool {
|
||||
self.denied
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
self.stopped.store(true, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
pub fn is_stopped(&self) -> bool {
|
||||
self.stopped.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
fn mark_active(&self) {
|
||||
*self.last_active_time.lock() = Instant::now();
|
||||
}
|
||||
|
||||
fn is_active(&self, ttl: Duration) -> bool {
|
||||
self.last_active_time.lock().elapsed() < ttl && !self.is_stopped()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct UdpProxyPeerContext {
|
||||
pub virtual_ipv4: Option<Ipv4Addr>,
|
||||
pub enable_exit_node: bool,
|
||||
pub no_tun: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum UdpProxyAction {
|
||||
ForwardToSocket {
|
||||
entry_id: UdpNatEntryId,
|
||||
dst: SocketAddr,
|
||||
payload: Bytes,
|
||||
},
|
||||
Drop,
|
||||
Pass,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct UdpProxyEngine {
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
nat_table: DashMap<UdpNatKey, Arc<UdpNatEntry>>,
|
||||
nat_ids: DashMap<UdpNatEntryId, UdpNatKey>,
|
||||
ip_reassembler: IpReassembler,
|
||||
entry_ttl: Duration,
|
||||
next_ip_id: AtomicU16,
|
||||
}
|
||||
|
||||
impl UdpProxyEngine {
|
||||
pub fn new(cidr_table: Arc<ProxyCidrTable>, fragment_timeout: Duration) -> Self {
|
||||
Self {
|
||||
cidr_table,
|
||||
nat_table: DashMap::new(),
|
||||
nat_ids: DashMap::new(),
|
||||
ip_reassembler: IpReassembler::new(fragment_timeout),
|
||||
entry_ttl: Duration::from_secs(180),
|
||||
next_ip_id: AtomicU16::new(1),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn entry_ids(&self) -> Vec<UdpNatEntryId> {
|
||||
self.nat_ids.iter().map(|entry| *entry.key()).collect()
|
||||
}
|
||||
|
||||
pub fn remove_expired_entries(&self) -> Vec<UdpNatEntryId> {
|
||||
let mut removed = Vec::new();
|
||||
self.nat_table.retain(|_, entry| {
|
||||
if entry.is_active(self.entry_ttl) {
|
||||
true
|
||||
} else {
|
||||
tracing::info!(?entry, "udp nat table entry removed");
|
||||
entry.stop();
|
||||
self.nat_ids.remove(&entry.id());
|
||||
removed.push(entry.id());
|
||||
false
|
||||
}
|
||||
});
|
||||
self.nat_table.shrink_to_fit();
|
||||
self.nat_ids.shrink_to_fit();
|
||||
removed
|
||||
}
|
||||
|
||||
pub fn remove_entry(&self, entry_id: UdpNatEntryId) {
|
||||
if let Some((_, key)) = self.nat_ids.remove(&entry_id)
|
||||
&& let Some((_, entry)) = self.nat_table.remove(&key)
|
||||
{
|
||||
entry.stop();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn remove_expired_fragments(&self) {
|
||||
self.ip_reassembler.remove_expired_packets();
|
||||
}
|
||||
|
||||
pub fn handle_peer_packet(
|
||||
&self,
|
||||
packet: &ZCPacket,
|
||||
ctx: UdpProxyPeerContext,
|
||||
runtime: &impl UdpProxyRuntime,
|
||||
) -> UdpProxyAction {
|
||||
if self.cidr_table.is_empty() && !ctx.enable_exit_node && !ctx.no_tun {
|
||||
return UdpProxyAction::Pass;
|
||||
}
|
||||
|
||||
let Some(virtual_ipv4) = ctx.virtual_ipv4 else {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
let Some(hdr) = packet.peer_manager_header() else {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
let is_exit_node = hdr.is_exit_node();
|
||||
if hdr.packet_type != PacketType::Data as u8 || hdr.is_no_proxy() {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
|
||||
let Ok(ipv4) = Ipv4Packet::new_checked(packet.payload()) else {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
if ipv4.version() != 4 || ipv4.next_header() != IpProtocol::Udp {
|
||||
return UdpProxyAction::Pass;
|
||||
}
|
||||
|
||||
let origin_dst_ip = ipv4.dst_addr();
|
||||
let mut real_dst_ip = origin_dst_ip;
|
||||
let no_tun_local_virtual_ip =
|
||||
ctx.no_tun && Some(origin_dst_ip) == ctx.virtual_ipv4.as_ref().copied();
|
||||
if let Some(mapped_real_ip) = self.cidr_table.lookup_v4(origin_dst_ip) {
|
||||
real_dst_ip = mapped_real_ip;
|
||||
} else if !is_exit_node && !no_tun_local_virtual_ip {
|
||||
return UdpProxyAction::Pass;
|
||||
}
|
||||
|
||||
let reassembled_buf;
|
||||
let udp_packet = if IpReassembler::is_packet_fragmented(&ipv4) {
|
||||
let Some(buf) = self.ip_reassembler.add_fragment(&ipv4) else {
|
||||
return UdpProxyAction::Drop;
|
||||
};
|
||||
reassembled_buf = buf;
|
||||
let Ok(udp_packet) = UdpPacket::new_checked(reassembled_buf.as_slice()) else {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
udp_packet
|
||||
} else {
|
||||
let Ok(udp_packet) = UdpPacket::new_checked(ipv4.payload()) else {
|
||||
return UdpProxyAction::Pass;
|
||||
};
|
||||
udp_packet
|
||||
};
|
||||
|
||||
let dst_socket = if runtime.is_ip_local_virtual_ip(&IpAddr::V4(real_dst_ip)) {
|
||||
SocketAddr::new(Ipv4Addr::LOCALHOST.into(), udp_packet.dst_port())
|
||||
} else {
|
||||
SocketAddr::new(real_dst_ip.into(), udp_packet.dst_port())
|
||||
};
|
||||
|
||||
tracing::trace!(
|
||||
?packet,
|
||||
?ipv4,
|
||||
?udp_packet,
|
||||
"udp nat packet request received"
|
||||
);
|
||||
|
||||
let nat_key = UdpNatKey::new(
|
||||
SocketAddr::new(ipv4.src_addr().into(), udp_packet.src_port()),
|
||||
SocketAddr::new(origin_dst_ip.into(), udp_packet.dst_port()),
|
||||
);
|
||||
let deny_dst = SocketAddr::new(real_dst_ip.into(), udp_packet.dst_port());
|
||||
let nat_entry = match self.nat_table.entry(nat_key) {
|
||||
Entry::Occupied(entry) => entry.get().clone(),
|
||||
Entry::Vacant(entry) => {
|
||||
let denied = runtime.should_deny_udp_proxy(deny_dst);
|
||||
let nat_entry = Arc::new(UdpNatEntry::new(
|
||||
hdr.from_peer_id.get(),
|
||||
hdr.to_peer_id.get(),
|
||||
nat_key.src_socket,
|
||||
real_dst_ip,
|
||||
origin_dst_ip,
|
||||
virtual_ipv4,
|
||||
denied,
|
||||
));
|
||||
self.nat_ids.insert(nat_entry.id(), nat_key);
|
||||
tracing::info!(?packet, ?ipv4, ?udp_packet, "udp nat table entry created");
|
||||
entry.insert(nat_entry).clone()
|
||||
}
|
||||
};
|
||||
|
||||
if nat_entry.is_denied() {
|
||||
tracing::debug!(
|
||||
dst_port = udp_packet.dst_port(),
|
||||
"dst socket is in running listeners, ignore it"
|
||||
);
|
||||
return UdpProxyAction::Drop;
|
||||
}
|
||||
|
||||
nat_entry.mark_active();
|
||||
UdpProxyAction::ForwardToSocket {
|
||||
entry_id: nat_entry.id(),
|
||||
dst: dst_socket,
|
||||
payload: Bytes::copy_from_slice(udp_packet.payload()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn handle_socket_response(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
src_socket: SocketAddr,
|
||||
payload: &[u8],
|
||||
ipv4_mtu: usize,
|
||||
) -> anyhow::Result<Vec<ZCPacket>> {
|
||||
let Some(key) = self.nat_ids.get(&entry_id).map(|entry| *entry.value()) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let Some(entry) = self.nat_table.get(&key).map(|entry| entry.clone()) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
entry.mark_active();
|
||||
|
||||
let SocketAddr::V4(mut src_v4) = src_socket else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let SocketAddr::V4(nat_src_v4) = entry.src_socket else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
|
||||
let has_mapped_dst = entry.real_dst_ip != entry.mapped_dst_ip;
|
||||
let mut reply_src_ip = *src_v4.ip();
|
||||
if has_mapped_dst && reply_src_ip == entry.real_dst_ip {
|
||||
reply_src_ip = entry.mapped_dst_ip;
|
||||
} else if reply_src_ip.is_loopback() {
|
||||
reply_src_ip = entry.virtual_ipv4;
|
||||
}
|
||||
if has_mapped_dst && reply_src_ip == entry.real_dst_ip {
|
||||
reply_src_ip = entry.mapped_dst_ip;
|
||||
}
|
||||
src_v4.set_ip(reply_src_ip);
|
||||
|
||||
let payload_mtu = ipv4_mtu
|
||||
.saturating_sub(smoltcp::wire::IPV4_HEADER_LEN)
|
||||
.max(8);
|
||||
let payload_mtu = payload_mtu - (payload_mtu % 8);
|
||||
let ip_id = self.next_ip_id.fetch_add(1, Ordering::Relaxed);
|
||||
compose_udp_ipv4_response(&entry, &src_v4, &nat_src_v4, payload, payload_mtu, ip_id)
|
||||
}
|
||||
}
|
||||
|
||||
fn compose_udp_ipv4_response(
|
||||
entry: &UdpNatEntry,
|
||||
src_v4: &SocketAddrV4,
|
||||
nat_src_v4: &SocketAddrV4,
|
||||
payload: &[u8],
|
||||
payload_mtu: usize,
|
||||
ip_id: u16,
|
||||
) -> anyhow::Result<Vec<ZCPacket>> {
|
||||
assert_eq!(0, payload_mtu % 8);
|
||||
|
||||
let mut buf =
|
||||
vec![0; smoltcp::wire::IPV4_HEADER_LEN + smoltcp::wire::UDP_HEADER_LEN + payload.len()];
|
||||
let udp_start = smoltcp::wire::IPV4_HEADER_LEN;
|
||||
let udp_len = smoltcp::wire::UDP_HEADER_LEN + payload.len();
|
||||
{
|
||||
let mut udp_packet = UdpPacket::new_unchecked(&mut buf[udp_start..udp_start + udp_len]);
|
||||
udp_packet.set_src_port(src_v4.port());
|
||||
udp_packet.set_dst_port(nat_src_v4.port());
|
||||
udp_packet.set_len(udp_len as u16);
|
||||
udp_packet.payload_mut().copy_from_slice(payload);
|
||||
udp_packet.fill_checksum(
|
||||
&IpAddress::Ipv4(*src_v4.ip()),
|
||||
&IpAddress::Ipv4(*nat_src_v4.ip()),
|
||||
);
|
||||
}
|
||||
|
||||
let mut packets = Vec::new();
|
||||
compose_ipv4_packet(
|
||||
ComposeIpv4PacketArgs {
|
||||
buf: &mut buf,
|
||||
src_v4: src_v4.ip(),
|
||||
dst_v4: nat_src_v4.ip(),
|
||||
next_protocol: IpProtocol::Udp,
|
||||
payload_len: udp_len,
|
||||
payload_mtu,
|
||||
ip_id,
|
||||
},
|
||||
|buf| {
|
||||
let mut packet = ZCPacket::new_with_payload(buf);
|
||||
packet.fill_peer_manager_hdr(
|
||||
entry.my_peer_id,
|
||||
entry.src_peer_id,
|
||||
PacketType::Data as u8,
|
||||
);
|
||||
packet
|
||||
.mut_peer_manager_header()
|
||||
.expect("peer manager header")
|
||||
.set_no_proxy(true);
|
||||
packets.push(packet);
|
||||
Ok(())
|
||||
},
|
||||
)?;
|
||||
|
||||
Ok(packets)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gateway::proxy::{
|
||||
cidr_table::{ProxyCidrRule, ProxyCidrSnapshot},
|
||||
traits::{ProxyRuntimeError, ProxyRuntimeInfo, ProxyRuntimeSnapshot, UdpProxyResponseSink},
|
||||
};
|
||||
|
||||
struct TestRuntime;
|
||||
|
||||
impl ProxyRuntimeInfo for TestRuntime {
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
ProxyRuntimeSnapshot::default()
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
matches!(ip, IpAddr::V4(ip) if *ip == Ipv4Addr::new(10, 144, 144, 204))
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UdpProxyRuntime for TestRuntime {
|
||||
fn should_deny_udp_proxy(&self, _dst_socket: SocketAddr) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn udp_response_ipv4_mtu(&self) -> usize {
|
||||
1280
|
||||
}
|
||||
|
||||
async fn send_udp_to_socket(
|
||||
&self,
|
||||
_entry_id: UdpNatEntryId,
|
||||
_dst: SocketAddr,
|
||||
_payload: bytes::Bytes,
|
||||
_response_sink: std::sync::Weak<dyn UdpProxyResponseSink>,
|
||||
) -> Result<(), ProxyRuntimeError> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close_udp_socket(&self, _entry_id: UdpNatEntryId) {}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socket_response_uses_mapped_source_for_mapped_destination() {
|
||||
let table = Arc::new(ProxyCidrTable::from_snapshot(ProxyCidrSnapshot {
|
||||
rules: vec![ProxyCidrRule {
|
||||
cidr: "10.144.144.204/32".parse().unwrap(),
|
||||
mapped_cidr: Some("10.10.10.3/32".parse().unwrap()),
|
||||
}],
|
||||
}));
|
||||
let engine = UdpProxyEngine::new(table, Duration::from_secs(10));
|
||||
|
||||
let mut request =
|
||||
vec![0; smoltcp::wire::IPV4_HEADER_LEN + smoltcp::wire::UDP_HEADER_LEN + 7];
|
||||
{
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut request);
|
||||
ipv4.set_version(4);
|
||||
ipv4.set_header_len(smoltcp::wire::IPV4_HEADER_LEN as u8);
|
||||
ipv4.set_total_len(
|
||||
(smoltcp::wire::IPV4_HEADER_LEN + smoltcp::wire::UDP_HEADER_LEN + 7) as u16,
|
||||
);
|
||||
ipv4.set_hop_limit(64);
|
||||
ipv4.set_next_header(IpProtocol::Udp);
|
||||
ipv4.set_src_addr("10.144.144.206".parse().unwrap());
|
||||
ipv4.set_dst_addr("10.10.10.3".parse().unwrap());
|
||||
ipv4.fill_checksum();
|
||||
}
|
||||
{
|
||||
let mut udp = UdpPacket::new_unchecked(&mut request[smoltcp::wire::IPV4_HEADER_LEN..]);
|
||||
udp.set_src_port(53864);
|
||||
udp.set_dst_port(12345);
|
||||
udp.set_len((smoltcp::wire::UDP_HEADER_LEN + 7) as u16);
|
||||
udp.payload_mut().copy_from_slice(b"request");
|
||||
udp.fill_checksum(
|
||||
&IpAddress::Ipv4("10.144.144.206".parse().unwrap()),
|
||||
&IpAddress::Ipv4("10.10.10.3".parse().unwrap()),
|
||||
);
|
||||
}
|
||||
|
||||
let mut zc = ZCPacket::new_with_payload(&request);
|
||||
zc.fill_peer_manager_hdr(1, 2, PacketType::Data as u8);
|
||||
|
||||
let action = engine.handle_peer_packet(
|
||||
&zc,
|
||||
UdpProxyPeerContext {
|
||||
virtual_ipv4: Some("10.144.144.204".parse().unwrap()),
|
||||
enable_exit_node: false,
|
||||
no_tun: false,
|
||||
},
|
||||
&TestRuntime,
|
||||
);
|
||||
let UdpProxyAction::ForwardToSocket { entry_id, .. } = action else {
|
||||
panic!("expected forward action");
|
||||
};
|
||||
|
||||
let packets = engine
|
||||
.handle_socket_response(entry_id, "127.0.0.1:12345".parse().unwrap(), b"reply", 1280)
|
||||
.unwrap();
|
||||
assert_eq!(packets.len(), 1);
|
||||
let ipv4 = Ipv4Packet::new_checked(packets[0].payload()).unwrap();
|
||||
assert_eq!(ipv4.src_addr(), Ipv4Addr::new(10, 10, 10, 3));
|
||||
assert_eq!(ipv4.dst_addr(), Ipv4Addr::new(10, 144, 144, 206));
|
||||
let udp = UdpPacket::new_checked(ipv4.payload()).unwrap();
|
||||
assert_eq!(udp.src_port(), 12345);
|
||||
assert_eq!(udp.dst_port(), 53864);
|
||||
assert_eq!(udp.payload(), b"reply");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
use std::sync::{
|
||||
Arc, Weak,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
};
|
||||
use std::time::Duration;
|
||||
|
||||
use bytes::Bytes;
|
||||
use tokio::sync::mpsc::{self, Receiver, Sender};
|
||||
use tokio::task::JoinSet;
|
||||
|
||||
use crate::packet::ZCPacket;
|
||||
use crate::peers::PeerPacketFilter;
|
||||
use crate::peers::peer_manager::{PeerManagerCore, PipelineRegistrationGuard};
|
||||
|
||||
use super::cidr_table::ProxyCidrTable;
|
||||
use super::traits::{UdpProxyResponseSink, UdpProxyRuntime};
|
||||
use super::udp_proxy_engine::{UdpNatEntryId, UdpProxyAction, UdpProxyEngine, UdpProxyPeerContext};
|
||||
|
||||
pub struct UdpProxyService<R: UdpProxyRuntime + 'static> {
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
engine: Arc<UdpProxyEngine>,
|
||||
response_tx: Sender<ZCPacket>,
|
||||
response_rx: std::sync::Mutex<Option<Receiver<ZCPacket>>>,
|
||||
pipeline_guard: std::sync::Mutex<Option<PipelineRegistrationGuard>>,
|
||||
tasks: std::sync::Mutex<JoinSet<()>>,
|
||||
started: AtomicBool,
|
||||
}
|
||||
|
||||
impl<R: UdpProxyRuntime + 'static> UdpProxyService<R> {
|
||||
pub fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<R>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
fragment_timeout: Duration,
|
||||
) -> Arc<Self> {
|
||||
let (response_tx, response_rx) = mpsc::channel(1024);
|
||||
Arc::new(Self {
|
||||
peer_manager,
|
||||
runtime,
|
||||
engine: Arc::new(UdpProxyEngine::new(cidr_table, fragment_timeout)),
|
||||
response_tx,
|
||||
response_rx: std::sync::Mutex::new(Some(response_rx)),
|
||||
pipeline_guard: std::sync::Mutex::new(None),
|
||||
tasks: std::sync::Mutex::new(JoinSet::new()),
|
||||
started: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
pub async fn start(self: &Arc<Self>) {
|
||||
if self.started.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
|
||||
let guard = self
|
||||
.peer_manager
|
||||
.add_managed_packet_process_pipeline(Box::new(UdpProxyServiceFilter {
|
||||
service: Arc::downgrade(self),
|
||||
}))
|
||||
.await;
|
||||
self.pipeline_guard.lock().unwrap().replace(guard);
|
||||
|
||||
if let Some(mut response_rx) = self.response_rx.lock().unwrap().take() {
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
while let Some(mut packet) = response_rx.recv().await {
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
let latency_first = service.runtime.proxy_runtime_snapshot().latency_first;
|
||||
let Some(hdr) = packet.mut_peer_manager_header() else {
|
||||
continue;
|
||||
};
|
||||
hdr.set_latency_first(latency_first);
|
||||
let dst_peer_id = hdr.to_peer_id.into();
|
||||
tracing::trace!(?packet, ?dst_peer_id, "udp nat packet response send");
|
||||
if let Err(err) = service
|
||||
.peer_manager
|
||||
.send_msg_for_proxy(packet, dst_peer_id)
|
||||
.await
|
||||
{
|
||||
tracing::error!(?err, "send udp proxy response to peer failed");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(15)).await;
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
for entry_id in service.engine.remove_expired_entries() {
|
||||
service.runtime.close_udp_socket(entry_id);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let service = Arc::downgrade(self);
|
||||
self.tasks.lock().unwrap().spawn(async move {
|
||||
loop {
|
||||
crate::foundation::time::sleep(Duration::from_secs(1)).await;
|
||||
let Some(service) = service.upgrade() else {
|
||||
break;
|
||||
};
|
||||
service.engine.remove_expired_fragments();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub fn stop(&self) {
|
||||
if !self.started.swap(false, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
if let Some(guard) = self.pipeline_guard.lock().unwrap().take() {
|
||||
guard.close();
|
||||
}
|
||||
self.tasks.lock().unwrap().abort_all();
|
||||
for entry_id in self.engine.entry_ids() {
|
||||
self.engine.remove_entry(entry_id);
|
||||
self.runtime.close_udp_socket(entry_id);
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_peer_packet(self: Arc<Self>, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let action = self.engine.handle_peer_packet(
|
||||
&packet,
|
||||
UdpProxyPeerContext {
|
||||
virtual_ipv4: snapshot.virtual_ipv4,
|
||||
enable_exit_node: snapshot.enable_exit_node,
|
||||
no_tun: snapshot.no_tun,
|
||||
},
|
||||
self.runtime.as_ref(),
|
||||
);
|
||||
|
||||
let UdpProxyAction::ForwardToSocket {
|
||||
entry_id,
|
||||
dst,
|
||||
payload,
|
||||
} = action
|
||||
else {
|
||||
return matches!(action, UdpProxyAction::Pass).then_some(packet);
|
||||
};
|
||||
|
||||
let sink: Arc<dyn UdpProxyResponseSink> = self.clone();
|
||||
if let Err(err) = self
|
||||
.runtime
|
||||
.send_udp_to_socket(entry_id, dst, payload, Arc::downgrade(&sink))
|
||||
.await
|
||||
{
|
||||
tracing::error!(?err, ?entry_id, "udp proxy runtime send failed");
|
||||
self.engine.remove_entry(entry_id);
|
||||
self.runtime.close_udp_socket(entry_id);
|
||||
}
|
||||
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
impl<R: UdpProxyRuntime + 'static> Drop for UdpProxyService<R> {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<R: UdpProxyRuntime + 'static> UdpProxyResponseSink for UdpProxyService<R> {
|
||||
async fn handle_socket_response(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
src: std::net::SocketAddr,
|
||||
payload: Bytes,
|
||||
) {
|
||||
let packets = match self.engine.handle_socket_response(
|
||||
entry_id,
|
||||
src,
|
||||
payload.as_ref(),
|
||||
self.runtime.udp_response_ipv4_mtu(),
|
||||
) {
|
||||
Ok(packets) => packets,
|
||||
Err(err) => {
|
||||
tracing::error!(?err, ?entry_id, "compose udp response packet failed");
|
||||
self.engine.remove_entry(entry_id);
|
||||
self.runtime.close_udp_socket(entry_id);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
for mut packet in packets {
|
||||
let Some(hdr) = packet.mut_peer_manager_header() else {
|
||||
continue;
|
||||
};
|
||||
let dst_peer_id: crate::config::PeerId = hdr.to_peer_id.into();
|
||||
tracing::trace!(?packet, ?dst_peer_id, "udp nat packet response queued");
|
||||
if let Err(err) = self.response_tx.try_send(packet) {
|
||||
tracing::error!(?err, ?dst_peer_id, "queue udp proxy response failed");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpProxyServiceFilter<R: UdpProxyRuntime + 'static> {
|
||||
service: Weak<UdpProxyService<R>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<R: UdpProxyRuntime + 'static> PeerPacketFilter for UdpProxyServiceFilter<R> {
|
||||
async fn try_process_packet_from_peer(&self, packet: ZCPacket) -> Option<ZCPacket> {
|
||||
let Some(service) = self.service.upgrade() else {
|
||||
return Some(packet);
|
||||
};
|
||||
service.handle_peer_packet(packet).await
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,647 @@
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::{
|
||||
Arc, Weak,
|
||||
atomic::{AtomicBool, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
use bytes::Bytes;
|
||||
use dashmap::{DashMap, mapref::entry::Entry};
|
||||
use tokio::sync::Notify;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
|
||||
use crate::{
|
||||
foundation::time,
|
||||
socket::udp::{UdpBindOptions, VirtualUdpSocket, VirtualUdpSocketFactory},
|
||||
};
|
||||
|
||||
use super::{
|
||||
traits::{
|
||||
ProxyRuntimeError, ProxyRuntimeInfo, ProxyRuntimeSnapshot, UdpProxyPolicy,
|
||||
UdpProxyResponseSink, UdpProxyRuntime,
|
||||
},
|
||||
udp_proxy_engine::UdpNatEntryId,
|
||||
};
|
||||
|
||||
const UDP_PROXY_RECEIVE_BUFFER_SIZE: usize = 64 * 1024;
|
||||
|
||||
struct UdpSocketNatEntry<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
socket: Arc<S>,
|
||||
receive_task: std::sync::Mutex<Option<AbortOnDropHandle<()>>>,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
struct UdpSocketEntryState<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
entry: Option<Arc<UdpSocketNatEntry<S>>>,
|
||||
error: Option<String>,
|
||||
}
|
||||
|
||||
struct UdpSocketEntrySlot<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
state: std::sync::Mutex<UdpSocketEntryState<S>>,
|
||||
changed: Notify,
|
||||
closed: AtomicBool,
|
||||
}
|
||||
|
||||
impl<S> UdpSocketEntrySlot<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
fn new() -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
state: std::sync::Mutex::new(UdpSocketEntryState {
|
||||
entry: None,
|
||||
error: None,
|
||||
}),
|
||||
changed: Notify::new(),
|
||||
closed: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
async fn wait_for_entry(&self) -> Result<Arc<UdpSocketNatEntry<S>>, ProxyRuntimeError> {
|
||||
loop {
|
||||
let changed = self.changed.notified();
|
||||
{
|
||||
let state = self.state.lock().unwrap();
|
||||
if let Some(entry) = &state.entry {
|
||||
return Ok(entry.clone());
|
||||
}
|
||||
if let Some(error) = &state.error {
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(error.clone())));
|
||||
}
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"UDP proxy socket entry was closed while being created"
|
||||
)));
|
||||
}
|
||||
}
|
||||
changed.await;
|
||||
}
|
||||
}
|
||||
|
||||
fn fail(&self, error: &ProxyRuntimeError) {
|
||||
self.state.lock().unwrap().error = Some(error.to_string());
|
||||
self.changed.notify_waiters();
|
||||
}
|
||||
|
||||
fn cancel_creation(&self) {
|
||||
self.closed.store(true, Ordering::Release);
|
||||
self.state.lock().unwrap().error =
|
||||
Some("UDP proxy socket creation was cancelled".to_owned());
|
||||
self.changed.notify_waiters();
|
||||
}
|
||||
|
||||
fn close(&self) {
|
||||
self.closed.store(true, Ordering::Release);
|
||||
if let Some(entry) = self.state.lock().unwrap().entry.take() {
|
||||
entry.stop();
|
||||
}
|
||||
self.changed.notify_waiters();
|
||||
}
|
||||
}
|
||||
|
||||
fn remove_entry_slot<S>(
|
||||
entries: &DashMap<UdpNatEntryId, Arc<UdpSocketEntrySlot<S>>>,
|
||||
entry_id: UdpNatEntryId,
|
||||
slot: &Arc<UdpSocketEntrySlot<S>>,
|
||||
) where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
if let Entry::Occupied(entry) = entries.entry(entry_id)
|
||||
&& Arc::ptr_eq(entry.get(), slot)
|
||||
{
|
||||
entry.remove();
|
||||
}
|
||||
}
|
||||
|
||||
struct UdpSocketCreationGuard<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
entries: Arc<DashMap<UdpNatEntryId, Arc<UdpSocketEntrySlot<S>>>>,
|
||||
entry_id: UdpNatEntryId,
|
||||
slot: Arc<UdpSocketEntrySlot<S>>,
|
||||
armed: bool,
|
||||
}
|
||||
|
||||
impl<S> UdpSocketCreationGuard<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
fn new(
|
||||
entries: Arc<DashMap<UdpNatEntryId, Arc<UdpSocketEntrySlot<S>>>>,
|
||||
entry_id: UdpNatEntryId,
|
||||
slot: Arc<UdpSocketEntrySlot<S>>,
|
||||
) -> Self {
|
||||
Self {
|
||||
entries,
|
||||
entry_id,
|
||||
slot,
|
||||
armed: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn disarm(&mut self) {
|
||||
self.armed = false;
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> Drop for UdpSocketCreationGuard<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
if !self.armed {
|
||||
return;
|
||||
}
|
||||
self.slot.cancel_creation();
|
||||
remove_entry_slot(&self.entries, self.entry_id, &self.slot);
|
||||
}
|
||||
}
|
||||
|
||||
impl<S> UdpSocketNatEntry<S>
|
||||
where
|
||||
S: VirtualUdpSocket,
|
||||
{
|
||||
fn new(socket: Arc<S>) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
socket,
|
||||
receive_task: std::sync::Mutex::new(None),
|
||||
closed: AtomicBool::new(false),
|
||||
})
|
||||
}
|
||||
|
||||
fn start_receive_task(
|
||||
self: &Arc<Self>,
|
||||
entry_id: UdpNatEntryId,
|
||||
response_sink: Weak<dyn UdpProxyResponseSink>,
|
||||
receive_timeout: Duration,
|
||||
) {
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
return;
|
||||
}
|
||||
|
||||
let socket = self.socket.clone();
|
||||
let task = AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
loop {
|
||||
let mut buffer = vec![0; UDP_PROXY_RECEIVE_BUFFER_SIZE];
|
||||
let (length, source) =
|
||||
match time::timeout(receive_timeout, socket.recv_from(&mut buffer)).await {
|
||||
Ok(Ok(received)) => received,
|
||||
Ok(Err(error)) => {
|
||||
tracing::error!(?error, ?entry_id, "UDP proxy receive failed");
|
||||
break;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::error!(?error, ?entry_id, "UDP proxy receive timed out");
|
||||
break;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(response_sink) = response_sink.upgrade() else {
|
||||
break;
|
||||
};
|
||||
response_sink
|
||||
.handle_socket_response(
|
||||
entry_id,
|
||||
source,
|
||||
Bytes::copy_from_slice(&buffer[..length]),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
}));
|
||||
|
||||
let mut receive_task = self.receive_task.lock().unwrap();
|
||||
if self.closed.load(Ordering::Acquire) {
|
||||
drop(task);
|
||||
} else {
|
||||
receive_task.replace(task);
|
||||
}
|
||||
}
|
||||
|
||||
fn stop(&self) {
|
||||
self.closed.store(true, Ordering::Release);
|
||||
self.receive_task.lock().unwrap().take();
|
||||
}
|
||||
}
|
||||
|
||||
pub struct UdpSocketProxyRuntime<F, P>
|
||||
where
|
||||
F: VirtualUdpSocketFactory,
|
||||
P: UdpProxyPolicy,
|
||||
{
|
||||
factory: Arc<F>,
|
||||
policy: Arc<P>,
|
||||
bind_options: UdpBindOptions,
|
||||
receive_timeout: Duration,
|
||||
entries: Arc<DashMap<UdpNatEntryId, Arc<UdpSocketEntrySlot<F::Socket>>>>,
|
||||
closing: AtomicBool,
|
||||
}
|
||||
|
||||
impl<F, P> UdpSocketProxyRuntime<F, P>
|
||||
where
|
||||
F: VirtualUdpSocketFactory,
|
||||
P: UdpProxyPolicy,
|
||||
{
|
||||
pub fn new(
|
||||
factory: Arc<F>,
|
||||
policy: Arc<P>,
|
||||
bind_options: UdpBindOptions,
|
||||
receive_timeout: Duration,
|
||||
) -> Self {
|
||||
Self {
|
||||
factory,
|
||||
policy,
|
||||
bind_options,
|
||||
receive_timeout,
|
||||
entries: Arc::new(DashMap::new()),
|
||||
closing: AtomicBool::new(false),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ensure_socket_entry(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
response_sink: Weak<dyn UdpProxyResponseSink>,
|
||||
) -> Result<Arc<UdpSocketNatEntry<F::Socket>>, ProxyRuntimeError> {
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"UDP proxy runtime is closing"
|
||||
)));
|
||||
}
|
||||
|
||||
let (slot, create) = match self.entries.entry(entry_id) {
|
||||
Entry::Occupied(entry) => (entry.get().clone(), false),
|
||||
Entry::Vacant(entry) => {
|
||||
let slot = UdpSocketEntrySlot::new();
|
||||
entry.insert(slot.clone());
|
||||
(slot, true)
|
||||
}
|
||||
};
|
||||
if self.closing.load(Ordering::Acquire) {
|
||||
slot.close();
|
||||
self.remove_slot(entry_id, &slot);
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"UDP proxy runtime is closing"
|
||||
)));
|
||||
}
|
||||
if !create {
|
||||
return slot.wait_for_entry().await;
|
||||
}
|
||||
|
||||
let mut creation =
|
||||
UdpSocketCreationGuard::new(self.entries.clone(), entry_id, slot.clone());
|
||||
|
||||
let socket = match self.factory.bind_udp(self.bind_options.clone()).await {
|
||||
Ok(socket) => socket,
|
||||
Err(error) => {
|
||||
let error = ProxyRuntimeError::Other(error);
|
||||
slot.fail(&error);
|
||||
self.remove_slot(entry_id, &slot);
|
||||
creation.disarm();
|
||||
return Err(error);
|
||||
}
|
||||
};
|
||||
let candidate = UdpSocketNatEntry::new(socket);
|
||||
{
|
||||
let mut state = slot.state.lock().unwrap();
|
||||
if slot.closed.load(Ordering::Acquire) || self.closing.load(Ordering::Acquire) {
|
||||
candidate.stop();
|
||||
drop(state);
|
||||
slot.changed.notify_waiters();
|
||||
self.remove_slot(entry_id, &slot);
|
||||
creation.disarm();
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"UDP proxy socket entry was closed while being created"
|
||||
)));
|
||||
}
|
||||
candidate.start_receive_task(entry_id, response_sink, self.receive_timeout);
|
||||
state.entry = Some(candidate.clone());
|
||||
}
|
||||
slot.changed.notify_waiters();
|
||||
creation.disarm();
|
||||
Ok(candidate)
|
||||
}
|
||||
|
||||
fn remove_slot(&self, entry_id: UdpNatEntryId, slot: &Arc<UdpSocketEntrySlot<F::Socket>>) {
|
||||
remove_entry_slot(&self.entries, entry_id, slot);
|
||||
}
|
||||
|
||||
pub fn close_all(&self) {
|
||||
self.closing.store(true, Ordering::Release);
|
||||
for slot in self.entries.iter() {
|
||||
slot.close();
|
||||
}
|
||||
self.entries.clear();
|
||||
self.entries.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, P> ProxyRuntimeInfo for UdpSocketProxyRuntime<F, P>
|
||||
where
|
||||
F: VirtualUdpSocketFactory,
|
||||
P: UdpProxyPolicy,
|
||||
{
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
self.policy.proxy_runtime_snapshot()
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
self.policy.is_ip_local_virtual_ip(ip)
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<F, P> UdpProxyRuntime for UdpSocketProxyRuntime<F, P>
|
||||
where
|
||||
F: VirtualUdpSocketFactory,
|
||||
P: UdpProxyPolicy,
|
||||
{
|
||||
fn should_deny_udp_proxy(&self, dst: SocketAddr) -> bool {
|
||||
self.policy.should_deny_udp_proxy(dst)
|
||||
}
|
||||
|
||||
fn udp_response_ipv4_mtu(&self) -> usize {
|
||||
self.policy.udp_response_ipv4_mtu()
|
||||
}
|
||||
|
||||
async fn send_udp_to_socket(
|
||||
&self,
|
||||
entry_id: UdpNatEntryId,
|
||||
dst: SocketAddr,
|
||||
payload: Bytes,
|
||||
response_sink: Weak<dyn UdpProxyResponseSink>,
|
||||
) -> Result<(), ProxyRuntimeError> {
|
||||
let entry = self.ensure_socket_entry(entry_id, response_sink).await?;
|
||||
if entry.closed.load(Ordering::Acquire) {
|
||||
return Err(ProxyRuntimeError::Other(anyhow::anyhow!(
|
||||
"UDP proxy socket entry is closed"
|
||||
)));
|
||||
}
|
||||
entry.socket.send_to(&payload, dst).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn close_udp_socket(&self, entry_id: UdpNatEntryId) {
|
||||
if let Some((_, slot)) = self.entries.remove(&entry_id) {
|
||||
slot.close();
|
||||
}
|
||||
self.entries.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
|
||||
impl<F, P> Drop for UdpSocketProxyRuntime<F, P>
|
||||
where
|
||||
F: VirtualUdpSocketFactory,
|
||||
P: UdpProxyPolicy,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
self.close_all();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::{
|
||||
io,
|
||||
net::Ipv4Addr,
|
||||
sync::atomic::{AtomicUsize, Ordering as AtomicOrdering},
|
||||
};
|
||||
|
||||
use super::*;
|
||||
use crate::socket::udp::UdpSocketPurpose;
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingSocket {
|
||||
sent: std::sync::Mutex<Vec<(Vec<u8>, SocketAddr)>>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl VirtualUdpSocket for RecordingSocket {
|
||||
fn local_addr(&self) -> io::Result<SocketAddr> {
|
||||
Ok("127.0.0.1:40000".parse().unwrap())
|
||||
}
|
||||
|
||||
async fn send_to(&self, data: &[u8], addr: SocketAddr) -> io::Result<usize> {
|
||||
self.sent.lock().unwrap().push((data.to_vec(), addr));
|
||||
Ok(data.len())
|
||||
}
|
||||
|
||||
async fn recv_from(&self, _buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
|
||||
std::future::pending().await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct RecordingFactory {
|
||||
options: std::sync::Mutex<Vec<UdpBindOptions>>,
|
||||
socket: Arc<RecordingSocket>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl VirtualUdpSocketFactory for RecordingFactory {
|
||||
type Socket = RecordingSocket;
|
||||
|
||||
async fn bind_udp(&self, options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.options.lock().unwrap().push(options);
|
||||
Ok(self.socket.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct DelayedFactory {
|
||||
socket: Arc<RecordingSocket>,
|
||||
bind_calls: AtomicUsize,
|
||||
bind_started: Notify,
|
||||
release_bind: Notify,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl VirtualUdpSocketFactory for DelayedFactory {
|
||||
type Socket = RecordingSocket;
|
||||
|
||||
async fn bind_udp(&self, _options: UdpBindOptions) -> anyhow::Result<Arc<Self::Socket>> {
|
||||
self.bind_calls.fetch_add(1, AtomicOrdering::AcqRel);
|
||||
self.bind_started.notify_one();
|
||||
self.release_bind.notified().await;
|
||||
Ok(self.socket.clone())
|
||||
}
|
||||
}
|
||||
|
||||
struct TestPolicy;
|
||||
|
||||
impl ProxyRuntimeInfo for TestPolicy {
|
||||
fn proxy_runtime_snapshot(&self) -> ProxyRuntimeSnapshot {
|
||||
ProxyRuntimeSnapshot::default()
|
||||
}
|
||||
|
||||
fn is_ip_local_virtual_ip(&self, _ip: &IpAddr) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
impl UdpProxyPolicy for TestPolicy {
|
||||
fn should_deny_udp_proxy(&self, _dst: SocketAddr) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn udp_response_ipv4_mtu(&self) -> usize {
|
||||
1280
|
||||
}
|
||||
}
|
||||
|
||||
struct NoopResponseSink;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl UdpProxyResponseSink for NoopResponseSink {
|
||||
async fn handle_socket_response(
|
||||
&self,
|
||||
_entry_id: UdpNatEntryId,
|
||||
_src: SocketAddr,
|
||||
_payload: Bytes,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reuses_one_host_socket_per_nat_entry_and_recreates_after_close() {
|
||||
let factory = Arc::new(RecordingFactory::default());
|
||||
let runtime = UdpSocketProxyRuntime::new(
|
||||
factory.clone(),
|
||||
Arc::new(TestPolicy),
|
||||
UdpBindOptions::proxy_nat(),
|
||||
Duration::from_secs(120),
|
||||
);
|
||||
let sink: Arc<dyn UdpProxyResponseSink> = Arc::new(NoopResponseSink);
|
||||
let entry_id = UdpNatEntryId::new();
|
||||
let destination = SocketAddr::from((Ipv4Addr::LOCALHOST, 53));
|
||||
|
||||
runtime
|
||||
.send_udp_to_socket(
|
||||
entry_id,
|
||||
destination,
|
||||
Bytes::from_static(b"first"),
|
||||
Arc::downgrade(&sink),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
runtime
|
||||
.send_udp_to_socket(
|
||||
entry_id,
|
||||
destination,
|
||||
Bytes::from_static(b"second"),
|
||||
Arc::downgrade(&sink),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(factory.options.lock().unwrap().len(), 1);
|
||||
assert_eq!(
|
||||
factory.options.lock().unwrap()[0].purpose,
|
||||
UdpSocketPurpose::ProxyNat
|
||||
);
|
||||
assert_eq!(factory.socket.sent.lock().unwrap().len(), 2);
|
||||
|
||||
runtime.close_udp_socket(entry_id);
|
||||
runtime
|
||||
.send_udp_to_socket(
|
||||
entry_id,
|
||||
destination,
|
||||
Bytes::from_static(b"third"),
|
||||
Arc::downgrade(&sink),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(factory.options.lock().unwrap().len(), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn close_all_cancels_an_inflight_socket_creation() {
|
||||
let factory = Arc::new(DelayedFactory::default());
|
||||
let runtime = Arc::new(UdpSocketProxyRuntime::new(
|
||||
factory.clone(),
|
||||
Arc::new(TestPolicy),
|
||||
UdpBindOptions::proxy_nat(),
|
||||
Duration::from_secs(120),
|
||||
));
|
||||
let sink: Arc<dyn UdpProxyResponseSink> = Arc::new(NoopResponseSink);
|
||||
let entry_id = UdpNatEntryId::new();
|
||||
let destination = SocketAddr::from((Ipv4Addr::LOCALHOST, 53));
|
||||
let send_task = tokio::spawn({
|
||||
let runtime = runtime.clone();
|
||||
let sink = Arc::downgrade(&sink);
|
||||
async move {
|
||||
runtime
|
||||
.send_udp_to_socket(entry_id, destination, Bytes::from_static(b"request"), sink)
|
||||
.await
|
||||
}
|
||||
});
|
||||
|
||||
factory.bind_started.notified().await;
|
||||
runtime.close_all();
|
||||
factory.release_bind.notify_one();
|
||||
|
||||
let error = send_task.await.unwrap().unwrap_err();
|
||||
assert!(error.to_string().contains("closed while being created"));
|
||||
assert_eq!(factory.bind_calls.load(AtomicOrdering::Acquire), 1);
|
||||
assert!(factory.socket.sent.lock().unwrap().is_empty());
|
||||
assert!(runtime.entries.is_empty());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_creator_releases_the_slot_for_retry() {
|
||||
let factory = Arc::new(DelayedFactory::default());
|
||||
let runtime = Arc::new(UdpSocketProxyRuntime::new(
|
||||
factory.clone(),
|
||||
Arc::new(TestPolicy),
|
||||
UdpBindOptions::proxy_nat(),
|
||||
Duration::from_secs(120),
|
||||
));
|
||||
let sink: Arc<dyn UdpProxyResponseSink> = Arc::new(NoopResponseSink);
|
||||
let entry_id = UdpNatEntryId::new();
|
||||
let destination = SocketAddr::from((Ipv4Addr::LOCALHOST, 53));
|
||||
let first_send = tokio::spawn({
|
||||
let runtime = runtime.clone();
|
||||
let sink = Arc::downgrade(&sink);
|
||||
async move {
|
||||
runtime
|
||||
.send_udp_to_socket(entry_id, destination, Bytes::from_static(b"first"), sink)
|
||||
.await
|
||||
}
|
||||
});
|
||||
|
||||
factory.bind_started.notified().await;
|
||||
first_send.abort();
|
||||
assert!(first_send.await.unwrap_err().is_cancelled());
|
||||
|
||||
let retry = tokio::spawn({
|
||||
let runtime = runtime.clone();
|
||||
let sink = Arc::downgrade(&sink);
|
||||
async move {
|
||||
runtime
|
||||
.send_udp_to_socket(entry_id, destination, Bytes::from_static(b"retry"), sink)
|
||||
.await
|
||||
}
|
||||
});
|
||||
factory.bind_started.notified().await;
|
||||
factory.release_bind.notify_one();
|
||||
|
||||
time::timeout(Duration::from_secs(1), retry)
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(factory.bind_calls.load(AtomicOrdering::Acquire), 2);
|
||||
assert_eq!(factory.socket.sent.lock().unwrap().len(), 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,489 @@
|
||||
use std::{
|
||||
future::Future,
|
||||
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
use easytier_proto::acl::{ChainType, Protocol};
|
||||
use smoltcp::wire::{IpProtocol, Ipv4Packet, TcpPacket};
|
||||
|
||||
use crate::{
|
||||
gateway::proxy::{
|
||||
cidr_table::ProxyCidrTable, proxy_acl::ProxyAclHandler,
|
||||
traits::WrappedTcpDestinationRuntime,
|
||||
},
|
||||
packet::{PacketType, ZCPacket},
|
||||
peers::{
|
||||
acl::{filter::AclFilter, processor::PacketInfo},
|
||||
route::Route,
|
||||
},
|
||||
};
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub trait WrappedTcpPeerGroupResolver: Send + Sync {
|
||||
async fn get_peer_groups_by_ip(&self, ip: &IpAddr) -> Arc<Vec<String>>;
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<T> WrappedTcpPeerGroupResolver for T
|
||||
where
|
||||
T: Route + Send + Sync + ?Sized,
|
||||
{
|
||||
async fn get_peer_groups_by_ip(&self, ip: &IpAddr) -> Arc<Vec<String>> {
|
||||
Route::get_peer_groups_by_ip(self, ip).await
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WrappedTcpDestinationRequest {
|
||||
pub src: SocketAddr,
|
||||
pub dst: SocketAddr,
|
||||
pub initial_packet_size: usize,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WrappedTcpDestinationPlan {
|
||||
pub socket_dst: SocketAddr,
|
||||
pub acl_handler: ProxyAclHandler,
|
||||
}
|
||||
|
||||
pub async fn plan_wrapped_tcp_destination<GroupResolver>(
|
||||
request: WrappedTcpDestinationRequest,
|
||||
cidr_table: &ProxyCidrTable,
|
||||
runtime: &dyn WrappedTcpDestinationRuntime,
|
||||
group_resolver: &GroupResolver,
|
||||
acl_filter: Arc<AclFilter>,
|
||||
) -> anyhow::Result<WrappedTcpDestinationPlan>
|
||||
where
|
||||
GroupResolver: WrappedTcpPeerGroupResolver + ?Sized,
|
||||
{
|
||||
let mut mapped_dst = request.dst;
|
||||
if let IpAddr::V4(dst_ip) = mapped_dst.ip()
|
||||
&& let Some(real_ip) = cidr_table.lookup_v4(dst_ip)
|
||||
{
|
||||
mapped_dst.set_ip(real_ip.into());
|
||||
}
|
||||
|
||||
let src_ip = request.src.ip();
|
||||
let dst_ip = mapped_dst.ip();
|
||||
let (src_groups, dst_groups) = tokio::join!(
|
||||
group_resolver.get_peer_groups_by_ip(&src_ip),
|
||||
group_resolver.get_peer_groups_by_ip(&dst_ip),
|
||||
);
|
||||
|
||||
if runtime.should_deny_tcp_proxy(mapped_dst) {
|
||||
anyhow::bail!(
|
||||
"dst socket {:?} is in running listeners, ignore it",
|
||||
mapped_dst
|
||||
);
|
||||
}
|
||||
|
||||
let send_to_self = runtime.is_ip_local_virtual_ip(&dst_ip);
|
||||
let socket_dst = if send_to_self && runtime.no_tun() {
|
||||
SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), mapped_dst.port())
|
||||
} else {
|
||||
mapped_dst
|
||||
};
|
||||
|
||||
let acl_handler = ProxyAclHandler {
|
||||
acl_filter,
|
||||
packet_info: PacketInfo {
|
||||
src_ip,
|
||||
dst_ip,
|
||||
src_port: Some(request.src.port()),
|
||||
dst_port: Some(socket_dst.port()),
|
||||
protocol: Protocol::Tcp,
|
||||
packet_size: request.initial_packet_size,
|
||||
src_groups,
|
||||
dst_groups,
|
||||
},
|
||||
chain_type: if send_to_self {
|
||||
ChainType::Inbound
|
||||
} else {
|
||||
ChainType::Forward
|
||||
},
|
||||
};
|
||||
acl_handler.handle_packet_size(request.initial_packet_size)?;
|
||||
|
||||
Ok(WrappedTcpDestinationPlan {
|
||||
socket_dst,
|
||||
acl_handler,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum WrappedTcpProxyTransport {
|
||||
Kcp,
|
||||
Quic,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WrappedTcpProxyNicContext {
|
||||
pub transport: WrappedTcpProxyTransport,
|
||||
pub my_peer_id: u32,
|
||||
pub local_ipv4: Option<Ipv4Addr>,
|
||||
pub smoltcp_enabled: bool,
|
||||
}
|
||||
|
||||
pub async fn try_process_wrapped_tcp_packet_from_nic<ConnectionLookup, AllowCheck, AllowCheckFut>(
|
||||
zc_packet: &mut ZCPacket,
|
||||
ctx: WrappedTcpProxyNicContext,
|
||||
is_tcp_proxy_flow: ConnectionLookup,
|
||||
check_dst_allowed: AllowCheck,
|
||||
) -> bool
|
||||
where
|
||||
ConnectionLookup: Fn(SocketAddr, SocketAddr) -> bool,
|
||||
AllowCheck: FnOnce(Ipv4Addr) -> AllowCheckFut,
|
||||
AllowCheckFut: Future<Output = bool>,
|
||||
{
|
||||
let Some(hdr) = zc_packet.peer_manager_header() else {
|
||||
return false;
|
||||
};
|
||||
if hdr.packet_type != PacketType::Data as u8 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(ip_packet) = Ipv4Packet::new_checked(zc_packet.payload()) else {
|
||||
return false;
|
||||
};
|
||||
if ip_packet.version() != 4 || ip_packet.next_header() != IpProtocol::Tcp {
|
||||
return false;
|
||||
}
|
||||
|
||||
let Ok(tcp_packet) = TcpPacket::new_checked(ip_packet.payload()) else {
|
||||
return false;
|
||||
};
|
||||
let src_ip = ip_packet.src_addr();
|
||||
let dst_ip = ip_packet.dst_addr();
|
||||
let src_port = tcp_packet.src_port();
|
||||
let dst_port = tcp_packet.dst_port();
|
||||
let is_syn = tcp_packet.syn() && !tcp_packet.ack();
|
||||
|
||||
if is_syn {
|
||||
// Own virtual IP traffic must stay local; it can never reach a peer.
|
||||
if ctx.local_ipv4 == Some(dst_ip) {
|
||||
return false;
|
||||
}
|
||||
if !check_dst_allowed(dst_ip).await {
|
||||
tracing::warn!(
|
||||
?ctx.transport,
|
||||
dst = %dst_ip,
|
||||
"wrapped tcp proxy src dst is not allowed"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} else if !is_tcp_proxy_flow(
|
||||
SocketAddr::V4(SocketAddrV4::new(src_ip, src_port)),
|
||||
SocketAddr::V4(SocketAddrV4::new(dst_ip, dst_port)),
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if let Some(local_ipv4) = ctx.local_ipv4
|
||||
&& src_ip != local_ipv4
|
||||
&& !ctx.smoltcp_enabled
|
||||
{
|
||||
tracing::warn!(
|
||||
?ctx.transport,
|
||||
src = %src_ip,
|
||||
dst = %dst_ip,
|
||||
"wrapped tcp proxy net-to-net input is not allowed without smoltcp"
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
let hdr = zc_packet
|
||||
.mut_peer_manager_header()
|
||||
.expect("peer manager header");
|
||||
hdr.to_peer_id = ctx.my_peer_id.into();
|
||||
match ctx.transport {
|
||||
WrappedTcpProxyTransport::Kcp => {
|
||||
hdr.mark_kcp_src_modified();
|
||||
}
|
||||
WrappedTcpProxyTransport::Quic => {
|
||||
hdr.mark_quic_src_modified();
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::gateway::proxy::cidr_table::{ProxyCidrRule, ProxyCidrSnapshot};
|
||||
use smoltcp::wire::{IpAddress, IpProtocol, Ipv4Packet, TcpPacket};
|
||||
|
||||
struct TestDestinationRuntime {
|
||||
local_ip: IpAddr,
|
||||
no_tun: bool,
|
||||
denied: Option<SocketAddr>,
|
||||
}
|
||||
|
||||
impl WrappedTcpDestinationRuntime for TestDestinationRuntime {
|
||||
fn is_ip_local_virtual_ip(&self, ip: &IpAddr) -> bool {
|
||||
*ip == self.local_ip
|
||||
}
|
||||
|
||||
fn no_tun(&self) -> bool {
|
||||
self.no_tun
|
||||
}
|
||||
|
||||
fn should_deny_tcp_proxy(&self, dst: SocketAddr) -> bool {
|
||||
self.denied == Some(dst)
|
||||
}
|
||||
}
|
||||
|
||||
struct TestGroupResolver;
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl WrappedTcpPeerGroupResolver for TestGroupResolver {
|
||||
async fn get_peer_groups_by_ip(&self, ip: &IpAddr) -> Arc<Vec<String>> {
|
||||
Arc::new(vec![format!("group-{ip}")])
|
||||
}
|
||||
}
|
||||
|
||||
fn destination_runtime(local_ip: &str, no_tun: bool) -> TestDestinationRuntime {
|
||||
TestDestinationRuntime {
|
||||
local_ip: local_ip.parse().unwrap(),
|
||||
no_tun,
|
||||
denied: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn mapped_cidr_table() -> ProxyCidrTable {
|
||||
ProxyCidrTable::from_snapshot(ProxyCidrSnapshot {
|
||||
rules: vec![ProxyCidrRule {
|
||||
cidr: "10.10.0.0/16".parse().unwrap(),
|
||||
mapped_cidr: Some("100.64.0.0/16".parse().unwrap()),
|
||||
}],
|
||||
})
|
||||
}
|
||||
|
||||
async fn destination_plan(
|
||||
runtime: &TestDestinationRuntime,
|
||||
dst: &str,
|
||||
) -> anyhow::Result<WrappedTcpDestinationPlan> {
|
||||
plan_wrapped_tcp_destination(
|
||||
WrappedTcpDestinationRequest {
|
||||
src: "10.20.0.2:40000".parse().unwrap(),
|
||||
dst: dst.parse().unwrap(),
|
||||
initial_packet_size: b"header".len(),
|
||||
},
|
||||
&mapped_cidr_table(),
|
||||
runtime,
|
||||
&TestGroupResolver,
|
||||
Arc::new(AclFilter::new()),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destination_plan_maps_cidr_and_builds_forward_acl_context() {
|
||||
let plan = destination_plan(&destination_runtime("10.30.0.1", false), "100.64.2.3:443")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(plan.socket_dst, "10.10.2.3:443".parse().unwrap());
|
||||
assert_eq!(plan.acl_handler.chain_type, ChainType::Forward);
|
||||
assert_eq!(
|
||||
plan.acl_handler.packet_info.dst_ip,
|
||||
"10.10.2.3".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
plan.acl_handler.packet_info.dst_groups.as_ref(),
|
||||
&["group-10.10.2.3"]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destination_plan_rewrites_local_no_tun_socket_after_acl_identity() {
|
||||
let plan = destination_plan(&destination_runtime("10.10.2.3", true), "100.64.2.3:443")
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(plan.socket_dst, "127.0.0.1:443".parse().unwrap());
|
||||
assert_eq!(plan.acl_handler.chain_type, ChainType::Inbound);
|
||||
assert_eq!(
|
||||
plan.acl_handler.packet_info.dst_ip,
|
||||
"10.10.2.3".parse::<IpAddr>().unwrap()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn destination_plan_denies_mapped_running_listener() {
|
||||
let mut runtime = destination_runtime("10.30.0.1", false);
|
||||
runtime.denied = Some("10.10.2.3:443".parse().unwrap());
|
||||
|
||||
let err = destination_plan(&runtime, "100.64.2.3:443")
|
||||
.await
|
||||
.err()
|
||||
.expect("mapped listener must be denied");
|
||||
assert!(err.to_string().contains("running listeners"));
|
||||
}
|
||||
|
||||
fn build_tcp_packet(src: SocketAddrV4, dst: SocketAddrV4, syn: bool, ack: bool) -> ZCPacket {
|
||||
let mut raw = vec![0; smoltcp::wire::IPV4_HEADER_LEN + smoltcp::wire::TCP_HEADER_LEN];
|
||||
{
|
||||
let mut ipv4 = Ipv4Packet::new_unchecked(&mut raw);
|
||||
ipv4.set_version(4);
|
||||
ipv4.set_header_len(smoltcp::wire::IPV4_HEADER_LEN as u8);
|
||||
ipv4.set_total_len(
|
||||
(smoltcp::wire::IPV4_HEADER_LEN + smoltcp::wire::TCP_HEADER_LEN) as u16,
|
||||
);
|
||||
ipv4.set_hop_limit(64);
|
||||
ipv4.set_next_header(IpProtocol::Tcp);
|
||||
ipv4.set_src_addr(*src.ip());
|
||||
ipv4.set_dst_addr(*dst.ip());
|
||||
ipv4.fill_checksum();
|
||||
}
|
||||
{
|
||||
let mut tcp = TcpPacket::new_unchecked(&mut raw[smoltcp::wire::IPV4_HEADER_LEN..]);
|
||||
tcp.set_src_port(src.port());
|
||||
tcp.set_dst_port(dst.port());
|
||||
tcp.set_header_len(smoltcp::wire::TCP_HEADER_LEN as u8);
|
||||
tcp.set_syn(syn);
|
||||
tcp.set_ack(ack);
|
||||
tcp.fill_checksum(&IpAddress::Ipv4(*src.ip()), &IpAddress::Ipv4(*dst.ip()));
|
||||
}
|
||||
|
||||
let mut packet = ZCPacket::new_with_payload(&raw);
|
||||
packet.fill_peer_manager_hdr(1, 2, PacketType::Data as u8);
|
||||
packet
|
||||
}
|
||||
|
||||
fn context(transport: WrappedTcpProxyTransport) -> WrappedTcpProxyNicContext {
|
||||
WrappedTcpProxyNicContext {
|
||||
transport,
|
||||
my_peer_id: 42,
|
||||
local_ipv4: Some("10.144.144.204".parse().unwrap()),
|
||||
smoltcp_enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn allowed_syn_is_marked_for_kcp() {
|
||||
let src = SocketAddrV4::new("10.144.144.204".parse().unwrap(), 50000);
|
||||
let dst = SocketAddrV4::new("10.10.10.10".parse().unwrap(), 80);
|
||||
let mut packet = build_tcp_packet(src, dst, true, false);
|
||||
|
||||
assert!(
|
||||
try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(WrappedTcpProxyTransport::Kcp),
|
||||
|_, _| false,
|
||||
|_| async { true },
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
let hdr = packet.peer_manager_header().unwrap();
|
||||
assert_eq!(hdr.to_peer_id.get(), 42);
|
||||
assert!(hdr.is_kcp_src_modified());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn denied_syn_is_not_marked() {
|
||||
let src = SocketAddrV4::new("10.144.144.204".parse().unwrap(), 50000);
|
||||
let dst = SocketAddrV4::new("10.10.10.10".parse().unwrap(), 80);
|
||||
let mut packet = build_tcp_packet(src, dst, true, false);
|
||||
|
||||
assert!(
|
||||
!try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(WrappedTcpProxyTransport::Kcp),
|
||||
|_, _| false,
|
||||
|_| async { false },
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
let hdr = packet.peer_manager_header().unwrap();
|
||||
assert_eq!(hdr.packet_type, PacketType::Data as u8);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn established_non_syn_is_marked_for_quic() {
|
||||
let src = SocketAddrV4::new("10.144.144.204".parse().unwrap(), 50000);
|
||||
let dst = SocketAddrV4::new("10.10.10.10".parse().unwrap(), 80);
|
||||
let mut packet = build_tcp_packet(src, dst, false, true);
|
||||
|
||||
assert!(
|
||||
try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(WrappedTcpProxyTransport::Quic),
|
||||
|src_addr, dst_addr| {
|
||||
src_addr == SocketAddr::V4(src) && dst_addr == SocketAddr::V4(dst)
|
||||
},
|
||||
|_| async { false },
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
let hdr = packet.peer_manager_header().unwrap();
|
||||
assert_eq!(hdr.to_peer_id.get(), 42);
|
||||
assert!(hdr.is_quic_src_modified());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_syn_without_connection_is_rejected() {
|
||||
let src = SocketAddrV4::new("10.144.144.204".parse().unwrap(), 50000);
|
||||
let dst = SocketAddrV4::new("10.10.10.10".parse().unwrap(), 80);
|
||||
let mut packet = build_tcp_packet(src, dst, false, true);
|
||||
|
||||
assert!(
|
||||
!try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(WrappedTcpProxyTransport::Quic),
|
||||
|_, _| false,
|
||||
|_| async { true },
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn net_to_net_without_smoltcp_is_rejected() {
|
||||
let src = SocketAddrV4::new("10.144.144.205".parse().unwrap(), 50000);
|
||||
let dst = SocketAddrV4::new("10.10.10.10".parse().unwrap(), 80);
|
||||
let mut packet = build_tcp_packet(src, dst, true, false);
|
||||
|
||||
assert!(
|
||||
!try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(WrappedTcpProxyTransport::Kcp),
|
||||
|_, _| false,
|
||||
|_| async { true },
|
||||
)
|
||||
.await
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn own_virtual_ip_syn_is_not_marked() {
|
||||
let own_ip = "10.144.144.204".parse().unwrap();
|
||||
let src = SocketAddrV4::new(own_ip, 50000);
|
||||
let dst = SocketAddrV4::new(own_ip, 80);
|
||||
|
||||
for transport in [
|
||||
WrappedTcpProxyTransport::Kcp,
|
||||
WrappedTcpProxyTransport::Quic,
|
||||
] {
|
||||
let mut packet = build_tcp_packet(src, dst, true, false);
|
||||
|
||||
assert!(
|
||||
!try_process_wrapped_tcp_packet_from_nic(
|
||||
&mut packet,
|
||||
context(transport),
|
||||
|_, _| false,
|
||||
|_| async { true },
|
||||
)
|
||||
.await
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
packet.peer_manager_header().unwrap().packet_type,
|
||||
PacketType::Data as u8
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+56
@@ -0,0 +1,56 @@
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use crate::gateway::proxy::traits::TcpProxyStream;
|
||||
|
||||
use super::{
|
||||
WrappedTransportKind, WrappedTransportPacketPlane, WrappedTransportPacketState,
|
||||
WrappedTransportProxyModule, packet_plane::connect_wrapped_transport_source,
|
||||
};
|
||||
|
||||
impl WrappedTransportPacketPlane {
|
||||
fn source_connect_ready(
|
||||
&self,
|
||||
state: &WrappedTransportPacketState,
|
||||
transport: WrappedTransportKind,
|
||||
) -> bool {
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => state.kcp_source_connect_ready,
|
||||
WrappedTransportKind::Quic => state.quic_source_connect_ready,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl WrappedTransportProxyModule {
|
||||
pub(crate) async fn source_connect_ready(&self, transport: WrappedTransportKind) -> bool {
|
||||
let state = self.state.lock().await;
|
||||
state.active
|
||||
&& self
|
||||
.packet_plane
|
||||
.source_connect_ready(&state.packet, transport)
|
||||
}
|
||||
|
||||
pub(crate) async fn connect_source(
|
||||
&self,
|
||||
transport: WrappedTransportKind,
|
||||
src: SocketAddr,
|
||||
dst: SocketAddr,
|
||||
) -> anyhow::Result<Box<dyn TcpProxyStream>> {
|
||||
let engine = {
|
||||
let state = self.state.lock().await;
|
||||
let ready = state.active
|
||||
&& self
|
||||
.packet_plane
|
||||
.source_connect_ready(&state.packet, transport);
|
||||
if !ready {
|
||||
anyhow::bail!("{transport:?} source is not ready");
|
||||
}
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => self.kcp.clone(),
|
||||
WrappedTransportKind::Quic => self.quic.clone(),
|
||||
}
|
||||
}
|
||||
.ok_or_else(|| anyhow::anyhow!("{transport:?} engine is not available"))?;
|
||||
|
||||
connect_wrapped_transport_source(&self.peer_manager, engine, src, dst).await
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use async_trait::async_trait;
|
||||
use bytes::Bytes;
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
use crate::gateway::proxy::{
|
||||
traits::TcpProxyStream, wrapped_transport_destination::WrappedTransportDestinationIngress,
|
||||
};
|
||||
|
||||
use super::{WrappedTransportDatagram, WrappedTransportDirections, WrappedTransportRole};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WrappedTransportEngineStart {
|
||||
pub directions: WrappedTransportDirections,
|
||||
pub my_peer_id: u32,
|
||||
pub datagrams: tokio::sync::mpsc::Sender<WrappedTransportDatagram>,
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub destination_ingress: Option<WrappedTransportDestinationIngress>,
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct WrappedTransportConnect {
|
||||
pub my_peer_id: u32,
|
||||
pub dst_peer_id: u32,
|
||||
pub src: SocketAddr,
|
||||
pub dst: SocketAddr,
|
||||
}
|
||||
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
pub struct WrappedTransportAcceptedStream {
|
||||
pub src: SocketAddr,
|
||||
pub dst: SocketAddr,
|
||||
pub initial_acl_packet_size: usize,
|
||||
pub stream: Box<dyn TcpProxyStream>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait WrappedTransportEngine: Send + Sync + 'static {
|
||||
async fn prepare(&self, options: WrappedTransportEngineStart) -> anyhow::Result<()>;
|
||||
async fn activate(&self) -> anyhow::Result<()>;
|
||||
async fn inject_peer_datagram(
|
||||
&self,
|
||||
role: WrappedTransportRole,
|
||||
from_peer_id: u32,
|
||||
payload: Bytes,
|
||||
) -> anyhow::Result<()>;
|
||||
#[cfg(feature = "proxy-packet")]
|
||||
async fn connect_source(
|
||||
&self,
|
||||
request: WrappedTransportConnect,
|
||||
) -> anyhow::Result<Box<dyn TcpProxyStream>>;
|
||||
async fn stop(&self);
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
use crate::gateway::proxy::tcp_proxy_engine::TcpNatEntrySnapshot;
|
||||
|
||||
use super::{WrappedTransportKind, WrappedTransportProxyModule};
|
||||
|
||||
impl WrappedTransportProxyModule {
|
||||
pub(crate) fn source_entry_snapshots(
|
||||
&self,
|
||||
transport: WrappedTransportKind,
|
||||
) -> Vec<TcpNatEntrySnapshot> {
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => self.packet_plane.kcp_source.as_ref(),
|
||||
WrappedTransportKind::Quic => self.packet_plane.quic_source.as_ref(),
|
||||
}
|
||||
.map_or_else(Vec::new, |source| source.entry_snapshots())
|
||||
}
|
||||
|
||||
pub(crate) fn source_is_started(&self, transport: WrappedTransportKind) -> bool {
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => self.packet_plane.kcp_source.as_ref(),
|
||||
WrappedTransportKind::Quic => self.packet_plane.quic_source.as_ref(),
|
||||
}
|
||||
.is_some_and(|source| source.is_started())
|
||||
}
|
||||
|
||||
pub(crate) fn destination_entry_snapshots(
|
||||
&self,
|
||||
transport: WrappedTransportKind,
|
||||
) -> Vec<TcpNatEntrySnapshot> {
|
||||
self.packet_plane
|
||||
.destination
|
||||
.as_ref()
|
||||
.map_or_else(Vec::new, |destination| {
|
||||
destination.entry_snapshots(transport)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn destination_is_started(&self, transport: WrappedTransportKind) -> bool {
|
||||
self.packet_plane
|
||||
.destination
|
||||
.as_ref()
|
||||
.is_some_and(|destination| destination.is_started(transport))
|
||||
}
|
||||
}
|
||||
+531
@@ -0,0 +1,531 @@
|
||||
use std::{
|
||||
net::{IpAddr, SocketAddr},
|
||||
sync::{Arc, Mutex as StdMutex, Weak},
|
||||
};
|
||||
|
||||
use async_trait::async_trait;
|
||||
|
||||
use crate::{
|
||||
config::runtime::CoreRuntimeConfigStore,
|
||||
connectivity::direct::DirectConnectorHost,
|
||||
connectivity::hole_punch::tcp::TcpHolePunchHost,
|
||||
gateway::proxy::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
service::CoreProxyRuntime,
|
||||
tcp_proxy_engine::{TcpNatEntrySnapshot, TcpProxyMode, TcpProxyNicContext},
|
||||
tcp_proxy_service::TcpProxyService,
|
||||
traits::{ProxyRuntimeInfo, TcpProxyDestinationConnector, TcpProxyStream},
|
||||
wrapped_tcp_proxy::{
|
||||
WrappedTcpProxyNicContext, WrappedTcpProxyTransport,
|
||||
try_process_wrapped_tcp_packet_from_nic,
|
||||
},
|
||||
wrapped_transport_destination::{
|
||||
WrappedTransportDestinationIngresses, WrappedTransportDestinationLifecycle,
|
||||
WrappedTransportDestinationModule,
|
||||
},
|
||||
},
|
||||
listener::RunningListenerRegistry,
|
||||
packet::ZCPacket,
|
||||
peers::peer_manager::{PeerManagerCore, PipelineRegistrationGuard},
|
||||
process_runtime::ProtectedTcpPortRegistry,
|
||||
socket::SocketContext,
|
||||
};
|
||||
|
||||
pub use crate::gateway::proxy::wrapped_transport_destination::WrappedTransportDestinationIngress;
|
||||
|
||||
use super::{
|
||||
WrappedTransportConnect, WrappedTransportDatagram, WrappedTransportDirections,
|
||||
WrappedTransportEngine, WrappedTransportEngineStart, WrappedTransportKind,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WrappedTransportPacketState {
|
||||
pub(super) kcp_source_connect_ready: bool,
|
||||
pub(super) quic_source_connect_ready: bool,
|
||||
pub(super) kcp_source_started: bool,
|
||||
pub(super) quic_source_started: bool,
|
||||
pub(super) destination_started: bool,
|
||||
pub(super) kcp_source_guard: Option<PipelineRegistrationGuard>,
|
||||
pub(super) quic_source_guard: Option<PipelineRegistrationGuard>,
|
||||
destination_ingresses: WrappedTransportDestinationIngresses,
|
||||
}
|
||||
|
||||
impl WrappedTransportPacketState {
|
||||
fn has_partial_start(&self) -> bool {
|
||||
self.kcp_source_started || self.quic_source_started || self.destination_started
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WrappedTransportPacketPlane {
|
||||
pub(super) kcp_source: Option<Arc<dyn WrappedTransportSourceLifecycle>>,
|
||||
pub(super) quic_source: Option<Arc<dyn WrappedTransportSourceLifecycle>>,
|
||||
pub(super) destination: Option<Arc<dyn WrappedTransportDestinationLifecycle>>,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct WrappedTransportSourceConnector {
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
engine: Weak<dyn WrappedTransportEngine>,
|
||||
transport: WrappedTransportKind,
|
||||
}
|
||||
|
||||
pub(super) async fn connect_wrapped_transport_source(
|
||||
peer_manager: &PeerManagerCore,
|
||||
engine: Arc<dyn WrappedTransportEngine>,
|
||||
src: SocketAddr,
|
||||
dst: SocketAddr,
|
||||
) -> anyhow::Result<Box<dyn TcpProxyStream>> {
|
||||
let SocketAddr::V4(dst_v4) = dst else {
|
||||
anyhow::bail!("IPv6 is not supported by wrapped TCP proxy");
|
||||
};
|
||||
let dst_peer_id = peer_manager
|
||||
.get_peer_map()
|
||||
.get_peer_id_by_ipv4(dst_v4.ip())
|
||||
.await
|
||||
.ok_or_else(|| anyhow::anyhow!("no peer found for wrapped TCP dst: {dst}"))?;
|
||||
engine
|
||||
.connect_source(WrappedTransportConnect {
|
||||
my_peer_id: peer_manager.my_peer_id(),
|
||||
dst_peer_id,
|
||||
src,
|
||||
dst,
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl TcpProxyDestinationConnector for WrappedTransportSourceConnector {
|
||||
type DstStream = Box<dyn TcpProxyStream>;
|
||||
|
||||
async fn connect(&self, src: SocketAddr, dst: SocketAddr) -> anyhow::Result<Self::DstStream> {
|
||||
let engine = self
|
||||
.engine
|
||||
.upgrade()
|
||||
.ok_or_else(|| anyhow::anyhow!("wrapped transport engine is not available"))?;
|
||||
connect_wrapped_transport_source(&self.peer_manager, engine, src, dst).await
|
||||
}
|
||||
|
||||
fn proxy_mode(&self) -> TcpProxyMode {
|
||||
match self.transport {
|
||||
WrappedTransportKind::Kcp => TcpProxyMode::KcpSrc,
|
||||
WrappedTransportKind::Quic => TcpProxyMode::QuicSrc,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type WrappedTransportSourceService<H> =
|
||||
TcpProxyService<CoreProxyRuntime<H>, H, WrappedTransportSourceConnector>;
|
||||
|
||||
pub(super) struct WrappedTransportSource<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime: Arc<CoreProxyRuntime<H>>,
|
||||
host: Arc<H>,
|
||||
connector: Arc<WrappedTransportSourceConnector>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
socket_context: SocketContext,
|
||||
service: StdMutex<Option<Arc<WrappedTransportSourceService<H>>>>,
|
||||
transport: WrappedTransportKind,
|
||||
}
|
||||
|
||||
impl<H> WrappedTransportSource<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
socket_context: SocketContext,
|
||||
engine: &Arc<dyn WrappedTransportEngine>,
|
||||
transport: WrappedTransportKind,
|
||||
) -> Arc<Self> {
|
||||
let protocol_label = match transport {
|
||||
WrappedTransportKind::Kcp => "KCP",
|
||||
WrappedTransportKind::Quic => "QUIC",
|
||||
};
|
||||
let runtime = CoreProxyRuntime::new(
|
||||
peer_manager.clone(),
|
||||
host.clone(),
|
||||
protected_tcp_ports,
|
||||
running_listeners,
|
||||
runtime_config,
|
||||
protocol_label,
|
||||
);
|
||||
let connector = Arc::new(WrappedTransportSourceConnector {
|
||||
peer_manager: peer_manager.clone(),
|
||||
engine: Arc::downgrade(engine),
|
||||
transport,
|
||||
});
|
||||
Arc::new(Self {
|
||||
peer_manager,
|
||||
runtime,
|
||||
host,
|
||||
connector,
|
||||
cidr_table,
|
||||
socket_context,
|
||||
service: StdMutex::new(None),
|
||||
transport,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_service(&self) -> Arc<WrappedTransportSourceService<H>> {
|
||||
TcpProxyService::new_with_socket_context(
|
||||
self.peer_manager.clone(),
|
||||
self.runtime.clone(),
|
||||
self.host.clone(),
|
||||
self.connector.clone(),
|
||||
self.cidr_table.clone(),
|
||||
self.socket_context.clone(),
|
||||
)
|
||||
}
|
||||
|
||||
async fn start_service(self: &Arc<Self>) -> Result<PipelineRegistrationGuard, anyhow::Error> {
|
||||
let service = {
|
||||
let mut active = self.service.lock().unwrap();
|
||||
if active.is_some() {
|
||||
anyhow::bail!("wrapped transport source is already started");
|
||||
}
|
||||
let service = self.build_service();
|
||||
active.replace(service.clone());
|
||||
service
|
||||
};
|
||||
self.runtime.latch_smoltcp();
|
||||
let guard = self
|
||||
.peer_manager
|
||||
.add_managed_nic_packet_process_pipeline(Box::new(WrappedTransportSourceFilter {
|
||||
source: Arc::downgrade(self),
|
||||
}))
|
||||
.await;
|
||||
service.register_peer_pipeline().await;
|
||||
if let Err(error) = service.start(false).await {
|
||||
guard.close();
|
||||
self.stop_service().await;
|
||||
return Err(anyhow::Error::new(error));
|
||||
}
|
||||
Ok(guard)
|
||||
}
|
||||
|
||||
async fn stop_service(&self) {
|
||||
let service = self.service.lock().unwrap().take();
|
||||
if let Some(service) = service {
|
||||
service.stop_and_wait().await;
|
||||
}
|
||||
}
|
||||
|
||||
fn source_entry_snapshots(&self) -> Vec<TcpNatEntrySnapshot> {
|
||||
self.service
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.map_or_else(Vec::new, |service| service.engine().list_entries())
|
||||
}
|
||||
|
||||
async fn try_process_nic_packet(&self, packet: &mut ZCPacket) -> bool {
|
||||
let Some(service) = self.service.lock().unwrap().clone() else {
|
||||
return false;
|
||||
};
|
||||
let snapshot = self.runtime.proxy_runtime_snapshot();
|
||||
let engine = service.engine();
|
||||
if engine.try_process_packet_from_nic(
|
||||
packet,
|
||||
TcpProxyNicContext {
|
||||
local_inet: snapshot.local_inet,
|
||||
local_port: engine.local_port(),
|
||||
my_peer_id: self.peer_manager.my_peer_id(),
|
||||
smoltcp_enabled: snapshot.smoltcp_enabled,
|
||||
},
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
let connection_engine = engine.clone();
|
||||
let peer_manager = self.peer_manager.clone();
|
||||
let transport = self.transport;
|
||||
try_process_wrapped_tcp_packet_from_nic(
|
||||
packet,
|
||||
WrappedTcpProxyNicContext {
|
||||
transport: match transport {
|
||||
WrappedTransportKind::Kcp => WrappedTcpProxyTransport::Kcp,
|
||||
WrappedTransportKind::Quic => WrappedTcpProxyTransport::Quic,
|
||||
},
|
||||
my_peer_id: self.peer_manager.my_peer_id(),
|
||||
local_ipv4: snapshot.virtual_ipv4,
|
||||
smoltcp_enabled: snapshot.smoltcp_enabled,
|
||||
},
|
||||
move |src, mapped_dst| connection_engine.is_tcp_proxy_flow(src, mapped_dst),
|
||||
move |dst_ip| async move {
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => {
|
||||
peer_manager
|
||||
.check_allow_kcp_to_dst(&IpAddr::V4(dst_ip))
|
||||
.await
|
||||
}
|
||||
WrappedTransportKind::Quic => {
|
||||
peer_manager
|
||||
.check_allow_quic_to_dst(&IpAddr::V4(dst_ip))
|
||||
.await
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub(super) trait WrappedTransportSourceLifecycle: Send + Sync {
|
||||
async fn start(self: Arc<Self>) -> anyhow::Result<PipelineRegistrationGuard>;
|
||||
async fn stop(&self);
|
||||
fn entry_snapshots(&self) -> Vec<TcpNatEntrySnapshot>;
|
||||
fn is_started(&self) -> bool;
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<H> WrappedTransportSourceLifecycle for WrappedTransportSource<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
async fn start(self: Arc<Self>) -> anyhow::Result<PipelineRegistrationGuard> {
|
||||
self.start_service().await
|
||||
}
|
||||
|
||||
async fn stop(&self) {
|
||||
self.stop_service().await;
|
||||
}
|
||||
|
||||
fn entry_snapshots(&self) -> Vec<TcpNatEntrySnapshot> {
|
||||
self.source_entry_snapshots()
|
||||
}
|
||||
|
||||
fn is_started(&self) -> bool {
|
||||
self.service
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.is_some_and(|service| service.is_started())
|
||||
}
|
||||
}
|
||||
|
||||
struct WrappedTransportSourceFilter<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
source: Weak<WrappedTransportSource<H>>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
impl<H> crate::peers::NicPacketFilter for WrappedTransportSourceFilter<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
async fn try_process_packet_from_nic(&self, packet: &mut ZCPacket) -> bool {
|
||||
let Some(source) = self.source.upgrade() else {
|
||||
return false;
|
||||
};
|
||||
source.try_process_nic_packet(packet).await
|
||||
}
|
||||
}
|
||||
|
||||
impl WrappedTransportPacketPlane {
|
||||
pub(super) fn has_partial_start(&self, state: &WrappedTransportPacketState) -> bool {
|
||||
state.has_partial_start()
|
||||
}
|
||||
|
||||
pub(super) fn clear_connect_ready(&self, state: &mut WrappedTransportPacketState) {
|
||||
state.kcp_source_connect_ready = false;
|
||||
state.quic_source_connect_ready = false;
|
||||
}
|
||||
|
||||
pub(super) async fn stop_source(
|
||||
&self,
|
||||
state: &mut WrappedTransportPacketState,
|
||||
transport: WrappedTransportKind,
|
||||
) {
|
||||
let (source, started, guard) = match transport {
|
||||
WrappedTransportKind::Kcp => (
|
||||
&self.kcp_source,
|
||||
&mut state.kcp_source_started,
|
||||
&mut state.kcp_source_guard,
|
||||
),
|
||||
WrappedTransportKind::Quic => (
|
||||
&self.quic_source,
|
||||
&mut state.quic_source_started,
|
||||
&mut state.quic_source_guard,
|
||||
),
|
||||
};
|
||||
if let Some(guard) = guard.take() {
|
||||
guard.close();
|
||||
}
|
||||
if *started {
|
||||
if let Some(source) = source {
|
||||
source.stop().await;
|
||||
}
|
||||
*started = false;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn stop_destination(&self, state: &mut WrappedTransportPacketState) {
|
||||
if state.destination_started {
|
||||
if let Some(destination) = &self.destination {
|
||||
destination.stop().await;
|
||||
}
|
||||
state.destination_started = false;
|
||||
}
|
||||
state.destination_ingresses = WrappedTransportDestinationIngresses::default();
|
||||
}
|
||||
|
||||
pub(super) async fn start_destinations(
|
||||
&self,
|
||||
state: &mut WrappedTransportPacketState,
|
||||
kcp_directions: WrappedTransportDirections,
|
||||
quic_directions: WrappedTransportDirections,
|
||||
kcp_available: bool,
|
||||
quic_available: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
let kcp = kcp_directions.destination && kcp_available;
|
||||
let quic = quic_directions.destination && quic_available;
|
||||
state.destination_ingresses = if kcp || quic {
|
||||
state.destination_started = true;
|
||||
self.destination
|
||||
.as_ref()
|
||||
.expect("wrapped destination owner must match its engines")
|
||||
.clone()
|
||||
.start(kcp, quic)
|
||||
.await?
|
||||
} else {
|
||||
WrappedTransportDestinationIngresses::default()
|
||||
};
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn engine_start(
|
||||
&self,
|
||||
state: &WrappedTransportPacketState,
|
||||
transport: WrappedTransportKind,
|
||||
directions: WrappedTransportDirections,
|
||||
my_peer_id: u32,
|
||||
datagrams: tokio::sync::mpsc::Sender<WrappedTransportDatagram>,
|
||||
) -> WrappedTransportEngineStart {
|
||||
let destination_ingress = match transport {
|
||||
WrappedTransportKind::Kcp => state.destination_ingresses.kcp.clone(),
|
||||
WrappedTransportKind::Quic => state.destination_ingresses.quic.clone(),
|
||||
};
|
||||
WrappedTransportEngineStart {
|
||||
directions,
|
||||
my_peer_id,
|
||||
datagrams,
|
||||
destination_ingress,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn start_source(
|
||||
&self,
|
||||
state: &mut WrappedTransportPacketState,
|
||||
transport: WrappedTransportKind,
|
||||
directions: WrappedTransportDirections,
|
||||
) -> anyhow::Result<()> {
|
||||
if !directions.source {
|
||||
return Ok(());
|
||||
}
|
||||
let (source, started, guard) = match transport {
|
||||
WrappedTransportKind::Kcp => (
|
||||
&self.kcp_source,
|
||||
&mut state.kcp_source_started,
|
||||
&mut state.kcp_source_guard,
|
||||
),
|
||||
WrappedTransportKind::Quic => (
|
||||
&self.quic_source,
|
||||
&mut state.quic_source_started,
|
||||
&mut state.quic_source_guard,
|
||||
),
|
||||
};
|
||||
let Some(source) = source else {
|
||||
return Ok(());
|
||||
};
|
||||
*started = true;
|
||||
*guard = Some(source.clone().start().await?);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn mark_source_connect_ready(
|
||||
&self,
|
||||
state: &mut WrappedTransportPacketState,
|
||||
transport: WrappedTransportKind,
|
||||
directions: WrappedTransportDirections,
|
||||
) {
|
||||
if !directions.source {
|
||||
return;
|
||||
}
|
||||
match transport {
|
||||
WrappedTransportKind::Kcp => state.kcp_source_connect_ready = true,
|
||||
WrappedTransportKind::Quic => state.quic_source_connect_ready = true,
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn new<H>(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
kcp: &Option<Arc<dyn WrappedTransportEngine>>,
|
||||
quic: &Option<Arc<dyn WrappedTransportEngine>>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
socket_context: SocketContext,
|
||||
) -> Self
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
let kcp_source = kcp.as_ref().map(|engine| {
|
||||
WrappedTransportSource::new(
|
||||
peer_manager.clone(),
|
||||
host.clone(),
|
||||
protected_tcp_ports.clone(),
|
||||
running_listeners.clone(),
|
||||
runtime_config.clone(),
|
||||
cidr_table.clone(),
|
||||
socket_context.clone(),
|
||||
engine,
|
||||
WrappedTransportKind::Kcp,
|
||||
) as Arc<dyn WrappedTransportSourceLifecycle>
|
||||
});
|
||||
let quic_source = quic.as_ref().map(|engine| {
|
||||
WrappedTransportSource::new(
|
||||
peer_manager.clone(),
|
||||
host.clone(),
|
||||
protected_tcp_ports.clone(),
|
||||
running_listeners.clone(),
|
||||
runtime_config.clone(),
|
||||
cidr_table.clone(),
|
||||
socket_context.clone(),
|
||||
engine,
|
||||
WrappedTransportKind::Quic,
|
||||
) as Arc<dyn WrappedTransportSourceLifecycle>
|
||||
});
|
||||
let destination = (kcp.is_some() || quic.is_some()).then(|| {
|
||||
WrappedTransportDestinationModule::new(
|
||||
peer_manager,
|
||||
host,
|
||||
protected_tcp_ports,
|
||||
running_listeners,
|
||||
runtime_config,
|
||||
cidr_table,
|
||||
socket_context,
|
||||
) as Arc<dyn WrappedTransportDestinationLifecycle>
|
||||
});
|
||||
Self {
|
||||
kcp_source,
|
||||
quic_source,
|
||||
destination,
|
||||
}
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use crate::{
|
||||
config::runtime::CoreRuntimeConfigStore, connectivity::direct::DirectConnectorHost,
|
||||
connectivity::hole_punch::tcp::TcpHolePunchHost, gateway::proxy::cidr_table::ProxyCidrTable,
|
||||
listener::RunningListenerRegistry, peers::peer_manager::PeerManagerCore,
|
||||
process_runtime::ProtectedTcpPortRegistry, socket::SocketContext,
|
||||
};
|
||||
|
||||
use super::{
|
||||
WrappedTransportDatagram, WrappedTransportDirections, WrappedTransportEngine,
|
||||
WrappedTransportEngineStart, WrappedTransportKind,
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WrappedTransportPacketState;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WrappedTransportPacketPlane;
|
||||
|
||||
impl WrappedTransportPacketPlane {
|
||||
pub(super) fn has_partial_start(&self, _state: &WrappedTransportPacketState) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub(super) fn clear_connect_ready(&self, _state: &mut WrappedTransportPacketState) {}
|
||||
|
||||
pub(super) async fn stop_source(
|
||||
&self,
|
||||
_state: &mut WrappedTransportPacketState,
|
||||
_transport: WrappedTransportKind,
|
||||
) {
|
||||
}
|
||||
|
||||
pub(super) async fn stop_destination(&self, _state: &mut WrappedTransportPacketState) {}
|
||||
|
||||
pub(super) async fn start_destinations(
|
||||
&self,
|
||||
_state: &mut WrappedTransportPacketState,
|
||||
_kcp_directions: WrappedTransportDirections,
|
||||
_quic_directions: WrappedTransportDirections,
|
||||
_kcp_available: bool,
|
||||
_quic_available: bool,
|
||||
) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn engine_start(
|
||||
&self,
|
||||
_state: &WrappedTransportPacketState,
|
||||
_transport: WrappedTransportKind,
|
||||
directions: WrappedTransportDirections,
|
||||
my_peer_id: u32,
|
||||
datagrams: tokio::sync::mpsc::Sender<WrappedTransportDatagram>,
|
||||
) -> WrappedTransportEngineStart {
|
||||
WrappedTransportEngineStart {
|
||||
directions,
|
||||
my_peer_id,
|
||||
datagrams,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn start_source(
|
||||
&self,
|
||||
_state: &mut WrappedTransportPacketState,
|
||||
_transport: WrappedTransportKind,
|
||||
_directions: WrappedTransportDirections,
|
||||
) -> anyhow::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn mark_source_connect_ready(
|
||||
&self,
|
||||
_state: &mut WrappedTransportPacketState,
|
||||
_transport: WrappedTransportKind,
|
||||
_directions: WrappedTransportDirections,
|
||||
) {
|
||||
}
|
||||
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub(super) fn new<H>(
|
||||
_peer_manager: Arc<PeerManagerCore>,
|
||||
_runtime_config: CoreRuntimeConfigStore,
|
||||
_kcp: &Option<Arc<dyn WrappedTransportEngine>>,
|
||||
_quic: &Option<Arc<dyn WrappedTransportEngine>>,
|
||||
_host: Arc<H>,
|
||||
_protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
_running_listeners: Arc<RunningListenerRegistry>,
|
||||
_cidr_table: Arc<ProxyCidrTable>,
|
||||
_socket_context: SocketContext,
|
||||
) -> Self
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
Self
|
||||
}
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
use std::{
|
||||
net::SocketAddr,
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicBool, AtomicU8, Ordering},
|
||||
},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use dashmap::DashMap;
|
||||
use guarden::defer;
|
||||
use tokio::{sync::Mutex, task::JoinSet};
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
use crate::{
|
||||
config::runtime::CoreRuntimeConfigStore, connectivity::direct::DirectConnectorHost,
|
||||
connectivity::hole_punch::tcp::TcpHolePunchHost, listener::RunningListenerRegistry,
|
||||
peers::peer_manager::PeerManagerCore, process_runtime::ProtectedTcpPortRegistry,
|
||||
socket::SocketContext,
|
||||
};
|
||||
|
||||
use super::{
|
||||
cidr_table::ProxyCidrTable,
|
||||
service::CoreProxyRuntime,
|
||||
tcp_proxy_engine::{TcpNatEntrySnapshot, TcpNatEntryState},
|
||||
tcp_socket_connector::TcpSocketProxyConnector,
|
||||
traits::TcpProxyDestinationConnector,
|
||||
wrapped_tcp_proxy::{WrappedTcpDestinationRequest, plan_wrapped_tcp_destination},
|
||||
wrapped_transport::{WrappedTransportAcceptedStream, WrappedTransportKind},
|
||||
};
|
||||
|
||||
struct DestinationEntry {
|
||||
transport: WrappedTransportKind,
|
||||
src: SocketAddr,
|
||||
dst: SocketAddr,
|
||||
mapped_dst: std::sync::RwLock<SocketAddr>,
|
||||
start_time: u64,
|
||||
state: AtomicU8,
|
||||
}
|
||||
|
||||
impl DestinationEntry {
|
||||
fn new(transport: WrappedTransportKind, src: SocketAddr, dst: SocketAddr) -> Self {
|
||||
Self {
|
||||
transport,
|
||||
src,
|
||||
dst,
|
||||
mapped_dst: std::sync::RwLock::new(dst),
|
||||
start_time: SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|duration| duration.as_secs())
|
||||
.unwrap_or_default(),
|
||||
state: AtomicU8::new(TcpNatEntryState::ConnectingDst as u8),
|
||||
}
|
||||
}
|
||||
|
||||
fn set_mapped_dst(&self, mapped_dst: SocketAddr) {
|
||||
*self
|
||||
.mapped_dst
|
||||
.write()
|
||||
.expect("wrapped destination entry mutex poisoned") = mapped_dst;
|
||||
}
|
||||
|
||||
fn set_state(&self, state: TcpNatEntryState) {
|
||||
self.state.store(state as u8, Ordering::Release);
|
||||
}
|
||||
|
||||
fn snapshot(&self) -> TcpNatEntrySnapshot {
|
||||
let state = match self.state.load(Ordering::Acquire) {
|
||||
value if value == TcpNatEntryState::Connected as u8 => TcpNatEntryState::Connected,
|
||||
_ => TcpNatEntryState::ConnectingDst,
|
||||
};
|
||||
TcpNatEntrySnapshot {
|
||||
src: self.src,
|
||||
dst: self.dst,
|
||||
mapped_dst: *self
|
||||
.mapped_dst
|
||||
.read()
|
||||
.expect("wrapped destination entry mutex poisoned"),
|
||||
start_time: self.start_time,
|
||||
state,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct AcceptedDestination {
|
||||
transport: WrappedTransportKind,
|
||||
stream: WrappedTransportAcceptedStream,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct WrappedTransportDestinationIngress {
|
||||
transport: WrappedTransportKind,
|
||||
accepted: tokio::sync::mpsc::Sender<AcceptedDestination>,
|
||||
}
|
||||
|
||||
impl WrappedTransportDestinationIngress {
|
||||
pub async fn submit(&self, stream: WrappedTransportAcceptedStream) -> anyhow::Result<()> {
|
||||
self.accepted
|
||||
.send(AcceptedDestination {
|
||||
transport: self.transport,
|
||||
stream,
|
||||
})
|
||||
.await
|
||||
.map_err(|_| anyhow::anyhow!("wrapped destination ingress is stopped"))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct WrappedTransportDestinationIngresses {
|
||||
pub(crate) kcp: Option<WrappedTransportDestinationIngress>,
|
||||
pub(crate) quic: Option<WrappedTransportDestinationIngress>,
|
||||
}
|
||||
|
||||
struct DestinationRun {
|
||||
cancel: CancellationToken,
|
||||
supervisor: tokio::task::JoinHandle<()>,
|
||||
}
|
||||
|
||||
async fn stop_destination_run(run: &Mutex<Option<DestinationRun>>) {
|
||||
let mut run = run.lock().await;
|
||||
if let Some(current) = run.as_mut() {
|
||||
current.cancel.cancel();
|
||||
let _ = (&mut current.supervisor).await;
|
||||
run.take();
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct WrappedTransportDestinationModule<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
runtime: Arc<CoreProxyRuntime<H>>,
|
||||
connector: TcpSocketProxyConnector<H>,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
entries: DashMap<uuid::Uuid, Arc<DestinationEntry>>,
|
||||
run: Mutex<Option<DestinationRun>>,
|
||||
active: AtomicBool,
|
||||
enabled: AtomicU8,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
pub(crate) trait WrappedTransportDestinationLifecycle: Send + Sync {
|
||||
async fn start(
|
||||
self: Arc<Self>,
|
||||
kcp: bool,
|
||||
quic: bool,
|
||||
) -> anyhow::Result<WrappedTransportDestinationIngresses>;
|
||||
async fn stop(&self);
|
||||
fn entry_snapshots(&self, transport: WrappedTransportKind) -> Vec<TcpNatEntrySnapshot>;
|
||||
fn is_started(&self, transport: WrappedTransportKind) -> bool;
|
||||
}
|
||||
|
||||
impl<H> WrappedTransportDestinationModule<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
const INGRESS_CAPACITY: usize = 128;
|
||||
|
||||
pub(crate) fn new(
|
||||
peer_manager: Arc<PeerManagerCore>,
|
||||
host: Arc<H>,
|
||||
protected_tcp_ports: Arc<ProtectedTcpPortRegistry>,
|
||||
running_listeners: Arc<RunningListenerRegistry>,
|
||||
runtime_config: CoreRuntimeConfigStore,
|
||||
cidr_table: Arc<ProxyCidrTable>,
|
||||
socket_context: SocketContext,
|
||||
) -> Arc<Self> {
|
||||
Arc::new(Self {
|
||||
runtime: CoreProxyRuntime::new(
|
||||
peer_manager.clone(),
|
||||
host.clone(),
|
||||
protected_tcp_ports,
|
||||
running_listeners,
|
||||
runtime_config,
|
||||
"TCP",
|
||||
),
|
||||
connector: TcpSocketProxyConnector::new(host).with_socket_context(socket_context),
|
||||
cidr_table,
|
||||
peer_manager,
|
||||
entries: DashMap::new(),
|
||||
run: Mutex::new(None),
|
||||
active: AtomicBool::new(false),
|
||||
enabled: AtomicU8::new(0),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn start(
|
||||
self: &Arc<Self>,
|
||||
kcp: bool,
|
||||
quic: bool,
|
||||
) -> anyhow::Result<WrappedTransportDestinationIngresses> {
|
||||
let mut run = self.run.lock().await;
|
||||
if run.is_some() {
|
||||
anyhow::bail!("wrapped transport destination is already started");
|
||||
}
|
||||
|
||||
let (accepted, mut receiver) = tokio::sync::mpsc::channel(Self::INGRESS_CAPACITY);
|
||||
let cancel = CancellationToken::new();
|
||||
let task_cancel = cancel.clone();
|
||||
let owner = Arc::downgrade(self);
|
||||
let supervisor = tokio::spawn(async move {
|
||||
let mut sessions = JoinSet::new();
|
||||
loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = task_cancel.cancelled() => break,
|
||||
accepted = receiver.recv() => {
|
||||
let Some(accepted) = accepted else { break };
|
||||
let Some(owner) = owner.upgrade() else { break };
|
||||
sessions.spawn(async move {
|
||||
if let Err(error) = owner.handle_destination(accepted).await {
|
||||
tracing::debug!(?error, "wrapped destination session failed");
|
||||
}
|
||||
});
|
||||
}
|
||||
_ = sessions.join_next(), if !sessions.is_empty() => {}
|
||||
}
|
||||
}
|
||||
sessions.shutdown().await;
|
||||
});
|
||||
self.active.store(true, Ordering::Release);
|
||||
self.enabled
|
||||
.store((kcp as u8) | ((quic as u8) << 1), Ordering::Release);
|
||||
*run = Some(DestinationRun { cancel, supervisor });
|
||||
|
||||
let ingress = |transport| WrappedTransportDestinationIngress {
|
||||
transport,
|
||||
accepted: accepted.clone(),
|
||||
};
|
||||
Ok(WrappedTransportDestinationIngresses {
|
||||
kcp: kcp.then(|| ingress(WrappedTransportKind::Kcp)),
|
||||
quic: quic.then(|| ingress(WrappedTransportKind::Quic)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn stop(&self) {
|
||||
self.active.store(false, Ordering::Release);
|
||||
self.enabled.store(0, Ordering::Release);
|
||||
stop_destination_run(&self.run).await;
|
||||
self.entries.clear();
|
||||
}
|
||||
|
||||
pub(crate) fn entry_snapshots(
|
||||
&self,
|
||||
transport: WrappedTransportKind,
|
||||
) -> Vec<TcpNatEntrySnapshot> {
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.value().transport == transport)
|
||||
.map(|entry| entry.value().snapshot())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn is_started(&self, transport: WrappedTransportKind) -> bool {
|
||||
let mask = match transport {
|
||||
WrappedTransportKind::Kcp => 1,
|
||||
WrappedTransportKind::Quic => 2,
|
||||
};
|
||||
self.active.load(Ordering::Acquire) && self.enabled.load(Ordering::Acquire) & mask != 0
|
||||
}
|
||||
|
||||
async fn handle_destination(&self, accepted: AcceptedDestination) -> anyhow::Result<()> {
|
||||
if !self.active.load(Ordering::Acquire) {
|
||||
anyhow::bail!("wrapped transport destination is not active");
|
||||
}
|
||||
|
||||
let entry_id = uuid::Uuid::new_v4();
|
||||
let entry = Arc::new(DestinationEntry::new(
|
||||
accepted.transport,
|
||||
accepted.stream.src,
|
||||
accepted.stream.dst,
|
||||
));
|
||||
self.entries.insert(entry_id, entry.clone());
|
||||
defer! {
|
||||
self.remove_entry(entry_id);
|
||||
}
|
||||
|
||||
let route = self.peer_manager.get_route();
|
||||
let plan = plan_wrapped_tcp_destination(
|
||||
WrappedTcpDestinationRequest {
|
||||
src: accepted.stream.src,
|
||||
dst: accepted.stream.dst,
|
||||
initial_packet_size: accepted.stream.initial_acl_packet_size,
|
||||
},
|
||||
self.cidr_table.as_ref(),
|
||||
self.runtime.as_ref(),
|
||||
route.as_ref(),
|
||||
self.peer_manager.acl_filter(),
|
||||
)
|
||||
.await?;
|
||||
entry.set_mapped_dst(plan.socket_dst);
|
||||
|
||||
tracing::debug!(dst = ?plan.socket_dst, "wrapped transport connect to destination");
|
||||
let destination = self
|
||||
.connector
|
||||
.connect("0.0.0.0:0".parse().unwrap(), plan.socket_dst)
|
||||
.await?;
|
||||
entry.set_state(TcpNatEntryState::Connected);
|
||||
|
||||
plan.acl_handler
|
||||
.copy_bidirection_with_acl(accepted.stream.stream, destination)
|
||||
.await
|
||||
}
|
||||
|
||||
fn remove_entry(&self, id: uuid::Uuid) {
|
||||
self.entries.remove(&id);
|
||||
if self.entries.capacity() - self.entries.len() > 16 {
|
||||
self.entries.shrink_to_fit();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl<H> WrappedTransportDestinationLifecycle for WrappedTransportDestinationModule<H>
|
||||
where
|
||||
H: DirectConnectorHost + TcpHolePunchHost,
|
||||
{
|
||||
async fn start(
|
||||
self: Arc<Self>,
|
||||
kcp: bool,
|
||||
quic: bool,
|
||||
) -> anyhow::Result<WrappedTransportDestinationIngresses> {
|
||||
WrappedTransportDestinationModule::start(&self, kcp, quic).await
|
||||
}
|
||||
|
||||
async fn stop(&self) {
|
||||
WrappedTransportDestinationModule::stop(self).await;
|
||||
}
|
||||
|
||||
fn entry_snapshots(&self, transport: WrappedTransportKind) -> Vec<TcpNatEntrySnapshot> {
|
||||
WrappedTransportDestinationModule::entry_snapshots(self, transport)
|
||||
}
|
||||
|
||||
fn is_started(&self, transport: WrappedTransportKind) -> bool {
|
||||
WrappedTransportDestinationModule::is_started(self, transport)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use tokio::sync::Notify;
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancelled_stop_retains_supervisor_for_retry() {
|
||||
let cancel = CancellationToken::new();
|
||||
let stop_entered = Arc::new(Notify::new());
|
||||
let release_stop = Arc::new(Notify::new());
|
||||
let supervisor = tokio::spawn({
|
||||
let cancel = cancel.clone();
|
||||
let stop_entered = stop_entered.clone();
|
||||
let release_stop = release_stop.clone();
|
||||
async move {
|
||||
cancel.cancelled().await;
|
||||
stop_entered.notify_one();
|
||||
release_stop.notified().await;
|
||||
}
|
||||
});
|
||||
let run = Arc::new(Mutex::new(Some(DestinationRun { cancel, supervisor })));
|
||||
|
||||
let first_stop = tokio::spawn({
|
||||
let run = run.clone();
|
||||
async move { stop_destination_run(run.as_ref()).await }
|
||||
});
|
||||
stop_entered.notified().await;
|
||||
first_stop.abort();
|
||||
assert!(first_stop.await.unwrap_err().is_cancelled());
|
||||
assert!(run.lock().await.is_some());
|
||||
|
||||
release_stop.notify_one();
|
||||
stop_destination_run(run.as_ref()).await;
|
||||
assert!(run.lock().await.is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
mod stack;
|
||||
mod tokio_smoltcp;
|
||||
|
||||
pub(super) use stack::{SmolTcpStack, output_dst_ip};
|
||||
pub(super) use tokio_smoltcp::{
|
||||
BufferSize, Net, NetConfig, TcpListener, UdpSocket, channel_device,
|
||||
};
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user