diff --git a/.forgejo/workflows/test.yaml b/.forgejo/workflows/test.yaml
index 7121ca0..bdb1313 100644
--- a/.forgejo/workflows/test.yaml
+++ b/.forgejo/workflows/test.yaml
@@ -39,6 +39,27 @@ jobs:
- name: Fuzz the parsers
run: nix develop -c zig build fuzz-run -- --iterations 500000
+ # Published only from main, so that a branch build cannot replace the site
+ # with a work in progress, and only after `test` has passed, so that it
+ # cannot document a tree that does not compile.
+ docs:
+ needs: test
+ if: ${{ forge.ref == 'refs/heads/main' }}
+ runs-on: nixos-do-s
+ steps:
+ - name: Check out
+ uses: https://code.forgejo.org/actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+
+ - name: Build API docs
+ run: nix develop -c zig build docs
+
+ - name: Publish docs
+ run: >
+ nix develop -c git-pages-cli https://jeff.ocj.page/zig-ftp/
+ --server ocj.page
+ --token ${{ forge.token }}
+ --upload-dir zig-out/docs
+
# The virtual machine tests are deliberately not here. Each boots a NixOS
# guest, which needs KVM, and these runners cannot nest virtualisation. They
# are run by hand instead:
diff --git a/README.md b/README.md
index 2e9112c..d61799a 100644
--- a/README.md
+++ b/README.md
@@ -29,6 +29,9 @@ The whole thing is built on `std.Io`, so it runs on whatever `Io`
implementation the calling program chose — threads, fibers, io_uring — and
none of it spawns a thread of its own.
+The [API documentation](https://jeff.ocj.page/zig-ftp/) is generated from the
+doc comments, which are most of the explanation of why FTP is the shape it is.
+
## Adding it to a project
```console
@@ -382,6 +385,25 @@ argument` and a log line that says only "Incorrect password". The test
authenticates from an `AuthUserFile` instead, which is an ordinary way to run
proftpd and still a real crypt(3) check against a real hash.
+## The API documentation
+
+, rebuilt from `main` on every push. Zig writes
+it out of the doc comments, which in this project carry most of the
+explanation — why a multi-line reply can only be ended by looking for its own
+code again, why `EPSV` is better than `PASV`, what `TYPE A` actually converts.
+
+```console
+$ zig build docs-serve # then open http://127.0.0.1:8000/
+$ zig build docs # or just build it, into zig-out/docs
+```
+
+It has to be served rather than opened. What Zig emits is not a page but a
+program: a WebAssembly viewer that fetches the source of everything it shows
+out of a tar file beside it, and a browser refuses to fetch anything from a
+`file://` page. That is the same reason `zig std` runs a server rather than
+opening a file. `tools/docs_server.zig` is that server — one directory, one
+person, the loopback interface, and nothing else.
+
## Licence
MIT. See `LICENSES/MIT.txt`.
diff --git a/build.zig b/build.zig
index c203b3f..6bcbe5b 100644
--- a/build.zig
+++ b/build.zig
@@ -109,13 +109,52 @@ pub fn build(b: *std.Build) void {
const check_step = b.step("check", "Compile everything without running it");
check_step.dependOn(&fuzz_run.step);
+ // -- documentation -------------------------------------------------------
+ //
// Zig emits the API documentation as a side effect of compiling, so the
- // module is built as a library purely to get at it.
- const docs_step = b.step("docs", "Build the API documentation into zig-out/docs");
+ // module is built as a library purely to get at it. What comes out is not
+ // a page but a program: a WebAssembly viewer, its javascript, and a tar of
+ // the sources it reads from.
const library = b.addLibrary(.{ .name = "ftp", .root_module = mod });
- docs_step.dependOn(&b.addInstallDirectory(.{
+ const install_docs = b.addInstallDirectory(.{
.source_dir = library.getEmittedDocs(),
.install_dir = .prefix,
.install_subdir = "docs",
- }).step);
+ });
+ const docs_step = b.step("docs", "Build the API documentation into zig-out/docs");
+ docs_step.dependOn(&install_docs.step);
+
+ // That viewer fetches `sources.tar` and `main.wasm` at runtime, which a
+ // browser refuses to do from a `file://` page, so reading the docs
+ // locally means serving them. It is the same reason `zig std` runs a
+ // server rather than opening a file.
+ const docs_port = b.option(u16, "docs-port", "Port for `zig build docs-serve` (default 8000)") orelse 8000;
+
+ const docs_server = b.addExecutable(.{
+ .name = "docs-server",
+ .root_module = b.createModule(.{
+ .root_source_file = b.path("tools/docs_server.zig"),
+ // Always built for the machine running the build, never for
+ // whatever -Dtarget the library is being built for.
+ .target = b.graph.host,
+ .optimize = .Debug,
+ }),
+ });
+
+ const run_docs_server = b.addRunArtifact(docs_server);
+ run_docs_server.step.dependOn(&install_docs.step);
+ run_docs_server.addArg(b.getInstallPath(.prefix, "docs"));
+ run_docs_server.addArg(b.fmt("{d}", .{docs_port}));
+ // The server runs until interrupted, so its output has to reach the
+ // terminal rather than being captured by the build runner.
+ run_docs_server.stdio = .inherit;
+
+ const docs_serve_step = b.step("docs-serve", "Serve the API documentation over HTTP");
+ docs_serve_step.dependOn(&run_docs_server.step);
+
+ // The server has tests of its own; without this they would never run.
+ test_step.dependOn(&b.addRunArtifact(
+ b.addTest(.{ .root_module = docs_server.root_module }),
+ ).step);
+ check_step.dependOn(&docs_server.step);
}
diff --git a/tools/docs_server.zig b/tools/docs_server.zig
new file mode 100644
index 0000000..c95ff2b
--- /dev/null
+++ b/tools/docs_server.zig
@@ -0,0 +1,171 @@
+// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie
+// SPDX-License-Identifier: MIT
+
+//! Serves the generated API documentation over HTTP, the way `zig std` serves
+//! the standard library's.
+//!
+//! A server is needed rather than just opening `index.html`, because the
+//! viewer fetches `sources.tar` and `main.wasm` at runtime and a browser
+//! refuses those requests from a `file://` page.
+//!
+//! Run through the build system: `zig build docs-serve`. It is deliberately
+//! minimal, serving one directory to one person on the loopback interface —
+//! it is a convenience for reading `zig build docs`, not a web server, and
+//! nothing about it should be pointed at a network.
+//!
+//! It is worth noting what this is *not*: this repository implements a file
+//! transfer protocol, and none of that is used here. HTTP is what a browser
+//! speaks, so HTTP is what this speaks.
+//!
+//! Every connection gets its own thread, which is not a throughput concern but
+//! a correctness one: a browser opens several connections at once and holds
+//! some of them open without sending anything, so a server that reads them one
+//! at a time blocks on a speculative connection and never answers the real
+//! requests.
+//!
+//! A thread each, rather than a pool: a connection handler blocks until its
+//! client goes away, which can be minutes, and a pool sized for short tasks
+//! wedges once every worker is parked on an idle socket. A browser opens a
+//! handful of connections, so the thread count stays small in practice.
+
+const std = @import("std");
+const Io = std.Io;
+
+/// Nothing in a documentation bundle comes close to this; it exists so that a
+/// stray huge file cannot exhaust memory.
+const max_file_size = 64 * 1024 * 1024;
+
+pub fn main(init: std.process.Init) !void {
+ const gpa = init.gpa;
+ const io = init.io;
+ const args = try init.minimal.args.toSlice(init.arena.allocator());
+
+ var stderr_buffer: [512]u8 = undefined;
+ var stderr_writer: Io.File.Writer = .init(.stderr(), io, &stderr_buffer);
+ const stderr = &stderr_writer.interface;
+
+ if (args.len != 3) {
+ try stderr.writeAll("usage: docs-server \n");
+ try stderr.flush();
+ std.process.exit(2);
+ }
+ const docs_path = args[1];
+ const port = try std.fmt.parseInt(u16, args[2], 10);
+
+ var docs_dir = Io.Dir.cwd().openDir(io, docs_path, .{}) catch |err| {
+ try stderr.print("cannot open {s}: {s}\n", .{ docs_path, @errorName(err) });
+ try stderr.flush();
+ std.process.exit(1);
+ };
+ defer docs_dir.close(io);
+
+ const address: Io.net.IpAddress = .{ .ip4 = .{ .bytes = .{ 127, 0, 0, 1 }, .port = port } };
+ var server = address.listen(io, .{ .reuse_address = true }) catch |err| {
+ try stderr.print("cannot listen on 127.0.0.1:{d}: {s}\n", .{ port, @errorName(err) });
+ if (err == error.AddressInUse) {
+ try stderr.writeAll("another port can be chosen with -Ddocs-port=N\n");
+ }
+ try stderr.flush();
+ std.process.exit(1);
+ };
+ defer server.deinit(io);
+
+ try stderr.print("serving {s} at http://127.0.0.1:{d}/\npress ctrl-c to stop\n", .{ docs_path, port });
+ try stderr.flush();
+
+ while (true) {
+ const stream = server.accept(io) catch |err| switch (err) {
+ // One client giving up is not a reason to stop serving.
+ error.ConnectionAborted, error.WouldBlock, error.ProtocolFailure => continue,
+ else => return err,
+ };
+
+ const thread = std.Thread.spawn(.{}, handleConnection, .{ io, gpa, docs_dir, stream }) catch {
+ // Out of threads. Serving it here blocks the ones behind it, but
+ // dropping it silently would look like the same hang from the
+ // browser's side with none of the progress.
+ handleConnection(io, gpa, docs_dir, stream);
+ continue;
+ };
+ // Nothing joins these: each ends when its client disconnects, and the
+ // process runs until interrupted.
+ thread.detach();
+ }
+}
+
+/// Serves one connection until the client goes away, then closes it.
+fn handleConnection(io: Io, gpa: std.mem.Allocator, docs_dir: Io.Dir, stream: Io.net.Stream) void {
+ defer stream.close(io);
+
+ var recv_buffer: [16 * 1024]u8 = undefined;
+ var send_buffer: [64 * 1024]u8 = undefined;
+ var stream_reader = stream.reader(io, &recv_buffer);
+ var stream_writer = stream.writer(io, &send_buffer);
+ var http_server: std.http.Server = .init(&stream_reader.interface, &stream_writer.interface);
+
+ // Keep answering on the same connection, so that one page load does not
+ // need a connection per file.
+ while (true) {
+ var request = http_server.receiveHead() catch return;
+ serve(&request, io, gpa, docs_dir) catch return;
+ // A client that asked to close is waiting for exactly that; waiting
+ // for another request it will never send would hang it until it times
+ // out.
+ if (!request.head.keep_alive) return;
+ }
+}
+
+fn serve(
+ request: *std.http.Server.Request,
+ io: Io,
+ gpa: std.mem.Allocator,
+ docs_dir: Io.Dir,
+) !void {
+ const target = request.head.target;
+ const path_end = std.mem.indexOfAny(u8, target, "?#") orelse target.len;
+ var path = target[0..path_end];
+ if (std.mem.startsWith(u8, path, "/")) path = path[1..];
+ if (path.len == 0) path = "index.html";
+
+ // The documentation directory is the whole world this server knows about.
+ if (std.mem.indexOf(u8, path, "..") != null or std.fs.path.isAbsolute(path)) {
+ return request.respond("bad request\n", .{ .status = .bad_request });
+ }
+
+ const content = docs_dir.readFileAlloc(io, path, gpa, .limited(max_file_size)) catch {
+ return request.respond("not found\n", .{ .status = .not_found });
+ };
+ defer gpa.free(content);
+
+ try request.respond(content, .{
+ .extra_headers = &.{.{ .name = "content-type", .value = mimeType(path) }},
+ });
+}
+
+/// Enough of a MIME table for what `zig build docs` emits.
+fn mimeType(path: []const u8) []const u8 {
+ const extension = std.fs.path.extension(path);
+ const table = [_]struct { []const u8, []const u8 }{
+ .{ ".html", "text/html; charset=utf-8" },
+ .{ ".js", "text/javascript; charset=utf-8" },
+ .{ ".css", "text/css; charset=utf-8" },
+ .{ ".wasm", "application/wasm" },
+ .{ ".tar", "application/x-tar" },
+ .{ ".json", "application/json" },
+ .{ ".svg", "image/svg+xml" },
+ };
+ for (table) |entry| {
+ if (std.mem.eql(u8, extension, entry[0])) return entry[1];
+ }
+ return "application/octet-stream";
+}
+
+const testing = std.testing;
+
+test mimeType {
+ try testing.expectEqualStrings("text/html; charset=utf-8", mimeType("index.html"));
+ try testing.expectEqualStrings("application/wasm", mimeType("main.wasm"));
+ try testing.expectEqualStrings("application/x-tar", mimeType("sources.tar"));
+ try testing.expectEqualStrings("text/javascript; charset=utf-8", mimeType("main.js"));
+ try testing.expectEqualStrings("application/octet-stream", mimeType("noextension"));
+}