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
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);
}