2017-10-16 19:43:35 +02:00
|
|
|
//! Static files support.
|
|
|
|
//!
|
|
|
|
//! 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};
|
|
|
|
use std::path::PathBuf;
|
2017-10-15 07:52:38 +02:00
|
|
|
|
|
|
|
use task::Task;
|
|
|
|
use route::RouteHandler;
|
2017-10-16 10:19:23 +02:00
|
|
|
use mime_guess::get_mime_type;
|
2017-10-15 07:52:38 +02:00
|
|
|
use httprequest::HttpRequest;
|
2017-10-24 08:25:32 +02:00
|
|
|
use httpresponse::HttpResponse;
|
2017-11-25 19:52:43 +01:00
|
|
|
use httpcodes::{HTTPOk, HTTPNotFound, HTTPForbidden};
|
2017-10-15 07:52:38 +02:00
|
|
|
|
2017-10-16 10:19:23 +02:00
|
|
|
/// Static files handling
|
|
|
|
///
|
|
|
|
/// Can be registered with `Application::route_handler()`.
|
|
|
|
///
|
|
|
|
/// ```rust
|
|
|
|
/// extern crate actix_web;
|
|
|
|
/// use actix_web::*;
|
|
|
|
///
|
|
|
|
/// fn main() {
|
2017-10-22 03:54:24 +02:00
|
|
|
/// let app = Application::default("/")
|
2017-10-16 10:19:23 +02:00
|
|
|
/// .route_handler("/static", StaticFiles::new(".", true))
|
|
|
|
/// .finish();
|
|
|
|
/// }
|
|
|
|
/// ```
|
2017-10-15 07:52:38 +02:00
|
|
|
pub struct StaticFiles {
|
2017-10-16 10:19:23 +02:00
|
|
|
directory: PathBuf,
|
|
|
|
accessible: bool,
|
2017-11-25 19:52:43 +01:00
|
|
|
_show_index: bool,
|
|
|
|
_chunk_size: usize,
|
|
|
|
_follow_symlinks: bool,
|
2017-10-16 10:19:23 +02:00
|
|
|
prefix: String,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl StaticFiles {
|
|
|
|
/// Create new `StaticFiles` instance
|
|
|
|
///
|
|
|
|
/// `dir` - base directory
|
|
|
|
/// `index` - show index for directory
|
|
|
|
pub fn new<D: Into<PathBuf>>(dir: D, index: bool) -> StaticFiles {
|
|
|
|
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,
|
2017-11-25 19:52:43 +01:00
|
|
|
_show_index: index,
|
|
|
|
_chunk_size: 0,
|
|
|
|
_follow_symlinks: false,
|
2017-10-16 10:19:23 +02:00
|
|
|
prefix: String::new(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2017-11-27 02:30:35 +01:00
|
|
|
fn index(&self, relpath: &str, filename: &PathBuf) -> Result<HttpResponse, io::Error> {
|
2017-10-16 10:19:23 +02:00
|
|
|
let index_of = format!("Index of {}/{}", self.prefix, relpath);
|
|
|
|
let mut body = String::new();
|
|
|
|
|
|
|
|
for entry in filename.read_dir()? {
|
|
|
|
if self.can_list(&entry) {
|
|
|
|
let entry = entry.unwrap();
|
|
|
|
// show file url as relative to static path
|
|
|
|
let file_url = format!(
|
2017-10-21 02:16:17 +02:00
|
|
|
"{}/{}", self.prefix,
|
2017-10-16 10:19:23 +02:00
|
|
|
entry.path().strip_prefix(&self.directory).unwrap().to_string_lossy());
|
|
|
|
|
|
|
|
// if file is a directory, add '/' to the end of the name
|
2017-11-25 19:52:43 +01:00
|
|
|
if let Ok(metadata) = entry.metadata() {
|
2017-10-16 10:19:23 +02:00
|
|
|
if metadata.is_dir() {
|
|
|
|
//format!("<li><a href=\"{}\">{}</a></li>", file_url, file_name));
|
2017-11-25 19:52:43 +01:00
|
|
|
let _ = write!(body, "<li><a href=\"{}\">{}/</a></li>",
|
|
|
|
file_url, entry.file_name().to_string_lossy());
|
2017-10-16 10:19:23 +02:00
|
|
|
} else {
|
|
|
|
// write!(body, "{}/", entry.file_name())
|
2017-11-25 19:52:43 +01:00
|
|
|
let _ = write!(body, "<li><a href=\"{}\">{}</a></li>",
|
|
|
|
file_url, entry.file_name().to_string_lossy());
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
continue
|
2017-11-25 19:52:43 +01:00
|
|
|
}
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
let html = format!("<html>\
|
|
|
|
<head><title>{}</title></head>\
|
|
|
|
<body><h1>{}</h1>\
|
|
|
|
<ul>\
|
|
|
|
{}\
|
|
|
|
</ul></body>\n</html>", index_of, index_of, body);
|
|
|
|
Ok(
|
2017-11-27 07:31:29 +01:00
|
|
|
HTTPOk.build()
|
2017-10-16 10:19:23 +02:00
|
|
|
.content_type("text/html; charset=utf-8")
|
2017-10-24 08:25:32 +02:00
|
|
|
.body(html).unwrap()
|
2017-10-16 10:19:23 +02: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-10-15 07:52:38 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<S: 'static> RouteHandler<S> for StaticFiles {
|
|
|
|
|
2017-10-16 10:19:23 +02:00
|
|
|
fn set_prefix(&mut self, prefix: String) {
|
2017-10-21 06:08:38 +02:00
|
|
|
if prefix != "/" {
|
|
|
|
self.prefix += &prefix;
|
|
|
|
}
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
|
2017-11-29 04:49:17 +01:00
|
|
|
fn handle(&self, req: HttpRequest<S>, task: &mut Task) {
|
2017-10-16 10:19:23 +02:00
|
|
|
if !self.accessible {
|
2017-11-29 04:49:17 +01:00
|
|
|
task.reply(HTTPNotFound)
|
2017-10-16 10:19:23 +02:00
|
|
|
} else {
|
|
|
|
let mut hidden = false;
|
|
|
|
let filepath = req.path()[self.prefix.len()..]
|
|
|
|
.split('/').filter(|s| {
|
|
|
|
if s.starts_with('.') {
|
|
|
|
hidden = true;
|
|
|
|
}
|
|
|
|
!s.is_empty()
|
|
|
|
})
|
|
|
|
.fold(String::new(), |s, i| {s + "/" + i});
|
|
|
|
|
|
|
|
// hidden file
|
|
|
|
if hidden {
|
2017-11-29 04:49:17 +01:00
|
|
|
task.reply(HTTPNotFound)
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// full filepath
|
|
|
|
let idx = if filepath.starts_with('/') { 1 } else { 0 };
|
|
|
|
let filename = match self.directory.join(&filepath[idx..]).canonicalize() {
|
|
|
|
Ok(fname) => fname,
|
|
|
|
Err(err) => return match err.kind() {
|
2017-11-29 04:49:17 +01:00
|
|
|
io::ErrorKind::NotFound => task.reply(HTTPNotFound),
|
|
|
|
io::ErrorKind::PermissionDenied => task.reply(HTTPForbidden),
|
|
|
|
_ => task.error(err),
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
if filename.is_dir() {
|
2017-11-27 02:30:35 +01:00
|
|
|
match self.index(&filepath[idx..], &filename) {
|
2017-11-29 04:49:17 +01:00
|
|
|
Ok(resp) => task.reply(resp),
|
2017-10-16 10:19:23 +02:00
|
|
|
Err(err) => match err.kind() {
|
2017-11-29 04:49:17 +01:00
|
|
|
io::ErrorKind::NotFound => task.reply(HTTPNotFound),
|
|
|
|
io::ErrorKind::PermissionDenied => task.reply(HTTPForbidden),
|
|
|
|
_ => task.error(err),
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
} else {
|
2017-11-27 07:31:29 +01:00
|
|
|
let mut resp = HTTPOk.build();
|
2017-10-16 10:19:23 +02:00
|
|
|
if let Some(ext) = filename.extension() {
|
|
|
|
let mime = get_mime_type(&ext.to_string_lossy());
|
|
|
|
resp.content_type(format!("{}", mime).as_str());
|
|
|
|
}
|
|
|
|
match File::open(filename) {
|
|
|
|
Ok(mut file) => {
|
|
|
|
let mut data = Vec::new();
|
|
|
|
let _ = file.read_to_end(&mut data);
|
2017-11-29 04:49:17 +01:00
|
|
|
task.reply(resp.body(data).unwrap())
|
2017-10-16 10:19:23 +02:00
|
|
|
},
|
2017-11-29 04:49:17 +01:00
|
|
|
Err(err) => task.error(err),
|
2017-10-16 10:19:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2017-10-15 07:52:38 +02:00
|
|
|
}
|
|
|
|
}
|