From b9f42d2ed2ef737618f3c800a1092a63421555b3 Mon Sep 17 00:00:00 2001 From: Muaz Ahmad Date: Fri, 10 May 2024 14:23:57 +0500 Subject: [PATCH] input domain parsing --- src/mdns.zig | 4 ++-- src/util.zig | 34 ++++++++++++++++++++++++++++++++-- 2 files changed, 34 insertions(+), 4 deletions(-) diff --git a/src/mdns.zig b/src/mdns.zig index 2d9364a..f4c08b6 100644 --- a/src/mdns.zig +++ b/src/mdns.zig @@ -1,8 +1,8 @@ const std = @import("std"); const util = @import("util.zig"); -pub fn get_mdns(domain: [:0]const u8) !util.IPs { - std.debug.print("{s}\n", .{domain}); +pub fn get_mdns(domain: util.Domain) !util.IPs { + std.debug.print("{}\n", .{domain}); return util.IPs{ .v4 = "stub v4", .v6 = "stub v6", diff --git a/src/util.zig b/src/util.zig index 40b3a97..33a7a74 100644 --- a/src/util.zig +++ b/src/util.zig @@ -1,15 +1,45 @@ const std = @import("std"); +const ArgError = error{ + NotEnoughArgs, + BadDomain, +}; + pub const IPs = struct { v4: [:0]const u8, v6: [:0]const u8, }; +pub const Domain = struct { + name: [:0]const u8, + labels: u8, +}; + pub fn check_perms() !void { var f = try std.fs.openFileAbsolute("/etc/hosts", .{ .mode = .write_only }); f.close(); } -pub fn get_input() ![:0]const u8 { - return "stub"; +pub fn get_input() !Domain { + var args = std.process.args(); + _ = args.next(); + const domain = args.next() orelse return ArgError.NotEnoughArgs; + return check_domain(domain); +} + +fn check_domain(domain_str: [:0]const u8) !Domain { + var domain = Domain{ + .name = domain_str, + .labels = 0, + }; + var labels = std.mem.split(u8, domain_str, "."); + var last: []const u8 = ""; + while (labels.next()) |segment| { + last = segment; + domain.labels += 1; + } + if (domain.labels <= 1 or !std.mem.eql(u8, last, "local")) { + return ArgError.BadDomain; + } + return domain; }