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
use log::warn;
use nom::{error::Error as NomError, Err as NomErr, Offset, ParseTo};
use std::cmp::min;
use std::mem;
/// Primitives used to parse http using nom and simd optimization when applicable
pub mod primitives;
use crate::{
protocol::{
h1::parser::primitives::{
crlf, parse_chunk_header, parse_header, parse_header_or_cookie, parse_request_line,
parse_response_line, parse_single_crumb, parse_url,
},
utils::compare_no_case,
},
storage::{
AsBuffer, Block, BodySize, Chunk, ChunkHeader, Flags, Kawa, Kind, Pair, ParsingPhase,
StatusLine, Store,
},
};
#[inline]
fn handle_error<T: AsBuffer>(kawa: &Kawa<T>, error: NomErr<NomError<&[u8]>>) -> ParsingPhase {
match error {
NomErr::Error(error) | NomErr::Failure(error) => {
let index = kawa.storage.buffer().offset(error.input) as u32;
ParsingPhase::Error {
marker: kawa.parsing_phase.marker(),
kind: index.into(),
}
}
NomErr::Incomplete(_) => kawa.parsing_phase,
}
}
#[inline]
fn handle_recovery_error<T: AsBuffer>(
kawa: &Kawa<T>,
primary_error: NomError<&[u8]>,
recovery_error: NomErr<NomError<&[u8]>>,
) -> ParsingPhase {
match recovery_error {
NomErr::Error(_) | NomErr::Failure(_) => {
let index = kawa.storage.buffer().offset(primary_error.input) as u32;
ParsingPhase::Error {
marker: kawa.parsing_phase.marker(),
kind: index.into(),
}
}
NomErr::Incomplete(_) => kawa.parsing_phase,
}
}
/// Trims leading and trailing optional whitespace (OWS) as defined by
/// RFC 9110 §5.6.3: space (0x20) and horizontal tab (0x09).
#[inline]
fn trim_ows(mut data: &[u8]) -> &[u8] {
while let [b' ' | b'\t', rest @ ..] = data {
data = rest;
}
while let [rest @ .., b' ' | b'\t'] = data {
data = rest;
}
data
}
/// Returns true if the FINAL comma-separated transfer-coding token of a
/// Transfer-Encoding header value is `chunked`, case-insensitively, once
/// OWS has been trimmed from around the token (RFC 9112 §6.1).
#[inline]
fn ends_with_chunked_coding(val: &[u8]) -> bool {
const CHUNKED: &[u8] = b"chunked";
let last_token = val.rsplit(|&b| b == b',').next().unwrap_or(val);
compare_no_case(trim_ows(last_token), CHUNKED)
}
fn process_headers<T: AsBuffer>(kawa: &mut Kawa<T>) {
let buf = kawa.storage.buffer();
let (mut authority, path) = match &kawa.detached.status_line {
StatusLine::Request {
uri: Store::Slice(uri),
method: Store::Slice(method),
..
} => {
let uri = uri.data(buf);
let method = method.data(buf);
match parse_url(buf, method, uri) {
Some((authority, path)) => (authority, path),
_ => {
kawa.parsing_phase.error("Invalid URI".into());
return;
}
}
}
_ => (Store::Empty, Store::Empty),
};
// Transfer-Encoding is resolved up front, before Content-Length, because
// repeated Transfer-Encoding field lines combine (RFC 9110 §5.3) and the
// combined final transfer-coding is the final coding of the LAST line: a
// split "gzip" then "chunked" frames as chunked, while "chunked" then a
// later non-chunked line (e.g. "identity") does NOT -- the combined final
// coding wins, so an earlier "chunked" line must never latch chunked
// framing on its own. Knowing Transfer-Encoding presence up front also lets
// Content-Length processing honor RFC 9110 §6.3 (a present Transfer-Encoding
// overrides Content-Length) regardless of header order.
let mut transfer_encoding_present = false;
let mut transfer_encoding_final_chunked = false;
for block in &kawa.blocks {
if let Block::Header(header) = block {
if let Store::Slice(key) = &header.key {
if compare_no_case(key.data(buf), b"transfer-encoding") {
transfer_encoding_present = true;
transfer_encoding_final_chunked =
ends_with_chunked_coding(header.val.data(buf));
}
}
}
}
for block in &mut kawa.blocks {
if let Block::Header(header) = block {
let Store::Slice(key) = &header.key else {
unreachable!()
};
let key = key.data(buf);
if compare_no_case(key, b"host") {
// request line has higher priority than Host header
if let Store::Empty = authority {
mem::swap(&mut authority, &mut header.val);
}
header.elide(); // Host header is elided
} else if compare_no_case(key, b"content-length") {
if transfer_encoding_present {
// RFC 9110 §6.3: when both Transfer-Encoding and
// Content-Length are present, the Transfer-Encoding
// overrides the Content-Length. Drop every Content-Length
// so a single, unambiguous framing reaches downstream
// (anti-smuggling), and do not length-reconcile a value
// that no longer frames the body.
warn!(
"Found both a Transfer-Encoding and a Content-Length, ignoring the latter"
);
header.elide();
continue;
}
let length = match header.val.data(buf).parse_to() {
Some(length) => length,
None => {
kawa.parsing_phase
.error("Invalid Content-Length field value".into());
return;
}
};
match kawa.body_size {
BodySize::Empty => {
kawa.body_size = BodySize::Length(length);
}
BodySize::Length(previous_length) => {
if previous_length != length {
kawa.parsing_phase
.error("Inconsistent Content-Length information".into());
return;
} else {
header.elide();
}
}
// Unreachable while `transfer_encoding_present` is false
// (chunked framing is only selected after this loop); elide
// defensively rather than panic on network-controlled input.
BodySize::Chunked => header.elide(),
}
}
// Transfer-Encoding header lines are intentionally left in place
// (forwarded as received); their combined framing was resolved by
// the pre-scan above.
}
}
if transfer_encoding_present {
if transfer_encoding_final_chunked {
// The combined Transfer-Encoding ends in chunked -> chunked
// framing. Any Content-Length was already elided above.
kawa.body_size = BodySize::Chunked;
} else if kawa.kind == Kind::Request {
// RFC 9112 §6.3: a REQUEST whose combined Transfer-Encoding does
// not end in chunked has no reliably determinable body length, so
// reject rather than forward ambiguous framing.
kawa.parsing_phase
.error("Transfer-Encoding present without chunked as the final coding".into());
return;
}
// else: a RESPONSE with a non-chunked-final Transfer-Encoding is
// spec-valid and close-delimited (read until connection close). The
// Content-Length was removed above, so body_size stays Empty; a leading
// `chunked` line does NOT force chunked framing here, because the
// combined final coding is what determines message framing.
}
match &mut kawa.detached.status_line {
StatusLine::Request {
authority: old_authority,
path: old_path,
..
} => {
*old_authority = authority;
*old_path = path;
}
// RFC 2616, 10.2.5:
// The 204 response MUST NOT include a message-body, and thus is always
// terminated by the first empty line after the header fields.
// RFC 2616, 10.3.5:
// The 304 response MUST NOT contain a message-body, and thus is always
// terminated by the first empty line after the header fields.
// RFC 2616, 10.1:
// This class of status code indicates a provisional response,
// consisting only of the Status-Line and optional headers, and is
// terminated by an empty line.
StatusLine::Response { code, .. }
if *code == 204 || *code == 304 || (*code >= 100 && *code < 200) =>
{
kawa.body_size = BodySize::Length(0);
}
_ => {}
};
}
pub trait ParserCallbacks<T: AsBuffer> {
fn on_headers(&mut self, _kawa: &mut Kawa<T>) {}
}
pub struct NoCallbacks;
impl<T: AsBuffer> ParserCallbacks<T> for NoCallbacks {}
pub fn parse<T: AsBuffer, C: ParserCallbacks<T>>(kawa: &mut Kawa<T>, callbacks: &mut C) {
let mut need_processing = false;
loop {
let buf = kawa.storage.buffer();
let mut unparsed_buf = kawa.storage.unparsed_data();
while !unparsed_buf.is_empty() {
match kawa.parsing_phase {
ParsingPhase::StatusLine => {
match kawa.kind {
Kind::Request => match parse_request_line(unparsed_buf) {
Ok((i, (method, uri, version))) => {
kawa.detached.status_line = StatusLine::Request {
version,
method: Store::new_slice(buf, method),
uri: Store::new_slice(buf, uri),
authority: Store::Empty,
path: Store::Empty,
};
unparsed_buf = i;
}
Err(error) => {
kawa.parsing_phase = handle_error(kawa, error);
break;
}
},
Kind::Response => match parse_response_line(unparsed_buf) {
Ok((i, (version, status, code, reason))) => {
kawa.detached.status_line = StatusLine::Response {
version,
code,
status: Store::new_slice(buf, status),
reason: Store::new_slice(buf, reason),
};
unparsed_buf = i;
}
Err(error) => {
kawa.parsing_phase = handle_error(kawa, error);
break;
}
},
};
kawa.blocks.push_back(Block::StatusLine);
kawa.parsing_phase = ParsingPhase::Headers;
}
ParsingPhase::Headers => match parse_header_or_cookie(unparsed_buf) {
Ok((i, Some((key, val)))) => {
kawa.blocks.push_back(Block::Header(Pair {
key: Store::new_slice(buf, key),
val: Store::new_slice(buf, val),
}));
unparsed_buf = i;
}
Ok((i, None)) => {
kawa.blocks.push_back(Block::Cookies);
kawa.parsing_phase = ParsingPhase::Cookies { first: true };
unparsed_buf = i;
}
Err(NomErr::Incomplete(_)) => {
break;
}
Err(NomErr::Error(error)) | Err(NomErr::Failure(error)) => {
match crlf(unparsed_buf) {
Ok((i, _)) => {
need_processing = true;
unparsed_buf = i;
break;
}
Err(recovery_error) => {
kawa.parsing_phase =
handle_recovery_error(kawa, error, recovery_error);
break;
}
}
}
},
ParsingPhase::Cookies { ref mut first } => {
match parse_single_crumb(unparsed_buf, *first) {
Ok((i, (key, val))) => {
*first = false;
kawa.detached.jar.push_back(Pair {
key: Store::new_slice(buf, key),
val: Store::new_slice(buf, val),
});
unparsed_buf = i;
}
Err(NomErr::Incomplete(_)) => {
break;
}
Err(NomErr::Error(error)) | Err(NomErr::Failure(error)) => {
match crlf(unparsed_buf) {
Ok((i, _)) => {
kawa.parsing_phase = ParsingPhase::Headers;
unparsed_buf = i;
}
Err(recovery_error) => {
kawa.parsing_phase =
handle_recovery_error(kawa, error, recovery_error);
break;
}
}
}
}
}
ParsingPhase::Body => {
let len = unparsed_buf.len();
let taken = if kawa.body_size == BodySize::Empty {
len
} else {
let taken = min(len, kawa.expects);
kawa.expects -= taken;
taken
};
kawa.blocks.push_back(Block::Chunk(Chunk {
data: Store::new_slice(buf, &unparsed_buf[..taken]),
}));
if kawa.expects == 0 {
kawa.parsing_phase = ParsingPhase::Terminated;
kawa.blocks.push_back(Block::Flags(Flags {
end_body: true,
end_chunk: false,
end_header: false,
end_stream: true,
}));
}
unparsed_buf = &unparsed_buf[taken..];
}
ParsingPhase::Chunks { ref mut first } => {
if kawa.expects == 0 {
let (i, (size_hexa, size)) = match parse_chunk_header(*first, unparsed_buf)
{
Ok(ok) => {
*first = false;
ok
}
Err(error) => {
kawa.parsing_phase = handle_error(kawa, error);
break;
}
};
kawa.expects = size;
if size == 0 {
kawa.blocks.push_back(Block::Flags(Flags {
end_body: true,
end_chunk: false,
end_header: false,
end_stream: false,
}));
kawa.parsing_phase = ParsingPhase::Trailers;
} else {
kawa.blocks.push_back(Block::ChunkHeader(ChunkHeader {
length: Store::new_slice(buf, size_hexa),
}));
}
unparsed_buf = i;
} else {
let len = unparsed_buf.len();
let taken = min(len, kawa.expects);
kawa.expects -= taken;
kawa.blocks.push_back(Block::Chunk(Chunk {
data: Store::new_slice(buf, &unparsed_buf[..taken]),
}));
if kawa.expects == 0 {
kawa.blocks.push_back(Block::Flags(Flags {
end_body: false,
end_chunk: true,
end_header: false,
end_stream: false,
}));
}
unparsed_buf = &unparsed_buf[taken..];
}
}
ParsingPhase::Trailers => match parse_header(unparsed_buf) {
Ok((i, (key, val))) => {
kawa.blocks.push_back(Block::Header(Pair {
key: Store::new_slice(buf, key),
val: Store::new_slice(buf, val),
}));
unparsed_buf = i;
}
Err(NomErr::Incomplete(_)) => {
break;
}
Err(NomErr::Error(error)) | Err(NomErr::Failure(error)) => {
match crlf(unparsed_buf) {
Ok((i, _)) => {
kawa.parsing_phase = ParsingPhase::Terminated;
kawa.blocks.push_back(Block::Flags(Flags {
end_body: false,
end_chunk: false,
end_header: true,
end_stream: true,
}));
unparsed_buf = i;
break;
}
Err(recovery_error) => {
kawa.parsing_phase =
handle_recovery_error(kawa, error, recovery_error);
break;
}
}
}
},
ParsingPhase::Terminated | ParsingPhase::Error { .. } => break,
};
}
// it is absolutely essential that this line is called at the end of a parsing phase
// do not for any reason short circuit this line
kawa.storage.head = buf.offset(unparsed_buf);
if need_processing {
process_headers(kawa);
if kawa.is_error() {
return;
}
need_processing = false;
kawa.parsing_phase = match kawa.body_size {
BodySize::Chunked => ParsingPhase::Chunks { first: true },
BodySize::Length(0) => ParsingPhase::Terminated,
BodySize::Length(length) => {
kawa.expects = length;
ParsingPhase::Body
}
BodySize::Empty => {
kawa.expects = 1;
ParsingPhase::Body
}
};
callbacks.on_headers(kawa);
kawa.blocks.push_back(Block::Flags(Flags {
end_body: false,
end_chunk: false,
end_header: true,
end_stream: kawa.is_terminated(),
}));
} else {
return;
}
}
}