///| /// Pure MoonBit Router-integrated I2P BitTorrent + I2P DHT Engine. /// /// Transport stack: /// - Peer & Tracker TCP-like streams: I2P Streaming (`from_port=0U`, `to_port=0U` / tracker port) /// over Proposal 144 ECIES-X25519-AEAD-Ratchet Garlic using internal `"__torrent__"` session. /// - I2P DHT KRPC (`ping`, `find_node`, `get_peers`, `announce_peer`): /// - Queries: I2CP protocol `17` (0x11) Ed25519 RepliableDatagram with `LeaseSet2` piggybacked /// - Replies: I2CP protocol `18` (0x12) RawDatagram to requester's `rport` (`query_port + 1`) ///| priv struct TorrentTrackerConn { url : String host : String port : UInt32 path : String mut state : Int32 // 0=idle/backoff, 1=lookup_ls2, 2=streaming, 3=error_backoff mut started_ms : UInt64 mut next_announce_ms : UInt64 mut stream_id : UInt32 mut peer_hash : @common.Hash? mut sent_req : Bool recv_buf : Array[Byte] } ///| priv struct TorrentPeerConn { peer_hash : @common.Hash mut state : Int32 // 0=lookup_ls2, 1=streaming_connect, 2=await_bt_hs, 3=active, 4=closed mut started_ms : UInt64 mut last_activity_ms : UInt64 mut stream_id : UInt32 mut peer_static : Bytes mut lease_gw : @common.Hash? mut lease_tid : UInt32 recv_buf : Array[Byte] send_buf : Array[Byte] mut sent_bt_hs : Bool mut sent_ext_hs : Bool mut peer_choking : Bool mut am_choking : Bool mut am_interested : Bool mut remote_ext : @bittorrent.RemoteExtensions? mut peer_bitfield : Array[Bool] in_flight : Array[(Int32, Int32, Int32, UInt64)] // (piece_idx, begin, len, req_ms) mut dht_pinged : Bool } ///| priv struct TorrentInboundConn { stream_id : UInt32 peer_hash : @common.Hash peer_static : Bytes lease_gw : @common.Hash lease_tid : UInt32 started_ms : UInt64 recv_buf : Array[Byte] } ///| priv struct ActivePieceBuf { piece_idx : Int32 data : FixedArray[Byte] got_blocks : Array[Bool] num_blocks : Int32 } ///| priv struct ActiveTorrent { info_hash : Bytes info_hash_hex : String mut name : String download_dir : String mut metainfo : @bittorrent.Metainfo? mut raw_info : Bytes mut paused : Bool mut completed : Bool mut error : String mut downloaded_bytes : UInt64 mut uploaded_bytes : UInt64 mut have_pieces : Array[Bool] inflight_pieces : Array[ActivePieceBuf] mut meta_size : Int32 meta_pieces : Array[(Int32, Bytes)] mut meta_req_ms : UInt64 known_peers : Array[@common.Hash] peers : Array[TorrentPeerConn] trackers : Array[TorrentTrackerConn] mut last_dht_lookup_ms : UInt64 mut last_pex_ms : UInt64 } ///| priv struct TorrentEngine { session_id : String peer_id : Bytes mut download_dir : String dht : @bittorrent.I2pDht torrents : Array[ActiveTorrent] pending_inbound : Array[TorrentInboundConn] pending_dht_pings : Array[(@common.Hash, UInt32, UInt64)] mut last_dht_maint_ms : UInt64 mut last_ls2_pub_ms : UInt64 mut last_ls2_pub_tunnels : Int32 } ///| fn bt_default_download_dir() -> String { let home = @ntcp2_net.get_home_dir() if home.length() > 0 { home + "/Downloads/moon-i2p" } else { "./downloads" } } ///| fn bt_normalize_dir(dir : String) -> String { if dir.length() > 1 && dir.has_suffix("/") { dir[:dir.length() - 1].to_owned() } else { dir } } ///| fn bt_join_rel_path(base_dir : String, segs : Array[String]) -> String { let out = StringBuilder() out.write_string(bt_normalize_dir(base_dir)) for seg in segs { out.write_char('/') out.write_string(seg) } out.to_string() } ///| fn bt_parent_dir(base_dir : String, segs : Array[String]) -> String { if segs.length() <= 1 { return bt_normalize_dir(base_dir) } let out = StringBuilder() out.write_string(bt_normalize_dir(base_dir)) for i = 0; i < segs.length() - 1; i = i + 1 { out.write_char('/') out.write_string(segs[i]) } out.to_string() } ///| fn bt_hex_lower(s : String) -> String { s.trim().to_owned().to_lower() } ///| fn bt_err_msg(e : @bittorrent.BtError) -> String { match e { InvalidBencode(m) => "invalid bencode: \{m}" InvalidMetainfo(m) => "invalid metainfo: \{m}" InvalidMagnet(m) => "invalid magnet: \{m}" InvalidWire(m) => "wire error: \{m}" InvalidKrpc(m) => "KRPC error: \{m}" Encoding(_) => "encoding error" Common(_) => "I2P structure error" } } ///| fn bt_piece_length(meta : @bittorrent.Metainfo, piece_idx : Int32) -> Int32 { let num = meta.piece_hashes.length() if piece_idx < 0 || piece_idx >= num { return 0 } let start = piece_idx.to_int64() * meta.piece_length let rem = meta.total_length - start if rem <= 0L { 0 } else if rem < meta.piece_length { rem.to_int() } else { meta.piece_length.to_int() } } ///| fn bt_write_piece_to_files( t : ActiveTorrent, piece_idx : Int32, piece_bytes : Bytes, ) -> Bool { let meta = match t.metainfo { Some(m) => m None => return false } let global_start = piece_idx.to_int64() * meta.piece_length let mut cursor = 0 let mut file_start = 0L for f in meta.files { let file_end = file_start + f.length let piece_end = global_start + piece_bytes.length().to_int64() if piece_end > file_start && global_start < file_end { let overlap_start = if global_start > file_start { global_start } else { file_start } let overlap_end = if piece_end < file_end { piece_end } else { file_end } let chunk_len = (overlap_end - overlap_start).to_int() let slice_off = (overlap_start - global_start).to_int() let file_off = overlap_start - file_start let pdir = bt_parent_dir(t.download_dir, f.path) let _ = @ntcp2_net.mkdir_p(pdir) catch { _ => return false } let full_path = bt_join_rel_path(t.download_dir, f.path) let chunk = piece_bytes[slice_off:slice_off + chunk_len].to_owned() let _ = @ntcp2_net.write_file_at(full_path, file_off, chunk) catch { _ => return false } cursor += chunk_len } file_start = file_end } cursor == piece_bytes.length() } ///| fn bt_read_span_from_files( t : ActiveTorrent, piece_idx : Int32, begin : Int32, length : Int32, ) -> Bytes? { let meta = match t.metainfo { Some(m) => m None => return None } if length <= 0 || begin < 0 { return None } let plen = bt_piece_length(meta, piece_idx) if begin + length > plen { return None } let global_start = piece_idx.to_int64() * meta.piece_length + begin.to_int64() let global_end = global_start + length.to_int64() let w = @encoding.Writer::new(capacity=length) let mut file_start = 0L for f in meta.files { let file_end = file_start + f.length if global_end > file_start && global_start < file_end { let overlap_start = if global_start > file_start { global_start } else { file_start } let overlap_end = if global_end < file_end { global_end } else { file_end } let chunk_len = (overlap_end - overlap_start).to_int() let file_off = overlap_start - file_start let full_path = bt_join_rel_path(t.download_dir, f.path) let got = @ntcp2_net.read_file_at(full_path, file_off, chunk_len) catch { _ => return None } if got.length() != chunk_len { return None } w.write_bytes(got) } file_start = file_end } let res = w.to_bytes() if res.length() == length { Some(res) } else { None } } ///| fn bt_verify_existing_pieces(t : ActiveTorrent) -> Unit { let meta = match t.metainfo { Some(m) => m None => return } let num = meta.piece_hashes.length() if t.have_pieces.length() != num { t.have_pieces = Array::make(num, false) } let mut done_bytes = 0UL let mut all_have = num > 0 for i = 0; i < num; i = i + 1 { let plen = bt_piece_length(meta, i) match bt_read_span_from_files(t, i, 0, plen) { Some(pbytes) => if @crypto.ct_eq(@crypto.sha1(pbytes), meta.piece_hashes[i]) { t.have_pieces[i] = true done_bytes += plen.to_uint64() } else { t.have_pieces[i] = false all_have = false } None => { t.have_pieces[i] = false all_have = false } } } t.downloaded_bytes = done_bytes t.completed = all_have } ///| fn bt_init_torrent_metainfo( t : ActiveTorrent, meta : @bittorrent.Metainfo, ) -> Unit { t.name = meta.name t.raw_info = meta.raw_info t.meta_size = meta.raw_info.length() t.metainfo = Some(meta) t.have_pieces = Array::make(meta.piece_hashes.length(), false) for tr in meta.trackers { bt_add_tracker_url(t, tr) } bt_verify_existing_pieces(t) } ///| fn bt_add_tracker_url(t : ActiveTorrent, url : String) -> Unit { match @bittorrent.parse_http_tracker_url(url) { Some(parsed) => { for existing in t.trackers { if existing.url == url { return } } t.trackers.push({ url, host: parsed.host, port: parsed.port, path: parsed.request_target, state: 0, started_ms: 0UL, next_announce_ms: 0UL, stream_id: 0U, peer_hash: None, sent_req: false, recv_buf: [], }) } None => () } } ///| fn bt_add_known_peer( t : ActiveTorrent, peer_hash : @common.Hash, local_hash : @common.Hash, ) -> Bool { if peer_hash == local_hash { return false } for h in t.known_peers { if h == peer_hash { return false } } t.known_peers.push(peer_hash) true } ///| fn bt_build_bitfield_bytes(have : Array[Bool]) -> Bytes { let num = have.length() let byte_len = (num + 7) / 8 let buf = FixedArray::make(byte_len, b'\x00') for i = 0; i < num; i = i + 1 { if have[i] { let b = buf[i / 8].to_int() | (0x80 >> (i % 8)) buf[i / 8] = b.to_byte() } } Bytes::from_array(buf) } ///| fn bt_decode_bitfield(payload : Bytes, num_pieces : Int32) -> Array[Bool] { let out = Array::make(num_pieces, false) for i = 0; i < num_pieces; i = i + 1 { let byte_idx = i / 8 if byte_idx < payload.length() { let mask = 0x80 >> (i % 8) if (payload[byte_idx].to_int() & mask) != 0 { out[i] = true } } } out } ///| fn bt_pop_front_bytes(buf : Array[Byte], count : Int32) -> Unit { if count <= 0 { return } if count >= buf.length() { buf.clear() return } let rem : Array[Byte] = [] for i = count; i < buf.length(); i = i + 1 { rem.push(buf[i]) } buf.clear() for b in rem { buf.push(b) } } ///| fn bt_find_torrent_by_ih(eng : TorrentEngine, ih : Bytes) -> ActiveTorrent? { for t in eng.torrents { if @crypto.ct_eq(t.info_hash, ih) { return Some(t) } } None } ///| fn bt_find_torrent_by_hex( eng : TorrentEngine, hex_ih : String, ) -> ActiveTorrent? { let norm = bt_hex_lower(hex_ih) for t in eng.torrents { if t.info_hash_hex == norm { return Some(t) } } None } ///| fn Router::resolve_i2p_host_hash(self : Router, host : String) -> @common.Hash? { let trimmed = host.trim().to_owned() if trimmed.length() == 0 { return None } match parse_b32_hash(trimmed) { Some(h) => return Some(h) None => () } let lower = trimmed.to_lower() if lower.length() >= 52 && !lower.contains(".") { match parse_b32_hash(lower + ".b32.i2p") { Some(h) => return Some(h) None => () } } if lower.length() == 64 { let raw = @encoding.hex_decode(lower) catch { _ => b"" } if raw.length() == 32 { let h = @common.Hash::from_bytes(raw) catch { _ => return None } return Some(h) } } match self.resolve_b32_alias(lower) { Some(h) => return Some(h) None => () } match self.resolve_name_local(lower, None) { Some(pub_b64) => { let d = @common.Destination::from_base64(pub_b64) catch { _ => return None } Some(d.hash()) } None => None } } ///| fn Router::ensure_torrent_session(self : Router) -> SamSession? { let sid = "__torrent__" match self.find_session_by_id(sid) { Some(s) => return Some(s) None => () } let (dest, pub_b64, _priv_b64, xkp, seed) = generate_transient_destination() catch { _ => return None } let hash = dest.hash() let b32 = dest.b32_address() let sess : SamSession = { id: sid, dest, hash, pub_b64, b32, virtual_tid: self.alloc_tunnel_id(), x25519_pub: Some(xkp.public_key), ed_seed: Some(seed), ratchet: Some(@ratchet.RatchetSessionManager::new(xkp)), stream_mgr: Some( @streaming.StreamManager::new( dest, seed, initial_stream_id=self.alloc_stream_id(), ), ), } self.sessions.push(sess) self.publish_session_leaseset2(sess) Some(sess) } ///| /// Enables the router's integrated I2P BitTorrent + I2P DHT engine. pub fn Router::enable_torrent_engine( self : Router, download_dir~ : String = "", dht_query_port~ : UInt32 = 6881U, dht_reply_port~ : UInt32 = 6882U, ) -> Unit raise RouterError { let dl_trimmed = download_dir.trim().to_owned() let clean_dir = if dl_trimmed.length() > 0 { bt_normalize_dir(dl_trimmed) } else { bt_default_download_dir() } let _ = @ntcp2_net.mkdir_p(clean_dir) catch { e => raise Net(e) } match self.torrent_engine { Some(eng) => { if dl_trimmed.length() > 0 { eng.download_dir = clean_dir } return } None => () } let sess = match self.ensure_torrent_session() { Some(s) => s None => raise Protocol("failed to initialize __torrent__ I2P session") } let rand14 = @ntcp2_net.random_bytes(14) catch { e => raise Net(e) } let secret = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) } let dht = @bittorrent.I2pDht::new( sess.hash, rand14, secret, query_port=dht_query_port, reply_port=dht_reply_port, ) catch { e => raise Protocol("failed to init I2P DHT: \{bt_err_msg(e)}") } let pid_rand = @ntcp2_net.random_bytes(12) catch { e => raise Net(e) } let pw = @encoding.Writer::new(capacity=20) pw.write_bytes(b"-MI0100-") pw.write_bytes(pid_rand) self.torrent_engine = Some({ session_id: sess.id, peer_id: pw.to_bytes(), download_dir: clean_dir, dht, torrents: [], pending_inbound: [], pending_dht_pings: [], last_dht_maint_ms: 0UL, last_ls2_pub_ms: @ntcp2_net.unix_time_ms(), last_ls2_pub_tunnels: self.tunnels.inbound.length(), }) } ///| pub fn Router::torrent_session_hash(self : Router) -> @common.Hash? { match self.find_session_by_id("__torrent__") { Some(s) => Some(s.hash) None => None } } ///| pub fn Router::torrent_b32_address(self : Router) -> String { match self.find_session_by_id("__torrent__") { Some(s) => s.b32 None => "" } } ///| fn Router::enqueue_dht_bootstrap( self : Router, eng : TorrentEngine, node_hash : @common.Hash, port : UInt32, ) -> Bool { match self.find_session_by_id(eng.session_id) { Some(s) if node_hash == s.hash => return false None => return false _ => () } let use_port = if port == 0U { 6881U } else { port } let now_ms = @ntcp2_net.unix_time_ms() for p in eng.pending_dht_pings { if p.0 == node_hash && p.1 == use_port { return true } } let _ = self.start_proxy_netdb_lookup(node_hash) eng.pending_dht_pings.push((node_hash, use_port, now_ms)) true } ///| pub fn Router::dht_add_bootstrap_node( self : Router, node_hash : @common.Hash, port~ : UInt32 = 6881U, ) -> Bool { let eng = match self.torrent_engine { Some(e) => e None => return false } self.enqueue_dht_bootstrap(eng, node_hash, port) } ///| pub fn Router::add_torrent_bytes( self : Router, torrent_bytes : Bytes, download_dir~ : String = "", ) -> String raise RouterError { self.enable_torrent_engine(download_dir~) let eng = match self.torrent_engine { Some(e) => e None => raise Protocol("torrent engine unavailable") } let meta = @bittorrent.parse_torrent(torrent_bytes) catch { e => raise Protocol("invalid .torrent metainfo: \{bt_err_msg(e)}") } let hex = @encoding.hex_encode(meta.info_hash) let dl_trimmed = download_dir.trim().to_owned() let target_dir = if dl_trimmed.length() > 0 { let d = bt_normalize_dir(dl_trimmed) let _ = @ntcp2_net.mkdir_p(d) catch { e => raise Net(e) } d } else { eng.download_dir } match bt_find_torrent_by_ih(eng, meta.info_hash) { Some(existing) => { if existing.metainfo is None { bt_init_torrent_metainfo(existing, meta) } for tr in meta.trackers { bt_add_tracker_url(existing, tr) } existing.paused = false return hex } None => () } let now_ms = @ntcp2_net.unix_time_ms() let t : ActiveTorrent = { info_hash: meta.info_hash, info_hash_hex: hex, name: meta.name, download_dir: target_dir, metainfo: Some(meta), raw_info: meta.raw_info, paused: false, completed: false, error: "", downloaded_bytes: 0UL, uploaded_bytes: 0UL, have_pieces: Array::make(meta.piece_hashes.length(), false), inflight_pieces: [], meta_size: meta.raw_info.length(), meta_pieces: [], meta_req_ms: 0UL, known_peers: [], peers: [], trackers: [], last_dht_lookup_ms: 0UL, last_pex_ms: 0UL, } bt_init_torrent_metainfo(t, meta) eng.torrents.push(t) match self.find_session_by_id(eng.session_id) { Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) None => () } hex } ///| pub fn Router::add_seed_torrent( self : Router, torrent_bytes : Bytes, seed_dir : String, ) -> String raise RouterError { self.add_torrent_bytes(torrent_bytes, download_dir=seed_dir) } ///| pub fn Router::add_torrent_magnet( self : Router, uri : String, download_dir~ : String = "", ) -> String raise RouterError { self.enable_torrent_engine(download_dir~) let eng = match self.torrent_engine { Some(e) => e None => raise Protocol("torrent engine unavailable") } let mag = @bittorrent.parse_magnet(uri) catch { e => raise Protocol("invalid magnet URI: \{bt_err_msg(e)}") } let hex = @encoding.hex_encode(mag.info_hash) let dl_trimmed = download_dir.trim().to_owned() let target_dir = if dl_trimmed.length() > 0 { let d = bt_normalize_dir(dl_trimmed) let _ = @ntcp2_net.mkdir_p(d) catch { e => raise Net(e) } d } else { eng.download_dir } match bt_find_torrent_by_ih(eng, mag.info_hash) { Some(existing) => { for tr in mag.trackers { bt_add_tracker_url(existing, tr) } for dn in mag.dht_nodes { match self.resolve_i2p_host_hash(dn.0) { Some(h) => { let _ = self.enqueue_dht_bootstrap(eng, h, dn.1) } None => () } } existing.paused = false return hex } None => () } let now_ms = @ntcp2_net.unix_time_ms() let t : ActiveTorrent = { info_hash: mag.info_hash, info_hash_hex: hex, name: if mag.display_name.length() > 0 { mag.display_name } else { hex }, download_dir: target_dir, metainfo: None, raw_info: b"", paused: false, completed: false, error: "", downloaded_bytes: 0UL, uploaded_bytes: 0UL, have_pieces: [], inflight_pieces: [], meta_size: 0, meta_pieces: [], meta_req_ms: 0UL, known_peers: [], peers: [], trackers: [], last_dht_lookup_ms: 0UL, last_pex_ms: 0UL, } for tr in mag.trackers { bt_add_tracker_url(t, tr) } for dn in mag.dht_nodes { match self.resolve_i2p_host_hash(dn.0) { Some(h) => { let _ = self.enqueue_dht_bootstrap(eng, h, dn.1) } None => () } } eng.torrents.push(t) match self.find_session_by_id(eng.session_id) { Some(sess) => eng.dht.store_peer(t.info_hash, sess.hash, now_ms) None => () } hex } ///| pub fn Router::pause_torrent(self : Router, info_hash_hex : String) -> Bool { let eng = match self.torrent_engine { Some(e) => e None => return false } match bt_find_torrent_by_hex(eng, info_hash_hex) { Some(t) => { t.paused = true let mgr_opt = match self.find_session_by_id(eng.session_id) { Some(s) => s.stream_mgr None => None } let now_ms = @ntcp2_net.unix_time_ms() for p in t.peers { p.state = 4 match mgr_opt { Some(mgr) if p.stream_id != 0U => { match find_stream_by_id(mgr, p.stream_id) { Some(c) => { let _ = c.close(now_ms) catch { _ => () } } None => () } remove_stream_by_id(mgr, p.stream_id) } _ => () } } t.peers.clear() true } None => false } } ///| pub fn Router::resume_torrent(self : Router, info_hash_hex : String) -> Bool { let eng = match self.torrent_engine { Some(e) => e None => return false } match bt_find_torrent_by_hex(eng, info_hash_hex) { Some(t) => { t.paused = false t.last_dht_lookup_ms = 0UL for tr in t.trackers { tr.next_announce_ms = 0UL } true } None => false } } ///| pub fn Router::remove_torrent(self : Router, info_hash_hex : String) -> Bool { let eng = match self.torrent_engine { Some(e) => e None => return false } let norm = bt_hex_lower(info_hash_hex) let mgr_opt = match self.find_session_by_id(eng.session_id) { Some(s) => s.stream_mgr None => None } let now_ms = @ntcp2_net.unix_time_ms() for i = 0; i < eng.torrents.length(); i = i + 1 { if eng.torrents[i].info_hash_hex == norm { let t = eng.torrents[i] for p in t.peers { match mgr_opt { Some(mgr) if p.stream_id != 0U => { match find_stream_by_id(mgr, p.stream_id) { Some(c) => { let _ = c.close(now_ms) catch { _ => () } } None => () } remove_stream_by_id(mgr, p.stream_id) } _ => () } } for tr in t.trackers { match mgr_opt { Some(mgr) if tr.stream_id != 0U => remove_stream_by_id(mgr, tr.stream_id) _ => () } } let _ = eng.torrents.remove(i) return true } } false } ///| fn Router::send_torrent_i2cp( self : Router, sess : SamSession, peer_hash : @common.Hash, i2cp_bytes : Bytes, send_ls2~ : Bool = false, ) -> Bool { let ratchet = match sess.ratchet { Some(r) => r None => return false } let now_sec = @ntcp2_net.unix_time_sec() let ls2 = match self.netdb.get_lease_set2(peer_hash, now_sec) { Some(l) if l.leases.length() > 0 => l _ => return false } let peer_static = match extract_x25519_key(ls2) { Some(k) => k None => return false } let valid : Array[@common.Lease2] = [] for l in ls2.leases { if l.end_date_sec > now_sec { valid.push(l) } } let pool = if valid.length() > 0 { valid } else { ls2.leases } let rr = if self.lease_rr < 0 { 0 } else { self.lease_rr } self.lease_rr = (self.lease_rr + 1) & 0x3FFFFFFF let chosen = pool[rr % pool.length()] let exp_sec = now_sec + 60U let blocks : Array[@ratchet.RatchetBlock] = [] if send_ls2 { match self.build_session_leaseset2(sess, now_sec) { Some(my_ls2) => { let ls_bytes = my_ls2.to_bytes() catch { _ => b"" } if ls_bytes.length() > 0 { let ls_blk = @ratchet.garlic_clove_block( Local, self.alloc_msg_id(), exp_sec, DatabaseStore( key=sess.hash, store_type=b'\x03', reply_token=0U, reply_tunnel_id=0U, reply_gateway=None, data=ls_bytes, ), ) catch { _ => return false } blocks.push(ls_blk) } } None => () } } let clove = @ratchet.garlic_clove_block( Destination(peer_hash), self.alloc_msg_id(), exp_sec, Data(data=i2cp_bytes), ) catch { _ => return false } blocks.push(clove) let wire = ratchet.encrypt_to_peer(peer_static, blocks, now_sec, next_rand_32) catch { _ => return false } self.send_routed_i2np( chosen.tunnel_gw, Some(chosen.tunnel_id), Garlic(data=wire), ) true } ///| fn Router::send_dht_query( self : Router, eng : TorrentEngine, sess : SamSession, target_hash : @common.Hash, target_port : UInt32, kind : @bittorrent.KrpcQueryKind, now_ms : UInt64, info_hash~ : Bytes? = None, ) -> Bool { if target_hash == sess.hash { return false } let seed = match sess.ed_seed { Some(s) => s 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 _ = self.start_proxy_netdb_lookup(target_hash) return false } } let tx_id = eng.dht.alloc_tx_id() let payload = @bittorrent.encode_krpc( Query(tx_id~, sender_id=eng.dht.local_id, kind~), ) let dgram = @streaming.RepliableDatagram::sign_ed25519( sess.dest, seed, payload, ) catch { _ => return false } 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) { return false } let kind_str = match kind { Ping => "ping" FindNode(..) => "find_node" GetPeers(..) => "get_peers" AnnouncePeer(..) => "announce_peer" } eng.dht.register_pending_tx( tx_id, kind_str, target_hash, port, now_ms, info_hash~, ) true } ///| fn Router::send_dht_reply( self : Router, eng : TorrentEngine, sess : SamSession, target_hash : @common.Hash, reply_port : UInt32, tx_id : Bytes, nodes : Bytes, values : Array[Bytes], token : Bytes?, ) -> Bool { let payload = @bittorrent.encode_krpc( Response(tx_id~, sender_id=eng.dht.local_id, nodes~, values~, token~), ) let i2cp = @streaming.encode_raw_datagram( payload, from_port=eng.dht.query_port, to_port=reply_port, ) self.send_torrent_i2cp(sess, target_hash, i2cp, send_ls2=false) } ///| fn Router::poll_dht_datagrams( self : Router, eng : TorrentEngine, sess : SamSession, mgr : @streaming.StreamManager, now_ms : UInt64, ) -> Bool { let mut did_work = false // 1. Incoming Repliable Datagrams (proto 0x11): KRPC Queries while mgr.incoming_repliable_dgrams.length() > 0 { did_work = true let (hdr, dgram) = mgr.incoming_repliable_dgrams.remove(0) if hdr.to_port != 0U && hdr.to_port != eng.dht.query_port { continue } if !dgram.verify() { continue } let sender_hash = dgram.sender.hash() let sender_port = if hdr.from_port > 0U { hdr.from_port } else { 6881U } let reply_port = if sender_port < 65535U { sender_port + 1U } else { sender_port } let msg = Some(@bittorrent.decode_krpc(dgram.payload)) catch { _ => None } match msg { Some(Query(tx_id~, sender_id~, kind~)) => { eng.dht.record_query_recv() let _ = eng.dht.upsert_node(sender_id, sender_hash, sender_port, now_ms) match kind { Ping => { let _ = self.send_dht_reply( eng, sess, sender_hash, reply_port, tx_id, b"", [], None, ) } FindNode(target~) => { let closest = eng.dht.closest_nodes(target, limit=8) let compact = @bittorrent.encode_compact_nodes(closest) let _ = self.send_dht_reply( eng, sess, sender_hash, reply_port, tx_id, compact, [], None, ) } GetPeers(info_hash~) => { let tk = eng.dht.make_token(sender_hash) let local_peers = eng.dht.get_peers_local(info_hash, now_ms) match bt_find_torrent_by_ih(eng, info_hash) { Some(t) if !t.paused => { let mut has_self = false for ph in local_peers { if ph == sess.hash { has_self = true break } } if !has_self { local_peers.push(sess.hash) } } _ => () } let values : Array[Bytes] = [] for ph in local_peers { values.push(ph.as_bytes()) } let compact = if values.length() == 0 { @bittorrent.encode_compact_nodes( eng.dht.closest_nodes(info_hash, limit=8), ) } else { b"" } let _ = self.send_dht_reply( eng, sess, sender_hash, reply_port, tx_id, compact, values, Some(tk), ) } AnnouncePeer(info_hash~, ..) => { match kind { AnnouncePeer(token~, ..) => if eng.dht.verify_token(sender_hash, token) { eng.dht.store_peer(info_hash, sender_hash, now_ms) } _ => () } let _ = self.send_dht_reply( eng, sess, sender_hash, reply_port, tx_id, b"", [], None, ) } } } _ => () } } // 2. Incoming Raw Datagrams (proto 0x12): KRPC Responses while mgr.incoming_raw_dgrams.length() > 0 { did_work = true let (hdr, raw) = mgr.incoming_raw_dgrams.remove(0) if hdr.to_port != 0U && hdr.to_port != eng.dht.reply_port && hdr.to_port != eng.dht.query_port { continue } let msg = Some(@bittorrent.decode_krpc(raw)) catch { _ => None } match msg { Some(Response(tx_id~, sender_id~, nodes~, values~, token~)) => match eng.dht.take_pending_tx(tx_id) { Some(tx) => { let _ = eng.dht.upsert_node( sender_id, tx.dest_hash, tx.port, now_ms, ) if nodes.length() > 0 { let decoded_nodes = @bittorrent.decode_compact_nodes( nodes, now_ms~, ) catch { _ => [] } for dn in decoded_nodes { let added = eng.dht.upsert_node( dn.node_id, dn.dest_hash, dn.port, now_ms, ) if added { 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( eng, sess, dn.dest_hash, dn.port, GetPeers(info_hash=ih), now_ms, info_hash=Some(ih), ) } _ => () } None => () } } } } match tx.info_hash { Some(ih) => match bt_find_torrent_by_ih(eng, ih) { Some(t) => { let mut newly_added = 0UL for v in values { if v.length() == 32 { let ph = @common.Hash::from_bytes(v) catch { _ => continue } eng.dht.store_peer(ih, ph, now_ms) if bt_add_known_peer(t, ph, sess.hash) { newly_added += 1UL } } } if newly_added > 0UL { eng.dht.record_peers_discovered(newly_added) } 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), ) } None => () } } } None => () } None => () } } None => () } _ => () } } did_work } ///| fn Router::step_dht( self : Router, eng : TorrentEngine, sess : SamSession, now_ms : UInt64, ) -> Bool { let mut did_work = false eng.dht.prune_expired_txs(now_ms) // Retry pending bootstrap pings once peer LeaseSet2 resolves let mut pi = 0 while pi < eng.pending_dht_pings.length() { let (ph, port, started_ms) = eng.pending_dht_pings[pi] if self.send_dht_query(eng, sess, ph, port, Ping, now_ms) { let _ = eng.pending_dht_pings.remove(pi) did_work = true continue } if now_ms > started_ms + 30000UL { let _ = eng.pending_dht_pings.remove(pi) continue } pi += 1 } // Background self-lookup maintenance every 25s if eng.dht.nodes.length() > 0 && now_ms >= eng.last_dht_maint_ms + 25000UL { eng.last_dht_maint_ms = now_ms let closest = eng.dht.closest_nodes(eng.dht.local_id, limit=3) for n in closest { if self.send_dht_query( eng, sess, n.dest_hash, n.port, FindNode(target=eng.dht.local_id), now_ms, ) { did_work = true } } } // Per-torrent DHT peer lookup & announce 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 { 800UL } else { 15000UL } if now_ms >= t.last_dht_lookup_ms + interval_ms { t.last_dht_lookup_ms = now_ms let closest = eng.dht.closest_nodes(t.info_hash, limit=4) for n in closest { if self.send_dht_query( eng, sess, n.dest_hash, n.port, GetPeers(info_hash=t.info_hash), now_ms, info_hash=Some(t.info_hash), ) { did_work = true } } } } did_work } ///| fn Router::step_trackers( self : Router, eng : TorrentEngine, sess : SamSession, mgr : @streaming.StreamManager, now_ms : UInt64, ) -> Bool { let now_sec = (now_ms / 1000UL).to_uint() let mut did_work = false for t in eng.torrents { if t.paused { continue } for tr in t.trackers { match tr.state { 0 => { if now_ms < tr.next_announce_ms { continue } match self.resolve_i2p_host_hash(tr.host) { Some(thash) => { tr.peer_hash = Some(thash) tr.state = 1 tr.started_ms = now_ms tr.recv_buf.clear() tr.sent_req = false let _ = self.start_proxy_netdb_lookup(thash) did_work = true } None => tr.next_announce_ms = now_ms + 30000UL } } 1 => { let thash = match tr.peer_hash { Some(h) => h None => { tr.state = 0 tr.next_announce_ms = now_ms + 30000UL continue } } match self.netdb.get_lease_set2(thash, now_sec) { Some(ls2) if ls2.leases.length() > 0 => { let to_port = if tr.port == 80U { 0U } else { tr.port } let conn = mgr.connect(thash, now_ms, from_port=0U, to_port~) catch { _ => { tr.state = 0 tr.next_announce_ms = now_ms + 20000UL continue } } tr.stream_id = conn.local_stream_id tr.state = 2 tr.started_ms = now_ms match extract_x25519_key(ls2) { Some(pstat) => self.flush_stream_outbound( sess, conn, thash, pstat, ls2.leases[0].tunnel_gw, ls2.leases[0].tunnel_id, send_ls2=true, ) None => () } did_work = true } _ => if now_ms > tr.started_ms + 25000UL { tr.state = 0 tr.next_announce_ms = now_ms + 30000UL } } } 2 => { let thash = match tr.peer_hash { Some(h) => h None => { tr.state = 0 continue } } let conn = match find_stream_by_id(mgr, tr.stream_id) { Some(c) => c None => { tr.state = 0 tr.next_announce_ms = now_ms + 20000UL continue } } if !tr.sent_req && conn.state == Established { let total_len = match t.metainfo { Some(m) => m.total_length None => 0L } let left = if total_len.reinterpret_as_uint64() > t.downloaded_bytes { (total_len.reinterpret_as_uint64() - t.downloaded_bytes).reinterpret_as_int64() } else { 0L } let req_str = @bittorrent.build_http_announce_request( { host: tr.host, port: tr.port, request_target: tr.path, }, t.info_hash, eng.peer_id, t.uploaded_bytes.reinterpret_as_int64(), t.downloaded_bytes.reinterpret_as_int64(), left, event=if t.completed { "completed" } else { "started" }, local_dest_b64=sess.pub_b64, ) let _ = conn.write(@encoding.string_to_utf8_bytes(req_str), now_ms) catch { _ => 0 } tr.sent_req = true match self.netdb.get_lease_set2(thash, now_sec) { Some(ls2) if ls2.leases.length() > 0 => match extract_x25519_key(ls2) { Some(pstat) => self.flush_stream_outbound( sess, conn, thash, pstat, ls2.leases[0].tunnel_gw, ls2.leases[0].tunnel_id, send_ls2=false, ) None => () } _ => () } did_work = true } let avail = conn.read_available() if avail.length() > 0 { for i = 0; i < avail.length(); i = i + 1 { if tr.recv_buf.length() < 512 * 1024 { tr.recv_buf.push(avail[i]) } } did_work = true } if conn.is_eof() || conn.state == Reset || now_ms > tr.started_ms + 25000UL { let _ = conn.close(now_ms) catch { _ => () } remove_stream_by_id(mgr, tr.stream_id) tr.stream_id = 0U let mut next_wait = 60000UL if tr.recv_buf.length() > 0 { let raw = Bytes::from_array(tr.recv_buf) tr.recv_buf.clear() let resp_opt = Some(@bittorrent.parse_http_tracker_response(raw)) catch { _ => None } match resp_opt { Some(resp) => { for ph in resp.peers { if bt_add_known_peer(t, ph, sess.hash) { eng.dht.record_peers_discovered(1UL) } } if resp.interval >= 15 { next_wait = resp.interval.to_uint64() * 1000UL } } None => () } } tr.state = 0 tr.next_announce_ms = now_ms + next_wait did_work = true } } _ => tr.state = 0 } } } did_work } ///| fn Router::bt_flush_peer_send_buf( self : Router, sess : SamSession, conn : @streaming.StreamConnection, peer : TorrentPeerConn, now_ms : UInt64, ) -> Bool { if peer.send_buf.length() == 0 { return false } let wrote = conn.write(Bytes::from_array(peer.send_buf), now_ms) catch { _ => 0 } if wrote <= 0 { return false } bt_pop_front_bytes(peer.send_buf, wrote) match (peer.lease_gw, peer.peer_static.length() == 32) { (Some(gw), true) => self.flush_stream_outbound( sess, conn, peer.peer_hash, peer.peer_static, gw, peer.lease_tid, send_ls2=false, ) _ => () } true } ///| fn Router::bt_send_peer_wire( self : Router, sess : SamSession, conn : @streaming.StreamConnection, peer : TorrentPeerConn, data : Bytes, now_ms : UInt64, ) -> Unit { for i = 0; i < data.length(); i = i + 1 { peer.send_buf.push(data[i]) } let _ = self.bt_flush_peer_send_buf(sess, conn, peer, now_ms) } ///| fn Router::bt_send_post_handshake( self : Router, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, peer : TorrentPeerConn, now_ms : UInt64, ) -> Unit { if !peer.sent_ext_hs { peer.sent_ext_hs = true let msize : Int32? = if t.meta_size > 0 { Some(t.meta_size) } else { None } let ext_hs = @bittorrent.encode_ext_handshake(metadata_size=msize) self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Extended(b'\x00', ext_hs)), now_ms, ) if t.have_pieces.length() > 0 { let bf = bt_build_bitfield_bytes(t.have_pieces) self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Bitfield(bf)), now_ms, ) } if peer.am_choking { peer.am_choking = false self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Unchoke), now_ms, ) } if !t.completed && !peer.am_interested { peer.am_interested = true self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Interested), now_ms, ) } } } ///| fn Router::bt_handle_ext_message( self : Router, eng : TorrentEngine, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, peer : TorrentPeerConn, ext_id : Byte, payload : Bytes, now_ms : UInt64, ) -> Unit { if ext_id == b'\x00' { let re = @bittorrent.decode_ext_handshake(payload) catch { _ => return } peer.remote_ext = Some(re) match re.metadata_size { Some(ms) if ms > 0 && t.meta_size == 0 => t.meta_size = ms _ => () } match re.i2p_dht_id { Some(did) => { let msg = @bittorrent.encode_i2p_dht_ext( eng.dht.query_port, eng.dht.reply_port, ) self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Extended(did, msg)), now_ms, ) } None => () } return } if ext_id == @bittorrent.ext_id_ut_metadata { let mm = @bittorrent.decode_metadata_msg(payload) catch { _ => return } match mm { MetaRequest(piece) => { if t.raw_info.length() == 0 || piece < 0 { match peer.remote_ext { Some(re) => match re.ut_metadata_id { Some(rid) => self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message( Extended(rid, @bittorrent.encode_metadata_reject(piece)), ), now_ms, ) None => () } None => () } return } let off = piece * 16384 if off >= t.raw_info.length() { return } let end = if off + 16384 < t.raw_info.length() { off + 16384 } else { t.raw_info.length() } let slice = t.raw_info[off:end].to_owned() match peer.remote_ext { Some(re) => match re.ut_metadata_id { Some(rid) => self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message( Extended( rid, @bittorrent.encode_metadata_data( piece, t.raw_info.length(), slice, ), ), ), now_ms, ) None => () } None => () } } MetaData(piece, total_size, slice) => { if t.metainfo is Some(_) { return } if total_size > 0 && total_size <= 8 * 1024 * 1024 { t.meta_size = total_size let mut exists = false for mp in t.meta_pieces { if mp.0 == piece { exists = true break } } if !exists { t.meta_pieces.push((piece, slice)) } let need_pieces = (total_size + 16383) / 16384 if t.meta_pieces.length() >= need_pieces { let w = @encoding.Writer::new(capacity=total_size) let mut ok = true for idx = 0; idx < need_pieces; idx = idx + 1 { let mut found : Bytes? = None for mp in t.meta_pieces { if mp.0 == idx { found = Some(mp.1) break } } match found { Some(b) => w.write_bytes(b) None => { ok = false break } } } if ok { let raw = w.to_bytes() if raw.length() == total_size && @crypto.ct_eq(@crypto.sha1(raw), t.info_hash) { let parsed = @bittorrent.parse_info_dict(raw) catch { e => { t.error = "metadata parse failed: \{bt_err_msg(e)}" return } } bt_init_torrent_metainfo(t, parsed) t.meta_pieces.clear() } else { t.meta_pieces.clear() } } } } } MetaReject(_) => () } return } if ext_id == @bittorrent.ext_id_pex { let added = @bittorrent.decode_i2p_pex(payload) for ph in added { if bt_add_known_peer(t, ph, sess.hash) { eng.dht.record_peers_discovered(1UL) } } return } if ext_id == @bittorrent.ext_id_i2p_dht { match @bittorrent.decode_i2p_dht_ext(payload) { Some((qp, _rp)) => if !peer.dht_pinged { peer.dht_pinged = true let _ = self.send_dht_query( eng, sess, peer.peer_hash, qp, Ping, now_ms, ) } None => () } } } ///| fn Router::bt_request_metadata_if_needed( self : Router, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, peer : TorrentPeerConn, now_ms : UInt64, ) -> Unit { if t.metainfo is Some(_) || t.meta_size <= 0 { return } if now_ms < t.meta_req_ms + 2500UL { return } let rid = match peer.remote_ext { Some(re) => match re.ut_metadata_id { Some(id) => id None => return } None => return } let need_pieces = (t.meta_size + 16383) / 16384 for p = 0; p < need_pieces; p = p + 1 { let mut have = false for mp in t.meta_pieces { if mp.0 == p { have = true break } } if !have { t.meta_req_ms = now_ms self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message( Extended(rid, @bittorrent.encode_metadata_request(p)), ), now_ms, ) return } } } ///| fn Router::bt_schedule_piece_requests( self : Router, sess : SamSession, conn : @streaming.StreamConnection, t : ActiveTorrent, peer : TorrentPeerConn, now_ms : UInt64, ) -> Unit { let meta = match t.metainfo { Some(m) => m None => return } if t.completed || peer.peer_choking { return } // Drop timed-out in-flight requests (> 12s) let mut i = 0 while i < peer.in_flight.length() { if now_ms > peer.in_flight[i].3 + 12000UL { let _ = peer.in_flight.remove(i) } else { i += 1 } } let max_pipeline = 4 let num_pieces = meta.piece_hashes.length() while peer.in_flight.length() < max_pipeline { let mut picked : (Int32, Int32, Int32)? = None // First fill blocks inside already-active piece buffers for pbuf in t.inflight_pieces { let pidx = pbuf.piece_idx if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { continue } let plen = bt_piece_length(meta, pidx) for bidx = 0; bidx < pbuf.num_blocks; bidx = bidx + 1 { if pbuf.got_blocks[bidx] { continue } let begin = bidx * @bittorrent.bt_block_size let mut already_req = false for op in t.peers { for inf in op.in_flight { if inf.0 == pidx && inf.1 == begin { already_req = true break } } if already_req { break } } if !already_req { let rem = plen - begin let blen = if rem < @bittorrent.bt_block_size { rem } else { @bittorrent.bt_block_size } picked = Some((pidx, begin, blen)) break } } if picked is Some(_) { break } } // Otherwise start a new piece buffer we don't have yet if picked is None && t.inflight_pieces.length() < 4 { for pidx = 0; pidx < num_pieces; pidx = pidx + 1 { if t.have_pieces[pidx] { continue } if pidx < peer.peer_bitfield.length() && !peer.peer_bitfield[pidx] { continue } let mut active = false for pbuf in t.inflight_pieces { if pbuf.piece_idx == pidx { active = true break } } if active { continue } let plen = bt_piece_length(meta, pidx) if plen <= 0 { continue } let nblocks = (plen + @bittorrent.bt_block_size - 1) / @bittorrent.bt_block_size t.inflight_pieces.push({ piece_idx: pidx, data: FixedArray::make(plen, b'\x00'), got_blocks: Array::make(nblocks, false), num_blocks: nblocks, }) let blen = if plen < @bittorrent.bt_block_size { plen } else { @bittorrent.bt_block_size } picked = Some((pidx, 0, blen)) break } } match picked { Some((pidx, begin, blen)) => { peer.in_flight.push((pidx, begin, blen, now_ms)) self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message(Request(pidx, begin, blen)), now_ms, ) } None => break } } } ///| fn Router::bt_on_piece_block( self : Router, sess : SamSession, mgr : @streaming.StreamManager, t : ActiveTorrent, peer : TorrentPeerConn, piece_idx : Int32, begin : Int32, block : Bytes, now_ms : UInt64, ) -> Unit { let meta = match t.metainfo { Some(m) => m None => return } // Remove from peer.in_flight let mut k = 0 while k < peer.in_flight.length() { if peer.in_flight[k].0 == piece_idx && peer.in_flight[k].1 == begin { let _ = peer.in_flight.remove(k) break } k += 1 } if begin % @bittorrent.bt_block_size != 0 { return } let bidx = begin / @bittorrent.bt_block_size for p_i = 0; p_i < t.inflight_pieces.length(); p_i = p_i + 1 { let pbuf = t.inflight_pieces[p_i] if pbuf.piece_idx == piece_idx { if bidx >= 0 && bidx < pbuf.num_blocks && begin + block.length() <= pbuf.data.length() { for j = 0; j < block.length(); j = j + 1 { pbuf.data[begin + j] = block[j] } pbuf.got_blocks[bidx] = true } let mut complete = true for g in pbuf.got_blocks { if !g { complete = false break } } if complete { let piece_bytes = Bytes::from_array(pbuf.data) let _ = t.inflight_pieces.remove(p_i) if @crypto.ct_eq( @crypto.sha1(piece_bytes), meta.piece_hashes[piece_idx], ) { if bt_write_piece_to_files(t, piece_idx, piece_bytes) { t.have_pieces[piece_idx] = true t.downloaded_bytes += piece_bytes.length().to_uint64() let have_msg = @bittorrent.encode_peer_message( Have(piece_idx.reinterpret_as_uint()), ) for op in t.peers { if op.state == 3 { match find_stream_by_id(mgr, op.stream_id) { Some(oc) => self.bt_send_peer_wire(sess, oc, op, have_msg, now_ms) None => () } } } let mut all_done = true for h in t.have_pieces { if !h { all_done = false break } } if all_done { t.completed = true } } } } break } } } ///| fn Router::bt_process_peer_messages( self : Router, eng : TorrentEngine, sess : SamSession, mgr : @streaming.StreamManager, conn : @streaming.StreamConnection, t : ActiveTorrent, peer : TorrentPeerConn, now_ms : UInt64, ) -> Unit { for _iter = 0; _iter < 64; _iter = _iter + 1 { let msg_opt = @bittorrent.try_decode_peer_message(peer.recv_buf) catch { _ => { peer.state = 4 return } } match msg_opt { None => break Some(msg) => { peer.last_activity_ms = now_ms match msg { KeepAlive => () Choke => { peer.peer_choking = true peer.in_flight.clear() } Unchoke => peer.peer_choking = false Interested | NotInterested => () Have(idx) => { let pidx = idx.reinterpret_as_int() if pidx >= 0 { while peer.peer_bitfield.length() <= pidx { peer.peer_bitfield.push(false) } peer.peer_bitfield[pidx] = true } } Bitfield(bf) => match t.metainfo { Some(m) => peer.peer_bitfield = bt_decode_bitfield( bf, m.piece_hashes.length(), ) None => // Guess piece count from bitfield bytes until metadata arrives peer.peer_bitfield = bt_decode_bitfield(bf, bf.length() * 8) } Request(piece_idx, begin, req_len) => if req_len > 0 && req_len <= 32768 && piece_idx >= 0 && piece_idx < t.have_pieces.length() && t.have_pieces[piece_idx] { match bt_read_span_from_files(t, piece_idx, begin, req_len) { Some(block) => { t.uploaded_bytes += block.length().to_uint64() self.bt_send_peer_wire( sess, conn, peer, @bittorrent.encode_peer_message( Piece(piece_idx, begin, block), ), now_ms, ) } None => () } } Piece(piece_idx, begin, block) => self.bt_on_piece_block( sess, mgr, t, peer, piece_idx, begin, block, now_ms, ) Cancel(_, _, _) => () Extended(eid, epayload) => self.bt_handle_ext_message( eng, sess, conn, t, peer, eid, epayload, now_ms, ) } } } } } ///| fn Router::step_torrent_engine(self : Router) -> Bool { let eng = match self.torrent_engine { Some(e) => e None => return false } let sess = match self.find_session_by_id(eng.session_id) { Some(s) => s None => return false } let mgr = match sess.stream_mgr { Some(m) => m None => return false } let now_ms = @ntcp2_net.unix_time_ms() let now_sec = (now_ms / 1000UL).to_uint() let mut did_work = false // 0. Republish __torrent__ LeaseSet2 once inbound tunnels appear or every 120s let cur_in = self.tunnels.inbound.length() if (cur_in > 0 && eng.last_ls2_pub_tunnels == 0) || now_ms >= eng.last_ls2_pub_ms + 120000UL { eng.last_ls2_pub_ms = now_ms eng.last_ls2_pub_tunnels = cur_in self.publish_session_leaseset2(sess) } // 1. Poll I2P DHT datagrams (proto 0x11 + 0x12) and run DHT maintenance if self.poll_dht_datagrams(eng, sess, mgr, now_ms) { did_work = true } if self.step_dht(eng, sess, now_ms) { did_work = true } // 2. Drive I2P HTTP trackers if self.step_trackers(eng, sess, mgr, now_ms) { did_work = true } // 3. Accept incoming I2P Streaming connections on __torrent__ for _k = 0; _k < 8; _k = _k + 1 { match mgr.accept_next() { Some(conn) => { did_work = true let mut peer_static = b"" let mut gw = self.router_hash() let mut tid = sess.virtual_tid match self.netdb.get_lease_set2(conn.remote_hash, now_sec) { Some(ls2) if ls2.leases.length() > 0 => { gw = ls2.leases[0].tunnel_gw tid = ls2.leases[0].tunnel_id match extract_x25519_key(ls2) { Some(k) => peer_static = k None => () } } _ => () } self.flush_stream_outbound( sess, conn, conn.remote_hash, peer_static, gw, tid, send_ls2=true, ) eng.pending_inbound.push({ stream_id: conn.local_stream_id, peer_hash: conn.remote_hash, peer_static, lease_gw: gw, lease_tid: tid, started_ms: now_ms, recv_buf: [], }) } None => break } } // Match pending inbound streams once 68-byte BitTorrent handshake arrives let mut ib_i = 0 while ib_i < eng.pending_inbound.length() { let ib = eng.pending_inbound[ib_i] let conn = match find_stream_by_id(mgr, ib.stream_id) { Some(c) => c None => { let _ = eng.pending_inbound.remove(ib_i) continue } } let avail = conn.read_available() if avail.length() > 0 { for j = 0; j < avail.length(); j = j + 1 { ib.recv_buf.push(avail[j]) } did_work = true } if ib.recv_buf.length() >= 68 { let hs_raw = Bytes::from_array(ib.recv_buf[:68]) let parsed_hs = Some(@bittorrent.decode_handshake(hs_raw)) catch { _ => None } match parsed_hs { Some((_ext, ih, _remote_pid)) => match bt_find_torrent_by_ih(eng, ih) { Some(t) if !t.paused => { let _ = bt_add_known_peer(t, ib.peer_hash, sess.hash) bt_pop_front_bytes(ib.recv_buf, 68) let rem_buf : Array[Byte] = [] for b in ib.recv_buf { rem_buf.push(b) } let peer : TorrentPeerConn = { peer_hash: ib.peer_hash, state: 3, started_ms: now_ms, last_activity_ms: now_ms, stream_id: conn.local_stream_id, peer_static: ib.peer_static, lease_gw: Some(ib.lease_gw), lease_tid: ib.lease_tid, recv_buf: rem_buf, send_buf: [], sent_bt_hs: true, sent_ext_hs: false, peer_choking: true, am_choking: true, am_interested: false, remote_ext: None, peer_bitfield: [], in_flight: [], dht_pinged: false, } let hs_out = @bittorrent.encode_handshake( t.info_hash, eng.peer_id, ) catch { _ => b"" } self.bt_send_peer_wire(sess, conn, peer, hs_out, now_ms) self.bt_send_post_handshake(sess, conn, t, peer, now_ms) self.bt_process_peer_messages( eng, sess, mgr, conn, t, peer, now_ms, ) t.peers.push(peer) let _ = eng.pending_inbound.remove(ib_i) did_work = true continue } _ => { let _ = conn.close(now_ms) catch { _ => () } remove_stream_by_id(mgr, conn.local_stream_id) let _ = eng.pending_inbound.remove(ib_i) continue } } None => { let _ = conn.close(now_ms) catch { _ => () } remove_stream_by_id(mgr, conn.local_stream_id) let _ = eng.pending_inbound.remove(ib_i) continue } } } if conn.state == Reset || conn.is_eof() || now_ms > ib.started_ms + 25000UL { let _ = conn.close(now_ms) catch { _ => () } remove_stream_by_id(mgr, conn.local_stream_id) let _ = eng.pending_inbound.remove(ib_i) continue } ib_i += 1 } // 4. Spawn outbound peer connections and pump active peer swarms for t in eng.torrents { if t.paused { continue } // Spawn up to 12 peers per torrent when incomplete if !t.completed { for kh in t.known_peers { if t.peers.length() >= 12 { break } let mut already = kh == sess.hash if !already { for p in t.peers { if p.peer_hash == kh { already = true break } } } if !already { let _ = self.start_proxy_netdb_lookup(kh) t.peers.push({ peer_hash: kh, state: 0, started_ms: now_ms, last_activity_ms: now_ms, stream_id: 0U, peer_static: b"", lease_gw: None, lease_tid: 0U, recv_buf: [], send_buf: [], sent_bt_hs: false, sent_ext_hs: false, peer_choking: true, am_choking: true, am_interested: false, remote_ext: None, peer_bitfield: [], in_flight: [], dht_pinged: false, }) did_work = true } } } let mut pi = 0 while pi < t.peers.length() { let p = t.peers[pi] match p.state { 0 => { match self.netdb.get_lease_set2(p.peer_hash, now_sec) { Some(ls2) if ls2.leases.length() > 0 => match extract_x25519_key(ls2) { Some(pstat) => { let conn = mgr.connect( p.peer_hash, now_ms, from_port=0U, to_port=0U, ) catch { _ => { p.state = 4 continue } } p.stream_id = conn.local_stream_id p.peer_static = pstat p.lease_gw = Some(ls2.leases[0].tunnel_gw) p.lease_tid = ls2.leases[0].tunnel_id p.state = 1 p.started_ms = now_ms self.flush_stream_outbound( sess, conn, p.peer_hash, pstat, ls2.leases[0].tunnel_gw, ls2.leases[0].tunnel_id, send_ls2=true, ) did_work = true } None => () } _ => () } if p.state == 0 && now_ms > p.started_ms + 30000UL { p.state = 4 } } 1 => { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { p.state = 4 continue } } if conn.state == Established { p.state = 2 p.last_activity_ms = now_ms if !p.sent_bt_hs { p.sent_bt_hs = true let hs = @bittorrent.encode_handshake(t.info_hash, eng.peer_id) catch { _ => b"" } self.bt_send_peer_wire(sess, conn, p, hs, now_ms) } did_work = true } else if conn.state == Reset || now_ms > p.started_ms + 30000UL { p.state = 4 } } 2 => { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { p.state = 4 continue } } if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { did_work = true } let avail = conn.read_available() if avail.length() > 0 { for j = 0; j < avail.length(); j = j + 1 { p.recv_buf.push(avail[j]) } did_work = true } 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 { _ => None } match parsed { Some((_ext, ih, _pid)) if @crypto.ct_eq(ih, t.info_hash) => { bt_pop_front_bytes(p.recv_buf, 68) p.state = 3 p.last_activity_ms = now_ms self.bt_send_post_handshake(sess, conn, t, p, now_ms) self.bt_process_peer_messages( eng, sess, mgr, conn, t, p, now_ms, ) } _ => p.state = 4 } } else if conn.is_eof() || conn.state == Reset || now_ms > p.last_activity_ms + 20000UL { p.state = 4 } } 3 => { let conn = match find_stream_by_id(mgr, p.stream_id) { Some(c) => c None => { p.state = 4 continue } } if self.bt_flush_peer_send_buf(sess, conn, p, now_ms) { did_work = true } let avail = conn.read_available() if avail.length() > 0 { for j = 0; j < avail.length(); j = j + 1 { p.recv_buf.push(avail[j]) } p.last_activity_ms = now_ms did_work = true } self.bt_process_peer_messages(eng, sess, mgr, conn, t, p, now_ms) if p.state == 3 { self.bt_request_metadata_if_needed(sess, conn, t, p, now_ms) self.bt_schedule_piece_requests(sess, conn, t, p, now_ms) if conn.is_eof() || conn.state == Reset { p.state = 4 } } } _ => () } if p.state == 4 { if p.stream_id != 0U { match find_stream_by_id(mgr, p.stream_id) { Some(c) => { let _ = c.close(now_ms) catch { _ => () } } None => () } remove_stream_by_id(mgr, p.stream_id) } let _ = t.peers.remove(pi) did_work = true continue } pi += 1 } // Periodic i2p_pex gossip (every 30s) if t.peers.length() > 0 && t.known_peers.length() > 0 && now_ms >= t.last_pex_ms + 30000UL { t.last_pex_ms = now_ms let pex_bytes = @bittorrent.encode_i2p_pex(t.known_peers) for p in t.peers { if p.state == 3 { match (p.remote_ext, find_stream_by_id(mgr, p.stream_id)) { (Some(re), Some(conn)) => match re.i2p_pex_id { Some(pid) => self.bt_send_peer_wire( sess, conn, p, @bittorrent.encode_peer_message(Extended(pid, pex_bytes)), now_ms, ) None => () } _ => () } } } } } did_work }