2017-10-16 19:43:35 +02:00
|
|
|
//! Static files support.
|
2017-12-03 23:22:04 +01:00
|
|
|
|
|
|
|
// //! TODO: needs to re-implement actual files handling, current impl blocks
|
2017-10-16 10:19:23 +02:00
|
|
|
use std::io;
|
|
|
|
use std::io::Read;
|
|
|
|
use std::fmt::Write;
|
|
|
|
use std::fs::{File, DirEntry};
|
2017-12-04 01:57:25 +01:00
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use std::ops::{Deref, DerefMut};
|
2017-10-15 07:52:38 +02:00
|
|
|
|
2017-10-16 10:19:23 +02:00
|
|
|
use mime_guess::get_mime_type;
|
2018-01-13 20:33:42 +01:00
|
|
|
|
2017-12-08 01:22:26 +01:00
|
|
|
use param::FromParam;
|
2017-12-14 18:43:42 +01:00
|
|
|
use handler::{Handler, Responder};
|
2018-01-13 20:33:42 +01:00
|
|
|
use headers::ContentEncoding;
|
2017-10-15 07:52:38 +02:00
|
|
|
use httprequest::HttpRequest;
|
2017-10-24 08:25:32 +02:00
|
|
|
use httpresponse::HttpResponse;
|
2018-03-02 04:12:59 +01:00
|
|
|
use httpcodes::{HttpOk, HttpFound};
|
2017-12-04 01:57:25 +01:00
|
|
|
|
|
|
|
/// A file with an associated name; responds with the Content-Type based on the
|
|
|
|
/// file extension.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct NamedFile(PathBuf, File);
|
|
|
|
|
|
|
|
impl NamedFile {
|
|
|
|
/// Attempts to open a file in read-only mode.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// use actix_web::fs::NamedFile;
|
|
|
|
///
|
|
|
|
/// # #[allow(unused_variables)]
|
|
|
|
/// let file = NamedFile::open("foo.txt");
|
|
|
|
/// ```
|
|
|
|
pub fn open<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> {
|
|
|
|
let file = File::open(path.as_ref())?;
|
|
|
|
Ok(NamedFile(path.as_ref().to_path_buf(), file))
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Returns reference to the underlying `File` object.
|
|
|
|
#[inline]
|
|
|
|
pub fn file(&self) -> &File {
|
|
|
|
&self.1
|
|
|
|
}
|
|
|
|
|
|
|
|
/// Retrieve the path of this file.
|
|
|
|
///
|
|
|
|
/// # Examples
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// # use std::io;
|
|
|
|
/// use actix_web::fs::NamedFile;
|
|
|
|
///
|
|
|
|
/// # #[allow(dead_code)]
|
|
|
|
/// # fn path() -> io::Result<()> {
|
|
|
|
/// let file = NamedFile::open("test.txt")?;
|
|
|
|
/// assert_eq!(file.path().as_os_str(), "foo.txt");
|
|
|
|
/// # Ok(())
|
|
|
|
/// # }
|
|
|
|
/// ```
|
|
|
|
#[inline]
|
|
|
|
pub fn path(&self) -> &Path {
|
|
|
|
self.0.as_path()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Deref for NamedFile {
|
|
|
|
type Target = File;
|
|
|
|
|
|
|
|
fn deref(&self) -> &File {
|
|
|
|
&self.1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl DerefMut for NamedFile {
|
|
|
|
fn deref_mut(&mut self) -> &mut File {
|
|
|
|
&mut self.1
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl Responder for NamedFile {
|
2017-12-04 01:57:25 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = io::Error;
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(mut self, _: HttpRequest) -> Result<HttpResponse, io::Error> {
|
2018-03-02 04:12:59 +01:00
|
|
|
let mut resp = HttpOk.build();
|
2017-12-04 01:57:25 +01:00
|
|
|
if let Some(ext) = self.path().extension() {
|
|
|
|
let mime = get_mime_type(&ext.to_string_lossy());
|
|
|
|
resp.content_type(format!("{}", mime).as_str());
|
|
|
|
}
|
|
|
|
let mut data = Vec::new();
|
|
|
|
let _ = self.1.read_to_end(&mut data);
|
|
|
|
Ok(resp.body(data).unwrap())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// A directory; responds with the generated directory listing.
|
|
|
|
#[derive(Debug)]
|
|
|
|
pub struct Directory{
|
|
|
|
base: PathBuf,
|
|
|
|
path: PathBuf
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Directory {
|
|
|
|
pub fn new(base: PathBuf, path: PathBuf) -> Directory {
|
2018-02-26 23:33:56 +01:00
|
|
|
Directory { base, path }
|
2017-12-04 01:57:25 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
fn can_list(&self, entry: &io::Result<DirEntry>) -> bool {
|
|
|
|
if let Ok(ref entry) = *entry {
|
|
|
|
if let Some(name) = entry.file_name().to_str() {
|
|
|
|
if name.starts_with('.') {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if let Ok(ref md) = entry.metadata() {
|
|
|
|
let ft = md.file_type();
|
|
|
|
return ft.is_dir() || ft.is_file() || ft.is_symlink()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl Responder for Directory {
|
2017-12-04 01:57:25 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = io::Error;
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
|
2017-12-04 01:57:25 +01:00
|
|
|
let index_of = format!("Index of {}", req.path());
|
|
|
|
let mut body = String::new();
|
|
|
|
let base = Path::new(req.path());
|
|
|
|
|
|
|
|
for entry in self.path.read_dir()? {
|
|
|
|
if self.can_list(&entry) {
|
|
|
|
let entry = entry.unwrap();
|
2018-01-13 09:37:27 +01:00
|
|
|
let p = match entry.path().strip_prefix(&self.path) {
|
2017-12-04 01:57:25 +01:00
|
|
|
Ok(p) => base.join(p),
|
|
|
|
Err(_) => continue
|
|
|
|
};
|
|
|
|
// show file url as relative to static path
|
|
|
|
let file_url = format!("{}", p.to_string_lossy());
|
|
|
|
|
|
|
|
// if file is a directory, add '/' to the end of the name
|
|
|
|
if let Ok(metadata) = entry.metadata() {
|
|
|
|
if metadata.is_dir() {
|
|
|
|
let _ = write!(body, "<li><a href=\"{}\">{}/</a></li>",
|
|
|
|
file_url, entry.file_name().to_string_lossy());
|
|
|
|
} else {
|
|
|
|
let _ = write!(body, "<li><a href=\"{}\">{}</a></li>",
|
|
|
|
file_url, entry.file_name().to_string_lossy());
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let html = format!("<html>\
|
|
|
|
<head><title>{}</title></head>\
|
|
|
|
<body><h1>{}</h1>\
|
|
|
|
<ul>\
|
|
|
|
{}\
|
|
|
|
</ul></body>\n</html>", index_of, index_of, body);
|
2018-03-02 04:12:59 +01:00
|
|
|
Ok(HttpOk.build()
|
2017-12-04 01:57:25 +01:00
|
|
|
.content_type("text/html; charset=utf-8")
|
|
|
|
.body(html).unwrap())
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This enum represents all filesystem elements.
|
|
|
|
pub enum FilesystemElement {
|
|
|
|
File(NamedFile),
|
|
|
|
Directory(Directory),
|
2018-01-29 12:23:45 +01:00
|
|
|
Redirect(HttpResponse),
|
2017-12-04 01:57:25 +01:00
|
|
|
}
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
impl Responder for FilesystemElement {
|
2017-12-04 01:57:25 +01:00
|
|
|
type Item = HttpResponse;
|
|
|
|
type Error = io::Error;
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
fn respond_to(self, req: HttpRequest) -> Result<HttpResponse, io::Error> {
|
2017-12-04 01:57:25 +01:00
|
|
|
match self {
|
2017-12-14 18:43:42 +01:00
|
|
|
FilesystemElement::File(file) => file.respond_to(req),
|
|
|
|
FilesystemElement::Directory(dir) => dir.respond_to(req),
|
2018-01-29 12:23:45 +01:00
|
|
|
FilesystemElement::Redirect(resp) => Ok(resp),
|
2017-12-04 01:57:25 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-10-15 07:52:38 +02:00
|
|
|
|
2017-10-16 10:19:23 +02:00
|
|
|
/// Static files handling
|
|
|
|
///
|
2018-01-03 00:23:31 +01:00
|
|
|
/// `StaticFile` handler must be registered with `Application::handler()` method,
|
|
|
|
/// because `StaticFile` handler requires access sub-path information.
|
2017-10-16 10:19:23 +02:00
|
|
|
///
|
|
|
|
/// ```rust
|
2017-12-06 20:00:39 +01:00
|
|
|
/// # extern crate actix_web;
|
|
|
|
/// use actix_web::{fs, Application};
|
2017-10-16 10:19:23 +02:00
|
|
|
///
|
|
|
|
/// fn main() {
|
2017-12-11 23:16:29 +01:00
|
|
|
/// let app = Application::new()
|
2018-01-03 00:23:31 +01:00
|
|
|
/// .handler("/static", fs::StaticFiles::new(".", true))
|
2017-10-16 10:19:23 +02:00
|
|
|
/// .finish();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-10-15 07:52:38 +02:00
|
|
|
pub struct StaticFiles {
|
2017-10-16 10:19:23 +02:00
|
|
|
directory: PathBuf,
|
|
|
|
accessible: bool,
|
2018-01-29 12:23:45 +01:00
|
|
|
index: Option<String>,
|
2017-12-04 01:58:31 +01:00
|
|
|
show_index: bool,
|
2017-11-25 19:52:43 +01:00
|
|
|
_chunk_size: usize,
|
|
|
|
_follow_symlinks: bool,
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl StaticFiles {
|
|
|
|
/// Create new `StaticFiles` instance
|
|
|
|
///
|
|
|
|
/// `dir` - base directory
|
2017-12-03 23:22:04 +01:00
|
|
|
///
|
2017-10-16 10:19:23 +02:00
|
|
|
/// `index` - show index for directory
|
2018-01-29 12:23:45 +01:00
|
|
|
pub fn new<T: Into<PathBuf>>(dir: T, index: bool) -> StaticFiles {
|
2017-10-16 10:19:23 +02:00
|
|
|
let dir = dir.into();
|
|
|
|
|
2017-10-22 07:59:09 +02:00
|
|
|
let (dir, access) = match dir.canonicalize() {
|
|
|
|
Ok(dir) => {
|
|
|
|
if dir.is_dir() {
|
|
|
|
(dir, true)
|
|
|
|
} else {
|
|
|
|
warn!("Is not directory `{:?}`", dir);
|
|
|
|
(dir, false)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
Err(err) => {
|
|
|
|
warn!("Static files directory `{:?}` error: {}", dir, err);
|
2017-10-16 10:19:23 +02:00
|
|
|
(dir, false)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
StaticFiles {
|
|
|
|
directory: dir,
|
|
|
|
accessible: access,
|
2018-01-29 12:23:45 +01:00
|
|
|
index: None,
|
2017-12-04 01:58:31 +01:00
|
|
|
show_index: index,
|
2017-11-25 19:52:43 +01:00
|
|
|
_chunk_size: 0,
|
|
|
|
_follow_symlinks: false,
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2018-01-29 12:23:45 +01:00
|
|
|
/// Set index file
|
|
|
|
///
|
|
|
|
/// Redirects to specific index file for directory "/" instead of
|
|
|
|
/// showing files listing.
|
|
|
|
pub fn index_file<T: Into<String>>(mut self, index: T) -> StaticFiles {
|
|
|
|
self.index = Some(index.into());
|
|
|
|
self
|
|
|
|
}
|
2017-10-15 07:52:38 +02:00
|
|
|
}
|
|
|
|
|
2017-11-29 22:26:55 +01:00
|
|
|
impl<S> Handler<S> for StaticFiles {
|
2017-12-04 01:57:25 +01:00
|
|
|
type Result = Result<FilesystemElement, io::Error>;
|
2017-10-15 07:52:38 +02:00
|
|
|
|
2017-12-26 18:00:45 +01:00
|
|
|
fn handle(&mut self, req: HttpRequest<S>) -> Self::Result {
|
2017-10-16 10:19:23 +02:00
|
|
|
if !self.accessible {
|
2017-12-04 01:57:25 +01:00
|
|
|
Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
|
2017-10-16 10:19:23 +02:00
|
|
|
} else {
|
2018-01-03 00:23:31 +01:00
|
|
|
let path = if let Some(path) = req.match_info().get("tail") {
|
2017-12-08 21:29:28 +01:00
|
|
|
path
|
|
|
|
} else {
|
|
|
|
return Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
|
|
|
|
};
|
|
|
|
|
|
|
|
let relpath = PathBuf::from_param(path)
|
2017-12-04 01:57:25 +01:00
|
|
|
.map_err(|_| io::Error::new(io::ErrorKind::NotFound, "not found"))?;
|
2017-10-16 10:19:23 +02:00
|
|
|
|
|
|
|
// full filepath
|
2017-12-04 01:57:25 +01:00
|
|
|
let path = self.directory.join(&relpath).canonicalize()?;
|
2017-10-16 10:19:23 +02:00
|
|
|
|
2017-12-04 01:57:25 +01:00
|
|
|
if path.is_dir() {
|
2018-01-29 12:23:45 +01:00
|
|
|
if let Some(ref redir_index) = self.index {
|
2018-02-07 22:31:09 +01:00
|
|
|
// TODO: Don't redirect, just return the index content.
|
|
|
|
// TODO: It'd be nice if there were a good usable URL manipulation library
|
|
|
|
let mut new_path: String = req.path().to_owned();
|
|
|
|
for el in relpath.iter() {
|
|
|
|
new_path.push_str(&el.to_string_lossy());
|
|
|
|
new_path.push('/');
|
|
|
|
}
|
|
|
|
new_path.push_str(redir_index);
|
2018-01-29 12:23:45 +01:00
|
|
|
Ok(FilesystemElement::Redirect(
|
2018-03-02 04:12:59 +01:00
|
|
|
HttpFound
|
2018-01-29 12:23:45 +01:00
|
|
|
.build()
|
2018-02-07 22:31:09 +01:00
|
|
|
.header::<_, &str>("LOCATION", &new_path)
|
2018-01-29 12:23:45 +01:00
|
|
|
.finish().unwrap()))
|
|
|
|
} else if self.show_index {
|
2017-12-04 01:58:31 +01:00
|
|
|
Ok(FilesystemElement::Directory(Directory::new(self.directory.clone(), path)))
|
|
|
|
} else {
|
|
|
|
Err(io::Error::new(io::ErrorKind::NotFound, "not found"))
|
|
|
|
}
|
2017-10-16 10:19:23 +02:00
|
|
|
} else {
|
2017-12-04 01:57:25 +01:00
|
|
|
Ok(FilesystemElement::File(NamedFile::open(path)?))
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
}
|
2017-10-15 07:52:38 +02:00
|
|
|
}
|
|
|
|
}
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod tests {
|
|
|
|
use super::*;
|
2018-01-29 12:23:45 +01:00
|
|
|
use http::{header, StatusCode};
|
2017-12-04 03:15:09 +01:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_named_file() {
|
|
|
|
assert!(NamedFile::open("test--").is_err());
|
|
|
|
let mut file = NamedFile::open("Cargo.toml").unwrap();
|
|
|
|
{ file.file();
|
|
|
|
let _f: &File = &file; }
|
|
|
|
{ let _f: &mut File = &mut file; }
|
|
|
|
|
2017-12-14 18:43:42 +01:00
|
|
|
let resp = file.respond_to(HttpRequest::default()).unwrap();
|
2017-12-04 03:15:09 +01:00
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml")
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_static_files() {
|
2018-01-03 00:23:31 +01:00
|
|
|
let mut st = StaticFiles::new(".", true);
|
2017-12-04 03:15:09 +01:00
|
|
|
st.accessible = false;
|
|
|
|
assert!(st.handle(HttpRequest::default()).is_err());
|
|
|
|
|
|
|
|
st.accessible = true;
|
|
|
|
st.show_index = false;
|
|
|
|
assert!(st.handle(HttpRequest::default()).is_err());
|
|
|
|
|
2017-12-08 21:29:28 +01:00
|
|
|
let mut req = HttpRequest::default();
|
|
|
|
req.match_info_mut().add("tail", "");
|
|
|
|
|
2017-12-04 03:15:09 +01:00
|
|
|
st.show_index = true;
|
2017-12-14 18:43:42 +01:00
|
|
|
let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap();
|
2017-12-04 03:15:09 +01:00
|
|
|
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/html; charset=utf-8");
|
|
|
|
assert!(resp.body().is_binary());
|
|
|
|
assert!(format!("{:?}", resp.body()).contains("README.md"));
|
|
|
|
}
|
2018-01-29 12:23:45 +01:00
|
|
|
|
|
|
|
#[test]
|
2018-02-07 22:31:09 +01:00
|
|
|
fn test_redirect_to_index() {
|
2018-01-29 12:23:45 +01:00
|
|
|
let mut st = StaticFiles::new(".", false).index_file("index.html");
|
|
|
|
let mut req = HttpRequest::default();
|
|
|
|
req.match_info_mut().add("tail", "guide");
|
|
|
|
|
|
|
|
let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
|
|
|
assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/guide/index.html");
|
2018-02-07 22:31:09 +01:00
|
|
|
|
|
|
|
let mut req = HttpRequest::default();
|
|
|
|
req.match_info_mut().add("tail", "guide/");
|
|
|
|
|
|
|
|
let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
|
|
|
assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/guide/index.html");
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_redirect_to_index_nested() {
|
|
|
|
let mut st = StaticFiles::new(".", false).index_file("Cargo.toml");
|
|
|
|
let mut req = HttpRequest::default();
|
|
|
|
req.match_info_mut().add("tail", "examples/basics");
|
|
|
|
|
|
|
|
let resp = st.handle(req).respond_to(HttpRequest::default()).unwrap();
|
|
|
|
assert_eq!(resp.status(), StatusCode::FOUND);
|
|
|
|
assert_eq!(resp.headers().get(header::LOCATION).unwrap(), "/examples/basics/Cargo.toml");
|
2018-01-29 12:23:45 +01:00
|
|
|
}
|
2017-12-04 03:15:09 +01:00
|
|
|
}
|