291 lines
6.6 KiB
MoonBit
291 lines
6.6 KiB
MoonBit
///|
|
|
/// Low-level C FFI declarations backed by `tcp_stub.c`.
|
|
extern "C" fn c_last_error_len() -> Int32 = "moon_i2p_last_error_len"
|
|
|
|
///|
|
|
#borrow(dst)
|
|
extern "C" fn c_last_error_copy(
|
|
dst : FixedArray[Byte],
|
|
max_len : Int32,
|
|
) -> Int32 = "moon_i2p_last_error_copy"
|
|
|
|
///|
|
|
#borrow(host)
|
|
extern "C" fn c_tcp_connect(
|
|
host : Bytes,
|
|
host_len : Int32,
|
|
port : Int32,
|
|
) -> Int32 = "moon_i2p_tcp_connect"
|
|
|
|
///|
|
|
#borrow(data)
|
|
extern "C" fn c_tcp_send(
|
|
fd : Int32,
|
|
data : Bytes,
|
|
offset : Int32,
|
|
len : Int32,
|
|
) -> Int32 = "moon_i2p_tcp_send"
|
|
|
|
///|
|
|
#borrow(buf)
|
|
extern "C" fn c_tcp_recv(
|
|
fd : Int32,
|
|
buf : FixedArray[Byte],
|
|
max_len : Int32,
|
|
) -> Int32 = "moon_i2p_tcp_recv"
|
|
|
|
///|
|
|
extern "C" fn c_tcp_shutdown_write(fd : Int32) -> Int32 = "moon_i2p_tcp_shutdown_write"
|
|
|
|
///|
|
|
extern "C" fn c_tcp_close(fd : Int32) -> Int32 = "moon_i2p_tcp_close"
|
|
|
|
///|
|
|
#borrow(buf)
|
|
extern "C" fn c_read_stdin(buf : FixedArray[Byte], max_len : Int32) -> Int32 = "moon_i2p_read_stdin"
|
|
|
|
///|
|
|
extern "C" fn c_flush_stdout() -> Unit = "moon_i2p_flush_stdout"
|
|
|
|
///|
|
|
/// Flushes standard output (useful before blocking on `stream_accept`).
|
|
pub fn flush_stdout() -> Unit {
|
|
c_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)
|
|
let bytes = Bytes::from_array(buf)
|
|
@encoding.utf8_bytes_to_string(bytes[:copied].to_owned()) catch {
|
|
_ => "OS error"
|
|
}
|
|
}
|
|
|
|
///|
|
|
/// Reads all bytes from standard input until EOF.
|
|
pub fn read_all_stdin() -> Bytes raise SamClientError {
|
|
let out : Array[Byte] = []
|
|
let chunk = FixedArray::make(4096, b'\x00')
|
|
while true {
|
|
let n = c_read_stdin(chunk, 4096)
|
|
if n < 0 {
|
|
raise IoError("failed to read stdin: \{last_os_error()}")
|
|
}
|
|
if n == 0 {
|
|
break
|
|
}
|
|
for i = 0; i < n; i = i + 1 {
|
|
out.push(chunk[i])
|
|
}
|
|
}
|
|
Bytes::from_array(out)
|
|
}
|
|
|
|
///|
|
|
/// Buffered POSIX TCP connection. Preserves unconsumed bytes across line
|
|
/// reads and raw stream reads so SAMv3 transitions from text replies to
|
|
/// binary stream payloads never lose data.
|
|
struct TcpConn {
|
|
mut fd : Int32
|
|
buf : FixedArray[Byte]
|
|
mut pos : Int32
|
|
mut len : Int32
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::connect(
|
|
host : String,
|
|
port : Int32,
|
|
) -> TcpConn raise SamClientError {
|
|
let host_bytes = @encoding.string_to_utf8_bytes(host)
|
|
let fd = c_tcp_connect(host_bytes, host_bytes.length(), port)
|
|
if fd < 0 {
|
|
raise ConnectFailed(host, port, last_os_error())
|
|
}
|
|
{ fd, buf: FixedArray::make(4096, b'\x00'), pos: 0, len: 0, }
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::is_open(self : TcpConn) -> Bool {
|
|
self.fd >= 0
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::close(self : TcpConn) -> Unit {
|
|
if self.fd >= 0 {
|
|
let _ = c_tcp_close(self.fd)
|
|
self.fd = -1
|
|
}
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::shutdown_write(self : TcpConn) -> Unit raise SamClientError {
|
|
if self.fd < 0 {
|
|
raise Closed
|
|
}
|
|
if c_tcp_shutdown_write(self.fd) < 0 {
|
|
raise IoError("shutdown(SHUT_WR) failed: \{last_os_error()}")
|
|
}
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::write(self : TcpConn, data : Bytes) -> Int32 raise SamClientError {
|
|
if self.fd < 0 {
|
|
raise Closed
|
|
}
|
|
if data.length() == 0 {
|
|
return 0
|
|
}
|
|
let n = c_tcp_send(self.fd, data, 0, data.length())
|
|
if n < 0 {
|
|
raise IoError("send failed: \{last_os_error()}")
|
|
}
|
|
n
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::write_all(
|
|
self : TcpConn,
|
|
data : Bytes,
|
|
) -> Unit raise SamClientError {
|
|
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 IoError("peer closed connection during write")
|
|
}
|
|
sent += n
|
|
}
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::write_string(
|
|
self : TcpConn,
|
|
s : String,
|
|
) -> Unit raise SamClientError {
|
|
self.write_all(@encoding.string_to_utf8_bytes(s))
|
|
}
|
|
|
|
///|
|
|
fn TcpConn::refill(self : TcpConn) -> Int32 raise SamClientError {
|
|
if self.fd < 0 {
|
|
raise Closed
|
|
}
|
|
let n = c_tcp_recv(self.fd, self.buf, self.buf.length())
|
|
if n < 0 {
|
|
raise IoError("recv failed: \{last_os_error()}")
|
|
}
|
|
self.pos = 0
|
|
self.len = n
|
|
n
|
|
}
|
|
|
|
///|
|
|
/// Reads a single `\n`-terminated UTF-8 line (stripping trailing `\r\n` or `\n`).
|
|
fn TcpConn::read_line(self : TcpConn) -> String raise SamClientError {
|
|
let line_bytes : Array[Byte] = []
|
|
while true {
|
|
while self.pos < self.len {
|
|
let b = self.buf[self.pos]
|
|
self.pos += 1
|
|
if b == b'\n' {
|
|
// Strip optional trailing '\r'
|
|
if line_bytes.length() > 0 &&
|
|
line_bytes[line_bytes.length() - 1] == b'\r' {
|
|
let _ = line_bytes.pop()
|
|
}
|
|
let raw = Bytes::from_array(line_bytes)
|
|
return @encoding.utf8_bytes_to_string(raw) catch {
|
|
_ => raise ProtocolError("invalid UTF-8 in SAM reply line")
|
|
}
|
|
}
|
|
line_bytes.push(b)
|
|
}
|
|
let n = self.refill()
|
|
if n == 0 {
|
|
if line_bytes.length() == 0 {
|
|
raise UnexpectedEof("connection closed while waiting for SAM reply")
|
|
}
|
|
let raw = Bytes::from_array(line_bytes)
|
|
return @encoding.utf8_bytes_to_string(raw) catch {
|
|
_ => raise ProtocolError("invalid UTF-8 in SAM reply line")
|
|
}
|
|
}
|
|
}
|
|
""
|
|
}
|
|
|
|
///|
|
|
/// Reads up to `max_bytes` from the connection (returning empty `Bytes` on EOF).
|
|
fn TcpConn::read(
|
|
self : TcpConn,
|
|
max_bytes : Int32,
|
|
) -> Bytes raise SamClientError {
|
|
if self.fd < 0 {
|
|
raise Closed
|
|
}
|
|
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 tmp = FixedArray::make(max_bytes, b'\x00')
|
|
let n = c_tcp_recv(self.fd, tmp, max_bytes)
|
|
if n < 0 {
|
|
raise IoError("recv failed: \{last_os_error()}")
|
|
}
|
|
if n == 0 {
|
|
return b""
|
|
}
|
|
let out = FixedArray::make(n, b'\x00')
|
|
for i = 0; i < n; i = i + 1 {
|
|
out[i] = tmp[i]
|
|
}
|
|
Bytes::from_array(out)
|
|
}
|
|
|
|
///|
|
|
/// Reads until EOF and returns all received bytes.
|
|
fn TcpConn::read_all(self : TcpConn) -> Bytes raise SamClientError {
|
|
let out : Array[Byte] = []
|
|
while self.pos < self.len {
|
|
out.push(self.buf[self.pos])
|
|
self.pos += 1
|
|
}
|
|
let chunk = FixedArray::make(4096, b'\x00')
|
|
while true {
|
|
let n = c_tcp_recv(self.fd, chunk, 4096)
|
|
if n < 0 {
|
|
raise IoError("recv failed: \{last_os_error()}")
|
|
}
|
|
if n == 0 {
|
|
break
|
|
}
|
|
for i = 0; i < n; i = i + 1 {
|
|
out.push(chunk[i])
|
|
}
|
|
}
|
|
Bytes::from_array(out)
|
|
}
|