From 14eae00f5cd15b5f8802724b6b3b554f98d750f3 Mon Sep 17 00:00:00 2001 From: nandithebull Date: Sat, 28 Nov 2026 01:46:36 -0800 Subject: [PATCH] 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 --- README.md | 29 +- cmd/router/main.mbt | 110 +++- justfile | 5 + netdb/netdb.mbt | 16 + netdb/pkg.generated.mbti | 1 + ratchet/ecies.mbt | 43 +- ratchet/pkg.generated.mbti | 2 + ratchet/ratchet_test.mbt | 108 ++++ router/http_proxy.mbt | 1075 ++++++++++++++++++++++++++++++++++ router/http_proxy_wbtest.mbt | 102 ++++ router/netdb_protocol.mbt | 26 +- router/public_bootstrap.mbt | 116 +++- router/router.mbt | 69 ++- router/router_test.mbt | 148 +++++ router/sam_handler.mbt | 132 ++++- 15 files changed, 1941 insertions(+), 41 deletions(-) create mode 100644 router/http_proxy.mbt create mode 100644 router/http_proxy_wbtest.mbt diff --git a/README.md b/README.md index 2b46e25..0cfb373 100644 --- a/README.md +++ b/README.md @@ -19,9 +19,9 @@ moon-i2p/ ├── streaming/ # Pure-MoonBit Ed25519-signed I2P Streaming (SYN/ACK/NACK/CLOSE/RESET, RTO retransmit, sliding window) & Repliable/Raw Datagrams ├── sam/ # SAMv3 text protocol parser, serializer, PING/PONG, and command builders ├── sam_client/ # Native POSIX TCP SAMv3 client with PING/PONG, --dest support, and modern I2P defaults -├── router/ # Native MoonBit I2P Router Core with NTCP2 peer pool, floodfill NetDB crawl, Proposal 157 transit tunnels, Garlic/Streaming & SAMv3 bridge +├── router/ # Native MoonBit I2P Router Core with NTCP2 peer pool, floodfill NetDB crawl, Proposal 157 transit tunnels, Garlic/Streaming, HTTP proxy & SAMv3 bridge ├── cmd/main/ # Pure protocol demo CLI entrypoint -├── cmd/router/ # Native MoonBit I2P router daemon (`--public`, `--hops`, `--hosts`, `--debug`, `--sam`, `--ntcp2-port`, `--peer`, `--peer-dir`, `--su3`, `--reseed`, `--floodfill`) +├── cmd/router/ # Native MoonBit I2P router daemon (`--public`, `--http-proxy`, `--hops`, `--hosts`, `--debug`, `--sam`, `--ntcp2-port`, `--peer`, `--peer-dir`, `--su3`, `--reseed`, `--floodfill`) ├── cmd/client/ # Native SAMv3 CLI (`keygen`, `lookup`, `http-get`, `dial`, `listen`, `--sam`, `--dest`) └── scripts/ # Loopback SAMv3 bridge (`mock_sam.py`), multi-router `demo.py`, and end-to-end test (`e2e_test.py`) ``` @@ -51,14 +51,29 @@ moon build --target native cmd/router moon build --target native cmd/client # Join the live public I2P network behind NAT (auto-reseeds, connects NTCP2 peers, builds tunnels) -./_build/native/debug/build/cmd/router/router.exe --public --hops 1 --debug +# Add --http-proxy 127.0.0.1:4444 to also run the native I2P browser HTTP proxy on port 4444: +./_build/native/debug/build/cmd/router/router.exe --public --hops 1 --http-proxy 127.0.0.1:4444 + +# Or via just: +just proxy # Optional flags: -# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels) -# --hosts Load hostname=base64dest entries from a local I2P hosts.txt file -# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state +# --http-proxy [host:port] Enable HTTP-over-I2P proxy (default: 127.0.0.1:4444) +# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels) +# --hosts Load hostname=base64dest (or .b32.i2p) entries from a local I2P hosts.txt +# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state -# Once tunnels are up (`tunnels=in:2/out:2`), resolve and fetch live public eepsites: +# Once tunnels are up (`tunnels=in:2/out:2`), browse .i2p / .b32.i2p eepsites via the HTTP proxy: +# Point your browser's HTTP Proxy to 127.0.0.1:4444 (or test with curl): +curl -x http://127.0.0.1:4444 http://stats.i2p/ +curl -x http://127.0.0.1:4444 http://zzz.i2p/ +# Note: Non-.i2p clearnet requests are blocked (403 Forbidden), CONNECT/https:// are rejected (501), +# User-Agent is normalized to MYOB/6.66 (AN/ON) for anti-fingerprinting compatibility, +# built-in aliases cover well-known public eepsites (stats.i2p, zzz.i2p, tracker2.postman.i2p, +# notbob.i2p, insulaocculta.i2p, tracker.insulaocculta.i2p, tracker.queke.i2p, opentracker.dg2.i2p), +# and ?i2paddresshelper= jump links register aliases on the fly. + +# Or resolve and fetch directly via SAMv3 with cmd/client: ./_build/native/debug/build/cmd/client/client.exe lookup kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p ./_build/native/debug/build/cmd/client/client.exe http-get kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p / ``` diff --git a/cmd/router/main.mbt b/cmd/router/main.mbt index 243d5c3..4df6b09 100644 --- a/cmd/router/main.mbt +++ b/cmd/router/main.mbt @@ -37,11 +37,60 @@ fn split_host_port(spec : String) -> (String, Int32)? { } } +///| +fn print_usage() -> Unit { + println("moon-i2p native router daemon") + println("") + println("Usage:") + println(" router.exe [options]") + println("") + println("Options:") + println( + " --sam SAMv3 TCP listen address (default: 127.0.0.1:7656)", + ) + println( + " --http-proxy [host:port] Enable HTTP-over-I2P proxy (default when omitted: 127.0.0.1:4444)", + ) + println(" --proxy [host:port] Alias for --http-proxy") + println( + " --ntcp2-host NTCP2 advertise/bind IP (default: 127.0.0.1)", + ) + println( + " --ntcp2-port NTCP2 TCP listen port (default: 0 = ephemeral)", + ) + println( + " --public Join live public I2P network (auto-reseed + tunnels + NetDB)", + ) + println( + " --hops <1..4> Inbound/Outbound tunnel hop count (default: 1)", + ) + println( + " --hosts Load hostname=dest_or_b32 aliases into addressbook", + ) + println(" --peer Load a RouterInfo file into NetDB") + println( + " --peer-dir Load RouterInfo files from directory into NetDB", + ) + println( + " --su3 Import peers from local .su3 reseed file", + ) + println( + " --reseed Import peers from an HTTPS .su3 reseed URL", + ) + println(" --floodfill Advertise LRf floodfill capabilities") + println(" --no-clock-skew Disable NTCP2 clock skew check") + println(" --debug Enable verbose router debug logs") + println(" -h, --help Show this help message") +} + ///| fn main { let args = @env.args() let mut sam_host = "127.0.0.1" let mut sam_port = 7656 + let mut http_proxy_enabled = false + let mut http_proxy_host = "127.0.0.1" + let mut http_proxy_port = 4444 let mut ntcp2_host = "127.0.0.1" let mut ntcp2_port = 0 let mut floodfill = false @@ -58,6 +107,10 @@ fn main { let mut i = 1 while i < args.length() { match args[i] { + "-h" | "--help" => { + print_usage() + return + } "--sam" => if i + 1 < args.length() { match split_host_port(args[i + 1]) { @@ -71,6 +124,28 @@ fn main { } else { i += 1 } + "--http-proxy" | "--proxy" => { + http_proxy_enabled = true + if i + 1 < args.length() && !args[i + 1].has_prefix("-") { + match split_host_port(args[i + 1]) { + Some((h, p)) => { + http_proxy_host = h + http_proxy_port = p + i += 2 + } + None => + match parse_port(args[i + 1]) { + Some(p) => { + http_proxy_port = p + i += 2 + } + None => i += 1 + } + } + } else { + i += 1 + } + } "--ntcp2-port" => if i + 1 < args.length() { match parse_port(args[i + 1]) { @@ -149,7 +224,26 @@ fn main { check_clock_skew = false i += 1 } - _ => i += 1 + _ => + if args[i].has_prefix("--http-proxy=") { + http_proxy_enabled = true + let spec = args[i][13:].to_owned() + match split_host_port(spec) { + Some((h, p)) => { + http_proxy_host = h + http_proxy_port = p + } + None => + match parse_port(spec) { + Some(p) => http_proxy_port = p + None => + println("warning: ignoring invalid --http-proxy \{spec}") + } + } + i += 1 + } else { + i += 1 + } } } @@ -166,6 +260,17 @@ fn main { return } } + if http_proxy_enabled { + let _ = r.start_http_proxy(host=http_proxy_host, port=http_proxy_port) catch { + _ => { + r.close() + println( + "error: failed to bind HTTP proxy on \{http_proxy_host}:\{http_proxy_port}", + ) + return + } + } + } for pf in peer_files { let _ = r.load_peer_file(pf) catch { _ => { @@ -225,6 +330,9 @@ fn main { " NTCP2: \{ntcp2_host}:\{r.ntcp2_port()} (public=\{public_mode}, hops=\{tunnel_hops})", ) println(" SAMv3: \{sam_host}:\{r.sam_port()}") + if http_proxy_enabled { + println(" HTTP Proxy: \{http_proxy_host}:\{r.http_proxy_port()}") + } println( " NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})", ) diff --git a/justfile b/justfile index f8ed338..13a3e07 100644 --- a/justfile +++ b/justfile @@ -11,6 +11,11 @@ build: moon build --target native cmd/router moon build --target native cmd/client +# Start public I2P router with embedded HTTP proxy on 127.0.0.1:4444 +proxy: + moon build --target native cmd/router + ./_build/native/debug/build/cmd/router/router.exe --public --http-proxy 127.0.0.1:4444 + # Run all MoonBit tests across wasm, js, and native targets test: moon test --target wasm diff --git a/netdb/netdb.mbt b/netdb/netdb.mbt index fab263b..ac427a1 100644 --- a/netdb/netdb.mbt +++ b/netdb/netdb.mbt @@ -236,6 +236,22 @@ pub fn NetDb::get_lease_set2_by_b32( None } +///| +/// Removes any cached `LeaseSet2` for `hash` and returns `true` if one was removed. +pub fn NetDb::remove_lease_set2(self : NetDb, hash : @common.Hash) -> Bool { + let mut removed = false + let mut i = 0 + while i < self.leasesets.length() { + if self.leasesets[i].0 == hash { + let _ = self.leasesets.remove(i) + removed = true + } else { + i += 1 + } + } + removed +} + ///| /// Removes expired `LeaseSet2` entries and returns the number pruned. pub fn NetDb::prune_expired(self : NetDb, now_sec : UInt32) -> Int32 { diff --git a/netdb/pkg.generated.mbti b/netdb/pkg.generated.mbti index 11cb3b8..62dccac 100644 --- a/netdb/pkg.generated.mbti +++ b/netdb/pkg.generated.mbti @@ -43,6 +43,7 @@ pub fn NetDb::handle_database_store(Self, Byte, @common.Hash, Bytes, UInt32) -> pub fn NetDb::leaseset_count(Self) -> Int32 pub fn NetDb::new() -> Self pub fn NetDb::prune_expired(Self, UInt32) -> Int32 +pub fn NetDb::remove_lease_set2(Self, @common.Hash) -> Bool pub fn NetDb::router_count(Self) -> Int32 pub fn NetDb::store_lease_set2(Self, @common.LeaseSet2, UInt32) -> Bool raise NetDbError pub fn NetDb::store_router_info(Self, @common.RouterInfo) -> Bool raise NetDbError diff --git a/ratchet/ecies.mbt b/ratchet/ecies.mbt index 9b96fee..83ec3a6 100644 --- a/ratchet/ecies.mbt +++ b/ratchet/ecies.mbt @@ -295,6 +295,7 @@ pub struct RatchetPeerSession { mut local_next_priv : Bytes? mut local_next_pub : Bytes? mut remote_next_pub : Bytes? + mut last_used_sec : UInt32 } ///| @@ -433,6 +434,7 @@ pub fn encrypt_new_session_reply( local_next_priv: None, local_next_pub: None, remote_next_pub: None, + last_used_sec: 0U, } sess.refill_recv_window() (w.to_bytes(), sess) @@ -505,6 +507,7 @@ pub fn decrypt_new_session_reply( local_next_priv: None, local_next_pub: None, remote_next_pub: None, + last_used_sec: 0U, } sess.refill_recv_window() (blocks, sess) @@ -642,6 +645,34 @@ fn RatchetSessionManager::find_session( -1 } +///| +/// Drops any established or pending outbound ratchet state for `remote_static_pub` +/// so subsequent sends start a fresh Bound `NewSession` handshake. +pub fn RatchetSessionManager::drop_session( + self : RatchetSessionManager, + remote_static_pub : Bytes, +) -> Unit { + let mut si = 0 + while si < self.sessions.length() { + if @crypto.ct_eq(self.sessions[si].remote_static_pub, remote_static_pub) { + let _ = self.sessions.remove(si) + } else { + si += 1 + } + } + let mut pi = 0 + while pi < self.outbound_pending.length() { + if @crypto.ct_eq( + self.outbound_pending[pi].1.remote_static_pub, + remote_static_pub, + ) { + let _ = self.outbound_pending.remove(pi) + } else { + pi += 1 + } + } +} + ///| /// Initiates a DH ratchet step (`NextKey` block type 7) for `remote_static_pub`, /// returning `Some(NextKey(...))` if a session is established. @@ -715,7 +746,13 @@ pub fn RatchetSessionManager::encrypt_to_peer( ) -> Bytes raise RatchetError { let sidx = self.find_session(remote_static_pub) if sidx >= 0 { - return self.sessions[sidx].encrypt_existing(blocks) + let sess = self.sessions[sidx] + if sess.last_used_sec != 0U && now_sec > sess.last_used_sec + 300U { + let _ = self.sessions.remove(sidx) + } else { + sess.last_used_sec = now_sec + return sess.encrypt_existing(blocks) + } } // Check if we owe this peer an NSR for i = 0; i < self.inbound_pending.length(); i = i + 1 { @@ -724,6 +761,7 @@ pub fn RatchetSessionManager::encrypt_to_peer( let _ = self.inbound_pending.remove(i) let ephem_b = generate_elligator_keypair(next_rand_32) let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks) + sess.last_used_sec = now_sec self.sessions.push(sess) return wire } @@ -754,6 +792,9 @@ pub fn RatchetSessionManager::encrypt_to_peer( // Pre-register first 4 NSR tags so any reply matches for _k = 0; _k < 4; _k = _k + 1 { let (_n, tag, _k32) = p.nsr_tagset.next_entry() + while self.outbound_pending.length() >= 64 { + let _ = self.outbound_pending.remove(0) + } self.outbound_pending.push((tag, p)) } None => () diff --git a/ratchet/pkg.generated.mbti b/ratchet/pkg.generated.mbti index c5d8e32..a83c769 100644 --- a/ratchet/pkg.generated.mbti +++ b/ratchet/pkg.generated.mbti @@ -108,6 +108,7 @@ pub struct RatchetPeerSession { mut local_next_priv : Bytes? mut local_next_pub : Bytes? mut remote_next_pub : Bytes? + mut last_used_sec : UInt32 } pub fn RatchetPeerSession::apply_dh_ratchet(Self, Bytes, Bytes, for_send~ : Bool) -> Unit raise RatchetError pub fn RatchetPeerSession::encrypt_existing(Self, Array[RatchetBlock]) -> Bytes raise RatchetError @@ -120,6 +121,7 @@ pub struct RatchetSessionManager { } pub fn RatchetSessionManager::create_next_key_block(Self, Bytes, () -> Bytes) -> RatchetBlock? raise RatchetError pub fn RatchetSessionManager::decrypt_incoming(Self, Bytes) -> (Bytes?, Array[RatchetBlock]) raise RatchetError +pub fn RatchetSessionManager::drop_session(Self, Bytes) -> Unit pub fn RatchetSessionManager::encrypt_to_peer(Self, Bytes, Array[RatchetBlock], UInt32, () -> Bytes) -> Bytes raise RatchetError pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self diff --git a/ratchet/ratchet_test.mbt b/ratchet/ratchet_test.mbt index 2f4ebc9..9165c34 100644 --- a/ratchet/ratchet_test.mbt +++ b/ratchet/ratchet_test.mbt @@ -190,3 +190,111 @@ test "Proposal 144 ECIES-X25519-AEAD-Ratchet NS -> NSR -> bidirectional ES + DH } assert_eq(wrong_failed, true) } + +///| +test "Proposal 144 ECIES Ratchet idle session expiry (>300s) and drop_session recovery" { + let alice_s = @noise.KeyPair::from_private(@crypto.sha256(b"alice-idle-s")) + let bob_s = @noise.KeyPair::from_private(@crypto.sha256(b"bob-idle-s")) + let alice_mgr = @ratchet.RatchetSessionManager::new(alice_s) + let bob_mgr = @ratchet.RatchetSessionManager::new(bob_s) + let rand_a = det_rand_gen(b'\x21') + let rand_b = det_rand_gen(b'\x61') + + // Initial NS -> NSR -> ES at t=1700000100 + let c1 = @ratchet.garlic_clove_block( + Local, + 1U, + 1700000600U, + Data(data=b"init"), + ) + let w1 = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c1], + 1700000100U, + rand_a, + ) + let _ = bob_mgr.decrypt_incoming(w1) + let c2 = @ratchet.garlic_clove_block( + Local, + 2U, + 1700000600U, + Data(data=b"nsr"), + ) + let w2 = bob_mgr.encrypt_to_peer( + alice_s.public_key, + [c2], + 1700000101U, + rand_b, + ) + let _ = alice_mgr.decrypt_incoming(w2) + + // Encrypting within window at t=1700000105 uses ExistingSession (accepted by bob_mgr) + let c3 = @ratchet.garlic_clove_block( + Local, + 3U, + 1700000600U, + Data(data=b"es-alive"), + ) + let w3 = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c3], + 1700000105U, + rand_a, + ) + let (_, dec3) = bob_mgr.decrypt_incoming(w3) + assert_eq(dec3, [c3]) + + // After >300s idle (t=1700000406 > 1700000105+300), alice initiates a fresh Bound NS + // that even a restarted responder with empty session state can decrypt + let bob_restarted = @ratchet.RatchetSessionManager::new(bob_s) + let c4 = @ratchet.garlic_clove_block( + Local, + 4U, + 1700000900U, + Data(data=b"after-idle"), + ) + let w4 = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c4], + 1700000406U, + rand_a, + ) + let (from4, dec4) = bob_restarted.decrypt_incoming(w4) + assert_eq(from4, Some(alice_s.public_key)) + assert_eq(dec4.length(), 2) // DateTime + c4 + + // Responder replies with NSR so alice establishes new session + let c5 = @ratchet.garlic_clove_block( + Local, + 5U, + 1700000900U, + Data(data=b"nsr2"), + ) + let w5 = bob_restarted.encrypt_to_peer( + alice_s.public_key, + [c5], + 1700000407U, + rand_b, + ) + let (_, dec5) = alice_mgr.decrypt_incoming(w5) + assert_eq(dec5, [c5]) + + // Explicit drop_session also forces fresh Bound NS immediately + alice_mgr.drop_session(bob_s.public_key) + let bob_fresh = @ratchet.RatchetSessionManager::new(bob_s) + let c6 = @ratchet.garlic_clove_block( + Local, + 6U, + 1700000900U, + Data(data=b"after-drop"), + ) + let w6 = alice_mgr.encrypt_to_peer( + bob_s.public_key, + [c6], + 1700000408U, + rand_a, + ) + let (from6, dec6) = bob_fresh.decrypt_incoming(w6) + assert_eq(from6, Some(alice_s.public_key)) + assert_eq(dec6.length(), 2) +} diff --git a/router/http_proxy.mbt b/router/http_proxy.mbt new file mode 100644 index 0000000..e2ff23d --- /dev/null +++ b/router/http_proxy.mbt @@ -0,0 +1,1075 @@ +///| +/// Native non-blocking HTTP/1.1-over-I2P proxy integrated into `Router`. +/// Routes `.i2p` and `.b32.i2p` HTTP requests through embedded ECIES Garlic + +/// Ed25519 I2P Streaming, blocks clearnet leaks (`403`) and `CONNECT` (`501`), +/// and supports `?i2paddresshelper=` jump links. + +///| +priv struct HttpProxyConn { + sock : @ntcp2_net.TcpSocket + recv_buf : Array[Byte] + mut state : Int32 // 0 = reading_headers, 1 = waiting_lookup + mut target_host : String + mut target_hash : @common.Hash? + mut target_port : UInt32 + mut wire_request : Bytes + started_ms : UInt64 + mut closed : Bool +} + +///| +priv struct ParsedProxyRequest { + http_method : String + host : String + port : UInt32 + origin_path : String + wire_headers : String + helper_dest_b64 : String? + clean_redirect_url : String? +} + +///| +priv enum ProxyParseResult { + Ok(ParsedProxyRequest) + Error(Int32, String, String) +} + +///| +fn find_http_header_end(buf : Array[Byte]) -> (Int32, Int32)? { + let n = buf.length() + for i = 0; i < n; i = i + 1 { + if i + 3 < n && + buf[i] == b'\r' && + buf[i + 1] == b'\n' && + buf[i + 2] == b'\r' && + buf[i + 3] == b'\n' { + return Some((i, 4)) + } + if i + 1 < n && buf[i] == b'\n' && buf[i + 1] == b'\n' { + return Some((i, 2)) + } + } + None +} + +///| +fn split_crlf_or_lf_lines(s : String) -> Array[String] { + let out : Array[String] = [] + for raw in s.split("\n") { + let line = raw.to_owned() + if line.has_suffix("\r") { + out.push(line[:line.length() - 1].to_owned()) + } else { + out.push(line) + } + } + out +} + +///| +fn find_char_idx(s : String, target : Char, start~ : Int32 = 0) -> Int32 { + for i = start; i < s.length(); i = i + 1 { + if s[i].to_int() == target.to_int() { + return i + } + } + -1 +} + +///| +fn find_first_ws(s : String, start~ : Int32 = 0) -> Int32 { + for i = start; i < s.length(); i = i + 1 { + if s[i] == ' ' || s[i] == '\t' { + return i + } + } + -1 +} + +///| +fn parse_u32_port_exact(s : String) -> UInt32? { + if s.length() == 0 { + return None + } + let mut val = 0U + for ch in s { + if ch < '0' || ch > '9' { + return None + } + val = val * 10U + (ch.to_int() - '0'.to_int()).reinterpret_as_uint() + if val > 65535U { + return None + } + } + if val == 0U { + None + } else { + Some(val) + } +} + +///| +fn parse_authority_host_port(raw_auth : String) -> (String, UInt32)? { + let trimmed = raw_auth.trim().to_owned() + if trimmed.length() == 0 { + return None + } + // Reject IPv6 bracket hosts or embedded userinfo '@' confusion + let at = find_char_idx(trimmed, '@') + let auth = if at >= 0 { trimmed[at + 1:].to_owned() } else { trimmed } + if auth.length() == 0 || auth.contains("[") || auth.contains("]") { + return None + } + let colon = find_char_idx(auth, ':') + if colon < 0 { + return Some((auth, 80U)) + } + if colon == 0 { + return None + } + // Reject multiple colons + if find_char_idx(auth, ':', start=colon + 1) >= 0 { + return None + } + let host = auth[:colon].to_owned() + let port_str = auth[colon + 1:].to_owned() + match parse_u32_port_exact(port_str) { + Some(p) => Some((host, p)) + None => None + } +} + +///| +fn is_valid_i2p_hostname(host : String) -> Bool { + if host.length() == 0 { + return false + } + for ch in host { + if ch <= ' ' || ch == '/' || ch == '?' || ch == '#' || ch == '@' { + return false + } + } + true +} + +///| +fn hex_nibble(c : Int32) -> Int32 { + if c >= 48 && c <= 57 { + c - 48 + } else if c >= 65 && c <= 70 { + c - 55 + } else if c >= 97 && c <= 102 { + c - 87 + } else { + -1 + } +} + +///| +fn percent_decode_url_component(s : String) -> String { + let bytes : Array[Byte] = [] + let raw = @encoding.string_to_utf8_bytes(s) + let mut i = 0 + while i < raw.length() { + if raw[i] == b'%' && i + 2 < raw.length() { + let hi = hex_nibble(raw[i + 1].to_int()) + let lo = hex_nibble(raw[i + 2].to_int()) + if hi >= 0 && lo >= 0 { + bytes.push(((hi << 4) | lo).to_byte()) + i += 3 + continue + } + } + bytes.push(raw[i]) + i += 1 + } + @encoding.utf8_bytes_to_string(Bytes::from_array(bytes)) catch { + _ => s + } +} + +///| +fn extract_address_helper( + origin_path : String, + host : String, + port : UInt32, +) -> (String?, String?) { + let q_idx = find_char_idx(origin_path, '?') + if q_idx < 0 { + return (None, None) + } + let base_path = origin_path[:q_idx].to_owned() + let query = origin_path[q_idx + 1:].to_owned() + let kept : Array[String] = [] + let mut helper : String? = None + for part_view in query.split("&") { + let part = part_view.to_owned() + if part.length() == 0 { + continue + } + if part.has_prefix("i2paddresshelper=") { + let val = percent_decode_url_component(part[17:].to_owned()) + if val.length() > 0 { + helper = Some(val) + } + } else { + kept.push(part) + } + } + match helper { + Some(h) => { + let clean_q = if kept.length() > 0 { "?" + kept.join("&") } else { "" } + let host_part = if port == 80U { host } else { "\{host}:\{port}" } + (Some(h), Some("http://\{host_part}\{base_path}\{clean_q}")) + } + None => (None, None) + } +} + +///| +fn is_stripped_proxy_header(lower_name : String) -> Bool { + lower_name == "proxy-connection" || + lower_name == "proxy-authorization" || + lower_name == "proxy-authenticate" || + lower_name == "connection" || + lower_name == "keep-alive" || + lower_name == "te" || + lower_name == "upgrade" || + lower_name == "x-forwarded-for" || + lower_name == "forwarded" || + lower_name == "via" || + lower_name == "user-agent" +} + +///| +fn is_i2p_referer(val : String) -> Bool { + let lower = val.trim().to_owned().to_lower() + if !lower.has_prefix("http://") { + return false + } + let rest = lower[7:].to_owned() + let mut end = rest.length() + for i = 0; i < rest.length(); i = i + 1 { + if rest[i] == '/' || rest[i] == '?' || rest[i] == '#' { + end = i + break + } + } + match parse_authority_host_port(rest[:end].to_owned()) { + Some((h, _)) => { + let nh = if h.has_suffix(".") { h[:h.length() - 1].to_owned() } else { h } + nh.has_suffix(".i2p") && nh.length() > 4 + } + None => false + } +} + +///| +fn parse_http_proxy_request(header_bytes : Bytes) -> ProxyParseResult { + let header_text = @encoding.utf8_bytes_to_string(header_bytes) catch { + _ => return Error(400, "Bad Request", "Malformed UTF-8 in HTTP headers.") + } + let lines = split_crlf_or_lf_lines(header_text) + if lines.length() == 0 { + return Error(400, "Bad Request", "Empty HTTP request.") + } + let req_line = lines[0].trim().to_owned() + let sp1 = find_first_ws(req_line) + if sp1 <= 0 { + return Error(400, "Bad Request", "Malformed HTTP request line.") + } + let http_method = req_line[:sp1].to_owned().to_upper() + let rest1 = req_line[sp1 + 1:].to_owned().trim().to_owned() + let sp2 = find_first_ws(rest1) + if sp2 <= 0 { + return Error( + 400, "Bad Request", "Malformed HTTP request target or version.", + ) + } + let raw_target = rest1[:sp2].to_owned() + let version = rest1[sp2 + 1:].to_owned().trim().to_owned() + if !version.to_upper().has_prefix("HTTP/1.") { + return Error( + 505, + "HTTP Version Not Supported", + "Unsupported HTTP version: \{version}.", + ) + } + if http_method == "CONNECT" { + return Error( + 501, "Not Implemented", "CONNECT tunneling is disabled on the moon-i2p HTTP proxy. Use plain http:// URLs for .i2p eepsites (traffic is already end-to-end encrypted inside I2P).", + ) + } + + let headers : Array[(String, String)] = [] + let mut header_host_val : String? = None + for i = 1; i < lines.length(); i = i + 1 { + let line = lines[i] + if line.length() == 0 { + continue + } + let colon = find_char_idx(line, ':') + if colon <= 0 { + return Error(400, "Bad Request", "Malformed HTTP header line.") + } + let name = line[:colon].to_owned().trim().to_owned() + let val = line[colon + 1:].to_owned().trim().to_owned() + if name.to_lower() == "host" && header_host_val is None { + header_host_val = Some(val) + } + headers.push((name, val)) + } + + // Strip optional #fragment if sent in request target + let hash_idx = find_char_idx(raw_target, '#') + let clean_target = if hash_idx >= 0 { + raw_target[:hash_idx].to_owned() + } else { + raw_target + } + let lower_target = clean_target.to_lower() + + let (raw_host, port, origin_path) = if lower_target.has_prefix("http://") { + let after_scheme = clean_target[7:].to_owned() + let mut split_at = after_scheme.length() + for i = 0; i < after_scheme.length(); i = i + 1 { + if after_scheme[i] == '/' || after_scheme[i] == '?' { + split_at = i + break + } + } + let auth = after_scheme[:split_at].to_owned() + let tail = after_scheme[split_at:].to_owned() + let path = if tail.length() == 0 { + "/" + } else if tail.has_prefix("?") { + "/" + tail + } else { + tail + } + match parse_authority_host_port(auth) { + Some((h, p)) => (h, p, path) + None => + return Error(400, "Bad Request", "Invalid target host or port in URL.") + } + } else if lower_target.has_prefix("https://") { + return Error( + 501, "Not Implemented", "Use http:// instead of https:// for .i2p eepsites (I2P encrypts traffic end-to-end inside tunnels and Garlic).", + ) + } else if clean_target.has_prefix("/") { + match header_host_val { + Some(hv) => + match parse_authority_host_port(hv) { + Some((h, p)) => (h, p, clean_target) + None => return Error(400, "Bad Request", "Invalid Host header value.") + } + None => + return Error( + 400, "Bad Request", "Missing Host header in origin-form HTTP request.", + ) + } + } else { + return Error(400, "Bad Request", "Unsupported request target URI.") + } + + let mut host = raw_host.to_lower() + while host.has_suffix(".") { + host = host[:host.length() - 1].to_owned() + } + if !is_valid_i2p_hostname(host) { + return Error(400, "Bad Request", "Invalid target hostname.") + } + if !host.has_suffix(".i2p") || host.length() <= 4 { + return Error( + 403, + "Forbidden", + "Clearnet host '\{host}' blocked: moon-i2p HTTP proxy only routes .i2p destinations.", + ) + } + + let (helper_dest_b64, clean_redirect_url) = extract_address_helper( + origin_path, host, port, + ) + + let out = StringBuilder() + out.write_string("\{http_method} \{origin_path} HTTP/1.1\r\n") + let mut has_host = false + for kv in headers { + let lname = kv.0.to_lower() + if is_stripped_proxy_header(lname) { + continue + } + if lname == "referer" && !is_i2p_referer(kv.1) { + continue + } + if lname == "host" { + has_host = true + } + out.write_string("\{kv.0}: \{kv.1}\r\n") + } + if !has_host { + let host_hdr = if port == 80U { host } else { "\{host}:\{port}" } + out.write_string("Host: \{host_hdr}\r\n") + } + out.write_string("User-Agent: MYOB/6.66 (AN/ON)\r\n") + out.write_string("Connection: close\r\n\r\n") + + Ok({ + http_method, + host, + port, + origin_path, + wire_headers: out.to_string(), + helper_dest_b64, + clean_redirect_url, + }) +} + +///| +fn escape_html(s : String) -> String { + let out = StringBuilder() + for ch in s { + match ch { + '&' => out.write_string("&") + '<' => out.write_string("<") + '>' => out.write_string(">") + '"' => out.write_string(""") + _ => out.write_char(ch) + } + } + out.to_string() +} + +///| +fn send_http_proxy_error( + sock : @ntcp2_net.TcpSocket, + status : Int32, + reason : String, + detail : String, +) -> Unit { + let safe_reason = escape_html(reason) + let safe_detail = escape_html(detail) + let body = "\{status} \{safe_reason}

