Compare commits

...

19 Commits

Author SHA1 Message Date
sigoden
605c6c56c4 chore: upgrade version 2022-06-01 23:12:52 +08:00
sigoden
8718562889 chore: update description 2022-06-01 22:55:11 +08:00
sigoden
830d3343f4 feat: support render-index/render-spa
closes #5
2022-06-01 22:49:55 +08:00
sigoden
1fe391f9d9 chore: move src/assets out of src 2022-06-01 20:26:03 +08:00
sigoden
b88381167b feat: add some headers to res 2022-06-01 20:02:35 +08:00
sigoden
35ed4394df fix: caught 500 if no permission to access dir
releated #4
2022-06-01 19:59:35 +08:00
sigoden
f43d0b646d fix: some typos
close #6
2022-05-31 22:38:00 +08:00
sigoden
a9294f602c feat: cli add allow-symlink option 2022-05-31 21:22:44 +08:00
sigoden
584d33940a chore: upgrade version 2022-05-31 17:02:55 +08:00
sigoden
fc090b6930 fix: not found dir when allow_upload is false 2022-05-31 16:55:52 +08:00
sigoden
19d7b36462 feat: drag and drop uploads, upload folder
close #3
2022-05-31 16:47:06 +08:00
sigoden
755554d3f2 fix: miss file 500 2022-05-31 16:32:50 +08:00
sigoden
6a097e0496 fix: unzip override existed file in uploadonly mode 2022-05-31 15:20:47 +08:00
sigoden
412d42e338 fix: downloaded zip file has no.zip ext in firefox
close #2
2022-05-31 14:39:07 +08:00
sigoden
ec60752ba2 chore: upgrade version 2022-05-31 11:10:15 +08:00
sigoden
ed7f5e425a feat: support range requests 2022-05-31 10:58:32 +08:00
sigoden
3032052923 feat: distinct upload and delete operation 2022-05-31 09:23:35 +08:00
sigoden
be3ae2fe00 feat: delete confirm
close #1
2022-05-31 08:01:03 +08:00
sigoden
fb03f7ddb8 refactor: improve code quality 2022-05-31 07:56:05 +08:00
8 changed files with 561 additions and 272 deletions

2
Cargo.lock generated
View File

