From 26935db97bc68d21c9716dea6f109cfff2c7bed6 Mon Sep 17 00:00:00 2001 From: Aarnav Tale Date: Sat, 20 Apr 2024 19:33:44 -0400 Subject: [PATCH] tcp: use unix:// or tcp:// as config values for tcp binding --- src/tcp/Server.zig | 30 ------------------------------ src/tcp/Thread.zig | 19 +++++++++++++------ 2 files changed, 13 insertions(+), 36 deletions(-) diff --git a/src/tcp/Server.zig b/src/tcp/Server.zig index 7b48bfb7f..8ed3a301a 100644 --- a/src/tcp/Server.zig +++ b/src/tcp/Server.zig @@ -58,36 +58,6 @@ pub fn init( }; } -const BindError = error{ - NoAddress, - InvalidAddress, -}; - -/// Tries to generate a valid address to bind to -/// TODO: Maybe unix sockets should start with unix:// -pub fn parseAddress(raw_addr: ?[:0]const u8) BindError!std.net.Address { - const addr = raw_addr orelse { - return BindError.NoAddress; - }; - - if (addr.len == 0) { - return BindError.NoAddress; - } - - var iter = std.mem.splitScalar(u8, addr, ':'); - const host = iter.next() orelse return BindError.InvalidAddress; - const port = iter.next() orelse return BindError.InvalidAddress; - const numPort = std.fmt.parseInt(u16, port, 10) catch { - return std.net.Address.initUnix(addr) catch BindError.InvalidAddress; - }; - - const ip = std.net.Address.parseIp4(host, numPort) catch { - return std.net.Address.initUnix(addr) catch BindError.InvalidAddress; - }; - - return ip; -} - /// Deinitializes the server pub fn deinit(self: *Server) void { log.info("shutting down server", .{}); diff --git a/src/tcp/Thread.zig b/src/tcp/Thread.zig index 5afa91ab0..e348718e0 100644 --- a/src/tcp/Thread.zig +++ b/src/tcp/Thread.zig @@ -14,7 +14,7 @@ const log = std.log.scoped(.tcp_thread); alloc: std.mem.Allocator, /// The TCP server for handling incoming connections. -server: tcp.Server, +server: ?tcp.Server, /// Initialize the thread. This does not START the thread. This only sets /// up all the internal state necessary prior to starting the thread. It @@ -26,7 +26,10 @@ pub fn init(alloc: Allocator) !Thread { const parsedAddr = tcp.Server.parseAddress(addr) catch |err| { log.err("failed to parse address addr={any} err={any}", .{ addr, err }); - return err; + return Thread{ + .alloc = alloc, + .server = undefined, + }; }; log.debug("parsed address addr={any}", .{parsedAddr}); @@ -42,7 +45,9 @@ pub fn init(alloc: Allocator) !Thread { /// Clean up the thread. This is only safe to call once the thread /// completes executing; the caller must join prior to this. pub fn deinit(self: *Thread) void { - self.server.deinit(); + if (self.server) |*server| { + server.deinit(); + } } /// The main entrypoint for the thread. @@ -53,7 +58,9 @@ pub fn threadMain(self: *Thread) void { } fn threadMain_(self: *Thread) !void { - log.debug("starting tcp thread", .{}); - try self.server.start(); - errdefer log.debug("tcp thread exited", .{}); + if (self.server) |*server| { + log.debug("starting tcp thread", .{}); + defer log.debug("tcp thread exited", .{}); + try server.start(); + } }