From 7a07e24916cd5bc762996d81aa1faf550177cd6f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 12 Oct 2026 17:15:03 -0300 Subject: 9web: serve prefixed sites through the composed 9P namespace Post only the pure site/control/discovery tree, with a separate host-only adapter and no duplicate supervision. Serve websites, metadata and legacy controls through the ordinary 9P mux; retain whole-root filesystem browsing and compatibility paths. Pin public file descriptors across publication. Add opt-in build-time HTML/CSS prefix packaging with separate atomic preview generations and unchanged JavaScript/default output. Optional compatibility ports use ?u16. Deploy all five workstation sites on [::]:8090, with /mnt/9p/9web controls. Document Plan 9 references, companion build commits, shared-origin trust and live validation. Validated catalogue, host/FUSE, HTTP FS, mux, prefix and Chromium suites; original E2E 32 scenarios; all five live sites, blog navigation, IPv4/IPv6 and real cafe build through 9P. --- web/httpfs.zig | 124 +++++++++++++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 112 insertions(+), 12 deletions(-) (limited to 'web/httpfs.zig') diff --git a/web/httpfs.zig b/web/httpfs.zig index 8af5793..31c4014 100644 --- a/web/httpfs.zig +++ b/web/httpfs.zig @@ -23,9 +23,31 @@ const Request = c9.Client.Request; const max_components = 64; const name_bytes = 8192; +/// A website is a view of a subtree of the SAME upstream namespace. Index and +/// pretty-URL lookup are HTTP policy; all stat/open/read operations remain 9P. +pub fn website(m: anytype, request: *Server.Request, root: []const u8, path: []const u8, big: []u8, small: []u8) void { + var fs: FS(@TypeOf(m.*)) = .{ .m = m, .request = request, .big = big, .small = small, .website_mode = true }; + defer fs.cleanup(); + fs.serveWebsite(root, path) catch |err| switch (err) { + error.Handled => {}, + error.NotFound => fs.fail(.not_found, "Site has not been built, or file is missing.\n"), + error.BadPath => fs.fail(.bad_request, "Invalid path\n"), + error.Upstream, error.Disconnected => fs.fail(.bad_gateway, "9P upstream unavailable\n"), + else => fs.fail(.internal_server_error, "Internal error\n"), + }; +} + pub fn handle(m: anytype, request: *Server.Request, path: []const u8, big: []u8, small: []u8) void { + return handleOptions(m, request, path, big, small, false); +} + +pub fn control(m: anytype, request: *Server.Request, path: []const u8, big: []u8, small: []u8) void { + return handleOptions(m, request, path, big, small, true); +} + +fn handleOptions(m: anytype, request: *Server.Request, path: []const u8, big: []u8, small: []u8, legacy_control: bool) void { const M = @TypeOf(m.*); - var fs: FS(M) = .{ .m = m, .request = request, .big = big, .small = small }; + var fs: FS(M) = .{ .m = m, .request = request, .big = big, .small = small, .legacy_control = legacy_control }; fs.serve(path) catch |err| switch (err) { error.Handled => {}, error.NotFound => fs.fail(.not_found, "No such file or directory\n"), @@ -47,6 +69,9 @@ fn FS(comptime M: type) type { root_fid: ?u32 = null, leaf_fid: ?u32 = null, responded: bool = false, + website_mode: bool = false, + content_type: ?[]const u8 = null, + legacy_control: bool = false, fn rpcSmall(self: *Self, req: Request) !wire.Decoded { var r: M.Rpc = .{ .buf = self.small }; @@ -65,9 +90,10 @@ fn FS(comptime M: type) type { /// A 9P Rerror: map to a status and answer, then stop the request. fn rerr(self: *Self, ename: []const u8) anyerror { + if (self.website_mode and mapError(ename) == .not_found) return error.NotFound; var buf: [160]u8 = undefined; const body = std.fmt.bufPrint(&buf, "{s}\n", .{ename[0..@min(ename.len, 128)]}) catch "error\n"; - self.fail(mapError(ename), body); + self.fail(if (self.legacy_control) .bad_request else mapError(ename), body); return error.Handled; } @@ -136,6 +162,44 @@ fn FS(comptime M: type) type { // -- dispatch ------------------------------------------------------ + fn serveWebsite(self: *Self, root: []const u8, path: []const u8) !void { + if (self.request.head.method != .GET and self.request.head.method != .HEAD) { + self.fail(.method_not_allowed, "Use GET or HEAD\n"); + return; + } + var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); + defer arena.deinit(); + const a = arena.allocator(); + var storage: [name_bytes]u8 = undefined; + var names: [max_components][]const u8 = undefined; + var n = try decodePath(try std.fmt.allocPrint(a, "{s}/{s}", .{ root, path }), &storage, &names); + // Public documents only; controls and provider configuration must + // never become executable documents through the website view. + for (names[0..n]) |name| if (name[0] == '.' or std.mem.eql(u8, name, "_headers") or std.mem.eql(u8, name, "_redirects")) return error.NotFound; + var st = self.walkTo(names[0..n]) catch |err| blk: { + if (err != error.NotFound or n == 0 or std.fs.path.extension(names[n - 1]).len != 0) return err; + names[n - 1] = try std.fmt.allocPrint(a, "{s}.html", .{names[n - 1]}); + break :blk try self.walkTo(names[0..n]); + }; + if (st.qid.type & c9.qtdir != 0) { + const raw = std.mem.sliceTo(self.request.head.target, '?'); + if (!std.mem.endsWith(u8, raw, "/")) { + const query = self.request.head.target[raw.len..]; + const location = try std.fmt.allocPrint(a, "{s}/{s}", .{ raw, query }); + self.responded = true; + try self.request.respond("", .{ .status = .moved_permanently, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); + return; + } + if (n == names.len) return error.BadPath; + names[n] = "index.html"; + n += 1; + st = try self.walkTo(names[0..n]); + if (st.qid.type & c9.qtdir != 0) return error.NotFound; + } + self.content_type = @import("catalog.zig").mime(names[n - 1]); + return self.getFile(st); + } + fn serve(self: *Self, path: []const u8) !void { const rel = path[3..]; // after "/fs" const trailing = rel.len != 0 and rel[rel.len - 1] == '/'; @@ -192,17 +256,33 @@ fn FS(comptime M: type) type { if (opened.msg == .rerror) return self.rerr(opened.msg.rerror.ename); if (opened.msg != .ropen) return error.Upstream; - const range = self.parseRange(st.length); + const range = try self.parseRange(st.length); const status: Status = if (range.partial) .partial_content else .ok; var offset: u64 = range.start; + if (self.request.head.method == .HEAD) { + var length_buf: [24]u8 = undefined; + var range_buf: [64]u8 = undefined; + const range_header: []const std.http.Header = if (range.partial) &.{.{ .name = "content-range", .value = try std.fmt.bufPrint(&range_buf, "bytes {d}-{d}/{d}", .{ range.start, range.end - 1, st.length }) }} else &.{}; + var headers: std.ArrayList(std.http.Header) = .empty; + defer headers.deinit(std.heap.page_allocator); + try headers.appendSlice(std.heap.page_allocator, &.{ + .{ .name = "content-type", .value = self.content_type orelse "application/octet-stream" }, + .{ .name = "content-length", .value = try std.fmt.bufPrint(&length_buf, "{d}", .{range.end - range.start}) }, + .{ .name = "accept-ranges", .value = "bytes" }, + .{ .name = "x-content-type-options", .value = "nosniff" }, + }); + try headers.appendSlice(std.heap.page_allocator, range_header); + self.responded = true; + return self.request.respond("", .{ .status = status, .keep_alive = false, .transfer_encoding = .none, .extra_headers = headers.items }); + } const first = try self.readAt(leaf, offset, self.chunk()); if (first.msg == .rerror) return self.rerr(first.msg.rerror.ename); if (first.msg != .rread) return error.Upstream; - const ctype = sniff(first.msg.rread.data); + const ctype = self.content_type orelse sniff(first.msg.rread.data); var cr_buf: [64]u8 = undefined; - var headers: [4]std.http.Header = undefined; + var headers: [5]std.http.Header = undefined; var nh: usize = 0; headers[nh] = .{ .name = "content-type", .value = ctype }; nh += 1; @@ -210,6 +290,8 @@ fn FS(comptime M: type) type { nh += 1; headers[nh] = .{ .name = "cache-control", .value = "no-store" }; nh += 1; + headers[nh] = .{ .name = "x-content-type-options", .value = "nosniff" }; + nh += 1; if (range.partial) { headers[nh] = .{ .name = "content-range", .value = std.fmt.bufPrint(&cr_buf, "bytes {d}-{d}/{d}", .{ range.start, range.end - 1, st.length }) catch return error.Upstream }; nh += 1; @@ -388,6 +470,10 @@ fn FS(comptime M: type) type { if (cr.msg != .rcreate) return error.Upstream; } const written = try self.streamBody(self.leaf_fid.?, write_off); + if (self.legacy_control) { + self.fail(.accepted, "queued\n"); + return; + } var buf: [48]u8 = undefined; const body = std.fmt.bufPrint(&buf, "{{\"written\":{d}}}\n", .{written}) catch "{}\n"; self.responded = true; @@ -437,6 +523,10 @@ fn FS(comptime M: type) type { while (true) { const n = br.readSliceShort(cbuf[0..maxw]) catch return error.Upstream; if (n == 0) break; + if (self.legacy_control and total + n > 128) { + self.fail(.bad_request, "Command too long\n"); + return error.Handled; + } var done: usize = 0; while (done < n) { const w = try self.rpcSmall(.{ .write = .{ .fid = fid, .offset = offset + done, .data = cbuf[done..n] } }); @@ -463,25 +553,35 @@ fn FS(comptime M: type) type { } const Range = struct { start: u64, end: u64, partial: bool }; - fn parseRange(self: *Self, length: u64) Range { + fn parseRange(self: *Self, length: u64) !Range { var it = self.request.iterateHeaders(); while (it.next()) |h| { if (!std.ascii.eqlIgnoreCase(h.name, "range")) continue; - if (!std.mem.startsWith(u8, h.value, "bytes=")) break; + if (!std.mem.startsWith(u8, h.value, "bytes=")) return self.badRange(); const spec = h.value[6..]; - const dash = std.mem.indexOfScalar(u8, spec, '-') orelse break; - const start = std.fmt.parseInt(u64, spec[0..dash], 10) catch break; + const dash = std.mem.indexOfScalar(u8, spec, '-') orelse return self.badRange(); + if (dash == 0) { + const suffix = std.fmt.parseInt(u64, spec[1..], 10) catch return self.badRange(); + if (suffix == 0 or length == 0) return self.badRange(); + return .{ .start = length - @min(length, suffix), .end = length, .partial = true }; + } + const start = std.fmt.parseInt(u64, spec[0..dash], 10) catch return self.badRange(); var end: u64 = length; if (dash + 1 < spec.len) { - const e = std.fmt.parseInt(u64, spec[dash + 1 ..], 10) catch break; - end = @min(e + 1, length); + const e = std.fmt.parseInt(u64, spec[dash + 1 ..], 10) catch return self.badRange(); + end = @min(e +| 1, length); } - if (start >= length or start >= end) break; + if (start >= length or start >= end) return self.badRange(); return .{ .start = start, .end = end, .partial = true }; } return .{ .start = 0, .end = length, .partial = false }; } + fn badRange(self: *Self) anyerror { + self.fail(.range_not_satisfiable, "Unsatisfiable range\n"); + return error.Handled; + } + fn wantsFollow(self: *Self) bool { if (std.mem.indexOf(u8, self.request.head.target, "follow=1") != null) return true; return self.acceptHas("text/event-stream"); -- cgit v1.3