8 Commits

Author SHA1 Message Date
180babae15 Big changes to the C api implementations
Should map directly to the zig struct instead of mallocing
2025-04-27 16:18:48 -04:00
fe1c735026 Add C to Zig converter
Further simplify struct
2025-04-27 16:18:48 -04:00
444f4868d5 Make C struct match the binary API more closely
Also make the internal conversion function return errors properly
2025-04-27 16:18:48 -04:00
ef33d2aec8 Convert from Zig struct to C struct 2025-04-27 16:18:48 -04:00
733deeb6e1 use InstallHeader function to install the header 2025-04-27 16:18:48 -04:00
8540dfb5b9 successfully build c interface 2025-04-27 16:18:48 -04:00
247c6b4407 Initial C api 2025-04-27 16:18:48 -04:00
e847989592 Use FAIL as the default dest if unable to parse 2025-04-27 16:18:48 -04:00
6 changed files with 198 additions and 7 deletions

View File

@@ -1,4 +1,5 @@
const std = @import("std"); const std = @import("std");
const Step = std.Build.Step;
// Although this function looks imperative, note that its job is to // Although this function looks imperative, note that its job is to
// declaratively construct a build graph that will be executed by an external // declaratively construct a build graph that will be executed by an external
@@ -37,13 +38,29 @@ pub fn build(b: *std.Build) void {
exe_mod.addImport("zaprus", lib_mod); exe_mod.addImport("zaprus", lib_mod);
exe_mod.addImport("clap", b.dependency("clap", .{}).module("clap")); exe_mod.addImport("clap", b.dependency("clap", .{}).module("clap"));
const lib = b.addLibrary(.{ const static_lib = b.addLibrary(.{
.linkage = .static, .linkage = .static,
.name = "zaprus", .name = "zaprus",
.root_module = lib_mod, .root_module = lib_mod,
}); });
static_lib.addIncludePath(.{ .cwd_relative = "include" });
static_lib.linkLibC();
b.installArtifact(lib); b.installArtifact(static_lib);
const dynamic_lib = b.addLibrary(.{
.linkage = .dynamic,
.name = "zaprus",
.root_module = lib_mod,
});
dynamic_lib.addIncludePath(.{ .cwd_relative = "include" });
dynamic_lib.linkLibC();
b.installArtifact(dynamic_lib);
// C Headers
const c_header = b.addInstallHeaderFile(b.path("include/zaprus.h"), "zaprus.h");
b.getInstallStep().dependOn(&c_header.step);
// This creates another `std.Build.Step.Compile`, but this one builds an executable // This creates another `std.Build.Step.Compile`, but this one builds an executable
// rather than a static library. // rather than a static library.

46
include/zaprus.h Normal file
View File

@@ -0,0 +1,46 @@
// client
#include<stdint.h>
#include<stdlib.h>
int zaprus_init(void);
int zaprus_deinit(void);
int zaprus_send_relay(const char* payload, size_t len, char dest[4]);
int zaprus_send_initial_connection(const char* payload, size_t len, uint16_t initial_port);
struct SaprusMessage* zaprus_connect(const char* payload, size_t len);
// message
#define SAPRUS_RELAY_MESSAGE_TYPE 0x003C
#define SAPRUS_FILE_TRANSFER_MESSAGE_TYPE 0x8888
#define SAPRUS_CONNECTION_MESSAGE_TYPE 0x00E9
struct SaprusMessage {
uint16_t packet_type;
uint16_t payload_len;
union {
struct {
char dest[4];
} relay;
struct {
uint16_t src_port;
uint16_t dest_port;
uint32_t seq_num;
uint32_t msg_id;
char _reserved;
char options;
} connection;
} headers;
char *payload;
};
// ptr should be freed by the caller.
int zaprus_message_to_bytes(struct SaprusMessage msg, char** ptr, size_t* len);
// Return value should be destroyed with zaprus_message_deinit.
struct SaprusMessage* zaprus_message_from_bytes(const char* bytes, size_t len);
void zaprus_message_deinit(struct SaprusMessage* msg);

View File

@@ -76,7 +76,7 @@ pub fn sendInitialConnection(payload: []const u8, initial_port: u16, allocator:
return msg; return msg;
} }
pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage { pub fn connect(payload: []const u8, allocator: Allocator) !SaprusMessage {
var initial_port: u16 = 0; var initial_port: u16 = 0;
if (rand) |r| { if (rand) |r| {
initial_port = r.intRangeAtMost(u16, 1024, 65000); initial_port = r.intRangeAtMost(u16, 1024, 65000);
@@ -109,7 +109,7 @@ pub fn connect(payload: []const u8, allocator: Allocator) !?SaprusMessage {
// Complete handshake after awaiting response // Complete handshake after awaiting response
try broadcastSaprusMessage(msg, randomPort(), allocator); try broadcastSaprusMessage(msg, randomPort(), allocator);
return initial_conn_res; return initial_conn_res.?;
} }
const SaprusMessage = @import("message.zig").Message; const SaprusMessage = @import("message.zig").Message;

126
src/c_api.zig Normal file
View File

@@ -0,0 +1,126 @@
const c = @cImport({
@cInclude("zaprus.h");
});
fn zigToCMessage(msg: zaprus.Message) !c.SaprusMessage {
return switch (msg) {
.relay => |r| .{
.packet_type = @intFromEnum(msg),
.payload_len = @intCast(r.payload.len),
.headers = .{ .relay = .{
.dest = r.header.dest,
} },
.payload = @constCast(r.payload.ptr),
},
.connection => |con| .{
.packet_type = @intFromEnum(msg),
.payload_len = @intCast(con.payload.len),
.headers = .{ .connection = .{
.src_port = con.header.src_port,
.dest_port = con.header.dest_port,
.seq_num = con.header.seq_num,
.msg_id = con.header.msg_id,
._reserved = con.header.reserved,
.options = @bitCast(con.header.options),
} },
.payload = @constCast(con.payload.ptr),
},
.file_transfer => return zaprus.Error.NotImplementedSaprusType,
else => return zaprus.Error.UnknownSaprusType,
};
}
fn cToZigMessage(msg: c.SaprusMessage) !zaprus.Message {
const msg_type: zaprus.PacketType = @enumFromInt(msg.packet_type);
return switch (msg_type) {
.relay => .{
.relay = .{
.header = .{
.dest = msg.headers.relay.dest[0..4].*,
},
.payload = msg.payload[0..msg.payload_len],
},
},
.connection => .{
.connection = .{
.header = .{
.src_port = msg.headers.connection.src_port,
.dest_port = msg.headers.connection.dest_port,
.seq_num = msg.headers.connection.seq_num,
.msg_id = msg.headers.connection.msg_id,
.reserved = msg.headers.connection._reserved,
.options = @bitCast(msg.headers.connection.options),
},
.payload = msg.payload[0..msg.payload_len],
},
},
.file_transfer => return zaprus.Error.NotImplementedSaprusType,
else => return zaprus.Error.UnknownSaprusType,
};
}
// client
export fn zaprus_init() c_int {
SaprusClient.init() catch return 1;
return 0;
}
export fn zaprus_deinit() c_int {
SaprusClient.deinit();
return 0;
}
export fn zaprus_send_relay(payload: [*]const u8, len: usize, dest: [*]u8) c_int {
SaprusClient.sendRelay(payload[0..len], dest[0..4].*, allocator) catch return 1;
return 0;
}
export fn zaprus_send_initial_connection(payload: [*]const u8, len: usize, initial_port: u16) c_int {
_ = SaprusClient.sendInitialConnection(payload[0..len], initial_port, allocator) catch return 1;
return 0;
}
export fn zaprus_connect(payload: [*]const u8, len: usize) ?*c.SaprusMessage {
if (SaprusClient.connect(payload[0..len], allocator)) |msg| {
var m = zigToCMessage(msg) catch return null;
return &m;
} else |_| {
return null;
}
}
// message
/// ptr should be freed by the caller.
export fn zaprus_message_to_bytes(msg: c.SaprusMessage, ptr: *[*]u8, len: *usize) c_int {
var m = cToZigMessage(msg) catch return 1;
const bytes = m.toBytes(allocator) catch return 1;
ptr.* = bytes.ptr;
len.* = bytes.len;
return 0;
}
/// Return value should be destroyed with zaprus_message_deinit.
export fn zaprus_message_from_bytes(bytes: [*]const u8, len: usize) ?*c.SaprusMessage {
if (zaprus.Message.fromBytes(bytes[0..len], allocator)) |msg| {
var m = zigToCMessage(msg) catch return null;
return &m;
} else |_| return null;
}
export fn zaprus_message_deinit(msg: *c.SaprusMessage) void {
if (cToZigMessage(msg.*)) |m| {
m.deinit(allocator);
} else |_| unreachable;
}
const std = @import("std");
const zaprus = @import("./root.zig");
const SaprusClient = zaprus.Client;
const allocator = std.heap.c_allocator;
test {
std.testing.refAllDeclsRecursively(@This());
}

View File

@@ -75,7 +75,7 @@ pub fn main() !void {
return clap.help(std.io.getStdErr().writer(), clap.Help, &params, .{}); return clap.help(std.io.getStdErr().writer(), clap.Help, &params, .{});
} }
fn parseDest(in: ?[]const u8) [4]u8 { fn parseDest(in: ?[]const u8) ![4]u8 {
if (in) |dest| { if (in) |dest| {
if (dest.len <= 4) { if (dest.len <= 4) {
var res: [4]u8 = @splat(0); var res: [4]u8 = @splat(0);
@@ -83,10 +83,10 @@ fn parseDest(in: ?[]const u8) [4]u8 {
return res; return res;
} }
const addr = std.net.Ip4Address.parse(dest, 0) catch return "FAIL".*; const addr = try std.net.Ip4Address.parse(dest, 0);
return @bitCast(addr.sa.addr); return @bitCast(addr.sa.addr);
} }
return "zap".*; return "FAIL".*;
} }
const builtin = @import("builtin"); const builtin = @import("builtin");

View File

@@ -1,2 +1,4 @@
pub const Client = @import("Client.zig"); pub const Client = @import("Client.zig");
pub usingnamespace @import("message.zig"); pub usingnamespace @import("message.zig");
pub usingnamespace @import("c_api.zig");