seva 0.1.3

Simple directory http server inspired by Python's http.server
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
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
use std::{
    collections::BTreeMap,
    fmt::Display,
    io::{self, Empty, Read},
};

use chrono::{DateTime, Local};
use contracts::*;
use pest::{iterators::Pair, Parser as PestParser};
use pest_derive::Parser as PestDeriveParser;
use tracing::{trace, warn};

use crate::errors::{ParsingError, Result, SevaError};

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Request<'a> {
    pub method: HttpMethod,
    pub path: &'a str,
    //TODO: support repeated headers
    pub headers: BTreeMap<HeaderName, &'a str>,
    pub version: &'a str,
    pub time: DateTime<Local>,
}

impl<'a> Request<'a> {
    pub fn is_partial(&self) -> bool {
        self.headers.contains_key(&HeaderName::Range)
    }
    pub fn parse(req_str: &str) -> Result<Request> {
        trace!("Request::parse");
        let mut res = HttpParser::parse(Rule::request, req_str)
            .map_err(|e| ParsingError::PestRuleError(format!("{e:?}")))?;
        let req_rule = res.next().unwrap();
        Request::try_from(req_rule)
    }

    fn parse_headers(pair: Pair<'a, Rule>) -> Result<BTreeMap<HeaderName, &'a str>> {
        trace!("Request::parse_headers");
        let mut headers = BTreeMap::new();
        for hdr in pair.into_inner() {
            let mut hdr = hdr.into_inner();
            let hdr_name_opt = hdr.next().unwrap().as_str();
            if let Some(name) = HeaderName::from_str(hdr_name_opt) {
                let value = hdr.next().unwrap().as_str();
                headers.insert(name, value);
            } else {
                warn!("ignored unknown header: {hdr_name_opt}")
            }
        }

        Ok(headers)
    }
}
impl<'i> TryFrom<Pair<'i, Rule>> for Request<'i> {
    type Error = SevaError;
    fn try_from(
        pair: Pair<'i, Rule>,
    ) -> std::prelude::v1::Result<Self, Self::Error> {
        let mut iterator = pair.into_inner();
        let method = iterator.next().unwrap().try_into()?;
        let path = iterator.next().unwrap().as_str();
        let version = iterator.next().unwrap().as_str();
        let headers = match iterator.next() {
            Some(rule) => Request::parse_headers(rule)?,
            None => BTreeMap::new(),
        };
        let req = Self {
            method,
            path,
            version,
            headers,
            time: Local::now(),
        };

        Ok(req)
    }
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Response<B>
where
    B: Read,
{
    pub status: StatusCode,
    pub headers: BTreeMap<HeaderName, String>,
    pub body: B,
}
impl<B> Response<B>
where
    B: Read,
{
    pub fn new(
        status: StatusCode,
        headers: BTreeMap<HeaderName, String>,
        body: B,
    ) -> Response<B> {
        Self {
            status,
            headers,
            body,
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct ResponseBuilder<B> {
    status: StatusCode,
    headers: BTreeMap<HeaderName, String>,
    body: B,
}

impl ResponseBuilder<Empty> {
    pub fn new(
        status: StatusCode,
        headers: BTreeMap<HeaderName, String>,
    ) -> ResponseBuilder<Empty> {
        Self {
            status,
            headers,
            body: io::empty(),
        }
    }

    pub fn ok() -> ResponseBuilder<Empty> {
        Self::new(StatusCode::Ok, BTreeMap::new())
    }

    pub fn partial() -> ResponseBuilder<Empty> {
        Self::new(StatusCode::PartialContent, BTreeMap::new())
    }

    pub fn not_found() -> ResponseBuilder<Empty> {
        Self::new(StatusCode::NotFound, BTreeMap::new())
    }

    pub fn method_not_allowed() -> ResponseBuilder<Empty> {
        Self::new(StatusCode::MethodNotAllowed, BTreeMap::new())
    }

    #[debug_ensures(ret.headers.len() == 1)]
    pub fn redirect(location: &str) -> ResponseBuilder<Empty> {
        let mut headers = BTreeMap::new();
        headers.insert(HeaderName::Location, location.to_owned());
        Self::new(StatusCode::MovedPermanently, headers)
    }

    pub fn body<B: Read>(&self, body: B) -> ResponseBuilder<B> {
        ResponseBuilder {
            status: self.status,
            headers: self.headers.clone(),
            body,
        }
    }
}

impl<B> ResponseBuilder<B>
where
    B: Read,
{
    #[allow(unused)]
    pub fn header(&mut self, name: HeaderName, val: &str) -> &mut Self {
        self.headers.insert(name, val.to_owned());
        self
    }

    pub fn headers(
        &mut self,
        hdrs: impl IntoIterator<Item = (HeaderName, String)>,
    ) -> &mut Self {
        self.headers.extend(hdrs);
        self
    }

    #[allow(unused)]
    pub fn status(&mut self, status: StatusCode) -> &mut Self {
        self.status = status;
        self
    }

    pub fn build(self) -> Response<B> {
        Response::new(self.status, self.headers, self.body)
    }
}

/// HTTP defines a set of request methods to indicate the desired action to be
/// performed for a given resource.
///
/// Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum HttpMethod {
    /// The CONNECT method establishes a tunnel to the server identified by the
    /// target resource.
    Connect,
    /// The DELETE method deletes the specified resource.
    Delete,
    /// The GET method requests a representation of the specified resource.
    /// Requests using GET should only retrieve data.
    Get,
    /// The HEAD method asks for a response identical to a GET request, but
    /// without the response body.
    Head,
    /// The OPTIONS method describes the communication options for the target
    /// resource.
    Options,
    /// The PATCH method applies partial modifications to a resource.
    Patch,
    /// The POST method submits an entity to the specified resource, often
    /// causing a change in state or side effects on the server
    Post,
    /// The PUT method replaces all current representations of the target
    /// resource with the request payload.
    Put,
    /// The TRACE method performs a message loop-back test along the path to the
    /// target resource.
    Trace,
}

impl<'i> TryFrom<Pair<'i, Rule>> for HttpMethod {
    type Error = ParsingError;
    fn try_from(
        value: Pair<'i, Rule>,
    ) -> std::prelude::v1::Result<Self, Self::Error> {
        Self::try_from(value.as_str().as_bytes())
    }
}

impl TryFrom<&[u8]> for HttpMethod {
    type Error = ParsingError;
    fn try_from(value: &[u8]) -> std::prelude::v1::Result<Self, Self::Error> {
        match value {
            b"CONNECT" => Ok(HttpMethod::Connect),
            b"DELETE" => Ok(HttpMethod::Delete),
            b"GET" => Ok(HttpMethod::Get),
            b"HEAD" => Ok(HttpMethod::Head),
            b"OPTIONS" => Ok(HttpMethod::Options),
            b"PATCH" => Ok(HttpMethod::Patch),
            b"POST" => Ok(HttpMethod::Post),
            b"PUT" => Ok(HttpMethod::Put),
            b"TRACE" => Ok(HttpMethod::Trace),
            _ => Err(ParsingError::UnknownMethod(
                String::from_utf8(value.to_vec()).unwrap_or_default(),
            )),
        }
    }
}
impl From<HttpMethod> for String {
    fn from(value: HttpMethod) -> Self {
        let s = match value {
            HttpMethod::Connect => "connect",
            HttpMethod::Delete => "delete",
            HttpMethod::Get => "get",
            HttpMethod::Head => "head",
            HttpMethod::Options => "options",
            HttpMethod::Patch => "patch",
            HttpMethod::Post => "post",
            HttpMethod::Put => "put",
            HttpMethod::Trace => "trace",
        };
        s.to_uppercase().to_string()
    }
}

impl Display for HttpMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&String::from(*self))
    }
}

