///| /// 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_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" ///| extern "C" fn c_tcp_poll_readable(fd : Int32, timeout_ms : Int32) -> Int32 = "moon_i2p_net_tcp_poll_readable" ///| 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" ///| 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() } ///| /// 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 < 0 { raise IoError("send failed: \{last_os_error()}") } if n == 0 { raise Closed } sent += n } } ///| 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, }) } ///| 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 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 } } let port = match parse_port_str(port_str) { Some(p) => p None => continue } let static_key = @encoding.base64_decode(s_b64) catch { _ => raise InvalidPeer("invalid base64 in NTCP2 's' option") } let iv = @encoding.base64_decode(i_b64) catch { _ => raise InvalidPeer("invalid base64 in NTCP2 'i' option") } 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? } ///| /// 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, ) -> Ntcp2Conn raise Ntcp2NetError { let sock = TcpSocket::connect(peer.host, peer.port) sock.set_recv_timeout(timeout_ms) let hs = @ntcp2.Ntcp2Handshake::new_initiator( local_static, peer.static_key, peer.router_hash, peer.iv, ) catch { e => { sock.close() raise Protocol(e) } } let ephem_priv = random_bytes(32) let ephem = @noise.KeyPair::from_private(ephem_priv) catch { e => { sock.close() raise Noise(e) } } hs.set_ephemeral(ephem) // Prepare Msg 3 Part 2 blocks first so we know exact m3p2_len for Msg 1 let ri_blk = @ntcp2.router_info_block(local_ri, flood~) catch { e => { sock.close() 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 => { sock.close() raise Protocol(e) } } let m3p2_ct_len = m3p2_pt.length() + 16 // Send Msg 1 (SessionRequest) with 16 bytes of random cleartext padding let m1_pad = random_bytes(16) let msg1 = hs.write_session_request( m3p2_ct_len, unix_time_sec(), padding=m1_pad, ) catch { e => { sock.close() raise Protocol(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) } } 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) } } { socket: sock, session, remote_router_info: None, } } ///| /// Accepts an incoming NTCP2 handshake on an already-accepted `TcpSocket`. pub fn accept_ntcp2( sock : TcpSocket, local_static : @noise.KeyPair, local_router_hash : Bytes, local_iv : Bytes, timeout_ms~ : Int32 = 10000, ) -> 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) catch { e => raise Protocol(e) } 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 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) } remote_ri = Some(parsed) } _ => () } } let session = hs.into_data_session() catch { e => raise Protocol(e) } { socket: sock, session, remote_router_info: remote_ri, } } ///| /// 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 { let len_hdr = self.socket.read_exact(2) 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}") } let ct = self.socket.read_exact(frame_len) 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() }