mirror of
https://github.com/sigoden/dufs.git
synced 2026-04-09 09:09:03 +03:00
Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
605c6c56c4 | ||
|
|
8718562889 | ||
|
|
830d3343f4 | ||
|
|
1fe391f9d9 | ||
|
|
b88381167b | ||
|
|
35ed4394df | ||
|
|
f43d0b646d | ||
|
|
a9294f602c | ||
|
|
584d33940a | ||
|
|
fc090b6930 | ||
|
|
19d7b36462 | ||
|
|
755554d3f2 | ||
|
|
6a097e0496 | ||
|
|
412d42e338 |
2
Cargo.lock
generated
2
Cargo.lock
generated
@@ -296,7 +296,7 @@ dependencies = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.6.0"
|
version = "0.8.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-walkdir",
|
"async-walkdir",
|
||||||
"async_zip",
|
"async_zip",
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.6.0"
|
version = "0.8.0"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = ["sigoden <sigoden@gmail.com>"]
|
authors = ["sigoden <sigoden@gmail.com>"]
|
||||||
description = "Duf is a simple file server."
|
description = "Duf is a fully functional file server."
|
||||||
license = "MIT OR Apache-2.0"
|
license = "MIT OR Apache-2.0"
|
||||||
homepage = "https://github.com/sigoden/duf"
|
homepage = "https://github.com/sigoden/duf"
|
||||||
repository = "https://github.com/sigoden/duf"
|
repository = "https://github.com/sigoden/duf"
|
||||||
|
|||||||
@@ -3,7 +3,7 @@
|
|||||||
[](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
|
[](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
|
||||||
[](https://crates.io/crates/duf)
|
[](https://crates.io/crates/duf)
|
||||||
|
|
||||||
Duf is a simple file server.
|
Duf is a fully functional file server.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@@ -12,10 +12,10 @@ Duf is a simple file server.
|
|||||||
- Serve static files
|
- Serve static files
|
||||||
- Download folder as zip file
|
- Download folder as zip file
|
||||||
- Search files
|
- Search files
|
||||||
- Upload files
|
- Upload files and folders
|
||||||
- Delete files
|
- Delete files
|
||||||
- Basic authentication
|
- Basic authentication
|
||||||
- Unzip zip file when upload
|
- Upload zip file then unzip
|
||||||
- Easy to use with curl
|
- Easy to use with curl
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
|
|||||||
@@ -159,8 +159,6 @@ body {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.uploaders {
|
.uploaders {
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 0.5em 0;
|
padding: 0.5em 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -15,7 +15,7 @@
|
|||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
|
||||||
</a>
|
</a>
|
||||||
</div>
|
</div>
|
||||||
<div class="upload-control hidden" title="Upload file">
|
<div class="upload-control hidden" title="Upload files">
|
||||||
<label for="file">
|
<label for="file">
|
||||||
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
|
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
|
||||||
</label>
|
</label>
|
||||||
@@ -1,33 +1,34 @@
|
|||||||
let $tbody, $uploaders;
|
let $tbody, $uploaders;
|
||||||
let uploaderIdx = 0;
|
|
||||||
let baseDir;
|
let baseDir;
|
||||||
|
|
||||||
class Uploader {
|
class Uploader {
|
||||||
idx = 0;
|
idx;
|
||||||
file;
|
file;
|
||||||
|
name;
|
||||||
$elem;
|
$elem;
|
||||||
constructor(idx, file) {
|
static globalIdx = 0;
|
||||||
this.idx = idx;
|
constructor(file, dirs) {
|
||||||
|
this.name = [...dirs, file.name].join("/");
|
||||||
|
this.idx = Uploader.globalIdx++;
|
||||||
this.file = file;
|
this.file = file;
|
||||||
}
|
}
|
||||||
|
|
||||||
upload() {
|
upload() {
|
||||||
const { file, idx } = this;
|
const { file, idx, name } = this;
|
||||||
let url = getUrl(file.name);
|
let url = getUrl(name);
|
||||||
if (file.name == baseDir + ".zip") {
|
if (file.name == baseDir + ".zip") {
|
||||||
url += "?unzip";
|
url += "?unzip";
|
||||||
}
|
}
|
||||||
$uploaders.insertAdjacentHTML("beforeend", `
|
$uploaders.insertAdjacentHTML("beforeend", `
|
||||||
<div class="uploader path">
|
<div class="uploader path">
|
||||||
<div><svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg></div>
|
<div><svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M6 5H2V4h4v1zM2 8h7V7H2v1zm0 2h7V9H2v1zm0 2h7v-1H2v1zm10-7.5V14c0 .55-.45 1-1 1H1c-.55 0-1-.45-1-1V2c0-.55.45-1 1-1h7.5L12 4.5zM11 5L8 2H1v12h10V5z"></path></svg></div>
|
||||||
<a href="${url}" id="file${idx}">${file.name} (0%)</a>
|
<a href="${url}" id="file${idx}">${name} (0%)</a>
|
||||||
</div>`);
|
</div>`);
|
||||||
this.$elem = document.getElementById(`file${idx}`);
|
this.$elem = document.getElementById(`file${idx}`);
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
const ajax = new XMLHttpRequest();
|
||||||
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
||||||
ajax.addEventListener("readystatechange", () => {
|
ajax.addEventListener("readystatechange", () => {
|
||||||
console.log(ajax.readyState, ajax.status)
|
|
||||||
if(ajax.readyState === 4) {
|
if(ajax.readyState === 4) {
|
||||||
if (ajax.status == 200) {
|
if (ajax.status == 200) {
|
||||||
this.complete();
|
this.complete();
|
||||||
@@ -44,15 +45,15 @@ class Uploader {
|
|||||||
|
|
||||||
progress(event) {
|
progress(event) {
|
||||||
const percent = (event.loaded / event.total) * 100;
|
const percent = (event.loaded / event.total) * 100;
|
||||||
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`;
|
this.$elem.innerHTML = `${this.name} (${percent.toFixed(2)}%)`;
|
||||||
}
|
}
|
||||||
|
|
||||||
complete() {
|
complete() {
|
||||||
this.$elem.innerHTML = `${this.file.name}`;
|
this.$elem.innerHTML = `${this.name}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
fail() {
|
fail() {
|
||||||
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`;
|
this.$elem.innerHTML = `<strike>${this.name}</strike>`;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -141,6 +142,44 @@ async function deletePath(index) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function dropzone() {
|
||||||
|
["drag", "dragstart", "dragend", "dragover", "dragenter", "dragleave", "drop"].forEach(name => {
|
||||||
|
document.addEventListener(name, e => {
|
||||||
|
e.preventDefault();
|
||||||
|
e.stopPropagation();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
document.addEventListener("drop", e => {
|
||||||
|
if (!e.dataTransfer.items[0].webkitGetAsEntry) {
|
||||||
|
const files = e.dataTransfer.files.filter(v => v.size > 0);
|
||||||
|
for (const file of files) {
|
||||||
|
new Uploader(file, []).upload();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
const entries = [];
|
||||||
|
const len = e.dataTransfer.items.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
entries.push(e.dataTransfer.items[i].webkitGetAsEntry());
|
||||||
|
}
|
||||||
|
addFileEntries(entries, [])
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function addFileEntries(entries, dirs) {
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (entry.isFile) {
|
||||||
|
entry.file(file => {
|
||||||
|
new Uploader(file, dirs).upload();
|
||||||
|
});
|
||||||
|
} else if (entry.isDirectory) {
|
||||||
|
const dirReader = entry.createReader()
|
||||||
|
dirReader.readEntries(entries => addFileEntries(entries, [...dirs, entry.name]));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
function getUrl(name) {
|
function getUrl(name) {
|
||||||
let url = location.href.split('?')[0];
|
let url = location.href.split('?')[0];
|
||||||
if (!url.endsWith("/")) url += "/";
|
if (!url.endsWith("/")) url += "/";
|
||||||
@@ -184,21 +223,24 @@ function formatSize(size) {
|
|||||||
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
function ready() {
|
function ready() {
|
||||||
$tbody = document.querySelector(".main tbody");
|
$tbody = document.querySelector(".main tbody");
|
||||||
$uploaders = document.querySelector(".uploaders");
|
$uploaders = document.querySelector(".uploaders");
|
||||||
|
|
||||||
addBreadcrumb(DATA.breadcrumb);
|
addBreadcrumb(DATA.breadcrumb);
|
||||||
DATA.paths.forEach((file, index) => addPath(file, index));
|
if (Array.isArray(DATA.paths)) {
|
||||||
|
const len = DATA.paths.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
addPath(DATA.paths[i], i);
|
||||||
|
}
|
||||||
|
}
|
||||||
if (DATA.allow_upload) {
|
if (DATA.allow_upload) {
|
||||||
|
dropzone();
|
||||||
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
||||||
document.getElementById("file").addEventListener("change", e => {
|
document.getElementById("file").addEventListener("change", e => {
|
||||||
const files = e.target.files;
|
const files = e.target.files;
|
||||||
for (let file of files) {
|
for (let file of files) {
|
||||||
uploaderIdx += 1;
|
new Uploader(file, []).upload();
|
||||||
const uploader = new Uploader(uploaderIdx, file);
|
|
||||||
uploader.upload();
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
31
src/args.rs
31
src/args.rs
@@ -1,7 +1,6 @@
|
|||||||
use clap::crate_description;
|
use clap::crate_description;
|
||||||
use clap::{Arg, ArgMatches};
|
use clap::{Arg, ArgMatches};
|
||||||
use std::env;
|
use std::env;
|
||||||
use std::fs::canonicalize;
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
@@ -32,7 +31,7 @@ fn app() -> clap::Command<'static> {
|
|||||||
Arg::new("path")
|
Arg::new("path")
|
||||||
.default_value(".")
|
.default_value(".")
|
||||||
.allow_invalid_utf8(true)
|
.allow_invalid_utf8(true)
|
||||||
.help("Path to a directory for serving files"),
|
.help("Path to a root directory for serving files"),
|
||||||
)
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("allow-all")
|
Arg::new("allow-all")
|
||||||
@@ -47,9 +46,24 @@ fn app() -> clap::Command<'static> {
|
|||||||
)
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("allow-delete")
|
Arg::new("allow-delete")
|
||||||
.long("allo-delete")
|
.long("allow-delete")
|
||||||
.help("Allow delete operation"),
|
.help("Allow delete operation"),
|
||||||
)
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("allow-symlink")
|
||||||
|
.long("allow-symlink")
|
||||||
|
.help("Allow symlink to directories/files outside root directory"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("render-index")
|
||||||
|
.long("render-index")
|
||||||
|
.help("Render existing index.html when requesting a directory"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("render-spa")
|
||||||
|
.long("render-spa")
|
||||||
|
.help("Render spa, rewrite all not-found requests to `index.html"),
|
||||||
|
)
|
||||||
.arg(
|
.arg(
|
||||||
Arg::new("auth")
|
Arg::new("auth")
|
||||||
.short('a')
|
.short('a')
|
||||||
@@ -82,6 +96,9 @@ pub struct Args {
|
|||||||
pub no_auth_read: bool,
|
pub no_auth_read: bool,
|
||||||
pub allow_upload: bool,
|
pub allow_upload: bool,
|
||||||
pub allow_delete: bool,
|
pub allow_delete: bool,
|
||||||
|
pub allow_symlink: bool,
|
||||||
|
pub render_index: bool,
|
||||||
|
pub render_spa: bool,
|
||||||
pub cors: bool,
|
pub cors: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -99,6 +116,9 @@ impl Args {
|
|||||||
let no_auth_read = matches.is_present("no-auth-read");
|
let no_auth_read = matches.is_present("no-auth-read");
|
||||||
let allow_upload = matches.is_present("allow-all") || matches.is_present("allow-upload");
|
let allow_upload = matches.is_present("allow-all") || matches.is_present("allow-upload");
|
||||||
let allow_delete = matches.is_present("allow-all") || matches.is_present("allow-delete");
|
let allow_delete = matches.is_present("allow-all") || matches.is_present("allow-delete");
|
||||||
|
let allow_symlink = matches.is_present("allow-all") || matches.is_present("allow-symlink");
|
||||||
|
let render_index = matches.is_present("render-index");
|
||||||
|
let render_spa = matches.is_present("render-spa");
|
||||||
|
|
||||||
Ok(Args {
|
Ok(Args {
|
||||||
address,
|
address,
|
||||||
@@ -109,6 +129,9 @@ impl Args {
|
|||||||
cors,
|
cors,
|
||||||
allow_delete,
|
allow_delete,
|
||||||
allow_upload,
|
allow_upload,
|
||||||
|
allow_symlink,
|
||||||
|
render_index,
|
||||||
|
render_spa,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -122,7 +145,7 @@ impl Args {
|
|||||||
env::current_dir()
|
env::current_dir()
|
||||||
.and_then(|mut p| {
|
.and_then(|mut p| {
|
||||||
p.push(path); // If path is absolute, it replaces the current path.
|
p.push(path); // If path is absolute, it replaces the current path.
|
||||||
canonicalize(p)
|
std::fs::canonicalize(p)
|
||||||
})
|
})
|
||||||
.or_else(|err| {
|
.or_else(|err| {
|
||||||
bail!(
|
bail!(
|
||||||
|
|||||||
256
src/server.rs
256
src/server.rs
@@ -7,10 +7,14 @@ use async_zip::Compression;
|
|||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
use headers::{
|
use headers::{
|
||||||
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentRange, ContentType, ETag,
|
AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
|
||||||
HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range,
|
ContentType, ETag, HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange,
|
||||||
|
LastModified, Range,
|
||||||
|
};
|
||||||
|
use hyper::header::{
|
||||||
|
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, ORIGIN, RANGE,
|
||||||
|
WWW_AUTHENTICATE,
|
||||||
};
|
};
|
||||||
use hyper::header::{HeaderValue, ACCEPT, CONTENT_TYPE, ORIGIN, RANGE, WWW_AUTHENTICATE};
|
|
||||||
use hyper::service::{make_service_fn, service_fn};
|
use hyper::service::{make_service_fn, service_fn};
|
||||||
use hyper::{Body, Method, StatusCode};
|
use hyper::{Body, Method, StatusCode};
|
||||||
use percent_encoding::percent_decode;
|
use percent_encoding::percent_decode;
|
||||||
@@ -29,9 +33,10 @@ use tokio_util::io::{ReaderStream, StreamReader};
|
|||||||
type Request = hyper::Request<Body>;
|
type Request = hyper::Request<Body>;
|
||||||
type Response = hyper::Response<Body>;
|
type Response = hyper::Response<Body>;
|
||||||
|
|
||||||
const INDEX_HTML: &str = include_str!("assets/index.html");
|
const INDEX_HTML: &str = include_str!("../assets/index.html");
|
||||||
const INDEX_CSS: &str = include_str!("assets/index.css");
|
const INDEX_CSS: &str = include_str!("../assets/index.css");
|
||||||
const INDEX_JS: &str = include_str!("assets/index.js");
|
const INDEX_JS: &str = include_str!("../assets/index.js");
|
||||||
|
const INDEX_NAME: &str = "index.html";
|
||||||
const BUF_SIZE: usize = 1024 * 16;
|
const BUF_SIZE: usize = 1024 * 16;
|
||||||
|
|
||||||
macro_rules! status {
|
macro_rules! status {
|
||||||
@@ -102,59 +107,81 @@ impl InnerService {
|
|||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
|
|
||||||
let path = req.uri().path();
|
let req_path = req.uri().path();
|
||||||
|
|
||||||
let filepath = match self.extract_path(path) {
|
let path = match self.extract_path(req_path) {
|
||||||
Some(v) => v,
|
Some(v) => v,
|
||||||
None => {
|
None => {
|
||||||
status!(res, StatusCode::FORBIDDEN);
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
return Ok(res);
|
return Ok(res);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
let filepath = filepath.as_path();
|
let path = path.as_path();
|
||||||
|
|
||||||
let query = req.uri().query().unwrap_or_default();
|
let query = req.uri().query().unwrap_or_default();
|
||||||
|
|
||||||
let meta = fs::metadata(filepath).await.ok();
|
let meta = fs::metadata(path).await.ok();
|
||||||
|
|
||||||
let is_miss = meta.is_none();
|
let is_miss = meta.is_none();
|
||||||
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
||||||
let is_file = !is_miss && !is_dir;
|
let is_file = !is_miss && !is_dir;
|
||||||
|
|
||||||
let allow_upload = self.args.allow_upload;
|
let allow_upload = self.args.allow_upload;
|
||||||
let allow_delete = self.args.allow_delete;
|
let allow_delete = self.args.allow_delete;
|
||||||
|
let render_index = self.args.render_index;
|
||||||
|
let render_spa = self.args.render_spa;
|
||||||
|
|
||||||
|
if !self.args.allow_symlink && !is_miss && !self.is_root_contained(path).await {
|
||||||
|
status!(res, StatusCode::NOT_FOUND);
|
||||||
|
return Ok(res);
|
||||||
|
}
|
||||||
|
|
||||||
match *req.method() {
|
match *req.method() {
|
||||||
Method::GET if is_dir && query == "zip" => {
|
Method::GET => {
|
||||||
self.handle_zip_dir(filepath, &mut res).await?
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Method::GET if is_dir && query.starts_with("q=") => {
|
|
||||||
self.handle_query_dir(filepath, &query[3..], &mut res)
|
|
||||||
.await?
|
|
||||||
}
|
|
||||||
Method::GET if is_file => {
|
|
||||||
self.handle_send_file(filepath, req.headers(), &mut res)
|
|
||||||
.await?
|
|
||||||
}
|
|
||||||
Method::GET if is_miss && path.ends_with('/') => {
|
|
||||||
self.handle_ls_dir(filepath, false, &mut res).await?
|
|
||||||
}
|
|
||||||
Method::GET => self.handle_ls_dir(filepath, true, &mut res).await?,
|
|
||||||
Method::OPTIONS => {
|
Method::OPTIONS => {
|
||||||
status!(res, StatusCode::NO_CONTENT);
|
status!(res, StatusCode::NO_CONTENT);
|
||||||
}
|
}
|
||||||
Method::PUT if !allow_upload || (!allow_delete && is_file) => {
|
Method::PUT => {
|
||||||
status!(res, StatusCode::FORBIDDEN);
|
if !allow_upload || (!allow_delete && is_file) {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
} else {
|
||||||
|
self.handle_upload(path, req, &mut res).await?;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Method::PUT => self.handle_upload(filepath, req, &mut res).await?,
|
Method::DELETE => {
|
||||||
Method::DELETE if !allow_delete => {
|
if !allow_delete {
|
||||||
status!(res, StatusCode::FORBIDDEN);
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
} else if !is_miss {
|
||||||
|
self.handle_delete(path, is_dir).await?
|
||||||
|
} else {
|
||||||
|
status!(res, StatusCode::NOT_FOUND);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Method::DELETE if !is_miss => self.handle_delete(filepath, is_dir).await?,
|
|
||||||
_ => {
|
_ => {
|
||||||
status!(res, StatusCode::NOT_FOUND);
|
status!(res, StatusCode::METHOD_NOT_ALLOWED);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -191,8 +218,8 @@ impl InnerService {
|
|||||||
|
|
||||||
io::copy(&mut body_reader, &mut file).await?;
|
io::copy(&mut body_reader, &mut file).await?;
|
||||||
|
|
||||||
let req_query = req.uri().query().unwrap_or_default();
|
let query = req.uri().query().unwrap_or_default();
|
||||||
if req_query == "unzip" {
|
if query == "unzip" {
|
||||||
let root = path.parent().unwrap();
|
let root = path.parent().unwrap();
|
||||||
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
|
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
|
||||||
for i in 0..zip.entries().len() {
|
for i in 0..zip.entries().len() {
|
||||||
@@ -202,6 +229,9 @@ impl InnerService {
|
|||||||
if entry_name.ends_with('/') {
|
if entry_name.ends_with('/') {
|
||||||
fs::create_dir_all(entry_path).await?;
|
fs::create_dir_all(entry_path).await?;
|
||||||
} else {
|
} else {
|
||||||
|
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if let Some(parent) = entry_path.parent() {
|
if let Some(parent) = entry_path.parent() {
|
||||||
if fs::symlink_metadata(parent).await.is_err() {
|
if fs::symlink_metadata(parent).await.is_err() {
|
||||||
fs::create_dir_all(&parent).await?;
|
fs::create_dir_all(&parent).await?;
|
||||||
@@ -229,10 +259,16 @@ impl InnerService {
|
|||||||
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
|
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
|
||||||
let mut paths: Vec<PathItem> = vec![];
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
if exist {
|
if exist {
|
||||||
let mut rd = fs::read_dir(path).await?;
|
let mut rd = match fs::read_dir(path).await {
|
||||||
|
Ok(rd) => rd,
|
||||||
|
Err(_) => {
|
||||||
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
};
|
||||||
while let Some(entry) = rd.next_entry().await? {
|
while let Some(entry) = rd.next_entry().await? {
|
||||||
let entry_path = entry.path();
|
let entry_path = entry.path();
|
||||||
if let Ok(item) = to_pathitem(entry_path, path.to_path_buf()).await {
|
if let Ok(Some(item)) = self.to_pathitem(entry_path, path.to_path_buf()).await {
|
||||||
paths.push(item);
|
paths.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -261,7 +297,7 @@ impl InnerService {
|
|||||||
if fs::symlink_metadata(entry.path()).await.is_err() {
|
if fs::symlink_metadata(entry.path()).await.is_err() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
if let Ok(item) = to_pathitem(entry.path(), path.to_path_buf()).await {
|
if let Ok(Some(item)) = self.to_pathitem(entry.path(), path.to_path_buf()).await {
|
||||||
paths.push(item);
|
paths.push(item);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -271,14 +307,54 @@ impl InnerService {
|
|||||||
|
|
||||||
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
|
||||||
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
|
||||||
|
let filename = path.file_name().unwrap().to_str().unwrap();
|
||||||
let path = path.to_owned();
|
let path = path.to_owned();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
if let Err(e) = dir_zip(&mut writer, &path).await {
|
if let Err(e) = zip_dir(&mut writer, &path).await {
|
||||||
error!("Fail to zip {}, {}", path.display(), e.to_string());
|
error!("Fail to zip {}, {}", path.display(), e.to_string());
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
let stream = ReaderStream::new(reader);
|
let stream = ReaderStream::new(reader);
|
||||||
*res.body_mut() = Body::wrap_stream(stream);
|
*res.body_mut() = Body::wrap_stream(stream);
|
||||||
|
res.headers_mut().insert(
|
||||||
|
CONTENT_DISPOSITION,
|
||||||
|
HeaderValue::from_str(&format!("attachment; filename=\"{}.zip\"", filename,)).unwrap(),
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -343,6 +419,9 @@ impl InnerService {
|
|||||||
Body::wrap_stream(stream)
|
Body::wrap_stream(stream)
|
||||||
};
|
};
|
||||||
*res.body_mut() = body;
|
*res.body_mut() = body;
|
||||||
|
res.headers_mut().typed_insert(AcceptRanges::bytes());
|
||||||
|
res.headers_mut()
|
||||||
|
.typed_insert(ContentLength(meta.len() as u64));
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -388,7 +467,7 @@ impl InnerService {
|
|||||||
let pass = {
|
let pass = {
|
||||||
match &self.args.auth {
|
match &self.args.auth {
|
||||||
None => true,
|
None => true,
|
||||||
Some(auth) => match req.headers().get("Authorization") {
|
Some(auth) => match req.headers().get(AUTHORIZATION) {
|
||||||
Some(value) => match value.to_str().ok().map(|v| {
|
Some(value) => match value.to_str().ok().map(|v| {
|
||||||
let mut it = v.split(' ');
|
let mut it = v.split(' ');
|
||||||
(it.next(), it.next())
|
(it.next(), it.next())
|
||||||
@@ -412,6 +491,14 @@ impl InnerService {
|
|||||||
pass
|
pass
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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()
|
||||||
|
}
|
||||||
|
|
||||||
fn extract_path(&self, path: &str) -> Option<PathBuf> {
|
fn extract_path(&self, path: &str) -> Option<PathBuf> {
|
||||||
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
|
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
|
||||||
let slashes_switched = if cfg!(windows) {
|
let slashes_switched = if cfg!(windows) {
|
||||||
@@ -419,12 +506,41 @@ impl InnerService {
|
|||||||
} else {
|
} else {
|
||||||
decoded_path.into_owned()
|
decoded_path.into_owned()
|
||||||
};
|
};
|
||||||
let full_path = self.args.path.join(&slashes_switched);
|
Some(self.args.path.join(&slashes_switched))
|
||||||
if full_path.starts_with(&self.args.path) {
|
}
|
||||||
Some(full_path)
|
|
||||||
} else {
|
async fn to_pathitem<P: AsRef<Path>>(
|
||||||
None
|
&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);
|
||||||
}
|
}
|
||||||
|
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,
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -452,33 +568,6 @@ enum PathType {
|
|||||||
SymlinkFile,
|
SymlinkFile,
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn to_pathitem<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<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_dir = meta.is_dir();
|
|
||||||
let is_symlink = meta2.file_type().is_symlink();
|
|
||||||
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(PathItem {
|
|
||||||
path_type,
|
|
||||||
name,
|
|
||||||
mtime,
|
|
||||||
size,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_timestamp(time: &SystemTime) -> u64 {
|
fn to_timestamp(time: &SystemTime) -> u64 {
|
||||||
time.duration_since(SystemTime::UNIX_EPOCH)
|
time.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
@@ -504,27 +593,28 @@ fn add_cors(res: &mut Response) {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
|
async fn zip_dir<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
|
||||||
let mut writer = ZipFileWriter::new(writer);
|
let mut writer = ZipFileWriter::new(writer);
|
||||||
let mut walkdir = WalkDir::new(dir);
|
let mut walkdir = WalkDir::new(dir);
|
||||||
while let Some(entry) = walkdir.next().await {
|
while let Some(entry) = walkdir.next().await {
|
||||||
if let Ok(entry) = entry {
|
if let Ok(entry) = entry {
|
||||||
|
let entry_path = entry.path();
|
||||||
let meta = match fs::symlink_metadata(entry.path()).await {
|
let meta = match fs::symlink_metadata(entry.path()).await {
|
||||||
Ok(meta) => meta,
|
Ok(meta) => meta,
|
||||||
Err(_) => continue,
|
Err(_) => continue,
|
||||||
};
|
};
|
||||||
if meta.is_file() {
|
if !meta.is_file() {
|
||||||
let filepath = entry.path();
|
continue;
|
||||||
let filename = match filepath.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(&filepath).await?;
|
|
||||||
let mut file_writer = writer.write_entry_stream(entry_options).await?;
|
|
||||||
io::copy(&mut file, &mut file_writer).await?;
|
|
||||||
file_writer.close().await?;
|
|
||||||
}
|
}
|
||||||
|
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?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
writer.close().await?;
|
writer.close().await?;
|
||||||
|
|||||||
Reference in New Issue
Block a user