Skip to content

Commit 39e8c53

Browse files
fix(udp): drop pre-parse client lock + bound session/task lifecycle
1 parent bf6fab3 commit 39e8c53

1 file changed

Lines changed: 163 additions & 58 deletions

File tree

‎src/proxy_server.rs‎

Lines changed: 163 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ use std::time::Duration;
66
use tokio::io::{AsyncReadExt, AsyncWriteExt};
77
use tokio::net::{TcpListener, TcpStream, UdpSocket};
88
use tokio::sync::{mpsc, Mutex};
9+
use tokio::task::JoinSet;
910
use tokio_rustls::rustls::client::danger::{
1011
HandshakeSignatureValid, ServerCertVerified, ServerCertVerifier,
1112
};
@@ -577,11 +578,82 @@ struct SocksUdpTarget {
577578
/// Per-target relay session state shared between the dispatch loop and
578579
/// the per-session task. The dispatch loop pushes uplink datagrams via
579580
/// `uplink`; the task drains the upstream and serializes both directions
580-
/// onto a single tunnel-mux call at a time.
581+
/// onto a single tunnel-mux call at a time. `sid` is held here so the
582+
/// dispatch teardown path can issue close_session for any task it has
583+
/// to abort mid-await.
581584
struct UdpRelaySession {
585+
sid: String,
582586
uplink: mpsc::Sender<Vec<u8>>,
583587
}
584588

589+
/// All per-ASSOCIATE UDP relay state behind a single mutex so insertion
590+
/// order, the live-session map, and per-task self-removal can all stay
591+
/// consistent. Wrapping each separately invited a slow leak: the
592+
/// previous design's `insertion_order` deque was only pruned on
593+
/// overflow eviction, so a long-lived ASSOCIATE that opened many
594+
/// short-lived sessions accumulated dead `SocksUdpTarget` entries.
595+
struct UdpRelayState {
596+
sessions: HashMap<SocksUdpTarget, UdpRelaySession>,
597+
/// Insertion-order log for FIFO eviction. NOT a real LRU — repeated
598+
/// uplinks to a hot session do not move it to the back. We keep it
599+
/// in lockstep with `sessions` (insert appends; remove scans and
600+
/// erases the matching entry — O(N) but N ≤ 256).
601+
order: VecDeque<SocksUdpTarget>,
602+
}
603+
604+
impl UdpRelayState {
605+
fn new() -> Self {
606+
Self {
607+
sessions: HashMap::new(),
608+
order: VecDeque::new(),
609+
}
610+
}
611+
612+
fn get_uplink(&self, target: &SocksUdpTarget) -> Option<mpsc::Sender<Vec<u8>>> {
613+
self.sessions.get(target).map(|s| s.uplink.clone())
614+
}
615+
616+
fn insert(&mut self, target: SocksUdpTarget, session: UdpRelaySession) {
617+
self.order.push_back(target.clone());
618+
self.sessions.insert(target, session);
619+
}
620+
621+
fn remove(&mut self, target: &SocksUdpTarget) {
622+
if let Some(pos) = self.order.iter().position(|t| t == target) {
623+
self.order.remove(pos);
624+
}
625+
self.sessions.remove(target);
626+
}
627+
628+
/// Pop the oldest session entries until `sessions.len() < cap`.
629+
/// Stale `order` entries (already removed by self-cleanup on a
630+
/// task's natural exit) are quietly skipped.
631+
fn evict_until_under(&mut self, cap: usize) -> Vec<SocksUdpTarget> {
632+
let mut evicted = Vec::new();
633+
while self.sessions.len() >= cap {
634+
let Some(victim) = self.order.pop_front() else {
635+
break;
636+
};
637+
if self.sessions.remove(&victim).is_some() {
638+
evicted.push(victim);
639+
}
640+
}
641+
evicted
642+
}
643+
644+
/// Snapshot live sids for the teardown close_session sweep. We
645+
/// take a copy (not a drain) so the caller can decide whether to
646+
/// also clear the map.
647+
fn live_sids(&self) -> Vec<String> {
648+
self.sessions.values().map(|s| s.sid.clone()).collect()
649+
}
650+
651+
fn clear(&mut self) {
652+
self.sessions.clear();
653+
self.order.clear();
654+
}
655+
}
656+
585657
/// SOCKS5 UDP request frame: 4-byte header + atyp-specific address + 2-byte
586658
/// port + payload. DOMAIN atyp uses a 1-byte length prefix + up to 255
587659
/// bytes, so the largest header is `4 + 1 + 255 + 2 = 262`. Round to 300
@@ -608,9 +680,14 @@ const UDP_MAX_POLL_DELAY: Duration = Duration::from_secs(30);
608680
/// candidate gathering and DNS fanout produce dozens of distinct
609681
/// targets; an abusive or runaway client could produce thousands.
610682
/// 256 is generous for legitimate use and bounds tunnel-node UDP
611-
/// sessions a single ASSOCIATE can hold open. On overflow we evict
612-
/// the least-recently-inserted target (rough LRU — good enough for
613-
/// long-tail eviction without tracking access on the hot path).
683+
/// sessions a single ASSOCIATE can hold open.
684+
///
685+
/// Eviction policy is FIFO by insertion time, not true LRU — repeated
686+
/// uplinks to a hot session do not move it to the back. Real LRU
687+
/// would need a touch on every uplink (extra lock acquisition per
688+
/// datagram); the long-tail of dead targets gets cleaned up here just
689+
/// fine without that cost, and live targets are typically also recently
690+
/// inserted.
614691
const MAX_UDP_SESSIONS_PER_ASSOCIATE: usize = 256;
615692

616693
/// Drop UDP datagrams larger than this (pre-base64). Standard MTU is
@@ -662,14 +739,16 @@ async fn handle_socks5_udp_associate(
662739
let mut buf = vec![0u8; SOCKS5_UDP_RECV_BUF_BYTES];
663740
let mut control_buf = [0u8; 1];
664741
let mut client_addr: Option<SocketAddr> = None;
665-
let sessions: Arc<Mutex<HashMap<SocksUdpTarget, UdpRelaySession>>> =
666-
Arc::new(Mutex::new(HashMap::new()));
667-
// Insertion-order log used for LRU-on-overflow eviction. We track
668-
// it alongside (rather than inside) the HashMap so eviction can
669-
// run under the same lock as the cap check.
670-
let mut insertion_order: VecDeque<SocksUdpTarget> = VecDeque::new();
742+
let state: Arc<Mutex<UdpRelayState>> = Arc::new(Mutex::new(UdpRelayState::new()));
743+
// Tracking per-target tasks here — instead of bare `tokio::spawn`
744+
// — lets the teardown path call `abort_all()`, cancelling any
745+
// in-flight `mux.udp_data` await. Without it, a task mid-poll
746+
// could keep paying tunnel-node round trips for up to 5 s after
747+
// the SOCKS5 client went away.
748+
let mut tasks: JoinSet<()> = JoinSet::new();
671749
let mut oversized_dropped: u64 = 0;
672750
let mut sessions_evicted: u64 = 0;
751+
let mut foreign_ip_drops: u64 = 0;
673752

674753
loop {
675754
tokio::select! {
@@ -682,11 +761,32 @@ async fn handle_socks5_udp_associate(
682761
}
683762
};
684763
// Source-IP check: anything not from the SOCKS5 client's
685-
// host is dropped silently. After the first valid packet,
686-
// also lock to its source port (RFC 1928 §6).
764+
// host is dropped silently.
687765
if peer.ip() != client_peer_ip {
766+
foreign_ip_drops += 1;
767+
if foreign_ip_drops == 1 || foreign_ip_drops.is_multiple_of(100) {
768+
tracing::debug!(
769+
"udp dropped from unauthorized source {}: count={}",
770+
peer.ip(),
771+
foreign_ip_drops,
772+
);
773+
}
688774
continue;
689775
}
776+
777+
// Parse BEFORE port-locking. A malformed datagram from
778+
// the right IP must not pin client_addr to its source
779+
// port — otherwise a co-tenant on the bind interface
780+
// can race one bad packet to DoS the legitimate client
781+
// (whose real datagram, sent from a different ephemeral
782+
// port, would then be silently rejected).
783+
let Some((target, payload)) = parse_socks5_udp_packet(&buf[..n]) else {
784+
continue;
785+
};
786+
787+
// RFC 1928 §6: lock to the first VALID datagram's source
788+
// port. Subsequent datagrams must come from the same
789+
// (ip, port) pair.
690790
if let Some(existing) = client_addr {
691791
if existing != peer {
692792
continue;
@@ -696,10 +796,6 @@ async fn handle_socks5_udp_associate(
696796
client_addr = Some(peer);
697797
}
698798

699-
let Some((target, payload)) = parse_socks5_udp_packet(&buf[..n]) else {
700-
continue;
701-
};
702-
703799
// Size guard: drop oversize datagrams before they reach
704800
// the mux. Each datagram costs ~payload * 1.33 in the
705801
// batched JSON envelope plus tunnel-node CPU; uncapped,
@@ -721,38 +817,31 @@ async fn handle_socks5_udp_associate(
721817
// Fast path: existing session — push payload onto its
722818
// bounded uplink queue, drop on overflow (UDP semantics).
723819
{
724-
let sess = sessions.lock().await;
725-
if let Some(session) = sess.get(&target) {
726-
let _ = session.uplink.try_send(payload);
820+
let st = state.lock().await;
821+
if let Some(uplink) = st.get_uplink(&target) {
822+
let _ = uplink.try_send(payload);
727823
continue;
728824
}
729825
}
730826

731-
// Cap reached → evict the oldest session before opening
732-
// a new one. The evicted target's `UdpRelaySession` is
733-
// dropped here, which closes its uplink channel; the
734-
// task then exits its select! and tells tunnel-node to
735-
// close. Any in-flight uplink already in the channel is
736-
// delivered before the task exits.
827+
// Cap reached → evict oldest sessions before opening a
828+
// new one. Each evicted entry drops its uplink Sender,
829+
// which causes the per-session task to exit its select
830+
// and tell tunnel-node to close. Any uplink already in
831+
// that channel is delivered before the task exits.
737832
{
738-
let mut sess = sessions.lock().await;
739-
while sess.len() >= MAX_UDP_SESSIONS_PER_ASSOCIATE {
740-
let Some(victim) = insertion_order.pop_front() else {
741-
break;
742-
};
743-
if sess.remove(&victim).is_some() {
744-
sessions_evicted += 1;
745-
if sessions_evicted == 1
746-
|| sessions_evicted.is_multiple_of(50)
747-
{
748-
tracing::debug!(
749-
"udp session cap {} reached; evicted {}:{} (total evicted={})",
750-
MAX_UDP_SESSIONS_PER_ASSOCIATE,
751-
victim.host,
752-
victim.port,
753-
sessions_evicted,
754-
);
755-
}
833+
let mut st = state.lock().await;
834+
let evicted = st.evict_until_under(MAX_UDP_SESSIONS_PER_ASSOCIATE);
835+
for victim in evicted {
836+
sessions_evicted += 1;
837+
if sessions_evicted == 1 || sessions_evicted.is_multiple_of(50) {
838+
tracing::debug!(
839+
"udp session cap {} reached; evicted {}:{} (total evicted={})",
840+
MAX_UDP_SESSIONS_PER_ASSOCIATE,
841+
victim.host,
842+
victim.port,
843+
sessions_evicted,
844+
);
756845
}
757846
}
758847
}
@@ -787,9 +876,9 @@ async fn handle_socks5_udp_associate(
787876
let task_mux = mux.clone();
788877
let task_udp = udp.clone();
789878
let task_target = target.clone();
790-
let task_sessions = sessions.clone();
879+
let task_state = state.clone();
791880
let task_sid = sid.clone();
792-
tokio::spawn(async move {
881+
tasks.spawn(async move {
793882
udp_session_task(
794883
task_mux,
795884
task_udp,
@@ -799,17 +888,21 @@ async fn handle_socks5_udp_associate(
799888
uplink_rx,
800889
)
801890
.await;
802-
// On exit (eof / mux error / channel close) remove
803-
// ourselves from the dispatch map so a future packet
804-
// to the same target opens a fresh tunnel-node session.
805-
task_sessions.lock().await.remove(&task_target);
891+
// Natural-exit cleanup (eof / mux error / channel
892+
// close): remove from shared state so a future
893+
// packet to the same target opens a fresh session,
894+
// and so insertion_order doesn't leak. Skipped on
895+
// teardown since abort_all cancels this await point.
896+
task_state.lock().await.remove(&task_target);
806897
});
807898

808-
insertion_order.push_back(target.clone());
809-
sessions
810-
.lock()
811-
.await
812-
.insert(target, UdpRelaySession { uplink: uplink_tx });
899+
state.lock().await.insert(
900+
target,
901+
UdpRelaySession {
902+
sid,
903+
uplink: uplink_tx,
904+
},
905+
);
813906
}
814907
read = control.read(&mut control_buf) => {
815908
match read {
@@ -820,10 +913,22 @@ async fn handle_socks5_udp_associate(
820913
}
821914
}
822915

823-
// Drop every uplink Sender. Each per-session task observes its
824-
// receiver close, breaks out of select!, and issues close_session
825-
// on the tunnel-node before exiting.
826-
sessions.lock().await.clear();
916+
// Teardown. Snapshot live sids first; they're authoritative for
917+
// which tunnel-node sessions still exist. Then clear state — that
918+
// drops every uplink Sender, so any task waiting on `recv()` wakes
919+
// and exits naturally. Finally `abort_all` cancels tasks that were
920+
// mid-`mux.udp_data` await; for those the natural-exit close won't
921+
// run, so we send close_session here on their behalf.
922+
let live_sids: Vec<String>;
923+
{
924+
let mut st = state.lock().await;
925+
live_sids = st.live_sids();
926+
st.clear();
927+
}
928+
tasks.abort_all();
929+
for sid in live_sids {
930+
mux.close_session(&sid).await;
931+
}
827932
Ok(())
828933
}
829934

0 commit comments

Comments
 (0)