This commit is contained in:
Motiejus Jakštys 2024-10-11 09:40:21 +02:00
parent 519137df05
commit c3858b01a2

View File

@ -2,12 +2,11 @@ const std = @import("std");
const os = std.os; const os = std.os;
const mem = std.mem; const mem = std.mem;
const posix = std.posix; const posix = std.posix;
const log = std.log.scoped(.nyotun); const log = std.log.scoped(.nyotun);
const IFF_TUN = 0x0001; // <linux/if_tun.h> const IFF_TUN = 0x0001; // <linux/if_tun.h>
const IFF_NO_PI = 0x1000; // <linux/if_tun.h> const IFF_NO_PI = 0x1000; // <linux/if_tun.h>
const TUNSETIFF = 0x400454ca; // compile a C program, run and see const TUNSETIFF = 0x400454ca; // write a C program, run and see
dev: [posix.IFNAMESIZE:0]u8, dev: [posix.IFNAMESIZE:0]u8,
tunFile: posix.fd_t, tunFile: posix.fd_t,
@ -15,18 +14,15 @@ tunFile: posix.fd_t,
pub fn init(devname: ?[]const u8) !Tunnel { pub fn init(devname: ?[]const u8) !Tunnel {
const tunFile = try posix.open( const tunFile = try posix.open(
"/dev/net/tun", "/dev/net/tun",
posix.O{ posix.O{ .ACCMODE = .RDWR, .CLOEXEC = true },
.ACCMODE = .RDWR,
.CLOEXEC = true,
},
0, 0,
); );
errdefer posix.close(tunFile); errdefer posix.close(tunFile);
var ifr: posix.ifreq = undefined; var ifr = mem.zeroInit(
@memset(@as([*]u8, @ptrCast(&ifr))[0..@sizeOf(posix.ifreq)], 0); posix.ifreq,
.{ .ifru = .{ .flags = IFF_TUN | IFF_NO_PI } },
ifr.ifru.flags = IFF_TUN | IFF_NO_PI; );
if (devname) |name| { if (devname) |name| {
if (name.len >= posix.IFNAMESIZE - 1) return error.BadInterfaceName; if (name.len >= posix.IFNAMESIZE - 1) return error.BadInterfaceName;
@ -39,11 +35,7 @@ pub fn init(devname: ?[]const u8) !Tunnel {
return error.OpenDevTun; return error.OpenDevTun;
} }
var tunnel = Tunnel{ var tunnel = Tunnel{ .dev = .{0} ** posix.IFNAMESIZE, .tunFile = tunFile };
.dev = .{0} ** posix.IFNAMESIZE,
.tunFile = tunFile,
};
const ifname = mem.sliceTo(&ifr.ifrn.name, 0); const ifname = mem.sliceTo(&ifr.ifrn.name, 0);
@memcpy(tunnel.dev[0..ifname.len], ifname); @memcpy(tunnel.dev[0..ifname.len], ifname);
return tunnel; return tunnel;