const std = @import("std"); const mem = std.mem; const Io = std.Io; const linux = std.os.linux; const log = std.log; pub const Error = error{ SocketFailed, BindFailed, }; fd: Io.File, seq: u32 = 0, const Self = @This(); pub fn init(protocol: linux.sa_family_t) Error!Self { const fd = linux.socket( linux.AF.NETLINK, linux.SOCK.RAW | linux.SOCK.CLOEXEC, protocol, ); switch (linux.errno(fd)) { .SUCCESS => {}, else => |err| { log.err("socket failed: {}\n", .{err}); return Error.SocketFailed; }, } const local: linux.sockaddr.nl = .{ .family = linux.AF.NETLINK, .__pad1 = 0, .pid = 0, .groups = 0, }; switch (linux.errno(linux.bind(@intCast(fd), @ptrCast(&local), @sizeOf(@TypeOf(local))))) { .SUCCESS => {}, else => |err| { log.err("bind failed: {}\n", .{err}); _ = linux.close(@intCast(fd)); return Error.BindFailed; }, } return .{ .fd = Io.File{ .flags = .{ .nonblocking = false }, .handle = @intCast(fd), }, }; } pub fn deinit(self: *Self, io: Io) void { self.fd.close(io); self.* = undefined; } pub fn nextSeq(self: *Self) u32 { self.seq +%= 1; return self.seq; } pub fn send(self: *Self, io: Io, @"type": linux.NetlinkMessageType, req: anytype) !u32 { const seq = self.nextSeq(); const header: linux.nlmsghdr = .{ .len = @intCast(@sizeOf(linux.nlmsghdr) + req.bytes().len), .type = @"type", .flags = @TypeOf(req.*).nlmsg_flags, .seq = seq, .pid = 0, }; const n = try self.fd.writeStreaming(io, mem.asBytes(&header), &.{req.bytes()}, 1); if (n != header.len) return error.ShortWrite; return seq; } pub fn receive(self: *const Self, io: Io, buf: []u8) Io.File.ReadStreamingError![]const u8 { const n = try self.fd.readStreaming(io, &.{buf}); return buf[0..n]; }