-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfuse.zig
734 lines (595 loc) · 17.6 KB
/
fuse.zig
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
const std = @import("std");
const assert = std.debug.assert;
const log = std.log;
const net = std.net;
const os = std.os;
const fs = std.fs;
const errno = os.errno;
const l = os.linux;
const E = l.E;
const mem = std.mem;
const Allocator = mem.Allocator;
const MIN_READ_BUFFER = 8192;
const Opcode = enum(u32) {
LOOKUP = 1,
FORGET = 2,
GETATTR = 3,
SETATTR = 4,
READLINK = 5,
SYMLINK = 6,
MKNOD = 8,
MKDIR = 9,
UNLINK = 10,
RMDIR = 11,
RENAME = 12,
LINK = 13,
OPEN = 14,
READ = 15,
WRITE = 16,
STATFS = 17,
RELEASE = 18,
FSYNC = 20,
SETXATTR = 21,
GETXATTR = 22,
LISTXATTR = 23,
REMOVEXATTR = 24,
FLUSH = 25,
INIT = 26,
OPENDIR = 27,
READDIR = 28,
RELEASEDIR = 29,
FSYNCDIR = 30,
GETLK = 31,
SETLK = 32,
SETLKW = 33,
ACCESS = 34,
CREATE = 35,
INTERRUPT = 36,
BMAP = 37,
DESTROY = 38,
IOCTL = 39,
POLL = 40,
NOTIFY_REPLY = 41,
BATCH_FORGET = 42,
FALLOCATE = 43,
READDIRPLUS = 44,
RENAME2 = 45,
LSEEK = 46,
COPY_FILE_RANGE = 47,
SETUPMAPPING = 48,
REMOVEMAPPING = 49,
SYNCFS = 50,
TMPFILE = 51,
CUSE_INIT = 4096,
CUSE_INIT_BSWAP_RESERVED = 1048576,
INIT_BSWAP_RESERVED = 436207616,
};
const FATTR = struct {
pub const MODE = @as(u32, 1) << @as(u32, 0);
pub const UID = @as(u32, 1) << @as(u32, 1);
pub const GID = @as(u32, 1) << @as(u32, 2);
pub const SIZE = @as(u32, 1) << @as(u32, 3);
pub const ATIME = @as(u32, 1) << @as(u32, 4);
pub const MTIME = @as(u32, 1) << @as(u32, 5);
pub const FH = @as(u32, 1) << @as(u32, 6);
pub const ATIME_NOW = @as(u32, 1) << @as(u32, 7);
pub const MTIME_NOW = @as(u32, 1) << @as(u32, 8);
pub const LOCKOWNER = @as(u32, 1) << @as(u32, 9);
pub const CTIME = @as(u32, 1) << @as(u32, 10);
pub const KILL_SUIDGID = @as(u32, 1) << @as(u32, 11);
};
const InHeader = extern struct {
len: u32,
opcode: u32,
unique: u64,
nodeid: u64,
uid: l.uid_t,
gid: l.gid_t,
pid: l.pid_t,
padding: u32,
};
const OutHeader = extern struct {
len: u32,
err: i32,
unique: u64,
};
const InitIn = extern struct {
major: u32,
minor: u32,
max_readahead: u32,
flags: u32,
flags2: u32,
unused: [11]u32,
};
const InitOut = extern struct {
major: u32,
minor: u32,
max_readahead: u32,
flags: u32,
max_background: u16,
congestion_threshold: u16,
max_write: u32,
time_gran: u32,
max_pages: u16,
map_alignment: u16,
flags2: u32,
unused: [7]u32 = .{0} ** 7,
};
const InitOutMsg = extern struct {
head: OutHeader,
body: InitOut,
};
const GetattrIn = extern struct {
flags: u32,
dummy: u32,
fh: u64,
};
const Attr = extern struct {
ino: u64,
size: u64,
blocks: u64,
atime: u64,
mtime: u64,
ctime: u64,
atimensec: u32,
mtimensec: u32,
ctimensec: u32,
mode: u32,
nlink: u32,
uid: u32,
gid: u32,
rdev: u32,
blksize: u32,
flags: u32,
};
const AttrOut = extern struct {
valid: u64,
valid_nsec: u32,
dummy: u32,
attr: Attr,
};
const ValidAttrs = packed struct {};
const SetattrIn = extern struct {
valid: u32,
padding: u32,
fh: u64,
size: u64,
lock_owner: u64,
atime: u64,
mtime: u64,
ctime: u64,
atimensec: u32,
mtimensec: u32,
ctimensec: u32,
mode: u32,
unused4: u32,
uid: u32,
gid: u32,
unused5: u32,
};
const EntryOut = extern struct {
nodeid: u64,
generation: u64,
entry_valid: u64,
attr_valid: u64,
entry_valid_nsec: u32,
attr_valid_nsec: u32,
attr: Attr,
};
const SetxattrIn = extern struct {
size: u32,
flags: u32,
setxattr_flags: u32,
padding: u32 = 0,
};
const SetxattrInReq = struct {
hdr: SetxattrIn,
name: [:0]const u8,
value: []const u8,
};
const ForgetIn = extern struct {
nlookup: u64,
};
const Request = struct {
hdr: *InHeader,
body: union(enum) {
getattr: *GetattrIn,
setattr: *SetattrIn,
lookup: []const u8,
forget: *ForgetIn,
setxattr: SetxattrInReq,
other: Opcode,
},
};
const OutUnion = extern union {
init: InitOut,
attr: AttrOut,
entry: EntryOut,
};
pub const Response = extern struct {
hdr: OutHeader,
out: OutUnion,
pub fn init(req: Request) Response {
return Response{
.hdr = .{
.len = @sizeOf(OutHeader),
.unique = req.hdr.unique,
.err = 0,
},
.out = undefined,
};
}
pub fn err(self: *Response, e: E) void {
self.hdr.err = -@as(i32, @intFromEnum(e));
}
pub fn send(self: Response, fd: os.fd_t) !void {
var to_write: []const u8 align(1) = mem.asBytes(&self)[0..self.hdr.len];
while (to_write.len > 0) {
const written = try os.write(fd, to_write);
to_write = to_write[written..];
}
}
};
comptime {
assert(@sizeOf(Response) == @sizeOf(OutHeader) + @sizeOf(OutUnion));
}
const MNT = struct {
const NOSUID = 0x02;
const NODEV = 0x04;
const NOEXEC = 0x08;
};
pub const Ops = struct {
onSetxattr: ?fn (name: [:0]const u8, value: []const u8) void,
};
const S = @This();
const XATTR_NAME: [:0]const u8 = "user.bar";
dev: fs.File,
path: [fs.MAX_PATH_BYTES - 1:0]u8,
read_len: usize = 0,
read_buf: [MIN_READ_BUFFER * 2]u8 align(@alignOf(InHeader)) = undefined,
fn umount(self: S) void {
const ret = os.errno(l.umount(&self.path));
if (ret != .SUCCESS)
log.err("fuse: umount {s}: {}", .{ &self.path, ret });
}
pub fn init(dir: fs.Dir) !S {
var self = blk: {
var real_path_buf: [fs.MAX_PATH_BYTES]u8 = undefined;
const path = try dir.realpath(".", &real_path_buf);
break :blk S{
.dev = try fs.openFileAbsolute("/dev/fuse", .{ .mode = .read_write }),
.path = try os.toPosixPath(path),
};
};
const fd = self.dev.handle;
{
const uid = l.geteuid();
const gid = l.getegid();
var buf: [64]u8 = .{0} ** 64;
const opts = try std.fmt.bufPrintZ(&buf, "fd={},rootmode=40000,user_id={},group_id={}", .{ self.dev.handle, uid, gid });
const ret = l.mount("fuse", &self.path, "fuse.fuse", MNT.NODEV | MNT.NOSUID, @intFromPtr(opts.ptr));
const err = os.errno(ret);
if (err != .SUCCESS) {
log.err("fuse: mount {s}: {}", .{ &self.path, err });
unreachable;
}
errdefer self.umount();
}
{
var buf: []u8 = &self.read_buf;
const len = try os.read(fd, buf);
assert(len >= @sizeOf(InHeader) + @sizeOf(InitIn));
const hdr = mem.bytesAsValue(InHeader, buf[0..@sizeOf(InHeader)]);
log.info("kernel: hdr: {}", .{hdr.*});
const opcode: Opcode = @enumFromInt(hdr.opcode);
assert(opcode == .INIT);
assert(hdr.len == @sizeOf(InHeader) + @sizeOf(InitIn));
self.read_len = len - hdr.len;
const req = mem.bytesAsValue(InitIn, (buf[@sizeOf(InHeader)..][0..@sizeOf(InitIn)]));
log.info("kernel: init: {}", .{req.*});
assert(req.major == 7);
assert(req.minor == 37);
const res = InitOutMsg{
.head = .{
.len = @sizeOf(InitOutMsg),
.err = 0,
.unique = hdr.unique,
},
.body = .{
.major = 7,
.minor = 37,
.max_readahead = req.max_readahead,
.flags = req.flags,
.flags2 = req.flags2,
.max_background = 0,
.congestion_threshold = 0,
.max_write = 4096,
.time_gran = 0,
.max_pages = 1,
.map_alignment = 1,
},
};
log.info("fuse: init: {}", .{res});
assert(try os.write(fd, mem.asBytes(&res)) == @sizeOf(@TypeOf(res)));
mem.copyForwards(u8, buf, buf[@sizeOf(InHeader) + @sizeOf(InitIn) ..]);
}
return self;
}
pub fn deinit(self: S) void {
self.dev.close();
self.umount();
}
pub fn start_read_req(self: *S) !Request {
const buf: []align(@alignOf(InHeader)) u8 = &self.read_buf;
const fd = self.dev.handle;
while (self.read_len < @sizeOf(InHeader)) {
self.read_len += if (self.read_len < @sizeOf(InHeader))
try os.read(fd, buf[self.read_len..])
else
0;
}
const hdr = mem.bytesAsValue(InHeader, buf[0..@sizeOf(InHeader)]);
log.info("kernel: hdr: {}", .{hdr});
const opcode: Opcode = @enumFromInt(hdr.opcode);
log.info("kernel: opcode: {}", .{opcode});
assert(hdr.len <= MIN_READ_BUFFER);
while (hdr.len > self.read_len)
self.read_len += try os.read(fd, buf[self.read_len..]);
const msg = buf[@sizeOf(InHeader)..hdr.len];
const msg_len = hdr.len - @sizeOf(InHeader);
var req = Request{
.hdr = hdr,
.body = .{ .other = opcode },
};
switch (opcode) {
.GETATTR => {
const getattr_in =
mem.bytesAsValue(GetattrIn, msg[0..@sizeOf(GetattrIn)]);
log.info("kernel: getattr: {}", .{getattr_in});
req.body = .{ .getattr = getattr_in };
},
.SETATTR => {
const setattr_in =
mem.bytesAsValue(SetattrIn, msg[0..@sizeOf(SetattrIn)]);
log.info("kernel: setattr: {}", .{setattr_in});
req.body = .{ .setattr = setattr_in };
},
.LOOKUP => {
const lookup_in: []const u8 = msg[0..msg_len];
log.info("kernel: lookup: {s}", .{lookup_in});
req.body = .{ .lookup = lookup_in };
},
.FORGET => {
const forget_in = mem.bytesAsValue(ForgetIn, msg[0..@sizeOf(ForgetIn)]);
log.info("kernel: forget: {}:", .{forget_in});
req.body = .{ .forget = forget_in };
},
.SETXATTR => {
const xattr_in = mem.bytesToValue(SetxattrIn, msg[0..@sizeOf(SetxattrIn)]);
const tail = msg[@sizeOf(SetxattrIn)..];
log.info("kernel: setxattr: {}", .{xattr_in});
const name_len = msg_len - @sizeOf(SetxattrIn) - xattr_in.size;
const name = tail[0 .. name_len - 1 :0];
const value = tail[name_len..];
req.body = .{ .setxattr = .{
.hdr = xattr_in,
.name = name,
.value = value,
} };
},
else => {
log.info("fuse: Not implemented: {}", .{opcode});
},
}
return req;
}
pub fn done_read_req(self: *S, req: Request) void {
const buf: []u8 = &self.read_buf;
self.read_len -= req.hdr.len;
mem.copyForwards(u8, buf, buf[req.hdr.len..]);
}
pub fn do_default(self: *S, req: *const Request, res: *Response) !void {
_ = self;
switch (req.body) {
.getattr => {
const time: u64 = @intCast(@min(0, std.time.timestamp()));
res.out.attr = .{
.valid = 0,
.valid_nsec = 0,
.dummy = 0,
.attr = .{
.ino = req.hdr.nodeid,
.blocks = 1,
.size = 42,
.atime = time,
.mtime = time,
.ctime = time,
.atimensec = 0,
.mtimensec = 0,
.ctimensec = 0,
.mode = l.S.IFDIR | 0o666,
.nlink = 1,
.uid = l.getuid(),
.gid = l.getgid(),
.rdev = 0,
.blksize = 0,
.flags = 0,
},
};
res.hdr.len += @sizeOf(AttrOut);
},
.setattr => |setattr_in| {
const time: u64 = @intCast(@min(0, std.time.timestamp()));
res.out.attr = .{
.valid = 0,
.valid_nsec = 0,
.dummy = 0,
.attr = .{
.ino = req.hdr.nodeid,
.blocks = 1,
.size = 42,
.atime = time,
.mtime = time,
.ctime = time,
.atimensec = 0,
.mtimensec = 0,
.ctimensec = 0,
.mode = l.S.IFDIR | 0o666,
.nlink = 1,
.uid = l.getuid(),
.gid = l.getgid(),
.rdev = 0,
.blksize = 0,
.flags = 0,
},
};
const v = setattr_in.valid;
if (v & ~(FATTR.ATIME | FATTR.MTIME | FATTR.CTIME) > 0) {
log.info("setattr: setting attributes not supported", .{});
res.hdr.err = -@as(i32, @intFromEnum(E.OPNOTSUPP));
} else {
res.hdr.len += @sizeOf(AttrOut);
}
},
.lookup => |lookup_in| blk: {
const Static = struct {
var generation: u64 = 0;
};
if (!mem.eql(u8, "foo", lookup_in[0..3])) {
res.hdr.err = -@as(i32, @intFromEnum(E.NOENT));
break :blk;
}
const time: u64 = @intCast(@min(0, std.time.timestamp()));
Static.generation += 1;
res.out.entry = .{
.nodeid = 0xf00 + Static.generation - 1,
.generation = Static.generation,
.entry_valid = 1000,
.entry_valid_nsec = 0,
.attr_valid = 1000,
.attr_valid_nsec = 0,
.attr = .{
.ino = 0xf00,
.blocks = 1,
.size = 420,
.atime = time,
.mtime = time,
.ctime = time,
.atimensec = 0,
.mtimensec = 0,
.ctimensec = 0,
.mode = l.S.IFREG | 0o666,
.nlink = 1,
.uid = l.getuid(),
.gid = l.getgid(),
.rdev = 0,
.blksize = 0,
.flags = 0,
},
};
res.hdr.len += @sizeOf(EntryOut);
},
.forget => {},
.setxattr => unreachable,
.other => |opcode| {
log.err("fuse: Op not supported: {}", .{opcode});
res.hdr.err = -@as(i32, @intFromEnum(E.OPNOTSUPP));
},
}
}
pub fn do_one(self: *S, comptime ops: Ops) !void {
const req = try self.start_read_req();
var res = Response.init(req);
switch (req.body) {
.setxattr => |xattr| {
if (ops.onSetxattr != null)
ops.onSetxattr.?(xattr.name, xattr.value);
},
else => try do_default(self, &req, &res),
}
try res.send(self.dev.handle);
self.done_read_req(req);
}
pub fn more(self: *S) !bool {
var fds = [_]os.pollfd{
.{
.fd = self.dev.handle,
.events = os.POLL.IN,
.revents = 0,
},
};
const len = try os.poll(&fds, 10);
assert(len < 2);
assert(len == 0 or fds[0].revents & os.POLL.IN != 0);
return len == 1;
}
pub fn getTmpDir(env: std.process.EnvMap) !fs.Dir {
const tmp_dir_path = env.get("TMPDIR") orelse "/tmp";
return try fs.openDirAbsolute(tmp_dir_path, .{});
}
pub fn mkTmpDir(basename: []const u8, env: std.process.EnvMap) !fs.Dir {
var tmp_dir = try getTmpDir(env);
defer tmp_dir.close();
tmp_dir.makeDir(basename) catch |err| {
if (err != error.PathAlreadyExists)
return err;
};
return try tmp_dir.openDir(basename, .{});
}
pub fn realPosixPath(dir: fs.Dir, path: []const u8) ![fs.MAX_PATH_BYTES - 1:0]u8 {
var buf: [os.PATH_MAX]u8 = .{0} ** os.PATH_MAX;
return try os.toPosixPath(try dir.realpath(path, &buf));
}
const TestEnv = struct {
dir: fs.Dir,
const allc = std.testing.allocator;
pub fn init() !TestEnv {
var env = try std.process.getEnvMap(allc);
defer env.deinit();
return .{
.dir = try mkTmpDir("fuse-test", env),
};
}
pub fn deinit(self: *TestEnv) void {
self.dir.close();
}
};
test "init" {
var env = try TestEnv.init();
defer env.deinit();
var mnt = try init(env.dir);
defer mnt.deinit();
assert(!try mnt.more());
}
pub fn setxattr(path: [*:0]const u8, name: [*:0]const u8, value: []const u8, size: usize, flags: usize) usize {
return l.syscall5(.setxattr, @intFromPtr(path), @intFromPtr(name), @intFromPtr(value.ptr), size, flags);
}
fn setXAttr(env: *const TestEnv) void {
const path_c = os.toPosixPath("/tmp/fuse-test/foo") catch |err| {
log.err("setxattr: toPosixPath: {}", .{err});
return;
};
const res = setxattr(@ptrCast(&path_c), XATTR_NAME, "baz", 3, 0);
const err = os.errno(res);
log.info("setxattr: {}: {}", .{ env.dir, err });
}
fn setXAttrOp(name: [:0]const u8, value: []const u8) void {
log.info("kernel: setxattr: [{}]{s} => {s}", .{ name.len, name, value });
assert(mem.eql(u8, XATTR_NAME, name));
assert(mem.eql(u8, "baz", value));
}
test "one" {
var env = try TestEnv.init();
defer env.deinit();
var mnt = try init(env.dir);
defer mnt.deinit();
log.info("init: {}", .{env.dir});
var thread = try std.Thread.spawn(.{}, setXAttr, .{&env});
const ops = Ops{ .onSetxattr = setXAttrOp };
try mnt.do_one(ops);
try mnt.do_one(ops);
try mnt.do_one(ops);
try mnt.do_one(ops);
assert(!try mnt.more());
thread.join();
}