///| /// Active Floodfill NetDB protocol handlers (`DatabaseStore`, ECIES `DatabaseLookup`, /// and iterative `DatabaseSearchReply` Kademlia lookup crawl). ///| priv struct PendingNetDbLookup { target_hash : @common.Hash reply_key : Bytes reply_tag : Bytes queried_peers : Array[@common.Hash] candidate_peers : Array[@common.Hash] started_ms : UInt64 kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2 client_idx : Int32 req_name : String session_id : String silent : Bool } ///| fn is_hash_in(h : @common.Hash, list : Array[@common.Hash]) -> Bool { for item in list { if item == h { return true } } false } ///| fn Router::build_session_leaseset2( self : Router, sess : SamSession, now_sec : UInt32, ) -> @common.LeaseSet2? { let seed = match sess.ed_seed { Some(s) => s None => return None } let leases : Array[@common.Lease2] = [] let max_leases = 3 for t in self.tunnels.inbound { if t.expires_sec > now_sec && t.hops.length() > 0 && leases.length() < max_leases { leases.push({ tunnel_gw: t.hops[0].router_hash, tunnel_id: t.hops[0].receive_tunnel_id, end_date_sec: t.expires_sec, }) } } if leases.length() == 0 { leases.push({ tunnel_gw: self.router_hash(), tunnel_id: sess.virtual_tid, end_date_sec: now_sec + 600U, }) } let ls2 : @common.LeaseSet2 = { destination: sess.dest, published_sec: now_sec, expires_offset: 600U, flags: 0U, offline_sig: None, options: @common.Mapping::new(), encryption_keys: [ { key_type: X25519, key_data: sess.dest.inner.crypto_public_key(), }, ], leases, signature: b"", } let signed = ls2.sign_ed25519(seed) catch { _ => return None } let _ = self.netdb.store_lease_set2(signed, now_sec) catch { _ => false } Some(signed) } ///| fn Router::publish_session_leaseset2(self : Router, sess : SamSession) -> Unit { let now_sec = @ntcp2_net.unix_time_sec() let ls2 = match self.build_session_leaseset2(sess, now_sec) { Some(l) => l None => return } let raw = ls2.to_bytes() catch { _ => return } let utc_date = @netdb.format_utc_date(now_sec.to_uint64()) let floodfills = self.netdb.closest_peers( sess.hash, utc_date, 3, floodfills_only=true, excluded=[self.router_hash()], ) let payload : @i2np.I2npPayload = DatabaseStore( key=sess.hash, store_type=b'\x03', reply_token=0U, reply_tunnel_id=0U, reply_gateway=None, data=raw, ) for ff in floodfills { let _ = self.send_i2np_to_peer(ff.identity.hash(), payload) } } ///| fn Router::republish_all_sessions(self : Router) -> Unit { for sess in self.sessions { self.publish_session_leaseset2(sess) } } ///| fn Router::select_lookup_peers( self : Router, target_hash : @common.Hash, excluded : Array[@common.Hash], now_sec : UInt32, limit : Int32, ) -> Array[@common.Hash] { let utc_date = @netdb.format_utc_date(now_sec.to_uint64()) let excl : Array[@common.Hash] = [self.router_hash()] for e in excluded { excl.push(e) } let ffs = self.netdb.closest_peers( target_hash, utc_date, limit, floodfills_only=true, excluded=excl, ) let peers = if ffs.length() > 0 { ffs } else { self.netdb.closest_peers( target_hash, utc_date, limit, floodfills_only=false, excluded=excl, ) } let out : Array[@common.Hash] = [] for p in peers { out.push(p.identity.hash()) } out } ///| fn Router::send_lookup_query( self : Router, lk : PendingNetDbLookup, peer_hash : @common.Hash, ) -> Unit { if !is_hash_in(peer_hash, lk.queried_peers) { lk.queried_peers.push(peer_hash) } // Proposal 154 ECIES encrypted reply (0x10) + LeaseSet lookup type (0x04) let lookup : @i2np.I2npPayload = DatabaseLookup( key=lk.target_hash, from=self.router_hash(), flags=b'\x14', reply_tunnel_id=None, excluded_peers=lk.queried_peers, reply_key=Some(lk.reply_key), reply_tags=[lk.reply_tag], ) let _ = self.send_i2np_to_peer(peer_hash, lookup) } ///| fn Router::start_netdb_lookup( self : Router, target_hash : @common.Hash, kind : Int32, client_idx : Int32, req_name : String, session_id : String, silent : Bool, ) -> Bool { let now_sec = @ntcp2_net.unix_time_sec() let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 3) if initial_peers.length() == 0 { return false } let reply_key = next_rand_32() let tag_rand = @ntcp2_net.random_bytes(8) catch { _ => Bytes::make(8, b'\x77') } let lk : PendingNetDbLookup = { target_hash, reply_key, reply_tag: tag_rand, queried_peers: [], candidate_peers: [], started_ms: @ntcp2_net.unix_time_ms(), kind, client_idx, req_name, session_id, silent, } self.pending_lookups.push(lk) self.send_lookup_query(lk, initial_peers[0]) for i = 1; i < initial_peers.length(); i = i + 1 { lk.candidate_peers.push(initial_peers[i]) } true } ///| fn Router::handle_database_store_msg( self : Router, from_peer : @common.Hash?, key : @common.Hash, store_type : Byte, reply_token : UInt32, reply_tunnel_id : UInt32, reply_gateway : @common.Hash?, data : Bytes, now_sec : UInt32, ) -> Unit { let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch { _ => false } if stored && (store_type.to_int() & 0x0F) == 3 { self.complete_lookups_for_hash(key, now_sec) } if reply_token != 0U { let status : @i2np.I2npPayload = DeliveryStatus( msg_id=reply_token, timestamp_ms=@ntcp2_net.unix_time_ms(), ) match reply_gateway { Some(gw) => if reply_tunnel_id != 0U { let std = @i2np.encode_standard_message( self.alloc_msg_id(), @ntcp2_net.unix_time_ms() + 60000UL, status, ) catch { _ => return } let _ = self.send_i2np_to_peer( gw, TunnelGateway(tunnel_id=reply_tunnel_id, data=std), ) } else { let _ = self.send_i2np_to_peer(gw, status) } None => match from_peer { Some(ph) => { let _ = self.send_i2np_to_peer(ph, status) } None => () } } } } ///| fn Router::handle_database_lookup_msg( self : Router, from_peer : @common.Hash?, key : @common.Hash, from : @common.Hash, flags : Byte, reply_tunnel_id : UInt32?, excluded_peers : Array[@common.Hash], reply_key : Bytes?, reply_tags : Array[Bytes], now_sec : UInt32, ) -> Unit { let reply = self.netdb.handle_database_lookup( self.router_hash(), key, flags, excluded_peers, now_sec, ) catch { _ => return } let enc_ecies = (flags.to_int() & 0x10) != 0 let wire_reply : @i2np.I2npPayload = if enc_ecies && reply is DatabaseStore(..) { match reply_key { Some(rk) if reply_tags.length() > 0 => { let exp_sec = now_sec + 60U let clove = @ratchet.garlic_clove_block( Local, self.alloc_msg_id(), exp_sec, reply, ) catch { _ => return } let enc = @ratchet.encrypt_ecies_lookup_reply(rk, reply_tags[0], [clove]) catch { _ => return } Garlic(data=enc) } _ => reply } } else { reply } if (flags.to_int() & 0x01) != 0 { match reply_tunnel_id { Some(tid) => { let std = @i2np.encode_standard_message( self.alloc_msg_id(), @ntcp2_net.unix_time_ms() + 60000UL, wire_reply, ) catch { _ => return } let _ = self.send_i2np_to_peer( from, TunnelGateway(tunnel_id=tid, data=std), ) return } None => () } } let dest_peer = match self.netdb.get_router_info(from) { Some(_) => from None => match from_peer { Some(p) => p None => from } } let _ = self.send_i2np_to_peer(dest_peer, wire_reply) } ///| fn Router::handle_database_search_reply_msg( self : Router, key : @common.Hash, peer_hashes : Array[@common.Hash], from : @common.Hash, ) -> Unit { for lk in self.pending_lookups { if lk.target_hash == key { if !is_hash_in(from, lk.queried_peers) { lk.queried_peers.push(from) } for ph in peer_hashes { if ph != self.router_hash() && !is_hash_in(ph, lk.queried_peers) && !is_hash_in(ph, lk.candidate_peers) && self.netdb.get_router_info(ph) is Some(_) { lk.candidate_peers.push(ph) } } while lk.candidate_peers.length() > 0 && lk.queried_peers.length() < 8 { let next_peer = lk.candidate_peers.remove(0) if !is_hash_in(next_peer, lk.queried_peers) { self.send_lookup_query(lk, next_peer) break } } } } } ///| fn Router::try_handle_lookup_garlic_reply( self : Router, garlic_data : Bytes, now_sec : UInt32, ) -> Bool { if garlic_data.length() < 24 { return false } let wire_tag = garlic_data[:8].to_owned() let mut matched_idx = -1 for i = 0; i < self.pending_lookups.length(); i = i + 1 { if @crypto.ct_eq(wire_tag, self.pending_lookups[i].reply_tag) { matched_idx = i break } } if matched_idx < 0 { return false } let lk = self.pending_lookups[matched_idx] let blocks = @ratchet.decrypt_ecies_lookup_reply( lk.reply_key, lk.reply_tag, garlic_data, ) catch { _ => return false } for blk in blocks { match blk { GarlicClove(i2np_short~, ..) => { let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch { _ => None } match decoded { Some((hdr, inner)) => self.handle_i2np_message(None, hdr, inner) None => () } } _ => () } } let _ = now_sec true } ///| fn Router::complete_lookups_for_hash( self : Router, key : @common.Hash, now_sec : UInt32, ) -> Unit { let ls2 = match self.netdb.get_lease_set2(key, now_sec) { Some(l) => l None => return } let mut i = 0 while i < self.pending_lookups.length() { let lk = self.pending_lookups[i] if lk.target_hash == key { let _ = self.pending_lookups.remove(i) if lk.client_idx < self.sam_clients.length() { let c = self.sam_clients[lk.client_idx] if !c.closed { if lk.kind == 0 { let val = ls2.destination.to_base64() let _ = send_sam_line( c.sock, "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}", ) } else { self.finish_remote_stream_connect(lk, ls2) } } } } else { i += 1 } } } ///| fn Router::poll_netdb_lookups(self : Router) -> Unit { let now_ms = @ntcp2_net.unix_time_ms() let now_sec = (now_ms / 1000UL).to_uint() let mut i = 0 while i < self.pending_lookups.length() { let lk = self.pending_lookups[i] match self.netdb.get_lease_set2(lk.target_hash, now_sec) { Some(ls2) => { let _ = self.pending_lookups.remove(i) if lk.client_idx < self.sam_clients.length() && !self.sam_clients[lk.client_idx].closed { if lk.kind == 0 { let _ = send_sam_line( self.sam_clients[lk.client_idx].sock, "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{ls2.destination.to_base64()}", ) } else { self.finish_remote_stream_connect(lk, ls2) } } continue } None => () } if now_ms > lk.started_ms + 8000UL { let _ = self.pending_lookups.remove(i) if lk.client_idx < self.sam_clients.length() { let c = self.sam_clients[lk.client_idx] if !c.closed { if lk.kind == 0 { let _ = send_sam_line( c.sock, "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}", ) } else { if !lk.silent { let _ = send_sam_line( c.sock, "STREAM STATUS RESULT=CANT_REACH_PEER", ) } c.closed = true c.sock.close() } } } } else { i += 1 } } }