Compare commits

...

31 Commits

Author SHA1 Message Date
sigoden
f66e129985 chore(release): version v0.10.1 2022-06-03 07:21:15 +08:00
sigoden
7c3970480e chore: add type comments to assets/js 2022-06-03 07:18:12 +08:00
sigoden
34bc8d411a fix: panic when bind already used port 2022-06-03 07:15:41 +08:00
sigoden
51cedf2f8a chore(release): version v0.10.0 2022-06-03 06:58:10 +08:00
sigoden
48c3c7ded6 fix: broken ui 2022-06-03 06:57:20 +08:00
sigoden
4491a74b34 docs: refactor readme 2022-06-03 06:51:50 +08:00
sigoden
7c2449cb1a fix: rename --no-auth-read to --no-auth-access 2022-06-03 06:51:03 +08:00
sigoden
0a3d9c391f feat: improve ui 2022-06-03 06:49:55 +08:00
sigoden
07f4e7d0f2 fix: remove unzip file even failed to unzip 2022-06-02 19:43:43 +08:00
sigoden
c50f97925c feat: change auth logic/options 2022-06-02 19:36:04 +08:00
sigoden
ecb3984edc chore(readme): insert cli output 2022-06-02 17:10:15 +08:00
sigoden
24f885164a refactor: small improvement 2022-06-02 17:06:22 +08:00
sigoden
201afa6725 chore(release): version v0.9.0 2022-06-02 16:31:43 +08:00
sigoden
e2d7f996c7 feat: support tls 2022-06-02 12:15:06 +08:00
sigoden
97978719b3 feat: list all ifaces when listening 0.0.0.0 2022-06-02 09:44:40 +08:00
sigoden
9aa16d3a10 docs: improve readme 2022-06-02 09:08:55 +08:00
sigoden
d208b5cb6b feat: support path prefix 2022-06-02 08:32:31 +08:00
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
10 changed files with 994 additions and 290 deletions

173
CHANGELOG.md Normal file
View File

@@ -0,0 +1,173 @@
# Changelog
All notable changes to this project will be documented in this file.
## [0.10.1] - 2022-06-02
### Bug Fixes
- Panic when bind already used port
## [0.10.0] - 2022-06-02
### Bug Fixes
- Remove unzip file even failed to unzip
- Rename --no-auth-read to --no-auth-access
- Broken ui
### Documentation
- Refactor readme
### Features
- Change auth logic/options
- Improve ui
### Refactor
- Small improvement
## [0.9.0] - 2022-06-02
### Documentation
- Improve readme
### Features
- Support path prefix
- List all ifaces when listening 0.0.0.0
- Support tls
## [0.8.0] - 2022-06-01
### Bug Fixes
- Some typos
- Caught 500 if no permission to access dir
### Features
- Cli add allow-symlink option
- Add some headers to res
- Support render-index/render-spa
## [0.7.0] - 2022-05-31
### Bug Fixes
- Downloaded zip file has no.zip ext in firefox
- Unzip override existed file in uploadonly mode
- Miss file 500
- Not found dir when allow_upload is false
### Features
- Drag and drop uploads, upload folder
## [0.6.0] - 2022-05-31
### Features
- Delete confirm
- Distinct upload and delete operation
- Support range requests
### Refactor
- Improve code quality
## [0.5.0] - 2022-05-30
### Features
- Add mime and cache headers to response
- Add no-auth-read options
- Unzip zip file when unload
## [0.4.0] - 2022-05-29
### Features
- Replace --static option to --no-edit
- Add cors
## [0.3.0] - 2022-05-29
### Documentation
- Update readme demo png
### Features
- Automatically create dir while uploading
- Support searching
### Refactor
- Handler zip
### Styling
- Optimize css
## [0.2.1] - 2022-05-28
### Bug Fixes
- Cannot upload in root
- Optimize download zip
### Documentation
- Improve readme
### Features
- Aware RUST_LOG
## [0.2.0] - 2022-05-28
### Documentation
- Update demo png
- Improve readme
### Features
- Add logger
- Download folder as zip file
## [0.1.0] - 2022-05-26
### Bug Fixes
- Caught server error when symlink broken
### Documentation
- Improve readme
- Update readme
### Features
- Add basic auth and readonly mode
- Support delete operation
- Remove parent path
### Styling
- Cargo fmt
- Update index page
### Build
- Remove dev deps
### Ci
- Init ci
<!-- generated by git-cliff -->

