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

+26 -1
View File
@@ -10,6 +10,7 @@
#include <fcntl.h>
#include <netdb.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <signal.h>
#include <stdint.h>
@@ -30,6 +31,10 @@
#define MSG_NOSIGNAL 0
#endif
#ifndef MSG_DONTWAIT
#define MSG_DONTWAIT 0
#endif
static char g_net_last_error[256] = {0};
static void net_set_error(const char *msg) {
@@ -329,7 +334,7 @@ int32_t moon_i2p_net_tcp_send(
moonbit_bytes_t data,
int32_t offset,
int32_t len) {
ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL);
ssize_t n = send((int)fd, data + offset, (size_t)len, MSG_NOSIGNAL | MSG_DONTWAIT);
if (n < 0) {
if (errno == EAGAIN || errno == EWOULDBLOCK) {
return -2;
@@ -340,6 +345,26 @@ int32_t moon_i2p_net_tcp_send(
return (int32_t)n;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_set_peer_timeouts(int32_t fd, int32_t user_timeout_ms) {
(void)user_timeout_ms;
int keepalive = 1;
if (setsockopt((int)fd, SOL_SOCKET, SO_KEEPALIVE, &keepalive, sizeof(keepalive)) < 0) {
net_set_error(strerror(errno));
return -1;
}
#ifdef TCP_USER_TIMEOUT
if (user_timeout_ms > 0) {
unsigned int uto = (unsigned int)user_timeout_ms;
if (setsockopt((int)fd, IPPROTO_TCP, TCP_USER_TIMEOUT, &uto, sizeof(uto)) < 0) {
net_set_error(strerror(errno));
return -1;
}
}
#endif
return 0;
}
MOONBIT_FFI_EXPORT
int32_t moon_i2p_net_tcp_poll_writable(int32_t fd, int32_t timeout_ms) {
struct pollfd pfd;
+139
View File
@@ -55,3 +55,142 @@ test "extract_ntcp2_peer from signed RouterInfo" {
assert_eq(peer.iv, iv)
assert_eq(peer.router_hash, ri_id.hash().as_bytes())
}
///|
test "TcpSocket::write_all times out instead of blocking on a full unread socket" {
let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0)
let client = @ntcp2_net.TcpSocket::connect("127.0.0.1", listener.local_port())
let server = match listener.accept(timeout_ms=2000) {
Some(s) => s
None => fail("expected accepted TCP socket")
}
let chunk = Bytes::make(65536, b'\xab')
let mut got_timeout = false
for _i = 0; _i < 512; _i = _i + 1 {
let timed_out = try {
client.write_all(chunk, timeout_ms=100)
false
} catch {
Timeout => true
_ => false
}
if timed_out {
got_timeout = true
break
}
}
assert_true(got_timeout)
client.close()
server.close()
listener.close()
}
///|
test "PendingNtcp2Dial/Accept stay non-blocking and Ntcp2Conn::send_blocks_nb transfers frames" {
let alice_ed_seed = @ntcp2_net.random_bytes(32)
let alice_ed_pub = @crypto.ed25519_public_key(alice_ed_seed)
let alice_x_priv = @ntcp2_net.random_bytes(32)
let alice_static = @noise.KeyPair::from_private(alice_x_priv)
let alice_iv = @ntcp2_net.random_bytes(16)
let alice_id = @common.RouterIdentity::new_x25519_ed25519(
alice_static.public_key,
alice_ed_pub,
)
let bob_ed_seed = @ntcp2_net.random_bytes(32)
let bob_ed_pub = @crypto.ed25519_public_key(bob_ed_seed)
let bob_x_priv = @ntcp2_net.random_bytes(32)
let bob_static = @noise.KeyPair::from_private(bob_x_priv)
let bob_iv = @ntcp2_net.random_bytes(16)
let bob_id = @common.RouterIdentity::new_x25519_ed25519(
bob_static.public_key,
bob_ed_pub,
)
let listener = @ntcp2_net.TcpListener::bind("127.0.0.1", 0)
let listen_port = listener.local_port()
let alice_ri : @common.RouterInfo = {
identity: alice_id,
published: @ntcp2_net.unix_time_ms(),
addresses: [
@common.RouterAddress::new(
b'\x03',
"NTCP2",
@common.Mapping::from_entries([
("host", "127.0.0.1"),
("i", @encoding.base64_encode(alice_iv)),
("port", "1"),
("s", @encoding.base64_encode(alice_static.public_key)),
("v", "2"),
]),
),
],
options: @common.Mapping::from_entries([("caps", "LR"), ("netId", "2")]),
signature: b"",
}
let signed_alice_ri = alice_ri.sign_ed25519(alice_ed_seed)
let bob_peer : @ntcp2_net.Ntcp2PeerInfo = {
router_hash: bob_id.hash().as_bytes(),
static_key: bob_static.public_key,
iv: bob_iv,
host: "127.0.0.1",
port: listen_port,
}
let dial = @ntcp2_net.PendingNtcp2Dial::start(
bob_peer, alice_static, signed_alice_ri,
)
let acc_sock = match listener.accept(timeout_ms=2000) {
Some(s) => s
None => fail("expected incoming NTCP2 TCP connection")
}
let acc = @ntcp2_net.PendingNtcp2Accept::start(
acc_sock,
bob_static,
bob_id.hash().as_bytes(),
bob_iv,
)
let mut alice_conn_opt : @ntcp2_net.Ntcp2Conn? = None
let mut bob_conn_opt : @ntcp2_net.Ntcp2Conn? = None
for _step = 0; _step < 100; _step = _step + 1 {
if alice_conn_opt is None {
alice_conn_opt = dial.step()
}
if bob_conn_opt is None {
bob_conn_opt = acc.step()
}
if alice_conn_opt is Some(_) && bob_conn_opt is Some(_) {
break
}
}
let alice_conn = match alice_conn_opt {
Some(c) => c
None => fail("PendingNtcp2Dial did not finish")
}
let bob_conn = match bob_conn_opt {
Some(c) => c
None => fail("PendingNtcp2Accept did not finish")
}
alice_conn.send_blocks_nb([@ntcp2.Ntcp2Block::Padding(b"nb-ntcp2-ok")])
let _ = alice_conn.flush_nonblocking()
let mut got_blocks : Array[@ntcp2.Ntcp2Block]? = None
for _i = 0; _i < 100; _i = _i + 1 {
if bob_conn.poll_readable(10) {
got_blocks = bob_conn.try_recv_blocks()
if got_blocks is Some(_) {
break
}
}
}
match got_blocks {
Some(blks) => assert_eq(blks, [@ntcp2.Ntcp2Block::Padding(b"nb-ntcp2-ok")])
None => fail("expected NTCP2 non-blocking blocks on responder")
}
alice_conn.close()
bob_conn.close()
listener.close()
}
+135 -6
View File
@@ -45,6 +45,12 @@ extern "C" fn c_tcp_check_connected(fd : Int32) -> Int32 = "moon_i2p_net_tcp_che
///|
extern "C" fn c_tcp_set_nonblocking(fd : Int32, nonblocking : Int32) -> Int32 = "moon_i2p_net_tcp_set_nonblocking"
///|
extern "C" fn c_tcp_set_peer_timeouts(
fd : Int32,
user_timeout_ms : Int32,
) -> Int32 = "moon_i2p_net_tcp_set_peer_timeouts"
///|
#borrow(host)
extern "C" fn c_tcp_listen(
@@ -384,20 +390,32 @@ pub fn TcpSocket::poll_readable(
pub fn TcpSocket::write_all(
self : TcpSocket,
data : Bytes,
timeout_ms~ : Int32 = 5000,
) -> Unit raise Ntcp2NetError {
if self.fd < 0 {
raise Closed
}
let total = data.length()
if total == 0 {
return
}
let budget = if timeout_ms > 0 { timeout_ms.to_uint64() } else { 1UL }
let deadline_ms = unix_time_ms() + budget
let mut sent = 0
while sent < total {
let n = c_tcp_send(self.fd, data, sent, total - sent)
if n == -2 {
let rc = c_tcp_poll_writable(self.fd, 5000)
let now_ms = unix_time_ms()
if now_ms >= deadline_ms {
raise Timeout
}
let rem64 = deadline_ms - now_ms
let rem_ms = if rem64 > 5000UL { 5000 } else { rem64.to_int() }
let rc = c_tcp_poll_writable(self.fd, if rem_ms > 0 { rem_ms } else { 1 })
if rc < 0 {
raise IoError("poll writable failed: \{last_os_error()}")
}
if rc == 0 {
if rc == 0 && unix_time_ms() >= deadline_ms {
raise Timeout
}
continue
@@ -745,6 +763,10 @@ pub struct Ntcp2Conn {
remote_router_info : @common.RouterInfo?
priv frame_buf : Array[Byte]
priv mut expected_frame_len : Int32
priv send_queue : Array[Bytes]
priv mut send_head_off : Int32
priv mut send_queued_bytes : Int32
priv mut send_blocked_since_ms : UInt64
}
///|
@@ -759,6 +781,10 @@ fn make_ntcp2_conn(
remote_router_info,
frame_buf: [],
expected_frame_len: -1,
send_queue: [],
send_head_off: 0,
send_queued_bytes: 0,
send_blocked_since_ms: 0UL,
}
}
@@ -877,6 +903,7 @@ pub fn PendingNtcp2Dial::start(
"connect_nb(\{peer.host}:\{peer.port}) failed: \{last_os_error()}",
)
}
let _ = c_tcp_set_peer_timeouts(fd, 15000)
let sock : TcpSocket = {
fd,
buf: FixedArray::make(4096, b'\x00'),
@@ -933,8 +960,7 @@ pub fn PendingNtcp2Dial::step(
self.sock.close()
raise IoError("non-blocking connect failed: \{msg}")
}
let _ = c_tcp_set_nonblocking(self.sock.fd, 0)
self.sock.write_all(self.m1_bytes) catch {
self.sock.write_all(self.m1_bytes, timeout_ms=250) catch {
e => {
self.sock.close()
raise e
@@ -1002,7 +1028,7 @@ pub fn PendingNtcp2Dial::step(
raise Protocol(e)
}
}
self.sock.write_all(msg3) catch {
self.sock.write_all(msg3, timeout_ms=250) catch {
e => {
self.sock.close()
raise e
@@ -1068,6 +1094,8 @@ pub fn PendingNtcp2Accept::start(
}
}
hs.set_ephemeral(ephem)
let _ = c_tcp_set_nonblocking(sock.fd, 1)
let _ = c_tcp_set_peer_timeouts(sock.fd, 15000)
{
sock,
hs,
@@ -1182,7 +1210,7 @@ pub fn PendingNtcp2Accept::step(
raise Protocol(e)
}
}
self.sock.write_all(msg2) catch {
self.sock.write_all(msg2, timeout_ms=250) catch {
e => {
self.sock.close()
raise e
@@ -1416,12 +1444,113 @@ pub fn Ntcp2Conn::try_recv_blocks(
Some(blocks)
}
///|
/// Flushes queued outbound NTCP2 frames without blocking. Returns `true` if any bytes were written.
/// Raises `Timeout` if outbound socket stays un-writable with queued data for >10s.
pub fn Ntcp2Conn::flush_nonblocking(
self : Ntcp2Conn,
) -> Bool raise Ntcp2NetError {
if self.send_queue.length() == 0 {
self.send_head_off = 0
self.send_queued_bytes = 0
self.send_blocked_since_ms = 0UL
return false
}
if self.socket.fd < 0 {
raise Closed
}
let mut wrote_any = false
while self.send_queue.length() > 0 {
let head = self.send_queue[0]
let rem = head.length() - self.send_head_off
if rem <= 0 {
let _ = self.send_queue.remove(0)
self.send_head_off = 0
continue
}
let n = c_tcp_send(self.socket.fd, head, self.send_head_off, rem)
if n == -2 {
break
}
if n < 0 {
raise IoError("non-blocking send failed: \{last_os_error()}")
}
if n == 0 {
raise Closed
}
wrote_any = true
self.send_head_off += n
self.send_queued_bytes -= n
if self.send_head_off >= head.length() {
let _ = self.send_queue.remove(0)
self.send_head_off = 0
}
}
let now_ms = unix_time_ms()
if self.send_queue.length() == 0 {
self.send_blocked_since_ms = 0UL
} else if wrote_any {
self.send_blocked_since_ms = now_ms
} else if self.send_blocked_since_ms == 0UL {
self.send_blocked_since_ms = now_ms
} else if now_ms > self.send_blocked_since_ms + 10000UL {
raise Timeout
}
wrote_any
}
///|
/// Encrypts and queues a data-phase frame for non-blocking transmission.
pub fn Ntcp2Conn::send_blocks_nb(
self : Ntcp2Conn,
blocks : Array[@ntcp2.Ntcp2Block],
) -> Unit raise Ntcp2NetError {
if self.send_queued_bytes > 262144 {
raise IoError("NTCP2 outbound send queue full")
}
let frame = self.session.encrypt_frame(blocks) catch {
e => raise Protocol(e)
}
self.send_queue.push(frame)
self.send_queued_bytes += frame.length()
let _ = self.flush_nonblocking()
}
///|
/// Encrypts and queues a single I2NP message for non-blocking NTCP2 transmission.
pub fn Ntcp2Conn::send_i2np_nb(
self : Ntcp2Conn,
msg_id : UInt32,
expiration_sec : UInt32,
payload : @i2np.I2npPayload,
) -> Unit raise Ntcp2NetError {
let blk = @ntcp2.i2np_block(msg_id, expiration_sec, payload) catch {
e => raise Protocol(e)
}
self.send_blocks_nb([blk])
}
///|
/// Encrypts and sends a data-phase frame containing `blocks`.
pub fn Ntcp2Conn::send_blocks(
self : Ntcp2Conn,
blocks : Array[@ntcp2.Ntcp2Block],
) -> Unit raise Ntcp2NetError {
if self.send_queue.length() > 0 {
let head = self.send_queue[0]
if self.send_head_off > 0 && self.send_head_off < head.length() {
self.socket.write_all(head[self.send_head_off:].to_owned())
} else if self.send_head_off == 0 {
self.socket.write_all(head)
}
let _ = self.send_queue.remove(0)
self.send_head_off = 0
while self.send_queue.length() > 0 {
self.socket.write_all(self.send_queue.remove(0))
}
self.send_queued_bytes = 0
self.send_blocked_since_ms = 0UL
}
let frame = self.session.encrypt_frame(blocks) catch {
e => raise Protocol(e)
}