///| /// Native POSIX TCP transport, OS CSPRNG/clock helpers, and NTCP2 session manager. ///| #derive(Eq, Debug) pub suberror Ntcp2NetError { IoError(String) Timeout Closed Protocol(@ntcp2.Ntcp2Error) Common(@common.CommonError) Noise(@noise.NoiseError) InvalidPeer(String) } ///| extern "C" fn c_last_error_len() -> Int32 = "moon_i2p_net_last_error_len" ///| #borrow(dst) extern "C" fn c_last_error_copy( dst : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_last_error_copy" ///| #borrow(host) extern "C" fn c_tcp_connect( host : Bytes, host_len : Int32, port : Int32, ) -> Int32 = "moon_i2p_net_tcp_connect" ///| #borrow(host) extern "C" fn c_tcp_connect_nb( host : Bytes, host_len : Int32, port : Int32, ) -> Int32 = "moon_i2p_net_tcp_connect_nb" ///| extern "C" fn c_tcp_check_connected(fd : Int32) -> Int32 = "moon_i2p_net_tcp_check_connected" ///| extern "C" fn c_tcp_set_nonblocking(fd : Int32, nonblocking : Int32) -> Int32 = "moon_i2p_net_tcp_set_nonblocking" ///| #borrow(host) extern "C" fn c_tcp_listen( host : Bytes, host_len : Int32, port : Int32, ) -> Int32 = "moon_i2p_net_tcp_listen" ///| extern "C" fn c_tcp_local_port(fd : Int32) -> Int32 = "moon_i2p_net_tcp_local_port" ///| extern "C" fn c_tcp_accept(listen_fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_accept" ///| extern "C" fn c_tcp_set_recv_timeout(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_set_recv_timeout" ///| #borrow(data) extern "C" fn c_tcp_send( fd : Int32, data : Bytes, offset : Int32, len : Int32, ) -> Int32 = "moon_i2p_net_tcp_send" ///| #borrow(buf) extern "C" fn c_tcp_recv( fd : Int32, buf : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_tcp_recv" ///| #borrow(buf) extern "C" fn c_tcp_recv_nb( fd : Int32, buf : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_tcp_recv_nb" ///| extern "C" fn c_tcp_poll_readable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_readable" ///| extern "C" fn c_tcp_poll_writable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_writable" ///| extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_net_tcp_shutdown_write" ///| extern "C" fn c_tcp_close(fd : Int32) -> Int32 = "moon_i2p_net_tcp_close" ///| #borrow(buf) extern "C" fn c_random_bytes(buf : FixedArray[Byte], len : Int32) -> Int32 = "moon_i2p_net_random_bytes" ///| extern "C" fn c_unix_time_ms() -> UInt64 = "moon_i2p_net_unix_time_ms" ///| #borrow(path) extern "C" fn c_file_size(path : Bytes, path_len : Int32) -> Int32 = "moon_i2p_net_file_size" ///| #borrow(path, dst) extern "C" fn c_read_file( path : Bytes, path_len : Int32, dst : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_read_file" ///| extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_net_flush_stdout" ///| #borrow(path, dst) extern "C" fn c_list_dir( path : Bytes, path_len : Int32, dst : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_list_dir" ///| #borrow(url, dst) extern "C" fn c_fetch_https( url : Bytes, url_len : Int32, dst : FixedArray[Byte], max_len : Int32, ) -> Int32 = "moon_i2p_net_fetch_https" ///| fn last_os_error() -> String { let n = c_last_error_len() if n <= 0 { return "unknown OS error" } let buf = FixedArray::make(n, b'\x00') let copied = c_last_error_copy(buf, n) @encoding.utf8_bytes_to_string(Bytes::from_array(buf)[:copied].to_owned()) catch { _ => "OS error" } } ///| pub fn flush_stdout() -> Unit { c_flush_stdout() } ///| /// Lists non-`.`/`..` entry names inside local directory `dir`. pub fn list_dir_files(dir : String) -> Array[String] raise Ntcp2NetError { let pb = @encoding.string_to_utf8_bytes(dir) let buf = FixedArray::make(65536, b'\x00') let n = c_list_dir(pb, pb.length(), buf, 65536) if n < 0 { raise IoError("opendir(\{dir}) failed: \{last_os_error()}") } let text = @encoding.utf8_bytes_to_string( Bytes::from_array(buf)[:n].to_owned(), ) catch { _ => raise IoError("invalid UTF-8 in directory listing") } let out : Array[String] = [] let cur = StringBuilder() for ch in text { if ch == '\n' { let s = cur.to_string() if s.length() > 0 { out.push(s) } cur.reset() } else { cur.write_char(ch) } } out } ///| /// Fetches up to 2 MiB from an `https://` URL using system `curl` (no shell). pub fn fetch_https_bytes(url : String) -> Bytes raise Ntcp2NetError { let ub = @encoding.string_to_utf8_bytes(url) let buf = FixedArray::make(2 * 1024 * 1024, b'\x00') let n = c_fetch_https(ub, ub.length(), buf, 2 * 1024 * 1024) if n < 0 { raise IoError("https fetch(\{url}) failed: \{last_os_error()}") } Bytes::from_array(buf)[:n].to_owned() } ///| /// Reads `n` cryptographically secure random bytes from `/dev/urandom`. pub fn random_bytes(n : Int32) -> Bytes raise Ntcp2NetError { if n <= 0 { return b"" } let buf = FixedArray::make(n, b'\x00') let got = c_random_bytes(buf, n) if got != n { raise IoError("failed to read random bytes: \{last_os_error()}") } Bytes::from_array(buf) } ///| /// Returns the current Unix timestamp in milliseconds. pub fn unix_time_ms() -> UInt64 { c_unix_time_ms() } ///| /// Returns the current Unix timestamp in seconds. pub fn unix_time_sec() -> UInt32 { (c_unix_time_ms() / 1000UL).to_uint() } ///| /// Reads an entire local file into `Bytes`. pub fn read_file_bytes(path : String) -> Bytes raise Ntcp2NetError { let pb = @encoding.string_to_utf8_bytes(path) let sz = c_file_size(pb, pb.length()) if sz < 0 { raise IoError("stat(\{path}) failed: \{last_os_error()}") } if sz == 0 { return b"" } let buf = FixedArray::make(sz, b'\x00') let got = c_read_file(pb, pb.length(), buf, sz) if got < 0 { raise IoError("read(\{path}) failed: \{last_os_error()}") } Bytes::from_array(buf)[:got].to_owned() } ///| /// Native POSIX TCP socket wrapper with exact-length reads and line reading. pub struct TcpSocket { mut fd : Int32 buf : FixedArray[Byte] mut pos : Int32 mut len : Int32 } ///| pub fn TcpSocket::connect( host : String, port : Int32, ) -> TcpSocket raise Ntcp2NetError { let hb = @encoding.string_to_utf8_bytes(host) let fd = c_tcp_connect(hb, hb.length(), port) if fd < 0 { raise IoError("connect(\{host}:\{port}) failed: \{last_os_error()}") } { fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, } } ///| pub fn TcpSocket::set_recv_timeout( self : TcpSocket, timeout_ms : Int32, ) -> Unit raise Ntcp2NetError { if self.fd < 0 { raise Closed } if c_tcp_set_recv_timeout(self.fd, timeout_ms) < 0 { raise IoError("setsockopt(SO_RCVTIMEO) failed: \{last_os_error()}") } } ///| pub fn TcpSocket::poll_readable( self : TcpSocket, timeout_ms : Int32, ) -> Bool raise Ntcp2NetError { if self.pos < self.len { return true } if self.fd < 0 { raise Closed } let rc = c_tcp_poll_readable(self.fd, timeout_ms) if rc < 0 { raise IoError("poll failed: \{last_os_error()}") } rc > 0 } ///| pub fn TcpSocket::write_all( self : TcpSocket, data : Bytes, ) -> Unit raise Ntcp2NetError { if self.fd < 0 { raise Closed } let total = data.length() 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) if rc < 0 { raise IoError("poll writable failed: \{last_os_error()}") } if rc == 0 { raise Timeout } continue } if n < 0 { raise IoError("send failed: \{last_os_error()}") } if n == 0 { raise Closed } sent += n } } ///| /// Non-blocking read of up to `needed` bytes into `dst`. Returns bytes added /// (`0` if socket would block). Raises `Closed` on EOF when no bytes were read. pub fn TcpSocket::pump_nonblocking( self : TcpSocket, dst : Array[Byte], needed : Int32, ) -> Int32 raise Ntcp2NetError { if needed <= 0 { return 0 } if self.fd < 0 { raise Closed } let mut added = 0 while added < needed { if self.pos < self.len { let avail = self.len - self.pos let want = needed - added let take = if avail < want { avail } else { want } for i = 0; i < take; i = i + 1 { dst.push(self.buf[self.pos + i]) } self.pos += take added += take } else { let n = c_tcp_recv_nb(self.fd, self.buf, self.buf.length()) if n == -2 { break } if n < 0 { raise IoError("recv_nb failed: \{last_os_error()}") } if n == 0 { if added > 0 { return added } raise Closed } self.pos = 0 self.len = n } } added } ///| fn TcpSocket::refill(self : TcpSocket) -> Int32 raise Ntcp2NetError { if self.fd < 0 { raise Closed } let n = c_tcp_recv(self.fd, self.buf, self.buf.length()) if n == -2 { raise Timeout } if n < 0 { raise IoError("recv failed: \{last_os_error()}") } self.pos = 0 self.len = n n } ///| /// Reads exactly `count` bytes from the socket (or raises `Closed`/`Timeout`/`IoError`). pub fn TcpSocket::read_exact( self : TcpSocket, count : Int32, ) -> Bytes raise Ntcp2NetError { if count <= 0 { return b"" } let out = FixedArray::make(count, b'\x00') let mut got = 0 while got < count { if self.pos < self.len { let avail = self.len - self.pos let need = count - got let take = if avail < need { avail } else { need } for i = 0; i < take; i = i + 1 { out[got + i] = self.buf[self.pos + i] } self.pos += take got += take } else { let n = self.refill() if n == 0 { raise Closed } } } Bytes::from_array(out) } ///| /// Reads up to `max_bytes` available bytes (returns empty `Bytes` on EOF). pub fn TcpSocket::read_some( self : TcpSocket, max_bytes : Int32, ) -> Bytes raise Ntcp2NetError { if max_bytes <= 0 { return b"" } if self.pos < self.len { let avail = self.len - self.pos let take = if avail < max_bytes { avail } else { max_bytes } let out = FixedArray::make(take, b'\x00') for i = 0; i < take; i = i + 1 { out[i] = self.buf[self.pos + i] } self.pos += take return Bytes::from_array(out) } let n = self.refill() if n == 0 { return b"" } let take = if self.len < max_bytes { self.len } else { max_bytes } let out = FixedArray::make(take, b'\x00') for i = 0; i < take; i = i + 1 { out[i] = self.buf[i] } self.pos = take Bytes::from_array(out) } ///| /// Reads a `\n`-terminated UTF-8 line (stripping trailing `\r`). Returns `None` on clean EOF. pub fn TcpSocket::read_line(self : TcpSocket) -> String? raise Ntcp2NetError { let line : Array[Byte] = [] while true { while self.pos < self.len { let b = self.buf[self.pos] self.pos += 1 if b == b'\n' { if line.length() > 0 && line[line.length() - 1] == b'\r' { let _ = line.pop() } let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch { _ => raise IoError("invalid UTF-8 in line") } return Some(s) } line.push(b) } let n = self.refill() if n == 0 { if line.length() == 0 { return None } let s = @encoding.utf8_bytes_to_string(Bytes::from_array(line)) catch { _ => raise IoError("invalid UTF-8 in line") } return Some(s) } } None } ///| pub fn TcpSocket::shutdown_write(self : TcpSocket) -> Unit { if self.fd >= 0 { let _ = c_tcp_shutdown_write(self.fd) } } ///| pub fn TcpSocket::close(self : TcpSocket) -> Unit { if self.fd >= 0 { let _ = c_tcp_close(self.fd) self.fd = -1 } } ///| /// Native POSIX TCP server listener. pub struct TcpListener { mut fd : Int32 port : Int32 } ///| pub fn TcpListener::bind( host : String, port : Int32, ) -> TcpListener raise Ntcp2NetError { let hb = @encoding.string_to_utf8_bytes(host) let fd = c_tcp_listen(hb, hb.length(), port) if fd < 0 { raise IoError("listen(\{host}:\{port}) failed: \{last_os_error()}") } let bound_port = c_tcp_local_port(fd) { fd, port: if bound_port > 0 { bound_port } else { port }, } } ///| pub fn TcpListener::local_port(self : TcpListener) -> Int32 { self.port } ///| /// Accepts an incoming TCP connection. If `timeout_ms >= 0`, returns `None` on timeout. pub fn TcpListener::accept( self : TcpListener, timeout_ms~ : Int32 = -1, ) -> TcpSocket? raise Ntcp2NetError { if self.fd < 0 { raise Closed } let cfd = c_tcp_accept(self.fd, timeout_ms) if cfd == -2 { return None } if cfd < 0 { raise IoError("accept failed: \{last_os_error()}") } Some({ fd: cfd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }) } ///| /// Non-blocking accept: returns `None` immediately when no peer is waiting. pub fn TcpListener::accept_nonblocking( self : TcpListener, ) -> TcpSocket? raise Ntcp2NetError { self.accept(timeout_ms=0) } ///| pub fn TcpListener::close(self : TcpListener) -> Unit { if self.fd >= 0 { let _ = c_tcp_close(self.fd) self.fd = -1 } } ///| /// Extracted NTCP2 connection parameters from a peer's `RouterInfo`. #derive(Eq, Debug) pub(all) struct Ntcp2PeerInfo { router_hash : Bytes // 32-byte RH_B static_key : Bytes // 32-byte X25519 's' iv : Bytes // 16-byte 'i' host : String port : Int32 } ///| fn parse_port_str(s : String) -> Int32? { if s.length() == 0 { return None } let mut v = 0 for i = 0; i < s.length(); i = i + 1 { let c = s[i].to_int() if c < 48 || c > 57 { return None } v = v * 10 + (c - 48) } if v > 0 && v <= 65535 { Some(v) } else { None } } ///| /// Extracts the first reachable NTCP2 address (`host`, `port`, `s`, `i`) and `RH_B` /// from a peer's `RouterInfo`. pub fn extract_ntcp2_peer( ri : @common.RouterInfo, host_override~ : String? = None, ) -> Ntcp2PeerInfo raise Ntcp2NetError { for pass = 0; pass < 2; pass = pass + 1 { let allow_ipv6 = pass == 1 for addr in ri.addresses { if addr.transport_style != "NTCP2" { continue } let s_b64 = match addr.options.get("s") { Some(v) => v None => continue } let i_b64 = match addr.options.get("i") { Some(v) => v None => continue } let port_str = match addr.options.get("port") { Some(v) => v None => continue } let host = match host_override { Some(h) => h None => match addr.options.get("host") { Some(v) => v None => continue } } if !allow_ipv6 && host.contains(":") { continue } let port = match parse_port_str(port_str) { Some(p) => p None => continue } let static_key = @encoding.base64_decode(s_b64) catch { _ => continue } let iv = @encoding.base64_decode(i_b64) catch { _ => continue } if static_key.length() != 32 || iv.length() != 16 { continue } return { router_hash: ri.identity.hash().as_bytes(), static_key, iv, host, port, } } } raise InvalidPeer( "no reachable NTCP2 address with s/i/port found in RouterInfo", ) } ///| /// Active NTCP2 encrypted TCP connection in Data Phase. pub struct Ntcp2Conn { socket : TcpSocket session : @ntcp2.Ntcp2DataSession remote_router_info : @common.RouterInfo? priv frame_buf : Array[Byte] priv mut expected_frame_len : Int32 } ///| fn make_ntcp2_conn( socket : TcpSocket, session : @ntcp2.Ntcp2DataSession, remote_router_info : @common.RouterInfo?, ) -> Ntcp2Conn { { socket, session, remote_router_info, frame_buf: [], expected_frame_len: -1, } } ///| fn prepare_initiator_handshake( peer : Ntcp2PeerInfo, local_static : @noise.KeyPair, local_ri : @common.RouterInfo, flood : Bool, ) -> (@ntcp2.Ntcp2Handshake, Bytes, Array[@ntcp2.Ntcp2Block]) raise Ntcp2NetError { let hs = @ntcp2.Ntcp2Handshake::new_initiator( local_static, peer.static_key, peer.router_hash, peer.iv, ) catch { e => raise Protocol(e) } let ephem_priv = random_bytes(32) let ephem = @noise.KeyPair::from_private(ephem_priv) catch { e => raise Noise(e) } hs.set_ephemeral(ephem) let ri_blk = @ntcp2.router_info_block(local_ri, flood~) catch { e => raise Protocol(e) } let m3_pad = random_bytes(16) let m3_blocks : Array[@ntcp2.Ntcp2Block] = [ri_blk, Padding(m3_pad)] let m3p2_pt = @ntcp2.encode_blocks(m3_blocks) catch { e => raise Protocol(e) } let m3p2_ct_len = m3p2_pt.length() + 16 let m1_pad = random_bytes(16) let msg1 = hs.write_session_request( m3p2_ct_len, unix_time_sec(), padding=m1_pad, ) catch { e => raise Protocol(e) } (hs, msg1, m3_blocks) } ///| fn verify_confirmed_blocks( blocks : Array[@ntcp2.Ntcp2Block], session : @ntcp2.Ntcp2DataSession, ) -> @common.RouterInfo? raise Ntcp2NetError { let mut remote_ri : @common.RouterInfo? = None for blk in blocks { match blk { RouterInfo(router_info~, ..) => { let parsed = @common.RouterInfo::decode( @encoding.Reader::new(router_info), ) catch { e => raise Common(e) } if !parsed.verify_signature() { raise InvalidPeer("incoming RouterInfo failed Ed25519 verification") } let mut bound = true for addr in parsed.addresses { if addr.transport_style == "NTCP2" { match addr.options.get("s") { Some(s_b64) => { let s_bytes = @encoding.base64_decode(s_b64) catch { _ => b"" } if s_bytes.length() == 32 && !@crypto.ct_eq(s_bytes, session.remote_static()) { bound = false } } None => () } } } if !bound { raise InvalidPeer("incoming RouterInfo static key mismatch") } remote_ri = Some(parsed) } _ => () } } remote_ri } ///| /// Non-blocking outbound NTCP2 handshake state machine (`connect_nb` -> Msg 1 -> Msg 2 -> Msg 3). pub struct PendingNtcp2Dial { sock : TcpSocket hs : @ntcp2.Ntcp2Handshake m1_bytes : Bytes m3_blocks : Array[@ntcp2.Ntcp2Block] remote_ri : @common.RouterInfo? check_clock_skew : Bool max_skew_sec : UInt32 recv_buf : Array[Byte] mut step : Int32 // 0: wait connect, 1: wait m2 head, 2: wait m2 pad mut need_len : Int32 started_ms : UInt64 } ///| /// Starts a non-blocking NTCP2 dial to `peer`. Drive forward with `step()`. pub fn PendingNtcp2Dial::start( peer : Ntcp2PeerInfo, local_static : @noise.KeyPair, local_ri : @common.RouterInfo, flood~ : Bool = false, check_clock_skew~ : Bool = true, max_skew_sec~ : UInt32 = 60U, remote_ri~ : @common.RouterInfo? = None, ) -> PendingNtcp2Dial raise Ntcp2NetError { let hb = @encoding.string_to_utf8_bytes(peer.host) let fd = c_tcp_connect_nb(hb, hb.length(), peer.port) if fd < 0 { raise IoError( "connect_nb(\{peer.host}:\{peer.port}) failed: \{last_os_error()}", ) } let sock : TcpSocket = { fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, } let (hs, m1_bytes, m3_blocks) = prepare_initiator_handshake( peer, local_static, local_ri, flood, ) catch { e => { sock.close() raise e } } { sock, hs, m1_bytes, m3_blocks, remote_ri, check_clock_skew, max_skew_sec, recv_buf: [], step: 0, need_len: 0, started_ms: unix_time_ms(), } } ///| pub fn PendingNtcp2Dial::started_at_ms(self : PendingNtcp2Dial) -> UInt64 { self.started_ms } ///| pub fn PendingNtcp2Dial::close(self : PendingNtcp2Dial) -> Unit { self.sock.close() } ///| /// Advances a pending non-blocking outbound NTCP2 dial. Returns `None` while /// waiting for socket readiness, or `Some(Ntcp2Conn)` once Data Phase is ready. pub fn PendingNtcp2Dial::step( self : PendingNtcp2Dial, ) -> Ntcp2Conn? raise Ntcp2NetError { while true { if self.step == 0 { let rc = c_tcp_check_connected(self.sock.fd) if rc == 0 { return None } if rc < 0 { let msg = last_os_error() 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 { e => { self.sock.close() raise e } } self.step = 1 self.need_len = 64 } else if self.step == 1 { let need = self.need_len - self.recv_buf.length() let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { e => { self.sock.close() raise e } } if self.recv_buf.length() < self.need_len { return None } let m2_head = Bytes::from_array(self.recv_buf) self.recv_buf.clear() let m2_opts = self.hs.read_session_created_head(m2_head) catch { e => { self.sock.close() raise Protocol(e) } } if self.check_clock_skew { @ntcp2.validate_clock_skew( m2_opts.timestamp_sec, unix_time_sec(), max_skew_sec=self.max_skew_sec, ) catch { e => { self.sock.close() raise Protocol(e) } } } self.need_len = m2_opts.pad_len.reinterpret_as_int() self.step = 2 } else { if self.need_len > 0 { let need = self.need_len - self.recv_buf.length() let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { e => { self.sock.close() raise e } } if self.recv_buf.length() < self.need_len { return None } } let m2_pad = Bytes::from_array(self.recv_buf) self.recv_buf.clear() self.hs.finish_read_session_created(m2_pad) catch { e => { self.sock.close() raise Protocol(e) } } let msg3 = self.hs.write_session_confirmed(self.m3_blocks) catch { e => { self.sock.close() raise Protocol(e) } } self.sock.write_all(msg3) catch { e => { self.sock.close() raise e } } let session = self.hs.into_data_session() catch { e => { self.sock.close() raise Protocol(e) } } return Some(make_ntcp2_conn(self.sock, session, self.remote_ri)) } } None } ///| /// Non-blocking inbound NTCP2 handshake state machine (Msg 1 -> Msg 2 -> Msg 3). pub struct PendingNtcp2Accept { sock : TcpSocket hs : @ntcp2.Ntcp2Handshake replay_cache : @ntcp2.EphemeralReplayCache? check_clock_skew : Bool max_skew_sec : UInt32 expected_network_id : Byte recv_buf : Array[Byte] mut step : Int32 // 0: wait m1 head, 1: wait m1 pad, 2: wait m3 mut need_len : Int32 started_ms : UInt64 } ///| /// Begins a non-blocking NTCP2 responder handshake on an accepted TCP socket. pub fn PendingNtcp2Accept::start( sock : TcpSocket, local_static : @noise.KeyPair, local_router_hash : Bytes, local_iv : Bytes, replay_cache~ : @ntcp2.EphemeralReplayCache? = None, check_clock_skew~ : Bool = true, max_skew_sec~ : UInt32 = 60U, expected_network_id~ : Byte = b'\x02', ) -> PendingNtcp2Accept raise Ntcp2NetError { let hs = @ntcp2.Ntcp2Handshake::new_responder( local_static, local_router_hash, local_iv, ) catch { e => { sock.close() raise Protocol(e) } } let ephem_priv = random_bytes(32) catch { e => { sock.close() raise e } } let ephem = @noise.KeyPair::from_private(ephem_priv) catch { e => { sock.close() raise Noise(e) } } hs.set_ephemeral(ephem) { sock, hs, replay_cache, check_clock_skew, max_skew_sec, expected_network_id, recv_buf: [], step: 0, need_len: 64, started_ms: unix_time_ms(), } } ///| pub fn PendingNtcp2Accept::started_at_ms(self : PendingNtcp2Accept) -> UInt64 { self.started_ms } ///| pub fn PendingNtcp2Accept::close(self : PendingNtcp2Accept) -> Unit { self.sock.close() } ///| /// Advances a pending non-blocking inbound NTCP2 handshake. pub fn PendingNtcp2Accept::step( self : PendingNtcp2Accept, ) -> Ntcp2Conn? raise Ntcp2NetError { while true { if self.step == 0 { let need = self.need_len - self.recv_buf.length() let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { e => { self.sock.close() raise e } } if self.recv_buf.length() < self.need_len { return None } let m1_head = Bytes::from_array(self.recv_buf) self.recv_buf.clear() let m1_opts = self.hs.read_session_request_head( m1_head, expected_network_id=self.expected_network_id, ) catch { e => { self.sock.close() raise Protocol(e) } } let now_sec = unix_time_sec() if self.check_clock_skew { @ntcp2.validate_clock_skew( m1_opts.timestamp_sec, now_sec, max_skew_sec=self.max_skew_sec, ) catch { e => { self.sock.close() raise Protocol(e) } } } match self.replay_cache { Some(rc) => match self.hs.remote_ephemeral() { Some(rx) => rc.check_or_raise(rx, now_sec) catch { e => { self.sock.close() raise Protocol(e) } } None => () } None => () } self.need_len = m1_opts.pad_len.reinterpret_as_int() self.step = 1 } else if self.step == 1 { if self.need_len > 0 { let need = self.need_len - self.recv_buf.length() let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { e => { self.sock.close() raise e } } if self.recv_buf.length() < self.need_len { return None } } let m1_pad = Bytes::from_array(self.recv_buf) self.recv_buf.clear() self.hs.finish_read_session_request(m1_pad) catch { e => { self.sock.close() raise Protocol(e) } } let m2_pad = random_bytes(16) catch { e => { self.sock.close() raise e } } let msg2 = self.hs.write_session_created(unix_time_sec(), padding=m2_pad) catch { e => { self.sock.close() raise Protocol(e) } } self.sock.write_all(msg2) catch { e => { self.sock.close() raise e } } self.need_len = 48 + self.hs.m3p2_len() self.step = 2 } else { let need = self.need_len - self.recv_buf.length() let _ = self.sock.pump_nonblocking(self.recv_buf, need) catch { e => { self.sock.close() raise e } } if self.recv_buf.length() < self.need_len { return None } let msg3 = Bytes::from_array(self.recv_buf) self.recv_buf.clear() let blocks = self.hs.read_session_confirmed(msg3) catch { e => { self.sock.close() raise Protocol(e) } } let session = self.hs.into_data_session() catch { e => { self.sock.close() raise Protocol(e) } } let remote_ri = verify_confirmed_blocks(blocks, session) catch { e => { self.sock.close() raise e } } return Some(make_ntcp2_conn(self.sock, session, remote_ri)) } } None } ///| /// Connects to a remote NTCP2 peer over TCP and completes the full 3-message /// NTCP2 handshake (`SessionRequest` -> `SessionCreated` -> `SessionConfirmed`). pub fn dial_ntcp2( peer : Ntcp2PeerInfo, local_static : @noise.KeyPair, local_ri : @common.RouterInfo, flood~ : Bool = false, timeout_ms~ : Int32 = 10000, check_clock_skew~ : Bool = true, max_skew_sec~ : UInt32 = 60U, ) -> Ntcp2Conn raise Ntcp2NetError { let sock = TcpSocket::connect(peer.host, peer.port) sock.set_recv_timeout(timeout_ms) let (hs, msg1, m3_blocks) = prepare_initiator_handshake( peer, local_static, local_ri, flood, ) catch { e => { sock.close() raise e } } sock.write_all(msg1) // Read Msg 2 (SessionCreated): 64-byte head + pad_len bytes let m2_head = sock.read_exact(64) let m2_opts = hs.read_session_created_head(m2_head) catch { e => { sock.close() raise Protocol(e) } } if check_clock_skew { @ntcp2.validate_clock_skew( m2_opts.timestamp_sec, unix_time_sec(), max_skew_sec~, ) catch { e => { sock.close() raise Protocol(e) } } } let m2_pad_len = m2_opts.pad_len.reinterpret_as_int() let m2_pad = if m2_pad_len > 0 { sock.read_exact(m2_pad_len) } else { b"" } hs.finish_read_session_created(m2_pad) catch { e => { sock.close() raise Protocol(e) } } // Send Msg 3 (SessionConfirmed) let msg3 = hs.write_session_confirmed(m3_blocks) catch { e => { sock.close() raise Protocol(e) } } sock.write_all(msg3) let session = hs.into_data_session() catch { e => { sock.close() raise Protocol(e) } } make_ntcp2_conn(sock, session, None) } ///| /// Accepts an incoming NTCP2 handshake on an already-accepted `TcpSocket`. /// Checks network ID, optional clock skew (`±60s`), optional ephemeral X replay cache, /// remote `RouterInfo` Ed25519 signature, and static key binding. pub fn accept_ntcp2( sock : TcpSocket, local_static : @noise.KeyPair, local_router_hash : Bytes, local_iv : Bytes, timeout_ms~ : Int32 = 10000, replay_cache~ : @ntcp2.EphemeralReplayCache? = None, check_clock_skew~ : Bool = true, max_skew_sec~ : UInt32 = 60U, expected_network_id~ : Byte = b'\x02', ) -> Ntcp2Conn raise Ntcp2NetError { sock.set_recv_timeout(timeout_ms) let hs = @ntcp2.Ntcp2Handshake::new_responder( local_static, local_router_hash, local_iv, ) catch { e => raise Protocol(e) } let ephem_priv = random_bytes(32) let ephem = @noise.KeyPair::from_private(ephem_priv) catch { e => raise Noise(e) } hs.set_ephemeral(ephem) // Read Msg 1 (SessionRequest) let m1_head = sock.read_exact(64) let m1_opts = hs.read_session_request_head(m1_head, expected_network_id~) catch { e => raise Protocol(e) } let now_sec = unix_time_sec() if check_clock_skew { @ntcp2.validate_clock_skew(m1_opts.timestamp_sec, now_sec, max_skew_sec~) catch { e => raise Protocol(e) } } match replay_cache { Some(rc) => match hs.remote_ephemeral() { Some(rx) => rc.check_or_raise(rx, now_sec) catch { e => raise Protocol(e) } None => () } None => () } let m1_pad_len = m1_opts.pad_len.reinterpret_as_int() let m1_pad = if m1_pad_len > 0 { sock.read_exact(m1_pad_len) } else { b"" } hs.finish_read_session_request(m1_pad) catch { e => raise Protocol(e) } // Send Msg 2 (SessionCreated) let m2_pad = random_bytes(16) let msg2 = hs.write_session_created(unix_time_sec(), padding=m2_pad) catch { e => raise Protocol(e) } sock.write_all(msg2) // Read Msg 3 (SessionConfirmed) let m3_total = 48 + hs.m3p2_len() let msg3 = sock.read_exact(m3_total) let blocks = hs.read_session_confirmed(msg3) catch { e => raise Protocol(e) } let session = hs.into_data_session() catch { e => raise Protocol(e) } let remote_ri = verify_confirmed_blocks(blocks, session) make_ntcp2_conn(sock, session, remote_ri) } ///| /// Polls the underlying NTCP2 socket for readability (`timeout_ms=0` is non-blocking). pub fn Ntcp2Conn::poll_readable( self : Ntcp2Conn, timeout_ms : Int32, ) -> Bool raise Ntcp2NetError { self.frame_buf.length() > 0 || self.socket.poll_readable(timeout_ms) } ///| /// Non-blocking Data Phase read: accumulates partial TCP chunks safely across calls, /// returning `None` until a complete frame has arrived and been decrypted. pub fn Ntcp2Conn::try_recv_blocks( self : Ntcp2Conn, ) -> Array[@ntcp2.Ntcp2Block]? raise Ntcp2NetError { if self.expected_frame_len < 0 { let need = 2 - self.frame_buf.length() let _ = self.socket.pump_nonblocking(self.frame_buf, need) if self.frame_buf.length() < 2 { return None } let hdr = Bytes::from_array(self.frame_buf) self.frame_buf.clear() let flen = self.session.unmask_frame_length(hdr) catch { e => raise Protocol(e) } if flen < 16 { raise IoError("NTCP2 frame shorter than 16-byte MAC: \{flen}") } self.expected_frame_len = flen } let need = self.expected_frame_len - self.frame_buf.length() if need > 0 { let _ = self.socket.pump_nonblocking(self.frame_buf, need) } if self.frame_buf.length() < self.expected_frame_len { return None } let ct = Bytes::from_array(self.frame_buf) self.frame_buf.clear() self.expected_frame_len = -1 let blocks = self.session.decrypt_frame_body(ct) catch { e => raise Protocol(e) } Some(blocks) } ///| /// Encrypts and sends a data-phase frame containing `blocks`. pub fn Ntcp2Conn::send_blocks( self : Ntcp2Conn, blocks : Array[@ntcp2.Ntcp2Block], ) -> Unit raise Ntcp2NetError { let frame = self.session.encrypt_frame(blocks) catch { e => raise Protocol(e) } self.socket.write_all(frame) } ///| /// Reads, unmasks, and decrypts the next data-phase frame. pub fn Ntcp2Conn::recv_blocks( self : Ntcp2Conn, ) -> Array[@ntcp2.Ntcp2Block] raise Ntcp2NetError { if self.expected_frame_len < 0 { let need_hdr = 2 - self.frame_buf.length() if need_hdr > 0 { let rest = self.socket.read_exact(need_hdr) for i = 0; i < rest.length(); i = i + 1 { self.frame_buf.push(rest[i]) } } let len_hdr = Bytes::from_array(self.frame_buf) self.frame_buf.clear() let frame_len = self.session.unmask_frame_length(len_hdr) catch { e => raise Protocol(e) } if frame_len < 16 { raise IoError("NTCP2 frame shorter than 16-byte MAC: \{frame_len}") } self.expected_frame_len = frame_len } let need_body = self.expected_frame_len - self.frame_buf.length() if need_body > 0 { let rest = self.socket.read_exact(need_body) for i = 0; i < rest.length(); i = i + 1 { self.frame_buf.push(rest[i]) } } let ct = Bytes::from_array(self.frame_buf) self.frame_buf.clear() self.expected_frame_len = -1 self.session.decrypt_frame_body(ct) catch { e => raise Protocol(e) } } ///| /// Convenience helper to send a single I2NP message in an NTCP2 Data Phase frame. pub fn Ntcp2Conn::send_i2np( 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([blk]) } ///| pub fn Ntcp2Conn::close(self : Ntcp2Conn) -> Unit { self.socket.close() }