robin/maivi

a tiny cute lua web framework

git clone https://git.robinwobin.dev/robin/maivi

robinmaivi: proper io usage6e07b35

push-srxvuswpkqxx
10.5 KiB377 linesraw
1const std = @import("std");
2const Io = std.Io;
3const http = std.http;
4const Request = http.Server.Request;
5const Status = http.Status;
6
7const fern = @import("fern");
8
9const handler = @import("handler.zig");
10const Connection = handler.Connection;
11const maivi = @import("root.zig");
12
13pub fn requestHeader(request: Request, name: []const u8) ?http.Header {
14    var it = request.iterateHeaders();
15    while (it.next()) |header|
16        if (std.mem.eql(u8, header.name, name)) return header;
17    return null;
18}
19
20const SERVER_HEADER: http.Header = .{
21    .name = "server",
22    .value = "maivi",
23};
24
25pub fn respond(request: *Request, buf: []u8, opts: struct {
26    content_length: ?u64 = null,
27    content_type: ContentType = .octetstream,
28    status: http.Status = .ok,
29    reason: ?[]const u8 = null,
30    headers: []const http.Header = &.{},
31}) !http.BodyWriter {
32    const headers = try std.mem.concat(maivi.allocator, http.Header, &.{
33        &.{SERVER_HEADER},
34        &.{opts.content_type.header()},
35        opts.headers,
36    });
37    defer maivi.allocator.free(headers);
38
39    return try request.respondStreaming(buf, .{
40        .content_length = opts.content_length,
41        .respond_options = .{
42            .status = opts.status,
43            .reason = opts.reason,
44            .extra_headers = headers,
45        },
46    });
47}
48
49// u usually want to use sendfile(2) to directly stream other FDs
50// luckily zig std is awesome and already implements everything
51//   b.writer.sendFileAll(file_reader: *Reader, .unlimited);
52// later on u probably wanna make it chunked too, see
53//   std.http.BodyWriter.chunkedSendFile
54// for reference :3
55
56pub fn sendfile(conn: *Connection, dir: std.Io.Dir, path: []const u8) !void {
57    const request = conn.request;
58
59    const sub_path = std.mem.cutPrefix(u8, path, "/") orelse path;
60    const file = try dir.openFile(conn.io, sub_path, .{});
61    defer file.close(conn.io);
62
63    const stat = try file.stat(conn.io);
64    if (stat.kind == .directory) return error.IsDirectory;
65    if (stat.kind != .file) return error.NonFile;
66    const size = stat.size;
67
68    const content_type = content_type_for_file(path) orelse .txt;
69
70    var wbuf: [0x0]u8 = undefined;
71    var b = try maivi.helpers.respond(request, &wbuf, .{
72        .content_length = size,
73        .content_type = content_type,
74    });
75    try b.flush();
76
77    var remaining = size;
78    var offset: i64 = 0;
79    while (remaining > 0) {
80        const count: usize = @intCast(@min(remaining, 0x7ffff000)); // ~2GiB
81        const ret = std.c.sendfile(conn.handle, file.handle, &offset, count);
82        if (ret == -1) {
83            const errno = std.c.errno(ret);
84            if (errno == .AGAIN or errno == .INTR) continue;
85            return error.SendFileFailed;
86        } else if (ret == 0)
87            return error.UnexpectedEndOfFile;
88        remaining -= @intCast(ret);
89    }
90
91    b.state = .end;
92}
93
94/// NOTE: returns allocated memory that can optionally be freed by the caller
95pub fn redirect(arena: std.mem.Allocator, request: *Request, uri: []const u8, code: ?Status) ![]http.Header {
96    const headers = try std.mem.concat(arena, http.Header, &.{
97        &.{SERVER_HEADER},
98        &.{.{ .name = "location", .value = uri }},
99    });
100
101    try request.respond(uri, .{
102        .status = code orelse Status.found,
103        .extra_headers = headers,
104    });
105
106    return headers;
107}
108
109pub fn statusFromErr(err: anyerror) ?Status {
110    return switch (err) {
111        error.FileNotFound => Status.not_found,
112        error.AccessDenied => Status.forbidden,
113        else => null,
114    };
115}
116
117pub fn content_type_for_file(path: []const u8) ?ContentType {
118    return .forExtension(std.fs.path.extension(path));
119}
120
121pub const ContentType = enum {
122    @"3g2",
123    @"3gp",
124    @"7z",
125    aac,
126    abw,
127    apng,
128    arc,
129    avi,
130    avif,
131    azw,
132    bin,
133    bmp,
134    bz,
135    bz2,
136    cda,
137    csh,
138    css,
139    csv,
140    doc,
141    docx,
142    eot,
143    epub,
144    gif,
145    gz,
146    htm,
147    html,
148    ico,
149    ics,
150    jar,
151    jpeg,
152    jpg,
153    js,
154    json,
155    jsonld,
156    m4a,
157    md,
158    midi,
159    mid,
160    mjs,
161    mp3,
162    mp4,
163    mpeg,
164    mpkg,
165    octetstream,
166    odp,
167    ods,
168    odt,
169    oga,
170    ogv,
171    ogx,
172    opus,
173    otf,
174    pdf,
175    php,
176    png,
177    ppt,
178    pptx,
179    rar,
180    rtf,
181    sh,
182    svg,
183    tar,
184    tiff,
185    tif,
186    tkt,
187    ts,
188    ttf,
189    txt,
190    vsd,
191    wasm,
192    wav,
193    weba,
194    webm,
195    webmanifest,
196    webp,
197    woff,
198    woff2,
199    xhtml,
200    xls,
201    xlsx,
202    xml,
203    xul,
204    zip,
205
206    pub fn header(self: ContentType) http.Header {
207        return .{
208            .name = "content-type",
209            .value = self.toHeader(),
210        };
211    }
212
213    fn toHeader(self: ContentType) []const u8 {
214        return switch (self) {
215            .@"3g2" => "audio/3gpp2",
216            .@"3gp" => "audio/3gpp",
217            .@"7z" => "application/x-7z-compressed",
218            .aac => "audio/aac",
219            .abw => "application/x-abiword",
220            .apng => "image/apng",
221            .arc => "application/x-freearc",
222            .avi => "video/x-msvideo",
223            .avif => "image/avif",
224            .azw => "application/vnd.amazon.ebook",
225            .bin => "application/octet-stream",
226            .bmp => "image/bmp",
227            .bz => "application/x-bzip",
228            .bz2 => "application/x-bzip2",
229            .cda => "application/x-cdf",
230            .csh => "application/x-csh",
231            .css => "text/css",
232            .csv => "text/csv",
233            .doc => "application/msword",
234            .docx => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
235            .eot => "application/vnd.ms-fontobject",
236            .epub => "application/epub+zip",
237            .gif => "image/gif",
238            .gz => "application/x-gzip",
239            .htm, .html => "text/html",
240            .ico => "image/vnd.microsoft.icon",
241            .ics => "text/calendar",
242            .jar => "application/java-archive",
243            .jpeg, .jpg => "image/jpeg",
244            .js => "text/javascript",
245            .json => "application/json",
246            .jsonld => "application/ld+json",
247            .m4a => "audio/mp4",
248            .md => "text/markdown",
249            .mid, .midi => "audio/x-midi",
250            .mjs => "text/javascript",
251            .mp3 => "audio/mpeg",
252            .mp4 => "video/mp4",
253            .mpeg => "video/mpeg",
254            .mpkg => "application/vnd.apple.installer+xml",
255            .octetstream => "application/octet-stream",
256            .odp => "application/vnd.oasis.opendocument.presentation",
257            .ods => "application/vnd.oasis.opendocument.spreadsheet",
258            .odt => "application/vnd.oasis.opendocument.text",
259            .oga => "audio/ogg",
260            .ogv => "video/ogg",
261            .ogx => "application/ogg",
262            .opus => "audio/ogg",
263            .otf => "font/otf",
264            .pdf => "application/pdf",
265            .php => "application/x-httpd-php",
266            .png => "image/png",
267            .ppt => "application/vnd.ms-powerpoint",
268            .pptx => "application/vnd.openxmlformats-officedocument.presentationml.presentation",
269            .rar => "application/vnd.rar",
270            .rtf => "application/rtf",
271            .sh => "application/x-sh",
272            .svg => "image/svg+xml",
273            .tar => "application/x-tar",
274            .tif, .tiff => "image/tiff",
275            .tkt => "text/trinket",
276            .ts => "video/mp2t",
277            .ttf => "font/ttf",
278            .txt => "text/plain",
279            .vsd => "application/vnd.visio",
280            .wasm => "text/wasm",
281            .wav => "audio/wav",
282            .weba => "audio/webm",
283            .webm => "video/webm",
284            .webmanifest => "application/manifest+json",
285            .webp => "image/webp",
286            .woff => "font/woff",
287            .woff2 => "font/woff2",
288            .xhtml => "application/xhtml+xml",
289            .xls => "application/vnd.ms-excel",
290            .xlsx => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
291            .xml => "application/xml",
292            .xul => "application/vnd.mozilla.xul+xml",
293            .zip => "application/x-zip-compressed",
294        };
295    }
296
297    pub fn forExtension(ext: []const u8) ?ContentType {
298        if (ext.len == 0) return null;
299        const temp = if (ext[0] == '.') ext[1..] else ext;
300        if (temp.len == 0) return null;
301        if (temp.len > 5) return null;
302
303        var normalized: [5]u8 = undefined;
304        for (temp, 0..) |c, i| {
305            normalized[i] = std.ascii.toLower(c);
306        }
307
308        return ContentType.map.get(normalized[0..temp.len]);
309    }
310
311    const map = std.StaticStringMap(@This()).initComptime(.{
312        .{ "css", .css },
313        .{ "csv", .csv },
314        .{ "eot", .eot },
315        .{ "gif", .gif },
316        .{ "gz", .gz },
317        .{ "htm", .html },
318        .{ "html", .html },
319        .{ "ico", .ico },
320        .{ "jpeg", .jpg },
321        .{ "jpg", .jpg },
322        .{ "js", .js },
323        .{ "json", .json },
324        .{ "otf", .otf },
325        .{ "pdf", .pdf },
326        .{ "png", .png },
327        .{ "svg", .svg },
328        .{ "tar", .tar },
329        .{ "ttf", .ttf },
330        .{ "txt", .txt },
331        .{ "wasm", .wasm },
332        .{ "webp", .webp },
333        .{ "woff", .woff },
334        .{ "woff2", .woff2 },
335        .{ "xml", .xml },
336    });
337};
338
339pub fn read_file(io: Io, allocator: std.mem.Allocator, dir: std.Io.Dir, path: []const u8) ![]const u8 {
340    fern.debug().ctx("helpers.read_file").str("path", path).log();
341
342    const sub_path = std.mem.cutPrefix(u8, path, "/") orelse path;
343    const file = try dir.openFile(io, sub_path, .{});
344    defer file.close(io);
345
346    const stat = try file.stat(io);
347    if (stat.kind == .directory) return error.IsDirectory;
348    if (stat.kind != .file) return error.NonFile;
349    const size = stat.size;
350
351    var buf: [0x400]u8 = undefined;
352    var file_reader = file.reader(io, &buf);
353    const reader = &file_reader.interface;
354    const contents = try reader.readAlloc(allocator, size);
355
356    return contents;
357}
358
359const SanitizationError = error{NoTrailingSlashes} || std.mem.Allocator.Error;
360pub fn sanitize(arena: std.mem.Allocator, path: []const u8) ![]u8 {
361    const buf = try arena.dupe(u8, path);
362    const decoded = std.Uri.percentDecodeInPlace(buf);
363
364    // redirect: no-trailing-slashes
365    if (path.len > 1 and std.mem.endsWith(u8, path, "/")) return error.TrailingSlash;
366
367    // replace double slash (//) with single slash (/)
368    return decoded[0..std.mem.collapseRepeatsLen(u8, decoded, '/')];
369}
370
371pub fn try_path(conn: *Connection, dir: std.Io.Dir, path: ?[]const u8) !bool {
372    sendfile(conn, dir, path orelse conn.path) catch |err| switch (err) {
373        error.FileNotFound => return false,
374        else => return err,
375    };
376    return true;
377}