~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zttp

mirror of https://tangled.org/zat.dev/zttp

0
0
main
201 lines · 8.8 KB Raw History
const std = @import("std");
const Io = std.Io;

pub fn token(byte: u8) bool {
    return std.ascii.isAlphanumeric(byte) or std.mem.indexOfScalar(u8, "!#$%&'*+-.^_`|~", byte) != null;
}

pub fn field(line: []const u8) !void {
    const colon = std.mem.indexOfScalar(u8, line, ':') orelse return error.HttpHeadersInvalid;
    if (colon == 0) return error.HttpHeadersInvalid;
    for (line[0..colon]) |byte| if (!token(byte)) return error.HttpHeadersInvalid;
    for (line[colon + 1 ..]) |byte| if ((byte < 32 and byte != '\t') or byte == 127) return error.HttpHeadersInvalid;
    if (std.ascii.eqlIgnoreCase(line[0..colon], "content-length")) {
        const value = std.mem.trim(u8, line[colon + 1 ..], " \t");
        if (value.len == 0) return error.HttpHeadersInvalid;
        for (value) |byte| if (!std.ascii.isDigit(byte) and byte != ',' and byte != ' ' and byte != '\t') return error.HttpHeadersInvalid;
    }
}

pub fn fields(bytes: []const u8) !void {
    var lines = std.mem.splitSequence(u8, bytes, "\r\n");
    while (lines.next()) |line| {
        if (line.len == 0) continue;
        try field(line);
    }
}

fn chunkLine(line: []const u8) !void {
    if (!std.mem.endsWith(u8, line, "\r\n")) return error.HttpChunkInvalid;
    const content = line[0 .. line.len - 2];
    var index: usize = 0;
    var size: u64 = 0;
    while (index < content.len and std.ascii.isHex(content[index])) : (index += 1) {
        const digit = std.fmt.charToDigit(content[index], 16) catch unreachable;
        const multiplied = @mulWithOverflow(size, 16);
        const added = @addWithOverflow(multiplied[0], digit);
        if (multiplied[1] != 0 or added[1] != 0) return error.HttpChunkInvalid;
        size = added[0];
    }
    if (index == 0 or size > std.math.maxInt(u64) - 2) return error.HttpChunkInvalid;
    while (index < content.len) {
        while (index < content.len and (content[index] == ' ' or content[index] == '\t')) : (index += 1) {}
        if (index == content.len or content[index] != ';') return error.HttpChunkInvalid;
        index += 1;
        while (index < content.len and (content[index] == ' ' or content[index] == '\t')) : (index += 1) {}
        const name = index;
        while (index < content.len and token(content[index])) : (index += 1) {}
        if (index == name) return error.HttpChunkInvalid;
        while (index < content.len and (content[index] == ' ' or content[index] == '\t')) : (index += 1) {}
        if (index == content.len) return;
        if (content[index] == ';') continue;
        if (content[index] != '=') return error.HttpChunkInvalid;
        index += 1;
        while (index < content.len and (content[index] == ' ' or content[index] == '\t')) : (index += 1) {}
        if (index == content.len) return error.HttpChunkInvalid;
        if (content[index] == '"') {
            index += 1;
            var closed = false;
            while (index < content.len) : (index += 1) {
                var byte = content[index];
                if (byte == '"') {
                    index += 1;
                    closed = true;
                    break;
                }
                if (byte == '\\') {
                    index += 1;
                    if (index == content.len) return error.HttpChunkInvalid;
                    byte = content[index];
                }
                if ((byte < 32 and byte != '\t') or byte == 127) return error.HttpChunkInvalid;
            }
            if (!closed) return error.HttpChunkInvalid;
        } else {
            const value = index;
            while (index < content.len and token(content[index])) : (index += 1) {}
            if (index == value) return error.HttpChunkInvalid;
        }
    }
}

