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
use futures::{Async::*, Future, Poll};
use http::{Method, Request};
use mime_guess::Mime;
use std::convert::AsRef;
use std::fs::Metadata;
use std::io::{Error, ErrorKind};
use std::path::{Path, PathBuf};
use tokio::fs::File;
use util::{open_with_metadata, OpenWithMetadataFuture, RequestedPath};

/// 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 request URI was not just a path.
    UriNotMatched,
    /// 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),
}

/// State of `resolve` as it progresses.
enum ResolveState {
    /// Immediate result for method not matched.
    MethodNotMatched,
    /// Immediate result for route not matched.
    UriNotMatched,
    /// Wait for the file to open.
    WaitOpen(OpenWithMetadataFuture),
    /// Wait for the directory index file to open.
    WaitOpenIndex(OpenWithMetadataFuture),
}

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

/// Future returned by `resolve`.
pub struct ResolveFuture {
    /// Resolved filesystem path. An option, because we take ownership later.
    full_path: Option<PathBuf>,
    /// Whether this is a directory request. (Request path ends with a slash.)
    is_dir_request: bool,
    /// Current state of this future.
    state: ResolveState,
}

impl Future for ResolveFuture {
    type Item = ResolveResult;
    type Error = Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        loop {
            self.state = match self.state {
                ResolveState::MethodNotMatched => {
                    return Ok(Ready(ResolveResult::MethodNotMatched));
                }
                ResolveState::UriNotMatched => {
                    return Ok(Ready(ResolveResult::UriNotMatched));
                }
                ResolveState::WaitOpen(ref mut future) => {
                    let (file, metadata) = match future.poll() {
                        Ok(Ready(pair)) => pair,
                        Ok(NotReady) => return Ok(NotReady),
                        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 self.is_dir_request && !metadata.is_dir() {
                        return Ok(Ready(ResolveResult::NotFound));
                    }

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

                    // If not a directory, serve this file.
                    if !self.is_dir_request {
                        let mime = mime_guess::guess_mime_type(
                            self.full_path.as_ref().expect("invalid state"),
                        );
                        return Ok(Ready(ResolveResult::Found(file, metadata, mime)));
                    }

                    // Resolve the directory index.
                    let full_path = self.full_path.as_mut().expect("invalid state");
                    full_path.push("index.html");
                    ResolveState::WaitOpenIndex(open_with_metadata(full_path.to_path_buf()))
                }
                ResolveState::WaitOpenIndex(ref mut future) => {
                    let (file, metadata) = match future.poll() {
                        Ok(Ready(pair)) => pair,
                        Ok(NotReady) => return Ok(NotReady),
                        Err(err) => return map_open_err(err),
                    };

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

                    // Serve this file.
                    let mime = mime_guess::guess_mime_type(
                        self.full_path.as_ref().expect("invalid state"),
                    );
                    return Ok(Ready(ResolveResult::Found(file, metadata, mime)));
                }
            }
        }
    }
}

/// 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
/// their 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 fn resolve<B, P: AsRef<Path>>(root: P, req: &Request<B>) -> ResolveFuture {
    // Handle only `GET`/`HEAD` and absolute paths.
    match *req.method() {
        Method::HEAD | Method::GET => {}
        _ => {
            return ResolveFuture {
                full_path: None,
                is_dir_request: false,
                state: ResolveState::MethodNotMatched,
            };
        }
    }

    // Handle only simple path requests.
    if req.uri().scheme_part().is_some() || req.uri().host().is_some() {
        return ResolveFuture {
            full_path: None,
            is_dir_request: false,
            state: ResolveState::UriNotMatched,
        };
    }

    let RequestedPath {
        full_path,
        is_dir_request,
    } = RequestedPath::resolve(root.as_ref(), req.uri().path());

    let state = ResolveState::WaitOpen(open_with_metadata(full_path.clone()));
    let full_path = Some(full_path);
    ResolveFuture {
        full_path,
        is_dir_request,
        state,
    }
}