diff --git a/bittorrent/dht.mbt b/bittorrent/dht.mbt index c2920d7..f4082bd 100644 --- a/bittorrent/dht.mbt +++ b/bittorrent/dht.mbt @@ -480,6 +480,21 @@ pub fn I2pDht::prune_expired_txs(self : I2pDht, now_ms : UInt64) -> Unit { } } +///| +/// Returns `true` if `(dest_hash, port)` is already present in the DHT routing table. +pub fn I2pDht::has_node( + self : I2pDht, + dest_hash : @common.Hash, + port : UInt32, +) -> Bool { + for n in self.nodes { + if n.dest_hash == dest_hash && n.port == port { + return true + } + } + false +} + ///| /// Inserts or refreshes a remote DHT node, enforcing Secure I2P Node ID verification by default. pub fn I2pDht::upsert_node( diff --git a/ratchet/ecies.mbt b/ratchet/ecies.mbt index 2e1890f..739ccd8 100644 --- a/ratchet/ecies.mbt +++ b/ratchet/ecies.mbt @@ -634,6 +634,7 @@ pub struct RatchetSessionManager { local_static : @noise.KeyPair sessions : Array[RatchetPeerSession] outbound_pending : Array[(Bytes, PendingNewSession)] // (nsr_tag_8, pending) + priv outbound_pending_sec : Array[UInt32] inbound_pending : Array[PendingNewSession] // waiting to send NSR to remote_static_pub } @@ -641,7 +642,13 @@ pub struct RatchetSessionManager { pub fn RatchetSessionManager::new( local_static : @noise.KeyPair, ) -> RatchetSessionManager { - { local_static, sessions: [], outbound_pending: [], inbound_pending: [], } + { + local_static, + sessions: [], + outbound_pending: [], + outbound_pending_sec: [], + inbound_pending: [], + } } ///| @@ -652,15 +659,129 @@ fn is_ratchet_session_expired( if now_sec == 0U || sess.last_used_sec == 0U { return false } + if sess.send_tagset.msg_num >= 60000U { + return true + } if now_sec > sess.last_used_sec + 300U { return true } if !sess.confirmed && now_sec > sess.last_used_sec + 45U { return true } + if sess.last_recv_sec > 0U && + !sess.confirmed && + now_sec > sess.last_recv_sec + 45U { + return true + } + if sess.last_recv_sec > 0U && now_sec > sess.last_recv_sec + 180U { + return true + } false } +///| +fn RatchetSessionManager::remove_outbound_pending( + self : RatchetSessionManager, + idx : Int32, +) -> Unit { + let _ = self.outbound_pending.remove(idx) + if idx < self.outbound_pending_sec.length() { + let _ = self.outbound_pending_sec.remove(idx) + } +} + +///| +fn RatchetSessionManager::prune_outbound_pending( + self : RatchetSessionManager, + now_sec : UInt32, +) -> Unit { + if now_sec == 0U { + return + } + let mut i = 0 + while i < self.outbound_pending.length() { + let ts = if i < self.outbound_pending_sec.length() { + self.outbound_pending_sec[i] + } else { + 0U + } + if ts > 0U && now_sec > ts + 180U { + self.remove_outbound_pending(i) + } else { + i += 1 + } + } +} + +///| +fn RatchetSessionManager::cap_peer_outbound_pending( + self : RatchetSessionManager, + remote_static_pub : Bytes, + max_tags : Int32, +) -> Unit { + while true { + let mut count = 0 + let mut oldest_idx = -1 + for i = 0; i < self.outbound_pending.length(); i = i + 1 { + if @crypto.ct_eq( + self.outbound_pending[i].1.remote_static_pub, + remote_static_pub, + ) { + count += 1 + if oldest_idx < 0 { + oldest_idx = i + } + } + } + if count <= max_tags || oldest_idx < 0 { + break + } + self.remove_outbound_pending(oldest_idx) + } +} + +///| +fn RatchetSessionManager::push_outbound_pending( + self : RatchetSessionManager, + tag : Bytes, + pending : PendingNewSession, + now_sec : UInt32, +) -> Unit { + while self.outbound_pending.length() >= 2048 { + self.remove_outbound_pending(0) + } + self.outbound_pending.push((tag, pending)) + self.outbound_pending_sec.push(now_sec) +} + +///| +fn RatchetSessionManager::prune_expired_sessions( + self : RatchetSessionManager, + now_sec : UInt32, +) -> Unit { + if now_sec > 0U && self.sessions.length() > 128 { + let mut i = 0 + while i < self.sessions.length() { + if is_ratchet_session_expired(self.sessions[i], now_sec) { + let _ = self.sessions.remove(i) + } else { + i += 1 + } + } + } + while self.sessions.length() > 512 { + let mut oldest_idx = 0 + let mut oldest_ts = self.sessions[0].last_used_sec + for i = 1; i < self.sessions.length(); i = i + 1 { + if self.sessions[i].last_used_sec < oldest_ts { + oldest_ts = self.sessions[i].last_used_sec + oldest_idx = i + } + } + let _ = self.sessions.remove(oldest_idx) + } +} + ///| fn RatchetSessionManager::find_session( self : RatchetSessionManager, @@ -782,7 +903,7 @@ pub fn RatchetSessionManager::drop_session( self.outbound_pending[pi].1.remote_static_pub, remote_static_pub, ) { - let _ = self.outbound_pending.remove(pi) + self.remove_outbound_pending(pi) } else { pi += 1 } @@ -860,6 +981,7 @@ pub fn RatchetSessionManager::encrypt_to_peer( now_sec : UInt32, next_rand_32 : () -> Bytes, ) -> Bytes raise RatchetError { + self.prune_expired_sessions(now_sec) let mut ei = 0 while ei < self.sessions.length() { let s = self.sessions[ei] @@ -875,7 +997,9 @@ pub fn RatchetSessionManager::encrypt_to_peer( let sess = self.sessions[sidx] sess.last_used_sec = now_sec sess.sent_es = true - sess.confirmed = true + if sess.last_recv_sec == 0U { + sess.confirmed = true + } return sess.encrypt_existing(blocks) } // Check if we owe this peer an NSR @@ -916,15 +1040,15 @@ pub fn RatchetSessionManager::encrypt_to_peer( ns_blocks, ) match pending_opt { - Some(p) => + Some(p) => { + self.prune_outbound_pending(now_sec) // Pre-register first 6 NSR tags so any reply (or multi-NSR) matches for _k = 0; _k < 6; _k = _k + 1 { let (_n, tag, _k32) = p.nsr_tagset.next_entry() - while self.outbound_pending.length() >= 128 { - let _ = self.outbound_pending.remove(0) - } - self.outbound_pending.push((tag, p)) + self.push_outbound_pending(tag, p, now_sec) } + self.cap_peer_outbound_pending(remote_static_pub, 24) + } None => () } wire @@ -964,31 +1088,35 @@ pub fn RatchetSessionManager::decrypt_incoming( } si -= 1 } - // 2. New Session Reply lookup + // 2. New Session Reply lookup (keep entries across multi-NSR until aged out) for i = 0; i < self.outbound_pending.length(); i = i + 1 { let (expected_tag, p) = self.outbound_pending[i] if @crypto.ct_eq(expected_tag, tag_8) { - let (blocks, sess) = decrypt_new_session_reply( - self.local_static, - p, - garlic_data, - ) - let _ = self.outbound_pending.remove(i) - sess.last_used_sec = now_sec - sess.last_recv_sec = now_sec - let mut already_has_active_es = false - for s in self.sessions { - if s.send_enabled && - s.sent_es && - @crypto.ct_eq(s.remote_static_pub, sess.remote_static_pub) { - already_has_active_es = true - break + let nsr_res = Some( + decrypt_new_session_reply(self.local_static, p, garlic_data), + ) catch { + _ => None + } + match nsr_res { + Some((blocks, sess)) => { + sess.last_used_sec = now_sec + sess.last_recv_sec = now_sec + let mut already_has_active_es = false + for s in self.sessions { + if s.send_enabled && + s.sent_es && + @crypto.ct_eq(s.remote_static_pub, sess.remote_static_pub) { + already_has_active_es = true + break + } + } + sess.send_enabled = !already_has_active_es + self.sessions.push(sess) + self.cap_peer_sessions(sess.remote_static_pub, 4) + return (Some(sess.remote_static_pub), blocks) } + None => () } - sess.send_enabled = !already_has_active_es - self.sessions.push(sess) - self.cap_peer_sessions(sess.remote_static_pub, 4) - return (Some(sess.remote_static_pub), blocks) } } } @@ -1011,6 +1139,9 @@ pub fn RatchetSessionManager::decrypt_incoming( i += 1 } } + while self.inbound_pending.length() >= 256 { + let _ = self.inbound_pending.remove(0) + } self.inbound_pending.push(p) (Some(p.remote_static_pub), blocks) } diff --git a/router/sam_handler.mbt b/router/sam_handler.mbt index 4796f57..ee05fc3 100644 --- a/router/sam_handler.mbt +++ b/router/sam_handler.mbt @@ -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 { diff --git a/router/torrent_engine.mbt b/router/torrent_engine.mbt index f98362a..6fbd113 100644 --- a/router/torrent_engine.mbt +++ b/router/torrent_engine.mbt @@ -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", + ) } } }