Files
nandi 5d97ad8b28
check / check (macos-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 26s
fix: harden ratchet sessions and throttle BitTorrent DHT traffic
- Ratchet: cap outbound NSR pending entries per peer and globally, age them out after 180s, and prune expired or excess sessions.
- Ratchet: keep NSR pending entries across multi-NSR replies, skip failed decrypts instead of aborting, and bound inbound pending entries.
- Ratchet: expire sessions with stale receive state or high message counts; only mark sessions confirmed when no reply has been received.
- Torrent DHT: add per-node cooldowns for get_peers and announce, limit fanout and pending transactions, and skip nodes already in the routing table.
- Torrent DHT: use slower maintenance and query intervals in public mode.
- Torrent peers: mark ratchet sessions stale after stalled SYN, connect timeout, handshake timeout, or idle timeout so they re-key.
- Torrent peers: raise the per-torrent peer limit to 16 and log I2CP decode errors in debug mode.
2026-11-28 19:43:10 -08:00

1480 lines
40 KiB
MoonBit

///|
/// Embedded SAMv3 bridge wired to Proposal 144 ECIES Garlic + Ed25519 I2P Streaming
/// (plus fast loopback bridge for co-hosted local SAM sessions).
///|
priv struct SamSession {
id : String
dest : @common.Destination
hash : @common.Hash
pub_b64 : String
b32 : String
virtual_tid : UInt32
x25519_pub : Bytes?
ed_seed : Bytes?
ratchet : @ratchet.RatchetSessionManager?
stream_mgr : @streaming.StreamManager?
}
///|
priv struct SamClientConn {
sock : @ntcp2_net.TcpSocket
recv_buf : Array[Byte]
mut session_id : String?
mut mode : Int32 // 0 = command, 1 = waiting_accept, 2 = bridged
mut accept_session_id : String
mut accept_silent : Bool
mut closed : Bool
}
///|
priv struct StreamBridge {
a : @ntcp2_net.TcpSocket
b : @ntcp2_net.TcpSocket
mut a_eof : Bool
mut b_eof : Bool
}
///|
priv struct RemoteStreamBridge {
sock : @ntcp2_net.TcpSocket
session_id : String
peer_hash : @common.Hash
peer_static_pub : Bytes
lease_gw : @common.Hash
lease_tid : UInt32
local_stream_id : UInt32
mut state : Int32 // 0 = waiting_syn_ack, 1 = open
silent : Bool
mut local_eof : Bool
mut remote_eof_sent : Bool
mut closed : Bool
started_ms : UInt64
pending_buf : Array[Byte]
is_http_proxy : Bool
http_host : String
mut closing_since_ms : UInt64
mut ratchet_reset : Bool
}
///|
/// Generates a valid canonical 391-byte Ed25519 I2P Destination (sig=7, crypto=0 ElGamal)
/// plus paired X25519 encryption keypair for LeaseSet2, and returns
/// `(dest, pub_b64, priv_b64, x_keypair, ed_seed)`.
fn generate_transient_destination() -> (
@common.Destination,
String,
String,
@noise.KeyPair,
Bytes,
) raise RouterError {
let ed_seed = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
let ed_pub = @crypto.ed25519_public_key(ed_seed) catch {
e => raise Crypto(e)
}
let x_priv = @ntcp2_net.random_bytes(32) catch { e => raise Net(e) }
let x_kp = @noise.KeyPair::from_private(x_priv) catch { e => raise Noise(e) }
let pad = @ntcp2_net.random_bytes(352) catch { e => raise Net(e) }
let dest = @common.Destination::new_ed25519(ed_pub, padding=pad) catch {
e => raise Common(e)
}
let pub_bytes = dest.to_bytes()
let priv_w = @encoding.Writer::new(capacity=pub_bytes.length() + 64)
priv_w.write_bytes(pub_bytes)
priv_w.write_bytes(x_priv)
priv_w.write_bytes(ed_seed)
let pub_b64 = @encoding.base64_encode(pub_bytes)
let priv_b64 = @encoding.base64_encode(priv_w.to_bytes())
(dest, pub_b64, priv_b64, x_kp, ed_seed)
}
///|
fn Router::find_session_by_id(self : Router, id : String) -> SamSession? {
for s in self.sessions {
if s.id == id {
return Some(s)
}
}
None
}
///|
fn Router::find_session_by_pub(self : Router, pub_b64 : String) -> SamSession? {
for s in self.sessions {
if s.pub_b64 == pub_b64 {
return Some(s)
}
}
None
}
///|
fn parse_b32_hash(name : String) -> @common.Hash? {
let lower = name.to_lower()
if !lower.has_suffix(".b32.i2p") {
return None
}
let prefix = lower[:lower.length() - 8].to_owned()
let raw = @encoding.base32_decode(prefix) catch { _ => return None }
if raw.length() != 32 {
return None
}
Some(@common.Hash::from_bytes(raw) catch { _ => return None })
}
///|
fn extract_x25519_key(ls2 : @common.LeaseSet2) -> Bytes? {
for ek in ls2.encryption_keys {
if ek.key_type == X25519 && ek.key_data.length() == 32 {
return Some(ek.key_data)
}
}
let fallback = ls2.destination.inner.crypto_public_key()
if fallback.length() == 32 {
Some(fallback)
} else {
None
}
}
///|
fn Router::resolve_b32_alias(self : Router, name : String) -> @common.Hash? {
let lower = name.to_lower()
for entry in self.b32_aliases {
if entry.0 == lower {
return parse_b32_hash(entry.1)
}
}
None
}
///|
fn Router::resolve_name_local(
self : Router,
name : String,
client_session_id : String?,
) -> String? {
if name == "ME" {
match client_session_id {
Some(sid) =>
match self.find_session_by_id(sid) {
Some(s) => return Some(s.pub_b64)
None => ()
}
None => ()
}
return None
}
let lower = name.to_lower()
for entry in self.aliases {
if entry.0 == lower {
return Some(entry.1)
}
}
let now_sec = @ntcp2_net.unix_time_sec()
for entry in self.b32_aliases {
if entry.0 == lower {
match self.netdb.get_lease_set2_by_b32(entry.1, now_sec) {
Some(ls2) => return Some(ls2.destination.to_base64())
None => ()
}
}
}
for s in self.sessions {
if s.b32 == lower {
return Some(s.pub_b64)
}
}
match self.netdb.get_lease_set2_by_b32(lower, now_sec) {
Some(ls2) => return Some(ls2.destination.to_base64())
None => ()
}
None
}
///|
fn Router::has_active_bridge_to(
self : Router,
peer_hash : @common.Hash,
) -> Bool {
for br in self.remote_bridges {
if !br.closed && br.peer_hash == peer_hash && br.state == 1 && !br.local_eof {
return true
}
}
false
}
///|
fn Router::try_acquire_ratchet_reset(
self : Router,
peer_hash : @common.Hash,
now_ms : UInt64,
cooldown_ms : UInt64,
) -> Bool {
let mut i = 0
let mut recent = false
while i < self.ratchet_resets.length() {
if now_ms > self.ratchet_resets[i].1 + cooldown_ms {
let _ = self.ratchet_resets.remove(i)
} else {
if self.ratchet_resets[i].0 == peer_hash {
recent = true
}
i += 1
}
}
if recent {
return false
}
if self.ratchet_resets.length() >= 256 {
let _ = self.ratchet_resets.remove(0)
}
self.ratchet_resets.push((peer_hash, now_ms))
true
}
///|
fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool {
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n"), timeout_ms=500) catch {
_ => return false
}
true
}
///|
fn Router::flush_stream_outbound(
self : Router,
sess : SamSession,
conn : @streaming.StreamConnection,
peer_hash : @common.Hash,
peer_static_pub : Bytes,
fallback_gw : @common.Hash,
fallback_tid : UInt32,
send_ls2~ : Bool = false,
) -> Unit {
if peer_static_pub.length() != 32 {
return
}
let packets = conn.drain_outbound()
if packets.length() == 0 {
return
}
let ratchet = match sess.ratchet {
Some(r) => r
None => return
}
let now_sec = @ntcp2_net.unix_time_sec()
let mut gw = fallback_gw
let mut tid = fallback_tid
match self.netdb.get_lease_set2(peer_hash, now_sec) {
Some(ls2) if ls2.leases.length() > 0 => {
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()]
gw = chosen.tunnel_gw
tid = chosen.tunnel_id
}
_ => ()
}
let exp_sec = now_sec + 60U
let effective_send_ls2 = send_ls2 ||
!ratchet.has_active_session(peer_static_pub, now_sec~)
for idx = 0; idx < packets.length(); idx = idx + 1 {
let blocks : Array[@ratchet.RatchetBlock] = []
if effective_send_ls2 && idx == 0 {
match self.build_session_leaseset2(sess, now_sec) {
Some(ls2) => {
let ls_bytes = 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 {
_ => continue
}
blocks.push(ls_blk)
}
}
None => ()
}
}
let clove = @ratchet.garlic_clove_block(
Destination(peer_hash),
self.alloc_msg_id(),
exp_sec,
Data(data=packets[idx]),
) catch {
_ => continue
}
blocks.push(clove)
let wire = ratchet.encrypt_to_peer(
peer_static_pub, blocks, now_sec, next_rand_32,
) catch {
_ => continue
}
if self.debug {
println(
"[debug] send Garlic (\{wire.length()}B, ls2=\{effective_send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}",
)
}
self.send_routed_i2np(gw, Some(tid), Garlic(data=wire))
}
}
///|
fn Router::initiate_remote_stream(
self : Router,
client_idx : Int32,
caller_sess : SamSession,
target_dest : @common.Destination,
ls2 : @common.LeaseSet2,
silent : Bool,
from_port~ : UInt32 = 0U,
to_port~ : UInt32 = 0U,
) -> Unit {
let c = self.sam_clients[client_idx]
if c.closed {
return
}
let mgr = match caller_sess.stream_mgr {
Some(m) => m
None => {
if !silent {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR")
}
c.closed = true
c.sock.close()
return
}
}
let peer_static = match extract_x25519_key(ls2) {
Some(k) => k
None => {
if !silent {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
}
c.closed = true
c.sock.close()
return
}
}
if ls2.leases.length() == 0 {
if !silent {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
}
c.closed = true
c.sock.close()
return
}
let lease = ls2.leases[0]
if self.debug {
println(
"[debug] initiating remote stream to \{target_dest.b32_address()} leases=\{ls2.leases.length()} keys=\{ls2.encryption_keys.length()} first_gw=\{lease.tunnel_gw.to_b32_address()} tid=\{lease.tunnel_id}",
)
}
let now_ms = @ntcp2_net.unix_time_ms()
let peer_hash = target_dest.hash()
let conn = mgr.connect(peer_hash, now_ms, from_port~, to_port~) catch {
_ => {
if !silent {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=I2P_ERROR")
}
c.closed = true
c.sock.close()
return
}
}
c.mode = 2
let left_bytes = Bytes::from_array(c.recv_buf)
c.recv_buf.clear()
let pending_buf : Array[Byte] = []
for i = 0; i < left_bytes.length(); i = i + 1 {
pending_buf.push(left_bytes[i])
}
self.remote_bridges.push({
sock: c.sock,
session_id: caller_sess.id,
peer_hash,
peer_static_pub: peer_static,
lease_gw: lease.tunnel_gw,
lease_tid: lease.tunnel_id,
local_stream_id: conn.local_stream_id,
state: 0,
silent,
local_eof: false,
remote_eof_sent: false,
closed: false,
started_ms: now_ms,
pending_buf,
is_http_proxy: false,
http_host: "",
closing_since_ms: 0UL,
ratchet_reset: false,
})
self.flush_stream_outbound(
caller_sess,
conn,
peer_hash,
peer_static,
lease.tunnel_gw,
lease.tunnel_id,
send_ls2=true,
)
}
///|
fn Router::finish_remote_stream_connect(
self : Router,
lk : PendingNetDbLookup,
ls2 : @common.LeaseSet2,
) -> Unit {
let caller_sess = match self.find_session_by_id(lk.session_id) {
Some(s) => s
None => {
let c = self.sam_clients[lk.client_idx]
if !lk.silent && !c.closed {
let _ = send_sam_line(c.sock, "STREAM STATUS RESULT=INVALID_ID")
}
c.closed = true
c.sock.close()
return
}
}
self.initiate_remote_stream(
lk.client_idx,
caller_sess,
ls2.destination,
ls2,
lk.silent,
from_port=lk.from_port,
to_port=lk.to_port,
)
}
///|
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,
garlic_data : Bytes,
now_sec : UInt32,
) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms()
for sess in self.sessions {
let ratchet = match sess.ratchet {
Some(r) => r
None => continue
}
let res = Some(ratchet.decrypt_incoming(garlic_data, now_sec~)) catch {
_ => None
}
match res {
Some((_remote_static, blocks)) => {
if self.debug {
println(
"[debug] Garlic decrypted for session \{sess.id} (\{blocks.length()} blocks)",
)
}
// 1. Apply DatabaseStore cloves first so peer LeaseSet2 is cached for reply
for blk in blocks {
match blk {
GarlicClove(i2np_short~, ..) => {
let decoded = Some(@ratchet.decode_garlic_clove_i2np(i2np_short)) catch {
_ => None
}
match decoded {
Some((_h, DatabaseStore(key~, store_type~, data~, ..))) => {
let _ = self.netdb.handle_database_store(
store_type, key, data, now_sec,
) catch {
_ => false
}
}
_ => ()
}
}
_ => ()
}
}
// 2. Deliver Data (I2CP Streaming/Datagram) & other cloves
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)) =>
match inner {
Data(data~) =>
match sess.stream_mgr {
Some(mgr) => {
let prev_streams = mgr.streams.length()
let conn_opt = mgr.handle_incoming_i2cp(data, now_ms) catch {
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 {
Some(conn) =>
// Immediately send any generated SYN-ACK or ACK back if peer LeaseSet2 is known
match
self.netdb.get_lease_set2(
conn.remote_hash,
now_sec,
) {
Some(ls2) if ls2.leases.length() > 0 =>
match extract_x25519_key(ls2) {
Some(pstat) =>
self.flush_stream_outbound(
sess,
conn,
conn.remote_hash,
pstat,
ls2.leases[0].tunnel_gw,
ls2.leases[0].tunnel_id,
send_ls2=send_ls2_now,
)
None => ()
}
_ => ()
}
None => ()
}
}
None => ()
}
DatabaseStore(..) => ()
_ => self.handle_i2np_message(None, hdr, inner)
}
None => ()
}
}
_ => ()
}
}
return
}
None => ()
}
}
// Fallback: router-targeted Noise_N Garlic message addressed to self.static_key
let router_blocks = Some(
@ratchet.decrypt_router_garlic(self.static_key, garlic_data),
) catch {
_ => None
}
match router_blocks {
Some(blocks) =>
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 => ()
}
}
_ => ()
}
}
None =>
if self.debug {
let tag_hex = if garlic_data.length() >= 8 {
@encoding.hex_encode(garlic_data[:8].to_owned())
} else {
""
}
println(
"[debug] unhandled incoming Garlic (\{garlic_data.length()}B tag=\{tag_hex} sessions=\{self.sessions.length()})",
)
}
}
}
///|
fn Router::handle_sam_command(
self : Router,
client_idx : Int32,
line : String,
) -> Unit {
let client = self.sam_clients[client_idx]
let msg = @sam.SamMessage::parse(line) catch {
_ => {
let _ = send_sam_line(
client.sock,
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=parse_error",
)
return
}
}
match (msg.verb, msg.subcommand) {
("HELLO", Some("VERSION")) => {
let _ = send_sam_line(client.sock, "HELLO REPLY RESULT=OK VERSION=3.3")
}
("PING", _) => {
let pong = @sam.SamMessage::new(
"PONG",
subcommand=msg.subcommand,
params=msg.params,
)
let _ = client.sock.write_all(
@encoding.string_to_utf8_bytes(pong.serialize()),
) catch {
_ => ()
}
}
("DEST", Some("GENERATE")) => {
let (_dest, pub_b64, priv_b64, _xkp, _seed) = generate_transient_destination() catch {
_ => {
let _ = send_sam_line(client.sock, "DEST REPLY RESULT=I2P_ERROR")
return
}
}
let _ = send_sam_line(
client.sock,
"DEST REPLY PUB=\{pub_b64} PRIV=\{priv_b64}",
)
}
("NAMING", Some("LOOKUP")) => {
let name = match msg.get("NAME") {
Some(n) => n
None => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=INVALID_KEY NAME=",
)
return
}
}
match self.resolve_name_local(name, client.session_id) {
Some(val) => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}",
)
}
None => {
let target_opt = match parse_b32_hash(name) {
Some(h) => Some(h)
None => self.resolve_b32_alias(name)
}
match target_opt {
Some(target_hash) => {
let sid = match client.session_id {
Some(s) => s
None => ""
}
if !self.start_netdb_lookup(
target_hash, 0, client_idx, name, sid, false,
) {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}",
)
}
}
None => {
let _ = send_sam_line(
client.sock,
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{name}",
)
}
}
}
}
}
("SESSION", Some("CREATE")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=I2P_ERROR MESSAGE=missing_id",
)
return
}
}
if self.find_session_by_id(sid) is Some(_) {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=DUPLICATED_ID",
)
return
}
let dest_param = match msg.get("DESTINATION") {
Some(d) => d
None => "TRANSIENT"
}
let (dest, pub_b64, priv_b64, opt_xkp, opt_seed) = if dest_param ==
"TRANSIENT" {
let (d, pb, prb, xkp, seed) = generate_transient_destination() catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=I2P_ERROR",
)
return
}
}
(d, pb, prb, Some(xkp), Some(seed))
} else {
let raw = @encoding.base64_decode(dest_param) catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=INVALID_KEY",
)
return
}
}
let r = @encoding.Reader::new(raw)
let d = @common.Destination::decode(r) catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=INVALID_KEY",
)
return
}
}
let tail = r.read_remaining()
if tail.length() >= 64 {
let x_priv = tail[:32].to_owned()
let ed_seed = tail[32:64].to_owned()
let xkp = @noise.KeyPair::from_private(x_priv) catch {
_ => {
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=INVALID_KEY",
)
return
}
}
(d, d.to_base64(), dest_param, Some(xkp), Some(ed_seed))
} else {
(d, d.to_base64(), dest_param, None, None)
}
}
let b32 = dest.b32_address()
let hash = dest.hash()
let ratchet = match opt_xkp {
Some(xkp) => Some(@ratchet.RatchetSessionManager::new(xkp))
None => None
}
let stream_mgr = match opt_seed {
Some(seed) =>
Some(
@streaming.StreamManager::new(
dest,
seed,
initial_stream_id=self.alloc_stream_id(),
),
)
None => None
}
let x25519_pub = match opt_xkp {
Some(xkp) => Some(xkp.public_key)
None => None
}
let sess : SamSession = {
id: sid,
dest,
hash,
pub_b64,
b32,
virtual_tid: self.alloc_tunnel_id(),
x25519_pub,
ed_seed: opt_seed,
ratchet,
stream_mgr,
}
self.sessions.push(sess)
self.publish_session_leaseset2(sess)
client.session_id = Some(sid)
let _ = send_sam_line(
client.sock,
"SESSION STATUS RESULT=OK DESTINATION=\{priv_b64}",
)
}
("STREAM", Some("ACCEPT")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
if self.find_session_by_id(sid) is None {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
let silent = match msg.get("SILENT") {
Some(v) => v.to_lower() == "true"
None => false
}
client.mode = 1
client.accept_session_id = sid
client.accept_silent = silent
if !silent {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
}
}
("STREAM", Some("CONNECT")) => {
let sid = match msg.get("ID") {
Some(id) => id
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
let caller_sess = match self.find_session_by_id(sid) {
Some(s) => s
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_ID")
return
}
}
let dest_b64 = match msg.get("DESTINATION") {
Some(d) => d
None => {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=INVALID_KEY")
return
}
}
let silent = match msg.get("SILENT") {
Some(v) => v.to_lower() == "true"
None => false
}
let from_port = parse_sam_port(msg.get("FROM_PORT"))
let to_port = parse_sam_port(msg.get("TO_PORT"))
// 1. Check co-hosted local session fast path first
match self.find_session_by_pub(dest_b64) {
Some(target_sess) => {
let mut acceptor_idx = -1
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if !c.closed && c.mode == 1 && c.accept_session_id == target_sess.id {
acceptor_idx = i
break
}
}
if acceptor_idx < 0 {
if !silent {
let _ = send_sam_line(
client.sock,
"STREAM STATUS RESULT=CANT_REACH_PEER",
)
}
client.closed = true
client.sock.close()
return
}
let acceptor = self.sam_clients[acceptor_idx]
if !silent {
let _ = send_sam_line(client.sock, "STREAM STATUS RESULT=OK")
}
if !acceptor.accept_silent {
let _ = send_sam_line(acceptor.sock, caller_sess.pub_b64)
}
client.mode = 2
acceptor.mode = 2
self.bridges.push({
a: client.sock,
b: acceptor.sock,
a_eof: false,
b_eof: false,
})
return
}
None => ()
}
// 2. Remote destination over ECIES Garlic + Ed25519 I2P Streaming
let target_dest = @common.Destination::from_base64(dest_b64) catch {
_ => {
if !silent {
let _ = send_sam_line(
client.sock,
"STREAM STATUS RESULT=INVALID_KEY",
)
}
client.closed = true
client.sock.close()
return
}
}
let target_hash = target_dest.hash()
let now_sec = @ntcp2_net.unix_time_sec()
match self.netdb.get_lease_set2(target_hash, now_sec) {
Some(ls2) =>
self.initiate_remote_stream(
client_idx,
caller_sess,
target_dest,
ls2,
silent,
from_port~,
to_port~,
)
None =>
if !self.start_netdb_lookup(
target_hash,
1,
client_idx,
"",
caller_sess.id,
silent,
from_port~,
to_port~,
) {
if !silent {
let _ = send_sam_line(
client.sock,
"STREAM STATUS RESULT=CANT_REACH_PEER",
)
}
client.closed = true
client.sock.close()
}
}
}
_ => {
let _ = send_sam_line(
client.sock,
"HELLO REPLY RESULT=I2P_ERROR MESSAGE=unsupported_command",
)
}
}
}
///|
fn pop_line_from_buf(buf : Array[Byte]) -> String? {
let mut nl_idx = -1
for i = 0; i < buf.length(); i = i + 1 {
if buf[i] == b'\n' {
nl_idx = i
break
}
}
if nl_idx < 0 {
return None
}
let end = if nl_idx > 0 && buf[nl_idx - 1] == b'\r' {
nl_idx - 1
} else {
nl_idx
}
let line_bytes = Bytes::from_array(buf[:end])
for _k = 0; _k <= nl_idx; _k = _k + 1 {
let _ = buf.remove(0)
}
Some(@encoding.utf8_bytes_to_string(line_bytes) catch { _ => "" })
}
///|
fn Router::step_sam_clients(self : Router) -> Bool {
let mut did_work = false
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if c.closed || c.mode != 0 {
continue
}
let prev_len = c.recv_buf.length()
let eof = try {
let _ = c.sock.pump_nonblocking(c.recv_buf, 4096)
false
} catch {
_ => true
}
if c.recv_buf.length() != prev_len {
did_work = true
}
if eof {
c.closed = true
c.sock.close()
did_work = true
continue
}
while !c.closed && c.mode == 0 {
match pop_line_from_buf(c.recv_buf) {
Some(line) =>
if line.length() > 0 {
did_work = true
self.handle_sam_command(i, line)
}
None => break
}
}
}
did_work
}
///|
fn Router::step_bridges(self : Router) -> Bool {
let mut did_work = false
let mut bi = 0
while bi < self.bridges.length() {
let br = self.bridges[bi]
if !br.a_eof {
let r = br.a.poll_readable(0) catch { _ => false }
if r {
did_work = true
let data = br.a.read_some(4096) catch { _ => b"" }
if data.length() == 0 {
br.a_eof = true
br.b.shutdown_write()
} else {
br.b.write_all(data) catch {
_ => br.b_eof = true
}
}
}
}
if !br.b_eof {
let r = br.b.poll_readable(0) catch { _ => false }
if r {
did_work = true
let data = br.b.read_some(4096) catch { _ => b"" }
if data.length() == 0 {
br.b_eof = true
br.a.shutdown_write()
} else {
br.a.write_all(data) catch {
_ => br.a_eof = true
}
}
}
}
if br.a_eof && br.b_eof {
did_work = true
br.a.close()
br.b.close()
let _ = self.bridges.remove(bi)
} else {
bi += 1
}
}
did_work
}
///|
fn parse_sam_port(s_opt : String?) -> UInt32 {
let s = match s_opt {
Some(v) => v
None => return 0U
}
if s.length() == 0 {
return 0U
}
let mut val = 0U
for ch in s {
if ch < '0' || ch > '9' {
return 0U
}
val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint()
if val > 65535U {
return 0U
}
}
val
}
///|
fn find_stream_by_id(
mgr : @streaming.StreamManager,
sid : UInt32,
) -> @streaming.StreamConnection? {
for s in mgr.streams {
if s.local_stream_id == sid {
return Some(s)
}
}
None
}
///|
fn remove_stream_by_id(mgr : @streaming.StreamManager, sid : UInt32) -> Unit {
let mut i = 0
while i < mgr.streams.length() {
if mgr.streams[i].local_stream_id == sid {
let _ = mgr.streams.remove(i)
} else {
i += 1
}
}
}
///|
fn Router::step_remote_bridges(self : Router) -> Bool {
let now_ms = @ntcp2_net.unix_time_ms()
let now_sec = (now_ms / 1000UL).to_uint()
let mut did_work = false
// 1. Pair incoming Streaming SYN connections with waiting SAM STREAM ACCEPT sockets
for sess in self.sessions {
let mgr = match sess.stream_mgr {
Some(m) => m
None => continue
}
for i = 0; i < self.sam_clients.length(); i = i + 1 {
let c = self.sam_clients[i]
if c.closed || c.mode != 1 || c.accept_session_id != sess.id {
continue
}
match mgr.accept_next() {
Some(conn) => {
let peer_dest = match conn.remote_dest {
Some(d) => d
None => continue
}
let peer_ls2 = self.netdb.get_lease_set2(conn.remote_hash, now_sec)
let fallback_key = if peer_dest.inner.crypto_type() == X25519 {
peer_dest.inner.crypto_public_key()
} else {
b""
}
let (gw, tid, peer_static) = match peer_ls2 {
Some(l) if l.leases.length() > 0 =>
(
l.leases[0].tunnel_gw,
l.leases[0].tunnel_id,
extract_x25519_key(l).unwrap_or(fallback_key),
)
_ => (self.router_hash(), 0U, fallback_key)
}
if !c.accept_silent {
let _ = send_sam_line(c.sock, peer_dest.to_base64())
}
c.mode = 2
let left_bytes = Bytes::from_array(c.recv_buf)
c.recv_buf.clear()
let pending_buf : Array[Byte] = []
for j = 0; j < left_bytes.length(); j = j + 1 {
pending_buf.push(left_bytes[j])
}
self.remote_bridges.push({
sock: c.sock,
session_id: sess.id,
peer_hash: conn.remote_hash,
peer_static_pub: peer_static,
lease_gw: gw,
lease_tid: tid,
local_stream_id: conn.local_stream_id,
state: 1,
silent: c.accept_silent,
local_eof: false,
remote_eof_sent: false,
closed: false,
started_ms: now_ms,
pending_buf,
is_http_proxy: false,
http_host: "",
closing_since_ms: 0UL,
ratchet_reset: false,
})
did_work = true
self.flush_stream_outbound(
sess,
conn,
conn.remote_hash,
peer_static,
gw,
tid,
send_ls2=true,
)
}
None => break
}
}
}
// 1b. Self-heal stalled SynSent streams by marking outbound ECIES send state stale
// so a fresh Bound NewSession + LeaseSet2 is sent without dropping active recv windows
for br in self.remote_bridges {
if br.state == 0 && !br.ratchet_reset && now_ms > br.started_ms + 7000UL {
br.ratchet_reset = true
if self.has_active_bridge_to(br.peer_hash) {
continue
}
match self.find_session_by_id(br.session_id) {
Some(sess) =>
match sess.ratchet {
Some(r) => {
let lrx = r.last_recv_sec(br.peer_static_pub)
let recent_rx = lrx != 0U && now_sec <= lrx + 8U
if r.has_active_session(br.peer_static_pub, now_sec~) &&
!recent_rx &&
self.try_acquire_ratchet_reset(br.peer_hash, now_ms, 12000UL) {
r.mark_send_stale(br.peer_static_pub)
if self.debug {
println(
"[debug] marking ECIES ratchet send-stale for stalled SYN to \{br.peer_hash.to_b32_address()}",
)
}
}
}
None => ()
}
None => ()
}
}
}
// 2. Pump retransmits & flush outbound packets (ACKs, SYN-ACKs, retransmissions)
let rto_ms = if self.public_mode { 3500UL } else { 1500UL }
for sess in self.sessions {
let mgr = match sess.stream_mgr {
Some(m) => m
None => continue
}
for conn in mgr.streams {
let _ = conn.poll_retransmits(now_ms, rto_ms~) catch { _ => () }
match self.netdb.get_lease_set2(conn.remote_hash, now_sec) {
Some(ls2) if ls2.leases.length() > 0 =>
match extract_x25519_key(ls2) {
Some(pstat) =>
self.flush_stream_outbound(
sess,
conn,
conn.remote_hash,
pstat,
ls2.leases[0].tunnel_gw,
ls2.leases[0].tunnel_id,
send_ls2=conn.state == SynSent,
)
None => ()
}
_ => ()
}
}
}
// 3. Pump bidirectional SAM socket <-> StreamConnection I/O
let connect_timeout_ms = if self.public_mode { 30000UL } else { 12000UL }
let mut ri = 0
while ri < self.remote_bridges.length() {
let br = self.remote_bridges[ri]
let sess = match self.find_session_by_id(br.session_id) {
Some(s) => s
None => {
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
}
let mgr = match sess.stream_mgr {
Some(m) => m
None => {
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
}
let conn = match find_stream_by_id(mgr, br.local_stream_id) {
Some(c) => c
None => {
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
}
if br.state == 0 {
if conn.state == Established ||
conn.state == Closing ||
conn.state == Closed {
br.state = 1
did_work = true
if self.debug {
println(
"[debug] Streaming established to \{br.peer_hash.to_b32_address()} (local_sid=\{br.local_stream_id})",
)
}
if !br.silent {
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=OK")
}
} else if conn.state == Reset ||
now_ms > br.started_ms + connect_timeout_ms {
did_work = true
if self.debug {
println(
"[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}",
)
}
if !self.has_active_bridge_to(br.peer_hash) {
match sess.ratchet {
Some(r) => {
let lrx = r.last_recv_sec(br.peer_static_pub)
if lrx == 0U || now_sec > lrx + 15U {
r.mark_send_stale(br.peer_static_pub)
let _ = self.netdb.remove_lease_set2(br.peer_hash)
}
}
None => ()
}
}
if br.is_http_proxy {
send_http_proxy_error(
br.sock,
504,
"Gateway Timeout",
"Timed out establishing an I2P Streaming connection to \{br.http_host} (\{br.peer_hash.to_b32_address()}).",
)
} else if !br.silent {
let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
}
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
}
if br.state == 1 {
let avail = conn.read_available()
if avail.length() > 0 {
did_work = true
if self.debug {
println(
"[debug] stream \{br.local_stream_id} recv \{avail.length()}B",
)
}
br.sock.write_all(avail, timeout_ms=500) catch {
_ => {
br.local_eof = true
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
let _ = conn.close(now_ms) catch { _ => () }
}
}
}
if conn.is_eof() && !br.remote_eof_sent {
did_work = true
if self.debug {
println("[debug] stream \{br.local_stream_id} EOF")
}
br.sock.shutdown_write()
br.remote_eof_sent = true
if br.is_http_proxy && !br.local_eof {
br.local_eof = true
br.closing_since_ms = now_ms
let _ = conn.close(now_ms) catch { _ => () }
}
}
if conn.state == Reset {
did_work = true
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
if br.pending_buf.length() > 0 {
if conn.state != Established && conn.state != SynSent {
br.pending_buf.clear()
} else {
did_work = true
let pbytes = Bytes::from_array(br.pending_buf)
let wrote = conn.write(pbytes, now_ms) catch { _ => 0 }
if wrote >= br.pending_buf.length() {
br.pending_buf.clear()
} else if wrote > 0 {
let rem : Array[Byte] = []
for k = wrote; k < br.pending_buf.length(); k = k + 1 {
rem.push(br.pending_buf[k])
}
br.pending_buf.clear()
for b in rem {
br.pending_buf.push(b)
}
}
}
}
if !br.local_eof {
let readable = br.sock.poll_readable(0) catch { _ => false }
if readable {
did_work = true
let chunk = br.sock.read_some(4096) catch { _ => b"" }
if chunk.length() == 0 {
br.local_eof = true
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
let _ = conn.close(now_ms) catch { _ => () }
} else {
let wrote = conn.write(chunk, now_ms) catch { _ => 0 }
for k = wrote; k < chunk.length(); k = k + 1 {
br.pending_buf.push(chunk[k])
}
}
}
}
self.flush_stream_outbound(
sess,
conn,
br.peer_hash,
br.peer_static_pub,
br.lease_gw,
br.lease_tid,
send_ls2=false,
)
if br.local_eof {
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
let done_gracefully = conn.is_eof() &&
(!conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL)
if done_gracefully || now_ms > br.closing_since_ms + 5000UL {
did_work = true
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
}
}
ri += 1
}
did_work
}