@@ -296,7 +296,7 @@ dependencies = [
[[package]] [[package]]
name = "duf" name = "duf"
version = "0.5.0" version = "0.8.0"
dependencies = [ dependencies = [
"async-walkdir", "async-walkdir",
"async_zip", "async_zip",

View File

@@ -1,9 +1,9 @@
[package] [package]
name = "duf" name = "duf"
version = "0.5.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"

View File

@@ -3,7 +3,7 @@
[![CI](https://github.com/sigoden/duf/actions/workflows/ci.yaml/badge.svg)](https://github.com/sigoden/duf/actions/workflows/ci.yaml) [![CI](https://github.com/sigoden/duf/actions/workflows/ci.yaml/badge.svg)](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
[![Crates](https://img.shields.io/crates/v/duf.svg)](https://crates.io/crates/duf) [![Crates](https://img.shields.io/crates/v/duf.svg)](https://crates.io/crates/duf)
Duf is a simple file server. Duf is a fully functional file server.
![demo](https://user-images.githubusercontent.com/4012553/170853369-dfcdc4c7-4864-4401-bf49-6e41ffe05df3.png) ![demo](https://user-images.githubusercontent.com/4012553/170853369-dfcdc4c7-4864-4401-bf49-6e41ffe05df3.png)
@@ -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
@@ -44,14 +44,25 @@ duf
duf folder_name duf folder_name
``` ```
Only serve static files, disable editing operations such as update or delete Allow all operations such as upload, delete
``` ```
duf --readonly duf --allow-all
``` ```
Finally, run this command to see a list of all available option Only allow upload operations
### Curl ```
duf --allow-upload
```
Use http authentication
```
duf --auth user:pass
```
### Api
Download a file Download a file
``` ```

View File

@@ -159,8 +159,6 @@ body {
} }
.uploaders { .uploaders {
display: flex;
flex-wrap: wrap;
padding: 0.5em 0; padding: 0.5em 0;
} }

View File

@@ -4,7 +4,7 @@
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<meta name="viewport" content="width=device-width" /> <meta name="viewport" content="width=device-width" />
__SLOB__ __SLOT__
</head> </head>
<body> <body>
<div class="head"> <div class="head">
@@ -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>

View File

@@ -1,58 +1,69 @@
var $toolbox, $tbody, $breadcrumb, $uploaders, $uploadControl; let $tbody, $uploaders;
var uploaderIdx = 0; let baseDir;
var 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() {
var { file, idx } = this; const { file, idx, name } = this;
var 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}`);
var 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("load", e => this.complete(e), false); ajax.addEventListener("readystatechange", () => {
ajax.addEventListener("error", e => this.fail(e), false); if(ajax.readyState === 4) {
ajax.addEventListener("abort", e => this.fail(e), false); if (ajax.status == 200) {
this.complete();
} else {
this.fail();
}
}
})
ajax.addEventListener("error", () => this.fail(), false);
ajax.addEventListener("abort", () => this.fail(), false);
ajax.open("PUT", url); ajax.open("PUT", url);
ajax.send(file); ajax.send(file);
} }
progress(event) { progress(event) {
var 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(event) { complete() {
this.$elem.innerHTML = `${this.file.name}`; this.$elem.innerHTML = `${this.name}`;
} }
fail(event) { fail() {
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`; this.$elem.innerHTML = `<strike>${this.name}</strike>`;
} }
} }
function addBreadcrumb(value) { function addBreadcrumb(value) {
var parts = value.split("/").filter(v => !!v); const $breadcrumb = document.querySelector(".breadcrumb");
var len = parts.length; const parts = value.split("/").filter(v => !!v);
var path = ""; const len = parts.length;
for (var i = 0; i < len; i++) { let path = "";
var name = parts[i]; for (let i = 0; i < len; i++) {
const name = parts[i];
if (i > 0) { if (i > 0) {
path += "/" + name; path += "/" + name;
} }
@@ -69,9 +80,9 @@ function addBreadcrumb(value) {
} }
function addPath(file, index) { function addPath(file, index) {
var url = getUrl(file.name) const url = getUrl(file.name)
var actionDelete = ""; let actionDelete = "";
var actionDownload = ""; let actionDownload = "";
if (file.path_type.endsWith("Dir")) { if (file.path_type.endsWith("Dir")) {
actionDownload = ` actionDownload = `
<div class="action-btn"> <div class="action-btn">
@@ -87,13 +98,13 @@ function addPath(file, index) {
</a> </a>
</div>`; </div>`;
} }
if (!DATA.readonly) { if (DATA.allow_delete) {
actionDelete = ` actionDelete = `
<div onclick="deletePath(${index})" class="action-btn" id="deleteBtn${index}" title="Delete ${file.name}"> <div onclick="deletePath(${index})" class="action-btn" id="deleteBtn${index}" title="Delete ${file.name}">
<svg width="16" height="16" fill="currentColor"viewBox="0 0 16 16"><path d="M6.854 7.146a.5.5 0 1 0-.708.708L7.293 9l-1.147 1.146a.5.5 0 0 0 .708.708L8 9.707l1.146 1.147a.5.5 0 0 0 .708-.708L8.707 9l1.147-1.146a.5.5 0 0 0-.708-.708L8 8.293 6.854 7.146z"/><path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/></svg> <svg width="16" height="16" fill="currentColor"viewBox="0 0 16 16"><path d="M6.854 7.146a.5.5 0 1 0-.708.708L7.293 9l-1.147 1.146a.5.5 0 0 0 .708.708L8 9.707l1.146 1.147a.5.5 0 0 0 .708-.708L8.707 9l1.147-1.146a.5.5 0 0 0-.708-.708L8 8.293 6.854 7.146z"/><path d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z"/></svg>
</div>`; </div>`;
} }
var actionCell = ` let actionCell = `
<td class="cell-actions"> <td class="cell-actions">
${actionDownload} ${actionDownload}
${actionDelete} ${actionDelete}
@@ -112,21 +123,65 @@ ${actionCell}
} }
async function deletePath(index) { async function deletePath(index) {
var file = DATA.paths[index]; const file = DATA.paths[index];
if (!file) return; if (!file) return;
var ajax = new XMLHttpRequest(); if (!confirm(`Delete \`${file.name}\`?`)) return;
ajax.open("DELETE", getUrl(file.name));
ajax.addEventListener("readystatechange", function() { try {
if(ajax.readyState === 4 && ajax.status === 200) { const res = await fetch(getUrl(file.name), {
document.getElementById(`addPath${index}`).remove(); method: "DELETE",
}
}); });
ajax.send(); if (res.status === 200) {
document.getElementById(`addPath${index}`).remove();
} else {
throw new Error(await res.text())
}
} catch (err) {
alert(`Cannot delete \`${file.name}\`, ${err.message}`);
}
} }
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) {
var url = location.href.split('?')[0]; let url = location.href.split('?')[0];
if (!url.endsWith("/")) url += "/"; if (!url.endsWith("/")) url += "/";
url += encodeURI(name); url += encodeURI(name);
return url; return url;
@@ -147,12 +202,12 @@ function getSvg(path_type) {
function formatMtime(mtime) { function formatMtime(mtime) {
if (!mtime) return "" if (!mtime) return ""
var date = new Date(mtime); const date = new Date(mtime);
var year = date.getFullYear(); const year = date.getFullYear();
var month = padZero(date.getMonth() + 1, 2); const month = padZero(date.getMonth() + 1, 2);
var day = padZero(date.getDate(), 2); const day = padZero(date.getDate(), 2);
var hours = padZero(date.getHours(), 2); const hours = padZero(date.getHours(), 2);
var minutes = padZero(date.getMinutes(), 2); const minutes = padZero(date.getMinutes(), 2);
return `${year}/${month}/${day} ${hours}:${minutes}`; return `${year}/${month}/${day} ${hours}:${minutes}`;
} }
@@ -162,29 +217,30 @@ function padZero(value, size) {
function formatSize(size) { function formatSize(size) {
if (!size) return "" if (!size) return ""
var sizes = ['B', 'KB', 'MB', 'GB', 'TB']; const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (size == 0) return '0 Byte'; if (size == 0) return '0 Byte';
var i = parseInt(Math.floor(Math.log(size) / Math.log(1024))); const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
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() {
$toolbox = document.querySelector(".toolbox");
$tbody = document.querySelector(".main tbody"); $tbody = document.querySelector(".main tbody");
$breadcrumb = document.querySelector(".breadcrumb");
$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)) {
if (!DATA.readonly) { const len = DATA.paths.length;
for (let i = 0; i < len; i++) {
addPath(DATA.paths[i], i);
}
}
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 => {
var files = e.target.files; const files = e.target.files;
for (var file of files) { for (let file of files) {
uploaderIdx += 1; new Uploader(file, []).upload();
var uploader = new Uploader(uploaderIdx, file);
uploader.upload();
} }
}); });
} }

View File

@@ -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,13 +31,38 @@ 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("readonly") Arg::new("allow-all")
.short('r') .short('A')
.long("readonly") .long("allow-all")
.help("Disable change operations such as update or delete"), .help("Allow all operations"),
)
.arg(
Arg::new("allow-upload")
.long("allow-upload")
.help("Allow upload operation"),
)
.arg(
Arg::new("allow-delete")
.long("allow-delete")
.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")
@@ -68,9 +92,13 @@ pub struct Args {
pub address: String, pub address: String,
pub port: u16, pub port: u16,
pub path: PathBuf, pub path: PathBuf,
pub readonly: bool,
pub auth: Option<String>, pub auth: Option<String>,
pub no_auth_read: bool, pub no_auth_read: bool,
pub allow_upload: bool,
pub allow_delete: bool,
pub allow_symlink: bool,
pub render_index: bool,
pub render_spa: bool,
pub cors: bool, pub cors: bool,
} }
@@ -82,21 +110,28 @@ impl Args {
pub fn parse(matches: ArgMatches) -> BoxResult<Args> { pub fn parse(matches: ArgMatches) -> BoxResult<Args> {
let address = matches.value_of("address").unwrap_or_default().to_owned(); let address = matches.value_of("address").unwrap_or_default().to_owned();
let port = matches.value_of_t::<u16>("port")?; let port = matches.value_of_t::<u16>("port")?;
let path = matches.value_of_os("path").unwrap_or_default(); let path = Args::parse_path(matches.value_of_os("path").unwrap_or_default())?;
let path = Args::parse_path(path)?;
let readonly = matches.is_present("readonly");
let cors = matches.is_present("cors"); let cors = matches.is_present("cors");
let auth = matches.value_of("auth").map(|v| v.to_owned()); let auth = matches.value_of("auth").map(|v| v.to_owned());
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_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,
port, port,
path, path,
readonly,
auth, auth,
no_auth_read, no_auth_read,
cors, cors,
allow_delete,
allow_upload,
allow_symlink,
render_index,
render_spa,
}) })
} }
@@ -110,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!(

View File

@@ -7,20 +7,25 @@ use async_zip::Compression;
use futures::stream::StreamExt; use futures::stream::StreamExt;
use futures::TryStreamExt; use futures::TryStreamExt;
use headers::{ use headers::{
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentType, ETag, HeaderMapExt, AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
IfModifiedSince, IfNoneMatch, LastModified, 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;
use serde::Serialize; use serde::Serialize;
use std::convert::Infallible; use std::convert::Infallible;
use std::fs::Metadata;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use std::time::SystemTime; use std::time::SystemTime;
use tokio::fs::File; use tokio::fs::File;
use tokio::io::AsyncWrite; use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWrite};
use tokio::{fs, io}; use tokio::{fs, io};
use tokio_util::codec::{BytesCodec, FramedRead}; use tokio_util::codec::{BytesCodec, FramedRead};
use tokio_util::io::{ReaderStream, StreamReader}; use tokio_util::io::{ReaderStream, StreamReader};
@@ -28,20 +33,19 @@ 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>;
macro_rules! status_code { const INDEX_HTML: &str = include_str!("../assets/index.html");
($status:expr) => { const INDEX_CSS: &str = include_str!("../assets/index.css");
hyper::Response::builder() const INDEX_JS: &str = include_str!("../assets/index.js");
.status($status) const INDEX_NAME: &str = "index.html";
.body($status.canonical_reason().unwrap_or_default().into()) const BUF_SIZE: usize = 1024 * 16;
.unwrap()
macro_rules! status {
($res:ident, $status:expr) => {
*$res.status_mut() = $status;
*$res.body_mut() = Body::from($status.canonical_reason().unwrap_or_default());
}; };
} }
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");
const BUF_SIZE: usize = 1024 * 16;
pub async fn serve(args: Args) -> BoxResult<()> { pub async fn serve(args: Args) -> BoxResult<()> {
let address = args.address()?; let address = args.address()?;
let inner = Arc::new(InnerService::new(args)); let inner = Arc::new(InnerService::new(args));
@@ -76,11 +80,20 @@ impl InnerService {
let method = req.method().clone(); let method = req.method().clone();
let uri = req.uri().clone(); let uri = req.uri().clone();
let cors = self.args.cors; let cors = self.args.cors;
let mut res = self
.handle(req) let mut res = match self.handle(req).await {
.await Ok(res) => {
.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR));
info!(r#""{} {}" - {}"#, method, uri, res.status()); info!(r#""{} {}" - {}"#, method, uri, res.status());
res
}
Err(err) => {
let mut res = Response::default();
status!(res, StatusCode::INTERNAL_SERVER_ERROR);
error!(r#""{} {}" - {} {}"#, method, uri, res.status(), err);
res
}
};
if cors { if cors {
add_cors(&mut res); add_cors(&mut res);
} }
@@ -88,74 +101,109 @@ impl InnerService {
} }
pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> { pub async fn handle(self: Arc<Self>, req: Request) -> BoxResult<Response> {
if !self.auth_guard(&req).unwrap_or_default() { let mut res = Response::default();
let mut res = status_code!(StatusCode::UNAUTHORIZED);
res.headers_mut() if !self.auth_guard(&req, &mut res) {
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
return Ok(res); return Ok(res);
} }
match *req.method() {
Method::GET => self.handle_static(req).await,
Method::PUT => {
if self.args.readonly {
return Ok(status_code!(StatusCode::FORBIDDEN));
}
self.handle_upload(req).await
}
Method::OPTIONS => Ok(status_code!(StatusCode::NO_CONTENT)),
Method::DELETE => self.handle_delete(req).await,
_ => Ok(status_code!(StatusCode::NOT_FOUND)),
}
}
async fn handle_static(&self, req: Request) -> BoxResult<Response> {
let req_path = req.uri().path(); let req_path = req.uri().path();
let path = match self.get_file_path(req_path)? {
Some(path) => path, let path = match self.extract_path(req_path) {
None => return Ok(status_code!(StatusCode::FORBIDDEN)), Some(v) => v,
None => {
status!(res, StatusCode::FORBIDDEN);
return Ok(res);
}
}; };
match fs::metadata(&path).await { let path = path.as_path();
Ok(meta) => {
if meta.is_dir() { let query = req.uri().query().unwrap_or_default();
let req_query = req.uri().query().unwrap_or_default();
if req_query == "zip" { let meta = fs::metadata(path).await.ok();
return self.handle_send_dir_zip(path.as_path()).await;
} let is_miss = meta.is_none();
if let Some(q) = req_query.strip_prefix("q=") { let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
return self.handle_query_dir(path.as_path(), q).await; let is_file = !is_miss && !is_dir;
}
self.handle_ls_dir(path.as_path(), true).await let allow_upload = self.args.allow_upload;
} else { let allow_delete = self.args.allow_delete;
self.handle_send_file(&req, path.as_path()).await let render_index = self.args.render_index;
} let render_spa = self.args.render_spa;
}
Err(_) => { if !self.args.allow_symlink && !is_miss && !self.is_root_contained(path).await {
if req_path.ends_with('/') { status!(res, StatusCode::NOT_FOUND);
self.handle_ls_dir(path.as_path(), false).await return Ok(res);
} else {
Ok(status_code!(StatusCode::NOT_FOUND))
}
}
}
} }
async fn handle_upload(&self, mut req: Request) -> BoxResult<Response> { match *req.method() {
let forbidden = status_code!(StatusCode::FORBIDDEN); Method::GET => {
let path = match self.get_file_path(req.uri().path())? { let headers = req.headers();
Some(path) => path, if is_dir {
None => return Ok(forbidden), 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::OPTIONS => {
status!(res, StatusCode::NO_CONTENT);
}
Method::PUT => {
if !allow_upload || (!allow_delete && is_file) {
status!(res, StatusCode::FORBIDDEN);
} else {
self.handle_upload(path, req, &mut res).await?;
}
}
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);
}
}
_ => {
status!(res, StatusCode::METHOD_NOT_ALLOWED);
}
}
Ok(res)
}
match path.parent() { async fn handle_upload(
&self,
path: &Path,
mut req: Request,
res: &mut Response,
) -> BoxResult<()> {
let ensure_parent = match path.parent() {
Some(parent) => match fs::metadata(parent).await { Some(parent) => match fs::metadata(parent).await {
Ok(meta) => { Ok(meta) => meta.is_dir(),
if !meta.is_dir() { Err(_) => {
return Ok(forbidden); fs::create_dir_all(parent).await?;
true
} }
}
Err(_) => fs::create_dir_all(parent).await?,
}, },
None => return Ok(forbidden), None => false,
};
if !ensure_parent {
status!(res, StatusCode::FORBIDDEN);
return Ok(());
} }
let mut file = fs::File::create(&path).await?; let mut file = fs::File::create(&path).await?;
@@ -170,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() {
@@ -181,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?;
@@ -194,39 +245,43 @@ impl InnerService {
fs::remove_file(&path).await?; fs::remove_file(&path).await?;
} }
return Ok(status_code!(StatusCode::OK)); Ok(())
} }
async fn handle_delete(&self, req: Request) -> BoxResult<Response> { async fn handle_delete(&self, path: &Path, is_dir: bool) -> BoxResult<()> {
let path = match self.get_file_path(req.uri().path())? { match is_dir {
Some(path) => path, true => fs::remove_dir_all(path).await?,
None => return Ok(status_code!(StatusCode::FORBIDDEN)), false => fs::remove_file(path).await?,
};
let meta = fs::metadata(&path).await?;
if meta.is_file() {
fs::remove_file(path).await?;
} else {
fs::remove_dir_all(path).await?;
} }
Ok(status_code!(StatusCode::OK)) Ok(())
} }
async fn handle_ls_dir(&self, path: &Path, exist: bool) -> BoxResult<Response> { 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) = get_path_item(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);
} }
} }
} }
self.send_index(path, paths) self.send_index(path, paths, res)
} }
async fn handle_query_dir(&self, path: &Path, q: &str) -> BoxResult<Response> { async fn handle_query_dir(
&self,
path: &Path,
query: &str,
res: &mut Response,
) -> BoxResult<()> {
let mut paths: Vec<PathItem> = vec![]; let mut paths: Vec<PathItem> = vec![];
let mut walkdir = WalkDir::new(path); let mut walkdir = WalkDir::new(path);
while let Some(entry) = walkdir.next().await { while let Some(entry) = walkdir.next().await {
@@ -235,73 +290,148 @@ impl InnerService {
.file_name() .file_name()
.to_string_lossy() .to_string_lossy()
.to_lowercase() .to_lowercase()
.contains(&q.to_lowercase()) .contains(&query.to_lowercase())
{ {
continue; continue;
} }
if fs::symlink_metadata(entry.path()).await.is_err() { if fs::symlink_metadata(entry.path()).await.is_err() {
continue; continue;
} }
if let Ok(item) = get_path_item(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);
} }
} }
} }
self.send_index(path, paths) self.send_index(path, paths, res)
} }
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> { 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);
let body = Body::wrap_stream(stream); *res.body_mut() = Body::wrap_stream(stream);
Ok(Response::new(body)) res.headers_mut().insert(
CONTENT_DISPOSITION,
HeaderValue::from_str(&format!("attachment; filename=\"{}.zip\"", filename,)).unwrap(),
);
Ok(())
} }
async fn handle_send_file(&self, req: &Request, path: &Path) -> BoxResult<Response> { async fn handle_render_index(
let (file, meta) = tokio::join!(fs::File::open(path), fs::metadata(path),); &self,
let (file, meta) = (file?, meta?); path: &Path,
let mut res = Response::default(); headers: &HeaderMap<HeaderValue>,
if let Ok(mtime) = meta.modified() { res: &mut Response,
let timestamp = get_timestamp(&mtime); ) -> BoxResult<()> {
let size = meta.len(); let path = path.join(INDEX_NAME);
let etag = format!(r#""{}-{}""#, timestamp, size) if fs::metadata(&path)
.parse::<ETag>() .await
.unwrap(); .ok()
let last_modified = LastModified::from(mtime); .map(|v| v.is_file())
let fresh = { .unwrap_or_default()
// `If-None-Match` takes presedence over `If-Modified-Since`.
if let Some(if_none_match) = req.headers().typed_get::<IfNoneMatch>() {
!if_none_match.precondition_passes(&etag)
} else if let Some(if_modified_since) = req.headers().typed_get::<IfModifiedSince>()
{ {
!if_modified_since.is_modified(mtime) 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(())
}
async fn handle_send_file(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
let (file, meta) = tokio::join!(fs::File::open(path), fs::metadata(path),);
let (mut file, meta) = (file?, meta?);
let mut maybe_range = true;
if let Some((etag, last_modified)) = extract_cache_headers(&meta) {
let cached = {
if let Some(if_none_match) = headers.typed_get::<IfNoneMatch>() {
!if_none_match.precondition_passes(&etag)
} else if let Some(if_modified_since) = headers.typed_get::<IfModifiedSince>() {
!if_modified_since.is_modified(last_modified.into())
} else { } else {
false false
} }
}; };
res.headers_mut().typed_insert(last_modified); res.headers_mut().typed_insert(last_modified);
res.headers_mut().typed_insert(etag); res.headers_mut().typed_insert(etag.clone());
if fresh { if cached {
*res.status_mut() = StatusCode::NOT_MODIFIED; status!(res, StatusCode::NOT_MODIFIED);
return Ok(res); return Ok(());
}
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;
} }
} }
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
};
if let Some(mime) = mime_guess::from_path(&path).first() { if let Some(mime) = mime_guess::from_path(&path).first() {
res.headers_mut().typed_insert(ContentType::from(mime)); res.headers_mut().typed_insert(ContentType::from(mime));
} }
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()); let stream = FramedRead::new(file, BytesCodec::new());
let body = Body::wrap_stream(stream); Body::wrap_stream(stream)
};
*res.body_mut() = body; *res.body_mut() = body;
Ok(res) res.headers_mut().typed_insert(AcceptRanges::bytes());
res.headers_mut()
.typed_insert(ContentLength(meta.len() as u64));
Ok(())
} }
fn send_index(&self, path: &Path, mut paths: Vec<PathItem>) -> BoxResult<Response> { fn send_index(
&self,
path: &Path,
mut paths: Vec<PathItem>,
res: &mut Response,
) -> BoxResult<()> {
paths.sort_unstable(); paths.sort_unstable();
let rel_path = match self.args.path.parent() { let rel_path = match self.args.path.parent() {
Some(p) => path.strip_prefix(p).unwrap(), Some(p) => path.strip_prefix(p).unwrap(),
@@ -310,14 +440,15 @@ impl InnerService {
let data = IndexData { let data = IndexData {
breadcrumb: normalize_path(rel_path), breadcrumb: normalize_path(rel_path),
paths, paths,
readonly: self.args.readonly, allow_upload: self.args.allow_upload,
allow_delete: self.args.allow_delete,
}; };
let data = serde_json::to_string(&data).unwrap(); let data = serde_json::to_string(&data).unwrap();
let output = INDEX_HTML.replace( let output = INDEX_HTML.replace(
"__SLOB__", "__SLOT__",
&format!( &format!(
r#" r#"
<title>Files in {} - Duf/</title> <title>Files in {}/ - Duf</title>
<style>{}</style> <style>{}</style>
<script>var DATA = {}; {}</script> <script>var DATA = {}; {}</script>
"#, "#,
@@ -327,45 +458,89 @@ impl InnerService {
INDEX_JS INDEX_JS
), ),
); );
*res.body_mut() = output.into();
Ok(Response::new(output.into())) Ok(())
} }
fn auth_guard(&self, req: &Request) -> BoxResult<bool> { fn auth_guard(&self, req: &Request, res: &mut Response) -> bool {
if let Some(auth) = &self.args.auth { let pass = {
if let Some(value) = req.headers().get("Authorization") { match &self.args.auth {
let value = value.to_str()?; None => true,
let value = if value.contains("Basic ") { Some(auth) => match req.headers().get(AUTHORIZATION) {
&value[6..] Some(value) => match value.to_str().ok().map(|v| {
} else { let mut it = v.split(' ');
return Ok(false); (it.next(), it.next())
}) {
Some((Some("Basic"), Some(tail))) => base64::decode(tail)
.ok()
.and_then(|v| String::from_utf8(v).ok())
.map(|v| v.as_str() == auth)
.unwrap_or_default(),
_ => false,
},
None => self.args.no_auth_read && req.method() == Method::GET,
},
}
}; };
let value = base64::decode(value)?; if !pass {
let value = std::str::from_utf8(&value)?; status!(res, StatusCode::UNAUTHORIZED);
return Ok(value == auth); res.headers_mut()
} else { .insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic"));
if self.args.no_auth_read && req.method() == Method::GET {
return Ok(true);
} }
return Ok(false); pass
}
}
Ok(true)
} }
fn get_file_path(&self, path: &str) -> BoxResult<Option<PathBuf>> { async fn is_root_contained(&self, path: &Path) -> bool {
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?; fs::canonicalize(path)
.await
.ok()
.map(|v| v.starts_with(&self.args.path))
.unwrap_or_default()
}
fn extract_path(&self, path: &str) -> Option<PathBuf> {
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
let slashes_switched = if cfg!(windows) { let slashes_switched = if cfg!(windows) {
decoded_path.replace('/', "\\") decoded_path.replace('/', "\\")
} else { } else {
decoded_path.into_owned() decoded_path.into_owned()
}; };
let path = self.args.path.join(&slashes_switched); Some(self.args.path.join(&slashes_switched))
if path.starts_with(&self.args.path) {
Ok(Some(path))
} else {
Ok(None)
} }
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);
}
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,
}))
} }
} }
@@ -373,7 +548,8 @@ impl InnerService {
struct IndexData { struct IndexData {
breadcrumb: String, breadcrumb: String,
paths: Vec<PathItem>, paths: Vec<PathItem>,
readonly: bool, allow_upload: bool,
allow_delete: bool,
} }
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
@@ -392,34 +568,7 @@ enum PathType {
SymlinkFile, SymlinkFile,
} }
async fn get_path_item<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> { fn to_timestamp(time: &SystemTime) -> u64 {
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 = get_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 get_timestamp(time: &SystemTime) -> u64 {
time.duration_since(SystemTime::UNIX_EPOCH) time.duration_since(SystemTime::UNIX_EPOCH)
.unwrap() .unwrap()
.as_millis() as u64 .as_millis() as u64
@@ -444,29 +593,69 @@ 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()) { }
let filename = match entry_path.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
Some(v) => v, Some(v) => v,
None => continue, None => continue,
}; };
let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate); let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate);
let mut file = File::open(&filepath).await?; let mut file = File::open(&entry_path).await?;
let mut file_writer = writer.write_entry_stream(entry_options).await?; let mut file_writer = writer.write_entry_stream(entry_options).await?;
io::copy(&mut file, &mut file_writer).await?; io::copy(&mut file, &mut file_writer).await?;
file_writer.close().await?; file_writer.close().await?;
} }
} }
}
writer.close().await?; writer.close().await?;
Ok(()) Ok(())
} }
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,
})
}