feat: add HTTP-over-I2P proxy to router daemon
check / check (macos-latest) (push) Failing after 27s
check / check (ubuntu-latest) (push) Failing after 28s
check / check (windows-latest) (push) Failing after 26s

- 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
This commit is contained in:
nandi committed 2026-11-28 01:46:36 -08:00
1 parent 54cfb2faa9
commit 14eae00f5c
15 files changed
+1941 -41

No files matched your search

+22 -7
View File
@@ -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 ├── 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/ # 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 ├── 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/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`) ├── 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`) └── 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 moon build --target native cmd/client
# Join the live public I2P network behind NAT (auto-reseeds, connects NTCP2 peers, builds tunnels) # 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: # Optional flags:
# --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels) # --http-proxy [host:port] Enable HTTP-over-I2P proxy (default: 127.0.0.1:4444)
# --hosts <hosts.txt> Load hostname=base64dest entries from a local I2P hosts.txt file # --hops <1..4> Tunnel length (e.g. --hops 2 for 2-hop Inbound & Outbound tunnels)
# --debug Log peer dials, tunnel builds, NetDB lookups, and Garlic/Streaming state # --hosts <hosts.txt> 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=<dest> 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 lookup kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p
./_build/native/debug/build/cmd/client/client.exe http-get kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p / ./_build/native/debug/build/cmd/client/client.exe http-get kqypgjpjwrphnzebod5ev3ts2vtii6e5tntrg4rnfijqc7rypldq.b32.i2p /
``` ```
+109 -1
View File
@@ -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 <host:port> 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 <ip> NTCP2 advertise/bind IP (default: 127.0.0.1)",
)
println(
" --ntcp2-port <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 <hosts.txt> Load hostname=dest_or_b32 aliases into addressbook",
)
println(" --peer <ri.dat> Load a RouterInfo file into NetDB")
println(
" --peer-dir <dir> Load RouterInfo files from directory into NetDB",
)
println(
" --su3 <i2pseeds.su3> Import peers from local .su3 reseed file",
)
println(
" --reseed <https://...> 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 { fn main {
let args = @env.args() let args = @env.args()
let mut sam_host = "127.0.0.1" let mut sam_host = "127.0.0.1"
let mut sam_port = 7656 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_host = "127.0.0.1"
let mut ntcp2_port = 0 let mut ntcp2_port = 0
let mut floodfill = false let mut floodfill = false
@@ -58,6 +107,10 @@ fn main {
let mut i = 1 let mut i = 1
while i < args.length() { while i < args.length() {
match args[i] { match args[i] {
"-h" | "--help" => {
print_usage()
return
}
"--sam" => "--sam" =>
if i + 1 < args.length() { if i + 1 < args.length() {
match split_host_port(args[i + 1]) { match split_host_port(args[i + 1]) {
@@ -71,6 +124,28 @@ fn main {
} else { } else {
i += 1 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" => "--ntcp2-port" =>
if i + 1 < args.length() { if i + 1 < args.length() {
match parse_port(args[i + 1]) { match parse_port(args[i + 1]) {
@@ -149,7 +224,26 @@ fn main {
check_clock_skew = false check_clock_skew = false
i += 1 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 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 { for pf in peer_files {
let _ = r.load_peer_file(pf) catch { 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})", " NTCP2: \{ntcp2_host}:\{r.ntcp2_port()} (public=\{public_mode}, hops=\{tunnel_hops})",
) )
println(" SAMv3: \{sam_host}:\{r.sam_port()}") println(" SAMv3: \{sam_host}:\{r.sam_port()}")
if http_proxy_enabled {
println(" HTTP Proxy: \{http_proxy_host}:\{r.http_proxy_port()}")
}
println( println(
" NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})", " NetDB peers: \{r.netdb.router_count()} (floodfills=\{r.netdb.floodfill_count()})",
) )
+5
View File
@@ -11,6 +11,11 @@ build:
moon build --target native cmd/router moon build --target native cmd/router
moon build --target native cmd/client 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 # Run all MoonBit tests across wasm, js, and native targets
test: test:
moon test --target wasm moon test --target wasm
+16
View File
@@ -236,6 +236,22 @@ pub fn NetDb::get_lease_set2_by_b32(
None 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. /// Removes expired `LeaseSet2` entries and returns the number pruned.
pub fn NetDb::prune_expired(self : NetDb, now_sec : UInt32) -> Int32 { pub fn NetDb::prune_expired(self : NetDb, now_sec : UInt32) -> Int32 {
+1
View File
@@ -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::leaseset_count(Self) -> Int32
pub fn NetDb::new() -> Self pub fn NetDb::new() -> Self
pub fn NetDb::prune_expired(Self, UInt32) -> Int32 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::router_count(Self) -> Int32
pub fn NetDb::store_lease_set2(Self, @common.LeaseSet2, UInt32) -> Bool raise NetDbError 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 pub fn NetDb::store_router_info(Self, @common.RouterInfo) -> Bool raise NetDbError
+42 -1
View File
@@ -295,6 +295,7 @@ pub struct RatchetPeerSession {
mut local_next_priv : Bytes? mut local_next_priv : Bytes?
mut local_next_pub : Bytes? mut local_next_pub : Bytes?
mut remote_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_priv: None,
local_next_pub: None, local_next_pub: None,
remote_next_pub: None, remote_next_pub: None,
last_used_sec: 0U,
} }
sess.refill_recv_window() sess.refill_recv_window()
(w.to_bytes(), sess) (w.to_bytes(), sess)
@@ -505,6 +507,7 @@ pub fn decrypt_new_session_reply(
local_next_priv: None, local_next_priv: None,
local_next_pub: None, local_next_pub: None,
remote_next_pub: None, remote_next_pub: None,
last_used_sec: 0U,
} }
sess.refill_recv_window() sess.refill_recv_window()
(blocks, sess) (blocks, sess)
@@ -642,6 +645,34 @@ fn RatchetSessionManager::find_session(
-1 -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`, /// Initiates a DH ratchet step (`NextKey` block type 7) for `remote_static_pub`,
/// returning `Some(NextKey(...))` if a session is established. /// returning `Some(NextKey(...))` if a session is established.
@@ -715,7 +746,13 @@ pub fn RatchetSessionManager::encrypt_to_peer(
) -> Bytes raise RatchetError { ) -> Bytes raise RatchetError {
let sidx = self.find_session(remote_static_pub) let sidx = self.find_session(remote_static_pub)
if sidx >= 0 { 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 // Check if we owe this peer an NSR
for i = 0; i < self.inbound_pending.length(); i = i + 1 { 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 _ = self.inbound_pending.remove(i)
let ephem_b = generate_elligator_keypair(next_rand_32) let ephem_b = generate_elligator_keypair(next_rand_32)
let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks) let (wire, sess) = encrypt_new_session_reply(p, ephem_b, blocks)
sess.last_used_sec = now_sec
self.sessions.push(sess) self.sessions.push(sess)
return wire return wire
} }
@@ -754,6 +792,9 @@ pub fn RatchetSessionManager::encrypt_to_peer(
// Pre-register first 4 NSR tags so any reply matches // Pre-register first 4 NSR tags so any reply matches
for _k = 0; _k < 4; _k = _k + 1 { for _k = 0; _k < 4; _k = _k + 1 {
let (_n, tag, _k32) = p.nsr_tagset.next_entry() 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)) self.outbound_pending.push((tag, p))
} }
None => () None => ()
+2
View File
@@ -108,6 +108,7 @@ pub struct RatchetPeerSession {
mut local_next_priv : Bytes? mut local_next_priv : Bytes?
mut local_next_pub : Bytes? mut local_next_pub : Bytes?
mut remote_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::apply_dh_ratchet(Self, Bytes, Bytes, for_send~ : Bool) -> Unit raise RatchetError
pub fn RatchetPeerSession::encrypt_existing(Self, Array[RatchetBlock]) -> Bytes 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::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::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::encrypt_to_peer(Self, Bytes, Array[RatchetBlock], UInt32, () -> Bytes) -> Bytes raise RatchetError
pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self pub fn RatchetSessionManager::new(@noise.KeyPair) -> Self
+108
View File
@@ -190,3 +190,111 @@ test "Proposal 144 ECIES-X25519-AEAD-Ratchet NS -> NSR -> bidirectional ES + DH
} }
assert_eq(wrong_failed, true) 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)
}
File diff suppressed because it is too large. Load diff
+102
View File
@@ -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}")
}
}
+19 -7
View File
@@ -12,7 +12,7 @@ priv struct PendingNetDbLookup {
candidate_peers : Array[@common.Hash] candidate_peers : Array[@common.Hash]
started_ms : UInt64 started_ms : UInt64
mut last_query_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 client_idx : Int32
req_name : String req_name : String
session_id : String session_id : String
@@ -427,6 +427,17 @@ fn Router::start_netdb_lookup(
true 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( fn Router::handle_database_store_msg(
self : Router, self : Router,
@@ -690,7 +701,7 @@ fn Router::complete_lookups_for_hash(
let lk = self.pending_lookups[i] let lk = self.pending_lookups[i]
if lk.target_hash == key { if lk.target_hash == key {
let _ = self.pending_lookups.remove(i) 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] let c = self.sam_clients[lk.client_idx]
if !c.closed { if !c.closed {
if lk.kind == 0 { if lk.kind == 0 {
@@ -699,7 +710,7 @@ fn Router::complete_lookups_for_hash(
c.sock, c.sock,
"NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}", "NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{val}",
) )
} else { } else if lk.kind == 1 {
self.finish_remote_stream_connect(lk, ls2) 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) { match self.netdb.get_lease_set2(lk.target_hash, now_sec) {
Some(ls2) => { Some(ls2) => {
let _ = self.pending_lookups.remove(i) 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 { !self.sam_clients[lk.client_idx].closed {
if lk.kind == 0 { if lk.kind == 0 {
let _ = send_sam_line( let _ = send_sam_line(
self.sam_clients[lk.client_idx].sock, self.sam_clients[lk.client_idx].sock,
"NAMING REPLY RESULT=OK NAME=\{lk.req_name} VALUE=\{ls2.destination.to_base64()}", "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) 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 { if now_ms > lk.started_ms + timeout_ms {
let _ = self.pending_lookups.remove(i) 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] let c = self.sam_clients[lk.client_idx]
if !c.closed { if !c.closed {
if lk.kind == 0 { if lk.kind == 0 {
@@ -786,7 +798,7 @@ fn Router::poll_netdb_lookups(self : Router) -> Unit {
c.sock, c.sock,
"NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}", "NAMING REPLY RESULT=KEY_NOT_FOUND NAME=\{lk.req_name}",
) )
} else { } else if lk.kind == 1 {
if !lk.silent { if !lk.silent {
let _ = send_sam_line( let _ = send_sam_line(
c.sock, c.sock,
+114 -2
View File
@@ -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( pub fn Router::load_hosts_file(
self : Router, self : Router,
path : String, path : String,
@@ -56,7 +86,8 @@ pub fn Router::load_hosts_file(
if eq > 0 && eq + 1 < line.length() { if eq > 0 && eq + 1 < line.length() {
let host = line[:eq].to_owned().trim().to_owned() let host = line[:eq].to_owned().trim().to_owned()
let dest_b64 = line[eq + 1:].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) self.register_alias(host, dest_b64)
count += 1 count += 1
} }
@@ -174,6 +205,16 @@ fn Router::pick_connected_hop(
None 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 { fn Router::step_public_bootstrap(self : Router) -> Unit {
let now_ms = @ntcp2_net.unix_time_ms() 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 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 // 1. Keep up to 6 live outbound NTCP2 TCP peer sessions active
let target_peers = 6 let target_peers = 6
if self.peers.length() + self.pending_dials.length() < target_peers { if self.peers.length() + self.pending_dials.length() < target_peers {
+62 -7
View File
@@ -66,7 +66,11 @@ pub struct Router {
priv bridges : Array[StreamBridge] priv bridges : Array[StreamBridge]
priv remote_bridges : Array[RemoteStreamBridge] priv remote_bridges : Array[RemoteStreamBridge]
priv aliases : Array[(String, String)] // hostname -> pub_b64 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 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 lease_rr : Int32
priv mut outbound_rr : Int32 priv mut outbound_rr : Int32
priv mut last_bootstrap_ms : UInt64 priv mut last_bootstrap_ms : UInt64
@@ -225,7 +229,7 @@ pub fn Router::start(
} else { } else {
tunnel_hops tunnel_hops
} }
{ let r : Router = {
ed_seed, ed_seed,
static_key, static_key,
ntcp2_iv, ntcp2_iv,
@@ -254,12 +258,20 @@ pub fn Router::start(
bridges: [], bridges: [],
remote_bridges: [], remote_bridges: [],
aliases: [], aliases: [],
b32_aliases: [],
failed_peers: [], failed_peers: [],
http_proxy_listener: None,
http_proxy_conns: [],
http_proxy_session_id: None,
lease_rr: 0, lease_rr: 0,
outbound_rr: 0, outbound_rr: 0,
last_bootstrap_ms: 0UL, last_bootstrap_ms: 0UL,
last_explore_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() 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( pub fn Router::register_alias(
self : Router, self : Router,
@@ -304,13 +343,13 @@ pub fn Router::register_alias(
dest_pub_b64 : String, dest_pub_b64 : String,
) -> Unit { ) -> Unit {
let key = hostname.to_lower() let key = hostname.to_lower()
for i = 0; i < self.aliases.length(); i = i + 1 { if parse_b32_hash(dest_pub_b64) is Some(_) {
if self.aliases[i].0 == key { remove_alias_entry(self.aliases, key)
self.aliases[i] = (key, dest_pub_b64) upsert_alias_entry(self.b32_aliases, key, dest_pub_b64.to_lower())
return } 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 { 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 { for c in self.sam_clients {
if !c.closed { if !c.closed {
c.sock.close() c.sock.close()
@@ -509,6 +561,9 @@ pub fn Router::step(self : Router, poll_ms~ : Int32 = 10) -> Unit {
if self.step_sam_clients() { if self.step_sam_clients() {
did_work = true did_work = true
} }
if self.step_http_proxy() {
did_work = true
}
self.poll_netdb_lookups() self.poll_netdb_lookups()
self.poll_tunnel_builds() self.poll_tunnel_builds()
if self.public_mode { if self.public_mode {
+148
View File
@@ -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") 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" { test "Three-router live Proposal 157 multi-hop tunnel build and fragmented 2500B TunnelData stream" {
let router_b = @router.Router::start( let router_b = @router.Router::start(
+116 -16
View File
@@ -51,6 +51,10 @@ priv struct RemoteStreamBridge {
mut closed : Bool mut closed : Bool
started_ms : UInt64 started_ms : UInt64
pending_buf : Array[Byte] 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( fn Router::resolve_name_local(
self : Router, self : Router,
@@ -156,12 +171,20 @@ fn Router::resolve_name_local(
return Some(entry.1) 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 { for s in self.sessions {
if s.b32 == lower { if s.b32 == lower {
return Some(s.pub_b64) return Some(s.pub_b64)
} }
} }
let now_sec = @ntcp2_net.unix_time_sec()
match self.netdb.get_lease_set2_by_b32(lower, now_sec) { match self.netdb.get_lease_set2_by_b32(lower, now_sec) {
Some(ls2) => return Some(ls2.destination.to_base64()) Some(ls2) => return Some(ls2.destination.to_base64())
None => () None => ()
@@ -356,6 +379,10 @@ fn Router::initiate_remote_stream(
closed: false, closed: false,
started_ms: now_ms, started_ms: now_ms,
pending_buf, pending_buf,
is_http_proxy: false,
http_host: "",
closing_since_ms: 0UL,
ratchet_reset: false,
}) })
self.flush_stream_outbound( self.flush_stream_outbound(
caller_sess, caller_sess,
@@ -597,8 +624,12 @@ fn Router::handle_sam_command(
"NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}", "NAMING REPLY RESULT=OK NAME=\{name} VALUE=\{val}",
) )
} }
None => None => {
match parse_b32_hash(name) { let target_opt = match parse_b32_hash(name) {
Some(h) => Some(h)
None => self.resolve_b32_alias(name)
}
match target_opt {
Some(target_hash) => { Some(target_hash) => {
let sid = match client.session_id { let sid = match client.session_id {
Some(s) => s Some(s) => s
@@ -620,6 +651,7 @@ fn Router::handle_sam_command(
) )
} }
} }
}
} }
} }
("SESSION", Some("CREATE")) => { ("SESSION", Some("CREATE")) => {
@@ -1105,6 +1137,10 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
closed: false, closed: false,
started_ms: now_ms, started_ms: now_ms,
pending_buf, pending_buf,
is_http_proxy: false,
http_host: "",
closing_since_ms: 0UL,
ratchet_reset: false,
}) })
did_work = true did_work = true
self.flush_stream_outbound( 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) // 2. Pump retransmits & flush outbound packets (ACKs, SYN-ACKs, retransmissions)
let rto_ms = if self.public_mode { 3500UL } else { 1500UL } let rto_ms = if self.public_mode { 3500UL } else { 1500UL }
for sess in self.sessions { 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()}", "[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") let _ = send_sam_line(br.sock, "STREAM STATUS RESULT=CANT_REACH_PEER")
} }
remove_stream_by_id(mgr, br.local_stream_id) 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.sock.write_all(avail) catch {
_ => { _ => {
br.local_eof = true br.local_eof = true
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
let _ = conn.close(now_ms) catch { _ => () } let _ = conn.close(now_ms) catch { _ => () }
} }
} }
@@ -1238,13 +1312,31 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
} }
br.sock.shutdown_write() br.sock.shutdown_write()
br.remote_eof_sent = true 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 { if br.pending_buf.length() > 0 {
did_work = true if conn.state != Established && conn.state != SynSent {
let pbytes = Bytes::from_array(br.pending_buf) br.pending_buf.clear()
let wrote = conn.write(pbytes, now_ms) catch { _ => 0 } } else {
for _w = 0; _w < wrote; _w = _w + 1 { did_work = true
let _ = br.pending_buf.remove(0) 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 { 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"" } let chunk = br.sock.read_some(4096) catch { _ => b"" }
if chunk.length() == 0 { if chunk.length() == 0 {
br.local_eof = true br.local_eof = true
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
let _ = conn.close(now_ms) catch { _ => () } let _ = conn.close(now_ms) catch { _ => () }
} else { } else {
let wrote = conn.write(chunk, now_ms) catch { _ => 0 } let wrote = conn.write(chunk, now_ms) catch { _ => 0 }
@@ -1272,13 +1367,18 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
br.lease_tid, br.lease_tid,
send_ls2=false, send_ls2=false,
) )
if br.local_eof && conn.is_eof() && !conn.has_unacked() { if br.local_eof && conn.is_eof() {
did_work = true if br.closing_since_ms == 0UL {
remove_stream_by_id(mgr, br.local_stream_id) br.closing_since_ms = now_ms
br.sock.close() }
br.closed = true if !conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL {
let _ = self.remote_bridges.remove(ri) did_work = true
continue remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
} }
} }
ri += 1 ri += 1