feat: add non-blocking NTCP2 sends and Firefox settings sync
check / check (macos-latest) (push) Failing after 26s
check / check (ubuntu-latest) (push) Failing after 27s
check / check (windows-latest) (push) Failing after 30s

- NTCP2: queue outbound data frames and flush them without blocking (send_blocks_nb, send_i2np_nb, flush_nonblocking)
- NTCP2: bound write_all with a deadline and set TCP keepalive and user timeout on peer sockets
- Firefox extension 0.1.3: save settings as a patch, keep unsaved form fields from being overwritten on refresh, add timeouts to router API calls, and honor the interceptTorrents toggle in the content script
This commit is contained in:
nandi committed 2026-11-28 18:39:32 -08:00
1 parent 82aaa9f11e
commit 9aa15f9ae8
18 files changed
+1323 -239

No files matched your search

+5 -3
View File
@@ -463,10 +463,10 @@ fn send_http_proxy_error(
let body = "<!doctype html><html><head><meta charset=\"utf-8\">\{refresh_meta}<title>\{status} \{safe_reason}</title></head><body><h1>\{status} \{safe_reason}</h1><p>\{safe_detail}</p><hr><small>moon-i2p HTTP Proxy</small></body></html>\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\n\{refresh_hdr}Connection: close\r\n\r\n"
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr)) catch {
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr), timeout_ms=500) catch {
_ => return
}
let _ = sock.write_all(body_bytes) catch { _ => () }
let _ = sock.write_all(body_bytes, timeout_ms=500) catch { _ => () }
}
///|
@@ -475,7 +475,9 @@ fn send_http_proxy_redirect(
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 { _ => () }
let _ = sock.write_all(@encoding.string_to_utf8_bytes(hdr), timeout_ms=500) catch {
_ => ()
}
}
///|
+39 -16
View File
@@ -166,7 +166,7 @@ fn Router::send_i2np_to_peer(
while idx >= 0 {
if self.peers[idx].hash == target_hash {
let ok = try {
self.peers[idx].conn.send_i2np(mid, exp_sec, payload)
self.peers[idx].conn.send_i2np_nb(mid, exp_sec, payload)
true
} catch {
_ => false
@@ -177,6 +177,9 @@ fn Router::send_i2np_to_peer(
}
self.peers[idx].conn.close()
let _ = self.peers.remove(idx)
if self.public_mode {
self.mark_peer_failed(target_hash, 60000UL)
}
}
idx -= 1
}
@@ -246,7 +249,7 @@ fn Router::flush_pending_sends_for(
let ps = self.pending_sends[i]
if ps.target_hash == target_hash {
let ok = try {
peer.conn.send_i2np(ps.msg_id, ps.expiration_sec, ps.payload)
peer.conn.send_i2np_nb(ps.msg_id, ps.expiration_sec, ps.payload)
true
} catch {
_ => false
@@ -456,33 +459,53 @@ fn Router::step_ntcp2_peers(self : Router) -> Bool {
)
}
// 5. Non-blocking read & dispatch on all active NTCP2 peer sessions
// 5. Flush non-blocking outbound frames & read incoming frames on all active NTCP2 peers
let mut pi = 0
while pi < self.peers.length() {
let peer = self.peers[pi]
let mut alive = true
for _frame = 0; _frame < 32; _frame = _frame + 1 {
let recv_opt = peer.conn.try_recv_blocks() catch {
_ => {
alive = false
None
}
let flushed = peer.conn.flush_nonblocking() catch {
_ => {
alive = false
false
}
match recv_opt {
Some(blocks) => {
did_work = true
peer.last_active_ms = now_ms
if self.handle_peer_blocks(peer.hash, blocks) {
}
if flushed {
did_work = true
peer.last_active_ms = now_ms
}
if alive {
for _frame = 0; _frame < 32; _frame = _frame + 1 {
let recv_opt = peer.conn.try_recv_blocks() catch {
_ => {
alive = false
break
None
}
}
None => break
match recv_opt {
Some(blocks) => {
did_work = true
peer.last_active_ms = now_ms
if self.handle_peer_blocks(peer.hash, blocks) {
alive = false
break
}
}
None => break
}
}
}
if !alive || now_ms > peer.last_active_ms + 180000UL {
peer.conn.close()
let _ = self.peers.remove(pi)
if self.public_mode && !alive {
self.mark_peer_failed(peer.hash, 60000UL)
if self.debug {
println(
"[debug] NTCP2 peer closed/stalled: \{peer.hash.to_b32_address()}",
)
}
}
} else {
pi += 1
}
+4 -1
View File
@@ -247,7 +247,7 @@ fn Router::step_public_bootstrap(self : Router) -> Unit {
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")])
p.conn.send_blocks_nb([@ntcp2.Ntcp2Block::Padding(b"\x00\x00\x00\x00")])
true
} catch {
_ => false
@@ -258,6 +258,9 @@ fn Router::step_public_bootstrap(self : Router) -> Unit {
} else {
p.conn.close()
let _ = self.peers.remove(pi)
if self.public_mode {
self.mark_peer_failed(p.hash, 60000UL)
}
}
} else {
pi += 1
+2
View File
@@ -68,6 +68,7 @@ pub struct Router {
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 ratchet_resets : Array[(@common.Hash, UInt64)] // (peer_hash, last_reset_ms)
priv mut http_proxy_listener : @ntcp2_net.TcpListener?
priv http_proxy_conns : Array[HttpProxyConn]
priv mut http_proxy_session_id : String?
@@ -263,6 +264,7 @@ pub fn Router::start(
aliases: [],
b32_aliases: [],
failed_peers: [],
ratchet_resets: [],
http_proxy_listener: None,
http_proxy_conns: [],
http_proxy_session_id: None,
+131
View File
@@ -721,3 +721,134 @@ test "2-router I2P DHT + BEP 9 Magnet + Streaming torrent download and HTTP API
)
assert_true(nodes_json.contains(router_a.torrent_b32_address()))
}
///|
test "POST /api/torrents/add accepts standard, URL-safe, and rejects invalid Base64" {
let dl_dir = "/tmp/moon_i2p_bt_b64_test"
@ntcp2_net.mkdir_p(dl_dir)
let r = @router.Router::start({
sam_host: "127.0.0.1",
sam_port: 0,
ntcp2_host: "127.0.0.1",
ntcp2_port: 0,
})
defer r.close()
let api_port = r.start_torrent_api(
host="127.0.0.1",
port=0,
download_dir=dl_dir,
)
let rs = [r]
let make_b64 = fn(tbytes : Bytes, to_std : Bool, strip_pad : Bool) -> String {
let i2p_b64 = @encoding.base64_encode(tbytes)
let sb = StringBuilder()
for ch in i2p_b64 {
if strip_pad && ch == '=' {
continue
}
if to_std {
match ch {
'-' => sb.write_char('+')
'~' => sb.write_char('/')
_ => sb.write_char(ch)
}
} else {
match ch {
'~' => sb.write_char('_')
_ => sb.write_char(ch)
}
}
}
sb.to_string()
}
let t1 = @bittorrent.bencode_encode(
BDict([
(b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")),
(
b"info",
BDict([
(b"length", BInt(16L)),
(b"name", BBytes(b"std-b64.bin")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(Bytes::make(20, b'\xfb'))),
]),
),
]),
)
let ih1 = @encoding.hex_encode(@bittorrent.parse_torrent(t1).info_hash)
let std_b64 = make_b64(t1, true, false)
assert_true(std_b64.contains("+"))
assert_true(std_b64.contains("/"))
let resp1 = test_http_api_request(
api_port,
rs,
"POST",
"/api/torrents/add",
"127.0.0.1:\{api_port}",
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
"{\"torrent_b64\":\"\{std_b64}\"}",
)
assert_true(resp1.contains("200 OK"))
assert_true(resp1.contains(ih1))
// Unpadded URL-safe Base64 (ensure length % 3 != 0 so stripping '=' exercises padding recovery)
let mut t2 = @bittorrent.bencode_encode(
BDict([
(b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")),
(
b"info",
BDict([
(b"length", BInt(16L)),
(b"name", BBytes(b"url-b64-a.bin")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(Bytes::make(20, b'\xff'))),
]),
),
]),
)
if t2.length() % 3 == 0 {
t2 = @bittorrent.bencode_encode(
BDict([
(b"comment", BBytes(b"\xfb\xff\xbf\xfb\xff")),
(
b"info",
BDict([
(b"length", BInt(16L)),
(b"name", BBytes(b"url-b64-ab.bin")),
(b"piece length", BInt(16384L)),
(b"pieces", BBytes(Bytes::make(20, b'\xff'))),
]),
),
]),
)
}
let ih2 = @encoding.hex_encode(@bittorrent.parse_torrent(t2).info_hash)
let url_b64 = make_b64(t2, false, true)
assert_true(url_b64.contains("-") && url_b64.contains("_"))
assert_true(!url_b64.contains("="))
let resp2 = test_http_api_request(
api_port,
rs,
"POST",
"/api/torrents/add",
"127.0.0.1:\{api_port}",
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
"{\"torrent_b64\":\"\{url_b64}\"}",
)
assert_true(resp2.contains("200 OK"))
assert_true(resp2.contains(ih2))
let bad_resp = test_http_api_request(
api_port,
rs,
"POST",
"/api/torrents/add",
"127.0.0.1:\{api_port}",
[("Content-Type", "application/json"), ("X-Moon-I2P", "1")],
"{\"torrent_b64\":\"not*valid*b64!\"}",
)
assert_true(bad_resp.contains("400 Bad Request"))
assert_true(bad_resp.contains("invalid torrent_b64"))
}
+90 -18
View File
@@ -192,9 +192,51 @@ fn Router::resolve_name_local(
None
}
///|
fn Router::has_active_bridge_to(
self : Router,
peer_hash : @common.Hash,
) -> Bool {
for br in self.remote_bridges {
if !br.closed && br.peer_hash == peer_hash && br.state == 1 && !br.local_eof {
return true
}
}
false
}
///|
fn Router::try_acquire_ratchet_reset(
self : Router,
peer_hash : @common.Hash,
now_ms : UInt64,
cooldown_ms : UInt64,
) -> Bool {
let mut i = 0
let mut recent = false
while i < self.ratchet_resets.length() {
if now_ms > self.ratchet_resets[i].1 + cooldown_ms {
let _ = self.ratchet_resets.remove(i)
} else {
if self.ratchet_resets[i].0 == peer_hash {
recent = true
}
i += 1
}
}
if recent {
return false
}
if self.ratchet_resets.length() >= 256 {
let _ = self.ratchet_resets.remove(0)
}
self.ratchet_resets.push((peer_hash, now_ms))
true
}
///|
fn send_sam_line(sock : @ntcp2_net.TcpSocket, line : String) -> Bool {
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n")) catch {
sock.write_all(@encoding.string_to_utf8_bytes(line + "\n"), timeout_ms=500) catch {
_ => return false
}
true
@@ -243,9 +285,11 @@ fn Router::flush_stream_outbound(
_ => ()
}
let exp_sec = now_sec + 60U
let effective_send_ls2 = send_ls2 ||
!ratchet.has_active_session(peer_static_pub, now_sec~)
for idx = 0; idx < packets.length(); idx = idx + 1 {
let blocks : Array[@ratchet.RatchetBlock] = []
if send_ls2 && idx == 0 {
if effective_send_ls2 && idx == 0 {
match self.build_session_leaseset2(sess, now_sec) {
Some(ls2) => {
let ls_bytes = ls2.to_bytes() catch { _ => b"" }
@@ -287,7 +331,7 @@ fn Router::flush_stream_outbound(
}
if self.debug {
println(
"[debug] send Garlic (\{wire.length()}B, ls2=\{send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}",
"[debug] send Garlic (\{wire.length()}B, ls2=\{effective_send_ls2}) -> gw=\{gw.to_b32_address()} tid=\{tid}",
)
}
self.send_routed_i2np(gw, Some(tid), Garlic(data=wire))
@@ -436,7 +480,9 @@ fn Router::handle_incoming_garlic(
Some(r) => r
None => continue
}
let res = Some(ratchet.decrypt_incoming(garlic_data)) catch { _ => None }
let res = Some(ratchet.decrypt_incoming(garlic_data, now_sec~)) catch {
_ => None
}
match res {
Some((_remote_static, blocks)) => {
if self.debug {
@@ -1158,20 +1204,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
// 1b. Self-heal stalled SynSent streams by marking outbound ECIES send state stale
// so a fresh Bound NewSession + LeaseSet2 is sent without dropping active recv windows
for br in self.remote_bridges {
if br.state == 0 && !br.ratchet_reset && now_ms > br.started_ms + 7000UL {
br.ratchet_reset = true
if self.has_active_bridge_to(br.peer_hash) {
continue
}
match self.find_session_by_id(br.session_id) {
Some(sess) =>
match sess.ratchet {
Some(r) => {
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()}",
)
let lrx = r.last_recv_sec(br.peer_static_pub)
let recent_rx = lrx != 0U && now_sec <= lrx + 8U
if r.has_active_session(br.peer_static_pub, now_sec~) &&
!recent_rx &&
self.try_acquire_ratchet_reset(br.peer_hash, now_ms, 12000UL) {
r.mark_send_stale(br.peer_static_pub)
if self.debug {
println(
"[debug] marking ECIES ratchet send-stale for stalled SYN to \{br.peer_hash.to_b32_address()}",
)
}
}
}
None => ()
@@ -1264,11 +1319,18 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
"[debug] Streaming failed/timed out to \{br.peer_hash.to_b32_address()}",
)
}
match sess.ratchet {
Some(r) => r.drop_session(br.peer_static_pub)
None => ()
if !self.has_active_bridge_to(br.peer_hash) {
match sess.ratchet {
Some(r) => {
let lrx = r.last_recv_sec(br.peer_static_pub)
if lrx == 0U || now_sec > lrx + 15U {
r.mark_send_stale(br.peer_static_pub)
let _ = self.netdb.remove_lease_set2(br.peer_hash)
}
}
None => ()
}
}
let _ = self.netdb.remove_lease_set2(br.peer_hash)
if br.is_http_proxy {
send_http_proxy_error(
br.sock,
@@ -1295,7 +1357,7 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
"[debug] stream \{br.local_stream_id} recv \{avail.length()}B",
)
}
br.sock.write_all(avail) catch {
br.sock.write_all(avail, timeout_ms=500) catch {
_ => {
br.local_eof = true
if br.closing_since_ms == 0UL {
@@ -1318,6 +1380,14 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
let _ = conn.close(now_ms) catch { _ => () }
}
}
if conn.state == Reset {
did_work = true
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
br.closed = true
let _ = self.remote_bridges.remove(ri)
continue
}
if br.pending_buf.length() > 0 {
if conn.state != Established && conn.state != SynSent {
br.pending_buf.clear()
@@ -1367,11 +1437,13 @@ fn Router::step_remote_bridges(self : Router) -> Bool {
br.lease_tid,
send_ls2=false,
)
if br.local_eof && conn.is_eof() {
if br.local_eof {
if br.closing_since_ms == 0UL {
br.closing_since_ms = now_ms
}
if !conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL {
let done_gracefully = conn.is_eof() &&
(!conn.has_unacked() || now_ms > br.closing_since_ms + 3000UL)
if done_gracefully || now_ms > br.closing_since_ms + 5000UL {
did_work = true
remove_stream_by_id(mgr, br.local_stream_id)
br.sock.close()
+35 -3
View File
@@ -248,12 +248,44 @@ fn api_send_response(
}
sb.write_string("Connection: close\r\n\r\n")
let hdr_bytes = @encoding.string_to_utf8_bytes(sb.to_string())
let _ = sock.write_all(hdr_bytes) catch { _ => () }
let _ = sock.write_all(hdr_bytes, timeout_ms=500) catch { _ => () }
if body_bytes.length() > 0 {
let _ = sock.write_all(body_bytes) catch { _ => () }
let _ = sock.write_all(body_bytes, timeout_ms=500) catch { _ => () }
}
}
///|
/// Decodes standard (`+`/`/`), URL-safe (`-`/`_`), or I2P (`-`/`~`) Base64 strings,
/// restoring omitted trailing `=` padding when needed.
fn api_decode_base64_flexible(
b64 : String,
) -> Bytes raise @encoding.EncodingError {
let sb = StringBuilder()
let mut len = 0
for ch in b64 {
if ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' {
continue
}
let mapped = match ch {
'+' => '-'
'/' => '~'
'_' => '~'
_ => ch
}
sb.write_char(mapped)
len += 1
}
if len > 0 {
let rem = len % 4
if rem == 2 {
sb.write_string("==")
} else if rem == 3 {
sb.write_char('=')
}
}
@encoding.base64_decode(sb.to_string())
}
///|
fn api_router_err_msg(e : RouterError) -> String {
match e {
@@ -641,7 +673,7 @@ fn Router::dispatch_torrent_api_request(
(body.length() > 0 && body[0] == b'{') {
match api_json_get_string(body_str, "torrent_b64") {
Some(b64) =>
@encoding.base64_decode(b64) catch {
api_decode_base64_flexible(b64) catch {
_ => {
api_send_response(
ac.sock,