2022-05-26 11:17:55 +03:00
|
|
|
use crate::{Args, BoxResult};
|
|
|
|
|
2022-05-28 13:58:43 +03:00
|
|
|
use async_walkdir::WalkDir;
|
2022-05-30 09:22:35 +03:00
|
|
|
use async_zip::read::seek::ZipFileReader;
|
2022-05-28 13:58:43 +03:00
|
|
|
use async_zip::write::{EntryOptions, ZipFileWriter};
|
|
|
|
use async_zip::Compression;
|
2022-06-02 06:06:41 +03:00
|
|
|
use chrono::Local;
|
2022-05-28 13:58:43 +03:00
|
|
|
use futures::stream::StreamExt;
|
2022-05-26 11:17:55 +03:00
|
|
|
use futures::TryStreamExt;
|
2022-06-02 04:44:40 +03:00
|
|
|
use get_if_addrs::get_if_addrs;
|
2022-05-30 06:22:28 +03:00
|
|
|
use headers::{
|
2022-06-01 17:49:55 +03:00
|
|
|
AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
|
|
|
|
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-05-31 10:20:47 +03:00
|
|
|
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, ORIGIN, RANGE,
|
|
|
|
WWW_AUTHENTICATE,
|
2022-05-31 09:39:07 +03:00
|
|
|
};
|
2022-05-26 11:17:55 +03:00
|
|
|
use hyper::service::{make_service_fn, service_fn};
|
|
|
|
use hyper::{Body, Method, StatusCode};
|
|
|
|
use percent_encoding::percent_decode;
|
2022-06-02 06:06:41 +03:00
|
|
|
use rustls::ServerConfig;
|
2022-05-26 11:17:55 +03:00
|
|
|
use serde::Serialize;
|
|
|
|
use std::convert::Infallible;
|
2022-05-31 05:58:32 +03:00
|
|
|
use std::fs::Metadata;
|
2022-06-02 04:44:40 +03:00
|
|
|
use std::net::IpAddr;
|
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-05-31 05:58:32 +03:00
|
|
|
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWrite};
|
2022-06-02 06:06:41 +03:00
|
|
|
use tokio::net::TcpListener;
|
2022-05-26 11:17:55 +03:00
|
|
|
use tokio::{fs, io};
|
2022-06-02 06:06:41 +03:00
|
|
|
use tokio_rustls::TlsAcceptor;
|
2022-05-26 11:17:55 +03:00
|
|
|
use tokio_util::codec::{BytesCodec, FramedRead};
|
2022-05-29 01:57:16 +03:00
|
|
|
use tokio_util::io::{ReaderStream, StreamReader};
|
2022-05-26 11:17:55 +03:00
|
|
|
|
|
|
|
type Request = hyper::Request<Body>;
|
|
|
|
type Response = hyper::Response<Body>;
|
|
|
|
|
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-01 17:49:55 +03:00
|
|
|
const INDEX_NAME: &str = "index.html";
|
2022-05-28 17:27:28 +03:00
|
|
|
const BUF_SIZE: usize = 1024 * 16;
|
2022-05-26 11:17:55 +03:00
|
|
|
|
2022-05-31 03:38:30 +03:00
|
|
|
macro_rules! status {
|
|
|
|
($res:ident, $status:expr) => {
|
|
|
|
*$res.status_mut() = $status;
|
|
|
|
*$res.body_mut() = Body::from($status.canonical_reason().unwrap_or_default());
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
2022-05-26 11:17:55 +03:00
|
|
|
pub async fn serve(args: Args) -> BoxResult<()> {
|
2022-06-02 06:06:41 +03:00
|
|
|
let args = Arc::new(args);
|
2022-06-02 04:44:40 +03:00
|
|
|
let socket_addr = args.address()?;
|
2022-06-02 06:06:41 +03:00
|
|
|
let inner = Arc::new(InnerService::new(args.clone()));
|
|
|
|
if let Some((certs, key)) = args.tls.as_ref() {
|
|
|
|
let config = ServerConfig::builder()
|
|
|
|
.with_safe_defaults()
|
|
|
|
.with_no_client_auth()
|
|
|
|
.with_single_cert(certs.clone(), key.clone())?;
|
|
|
|
let tls_acceptor = TlsAcceptor::from(Arc::new(config));
|
|
|
|
let arc_acceptor = Arc::new(tls_acceptor);
|
2022-06-03 02:15:41 +03:00
|
|
|
let listener = TcpListener::bind(&socket_addr).await?;
|
2022-06-02 06:06:41 +03:00
|
|
|
let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);
|
|
|
|
let incoming = hyper::server::accept::from_stream(incoming.filter_map(|socket| async {
|
|
|
|
match socket {
|
|
|
|
Ok(stream) => match arc_acceptor.clone().accept(stream).await {
|
|
|
|
Ok(val) => Some(Ok::<_, Infallible>(val)),
|
|
|
|
Err(_) => None,
|
|
|
|
},
|
|
|
|
Err(_) => None,
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
let server = hyper::Server::builder(incoming).serve(make_service_fn(move |_| {
|
|
|
|
let inner = inner.clone();
|
|
|
|
async move {
|
|
|
|
Ok::<_, Infallible>(service_fn(move |req| {
|
|
|
|
let inner = inner.clone();
|
|
|
|
inner.call(req)
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
print_listening(args.address.as_str(), args.port, true);
|
|
|
|
server.await?;
|
|
|
|
} else {
|
2022-06-03 02:15:41 +03:00
|
|
|
let server = hyper::Server::try_bind(&socket_addr)?.serve(make_service_fn(move |_| {
|
2022-06-02 06:06:41 +03:00
|
|
|
let inner = inner.clone();
|
|
|
|
async move {
|
|
|
|
Ok::<_, Infallible>(service_fn(move |req| {
|
|
|
|
let inner = inner.clone();
|
|
|
|
inner.call(req)
|
|
|
|
}))
|
|
|
|
}
|
|
|
|
}));
|
|
|
|
print_listening(args.address.as_str(), args.port, false);
|
|
|
|
server.await?;
|
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
struct InnerService {
|
2022-06-02 06:06:41 +03:00
|
|
|
args: Arc<Args>,
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
impl InnerService {
|
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-05-27 04:01:16 +03:00
|
|
|
pub async fn call(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> {
|
|
|
|
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-06-02 06:06:41 +03:00
|
|
|
let timestamp = Local::now().format("%d/%b/%Y %H:%M:%S");
|
2022-05-31 03:38:30 +03:00
|
|
|
let mut res = match self.handle(req).await {
|
|
|
|
Ok(res) => {
|
2022-06-02 06:06:41 +03:00
|
|
|
println!(r#"[{}] "{} {}" - {}"#, timestamp, method, uri, res.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;
|
|
|
|
status!(res, status);
|
|
|
|
eprintln!(
|
|
|
|
r#"[{}] "{} {}" - {} {}"#,
|
|
|
|
timestamp, 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-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-05-31 03:38:30 +03:00
|
|
|
status!(res, StatusCode::FORBIDDEN);
|
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-01 17:49:55 +03:00
|
|
|
let meta = fs::metadata(path).await.ok();
|
2022-05-31 15:53:14 +03:00
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
let is_miss = meta.is_none();
|
|
|
|
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
2022-05-31 03:38:30 +03:00
|
|
|
let is_file = !is_miss && !is_dir;
|
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-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-05-31 15:53:14 +03:00
|
|
|
status!(res, StatusCode::NOT_FOUND);
|
|
|
|
return Ok(res);
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
match *req.method() {
|
2022-06-01 17:49:55 +03:00
|
|
|
Method::GET => {
|
|
|
|
let headers = req.headers();
|
|
|
|
if is_dir {
|
|
|
|
if render_index || render_spa {
|
|
|
|
self.handle_render_index(path, headers, &mut res).await?;
|
|
|
|
} else if query == "zip" {
|
|
|
|
self.handle_zip_dir(path, &mut res).await?;
|
|
|
|
} else if query.starts_with("q=") {
|
|
|
|
self.handle_query_dir(path, &query[3..], &mut res).await?;
|
|
|
|
} else {
|
|
|
|
self.handle_ls_dir(path, true, &mut res).await?;
|
|
|
|
}
|
|
|
|
} else if is_file {
|
|
|
|
self.handle_send_file(path, headers, &mut res).await?;
|
|
|
|
} else if render_spa {
|
|
|
|
self.handle_render_spa(path, headers, &mut res).await?;
|
|
|
|
} else if allow_upload && req_path.ends_with('/') {
|
|
|
|
self.handle_ls_dir(path, false, &mut res).await?;
|
|
|
|
} else {
|
|
|
|
status!(res, StatusCode::NOT_FOUND);
|
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
}
|
2022-05-31 03:38:30 +03:00
|
|
|
Method::OPTIONS => {
|
|
|
|
status!(res, StatusCode::NO_CONTENT);
|
|
|
|
}
|
2022-06-01 17:49:55 +03:00
|
|
|
Method::PUT => {
|
|
|
|
if !allow_upload || (!allow_delete && is_file) {
|
|
|
|
status!(res, StatusCode::FORBIDDEN);
|
|
|
|
} else {
|
|
|
|
self.handle_upload(path, req, &mut res).await?;
|
|
|
|
}
|
2022-05-31 03:38:30 +03:00
|
|
|
}
|
2022-06-01 17:49:55 +03:00
|
|
|
Method::DELETE => {
|
|
|
|
if !allow_delete {
|
|
|
|
status!(res, StatusCode::FORBIDDEN);
|
|
|
|
} else if !is_miss {
|
|
|
|
self.handle_delete(path, is_dir).await?
|
|
|
|
} else {
|
|
|
|
status!(res, StatusCode::NOT_FOUND);
|
|
|
|
}
|
2022-05-31 03:38:30 +03:00
|
|
|
}
|
|
|
|
_ => {
|
2022-06-01 17:49:55 +03:00
|
|
|
status!(res, StatusCode::METHOD_NOT_ALLOWED);
|
2022-05-31 03:38:30 +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<()> {
|
|
|
|
let ensure_parent = match path.parent() {
|
2022-05-29 05:53:19 +03:00
|
|
|
Some(parent) => match fs::metadata(parent).await {
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(meta) => meta.is_dir(),
|
|
|
|
Err(_) => {
|
|
|
|
fs::create_dir_all(parent).await?;
|
|
|
|
true
|
2022-05-29 05:53:19 +03:00
|
|
|
}
|
|
|
|
},
|
2022-05-31 00:49:42 +03:00
|
|
|
None => false,
|
|
|
|
};
|
|
|
|
if !ensure_parent {
|
2022-05-31 03:38:30 +03:00
|
|
|
status!(res, StatusCode::FORBIDDEN);
|
2022-05-31 00:49:42 +03:00
|
|
|
return Ok(());
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-05-30 09:22:35 +03:00
|
|
|
let mut file = fs::File::create(&path).await?;
|
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-05-31 10:20:47 +03:00
|
|
|
let query = req.uri().query().unwrap_or_default();
|
|
|
|
if query == "unzip" {
|
2022-06-02 14:43:43 +03:00
|
|
|
if let Err(e) = self.unzip_file(path).await {
|
|
|
|
eprintln!("Failed to unzip {}, {}", path.display(), e);
|
|
|
|
status!(res, StatusCode::BAD_REQUEST);
|
2022-05-30 09:22:35 +03:00
|
|
|
}
|
|
|
|
fs::remove_file(&path).await?;
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_delete(&self, path: &Path, is_dir: bool) -> BoxResult<()> {
|
|
|
|
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-05-31 00:49:42 +03:00
|
|
|
Ok(())
|
2022-05-26 14:52:54 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
|
2022-05-26 11:17:55 +03:00
|
|
|
let mut paths: Vec<PathItem> = vec![];
|
2022-05-29 05:53:19 +03:00
|
|
|
if exist {
|
2022-06-01 14:59:35 +03:00
|
|
|
let mut rd = match fs::read_dir(path).await {
|
|
|
|
Ok(rd) => rd,
|
|
|
|
Err(_) => {
|
|
|
|
status!(res, StatusCode::FORBIDDEN);
|
|
|
|
return Ok(());
|
|
|
|
}
|
|
|
|
};
|
2022-05-29 05:53:19 +03:00
|
|
|
while let Some(entry) = rd.next_entry().await? {
|
|
|
|
let entry_path = entry.path();
|
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 05:53:19 +03:00
|
|
|
paths.push(item);
|
|
|
|
}
|
2022-05-26 15:42:33 +03:00
|
|
|
}
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
2022-05-31 00:49:42 +03:00
|
|
|
self.send_index(path, paths, 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,
|
|
|
|
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-05-31 00:49:42 +03:00
|
|
|
self.send_index(path, paths, res)
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
2022-05-29 01:57:16 +03:00
|
|
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
2022-05-31 09:39:07 +03:00
|
|
|
let filename = path.file_name().unwrap().to_str().unwrap();
|
2022-05-28 17:27:28 +03:00
|
|
|
let path = path.to_owned();
|
|
|
|
tokio::spawn(async move {
|
2022-05-31 15:53:14 +03:00
|
|
|
if let Err(e) = zip_dir(&mut writer, &path).await {
|
2022-06-02 06:06:41 +03:00
|
|
|
eprintln!("Failed to zip {}, {}", path.display(), e);
|
2022-05-28 17:27:28 +03:00
|
|
|
}
|
|
|
|
});
|
2022-05-29 01:57:16 +03:00
|
|
|
let stream = ReaderStream::new(reader);
|
2022-05-31 00:49:42 +03:00
|
|
|
*res.body_mut() = Body::wrap_stream(stream);
|
2022-05-31 09:39:07 +03:00
|
|
|
res.headers_mut().insert(
|
|
|
|
CONTENT_DISPOSITION,
|
|
|
|
HeaderValue::from_str(&format!("attachment; filename=\"{}.zip\"", filename,)).unwrap(),
|
|
|
|
);
|
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>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
let path = path.join(INDEX_NAME);
|
|
|
|
if fs::metadata(&path)
|
|
|
|
.await
|
|
|
|
.ok()
|
|
|
|
.map(|v| v.is_file())
|
|
|
|
.unwrap_or_default()
|
|
|
|
{
|
|
|
|
self.handle_send_file(&path, headers, res).await?;
|
|
|
|
} else {
|
|
|
|
status!(res, StatusCode::NOT_FOUND);
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
async fn handle_render_spa(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> BoxResult<()> {
|
|
|
|
if path.extension().is_none() {
|
|
|
|
let path = self.args.path.join(INDEX_NAME);
|
|
|
|
self.handle_send_file(&path, headers, res).await?;
|
|
|
|
} else {
|
|
|
|
status!(res, StatusCode::NOT_FOUND);
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
async fn handle_send_file(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
headers: &HeaderMap<HeaderValue>,
|
|
|
|
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?);
|
|
|
|
let mut maybe_range = true;
|
|
|
|
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
|
|
|
|
}
|
|
|
|
};
|
|
|
|
res.headers_mut().typed_insert(last_modified);
|
2022-05-31 05:58:32 +03:00
|
|
|
res.headers_mut().typed_insert(etag.clone());
|
|
|
|
if cached {
|
2022-05-31 03:38:30 +03:00
|
|
|
status!(res, StatusCode::NOT_MODIFIED);
|
2022-05-31 00:49:42 +03:00
|
|
|
return Ok(());
|
2022-05-30 06:22:28 +03:00
|
|
|
}
|
2022-05-31 05:58:32 +03:00
|
|
|
if headers.typed_get::<Range>().is_some() {
|
|
|
|
maybe_range = headers
|
|
|
|
.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 {
|
|
|
|
maybe_range = false;
|
|
|
|
}
|
2022-05-30 06:22:28 +03:00
|
|
|
}
|
2022-05-31 05:58:32 +03:00
|
|
|
let file_range = if maybe_range {
|
|
|
|
if let Some(content_range) = headers
|
|
|
|
.typed_get::<Range>()
|
|
|
|
.and_then(|range| to_content_range(&range, meta.len()))
|
|
|
|
{
|
|
|
|
res.headers_mut().typed_insert(content_range.clone());
|
|
|
|
*res.status_mut() = StatusCode::PARTIAL_CONTENT;
|
|
|
|
content_range.bytes_range()
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
};
|
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-05-31 05:58:32 +03:00
|
|
|
let body = if let Some((begin, end)) = file_range {
|
|
|
|
file.seek(io::SeekFrom::Start(begin)).await?;
|
|
|
|
let stream = FramedRead::new(file.take(end - begin + 1), BytesCodec::new());
|
|
|
|
Body::wrap_stream(stream)
|
|
|
|
} else {
|
|
|
|
let stream = FramedRead::new(file, BytesCodec::new());
|
|
|
|
Body::wrap_stream(stream)
|
|
|
|
};
|
2022-05-30 06:22:28 +03:00
|
|
|
*res.body_mut() = body;
|
2022-06-01 15:02:35 +03:00
|
|
|
res.headers_mut().typed_insert(AcceptRanges::bytes());
|
2022-06-01 17:49:55 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(ContentLength(meta.len() as u64));
|
2022-05-31 00:49:42 +03:00
|
|
|
|
|
|
|
Ok(())
|
2022-05-26 11:17:55 +03:00
|
|
|
}
|
|
|
|
|
2022-05-31 00:49:42 +03:00
|
|
|
fn send_index(
|
|
|
|
&self,
|
|
|
|
path: &Path,
|
|
|
|
mut paths: Vec<PathItem>,
|
|
|
|
res: &mut Response,
|
|
|
|
) -> 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-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>
|
|
|
|
<script>var DATA = {}; {}</script>
|
|
|
|
"#,
|
|
|
|
rel_path.display(),
|
|
|
|
INDEX_CSS,
|
|
|
|
data,
|
|
|
|
INDEX_JS
|
|
|
|
),
|
|
|
|
);
|
2022-05-31 00:49:42 +03:00
|
|
|
*res.body_mut() = output.into();
|
2022-05-29 07:43:40 +03:00
|
|
|
|
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 {
|
|
|
|
let pass = {
|
|
|
|
match &self.args.auth {
|
|
|
|
None => true,
|
2022-05-31 10:20:47 +03:00
|
|
|
Some(auth) => match req.headers().get(AUTHORIZATION) {
|
2022-05-31 00:49:42 +03:00
|
|
|
Some(value) => match value.to_str().ok().map(|v| {
|
|
|
|
let mut it = v.split(' ');
|
|
|
|
(it.next(), it.next())
|
|
|
|
}) {
|
2022-05-31 03:38:30 +03:00
|
|
|
Some((Some("Basic"), Some(tail))) => base64::decode(tail)
|
2022-05-31 00:49:42 +03:00
|
|
|
.ok()
|
|
|
|
.and_then(|v| String::from_utf8(v).ok())
|
|
|
|
.map(|v| v.as_str() == auth)
|
|
|
|
.unwrap_or_default(),
|
|
|
|
_ => false,
|
|
|
|
},
|
2022-06-03 01:51:03 +03:00
|
|
|
None => self.args.no_auth_access && req.method() == Method::GET,
|
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-05-31 03:38:30 +03:00
|
|
|
status!(res, StatusCode::UNAUTHORIZED);
|
2022-05-31 00:49:42 +03:00
|
|
|
res.headers_mut()
|
|
|
|
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
|
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-02 14:43:43 +03:00
|
|
|
async fn unzip_file(&self, path: &Path) -> BoxResult<()> {
|
|
|
|
let root = path.parent().unwrap();
|
|
|
|
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
|
|
|
|
for i in 0..zip.entries().len() {
|
|
|
|
let entry = &zip.entries()[i];
|
|
|
|
let entry_name = entry.name();
|
|
|
|
let entry_path = root.join(entry_name);
|
|
|
|
if entry_name.ends_with('/') {
|
|
|
|
fs::create_dir_all(entry_path).await?;
|
|
|
|
} else {
|
|
|
|
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
|
|
|
|
continue;
|
|
|
|
}
|
|
|
|
if let Some(parent) = entry_path.parent() {
|
|
|
|
if fs::symlink_metadata(parent).await.is_err() {
|
|
|
|
fs::create_dir_all(&parent).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
let mut outfile = fs::File::create(&entry_path).await?;
|
|
|
|
let mut reader = zip.entry_reader(i).await?;
|
|
|
|
io::copy(&mut reader, &mut outfile).await?;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
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();
|
|
|
|
match self.args.path_prefix.as_deref() {
|
|
|
|
Some(prefix) => {
|
|
|
|
let prefix = prefix.trim_start_matches('/');
|
|
|
|
path.strip_prefix(prefix).ok()
|
|
|
|
}
|
|
|
|
None => Some(path),
|
|
|
|
}
|
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
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
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-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>,
|
|
|
|
}
|
|
|
|
|
|
|
|
#[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-05-29 12:33:21 +03:00
|
|
|
fn add_cors(res: &mut Response) {
|
|
|
|
res.headers_mut()
|
|
|
|
.typed_insert(AccessControlAllowOrigin::ANY);
|
|
|
|
res.headers_mut().typed_insert(
|
|
|
|
vec![RANGE, CONTENT_TYPE, ACCEPT, ORIGIN, WWW_AUTHENTICATE]
|
|
|
|
.into_iter()
|
|
|
|
.collect::<AccessControlAllowHeaders>(),
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
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))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn to_content_range(range: &Range, complete_length: u64) -> Option<ContentRange> {
|
|
|
|
use core::ops::Bound::{Included, Unbounded};
|
|
|
|
let mut iter = range.iter();
|
|
|
|
let bounds = iter.next();
|
|
|
|
|
|
|
|
if iter.next().is_some() {
|
|
|
|
// Found multiple byte-range-spec. Drop.
|
|
|
|
return None;
|
|
|
|
}
|
|
|
|
|
|
|
|
bounds.and_then(|b| match b {
|
|
|
|
(Included(start), Included(end)) if start <= end && start < complete_length => {
|
|
|
|
ContentRange::bytes(
|
|
|
|
start..=end.min(complete_length.saturating_sub(1)),
|
|
|
|
complete_length,
|
|
|
|
)
|
|
|
|
.ok()
|
|
|
|
}
|
|
|
|
(Included(start), Unbounded) if start < complete_length => {
|
|
|
|
ContentRange::bytes(start.., complete_length).ok()
|
|
|
|
}
|
|
|
|
(Unbounded, Included(end)) if end > 0 => {
|
|
|
|
ContentRange::bytes(complete_length.saturating_sub(end).., complete_length).ok()
|
|
|
|
}
|
|
|
|
_ => None,
|
|
|
|
})
|
|
|
|
}
|
2022-06-02 04:44:40 +03:00
|
|
|
|
2022-06-02 06:06:41 +03:00
|
|
|
fn print_listening(address: &str, port: u16, tls: bool) {
|
2022-06-02 04:44:40 +03:00
|
|
|
let addrs = retrive_listening_addrs(address);
|
2022-06-02 06:06:41 +03:00
|
|
|
let protocol = if tls { "https" } else { "http" };
|
2022-06-02 04:44:40 +03:00
|
|
|
if addrs.len() == 1 {
|
2022-06-02 06:06:41 +03:00
|
|
|
eprintln!("Listening on {}://{}:{}", protocol, addrs[0], port);
|
2022-06-02 04:44:40 +03:00
|
|
|
} else {
|
|
|
|
eprintln!("Listening on:");
|
|
|
|
for addr in addrs {
|
2022-06-02 06:06:41 +03:00
|
|
|
eprintln!(" {}://{}:{}", protocol, addr, port);
|
2022-06-02 04:44:40 +03:00
|
|
|
}
|
2022-06-03 01:51:03 +03:00
|
|
|
eprintln!();
|
2022-06-02 04:44:40 +03:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn retrive_listening_addrs(address: &str) -> Vec<String> {
|
|
|
|
if address == "0.0.0.0" {
|
|
|
|
if let Ok(interfaces) = get_if_addrs() {
|
|
|
|
let mut ifaces: Vec<IpAddr> = interfaces
|
|
|
|
.into_iter()
|
|
|
|
.map(|v| v.ip())
|
|
|
|
.filter(|v| v.is_ipv4())
|
|
|
|
.collect();
|
|
|
|
ifaces.sort();
|
|
|
|
return ifaces.into_iter().map(|v| v.to_string()).collect();
|
|
|
|
}
|
|
|
|
}
|
|
|
|
vec![address.to_owned()]
|
|
|
|
}
|