#[derive(PestDeriveParser)]
#[grammar_inline = r#"
request = { request_line ~ headers? ~ NEWLINE }

request_line = _{ method ~ " "+ ~ uri ~ " "+ ~ "HTTP/" ~ version ~ NEWLINE }
uri = { (!whitespace ~ ANY)+ }
method = { ("CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE") }
version = { (ASCII_DIGIT | ".")+ }
whitespace = _{ " " | "\t" }

headers = { header+ }
header = { header_name ~ ":" ~ whitespace ~ header_value ~ NEWLINE }
header_name = { (!(NEWLINE | ":") ~ ANY)+ }
header_value = { (!NEWLINE ~ ANY)+ }

// accept-encoding header parser
ws = _{( " " | "\t")*}
accept_encoding = { encoding ~ ws ~ ("," ~ ws ~ encoding)* ~ EOI}
algo = {(ASCII_ALPHA+ | "identity" | "*")}
weight = {ws ~ ";" ~ ws ~ "q=" ~ qvalue}
qvalue = { ("0" ~ ("." ~ ASCII_DIGIT{,3}){,1}) | ("1" ~ ("." ~ "0"{,3}){,1}) }
encoding = { algo ~ weight*}

// Range header parser
//
// A range request can specify a single range or a set of ranges within a single representation.
//
// Range = ranges-specifier
// ranges-specifier = range-unit "=" range-set
// range-unit       = token
// range-set        = 1#range-spec
// range-spec       = int-range / suffix-range / other-range
// int-range        = first-pos "-" [ last-pos ]
// first-pos        = 1*DIGIT
// last-pos         = 1*DIGIT
// suffix-range     = "-" suffix-length
// suffix-length    = 1*DIGIT
// other-range      = 1*( %x21-2B / %x2D-7E ) ; 1*(VCHAR excluding comma)
//
bytes_range = { "bytes" ~ ws ~ "=" ~ ws ~ range_sets }
range_sets = _{ range_set ~ ws ~ ("," ~ ws ~ range_set)* ~ EOI }
range_set = _{(int_range | suffix_range)}
int_range = { first_pos ~ "-" ~ last_pos*}
suffix_range = { "-" ~ len}
first_pos = { ASCII_DIGIT+ }
last_pos = { ASCII_DIGIT+ }
len = { ASCII_DIGIT* }
"#]
pub struct HttpParser;

