Skip to main content

compmd_host/
route.rs

1//! Which file a request names, or why it is refused ([hosting], decision 8): the serving contract's decision, apart
2//! from reading the file, so `respond` here and `@compmd/host`'s (this crate as WebAssembly) decide alike.
3//!
4//! [hosting]: https://github.com/comp-markdown/compmd/blob/main/docs/hosting.md
5
6use compmd_pack::{FilePath, Place};
7use http::Method;
8
9use crate::refusal::Refusal;
10
11/// What a request asks for: a file of the frames, a pack's file, or nothing the host serves.
12#[derive(Clone, Debug, PartialEq, Eq)]
13pub enum Route {
14    /// The frames' file at this path, in the bundle.
15    Frame(FilePath),
16    /// A pack's file, in the bundle or the store.
17    Pack(Place),
18    /// Refused, with why.
19    Refused(Refusal),
20}
21
22/// What a `method` request for `path` asks for, from a bundle whose frames' hash is `hash`.
23///
24/// The paths it answers are `/frames/<hash>/<path>` and `/packs/<place>`, where a path is a [`FilePath`], which can't
25/// leave its folder; another method than `GET` is refused with `405`, anything else with `404`.
26///
27/// ```
28/// use compmd_host::{route, Refusal, Route};
29///
30/// let route = route(&http::Method::GET, "/frames/1df336e75685de8c/strict.html", "1df336e75685de8c");
31/// assert!(matches!(route, Route::Frame(path) if path.as_str() == "strict.html"));
32/// let refused = compmd_host::route(&http::Method::GET, "/frames/1df336e75685de8c/../x", "1df336e75685de8c");
33/// assert_eq!(refused, Route::Refused(Refusal::NOT_SERVED));
34/// ```
35#[must_use]
36pub fn route(method: &Method, path: &str, hash: &str) -> Route {
37    if method != Method::GET {
38        return Route::Refused(Refusal::ONLY_GET);
39    }
40    file_of(path, hash).unwrap_or(Route::Refused(Refusal::NOT_SERVED))
41}
42
43/// The file `path` names, if it names one: each segment decoded first, so `my%20chart.js` is `my chart.js` and a
44/// decoded `..` is refused as a written one is (audit B12).
45fn file_of(path: &str, hash: &str) -> Option<Route> {
46    let decoded = path
47        .strip_prefix('/')?
48        .split('/')
49        .map(decoded)
50        .collect::<Option<Vec<String>>>()?;
51    let parts: Vec<&str> = decoded.iter().map(String::as_str).collect();
52    match parts.as_slice() {
53        ["frames", given, file @ ..] if *given == hash => {
54            FilePath::new(file.join("/")).ok().map(Route::Frame)
55        }
56        ["packs", place @ ..] => Place::from_parts(place).map(Route::Pack),
57        _ => None,
58    }
59}
60
61/// `segment` with its percent escapes decoded, as a URL's path segment is; `None` for an escape that isn't `%` and two
62/// hex digits, bytes that aren't UTF-8, or a `/` an escape would add, which would make another segment.
63fn decoded(segment: &str) -> Option<String> {
64    let bytes = segment.as_bytes();
65    let mut out = Vec::with_capacity(bytes.len());
66    let mut at = 0;
67    while let Some(&byte) = bytes.get(at) {
68        if byte == b'%' {
69            let hex = bytes.get(at + 1..at + 3)?;
70            if !hex.iter().all(u8::is_ascii_hexdigit) {
71                return None;
72            }
73            out.push(u8::from_str_radix(std::str::from_utf8(hex).ok()?, 16).ok()?);
74            at += 3;
75        } else {
76            out.push(byte);
77            at += 1;
78        }
79    }
80    String::from_utf8(out)
81        .ok()
82        .filter(|text| !text.contains('/'))
83}