2022-06-04 19:09:21 +03:00
|
|
|
use crate::auth::{generate_www_auth, valid_digest};
|
2022-06-16 05:24:32 +03:00
|
|
|
use crate::streamer::Streamer;
|
2022-06-06 03:00:26 +03:00
|
|
|
use crate::{Args, BoxResult};
|
2022-06-06 02:54:12 +03:00
|
|
|
use xml::escape::escape_str_pcdata;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-05-28 13:58:43 +03:00
|
|
|
use async_walkdir::WalkDir;
|
|
|
|
use async_zip::write::{EntryOptions, ZipFileWriter};
|
|
|
|
use async_zip::Compression;
|
2022-06-06 02:13:22 +03:00
|
|
|
use chrono::{TimeZone, Utc};
|
2022-05-28 13:58:43 +03:00
|
|
|
use futures::stream::StreamExt;
|
2022-05-26 11:17:55 +03:00
|
|
|
use futures::TryStreamExt;
|
2022-05-30 06:22:28 +03:00
|
|
|
use headers::{
|
2022-06-15 14:57:28 +03:00
|
|
|
AcceptRanges, AccessControlAllowCredentials, AccessControlAllowHeaders,
|
2022-06-16 05:24:32 +03:00
|
|
|
AccessControlAllowOrigin, Connection, ContentLength, ContentType, ETag, HeaderMap,
|
|
|
|
HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range,
|
2022-05-30 06:22:28 +03:00
|
|
|
};
|
2022-05-31 09:39:07 +03:00
|
|
|
use hyper::header::{
|
2022-06-16 05:24:32 +03:00
|
|
|
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_LENGTH, CONTENT_RANGE,
|
|
|
|
CONTENT_TYPE, ORIGIN, RANGE, WWW_AUTHENTICATE,
|
2022-05-31 09:39:07 +03:00
|
|
|
};
|
2022-06-04 07:51:56 +03:00
|
|
|
use hyper::{Body, Method, StatusCode, Uri};
|
2022-05-26 11:17:55 +03:00
|
|
|
use percent_encoding::percent_decode;
|
|
|
|
use serde::Serialize;
|
2022-05-31 05:58:32 +03:00
|
|
|
use std::fs::Metadata;
|
2022-06-16 05:24:32 +03:00
|
|
|
use std::io::SeekFrom;
|
2022-06-15 14:33:51 +03:00
|
|
|
use std::net::SocketAddr;
|
2022-05-26 11:17:55 +03:00
|
|
|
use std::path::{Path, PathBuf};
|
|
|
|
use std::sync::Arc;
|
|
|
|
use std::time::SystemTime;
|
2022-05-28 13:58:43 +03:00
|
|
|
use tokio::fs::File;
|
2022-06-16 05:24:32 +03:00
|
|
|
use tokio::io::{AsyncSeekExt, AsyncWrite};
|
2022-05-26 11:17:55 +03:00
|
|
|
use tokio::{fs, io};
|
2022-06-16 05:24:32 +03:00
|
|
|
use tokio_util::io::StreamReader;
|
2022-06-04 19:09:21 +03:00
|
|
|
use uuid::Uuid;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-06-15 14:33:51 +03:00
|
|
|
pub type Request = hyper::Request<Body>;
|
|
|
|
pub type Response = hyper::Response<Body>;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-06-01 15:26:03 +03:00
|
|
|
const INDEX_HTML: &str = include_str!("../assets/index.html");
|
|
|
|
const INDEX_CSS: &str = include_str!("../assets/index.css");
|
|
|
|
const INDEX_JS: &str = include_str!("../assets/index.js");
|
2022-06-07 03:59:44 +03:00
|
|
|
const FAVICON_ICO: &[u8] = include_bytes!("../assets/favicon.ico");
|
2022-06-01 17:49:55 +03:00
|
|
|
const INDEX_NAME: &str = "index.html";
|
2022-06-16 05:24:32 +03:00
|
|
|
const BUF_SIZE: usize = 65536;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-06-15 14:33:51 +03:00
|
|
|
pub struct Server {
|
2022-06-02 06:06:41 +03:00
|
|
|
args: Arc<Args>,
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-06-15 14:33:51 +03:00
|
|
|
impl Server {
|
2022-06-02 06:06:41 +03:00
|
|
|
pub fn new(args: Arc<Args>) -> Self {
|
2022-05-26 11:17:55 +03:00
|
|
|
Self { args }
|
|
|
|
}
|
|
|
|
|
2022-06-15 14:33:51 +03:00
|
|
|
pub async fn call(
|
|
|
|
self: Arc<Self>,
|
|
|
|
req: Request,
|
|
|
|
addr: SocketAddr,
|
|
|
|
) -> Result<Response, hyper::Error> {
|
2022-05-27 04:01:16 +03:00
|
|
|
let method = req.method().clone();
|
|
|
|
let uri = req.uri().clone();
|
2022-05-29 12:33:21 +03:00
|
|
|
let cors = self.args.cors;
|
2022-05-31 00:49:42 +03:00
|
|
|
|
2022-05-31 03:38:30 +03:00
|
|
|
let mut res = match self.handle(req).await {
|
|
|
|
Ok(res) => {
|
2022-06-15 14:57:28 +03:00
|
|
|
let status = res.status().as_u16();
|
|
|
|
info!(r#"{} "{} {}" - {}"#, addr.ip(), method, uri, status,);
|
2022-05-31 03:38:30 +03:00
|
|
|
res
|
|
|
|
}
|
|
|
|
Err(err) => {
|
|
|
|
let mut res = Response::default();
|
2022-06-02 06:06:41 +03:00
|
|
|
let status = StatusCode::INTERNAL_SERVER_ERROR;
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = status;
|
|
|
|
let status = status.as_u16();
|
|
|
|
error!(r#"{} "{} {}" - {} {}"#, addr.ip(), method, uri, status, err);
|
2022-05-31 03:38:30 +03:00
|
|
|
res
|
|
|
|
}
|
|
|
|
};
|
2022-05-31 00:49:42 +03:00
|
|
|
|
2022-05-29 12:33:21 +03:00
|
|
|
if cors {
|
|
|
|
add_cors(&mut res);
|
|
|
|
}
|
2022-05-27 04:01:16 +03:00
|
|
|
Ok(res)
|
|
|
|
}
|
|
|
|
|
|
|
|
pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> {
|
2022-05-31 00:49:42 +03:00
|
|
|
let mut res = Response::default();
|
|
|
|
|
|
|
|
if !self.auth_guard(&req, &mut res) {
|
2022-05-26 15:14:18 +03:00
|
|
|
return Ok(res);
|
2022-05-26 14:52:54 +03:00
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-06-01 17:49:55 +03:00
|
|
|
let req_path = req.uri().path();
|
2022-06-12 03:43:50 +03:00
|
|
|
let headers = req.headers();
|
|
|
|
let method = req.method().clone();
|
|
|
|
|
|
|
|
if req_path == "/favicon.ico" && method == Method::GET {
|
|
|
|
self.handle_send_favicon(req.headers(), &mut res).await?;
|
|
|
|
return Ok(res);
|
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
|
2022-06-01 17:49:55 +03:00
|
|
|
let path = match self.extract_path(req_path) {
|
2022-05-31 00:49:42 +03:00
|
|
|
Some(v) => v,
|
|
|
|
None => {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-05-31 00:49:42 +03:00
|
|
|
return Ok(res);
|
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
};
|
2022-06-01 17:49:55 +03:00
|
|
|
let path = path.as_path();
|
2022-05-31 00:49:42 +03:00
|
|
|
|
|
|
|
let query = req.uri().query().unwrap_or_default();
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
let (is_miss, is_dir, is_file, size) = match fs::metadata(path).await.ok() {
|
|
|
|
Some(meta) => (false, meta.is_dir(), meta.is_file(), meta.len()),
|
|
|
|
None => (true, false, false, 0),
|
|
|
|
};
|
2022-05-31 00:49:42 +03:00
|
|
|
|
2022-05-31 03:38:30 +03:00
|
|
|
let allow_upload = self.args.allow_upload;
|
|
|
|
let allow_delete = self.args.allow_delete;
|
2022-06-01 17:49:55 +03:00
|
|
|
let render_index = self.args.render_index;
|
|
|
|
let render_spa = self.args.render_spa;
|
2022-06-17 14:02:13 +03:00
|
|
|
let render_try_index = self.args.render_try_index;
|
2022-05-31 00:49:42 +03:00
|
|
|
|
2022-06-01 17:49:55 +03:00
|
|
|
if !self.args.allow_symlink && !is_miss && !self.is_root_contained(path).await {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-05-31 15:53:14 +03:00
|
|
|
return Ok(res);
|
|
|
|
}
|
2022-06-04 14:08:18 +03:00
|
|
|
|
2022-06-11 05:18:07 +03:00
|
|
|
match method {
|
|
|
|
Method::GET | Method::HEAD => {
|
|
|
|
let head_only = method == Method::HEAD;
|
2022-06-01 17:49:55 +03:00
|
|
|
if is_dir {
|
2022-06-17 14:02:13 +03:00
|
|
|
if render_try_index && query == "zip" {
|
|
|
|
self.handle_zip_dir(path, head_only, &mut res).await?;
|
|
|
|
} else if render_index || render_spa || render_try_index {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_render_index(path, headers, head_only, &mut res)
|
|
|
|
.await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else if query == "zip" {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_zip_dir(path, head_only, &mut res).await?;
|
2022-06-10 03:00:27 +03:00
|
|
|
} else if let Some(q) = query.strip_prefix("q=") {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_query_dir(path, q, head_only, &mut res).await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_ls_dir(path, true, head_only, &mut res).await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
}
|
|
|
|
} else if is_file {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_send_file(path, headers, head_only, &mut res)
|
|
|
|
.await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else if render_spa {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_render_spa(path, headers, head_only, &mut res)
|
|
|
|
.await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else if allow_upload && req_path.ends_with('/') {
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_ls_dir(path, false, head_only, &mut res).await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-01 17:49:55 +03:00
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
}
|
2022-06-11 05:18:07 +03:00
|
|
|
Method::OPTIONS => {
|
2022-06-15 14:57:28 +03:00
|
|
|
set_webdav_headers(&mut res);
|
2022-05-31 03:38:30 +03:00
|
|
|
}
|
2022-06-11 05:18:07 +03:00
|
|
|
Method::PUT => {
|
2022-06-04 14:08:18 +03:00
|
|
|
if !allow_upload || (!allow_delete && is_file && size > 0) {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
|
|
|
self.handle_upload(path, req, &mut res).await?;
|
|
|
|
}
|
2022-05-31 03:38:30 +03:00
|
|
|
}
|
2022-06-11 05:18:07 +03:00
|
|
|
Method::DELETE => {
|
2022-06-01 17:49:55 +03:00
|
|
|
if !allow_delete {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-06-01 17:49:55 +03:00
|
|
|
} else if !is_miss {
|
2022-06-04 07:51:56 +03:00
|
|
|
self.handle_delete(path, is_dir, &mut res).await?
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-01 17:49:55 +03:00
|
|
|
}
|
2022-05-31 03:38:30 +03:00
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
method => match method.as_str() {
|
|
|
|
"PROPFIND" => {
|
|
|
|
if is_dir {
|
2022-06-04 14:08:18 +03:00
|
|
|
self.handle_propfind_dir(path, headers, &mut res).await?;
|
2022-06-04 07:51:56 +03:00
|
|
|
} else if is_file {
|
|
|
|
self.handle_propfind_file(path, &mut res).await?;
|
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
|
|
|
}
|
2022-06-04 14:08:18 +03:00
|
|
|
"PROPPATCH" => {
|
|
|
|
if is_file {
|
2022-06-05 02:35:05 +03:00
|
|
|
self.handle_proppatch(req_path, &mut res).await?;
|
2022-06-04 14:08:18 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-04 14:08:18 +03:00
|
|
|
}
|
|
|
|
}
|
2022-06-12 03:43:50 +03:00
|
|
|
"MKCOL" => {
|
|
|
|
if !allow_upload || !is_miss {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-06-12 03:43:50 +03:00
|
|
|
} else {
|
|
|
|
self.handle_mkcol(path, &mut res).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
"COPY" => {
|
|
|
|
if !allow_upload {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-06-12 03:43:50 +03:00
|
|
|
} else if is_miss {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-12 03:43:50 +03:00
|
|
|
} else {
|
|
|
|
self.handle_copy(path, headers, &mut res).await?
|
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
2022-06-12 03:43:50 +03:00
|
|
|
"MOVE" => {
|
|
|
|
if !allow_upload || !allow_delete {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(&mut res);
|
2022-06-12 03:43:50 +03:00
|
|
|
} else if is_miss {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-12 03:43:50 +03:00
|
|
|
} else {
|
|
|
|
self.handle_move(path, headers, &mut res).await?
|
|
|
|
}
|
2022-06-04 14:08:18 +03:00
|
|
|
}
|
|
|
|
"LOCK" => {
|
|
|
|
// Fake lock
|
|
|
|
if is_file {
|
|
|
|
self.handle_lock(req_path, &mut res).await?;
|
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-04 14:08:18 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
"UNLOCK" => {
|
|
|
|
// Fake unlock
|
|
|
|
if is_miss {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(&mut res);
|
2022-06-04 14:08:18 +03:00
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
|
|
|
_ => {
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
|
|
|
},
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(res)
|
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_upload(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
mut req: Request,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-06-04 07:51:56 +03:00
|
|
|
ensure_path_parent(path).await?;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-06-12 03:43:50 +03:00
|
|
|
let mut file = match fs::File::create(&path).await {
|
|
|
|
Ok(v) => v,
|
|
|
|
Err(_) => {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(res);
|
2022-06-12 03:43:50 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
2022-05-26 11:17:55 +03:00
|
|
|
|
|
|
|
let body_with_io_error = req
|
|
|
|
.body_mut()
|
|
|
|
.map_err(|err| io::Error::new(io::ErrorKind::Other, err));
|
|
|
|
|
|
|
|
let body_reader = StreamReader::new(body_with_io_error);
|
|
|
|
|
|
|
|
futures::pin_mut!(body_reader);
|
|
|
|
|
|
|
|
io::copy(&mut body_reader, &mut file).await?;
|
|
|
|
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::CREATED;
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-06-04 07:51:56 +03:00
|
|
|
async fn handle_delete(&self, path: &Path, is_dir: bool, res: &mut Response) -> BoxResult<()> {
|
2022-05-31 00:49:42 +03:00
|
|
|
match is_dir {
|
|
|
|
true => fs::remove_dir_all(path).await?,
|
|
|
|
false => fs::remove_file(path).await?,
|
2022-05-26 14:52:54 +03:00
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
|
2022-06-15 14:57:28 +03:00
|
|
|
status_no_content(res);
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-26 14:52:54 +03:00
|
|
|
}
|
|
|
|
|
2022-06-11 05:18:07 +03:00
|
|
|
async fn handle_ls_dir(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
exist: bool,
|
|
|
|
head_only: bool,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-06-04 07:51:56 +03:00
|
|
|
let mut paths = vec![];
|
2022-05-29 05:53:19 +03:00
|
|
|
if exist {
|
2022-06-04 14:08:18 +03:00
|
|
|
paths = match self.list_dir(path, path).await {
|
2022-06-04 07:51:56 +03:00
|
|
|
Ok(paths) => paths,
|
2022-06-01 14:59:35 +03:00
|
|
|
Err(_) => {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(res);
|
2022-06-01 14:59:35 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
2022-05-26 15:42:33 +03:00
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
};
|
2022-06-11 05:18:07 +03:00
|
|
|
self.send_index(path, paths, exist, head_only, res)
|
2022-05-29 07:43:40 +03:00
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_query_dir(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
query: &str,
|
2022-06-11 05:18:07 +03:00
|
|
|
head_only: bool,
|
2022-05-31 00:49:42 +03:00
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-05-29 07:43:40 +03:00
|
|
|
let mut paths: Vec<PathItem> = vec![];
|
|
|
|
let mut walkdir = WalkDir::new(path);
|
|
|
|
while let Some(entry) = walkdir.next().await {
|
|
|
|
if let Ok(entry) = entry {
|
|
|
|
if !entry
|
|
|
|
.file_name()
|
|
|
|
.to_string_lossy()
|
|
|
|
.to_lowercase()
|
2022-05-31 00:49:42 +03:00
|
|
|
.contains(&query.to_lowercase())
|
2022-05-29 07:43:40 +03:00
|
|
|
{
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if fs::symlink_metadata(entry.path()).await.is_err() {
|
|
|
|
continue;
|
|
|
|
}
|
2022-05-31 15:53:14 +03:00
|
|
|
if let Ok(Some(item)) = self.to_pathitem(entry.path(), path.to_path_buf()).await {
|
2022-05-29 07:43:40 +03:00
|
|
|
paths.push(item);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-06-11 05:18:07 +03:00
|
|
|
self.send_index(path, paths, true, head_only, res)
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-06-11 05:18:07 +03:00
|
|
|
async fn handle_zip_dir(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
head_only: bool,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-05-29 01:57:16 +03:00
|
|
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
2022-06-04 19:09:21 +03:00
|
|
|
let filename = path
|
|
|
|
.file_name()
|
|
|
|
.and_then(|v| v.to_str())
|
|
|
|
.ok_or_else(|| format!("Failed to get name of `{}`", path.display()))?;
|
2022-05-31 09:39:07 +03:00
|
|
|
res.headers_mut().insert(
|
|
|
|
CONTENT_DISPOSITION,
|
2022-06-06 01:51:35 +03:00
|
|
|
HeaderValue::from_str(&format!(
|
|
|
|
"attachment; filename=\"{}.zip\"",
|
|
|
|
encode_uri(filename),
|
|
|
|
))
|
|
|
|
.unwrap(),
|
2022-05-31 09:39:07 +03:00
|
|
|
);
|
2022-06-11 05:18:07 +03:00
|
|
|
res.headers_mut()
|
2022-06-15 14:57:28 +03:00
|
|
|
.insert("content-type", HeaderValue::from_static("application/zip"));
|
2022-06-11 05:18:07 +03:00
|
|
|
if head_only {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
let path = path.to_owned();
|
|
|
|
tokio::spawn(async move {
|
|
|
|
if let Err(e) = zip_dir(&mut writer, &path).await {
|
|
|
|
error!("Failed to zip {}, {}", path.display(), e);
|
|
|
|
}
|
|
|
|
});
|
2022-06-16 05:24:32 +03:00
|
|
|
let reader = Streamer::new(reader, BUF_SIZE);
|
|
|
|
*res.body_mut() = Body::wrap_stream(reader.into_stream());
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-28 13:58:43 +03:00
|
|
|
}
|
|
|
|
|
2022-06-01 17:49:55 +03:00
|
|
|
async fn handle_render_index(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
2022-06-11 05:18:07 +03:00
|
|
|
head_only: bool,
|
2022-06-01 17:49:55 +03:00
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-06-17 03:41:01 +03:00
|
|
|
let index_path = path.join(INDEX_NAME);
|
|
|
|
if fs::metadata(&index_path)
|
2022-06-01 17:49:55 +03:00
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.map(|v| v.is_file())
|
|
|
|
.unwrap_or_default()
|
|
|
|
{
|
2022-06-17 03:41:01 +03:00
|
|
|
self.handle_send_file(&index_path, headers, head_only, res)
|
2022-06-11 05:18:07 +03:00
|
|
|
.await?;
|
2022-06-17 14:02:13 +03:00
|
|
|
} else if self.args.render_try_index {
|
2022-06-17 03:41:01 +03:00
|
|
|
self.handle_ls_dir(path, true, head_only, res).await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(res)
|
2022-06-01 17:49:55 +03:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_render_spa(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
2022-06-11 05:18:07 +03:00
|
|
|
head_only: bool,
|
2022-06-01 17:49:55 +03:00
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
if path.extension().is_none() {
|
|
|
|
let path = self.args.path.join(INDEX_NAME);
|
2022-06-11 05:18:07 +03:00
|
|
|
self.handle_send_file(&path, headers, head_only, res)
|
|
|
|
.await?;
|
2022-06-01 17:49:55 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(res)
|
2022-06-01 17:49:55 +03:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-06-12 03:43:50 +03:00
|
|
|
async fn handle_send_favicon(
|
|
|
|
&self,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
let path = self.args.path.join("favicon.ico");
|
|
|
|
let meta = fs::metadata(&path).await.ok();
|
|
|
|
let is_file = meta.map(|v| v.is_file()).unwrap_or_default();
|
|
|
|
if is_file {
|
|
|
|
self.handle_send_file(path.as_path(), headers, false, res)
|
|
|
|
.await?;
|
|
|
|
} else {
|
|
|
|
*res.body_mut() = Body::from(FAVICON_ICO);
|
|
|
|
res.headers_mut()
|
2022-06-15 14:57:28 +03:00
|
|
|
.insert("content-type", HeaderValue::from_static("image/x-icon"));
|
2022-06-12 03:43:50 +03:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_send_file(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
2022-06-11 05:18:07 +03:00
|
|
|
head_only: bool,
|
2022-05-31 00:49:42 +03:00
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
2022-05-30 06:22:28 +03:00
|
|
|
let (file, meta) = tokio::join!(fs::File::open(path), fs::metadata(path),);
|
2022-05-31 05:58:32 +03:00
|
|
|
let (mut file, meta) = (file?, meta?);
|
2022-06-16 05:24:32 +03:00
|
|
|
let mut use_range = true;
|
2022-05-31 05:58:32 +03:00
|
|
|
if let Some((etag, last_modified)) = extract_cache_headers(&meta) {
|
|
|
|
let cached = {
|
2022-05-31 00:49:42 +03:00
|
|
|
if let Some(if_none_match) = headers.typed_get::<IfNoneMatch>() {
|
2022-05-30 06:22:28 +03:00
|
|
|
!if_none_match.precondition_passes(&etag)
|
2022-05-31 00:49:42 +03:00
|
|
|
} else if let Some(if_modified_since) = headers.typed_get::<IfModifiedSince>() {
|
2022-05-31 05:58:32 +03:00
|
|
|
!if_modified_since.is_modified(last_modified.into())
|
2022-05-30 06:22:28 +03:00
|
|
|
} else {
|
|
|
|
false
|
|
|
|
}
|
|
|
|
};
|
2022-05-31 05:58:32 +03:00
|
|
|
if cached {
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::NOT_MODIFIED;
|
2022-05-31 00:49:42 +03:00
|
|
|
return Ok(());
|
2022-05-30 06:22:28 +03:00
|
|
|
}
|
2022-06-16 05:24:32 +03:00
|
|
|
|
|
|
|
res.headers_mut().typed_insert(last_modified);
|
|
|
|
res.headers_mut().typed_insert(etag.clone());
|
|
|
|
|
2022-05-31 05:58:32 +03:00
|
|
|
if headers.typed_get::<Range>().is_some() {
|
2022-06-16 05:24:32 +03:00
|
|
|
use_range = headers
|
2022-05-31 05:58:32 +03:00
|
|
|
.typed_get::<IfRange>()
|
|
|
|
.map(|if_range| !if_range.is_modified(Some(&etag), Some(&last_modified)))
|
|
|
|
// Always be fresh if there is no validators
|
|
|
|
.unwrap_or(true);
|
|
|
|
} else {
|
2022-06-16 05:24:32 +03:00
|
|
|
use_range = false;
|
2022-05-31 05:58:32 +03:00
|
|
|
}
|
2022-05-30 06:22:28 +03:00
|
|
|
}
|
2022-06-16 05:24:32 +03:00
|
|
|
|
|
|
|
let range = if use_range {
|
|
|
|
parse_range(headers)
|
2022-05-31 05:58:32 +03:00
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
2022-06-16 05:24:32 +03:00
|
|
|
|
2022-05-30 06:22:28 +03:00
|
|
|
if let Some(mime) = mime_guess::from_path(&path).first() {
|
|
|
|
res.headers_mut().typed_insert(ContentType::from(mime));
|
2022-06-16 05:24:32 +03:00
|
|
|
} else {
|
|
|
|
res.headers_mut().insert(
|
|
|
|
CONTENT_TYPE,
|
|
|
|
HeaderValue::from_static("application/octet-stream"),
|
|
|
|
);
|
2022-05-30 06:22:28 +03:00
|
|
|
}
|
2022-06-16 05:24:32 +03:00
|
|
|
|
2022-06-11 05:18:07 +03:00
|
|
|
res.headers_mut().typed_insert(AcceptRanges::bytes());
|
|
|
|
|
2022-06-16 05:24:32 +03:00
|
|
|
let size = meta.len();
|
|
|
|
|
|
|
|
if let Some(range) = range {
|
|
|
|
if range
|
|
|
|
.end
|
|
|
|
.map_or_else(|| range.start < size, |v| v >= range.start)
|
|
|
|
&& file.seek(SeekFrom::Start(range.start)).await.is_ok()
|
|
|
|
{
|
|
|
|
let end = range.end.unwrap_or(size - 1).min(size - 1);
|
|
|
|
let part_size = end - range.start + 1;
|
|
|
|
let reader = Streamer::new(file, BUF_SIZE);
|
|
|
|
*res.status_mut() = StatusCode::PARTIAL_CONTENT;
|
|
|
|
let content_range = format!("bytes {}-{}/{}", range.start, end, size);
|
|
|
|
res.headers_mut()
|
|
|
|
.insert(CONTENT_RANGE, content_range.parse().unwrap());
|
|
|
|
res.headers_mut()
|
|
|
|
.insert(CONTENT_LENGTH, format!("{}", part_size).parse().unwrap());
|
|
|
|
if head_only {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
*res.body_mut() = Body::wrap_stream(reader.into_stream_sized(part_size));
|
|
|
|
} else {
|
|
|
|
*res.status_mut() = StatusCode::RANGE_NOT_SATISFIABLE;
|
|
|
|
res.headers_mut()
|
|
|
|
.insert(CONTENT_RANGE, format!("bytes */{}", size).parse().unwrap());
|
|
|
|
}
|
2022-05-31 05:58:32 +03:00
|
|
|
} else {
|
2022-06-16 05:24:32 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.insert(CONTENT_LENGTH, format!("{}", size).parse().unwrap());
|
|
|
|
if head_only {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
let reader = Streamer::new(file, BUF_SIZE);
|
|
|
|
*res.body_mut() = Body::wrap_stream(reader.into_stream());
|
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
async fn handle_propfind_dir(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
let depth: u32 = match headers.get("depth") {
|
|
|
|
Some(v) => match v.to_str().ok().and_then(|v| v.parse().ok()) {
|
|
|
|
Some(v) => v,
|
|
|
|
None => {
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::BAD_REQUEST;
|
2022-06-04 14:08:18 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
},
|
2022-06-12 03:43:50 +03:00
|
|
|
None => 1,
|
2022-06-04 07:51:56 +03:00
|
|
|
};
|
2022-06-04 14:08:18 +03:00
|
|
|
let mut paths = vec![self.to_pathitem(path, &self.args.path).await?.unwrap()];
|
2022-06-12 03:43:50 +03:00
|
|
|
if depth != 0 {
|
2022-06-04 14:08:18 +03:00
|
|
|
match self.list_dir(path, &self.args.path).await {
|
|
|
|
Ok(child) => paths.extend(child),
|
|
|
|
Err(_) => {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(res);
|
2022-06-04 14:08:18 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
let output = paths
|
|
|
|
.iter()
|
2022-06-04 14:08:18 +03:00
|
|
|
.map(|v| v.to_dav_xml(self.args.uri_prefix.as_str()))
|
2022-06-04 07:51:56 +03:00
|
|
|
.fold(String::new(), |mut acc, v| {
|
|
|
|
acc.push_str(&v);
|
|
|
|
acc
|
|
|
|
});
|
2022-06-05 02:35:05 +03:00
|
|
|
res_multistatus(res, &output);
|
2022-06-04 07:51:56 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_propfind_file(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
|
|
|
if let Some(pathitem) = self.to_pathitem(path, &self.args.path).await? {
|
2022-06-05 02:35:05 +03:00
|
|
|
res_multistatus(res, &pathitem.to_dav_xml(self.args.uri_prefix.as_str()));
|
2022-06-04 07:51:56 +03:00
|
|
|
} else {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_not_found(res);
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_mkcol(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
|
|
|
fs::create_dir_all(path).await?;
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::CREATED;
|
2022-06-04 07:51:56 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_copy(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
let dest = match self.extract_dest(headers) {
|
|
|
|
Some(dest) => dest,
|
|
|
|
None => {
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::BAD_REQUEST;
|
2022-06-04 07:51:56 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
let meta = fs::symlink_metadata(path).await?;
|
|
|
|
if meta.is_dir() {
|
2022-06-15 14:57:28 +03:00
|
|
|
status_forbid(res);
|
2022-06-04 07:51:56 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
|
|
|
|
ensure_path_parent(&dest).await?;
|
|
|
|
|
|
|
|
fs::copy(path, &dest).await?;
|
|
|
|
|
2022-06-15 14:57:28 +03:00
|
|
|
status_no_content(res);
|
2022-06-04 07:51:56 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_move(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
let dest = match self.extract_dest(headers) {
|
|
|
|
Some(dest) => dest,
|
|
|
|
None => {
|
2022-06-15 14:57:28 +03:00
|
|
|
*res.status_mut() = StatusCode::BAD_REQUEST;
|
2022-06-04 07:51:56 +03:00
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
ensure_path_parent(&dest).await?;
|
|
|
|
|
|
|
|
fs::rename(path, &dest).await?;
|
|
|
|
|
2022-06-15 14:57:28 +03:00
|
|
|
status_no_content(res);
|
2022-06-04 07:51:56 +03:00
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
async fn handle_lock(&self, req_path: &str, res: &mut Response) -> BoxResult<()> {
|
2022-06-04 19:09:21 +03:00
|
|
|
let token = if self.args.auth.is_none() {
|
|
|
|
Utc::now().timestamp().to_string()
|
|
|
|
} else {
|
|
|
|
format!("opaquelocktoken:{}", Uuid::new_v4())
|
|
|
|
};
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
res.headers_mut().insert(
|
|
|
|
"content-type",
|
2022-06-15 14:57:28 +03:00
|
|
|
HeaderValue::from_static("application/xml; charset=utf-8"),
|
2022-06-04 14:08:18 +03:00
|
|
|
);
|
|
|
|
res.headers_mut()
|
2022-06-04 19:09:21 +03:00
|
|
|
.insert("lock-token", format!("<{}>", token).parse().unwrap());
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
*res.body_mut() = Body::from(format!(
|
|
|
|
r#"<?xml version="1.0" encoding="utf-8"?>
|
|
|
|
<D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>
|
2022-06-05 02:35:05 +03:00
|
|
|
<D:locktoken><D:href>{}</D:href></D:locktoken>
|
|
|
|
<D:lockroot><D:href>{}</D:href></D:lockroot>
|
2022-06-04 14:08:18 +03:00
|
|
|
</D:activelock></D:lockdiscovery></D:prop>"#,
|
2022-06-04 19:09:21 +03:00
|
|
|
token, req_path
|
2022-06-04 14:08:18 +03:00
|
|
|
));
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-06-05 02:35:05 +03:00
|
|
|
async fn handle_proppatch(&self, req_path: &str, res: &mut Response) -> BoxResult<()> {
|
|
|
|
let output = format!(
|
|
|
|
r#"<D:response>
|
|
|
|
<D:href>{}</D:href>
|
|
|
|
<D:propstat>
|
|
|
|
<D:prop>
|
|
|
|
</D:prop>
|
|
|
|
<D:status>HTTP/1.1 403 Forbidden</D:status>
|
|
|
|
</D:propstat>
|
|
|
|
</D:response>"#,
|
|
|
|
req_path
|
|
|
|
);
|
|
|
|
res_multistatus(res, &output);
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
fn send_index(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
mut paths: Vec<PathItem>,
|
2022-06-10 02:41:09 +03:00
|
|
|
exist: bool,
|
2022-06-11 05:18:07 +03:00
|
|
|
head_only: bool,
|
|
|
|
res: &mut Response,
|
2022-05-31 00:49:42 +03:00
|
|
|
) -> BoxResult<()> {
|
2022-05-29 07:43:40 +03:00
|
|
|
paths.sort_unstable();
|
2022-05-30 06:47:57 +03:00
|
|
|
let rel_path = match self.args.path.parent() {
|
|
|
|
Some(p) => path.strip_prefix(p).unwrap(),
|
|
|
|
None => path,
|
|
|
|
};
|
2022-05-29 07:43:40 +03:00
|
|
|
let data = IndexData {
|
2022-05-30 06:47:57 +03:00
|
|
|
breadcrumb: normalize_path(rel_path),
|
2022-05-29 07:43:40 +03:00
|
|
|
paths,
|
2022-05-31 03:38:30 +03:00
|
|
|
allow_upload: self.args.allow_upload,
|
|
|
|
allow_delete: self.args.allow_delete,
|
2022-06-10 02:41:09 +03:00
|
|
|
dir_exists: exist,
|
2022-05-29 07:43:40 +03:00
|
|
|
};
|
|
|
|
let data = serde_json::to_string(&data).unwrap();
|
2022-05-30 06:47:57 +03:00
|
|
|
let output = INDEX_HTML.replace(
|
2022-05-31 00:49:42 +03:00
|
|
|
"__SLOT__",
|
2022-05-30 06:47:57 +03:00
|
|
|
&format!(
|
|
|
|
r#"
|
2022-05-31 00:49:42 +03:00
|
|
|
<title>Files in {}/ - Duf</title>
|
2022-05-30 06:47:57 +03:00
|
|
|
<style>{}</style>
|
2022-06-12 03:43:50 +03:00
|
|
|
<script>
|
|
|
|
const DATA =
|
|
|
|
{}
|
|
|
|
{}</script>
|
2022-05-30 06:47:57 +03:00
|
|
|
"#,
|
|
|
|
rel_path.display(),
|
|
|
|
INDEX_CSS,
|
|
|
|
data,
|
|
|
|
INDEX_JS
|
|
|
|
),
|
|
|
|
);
|
2022-06-06 06:20:42 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(ContentType::from(mime_guess::mime::TEXT_HTML_UTF_8));
|
2022-06-11 05:18:07 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(ContentLength(output.as_bytes().len() as u64));
|
|
|
|
if head_only {
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
*res.body_mut() = output.into();
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-29 07:43:40 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
fn auth_guard(&self, req: &Request, res: &mut Response) -> bool {
|
2022-06-04 19:09:21 +03:00
|
|
|
let method = req.method();
|
2022-05-31 00:49:42 +03:00
|
|
|
let pass = {
|
|
|
|
match &self.args.auth {
|
|
|
|
None => true,
|
2022-06-04 19:09:21 +03:00
|
|
|
Some((user, pass)) => match req.headers().get(AUTHORIZATION) {
|
|
|
|
Some(value) => {
|
|
|
|
valid_digest(value, method.as_str(), user.as_str(), pass.as_str()).is_some()
|
|
|
|
}
|
|
|
|
None => {
|
|
|
|
self.args.no_auth_access
|
|
|
|
&& (method == Method::GET
|
|
|
|
|| method == Method::OPTIONS
|
|
|
|
|| method == Method::HEAD
|
|
|
|
|| method.as_str() == "PROPFIND")
|
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
},
|
2022-05-26 13:06:52 +03:00
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
};
|
|
|
|
if !pass {
|
2022-06-04 19:09:21 +03:00
|
|
|
let value = generate_www_auth(false);
|
2022-06-15 14:57:28 +03:00
|
|
|
set_webdav_headers(res);
|
|
|
|
*res.status_mut() = StatusCode::UNAUTHORIZED;
|
|
|
|
res.headers_mut().typed_insert(Connection::close());
|
2022-05-31 00:49:42 +03:00
|
|
|
res.headers_mut()
|
2022-06-04 19:09:21 +03:00
|
|
|
.insert(WWW_AUTHENTICATE, value.parse().unwrap());
|
2022-05-26 13:06:52 +03:00
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
pass
|
2022-05-26 13:06:52 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 15:53:14 +03:00
|
|
|
async fn is_root_contained(&self, path: &Path) -> bool {
|
|
|
|
fs::canonicalize(path)
|
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.map(|v| v.starts_with(&self.args.path))
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
|
|
|
|
2022-06-04 07:51:56 +03:00
|
|
|
fn extract_dest(&self, headers: &HeaderMap<HeaderValue>) -> Option<PathBuf> {
|
|
|
|
let dest = headers.get("Destination")?.to_str().ok()?;
|
|
|
|
let uri: Uri = dest.parse().ok()?;
|
|
|
|
self.extract_path(uri.path())
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
fn extract_path(&self, path: &str) -> Option<PathBuf> {
|
|
|
|
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
|
2022-05-26 11:17:55 +03:00
|
|
|
let slashes_switched = if cfg!(windows) {
|
|
|
|
decoded_path.replace('/', "\\")
|
|
|
|
} else {
|
|
|
|
decoded_path.into_owned()
|
|
|
|
};
|
2022-06-02 03:32:31 +03:00
|
|
|
let stripped_path = match self.strip_path_prefix(&slashes_switched) {
|
|
|
|
Some(path) => path,
|
|
|
|
None => return None,
|
|
|
|
};
|
|
|
|
Some(self.args.path.join(&stripped_path))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn strip_path_prefix<'a, P: AsRef<Path>>(&self, path: &'a P) -> Option<&'a Path> {
|
|
|
|
let path = path.as_ref();
|
2022-06-04 14:08:18 +03:00
|
|
|
if self.args.path_prefix.is_empty() {
|
|
|
|
Some(path)
|
|
|
|
} else {
|
|
|
|
path.strip_prefix(&self.args.path_prefix).ok()
|
2022-06-02 03:32:31 +03:00
|
|
|
}
|
2022-05-31 15:53:14 +03:00
|
|
|
}
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
async fn list_dir(&self, entry_path: &Path, base_path: &Path) -> BoxResult<Vec<PathItem>> {
|
2022-06-04 07:51:56 +03:00
|
|
|
let mut paths: Vec<PathItem> = vec![];
|
|
|
|
let mut rd = fs::read_dir(entry_path).await?;
|
|
|
|
while let Ok(Some(entry)) = rd.next_entry().await {
|
|
|
|
let entry_path = entry.path();
|
|
|
|
if let Ok(Some(item)) = self.to_pathitem(entry_path.as_path(), base_path).await {
|
|
|
|
paths.push(item);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(paths)
|
|
|
|
}
|
|
|
|
|
2022-05-31 15:53:14 +03:00
|
|
|
async fn to_pathitem<P: AsRef<Path>>(
|
|
|
|
&self,
|
|
|
|
path: P,
|
|
|
|
base_path: P,
|
|
|
|
) -> BoxResult<Option<PathItem>> {
|
|
|
|
let path = path.as_ref();
|
|
|
|
let rel_path = path.strip_prefix(base_path).unwrap();
|
|
|
|
let (meta, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
|
|
|
|
let (meta, meta2) = (meta?, meta2?);
|
|
|
|
let is_symlink = meta2.is_symlink();
|
|
|
|
if !self.args.allow_symlink && is_symlink && !self.is_root_contained(path).await {
|
|
|
|
return Ok(None);
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
2022-05-31 15:53:14 +03:00
|
|
|
let is_dir = meta.is_dir();
|
|
|
|
let path_type = match (is_symlink, is_dir) {
|
|
|
|
(true, true) => PathType::SymlinkDir,
|
|
|
|
(false, true) => PathType::Dir,
|
|
|
|
(true, false) => PathType::SymlinkFile,
|
|
|
|
(false, false) => PathType::File,
|
|
|
|
};
|
|
|
|
let mtime = to_timestamp(&meta.modified()?);
|
|
|
|
let size = match path_type {
|
|
|
|
PathType::Dir | PathType::SymlinkDir => None,
|
|
|
|
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
|
|
|
};
|
|
|
|
let name = normalize_path(rel_path);
|
|
|
|
Ok(Some(PathItem {
|
|
|
|
path_type,
|
|
|
|
name,
|
|
|
|
mtime,
|
|
|
|
size,
|
|
|
|
}))
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-06-04 07:51:56 +03:00
|
|
|
#[derive(Debug, Serialize)]
|
2022-05-29 07:43:40 +03:00
|
|
|
struct IndexData {
|
2022-05-26 11:17:55 +03:00
|
|
|
breadcrumb: String,
|
|
|
|
paths: Vec<PathItem>,
|
2022-05-31 03:38:30 +03:00
|
|
|
allow_upload: bool,
|
|
|
|
allow_delete: bool,
|
2022-06-10 02:41:09 +03:00
|
|
|
dir_exists: bool,
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
|
|
|
struct PathItem {
|
|
|
|
path_type: PathType,
|
|
|
|
name: String,
|
2022-05-30 06:22:28 +03:00
|
|
|
mtime: u64,
|
2022-05-26 11:17:55 +03:00
|
|
|
size: Option<u64>,
|
|
|
|
}
|
|
|
|
|
2022-06-04 07:51:56 +03:00
|
|
|
impl PathItem {
|
2022-06-15 15:24:53 +03:00
|
|
|
pub fn is_dir(&self) -> bool {
|
|
|
|
self.path_type == PathType::Dir || self.path_type == PathType::SymlinkDir
|
|
|
|
}
|
|
|
|
|
2022-06-04 14:08:18 +03:00
|
|
|
pub fn to_dav_xml(&self, prefix: &str) -> String {
|
2022-06-04 07:51:56 +03:00
|
|
|
let mtime = Utc.timestamp_millis(self.mtime as i64).to_rfc2822();
|
2022-06-15 15:24:53 +03:00
|
|
|
let mut href = encode_uri(&format!("{}{}", prefix, &self.name));
|
|
|
|
if self.is_dir() && !href.ends_with('/') {
|
|
|
|
href.push('/');
|
|
|
|
}
|
2022-06-12 03:43:50 +03:00
|
|
|
let displayname = escape_str_pcdata(self.base_name());
|
2022-06-04 07:51:56 +03:00
|
|
|
match self.path_type {
|
|
|
|
PathType::Dir | PathType::SymlinkDir => format!(
|
|
|
|
r#"<D:response>
|
2022-06-09 16:35:52 +03:00
|
|
|
<D:href>{}</D:href>
|
2022-06-04 07:51:56 +03:00
|
|
|
<D:propstat>
|
|
|
|
<D:prop>
|
|
|
|
<D:displayname>{}</D:displayname>
|
|
|
|
<D:getlastmodified>{}</D:getlastmodified>
|
|
|
|
<D:resourcetype><D:collection/></D:resourcetype>
|
|
|
|
</D:prop>
|
|
|
|
<D:status>HTTP/1.1 200 OK</D:status>
|
|
|
|
</D:propstat>
|
|
|
|
</D:response>"#,
|
2022-06-09 16:35:52 +03:00
|
|
|
href, displayname, mtime
|
2022-06-04 07:51:56 +03:00
|
|
|
),
|
|
|
|
PathType::File | PathType::SymlinkFile => format!(
|
|
|
|
r#"<D:response>
|
2022-06-09 16:35:52 +03:00
|
|
|
<D:href>{}</D:href>
|
2022-06-04 07:51:56 +03:00
|
|
|
<D:propstat>
|
|
|
|
<D:prop>
|
|
|
|
<D:displayname>{}</D:displayname>
|
|
|
|
<D:getcontentlength>{}</D:getcontentlength>
|
|
|
|
<D:getlastmodified>{}</D:getlastmodified>
|
|
|
|
<D:resourcetype></D:resourcetype>
|
|
|
|
</D:prop>
|
|
|
|
<D:status>HTTP/1.1 200 OK</D:status>
|
|
|
|
</D:propstat>
|
|
|
|
</D:response>"#,
|
2022-06-09 16:35:52 +03:00
|
|
|
href,
|
|
|
|
displayname,
|
2022-06-04 07:51:56 +03:00
|
|
|
self.size.unwrap_or_default(),
|
|
|
|
mtime
|
|
|
|
),
|
|
|
|
}
|
|
|
|
}
|
2022-06-12 03:43:50 +03:00
|
|
|
fn base_name(&self) -> &str {
|
|
|
|
Path::new(&self.name)
|
|
|
|
.file_name()
|
|
|
|
.and_then(|v| v.to_str())
|
|
|
|
.unwrap_or_default()
|
|
|
|
}
|
2022-06-04 07:51:56 +03:00
|
|
|
}
|
|
|
|
|
2022-05-26 11:17:55 +03:00
|
|
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
|
|
|
enum PathType {
|
|
|
|
Dir,
|
|
|
|
SymlinkDir,
|
|
|
|
File,
|
|
|
|
SymlinkFile,
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
fn to_timestamp(time: &SystemTime) -> u64 {
|
2022-05-30 06:22:28 +03:00
|
|
|
time.duration_since(SystemTime::UNIX_EPOCH)
|
|
|
|
.unwrap()
|
|
|
|
.as_millis() as u64
|
|
|
|
}
|
|
|
|
|
2022-05-26 11:17:55 +03:00
|
|
|
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
|
|
|
let path = path.as_ref().to_str().unwrap_or_default();
|
|
|
|
if cfg!(windows) {
|
|
|
|
path.replace('\\', "/")
|
|
|
|
} else {
|
|
|
|
path.to_string()
|
|
|
|
}
|
|
|
|
}
|
2022-05-28 13:58:43 +03:00
|
|
|
|
2022-06-04 07:51:56 +03:00
|
|
|
async fn ensure_path_parent(path: &Path) -> BoxResult<()> {
|
|
|
|
if let Some(parent) = path.parent() {
|
|
|
|
if fs::symlink_metadata(parent).await.is_err() {
|
|
|
|
fs::create_dir_all(&parent).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-05-29 12:33:21 +03:00
|
|
|
fn add_cors(res: &mut Response) {
|
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(AccessControlAllowOrigin::ANY);
|
2022-06-15 14:57:28 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(AccessControlAllowCredentials);
|
|
|
|
|
2022-05-29 12:33:21 +03:00
|
|
|
res.headers_mut().typed_insert(
|
|
|
|
vec![RANGE, CONTENT_TYPE, ACCEPT, ORIGIN, WWW_AUTHENTICATE]
|
|
|
|
.into_iter()
|
|
|
|
.collect::<AccessControlAllowHeaders>(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
2022-06-05 02:35:05 +03:00
|
|
|
fn res_multistatus(res: &mut Response, content: &str) {
|
2022-06-04 07:51:56 +03:00
|
|
|
*res.status_mut() = StatusCode::MULTI_STATUS;
|
2022-06-04 14:08:18 +03:00
|
|
|
res.headers_mut().insert(
|
|
|
|
"content-type",
|
2022-06-15 14:57:28 +03:00
|
|
|
HeaderValue::from_static("application/xml; charset=utf-8"),
|
2022-06-04 14:08:18 +03:00
|
|
|
);
|
2022-06-04 07:51:56 +03:00
|
|
|
*res.body_mut() = Body::from(format!(
|
|
|
|
r#"<?xml version="1.0" encoding="utf-8" ?>
|
|
|
|
<D:multistatus xmlns:D="DAV:">
|
|
|
|
{}
|
|
|
|
</D:multistatus>"#,
|
|
|
|
content,
|
|
|
|
));
|
|
|
|
}
|
|
|
|
|
2022-05-31 15:53:14 +03:00
|
|
|
async fn zip_dir<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
|
2022-05-28 13:58:43 +03:00
|
|
|
let mut writer = ZipFileWriter::new(writer);
|
|
|
|
let mut walkdir = WalkDir::new(dir);
|
|
|
|
while let Some(entry) = walkdir.next().await {
|
|
|
|
if let Ok(entry) = entry {
|
2022-05-31 15:53:14 +03:00
|
|
|
let entry_path = entry.path();
|
2022-05-29 07:43:40 +03:00
|
|
|
let meta = match fs::symlink_metadata(entry.path()).await {
|
|
|
|
Ok(meta) => meta,
|
|
|
|
Err(_) => continue,
|
|
|
|
};
|
2022-05-31 15:53:14 +03:00
|
|
|
if !meta.is_file() {
|
|
|
|
continue;
|
2022-05-28 13:58:43 +03:00
|
|
|
}
|
2022-05-31 15:53:14 +03:00
|
|
|
let filename = match entry_path.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
|
|
|
|
Some(v) => v,
|
|
|
|
None => continue,
|
|
|
|
};
|
|
|
|
let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate);
|
|
|
|
let mut file = File::open(&entry_path).await?;
|
|
|
|
let mut file_writer = writer.write_entry_stream(entry_options).await?;
|
|
|
|
io::copy(&mut file, &mut file_writer).await?;
|
|
|
|
file_writer.close().await?;
|
2022-05-28 13:58:43 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
writer.close().await?;
|
|
|
|
Ok(())
|
|
|
|
}
|
2022-05-31 05:58:32 +03:00
|
|
|
|
|
|
|
fn extract_cache_headers(meta: &Metadata) -> Option<(ETag, LastModified)> {
|
|
|
|
let mtime = meta.modified().ok()?;
|
|
|
|
let timestamp = to_timestamp(&mtime);
|
|
|
|
let size = meta.len();
|
|
|
|
let etag = format!(r#""{}-{}""#, timestamp, size)
|
|
|
|
.parse::<ETag>()
|
|
|
|
.unwrap();
|
|
|
|
let last_modified = LastModified::from(mtime);
|
|
|
|
Some((etag, last_modified))
|
|
|
|
}
|
|
|
|
|
2022-06-16 05:24:32 +03:00
|
|
|
#[derive(Debug)]
|
|
|
|
struct RangeValue {
|
|
|
|
start: u64,
|
|
|
|
end: Option<u64>,
|
|
|
|
}
|
2022-05-31 05:58:32 +03:00
|
|
|
|
2022-06-16 05:24:32 +03:00
|
|
|
fn parse_range(headers: &HeaderMap<HeaderValue>) -> Option<RangeValue> {
|
|
|
|
let range_hdr = headers.get(RANGE)?;
|
|
|
|
let hdr = range_hdr.to_str().ok()?;
|
|
|
|
let mut sp = hdr.splitn(2, '=');
|
|
|
|
let units = sp.next().unwrap();
|
|
|
|
if units == "bytes" {
|
|
|
|
let range = sp.next()?;
|
|
|
|
let mut sp_range = range.splitn(2, '-');
|
|
|
|
let start: u64 = sp_range.next().unwrap().parse().ok()?;
|
|
|
|
let end: Option<u64> = if let Some(end) = sp_range.next() {
|
|
|
|
if end.is_empty() {
|
|
|
|
None
|
|
|
|
} else {
|
|
|
|
Some(end.parse().ok()?)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
|
|
|
Some(RangeValue { start, end })
|
|
|
|
} else {
|
|
|
|
None
|
2022-05-31 05:58:32 +03:00
|
|
|
}
|
|
|
|
}
|
2022-06-02 04:44:40 +03:00
|
|
|
|
2022-06-06 03:00:26 +03:00
|
|
|
fn encode_uri(v: &str) -> String {
|
|
|
|
let parts: Vec<_> = v.split('/').map(urlencoding::encode).collect();
|
|
|
|
parts.join("/")
|
|
|
|
}
|
2022-06-15 14:57:28 +03:00
|
|
|
|
|
|
|
fn status_forbid(res: &mut Response) {
|
|
|
|
*res.status_mut() = StatusCode::FORBIDDEN;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn status_not_found(res: &mut Response) {
|
|
|
|
*res.status_mut() = StatusCode::NOT_FOUND;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn status_no_content(res: &mut Response) {
|
|
|
|
*res.status_mut() = StatusCode::NO_CONTENT;
|
|
|
|
}
|
|
|
|
|
|
|
|
fn set_webdav_headers(res: &mut Response) {
|
|
|
|
res.headers_mut().insert(
|
|
|
|
"Allow",
|
|
|
|
HeaderValue::from_static("GET,HEAD,PUT,OPTIONS,DELETE,PROPFIND,COPY,MOVE"),
|
|
|
|
);
|
|
|
|
res.headers_mut()
|
|
|
|
.insert("DAV", HeaderValue::from_static("1,2"));
|
|
|
|
}
|