fediglam/src/http/server.zig

73 lines
2.6 KiB
Zig

const std = @import("std");
const util = @import("util");
const http = @import("./lib.zig");
const response = @import("./server/response.zig");
const request = @import("./request.zig");
pub const Response = struct {
alloc: std.mem.Allocator,
stream: std.net.Stream,
should_close: bool = false,
pub const Stream = response.ResponseStream(std.net.Stream.Writer);
pub fn open(self: *Response, status: http.Status, headers: *const http.Fields) !Stream {
if (headers.get("Connection")) |hdr| {
if (std.ascii.indexOfIgnoreCase(hdr, "close")) |_| self.should_close = true;
}
return response.open(self.alloc, self.stream.writer(), headers, status);
}
pub fn upgrade(self: *Response, status: http.Status, headers: *const http.Fields) !std.net.Stream {
try response.writeRequestHeader(self.stream.writer(), headers, status);
return self.stream;
}
};
const Request = http.Request;
const request_buf_size = 1 << 16;
pub fn serveConn(conn: std.net.StreamServer.Connection, ctx: anytype, handler: anytype, alloc: std.mem.Allocator) !void {
// TODO: Timeouts
while (true) {
std.log.debug("waiting for request", .{});
var arena = std.heap.ArenaAllocator.init(alloc);
defer arena.deinit();
var req = request.parse(arena.allocator(), conn.stream.reader()) catch |err| {
return handleError(conn.stream.writer(), err) catch {};
};
std.log.debug("done parsing", .{});
var res = Response{
.alloc = arena.allocator(),
.stream = conn.stream,
};
handler(ctx, &req, &res);
std.log.debug("done handling", .{});
if (req.headers.get("Connection")) |hdr| {
if (std.ascii.indexOfIgnoreCase(hdr, "close")) |_| return;
} else if (req.headers.get("Keep-Alive")) |hdr| {
std.log.debug("keep-alive: {s}", .{hdr});
} else if (req.protocol == .http_1_0) return;
if (res.should_close) return;
}
}
/// Writes an error response message and requests closure of the connection
fn handleError(writer: anytype, err: anyerror) !void {
const status: http.Status = switch (err) {
error.EndOfStream => return, // Do nothing, the client closed the connection
error.BadRequest => .bad_request,
error.UnsupportedMediaType => .unsupported_media_type,
error.HttpVersionNotSupported => .http_version_not_supported,
else => .internal_server_error,
};
try writer.print("HTTP/1.1 {} {?s}\r\nConnection: close\r\n\r\n", .{ @enumToInt(status), status.phrase() });
}