pub const CheckedTransfer = struct {
    interface: Io.Reader = .{ .buffer = &.{}, .seek = 0, .end = 0, .vtable = &.{ .stream = stream } },
    http: *std.http.Reader,
    inner: *Io.Reader,
    failure: ?anyerror = null,

    fn prepare(self: *CheckedTransfer) !void {
        const http = self.http;
        switch (http.state) {
            .body_remaining_chunk_len => |remaining| {
                switch (remaining) {
                    .head => {},
                    .rn => {
                        const bytes = try http.in.peekArray(2);
                        if (!std.mem.eql(u8, bytes, "\r\n")) return error.HttpChunkInvalid;
                        http.in.toss(2);
                        http.state.body_remaining_chunk_len = .head;
                    },
                    .n => {
                        if (try http.in.takeByte() != '\n') return error.HttpChunkInvalid;
                        http.state.body_remaining_chunk_len = .head;
                    },
                    else => return,
                }
                const line = try http.in.peekDelimiterInclusive('\n');
                try chunkLine(line);
            },
            else => {},
        }
    }

    fn stream(reader: *Io.Reader, writer: *Io.Writer, limit: Io.Limit) Io.Reader.StreamError!usize {
        const self: *CheckedTransfer = @alignCast(@fieldParentPtr("interface", reader));
        self.prepare() catch |err| {
            self.failure = switch (err) {
                error.EndOfStream => error.ResponseTruncated,
                error.StreamTooLong => error.HttpHeadersOversize,
                error.ReadFailed => null,
                else => err,
            };
            return error.ReadFailed;
        };
        const count = self.inner.stream(writer, limit) catch |err| switch (err) {
            error.EndOfStream => {
                switch (self.http.state) {
                    .ready, .body_none, .closing => {},
                    else => {
                        self.failure = error.ResponseTruncated;
                        return error.ReadFailed;
                    },
                }
                fields(self.http.trailers) catch |failure| {
                    self.failure = failure;
                    return error.ReadFailed;
                };
                return error.EndOfStream;
            },
            else => return err,
        };
        if (self.http.state == .ready) {
            fields(self.http.trailers) catch |err| {
                self.failure = err;
                return error.ReadFailed;
            };
        }
        return count;
    }
};

pub fn normalizeHead(allocator: std.mem.Allocator, bytes: []const u8) !?[]u8 {
    var lines = std.mem.splitSequence(u8, bytes, "\r\n");
    const status_line = lines.first();
    if (status_line.len < 13 or status_line[8] != ' ' or status_line[12] != ' ') return error.HttpHeadersInvalid;
    for (status_line[9..12]) |byte| if (!std.ascii.isDigit(byte)) return error.HttpHeadersInvalid;
    if (status_line[9] < '1' or status_line[9] > '5') return error.HttpHeadersInvalid;
    for (status_line[13..]) |byte| if ((byte < 32 and byte != '\t') or byte == 127) return error.HttpHeadersInvalid;
    var codings: std.ArrayList([]const u8) = .empty;
    defer codings.deinit(allocator);
    var has_transfer = false;
    while (lines.next()) |line| {
        if (line.len == 0) continue;
        try field(line);
        const colon = std.mem.indexOfScalar(u8, line, ':').?;
        if (!std.ascii.eqlIgnoreCase(line[0..colon], "transfer-encoding")) continue;
        has_transfer = true;
        var values = std.mem.splitScalar(u8, line[colon + 1 ..], ',');
        while (values.next()) |value| {
            const coding = std.mem.trim(u8, value, " \t");
            if (coding.len == 0) continue;
            for (coding) |byte| if (!token(byte)) return error.HttpHeadersInvalid;
            if (codings.items.len >= 8) return error.HttpHeadersOversize;
            try codings.append(allocator, coding);
        }
    }
    if (!has_transfer) return null;
    if (codings.items.len == 0) return error.HttpHeadersInvalid;
    for (codings.items, 0..) |coding, index| {
        if (std.ascii.eqlIgnoreCase(coding, "chunked") and index != codings.items.len - 1) return error.HttpHeadersInvalid;
    }
    var normalized: std.ArrayList(u8) = .empty;
    errdefer normalized.deinit(allocator);
    try normalized.appendSlice(allocator, status_line);
    try normalized.appendSlice(allocator, "\r\n");
    lines = std.mem.splitSequence(u8, bytes, "\r\n");
    _ = lines.next();
    while (lines.next()) |line| {
        if (line.len == 0) continue;
        const colon = std.mem.indexOfScalar(u8, line, ':').?;
        if (std.ascii.eqlIgnoreCase(line[0..colon], "transfer-encoding")) continue;
        try normalized.appendSlice(allocator, line);
        try normalized.appendSlice(allocator, "\r\n");
    }
    try normalized.appendSlice(allocator, "Transfer-Encoding: ");
    for (codings.items, 0..) |coding, index| {
        if (index != 0) try normalized.appendSlice(allocator, ", ");
        for (coding) |byte| try normalized.append(allocator, std.ascii.toLower(byte));
    }
    try normalized.appendSlice(allocator, "\r\n\r\n");
    return try normalized.toOwnedSlice(allocator);
}