291
Cargo.lock generated
View File

@@ -101,17 +101,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "065374052e7df7ee4047b1160cca5e1467a12351a40b3da123c870ba0b8eda2a"
[[package]]
name = "atty"
version = "0.2.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8"
dependencies = [
"hermit-abi",
"libc",
"winapi",
]
[[package]]
name = "autocfg"
version = "1.1.0"
@@ -153,6 +142,12 @@ dependencies = [
"once_cell",
]
[[package]]
name = "bumpalo"
version = "3.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3"
[[package]]
name = "bytes"
version = "1.1.0"
@@ -180,6 +175,12 @@ dependencies = [
"pkg-config",
]
[[package]]
name = "c_linked_list"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b"
[[package]]
name = "cache-padded"
version = "1.2.0"
@@ -210,8 +211,8 @@ dependencies = [
"libc",
"num-integer",
"num-traits",
"time 0.1.44",
"winapi",
"time",
"winapi 0.3.9",
]
[[package]]
@@ -236,17 +237,6 @@ dependencies = [
"os_str_bytes",
]
[[package]]
name = "colored"
version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3616f750b84d8f0de8a58bda93e08e2a81ad3f523089b05f1dffecab48c6cbd"
dependencies = [
"atty",
"lazy_static",
"winapi",
]
[[package]]
name = "concurrent-queue"
version = "1.2.2"
@@ -296,22 +286,26 @@ dependencies = [
[[package]]
name = "duf"
version = "0.6.0"
version = "0.10.1"
dependencies = [
"async-walkdir",
"async_zip",
"base64",
"chrono",
"clap",
"futures",
"get_if_addrs",
"headers",
"hyper",
"log",
"mime_guess",
"percent-encoding",
"rustls",
"rustls-pemfile",
"serde",
"serde_json",
"simple_logger",
"tokio",
"tokio-rustls",
"tokio-stream",
"tokio-util",
]
@@ -452,6 +446,12 @@ dependencies = [
"slab",
]
[[package]]
name = "gcc"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
[[package]]
name = "generic-array"
version = "0.14.5"
@@ -462,6 +462,28 @@ dependencies = [
"version_check",
]
[[package]]
name = "get_if_addrs"
version = "0.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "abddb55a898d32925f3148bd281174a68eeb68bbfd9a5938a57b18f506ee4ef7"
dependencies = [
"c_linked_list",
"get_if_addrs-sys",
"libc",
"winapi 0.2.8",
]
[[package]]
name = "get_if_addrs-sys"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0d04f9fb746cf36b191c00f3ede8bde9c8e64f9f4b05ae2694a9ccf5e3f5ab48"
dependencies = [
"gcc",
"libc",
]
[[package]]
name = "hashbrown"
version = "0.11.2"
@@ -593,6 +615,15 @@ dependencies = [
"libc",
]
[[package]]
name = "js-sys"
version = "0.3.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "671a26f820db17c2a2750743f1dd03bafd15b98c9f30c7c2628c024c05d73397"
dependencies = [
"wasm-bindgen",
]
[[package]]
name = "lazy_static"
version = "1.4.0"
@@ -697,15 +728,6 @@ dependencies = [
"libc",
]
[[package]]
name = "num_threads"
version = "0.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
dependencies = [
"libc",
]
[[package]]
name = "once_cell"
version = "1.12.0"
@@ -766,12 +788,58 @@ dependencies = [
"proc-macro2",
]
[[package]]
name = "ring"
version = "0.16.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3053cf52e236a3ed746dfc745aa9cacf1b791d846bdaf412f60a8d7d6e17c8fc"
dependencies = [
"cc",
"libc",
"once_cell",
"spin",
"untrusted",
"web-sys",
"winapi 0.3.9",
]
[[package]]
name = "rustls"
version = "0.20.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5aab8ee6c7097ed6057f43c187a62418d0c05a4bd5f18b3571db50ee0f9ce033"
dependencies = [
"log",
"ring",
"sct",
"webpki",
]
[[package]]
name = "rustls-pemfile"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7522c9de787ff061458fe9a829dc790a3f5b22dc571694fc5883f448b94d9a9"
dependencies = [
"base64",
]
[[package]]
name = "ryu"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695"
[[package]]
name = "sct"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d53dcdb7c9f8158937a7981b48accfd39a43af418591a5d008c7b22b5e1b7ca4"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "serde"
version = "1.0.137"
@@ -814,19 +882,6 @@ dependencies = [
"digest",
]
[[package]]
name = "simple_logger"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75a9723083573ace81ad0cdfc50b858aa3c366c48636edb4109d73122a0c0ea"
dependencies = [
"atty",
"colored",
"log",
"time 0.3.9",
"winapi",
]
[[package]]
name = "slab"
version = "0.4.6"
@@ -840,9 +895,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0"
dependencies = [
"libc",
"winapi",
"winapi 0.3.9",
]
[[package]]
name = "spin"
version = "0.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"
[[package]]
name = "syn"
version = "1.0.95"
@@ -888,27 +949,9 @@ checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
dependencies = [
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
"winapi",
"winapi 0.3.9",
]
[[package]]
name = "time"
version = "0.3.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2702e08a7a860f005826c6815dcac101b19b5eb330c27fe4a5928fec1d20ddd"
dependencies = [
"itoa",
"libc",
"num_threads",
"time-macros",
]
[[package]]
name = "time-macros"
version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "42657b1a6f4d817cda8e7a0ace261fe0cc946cf3a80314390b22cc61ae080792"
[[package]]
name = "tokio"
version = "1.18.2"
@@ -924,7 +967,7 @@ dependencies = [
"pin-project-lite",
"socket2",
"tokio-macros",
"winapi",
"winapi 0.3.9",
]
[[package]]
@@ -938,6 +981,28 @@ dependencies = [
"syn",
]
[[package]]
name = "tokio-rustls"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c43ee83903113e03984cb9e5cebe6c04a5116269e900e3ddba8f068a62adda59"
dependencies = [
"rustls",
"tokio",
"webpki",
]
[[package]]
name = "tokio-stream"
version = "0.1.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50145484efff8818b5ccd256697f36863f587da82cf8b409c53adf1e840798e3"
dependencies = [
"futures-core",
"pin-project-lite",
"tokio",
]
[[package]]
name = "tokio-util"
version = "0.7.2"
@@ -1017,6 +1082,12 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
[[package]]
name = "untrusted"
version = "0.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"
[[package]]
name = "version_check"
version = "0.9.4"
@@ -1051,6 +1122,86 @@ version = "0.11.0+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
[[package]]
name = "wasm-bindgen"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "27370197c907c55e3f1a9fbe26f44e937fe6451368324e009cba39e139dc08ad"
dependencies = [
"cfg-if",
"wasm-bindgen-macro",
]
[[package]]
name = "wasm-bindgen-backend"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "53e04185bfa3a779273da532f5025e33398409573f348985af9a1cbf3774d3f4"
dependencies = [
"bumpalo",
"lazy_static",
"log",
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "17cae7ff784d7e83a2fe7611cfe766ecf034111b49deb850a3dc7699c08251f5"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "99ec0dc7a4756fffc231aab1b9f2f578d23cd391390ab27f952ae0c9b3ece20b"
dependencies = [
"proc-macro2",
"quote",
"syn",
"wasm-bindgen-backend",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
version = "0.2.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d554b7f530dee5964d9a9468d95c1f8b8acae4f282807e7d27d4b03099a46744"
[[package]]
name = "web-sys"
version = "0.3.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b17e741662c70c8bd24ac5c5b18de314a2c26c32bf8346ee1e6f53de919c283"
dependencies = [
"js-sys",
"wasm-bindgen",
]
[[package]]
name = "webpki"
version = "0.22.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f095d78192e208183081cc07bc5515ef55216397af48b873e5edcd72637fa1bd"
dependencies = [
"ring",
"untrusted",
]
[[package]]
name = "winapi"
version = "0.2.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "167dc9d6949a9b857f3451275e911c3f44255842c1f7a76f33c55103a909087a"
[[package]]
name = "winapi"
version = "0.3.9"

View File

@@ -1,9 +1,9 @@
[package]
name = "duf"
version = "0.6.0"
version = "0.10.1"
edition = "2021"
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"
homepage = "https://github.com/sigoden/duf"
repository = "https://github.com/sigoden/duf"
@@ -13,20 +13,24 @@ keywords = ["static", "file", "server", "http", "cli"]
[dependencies]
clap = { version = "3", default-features = false, features = ["std", "cargo"] }
chrono = "0.4"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util"]}
tokio-rustls = "0.23"
tokio-stream = { version = "0.1", features = ["net"] }
tokio-util = { version = "0.7", features = ["codec", "io-util"] }
hyper = { version = "0.14", features = ["http1", "server", "tcp", "stream"] }
percent-encoding = "2.1"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tokio-util = { version = "0.7", features = ["codec", "io-util"] }
futures = "0.3"
base64 = "0.13"
log = "0.4"
simple_logger = "2.1.0"
async_zip = "0.0.7"
async-walkdir = "0.2.0"
headers = "0.3.7"
mime_guess = "2.0.4"
get_if_addrs = "0.5.3"
rustls = { version = "0.20", default-features = false, features = ["tls12"] }
rustls-pemfile = "1"
[profile.release]
lto = true

View File

@@ -3,19 +3,21 @@
[![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)
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/171526189-09afc2de-793f-4216-b3d5-31ea408d3610.png)
## Features
- Serve static files
- Download folder as zip file
- Search files
- Upload files
- Upload files and folders (Drag & Drop)
- Delete files
- Basic authentication
- Unzip zip file when upload
- Upload zip file then unzip
- Partial responses (Parallel/Resume download)
- Support https/tls
- Easy to use with curl
## Install
@@ -30,7 +32,37 @@ cargo install duf
Download from [Github Releases](https://github.com/sigoden/duf/releases), unzip and add duf to your $PATH.
## Usage
## CLI
```
Duf is a fully functional file server.
USAGE:
duf [OPTIONS] [path]
ARGS:
<path> Path to a root directory for serving files [default: .]
OPTIONS:
-a, --auth <user:pass> Use HTTP authentication
--no-auth-access Not required auth when access static files
-A, --allow-all Allow all operations
--allow-delete Allow delete files/folders
--allow-symlink Allow symlink to files/folders outside root directory
--allow-upload Allow upload files/folders
-b, --bind <address> Specify bind address [default: 127.0.0.1]
--cors Enable CORS, sets `Access-Control-Allow-Origin: *`
-h, --help Print help information
-p, --port <port> Specify port to listen on [default: 5000]
--path-prefix <path> Specify an url path prefix
--render-index Render index.html when requesting a directory
--render-spa Render for single-page application
--tls-cert <path> Path to an SSL/TLS certificate to serve with HTTPS
--tls-key <path> Path to the SSL/TLS certificate's private key
-V, --version Print version information
```
## Examples
You can run this command to start serving your current working directory on 127.0.0.1:5000 by default.
@@ -44,25 +76,39 @@ duf
duf folder_name
```
Listen on all Interfaces and port 3000
```
duf -b 0.0.0.0 -p 3000
```
Allow all operations such as upload, delete
```
```sh
duf --allow-all
# or
duf -A
```
Only allow upload operations
Only allow upload operation
```
duf --allow-upload
```
Use http authentication
Serve a single page application (SPA)
```
duf --auth user:pass
duf --render-spa
```
### Api
Serve https
```
duf --tls-cert my.crt --tls-key my.key
```
## API
Download a file
```

View File

@@ -97,38 +97,46 @@ body {
padding: 0 1em;
}
.main th {
.uploaders-table th,
.paths-table th {
text-align: left;
font-weight: unset;
color: #5c5c5c;
white-space: nowrap;
}
.main td {
.uploaders-table td,
.paths-table td {
white-space: nowrap;
}
.main .cell-name {
width: 400px;
.uploaders-table .cell-name,
.paths-table .cell-name {
width: 500px;
}
.main .cell-mtime {
.uploaders-table .cell-status {
width: 80px;
padding-left: 0.6em;
}
.paths-table .cell-actions {
width: 60px;
display: flex;
padding-left: 0.6em;
}
.paths-table .cell-mtime {
width: 120px;
padding-left: 0.6em;
}
.main .cell-size {
.paths-table .cell-size {
text-align: right;
width: 70px;
padding-left: 0.6em;
}
.main .cell-actions {
width: 60px;
display: flex;
padding-left: 0.6em;
}
.path svg {
height: 100%;
@@ -158,9 +166,7 @@ body {
padding-left: 0.4em;
}
.uploaders {
display: flex;
flex-wrap: wrap;
.uploaders-table {
padding: 0.5em 0;
}

View File

@@ -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>
</a>
</div>
<div class="upload-control hidden" title="Upload file">
<div class="upload-control hidden" title="Upload files">
<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>
</label>
@@ -31,9 +31,15 @@
</form>
</div>
<div class="main">
<div class="uploaders">
</div>
<table>
<table class="uploaders-table hidden">
<thead>
<tr>
<th class="cell-name">Name</th>
<th class="cell-status">Status</th>
</tr>
</thead>
</table>
<table class="paths-table hidden">
<thead>
<tr>
<th class="cell-name">Name</th>

View File

@@ -1,33 +1,44 @@
let $tbody, $uploaders;
let uploaderIdx = 0;
/**
* @type Element
*/
let $pathsTable, $pathsTableBody, $uploadersTable;
/**
* @type string
*/
let baseDir;
class Uploader {
idx = 0;
idx;
file;
$elem;
constructor(idx, file) {
this.idx = idx;
name;
$uploadStatus;
static globalIdx = 0;
constructor(file, dirs) {
this.name = [...dirs, file.name].join("/");
this.idx = Uploader.globalIdx++;
this.file = file;
}
upload() {
const { file, idx } = this;
let url = getUrl(file.name);
const { file, idx, name } = this;
let url = getUrl(name);
if (file.name == baseDir + ".zip") {
url += "?unzip";
}
$uploaders.insertAdjacentHTML("beforeend", `
<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>
<a href="${url}" id="file${idx}">${file.name} (0%)</a>
</div>`);
this.$elem = document.getElementById(`file${idx}`);
$uploadersTable.insertAdjacentHTML("beforeend", `
<tr id="upload${idx}" class="uploader">
<td class="path cell-name">
<div>${getSvg("File")}</div>
<a href="${url}">${name}</a>
</td>
<td class="cell-status" id="uploadStatus${idx}"></td>
</tr>`);
$uploadersTable.classList.remove("hidden");
this.$uploadStatus = document.getElementById(`uploadStatus${idx}`);
const ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", e => this.progress(e), false);
ajax.addEventListener("readystatechange", () => {
console.log(ajax.readyState, ajax.status)
if(ajax.readyState === 4) {
if (ajax.status == 200) {
this.complete();
@@ -44,15 +55,15 @@ class Uploader {
progress(event) {
const percent = (event.loaded / event.total) * 100;
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`;
this.$uploadStatus.innerHTML = `${percent.toFixed(2)}%`;
}
complete() {
this.$elem.innerHTML = `${this.file.name}`;
this.$uploadStatus.innerHTML = ``;
}
fail() {
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`;
this.$uploadStatus.innerHTML = ``;
}
}
@@ -109,15 +120,15 @@ function addPath(file, index) {
${actionDelete}
</td>`
$tbody.insertAdjacentHTML("beforeend", `
$pathsTableBody.insertAdjacentHTML("beforeend", `
<tr id="addPath${index}">
<td class="path cell-name">
<div>${getSvg(file.path_type)}</div>
<a href="${url}" title="${file.name}">${file.name}</a>
</td>
<td class="cell-mtime">${formatMtime(file.mtime)}</td>
<td class="cell-size">${formatSize(file.size)}</td>
${actionCell}
<td class="path cell-name">
<div>${getSvg(file.path_type)}</div>
<a href="${url}" title="${file.name}">${file.name}</a>
</td>
<td class="cell-mtime">${formatMtime(file.mtime)}</td>
<td class="cell-size">${formatSize(file.size)}</td>
${actionCell}
</tr>`)
}
@@ -133,6 +144,10 @@ async function deletePath(index) {
});
if (res.status === 200) {
document.getElementById(`addPath${index}`).remove();
DATA.paths[index] = null;
if (!DATA.paths.find(v => !!v)) {
$pathsTable.classList.add("hidden");
}
} else {
throw new Error(await res.text())
}
@@ -141,6 +156,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) {
let url = location.href.split('?')[0];
if (!url.endsWith("/")) url += "/";
@@ -184,22 +237,29 @@ function formatSize(size) {
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
}
function ready() {
$tbody = document.querySelector(".main tbody");
$uploaders = document.querySelector(".uploaders");
$pathsTable = document.querySelector(".paths-table")
$pathsTableBody = document.querySelector(".paths-table tbody");
$uploadersTable = document.querySelector(".uploaders-table");
addBreadcrumb(DATA.breadcrumb);
DATA.paths.forEach((file, index) => addPath(file, index));
if (Array.isArray(DATA.paths)) {
const len = DATA.paths.length;
if (len > 0) {
$pathsTable.classList.remove("hidden");
}
for (let i = 0; i < len; i++) {
addPath(DATA.paths[i], i);
}
}
if (DATA.allow_upload) {
document.querySelector(".upload-control").classList.remove(["hidden"]);
dropzone();
document.querySelector(".upload-control").classList.remove("hidden");
document.getElementById("file").addEventListener("change", e => {
const files = e.target.files;
for (let file of files) {
uploaderIdx += 1;
const uploader = new Uploader(uploaderIdx, file);
uploader.upload();
new Uploader(file, []).upload();
}
});
}
}
}

View File

@@ -1,9 +1,9 @@
use clap::crate_description;
use clap::{Arg, ArgMatches};
use std::env;
use std::fs::canonicalize;
use rustls::{Certificate, PrivateKey};
use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::{env, fs, io};
use crate::BoxResult;
@@ -32,7 +32,13 @@ fn app() -> clap::Command<'static> {
Arg::new("path")
.default_value(".")
.allow_invalid_utf8(true)
.help("Path to a directory for serving files"),
.help("Path to a root directory for serving files"),
)
.arg(
Arg::new("path-prefix")
.long("path-prefix")
.value_name("path")
.help("Specify an url path prefix"),
)
.arg(
Arg::new("allow-all")
@@ -43,30 +49,59 @@ fn app() -> clap::Command<'static> {
.arg(
Arg::new("allow-upload")
.long("allow-upload")
.help("Allow upload operation"),
.help("Allow upload files/folders"),
)
.arg(
Arg::new("allow-delete")
.long("allo-delete")
.help("Allow delete operation"),
.long("allow-delete")
.help("Allow delete files/folders"),
)
.arg(
Arg::new("allow-symlink")
.long("allow-symlink")
.help("Allow symlink to files/folders outside root directory"),
)
.arg(
Arg::new("render-index")
.long("render-index")
.help("Render index.html when requesting a directory"),
)
.arg(
Arg::new("render-spa")
.long("render-spa")
.help("Render for single-page application"),
)
.arg(
Arg::new("auth")
.short('a')
.display_order(1)
.long("auth")
.help("Use HTTP authentication for all operations")
.help("Use HTTP authentication")
.value_name("user:pass"),
)
.arg(
Arg::new("no-auth-read")
.long("no-auth-read")
.help("Do not authenticate read operations like static serving"),
Arg::new("no-auth-access")
.display_order(1)
.long("no-auth-access")
.help("Not required auth when access static files"),
)
.arg(
Arg::new("cors")
.long("cors")
.help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
)
.arg(
Arg::new("tls-cert")
.long("tls-cert")
.value_name("path")
.help("Path to an SSL/TLS certificate to serve with HTTPS"),
)
.arg(
Arg::new("tls-key")
.long("tls-key")
.value_name("path")
.help("Path to the SSL/TLS certificate's private key"),
)
}
pub fn matches() -> ArgMatches {
@@ -78,11 +113,16 @@ pub struct Args {
pub address: String,
pub port: u16,
pub path: PathBuf,
pub path_prefix: Option<String>,
pub auth: Option<String>,
pub no_auth_read: bool,
pub no_auth_access: 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 tls: Option<(Vec<Certificate>, PrivateKey)>,
}
impl Args {
@@ -94,21 +134,38 @@ impl Args {
let address = matches.value_of("address").unwrap_or_default().to_owned();
let port = matches.value_of_t::<u16>("port")?;
let path = Args::parse_path(matches.value_of_os("path").unwrap_or_default())?;
let path_prefix = matches.value_of("path-prefix").map(|v| v.to_owned());
let cors = matches.is_present("cors");
let auth = matches.value_of("auth").map(|v| v.to_owned());
let no_auth_read = matches.is_present("no-auth-read");
let no_auth_access = matches.is_present("no-auth-access");
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");
let tls = match (matches.value_of("tls-cert"), matches.value_of("tls-key")) {
(Some(certs_file), Some(key_file)) => {
let certs = load_certs(certs_file)?;
let key = load_private_key(key_file)?;
Some((certs, key))
}
_ => None,
};
Ok(Args {
address,
port,
path,
path_prefix,
auth,
no_auth_read,
no_auth_access,
cors,
allow_delete,
allow_upload,
allow_symlink,
render_index,
render_spa,
tls,
})
}
@@ -122,7 +179,7 @@ impl Args {
env::current_dir()
.and_then(|mut p| {
p.push(path); // If path is absolute, it replaces the current path.
canonicalize(p)
std::fs::canonicalize(p)
})
.or_else(|err| {
bail!(
@@ -147,3 +204,35 @@ impl Args {
})
}
}
// Load public certificate from file.
pub fn load_certs(filename: &str) -> BoxResult<Vec<Certificate>> {
// Open certificate file.
let certfile =
fs::File::open(&filename).map_err(|e| format!("Failed to open {}: {}", &filename, e))?;
let mut reader = io::BufReader::new(certfile);
// Load and return certificate.
let certs = rustls_pemfile::certs(&mut reader).map_err(|_| "Failed to load certificate")?;
if certs.is_empty() {
return Err("Expected at least one certificate".into());
}
Ok(certs.into_iter().map(Certificate).collect())
}
// Load private key from file.
pub fn load_private_key(filename: &str) -> BoxResult<PrivateKey> {
// Open keyfile.
let keyfile =
fs::File::open(&filename).map_err(|e| format!("Failed to open {}: {}", &filename, e))?;
let mut reader = io::BufReader::new(keyfile);
// Load and return a single private key.
let keys = rustls_pemfile::rsa_private_keys(&mut reader)
.map_err(|e| format!("There was a problem with reading private key: {:?}", e))?;
if keys.len() != 1 {
return Err("Expected a single private key".into());
}
Ok(PrivateKey(keys[0].to_owned()))
}

View File

@@ -4,16 +4,11 @@ macro_rules! bail {
}
}
#[macro_use]
extern crate log;
mod args;
mod server;
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>;
use log::LevelFilter;
use crate::args::{matches, Args};
use crate::server::serve;
@@ -24,14 +19,6 @@ async fn main() {
async fn run() -> BoxResult<()> {
let args = Args::parse(matches())?;
if std::env::var("RUST_LOG").is_ok() {
simple_logger::init()?;
} else {
simple_logger::SimpleLogger::default()
.with_level(LevelFilter::Info)
.init()?;
}
serve(args).await
}

View File

@@ -4,34 +4,45 @@ use async_walkdir::WalkDir;
use async_zip::read::seek::ZipFileReader;
use async_zip::write::{EntryOptions, ZipFileWriter};
use async_zip::Compression;
use chrono::Local;
use futures::stream::StreamExt;
use futures::TryStreamExt;
use get_if_addrs::get_if_addrs;
use headers::{
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentRange, ContentType, ETag,
HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range,
AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
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::{Body, Method, StatusCode};
use percent_encoding::percent_decode;
use rustls::ServerConfig;
use serde::Serialize;
use std::convert::Infallible;
use std::fs::Metadata;
use std::net::IpAddr;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::SystemTime;
use tokio::fs::File;
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWrite};
use tokio::net::TcpListener;
use tokio::{fs, io};
use tokio_rustls::TlsAcceptor;
use tokio_util::codec::{BytesCodec, FramedRead};
use tokio_util::io::{ReaderStream, StreamReader};
type Request = hyper::Request<Body>;
type Response = hyper::Response<Body>;
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 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 INDEX_NAME: &str = "index.html";
const BUF_SIZE: usize = 1024 * 16;
macro_rules! status {
@@ -42,32 +53,61 @@ macro_rules! status {
}
pub async fn serve(args: Args) -> BoxResult<()> {
let address = args.address()?;
let inner = Arc::new(InnerService::new(args));
let make_svc = make_service_fn(move |_| {
let inner = inner.clone();
async {
Ok::<_, Infallible>(service_fn(move |req| {
let inner = inner.clone();
inner.call(req)
}))
}
});
let server = hyper::Server::try_bind(&address)?.serve(make_svc);
let address = server.local_addr();
eprintln!("Files served on http://{}", address);
server.await?;
let args = Arc::new(args);
let socket_addr = args.address()?;
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);
let listener = TcpListener::bind(&socket_addr).await?;
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 {
let server = hyper::Server::try_bind(&socket_addr)?.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, false);
server.await?;
}
Ok(())
}
struct InnerService {
args: Args,
args: Arc<Args>,
}
impl InnerService {
pub fn new(args: Args) -> Self {
pub fn new(args: Arc<Args>) -> Self {
Self { args }
}
@@ -76,15 +116,20 @@ impl InnerService {
let uri = req.uri().clone();
let cors = self.args.cors;
let timestamp = Local::now().format("%d/%b/%Y %H:%M:%S");
let mut res = match self.handle(req).await {
Ok(res) => {
info!(r#""{} {}" - {}"#, method, uri, res.status());
println!(r#"[{}] "{} {}" - {}"#, timestamp, 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);
let status = StatusCode::INTERNAL_SERVER_ERROR;
status!(res, status);
eprintln!(
r#"[{}] "{} {}" - {} {}"#,
timestamp, method, uri, status, err
);
res
}
};
@@ -102,59 +147,81 @@ impl InnerService {
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,
None => {
status!(res, StatusCode::FORBIDDEN);
return Ok(res);
}
};
let filepath = filepath.as_path();
let path = path.as_path();
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_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
let is_file = !is_miss && !is_dir;
let allow_upload = self.args.allow_upload;
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() {
Method::GET if is_dir && query == "zip" => {
self.handle_zip_dir(filepath, &mut res).await?
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);
}
}
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 => {
status!(res, StatusCode::NO_CONTENT);
}
Method::PUT if !allow_upload || (!allow_delete && is_file) => {
status!(res, StatusCode::FORBIDDEN);
Method::PUT => {
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 if !allow_delete => {
status!(res, StatusCode::FORBIDDEN);
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);
}
}
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)
}
@@ -191,26 +258,11 @@ impl InnerService {
io::copy(&mut body_reader, &mut file).await?;
let req_query = req.uri().query().unwrap_or_default();
if req_query == "unzip" {
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 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?;
}
let query = req.uri().query().unwrap_or_default();
if query == "unzip" {
if let Err(e) = self.unzip_file(path).await {
eprintln!("Failed to unzip {}, {}", path.display(), e);
status!(res, StatusCode::BAD_REQUEST);
}
fs::remove_file(&path).await?;
}
@@ -229,10 +281,16 @@ impl InnerService {
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
let mut paths: Vec<PathItem> = vec![];
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? {
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);
}
}
@@ -261,7 +319,7 @@ impl InnerService {
if fs::symlink_metadata(entry.path()).await.is_err() {
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);
}
}
@@ -271,14 +329,54 @@ impl InnerService {
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
let filename = path.file_name().unwrap().to_str().unwrap();
let path = path.to_owned();
tokio::spawn(async move {
if let Err(e) = dir_zip(&mut writer, &path).await {
error!("Fail to zip {}, {}", path.display(), e.to_string());
if let Err(e) = zip_dir(&mut writer, &path).await {
eprintln!("Failed to zip {}, {}", path.display(), e);
}
});
let stream = ReaderStream::new(reader);
*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(())
}
@@ -343,6 +441,9 @@ impl InnerService {
Body::wrap_stream(stream)
};
*res.body_mut() = body;
res.headers_mut().typed_insert(AcceptRanges::bytes());
res.headers_mut()
.typed_insert(ContentLength(meta.len() as u64));
Ok(())
}
@@ -388,7 +489,7 @@ impl InnerService {
let pass = {
match &self.args.auth {
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| {
let mut it = v.split(' ');
(it.next(), it.next())
@@ -400,7 +501,7 @@ impl InnerService {
.unwrap_or_default(),
_ => false,
},
None => self.args.no_auth_read && req.method() == Method::GET,
None => self.args.no_auth_access && req.method() == Method::GET,
},
}
};
@@ -412,6 +513,40 @@ impl InnerService {
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()
}
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(())
}
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) {
@@ -419,13 +554,57 @@ impl InnerService {
} else {
decoded_path.into_owned()
};
let full_path = self.args.path.join(&slashes_switched);
if full_path.starts_with(&self.args.path) {
Some(full_path)
} else {
None
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),
}
}
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,
}))
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
@@ -452,33 +631,6 @@ enum PathType {
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 {
time.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
@@ -504,27 +656,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 walkdir = WalkDir::new(dir);
while let Some(entry) = walkdir.next().await {
if let Ok(entry) = entry {
let entry_path = entry.path();
let meta = match fs::symlink_metadata(entry.path()).await {
Ok(meta) => meta,
Err(_) => continue,
};
if meta.is_file() {
let filepath = entry.path();
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?;
if !meta.is_file() {
continue;
}
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?;
@@ -569,3 +722,32 @@ fn to_content_range(range: &Range, complete_length: u64) -> Option<ContentRange>
_ => None,
})
}
fn print_listening(address: &str, port: u16, tls: bool) {
let addrs = retrive_listening_addrs(address);
let protocol = if tls { "https" } else { "http" };
if addrs.len() == 1 {
eprintln!("Listening on {}://{}:{}", protocol, addrs[0], port);
} else {
eprintln!("Listening on:");
for addr in addrs {
eprintln!(" {}://{}:{}", protocol, addr, port);
}
eprintln!();
}
}
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()]
}