//! The `fs` verbs: a program that serves a 9P tree, or reaches one, makes //! its own binary that tree's command line in a few lines: //! //! if (args.len > 1 and std.mem.eql(u8, args[1], "fs")) { //! var f: cloud9.Fsys = undefined; //! try f.dial(io, env, session, user); //! defer f.close(); //! return cloud9.verbs.run(&f, args[2..], stdin, stdout, stderr); //! } //! //! The tree is the documentation: `ls` and `complete` list what it serves //! now, `help` prints what its own README says of a path, and a refusal //! prints the server's words. Plain text; exit status 0, or 1 with the //! words on stderr. //! //! `help PATH` reads the tree's /README. A line is about the file its //! first word names, a path from the root (a leading slash, a trailing //! slash or comma dropped; `` stands for one name), and about //! everything under it; the lines after it indented deeper go with it. //! `help PATH` prints every line about PATH, or about something under it. //! pardes's README (src/fs-help.txt), 9proc's and 9agents' are in that //! shape already. const std = @import("std"); const Io = std.Io; const c9 = @import("root.zig"); const wire = @import("wire.zig"); const Fsys = @import("Fsys.zig"); pub const usage = \\usage: fs ls [PATH] the names in a directory, a / after each directory \\ fs read PATH the file, to its end (a held read streams) \\ fs write PATH [WORDS...] the words and a newline, else stdin, as > would \\ fs ask PATH WORDS... write the words and read the answer on the same open \\ fs follow PATH [WORDS...] ask, or read: what comes, as it comes, for as long \\ fs stat PATH mode length uid gid mtime name \\ fs help [PATH] what the tree's README says of PATH \\ fs complete [PREFIX] the paths that go on from PREFIX, for a shell \\ ; const Verb = enum { ls, read, write, ask, follow, stat, help, complete }; /// Runs the verb `args[0]` with the rest of `args` on the tree `f`: its /// exit status. `in` is read by `write` with no words. pub fn run(f: *Fsys, args: []const []const u8, in: *Io.Reader, out: *Io.Writer, err: *Io.Writer) u8 { const status = runVerb(f, args, in, out, err) catch |e| blk: { const path = if (args.len > 1) args[1] else "/"; (switch (e) { error.Refused => err.print("fs: {s}: {s}\n", .{ path, f.said() }), error.Hangup => err.print("fs: {s}: the server hung up\n", .{path}), error.Botch => err.print("fs: {s}: protocol botch\n", .{path}), error.Timeout => err.print("fs: {s}: no answer in {d} ms; fs follow waits for ever\n", .{ path, if (f.timeout.toDurationFromNow(f.io)) |d| d.raw.toMilliseconds() else 0 }), error.Usage => err.writeAll(usage), error.TooLong => err.print("fs: {s}: the words are longer than a message\n", .{path}), // Our own stdin or stdout: nothing to say it on. error.ReadFailed, error.WriteFailed => {}, }) catch {}; break :blk 1; }; out.flush() catch return 1; err.flush() catch {}; return status; } const RunError = Fsys.Error || Io.Writer.Error || error{ ReadFailed, Usage, TooLong }; fn runVerb(f: *Fsys, args: []const []const u8, in: *Io.Reader, out: *Io.Writer, err: *Io.Writer) RunError!u8 { if (args.len == 0) return error.Usage; const verb = std.meta.stringToEnum(Verb, args[0]) orelse return error.Usage; const path = if (args.len > 1) args[1] else ""; const words = if (args.len > 2) args[2..] else &.{}; var line_buf: [Fsys.msize]u8 = undefined; switch (verb) { .ls => try names(f, path, "", "", out), .read => try f.readFile(path, out), .write => { if (args.len < 2) return error.Usage; if (words.len != 0) { try f.writeFile(path, try line(&line_buf, words)); return 0; } // Stdin in a write a read of it, as `9p write` sends it; none // at all is one empty write, which a ctl may take as a word. const o = try f.open(path, c9.owrite | c9.otrunc); defer f.clunk(o.fid); var at: u64 = 0; while (true) { if (in.bufferedLen() == 0) in.fillMore() catch |e| switch (e) { error.EndOfStream => break, error.ReadFailed => return error.ReadFailed, }; const chunk = in.buffered(); var done: usize = 0; while (done < chunk.len) { const n = try f.write(o.fid, at, chunk[done..]); if (n == 0) return error.Botch; done += n; at += n; } in.toss(chunk.len); } if (at == 0) _ = try f.write(o.fid, 0, ""); }, .ask => { if (words.len == 0) return error.Usage; try f.ask(path, try line(&line_buf, words), out); }, .follow => { if (args.len < 2) return error.Usage; f.timeout = .none; if (words.len == 0) try f.readFile(path, out) else try f.ask(path, try line(&line_buf, words), out); }, .stat => { if (args.len < 2) return error.Usage; const st = try f.stat(path); var mode: [11]u8 = @splat('-'); if (st.mode & wire.dmdir != 0) mode[0] = 'd'; if (st.mode & wire.dmappend != 0) mode[0] = 'a'; if (st.mode & wire.dmexcl != 0) mode[1] = 'l'; for (0..9) |i| { if (st.mode & (@as(u32, 1) << @intCast(8 - i)) != 0) mode[2 + i] = "rwx"[i % 3]; } try out.print("{s} {d} {s} {s} {d} {s}\n", .{ &mode, st.length, st.uid, st.gid, st.mtime, st.name }); }, .help => return help(f, path, out, err), .complete => { const cut = if (std.mem.lastIndexOfScalar(u8, path, '/')) |s| s + 1 else 0; try names(f, path[0..cut], path[0..cut], path[cut..], out); }, } return 0; } /// The words, a blank between each, and a newline: what echo writes. fn line(buf: []u8, words: []const []const u8) error{TooLong}![]const u8 { var w: Io.Writer = .fixed(buf); for (words, 0..) |word, i| w.print("{s}{s}", .{ if (i == 0) "" else " ", word }) catch return error.TooLong; w.writeByte('\n') catch return error.TooLong; return w.buffered(); } /// The names in the directory `dir` that start with `part`, each after /// `prefix` and before a slash when it is a directory, a line each. A /// file is its own name. fn names(f: *Fsys, dir: []const u8, prefix: []const u8, part: []const u8, out: *Io.Writer) RunError!void { const o = try f.open(dir, c9.oread); defer f.clunk(o.fid); if (o.qid.type & wire.qtdir == 0) return out.print("{s}\n", .{dir}); var at: u64 = 0; while (true) { const bytes = try f.read(o.fid, at, Fsys.msize); if (bytes.len == 0) return; at += bytes.len; var entries: Fsys.Entries = .{ .bytes = bytes }; while (try entries.next()) |st| { if (!std.mem.startsWith(u8, st.name, part)) continue; try out.print("{s}{s}{s}\n", .{ prefix, st.name, if (st.qid.type & wire.qtdir != 0) "/" else "" }); } } } fn help(f: *Fsys, path: []const u8, out: *Io.Writer, err: *Io.Writer) RunError!u8 { // A README longer than this is helped from its start. var buf: [64 * 1024]u8 = undefined; var readme: Io.Writer = .fixed(&buf); f.readFile("README", &readme) catch |e| switch (e) { error.WriteFailed => {}, else => |other| return other, }; const want = std.mem.trim(u8, path, "/"); if (want.len == 0) { try out.writeAll(readme.buffered()); return 0; } var found = false; // The indentation of the line whose deeper lines go with it. var going: ?usize = null; var lines = std.mem.splitScalar(u8, readme.buffered(), '\n'); while (lines.next()) |text| { const body = std.mem.trimStart(u8, text, " \t"); const indent = text.len - body.len; if (going) |depth| { if (body.len != 0 and indent > depth) { try out.print("{s}\n", .{text}); continue; } going = null; } if (!about(body, want)) continue; try out.print("{s}\n", .{text}); going = indent; found = true; } if (found) return 0; try err.print("fs: help: the README says nothing of {s}\n", .{want}); return 1; } /// Whether the README line `body` (its indentation gone) is about `want`, /// or about something under it. fn about(body: []const u8, want: []const u8) bool { const word = std.mem.trim(u8, body[0 .. std.mem.indexOfAny(u8, body, " \t") orelse body.len], "/,"); if (word.len == 0) return false; var pattern = std.mem.tokenizeScalar(u8, word, '/'); var got = std.mem.tokenizeScalar(u8, want, '/'); while (true) { const p = pattern.next() orelse return true; const g = got.next() orelse return true; const any = p.len > 2 and p[0] == '<' and p[p.len - 1] == '>'; if (!any and !std.mem.eql(u8, p, g)) return false; } } // ---- tests: the verbs against a small tree in this process ---- const testing = std.testing; const TestTree = @import("TestTree.zig"); const Rig = struct { tree: TestTree, f: Fsys, out: Io.Writer.Allocating, err: Io.Writer.Allocating, fn start() !*Rig { const r = try testing.allocator.create(Rig); errdefer testing.allocator.destroy(r); try r.tree.start(); errdefer r.tree.stop(); var buf: [128]u8 = undefined; const no_env = [_:null]?[*:0]const u8{}; try r.f.dial(testing.io, &no_env, try std.fmt.bufPrint(&buf, "unix!{s}", .{r.tree.unix}), "glenda"); r.out = .init(testing.allocator); r.err = .init(testing.allocator); return r; } fn stop(r: *Rig) void { r.f.close(); r.tree.stop(); r.out.deinit(); r.err.deinit(); testing.allocator.destroy(r); } /// Runs `line`, split at blanks, with `stdin`: its status; its output /// and errors are in `out` and `err` until the next. fn fs(r: *Rig, cmd: []const u8, stdin: []const u8) u8 { r.out.clearRetainingCapacity(); r.err.clearRetainingCapacity(); var args: [8][]const u8 = undefined; var n: usize = 0; var it = std.mem.tokenizeScalar(u8, cmd, ' '); while (it.next()) |a| : (n += 1) args[n] = a; var in: Io.Reader = .fixed(stdin); return run(&r.f, args[0..n], &in, &r.out.writer, &r.err.writer); } fn expect(r: *Rig, cmd: []const u8, status: u8, out: []const u8, err: []const u8) !void { try testing.expectEqual(status, r.fs(cmd, "")); try testing.expectEqualStrings(out, r.out.written()); try testing.expectEqualStrings(err, r.err.written()); } }; test "verbs: ls, read, stat and complete list what the tree serves" { const r = try Rig.start(); defer r.stop(); try r.expect("ls", 0, "README\nctl\nbig\nshort\necho\nevent\nsub/\n", ""); try r.expect("ls /sub", 0, "deep\n", ""); try r.expect("ls sub/deep", 0, "sub/deep\n", ""); try r.expect("read README", 0, TestTree.readme, ""); try r.expect("read short", 0, "a short answer, three bytes a read", ""); var line_buf: [64]u8 = undefined; try r.expect("stat README", 0, try std.fmt.bufPrint(&line_buf, "--r-------- {d} glenda glenda 0 README\n", .{TestTree.readme.len}), ""); try r.expect("stat sub", 0, "d-rwx------ 0 glenda glenda 0 sub\n", ""); try r.expect("complete", 0, "README\nctl\nbig\nshort\necho\nevent\nsub/\n", ""); try r.expect("complete s", 0, "short\nsub/\n", ""); try r.expect("complete sub/", 0, "sub/deep\n", ""); try r.expect("complete sub/d", 0, "sub/deep\n", ""); try r.expect("complete sub/x", 0, "", ""); try r.expect("ls nowhere", 1, "", "fs: nowhere: No such file or directory\n"); } test "verbs: write and ask, and a refusal in the server's words" { const r = try Rig.start(); defer r.stop(); try r.expect("write ctl bogus", 1, "", "fs: ctl: unknown command: bogus\n"); try r.expect("write ctl ok", 0, "", ""); try r.expect("read ctl", 0, "ok\n", ""); try testing.expectEqual(@as(u8, 1), r.fs("write ctl", "no\n")); try testing.expectEqualStrings("fs: ctl: unknown command: no\n", r.err.written()); try testing.expectEqual(@as(u8, 0), r.fs("write ctl", "ok\n")); try r.expect("ask echo hello there", 0, "heard hello there\n", ""); try r.expect("write README x", 1, "", "fs: README: permission denied\n"); } test "verbs: help prints the README's lines about a path" { const r = try Rig.start(); defer r.stop(); try r.expect("help", 0, TestTree.readme, ""); try r.expect("help README", 0, "README this file\n", ""); try r.expect("help /ctl", 0, "ctl write ok; anything else is refused in words\n", ""); const sub = "sub/ a directory\n of one file\nsub/deep the file in it\n"; try r.expect("help sub", 0, sub, ""); try r.expect("help sub/deep", 0, sub, ""); try r.expect("help nowhere", 1, "", "fs: help: the README says nothing of nowhere\n"); try testing.expect(about("pane// name body tag", "pane/3/body")); try testing.expect(about("pane// name body tag", "pane")); try testing.expect(!about("pane/new open it", "pane/3")); try testing.expect(about("/build facts", "build/time")); try testing.expect(about("os/, src/ the host", "os")); try testing.expect(!about("cat ctl an example", "ctl")); } test "verbs: follow prints what comes, as it comes; a hangup says so" { const r = try Rig.start(); defer r.stop(); 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); try tree.feed("last\n"); try tree.feed(null); } }; var feeder = try testing.io.concurrent(Feeder.run, .{&r.tree}); defer _ = feeder.cancel(testing.io) catch {}; try r.expect("follow event follow", 0, "new 1\ndel 2\nnew 3\n", ""); try r.expect("follow event", 1, "last\n", "fs: event: the server hung up\n"); try feeder.await(testing.io); } test "verbs: a verb not known, or missing its path, is the usage" { const r = try Rig.start(); defer r.stop(); try r.expect("", 1, "", usage); try r.expect("cat README", 1, "", usage); try r.expect("ask echo", 1, "", usage); try r.expect("stat", 1, "", usage); }