1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
|
//! 9web: an HTTP/WebSocket gateway and 9P multiplexer.
//!
//! One shared upstream 9P connection (`mux.Mux`, all 16 tags) is fanned out to
//! any number of downstream sessions: the browser WASM client over a WebSocket
//! at `/_cloud9/9p`, plain 9P clients over an optional `--serve` TCP/Unix
//! listener (a 9pserve-style mux for 9ns and plan9port), and an HTTP view of
//! the tree under `/fs/<path>`. No web or namespace policy is added to the
//! cloud9 library; this file owns listeners, connection bounds and routing.
const std = @import("std");
const c9 = @import("cloud9");
const mux = @import("mux.zig");
const httpfs = @import("httpfs.zig");
const probe = @import("probe.zig");
const catalog = @import("catalog.zig");
const Io = std.Io;
const max_frame = 65536;
const max_connections = 64;
pub const MuxT = mux.Mux(.{
.msize = max_frame,
.upstream_fids = 2048,
.fids_per_conn = 256,
.downstreams = max_connections,
});
const Config = struct {
host: []const u8,
origin: []const u8,
public_host: []const u8,
timeout_ms: u32,
browser_config: []const u8,
wildcard: bool = false,
};
/// One downstream slot: buffers, the HTTP/WebSocket streams and the mux
/// session, all in stable memory for the process lifetime so the mux reader
/// task may reference a slot's sink after the slot's socket has closed.
const Session = struct {
used: std.atomic.Value(bool) = .init(false),
app: *App = undefined,
stream: Io.net.Stream = undefined,
reader: Io.net.Stream.Reader = undefined,
writer: Io.net.Stream.Writer = undefined,
in: [16384]u8 = undefined,
out: [16384]u8 = undefined,
frame: [max_frame]u8 = undefined,
body: [16384]u8 = undefined,
ws: c9.http.WebSocket = undefined,
conn: MuxT.Conn = undefined,
wmutex: Io.Mutex = .init,
is_ws: bool = false,
site: ?usize = null,
fn sink(s: *Session) mux.Sink {
return .{ .ctx = s, .send = sendReply };
}
fn sendReply(ctx: *anyopaque, frame: []const u8) anyerror!void {
const s: *Session = @ptrCast(@alignCast(ctx));
s.wmutex.lockUncancelable(s.app.io);
defer s.wmutex.unlock(s.app.io);
if (s.is_ws) {
try s.ws.send(frame, .binary, null);
} else {
try c9.transport.writeFrame(&s.writer.interface, frame, max_frame);
try s.writer.interface.flush();
}
}
};
pub const App = struct {
io: Io,
m: *MuxT,
config: Config,
catalog: ?*catalog.Catalog = null,
sessions: [max_connections]Session = @splat(.{}),
active: std.atomic.Value(u32) = .init(0),
fn take(app: *App) ?*Session {
for (&app.sessions) |*s| {
if (s.used.cmpxchgStrong(false, true, .acq_rel, .monotonic) == null) {
_ = app.active.fetchAdd(1, .monotonic);
return s;
}
}
return null;
}
fn giveBack(app: *App, s: *Session) void {
s.used.store(false, .release);
_ = app.active.fetchSub(1, .monotonic);
}
pub fn connectionCount(app: *App) u32 {
return app.active.load(.acquire);
}
};
fn parseUpstream(allocator: std.mem.Allocator, text: []const u8) !mux.Address {
if (std.mem.startsWith(u8, text, "tcp:"))
return .{ .network = .{ .tcp = try Io.net.IpAddress.parseLiteral(text[4..]) } };
if (std.mem.startsWith(u8, text, "unix:"))
return .{ .network = .{ .unix = try allocator.dupeSentinel(u8, text[5..], 0) } };
if (std.mem.startsWith(u8, text, "file:"))
return .{ .file = text[5..] };
return error.InvalidUpstream;
}
fn parseServe(allocator: std.mem.Allocator, text: []const u8) !c9.transport.Address {
if (std.mem.startsWith(u8, text, "tcp:"))
return .{ .tcp = try Io.net.IpAddress.parseLiteral(text[4..]) };
if (std.mem.startsWith(u8, text, "unix:"))
return .{ .unix = try allocator.dupeSentinel(u8, text[5..], 0) };
return error.InvalidServe;
}
pub fn main(init: std.process.Init) !void {
const allocator = init.arena.allocator();
const args = try init.minimal.args.toSlice(allocator);
var listen_text: []const u8 = "127.0.0.1:8080";
var upstream_text: []const u8 = "tcp:127.0.0.1:564";
var serve_text: ?[]const u8 = null;
var probe_text: ?[]const u8 = null;
var timeout_ms: u32 = 300000;
var user: []const u8 = "user";
var tree: []const u8 = "";
var public_origin: ?[]const u8 = null;
var catalog_file: ?[]const u8 = null;
var catalog_socket: ?[]const u8 = null;
var state_dir: ?[]const u8 = null;
var explicit_upstream = false;
var i: usize = 1;
while (i < args.len) : (i += 1) {
if (std.mem.eql(u8, args[i], "--help")) {
std.debug.print(
\\Usage: 9web [--listen IP:PORT] [--upstream tcp:IP:PORT|unix:PATH|file:PATH]
\\ [--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]
\\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
\\
, .{});
return;
}
if (i + 1 == args.len) return error.MissingArgument;
i += 1;
const v = args[i];
const k = args[i - 1];
if (std.mem.eql(u8, k, "--catalog")) {
catalog_file = v;
continue;
}
if (std.mem.eql(u8, k, "--catalog-socket")) {
catalog_socket = v;
continue;
}
if (std.mem.eql(u8, k, "--state-dir")) {
state_dir = 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;
}
if (user.len > 256 or tree.len > 256) return error.AttachNameTooLong;
const io = init.io;
var cat: ?*catalog.Catalog = null;
if (catalog_file) |file| {
if (@import("builtin").os.tag == .linux) {
if (explicit_upstream) return error.CatalogAndUpstreamAreExclusive;
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));
upstream_text = try std.fmt.allocPrint(allocator, "unix:{s}", .{socket});
} else return error.CatalogRequiresLinux;
}
defer if (cat) |c| c.stop();
const address = try Io.net.IpAddress.parseLiteral(listen_text);
const upstream = try parseUpstream(allocator, upstream_text);
var m: MuxT = undefined;
m.init(io, upstream, user, tree);
m.connect() catch {
std.debug.print("9web: upstream {s} unavailable at startup; will retry.\n", .{upstream_text});
};
defer m.stop();
var listener = c9.transport.listen(io, .{ .tcp = address }, max_connections) catch |err| {
if (err == error.AddressInUse) {
std.debug.print("9web: cannot listen on {s}: address already in use.\nUse --listen 127.0.0.1:0 to select a free port; the URL is printed at startup.\n", .{listen_text});
} else std.debug.print("9web: cannot listen on {s}: {s}\n", .{ listen_text, @errorName(err) });
return err;
};
defer listener.deinit(io);
const host = try std.fmt.allocPrint(allocator, "{f}", .{listener.socket.address});
const origin_text = public_origin orelse try std.fmt.allocPrint(allocator, "http://{s}", .{host});
const origin_uri = try std.Uri.parse(origin_text);
if ((!std.mem.eql(u8, origin_uri.scheme, "https") and !std.mem.eql(u8, origin_uri.scheme, "http")) or
origin_uri.host == null or origin_uri.user != null or origin_uri.password != null or
origin_uri.path.percent_encoded.len != 0 or origin_uri.query != null or origin_uri.fragment != null) return error.InvalidOrigin;
const browser_config = try std.json.Stringify.valueAlloc(allocator, .{ .user = user, .tree = tree }, .{});
var app: App = .{ .io = io, .m = &m, .catalog = cat, .config = .{
.host = host,
.origin = origin_text,
.public_host = origin_text[origin_uri.scheme.len + 3 ..],
.timeout_ms = timeout_ms,
.browser_config = browser_config,
.wildcard = std.mem.startsWith(u8, listen_text, "0.0.0.0:") or std.mem.startsWith(u8, listen_text, "[::]:"),
} };
std.debug.print("9web {s} -> {s}\n", .{ app.config.origin, upstream_text });
var group: Io.Group = .init;
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.
if (cat) |c| {
for (c.sites, 0..) |site, si| {
const l = try allocator.create(Io.net.Server);
var bind_address = address;
bind_address.setPort(site.port);
l.* = try c9.transport.listen(io, .{ .tcp = bind_address }, max_connections);
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 });
}
}
// Optional 9P listener for plan9port / 9ns clients (a mux like 9pserve).
var serve_listener: ?Io.net.Server = null;
if (serve_text) |t| {
const addr = try parseServe(allocator, t);
serve_listener = c9.transport.listen(io, addr, max_connections) catch |err| {
std.debug.print("9web: cannot --serve {s}: {s}\n", .{ t, @errorName(err) });
return err;
};
std.debug.print("9web: serving 9P on {s}\n", .{t});
try group.concurrent(io, serveLoop, .{ &app, &serve_listener.?, &group });
}
defer if (serve_listener) |*l| l.deinit(io);
// Optional self-introspection: embed 9proc under --probe.
const Introspect = probe.Probe(App);
if (probe_text) |t| {
Introspect.start(&app, allocator, t) catch |err| {
std.debug.print("9web: --probe {s} failed: {s}\n", .{ t, @errorName(err) });
};
}
defer Introspect.stop();
while (true) {
const stream = listener.accept(io) catch |err| switch (err) {
error.Canceled => return,
else => {
io.sleep(.fromMilliseconds(20), .awake) catch return;
continue;
},
};
const s = app.take() orelse {
stream.close(io);
continue;
};
s.app = &app;
s.site = null;
s.stream = stream;
group.concurrent(io, handleHttp, .{s}) catch {
app.giveBack(s);
stream.close(io);
continue;
};
}
}
fn siteAcceptLoop(app: *App, listener: *Io.net.Server, group: *Io.Group, si: usize) void {
defer listener.deinit(app.io);
while (true) {
const stream = listener.accept(app.io) catch return;
const s = app.take() orelse {
stream.close(app.io);
continue;
};
s.app = app;
s.stream = stream;
s.site = si;
group.concurrent(app.io, handleHttp, .{s}) catch {
app.giveBack(s);
stream.close(app.io);
};
}
}
/// Accepts plain 9P clients on the `--serve` listener; each runs a raw mux
/// session for its lifetime.
fn serveLoop(app: *App, listener: *Io.net.Server, group: *Io.Group) void {
const io = app.io;
while (true) {
const stream = listener.accept(io) catch return;
const s = app.take() orelse {
stream.close(io);
continue;
};
s.app = app;
s.stream = stream;
group.concurrent(io, rawSession, .{s}) catch {
app.giveBack(s);
stream.close(io);
};
}
}
/// A downstream 9P session over a raw stream (`--serve`).
fn rawSession(s: *Session) void {
const app = s.app;
const io = app.io;
defer {
s.stream.close(io);
app.giveBack(s);
}
s.is_ws = false;
s.reader = s.stream.reader(io, &s.in);
s.writer = s.stream.writer(io, &s.out);
s.conn = MuxT.Conn.init(app.m, s.sink());
defer s.conn.deinit();
while (true) {
const frame = c9.transport.readFrame(&s.reader.interface, &s.frame, max_frame) catch return;
app.m.forward(&s.conn, frame);
}
}
fn respond(request: *std.http.Server.Request, content: []const u8, mime: []const u8, status: std.http.Status) !void {
try request.respond(content, .{ .status = status, .keep_alive = false, .extra_headers = &.{
.{ .name = "content-type", .value = mime },
.{ .name = "cache-control", .value = "no-store" },
.{ .name = "x-content-type-options", .value = "nosniff" },
.{ .name = "content-security-policy", .value = "default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'" },
} });
}
fn handleHttp(s: *Session) void {
const app = s.app;
const io = app.io;
var timed: TimedSession = .{ .s = s };
var group: Io.Group = .init;
defer group.cancel(io);
group.concurrent(io, TimedSession.run, .{&timed}) catch {
s.stream.close(io);
app.giveBack(s);
return;
};
const timeout: Io.Timeout = if (app.config.timeout_ms == 0) .none else .{ .duration = .{ .raw = .fromMilliseconds(app.config.timeout_ms), .clock = .awake } };
timed.done.waitTimeout(io, timeout) catch {};
s.stream.close(io);
group.cancel(io);
app.giveBack(s);
}
const TimedSession = struct {
s: *Session,
done: Io.Event = .unset,
fn run(t: *TimedSession) void {
defer t.done.set(t.s.app.io);
serveHttp(t.s) catch {};
}
};
fn serveHttp(s: *Session) !void {
const app = s.app;
const io = app.io;
const config = app.config;
s.reader = s.stream.reader(io, &s.in);
s.writer = s.stream.writer(io, &s.out);
var http: std.http.Server = .init(&s.reader.interface, &s.writer.interface);
http.reader.max_head_len = 8192;
var request = try http.receiveHead();
var host: ?[]const u8 = null;
var origin: ?[]const u8 = null;
var version: ?[]const u8 = null;
var headers = request.iterateHeaders();
while (headers.next()) |header| {
if (std.ascii.eqlIgnoreCase(header.name, "host")) host = header.value;
if (std.ascii.eqlIgnoreCase(header.name, "origin")) origin = header.value;
if (std.ascii.eqlIgnoreCase(header.name, "sec-websocket-version")) version = header.value;
}
if (s.site) |si| return serveSite(s, &request, app.catalog.?.sites[si]);
const host_text = host orelse "";
const literal = Io.net.IpAddress.parseLiteral(host_text) catch null;
const bound = try Io.net.IpAddress.parseLiteral(config.host);
const wildcard_host = config.wildcard and ((if (literal) |ip| ip.getPort() == bound.getPort() else false) or std.mem.eql(u8, host_text, try std.fmt.bufPrint(&s.body, "localhost:{d}", .{bound.getPort()})));
if (!wildcard_host and !std.mem.eql(u8, host_text, config.host) and !std.mem.eql(u8, host_text, config.public_host))
return respond(&request, "Unexpected Host\n", "text/plain", .forbidden);
const path = std.mem.sliceTo(request.head.target, '?');
// Browsers must originate control writes from this dashboard. Site ports
// are separate origins. CLI and 9P clients do not send Origin.
const same_origin = if (origin) |o| std.mem.eql(u8, o, config.origin) or
(std.mem.startsWith(u8, o, "http://") and std.mem.eql(u8, o[7..], host_text)) else false;
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.eql(u8, path, "/")) return respond(&request, @embedFile("static/catalog.html"), "text/html; charset=utf-8", .ok);
if (std.mem.eql(u8, path, "/_cloud9/catalog.js")) return respond(&request, @embedFile("static/catalog.js"), "text/javascript", .ok);
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 (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);
};
return respond(&request, "Unknown site\n", "text/plain", .not_found);
}
}
// The WebSocket endpoint.
if (std.mem.eql(u8, path, "/_cloud9/9p")) {
if (request.head.method != .GET) return respond(&request, "Use GET\n", "text/plain", .method_not_allowed);
if (!same_origin) return respond(&request, "Unexpected Origin\n", "text/plain", .forbidden);
if (!std.mem.eql(u8, version orelse "", "13")) return respond(&request, "WebSocket version 13 required\n", "text/plain", .bad_request);
return wsSession(s, &request);
}
// The HTTP view of the tree.
if (std.mem.eql(u8, path, "/fs") or std.mem.startsWith(u8, path, "/fs/"))
return httpfs.handle(app.m, &request, path, &s.frame, &s.body);
// Static assets and configuration.
if (request.head.method != .GET and request.head.method != .HEAD)
return respond(&request, "Use GET\n", "text/plain", .method_not_allowed);
if (std.mem.eql(u8, path, "/_cloud9/config.json")) return respond(&request, config.browser_config, "application/json", .ok);
if (std.mem.eql(u8, path, "/_cloud9/app.mjs")) return respond(&request, @embedFile("static/app.mjs"), "text/javascript; charset=utf-8", .ok);
if (std.mem.eql(u8, path, "/_cloud9/client.mjs")) return respond(&request, @embedFile("static/client.mjs"), "text/javascript; charset=utf-8", .ok);
if (std.mem.eql(u8, path, "/_cloud9/style.css")) return respond(&request, @embedFile("static/style.css"), "text/css; charset=utf-8", .ok);
if (std.mem.eql(u8, path, "/_cloud9/cloud9.wasm")) return respond(&request, @embedFile("client.wasm"), "application/wasm", .ok);
if (std.mem.eql(u8, path, "/_cloud9") or std.mem.startsWith(u8, path, "/_cloud9/"))
return respond(&request, "Not found\n", "text/plain", .not_found);
// Any other path boots the browser client (it resolves the path in 9P).
return respond(&request, @embedFile("static/index.html"), "text/html; charset=utf-8", .ok);
}
fn wsSession(s: *Session, request: *std.http.Server.Request) !void {
const app = s.app;
s.is_ws = true;
s.ws = try c9.http.accept(request);
s.conn = MuxT.Conn.init(app.m, s.sink());
defer s.conn.deinit();
while (true) {
const message = s.ws.receive(&s.frame) catch return;
switch (message.opcode) {
.binary => app.m.forward(&s.conn, message.data),
.ping => {
s.wmutex.lockUncancelable(app.io);
defer s.wmutex.unlock(app.io);
s.ws.send(message.data, .pong, null) catch return;
},
.pong => {},
.close => {
s.wmutex.lockUncancelable(app.io);
defer s.wmutex.unlock(app.io);
s.ws.send(message.data, .close, null) catch {};
return;
},
else => return,
}
}
}
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();
}
|