Files
moon-i2p/router/netdb_protocol.mbt
nandi 14eae00f5c
check / check (macos-latest) (push) Failing after 27s
check / check (ubuntu-latest) (push) Failing after 28s
check / check (windows-latest) (push) Failing after 26s
feat: add HTTP-over-I2P proxy to router daemon
- Add --http-proxy/--proxy [host:port] (default 127.0.0.1:4444) to route .i2p and .b32.i2p HTTP requests over I2P streams
- Block clearnet hosts with 403 and reject CONNECT and https:// with 501
- Support ?i2paddresshelper= jump links that register host aliases
- Add `just proxy` target and -h/--help usage output
- Expire idle ratchet sessions after 300s and add RatchetSessionManager::drop_session for fresh NewSession handshakes
- Add NetDb::remove_lease_set2 and bound the outbound pending queue to 64 entries
2026-11-28 01:46:36 -08:00

818 lines
21 KiB
MoonBit

///|
/// Active Floodfill NetDB protocol handlers (`DatabaseStore`, ECIES `DatabaseLookup`,
/// and iterative `DatabaseSearchReply` Kademlia lookup crawl).
///|
priv struct PendingNetDbLookup {
target_hash : @common.Hash
lookup_type : Int32 // 1 = LeaseSet, 2 = RouterInfo, 3 = Exploration
reply_key : Bytes
reply_tag : Bytes
queried_peers : Array[@common.Hash]
candidate_peers : Array[@common.Hash]
started_ms : UInt64
mut last_query_ms : UInt64
kind : Int32 // 0 = NAMING LOOKUP (.b32), 1 = STREAM CONNECT awaiting LeaseSet2, 2 = background RI/exploration, 3 = HTTP proxy LeaseSet2 lookup
client_idx : Int32
req_name : String
session_id : String
silent : Bool
from_port : UInt32
to_port : UInt32
}
///|
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 enc_key = match sess.x25519_pub {
Some(k) if k.length() == 32 => k
_ => {
let fk = sess.dest.inner.crypto_public_key()
if fk.length() == 32 {
fk
} else {
return None
}
}
}
let mut max_end = now_sec + 60U
for l in leases {
if l.end_date_sec > max_end {
max_end = l.end_date_sec
}
}
let diff = if max_end > now_sec { max_end - now_sec } else { 60U }
let expires_offset = if diff < 60U {
60U
} else if diff > 660U {
660U
} else {
diff
}
let ls2 : @common.LeaseSet2 = {
destination: sess.dest,
published_sec: now_sec,
expires_offset,
flags: 0U,
offline_sig: None,
options: @common.Mapping::new(),
encryption_keys: [{ key_type: X25519, key_data: enc_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()
if self.public_mode && self.tunnels.inbound.length() == 0 {
return
}
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 {
self.send_routed_i2np(ff.identity.hash(), None, 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)
}
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
lk.last_query_ms = now_ms
let excl : Array[@common.Hash] = []
let excl_cap = if lk.queried_peers.length() < 8 {
lk.queried_peers.length()
} else {
8
}
for ei = lk.queried_peers.length() - excl_cap
ei < lk.queried_peers.length()
ei = ei + 1 {
excl.push(lk.queried_peers[ei])
}
let has_tunnels = self.tunnels.inbound.length() > 0 &&
self.tunnels.outbound.length() > 0
if has_tunnels && self.tunnels.inbound[0].hops.length() > 0 {
let in_idx = lk.queried_peers.length() % self.tunnels.inbound.length()
let in_t = if self.tunnels.inbound[in_idx].hops.length() > 0 {
self.tunnels.inbound[in_idx]
} else {
self.tunnels.inbound[0]
}
let out_idx = lk.queried_peers.length() % self.tunnels.outbound.length()
let out_t = self.tunnels.outbound[out_idx]
let ibgw = in_t.hops[0]
let flags_int = 0x01 | (lk.lookup_type << 2) | 0x10
let lookup : @i2np.I2npPayload = DatabaseLookup(
key=lk.target_hash,
from=ibgw.router_hash,
flags=flags_int.to_byte(),
reply_tunnel_id=Some(ibgw.receive_tunnel_id),
excluded_peers=excl,
reply_key=Some(lk.reply_key),
reply_tags=[lk.reply_tag],
)
let mut wrapped : @i2np.I2npPayload? = None
match self.netdb.get_router_info(peer_hash) {
Some(ri) =>
if ri.identity.inner.crypto_type() == X25519 {
let xpub = ri.identity.inner.crypto_public_key()
if xpub.length() == 32 {
let ephem_opt = Some(@noise.KeyPair::from_private(next_rand_32())) catch {
_ => None
}
match ephem_opt {
Some(ephem) => {
let clove_opt = Some(
@ratchet.garlic_clove_block(
Local,
self.alloc_msg_id(),
now_sec + 60U,
lookup,
),
) catch {
_ => None
}
match clove_opt {
Some(clove) => {
let enc_opt = Some(
@ratchet.encrypt_router_garlic(xpub, ephem, [
DateTime(now_sec),
clove,
]),
) catch {
_ => None
}
match enc_opt {
Some(enc) => wrapped = Some(Garlic(data=enc))
None => ()
}
}
None => ()
}
}
None => ()
}
}
}
None => ()
}
let wire_payload = wrapped.unwrap_or(lookup)
let ok = try {
self.send_through_tunnel(
out_t.id,
Router(router_hash=peer_hash),
wire_payload,
)
true
} catch {
_ => false
}
if ok {
if self.debug {
println(
"[debug] NetDB lookup type=\{lk.lookup_type} key=\{lk.target_hash.to_b32_address()} -> peer=\{peer_hash.to_b32_address()} via tunnel \{out_t.id} (reply_ibgw=\{ibgw.router_hash.to_b32_address()}:\{ibgw.receive_tunnel_id})",
)
}
return
}
}
// Fallback direct query (used during bootstrap when 0 tunnels exist, or in 2-router tests)
let flags_int = (lk.lookup_type << 2) | 0x10
let lookup : @i2np.I2npPayload = DatabaseLookup(
key=lk.target_hash,
from=self.router_hash(),
flags=flags_int.to_byte(),
reply_tunnel_id=None,
excluded_peers=excl,
reply_key=Some(lk.reply_key),
reply_tags=[lk.reply_tag],
)
let _ = self.send_i2np_to_peer(peer_hash, lookup)
}
///|
fn Router::has_pending_lookup(
self : Router,
target_hash : @common.Hash,
lookup_type : Int32,
) -> Bool {
for lk in self.pending_lookups {
if lk.target_hash == target_hash && lk.lookup_type == lookup_type {
return true
}
}
false
}
///|
fn Router::start_background_lookup(
self : Router,
target_hash : @common.Hash,
lookup_type : Int32,
preferred_peer~ : @common.Hash? = None,
) -> Unit {
if self.has_pending_lookup(target_hash, lookup_type) {
return
}
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let peers = self.select_lookup_peers(target_hash, [], now_sec, 3)
let ordered : Array[@common.Hash] = []
match preferred_peer {
Some(p) if p != self.router_hash() => ordered.push(p)
_ => ()
}
for p in peers {
if !is_hash_in(p, ordered) {
ordered.push(p)
}
}
if ordered.length() == 0 {
return
}
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,
lookup_type,
reply_key,
reply_tag: tag_rand,
queried_peers: [],
candidate_peers: [],
started_ms: now_ms,
last_query_ms: now_ms,
kind: 2,
client_idx: -1,
req_name: "",
session_id: "",
silent: true,
from_port: 0U,
to_port: 0U,
}
self.pending_lookups.push(lk)
self.send_lookup_query(lk, ordered[0])
for i = 1; i < ordered.length(); i = i + 1 {
lk.candidate_peers.push(ordered[i])
}
}
///|
fn Router::start_netdb_lookup(
self : Router,
target_hash : @common.Hash,
kind : Int32,
client_idx : Int32,
req_name : String,
session_id : String,
silent : Bool,
from_port~ : UInt32 = 0U,
to_port~ : UInt32 = 0U,
) -> Bool {
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let initial_peers = self.select_lookup_peers(target_hash, [], now_sec, 6)
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,
lookup_type: 1, // LeaseSet lookup
reply_key,
reply_tag: tag_rand,
queried_peers: [],
candidate_peers: [],
started_ms: now_ms,
last_query_ms: now_ms,
kind,
client_idx,
req_name,
session_id,
silent,
from_port,
to_port,
}
self.pending_lookups.push(lk)
let fanout = if self.public_mode && initial_peers.length() >= 2 {
2
} else {
1
}
for k = 0; k < fanout; k = k + 1 {
self.send_lookup_query(lk, initial_peers[k])
}
for i = fanout; i < initial_peers.length(); i = i + 1 {
lk.candidate_peers.push(initial_peers[i])
}
true
}
///|
fn Router::start_proxy_netdb_lookup(
self : Router,
target_hash : @common.Hash,
) -> Bool {
if self.has_pending_lookup(target_hash, 1) {
return true
}
self.start_netdb_lookup(target_hash, 3, -1, "", "", 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 stype = store_type.to_int() & 0x0F
let stored = self.netdb.handle_database_store(store_type, key, data, now_sec) catch {
_ => false
}
if self.debug && (stype == 3 || stored) {
println(
"[debug] NetDB DatabaseStore type=\{stype} stored=\{stored} key=\{key.to_b32_address()} (len=\{data.length()})",
)
}
if stype == 3 && stored {
self.complete_lookups_for_hash(key, now_sec)
} else if stype == 0 && stored {
// Complete any background RouterInfo lookups for `key` and feed new floodfill into active LS lookups
let mut idx = 0
while idx < self.pending_lookups.length() {
let lk = self.pending_lookups[idx]
if lk.kind == 2 && lk.lookup_type == 2 && lk.target_hash == key {
let _ = self.pending_lookups.remove(idx)
} else {
idx += 1
}
}
match self.netdb.get_router_info(key) {
Some(ri) if @netdb.is_floodfill(ri) =>
for lk in self.pending_lookups {
if lk.lookup_type == 1 &&
!is_hash_in(key, lk.queried_peers) &&
!is_hash_in(key, lk.candidate_peers) {
lk.candidate_peers.push(key)
}
}
_ => ()
}
}
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 {
if self.debug {
println(
"[debug] NetDB DatabaseSearchReply key=\{key.to_b32_address()} refs=\{peer_hashes.length()} from=\{from.to_b32_address()}",
)
}
let max_queries = if self.public_mode { 16 } else { 8 }
let unknown_to_fetch : Array[@common.Hash] = []
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) {
if self.netdb.get_router_info(ph) is Some(_) {
lk.candidate_peers.push(ph)
} else if lk.lookup_type != 2 &&
unknown_to_fetch.length() < 4 &&
!is_hash_in(ph, unknown_to_fetch) {
unknown_to_fetch.push(ph)
}
}
}
while lk.candidate_peers.length() > 0 &&
lk.queried_peers.length() < max_queries {
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
}
}
}
}
for ph in unknown_to_fetch {
self.start_background_lookup(ph, 2, preferred_peer=Some(from))
}
}
///|
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 >= 0 && 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 if lk.kind == 1 {
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 timeout_ms = if self.public_mode { 25000UL } else { 8000UL }
let max_queries = if self.public_mode { 16 } else { 8 }
let mut i = 0
while i < self.pending_lookups.length() {
let lk = self.pending_lookups[i]
if lk.kind == 2 {
if lk.lookup_type == 2 &&
self.netdb.get_router_info(lk.target_hash) is Some(_) {
let _ = self.pending_lookups.remove(i)
continue
}
if now_ms > lk.started_ms + 15000UL {
let _ = self.pending_lookups.remove(i)
continue
}
if now_ms > lk.last_query_ms + 3000UL && lk.candidate_peers.length() > 0 {
let next_p = lk.candidate_peers.remove(0)
self.send_lookup_query(lk, next_p)
}
i += 1
continue
}
match self.netdb.get_lease_set2(lk.target_hash, now_sec) {
Some(ls2) => {
let _ = self.pending_lookups.remove(i)
if lk.client_idx >= 0 &&
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 if lk.kind == 1 {
self.finish_remote_stream_connect(lk, ls2)
}
}
continue
}
None => ()
}
if self.public_mode &&
lk.queried_peers.length() < max_queries &&
now_ms > lk.last_query_ms + 2500UL {
if lk.candidate_peers.length() > 0 {
let next_p = lk.candidate_peers.remove(0)
if !is_hash_in(next_p, lk.queried_peers) {
self.send_lookup_query(lk, next_p)
}
} else {
let fresh = self.select_lookup_peers(
lk.target_hash,
lk.queried_peers,
now_sec,
2,
)
if fresh.length() > 0 {
self.send_lookup_query(lk, fresh[0])
} else {
lk.last_query_ms = now_ms
}
}
}
if now_ms > lk.started_ms + timeout_ms {
let _ = self.pending_lookups.remove(i)
if lk.client_idx >= 0 && 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.kind == 1 {
if !lk.silent {
let _ = send_sam_line(
c.sock,
"STREAM STATUS RESULT=CANT_REACH_PEER",
)
}
c.closed = true
c.sock.close()
}
}
}
} else {
i += 1
}
}
}