diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 00:44:58 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 10:06:26 -0300 |
| commit | 67fa2a1f2e6057bbce7441a16ebab84848f623ae (patch) | |
| tree | 515f38c20566fb14f126d057fb7ad11f14349c96 /src | |
| parent | 0702e33bcfadf0abd9ccbaa8b681a19a84c332fe (diff) | |
| download | cloud9-67fa2a1f2e6057bbce7441a16ebab84848f623ae.tar.gz cloud9-67fa2a1f2e6057bbce7441a16ebab84848f623ae.zip | |
Fsys: a blocking client on a socket, by path, with the server's words
Every program that serves a cloud9 tree should be drivable through it from
its own binary and from agents, and pardes, 9ns and pardes's Python tests
each carried a blocking client of their own. Fsys is the one the library
lacked, plan9port's lib9pclient over `Client`: dial a name posted in the
registry (a subdirectory entry such as pardes/main included), unix!PATH or
tcp!HOST!PORT; open, create, remove, stat, read, write and clunk by path and
fid; readFile, writeFile and ask (write, then read the answer on the same
open from the start, as Plan 9 reads /net/cs) streaming into a
std.Io.Writer, flushed per answer, so an event file whose reads park streams as it comes. A refusal is
error.Refused and said() holds the server's words, which a mount would have
turned into an errno.
Taken from pardes's Client (src/9p_io.zig): the walk sent ahead of the
request that uses its fid, the clunk not waited for, and the answers of
both checked or dropped on the way to the request's, so an open, a stat or
a remove is one round trip; error words kept as the server said them. Not
taken: its kept-connection table, flights of read-ahead, the stat-length
end of file and its pardes-only dials. From 9ns: the chunked read/write
loops and the iounit. Buffers inline (2 x 64 KiB), no allocator, std.Io
streams only, so it builds without libc.
TestTree.zig is a small tree on serve.Runner for these tests and the next
change's. Tests over a Unix socket and TCP against cloud9's own engine:
whole files longer than a message, stats, walks longer than 16 names, a
missing first name and a walk short of its names refused in the server's
words, a refused write whose words reach the caller, a short read that is
not the end, ask, a held read streaming three chunks flushed one at a time,
a server that hangs up mid-read, create and remove, a directory decoded as
entries, dial by posted name and a name that climbs out of the registry.
Diffstat (limited to 'src')
| -rw-r--r-- | src/Fsys.zig | 582 | ||||
| -rw-r--r-- | src/TestTree.zig | 232 | ||||
| -rw-r--r-- | src/root.zig | 2 |
3 files changed, 816 insertions, 0 deletions
diff --git a/src/Fsys.zig b/src/Fsys.zig new file mode 100644 index 0000000..224087b --- /dev/null +++ b/src/Fsys.zig @@ -0,0 +1,582 @@ +//! A blocking 9P2000 client: one connection to one tree, its calls made +//! one at a time from one thread, each waiting for its answer +//! (plan9port's lib9pclient `CFsys`). `Client` speaks the protocol; this +//! adds the socket, the fids and the server's words. A refusal is +//! `error.Refused` and `said()` is what the server said: the string a +//! mount would have turned into an errno. +//! +//! Paths are slash-separated names from the tree's root ("pane/3/body"). +//! The walk to a path goes out with the request that uses it, in one +//! write (a walk never parks, so the request always follows it), and a +//! fid is let go of without waiting for the answer: an open, a stat or a +//! remove costs one round trip. The buffers are in the struct +//! (2 × `msize`): an `Fsys` stays where it is while it is used. +const std = @import("std"); +const Io = std.Io; +const c9 = @import("root.zig"); +const wire = @import("wire.zig"); +const client = @import("client.zig"); +const transport = @import("transport.zig"); +const post = @import("post.zig"); +const fs = @import("fs.zig"); +const Client = client.Client; +const Stat = wire.Stat; +const Qid = wire.Qid; +const max_welem = wire.max_welem; + +const Fsys = @This(); + +/// The largest message asked for; the server may answer less. +pub const msize: u32 = 65536; + +pub const Error = error{ + /// The server refused: `said()` holds its words. + Refused, + /// The connection ended. + Hangup, + /// The server broke the protocol, or a request could not be made + /// (a name with a slash or longer than a message). + Botch, +}; + +io: Io, +stream: Io.net.Stream, +cl: Client, +in: [msize]u8, +out: [msize]u8, +next_fid: u32, +/// Clunks sent and not waited for, a bit per tag: their answers are +/// dropped as they come. +unwaited: u32, +/// The walk sent ahead of the request that uses its fid, and the names +/// it asked for: `rpc` checks its answer on the way to the request's. +walk_tag: u16, +walk_asked: usize, +words: [fs.errmax]u8, +words_len: usize, + +/// Speaks 9P on `stream`, which is this one's from here (`close`), on a +/// refusal too: the version, then an attach as `uname` to the tree's root. +pub fn init(f: *Fsys, io: Io, stream: Io.net.Stream, uname: []const u8) Error!void { + f.io = io; + f.stream = stream; + f.cl = .init(.{ .in = &f.in, .out = &f.out }); + f.next_fid = 1; + f.unwaited = 0; + f.walk_tag = wire.notag; + f.walk_asked = 0; + f.words_len = 0; + errdefer f.close(); + const v = (try f.rpc(.{ .version = .{ .msize = msize } })).version; + if (!std.mem.eql(u8, v.version, "9P2000")) return f.refuse("the server does not speak 9P2000"); + _ = try f.rpc(.{ .attach = .{ .fid = 0, .uname = uname } }); +} + +pub const DialError = error{ + /// Not `unix!PATH`, `tcp!HOST!PORT`, an absolute path or a legal name. + BadAddress, + /// $XDG_RUNTIME_DIR is unset, so there is no registry to find a name in. + NotRuntimeDir, +} || Error || Io.net.IpAddress.ConnectError || Io.net.UnixAddress.ConnectError || Io.net.UnixAddress.InitError; + +/// Dials `dest` and attaches (`init`). `unix!PATH`, or a path starting +/// with a slash, is a Unix socket; `tcp!HOST!PORT` a numeric address; +/// anything else a name posted in the registry (`post`), which may name +/// an entry of a subdirectory: `pardes/main` is +/// `$XDG_RUNTIME_DIR/9p/pardes/main`. +pub fn dial(f: *Fsys, io: Io, env: post.Env, dest: []const u8, uname: []const u8) DialError!void { + var buf: [transport.sun_path_len]u8 = undefined; + const address: transport.Address = if (std.mem.startsWith(u8, dest, "tcp!")) blk: { + const bang = std.mem.lastIndexOfScalar(u8, dest, '!').?; + if (bang < 5) return error.BadAddress; + const port = std.fmt.parseInt(u16, dest[bang + 1 ..], 10) catch return error.BadAddress; + break :blk .{ .tcp = Io.net.IpAddress.parse(dest[4..bang], port) catch return error.BadAddress }; + } else if (std.mem.startsWith(u8, dest, "unix!") or std.mem.startsWith(u8, dest, "/")) blk: { + const path = if (dest[0] == '/') dest else dest["unix!".len..]; + break :blk .{ .unix = std.fmt.bufPrintSentinel(&buf, "{s}", .{path}, 0) catch return error.BadAddress }; + } else blk: { + var it = std.mem.splitScalar(u8, dest, '/'); + while (it.next()) |name| if (!post.legalName(name)) return error.BadAddress; + var dir_buf: [transport.sun_path_len]u8 = undefined; + const dir = post.registryDir(env, &dir_buf) catch |err| switch (err) { + error.NotRuntimeDir => return error.NotRuntimeDir, + else => return error.BadAddress, + }; + break :blk .{ .unix = std.fmt.bufPrintSentinel(&buf, "{s}/{s}", .{ dir, dest }, 0) catch return error.BadAddress }; + }; + try f.init(io, try transport.connect(io, address), uname); +} + +/// Hangs up: the server lets go of every fid. +pub fn close(f: *Fsys) void { + f.stream.close(f.io); +} + +/// The server's words for the last `error.Refused`. +pub fn said(f: *const Fsys) []const u8 { + return f.words[0..f.words_len]; +} + +pub const Opened = struct { fid: u32, qid: Qid, iounit: u32 }; + +/// Opens `path` with `mode` (`cloud9.oread`, `owrite`, `ordwr`, with +/// `otrunc` and the rest): its fid, which `clunk` lets go of. +pub fn open(f: *Fsys, path: []const u8, mode: u8) Error!Opened { + const fid = try f.walkAhead(path); + errdefer f.clunk(fid); + const o = (try f.rpc(.{ .open = .{ .fid = fid, .mode = mode } })).open; + return .{ .fid = fid, .qid = o.qid, .iounit = o.iounit }; +} + +/// Creates `path` in its directory with `perm` (`cloud9.dmdir` for a +/// directory) and opens it with `mode`. +pub fn create(f: *Fsys, path: []const u8, perm: u32, mode: u8) Error!Opened { + const trimmed = std.mem.trim(u8, path, "/"); + const slash = std.mem.lastIndexOfScalar(u8, trimmed, '/'); + const fid = try f.walkAhead(if (slash) |s| trimmed[0..s] else ""); + errdefer f.clunk(fid); + const name = if (slash) |s| trimmed[s + 1 ..] else trimmed; + const c = (try f.rpc(.{ .create = .{ .fid = fid, .name = name, .perm = perm, .mode = mode } })).create; + return .{ .fid = fid, .qid = c.qid, .iounit = c.iounit }; +} + +/// Removes `path`. +pub fn remove(f: *Fsys, path: []const u8) Error!void { + // The fid is gone whatever the answer. + _ = try f.rpc(.{ .remove = .{ .fid = try f.walkAhead(path) } }); +} + +/// The stat of `path`; its strings are good until the next call. +pub fn stat(f: *Fsys, path: []const u8) Error!Stat { + const fid = try f.walkAhead(path); + defer f.clunk(fid); + return (try f.rpc(.{ .stat = .{ .fid = fid } })).stat; +} + +/// One Tread of up to `count` bytes (and the message size) at `offset`: +/// the bytes, good until the next call; none at the end. +pub fn read(f: *Fsys, fid: u32, offset: u64, count: u32) Error![]const u8 { + return (try f.rpc(.{ .read = .{ .fid = fid, .offset = offset, .count = @min(count, f.cl.maxRead()) } })).read; +} + +/// One Twrite of as much of `bytes` as a message holds: the count written. +pub fn write(f: *Fsys, fid: u32, offset: u64, bytes: []const u8) Error!u32 { + const n = @min(bytes.len, f.cl.maxWrite()); + return (try f.rpc(.{ .write = .{ .fid = fid, .offset = offset, .data = bytes[0..n] } })).write; +} + +/// Lets go of `fid`, without waiting for the answer. +pub fn clunk(f: *Fsys, fid: u32) void { + const tag = f.cl.submit(.{ .clunk = .{ .fid = fid } }) catch return; + if (tag < 32) f.unwaited |= @as(u32, 1) << @intCast(tag); + f.ship() catch {}; +} + +/// The file at `path`, read from the start until a read comes back +/// empty, into `out`, flushed after each answer: a file whose reads the +/// server parks (an event file) streams as it comes. +pub fn readFile(f: *Fsys, path: []const u8, out: *Io.Writer) (Error || Io.Writer.Error)!void { + const o = try f.open(path, c9.oread); + defer f.clunk(o.fid); + try f.drain(o, out); +} + +/// `bytes` as the whole of the file at `path`, as `>` would put them: +/// opened truncated, written in as many writes as it takes. +pub fn writeFile(f: *Fsys, path: []const u8, bytes: []const u8) Error!void { + const o = try f.open(path, c9.owrite | c9.otrunc); + defer f.clunk(o.fid); + try f.put(o, bytes); +} + +/// Writes `request` to `path` and reads the answer on the same open from +/// the start, into `out` (as `readFile`): Plan 9's write, seek 0, read of +/// /net/cs. An answer that never ends (a log written `follow`) streams +/// until the server hangs up. +pub fn ask(f: *Fsys, path: []const u8, request: []const u8, out: *Io.Writer) (Error || Io.Writer.Error)!void { + const o = try f.open(path, c9.ordwr); + defer f.clunk(o.fid); + try f.put(o, request); + try f.drain(o, out); +} + +/// Directory entries as a directory read answers them: `next` decodes +/// them one at a time (their strings borrow the bytes). +pub const Entries = struct { + bytes: []const u8, + pos: usize = 0, + + pub fn next(e: *Entries) Error!?Stat { + if (e.pos == e.bytes.len) return null; + if (e.bytes.len - e.pos < 2) return error.Botch; + const len = 2 + @as(usize, std.mem.readInt(u16, e.bytes[e.pos..][0..2], .little)); + if (len > e.bytes.len - e.pos) return error.Botch; + defer e.pos += len; + return Stat.decode(e.bytes[e.pos..][0..len]) catch error.Botch; + } +}; + +// ---- internals ---- + +/// Writes all of `bytes` from the start, in writes no larger than the +/// open's iounit. +fn put(f: *Fsys, o: Opened, bytes: []const u8) Error!void { + var done: usize = 0; + while (done < bytes.len) { + const chunk = bytes[done..][0..@min(bytes.len - done, if (o.iounit != 0) o.iounit else bytes.len)]; + const n = try f.write(o.fid, done, chunk); + if (n == 0) return f.refuse("short write"); + done += n; + } +} + +/// Reads from the start until a read comes back empty, each answer into +/// `out` and flushed. +fn drain(f: *Fsys, o: Opened, out: *Io.Writer) (Error || Io.Writer.Error)!void { + var at: u64 = 0; + while (true) { + const data = try f.read(o.fid, at, if (o.iounit != 0) o.iounit else msize); + if (data.len == 0) return; + try out.writeAll(data); + try out.flush(); + at += data.len; + } +} + +/// A new fid for `path`. Its walk (the last 16 names of it) is sent and +/// not waited for: the next `rpc` sends its request behind it and checks +/// its answer first. Names before the last 16 are walked a round trip +/// each, the fid stepping from itself. +fn walkAhead(f: *Fsys, path: []const u8) Error!u32 { + f.words_len = 0; + const fid = f.next_fid; + f.next_fid = if (fid == std.math.maxInt(u32) - 1) 1 else fid + 1; + var it = std.mem.tokenizeScalar(u8, path, '/'); + var from: u32 = 0; + while (true) { + var names: [max_welem][]const u8 = undefined; + var n: usize = 0; + while (n < names.len) : (n += 1) names[n] = it.next() orelse break; + if (it.peek() == null) { + f.walk_tag = f.cl.submit(.{ .walk = .{ .fid = from, .newfid = fid, .names = names[0..n] } }) catch return error.Botch; + f.walk_asked = n; + return fid; + } + const w = f.rpc(.{ .walk = .{ .fid = from, .newfid = fid, .names = names[0..n] } }) catch |err| { + if (from != 0) f.clunk(fid); + return err; + }; + if (w.walk.nwqid < n) { + if (from != 0) f.clunk(fid); + return f.refuse(fs.errString(fs.E.NOENT)); + } + from = fid; + } +} + +/// Sends what the client holds, then reads until `req` is answered. On +/// the way, the answer of a walk sent ahead is checked (a refusal or a +/// walk short of its names is this call's refusal: the request behind it +/// had no fid) and those of unwaited clunks are dropped. +fn rpc(f: *Fsys, req: Client.Request) Error!Client.Result { + if (f.walk_tag == wire.notag) f.words_len = 0; + const tag = f.cl.submit(req) catch { + // A request that cannot be made (a name too long for a message): + // the walk ahead of it still goes, its answer not waited for. + if (f.walk_tag < 32) f.unwaited |= @as(u32, 1) << @intCast(f.walk_tag); + f.walk_tag = wire.notag; + return error.Botch; + }; + try f.ship(); + while (true) { + const done = try f.next(); + if (f.walk_tag != wire.notag and done.tag == f.walk_tag) { + f.walk_tag = wire.notag; + switch (done.result) { + .fail => |words| f.keep(words), + .walk => |w| if (w.nwqid < f.walk_asked) f.keep(fs.errString(fs.E.NOENT)), + else => return error.Botch, + } + continue; + } + if (done.tag == tag) { + if (f.words_len != 0) return error.Refused; + return switch (done.result) { + .fail => |words| f.refuse(words), + else => done.result, + }; + } + if (done.tag < 32 and f.unwaited & @as(u32, 1) << @intCast(done.tag) != 0) { + f.unwaited &= ~(@as(u32, 1) << @intCast(done.tag)); + continue; + } + return error.Botch; + } +} + +/// The next answer, read from the socket as it takes; its slices are +/// good until the next. +fn next(f: *Fsys) Error!Client.Done { + while (true) { + if (f.cl.take()) |done| return done; + if (f.cl.dead) return error.Botch; + // take() found no whole frame and the client has dropped the last + // one, so the free end of its input is where the next bytes go + // (what `push` would copy them to). + var room = [1][]u8{f.cl.in[f.cl.in_len..]}; + if (room[0].len == 0) return error.Botch; + const n = f.stream.read(f.io, &room) catch return error.Hangup; + if (n == 0) return error.Hangup; + f.cl.in_len += n; + } +} + +fn ship(f: *Fsys) Error!void { + var w = f.stream.writer(f.io, &.{}); + const bytes = f.cl.output(); + w.interface.writeAll(bytes) catch return error.Hangup; + f.cl.wrote(bytes.len); +} + +/// Keeps `words` as the refusal, unless one is kept already (the walk's, +/// before the request it failed). +fn keep(f: *Fsys, words: []const u8) void { + if (f.words_len != 0) return; + f.words_len = @min(words.len, f.words.len); + @memcpy(f.words[0..f.words_len], words[0..f.words_len]); +} + +fn refuse(f: *Fsys, words: []const u8) error{Refused} { + f.keep(words); + return error.Refused; +} + +// ---- tests: against cloud9's own engine, served by `serve.Runner` ---- + +const testing = std.testing; +const TestTree = @import("TestTree.zig"); + +const no_env = [_:null]?[*:0]const u8{}; + +const Dest = enum { unix, tcp }; + +fn dialed(t: *TestTree, dest: Dest) !*Fsys { + const f = try testing.allocator.create(Fsys); + errdefer testing.allocator.destroy(f); + var buf: [128]u8 = undefined; + const address = switch (dest) { + .unix => try std.fmt.bufPrint(&buf, "unix!{s}", .{t.unix}), + .tcp => try std.fmt.bufPrint(&buf, "tcp!127.0.0.1!{d}", .{t.tcp.getPort()}), + }; + try f.dial(testing.io, &no_env, address, "glenda"); + return f; +} + +fn hangUp(f: *Fsys) void { + f.close(); + testing.allocator.destroy(f); +} + +fn readAll(f: *Fsys, path: []const u8) ![]u8 { + var out: Io.Writer.Allocating = .init(testing.allocator); + errdefer out.deinit(); + try f.readFile(path, &out.writer); + return out.toOwnedSlice(); +} + +test "fsys: whole files, stats and walks over a Unix socket and TCP" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + for ([_]Dest{ .unix, .tcp }) |dest| { + const f = try dialed(t, dest); + defer hangUp(f); + const readme = try readAll(f, "README"); + defer testing.allocator.free(readme); + try testing.expectEqualStrings(TestTree.readme, readme); + // Longer than a message (the server's is 8192): read on to the end. + const big = try readAll(f, "/big"); + defer testing.allocator.free(big); + try testing.expectEqual(TestTree.big_len, big.len); + for (big, 0..) |b, i| if (b != TestTree.bigByte(i)) return error.TestUnexpectedResult; + try testing.expectEqualStrings("deep", (try f.stat("sub/deep")).name); + try testing.expectEqual(@as(u64, TestTree.readme.len), (try f.stat("README")).length); + // More names than a walk carries: the first 16 a round trip of their own. + try testing.expectEqualStrings("deep", (try f.stat("sub/../sub/../sub/../sub/../sub/../sub/../sub/../sub/../sub/../sub/deep")).name); + try testing.expectError(error.Refused, f.stat("nowhere")); + try testing.expectEqualStrings("No such file or directory", f.said()); + // A walk short of its names is refused in the same words. + try testing.expectError(error.Refused, f.stat("sub/nowhere")); + try testing.expectEqualStrings("No such file or directory", f.said()); + try testing.expectError(error.Refused, f.stat("sub/../sub/../sub/../sub/../sub/../sub/../sub/../sub/../sub/../nowhere/deep")); + // Refusals leave the connection as good as before. + try testing.expectEqualStrings("README", (try f.stat("README")).name); + } +} + +test "fsys: a refused write's words reach the caller" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + try testing.expectError(error.Refused, f.writeFile("ctl", "bogus\n")); + try testing.expectEqualStrings("unknown command: bogus", f.said()); + try f.writeFile("ctl", "ok\n"); + const ctl = try readAll(f, "ctl"); + defer testing.allocator.free(ctl); + try testing.expectEqualStrings("ok\n", ctl); + try testing.expectError(error.Refused, f.writeFile("README", "x")); + try testing.expectEqualStrings("permission denied", f.said()); +} + +test "fsys: a short read is not the end of the file" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + const short = try readAll(f, "short"); + defer testing.allocator.free(short); + try testing.expectEqualStrings("a short answer, three bytes a read", short); + // One Tread is one answer, a short one included. + const o = try f.open("short", c9.oread); + defer f.clunk(o.fid); + try testing.expectEqualStrings("a s", try f.read(o.fid, 0, 100)); +} + +test "fsys: ask reads the answer on the open it wrote, from the start" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + var out: Io.Writer.Allocating = .init(testing.allocator); + defer out.deinit(); + try f.ask("echo", "hello\n", &out.writer); + try testing.expectEqualStrings("heard hello\n", out.written()); +} + +test "fsys: a read the server holds streams three chunks, then its end" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + const Feeder = struct { + fn run(tree: *TestTree) anyerror!void { + for ([_][]const u8{ "new 1\n", "del 2\n", "new 3\n", "" }) |chunk| try tree.feed(chunk); + } + }; + var feeder = try testing.io.concurrent(Feeder.run, .{t}); + defer _ = feeder.cancel(testing.io) catch {}; + // Each chunk is flushed as it comes: a writer that marks its flushes. + const Marked = struct { + w: Io.Writer, + marks: [8]usize = undefined, + n: usize = 0, + fn flush(w: *Io.Writer) Io.Writer.Error!void { + const m: *@This() = @fieldParentPtr("w", w); + m.marks[m.n] = w.end; + m.n += 1; + } + }; + var store: [64]u8 = undefined; + var marked: Marked = .{ .w = .{ .vtable = &.{ .drain = Io.Writer.fixedDrain, .flush = Marked.flush }, .buffer = &store } }; + const out = &marked.w; + try f.ask("event", "follow\n", out); + try testing.expectEqualStrings("new 1\ndel 2\nnew 3\n", out.buffered()); + try testing.expectEqualSlices(usize, &.{ 6, 12, 18 }, marked.marks[0..marked.n]); + try feeder.await(testing.io); +} + +test "fsys: a server that goes away mid-read is a hangup" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + const Feeder = struct { + fn run(tree: *TestTree) anyerror!void { + try tree.feed("first\n"); + try tree.feed(null); + } + }; + var feeder = try testing.io.concurrent(Feeder.run, .{t}); + defer _ = feeder.cancel(testing.io) catch {}; + var store: [64]u8 = undefined; + var out: Io.Writer = .fixed(&store); + try testing.expectError(error.Hangup, f.readFile("event", &out)); + try testing.expectEqualStrings("first\n", out.buffered()); + try feeder.await(testing.io); +} + +test "fsys: create, write, remove" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + const o = try f.create("/new", 0o600, c9.owrite); + try testing.expectEqual(@as(u32, 3), try f.write(o.fid, 0, "abc")); + f.clunk(o.fid); + try testing.expectError(error.Refused, f.create("new", 0o600, c9.owrite)); + try testing.expectEqualStrings("File exists", f.said()); + try f.remove("new"); + try testing.expectError(error.Refused, f.stat("new")); + try testing.expectError(error.Refused, f.remove("README")); + // A name no message holds is not sent, and the walk sent ahead of it + // does not stand in the way of the next call. + const long: [9000]u8 = @splat('x'); + try testing.expectError(error.Botch, f.create(&long, 0o600, c9.owrite)); + try testing.expectEqualStrings("README", (try f.stat("README")).name); +} + +test "fsys: a directory read decodes as entries" { + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + const f = try dialed(t, .unix); + defer hangUp(f); + const o = try f.open("", c9.oread); + defer f.clunk(o.fid); + try testing.expect(o.qid.type & wire.qtdir != 0); + var names: [8][]const u8 = undefined; + var n: usize = 0; + var entries: Entries = .{ .bytes = try f.read(o.fid, 0, msize) }; + while (try entries.next()) |st| : (n += 1) names[n] = st.name; + try testing.expectEqual(@as(usize, 7), n); + try testing.expectEqualStrings("README", names[0]); + try testing.expectEqualStrings("sub", names[6]); +} + +test "fsys: dial by a name posted in the registry, and refuse a name that climbs out of it" { + var dir = testing.tmpDir(.{}); + defer dir.cleanup(); + var real: [std.fs.max_path_bytes]u8 = undefined; + const len = try dir.dir.realPath(testing.io, &real); + var var_buf: [std.fs.max_path_bytes + 32]u8 = undefined; + const runtime = try std.fmt.bufPrintSentinel(&var_buf, "XDG_RUNTIME_DIR={s}", .{real[0..len]}, 0); + const env = [_:null]?[*:0]const u8{runtime.ptr}; + const t = try testing.allocator.create(TestTree); + defer testing.allocator.destroy(t); + try t.start(); + defer t.stop(); + try t.runner.listenPosted(&env, "c9test", 4); + const f = try testing.allocator.create(Fsys); + defer testing.allocator.destroy(f); + try f.dial(testing.io, &env, "c9test", "glenda"); + defer f.close(); + try testing.expectEqualStrings("README", (try f.stat("README")).name); + var g: Fsys = undefined; + try testing.expectError(error.BadAddress, g.dial(testing.io, &env, "../c9test", "glenda")); + try testing.expectError(error.NotRuntimeDir, g.dial(testing.io, &no_env, "c9test", "glenda")); +} diff --git a/src/TestTree.zig b/src/TestTree.zig new file mode 100644 index 0000000..ad75c1f --- /dev/null +++ b/src/TestTree.zig @@ -0,0 +1,232 @@ +//! A small tree served by `serve.Runner`, for the tests of Fsys.zig and +//! verbs.zig: a README in the house shape, a ctl that refuses in words, a +//! file longer than a message, one that answers a few bytes a read, one +//! that answers what was written to it, an event file whose reads are +//! held until the test feeds them, a directory, and room for one created +//! file. +const std = @import("std"); +const Io = std.Io; +const testing = std.testing; +const fs = @import("fs.zig"); +const serve = @import("serve.zig"); +const transport = @import("transport.zig"); +const post = @import("post.zig"); + +const TestTree = @This(); + +pub const Req = fs.Req; +pub const Reply = fs.Reply; +pub const features: fs.Features = .{ .create = true, .remove = true }; +pub const Runner = serve.Runner(TestTree, .{ .fid_capacity = 32, .slot_capacity = 4 }, .{ .msize = 8192, .connections = 2, .listeners = 3 }); + +pub const readme = + \\A tree for tests. + \\ + \\README this file + \\ctl write ok; anything else is refused in words + \\echo write a line, read it back heard + \\event reads wait for news + \\sub/ a directory + \\ of one file + \\sub/deep the file in it + \\ + \\ cat ctl an example, not a file + \\ +; + +pub const big_len = 200_000; + +pub fn bigByte(i: usize) u8 { + return @intCast('a' + i % 23); +} + +const Node = struct { name: []const u8, parent: u64, dir: bool = false, mode: u16 = 0o600 }; +const nodes = [_]Node{ + .{ .name = "/", .parent = 1, .dir = true, .mode = 0o700 }, + .{ .name = "README", .parent = 1, .mode = 0o400 }, + .{ .name = "ctl", .parent = 1 }, + .{ .name = "big", .parent = 1, .mode = 0o400 }, + .{ .name = "short", .parent = 1, .mode = 0o400 }, + .{ .name = "echo", .parent = 1 }, + .{ .name = "event", .parent = 1 }, + .{ .name = "sub", .parent = 1, .dir = true, .mode = 0o700 }, + .{ .name = "deep", .parent = 8 }, + .{ .name = "new", .parent = 1 }, +}; +const root = 1; +const readme_node = 2; +const ctl_node = 3; +const big_node = 4; +const short_node = 5; +const echo_node = 6; +const event_node = 7; +const new_node = 10; +const short_text = "a short answer, three bytes a read"; + +mutex: Io.Mutex = .init, +/// Whether `new` exists (made by a create, gone with a remove). +made: bool = false, +ctl: [64]u8 = undefined, +ctl_len: usize = 0, +heard: [128]u8 = undefined, +heard_len: usize = 0, +words: [fs.errmax]u8 = undefined, +/// The read of `event` held, until `feed` answers it. +held: ?struct { *Runner.Conn, fs.Ticket } = null, +dir: testing.TmpDir = undefined, +path_buf: [transport.sun_path_len]u8 = undefined, +/// The listener's socket and the TCP address, once `start` returns. +unix: [:0]const u8 = undefined, +tcp: Io.net.IpAddress = undefined, +runner: Runner = undefined, + +/// Serves the tree on a Unix socket in a temporary directory and on TCP +/// at the loopback address. +pub fn start(t: *TestTree) !void { + t.* = .{}; + t.dir = testing.tmpDir(.{}); + errdefer t.dir.cleanup(); + var real: [std.fs.max_path_bytes]u8 = undefined; + const len = try t.dir.dir.realPath(testing.io, &real); + t.unix = try std.fmt.bufPrintSentinel(&t.path_buf, "{s}/9p", .{real[0..len]}, 0); + t.runner.init(.{ .io = testing.io, .root = root, .handler = .{ .ctx = t, .serve = serveFn } }); + _ = try t.runner.listen(.{ .unix = t.unix }, 4); + t.tcp = try t.runner.listen(.{ .tcp = .{ .ip4 = .loopback(0) } }, 4); +} + +pub fn stop(t: *TestTree) void { + t.runner.stop(); + t.dir.cleanup(); +} + +/// Answers the held read of `event` with `chunk` once it is held (an empty +/// chunk is the end of the file), or with null hangs its connection up. +pub fn feed(t: *TestTree, chunk: ?[]const u8) !void { + var tries: usize = 0; + while (true) : (tries += 1) { + if (tries == 5000) return error.Timeout; + t.mutex.lockUncancelable(testing.io); + const got = t.held; + t.held = null; + t.mutex.unlock(testing.io); + const conn, const ticket = got orelse { + try testing.io.sleep(.fromMilliseconds(1), .awake); + continue; + }; + const bytes = chunk orelse return conn.close(); + const Make = struct { + fn make(b: *const []const u8) ?Runner.Conn.Answer { + return .{ .reply = .{ .tag = 0 }, .bytes = b.* }; + } + }; + _ = conn.answerWith(ticket, &bytes, Make.make); + return; + } +} + +fn attrOf(t: *const TestTree, node: u64) fs.Attr { + const n = nodes[node - 1]; + const size: u64 = switch (node) { + readme_node => readme.len, + big_node => big_len, + ctl_node => t.ctl_len, + else => 0, + }; + return .{ .name = n.name, .node = node, .dir = n.dir, .mode = n.mode, .size = size }; +} + +fn serveFn(ctx: ?*anyopaque, conn: *Runner.Conn, req: fs.Req) void { + const t: *TestTree = @ptrCast(@alignCast(ctx.?)); + if (req.op == .read and req.node == event_node) { + const ticket = conn.hold(&.{ .tag = req.tag, .status = .again }) orelse return; + t.mutex.lockUncancelable(testing.io); + defer t.mutex.unlock(testing.io); + t.held = .{ conn, ticket }; + return; + } + var buf: [8192]u8 = undefined; + var bytes: []const u8 = ""; + const reply = t.answer(req, &buf, &bytes); + conn.reply(&reply, bytes); +} + +fn answer(t: *TestTree, req: fs.Req, buf: []u8, bytes: *[]const u8) fs.Reply { + const ok: fs.Reply = .{ .tag = req.tag }; + switch (req.op) { + .lookup => { + if (std.mem.eql(u8, req.data, "..")) return .{ .tag = req.tag, .attr = t.attrOf(nodes[req.node - 1].parent) }; + for (nodes, 1..) |n, node| { + if (node == new_node and !t.made) continue; + if (node != root and n.parent == req.node and std.mem.eql(u8, n.name, req.data)) + return .{ .tag = req.tag, .attr = t.attrOf(node) }; + } + return .fail(req.tag, fs.E.NOENT); + }, + .getattr, .setattr => return .{ .tag = req.tag, .attr = t.attrOf(req.node) }, + .open => { + if (!req.create) return ok; + if (req.node != root or !std.mem.eql(u8, req.data, "new") or t.made) return .fail(req.tag, fs.E.EXIST); + t.made = true; + return .{ .tag = req.tag, .attr = t.attrOf(new_node) }; + }, + .release => { + if (req.remove) { + if (req.node != new_node) return .fail(req.tag, fs.E.PERM); + t.made = false; + } + return ok; + }, + .readdir => { + var w: Io.Writer = .fixed(buf); + var index: u64 = 0; + for (nodes, 1..) |n, node| { + if (node == root or n.parent != req.node or (node == new_node and !t.made)) continue; + defer index += 1; + if (index < req.off) continue; + w.writeInt(u64, node, .little) catch break; + w.writeByte(@intFromBool(n.dir)) catch break; + w.writeByte(@intCast(n.name.len)) catch break; + w.writeAll(n.name) catch break; + } + bytes.* = w.buffered(); + return ok; + }, + .read => { + const off: usize = @intCast(req.off); + bytes.* = switch (req.node) { + readme_node => readme[@min(off, readme.len)..], + ctl_node => t.ctl[@min(off, t.ctl_len)..t.ctl_len], + // A few bytes a read: a short read is not the end. + short_node => short_text[@min(off, short_text.len)..][0..@min(3, short_text.len -| off)], + echo_node => t.heard[@min(off, t.heard_len)..t.heard_len], + big_node => blk: { + const n = @min(big_len -| off, buf.len); + for (buf[0..n], off..) |*b, i| b.* = bigByte(i); + break :blk buf[0..n]; + }, + else => "", + }; + bytes.* = bytes.*[0..@min(bytes.len, req.size)]; + return ok; + }, + .write => switch (req.node) { + ctl_node => { + const line = std.mem.trimEnd(u8, req.data, "\n"); + if (!std.mem.eql(u8, line, "ok")) { + const words = std.fmt.bufPrint(&t.words, "unknown command: {s}", .{line}) catch &t.words; + return .{ .tag = req.tag, .status = .err, .errno = fs.E.INVAL, .ename = words }; + } + t.ctl_len = @min(req.data.len, t.ctl.len); + @memcpy(t.ctl[0..t.ctl_len], req.data[0..t.ctl_len]); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, + echo_node => { + const heard = std.fmt.bufPrint(&t.heard, "heard {s}", .{req.data}) catch return .fail(req.tag, fs.E.NOSPC); + t.heard_len = heard.len; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, + event_node, new_node => return .{ .tag = req.tag, .written = @intCast(req.data.len) }, + else => return .fail(req.tag, fs.E.PERM), + }, + } +} diff --git a/src/root.zig b/src/root.zig index 950fc26..8dc6132 100644 --- a/src/root.zig +++ b/src/root.zig @@ -52,8 +52,10 @@ pub const http = @import("http.zig"); pub const transport = @import("transport.zig"); pub const serve = @import("serve.zig"); pub const post = @import("post.zig"); +pub const Fsys = @import("Fsys.zig"); test { _ = @import("post.zig"); + _ = @import("Fsys.zig"); } pub const Quic = @import("quic.zig").Quic; test { |
