From 79b54e5dfe3645eef452aadd7c19cc6b49626adf Mon Sep 17 00:00:00 2001 From: eries Date: Thu, 26 Nov 2026 01:22:57 +0800 Subject: [PATCH] fix(tls,core): cache DNS TLS connectors, bound caches, and add jemalloc-stats feature --- crates/honk-core/Cargo.toml | 2 + crates/honk-core/src/control/tcp_sniff.rs | 45 +++++++- crates/honk-outbound/src/tls.rs | 71 ++++++++++-- crates/honk-outbound/src/tls/tests.rs | 127 ++++++++++++++++++++++ crates/honk-outbound/src/urltest.rs | 12 +- crates/honk-outbound/src/urltest/tests.rs | 22 ++++ 6 files changed, 257 insertions(+), 22 deletions(-) diff --git a/crates/honk-core/Cargo.toml b/crates/honk-core/Cargo.toml index 2f11cc2a..ef4b5f54 100644 --- a/crates/honk-core/Cargo.toml +++ b/crates/honk-core/Cargo.toml @@ -122,6 +122,8 @@ native-api = ["dep:axum", "dep:tower", "dep:tower-http", "dep:subtle", "dep:hmac native-ui = ["native-api", "dep:brotli", "dep:flate2"] # Route the shipped binary's allocations through jemalloc (see main.rs) jemalloc = ["dep:tikv-jemallocator"] +# Enable jemalloc runtime statistics (e.g. `_RJEM_MALLOC_CONF=stats_print:true`) +jemalloc-stats = ["jemalloc", "tikv-jemallocator/stats"] # VLESS / VMess proxy handlers (xtls-rprx-vision flow support) rprx = ["honk-outbound/rprx"] # Compile optional client DNS syslog auditing. diff --git a/crates/honk-core/src/control/tcp_sniff.rs b/crates/honk-core/src/control/tcp_sniff.rs index b281bba3..8931fe9a 100644 --- a/crates/honk-core/src/control/tcp_sniff.rs +++ b/crates/honk-core/src/control/tcp_sniff.rs @@ -116,10 +116,14 @@ impl TcpSniffNegCache { cache.remove(key); } - /// Prune all expired entries from the cache. + /// Prune all expired entries from the cache and shrink oversized backing storage. pub fn prune_expired(&self, now: Instant) { let mut cache = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + let cap = cache.capacity(); cache.retain(|_, entry| now < entry.expires_at); + if cap > 64 && cache.len() <= cap / 4 { + cache.shrink_to_fit(); + } } /// Return the number of entries in the cache. @@ -255,4 +259,43 @@ mod tests { cache.clear_all(); assert!(cache.is_empty()); } + + #[test] + fn test_prune_expired_shrinks_oversized_capacity_with_hysteresis() { + let key = |host, port| (SocketAddr::from(([198, 51, 100, host], port)), 2); + let cap = |c: &TcpSniffNegCache| c.inner.lock().unwrap().capacity(); + let now = Instant::now(); + let past = now - NEGATIVE_CACHE_TTL - Duration::from_secs(1); + + let cache = TcpSniffNegCache::new(); + for port in 1000..1200u16 { + cache.note_sniff_failure(key(1, port), past); + } + for port in 2000..2010u16 { + for _ in 0..SNIFF_FAILURE_THRESHOLD { + cache.note_sniff_failure(key(2, port), now); + } + } + assert!(cap(&cache) > 64); + cache.prune_expired(now); + assert_eq!(cache.len(), 10); + assert!(cap(&cache) <= 64); + assert!(cache.should_skip_sniff(&key(2, 2000), now)); + + for port in 3000..3200u16 { + cache.note_sniff_failure(key(3, port), now); + } + assert!(cap(&cache) > 64); + cache.prune_expired(now + NEGATIVE_CACHE_TTL + Duration::from_secs(1)); + assert!(cache.is_empty() && cap(&cache) == 0); + + let small = TcpSniffNegCache::new(); + for port in 4000..4008u16 { + small.note_sniff_failure(key(4, port), past); + } + let small_cap = cap(&small); + assert!(small_cap > 0 && small_cap <= 64); + small.prune_expired(now); + assert!(small.is_empty() && cap(&small) == small_cap); + } } diff --git a/crates/honk-outbound/src/tls.rs b/crates/honk-outbound/src/tls.rs index a37dc89d..bdf309f0 100644 --- a/crates/honk-outbound/src/tls.rs +++ b/crates/honk-outbound/src/tls.rs @@ -215,6 +215,16 @@ impl TlsConnector { self.ech_discovery && ech_discovery_name(domain).is_some() } + #[cfg(test)] + pub(crate) fn context_ptr(&self) -> usize { + self.connector.context().as_ptr() as usize + } + + #[cfg(test)] + pub(crate) fn is_chrome(&self) -> bool { + self.chrome + } + /// TLS client handshake over `stream`, verifying the peer against /// `domain` (unless the node skips verification). pub async fn connect(&self, domain: &str, stream: S) -> anyhow::Result> @@ -439,9 +449,33 @@ struct EchCacheEntry { expires: std::time::Instant, } +const MAX_ECH_CACHE_ENTRIES: usize = 256; + static ECH_DISCOVERY_CACHE: LazyLock< - std::sync::Mutex>, -> = LazyLock::new(|| std::sync::Mutex::new(std::collections::HashMap::new())); + parking_lot::Mutex>, +> = LazyLock::new(Default::default); + +fn insert_ech_cache_entry( + cache: &mut std::collections::HashMap, + key: String, + entry: EchCacheEntry, + now: std::time::Instant, +) { + if !cache.contains_key(&key) && cache.len() >= MAX_ECH_CACHE_ENTRIES { + cache.retain(|_, existing| existing.expires > now); + while cache.len() >= MAX_ECH_CACHE_ENTRIES { + let Some(evict) = cache + .iter() + .min_by(|(k1, e1), (k2, e2)| e1.expires.cmp(&e2.expires).then_with(|| k1.cmp(k2))) + .map(|(k, _)| k.clone()) + else { + break; + }; + cache.remove(&evict); + } + } + cache.insert(key, entry); +} /// Discover a domain's ECHConfigList via DNS HTTPS records (RFC 9460), /// cached per domain (positive: record TTL clamped to 60s..1d; negative: @@ -449,7 +483,7 @@ static ECH_DISCOVERY_CACHE: LazyLock< /// explicit `ech_config` which is fail-closed. pub async fn discover_ech_config(domain: &str) -> Option> { let key = ech_discovery_name(domain)?.to_ascii_lowercase(); - if let Some(hit) = ECH_DISCOVERY_CACHE.lock().unwrap().get(&key) + if let Some(hit) = ECH_DISCOVERY_CACHE.lock().get(&key) && hit.expires > std::time::Instant::now() { return hit.config.clone(); @@ -466,12 +500,15 @@ pub async fn discover_ech_config(domain: &str) -> Option> { if config.is_some() { tracing::debug!(domain = %key, "discovered ECH config via DNS HTTPS RR"); } - ECH_DISCOVERY_CACHE.lock().unwrap().insert( + let now = std::time::Instant::now(); + insert_ech_cache_entry( + &mut ECH_DISCOVERY_CACHE.lock(), key, EchCacheEntry { config: config.clone(), - expires: std::time::Instant::now() + std::time::Duration::from_secs(ttl as u64), + expires: now + std::time::Duration::from_secs(ttl as u64), }, + now, ); config } @@ -670,13 +707,25 @@ pub fn build_dns_connector( alpn_wire: &[u8], ) -> anyhow::Result { let chrome = chrome_mode(); - let mut builder = base_builder(skip_cert_verify)?; - if chrome { - apply_chrome_ctx(&mut builder)?; - } - builder.set_alpn_protos(alpn_wire)?; + let key = ConnectorKey { + reality: false, + skip_verify: skip_cert_verify, + pin: None, + alpn: (!alpn_wire.is_empty()).then(|| alpn_wire.to_vec()), + chrome, + }; + let connector = shared_connector(key, || { + let mut builder = base_builder(skip_cert_verify)?; + if chrome { + apply_chrome_ctx(&mut builder)?; + } + if !alpn_wire.is_empty() { + builder.set_alpn_protos(alpn_wire)?; + } + Ok(builder.build()) + })?; Ok(TlsConnector { - connector: builder.build(), + connector, chrome, alps: chrome && alpn_wire.windows(3).any(|proto| proto == b"\x02h2"), ech_config_list: None, diff --git a/crates/honk-outbound/src/tls/tests.rs b/crates/honk-outbound/src/tls/tests.rs index e41404ec..9181fb34 100644 --- a/crates/honk-outbound/src/tls/tests.rs +++ b/crates/honk-outbound/src/tls/tests.rs @@ -570,3 +570,130 @@ async fn ech_discovery_end_to_end() { assert_eq!(server.join().unwrap(), b"ok"); crate::bootstrap::set_global(None); } + +#[test] +fn dns_connector_shares_context_and_root_store_per_shape() { + use foreign_types::{ForeignType, ForeignTypeRef}; + if crate::bootstrap::run_global_test_in_child( + "tls::tests::dns_connector_shares_context_and_root_store_per_shape", + ) { + return; + } + + let shared_store = root_store().unwrap(); + let dns = |skip, alpn| { + let c = build_dns_connector(skip, alpn).unwrap(); + assert_eq!( + c.connector.context().cert_store().as_ptr(), + shared_store.as_ptr() + ); + c + }; + + set_tls_mode("tls"); + let dot = dns(false, b"\x03dot"); + let doh = dns(false, b"\x02h2"); + let empty = dns(false, b""); + let skip_dot = dns(true, b"\x03dot"); + assert_eq!(dot.context_ptr(), dns(false, b"\x03dot").context_ptr()); + assert_eq!(empty.context_ptr(), dns(false, b"").context_ptr()); + assert_ne!(doh.context_ptr(), dot.context_ptr()); + assert_ne!(empty.context_ptr(), dot.context_ptr()); + assert_ne!(skip_dot.context_ptr(), dot.context_ptr()); + + let mut plain = test_node(); + plain.tls_mut().unwrap().skip_cert_verify = false; + assert_eq!( + empty.context_ptr(), + build_connector(&plain).unwrap().context_ptr() + ); + + assert!(build_dns_connector(false, b"\x05hi").is_err()); + assert!(build_dns_connector(false, b"\x05hi").is_err()); + + set_tls_mode("utls"); + let dot_utls = dns(false, b"\x03dot"); + assert!(!dot.is_chrome() && dot_utls.is_chrome()); + assert_ne!(dot_utls.context_ptr(), dot.context_ptr()); + assert_eq!(dot_utls.context_ptr(), dns(false, b"\x03dot").context_ptr()); + + set_tls_mode("tls"); + assert_eq!(dns(false, b"\x03dot").context_ptr(), dot.context_ptr()); +} + +#[tokio::test] +async fn ech_discovery_cache_enforces_bound_and_eviction_order() { + use std::sync::atomic::Ordering as AOrd; + use std::time::{Duration, Instant}; + if crate::bootstrap::run_global_test_in_child( + "tls::tests::ech_discovery_cache_enforces_bound_and_eviction_order", + ) { + return; + } + + let now = Instant::now(); + let entry = |cfg: Option<&[u8]>, expires| EchCacheEntry { + config: cfg.map(<[u8]>::to_vec), + expires, + }; + let has = |k: &str| ECH_DISCOVERY_CACHE.lock().contains_key(k); + let len = || ECH_DISCOVERY_CACHE.lock().len(); + { + let mut cache = ECH_DISCOVERY_CACHE.lock(); + cache.clear(); + for name in ["expired-1.test", "expired-2.test"] { + cache.insert( + name.into(), + entry(Some(b"old"), now - Duration::from_secs(1)), + ); + } + for name in ["tie-b.test", "tie-a.test"] { + cache.insert(name.into(), entry(None, now + Duration::from_secs(30))); + } + for i in 0..(MAX_ECH_CACHE_ENTRIES - 4) { + cache.insert( + format!("live-{i:03}.test"), + entry(Some(&[i as u8]), now + Duration::from_secs(600)), + ); + } + } + + let (addr, count) = spawn_https_dns(Some(b"\x00\x01ech".to_vec()), 120).await; + crate::bootstrap::set_global(crate::bootstrap::BootstrapResolver::parse(&format!( + "udp://{addr}" + ))); + + assert_eq!( + discover_ech_config("fresh.test").await.as_deref(), + Some(b"\x00\x01ech".as_slice()) + ); + assert_eq!(len(), MAX_ECH_CACHE_ENTRIES - 1); + assert!(!has("expired-1.test") && !has("expired-2.test") && has("tie-a.test")); + + assert!(discover_ech_config("fill.test").await.is_some()); + insert_ech_cache_entry( + &mut ECH_DISCOVERY_CACHE.lock(), + "fresh.test".into(), + entry(Some(b"updated"), now + Duration::from_secs(700)), + Instant::now(), + ); + assert_eq!(len(), MAX_ECH_CACHE_ENTRIES); + assert!(has("tie-a.test")); + assert_eq!( + discover_ech_config("fresh.test").await.as_deref(), + Some(b"updated".as_slice()) + ); + assert_eq!(count.load(AOrd::SeqCst), 2); + + assert!(discover_ech_config("overflow-1.test").await.is_some()); + assert_eq!(len(), MAX_ECH_CACHE_ENTRIES); + assert!(!has("tie-a.test") && has("tie-b.test") && has("overflow-1.test")); + assert!(discover_ech_config("overflow-1.test").await.is_some()); + assert_eq!(count.load(AOrd::SeqCst), 3); + + assert!(discover_ech_config("tie-a.test").await.is_some()); + assert_eq!(count.load(AOrd::SeqCst), 4); + assert_eq!(len(), MAX_ECH_CACHE_ENTRIES); + assert!(!has("tie-b.test") && has("tie-a.test")); + crate::bootstrap::set_global(None); +} diff --git a/crates/honk-outbound/src/urltest.rs b/crates/honk-outbound/src/urltest.rs index 49732992..e895a1de 100644 --- a/crates/honk-outbound/src/urltest.rs +++ b/crates/honk-outbound/src/urltest.rs @@ -595,17 +595,9 @@ pub async fn measure_pinned_http_probe( .await } -/// BoringSSL connector with webpki root verification for HTTP probes. -/// Built once and reused across measurements (it never changes at runtime). -/// Offers `h2,http/1.1`; the exchange dispatches on the negotiated ALPN. +/// Shared BoringSSL probe connector (`h2,http/1.1`, webpki roots) tracking active TLS mode. fn https_connector() -> anyhow::Result { - static CONNECTOR: std::sync::OnceLock> = - std::sync::OnceLock::new(); - let connector = CONNECTOR.get_or_init(|| crate::tls::build_http_probe_connector(false)); - match connector { - Ok(c) => Ok(c.clone()), - Err(e) => Err(anyhow!("failed to build urltest TLS connector: {e:#}")), - } + crate::tls::build_http_probe_connector(false).context("failed to build urltest TLS connector") } /// Measure every member of a group concurrently (at most diff --git a/crates/honk-outbound/src/urltest/tests.rs b/crates/honk-outbound/src/urltest/tests.rs index b8defb11..c7d8c5fa 100644 --- a/crates/honk-outbound/src/urltest/tests.rs +++ b/crates/honk-outbound/src/urltest/tests.rs @@ -980,3 +980,25 @@ async fn urltest_group_failures_do_not_advance_real_dial_streaks() { assert!(alive_set.is_failure_demoted(member.id, ProbeDomain::Tcp, IpVersion::V4)); } } + +#[test] +fn https_connector_tracks_tls_mode_and_reuses_shared_context() { + if crate::bootstrap::run_global_test_in_child( + "urltest::tests::https_connector_tracks_tls_mode_and_reuses_shared_context", + ) { + return; + } + let build = |mode| { + crate::tls::set_tls_mode(mode); + let a = https_connector().unwrap(); + let b = https_connector().unwrap(); + assert_eq!(a.context_ptr(), b.context_ptr()); + a + }; + let tls = build("tls"); + let utls = build("utls"); + assert!(!tls.is_chrome() && utls.is_chrome()); + assert_ne!(utls.context_ptr(), tls.context_ptr()); + let tls_again = build("tls"); + assert!(!tls_again.is_chrome() && tls_again.context_ptr() == tls.context_ptr()); +}