impl HttpParser {
    pub fn parse_bytes_range(val: &str, max_len: usize) -> Result<Vec<BytesRange>> {
        let br = HttpParser::parse(Rule::bytes_range, val)
            .map_err(|e| ParsingError::PestRuleError(format!("{e:?}")))?
            .next()
            .unwrap();
        let mut ranges = vec![];
        for pair in br.into_inner() {
            match pair.as_rule() {
                Rule::int_range => {
                    let mut inner = pair.into_inner();
                    let start = inner
                        .next()
                        .unwrap()
                        .as_str()
                        .parse()
                        .map_err(ParsingError::IntError)?;
                    let end = match inner.next() {
                        Some(r) => {
                            r.as_str().parse().map_err(ParsingError::IntError)?
                        }
                        None => max_len,
                    };
                    if start > end {
                        Err(ParsingError::InvalidRangeHeader(val.to_owned()))?;
                    }
                    let size = end - start;
                    ranges.push(BytesRange { start, size });
                }
                Rule::suffix_range => {
                    let mut inner = pair.into_inner();
                    let size = inner
                        .next()
                        .unwrap()
                        .as_str()
                        .parse()
                        .map_err(ParsingError::IntError)?;
                    if size >= max_len {
                        Err(ParsingError::InvalidRangeHeader(val.to_owned()))?;
                    }
                    let start = max_len - size;
                    ranges.push(BytesRange { start, size });
                }
                _ => {}
            }
        }
        if ranges.len() > 10 {
            return Err(ParsingError::InvalidRangeHeader(val.to_owned()))?;
        }

        Ok(ranges)
    }
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct BytesRange {
    pub start: usize,
    pub size: usize,
}

macro_rules! status_codes {
    (
        $(
            $(#[$docs:meta])+
            ($name:ident, $code:literal);
        )+
    ) => {
        /// HTTP response status codes indicate whether a specific HTTP request has been
        /// successfully completed
        ///
        /// Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Copy)]
        #[allow(unused)]
        pub enum StatusCode {
             $(
                $(#[$docs])*
                $name,
            )+
        }

        impl StatusCode {
            pub fn as_u16(&self) -> u16 {
                match *self {
                    $(
                        StatusCode::$name => $code,
                    )+
                }
            }
            fn as_string(&self) -> String {
                match *self {
                    $(
                        StatusCode::$name => Self::split_name(stringify!($name)),
                    )+
                }
            }

            fn split_name(name:&str) -> String {
                let mut parts = vec!();
                let mut cur = String::new();
                for ch in name.chars() {
                    if ch.is_uppercase() && !cur.is_empty() {
                        parts.push(cur.clone());
                        cur.clear();
                    }
                    cur.push(ch);
                }
                parts.push(cur);
                parts.join(" ").to_uppercase()
            }
        }

        impl std::fmt::Display for StatusCode {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                write!(f, "{}", self.as_string())
            }
        }

    };
}

status_codes! {

    /// This code is sent in response to an Upgrade request header from the
    /// client and indicates the protocol the server is switching to.
    (SwitchingProtocols,101);

    /// The request succeeded.
    (Ok, 200);

    /// There is no content to send for this request
    (NoContent,204);

    /// This response code is used when the Range header is sent from the client
    /// to request only part of a resource.
    (PartialContent,206);

    /// This redirect status response code indicates that the requested resource
    /// has been definitively moved to the URL given by the Location headers.
    (MovedPermanently,301);

    /// This is used for caching purposes. It tells the client that the response
    /// has not been modified, so the client can continue to use the same
    /// cached version of the response.
    (NotModified,304);

    /// The server cannot or will not process the request due to something that
    /// is perceived to be a client error.
    (BadRequest,400);

    /// The client does not have access rights to the content; that is, it is
    /// unauthorized, so the server is refusing to give the requested
    /// resource.
    (Forbidden,403);

    /// The server cannot find the requested resource
    (NotFound,404);

    /// The request method is known by the server but is not supported by the
    /// target resource.
    (MethodNotAllowed,405);

    /// Request entity is larger than limits defined by server.
    (PayloadTooLarge,413);

    /// The URI requested by the client is longer than the server is willing to
    /// interpret.
    (UriTooLong, 414);

    /// This response is sent on an idle connection
    (RequestTimeout,408);

    /// Indicates that a server cannot serve the requested ranges.
    (RangeNotSatisifiable, 416);

    /// The user has sent too many requests in a given amount of time ("rate
    /// limiting").
    (TooManyRequests,429);

    /// The server has encountered a situation it does not know how to handle.
    (InternalServerError,500);

    /// The request method is not supported by the server and cannot be handled.
    (NotImplemented, 501);

    /// The HTTP version used in the request is not supported by the server.
    (HttpVersionNotSupported, 505);

    /// Further extensions to the request are required for the server to fulfill it.
    (NotExtended,510);
}

macro_rules! header_names {
    (
        $(
            $(#[$docs:meta])+
            ($hname:ident, $name_str:literal);
        )+
    ) => {

        #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Copy)]
        pub enum HeaderName {
            $(
                $(#[$docs])*
                $hname,
            )+
        }
        impl HeaderName {
            pub fn as_str(&self) -> &str {
                match *self {
                    $(
                        HeaderName::$hname => $name_str,
                    )+
                }
            }

            pub fn from_str(s: &str) -> Option<HeaderName> {
                match s.to_lowercase().as_str().trim() {
                    $(
                        $name_str => Some(HeaderName::$hname),
                    )+
                    _ => None
                }
            }
        }
        impl std::fmt::Display for HeaderName {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str(self.as_str())
            }
        }

    };
}

// inspired by the standard_headers! macro in the http crate
header_names! {
    /// Advertises which content types the client is able to understand.
    (Accept, "accept");

    /// Advertises which content encoding the client is able to understand.
    (AcceptEncoding, "accept-encoding");

    /// Advertises which languages the client is able to understand.
    (AcceptLanguage, "accept-language");


    /// Marker used by the server to advertise partial request support.
    (AcceptRanges, "accept-ranges");

    /// Lists the set of methods support by a resource.
    (Allow, "allow");

    /// Specifies directives for caching mechanisms in both requests and
    /// responses.
    (CacheControl, "cache-control");

    /// Controls whether or not the network connection stays open after the
    /// current transaction finishes.
    (Connection, "connection");

    /// Indicates if the content is expected to be displayed inline.
    (ContentDisposition, "content-disposition");

    /// Used to compress the media-type.
    (ContentEncoding, "content-encoding");

    /// Indicates the size of the entity-body.
    (ContentLength, "content-length");

    /// Indicates where in a full body message a partial message belongs.
    (ContentRange, "content-range");

    /// Used to indicate the media type of the resource.
    (ContentType, "content-type");

    /// Contains the date and time at which the message was originated.
    (Date, "date");

    /// Identifier for a specific version of a resource.
    (ETag, "etag");

    /// Specifies the domain name of the server and (optionally) the TCP port
    /// number on which the server is listening.
    (Host, "host");

    /// Makes a request conditional based on the modification date.
    (IfModifiedSince, "if-modified-since");

    /// Makes the request conditional based on the last modification date.
    (IfUnmodifiedSince, "if-unmodified-since");

    /// Content-Types that are acceptable for the response.
    (LastModified, "last-modified");

    /// Indicates the URL to redirect a page to.
    (Location, "location");

    /// Indicates the part of a document that the server should return.
    (Range, "range");

    /// Contains the absolute or partial address from which a resource has been requested.
    (Referer, "referer");

    /// Contains information about the software used by the origin server to
    /// handle the request.
    (Server, "server");

    /// Contains a string that allows identifying the requesting client's
    /// software.
    (UserAgent, "user-agent");

    /// Describes the parts of the request message aside from the method and URL that influenced the content of the response it occurs in.
    (Vary, "vary");

    /// General HTTP header contains information about possible problems with
    /// the status of the message.
    (Warning, "warning");
}

#[cfg(test)]
mod tests {
    use std::io::Cursor;

    use maplit::btreemap;

    use super::*;

    #[test]
    fn request_parsing() -> Result<()> {
        // Given
        let req_str =
            "GET / HTTP/1.1\r\nHost: developer.mozilla.org\r\nAccept-Language: fr\r\n\r\n";
        // When
        let parsed: Request = Request::parse(req_str)?;
        // Then
        let expected = Request {
            method: HttpMethod::Get,
            path: "/",
            headers: btreemap! {
                HeaderName::AcceptLanguage => "fr",
                HeaderName::Host => "developer.mozilla.org",
            },
            version: "1.1",
            time: Local::now(),
        };
        assert_eq!(parsed.method, expected.method);
        assert_eq!(parsed.path, expected.path);
        assert_eq!(parsed.version, expected.version);
        assert_eq!(parsed.headers, expected.headers);
        Ok(())
    }

    #[test]
    fn accept_encoding_parser() -> Result<()> {
        let val = "compress;q=0.5, gzip";
        let res = HttpParser::parse(Rule::accept_encoding, val);
        assert!(res.is_ok());
        Ok(())
    }

    #[test]
    fn bytes_range_parser() -> Result<()> {
        for val in [
            "bytes=0-499",
            "bytes=500-999",
            "bytes=-500",
            "bytes=9500-",
            "bytes=0-0,-1",
            "bytes= 0-0, -2",
            "bytes= 0-999, 4500-5499, -1000",
            "bytes=500-600,601-999",
            "bytes=500-700,601-999",
        ] {
            let range = HttpParser::parse_bytes_range(val, 10000);
            assert!(range.is_ok(), "failed to parse: {val}. Reason: {range:?}");
        }
        Ok(())
    }

    #[test]
    fn response_body_type_mapping() -> Result<()> {
        let builder = ResponseBuilder::ok();
        let builder = builder.body(Cursor::new(vec![]));
        let expected = ResponseBuilder {
            status: StatusCode::Ok,
            headers: BTreeMap::new(),
            body: Cursor::new(vec![]),
        };
        assert_eq!(builder, expected);
        Ok(())
    }
}