diff options
| author | Gabriel Schneider <[email protected]> | 2026-10-12 17:15:03 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:16 -0300 |
| commit | 7a07e24916cd5bc762996d81aa1faf550177cd6f (patch) | |
| tree | 4530a8562fb3f068cc4340f1fab1f6c599721735 /web/main.zig | |
| parent | f9ca3fb5ba767300bec3f1fbb13fc5e6552a90e3 (diff) | |
| download | cloud9-7a07e24916cd5bc762996d81aa1faf550177cd6f.tar.gz cloud9-7a07e24916cd5bc762996d81aa1faf550177cd6f.zip | |
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.
Diffstat (limited to 'web/main.zig')
| -rw-r--r-- | web/main.zig | 132 |
1 files changed, 32 insertions, 100 deletions
diff --git a/web/main.zig b/web/main.zig index 9d108c6..9c49b63 100644 --- a/web/main.zig +++ b/web/main.zig @@ -127,6 +127,7 @@ pub fn main(init: std.process.Init) !void { var catalog_file: ?[]const u8 = null; var catalog_socket: ?[]const u8 = null; var state_dir: ?[]const u8 = null; + var post_name: []const u8 = "9web"; var explicit_upstream = false; var i: usize = 1; while (i < args.len) : (i += 1) { @@ -136,6 +137,7 @@ pub fn main(init: std.process.Init) !void { \\ [--serve tcp:IP:PORT|unix:PATH] [--probe unix:PATH|tcp:IP:PORT] \\ [--origin https://HOST:PORT] [--timeout-ms 300000] [--user NAME] [--tree NAME] \\ [--catalog FILE --catalog-socket PATH --state-dir PATH] + \\ [--post NAME] (pure service name, default 9web, with filesystem /) \\Catalogue mode serves configured sites, build controls and passive listener discovery. \\One shared upstream, many downstreams. Default: http://127.0.0.1:8080 -> tcp:127.0.0.1:564 \\ @@ -158,6 +160,10 @@ pub fn main(init: std.process.Init) !void { state_dir = v; continue; } + if (std.mem.eql(u8, k, "--post")) { + post_name = v; + continue; + } if (std.mem.eql(u8, k, "--upstream")) explicit_upstream = true; if (std.mem.eql(u8, k, "--listen")) listen_text = v else if (std.mem.eql(u8, k, "--upstream")) upstream_text = v else if (std.mem.eql(u8, k, "--serve")) serve_text = v else if (std.mem.eql(u8, k, "--probe")) probe_text = v else if (std.mem.eql(u8, k, "--origin")) public_origin = v else if (std.mem.eql(u8, k, "--timeout-ms")) timeout_ms = try std.fmt.parseInt(u32, v, 10) else if (std.mem.eql(u8, k, "--user")) user = v else if (std.mem.eql(u8, k, "--tree")) tree = v else return error.UnknownArgument; } @@ -171,7 +177,7 @@ pub fn main(init: std.process.Init) !void { const socket = catalog_socket orelse return error.MissingCatalogSocket; cat = try catalog.Catalog.init(io, file, state_dir orelse return error.MissingStateDir); cat.?.http_port = (try Io.net.IpAddress.parseLiteral(listen_text)).getPort(); - try cat.?.start(try allocator.dupeSentinel(u8, socket, 0)); + try cat.?.start(try allocator.dupeSentinel(u8, socket, 0), init.minimal.environ.block.slice.ptr, post_name); upstream_text = try std.fmt.allocPrint(allocator, "unix:{s}", .{socket}); } else return error.CatalogRequiresLinux; } @@ -220,13 +226,13 @@ pub fn main(init: std.process.Init) !void { defer group.cancel(io); try group.concurrent(io, MuxT.readerLoop, .{&m}); - // Each site gets its own HTTP root, preserving /assets and /blog links. - // These listeners belong to this same 9web process, not preview daemons. + // Optional compatibility listeners; prefix routes need no extra port. if (cat) |c| { for (c.sites, 0..) |site, si| { + const port = site.port orelse continue; const l = try allocator.create(Io.net.Server); var bind_address = address; - bind_address.setPort(site.port); + bind_address.setPort(port); l.* = try listenHttp(io, bind_address); try group.concurrent(io, siteAcceptLoop, .{ &app, l, &group, si }); std.debug.print("9web: site {s} on {f} from {s}\n", .{ site.name, l.socket.address, site.root }); @@ -435,21 +441,26 @@ fn serveHttp(s: *Session) !void { if (app.catalog) |c| { if (request.head.method != .GET and request.head.method != .HEAD and origin != null and !same_origin) return respond(&request, "Unexpected Origin\n", "text/plain", .forbidden); + if (std.mem.startsWith(u8, path, "/sites/")) { + const rest = path[7..]; + const end = std.mem.indexOfScalar(u8, rest, '/') orelse rest.len; + for (c.sites) |site| if (std.mem.eql(u8, rest[0..end], site.name)) { + return serveSitePath(s, &request, site, rest[end..]); + }; + return respond(&request, "Unknown site\n", "text/plain", .not_found); + } if (std.mem.eql(u8, path, "/_cloud9/catalog.json")) { - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); - defer arena.deinit(); - return respond(&request, try c.snapshot(arena.allocator()), "application/json", .ok); + if (request.head.method != .GET and request.head.method != .HEAD) return respond(&request, "Use GET\n", "text/plain", .method_not_allowed); + var route: [1024]u8 = undefined; + return httpfs.handle(app.m, &request, try std.fmt.bufPrint(&route, "/fs{s}/index.json", .{c.namespace}), &s.frame, &s.body); } if (std.mem.startsWith(u8, path, "/_cloud9/sites/") and std.mem.endsWith(u8, path, "/ctl")) { if (request.head.method != .POST) return respond(&request, "Use POST\n", "text/plain", .method_not_allowed); const name = path[15 .. path.len - 4]; - for (c.sites, 0..) |site, si| if (std.mem.eql(u8, name, site.name)) { - var body_buf: [256]u8 = undefined; - const reader = try request.readerExpectContinue(&body_buf); - const command = reader.allocRemaining(std.heap.page_allocator, .limited(128)) catch return respond(&request, "Command too long\n", "text/plain", .bad_request); - defer std.heap.page_allocator.free(command); - c.control(si, command) catch |err| return respond(&request, @errorName(err), "text/plain", .bad_request); - return respond(&request, "queued\n", "text/plain", .accepted); + for (c.sites) |site| if (std.mem.eql(u8, name, site.name)) { + var route: [1024]u8 = undefined; + request.head.method = .PUT; + return httpfs.control(app.m, &request, try std.fmt.bufPrint(&route, "/fs{s}/sites/{s}/ctl", .{ c.namespace, name }), &s.frame, &s.body); }; return respond(&request, "Unknown site\n", "text/plain", .not_found); } @@ -510,90 +521,11 @@ fn wsSession(s: *Session, request: *std.http.Server.Request) !void { } fn serveSite(s: *Session, request: *std.http.Server.Request, site: catalog.Site) !void { - if (request.head.method != .GET and request.head.method != .HEAD) return respond(request, "Use GET or HEAD\n", "text/plain", .method_not_allowed); - const raw = std.mem.sliceTo(request.head.target, '?'); - if (raw.len == 0 or raw[0] != '/') return respond(request, "Bad path\n", "text/plain", .bad_request); - var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); - defer arena.deinit(); - const a = arena.allocator(); - const decoded = try a.alloc(u8, raw.len); - var n: usize = 0; - var i: usize = 1; - while (i < raw.len) : (i += 1) { - var ch = raw[i]; - if (ch == '%') { - if (i + 2 >= raw.len) return respond(request, "Bad escape\n", "text/plain", .bad_request); - ch = std.fmt.parseInt(u8, raw[i + 1 .. i + 3], 16) catch return respond(request, "Bad escape\n", "text/plain", .bad_request); - if (ch == '/' or ch == '\\') return respond(request, "Bad escape\n", "text/plain", .bad_request); - i += 2; - } - decoded[n] = ch; - n += 1; - } - var rel: []const u8 = decoded[0..n]; - if (!catalog.safeRelative(rel)) return respond(request, "Forbidden path\n", "text/plain", .forbidden); - // Dotfiles and builder/provider configuration are not public documents. - var components = std.mem.tokenizeScalar(u8, rel, '/'); - while (components.next()) |component| if (component[0] == '.' or std.mem.eql(u8, component, "_headers") or std.mem.eql(u8, component, "_redirects")) return respond(request, "Not found\n", "text/plain", .not_found); - var file = catalog.openBeneath(s.app.io, site.root, rel) catch blk: { - // Pretty URLs such as /blog/post resolve to /blog/post.html. - if (std.fs.path.extension(rel).len != 0) return respond(request, "Not found\n", "text/plain", .not_found); - rel = try std.fmt.allocPrint(a, "{s}.html", .{rel}); - break :blk catalog.openBeneath(s.app.io, site.root, rel) catch return respond(request, "Not found\n", "text/plain", .not_found); - }; - var st = try file.stat(s.app.io); - if (st.kind == .directory) { - file.close(s.app.io); - if (!std.mem.endsWith(u8, raw, "/")) { - const location = try std.fmt.allocPrint(a, "{s}/", .{raw}); - return request.respond("", .{ .status = .moved_permanently, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); - } - rel = try std.fs.path.join(a, &.{ rel, "index.html" }); - file = catalog.openBeneath(s.app.io, site.root, rel) catch return respond(request, "Site has not been built, or index.html is missing.\n", "text/plain", .not_found); - st = try file.stat(s.app.io); - } - defer file.close(s.app.io); - if (st.kind != .file) return respond(request, "Not a regular file\n", "text/plain", .forbidden); - var start: u64 = 0; - var end = st.size; - var partial = false; - var headers = request.iterateHeaders(); - while (headers.next()) |h| if (std.ascii.eqlIgnoreCase(h.name, "range")) { - const text = h.value; - if (!std.mem.startsWith(u8, text, "bytes=") or std.mem.indexOfScalar(u8, text, ',') != null) return respond(request, "Unsupported range\n", "text/plain", .range_not_satisfiable); - const dash = std.mem.indexOfScalar(u8, text[6..], '-') orelse return respond(request, "Bad range\n", "text/plain", .range_not_satisfiable); - const left = text[6 .. 6 + dash]; - const right = text[7 + dash ..]; - if (left.len == 0) { - const suffix = std.fmt.parseInt(u64, right, 10) catch return respond(request, "Bad range\n", "text/plain", .range_not_satisfiable); - start = st.size - @min(st.size, suffix); - } else { - start = std.fmt.parseInt(u64, left, 10) catch return respond(request, "Bad range\n", "text/plain", .range_not_satisfiable); - if (right.len != 0) { - const last = std.fmt.parseInt(u64, right, 10) catch return respond(request, "Bad range\n", "text/plain", .range_not_satisfiable); - end = @min(st.size, last +| 1); - } - } - if (start >= end) return respond(request, "Unsatisfiable range\n", "text/plain", .range_not_satisfiable); - partial = true; - }; - var extra: std.ArrayList(std.http.Header) = .empty; - try extra.appendSlice(a, &.{ .{ .name = "content-type", .value = catalog.mime(rel) }, .{ .name = "cache-control", .value = "no-cache" }, .{ .name = "x-content-type-options", .value = "nosniff" }, .{ .name = "accept-ranges", .value = "bytes" } }); - if (partial) try extra.append(a, .{ .name = "content-range", .value = try std.fmt.allocPrint(a, "bytes {d}-{d}/{d}", .{ start, end - 1, st.size }) }); - if (request.head.method == .HEAD) { - try extra.append(a, .{ .name = "content-length", .value = try std.fmt.allocPrint(a, "{d}", .{end - start}) }); - return request.respond("", .{ .status = if (partial) .partial_content else .ok, .keep_alive = false, .transfer_encoding = .none, .extra_headers = extra.items }); - } - var bw = try request.respondStreaming(&s.body, .{ .content_length = end - start, .respond_options = .{ .status = if (partial) .partial_content else .ok, .keep_alive = false, .extra_headers = extra.items } }); - if (request.head.method != .HEAD) { - var offset = start; - while (offset < end) { - const count: usize = @intCast(@min(end - offset, s.frame.len)); - const got = try file.readPositionalAll(s.app.io, s.frame[0..count], offset); - if (got == 0) return error.EndOfStream; - try bw.writer.writeAll(s.frame[0..got]); - offset += got; - } - } - try bw.end(); + return serveSitePath(s, request, site, std.mem.sliceTo(request.head.target, '?')); +} + +fn serveSitePath(s: *Session, request: *std.http.Server.Request, site: catalog.Site, path: []const u8) !void { + var root_buf: [1024]u8 = undefined; + const root = try std.fmt.bufPrint(&root_buf, "{s}/sites/{s}/public", .{ s.app.catalog.?.namespace, site.name }); + httpfs.website(s.app.m, request, root, path, &s.frame, &s.body); } |
