aboutsummaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/args.rs10
-rw-r--r--src/errors.rs20
-rw-r--r--src/file_upload.rs152
-rw-r--r--src/listing.rs9
-rw-r--r--src/main.rs37
-rw-r--r--src/renderer.rs48
6 files changed, 271 insertions, 5 deletions
diff --git a/src/args.rs b/src/args.rs
index 4f0dbf7..bb52824 100644
--- a/src/args.rs
+++ b/src/args.rs
@@ -47,6 +47,14 @@ struct CLIArgs {
/// Do not follow symbolic links
#[structopt(short = "P", long = "no-symlinks")]
no_symlinks: bool,
+
+ /// Enable file uploading
+ #[structopt(short = "u", long = "upload-files")]
+ file_upload: bool,
+
+ /// Enable overriding existing files during file upload
+ #[structopt(short = "o", long = "overwrite-files")]
+ overwrite_files: bool,
}
/// Checks wether an interface is valid, i.e. it can be parsed into an IP address
@@ -100,5 +108,7 @@ pub fn parse_args() -> crate::MiniserveConfig {
path_explicitly_chosen,
no_symlinks: args.no_symlinks,
random_route,
+ overwrite_files: args.overwrite_files,
+ file_upload: args.file_upload,
}
}
diff --git a/src/errors.rs b/src/errors.rs
index 2aa5f58..21d9e07 100644
--- a/src/errors.rs
+++ b/src/errors.rs
@@ -1,6 +1,26 @@
use failure::{Backtrace, Context, Fail};
use std::fmt::{self, Debug, Display};
+/// Kinds of errors which might happen during file upload
+#[derive(Debug, Fail)]
+pub enum FileUploadErrorKind {
+ /// This error will occur when file overriding is off and a file with same name already exists
+ #[fail(display = "File with this name already exists")]
+ FileExist,
+ /// This error will occur when the server fails to process the HTTP header during file upload
+ #[fail(display = "Failed to parse incoming request")]
+ ParseError,
+ /// This error will occur when we fail to process the multipart request
+ #[fail(display = "Failed to process multipart request")]
+ MultipartError(actix_web::error::MultipartError),
+ /// This error may occur when trying to write the incoming file to disk
+ #[fail(display = "Failed to create or write to file")]
+ IOError(std::io::Error),
+ /// This error will occur when we he have insuffictent permissions to create new file
+ #[fail(display = "Insufficient permissions to create file")]
+ InsufficientPermissions,
+}
+
/// Kinds of errors which might happen during the generation of an archive
#[derive(Debug, Fail)]
pub enum CompressionErrorKind {
diff --git a/src/file_upload.rs b/src/file_upload.rs
new file mode 100644
index 0000000..273d12c
--- /dev/null
+++ b/src/file_upload.rs
@@ -0,0 +1,152 @@
+use crate::errors::FileUploadErrorKind;
+use crate::renderer::file_upload_error;
+use actix_web::{
+ dev, http::header, multipart, FromRequest, FutureResponse, HttpMessage, HttpRequest,
+ HttpResponse, Query,
+};
+use futures::{future, Future, Stream};
+use serde::Deserialize;
+use std::{
+ fs,
+ io::Write,
+ path::{Component, PathBuf},
+};
+
+/// Query parameters
+#[derive(Debug, Deserialize)]
+struct QueryParameters {
+ path: PathBuf,
+}
+
+/// Create future to save file.
+fn save_file(
+ field: multipart::Field<dev::Payload>,
+ file_path: PathBuf,
+ overwrite_files: bool,
+) -> Box<Future<Item = i64, Error = FileUploadErrorKind>> {
+ if !overwrite_files && file_path.exists() {
+ return Box::new(future::err(FileUploadErrorKind::FileExist));
+ }
+ let mut file = match std::fs::File::create(file_path) {
+ Ok(file) => file,
+ Err(e) => {
+ return Box::new(future::err(FileUploadErrorKind::IOError(e)));
+ }
+ };
+ Box::new(
+ field
+ .map_err(FileUploadErrorKind::MultipartError)
+ .fold(0i64, move |acc, bytes| {
+ let rt = file
+ .write_all(bytes.as_ref())
+ .map(|_| acc + bytes.len() as i64)
+ .map_err(FileUploadErrorKind::IOError);
+ future::result(rt)
+ }),
+ )
+}
+
+/// Create new future to handle file as multipart data.
+fn handle_multipart(
+ item: multipart::MultipartItem<dev::Payload>,
+ mut file_path: PathBuf,
+ overwrite_files: bool,
+) -> Box<Stream<Item = i64, Error = FileUploadErrorKind>> {
+ match item {
+ multipart::MultipartItem::Field(field) => {
+ let filename = field
+ .headers()
+ .get(header::CONTENT_DISPOSITION)
+ .ok_or(FileUploadErrorKind::ParseError)
+ .and_then(|cd| {
+ header::ContentDisposition::from_raw(cd)
+ .map_err(|_| FileUploadErrorKind::ParseError)
+ })
+ .and_then(|content_disposition| {
+ content_disposition
+ .get_filename()
+ .ok_or(FileUploadErrorKind::ParseError)
+ .map(String::from)
+ });
+ let err = |e: FileUploadErrorKind| Box::new(future::err(e).into_stream());
+ match filename {
+ Ok(f) => {
+ match fs::metadata(&file_path) {
+ Ok(metadata) => {
+ if !metadata.is_dir() || metadata.permissions().readonly() {
+ return err(FileUploadErrorKind::InsufficientPermissions);
+ }
+ }
+ Err(_) => {
+ return err(FileUploadErrorKind::InsufficientPermissions);
+ }
+ }
+ file_path = file_path.join(f);
+ Box::new(save_file(field, file_path, overwrite_files).into_stream())
+ }
+ Err(e) => err(e),
+ }
+ }
+ multipart::MultipartItem::Nested(mp) => Box::new(
+ mp.map_err(FileUploadErrorKind::MultipartError)
+ .map(move |item| handle_multipart(item, file_path.clone(), overwrite_files))
+ .flatten(),
+ ),
+ }
+}
+
+/// Handle incoming request to upload file.
+/// Target file path is expected as path parameter in URI and is interpreted as relative from
+/// server root directory. Any path which will go outside of this directory is considered
+/// invalid.
+/// This method returns future.
+pub fn upload_file(req: &HttpRequest<crate::MiniserveConfig>) -> FutureResponse<HttpResponse> {
+ let app_root_dir = req.state().path.clone().canonicalize().unwrap();
+ let path = match Query::<QueryParameters>::extract(req) {
+ Ok(query) => {
+ if let Ok(stripped_path) = query.path.strip_prefix(Component::RootDir) {
+ stripped_path.to_owned()
+ } else {
+ query.path.clone()
+ }
+ }
+ Err(_) => {
+ return Box::new(future::ok(
+ HttpResponse::BadRequest().body("Unspecified parameter path"),
+ ))
+ }
+ };
+ // this is really ugly I will try to think about something smarter
+ let return_path: String = req.headers()[header::REFERER]
+ .clone()
+ .to_str()
+ .unwrap_or("/")
+ .to_owned();
+ let r_p2 = return_path.clone();
+
+ // If the target path is under the app root directory, save the file.
+ let target_dir = match &app_root_dir.clone().join(path.clone()).canonicalize() {
+ Ok(path) if path.starts_with(&app_root_dir) => path.clone(),
+ _ => return Box::new(future::ok(HttpResponse::BadRequest().body("Invalid path"))),
+ };
+ let overwrite_files = req.state().overwrite_files;
+ Box::new(
+ req.multipart()
+ .map_err(FileUploadErrorKind::MultipartError)
+ .map(move |item| handle_multipart(item, target_dir.clone(), overwrite_files))
+ .flatten()
+ .collect()
+ .map(move |_| {
+ HttpResponse::TemporaryRedirect()
+ .header(header::LOCATION, return_path.to_string())
+ .finish()
+ })
+ .or_else(move |e| {
+ let error_description = format!("{}", e);
+ future::ok(
+ HttpResponse::BadRequest()
+ .body(file_upload_error(&error_description, &r_p2.clone()).into_string()),
+ )
+ }),
+ )
+}
diff --git a/src/listing.rs b/src/listing.rs
index c4daf88..4a0927b 100644
--- a/src/listing.rs
+++ b/src/listing.rs
@@ -130,13 +130,19 @@ pub fn directory_listing<S>(
dir: &fs::Directory,
req: &HttpRequest<S>,
skip_symlinks: bool,
+ file_upload: bool,
random_route: Option<String>,
+ upload_route: String,
) -> Result<HttpResponse, io::Error> {
let title = format!("Index of {}", req.path());
let base = Path::new(req.path());
let random_route = format!("/{}", random_route.unwrap_or_default());
let is_root = base.parent().is_none() || req.path() == random_route;
let page_parent = base.parent().map(|p| p.display().to_string());
+ let current_dir = match base.strip_prefix(random_route) {
+ Ok(c_d) => Path::new("/").join(c_d),
+ Err(_) => base.to_path_buf(),
+ };
let (sort_method, sort_order, download) =
if let Ok(query) = Query::<QueryParameters>::extract(req) {
@@ -265,6 +271,9 @@ pub fn directory_listing<S>(
page_parent,
sort_method,
sort_order,
+ file_upload,
+ &upload_route,
+ &current_dir.display().to_string(),
)
.into_string(),
))
diff --git a/src/main.rs b/src/main.rs
index f662a73..0ca2fdf 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,6 @@
#![feature(proc_macro_hygiene)]
+use actix_web::http::Method;
use actix_web::{fs, middleware, server, App};
use clap::crate_version;
use simplelog::{Config, LevelFilter, TermLogger};
@@ -13,6 +14,7 @@ mod archive;
mod args;
mod auth;
mod errors;
+mod file_upload;
mod listing;
mod renderer;
@@ -42,6 +44,12 @@ pub struct MiniserveConfig {
/// Enable random route generation
pub random_route: Option<String>,
+
+ /// Enable file upload
+ pub file_upload: bool,
+
+ /// Enable upload to override existing files
+ pub overwrite_files: bool,
}
fn main() {
@@ -174,19 +182,33 @@ fn main() {
/// Configures the Actix application
fn configure_app(app: App<MiniserveConfig>) -> App<MiniserveConfig> {
+ let upload_route;
let s = {
let path = &app.state().path;
let no_symlinks = app.state().no_symlinks;
let random_route = app.state().random_route.clone();
+ let file_upload = app.state().file_upload;
+ upload_route = match app.state().random_route.clone() {
+ Some(random_route) => format!("/{}/upload", random_route),
+ None => "/upload".to_string(),
+ };
if path.is_file() {
None
} else {
+ let u_r = upload_route.clone();
Some(
fs::StaticFiles::new(path)
.expect("Couldn't create path")
.show_files_listing()
.files_listing_renderer(move |dir, req| {
- listing::directory_listing(dir, req, no_symlinks, random_route.clone())
+ listing::directory_listing(
+ dir,
+ req,
+ no_symlinks,
+ file_upload,
+ random_route.clone(),
+ u_r.clone(),
+ )
}),
)
}
@@ -196,8 +218,17 @@ fn configure_app(app: App<MiniserveConfig>) -> App<MiniserveConfig> {
let full_route = format!("/{}", random_route);
if let Some(s) = s {
- // Handle directories
- app.handler(&full_route, s)
+ if app.state().file_upload {
+ // Allow file upload
+ app.resource(&upload_route, |r| {
+ r.method(Method::POST).f(file_upload::upload_file)
+ })
+ // Handle directories
+ .handler(&full_route, s)
+ } else {
+ // Handle directories
+ app.handler(&full_route, s)
+ }
} else {
// Handle single files
app.resource(&full_route, |r| r.f(listing::file_handler))
diff --git a/src/renderer.rs b/src/renderer.rs
index 66fc714..c166bc6 100644
--- a/src/renderer.rs
+++ b/src/renderer.rs
@@ -14,12 +14,22 @@ pub fn page(
page_parent: Option<String>,
sort_method: Option<listing::SortingMethod>,
sort_order: Option<listing::SortingOrder>,
+ file_upload: bool,
+ upload_route: &str,
+ current_dir: &str,
) -> Markup {
html! {
(page_header(page_title))
- body {
+ body id="dropContainer" {
span #top { }
- h1.title { (page_title) }
+ h1 { (page_title) }
+ @if file_upload {
+ form id="file_submit" action={(upload_route) "?path=" (current_dir)} method="POST" enctype="multipart/form-data" {
+ p { "Select file to upload or drag it into the window" }
+ input type="file" name="file_to_upload" id="fileInput" {}
+ input type="submit" value="Upload file" {}
+ }
+ }
div.download {
(archive_button(archive::CompressionMethod::TarGz))
}
@@ -299,6 +309,9 @@ fn css() -> Markup {
.download a:not(:last-of-type) {
margin-right: 1rem;
}
+ .drag_hover {
+ box-shadow: inset 0 25px 40px #aae;
+ }
@media (max-width: 600px) {
h1 {
font-size: 1.375em;
@@ -355,6 +368,26 @@ fn page_header(page_title: &str) -> Markup {
meta name="viewport" content="width=device-width, initial-scale=1";
title { (page_title) }
style { (css()) }
+ (PreEscaped(r#"
+ <script>
+ window.onload = function() {
+ dropContainer.ondragover = dropContainer.ondragenter = function(evt) {
+ dropContainer.className = "drag_hover";
+ evt.preventDefault();
+ };
+
+ dropContainer.ondrop = function(evt) {
+ fileInput.files = evt.dataTransfer.files;
+ evt.preventDefault();
+ file_submit.submit();
+ };
+
+ dropContainer.ondragleave = function() {
+ dropContainer.className = "";
+ }
+ }
+ </script>
+ "#))
}
}
}
@@ -380,3 +413,14 @@ fn humanize_systemtime(src_time: Option<SystemTime>) -> Option<String> {
.and_then(|from_now| Duration::from_std(from_now).ok())
.map(|duration| HumanTime::from(duration).to_text_en(Accuracy::Rough, Tense::Past))
}
+
+/// Renders error page when file uploading fails
+pub fn file_upload_error(error_description: &str, return_address: &str) -> Markup {
+ html! {
+ h1 { "File uploading failed" }
+ p { (error_description) }
+ a href=(return_address) {
+ "back"
+ }
+ }
+}