\{status} \{safe_reason}

\{safe_detail}


moon-i2p HTTP Proxy\n" + let body_bytes = @encoding.string_to_utf8_bytes(body) + let hdr = "HTTP/1.1 \{status} \{reason}\r\nContent-Type: text/html; charset=utf-8\r\nContent-Length: \{body_bytes.length()}\r\nConnection: close\r\n\r\n" + let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { + _ => return + } + let _ = sock.write_all(body_bytes) catch { _ => () } +} + +///| +fn send_http_proxy_redirect( + sock : @ntcp2_net.TcpSocket, + location : String, +) -> Unit { + let hdr = "HTTP/1.1 302 Found\r\nLocation: \{location}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n" + let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch { _ => () } +} + +///| +/// Starts a non-blocking HTTP-over-I2P proxy listener (default `127.0.0.1:4444`) +/// inside the router event loop. Returns the bound local TCP port. +pub fn Router::start_http_proxy( + self : Router, + host~ : String = "127.0.0.1", + port~ : Int32 = 4444, +) -> Int32 raise RouterError { + match self.http_proxy_listener { + Some(existing) => existing.close() + None => () + } + let l = @ntcp2_net.TcpListener::bind(host, port) catch { e => raise Net(e) } + self.http_proxy_listener = Some(l) + l.local_port() +} + +///| +/// Returns the bound HTTP proxy TCP port, or `0` if the HTTP proxy is disabled. +pub fn Router::http_proxy_port(self : Router) -> Int32 { + match self.http_proxy_listener { + Some(l) => l.local_port() + None => 0 + } +} + +///| +fn Router::ensure_http_proxy_session(self : Router) -> SamSession? { + match self.http_proxy_session_id { + Some(sid) => + match self.find_session_by_id(sid) { + Some(s) => return Some(s) + None => () + } + None => () + } + let sid = "__http_proxy__" + match self.find_session_by_id(sid) { + Some(s) => { + self.http_proxy_session_id = Some(sid) + 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) + self.http_proxy_session_id = Some(sid) + Some(sess) +} + +///| +fn Router::has_registered_alias(self : Router, host : String) -> Bool { + let key = host.to_lower() + for e in self.aliases { + if e.0 == key { + return true + } + } + for e in self.b32_aliases { + if e.0 == key { + return true + } + } + false +} + +///| +fn Router::attach_http_proxy_remote_stream( + self : Router, + pc : HttpProxyConn, + sess : SamSession, + target_dest : @common.Destination, + ls2 : @common.LeaseSet2, +) -> Bool { + let mgr = match sess.stream_mgr { + Some(m) => m + None => { + send_http_proxy_error( + pc.sock, + 500, + "Internal Server Error", + "HTTP proxy I2P session lacks a stream manager.", + ) + return false + } + } + let peer_static = match extract_x25519_key(ls2) { + Some(k) => k + None => { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Target LeaseSet2 for \{pc.target_host} has no usable X25519 encryption key.", + ) + return false + } + } + if ls2.leases.length() == 0 { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Target LeaseSet2 for \{pc.target_host} contains zero active inbound leases.", + ) + return false + } + let lease = ls2.leases[0] + let now_ms = @ntcp2_net.unix_time_ms() + let peer_hash = target_dest.hash() + let to_port = if pc.target_port == 80U { 0U } else { pc.target_port } + let conn = mgr.connect(peer_hash, now_ms, from_port=0U, to_port~) catch { + _ => { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Failed to initiate I2P Streaming handshake to \{pc.target_host}.", + ) + return false + } + } + if self.debug { + println( + "[debug] http-proxy -> \{pc.target_host} (\{peer_hash.to_b32_address()}) port=\{to_port}", + ) + } + let pending_buf : Array[Byte] = [] + for i = 0; i < pc.wire_request.length(); i = i + 1 { + pending_buf.push(pc.wire_request[i]) + } + self.remote_bridges.push({ + sock: pc.sock, + session_id: 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: true, + local_eof: false, + remote_eof_sent: false, + closed: false, + started_ms: now_ms, + pending_buf, + is_http_proxy: true, + http_host: pc.target_host, + closing_since_ms: 0UL, + ratchet_reset: false, + }) + self.flush_stream_outbound( + sess, + conn, + peer_hash, + peer_static, + lease.tunnel_gw, + lease.tunnel_id, + send_ls2=true, + ) + true +} + +///| +fn Router::step_http_proxy(self : Router) -> Bool { + let listener = match self.http_proxy_listener { + Some(l) => l + None => return false + } + let mut did_work = false + let now_ms = @ntcp2_net.unix_time_ms() + let now_sec = (now_ms / 1000UL).to_uint() + + // 1. Accept incoming HTTP proxy TCP connections + for _i = 0; _i < 8; _i = _i + 1 { + match (listener.accept(timeout_ms=0) catch { _ => None }) { + Some(sock) => { + self.http_proxy_conns.push({ + sock, + recv_buf: [], + state: 0, + target_host: "", + target_hash: None, + target_port: 80U, + wire_request: b"", + started_ms: now_ms, + closed: false, + }) + did_work = true + } + None => break + } + } + + // 2. Drive pending HTTP proxy header reads and NetDB lookups + let lookup_timeout_ms = if self.public_mode { 30000UL } else { 10000UL } + let mut pi = 0 + while pi < self.http_proxy_conns.length() { + let pc = self.http_proxy_conns[pi] + if pc.closed { + let _ = self.http_proxy_conns.remove(pi) + continue + } + if pc.state == 0 { + if now_ms > pc.started_ms + 15000UL { + send_http_proxy_error( + pc.sock, + 408, + "Request Timeout", + "Timed out waiting for complete HTTP request headers.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + did_work = true + continue + } + let prev_len = pc.recv_buf.length() + let eof = try { + let _ = pc.sock.pump_nonblocking(pc.recv_buf, 8192) + false + } catch { + _ => true + } + if pc.recv_buf.length() != prev_len { + did_work = true + } + if pc.recv_buf.length() > 65536 { + send_http_proxy_error( + pc.sock, + 431, + "Request Header Fields Too Large", + "HTTP request headers exceed the 64 KiB proxy limit.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + did_work = true + continue + } + match find_http_header_end(pc.recv_buf) { + Some((hdr_end, sep_len)) => { + did_work = true + let raw_all = Bytes::from_array(pc.recv_buf) + let hdr_bytes = raw_all[:hdr_end].to_owned() + let body_bytes = raw_all[hdr_end + sep_len:].to_owned() + pc.recv_buf.clear() + match parse_http_proxy_request(hdr_bytes) { + Error(code, reason, detail) => { + send_http_proxy_error(pc.sock, code, reason, detail) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + Ok(parsed) => { + // Handle ?i2paddresshelper= + match (parsed.helper_dest_b64, parsed.clean_redirect_url) { + (Some(dest_b64), Some(redir)) => { + let valid_dest = try { + let _ = @common.Destination::from_base64(dest_b64) + true + } catch { + _ => false + } + if !valid_dest { + send_http_proxy_error( + pc.sock, + 400, + "Bad Request", + "Invalid Base64 I2P Destination in i2paddresshelper parameter.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + if !self.has_registered_alias(parsed.host) { + self.register_alias(parsed.host, dest_b64) + } + send_http_proxy_redirect(pc.sock, redir) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + _ => () + } + + if self.public_mode && + ( + self.tunnels.inbound.length() == 0 || + self.tunnels.outbound.length() == 0 + ) { + send_http_proxy_error( + pc.sock, + 503, + "Service Unavailable", + "I2P router is still bootstrapping tunnels (inbound=\{self.inbound_tunnel_count()}, outbound=\{self.outbound_tunnel_count()}, peers=\{self.peer_count()}). Retry shortly.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + + let sess = match self.ensure_http_proxy_session() { + Some(s) => s + None => { + send_http_proxy_error( + pc.sock, + 500, + "Internal Server Error", + "Failed to initialize HTTP proxy SAM session.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + } + + let hdr_wire = @encoding.string_to_utf8_bytes(parsed.wire_headers) + let wire_buf = @encoding.Writer::new( + capacity=hdr_wire.length() + body_bytes.length(), + ) + wire_buf.write_bytes(hdr_wire) + wire_buf.write_bytes(body_bytes) + let wire_req = wire_buf.to_bytes() + pc.target_host = parsed.host + pc.target_port = parsed.port + pc.wire_request = wire_req + if self.debug { + println( + "[debug] http-proxy req: \{parsed.http_method} http://\{parsed.host}:\{parsed.port}\{parsed.origin_path}", + ) + } + + // 1. Check co-hosted local SAM session fast path first + match self.resolve_name_local(parsed.host, None) { + Some(dest_b64) => + 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 { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Local destination \{parsed.host} is not currently accepting streams.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + let acceptor = self.sam_clients[acceptor_idx] + if !acceptor.accept_silent { + let _ = send_sam_line(acceptor.sock, sess.pub_b64) + } + let ok_write = try { + acceptor.sock.write_all(wire_req) + true + } catch { + _ => false + } + if !ok_write { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Failed writing HTTP request to local destination \{parsed.host}.", + ) + pc.sock.close() + pc.closed = true + acceptor.closed = true + acceptor.sock.close() + let _ = self.http_proxy_conns.remove(pi) + continue + } + acceptor.mode = 2 + self.bridges.push({ + a: pc.sock, + b: acceptor.sock, + a_eof: false, + b_eof: false, + }) + let _ = self.http_proxy_conns.remove(pi) + continue + } + None => { + let target_dest = @common.Destination::from_base64( + dest_b64, + ) catch { + _ => { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Resolved destination for \{parsed.host} is invalid.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + } + let target_hash = target_dest.hash() + match self.netdb.get_lease_set2(target_hash, now_sec) { + Some(ls2) => { + let attached = self.attach_http_proxy_remote_stream( + pc, sess, target_dest, ls2, + ) + if !attached { + pc.sock.close() + pc.closed = true + } + let _ = self.http_proxy_conns.remove(pi) + continue + } + None => { + pc.target_hash = Some(target_hash) + pc.state = 1 + if !self.start_proxy_netdb_lookup(target_hash) { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "No NetDB floodfill peers available to look up \{parsed.host}.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + pi += 1 + continue + } + } + } + } + None => () + } + + // 2. Try .b32.i2p address or built-in/hosts.txt .b32.i2p alias + let hash_opt = match parse_b32_hash(parsed.host) { + Some(h) => Some(h) + None => self.resolve_b32_alias(parsed.host) + } + match hash_opt { + Some(target_hash) => + match self.netdb.get_lease_set2(target_hash, now_sec) { + Some(ls2) => { + let attached = self.attach_http_proxy_remote_stream( + pc, + sess, + ls2.destination, + ls2, + ) + if !attached { + pc.sock.close() + pc.closed = true + } + let _ = self.http_proxy_conns.remove(pi) + continue + } + None => { + pc.target_hash = Some(target_hash) + pc.state = 1 + if !self.start_proxy_netdb_lookup(target_hash) { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "No NetDB floodfill peers available to look up \{parsed.host}.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + pi += 1 + continue + } + } + None => { + send_http_proxy_error( + pc.sock, + 502, + "Bad Gateway", + "Unknown .i2p host '\{parsed.host}'. Use its .b32.i2p address, add it via --hosts , or visit an ?i2paddresshelper= jump URL.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + } + } + } + } + None => + if eof { + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + did_work = true + continue + } + } + pi += 1 + } else if pc.state == 1 { + let target_hash = match pc.target_hash { + Some(h) => h + None => { + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + } + match self.netdb.get_lease_set2(target_hash, now_sec) { + Some(ls2) => { + did_work = true + match self.ensure_http_proxy_session() { + Some(sess) => { + let attached = self.attach_http_proxy_remote_stream( + pc, + sess, + ls2.destination, + ls2, + ) + if !attached { + pc.sock.close() + pc.closed = true + } + } + None => { + send_http_proxy_error( + pc.sock, + 500, + "Internal Server Error", + "Failed to initialize HTTP proxy SAM session.", + ) + pc.sock.close() + pc.closed = true + } + } + let _ = self.http_proxy_conns.remove(pi) + continue + } + None => () + } + if now_ms > pc.started_ms + lookup_timeout_ms || + !self.has_pending_lookup(target_hash, 1) { + did_work = true + send_http_proxy_error( + pc.sock, + 504, + "Gateway Timeout", + "Could not resolve LeaseSet2 for \{pc.target_host} (\{target_hash.to_b32_address()}) in I2P NetDB.", + ) + pc.sock.close() + pc.closed = true + let _ = self.http_proxy_conns.remove(pi) + continue + } + pi += 1 + } else { + pi += 1 + } + } + did_work +} diff --git a/router/http_proxy_wbtest.mbt b/router/http_proxy_wbtest.mbt new file mode 100644 index 0000000..5d97c6d --- /dev/null +++ b/router/http_proxy_wbtest.mbt @@ -0,0 +1,102 @@ +///| +test "parse_http_proxy_request rewrites GET request and strips leak/proxy headers" { + let raw = b"GET http://stats.i2p/path?x=1 HTTP/1.1\r\nHost: stats.i2p\r\nProxy-Connection: keep-alive\r\nProxy-Authorization: Basic dXNlcjpwYXNz\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5\r\nX-Forwarded-For: 1.2.3.4\r\nForwarded: for=1.2.3.4\r\nVia: 1.1 proxy\r\nReferer: https://google.com/search\r\nCookie: sid=xyz\r\nUser-Agent: TestBrowser/1.0\r\n\r\n" + match parse_http_proxy_request(raw) { + Ok(req) => { + assert_eq(req.http_method, "GET") + assert_eq(req.host, "stats.i2p") + assert_eq(req.port, 80U) + assert_eq(req.origin_path, "/path?x=1") + assert_true(req.wire_headers.has_prefix("GET /path?x=1 HTTP/1.1\r\n")) + assert_true(req.wire_headers.contains("Host: stats.i2p\r\n")) + assert_true(req.wire_headers.contains("Cookie: sid=xyz\r\n")) + assert_true( + req.wire_headers.contains("User-Agent: MYOB/6.66 (AN/ON)\r\n"), + ) + assert_true(!req.wire_headers.contains("TestBrowser/1.0")) + assert_true(req.wire_headers.has_suffix("Connection: close\r\n\r\n")) + assert_true(!req.wire_headers.contains("Proxy-Connection")) + assert_true(!req.wire_headers.contains("Proxy-Authorization")) + assert_true(!req.wire_headers.contains("Keep-Alive")) + assert_true(!req.wire_headers.contains("X-Forwarded-For")) + assert_true(!req.wire_headers.contains("Forwarded:")) + assert_true(!req.wire_headers.contains("Via:")) + assert_true(!req.wire_headers.contains("google.com")) + } + Error(code, _, detail) => fail("unexpected error \{code}: \{detail}") + } +} + +///| +test "parse_http_proxy_request preserves POST headers, port, and .i2p Referer" { + let raw = b"POST http://tracker2.postman.i2p:8080/?action=Enter HTTP/1.1\r\nHost: tracker2.postman.i2p:8080\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 42\r\nReferer: http://tracker2.postman.i2p/index.php\r\n\r\n" + match parse_http_proxy_request(raw) { + Ok(req) => { + assert_eq(req.http_method, "POST") + assert_eq(req.host, "tracker2.postman.i2p") + assert_eq(req.port, 8080U) + assert_eq(req.origin_path, "/?action=Enter") + assert_true( + req.wire_headers.contains( + "Content-Type: application/x-www-form-urlencoded\r\n", + ), + ) + assert_true(req.wire_headers.contains("Content-Length: 42\r\n")) + assert_true( + req.wire_headers.contains( + "Referer: http://tracker2.postman.i2p/index.php\r\n", + ), + ) + } + Error(code, _, detail) => fail("unexpected error \{code}: \{detail}") + } +} + +///| +test "parse_http_proxy_request blocks clearnet hosts with 403 and CONNECT/https with 501" { + match + parse_http_proxy_request( + b"GET http://example.com/secret HTTP/1.1\r\nHost: example.com\r\n\r\n", + ) { + Ok(_) => fail("expected 403 for clearnet host") + Error(code, _, _) => assert_eq(code, 403) + } + match + parse_http_proxy_request( + b"CONNECT stats.i2p:443 HTTP/1.1\r\nHost: stats.i2p:443\r\n\r\n", + ) { + Ok(_) => fail("expected 501 for CONNECT") + Error(code, _, _) => assert_eq(code, 501) + } + match + parse_http_proxy_request( + b"GET https://stats.i2p/ HTTP/1.1\r\nHost: stats.i2p\r\n\r\n", + ) { + Ok(_) => fail("expected 501 for https://") + Error(code, _, _) => assert_eq(code, 501) + } +} + +///| +test "parse_http_proxy_request extracts i2paddresshelper and builds clean redirect URL" { + match + parse_http_proxy_request( + b"GET http://newsite.i2p/?i2paddresshelper=TESTB64DATA~- HTTP/1.1\r\nHost: newsite.i2p\r\n\r\n", + ) { + Ok(req) => { + assert_eq(req.helper_dest_b64, Some("TESTB64DATA~-")) + assert_eq(req.clean_redirect_url, Some("http://newsite.i2p/")) + } + Error(code, _, detail) => fail("unexpected error \{code}: \{detail}") + } + match + parse_http_proxy_request( + b"GET http://newsite.i2p/dir?a=1&i2paddresshelper=ABC%7E1&b=2 HTTP/1.1\r\nHost: newsite.i2p\r\n\r\n", + ) { + Ok(req) => { + assert_eq(req.helper_dest_b64, Some("ABC~1")) + assert_eq(req.clean_redirect_url, Some("http://newsite.i2p/dir?a=1&b=2")) + } + Error(code, _, detail) => fail("unexpected error \{code}: \{detail}") + } +} diff --git a/router/netdb_protocol.mbt b/router/netdb_protocol.mbt index 6f76a4c..c7d9167 100644 --- a/router/netdb_protocol.mbt +++ b/router/netdb_protocol.mbt @@ -12,7 +12,7 @@ priv struct PendingNetDbLookup { 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 + 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 @@ -427,6 +427,17 @@ fn Router::start_netdb_lookup( 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, @@ -690,7 +701,7 @@ fn Router::complete_lookups_for_hash( 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() { + 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 { @@ -699,7 +710,7 @@ fn Router::complete_lookups_for_hash( c.sock, "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}", ) - } else { + } else if lk.kind == 1 { self.finish_remote_stream_connect(lk, ls2) } } @@ -739,14 +750,15 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit { 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() && + 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 { + } else if lk.kind == 1 { self.finish_remote_stream_connect(lk, ls2) } } @@ -778,7 +790,7 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit { } if now_ms > lk.started_ms + timeout_ms { let _ = self.pending_lookups.remove(i) - if lk.client_idx < self.sam_clients.length() { + 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 { @@ -786,7 +798,7 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit { c.sock, "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}", ) - } else { + } else if lk.kind == 1 { if !lk.silent { let _ = send_sam_line( c.sock, diff --git a/router/public_bootstrap.mbt b/router/public_bootstrap.mbt index c78bc78..6fabcf1 100644 --- a/router/public_bootstrap.mbt +++ b/router/public_bootstrap.mbt @@ -31,7 +31,37 @@ pub fn Router::auto_reseed(self : Router) -> Int32 { } ///| -/// Loads `hostname=base64dest` addressbook aliases from a local `hosts.txt` file. +pub let default_public_b32_aliases : Array[(String, String)] = [ + ("stats.i2p", "kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p"), + ("zzz.i2p", "lhbd7ojcaiofbfku7ixh47qj537g572zmhdc4oilvugzxdpdghua.b32.i2p"), + ( + "tracker2.postman.i2p", "6a4kxkg5wp33p25qqhgwl6sj4yh4xuf5b3p3qldwgclebchm3eea.b32.i2p", + ), + ("notbob.i2p", "nytzrhrjjfsutowojvxi7hphesskpqqr65wpistz6wa7cpajhp7a.b32.i2p"), + ( + "insulaocculta.i2p", "ls5mvws4ytegkfa2s56lo7wl5h5elocyrfhmufpzq4eyozc3vosa.b32.i2p", + ), + ( + "tracker.insulaocculta.i2p", "2rv2kch37xsn2fqdz6huyevq76njop4inumscnspklh3ufo7mkwa.b32.i2p", + ), + ( + "tracker.queke.i2p", "j4nrlimeg2loq5sfslb3c6nmnvbucet4gyrmog66igxrk5l5fxla.b32.i2p", + ), + ( + "opentracker.dg2.i2p", "w7tpbzncbcocrqtwwm3nezhnnsw4ozadvi2hmvzdhrqzfxfum7wa.b32.i2p", + ), +] + +///| +/// Registers built-in `.i2p` -> `.b32.i2p` aliases for well-known public eepsites. +pub fn Router::register_default_public_aliases(self : Router) -> Unit { + for entry in default_public_b32_aliases { + self.register_alias(entry.0, entry.1) + } +} + +///| +/// Loads `hostname=base64dest` or `hostname=<52char>.b32.i2p` aliases from a local `hosts.txt` file. pub fn Router::load_hosts_file( self : Router, path : String, @@ -56,7 +86,8 @@ pub fn Router::load_hosts_file( if eq > 0 && eq + 1 < line.length() { let host = line[:eq].to_owned().trim().to_owned() let dest_b64 = line[eq + 1:].to_owned().trim().to_owned() - if host.length() > 0 && dest_b64.length() > 100 { + if host.length() > 0 && + (dest_b64.length() > 100 || parse_b32_hash(dest_b64) is Some(_)) { self.register_alias(host, dest_b64) count += 1 } @@ -174,6 +205,16 @@ fn Router::pick_connected_hop( None } +///| +fn Router::has_connected_peer(self : Router, hash : @common.Hash) -> Bool { + for p in self.peers { + if p.hash == hash { + return true + } + } + false +} + ///| fn Router::step_public_bootstrap(self : Router) -> Unit { let now_ms = @ntcp2_net.unix_time_ms() @@ -182,6 +223,77 @@ fn Router::step_public_bootstrap(self : Router) -> Unit { } self.last_bootstrap_ms = now_ms + // Keepalive NTCP2 peers carrying active Inbound/Outbound tunnels so long-lived sessions stay reachable + let tunnel_peers : Array[@common.Hash] = [] + for t in self.tunnels.inbound { + if t.hops.length() > 0 { + let h = t.hops[t.hops.length() - 1].router_hash + if !is_peer_in_list(h, tunnel_peers) { + tunnel_peers.push(h) + } + } + } + for t in self.tunnels.outbound { + if t.hops.length() > 0 { + let h = t.hops[0].router_hash + if !is_peer_in_list(h, tunnel_peers) { + tunnel_peers.push(h) + } + } + } + let mut pi = 0 + while pi < self.peers.length() { + let p = self.peers[pi] + if is_peer_in_list(p.hash, tunnel_peers) && + now_ms > p.last_active_ms + 90000UL { + let ok = try { + p.conn.send_blocks([@ntcp2.Ntcp2Block::Padding(b"\x00\x00\x00\x00")]) + true + } catch { + _ => false + } + if ok { + p.last_active_ms = now_ms + pi += 1 + } else { + p.conn.close() + let _ = self.peers.remove(pi) + } + } else { + pi += 1 + } + } + + // Prune expired, nearly-expired, or disconnected-hop client tunnels so fresh replacements build automatically + let now_sec = (now_ms / 1000UL).to_uint() + let mut inbound_pruned = false + let mut ii = 0 + while ii < self.tunnels.inbound.length() { + let t = self.tunnels.inbound[ii] + let dead_last_hop = t.hops.length() > 0 && + !self.has_connected_peer(t.hops[t.hops.length() - 1].router_hash) + if t.expires_sec <= now_sec + 30U || dead_last_hop { + let _ = self.tunnels.inbound.remove(ii) + inbound_pruned = true + } else { + ii += 1 + } + } + let mut oi = 0 + while oi < self.tunnels.outbound.length() { + let t = self.tunnels.outbound[oi] + let dead_first_hop = t.hops.length() > 0 && + !self.has_connected_peer(t.hops[0].router_hash) + if t.expires_sec <= now_sec + 30U || dead_first_hop { + let _ = self.tunnels.outbound.remove(oi) + } else { + oi += 1 + } + } + if inbound_pruned && self.tunnels.inbound.length() > 0 { + self.republish_all_sessions() + } + // 1. Keep up to 6 live outbound NTCP2 TCP peer sessions active let target_peers = 6 if self.peers.length() + self.pending_dials.length() < target_peers { diff --git a/router/router.mbt b/router/router.mbt index 74c6a3f..e17bfc3 100644 --- a/router/router.mbt +++ b/router/router.mbt @@ -66,7 +66,11 @@ pub struct Router { priv bridges : Array[StreamBridge] priv remote_bridges : Array[RemoteStreamBridge] priv aliases : Array[(String, String)] // hostname -> pub_b64 + priv b32_aliases : Array[(String, String)] // hostname -> lowercase <52>.b32.i2p priv failed_peers : Array[(@common.Hash, UInt64)] // (router_hash, retry_after_ms) + priv mut http_proxy_listener : @ntcp2_net.TcpListener? + priv http_proxy_conns : Array[HttpProxyConn] + priv mut http_proxy_session_id : String? priv mut lease_rr : Int32 priv mut outbound_rr : Int32 priv mut last_bootstrap_ms : UInt64 @@ -225,7 +229,7 @@ pub fn Router::start( } else { tunnel_hops } - { + let r : Router = { ed_seed, static_key, ntcp2_iv, @@ -254,12 +258,20 @@ pub fn Router::start( bridges: [], remote_bridges: [], aliases: [], + b32_aliases: [], failed_peers: [], + http_proxy_listener: None, + http_proxy_conns: [], + http_proxy_session_id: None, lease_rr: 0, outbound_rr: 0, last_bootstrap_ms: 0UL, last_explore_ms: 0UL, } + if public_mode { + r.register_default_public_aliases() + } + r } ///| @@ -297,6 +309,33 @@ pub fn Router::router_hash(self : Router) -> @common.Hash { self.router_info.identity.hash() } +///| +fn remove_alias_entry(list : Array[(String, String)], key : String) -> Unit { + let mut i = 0 + while i < list.length() { + if list[i].0 == key { + let _ = list.remove(i) + } else { + i += 1 + } + } +} + +///| +fn upsert_alias_entry( + list : Array[(String, String)], + key : String, + val : String, +) -> Unit { + for i = 0; i < list.length(); i = i + 1 { + if list[i].0 == key { + list[i] = (key, val) + return + } + } + list.push((key, val)) +} + ///| pub fn Router::register_alias( self : Router, @@ -304,13 +343,13 @@ pub fn Router::register_alias( dest_pub_b64 : String, ) -> Unit { let key = hostname.to_lower() - for i = 0; i < self.aliases.length(); i = i + 1 { - if self.aliases[i].0 == key { - self.aliases[i] = (key, dest_pub_b64) - return - } + if parse_b32_hash(dest_pub_b64) is Some(_) { + remove_alias_entry(self.aliases, key) + upsert_alias_entry(self.b32_aliases, key, dest_pub_b64.to_lower()) + } else { + remove_alias_entry(self.b32_aliases, key) + upsert_alias_entry(self.aliases, key, dest_pub_b64) } - self.aliases.push((key, dest_pub_b64)) } ///| @@ -393,6 +432,19 @@ pub fn Router::reseed_from_url( ///| pub fn Router::close(self : Router) -> Unit { + for pc in self.http_proxy_conns { + if !pc.closed { + pc.sock.close() + pc.closed = true + } + } + match self.http_proxy_listener { + Some(l) => { + l.close() + self.http_proxy_listener = None + } + None => () + } for c in self.sam_clients { if !c.closed { c.sock.close() @@ -509,6 +561,9 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit { if self.step_sam_clients() { did_work = true } + if self.step_http_proxy() { + did_work = true + } self.poll_netdb_lookups() self.poll_tunnel_builds() if self.public_mode { diff --git a/router/router_test.mbt b/router/router_test.mbt index c9a1ca1..f844756 100644 --- a/router/router_test.mbt +++ b/router/router_test.mbt @@ -193,6 +193,154 @@ test "Two live routers end-to-end: NTCP2 + ECIES NetDB + Garlic Ratchet + Ed2551 assert_eq(got_on_alice, b"ack-from-bob") } +///| +fn pump_read_until_bytes_contains( + sock : @ntcp2_net.TcpSocket, + rs : Array[@router.Router], + marker : String, + max_ticks~ : Int32 = 1500, +) -> String raise { + let out : Array[Byte] = [] + for _i = 0; _i < max_ticks; _i = _i + 1 { + step_routers(rs, 1) + while sock.poll_readable(0) { + let chunk = sock.read_some(4096) + if chunk.length() == 0 { + return @encoding.utf8_bytes_to_string(Bytes::from_array(out)) + } + for j = 0; j < chunk.length(); j = j + 1 { + out.push(chunk[j]) + } + } + let s = @encoding.utf8_bytes_to_string(Bytes::from_array(out)) catch { + _ => "" + } + if s.contains(marker) { + return s + } + } + fail("timed out waiting for marker \{marker}") +} + +///| +test "Two-router HTTP-over-I2P proxy GET, POST, clearnet block, CONNECT block, and addresshelper" { + let router_b = @router.Router::start( + { + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }, + floodfill=true, + ) + defer router_b.close() + let router_a = @router.Router::start({ + sam_host: "127.0.0.1", + sam_port: 0, + ntcp2_host: "127.0.0.1", + ntcp2_port: 0, + }) + defer router_a.close() + let _ = router_a.netdb.store_router_info(router_b.router_info) + let _ = router_b.netdb.store_router_info(router_a.router_info) + let proxy_port = router_a.start_http_proxy(host="127.0.0.1", port=0) + assert_true(proxy_port > 0) + assert_eq(router_a.http_proxy_port(), proxy_port) + let rs = [router_a, router_b] + + // Bob creates a hidden eepsite destination on Router B and opens SAM STREAM ACCEPT + let bob_ctrl = sam_connect_and_hello(router_b.sam_port(), rs) + defer bob_ctrl.close() + bob_ctrl.write_all( + b"SESSION CREATE STYLE=STREAM ID=bobhttp DESTINATION=TRANSIENT\n", + ) + assert_true( + pump_read_line(bob_ctrl, rs).has_prefix("SESSION STATUS RESULT=OK"), + ) + bob_ctrl.write_all(b"NAMING LOOKUP NAME=ME\n") + let bob_pub_b64 = extract_kv(pump_read_line(bob_ctrl, rs), "VALUE") + let bob_b32 = @common.Destination::from_base64(bob_pub_b64).b32_address() + + // 1. Proxied HTTP/1.1 GET over .b32.i2p -> NetDB -> ECIES Garlic -> Streaming + let bob_acc1 = sam_connect_and_hello(router_b.sam_port(), rs) + defer bob_acc1.close() + bob_acc1.write_all(b"STREAM ACCEPT ID=bobhttp SILENT=false\n") + assert_eq(pump_read_line(bob_acc1, rs), "STREAM STATUS RESULT=OK") + + let p1 = @ntcp2_net.TcpSocket::connect("127.0.0.1", proxy_port) + defer p1.close() + let req1 = "GET http://\{bob_b32}/hello?x=1 HTTP/1.1\r\nHost: \{bob_b32}\r\nCookie: sid=abc\r\nProxy-Connection: keep-alive\r\nReferer: http://clearnet.example.com/\r\nConnection: keep-alive\r\n\r\n" + p1.write_all(@encoding.string_to_utf8_bytes(req1)) + + let peer_b64_1 = pump_read_line(bob_acc1, rs) + assert_true(peer_b64_1.length() > 100) + let got_req1 = pump_read_until_bytes_contains(bob_acc1, rs, "\r\n\r\n") + assert_true(got_req1.has_prefix("GET /hello?x=1 HTTP/1.1\r\n")) + assert_true(got_req1.contains("Host: \{bob_b32}\r\n")) + assert_true(got_req1.contains("Cookie: sid=abc\r\n")) + assert_true(got_req1.contains("Connection: close\r\n")) + assert_true(!got_req1.contains("Proxy-Connection")) + assert_true(!got_req1.contains("clearnet.example.com")) + + bob_acc1.write_all( + b"HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 9\r\n\r\npong-http", + ) + bob_acc1.shutdown_write() + let resp1_str = @encoding.utf8_bytes_to_string(pump_read_until_eof(p1, rs)) + assert_true(resp1_str.has_prefix("HTTP/1.1 200 OK\r\n")) + assert_true(resp1_str.has_suffix("pong-http")) + + // 2. Proxied HTTP/1.1 POST over .b32.i2p alias with body forwarding & .i2p Referer + router_a.register_alias("bobsite.i2p", bob_b32) + let bob_acc2 = sam_connect_and_hello(router_b.sam_port(), rs) + defer bob_acc2.close() + bob_acc2.write_all(b"STREAM ACCEPT ID=bobhttp SILENT=false\n") + assert_eq(pump_read_line(bob_acc2, rs), "STREAM STATUS RESULT=OK") + + let p2 = @ntcp2_net.TcpSocket::connect("127.0.0.1", proxy_port) + defer p2.close() + p2.write_all( + b"POST http://bobsite.i2p/form HTTP/1.1\r\nHost: bobsite.i2p\r\nContent-Type: application/x-www-form-urlencoded\r\nContent-Length: 7\r\nReferer: http://bobsite.i2p/\r\n\r\na=1&b=2", + ) + let _ = pump_read_line(bob_acc2, rs) + let got_req2 = pump_read_until_bytes_contains(bob_acc2, rs, "a=1&b=2") + assert_true(got_req2.has_prefix("POST /form HTTP/1.1\r\n")) + assert_true(got_req2.contains("Referer: http://bobsite.i2p/\r\n")) + assert_true(got_req2.has_suffix("a=1&b=2")) + + bob_acc2.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 7\r\n\r\npost-ok") + bob_acc2.shutdown_write() + let resp2_str = @encoding.utf8_bytes_to_string(pump_read_until_eof(p2, rs)) + assert_true(resp2_str.has_suffix("post-ok")) + + // 3. Clearnet host rejection (403 Forbidden) + let p3 = @ntcp2_net.TcpSocket::connect("127.0.0.1", proxy_port) + defer p3.close() + p3.write_all(b"GET http://example.com/ HTTP/1.1\r\nHost: example.com\r\n\r\n") + let resp3_str = @encoding.utf8_bytes_to_string(pump_read_until_eof(p3, rs)) + assert_true(resp3_str.has_prefix("HTTP/1.1 403 Forbidden\r\n")) + + // 4. CONNECT rejection (501 Not Implemented) + let p4 = @ntcp2_net.TcpSocket::connect("127.0.0.1", proxy_port) + defer p4.close() + p4.write_all( + b"CONNECT example.com:443 HTTP/1.1\r\nHost: example.com:443\r\n\r\n", + ) + let resp4_str = @encoding.utf8_bytes_to_string(pump_read_until_eof(p4, rs)) + assert_true(resp4_str.has_prefix("HTTP/1.1 501 Not Implemented\r\n")) + + // 5. ?i2paddresshelper= jump link registration + 302 redirect + let p5 = @ntcp2_net.TcpSocket::connect("127.0.0.1", proxy_port) + defer p5.close() + let req5 = "GET http://jumpnew.i2p/page?foo=1&i2paddresshelper=\{bob_pub_b64}&bar=2 HTTP/1.1\r\nHost: jumpnew.i2p\r\n\r\n" + p5.write_all(@encoding.string_to_utf8_bytes(req5)) + let resp5_str = @encoding.utf8_bytes_to_string(pump_read_until_eof(p5, rs)) + assert_true(resp5_str.has_prefix("HTTP/1.1 302 Found\r\n")) + assert_true( + resp5_str.contains("Location: http://jumpnew.i2p/page?foo=1&bar=2\r\n"), + ) +} + ///| test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B TunnelData stream" { let router_b = @router.Router::start( diff --git a/router/sam_handler.mbt b/router/sam_handler.mbt index 80f7e62..b9f45bd 100644 --- a/router/sam_handler.mbt +++ b/router/sam_handler.mbt @@ -51,6 +51,10 @@ priv struct RemoteStreamBridge { 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 } ///| @@ -133,6 +137,17 @@ fn extract_x25519_key(ls2 : @common.LeaseSet2) -> Bytes? { } } +///| +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, @@ -156,12 +171,20 @@ fn Router::resolve_name_local( 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) } } - let now_sec = @ntcp2_net.unix_time_sec() match self.netdb.get_lease_set2_by_b32(lower, now_sec) { Some(ls2) => return Some(ls2.destination.to_base64()) None => () @@ -356,6 +379,10 @@ fn Router::initiate_remote_stream( 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, @@ -597,8 +624,12 @@ fn Router::handle_sam_command( "NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}", ) } - None => - match parse_b32_hash(name) { + 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 @@ -620,6 +651,7 @@ fn Router::handle_sam_command( ) } } + } } } ("SESSION", Some("CREATE")) => { @@ -1105,6 +1137,10 @@ fn Router::step_remote_bridges(self : Router) -> Bool { 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( @@ -1122,6 +1158,29 @@ fn Router::step_remote_bridges(self : Router) -> Bool { } } + // 1b. Self-heal stalled SynSent streams by dropping potentially expired ECIES ratchet state + // before the next SYN retransmit so a fresh Bound NewSession + LeaseSet2 is sent + for br in self.remote_bridges { + if br.state == 0 && !br.ratchet_reset && now_ms > br.started_ms + 7000UL { + br.ratchet_reset = true + match self.find_session_by_id(br.session_id) { + Some(sess) => + match sess.ratchet { + Some(r) => { + r.drop_session(br.peer_static_pub) + if self.debug { + println( + "[debug] resetting ECIES ratchet 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 { @@ -1205,7 +1264,19 @@ fn Router::step_remote_bridges(self : Router) -> Bool { "[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}", ) } - if !br.silent { + match sess.ratchet { + Some(r) => r.drop_session(br.peer_static_pub) + None => () + } + let _ = self.netdb.remove_lease_set2(br.peer_hash) + 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) @@ -1227,6 +1298,9 @@ fn Router::step_remote_bridges(self : Router) -> Bool { br.sock.write_all(avail) catch { _ => { br.local_eof = true + if br.closing_since_ms == 0UL { + br.closing_since_ms = now_ms + } let _ = conn.close(now_ms) catch { _ => () } } } @@ -1238,13 +1312,31 @@ fn Router::step_remote_bridges(self : Router) -> Bool { } 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 br.pending_buf.length() > 0 { - did_work = true - let pbytes = Bytes::from_array(br.pending_buf) - let wrote = conn.write(pbytes, now_ms) catch { _ => 0 } - for _w = 0; _w < wrote; _w = _w + 1 { - let _ = br.pending_buf.remove(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 { @@ -1254,6 +1346,9 @@ fn Router::step_remote_bridges(self : Router) -> Bool { 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 } @@ -1272,13 +1367,18 @@ fn Router::step_remote_bridges(self : Router) -> Bool { br.lease_tid, send_ls2=false, ) - if br.local_eof && conn.is_eof() && !conn.has_unacked() { - 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.local_eof && conn.is_eof() { + if br.closing_since_ms == 0UL { + br.closing_since_ms = now_ms + } + if !conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL { + 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