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
use private::{SealedRequestLineParserState, SealedRequestParserState};
use std::collections::HashMap;
use thiserror::Error;
#[doc(hidden)]
const SPACE: u8 = ' ' as u8;
#[doc(hidden)]
const COLON: u8 = ':' as u8;
#[doc(hidden)]
const CR: u8 = '\r' as u8;
#[doc(hidden)]
const LF: u8 = '\n' as u8;
#[doc(hidden)]
const TAB: u8 = '\t' as u8;
type Result<T> = std::result::Result<T, ParsingError>;
type RequestLineParser<'a, S> = HttpRequestParser<'a, RequestLine<S>>;
#[doc(hidden)]
mod private {
pub trait SealedRequestParserState {}
impl<S> SealedRequestParserState for super::RequestLine<S> where S: super::RequestLineParserState {}
impl SealedRequestParserState for super::Header {}
impl SealedRequestParserState for super::Body {}
pub trait SealedRequestLineParserState {}
impl SealedRequestLineParserState for super::Method {}
impl SealedRequestLineParserState for super::Uri {}
impl SealedRequestLineParserState for super::Version {}
}
#[derive(Debug)]
pub struct Request<'a> {
method: &'a str,
request_uri: &'a str,
http_version: &'a str,
header: HashMap<&'a str, &'a str>,
body: &'a str,
}
impl<'a> Request<'a> {
fn new() -> Self {
Self {
method: "",
request_uri: "",
http_version: "",
header: HashMap::new(),
body: "",
}
}
}
pub trait Parse {
type NextState;
fn parse(self) -> Self::NextState;
}
pub trait RequestParserState: SealedRequestParserState {}
#[derive(Debug)]
pub struct HttpRequestParser<'a, S>
where
S: RequestParserState,
{
packet: &'a str,
request: Request<'a>,
state: S,
}
impl<'a, T> HttpRequestParser<'a, T>
where
T: RequestParserState,
{
fn skip_spaces(&mut self) {
let mut curr = 0;
let bytes = self.packet.as_bytes();
while curr < bytes.len() && bytes[curr] == SPACE {
curr += 1;
}
self.packet = &self.packet[curr..];
}
fn skip_crlf(&mut self) -> Result<()> {
let bytes = self.packet.as_bytes();
if self.packet.len() < 2 {
return Err(ParsingError::UnexpectedEndOfPacket);
}
if is_crlf(&[bytes[0], bytes[1]]) {
self.packet = &self.packet[2..];
}
Ok(())
}
fn parse_until_char(&mut self, chr: u8) -> &'a str {
let mut curr = 0;
let bytes = self.packet.as_bytes();
while curr < bytes.len() && bytes[curr] != chr {
curr += 1;
}
let res = &self.packet[..curr];
self.packet = &self.packet[curr..];
res
}
}
pub trait RequestLineParserState: SealedRequestLineParserState {}
#[derive(Debug)]
pub struct RequestLine<S>
where
S: RequestLineParserState,
{
state: S,
}
impl<S> RequestParserState for RequestLine<S> where S: RequestLineParserState {}
impl<'a, S> HttpRequestParser<'a, RequestLine<S>>
where
S: RequestLineParserState,
{
pub fn start(packet: &'a str) -> HttpRequestParser<'a, RequestLine<Method>> {
HttpRequestParser {
packet,
request: Request::new(),
state: RequestLine { state: Method },
}
}
}
#[derive(Debug)]
pub struct Method;
impl RequestLineParserState for Method {}
impl<'a> Parse for RequestLineParser<'a, Method> {
type NextState = Result<RequestLineParser<'a, Uri>>;
fn parse(mut self) -> Self::NextState {
let mut curr = 0;
let bytes = self.packet.as_bytes();
while bytes[curr] != SPACE {
curr += 1;
}
let method = &self.packet[0..curr];
if !is_valid_method(method) {
return Err(ParsingError::InvalidMethod(method.to_string()));
}
self.request.method = method;
self.packet = &self.packet[curr + 1..];
self.skip_spaces();
Ok(HttpRequestParser {
packet: self.packet,
request: self.request,
state: RequestLine { state: Uri },
})
}
}
#[derive(Debug)]
pub struct Uri;
impl RequestLineParserState for Uri {}
impl<'a> Parse for RequestLineParser<'a, Uri> {
type NextState = Result<RequestLineParser<'a, Version>>;
fn parse(mut self) -> Self::NextState {
self.request.request_uri = self.parse_until_char(SPACE);
self.skip_spaces();
Ok(HttpRequestParser {
packet: self.packet,
request: self.request,
state: RequestLine { state: Version },
})
}
}
#[derive(Debug)]
pub struct Version;
impl RequestLineParserState for Version {}
impl<'a> Parse for RequestLineParser<'a, Version> {
type NextState = Result<HttpRequestParser<'a, Header>>;
fn parse(mut self) -> Self::NextState {
let mut curr = 0;
let bytes = self.packet.as_bytes();
while !is_crlf(&[bytes[curr], bytes[curr + 1]]) {
curr += 1;
}
let version = &self.packet[..curr];
if !is_valid_version(version) {
return Err(ParsingError::InvalidVersion(version.to_string()));
}
self.request.http_version = version;
self.packet = &self.packet[curr + 2..];
Ok(HttpRequestParser {
packet: self.packet,
request: self.request,
state: Header,
})
}
}
#[derive(Debug)]
pub struct Header;
impl RequestParserState for Header {}
impl<'a> HttpRequestParser<'a, Header> {
fn parse_line(&mut self) {
let mut curr = 0;
let bytes = self.packet.as_bytes();
while !is_whitespace(bytes[curr]) && bytes[curr] != COLON {
curr += 1;
}
let key = &self.packet[0..curr];
self.packet = &self.packet[curr..];
let mut curr = 0;
let bytes = self.packet.as_bytes();
while is_whitespace(bytes[curr]) || bytes[curr] == COLON {
curr += 1;
}
self.packet = &self.packet[curr..];
let bytes = self.packet.as_bytes();
while bytes.len() >= 2 && !is_crlf(&[bytes[curr], bytes[curr + 1]]) {
curr += 1;
}
let value = &self.packet[0..curr];
self.packet = &self.packet[curr + 2..];
self.request.header.insert(key, value);
}
}
impl<'a> Parse for HttpRequestParser<'a, Header> {
type NextState = Result<HttpRequestParser<'a, Body>>;
fn parse(mut self) -> Self::NextState {
let mut bytes = self.packet.as_bytes();
while bytes.len() >= 2 && !is_crlf(&[bytes[0], bytes[1]]) {
self.parse_line();
bytes = self.packet.as_bytes();
}
self.skip_crlf()?;
Ok(HttpRequestParser {
packet: self.packet,
request: self.request,
state: Body,
})
}
}
#[derive(Debug)]
pub struct Body;
impl RequestParserState for Body {}
impl<'a> Parse for HttpRequestParser<'a, Body> {
type NextState = Request<'a>;
fn parse(mut self) -> Self::NextState {
self.request.body = self.packet;
self.request
}
}
fn is_valid_method(method: &str) -> bool {
match method {
"OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" => true,
_ => false,
}
}
fn is_valid_version(version: &str) -> bool {
match version {
"HTTP/1" | "HTTP/1.0" | "HTTP/1.1" | "HTTP/2" => true,
_ => false,
}
}
#[derive(Debug, Error)]
pub enum ParsingError {
#[error("invalid HTTP request method: {0}")]
InvalidMethod(String),
#[error("invalid HTTP version: {0}")]
InvalidVersion(String),
#[error("unexpected end of packet")]
UnexpectedEndOfPacket,
}
#[inline(always)]
fn is_crlf(bytes: &[u8; 2]) -> bool {
return bytes[0] == CR && bytes[1] == LF;
}
#[inline(always)]
fn is_whitespace(byte: u8) -> bool {
return byte == SPACE || byte == LF || byte == CR || byte == TAB;
}