fix: harden ratchet sessions and throttle BitTorrent DHT traffic
check / check (macos-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 26s

- Ratchet: cap outbound NSR pending entries per peer and globally, age them out after 180s, and prune expired or excess sessions.
- Ratchet: keep NSR pending entries across multi-NSR replies, skip failed decrypts instead of aborting, and bound inbound pending entries.
- Ratchet: expire sessions with stale receive state or high message counts; only mark sessions confirmed when no reply has been received.
- Torrent DHT: add per-node cooldowns for get_peers and announce, limit fanout and pending transactions, and skip nodes already in the routing table.
- Torrent DHT: use slower maintenance and query intervals in public mode.
- Torrent peers: mark ratchet sessions stale after stalled SYN, connect timeout, handshake timeout, or idle timeout so they re-key.
- Torrent peers: raise the per-torrent peer limit to 16 and log I2CP decode errors in debug mode.
This commit is contained in:
nandi committed 2026-11-28 19:43:10 -08:00
1 parent 4bb81f1b80
commit 5d97ad8b28
4 files changed
+474 -71

No files matched your search

+21 -1
View File
@@ -468,6 +468,19 @@ fn Router::finish_remote_stream_connect(
)
}
///|
fn streaming_err_msg(e : @streaming.StreamingError) -> String {
match e {
Encoding(_) => "encoding error"
Common(_) => "common decode error"
Crypto(_) => "crypto error"
InvalidFormat(msg) => "invalid format: \{msg}"
InvalidLength(msg) => "invalid length: \{msg}"
InvalidSignature => "invalid signature"
ProtocolError(msg) => "protocol error: \{msg}"
}
}
///|
fn Router::handle_incoming_garlic(
self : Router,
@@ -526,7 +539,14 @@ fn Router::handle_incoming_garlic(
Some(mgr) => {
let prev_streams = mgr.streams.length()
let conn_opt = mgr.handle_incoming_i2cp(data, now_ms) catch {
_ => None
e => {
if self.debug {
println(
"[debug] incoming I2CP error on \{sess.id}: \{streaming_err_msg(e)}",
)
}
None
}
}
let send_ls2_now = mgr.streams.length() > prev_streams
match conn_opt {
+279 -42
View File
@@ -52,6 +52,7 @@ priv struct TorrentPeerConn {
in_flight : Array[(Int32, Int32, Int32, UInt64)] // (piece_idx, begin, len, req_ms)
mut blocks_recv : UInt64
mut dht_pinged : Bool
mut ratchet_reset : Bool
mut close_reason : String
}
@@ -110,6 +111,8 @@ priv struct TorrentEngine {
torrents : Array[ActiveTorrent]
pending_inbound : Array[TorrentInboundConn]
pending_dht_pings : Array[(@common.Hash, UInt32, UInt64)]
dht_query_cd : Array[(@common.Hash, Bytes, UInt64)]
dht_announce_cd : Array[(@common.Hash, Bytes, UInt64)]
mut last_dht_maint_ms : UInt64
mut last_ls2_pub_ms : UInt64
mut last_ls2_pub_tunnels : Int32
@@ -672,6 +675,8 @@ pub fn Router::enable_torrent_engine(
torrents: [],
pending_inbound: [],
pending_dht_pings: [],
dht_query_cd: [],
dht_announce_cd: [],
last_dht_maint_ms: 0UL,
last_ls2_pub_ms: @ntcp2_net.unix_time_ms(),
last_ls2_pub_tunnels: self.tunnels.inbound.length(),
@@ -1089,6 +1094,71 @@ fn Router::send_torrent_i2cp(
true
}
///|
fn bt_dht_cooldown_allow(
table : Array[(@common.Hash, Bytes, UInt64)],
node_hash : @common.Hash,
key_20 : Bytes,
now_ms : UInt64,
cooldown_ms : UInt64,
) -> Bool {
let mut i = 0
let mut recent = false
while i < table.length() {
let e = table[i]
if now_ms >= e.2 + cooldown_ms {
let _ = table.remove(i)
} else {
if e.0 == node_hash && @crypto.ct_eq(e.1, key_20) {
recent = true
}
i += 1
}
}
if recent {
return false
}
while table.length() >= 512 {
let _ = table.remove(0)
}
table.push((node_hash, key_20, now_ms))
true
}
///|
fn bt_dht_can_query(
eng : TorrentEngine,
node_hash : @common.Hash,
target_20 : Bytes,
now_ms : UInt64,
cooldown_ms : UInt64,
) -> Bool {
bt_dht_cooldown_allow(
eng.dht_query_cd,
node_hash,
target_20,
now_ms,
cooldown_ms,
)
}
///|
fn bt_dht_can_announce(
eng : TorrentEngine,
node_hash : @common.Hash,
ih : Bytes,
now_ms : UInt64,
cooldown_ms : UInt64,
) -> Bool {
bt_dht_cooldown_allow(
eng.dht_announce_cd,
node_hash,
ih,
now_ms,
cooldown_ms,
)
}
///|
fn Router::send_dht_query(
self : Router,
@@ -1108,10 +1178,12 @@ fn Router::send_dht_query(
None => return false
}
let now_sec = (now_ms / 1000UL).to_uint()
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(l) if l.leases.length() > 0 => ()
let ls2 = match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(l) if l.leases.length() > 0 => l
_ => {
let _ = self.start_proxy_netdb_lookup(target_hash)
if self.pending_lookups.length() < 16 {
let _ = self.start_proxy_netdb_lookup(target_hash)
}
return false
}
}
@@ -1128,7 +1200,13 @@ fn Router::send_dht_query(
}
let port = if target_port == 0U { 6881U } else { target_port }
let i2cp = dgram.to_i2cp_bytes(from_port=eng.dht.query_port, to_port=port)
if !self.send_torrent_i2cp(sess, target_hash, i2cp, send_ls2=true) {
let need_ls2 = match (sess.ratchet, extract_x25519_key(ls2)) {
(Some(r), Some(pstat)) =>
!r.has_active_session(pstat, now_sec~) ||
now_ms < eng.last_ls2_pub_ms + 30000UL
_ => true
}
if !self.send_torrent_i2cp(sess, target_hash, i2cp, send_ls2=need_ls2) {
return false
}
let kind_str = match kind {
@@ -1330,6 +1408,8 @@ fn Router::poll_dht_datagrams(
tx.port,
now_ms,
)
let query_cd_ms = if self.public_mode { 60000UL } else { 1500UL }
let announce_cd_ms = if self.public_mode { 300000UL } else { 5000UL }
if nodes.length() > 0 {
let decoded_nodes = @bittorrent.decode_compact_nodes(
nodes,
@@ -1337,28 +1417,41 @@ fn Router::poll_dht_datagrams(
) catch {
_ => []
}
let mut fanout_sent = 0
for dn in decoded_nodes {
let was_known = eng.dht.has_node(dn.dest_hash, dn.port)
let added = eng.dht.upsert_node(
dn.node_id,
dn.dest_hash,
dn.port,
now_ms,
)
if added {
if added && !was_known && fanout_sent < 3 {
match tx.info_hash {
Some(ih) =>
match bt_find_torrent_by_ih(eng, ih) {
Some(t) if !t.paused && t.known_peers.length() < 8 => {
let _ = self.send_dht_query(
Some(t)
if !t.paused &&
t.known_peers.length() < 8 &&
eng.dht.pending_txs.length() < 24 &&
bt_dht_can_query(
eng,
sess,
dn.dest_hash,
dn.port,
GetPeers(info_hash=ih),
ih,
now_ms,
info_hash=Some(ih),
)
}
query_cd_ms,
) =>
if self.send_dht_query(
eng,
sess,
dn.dest_hash,
dn.port,
GetPeers(info_hash=ih),
now_ms,
info_hash=Some(ih),
) {
fanout_sent += 1
}
_ => ()
}
None => ()
@@ -1387,22 +1480,29 @@ fn Router::poll_dht_datagrams(
}
if tx.kind == "get_peers" && !t.paused {
match token {
Some(tk) => {
let _ = self.send_dht_query(
eng,
sess,
tx.dest_hash,
tx.port,
AnnouncePeer(
info_hash=ih,
port=eng.dht.query_port,
token=tk,
implied_port=false,
),
now_ms,
info_hash=Some(ih),
)
}
Some(tk) =>
if bt_dht_can_announce(
eng,
tx.dest_hash,
ih,
now_ms,
announce_cd_ms,
) {
let _ = self.send_dht_query(
eng,
sess,
tx.dest_hash,
tx.port,
AnnouncePeer(
info_hash=ih,
port=eng.dht.query_port,
token=tk,
implied_port=false,
),
now_ms,
info_hash=Some(ih),
)
}
None => ()
}
}
@@ -1452,10 +1552,14 @@ fn Router::step_dht(
pi += 1
}
// Background self-lookup maintenance every 25s
if eng.dht.nodes.length() > 0 && now_ms >= eng.last_dht_maint_ms + 25000UL {
// Background self-lookup maintenance
let maint_interval_ms = if self.public_mode { 60000UL } else { 25000UL }
if eng.dht.nodes.length() > 0 &&
eng.dht.pending_txs.length() < 16 &&
now_ms >= eng.last_dht_maint_ms + maint_interval_ms {
eng.last_dht_maint_ms = now_ms
let closest = eng.dht.closest_nodes(eng.dht.local_id, limit=3)
let maint_limit = if self.public_mode { 2 } else { 3 }
let closest = eng.dht.closest_nodes(eng.dht.local_id, limit=maint_limit)
for n in closest {
if self.send_dht_query(
eng,
@@ -1471,20 +1575,35 @@ fn Router::step_dht(
}
// Per-torrent DHT peer lookup & announce
let query_cd_ms = if self.public_mode { 60000UL } else { 1500UL }
for t in eng.torrents {
if t.paused || eng.dht.nodes.length() == 0 {
continue
}
eng.dht.store_peer(t.info_hash, sess.hash, now_ms)
let interval_ms = if t.known_peers.length() == 0 && !t.completed {
let interval_ms = if self.public_mode {
if t.known_peers.length() == 0 && !t.completed {
5000UL
} else {
45000UL
}
} else if t.known_peers.length() == 0 && !t.completed {
800UL
} else {
15000UL
}
if now_ms >= t.last_dht_lookup_ms + interval_ms {
if now_ms >= t.last_dht_lookup_ms + interval_ms &&
eng.dht.pending_txs.length() < 24 {
t.last_dht_lookup_ms = now_ms
let closest = eng.dht.closest_nodes(t.info_hash, limit=4)
let closest = eng.dht.closest_nodes(t.info_hash, limit=12)
let mut sent_cnt = 0
for n in closest {
if sent_cnt >= 3 || eng.dht.pending_txs.length() >= 24 {
break
}
if !bt_dht_can_query(eng, n.dest_hash, t.info_hash, now_ms, query_cd_ms) {
continue
}
if self.send_dht_query(
eng,
sess,
@@ -1494,6 +1613,7 @@ fn Router::step_dht(
now_ms,
info_hash=Some(t.info_hash),
) {
sent_cnt += 1
did_work = true
}
}
@@ -2561,6 +2681,67 @@ fn Router::bt_process_peer_messages(
}
}
///|
fn Router::bt_has_active_peer(
self : Router,
eng : TorrentEngine,
peer_hash : @common.Hash,
) -> Bool {
let _ = self
for t in eng.torrents {
for p in t.peers {
if p.peer_hash == peer_hash && p.state == 3 {
return true
}
}
}
false
}
///|
fn Router::bt_mark_peer_ratchet_stale(
self : Router,
eng : TorrentEngine,
sess : SamSession,
p : TorrentPeerConn,
now_ms : UInt64,
now_sec : UInt32,
quiet_sec : UInt32,
drop_ls2~ : Bool = false,
respect_cooldown~ : Bool = true,
reason~ : String = "",
) -> Unit {
if self.bt_has_active_peer(eng, p.peer_hash) {
return
}
if p.peer_static.length() == 32 {
match sess.ratchet {
Some(r) =>
if r.has_active_session(p.peer_static, now_sec~) {
let lrx = r.last_recv_sec(p.peer_static)
let quiet_ok = lrx == 0U || now_sec > lrx + quiet_sec
let cooldown_ok = if respect_cooldown {
self.try_acquire_ratchet_reset(p.peer_hash, now_ms, 15000UL)
} else {
true
}
if quiet_ok && cooldown_ok {
r.mark_send_stale(p.peer_static)
if self.debug {
println(
"[debug] bt peer \{bt_short_b32(p.peer_hash)} marking ECIES ratchet send-stale (\{reason})",
)
}
}
}
None => ()
}
}
if drop_ls2 {
let _ = self.netdb.remove_lease_set2(p.peer_hash)
}
}
///|
fn Router::step_torrent_engine(self : Router) -> Bool {
let eng = match self.torrent_engine {
@@ -2705,6 +2886,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
in_flight: [],
blocks_recv: 0UL,
dht_pinged: false,
ratchet_reset: false,
close_reason: "",
}
if self.debug {
@@ -2757,10 +2939,10 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
if t.paused {
continue
}
// Spawn up to 12 peers per torrent when incomplete
// Spawn up to 16 peers per torrent when incomplete
if !t.completed {
for kh in t.known_peers {
if t.peers.length() >= 12 {
if t.peers.length() >= 16 {
break
}
if bt_is_peer_backed_off(t, kh, now_ms) {
@@ -2808,6 +2990,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
in_flight: [],
blocks_recv: 0UL,
dht_pinged: false,
ratchet_reset: false,
close_reason: "",
})
did_work = true
@@ -2901,8 +3084,37 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
} else {
"stream connect timeout (30s)"
}
bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL)
let backoff_ms = if self.public_mode { 20000UL } else { 5000UL }
bt_set_peer_backoff(t, p.peer_hash, now_ms + backoff_ms)
p.state = 4
if conn.state != Reset {
self.bt_mark_peer_ratchet_stale(
eng,
sess,
p,
now_ms,
now_sec,
15U,
drop_ls2=true,
respect_cooldown=false,
reason="stream connect timeout",
)
}
} else if conn.state == SynSent &&
!p.ratchet_reset &&
now_ms > p.started_ms + 10000UL {
p.ratchet_reset = true
self.bt_mark_peer_ratchet_stale(
eng,
sess,
p,
now_ms,
now_sec,
10U,
drop_ls2=false,
respect_cooldown=true,
reason="stalled SYN",
)
}
}
2 => {
@@ -2924,6 +3136,7 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
}
did_work = true
}
let hs_timeout_ms = if self.public_mode { 30000UL } else { 20000UL }
if p.recv_buf.length() >= 68 {
let hs_raw = Bytes::from_array(p.recv_buf[:68])
let parsed = Some(@bittorrent.decode_handshake(hs_raw)) catch {
@@ -2952,16 +3165,30 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
}
} else if conn.is_eof() ||
conn.state == Reset ||
now_ms > p.last_activity_ms + 20000UL {
now_ms > p.last_activity_ms + hs_timeout_ms {
p.close_reason = if conn.state == Reset {
"stream reset before bt handshake"
} else if conn.is_eof() {
"stream eof before bt handshake"
} else {
"bt handshake timeout (20s)"
"bt handshake timeout (\{hs_timeout_ms / 1000UL}s)"
}
bt_set_peer_backoff(t, p.peer_hash, now_ms + 10000UL)
let backoff_ms = if self.public_mode { 25000UL } else { 10000UL }
bt_set_peer_backoff(t, p.peer_hash, now_ms + backoff_ms)
p.state = 4
if conn.state != Reset {
self.bt_mark_peer_ratchet_stale(
eng,
sess,
p,
now_ms,
now_sec,
20U,
drop_ls2=false,
respect_cooldown=false,
reason=p.close_reason,
)
}
}
}
3 => {
@@ -3009,8 +3236,18 @@ fn Router::step_torrent_engine(self : Router) -> Bool {
} else if !t.completed && now_ms > p.last_activity_ms + 90000UL {
p.close_reason = "idle 90s timeout"
bt_set_peer_backoff(t, p.peer_hash, now_ms + 15000UL)
let _ = self.netdb.remove_lease_set2(p.peer_hash)
p.state = 4
self.bt_mark_peer_ratchet_stale(
eng,
sess,
p,
now_ms,
now_sec,
15U,
drop_ls2=true,
respect_cooldown=false,
reason="idle 90s timeout",
)
}
}
}