-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathuplink.rs
More file actions
2007 lines (1734 loc) · 67.7 KB
/
uplink.rs
File metadata and controls
2007 lines (1734 loc) · 67.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Uplink: Unified Proxy Management Framework
//!
//! This module provides a generalized framework for managing multiple proxy types and routing decisions.
//!
//! ## Key Components
//!
//! ### 1. UplinkHub
//! Central hub for managing all available proxies and routing decisions. You provide proxies and a routing function.
//!
//! ### 2. UplinkProxy
//! Enum representing different proxy types (Trojan, SOCKS5, HTTP, etc.)
//!
//! ### 3. RoutingContext & RoutingDecision
//! Simple framework exposed as a function where you can:
//! - Access target domain, IP, port, source IP, and protocol
//! - Return a routing decision: proxy to use, direct connection, or special handling
//!
//! ### 4. ProxyStream Trait
//! Unified interface that all proxies implement for stream-based communication
//!
//! ## Typical Usage Pattern
//!
//! ```ignore
//! // 1. Create a UplinkHub with custom routing logic
//! let routing = RoutingBuilder::new()
//! .add_rule(|ctx| ctx.target_domain == Some("blocked.com".to_string()),
//! RoutingDecision::Proxy { target: WireAddress::DomainAddress("blocked.com".into(), 443), id: ProxyID::for_trojan("1.2.3.4:443".parse().unwrap(), "example.com", "secret") })
//! .build();
//!
//! let mut hub = UplinkHub::with_routing(routing);
//!
//! // 2. Add proxies to the hub
//! hub.add_proxy(
//! ProxyID::for_trojan("1.2.3.4:443".parse().unwrap(), "example.com", "secret"),
//! UplinkProxy::Clash(trojan_proxy)
//! );
//!
//! // 3. Pass the hub to the Router
//! let mut router = Router::new(device, RouterConfig { mtu, .. }, hub, file_tx, conf);
//! router.run().await?;
//! ```
//!
//! ## Resilience & Footprint Philosophy
//! - We cache proxy server addresses to avoid repeated DNS lookups when entry points are censored
//! - We route proxy domain resolution through anonymous channels once available
//! - We never take the direct path when more secure/anonymous paths are available
// Uplink is the part of nsproxy where it acts as a client for various proxy protocols
// The apex of nsproxy's handling as a protocol client, is that it maximizes Resilience, and minimizes Footprint.
// We will cache the addresses of the proxy servers whenever possible; always assume our entry points will be censored at some point.
// We will route resolution of proxy servers' domains through anonymous channels once we have any; never take the direct path when more secure and anonymous ones are at hand.
use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet, HashMap},
net::{IpAddr, SocketAddr},
path::PathBuf,
sync::{Arc, OnceLock},
time::Duration,
};
use anyhow::{Context, Result};
use nsproxy_common::crdt::CRDT;
use nsproxy_common::routing::{
DropReason, ProxyID, ProxyNym, RoutingContext, RoutingDecision, RoutingProtocol, RoutingResovled,
VDNSRES,
};
use nsproxy_common::stats::{
default_udp_expectation, ChronoData, ProxyProtocol, ProxyStats, Timestamp,
};
use serde::{Deserialize, Serialize};
use socks5_impl::protocol::WireAddress;
use tracing::{info, warn};
use tun2socks5::ArgProxy;
use tun2socks5::dns::{VirtDNSAsync, VirtDNSHandle};
use crate::{state_blueprint::PersistentState, state_paths};
pub mod router;
pub mod backup;
/// Maximum number of concurrent virtual DNS entries (mirrors tun2socks5 default)
const POOL_SIZE: usize = 65_535;
const DNS_PORT: u16 = 53;
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
fn ensure_rustls_crypto_provider() -> Result<()> {
static TLS_PROVIDER_INIT: OnceLock<()> = OnceLock::new();
if TLS_PROVIDER_INIT.get().is_some() || rustls::crypto::CryptoProvider::get_default().is_some()
{
let _ = TLS_PROVIDER_INIT.set(());
return Ok(());
}
match rustls::crypto::ring::default_provider().install_default() {
Ok(()) => {
let _ = TLS_PROVIDER_INIT.set(());
Ok(())
}
Err(_) if rustls::crypto::CryptoProvider::get_default().is_some() => {
let _ = TLS_PROVIDER_INIT.set(());
Ok(())
}
Err(_) => anyhow::bail!(
"Failed to initialize rustls CryptoProvider; call CryptoProvider::install_default() before TLS use"
),
}
}
// IPs are not ever deleted here.
// Because its expected sometimes DNS servers pollute the records with junk
pub type DomainsSolved = BTreeMap<Domain, BTreeMap<Timestamp, DNSResponse>>;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Domain(pub String);
impl Domain {
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::fmt::Display for Domain {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl From<String> for Domain {
fn from(value: String) -> Self {
Self(value)
}
}
impl From<&str> for Domain {
fn from(value: &str) -> Self {
Self(value.to_string())
}
}
impl From<Domain> for String {
fn from(value: Domain) -> Self {
value.0
}
}
impl std::ops::Deref for Domain {
type Target = str;
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
// Response of a single DNS packet
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DNSResponse {
pub ips: BTreeSet<IpAddr>,
}
/// Profile is only considered usable once all domains are resolved to IPs.
/// We keep this data separately
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProfileSolved {
pub domains: DomainsSolved,
}
impl ProfileSolved {
pub fn new() -> Self {
Self {
domains: BTreeMap::new(),
}
}
pub fn add_resolution(&mut self, domain: Domain, ips: BTreeSet<IpAddr>) {
self.domains
.entry(domain)
.or_default()
.insert(Timestamp::now(), DNSResponse { ips });
}
/// Get the most recent IPs for a domain
pub fn get_latest_ips(&self, domain: &str) -> Option<&BTreeSet<IpAddr>> {
self.domains
.get(&Domain::from(domain))?
.last_key_value()
.map(|(_, response)| &response.ips)
}
/// Check if all required domains are resolved
pub fn all_resolved(&self, required_domains: &[String]) -> bool {
required_domains
.iter()
.all(|domain| self.get_latest_ips(domain).is_some())
}
/// Load from a JSON file
pub fn load_from_file(path: &PathBuf) -> Result<Self> {
info!("Loading resolved addresses from {:?}", path);
let content = std::fs::read_to_string(path)
.context(format!("Failed to read solved.json from {:?}", path))?;
info!("Read {} bytes from {:?}", content.len(), path);
serde_json::from_str(&content).context("Failed to parse solved.json")
}
/// Save to a JSON file
pub fn save_to_file(&self, path: &PathBuf) -> Result<()> {
info!("Saving resolved addresses to {:?}", path);
let parent = path
.parent()
.ok_or_else(|| anyhow::anyhow!("Invalid solved.json path: {:?}", path))?;
info!("Ensuring parent directory exists: {:?}", parent);
std::fs::create_dir_all(parent).context("Failed to create uplink profile directory")?;
let content =
serde_json::to_string_pretty(self).context("Failed to serialize ProfileSolved")?;
let bytes = content.len();
std::fs::write(path, content)
.context(format!("Failed to write solved.json to {:?}", path))?;
info!("Wrote {} bytes to {:?}", bytes, path);
Ok(())
}
}
/// Generic DNS resolver for routing DNS queries through any proxy connection
pub mod proxy_dns {
use super::proxy_adapters::{TcpLike, UdpLike};
use super::*;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use trust_dns_proto::op::{Message, Query};
use trust_dns_proto::rr::{Name, RecordType};
use trust_dns_proto::serialize::binary::{BinDecodable, BinEncodable};
fn build_dns_query(domain: &str) -> Result<Vec<u8>> {
// Build DNS query
let name = Name::from_ascii(domain).context("Invalid domain name")?;
let query = Query::query(name, RecordType::A);
let mut msg = Message::new();
msg.add_query(query);
msg.set_id(rand::random());
msg.set_recursion_desired(true);
msg.to_vec().context("Failed to serialize DNS query")
}
fn parse_dns_response(response_bytes: &[u8], domain: &str) -> Result<Vec<IpAddr>> {
// Parse DNS response
let response =
Message::from_bytes(response_bytes).context("Failed to parse DNS response")?;
let mut ips = Vec::new();
for answer in response.answers() {
if let Some(data) = answer.data() {
if let Some(ip) = data.ip_addr() {
ips.push(ip);
}
}
}
if ips.is_empty() {
anyhow::bail!("No IP addresses found for {}", domain);
}
Ok(ips)
}
/// DNS query over any UDP-like tunnel.
pub async fn query_via_udp(
tunnel: &mut (impl UdpLike + ?Sized),
dns_server: &WireAddress,
domain: &str,
timeout: Duration,
) -> Result<Vec<IpAddr>> {
info!(
"Querying {} via {} through DNS {}",
domain,
tunnel.info(),
dns_server
);
let query_bytes = build_dns_query(domain)?;
// Send DNS query
tunnel
.send_to(&query_bytes, dns_server.clone())
.await
.context("Failed to send DNS query via UDP")?;
// Receive response with timeout
let packet = tokio::time::timeout(timeout, tunnel.recv_from())
.await
.context("DNS query timeout")??;
let ips = parse_dns_response(&packet.data, domain)?;
info!(
"Resolved {} to {} addresses via {}",
domain,
ips.len(),
tunnel.info()
);
Ok(ips)
}
/// DNS query over any TCP-like stream (RFC 1035 - 2-byte length prefix).
pub async fn query_via_tcp(
stream: &mut (impl TcpLike + ?Sized),
dns_server: &WireAddress,
domain: &str,
timeout: Duration,
) -> Result<Vec<IpAddr>> {
info!(
"Querying {} via {} through DNS {}",
domain,
stream.info(),
dns_server
);
let query_bytes = build_dns_query(domain)?;
// DNS over TCP: send length prefix (2 bytes) + query
let len = query_bytes.len() as u16;
let mut buf = Vec::with_capacity(2 + query_bytes.len());
buf.extend_from_slice(&len.to_be_bytes());
buf.extend_from_slice(&query_bytes);
tokio::time::timeout(timeout, stream.write_all(&buf))
.await
.context("Timeout writing DNS query")?
.context("Failed to write DNS query via TCP")?;
tokio::time::timeout(timeout, stream.flush())
.await
.context("Timeout flushing DNS query")?
.context("Failed to flush DNS query")?;
// Read response: first 2 bytes are length
let mut len_buf = [0u8; 2];
tokio::time::timeout(timeout, stream.read_exact(&mut len_buf))
.await
.context("Timeout reading DNS response length")?
.context("Failed to read DNS response length")?;
let response_len = u16::from_be_bytes(len_buf) as usize;
let mut response_buf = vec![0u8; response_len];
tokio::time::timeout(timeout, stream.read_exact(&mut response_buf))
.await
.context("Timeout reading DNS response data")?
.context("Failed to read DNS response data")?;
let ips = parse_dns_response(&response_buf, domain)?;
info!(
"Resolved {} to {} addresses via {}",
domain,
ips.len(),
stream.info()
);
Ok(ips)
}
}
pub mod clash;
// All uplink data is kept at /nsp3/uplink
use tokio::io::{AsyncRead, AsyncWrite};
/// Trait for a unified proxy stream interface
/// All proxy types (Trojan, SOCKS5, HTTP, etc.) implement this
pub trait ProxyStream: Send + Sync + 'static
where
Self: AsyncRead + AsyncWrite + Unpin,
{
/// Get information about this proxy stream
fn info(&self) -> &str;
}
/// Type alias for the routing decision function
/// Modify this function to customize routing behavior
pub type RoutingFunction =
Arc<dyn Fn(&RoutingContext, &UplinkHub) -> RoutingResovled + Send + Sync>;
pub fn preferred_addr(a: WireAddress, b: WireAddress) -> WireAddress {
match (&a, &b) {
(WireAddress::DomainAddress(..), _) => a,
(_, WireAddress::DomainAddress(..)) => b,
_ => a,
}
}
pub fn simple_routing(id: ProxyID) -> RoutingFunction {
Arc::new(move |ctx: &RoutingContext, _hub: &UplinkHub| {
if ctx.attempt_num > 0 {
return RoutingResovled::Drop(DropReason::MaxRetry);
}
match &ctx.dns {
// Real IP from TUN, no VirtDNS mapping — proxy using raw socket address
VDNSRES::NormalProxying => RoutingResovled::ProxyResovled {
target: WireAddress::SocketAddress(SocketAddr::new(ctx.target_ip, ctx.target_port)),
id: id.clone(),
},
// VirtDNS decoded to a domain — use hostname so the proxy resolves it, preserving privacy
VDNSRES::Opine(RoutingDecision::HostOverProxy(host)) => RoutingResovled::ProxyResovled {
target: WireAddress::DomainAddress(host.clone(), ctx.target_port),
id: id.clone(),
},
// VirtDNS decoded to a concrete socket — proxy to that socket directly
VDNSRES::Opine(RoutingDecision::SocketOverProxy(sock)) => RoutingResovled::ProxyResovled {
target: WireAddress::SocketAddress(*sock),
id: id.clone(),
},
VDNSRES::Opine(RoutingDecision::NATByTUN(sock)) => RoutingResovled::NATByTUN(*sock),
VDNSRES::Opine(RoutingDecision::Direct(sock)) => RoutingResovled::Direct(*sock),
VDNSRES::Opine(RoutingDecision::File(path)) => RoutingResovled::ProxyResovled {
target: WireAddress::SocketAddress(SocketAddr::new(ctx.target_ip, ctx.target_port)),
id: ProxyID::for_file(path.as_path()),
},
VDNSRES::Opine(RoutingDecision::Drop(reason)) => RoutingResovled::Drop(reason.clone()),
VDNSRES::ERR => RoutingResovled::Drop(DropReason::Preprocess(Cow::Borrowed(
"vdns error",
))),
}
})
}
// This struct is not directly serialized
/// Central hub of all resources we have
pub struct UplinkHub {
pub proxies: HashMap<ProxyID, UplinkProxy>,
routing_fn: RoutingFunction,
/// Centralized Clash resolver/cache state loaded from /nsp3/clash.json
pub clash: Option<clash::ClashState>,
pub stats: HashMap<ProxyID, ProxyStats>,
pub stats_clear: Timestamp,
/// Map from proxy pseudonym (nym) to ProxyID for O(1) lookup
pub nym_map: HashMap<ProxyNym, ProxyID>,
pub found_ips: ChronoData,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct RemoteProxyState {
pub proxies: Vec<ArgProxy>,
}
impl RemoteProxyState {
pub fn path() -> PathBuf {
<Self as PersistentState>::path()
}
pub fn load_or_default() -> Result<Self> {
<Self as PersistentState>::load_or_default()
}
pub fn save_atomic(&self) -> Result<()> {
<Self as PersistentState>::save_atomic(self)
}
pub fn add_proxy(&mut self, proxy: ArgProxy) -> bool {
if self
.proxies
.iter()
.any(|existing| existing.addr == proxy.addr)
{
return false;
}
self.proxies.push(proxy);
true
}
pub fn remove_proxy(&mut self, nym: &ProxyNym) -> bool {
let before = self.proxies.len();
self.proxies.retain(|proxy| {
let id = ProxyID::for_remote(proxy.addr);
id.nym() != *nym
});
self.proxies.len() != before
}
}
impl PersistentState for RemoteProxyState {
const STATE_NAME: &'static str = "uplink_remote";
fn path() -> PathBuf {
state_paths::uplink_remote_state()
}
}
/// All proxies here should be immediately connectable without further resolution dependent on other state
#[derive(Debug, Clone)]
pub enum UplinkProxy {
Trojan(clash::TrojanProxy),
Geph,
Remote(ArgProxy),
File(PathBuf),
}
impl std::fmt::Display for UplinkProxy {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UplinkProxy::Trojan(t) => write!(
f,
"trojan {}@{}:{}",
t.name,
t.server_name,
t.server_addr.port()
),
UplinkProxy::Geph => write!(f, "geph"),
UplinkProxy::Remote(arg) => write!(f, "remote {}", arg.addr),
UplinkProxy::File(p) => write!(f, "file {}", p.display()),
}
}
}
pub fn uplink_proxy_protocol(proxy: &UplinkProxy) -> ProxyProtocol {
match proxy {
UplinkProxy::Trojan(_) => ProxyProtocol::Trojan,
UplinkProxy::Geph => ProxyProtocol::Geph,
UplinkProxy::File(_) => ProxyProtocol::File,
UplinkProxy::Remote(arg) => match arg.proxy_type {
tun2socks5::ProxyType::Socks4 => ProxyProtocol::Socks4,
tun2socks5::ProxyType::Socks5 => ProxyProtocol::Socks5,
tun2socks5::ProxyType::Http => ProxyProtocol::Http,
},
}
}
pub fn uplink_proxy_default_udp_expected(proxy: &UplinkProxy) -> bool {
default_udp_expectation(uplink_proxy_protocol(proxy))
}
impl UplinkHub {
/// Create a new UplinkHub with a default routing function
pub fn new() -> Self {
Self {
proxies: HashMap::new(),
routing_fn: Arc::new(|_ctx: &RoutingContext, _hub: &UplinkHub| {
RoutingResovled::Drop(DropReason::Preprocess(Cow::Borrowed(
"no routing function set",
)))
}),
clash: None,
stats: HashMap::new(),
stats_clear: Timestamp::default(),
nym_map: HashMap::new(),
found_ips: ChronoData::default(),
}
}
pub fn update_link_ttfb(&mut self, id: &ProxyID, latency: Duration) {
self.stats
.entry(id.clone())
.or_default()
.record_latency_ms(latency.as_millis() as u64);
}
pub fn update_link_conn_check(&mut self, id: &ProxyID, success: bool) {
self.stats
.entry(id.clone())
.or_default()
.record_attempt(success);
}
pub fn get_link_stats(&self, id: &ProxyID) -> Option<ProxyStats> {
self.stats.get(id).cloned()
}
pub fn clear_stats(&mut self) {
self.stats.clear();
self.stats_clear = Timestamp::now();
}
/// Persist current in-memory stats to uplink/stats.json.
/// Loads the file first and merges to preserve stats from other processes.
pub fn save_stats(&mut self) -> Result<()> {
let persisted = UplinkStatsState::load_or_default()?;
if persisted.clear > self.stats_clear {
self.stats = persisted.stats;
self.stats_clear = persisted.clear;
return Ok(());
}
let mut state = UplinkStatsState {
stats: self.stats.clone(),
clear: self.stats_clear,
};
state.compact_for_save();
state.save_atomic()?;
self.stats = state.stats;
self.stats_clear = state.clear;
Ok(())
}
/// Load persisted stats from uplink/stats.json and merge into in-memory state.
/// In-memory entries take precedence over persisted ones.
pub fn load_stats(&mut self) -> Result<()> {
let state = UplinkStatsState::load_or_default()?;
if state.clear > self.stats_clear {
self.stats = state.stats;
self.stats_clear = state.clear;
return Ok(());
}
if state.clear < self.stats_clear {
return Ok(());
}
for (id, stats) in state.stats {
self.stats.entry(id).or_insert(stats);
}
Ok(())
}
/// Create a new UplinkHub with a custom routing function
pub fn with_routing(routing_fn: RoutingFunction) -> Self {
Self {
proxies: HashMap::new(),
routing_fn,
clash: None,
stats: HashMap::new(),
stats_clear: Timestamp::default(),
nym_map: HashMap::new(),
found_ips: ChronoData::default(),
}
}
/// Hydrate hub from persisted state in one entrypoint:
/// - loads centralized Clash state (`/nsp3/uplink/clash.json`)
/// - loads all saved proxies that can be materialized from that state
pub fn hydrate_from_persisted(&mut self) -> Result<usize> {
let _ = self.load_clash_state()?;
self.load_saved_proxies()?;
self.load_stats()?;
Ok(self.proxies.len())
}
/// Load centralized Clash state from /nsp3/clash.json when not yet present.
pub fn load_clash_state(&mut self) -> Result<&clash::ClashState> {
if self.clash.is_none() {
self.clash = Some(clash::ClashState::load_or_default()?);
}
Ok(self.clash.as_ref().expect("clash state must exist"))
}
/// Replace in-memory Clash state and persist it to /nsp3/clash.json.
pub fn set_clash_state(&mut self, state: clash::ClashState) -> Result<()> {
state.save_atomic()?;
self.clash = Some(state);
Ok(())
}
/// Add a proxy to the hub
pub fn add_proxy(&mut self, id: ProxyID, proxy: UplinkProxy) {
// insert into proxies and update proxynym map for fast lookup
let nym = id.nym();
self.nym_map.insert(nym, id.clone());
self.proxies.insert(id, proxy);
}
/// Get a proxy by ID
pub fn get_proxy(&self, id: &ProxyID) -> Option<&UplinkProxy> {
self.proxies.get(id)
}
/// Make a routing decision for the given context, resolving all intermediate variants
/// using hub state (proxy registry, etc.) into a concrete `RoutingResovled`.
pub fn route(&self, ctx: &RoutingContext) -> RoutingResovled {
(self.routing_fn)(ctx, self)
}
/// Set a new routing function
pub fn set_routing(&mut self, routing_fn: RoutingFunction) {
self.routing_fn = routing_fn;
}
/// Get all proxies
pub fn all_proxies(&self) -> &HashMap<ProxyID, UplinkProxy> {
&self.proxies
}
// `get_proxy_by_nym` removed — use `nym_map` directly for lookups
/// Get the nym for a proxy ID
pub fn get_nym(&self, id: &ProxyID) -> Option<ProxyNym> {
self.proxies.contains_key(id).then(|| id.nym())
}
/// Load all saved proxies across all uplink kinds
pub fn load_saved_proxies(&mut self) -> Result<usize> {
self.load_remote_proxies()?;
self.load_clash_proxies()?;
Ok(self.proxies.len())
}
/// Load all saved remote proxies from /nsp3/uplink/remote.json
pub fn load_remote_proxies(&mut self) -> Result<usize> {
let state = RemoteProxyState::load_or_default()?;
let mut count = 0;
for proxy in state.proxies {
let id = ProxyID::for_remote(proxy.addr);
self.add_proxy(id, UplinkProxy::Remote(proxy));
count += 1;
}
Ok(count)
}
/// Export a portable snapshot of all hub state that can be serialized to JSON.
///
/// The routing function is excluded — it must be re-supplied on import.
pub fn export(&self) -> UplinkSnapshot {
let remote_proxies: Vec<ArgProxy> = self
.proxies
.values()
.filter_map(|p| {
if let UplinkProxy::Remote(arg) = p {
Some(arg.clone())
} else {
None
}
})
.collect();
UplinkSnapshot {
clash: self.clash.clone(),
remote_proxies,
stats: self.stats.clone(),
}
}
/// Build an `UplinkHub` from a previously exported [`UplinkSnapshot`].
///
/// All persisted sub-states (clash, remote proxies, stats) are applied in
/// memory. The routing function defaults to the drop-all stub; callers
/// should call `set_routing` or `with_routing` afterwards.
pub fn from_snapshot(snapshot: UplinkSnapshot) -> Result<Self> {
let mut hub = Self::new();
if let Some(clash_state) = snapshot.clash {
hub.clash = Some(clash_state);
}
for proxy in snapshot.remote_proxies {
let id = ProxyID::for_remote(proxy.addr);
hub.add_proxy(id, UplinkProxy::Remote(proxy));
}
hub.load_clash_proxies()?;
for (id, stats) in snapshot.stats {
hub.stats.entry(id).or_insert(stats);
}
Ok(hub)
}
/// Load all Clash proxies from centralized clash state and add them to the hub
pub fn load_clash_proxies(&mut self) -> Result<usize> {
let clash_state = self.load_clash_state()?.clone();
let state_proxies = clash_state.proxies;
let mut count = 0;
for (_proxy_id, cfg) in clash_state.trojan_proxies {
let resolved_ip = state_proxies
.get(&Domain::from(cfg.server.clone()))
.and_then(|responses| responses.last_key_value())
.and_then(|(_, response)| response.ips.iter().next().copied());
if let Some(ip) = resolved_ip {
let runtime = clash::TrojanProxy {
name: cfg.name.clone(),
server_addr: SocketAddr::new(ip, cfg.port),
server_name: cfg.server.clone(),
password: cfg.password.clone(),
};
// Prefer domain-based ProxyID for stable identity across DNS changes
let id = ProxyID::for_trojan_domain(
&cfg.server,
cfg.port,
&cfg.password,
);
self.add_proxy(id, UplinkProxy::Trojan(runtime));
count += 1;
}
}
Ok(count)
}
}
/// Serializable snapshot of all per-proxy link stats, stored at uplink/stats.json.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UplinkStatsState {
pub stats: HashMap<ProxyID, ProxyStats>,
#[serde(default)]
pub clear: Timestamp,
}
impl UplinkStatsState {
/// Compact per-proxy timeseries only when beneficial for persistence.
/// Returns number of proxies that were simplified.
pub fn compact_for_save(&mut self) -> usize {
let mut simplified = 0;
for stats in self.stats.values_mut() {
if stats.simplify_if_needed() {
simplified += 1;
}
}
simplified
}
/// Clear all accumulated statistics.
pub fn clear_all(&mut self) {
self.stats.clear();
self.clear = Timestamp::now();
}
}
impl CRDT for UplinkStatsState {
fn merge(mut self, other: Self) -> Self {
if other.clear > self.clear {
return other;
}
if other.clear < self.clear {
return self;
}
for (id, stats) in other.stats {
self.stats
.entry(id)
.and_modify(|e| *e = e.clone().merge(stats.clone()))
.or_insert(stats);
}
self
}
}
/// Portable, fully serializable snapshot of an `UplinkHub`.
///
/// Captures all the state that the hub is built from so it can be written to a
/// single JSON file and later restored on another machine or after a reset.
///
/// The routing function is **not** included (it is code, not data). When
/// importing, callers should call `hydrate_from_persisted` or supply their own
/// routing function with `UplinkHub::with_routing`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct UplinkSnapshot {
/// Centralized Clash state (proxy configs, resolved IPs, …)
pub clash: Option<clash::ClashState>,
/// Saved remote proxies (SOCKS5 / HTTP, …)
pub remote_proxies: Vec<ArgProxy>,
/// Per-proxy link statistics keyed by proxy ID
pub stats: HashMap<ProxyID, ProxyStats>,
}
impl PersistentState for UplinkStatsState {
const STATE_NAME: &'static str = "uplink_stats";
fn path() -> PathBuf {
state_paths::uplink_stats_state()
}
}
impl Default for UplinkHub {
fn default() -> Self {
Self::new()
}
}
// ==============================================================================
// Handler Traits and Abstractions
// ==============================================================================
/// Handler for TCP connections
/// Implement this trait to customize TCP connection handling
pub trait TcpHandler: Send + Sync + 'static {
/// Handle a TCP connection
///
/// # Arguments
/// * `addr` - The destination socket address
/// * `stream` - The TCP stream from the client side
/// * `routing_decision` - The routing decision from the hub
fn handle(
&self,
addr: std::net::SocketAddr,
stream: ipstack::stream::IpStackTcpStream,
routing_decision: RoutingDecision,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>>;
}
/// Handler for UDP connections
pub trait UdpHandler: Send + Sync + 'static {
/// Handle a UDP connection
fn handle(
&self,
addr: std::net::SocketAddr,
stream: ipstack::stream::IpStackUdpStream,
routing_decision: RoutingDecision,
) -> std::pin::Pin<Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send>>;
}
// ==============================================================================
// Stream Adapters for Different Proxy Types
// ==============================================================================
/// Kernel-style connection interface that supports both streaming and datagram operations
pub mod proxy_adapters {
use super::*;
use anyhow::Context as AnyhowContext;
use bytes::{Buf, BufMut, BytesMut};
use rustls::pki_types::ServerName;
use socks5_impl::client;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio::net::{TcpStream, UdpSocket};
use tokio_rustls::TlsConnector;
use tokio_rustls::client::TlsStream;
/// UDP packet for datagram operations
#[derive(Debug, Clone)]
pub struct UdpPacket {
pub data: Vec<u8>,
pub dst_addr: WireAddress,
}
/// Trait for TCP proxy streams (unified interface for Trojan, SOCKS5, unproxy, etc.)
pub trait TcpLike: AsyncRead + AsyncWrite + Send + Sync + Unpin {
fn info(&self) -> &str;
}
/// Trait for UDP proxy tunnels (unified interface for Trojan, SOCKS5, unproxy, etc)
#[async_trait::async_trait]
pub trait UdpLike: Send + Sync {
async fn send_to(&mut self, data: &[u8], dst: WireAddress) -> std::io::Result<usize>;
async fn recv_from(&mut self) -> std::io::Result<UdpPacket>;
fn info(&self) -> &str;
}
/// Unified connection type that can handle both TCP streams and UDP tunnels
pub enum ProxyConnection {
/// TCP stream connection (Trojan, SOCKS5, etc.)
Tcp(Box<dyn TcpLike>),
/// UDP tunnel (Trojan, SOCKS5, etc.)
Udp(Box<dyn UdpLike>),
}
impl ProxyConnection {
/// Get connection info string
pub fn info(&self) -> &str {
match self {
ProxyConnection::Tcp(conn) => conn.info(),
ProxyConnection::Udp(conn) => conn.info(),
}
}
/// Check if this connection supports datagram operations
pub fn is_datagram(&self) -> bool {
matches!(self, ProxyConnection::Udp(_))
}
/// Convert to mutable UDP tunnel reference
pub fn as_udp_mut(&mut self) -> Option<&mut dyn UdpLike> {
match self {
ProxyConnection::Udp(tunnel) => Some(tunnel.as_mut()),
_ => None,
}
}
/// Convert to mutable TCP stream reference
pub fn as_tcp_mut(&mut self) -> Option<&mut dyn TcpLike> {
match self {
ProxyConnection::Tcp(stream) => Some(stream.as_mut()),
_ => None,
}
}
}
// ==============================================================================
// Trojan Implementations
// ==============================================================================
/// Trojan TCP connection wrapper
struct TrojanTcpConn {
inner: clash::TrojanTcpStream,
info: String,
}
impl TcpLike for TrojanTcpConn {