//! GET /e/[.ext] — resolve a bufo name to its image and serve the bytes. //! ported from the retired rust backend. //! //! this is the single place that knows where a bufo lives, so consumers (the //! status app, personal sites) use one dumb url and never re-implement the //! candidate walk. the extension is cosmetic: plenty of bufos are gif-only. //! //! resolution order: local static dir (custom bufos) → bufo.zone png → gif. const std = @import("std"); const http = std.http; const mem = std.mem; const Allocator = mem.Allocator; const Io = std.Io; const reconnect = @import("reconnect.zig"); const BUFO_ZONE = "https://all-the.bufo.zone"; /// matches the 14d freshness bufo.zone puts on these exact bytes; anything /// shorter would make /e/ cache worse than redirecting did pub const IMAGE_CACHE_CONTROL = "public, max-age=1209600, stale-while-revalidate=86400"; /// short, so a bufo added after a miss shows up soon pub const MISS_CACHE_CONTROL = "public, max-age=300"; const MAX_IMAGE_BYTES = 20 * 1024 * 1024; /// strip the cosmetic extension and reject anything that isn't a real bufo /// name. names are `[a-z0-9_-']`; anything else could be a path-traversal /// attempt against the local static check. pub fn bufoName(raw: []const u8) ?[]const u8 { const name = if (mem.lastIndexOfScalar(u8, raw, '.')) |i| raw[0..i] else raw; if (name.len == 0) return null; for (name) |c| { if (!(std.ascii.isAlphanumeric(c) or c == '-' or c == '_' or c == '\'')) return null; } return name; } pub const Image = struct { content_type: []const u8, bytes: []const u8, }; pub const Resolver = struct { io: Io, http: *http.Client, static_dir: []const u8, submissions_dir: ?[]const u8 = null, bufo_zone: []const u8 = BUFO_ZONE, pub const Error = error{ NotFound, Upstream, OutOfMemory }; pub fn resolve(self: Resolver, alloc: Allocator, name: []const u8) Error!Image { if (self.readLocal(alloc, name)) |img| return img; if (self.submissions_dir) |directory| { const extensions = [_][]const u8{ "png", "gif", "jpg", "webp" }; const types = [_][]const u8{ "image/png", "image/gif", "image/jpeg", "image/webp" }; for (extensions, types) |ext, content_type| { const path = try std.fmt.allocPrint(alloc, "{s}/{s}.{s}", .{ directory, name, ext }); const bytes = readFile(self.io, alloc, path, MAX_IMAGE_BYTES) catch continue; return .{ .content_type = content_type, .bytes = bytes }; } } // NotFound only when bufo.zone itself answers 404: a 404 is cached // downstream, so a transient failure must not become one var upstream_failed = false; for ([_][]const u8{ "png", "gif" }) |ext| { const url = try std.fmt.allocPrint(alloc, "{s}/{s}.{s}", .{ self.bufo_zone, name, ext }); var body: Io.Writer.Allocating = .init(alloc); const res = reconnect.fetch(self.http, .{ .location = .{ .url = url }, .method = .GET, .response_writer = &body.writer, }, null) catch |err| { std.log.warn("bufo fetch failed: {t}", .{err}); upstream_failed = true; continue; }; switch (res.status) { .ok => return .{ .content_type = if (mem.eql(u8, ext, "png")) "image/png" else "image/gif", .bytes = body.written(), }, .not_found => {}, else => upstream_failed = true, } } if (upstream_failed) return error.Upstream; std.log.info("bufo not found", .{}); return error.NotFound; } fn readLocal(self: Resolver, alloc: Allocator, name: []const u8) ?Image { const path = std.fmt.allocPrint(alloc, "{s}/{s}.png", .{ self.static_dir, name }) catch return null; const bytes = readFile(self.io, alloc, path, MAX_IMAGE_BYTES) catch return null; return .{ .content_type = "image/png", .bytes = bytes }; } }; pub fn readFile(io: Io, alloc: Allocator, path: []const u8, limit: usize) ![]u8 { const dir = Io.Dir.cwd(); const file = try dir.openFile(io, path, .{}); defer file.close(io); var buf: [8192]u8 = undefined; var reader = file.reader(io, &buf); return try reader.interface.allocRemaining(alloc, Io.Limit.limited(limit)); } // --- tests: the rust suite, ported --- const t = std.testing; test "strips the cosmetic extension" { try t.expectEqualStrings("bufo-happy", bufoName("bufo-happy.png").?); try t.expectEqualStrings("bufo-happy", bufoName("bufo-happy.gif").?); try t.expectEqualStrings("bufo-happy", bufoName("bufo-happy").?); } test "accepts real bufo names" { for ([_][]const u8{ "add-bufo", "bufo_underscore", "bigbufo_2_2.png", "according-to-all-known-laws-of-aviation-there-is-no-way-a-bufo-should-be-able-to-fly", "bufo's-a-gamer-girl-but-specifically-nyt-games", "bufo-can't-help-but-wonder-who-watches-the-watchmen.png", "my-name-is-buford-and-i-am-bufo's-father", }) |name| { try t.expect(bufoName(name) != null); } } test "rejects traversal and junk" { for ([_][]const u8{ "../../etc/passwd", "..%2f..%2fetc", "foo/bar.png", "a b.png", ".png", "", "bufo$(whoami).png", "../bufo's.png", "bufo's/../../etc/passwd", }) |raw| { try t.expect(bufoName(raw) == null); } } const TestPeer = struct { io: Io, listener: Io.net.Server, warm: bool, closed: Io.Event = .unset, /// one entry per connection; null closes it without responding responses: []const ?http.Status, fn run(self: *TestPeer) !void { defer self.listener.deinit(self.io); if (self.warm) { try self.respond(.ok); self.closed.set(self.io); } for (self.responses) |status| try self.respond(status); } fn respond(self: *TestPeer, status: ?http.Status) !void { const stream = try self.listener.accept(self.io); defer stream.close(self.io); var read_buffer: [4096]u8 = undefined; var write_buffer: [4096]u8 = undefined; var reader = stream.reader(self.io, &read_buffer); var writer = stream.writer(self.io, &write_buffer); var server = http.Server.init(&reader.interface, &writer.interface); var request = try server.receiveHead(); if (status) |code| try request.respond("bufo bytes", .{ .status = code }); } }; fn checkResolve(warm: bool, responses: []const ?http.Status, expected: Resolver.Error!void) !void { const alloc = t.allocator; var threaded = Io.Threaded.init(alloc, .{}); defer threaded.deinit(); const io = threaded.io(); var peer: TestPeer = .{ .io = io, .listener = try (try Io.net.IpAddress.parse("127.0.0.1", 0)).listen(io, .{}), .warm = warm, .responses = responses, }; const origin = try std.fmt.allocPrint(alloc, "http://127.0.0.1:{d}", .{peer.listener.socket.address.getPort()}); defer alloc.free(origin); const address = peer.listener.socket.address; var task = try io.concurrent(TestPeer.run, .{&peer}); defer { if (address.connect(io, .{ .mode = .stream })) |stream| stream.close(io) else |_| {} task.cancel(io) catch {}; } var client: http.Client = .{ .allocator = alloc, .io = io }; defer client.deinit(); var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); if (warm) { var body: Io.Writer.Allocating = .init(arena.allocator()); _ = try client.fetch(.{ .location = .{ .url = origin }, .response_writer = &body.writer }); try peer.closed.wait(io); } const resolver: Resolver = .{ .io = io, .http = &client, .static_dir = "/nonexistent", .bufo_zone = origin }; const result = resolver.resolve(arena.allocator(), "bufo-party"); if (address.connect(io, .{ .mode = .stream })) |stream| stream.close(io) else |_| {} if (expected) |_| { const img = try result; try t.expectEqualStrings("image/png", img.content_type); try t.expectEqualStrings("bufo bytes", img.bytes); } else |err| { try t.expectError(err, result); } try task.await(io); } test "resolves through a pooled connection bufo.zone already closed" { try checkResolve(true, &.{.ok}, {}); } test "a failed upstream fetch is Upstream, not a cacheable NotFound" { try checkResolve(false, &.{ null, null, null, null }, error.Upstream); try checkResolve(false, &.{ .service_unavailable, .not_found }, error.Upstream); } test "NotFound only when bufo.zone answers 404 for every candidate" { try checkResolve(false, &.{ .not_found, .not_found }, error.NotFound); }