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;

/// Possible transitions which can error return `Result<T, ParsingError>`.
type Result<T> = std::result::Result<T, ParsingError>;

/// Short form for `HttpRequestParser<'a, RequestLine<S>>`.
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 {}
}

/// The HTTP request structure.
///
/// This structure tries to follow RFC 2616 Section 5 <https://tools.ietf.org/html/rfc2616#section-5>.
/// Bellow you can see the expected request format.
/// ```text
/// Request = Request-Line
///           *(( general-header
///            | request-header
///            | entity-header ) CRLF)
///           CRLF
///           [ message-body ]
/// ```
/// *The implementation may not be complete as it is a work in progress.*
#[derive(Debug)]
pub struct Request<'a> {
    /// The method of the request, it can be one of: `OPTIONS`, `GET`, `HEAD`, `POST`, `PUT`, `DELETE`, `TRACE`, `CONNECT`
    method: &'a str,
    request_uri: &'a str,
    http_version: &'a str,
    header: HashMap<&'a str, &'a str>,
    body: &'a str,
}

// #[derive(Debug)]
// pub enum RequestMethod {
//     Options,
//     Get,
//     Head,
//     Post,
//     Put,
//     Delete,
//     Trace,
//     Connect,
// }

impl<'a> Request<'a> {
    /// Create a new `Request`.
    fn new() -> Self {
        Self {
            method: "",
            request_uri: "",
            http_version: "",
            header: HashMap::new(),
            body: "",
        }
    }
}

/// The provides the means of state transition for the parser,
/// it provides a single function `parse`,
/// when called it is supposed to parse the stream until the completion of the current state.
pub trait Parse {
    /// `NextState` type are of kind `Parser<'a, State>`
    /// Sadly we can't do `type NextParser = Parser<'a, Self::NextState>`
    /// and allow the final user to simply define `type NextState`
    /// until <https://github.com/rust-lang/rust/issues/29661> is resolved.
    type NextState;

    /// Parse the existing content consuming it in the process,
    /// in the end, return the next parser state.
    fn parse(self) -> Self::NextState;
}

/// A trait for the request parser states.
///
/// *This trait is sealed.*
pub trait RequestParserState: SealedRequestParserState {}

/// The `Parser` structure.
#[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,
{
    /// Skip existing spaces (other whitespace is not considered).
    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..];
    }

    /// If the next two characters are `\r\n`.
    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
    }
}
/// A trait for request line parser states.
///
/// *This trait is sealed.*
pub trait RequestLineParserState: SealedRequestLineParserState {}

/// The `RequestLine`, the parser starting state.
///
/// It is defined in RFC 2616 as follows:
/// ```text
/// Request-Line = Method SP Request-URI SP HTTP-Version CRLF
/// ```
/// Where `SP` is defined as ASCII character 32 and
/// `CRLF` the combination of ASCII characters 13 and 10 (`\r\n`).
#[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,
{
    /// Create a new `HttpRequestParser` which starts in `RequestLine<Method>`.
    pub fn start(packet: &'a str) -> HttpRequestParser<'a, RequestLine<Method>> {
        HttpRequestParser {
            packet,
            request: Request::new(),
            state: RequestLine { state: Method },
        }
    }
}

/// The method of the request line.
#[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 },
        })
    }
}

/// The URI of the request line.
#[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 },
        })
    }
}

/// The HTTP version part of the request line.
#[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,
        })
    }
}

/// The `Header` state.
///
/// *This state should be reached *after* the `RequestLine` state.*
#[derive(Debug)]
pub struct Header;

impl RequestParserState for Header {}

impl<'a> HttpRequestParser<'a, Header> {
    /// Parse a line in the header.
    fn parse_line(&mut self) {
        // Parse the line key
        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..];

        // Skip the separator which will match the regex `\s*:\s*`
        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..];

        // Parse the line value
        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,
        })
    }
}

/// The `Body` state.
///
/// *This state should be reached *after* the `Header` state.*
#[derive(Debug)]
pub struct Body;

impl RequestParserState for Body {}

impl<'a> Parse for HttpRequestParser<'a, Body> {
    /// Since the body is the last element of the request,
    /// the next possible state is final and thus returns the parsed request.
    type NextState = Request<'a>;

    /// Parse the body (which is composed of all remaining bytes)
    /// and return the next state.
    fn parse(mut self) -> Self::NextState {
        self.request.body = self.packet;
        self.request
    }
}

/// Checks if the given string slice is a valid HTTP method according to
/// IETF RFC 2616 [5.1.1](https://tools.ietf.org/html/rfc2616#section-5.1.1).
///
/// Supported valid methods are:
/// - `OPTIONS`
/// - `GET`
/// - `HEAD`
/// - `POST`
/// - `PUT`
/// - `DELETE`
/// - `TRACE`
/// - `CONNECT`
fn is_valid_method(method: &str) -> bool {
    match method {
        "OPTIONS" | "GET" | "HEAD" | "POST" | "PUT" | "DELETE" | "TRACE" | "CONNECT" => true,
        _ => false,
    }
}

/// Checks if the HTTP version is a valid version.
///
/// Versions considered valid are:
/// `HTTP/1`, `HTTP/1.0`, `HTTP/1.1`, `HTTP/2`
fn is_valid_version(version: &str) -> bool {
    match version {
        "HTTP/1" | "HTTP/1.0" | "HTTP/1.1" | "HTTP/2" => true,
        _ => false,
    }
}

/// Errors types for the parser.
#[derive(Debug, Error)]
pub enum ParsingError {
    /// An invalid request method was detected (e.g. `ADD`).
    #[error("invalid HTTP request method: {0}")]
    InvalidMethod(String),
    /// An invalid version was detected (e.g. `HTTP/0`).
    #[error("invalid HTTP version: {0}")]
    InvalidVersion(String),
    /// Unexpected reach to the end of the packet.
    #[error("unexpected end of packet")]
    UnexpectedEndOfPacket,
}

/// Check if a pair of bytes are CRLF.
#[inline(always)]
fn is_crlf(bytes: &[u8; 2]) -> bool {
    return bytes[0] == CR && bytes[1] == LF;
}

/// Check if a byte is whitespace.
#[inline(always)]
fn is_whitespace(byte: u8) -> bool {
    return byte == SPACE || byte == LF || byte == CR || byte == TAB;
}