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
use crate::util::{open_with_metadata, RequestedPath};
use http::{Method, Request};
use mime_guess::{mime, Mime, MimeGuess};
use std::fs::Metadata;
use std::io::{Error as IoError, ErrorKind as IoErrorKind};
use std::path::PathBuf;
use tokio::fs::File;

/// The result of `resolve`.
///
/// Covers all the possible 'normal' scenarios encountered when serving static files.
#[derive(Debug)]
pub enum ResolveResult {
    /// The request was not `GET` or `HEAD` request,
    MethodNotMatched,
    /// The requested file does not exist.
    NotFound,
    /// The requested file could not be accessed.
    PermissionDenied,
    /// A directory was requested as a file.
    IsDirectory,
    /// The requested file was found.
    Found(File, Metadata, Mime),
}

/// Some IO errors are expected when serving files, and mapped to a regular result here.
fn map_open_err(err: IoError) -> Result<ResolveResult, IoError> {
    match err.kind() {
        IoErrorKind::NotFound => Ok(ResolveResult::NotFound),
        IoErrorKind::PermissionDenied => Ok(ResolveResult::PermissionDenied),
        _ => Err(err),
    }
}

/// Resolve the request by trying to find the file in the given root.
///
/// This root may be absolute or relative. The request is mapped onto the filesystem by appending
/// its URL path to the root path. If the filesystem path corresponds to a regular file, the
/// service will attempt to serve it. Otherwise, if the path corresponds to a directory containing
/// an `index.html`, the service will attempt to serve that instead.
///
/// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
/// Certain expected IO errors are handled, though, and simply reflected in the result. These are
/// `NotFound` and `PermissionDenied`.
pub async fn resolve<B>(
    root: impl Into<PathBuf>,
    req: &Request<B>,
) -> Result<ResolveResult, IoError> {
    // Handle only `GET`/`HEAD` and absolute paths.
    match *req.method() {
        Method::HEAD | Method::GET => {}
        _ => {
            return Ok(ResolveResult::MethodNotMatched);
        }
    }

    resolve_path(root, req.uri().path()).await
}

/// Resolve the request path by trying to find the file in the given root.
///
/// This root may be absolute or relative. The request path is mapped onto the filesystem by
/// appending it to the root path. If the filesystem path corresponds to a regular file, the
/// service will attempt to serve it. Otherwise, if the path corresponds to a directory containing
/// an `index.html`, the service will attempt to serve that instead.
///
/// The returned future may error for unexpected IO errors, passing on the `std::io::Error`.
/// Certain expected IO errors are handled, though, and simply reflected in the result. These are
/// `NotFound` and `PermissionDenied`.
///
/// Note that, unlike `resolve`, it is up to the caller to check the request method.
pub async fn resolve_path(
    root: impl Into<PathBuf>,
    request_path: &str,
) -> Result<ResolveResult, IoError> {
    let RequestedPath {
        sanitized,
        is_dir_request,
    } = RequestedPath::resolve(request_path);

    let mut full_path = root.into();
    full_path.extend(&sanitized);

    let (file, metadata) = match open_with_metadata(&full_path).await {
        Ok(pair) => pair,
        Err(err) => return map_open_err(err),
    };

    // The resolved `full_path` doesn't contain the trailing slash anymore, so we may
    // have opened a file for a directory request, which we treat as 'not found'.
    if is_dir_request && !metadata.is_dir() {
        return Ok(ResolveResult::NotFound);
    }

    // We may have opened a directory for a file request, in which case we redirect.
    if !is_dir_request && metadata.is_dir() {
        return Ok(ResolveResult::IsDirectory);
    }

    // If not a directory, serve this file.
    if !is_dir_request {
        let mimetype = set_charset(MimeGuess::from_path(&full_path).first_or_octet_stream());
        return Ok(ResolveResult::Found(file, metadata, mimetype));
    }

    // Resolve the directory index.
    full_path.push("index.html");
    let (file, metadata) = match open_with_metadata(&full_path).await {
        Ok(pair) => pair,
        Err(err) => return map_open_err(err),
    };

    // The directory index cannot itself be a directory.
    if metadata.is_dir() {
        return Ok(ResolveResult::NotFound);
    }

    // Serve this file.
    let mimetype = MimeGuess::from_path(full_path).first_or_octet_stream();
    Ok(ResolveResult::Found(file, metadata, mimetype))
}

fn set_charset(mimetype: Mime) -> Mime {
    if mimetype == mime::APPLICATION_JAVASCRIPT {
        return mime::APPLICATION_JAVASCRIPT_UTF_8;
    }
    if mimetype == mime::TEXT_JAVASCRIPT {
        return "text/javascript; charset=utf-8".parse().unwrap();
    }
    mimetype
}