Code style using 'zig fmt'.

master
Philippe Pittoli 2023-02-07 07:47:00 +01:00
parent 5ca55f0525
commit 70c062a598
11 changed files with 294 additions and 311 deletions

View File

@ -57,7 +57,9 @@ export fn ipc_schedule (ctx: *Context, servicefd: i32, mcontent: [*]const u8, ml
/// Read a message from a file descriptor.
/// Buffer length will be changed to the size of the received message.
export fn ipc_read_fd(ctx: *Context, fd: i32, buffer: [*]u8, buflen: *usize) callconv(.C) i32 {
var m = ctx.read_fd (fd) catch {return -1;} orelse return -2;
var m = ctx.read_fd(fd) catch {
return -1;
} orelse return -2;
if (m.payload.len > buflen.*) return -3;
buflen.* = m.payload.len;
@ -72,7 +74,9 @@ export fn ipc_read_fd (ctx: *Context, fd: i32, buffer: [*]u8, buflen: *usize) ca
/// Read a message.
/// Buffer length will be changed to the size of the received message.
export fn ipc_read(ctx: *Context, index: usize, buffer: [*]u8, buflen: *usize) callconv(.C) i32 {
var m = ctx.read (index) catch {return -1;} orelse return -2;
var m = ctx.read(index) catch {
return -1;
} orelse return -2;
if (m.payload.len > buflen.*) return -3;
buflen.* = m.payload.len;
@ -98,8 +102,7 @@ export fn ipc_wait_event(ctx: *Context, t: *u8, index: *usize, originfd: *i32, b
_ = writer.write(m.payload) catch return -4;
buflen.* = m.payload.len;
m.deinit();
}
else {
} else {
buflen.* = 0;
}
@ -139,9 +142,7 @@ export fn ipc_add_switch (ctx: *Context, fd1: i32, fd2: i32) callconv(.C) i32 {
return 0;
}
export fn ipc_set_switch_callbacks(ctx: *Context, fd: i32
, in : *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType
, out : *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) callconv(.C) i32 {
export fn ipc_set_switch_callbacks(ctx: *Context, fd: i32, in: *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType, out: *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) callconv(.C) i32 {
ctx.set_switch_callbacks(fd, in, out) catch return -1;
return 0;
}

View File

@ -7,7 +7,6 @@ const print_eq = @import("./util.zig").print_eq;
pub const Connections = std.ArrayList(Connection);
pub const Connection = struct {
pub const Type = enum {
IPC, // Standard connection.
EXTERNAL, // Non IPC connection (TCP, UDP, etc.).

View File

@ -57,14 +57,7 @@ pub const Context = struct {
},
};
return Self {
.rundir = rundir
, .connections = Connections.init(allocator)
, .pollfd = PollFD.init(allocator)
, .tx = Messages.init(allocator)
, .switchdb = SwitchDB.init(allocator)
, .allocator = allocator
};
return Self{ .rundir = rundir, .connections = Connections.init(allocator), .pollfd = PollFD.init(allocator), .tx = Messages.init(allocator), .switchdb = SwitchDB.init(allocator), .allocator = allocator };
}
// create a server path for the UNIX socket based on the service name
@ -98,9 +91,7 @@ pub const Context = struct {
return newfd;
}
fn connect_ipcd (self: *Self, service_name: []const u8
, connection_type: Connection.Type) !?i32 {
fn connect_ipcd(self: *Self, service_name: []const u8, connection_type: Connection.Type) !?i32 {
const buffer_size = 10000;
var buffer: [buffer_size]u8 = undefined;
var fba = std.heap.FixedBufferAllocator.init(&buffer);
@ -121,7 +112,9 @@ pub const Context = struct {
log.debug("no IPC_NETWORK envvar: IPCd won't be contacted", .{});
return null;
}, // no need to contact IPCd
else => { return err; },
else => {
return err;
},
};
var lookupbuffer: [buffer_size]u8 = undefined;
@ -165,9 +158,7 @@ pub const Context = struct {
/// won't be added.
fn add_(self: *Self, new_connection: Connection, fd: os.socket_t) !void {
try self.connections.append(new_connection);
try self.pollfd.append(.{ .fd = fd
, .events = std.os.linux.POLL.IN
, .revents = 0 });
try self.pollfd.append(.{ .fd = fd, .events = std.os.linux.POLL.IN, .revents = 0 });
}
fn fd_to_index(self: Self, fd: i32) !usize {
@ -218,12 +209,7 @@ pub const Context = struct {
// net.StreamServer
var serverfd = self.pollfd.items[server_index].fd;
var path = self.connections.items[server_index].path orelse return error.ServerWithNoPath;
var server = net.StreamServer {
.sockfd = serverfd
, .kernel_backlog = 100
, .reuse_address = false
, .listen_address = try net.Address.initUnix(path)
};
var server = net.StreamServer{ .sockfd = serverfd, .kernel_backlog = 100, .reuse_address = false, .listen_address = try net.Address.initUnix(path) };
var client = try server.accept(); // net.StreamServer.Connection
const newfd = client.stream.handle;
@ -290,9 +276,7 @@ pub const Context = struct {
try self.switchdb.add_switch(fd1, fd2);
}
pub fn set_switch_callbacks(self: *Self, fd: i32
, in : *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType
, out : *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) !void {
pub fn set_switch_callbacks(self: *Self, fd: i32, in: *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType, out: *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) !void {
try self.switchdb.set_callbacks(fd, in, out);
}
@ -341,8 +325,12 @@ pub const Context = struct {
var current_event: Event = Event.init(Event.Type.ERROR, 0, 0, null);
var wait_duration: i32 = -1; // -1 == unlimited
if (self.timer) |t| { log.debug("listening (timer: {} ms)", .{t}); wait_duration = t; }
else { log.debug("listening (no timer)", .{}); }
if (self.timer) |t| {
log.debug("listening (timer: {} ms)", .{t});
wait_duration = t;
} else {
log.debug("listening (no timer)", .{});
}
// Make sure we listen to the right file descriptors,
// setting POLLIN & POLLOUT flags.
@ -376,8 +364,7 @@ pub const Context = struct {
if (count == 0) {
if (duration >= wait_duration) {
current_event = Event.init(Event.Type.TIMER, 0, 0, null);
}
else {
} else {
// In case nothing happened, and poll wasn't triggered by time out.
current_event = Event.init(Event.Type.ERROR, 0, 0, null);
}
@ -434,7 +421,9 @@ pub const Context = struct {
try self.close(i);
return Event.init(Event.Type.DISCONNECTION, i, fd.fd, null);
},
else => { return err; },
else => {
return err;
},
};
if (maybe_message) |m| {
@ -465,8 +454,7 @@ pub const Context = struct {
current_event = self.switchdb.handle_event_write(i, m);
// Message inner memory is already freed.
switch (current_event.t) {
.SWITCH_TX => {
},
.SWITCH_TX => {},
.ERROR => {
var dest = try self.switchdb.getDest(fd.fd);
log.warn("error from {} -> removing {}, too", .{ fd.fd, dest });
@ -480,8 +468,7 @@ pub const Context = struct {
},
}
return current_event;
}
else {
} else {
// otherwise = write message for the msg.fd
try self.write(m);
m.deinit();
@ -497,7 +484,8 @@ pub const Context = struct {
}
// if fd revent is POLLERR or POLLNVAL
if ((fd.revents & std.os.linux.POLL.HUP > 0) or
(fd.revents & std.os.linux.POLL.NVAL > 0)) {
(fd.revents & std.os.linux.POLL.NVAL > 0))
{
return Event.init(Event.Type.ERROR, i, fd.fd, null);
}
}
@ -543,13 +531,13 @@ pub const Context = struct {
}
pub fn close_all(self: *Self) !void {
while(self.connections.items.len > 0) { try self.close(0); }
while (self.connections.items.len > 0) {
try self.close(0);
}
}
pub fn format(self: Self, comptime form: []const u8, options: fmt.FormatOptions, out_stream: anytype) !void {
try fmt.format(out_stream
, "context ({} connections and {} messages):"
, .{self.connections.items.len, self.tx.items.len});
try fmt.format(out_stream, "context ({} connections and {} messages):", .{ self.connections.items.len, self.tx.items.len });
for (self.connections.items) |con| {
try fmt.format(out_stream, "\n- ", .{});
@ -663,7 +651,6 @@ const ConnectThenSendMessageThread = struct {
}
};
test "Context - creation, echo once" {
const config = .{ .safety = true };
var gpa = std.heap.GeneralPurposeAllocator(config){};

View File

@ -53,7 +53,12 @@ pub const Event = struct {
const Self = @This();
pub fn init(t: Event.Type, index: usize, origin: i32, m: ?Message) Self {
return Self { .t = t, .index = index, .origin = origin, .m = m, };
return Self{
.t = t,
.index = index,
.origin = origin,
.m = m,
};
}
pub fn set(self: *Self, t: Event.Type, index: usize, origin: i32, m: ?Message) void {
@ -74,11 +79,8 @@ pub const Event = struct {
}
pub fn format(self: Self, comptime _: []const u8, _: fmt.FormatOptions, out_stream: anytype) !void {
try fmt.format(out_stream
, "{}, origin: {}, index {}, message: [{?}]"
, .{ self.t, self.origin, self.index, self.m} );
try fmt.format(out_stream, "{}, origin: {}, index {}, message: [{?}]", .{ self.t, self.origin, self.index, self.m });
}
};
test "Event - creation and display" {

View File

@ -19,7 +19,7 @@ pub fn Cmsghdr(comptime T: type) type {
const Header = extern struct {
len: usize,
level: c_int,
@"type": c_int,
type: c_int,
};
const data_align = @sizeOf(usize);
@ -32,14 +32,14 @@ pub fn Cmsghdr(comptime T: type) type {
pub fn init(args: struct {
level: c_int,
@"type": c_int,
type: c_int,
data: T,
}) Self {
var self: Self = undefined;
self.headerPtr().* = .{
.len = data_offset + @sizeOf(T),
.level = args.level,
.@"type" = args.@"type",
.type = args.type,
};
self.dataPtr().* = args.data;
return self;
@ -48,13 +48,13 @@ pub fn Cmsghdr(comptime T: type) type {
// TODO: include this version if we submit a PR to add this to std
pub fn initNoData(args: struct {
level: c_int,
@"type": c_int,
type: c_int,
}) Self {
var self: Self = undefined;
self.headerPtr().* = .{
.len = data_offset + @sizeOf(T),
.level = args.level,
.@"type" = args.@"type",
.type = args.type,
};
return self;
}
@ -84,7 +84,7 @@ pub fn send_fd(sockfd: os.socket_t, msg: []const u8, fd: os.fd_t) void {
var cmsg = Cmsghdr(os.fd_t).init(.{
.level = os.SOL.SOCKET,
.@"type" = SCM_RIGHTS,
.type = SCM_RIGHTS,
.data = fd,
});
@ -187,31 +187,19 @@ pub fn recvmsg(
/// A message can be carried with it, copied into 'buffer'.
/// WARNING: buffer must be at least 1500 bytes.
pub fn receive_fd(sockfd: os.socket_t, buffer: []u8, msg_size: *usize) !os.fd_t {
var msg_buffer = [_]u8{0} ** 1500;
var iov = [_]os.iovec{
.{
.iov_base = msg_buffer[0..]
, .iov_len = msg_buffer.len
},
.{ .iov_base = msg_buffer[0..], .iov_len = msg_buffer.len },
};
var cmsg = Cmsghdr(os.fd_t).init(.{
.level = os.SOL.SOCKET,
.@"type" = SCM_RIGHTS,
.type = SCM_RIGHTS,
.data = 0,
});
var msg: std.os.msghdr = .{
.name = null
, .namelen = 0
, .iov = &iov
, .iovlen = 1
, .control = &cmsg
, .controllen = @sizeOf(@TypeOf(cmsg))
, .flags = 0
};
var msg: std.os.msghdr = .{ .name = null, .namelen = 0, .iov = &iov, .iovlen = 1, .control = &cmsg, .controllen = @sizeOf(@TypeOf(cmsg)), .flags = 0 };
var msglen = recvmsg(sockfd, msg, 0) catch |err| {
log.err("error recvmsg failed with {s}", .{@errorName(err)});

View File

@ -41,7 +41,9 @@ pub fn hexdump(stream: anytype, header: [] const u8, buffer: [] const u8) std.os
// Each line is 16 bytes to print, each byte takes 3 characters.
var missing_spaces = 3 * (15 - (i % 16));
// Missing an extra space if the current index % 16 is less than 7.
if ((i%16) < 7) { missing_spaces += 1; }
if ((i % 16) < 7) {
missing_spaces += 1;
}
while (missing_spaces > 0) : (missing_spaces -= 1) {
try stream.writeAll(" ");
}

View File

@ -8,7 +8,6 @@ const print_eq = @import("./util.zig").print_eq;
pub const Messages = std.ArrayList(Message);
pub const Message = struct {
fd: i32, // File descriptor concerned about this message.
payload: []const u8,
@ -16,12 +15,8 @@ pub const Message = struct {
const Self = @This();
pub fn init(fd: i32
, allocator: std.mem.Allocator
, payload: []const u8) !Self {
return Message { .fd = fd
, .allocator = allocator
, .payload = try allocator.dupe(u8, payload) };
pub fn init(fd: i32, allocator: std.mem.Allocator, payload: []const u8) !Self {
return Message{ .fd = fd, .allocator = allocator, .payload = try allocator.dupe(u8, payload) };
}
pub fn deinit(self: Self) void {
@ -29,7 +24,6 @@ pub const Message = struct {
}
pub fn read(fd: i32, buffer: []const u8, allocator: std.mem.Allocator) !Self {
var fbs = std.io.fixedBufferStream(buffer);
var reader = fbs.reader();
@ -48,8 +42,7 @@ pub const Message = struct {
}
pub fn format(self: Self, comptime _: []const u8, _: fmt.FormatOptions, out_stream: anytype) !void {
try fmt.format(out_stream, "fd: {}, payload: [{s}]",
.{self.fd, self.payload} );
try fmt.format(out_stream, "fd: {}, payload: [{s}]", .{ self.fd, self.payload });
}
};

View File

@ -62,9 +62,7 @@ pub const SwitchDB = struct {
try self.db.put(fd2, ManagedConnection{ .dest = fd1 });
}
pub fn set_callbacks(self: *Self, fd: i32
, in : *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType
, out : *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) !void {
pub fn set_callbacks(self: *Self, fd: i32, in: *const fn (origin: i32, mcontent: [*]u8, mlen: *u32) CBEventType, out: *const fn (origin: i32, mcontent: [*]const u8, mlen: u32) CBEventType) !void {
var managedconnection = self.db.get(fd) orelse return error.unregisteredFD;
managedconnection.in = in;
managedconnection.out = out;
@ -82,22 +80,25 @@ pub const SwitchDB = struct {
switch (r) {
// The message should be ignored (protocol specific).
CBEventType.IGNORE => { return null; },
CBEventType.IGNORE => {
return null;
},
CBEventType.NO_ERROR => {
// TODO: read message
// TODO: better allocator?
// TODO: better errors?
var message: Message
= Message.read(managedconnection.dest
, buffer[0..message_size]
, std.heap.c_allocator) catch {
var message: Message = Message.read(managedconnection.dest, buffer[0..message_size], std.heap.c_allocator) catch {
return error.generic;
};
return message;
},
CBEventType.FD_CLOSING => { return error.closeFD; },
CBEventType.FD_CLOSING => {
return error.closeFD;
},
// Generic error, or the message was read but with errors.
CBEventType.ERROR => { return error.generic; },
CBEventType.ERROR => {
return error.generic;
},
}
unreachable;
@ -125,10 +126,11 @@ pub const SwitchDB = struct {
CBEventType.NO_ERROR => {
return;
},
CBEventType.FD_CLOSING => { return error.closeFD; },
CBEventType.FD_CLOSING => {
return error.closeFD;
},
// Generic error, or the message was read but with errors.
CBEventType.IGNORE,
CBEventType.ERROR => {
CBEventType.IGNORE, CBEventType.ERROR => {
return error.generic;
},
}
@ -143,8 +145,7 @@ pub const SwitchDB = struct {
error.closeFD => {
return Event.init(Event.Type.DISCONNECTION, index, fd, null);
},
error.unregisteredFD,
error.generic => {
error.unregisteredFD, error.generic => {
return Event.init(Event.Type.ERROR, index, fd, null);
},
};
@ -159,8 +160,7 @@ pub const SwitchDB = struct {
error.closeFD => {
return Event.init(Event.Type.DISCONNECTION, index, fd, null);
},
error.unregisteredFD,
error.generic => {
error.unregisteredFD, error.generic => {
return Event.init(Event.Type.ERROR, index, fd, null);
},
};
@ -230,17 +230,25 @@ test "successful exchanges" {
// should return a new message (hardcoded: fd 8, payload "coucou")
var event_1: Event = switchdb.handle_event_read(1, 5);
if (event_1.m) |m| { m.deinit(); }
else { return error.NoMessage; }
if (event_1.m) |m| {
m.deinit();
} else {
return error.NoMessage;
}
// should return a new message (hardcoded: fd 8, payload "coucou")
var event_2: Event = switchdb.handle_event_read(1, 6);
if (event_2.m) |m| { m.deinit(); }
else { return error.NoMessage; }
if (event_2.m) |m| {
m.deinit();
} else {
return error.NoMessage;
}
var message = try Message.init(6, allocator, "coucou");
var event_3 = switchdb.handle_event_write(5, message);
if (event_3.m) |_| { return error.ShouldNotCarryMessage; }
if (event_3.m) |_| {
return error.ShouldNotCarryMessage;
}
}
fn unsuccessful_in(_: i32, _: [*]const u8, _: *u32) CBEventType {
@ -265,15 +273,21 @@ test "unsuccessful exchanges" {
// should return a new message (hardcoded: fd 8, payload "coucou")
var event_1: Event = switchdb.handle_event_read(1, 5);
if (event_1.m) |_| { return error.ShouldNotCarryMessage; }
if (event_1.m) |_| {
return error.ShouldNotCarryMessage;
}
// should return a new message (hardcoded: fd 8, payload "coucou")
var event_2: Event = switchdb.handle_event_read(1, 6);
if (event_2.m) |_| { return error.ShouldNotCarryMessage; }
if (event_2.m) |_| {
return error.ShouldNotCarryMessage;
}
var message = try Message.init(6, allocator, "coucou");
var event_3 = switchdb.handle_event_write(5, message);
if (event_3.m) |_| { return error.ShouldNotCarryMessage; }
if (event_3.m) |_| {
return error.ShouldNotCarryMessage;
}
}
test "nuke 'em" {

View File

@ -15,7 +15,6 @@ pub const URI = struct {
const Self = @This();
pub fn read(uri_to_decode: []const u8) Self {
var protocolit = std.mem.split(u8, uri_to_decode, "://");
var protocol = protocolit.first();
@ -24,9 +23,7 @@ pub const URI = struct {
var path = addressit.rest();
return Self { .protocol = protocol
, .address = address
, .path = path };
return Self{ .protocol = protocol, .address = address, .path = path };
}
};