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
use core::{file, Request, Response};
use futures::{future, prelude::*};
use hyper::{
	header::{HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
	Method,
};
use mime_guess::guess_mime_type;
use percent_encoding::percent_decode;
use proto::{MiddleWare, MiddleWareFuture};
use std::path::PathBuf;
use tokio::{fs::File, io::ErrorKind};

/// A static File Server implemented as a Middleware<Request>
#[derive(Clone, Debug)]
pub struct StaticFileServer {
	/// the root url for all your files. e.g `static`, `assets`
	/// request urls that begin with the supplied value for root would be
	/// matched.
	pub root: &'static str,
	/// Path to folder to serve your static files from.
	pub public: PathBuf,
}

impl StaticFileServer {
	/// Creates a StaticFileServer with the given
	/// root and pathbuf.
	pub fn new(root: &'static str, public: PathBuf) -> Self {
		Self { root, public }
	}
}

impl MiddleWare<Request> for StaticFileServer {
	fn call(&self, req: Request) -> MiddleWareFuture<Request> {
		let path = {
			req.path()
				.get(1..)
				.and_then(|path| {
					Some(
						percent_decode(path.as_ref())
							.decode_utf8_lossy()
							.into_owned(),
					)
				})
				.and_then(|path| {
					if path.contains("../") {
						None
					} else {
						Some(path)
					}
				})
		};

		let prefix = match path {
			Some(ref r) => r.get(..self.root.len()),
			None => None,
		};

		if prefix == Some(self.root) {
			// supported http-methods
			let method = { req.method().clone() };
			if method != Method::GET && method != Method::HEAD {
				return Box::new(future::ok(req));
			}

			let mut pathbuf = self.public.clone();
			if let Some(ref path) = path {
				if let Some(ref path) = path.get(self.root.len() + 1..) {
					pathbuf.push(path);
				}
			}
			if pathbuf.is_dir() {
				pathbuf.push("index.html");
			}

			let path_clone = pathbuf.clone();

			match method {
				Method::GET => {
					// if a MiddleWare<T> returns Err(Response)
					// that reponse is forwarded directly to the client.
					return Box::new(Response::new().with_file(pathbuf).then(|res| {
						match res {
							Ok(res) | Err(res) => Err(res),
						}
					}));
				}
				Method::HEAD => {
					let future = File::open(path_clone)
						.and_then(file::metadata)
						.then(|result| {
							match result {
								Ok((_, meta)) => {
									let mut res = Response::new();
									let mime_type = guess_mime_type(pathbuf);
									res.headers_mut().insert(
										CONTENT_LENGTH,
										HeaderValue::from_str(&meta.len().to_string()).unwrap(),
									);
									res.headers_mut().insert(
										CONTENT_TYPE,
										HeaderValue::from_str(mime_type.as_ref()).unwrap(),
									);
									return Err(res);
								}
								Err(err) => {
									error!("Error opening file: {}", err);
									match err.kind() {
										ErrorKind::NotFound => {
											let mut res = Response::new().with_status(404);
											return Err(res);
										}
										_ => {
											let mut res = Response::new().with_status(500);
											return Err(res);
										}
									}
								}
							}
						});

					return Box::new(future);
				}
				_ => {}
			}
		}

		Box::new(future::ok(req))
	}
}