mirror of
https://github.com/vnt-dev/vnt.git
synced 2026-12-06 16:04:30 +00:00
refactor(p2p): migrate to rustp2p-core endpoint API
This commit is contained in:
1 parent
c911b44b90
commit
ed41c08ea6
23 files changed
+724
-841
No files matched your search
Generated
+45
-245
@@ -189,16 +189,6 @@ dependencies = [
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-event"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c1222afd3d2bce3995035054046a279ae7aa154d70d0766cea050073f3fd7ddf"
|
||||
dependencies = [
|
||||
"loom",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-executor"
|
||||
version = "1.14.0"
|
||||
@@ -271,17 +261,6 @@ dependencies = [
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-scoped"
|
||||
version = "0.9.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4042078ea593edffc452eef14e99fdb2b120caa4ad9618bcdeabc4a023b98740"
|
||||
dependencies = [
|
||||
"futures",
|
||||
"pin-project",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "async-signal"
|
||||
version = "0.2.14"
|
||||
@@ -905,15 +884,6 @@ dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-queue"
|
||||
version = "0.3.12"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"
|
||||
dependencies = [
|
||||
"crossbeam-utils",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "crossbeam-utils"
|
||||
version = "0.8.21"
|
||||
@@ -1158,16 +1128,6 @@ version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3c877555693c14d2f84191cfd3ad8582790fc52b5e2274b40b59cf5f5cea25c7"
|
||||
|
||||
[[package]]
|
||||
name = "diatomic-waker"
|
||||
version = "0.1.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "28025fb55a9d815acf7b0877555f437254f373036eec6ed265116c7a5c0825e9"
|
||||
dependencies = [
|
||||
"loom",
|
||||
"waker-fn",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "digest"
|
||||
version = "0.10.7"
|
||||
@@ -1775,19 +1735,6 @@ dependencies = [
|
||||
"x11",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generator"
|
||||
version = "0.7.5"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "5cc16584ff22b460a382b7feec54b23d2908d858152e5739a120b949293bd74e"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"libc",
|
||||
"log",
|
||||
"rustversion",
|
||||
"windows 0.48.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "generic-array"
|
||||
version = "0.14.7"
|
||||
@@ -2194,7 +2141,7 @@ dependencies = [
|
||||
"libc",
|
||||
"percent-encoding",
|
||||
"pin-project-lite",
|
||||
"socket2 0.6.2",
|
||||
"socket2",
|
||||
"tokio",
|
||||
"tower-service",
|
||||
"tracing",
|
||||
@@ -2344,6 +2291,16 @@ dependencies = [
|
||||
"icu_properties",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "if-addrs"
|
||||
version = "0.15.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "indexmap"
|
||||
version = "1.9.3"
|
||||
@@ -2775,19 +2732,6 @@ dependencies = [
|
||||
"winapi",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "loom"
|
||||
version = "0.5.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ff50ecb28bb86013e935fb6683ab1f6d3a20016f123c76fd4c27470076ac30f5"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
"generator",
|
||||
"scoped-tls",
|
||||
"tracing",
|
||||
"tracing-subscriber",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "lru"
|
||||
version = "0.7.8"
|
||||
@@ -2834,15 +2778,6 @@ dependencies = [
|
||||
"web_atoms",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchers"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9"
|
||||
dependencies = [
|
||||
"regex-automata",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "matchit"
|
||||
version = "0.8.4"
|
||||
@@ -2988,7 +2923,7 @@ dependencies = [
|
||||
"system-configuration-sys",
|
||||
"thiserror 2.0.18",
|
||||
"widestring",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -3109,15 +3044,6 @@ dependencies = [
|
||||
"minimal-lexical",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "nu-ansi-term"
|
||||
version = "0.50.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
|
||||
dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.4.6"
|
||||
@@ -3633,26 +3559,6 @@ dependencies = [
|
||||
"siphasher",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "677f1add503faace112b9f1373e43e9e054bfdd22ff1a63c1bc485eaec6a6a8a"
|
||||
dependencies = [
|
||||
"pin-project-internal",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-internal"
|
||||
version = "1.1.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6e918e4ff8c4549eb882f14b3a4bc8c8bc93de829416eacf579f1207a8fbf861"
|
||||
dependencies = [
|
||||
"proc-macro2",
|
||||
"quote",
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "pin-project-lite"
|
||||
version = "0.2.16"
|
||||
@@ -4037,7 +3943,7 @@ dependencies = [
|
||||
"quinn-udp",
|
||||
"rustc-hash",
|
||||
"rustls",
|
||||
"socket2 0.6.2",
|
||||
"socket2",
|
||||
"thiserror 2.0.18",
|
||||
"tokio",
|
||||
"tracing",
|
||||
@@ -4074,7 +3980,7 @@ dependencies = [
|
||||
"cfg_aliases",
|
||||
"libc",
|
||||
"once_cell",
|
||||
"socket2 0.6.2",
|
||||
"socket2",
|
||||
"tracing",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
@@ -4376,34 +4282,6 @@ dependencies = [
|
||||
"walkdir",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rust-p2p-core"
|
||||
version = "0.4.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "eccee83a23618a90d50a11cf971e72ce68efee69dbca8c246795ecd791118e32"
|
||||
dependencies = [
|
||||
"async-broadcast",
|
||||
"async-lock",
|
||||
"async-scoped",
|
||||
"async-trait",
|
||||
"bytes",
|
||||
"crossbeam-queue",
|
||||
"crossbeam-utils",
|
||||
"dashmap",
|
||||
"dyn-clone",
|
||||
"futures",
|
||||
"libc",
|
||||
"log",
|
||||
"parking_lot 0.12.5",
|
||||
"rand 0.9.2",
|
||||
"serde",
|
||||
"socket2 0.5.10",
|
||||
"stun-format",
|
||||
"tachyonix",
|
||||
"tokio",
|
||||
"windows-sys 0.60.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustc-hash"
|
||||
version = "2.1.1"
|
||||
@@ -4528,6 +4406,26 @@ dependencies = [
|
||||
"untrusted",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustp2p-core"
|
||||
version = "0.1.1"
|
||||
source = "git+https://github.com/rustp2p/rustp2p#69f67f11bd76db219a2fca86943b01150e175781"
|
||||
dependencies = [
|
||||
"bytes",
|
||||
"dashmap",
|
||||
"dyn-clone",
|
||||
"if-addrs",
|
||||
"libc",
|
||||
"log",
|
||||
"parking_lot 0.12.5",
|
||||
"rand 0.10.2",
|
||||
"serde",
|
||||
"socket2",
|
||||
"stun-format",
|
||||
"tokio",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "rustversion"
|
||||
version = "1.0.22"
|
||||
@@ -4609,12 +4507,6 @@ dependencies = [
|
||||
"syn 2.0.114",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "scoped-tls"
|
||||
version = "1.0.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294"
|
||||
|
||||
[[package]]
|
||||
name = "scopeguard"
|
||||
version = "1.2.0"
|
||||
@@ -4911,15 +4803,6 @@ dependencies = [
|
||||
"digest 0.11.3",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "sharded-slab"
|
||||
version = "0.1.7"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"
|
||||
dependencies = [
|
||||
"lazy_static",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "shlex"
|
||||
version = "1.3.0"
|
||||
@@ -4976,16 +4859,6 @@ version = "1.15.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.5.10"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e22376abed350d73dd1cd119b57ffccad95b4e585a7cda43e286245ce23c0678"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"windows-sys 0.52.0",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "socket2"
|
||||
version = "0.6.2"
|
||||
@@ -5200,19 +5073,6 @@ dependencies = [
|
||||
"version-compare",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tachyonix"
|
||||
version = "0.3.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "86c3eafa053bbcc63bb4bfc5eb26362a33ea0bc2e589f28bce00287d1c167d45"
|
||||
dependencies = [
|
||||
"async-event",
|
||||
"crossbeam-utils",
|
||||
"diatomic-waker",
|
||||
"futures-core",
|
||||
"pin-project-lite",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tao"
|
||||
version = "0.35.3"
|
||||
@@ -5247,7 +5107,7 @@ dependencies = [
|
||||
"tao-macros",
|
||||
"unicode-segmentation",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"windows-core 0.61.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
@@ -5329,7 +5189,7 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"window-vibrancy",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5428,7 +5288,7 @@ dependencies = [
|
||||
"tauri-plugin",
|
||||
"thiserror 2.0.18",
|
||||
"url",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"zbus",
|
||||
]
|
||||
|
||||
@@ -5513,7 +5373,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -5538,7 +5398,7 @@ dependencies = [
|
||||
"url",
|
||||
"webkit2gtk",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"wry",
|
||||
]
|
||||
|
||||
@@ -5690,15 +5550,6 @@ dependencies = [
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "thread_local"
|
||||
version = "1.1.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"
|
||||
dependencies = [
|
||||
"cfg-if",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "time"
|
||||
version = "0.3.47"
|
||||
@@ -5769,7 +5620,7 @@ dependencies = [
|
||||
"parking_lot 0.12.5",
|
||||
"pin-project-lite",
|
||||
"signal-hook-registry",
|
||||
"socket2 0.6.2",
|
||||
"socket2",
|
||||
"tokio-macros",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
@@ -6031,36 +5882,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
||||
dependencies = [
|
||||
"once_cell",
|
||||
"valuable",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-log"
|
||||
version = "0.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"
|
||||
dependencies = [
|
||||
"log",
|
||||
"once_cell",
|
||||
"tracing-core",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "tracing-subscriber"
|
||||
version = "0.3.22"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2f30143827ddab0d256fd843b7a66d164e9f271cfa0dde49142c5ca0ca291f1e"
|
||||
dependencies = [
|
||||
"matchers",
|
||||
"nu-ansi-term",
|
||||
"once_cell",
|
||||
"regex-automata",
|
||||
"sharded-slab",
|
||||
"smallvec",
|
||||
"thread_local",
|
||||
"tracing",
|
||||
"tracing-core",
|
||||
"tracing-log",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
@@ -6314,12 +6135,6 @@ dependencies = [
|
||||
"wasm-bindgen",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "valuable"
|
||||
version = "0.1.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
|
||||
|
||||
[[package]]
|
||||
name = "version-compare"
|
||||
version = "0.2.1"
|
||||
@@ -6358,12 +6173,12 @@ dependencies = [
|
||||
"rcgen",
|
||||
"reed-solomon-erasure",
|
||||
"ring",
|
||||
"rust-p2p-core",
|
||||
"rustls",
|
||||
"rustls-native-certs",
|
||||
"rustp2p-core",
|
||||
"serde",
|
||||
"sha2 0.11.0",
|
||||
"socket2 0.6.2",
|
||||
"socket2",
|
||||
"subtle",
|
||||
"tcp_ip",
|
||||
"time",
|
||||
@@ -6503,12 +6318,6 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "waker-fn"
|
||||
version = "1.2.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "317211a0dc0ceedd78fb2ca9a44aed3d7b9b26f81870d485c07122b4350673b7"
|
||||
|
||||
[[package]]
|
||||
name = "walkdir"
|
||||
version = "2.5.0"
|
||||
@@ -6708,7 +6517,7 @@ checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"
|
||||
dependencies = [
|
||||
"webview2-com-macros",
|
||||
"webview2-com-sys",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"windows-core 0.61.2",
|
||||
"windows-implement",
|
||||
"windows-interface",
|
||||
@@ -6732,7 +6541,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
|
||||
dependencies = [
|
||||
"thiserror 2.0.18",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"windows-core 0.61.2",
|
||||
]
|
||||
|
||||
@@ -6800,15 +6609,6 @@ dependencies = [
|
||||
"windows-version",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.48.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f"
|
||||
dependencies = [
|
||||
"windows-targets 0.48.5",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "windows"
|
||||
version = "0.61.3"
|
||||
@@ -7372,7 +7172,7 @@ dependencies = [
|
||||
"webkit2gtk",
|
||||
"webkit2gtk-sys",
|
||||
"webview2-com",
|
||||
"windows 0.61.3",
|
||||
"windows",
|
||||
"windows-core 0.61.2",
|
||||
"windows-version",
|
||||
"x11-dl",
|
||||
|
||||
+1
-1
@@ -12,7 +12,7 @@ futures.workspace = true
|
||||
|
||||
tun-rs = { version = "2", features = ["async", "async_framed"] }
|
||||
|
||||
rust-p2p-core = { version="0.4" }
|
||||
rustp2p-core = { git = "https://github.com/rustp2p/rustp2p" }
|
||||
tcp_ip = "0.2"
|
||||
|
||||
anyhow.workspace = true
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::context::{AppState, NetworkAddr, PacketLossInfo, ServerNodeInfo, Traf
|
||||
use crate::protocol::control_message::ClientSimpleInfo;
|
||||
use crate::tunnel_core::p2p::route_table::Route;
|
||||
use crate::tunnel_core::server::rpc::ServerRPC;
|
||||
use rust_p2p_core::nat::NatInfo;
|
||||
use rustp2p_core::nat::NatInfo;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
#[derive(Clone)]
|
||||
|
||||
@@ -5,7 +5,7 @@ use crate::tls::verifier::CertValidationMode;
|
||||
use crate::tunnel_core::server::transport::config::{ConnectRegConfig, ProtocolAddress};
|
||||
use anyhow::bail;
|
||||
use ipnet::Ipv4Net;
|
||||
use rust_p2p_core::route::ConnectProtocol;
|
||||
use rustp2p_core::route_table::Protocol;
|
||||
use std::collections::HashSet;
|
||||
use std::fmt::{Display, Formatter};
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
@@ -113,14 +113,13 @@ impl PeerAddress {
|
||||
self.address
|
||||
}
|
||||
|
||||
pub(crate) fn endpoints(&self) -> Vec<(ConnectProtocol, SocketAddr)> {
|
||||
pub(crate) fn endpoints(&self) -> Vec<(Protocol, SocketAddr)> {
|
||||
match self.protocol {
|
||||
PeerProtocol::Both => vec![
|
||||
(ConnectProtocol::TCP, self.address),
|
||||
(ConnectProtocol::UDP, self.address),
|
||||
],
|
||||
PeerProtocol::Tcp => vec![(ConnectProtocol::TCP, self.address)],
|
||||
PeerProtocol::Udp => vec![(ConnectProtocol::UDP, self.address)],
|
||||
PeerProtocol::Both => {
|
||||
vec![(Protocol::TCP, self.address), (Protocol::UDP, self.address)]
|
||||
}
|
||||
PeerProtocol::Tcp => vec![(Protocol::TCP, self.address)],
|
||||
PeerProtocol::Udp => vec![(Protocol::UDP, self.address)],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -308,7 +307,7 @@ impl Config {
|
||||
pub(crate) fn to_connect_config(
|
||||
&self,
|
||||
index: usize,
|
||||
default_interface: Option<rust_p2p_core::socket::LocalInterface>,
|
||||
default_interface: Option<rustp2p_core::socket::LocalInterface>,
|
||||
registration_ip: crate::tunnel_core::server::transport::config::SharedRegistrationIp,
|
||||
) -> ConnectRegConfig {
|
||||
ConnectRegConfig {
|
||||
|
||||
@@ -7,8 +7,8 @@ use crate::tunnel_core::p2p::route_table::RouteTable;
|
||||
use crate::tunnel_core::server::transport::config::ProtocolAddress;
|
||||
use ipnet::Ipv4Net;
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rust_p2p_core::nat::NatInfo;
|
||||
use rust_p2p_core::route::RouteKey;
|
||||
use rustp2p_core::nat::NatInfo;
|
||||
use rustp2p_core::route_table::RouteKey;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::HashMap;
|
||||
use std::net::Ipv4Addr;
|
||||
|
||||
+12
-24
@@ -1,7 +1,5 @@
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rust_p2p_core::nat::{NatInfo, NatType};
|
||||
use rust_p2p_core::route::Index;
|
||||
use rust_p2p_core::tunnel::udp::UDPIndex;
|
||||
use rustp2p_core::nat::{NatInfo, NatType};
|
||||
use std::collections::HashMap;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
@@ -49,19 +47,19 @@ impl MyNatInfo {
|
||||
cb();
|
||||
}
|
||||
}
|
||||
pub fn update_public_addr(&self, index: Index, addr: SocketAddr) {
|
||||
pub fn update_public_addr(&self, addr: SocketAddr) {
|
||||
let (ip, port) = if let Some(r) = mapping_addr(addr) {
|
||||
r
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
log::debug!("public_addr:{},{},index={index:?}", ip, port);
|
||||
log::debug!("public_addr:{ip},{port}");
|
||||
let changed = {
|
||||
let mut guard = self.nat_info.write();
|
||||
let Some(info) = guard.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if !rust_p2p_core::extend::addr::is_ipv4_global(&ip) {
|
||||
if !rustp2p_core::util::addr::is_ipv4_global(&ip) {
|
||||
log::debug!("not public addr: {addr:?}");
|
||||
return;
|
||||
}
|
||||
@@ -69,21 +67,10 @@ impl MyNatInfo {
|
||||
if !info.public_ips.contains(&ip) {
|
||||
info.public_ips.push(ip);
|
||||
}
|
||||
match index {
|
||||
Index::Udp(index) => {
|
||||
let index = match index {
|
||||
UDPIndex::MainV4(index) => index,
|
||||
UDPIndex::MainV6(index) => index,
|
||||
UDPIndex::SubV4(_) => return,
|
||||
};
|
||||
if let Some(p) = info.public_udp_ports.get_mut(index) {
|
||||
*p = port;
|
||||
}
|
||||
}
|
||||
Index::Tcp(_) => {
|
||||
info.public_tcp_port = port;
|
||||
}
|
||||
_ => {}
|
||||
if let Some(public_port) = info.public_udp_ports.first_mut() {
|
||||
*public_port = port;
|
||||
} else {
|
||||
info.public_udp_ports.push(port);
|
||||
}
|
||||
nat_identity_changed(&old, info)
|
||||
}; // 写锁在此释放
|
||||
@@ -107,7 +94,7 @@ impl MyNatInfo {
|
||||
info.public_tcp_port = 0;
|
||||
return;
|
||||
}
|
||||
if !rust_p2p_core::extend::addr::is_ipv4_global(&ip) {
|
||||
if !rustp2p_core::util::addr::is_ipv4_global(&ip) {
|
||||
log::debug!("not public addr: {addr:?}");
|
||||
return;
|
||||
}
|
||||
@@ -250,6 +237,7 @@ mod tests {
|
||||
local_udp_ports: vec![],
|
||||
local_tcp_port: 0,
|
||||
public_tcp_port: 0,
|
||||
stun_mapped_ports: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
@@ -430,13 +418,13 @@ mod tests {
|
||||
|
||||
let addr: SocketAddr = "8.8.8.8:2222".parse().unwrap();
|
||||
// 对称 NAT:公网 IP 不变、仅同索引端口更新 → 不触发
|
||||
nat.update_public_addr(Index::Udp(UDPIndex::MainV4(0)), addr);
|
||||
nat.update_public_addr(addr);
|
||||
assert_eq!(notified.load(Ordering::SeqCst), 0);
|
||||
|
||||
// Cone:端口更新 → 触发
|
||||
nat.replace_nat_info(nat_info(NatType::Cone, vec![exit_ip], vec![1000], local));
|
||||
assert_eq!(notified.load(Ordering::SeqCst), 1);
|
||||
nat.update_public_addr(Index::Udp(UDPIndex::MainV4(0)), addr);
|
||||
nat.update_public_addr(addr);
|
||||
assert_eq!(notified.load(Ordering::SeqCst), 2);
|
||||
}
|
||||
}
|
||||
@@ -123,7 +123,6 @@ impl NetworkManager {
|
||||
peer_address: config.peer_address.clone(),
|
||||
turn: turn.clone(),
|
||||
default_interface: default_interface.clone(),
|
||||
outbound_interface_name: canonical_interface_name,
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -5,7 +5,7 @@ use pnet_packet::Packet;
|
||||
use pnet_packet::icmp::echo_reply::{Identifier, SequenceNumber};
|
||||
use pnet_packet::icmp::{IcmpPacket, IcmpTypes};
|
||||
use pnet_packet::ipv4::Ipv4Packet;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
@@ -8,7 +8,7 @@ use anyhow::Context;
|
||||
use bytes::BytesMut;
|
||||
use pnet_packet::ip::IpNextHeaderProtocol;
|
||||
use pnet_packet::ipv4::Ipv4Packet;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::context::SharedNetworkAddr;
|
||||
use crate::utils::socket::connect_tcp;
|
||||
use crate::utils::task_control::TaskGroup;
|
||||
use anyhow::Context;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::fmt::Debug;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
|
||||
use tcp_ip::IpStack;
|
||||
|
||||
@@ -2,7 +2,7 @@ use crate::utils::task_control::{SubTask, TaskGroup};
|
||||
use anyhow::Context;
|
||||
use bytes::Bytes;
|
||||
use futures::{SinkExt, StreamExt};
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::collections::HashMap;
|
||||
use std::fmt::Debug;
|
||||
use std::net::SocketAddr;
|
||||
|
||||
@@ -10,10 +10,10 @@ use std::net::{Ipv4Addr, Ipv6Addr};
|
||||
use crate::protocol::ProtoToBytesMut;
|
||||
pub use proto::*;
|
||||
|
||||
pub fn encode_nat_info(nat_info: &rust_p2p_core::nat::NatInfo) -> proto::NatInfo {
|
||||
pub fn encode_nat_info(nat_info: &rustp2p_core::nat::NatInfo) -> proto::NatInfo {
|
||||
let nat_type = match nat_info.nat_type {
|
||||
rust_p2p_core::nat::NatType::Cone => proto::NatType::Cone,
|
||||
rust_p2p_core::nat::NatType::Symmetric => proto::NatType::Symmetric,
|
||||
rustp2p_core::nat::NatType::Cone => proto::NatType::Cone,
|
||||
rustp2p_core::nat::NatType::Symmetric => proto::NatType::Symmetric,
|
||||
};
|
||||
|
||||
proto::NatInfo {
|
||||
@@ -36,10 +36,10 @@ pub fn encode_nat_info(nat_info: &rust_p2p_core::nat::NatInfo) -> proto::NatInfo
|
||||
public_tcp_port: nat_info.public_tcp_port.into(),
|
||||
}
|
||||
}
|
||||
pub fn decode_nat_info(msg: proto::NatInfo) -> anyhow::Result<rust_p2p_core::nat::NatInfo> {
|
||||
pub fn decode_nat_info(msg: proto::NatInfo) -> anyhow::Result<rustp2p_core::nat::NatInfo> {
|
||||
let nat_type = match msg.nat_type() {
|
||||
proto::NatType::Cone => rust_p2p_core::nat::NatType::Cone,
|
||||
proto::NatType::Symmetric => rust_p2p_core::nat::NatType::Symmetric,
|
||||
proto::NatType::Cone => rustp2p_core::nat::NatType::Cone,
|
||||
proto::NatType::Symmetric => rustp2p_core::nat::NatType::Symmetric,
|
||||
};
|
||||
let ipv6: Option<[u8; 16]> = msg.ipv6.and_then(|v| v.as_slice().try_into().ok());
|
||||
|
||||
@@ -56,7 +56,7 @@ pub fn decode_nat_info(msg: proto::NatInfo) -> anyhow::Result<rust_p2p_core::nat
|
||||
let local_udp_ports: Result<Vec<_>, _> =
|
||||
msg.local_udp_ports.into_iter().map(validate_port).collect();
|
||||
|
||||
Ok(rust_p2p_core::nat::NatInfo {
|
||||
Ok(rustp2p_core::nat::NatInfo {
|
||||
nat_type,
|
||||
public_ips: msg.public_ips.into_iter().map(|v| v.into()).collect(),
|
||||
public_udp_ports: public_udp_ports?,
|
||||
@@ -73,11 +73,12 @@ pub fn decode_nat_info(msg: proto::NatInfo) -> anyhow::Result<rust_p2p_core::nat
|
||||
local_udp_ports: local_udp_ports?,
|
||||
local_tcp_port: validate_port(msg.local_tcp_port)?,
|
||||
public_tcp_port: validate_port(msg.public_tcp_port)?,
|
||||
stun_mapped_ports: vec![],
|
||||
})
|
||||
}
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct PunchInfo {
|
||||
pub nat_info: rust_p2p_core::nat::NatInfo,
|
||||
pub nat_info: rustp2p_core::nat::NatInfo,
|
||||
}
|
||||
|
||||
impl PunchInfo {
|
||||
|
||||
@@ -9,8 +9,8 @@ use crate::protocol::transmission::TransmissionBytes;
|
||||
use crate::tunnel_core::outbound::BasicOutbound;
|
||||
use crate::tunnel_core::p2p::route_table::{Route, RouteTable};
|
||||
use anyhow::bail;
|
||||
use rust_p2p_core::route::RouteKey;
|
||||
use rust_p2p_core::tunnel::Tunnel;
|
||||
use rustp2p_core::endpoint::TunnelWriteHalf;
|
||||
use rustp2p_core::route_table::RouteKey;
|
||||
use std::net::{IpAddr, Ipv4Addr};
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -95,7 +95,7 @@ impl P2pInboundHandler {
|
||||
&self,
|
||||
buf: TransmissionBytes,
|
||||
route_key: RouteKey,
|
||||
tunnel: &mut Tunnel,
|
||||
tunnel: &TunnelWriteHalf,
|
||||
) {
|
||||
if let Err(e) = self.next_handle_impl(buf, route_key, tunnel).await {
|
||||
log::warn!(
|
||||
@@ -108,7 +108,7 @@ impl P2pInboundHandler {
|
||||
&self,
|
||||
buf: TransmissionBytes,
|
||||
route_key: RouteKey,
|
||||
tunnel: &mut Tunnel,
|
||||
tunnel: &TunnelWriteHalf,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut net_packet = NetPacket::new(buf)?;
|
||||
let _ = net_packet.msg_type()?;
|
||||
@@ -163,7 +163,7 @@ impl P2pInboundHandler {
|
||||
&self,
|
||||
net: &crate::context::NetworkAddr,
|
||||
route_key: RouteKey,
|
||||
tunnel: &mut Tunnel,
|
||||
tunnel: &TunnelWriteHalf,
|
||||
mut net_packet: NetPacket<TransmissionBytes>,
|
||||
) -> anyhow::Result<()> {
|
||||
if net_packet.msg_type()? != MsgType::Quic {
|
||||
@@ -178,7 +178,7 @@ impl P2pInboundHandler {
|
||||
&self,
|
||||
net: &crate::context::NetworkAddr,
|
||||
route_key: RouteKey,
|
||||
tunnel: &mut Tunnel,
|
||||
tunnel: &TunnelWriteHalf,
|
||||
net_packet: NetPacket<TransmissionBytes>,
|
||||
) -> anyhow::Result<()> {
|
||||
let msg_type = net_packet.msg_type()?;
|
||||
@@ -208,7 +208,7 @@ impl P2pInboundHandler {
|
||||
&self,
|
||||
net: &crate::context::NetworkAddr,
|
||||
route_key: RouteKey,
|
||||
tunnel: &mut Tunnel,
|
||||
tunnel: &TunnelWriteHalf,
|
||||
net_packet: NetPacket<TransmissionBytes>,
|
||||
ctx: &PacketContext,
|
||||
) -> anyhow::Result<()> {
|
||||
@@ -235,9 +235,7 @@ impl P2pInboundHandler {
|
||||
packet.set_dest_id(ctx.src_ip.into());
|
||||
packet.set_payload(net_packet.payload())?;
|
||||
self.packet_crypto.encrypt_in_place(&mut packet)?;
|
||||
tunnel
|
||||
.send_to(packet.into_bytes().into_buffer(), route_key.addr())
|
||||
.await?;
|
||||
tunnel.send(packet.into_bytes().into_buffer()).await?;
|
||||
}
|
||||
MsgType::Pong => {
|
||||
if net_packet.payload().len() >= 8 {
|
||||
@@ -274,7 +272,7 @@ impl P2pInboundHandler {
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if let IpAddr::V4(ip) = route_key.addr().ip()
|
||||
if let IpAddr::V4(ip) = route_key.peer_addr().ip()
|
||||
&& self.network_contains(&ip)
|
||||
{
|
||||
log::info!("===========loop PunchReq {route_key:?} {:?}", ctx.src_ip);
|
||||
@@ -294,9 +292,7 @@ impl P2pInboundHandler {
|
||||
)?;
|
||||
|
||||
self.packet_crypto.encrypt_in_place(&mut packet)?;
|
||||
tunnel
|
||||
.send_to(packet.into_bytes().into_buffer(), route_key.addr())
|
||||
.await?;
|
||||
tunnel.send(packet.into_bytes().into_buffer()).await?;
|
||||
}
|
||||
MsgType::PunchRes => {
|
||||
if !allow_punch(&self.turn, &ctx.src_ip) {
|
||||
@@ -310,7 +306,7 @@ impl P2pInboundHandler {
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
if let IpAddr::V4(ip) = route_key.addr().ip()
|
||||
if let IpAddr::V4(ip) = route_key.peer_addr().ip()
|
||||
&& self.network_contains(&ip)
|
||||
{
|
||||
log::info!("===========loop PunchRes {route_key:?} {:?}", ctx.src_ip);
|
||||
@@ -344,9 +340,7 @@ impl P2pInboundHandler {
|
||||
self.packet_crypto.encrypt_reserve(),
|
||||
)?;
|
||||
self.packet_crypto.encrypt_in_place(&mut packet)?;
|
||||
tunnel
|
||||
.send_to(packet.into_bytes().into_buffer(), route_key.addr())
|
||||
.await?;
|
||||
tunnel.send(packet.into_bytes().into_buffer()).await?;
|
||||
}
|
||||
MsgType::DirectConnectRes => {
|
||||
if !valid_punch_source(net, ctx.src_ip) {
|
||||
@@ -389,9 +383,7 @@ impl P2pInboundHandler {
|
||||
packet.set_src_id(ctx.dest_ip.into());
|
||||
packet.set_dest_id(ctx.src_ip.into());
|
||||
self.packet_crypto.encrypt_in_place(&mut packet)?;
|
||||
tunnel
|
||||
.send_to(packet.into_bytes().into_buffer(), route_key.addr())
|
||||
.await?;
|
||||
tunnel.send(packet.into_bytes().into_buffer()).await?;
|
||||
}
|
||||
MsgType::RelayProbeReply => {
|
||||
if !valid_relay_probe(net, ctx) {
|
||||
@@ -413,16 +405,24 @@ impl P2pInboundHandler {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn tcp_disconnect(&self, route_key: RouteKey) {
|
||||
if let Some(ip) = self.route_table.get_id_by_route_key(&route_key) {
|
||||
self.route_table.remove_route(&ip, &route_key);
|
||||
}
|
||||
pub fn tunnel_disconnect(&self, route_key: RouteKey) {
|
||||
cleanup_tunnel_routes(&self.route_table, &self.packet_loss_stats, &route_key);
|
||||
}
|
||||
}
|
||||
|
||||
fn cleanup_tunnel_routes(
|
||||
route_table: &RouteTable,
|
||||
packet_loss_stats: &PacketLossStats,
|
||||
route_key: &RouteKey,
|
||||
) {
|
||||
let removed = route_table.remove_route_key(route_key);
|
||||
packet_loss_stats.remove_batch(&removed);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rustp2p_core::route_table::Protocol;
|
||||
|
||||
fn network() -> NetworkAddr {
|
||||
NetworkAddr {
|
||||
@@ -494,4 +494,37 @@ mod tests {
|
||||
assert!(!valid_relay_probe(&net, &invalid));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tunnel_cleanup_removes_all_packet_loss_stats_for_the_route_key() {
|
||||
let route_table = RouteTable::new();
|
||||
let packet_loss_stats = PacketLossStats::default();
|
||||
let direct = Ipv4Addr::new(10, 26, 0, 3);
|
||||
let relayed = Ipv4Addr::new(10, 26, 0, 4);
|
||||
let route_key = RouteKey::new(
|
||||
Protocol::UDP,
|
||||
"127.0.0.1:2000".parse().unwrap(),
|
||||
"127.0.0.1:3000".parse().unwrap(),
|
||||
);
|
||||
|
||||
route_table.add_owner_route(direct, route_key);
|
||||
route_table.add_relay_route(relayed, Route::from_default_rt(route_key, 2));
|
||||
packet_loss_stats.record_sent(direct, route_key);
|
||||
packet_loss_stats.record_sent(relayed, route_key);
|
||||
|
||||
cleanup_tunnel_routes(&route_table, &packet_loss_stats, &route_key);
|
||||
|
||||
assert!(!route_table.exists(&direct));
|
||||
assert!(!route_table.exists(&relayed));
|
||||
assert!(
|
||||
packet_loss_stats
|
||||
.get_loss_info(&direct, &route_key)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
packet_loss_stats
|
||||
.get_loss_info(&relayed, &route_key)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -3,29 +3,47 @@ use crate::protocol::ip_packet_protocol::NetPacket;
|
||||
use crate::protocol::transmission::TransmissionBytes;
|
||||
use crate::tunnel_core::p2p::route_table::{Route, RouteTable};
|
||||
use bytes::Bytes;
|
||||
use rust_p2p_core::route::ConnectProtocol;
|
||||
use rust_p2p_core::route::RouteKey;
|
||||
use rust_p2p_core::tunnel::SocketManager;
|
||||
use parking_lot::RwLock;
|
||||
use rustp2p_core::endpoint::TunnelWriteHalf;
|
||||
use rustp2p_core::punch::Puncher;
|
||||
use rustp2p_core::route_table::{Protocol, RouteKey};
|
||||
use std::collections::HashMap;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct P2pOutbound {
|
||||
manager: SocketManager,
|
||||
puncher: Puncher,
|
||||
tunnels: Arc<RwLock<HashMap<RouteKey, TunnelWriteHalf>>>,
|
||||
route_table: RouteTable,
|
||||
packet_crypto: PacketCrypto,
|
||||
}
|
||||
|
||||
impl P2pOutbound {
|
||||
pub fn new(
|
||||
manager: SocketManager,
|
||||
route_table: RouteTable,
|
||||
packet_crypto: PacketCrypto,
|
||||
) -> Self {
|
||||
pub fn new(puncher: Puncher, route_table: RouteTable, packet_crypto: PacketCrypto) -> Self {
|
||||
Self {
|
||||
manager,
|
||||
puncher,
|
||||
tunnels: Arc::new(RwLock::new(HashMap::new())),
|
||||
route_table,
|
||||
packet_crypto,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn register_tunnel(&self, route_key: RouteKey, writer: TunnelWriteHalf) {
|
||||
self.tunnels.write().insert(route_key, writer);
|
||||
}
|
||||
|
||||
pub fn remove_tunnel(&self, route_key: &RouteKey) {
|
||||
self.tunnels.write().remove(route_key);
|
||||
}
|
||||
|
||||
fn tunnel(&self, route_key: &RouteKey) -> anyhow::Result<TunnelWriteHalf> {
|
||||
self.tunnels
|
||||
.read()
|
||||
.get(route_key)
|
||||
.cloned()
|
||||
.ok_or_else(|| anyhow::anyhow!("tunnel not found for {route_key}"))
|
||||
}
|
||||
pub fn encrypt_reserve(&self) -> usize {
|
||||
self.packet_crypto.encrypt_reserve()
|
||||
}
|
||||
@@ -51,7 +69,7 @@ impl P2pOutbound {
|
||||
buf: NetPacket<Bytes>,
|
||||
route_key: &RouteKey,
|
||||
) -> anyhow::Result<()> {
|
||||
self.manager.send_to(buf.into_buffer(), route_key).await?;
|
||||
self.tunnel(route_key)?.send(buf.into_buffer()).await?;
|
||||
Ok(())
|
||||
}
|
||||
pub async fn send_to(
|
||||
@@ -60,8 +78,8 @@ impl P2pOutbound {
|
||||
route_key: &RouteKey,
|
||||
) -> anyhow::Result<()> {
|
||||
self.packet_crypto.encrypt_in_place(&mut buf)?;
|
||||
self.manager
|
||||
.send_to(buf.into_buffer().into_bytes().freeze(), route_key)
|
||||
self.tunnel(route_key)?
|
||||
.send(buf.into_buffer().into_bytes().freeze())
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -72,20 +90,22 @@ impl P2pOutbound {
|
||||
route_key: &RouteKey,
|
||||
) -> anyhow::Result<()> {
|
||||
self.packet_crypto.encrypt_in_place(&mut buf)?;
|
||||
self.manager
|
||||
.try_send_to(buf.into_buffer().into_bytes().freeze(), route_key)?;
|
||||
self.tunnel(route_key)?
|
||||
.try_send(buf.into_buffer().into_bytes().freeze())?;
|
||||
Ok(())
|
||||
}
|
||||
pub async fn send_to_addr(
|
||||
&self,
|
||||
mut buf: NetPacket<TransmissionBytes>,
|
||||
protocol: ConnectProtocol,
|
||||
protocol: Protocol,
|
||||
address: SocketAddr,
|
||||
) -> anyhow::Result<()> {
|
||||
self.packet_crypto.encrypt_in_place(&mut buf)?;
|
||||
self.manager
|
||||
.send_to_addr(protocol, buf.into_buffer().into_bytes().freeze(), address)
|
||||
.await?;
|
||||
let bytes = buf.into_buffer().into_bytes().freeze();
|
||||
match protocol {
|
||||
Protocol::UDP => self.puncher.send_to(&bytes, address)?,
|
||||
Protocol::TCP => self.puncher.connect_tcp(address, Some(bytes)).await?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn get_route_by_id(&self, id: &Ipv4Addr) -> Option<Route> {
|
||||
@@ -148,8 +168,8 @@ impl P2pOutbound {
|
||||
continue;
|
||||
};
|
||||
if self
|
||||
.manager
|
||||
.try_send_to(buf.source_buf().clone(), &route.route_key())
|
||||
.tunnel(&route.route_key())
|
||||
.and_then(|tunnel| Ok(tunnel.try_send(buf.source_buf().clone())?))
|
||||
.is_ok()
|
||||
{
|
||||
list.push(*id);
|
||||
@@ -161,3 +181,61 @@ impl P2pOutbound {
|
||||
list
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use rustp2p_core::endpoint::{Config, TunnelIncoming};
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[tokio::test]
|
||||
async fn registered_writer_supports_send_try_send_and_removal() {
|
||||
let mut incoming = TunnelIncoming::bind(Config::udp(0).enable_ipv6(false))
|
||||
.await
|
||||
.unwrap();
|
||||
let target = SocketAddr::new(
|
||||
"127.0.0.1".parse().unwrap(),
|
||||
incoming.local_addr().unwrap().port(),
|
||||
);
|
||||
let client = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
client.send_to(b"open", target).await.unwrap();
|
||||
|
||||
let tunnel = incoming.next().await.unwrap();
|
||||
let route_key = tunnel.route_key();
|
||||
let (_reader, writer) = tunnel.split();
|
||||
let outbound = P2pOutbound::new(
|
||||
incoming.puncher(),
|
||||
RouteTable::new(),
|
||||
PacketCrypto::new_from_str(None).unwrap(),
|
||||
);
|
||||
outbound.register_tunnel(route_key, writer);
|
||||
|
||||
outbound
|
||||
.tunnel(&route_key)
|
||||
.unwrap()
|
||||
.send(Bytes::from_static(b"send"))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut buffer = [0; 16];
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(2), client.recv_from(&mut buffer))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buffer[..len], b"send");
|
||||
|
||||
outbound
|
||||
.tunnel(&route_key)
|
||||
.unwrap()
|
||||
.try_send(Bytes::from_static(b"try_send"))
|
||||
.unwrap();
|
||||
let (len, _) = tokio::time::timeout(Duration::from_secs(2), client.recv_from(&mut buffer))
|
||||
.await
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
assert_eq!(&buffer[..len], b"try_send");
|
||||
|
||||
outbound.remove_tunnel(&route_key);
|
||||
assert!(outbound.tunnel(&route_key).is_err());
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
use parking_lot::{Mutex, RwLock};
|
||||
use rust_p2p_core::route::{ConnectProtocol, DEFAULT_RTT, RouteKey};
|
||||
use rustp2p_core::route_table::{DEFAULT_RTT, Protocol, RouteKey};
|
||||
use std::collections::HashMap;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
@@ -165,13 +165,13 @@ impl RouteTable {
|
||||
}
|
||||
|
||||
/// 检查指定传输协议和物理地址是否已有直连路由。
|
||||
pub fn has_direct_endpoint(&self, protocol: ConnectProtocol, address: SocketAddr) -> bool {
|
||||
pub fn has_direct_endpoint(&self, protocol: Protocol, address: SocketAddr) -> bool {
|
||||
let guard = self.inner.route_table.read();
|
||||
guard.values().any(|routes| {
|
||||
routes.iter().any(|route| {
|
||||
route.is_direct()
|
||||
&& route.route_key().protocol() == protocol
|
||||
&& route.route_key().addr() == address
|
||||
&& route.route_key().peer_addr() == address
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -204,32 +204,24 @@ impl RouteTable {
|
||||
guard.iter().map(|(k, v)| (*k, v.clone())).collect()
|
||||
}
|
||||
|
||||
/// 根据 RouteKey 查找对应的 IP
|
||||
pub fn get_id_by_route_key(&self, route_key: &RouteKey) -> Option<Ipv4Addr> {
|
||||
let owner_map = self.inner.route_key_owner.lock();
|
||||
owner_map.get(route_key).copied()
|
||||
}
|
||||
|
||||
/// 移除指定 IP 和 RouteKey 的路由
|
||||
pub fn remove_route(&self, id: &Ipv4Addr, route_key: &RouteKey) {
|
||||
/// Removes every logical route carried by one physical tunnel.
|
||||
pub fn remove_route_key(&self, route_key: &RouteKey) -> Vec<(Ipv4Addr, RouteKey)> {
|
||||
let mut table = self.inner.route_table.write();
|
||||
let mut owner_map = self.inner.route_key_owner.lock();
|
||||
let mut time_map = self.inner.route_key_time.lock();
|
||||
let mut removed = Vec::new();
|
||||
|
||||
if let Some(list) = table.get_mut(id) {
|
||||
list.retain(|r| r.route_key() != *route_key);
|
||||
if list.is_empty() {
|
||||
table.remove(id);
|
||||
table.retain(|id, routes| {
|
||||
let old_len = routes.len();
|
||||
routes.retain(|route| route.route_key() != *route_key);
|
||||
if routes.len() != old_len {
|
||||
removed.push((*id, *route_key));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(owner_id) = owner_map.get(route_key)
|
||||
&& owner_id == id
|
||||
{
|
||||
owner_map.remove(route_key);
|
||||
}
|
||||
|
||||
time_map.remove(&(*id, *route_key));
|
||||
!routes.is_empty()
|
||||
});
|
||||
owner_map.remove(route_key);
|
||||
time_map.retain(|(_, key), _| key != route_key);
|
||||
removed
|
||||
}
|
||||
|
||||
/// 移除过期的路由
|
||||
@@ -404,10 +396,60 @@ mod tests {
|
||||
table.add_route(peer, Route::from(key, 1, 25), false);
|
||||
assert!(notify.notified().now_or_never().is_none());
|
||||
|
||||
table.remove_route(&peer, &key);
|
||||
table.remove_route_key(&key);
|
||||
assert!(notify.notified().now_or_never().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remove_route_key_cleans_direct_relay_owner_and_timestamps() {
|
||||
let table = RouteTable::new();
|
||||
let owner = Ipv4Addr::new(10, 0, 0, 2);
|
||||
let relayed = Ipv4Addr::new(10, 0, 0, 3);
|
||||
let unrelated = Ipv4Addr::new(10, 0, 0, 4);
|
||||
let key = RouteKey::new(
|
||||
Protocol::UDP,
|
||||
"127.0.0.1:2000".parse().unwrap(),
|
||||
"127.0.0.1:3000".parse().unwrap(),
|
||||
);
|
||||
let other_key = RouteKey::new(
|
||||
Protocol::TCP,
|
||||
"127.0.0.1:2001".parse().unwrap(),
|
||||
"127.0.0.1:3001".parse().unwrap(),
|
||||
);
|
||||
|
||||
table.add_owner_route(owner, key);
|
||||
table.add_relay_route(relayed, Route::from_default_rt(key, 2));
|
||||
table.add_owner_route(unrelated, other_key);
|
||||
|
||||
assert_eq!(table.inner.route_key_owner.lock().get(&key), Some(&owner));
|
||||
assert_eq!(
|
||||
table
|
||||
.inner
|
||||
.route_key_time
|
||||
.lock()
|
||||
.keys()
|
||||
.filter(|(_, route_key)| *route_key == key)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
|
||||
let mut removed = table.remove_route_key(&key);
|
||||
removed.sort_unstable();
|
||||
assert_eq!(removed, vec![(owner, key), (relayed, key)]);
|
||||
assert!(!table.exists(&owner));
|
||||
assert!(!table.exists(&relayed));
|
||||
assert!(table.exists(&unrelated));
|
||||
assert!(!table.inner.route_key_owner.lock().contains_key(&key));
|
||||
assert!(
|
||||
table
|
||||
.inner
|
||||
.route_key_time
|
||||
.lock()
|
||||
.keys()
|
||||
.all(|(_, route_key)| *route_key != key)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn direct_route_lookup_ignores_higher_scored_relay_route() {
|
||||
let relay = Route::from(RouteKey::default(), 2, 1);
|
||||
|
||||
@@ -1,221 +1,75 @@
|
||||
use crate::context::AppState;
|
||||
use rust_p2p_core::nat::{NatInfo, NatType};
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rust_p2p_core::tunnel::SocketManager;
|
||||
use rust_p2p_core::tunnel::udp::Model;
|
||||
use std::collections::HashMap;
|
||||
use rustp2p_core::nat::NatType;
|
||||
use rustp2p_core::punch::Puncher;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::collections::HashSet;
|
||||
use std::io;
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
|
||||
use std::time::Duration;
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
|
||||
pub async fn my_nat_info(
|
||||
app_context: AppState,
|
||||
socket_manager: SocketManager,
|
||||
default_interface: Option<LocalInterface>,
|
||||
outbound_interface_name: Option<String>,
|
||||
) {
|
||||
pub async fn my_nat_info(app_context: AppState, puncher: Puncher) {
|
||||
loop {
|
||||
my_nat_info_impl(
|
||||
&app_context,
|
||||
&socket_manager,
|
||||
default_interface.as_ref(),
|
||||
outbound_interface_name.as_deref(),
|
||||
)
|
||||
.await;
|
||||
my_nat_info_impl(&app_context, &puncher).await;
|
||||
tokio::time::sleep(Duration::from_secs(60 * 30)).await;
|
||||
}
|
||||
}
|
||||
async fn my_nat_info_impl(
|
||||
app_context: &AppState,
|
||||
socket_manager: &SocketManager,
|
||||
default_interface: Option<&LocalInterface>,
|
||||
outbound_interface_name: Option<&str>,
|
||||
) {
|
||||
let network = app_context.network.network();
|
||||
let mut local_ipv4s = Vec::new();
|
||||
let mut local_ipv6 = Vec::new();
|
||||
match getifaddrs::getifaddrs() {
|
||||
Ok(addrs) => {
|
||||
for x in addrs {
|
||||
if outbound_interface_name.is_some_and(|name| x.name != name) {
|
||||
continue;
|
||||
}
|
||||
let Some(ip) = x.address.ip_addr() else {
|
||||
continue;
|
||||
};
|
||||
if ip.is_loopback() {
|
||||
continue;
|
||||
}
|
||||
if ip.is_unspecified() {
|
||||
continue;
|
||||
}
|
||||
if ip.is_multicast() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match ip {
|
||||
IpAddr::V4(addr) => {
|
||||
if addr.is_documentation() {
|
||||
continue;
|
||||
}
|
||||
if addr.is_broadcast() {
|
||||
continue;
|
||||
}
|
||||
if let Some(network) = &network
|
||||
&& network.contains(&addr)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
local_ipv4s.push(addr);
|
||||
}
|
||||
IpAddr::V6(addr) => {
|
||||
if addr.is_unique_local() {
|
||||
continue;
|
||||
}
|
||||
if addr.is_unicast_link_local() {
|
||||
continue;
|
||||
}
|
||||
local_ipv6.push(addr);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("getifaddrs error: {e}");
|
||||
}
|
||||
}
|
||||
log::info!("local_ipv4s: {:?}", local_ipv4s);
|
||||
let detected = if outbound_interface_name.is_none() {
|
||||
rust_p2p_core::extend::addr::local_ipv4()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
log::warn!("local ipv4 failed {e:?}");
|
||||
e
|
||||
})
|
||||
.ok()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let Some((local_ipv4, merged)) = select_local_ipv4(detected, &local_ipv4s) else {
|
||||
log::warn!("未发现可用本机 IPv4 地址,跳过本次 NAT 信息更新");
|
||||
return;
|
||||
};
|
||||
// 保留网卡扫描结果,主地址排在首位
|
||||
local_ipv4s = merged;
|
||||
let mut ipv6 = if outbound_interface_name.is_none() {
|
||||
rust_p2p_core::extend::addr::local_ipv6().await.ok()
|
||||
} else {
|
||||
local_ipv6.first().cloned()
|
||||
};
|
||||
if let Some(addr) = ipv6 {
|
||||
if addr.is_loopback()
|
||||
|| addr.is_unique_local()
|
||||
|| addr.is_unicast_link_local()
|
||||
|| addr.is_unspecified()
|
||||
|| addr.is_multicast()
|
||||
{
|
||||
ipv6 = local_ipv6.first().cloned();
|
||||
}
|
||||
} else {
|
||||
ipv6 = local_ipv6.first().cloned();
|
||||
}
|
||||
let Some(udp_mgr) = socket_manager.udp_socket_manager_as_ref() else {
|
||||
log::warn!("udp socket manager 未就绪,跳过本次 NAT 信息更新");
|
||||
return;
|
||||
};
|
||||
let local_udp_ports = match udp_mgr.local_ports() {
|
||||
Ok(ports) => ports,
|
||||
Err(e) => {
|
||||
log::warn!("获取本地 UDP 端口失败: {e:?},跳过本次 NAT 信息更新");
|
||||
return;
|
||||
}
|
||||
};
|
||||
let local_tcp_port = socket_manager
|
||||
.tcp_socket_manager_as_ref()
|
||||
.map(|m| m.local_addr().port())
|
||||
.unwrap_or_else(|| {
|
||||
log::warn!("tcp socket manager 未就绪,local_tcp_port 置 0");
|
||||
0
|
||||
});
|
||||
log::info!(
|
||||
"local_ipv4={local_ipv4},ipv6={ipv6:?},local_udp_ports:{local_udp_ports:?},local_tcp_port:{local_tcp_port:?}"
|
||||
);
|
||||
let mut public_ports = local_udp_ports.clone();
|
||||
public_ports.fill(0);
|
||||
let mut nat_info = NatInfo {
|
||||
nat_type: NatType::Cone,
|
||||
public_ips: vec![],
|
||||
public_udp_ports: public_ports,
|
||||
mapping_tcp_addr: vec![],
|
||||
mapping_udp_addr: vec![],
|
||||
public_port_range: 0,
|
||||
local_ipv4s,
|
||||
local_ipv4,
|
||||
ipv6,
|
||||
local_udp_ports,
|
||||
local_tcp_port,
|
||||
public_tcp_port: 0,
|
||||
};
|
||||
async fn my_nat_info_impl(app_context: &AppState, puncher: &Puncher) {
|
||||
let mut stun_server = app_context.udp_stun();
|
||||
if stun_server.is_empty() {
|
||||
stun_server = default_udp_stun();
|
||||
}
|
||||
let (nat_type, public_ips, port_range) =
|
||||
rust_p2p_core::stun::stun_test_nat(stun_server, default_interface)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
log::warn!("stun_test_nat {e:?}");
|
||||
(NatType::Cone, vec![], 0)
|
||||
});
|
||||
log::info!("nat_type:{nat_type:?},public_ips:{public_ips:?},port_range={port_range}");
|
||||
nat_info.nat_type = nat_type;
|
||||
nat_info.public_ips = public_ips;
|
||||
nat_info.public_port_range = port_range;
|
||||
app_context.nat_info.replace_nat_info(nat_info);
|
||||
let model = match nat_type {
|
||||
NatType::Cone => Model::Low,
|
||||
NatType::Symmetric => Model::High,
|
||||
};
|
||||
if let Err(e) = udp_mgr.switch_model(model) {
|
||||
log::error!("switch_model error: {e:?}");
|
||||
match puncher.nat_info_with_servers(&stun_server).await {
|
||||
Ok(mut nat_info) => {
|
||||
// STUN NAT classification uses temporary sockets. The public
|
||||
// mapping of the P2P socket is learned separately by sending a
|
||||
// request through Puncher::send_to.
|
||||
// VNT tracks one public mapping for the Puncher-owned main UDP
|
||||
// endpoint and does not expose the core's IPv4/IPv6 socket layout.
|
||||
nat_info.public_udp_ports = vec![0];
|
||||
nat_info.stun_mapped_ports.clear();
|
||||
let nat_type = nat_info.nat_type;
|
||||
log::info!(
|
||||
"nat_type:{nat_type:?},public_ips:{:?},port_range={}",
|
||||
nat_info.public_ips,
|
||||
nat_info.public_port_range
|
||||
);
|
||||
app_context.nat_info.replace_nat_info(nat_info);
|
||||
if let Err(error) = puncher.apply_nat_model(nat_type) {
|
||||
log::error!("apply_nat_model error: {error:?}");
|
||||
}
|
||||
}
|
||||
Err(error) => log::warn!("nat_info_with_servers {error:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确定本机主 IPv4 并把它合并到地址列表首位。
|
||||
/// detected 为路由探测得到的主地址(可能不可用),scanned 为网卡扫描结果。
|
||||
/// 返回 None 表示没有任何可用地址,调用方应跳过本次发布,避免上报 0.0.0.0。
|
||||
fn select_local_ipv4(
|
||||
detected: Option<Ipv4Addr>,
|
||||
scanned: &[Ipv4Addr],
|
||||
) -> Option<(Ipv4Addr, Vec<Ipv4Addr>)> {
|
||||
let primary = detected
|
||||
.filter(|ip| !ip.is_unspecified())
|
||||
.or_else(|| scanned.first().copied())?;
|
||||
let mut list: Vec<Ipv4Addr> = scanned.iter().copied().filter(|a| *a != primary).collect();
|
||||
list.insert(0, primary);
|
||||
Some((primary, list))
|
||||
}
|
||||
|
||||
pub async fn query_udp_public_addr_loop(app_context: AppState, socket_manager: SocketManager) {
|
||||
pub async fn query_udp_public_addr_loop(app_context: AppState, puncher: Puncher) {
|
||||
let mut udp_stun_servers = app_context.udp_stun();
|
||||
if udp_stun_servers.is_empty() {
|
||||
udp_stun_servers = default_udp_stun();
|
||||
}
|
||||
let udp_len = udp_stun_servers.len();
|
||||
let mut udp_count = 0;
|
||||
let stun_request = rust_p2p_core::stun::send_stun_request();
|
||||
let stun_request = rustp2p_core::stun::send_stun_request();
|
||||
loop {
|
||||
if app_context
|
||||
.get_nat_info()
|
||||
.is_some_and(|info| info.nat_type == NatType::Symmetric)
|
||||
{
|
||||
// NAT type can change while the task is alive. Keep polling so
|
||||
// UDP public-port discovery resumes after returning to Cone NAT.
|
||||
tokio::time::sleep(Duration::from_secs(60)).await;
|
||||
continue;
|
||||
}
|
||||
let stun = &udp_stun_servers[udp_count % udp_len];
|
||||
udp_count += 1;
|
||||
match tokio::net::lookup_host(stun.as_str()).await {
|
||||
Ok(mut addr) => {
|
||||
if let Some(addr) = addr.next()
|
||||
&& let Some(w) = socket_manager.udp_socket_manager_as_ref()
|
||||
&& let Err(e) = w.detect_pub_addrs(&stun_request, addr).await
|
||||
&& let Err(e) = puncher.send_to(&stun_request, addr)
|
||||
{
|
||||
log::info!("detect_pub_addrs {e:?} {addr:?}");
|
||||
log::info!("send STUN request {e:?} {addr:?}");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
@@ -236,165 +90,207 @@ pub async fn query_udp_public_addr_loop(app_context: AppState, socket_manager: S
|
||||
|
||||
pub(crate) async fn query_tcp_public_addr_loop(
|
||||
app_context: AppState,
|
||||
socket_manager: SocketManager,
|
||||
local_tcp_port: u16,
|
||||
default_interface: Option<LocalInterface>,
|
||||
) {
|
||||
use rand::RngExt;
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
let tcp_stun_servers = {
|
||||
let servers = app_context.tcp_stun();
|
||||
if servers.is_empty() {
|
||||
default_tcp_stun()
|
||||
} else {
|
||||
servers
|
||||
}
|
||||
};
|
||||
|
||||
if tcp_stun_servers.is_empty() {
|
||||
if local_tcp_port == 0 {
|
||||
log::warn!("P2P TCP listener is disabled; skip TCP public address detection");
|
||||
return;
|
||||
}
|
||||
log::debug!("tcp_stun_servers = {tcp_stun_servers:?}");
|
||||
|
||||
let stun_request = rust_p2p_core::stun::send_stun_request();
|
||||
let target_conn_count = tcp_stun_servers.len().min(2);
|
||||
let mut active_connections: HashMap<SocketAddr, (TcpStream, SocketAddr)> = HashMap::new();
|
||||
|
||||
'outer: loop {
|
||||
while active_connections.len() < target_conn_count {
|
||||
let mut candidates: Vec<&String> = tcp_stun_servers.iter().collect();
|
||||
candidates.shuffle(&mut rand::rng());
|
||||
|
||||
let mut connected = false;
|
||||
for stun in candidates {
|
||||
let addr = match tokio::net::lookup_host(stun.as_str()).await {
|
||||
Ok(mut addrs) => addrs.next(),
|
||||
Err(e) => {
|
||||
log::debug!("lookup_host failed {stun} {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(addr) = addr else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if active_connections.contains_key(&addr) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(w) = socket_manager.tcp_socket_manager_as_ref() else {
|
||||
continue;
|
||||
};
|
||||
|
||||
match tokio::time::timeout(Duration::from_secs(5), w.connect_reuse_port_raw(addr))
|
||||
.await
|
||||
{
|
||||
Ok(Ok(mut tcp_stream)) => {
|
||||
let write_result = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
tcp_stream.write_all(&stun_request),
|
||||
)
|
||||
.await;
|
||||
|
||||
if let Ok(Ok(_)) = write_result {
|
||||
match stun_tcp_read(&mut tcp_stream).await {
|
||||
Ok(pub_addr) => {
|
||||
log::debug!(
|
||||
"update_tcp_public_addr {stun} {addr} -> {pub_addr}"
|
||||
);
|
||||
|
||||
let existing_pub_addr =
|
||||
active_connections.values().next().map(|(_, p)| *p);
|
||||
|
||||
if let Some(existing) = existing_pub_addr
|
||||
&& existing != pub_addr
|
||||
{
|
||||
log::debug!(
|
||||
"pub_addr mismatch: {existing} != {pub_addr}, wait 60s"
|
||||
);
|
||||
active_connections.clear();
|
||||
app_context.nat_info.update_tcp_public_addr(
|
||||
SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into(),
|
||||
);
|
||||
tokio::time::sleep(Duration::from_secs(5 * 60)).await;
|
||||
continue 'outer;
|
||||
}
|
||||
|
||||
active_connections.insert(addr, (tcp_stream, pub_addr));
|
||||
connected = true;
|
||||
break;
|
||||
}
|
||||
Err(e) => {
|
||||
log::debug!("stun_tcp_read failed {stun} {addr} {e}");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::debug!("write stun request failed {stun} {addr}");
|
||||
}
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("connect_reuse_port_raw failed {stun} {addr} {e}");
|
||||
}
|
||||
Err(_) => {
|
||||
log::debug!("connect_reuse_port_raw timeout {stun} {addr}");
|
||||
}
|
||||
}
|
||||
let stun_request = rustp2p_core::stun::send_stun_request();
|
||||
loop {
|
||||
let tcp_stun_servers = {
|
||||
let servers = app_context.tcp_stun();
|
||||
if servers.is_empty() {
|
||||
default_tcp_stun()
|
||||
} else {
|
||||
servers
|
||||
}
|
||||
};
|
||||
let Some(local_ipv4) = app_context
|
||||
.get_nat_info()
|
||||
.map(|info| info.local_ipv4)
|
||||
.filter(|ip| !ip.is_unspecified())
|
||||
else {
|
||||
log::debug!("local IPv4 is not available for TCP STUN port reuse");
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
continue;
|
||||
};
|
||||
let candidates = resolve_tcp_stun_candidates(&tcp_stun_servers).await;
|
||||
if candidates.len() < 2 {
|
||||
log::warn!("TCP public address detection requires two reachable STUN servers");
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
if !connected {
|
||||
let attempts = candidates.into_iter().map(|(stun, addr)| {
|
||||
connect_tcp_stun(
|
||||
stun,
|
||||
addr,
|
||||
local_tcp_port,
|
||||
local_ipv4,
|
||||
default_interface.as_ref(),
|
||||
&stun_request,
|
||||
)
|
||||
});
|
||||
let results = futures::future::join_all(attempts).await;
|
||||
let mut connections = Vec::with_capacity(2);
|
||||
for result in results {
|
||||
match result {
|
||||
Ok(connection) => connections.push(connection),
|
||||
Err(error) => log::debug!("TCP STUN connection failed: {error}"),
|
||||
}
|
||||
}
|
||||
if connections.len() != 2 {
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
let first_public_addr = connections[0].public_addr;
|
||||
let second_public_addr = connections[1].public_addr;
|
||||
if first_public_addr.port() != second_public_addr.port() {
|
||||
log::warn!(
|
||||
"TCP STUN public port mismatch: {first_public_addr} != {second_public_addr}; retry later"
|
||||
);
|
||||
app_context
|
||||
.nat_info
|
||||
.update_tcp_public_addr(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0).into());
|
||||
tokio::time::sleep(Duration::from_secs(5 * 60)).await;
|
||||
continue;
|
||||
}
|
||||
app_context
|
||||
.nat_info
|
||||
.update_tcp_public_addr(first_public_addr);
|
||||
|
||||
loop {
|
||||
let sleep_secs = rand::rng().random_range(10u64..=15);
|
||||
tokio::time::sleep(Duration::from_secs(sleep_secs)).await;
|
||||
if !keep_tcp_stun_connections_alive(&mut connections, &stun_request).await {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let existing_pub_addr = active_connections.values().next().map(|(_, p)| *p);
|
||||
if let Some(existing) = existing_pub_addr {
|
||||
app_context.nat_info.update_tcp_public_addr(existing);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let sleep_secs = rand::rng().random_range(10u64..=15);
|
||||
tokio::time::sleep(Duration::from_secs(sleep_secs)).await;
|
||||
struct TcpStunConnection {
|
||||
stun: String,
|
||||
remote_addr: SocketAddr,
|
||||
stream: TcpStream,
|
||||
public_addr: SocketAddr,
|
||||
}
|
||||
|
||||
let mut to_remove = Vec::new();
|
||||
let addrs: Vec<SocketAddr> = active_connections.keys().cloned().collect();
|
||||
async fn resolve_tcp_stun_candidates(servers: &[String]) -> Vec<(String, SocketAddr)> {
|
||||
use rand::seq::SliceRandom;
|
||||
|
||||
for addr in addrs {
|
||||
let Some((tcp_stream, _)) = active_connections.get_mut(&addr) else {
|
||||
continue;
|
||||
};
|
||||
let mut buf = [0u8; 1024];
|
||||
|
||||
match tcp_stream.try_read(&mut buf) {
|
||||
Ok(0) => {
|
||||
log::warn!("stun tcp close {addr} EOF");
|
||||
to_remove.push(addr);
|
||||
continue;
|
||||
}
|
||||
Err(e) if e.kind() != std::io::ErrorKind::WouldBlock => {
|
||||
log::warn!("stun tcp read error {addr} {e}");
|
||||
to_remove.push(addr);
|
||||
continue;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match tokio::time::timeout(Duration::from_secs(3), tcp_stream.write_all(&stun_request))
|
||||
.await
|
||||
{
|
||||
Ok(Ok(_)) => {}
|
||||
Ok(Err(e)) => {
|
||||
log::warn!("stun tcp write error {addr} {e}");
|
||||
to_remove.push(addr);
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!("stun tcp write timeout {addr}");
|
||||
to_remove.push(addr);
|
||||
let mut servers = servers.to_vec();
|
||||
servers.shuffle(&mut rand::rng());
|
||||
let mut remote_addrs = HashSet::new();
|
||||
let mut candidates = Vec::with_capacity(2);
|
||||
for stun in servers {
|
||||
match tokio::net::lookup_host(stun.as_str()).await {
|
||||
Ok(addrs) => {
|
||||
if let Some(addr) = addrs
|
||||
.filter(SocketAddr::is_ipv4)
|
||||
.find(|addr| remote_addrs.insert(*addr))
|
||||
{
|
||||
candidates.push((stun.clone(), addr));
|
||||
if candidates.len() == 2 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for addr in to_remove {
|
||||
active_connections.remove(&addr);
|
||||
Err(error) => log::debug!("lookup_host failed {stun} {error}"),
|
||||
}
|
||||
}
|
||||
candidates
|
||||
}
|
||||
|
||||
async fn connect_tcp_stun(
|
||||
stun: String,
|
||||
remote_addr: SocketAddr,
|
||||
local_tcp_port: u16,
|
||||
local_ipv4: Ipv4Addr,
|
||||
default_interface: Option<&LocalInterface>,
|
||||
stun_request: &[u8],
|
||||
) -> io::Result<TcpStunConnection> {
|
||||
let mut stream = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
crate::utils::socket::connect_tcp_reuse_port(
|
||||
remote_addr,
|
||||
local_tcp_port,
|
||||
local_ipv4,
|
||||
default_interface,
|
||||
),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;
|
||||
tokio::time::timeout(Duration::from_secs(5), stream.write_all(stun_request))
|
||||
.await
|
||||
.map_err(|_| io::Error::from(io::ErrorKind::TimedOut))??;
|
||||
let public_addr = stun_tcp_read(&mut stream).await?;
|
||||
log::debug!("TCP STUN {stun} {remote_addr} -> {public_addr}");
|
||||
Ok(TcpStunConnection {
|
||||
stun,
|
||||
remote_addr,
|
||||
stream,
|
||||
public_addr,
|
||||
})
|
||||
}
|
||||
|
||||
async fn keep_tcp_stun_connections_alive(
|
||||
connections: &mut [TcpStunConnection],
|
||||
stun_request: &[u8],
|
||||
) -> bool {
|
||||
for connection in connections {
|
||||
let mut buf = [0u8; 1024];
|
||||
match connection.stream.try_read(&mut buf) {
|
||||
Ok(0) => {
|
||||
log::warn!(
|
||||
"TCP STUN connection closed: {} {}",
|
||||
connection.stun,
|
||||
connection.remote_addr
|
||||
);
|
||||
return false;
|
||||
}
|
||||
Err(error) if error.kind() != io::ErrorKind::WouldBlock => {
|
||||
log::warn!(
|
||||
"TCP STUN read failed: {} {} {error}",
|
||||
connection.stun,
|
||||
connection.remote_addr
|
||||
);
|
||||
return false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match tokio::time::timeout(
|
||||
Duration::from_secs(3),
|
||||
connection.stream.write_all(stun_request),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(error)) => {
|
||||
log::warn!(
|
||||
"TCP STUN write failed: {} {} {error}",
|
||||
connection.stun,
|
||||
connection.remote_addr
|
||||
);
|
||||
return false;
|
||||
}
|
||||
Err(_) => {
|
||||
log::warn!(
|
||||
"TCP STUN write timeout: {} {}",
|
||||
connection.stun,
|
||||
connection.remote_addr
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
async fn stun_tcp_read(tcp_stream: &mut TcpStream) -> io::Result<SocketAddr> {
|
||||
@@ -415,7 +311,7 @@ async fn stun_tcp_read(tcp_stream: &mut TcpStream) -> io::Result<SocketAddr> {
|
||||
Ok(rs) => rs?,
|
||||
Err(_) => Err(io::Error::from(io::ErrorKind::TimedOut))?,
|
||||
};
|
||||
if let Some(addr) = rust_p2p_core::stun::recv_stun_response(&buf) {
|
||||
if let Some(addr) = rustp2p_core::stun::recv_stun_response(&buf) {
|
||||
Ok(addr)
|
||||
} else {
|
||||
log::debug!("stun_tcp_read {buf:?}");
|
||||
@@ -438,51 +334,3 @@ fn default_tcp_stun() -> Vec<String> {
|
||||
"stun.nextcloud.com:443".to_string(),
|
||||
]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn ip(s: &str) -> Ipv4Addr {
|
||||
s.parse().unwrap()
|
||||
}
|
||||
|
||||
/// 探测地址有效时:主地址在首位,扫描结果保留
|
||||
#[test]
|
||||
fn test_select_local_ipv4_detected_valid() {
|
||||
let scanned = vec![ip("192.168.1.2"), ip("10.0.0.3")];
|
||||
let (primary, list) = select_local_ipv4(Some(ip("172.16.0.2")), &scanned).unwrap();
|
||||
assert_eq!(primary, ip("172.16.0.2"));
|
||||
assert_eq!(
|
||||
list,
|
||||
vec![ip("172.16.0.2"), ip("192.168.1.2"), ip("10.0.0.3")]
|
||||
);
|
||||
}
|
||||
|
||||
/// 探测失败/0.0.0.0 时:回退到扫描结果首个地址
|
||||
#[test]
|
||||
fn test_select_local_ipv4_fallback_to_scanned() {
|
||||
let scanned = vec![ip("192.168.1.2"), ip("10.0.0.3")];
|
||||
let (primary, list) = select_local_ipv4(None, &scanned).unwrap();
|
||||
assert_eq!(primary, ip("192.168.1.2"));
|
||||
assert_eq!(list, scanned);
|
||||
|
||||
let (primary, _) = select_local_ipv4(Some(Ipv4Addr::UNSPECIFIED), &scanned).unwrap();
|
||||
assert_eq!(primary, ip("192.168.1.2"));
|
||||
}
|
||||
|
||||
/// 探测地址已在扫描结果中时不重复
|
||||
#[test]
|
||||
fn test_select_local_ipv4_no_duplicate() {
|
||||
let scanned = vec![ip("192.168.1.2"), ip("10.0.0.3")];
|
||||
let (_, list) = select_local_ipv4(Some(ip("10.0.0.3")), &scanned).unwrap();
|
||||
assert_eq!(list, vec![ip("10.0.0.3"), ip("192.168.1.2")]);
|
||||
}
|
||||
|
||||
/// 两者皆空:返回 None,调用方跳过发布,不会上报 0.0.0.0
|
||||
#[test]
|
||||
fn test_select_local_ipv4_none_when_empty() {
|
||||
assert!(select_local_ipv4(None, &[]).is_none());
|
||||
assert!(select_local_ipv4(Some(Ipv4Addr::UNSPECIFIED), &[]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -10,7 +10,7 @@ use crate::tunnel_core::server::outbound::ServerOutbound;
|
||||
use anyhow::bail;
|
||||
use log::error;
|
||||
use rand::seq::SliceRandom;
|
||||
use rust_p2p_core::punch::{PunchModel, Puncher};
|
||||
use rustp2p_core::punch::{PunchModel, Puncher};
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
@@ -147,8 +147,10 @@ async fn punch_now(
|
||||
packet.set_dest_id(dest_ip.into());
|
||||
packet.set_payload(&crate::utils::time::now_ts_ms().to_be_bytes())?;
|
||||
packet_crypto.encrypt_in_place(&mut packet)?;
|
||||
let buf = packet.buffer();
|
||||
let punch_info = rust_p2p_core::punch::PunchInfo::new(PunchModel::all(), nat_info.nat_info);
|
||||
puncher.punch_now(Some(buf), buf, punch_info).await?;
|
||||
let buf = packet.into_buffer().into_bytes().freeze();
|
||||
let punch_info = rustp2p_core::punch::PunchInfo::new(PunchModel::all(), nat_info.nat_info);
|
||||
puncher
|
||||
.punch_now(Some(buf.clone()), buf, punch_info)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -13,10 +13,10 @@ use crate::tunnel_core::p2p::transport::nat_test::{
|
||||
use crate::tunnel_core::p2p::transport::punch::{PunchTaskContext, punch_task};
|
||||
use crate::tunnel_core::server::outbound::ServerOutbound;
|
||||
use crate::utils::task_control::TaskGroup;
|
||||
use rust_p2p_core::punch::Puncher;
|
||||
use rust_p2p_core::route::ConnectProtocol;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rust_p2p_core::tunnel::{Tunnel, TunnelDispatcher, new_tunnel_component};
|
||||
use rustp2p_core::endpoint::{Config as TunnelConfig, LengthPrefixedInitCodec, TunnelIncoming};
|
||||
use rustp2p_core::punch::Puncher;
|
||||
use rustp2p_core::route_table::Protocol;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::collections::{HashMap, HashSet, VecDeque};
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::sync::Arc;
|
||||
@@ -28,7 +28,6 @@ pub(crate) struct P2pInitConfig {
|
||||
pub peer_address: Vec<PeerAddress>,
|
||||
pub turn: Arc<Vec<TurnRule>>,
|
||||
pub default_interface: Option<LocalInterface>,
|
||||
pub outbound_interface_name: Option<String>,
|
||||
}
|
||||
|
||||
pub async fn init_tunnel(
|
||||
@@ -39,48 +38,35 @@ pub async fn init_tunnel(
|
||||
config: P2pInitConfig,
|
||||
) -> anyhow::Result<(Puncher, P2pOutbound, P2pTask)> {
|
||||
let tunnel_port = config.tunnel_port.unwrap_or(0);
|
||||
let mut udp_config = rust_p2p_core::tunnel::config::UdpTunnelConfig::default()
|
||||
.set_main_udp_count(2)
|
||||
.set_sub_udp_count(82)
|
||||
.set_simple_udp_port(tunnel_port);
|
||||
let mut tcp_config = rust_p2p_core::tunnel::config::TcpTunnelConfig::new(Box::new(
|
||||
rust_p2p_core::tunnel::tcp::LengthPrefixedInitCodec,
|
||||
))
|
||||
.set_tcp_multiplexing_limit(2)
|
||||
.set_tcp_port(tunnel_port);
|
||||
let mut tunnel_config = TunnelConfig::new()
|
||||
.udp_port(tunnel_port)
|
||||
.tcp_port(tunnel_port)
|
||||
.tcp_codec(Box::new(LengthPrefixedInitCodec))
|
||||
.max_assistant_sockets(82)
|
||||
.max_udp_datagram_size(4096);
|
||||
if let Some(interface) = config.default_interface.clone() {
|
||||
// rust-p2p-core 当前的接口绑定实现针对 IPv4;指定出口网卡时关闭
|
||||
// 未绑定的 IPv6 Socket,避免流量绕过所选网卡。
|
||||
udp_config = udp_config
|
||||
.set_default_interface(interface.clone())
|
||||
.set_use_v6(false);
|
||||
tcp_config = tcp_config
|
||||
.set_default_interface(interface)
|
||||
.set_use_v6(false);
|
||||
tunnel_config = tunnel_config.default_interface(interface);
|
||||
}
|
||||
let tunnel_config = rust_p2p_core::tunnel::config::TunnelConfig::empty()
|
||||
.set_udp_tunnel_config(udp_config)
|
||||
.set_tcp_tunnel_config(tcp_config);
|
||||
let (tunnel_dispatcher, puncher) = new_tunnel_component(tunnel_config)?;
|
||||
let tunnel_incoming = TunnelIncoming::bind(tunnel_config).await?;
|
||||
let puncher = tunnel_incoming.puncher();
|
||||
let local_tcp_port = tunnel_incoming.local_tcp_port();
|
||||
let route_table = app_state.route_table.clone();
|
||||
let socket_manager = P2pOutbound::new(
|
||||
tunnel_dispatcher.socket_manager(),
|
||||
route_table.clone(),
|
||||
packet_crypto,
|
||||
);
|
||||
let socket_manager = P2pOutbound::new(puncher.clone(), route_table.clone(), packet_crypto);
|
||||
if config.automatic_punch {
|
||||
task_group.spawn(my_nat_info(
|
||||
app_state.clone(),
|
||||
tunnel_dispatcher.socket_manager(),
|
||||
config.default_interface,
|
||||
config.outbound_interface_name,
|
||||
));
|
||||
let manager = tunnel_dispatcher.socket_manager();
|
||||
let nat_app_state = app_state.clone();
|
||||
let nat_puncher = puncher.clone();
|
||||
task_group.spawn(async move {
|
||||
my_nat_info(nat_app_state, nat_puncher).await;
|
||||
});
|
||||
task_group.spawn(query_udp_public_addr_loop(
|
||||
app_state.clone(),
|
||||
manager.clone(),
|
||||
puncher.clone(),
|
||||
));
|
||||
task_group.spawn(query_tcp_public_addr_loop(
|
||||
app_state.clone(),
|
||||
local_tcp_port,
|
||||
config.default_interface.clone(),
|
||||
));
|
||||
task_group.spawn(query_tcp_public_addr_loop(app_state.clone(), manager));
|
||||
}
|
||||
|
||||
task_group.spawn(route_timeout_task(
|
||||
@@ -127,7 +113,8 @@ pub async fn init_tunnel(
|
||||
let p2p_task = P2pTask {
|
||||
task_group,
|
||||
nat_info: app_state.nat_info.clone(),
|
||||
tunnel_dispatcher,
|
||||
tunnel_incoming,
|
||||
outbound: socket_manager.clone(),
|
||||
};
|
||||
Ok((puncher, socket_manager, p2p_task))
|
||||
}
|
||||
@@ -136,7 +123,7 @@ async fn direct_peer_probe_task(
|
||||
network: SharedNetworkAddr,
|
||||
route_table: RouteTable,
|
||||
socket_manager: P2pOutbound,
|
||||
protocol: ConnectProtocol,
|
||||
protocol: Protocol,
|
||||
address: SocketAddr,
|
||||
) {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(5));
|
||||
@@ -180,14 +167,16 @@ fn build_direct_peer_probe(
|
||||
pub struct P2pTask {
|
||||
task_group: TaskGroup,
|
||||
nat_info: MyNatInfo,
|
||||
tunnel_dispatcher: TunnelDispatcher,
|
||||
tunnel_incoming: TunnelIncoming,
|
||||
outbound: P2pOutbound,
|
||||
}
|
||||
impl P2pTask {
|
||||
pub fn start(self, p2p_inbound_handler: P2pInboundHandler) {
|
||||
self.task_group.spawn(tunnel_dispatch_task(
|
||||
self.nat_info,
|
||||
self.task_group.clone(),
|
||||
self.tunnel_dispatcher,
|
||||
self.tunnel_incoming,
|
||||
self.outbound,
|
||||
p2p_inbound_handler,
|
||||
));
|
||||
}
|
||||
@@ -280,14 +269,14 @@ const RELAY_PROBE_BURST: f64 = 30.0;
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct RelayCandidate {
|
||||
ip: Ipv4Addr,
|
||||
route_key: rust_p2p_core::route::RouteKey,
|
||||
route_key: rustp2p_core::route_table::RouteKey,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
struct RelayProbeAction {
|
||||
target_ip: Ipv4Addr,
|
||||
relay_ip: Ipv4Addr,
|
||||
route_key: rust_p2p_core::route::RouteKey,
|
||||
route_key: rustp2p_core::route_table::RouteKey,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
@@ -561,54 +550,38 @@ pub async fn relay_probe_task(
|
||||
pub async fn tunnel_dispatch_task(
|
||||
nat_info: MyNatInfo,
|
||||
task_group: TaskGroup,
|
||||
mut tunnel_factory: TunnelDispatcher,
|
||||
mut tunnel_incoming: TunnelIncoming,
|
||||
outbound: P2pOutbound,
|
||||
p2p_inbound_handler: P2pInboundHandler,
|
||||
) {
|
||||
loop {
|
||||
let mut tunnel = match tunnel_factory.dispatch().await {
|
||||
Ok(rs) => rs,
|
||||
Err(e) => {
|
||||
log::error!("tunnel disptach :{e:?}");
|
||||
return;
|
||||
}
|
||||
};
|
||||
log::info!("tunnel {:?}-{:?}", tunnel.protocol(), tunnel.remote_addr());
|
||||
while let Some(tunnel) = tunnel_incoming.next().await {
|
||||
let route_key = tunnel.route_key();
|
||||
let protocol = tunnel.protocol();
|
||||
let remote_addr = tunnel.remote_addr();
|
||||
let (mut reader, writer) = tunnel.split();
|
||||
outbound.register_tunnel(route_key, writer.clone());
|
||||
log::info!("tunnel {protocol:?}-{remote_addr:?}");
|
||||
let p2p_inbound_handler = p2p_inbound_handler.clone();
|
||||
let nat_info = nat_info.clone();
|
||||
let outbound = outbound.clone();
|
||||
task_group.spawn(async move {
|
||||
let mut buf = vec![0; 65536];
|
||||
while let Some(rs) = tunnel.recv_from(&mut buf).await {
|
||||
let (len, route_key) = match rs {
|
||||
Ok(rs) => rs,
|
||||
Err(e) => {
|
||||
log::warn!("recv_from {e:?}");
|
||||
if tunnel.protocol().is_udp() {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
};
|
||||
if tunnel.protocol().is_udp()
|
||||
&& rust_p2p_core::stun::is_stun_response(&buf[..len])
|
||||
&& let Some(pub_addr) = rust_p2p_core::stun::recv_stun_response(&buf[..len])
|
||||
while let Some(buf) = reader.recv().await {
|
||||
if protocol.is_udp()
|
||||
&& rustp2p_core::stun::is_stun_response(&buf)
|
||||
&& let Some(pub_addr) = rustp2p_core::stun::recv_stun_response(&buf)
|
||||
{
|
||||
nat_info.update_public_addr(route_key.index(), pub_addr);
|
||||
nat_info.update_public_addr(pub_addr);
|
||||
continue;
|
||||
}
|
||||
let mut bytes = TransmissionBytes::zeroed(len);
|
||||
bytes.copy_from_slice(&buf[..len]);
|
||||
let mut bytes = TransmissionBytes::zeroed(buf.len());
|
||||
bytes.copy_from_slice(&buf);
|
||||
p2p_inbound_handler
|
||||
.next_handle(bytes, route_key, &mut tunnel)
|
||||
.next_handle(bytes, route_key, &writer)
|
||||
.await;
|
||||
}
|
||||
log::info!(
|
||||
"drop tunnel {:?}-{:?}",
|
||||
tunnel.protocol(),
|
||||
tunnel.remote_addr()
|
||||
);
|
||||
if let Tunnel::Tcp(tcp) = tunnel {
|
||||
p2p_inbound_handler.tcp_disconnect(tcp.route_key()).await;
|
||||
}
|
||||
outbound.remove_tunnel(&route_key);
|
||||
p2p_inbound_handler.tunnel_disconnect(route_key);
|
||||
log::info!("drop tunnel {protocol:?}-{remote_addr:?}");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -621,7 +594,7 @@ mod tests {
|
||||
(
|
||||
ip,
|
||||
vec![crate::tunnel_core::p2p::route_table::Route::from(
|
||||
rust_p2p_core::route::RouteKey::default(),
|
||||
rustp2p_core::route_table::RouteKey::default(),
|
||||
1,
|
||||
10,
|
||||
)],
|
||||
@@ -630,7 +603,7 @@ mod tests {
|
||||
|
||||
fn relay_route() -> crate::tunnel_core::p2p::route_table::Route {
|
||||
crate::tunnel_core::p2p::route_table::Route::from(
|
||||
rust_p2p_core::route::RouteKey::default(),
|
||||
rustp2p_core::route_table::RouteKey::default(),
|
||||
2,
|
||||
20,
|
||||
)
|
||||
@@ -708,7 +681,7 @@ mod tests {
|
||||
vec![
|
||||
relay_route(),
|
||||
crate::tunnel_core::p2p::route_table::Route::from(
|
||||
rust_p2p_core::route::RouteKey::default(),
|
||||
rustp2p_core::route_table::RouteKey::default(),
|
||||
1,
|
||||
10,
|
||||
),
|
||||
|
||||
@@ -49,7 +49,7 @@ pub(crate) fn create_server_tunnel(
|
||||
app_state: AppState,
|
||||
config: &Config,
|
||||
packet_crypto: PacketCrypto,
|
||||
default_interface: Option<rust_p2p_core::socket::LocalInterface>,
|
||||
default_interface: Option<rustp2p_core::socket::LocalInterface>,
|
||||
) -> (
|
||||
Vec<ServerTurnManager>,
|
||||
ServerOutbound,
|
||||
|
||||
@@ -28,7 +28,7 @@ use pnet_packet::Packet;
|
||||
use pnet_packet::icmp::{IcmpPacket, IcmpTypes};
|
||||
use pnet_packet::ipv4::Ipv4Packet;
|
||||
use prost::Message;
|
||||
use rust_p2p_core::nat::NatInfo;
|
||||
use rustp2p_core::nat::NatInfo;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
@@ -3,7 +3,7 @@ use crate::tls::verifier::CertValidationMode;
|
||||
use anyhow::Context;
|
||||
use parking_lot::Mutex;
|
||||
use rand::seq::SliceRandom;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use std::fmt;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::str::FromStr;
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::str::FromStr;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
|
||||
pub async fn dns_query_txt(
|
||||
domain: &str,
|
||||
@@ -232,7 +232,7 @@ fn bind_udp(
|
||||
} else {
|
||||
SocketAddr::from(([0; 8], 0))
|
||||
};
|
||||
let socket = rust_p2p_core::socket::bind_udp(addr, default_interface.as_ref())?;
|
||||
let socket = rustp2p_core::socket::bind_udp(addr, default_interface.as_ref())?;
|
||||
UdpSocket::from_std(socket.into())
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use anyhow::Context;
|
||||
use rust_p2p_core::socket::LocalInterface;
|
||||
use rustp2p_core::socket::LocalInterface;
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
use std::io;
|
||||
use std::net::SocketAddr;
|
||||
@@ -128,7 +128,7 @@ pub(crate) fn bind_udp(
|
||||
addr: SocketAddr,
|
||||
interface: Option<&LocalInterface>,
|
||||
) -> io::Result<tokio::net::UdpSocket> {
|
||||
let socket = rust_p2p_core::socket::bind_udp(addr, interface)?;
|
||||
let socket = rustp2p_core::socket::bind_udp(addr, interface)?;
|
||||
tokio::net::UdpSocket::from_std(socket.into())
|
||||
}
|
||||
|
||||
@@ -170,6 +170,58 @@ pub(crate) async fn connect_tcp(
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
/// Connects to `addr` while binding the outgoing socket to an existing local
|
||||
/// TCP listener port. This is used by TCP STUN so the observed public mapping
|
||||
/// belongs to the P2P listener rather than to an unrelated ephemeral port.
|
||||
pub(crate) async fn connect_tcp_reuse_port(
|
||||
addr: SocketAddr,
|
||||
local_port: u16,
|
||||
local_ipv4: std::net::Ipv4Addr,
|
||||
interface: Option<&LocalInterface>,
|
||||
) -> io::Result<tokio::net::TcpStream> {
|
||||
if !addr.is_ipv4() || local_ipv4.is_unspecified() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"TCP STUN port reuse requires a concrete local IPv4 address",
|
||||
));
|
||||
}
|
||||
let socket = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
|
||||
bind_socket_to_interface(
|
||||
&socket,
|
||||
interface,
|
||||
addr.is_ipv4() && !addr.ip().is_loopback(),
|
||||
)?;
|
||||
socket.set_reuse_address(true)?;
|
||||
#[cfg(unix)]
|
||||
socket.set_reuse_port(true)?;
|
||||
let local_addr = SocketAddr::from((local_ipv4, local_port));
|
||||
socket.bind(&local_addr.into())?;
|
||||
socket.set_nonblocking(true)?;
|
||||
socket.set_tcp_nodelay(true)?;
|
||||
|
||||
match socket.connect(&addr.into()) {
|
||||
Ok(()) => {}
|
||||
Err(ref error) if error.kind() == io::ErrorKind::WouldBlock => {}
|
||||
#[cfg(unix)]
|
||||
Err(ref error) if error.raw_os_error() == Some(libc::EINPROGRESS) => {}
|
||||
Err(error) => return Err(error),
|
||||
}
|
||||
|
||||
let stream = tokio::net::TcpStream::from_std(socket.into())?;
|
||||
tokio::time::timeout(CONNECT_TIMEOUT, stream.writable())
|
||||
.await
|
||||
.map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::TimedOut,
|
||||
format!("connect to {addr} timed out after {CONNECT_TIMEOUT:?}"),
|
||||
)
|
||||
})??;
|
||||
if let Some(error) = stream.take_error()? {
|
||||
return Err(error);
|
||||
}
|
||||
Ok(stream)
|
||||
}
|
||||
|
||||
pub(crate) async fn connect_tcp_resolved<A: tokio::net::ToSocketAddrs>(
|
||||
addr: A,
|
||||
interface: Option<&LocalInterface>,
|
||||
@@ -189,6 +241,74 @@ pub(crate) async fn connect_tcp_resolved<A: tokio::net::ToSocketAddrs>(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_stun_connection_reuses_the_p2p_listener_port() {
|
||||
let p2p_listener = rustp2p_core::endpoint::TunnelIncoming::bind(
|
||||
rustp2p_core::endpoint::Config::tcp(0).enable_ipv6(false),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let local_port = p2p_listener.local_tcp_port();
|
||||
let stun_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let stun_addr = stun_listener.local_addr().unwrap();
|
||||
|
||||
let accept = tokio::spawn(async move { stun_listener.accept().await.unwrap() });
|
||||
let stream =
|
||||
connect_tcp_reuse_port(stun_addr, local_port, std::net::Ipv4Addr::LOCALHOST, None)
|
||||
.await
|
||||
.unwrap();
|
||||
let (_accepted, peer_addr) = accept.await.unwrap();
|
||||
|
||||
assert_eq!(stream.local_addr().unwrap().port(), local_port);
|
||||
assert_eq!(peer_addr.port(), local_port);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_stun_connection_reports_connect_failure() {
|
||||
let p2p_listener = rustp2p_core::endpoint::TunnelIncoming::bind(
|
||||
rustp2p_core::endpoint::Config::tcp(0).enable_ipv6(false),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let local_port = p2p_listener.local_tcp_port();
|
||||
let closed_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let closed_addr = closed_listener.local_addr().unwrap();
|
||||
drop(closed_listener);
|
||||
|
||||
let result =
|
||||
connect_tcp_reuse_port(closed_addr, local_port, std::net::Ipv4Addr::LOCALHOST, None)
|
||||
.await;
|
||||
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tcp_stun_connections_can_reuse_the_listener_port_concurrently() {
|
||||
let p2p_listener = rustp2p_core::endpoint::TunnelIncoming::bind(
|
||||
rustp2p_core::endpoint::Config::tcp(0).enable_ipv6(false),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
let local_port = p2p_listener.local_tcp_port();
|
||||
let first_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let second_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let first_addr = first_listener.local_addr().unwrap();
|
||||
let second_addr = second_listener.local_addr().unwrap();
|
||||
|
||||
let first_accept = tokio::spawn(async move { first_listener.accept().await.unwrap() });
|
||||
let second_accept = tokio::spawn(async move { second_listener.accept().await.unwrap() });
|
||||
|
||||
let (first, second) = tokio::join!(
|
||||
connect_tcp_reuse_port(first_addr, local_port, std::net::Ipv4Addr::LOCALHOST, None,),
|
||||
connect_tcp_reuse_port(second_addr, local_port, std::net::Ipv4Addr::LOCALHOST, None,),
|
||||
);
|
||||
|
||||
assert_eq!(first.unwrap().local_addr().unwrap().port(), local_port);
|
||||
assert_eq!(second.unwrap().local_addr().unwrap().port(), local_port);
|
||||
first_accept.await.unwrap();
|
||||
second_accept.await.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_interface_name_disables_binding() {
|
||||
assert!(resolve_interface(None).unwrap().is_none());
|
||||
|
||||
Reference in new issue
Block a user