mirror of
https://github.com/sigoden/dufs.git
synced 2026-04-09 17:13:02 +03:00
Compare commits
42 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
201afa6725 | ||
|
|
e2d7f996c7 | ||
|
|
97978719b3 | ||
|
|
9aa16d3a10 | ||
|
|
d208b5cb6b | ||
|
|
605c6c56c4 | ||
|
|
8718562889 | ||
|
|
830d3343f4 | ||
|
|
1fe391f9d9 | ||
|
|
b88381167b | ||
|
|
35ed4394df | ||
|
|
f43d0b646d | ||
|
|
a9294f602c | ||
|
|
584d33940a | ||
|
|
fc090b6930 | ||
|
|
19d7b36462 | ||
|
|
755554d3f2 | ||
|
|
6a097e0496 | ||
|
|
412d42e338 | ||
|
|
ec60752ba2 | ||
|
|
ed7f5e425a | ||
|
|
3032052923 | ||
|
|
be3ae2fe00 | ||
|
|
fb03f7ddb8 | ||
|
|
54df4633e1 | ||
|
|
6b293c0f2e | ||
|
|
62696b45fd | ||
|
|
d9547ad00b | ||
|
|
8fbc742c52 | ||
|
|
d8d5aae898 | ||
|
|
a263d18963 | ||
|
|
10aabcb2f2 | ||
|
|
06ce7b0175 | ||
|
|
4841ebb76d | ||
|
|
586b209c89 | ||
|
|
2eba975066 | ||
|
|
c8a25b54ab | ||
|
|
8900dde7e7 | ||
|
|
06d2b81824 | ||
|
|
3673a64ec7 | ||
|
|
d9a917176a | ||
|
|
cdb7b5fc87 |
179
CHANGELOG.md
Normal file
179
CHANGELOG.md
Normal file
@@ -0,0 +1,179 @@
|
|||||||
|
# Changelog
|
||||||
|
|
||||||
|
All notable changes to this project will be documented in this file.
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Move src/assets out of src
|
||||||
|
- Update description
|
||||||
|
- Upgrade version
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Upgrade version
|
||||||
|
|
||||||
|
## [0.6.0] - 2022-05-31
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- Delete confirm
|
||||||
|
- Distinct upload and delete operation
|
||||||
|
- Support range requests
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Upgrade version
|
||||||
|
|
||||||
|
### 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
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Reorganize web static files
|
||||||
|
- Rename src/static to src/assets
|
||||||
|
- Upgrade version
|
||||||
|
|
||||||
|
## [0.4.0] - 2022-05-29
|
||||||
|
|
||||||
|
### Features
|
||||||
|
|
||||||
|
- Replace --static option to --no-edit
|
||||||
|
- Add cors
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Upgrade version
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Update cargo metadata
|
||||||
|
|
||||||
|
## [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
|
||||||
|
|
||||||
|
### Miscellaneous Tasks
|
||||||
|
|
||||||
|
- Add readme and license
|
||||||
|
- Update cargo metadata
|
||||||
|
|
||||||
|
### Styling
|
||||||
|
|
||||||
|
- Cargo fmt
|
||||||
|
- Update index page
|
||||||
|
|
||||||
|
### Build
|
||||||
|
|
||||||
|
- Remove dev deps
|
||||||
|
|
||||||
|
### Ci
|
||||||
|
|
||||||
|
- Init ci
|
||||||
|
|
||||||
|
<!-- generated by git-cliff -->
|
||||||
404
Cargo.lock
generated
404
Cargo.lock
generated
@@ -101,17 +101,6 @@ version = "1.0.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "065374052e7df7ee4047b1160cca5e1467a12351a40b3da123c870ba0b8eda2a"
|
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]]
|
[[package]]
|
||||||
name = "autocfg"
|
name = "autocfg"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
@@ -130,6 +119,15 @@ version = "1.3.2"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "block-buffer"
|
||||||
|
version = "0.10.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0bf7fe51849ea569fd452f37822f606a5cabb684dc918707a0193fd4664ff324"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "blocking"
|
name = "blocking"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
@@ -144,6 +142,12 @@ dependencies = [
|
|||||||
"once_cell",
|
"once_cell",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bumpalo"
|
||||||
|
version = "3.10.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "37ccbd214614c6783386c1af30caf03192f17891059cecc394b4fb119e363de3"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "bytes"
|
name = "bytes"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
@@ -171,6 +175,12 @@ dependencies = [
|
|||||||
"pkg-config",
|
"pkg-config",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "c_linked_list"
|
||||||
|
version = "1.1.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4964518bd3b4a8190e832886cdc0da9794f12e8e6c1613a9e90ff331c4c8724b"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "cache-padded"
|
name = "cache-padded"
|
||||||
version = "1.2.0"
|
version = "1.2.0"
|
||||||
@@ -201,8 +211,8 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
"num-integer",
|
"num-integer",
|
||||||
"num-traits",
|
"num-traits",
|
||||||
"time 0.1.44",
|
"time",
|
||||||
"winapi",
|
"winapi 0.3.9",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -227,17 +237,6 @@ dependencies = [
|
|||||||
"os_str_bytes",
|
"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]]
|
[[package]]
|
||||||
name = "concurrent-queue"
|
name = "concurrent-queue"
|
||||||
version = "1.2.2"
|
version = "1.2.2"
|
||||||
@@ -247,6 +246,15 @@ dependencies = [
|
|||||||
"cache-padded",
|
"cache-padded",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cpufeatures"
|
||||||
|
version = "0.2.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "59a6001667ab124aebae2a495118e11d30984c3a653e99d86d58971708cf5e4b"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "crc32fast"
|
name = "crc32fast"
|
||||||
version = "1.3.2"
|
version = "1.3.2"
|
||||||
@@ -256,22 +264,48 @@ dependencies = [
|
|||||||
"cfg-if",
|
"cfg-if",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crypto-common"
|
||||||
|
version = "0.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "57952ca27b5e3606ff4dd79b0020231aaf9d6aa76dc05fd30137538c50bd3ce8"
|
||||||
|
dependencies = [
|
||||||
|
"generic-array",
|
||||||
|
"typenum",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "digest"
|
||||||
|
version = "0.10.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f2fb860ca6fafa5552fb6d0e816a69c8e49f0908bf524e30a90d97c85892d506"
|
||||||
|
dependencies = [
|
||||||
|
"block-buffer",
|
||||||
|
"crypto-common",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.2.0"
|
version = "0.9.0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"async-walkdir",
|
"async-walkdir",
|
||||||
"async_zip",
|
"async_zip",
|
||||||
"base64",
|
"base64",
|
||||||
|
"chrono",
|
||||||
"clap",
|
"clap",
|
||||||
"futures",
|
"futures",
|
||||||
|
"get_if_addrs",
|
||||||
|
"headers",
|
||||||
"hyper",
|
"hyper",
|
||||||
"log",
|
"mime_guess",
|
||||||
"percent-encoding",
|
"percent-encoding",
|
||||||
|
"rustls",
|
||||||
|
"rustls-pemfile",
|
||||||
"serde",
|
"serde",
|
||||||
"serde_json",
|
"serde_json",
|
||||||
"simple_logger",
|
|
||||||
"tokio",
|
"tokio",
|
||||||
|
"tokio-rustls",
|
||||||
|
"tokio-stream",
|
||||||
"tokio-util",
|
"tokio-util",
|
||||||
]
|
]
|
||||||
|
|
||||||
@@ -412,12 +446,75 @@ dependencies = [
|
|||||||
"slab",
|
"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"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "fd48d33ec7f05fbfa152300fdad764757cbded343c1aa1cff2fbaf4134851803"
|
||||||
|
dependencies = [
|
||||||
|
"typenum",
|
||||||
|
"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]]
|
[[package]]
|
||||||
name = "hashbrown"
|
name = "hashbrown"
|
||||||
version = "0.11.2"
|
version = "0.11.2"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "headers"
|
||||||
|
version = "0.3.7"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4cff78e5788be1e0ab65b04d306b2ed5092c815ec97ec70f4ebd5aee158aa55d"
|
||||||
|
dependencies = [
|
||||||
|
"base64",
|
||||||
|
"bitflags",
|
||||||
|
"bytes",
|
||||||
|
"headers-core",
|
||||||
|
"http",
|
||||||
|
"httpdate",
|
||||||
|
"mime",
|
||||||
|
"sha-1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "headers-core"
|
||||||
|
version = "0.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e7f66481bfee273957b1f20485a4ff3362987f85b2c236580d81b4eb7a326429"
|
||||||
|
dependencies = [
|
||||||
|
"http",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "hermit-abi"
|
name = "hermit-abi"
|
||||||
version = "0.1.19"
|
version = "0.1.19"
|
||||||
@@ -518,6 +615,15 @@ dependencies = [
|
|||||||
"libc",
|
"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]]
|
[[package]]
|
||||||
name = "lazy_static"
|
name = "lazy_static"
|
||||||
version = "1.4.0"
|
version = "1.4.0"
|
||||||
@@ -556,6 +662,22 @@ version = "2.5.0"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mime"
|
||||||
|
version = "0.3.16"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "mime_guess"
|
||||||
|
version = "2.0.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef"
|
||||||
|
dependencies = [
|
||||||
|
"mime",
|
||||||
|
"unicase",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "miniz_oxide"
|
name = "miniz_oxide"
|
||||||
version = "0.5.1"
|
version = "0.5.1"
|
||||||
@@ -606,15 +728,6 @@ dependencies = [
|
|||||||
"libc",
|
"libc",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
|
||||||
name = "num_threads"
|
|
||||||
version = "0.1.6"
|
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
|
||||||
checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
|
|
||||||
dependencies = [
|
|
||||||
"libc",
|
|
||||||
]
|
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "once_cell"
|
name = "once_cell"
|
||||||
version = "1.12.0"
|
version = "1.12.0"
|
||||||
@@ -675,12 +788,58 @@ dependencies = [
|
|||||||
"proc-macro2",
|
"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]]
|
[[package]]
|
||||||
name = "ryu"
|
name = "ryu"
|
||||||
version = "1.0.10"
|
version = "1.0.10"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695"
|
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]]
|
[[package]]
|
||||||
name = "serde"
|
name = "serde"
|
||||||
version = "1.0.137"
|
version = "1.0.137"
|
||||||
@@ -713,16 +872,14 @@ dependencies = [
|
|||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "simple_logger"
|
name = "sha-1"
|
||||||
version = "2.1.0"
|
version = "0.10.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "c75a9723083573ace81ad0cdfc50b858aa3c366c48636edb4109d73122a0c0ea"
|
checksum = "028f48d513f9678cda28f6e4064755b3fbb2af6acd672f2c209b62323f7aea0f"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"atty",
|
"cfg-if",
|
||||||
"colored",
|
"cpufeatures",
|
||||||
"log",
|
"digest",
|
||||||
"time 0.3.9",
|
|
||||||
"winapi",
|
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -738,9 +895,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
|
|||||||
checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0"
|
checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0"
|
||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"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]]
|
[[package]]
|
||||||
name = "syn"
|
name = "syn"
|
||||||
version = "1.0.95"
|
version = "1.0.95"
|
||||||
@@ -786,27 +949,9 @@ checksum = "6db9e6914ab8b1ae1c260a4ae7a49b6c5611b40328a735b21862567685e73255"
|
|||||||
dependencies = [
|
dependencies = [
|
||||||
"libc",
|
"libc",
|
||||||
"wasi 0.10.0+wasi-snapshot-preview1",
|
"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]]
|
[[package]]
|
||||||
name = "tokio"
|
name = "tokio"
|
||||||
version = "1.18.2"
|
version = "1.18.2"
|
||||||
@@ -822,7 +967,7 @@ dependencies = [
|
|||||||
"pin-project-lite",
|
"pin-project-lite",
|
||||||
"socket2",
|
"socket2",
|
||||||
"tokio-macros",
|
"tokio-macros",
|
||||||
"winapi",
|
"winapi 0.3.9",
|
||||||
]
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
@@ -836,6 +981,28 @@ dependencies = [
|
|||||||
"syn",
|
"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]]
|
[[package]]
|
||||||
name = "tokio-util"
|
name = "tokio-util"
|
||||||
version = "0.7.2"
|
version = "0.7.2"
|
||||||
@@ -894,12 +1061,39 @@ version = "0.2.3"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
|
checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "typenum"
|
||||||
|
version = "1.15.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "dcf81ac59edc17cc8697ff311e8f5ef2d99fcbd9817b34cec66f90b6c3dfd987"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicase"
|
||||||
|
version = "2.6.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6"
|
||||||
|
dependencies = [
|
||||||
|
"version_check",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "unicode-ident"
|
name = "unicode-ident"
|
||||||
version = "1.0.0"
|
version = "1.0.0"
|
||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee"
|
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"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "waker-fn"
|
name = "waker-fn"
|
||||||
version = "1.1.0"
|
version = "1.1.0"
|
||||||
@@ -928,6 +1122,86 @@ version = "0.11.0+wasi-snapshot-preview1"
|
|||||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
|
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]]
|
[[package]]
|
||||||
name = "winapi"
|
name = "winapi"
|
||||||
version = "0.3.9"
|
version = "0.3.9"
|
||||||
|
|||||||
16
Cargo.toml
16
Cargo.toml
@@ -1,9 +1,9 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "duf"
|
name = "duf"
|
||||||
version = "0.2.0"
|
version = "0.9.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"
|
||||||
@@ -13,18 +13,24 @@ keywords = ["static", "file", "server", "http", "cli"]
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
clap = { version = "3", default-features = false, features = ["std", "cargo"] }
|
clap = { version = "3", default-features = false, features = ["std", "cargo"] }
|
||||||
|
chrono = "0.4"
|
||||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util"]}
|
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"] }
|
hyper = { version = "0.14", features = ["http1", "server", "tcp", "stream"] }
|
||||||
percent-encoding = "2.1"
|
percent-encoding = "2.1"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
serde_json = "1"
|
||||||
tokio-util = { version = "0.7", features = ["codec", "io-util"] }
|
|
||||||
futures = "0.3"
|
futures = "0.3"
|
||||||
base64 = "0.13"
|
base64 = "0.13"
|
||||||
log = "0.4"
|
|
||||||
simple_logger = "2.1.0"
|
|
||||||
async_zip = "0.0.7"
|
async_zip = "0.0.7"
|
||||||
async-walkdir = "0.2.0"
|
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]
|
[profile.release]
|
||||||
lto = true
|
lto = true
|
||||||
|
|||||||
49
README.md
49
README.md
@@ -3,17 +3,20 @@
|
|||||||
[](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
|
[](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
|
||||||
[](https://crates.io/crates/duf)
|
[](https://crates.io/crates/duf)
|
||||||
|
|
||||||
Duf is a simple file server.
|
Duf is a fully functional file server.
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- Serve static files
|
- Serve static files
|
||||||
- Download folder as zip file
|
- Download folder as zip file
|
||||||
- Upload files
|
- Search files
|
||||||
|
- Upload files and folders (Drag & Drop)
|
||||||
- Delete files
|
- Delete files
|
||||||
- Basic authentication
|
- Basic authentication
|
||||||
|
- Upload zip file then unzip
|
||||||
|
- Serve through https
|
||||||
- Easy to use with curl
|
- Easy to use with curl
|
||||||
|
|
||||||
## Install
|
## Install
|
||||||
@@ -36,17 +39,45 @@ You can run this command to start serving your current working directory on 127.
|
|||||||
duf
|
duf
|
||||||
```
|
```
|
||||||
|
|
||||||
...or specify which folder you want to serve:
|
...or specify which folder you want to serve.
|
||||||
|
|
||||||
```
|
```
|
||||||
duf folder_name
|
duf folder_name
|
||||||
```
|
```
|
||||||
|
|
||||||
Finally, run this command to see a list of all available option
|
Listen on all Interfaces and port 3000
|
||||||
|
|
||||||
|
```
|
||||||
|
duf -b 0.0.0.0 -p 3000
|
||||||
|
```
|
||||||
|
|
||||||
|
Allow all operations such as upload, delete
|
||||||
|
|
||||||
### Curl
|
```sh
|
||||||
|
duf --allow-all
|
||||||
|
# or
|
||||||
|
duf -A
|
||||||
|
```
|
||||||
|
|
||||||
|
Only allow upload operation
|
||||||
|
|
||||||
|
```
|
||||||
|
duf --allow-upload
|
||||||
|
```
|
||||||
|
|
||||||
|
Serve a single page application (SPA)
|
||||||
|
|
||||||
|
```
|
||||||
|
duf --render-spa
|
||||||
|
```
|
||||||
|
|
||||||
|
Serve https
|
||||||
|
|
||||||
|
```
|
||||||
|
duf --tls-cert my.crt --tls-key my.key
|
||||||
|
```
|
||||||
|
|
||||||
|
### Api
|
||||||
|
|
||||||
Download a file
|
Download a file
|
||||||
```
|
```
|
||||||
@@ -67,6 +98,12 @@ Upload a file
|
|||||||
curl --upload-file some-file http://127.0.0.1:5000/some-file
|
curl --upload-file some-file http://127.0.0.1:5000/some-file
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Unzip zip file when unload
|
||||||
|
|
||||||
|
```
|
||||||
|
curl --upload-file some-folder.zip http://127.0.0.1:5000/some-folder.zip?unzip
|
||||||
|
```
|
||||||
|
|
||||||
Delete a file/folder
|
Delete a file/folder
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -4,16 +4,21 @@ html {
|
|||||||
color: #24292e;
|
color: #24292e;
|
||||||
}
|
}
|
||||||
|
|
||||||
.head {
|
body {
|
||||||
display: flex;
|
width: 700px;
|
||||||
align-items: baseline;
|
|
||||||
padding: 1em 1em 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.head input {
|
.hidden {
|
||||||
display: none;
|
display: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.head {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
padding: 1em 1em 0;
|
||||||
|
}
|
||||||
|
|
||||||
.breadcrumb {
|
.breadcrumb {
|
||||||
font-size: 1.25em;
|
font-size: 1.25em;
|
||||||
}
|
}
|
||||||
@@ -44,11 +49,50 @@ html {
|
|||||||
padding-left: 0.5em;
|
padding-left: 0.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.toolbox {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar {
|
||||||
|
display: flex;
|
||||||
|
flex-wrap: nowrap;
|
||||||
|
width: 246px;
|
||||||
|
height: 22px;
|
||||||
|
background-color: #fafafa;
|
||||||
|
transition: all .15s;
|
||||||
|
border: 1px #ddd solid;
|
||||||
|
border-radius: 15px;
|
||||||
|
margin: 0 0 2px 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar #search {
|
||||||
|
box-sizing: border-box;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
font-size: 16px;
|
||||||
|
line-height: 16px;
|
||||||
|
padding: 1px;
|
||||||
|
font-family: helvetica neue,luxi sans,Tahoma,hiragino sans gb,STHeiti,sans-serif;
|
||||||
|
background-color: transparent;
|
||||||
|
border: none;
|
||||||
|
outline: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.searchbar .icon {
|
||||||
|
color: #9a9a9a;
|
||||||
|
padding: 3px 3px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
.upload-control {
|
.upload-control {
|
||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
padding-left: 0.25em;
|
padding-left: 0.25em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.upload-control input {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
.main {
|
.main {
|
||||||
padding: 0 1em;
|
padding: 0 1em;
|
||||||
}
|
}
|
||||||
@@ -65,22 +109,22 @@ html {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-name {
|
.main .cell-name {
|
||||||
width: 300px;
|
width: 400px;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-mtime {
|
.main .cell-mtime {
|
||||||
width: 150px;
|
width: 120px;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-size {
|
.main .cell-size {
|
||||||
text-align: right;
|
text-align: right;
|
||||||
width: 100px;
|
width: 70px;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.main .cell-actions {
|
.main .cell-actions {
|
||||||
width: 100px;
|
width: 60px;
|
||||||
display: flex;
|
display: flex;
|
||||||
padding-left: 0.6em;
|
padding-left: 0.6em;
|
||||||
}
|
}
|
||||||
@@ -115,8 +159,6 @@ html {
|
|||||||
}
|
}
|
||||||
|
|
||||||
.uploaders {
|
.uploaders {
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
padding: 0.5em 0;
|
padding: 0.5em 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
53
assets/index.html
Normal file
53
assets/index.html
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<meta name="viewport" content="width=device-width" />
|
||||||
|
__SLOT__
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="head">
|
||||||
|
<div class="breadcrumb"></div>
|
||||||
|
<div class="toolbox">
|
||||||
|
<div>
|
||||||
|
<a href="?zip" title="Download folder as a .zip 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 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 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>
|
||||||
|
<input type="file" id="file" name="file" multiple>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<form class="searchbar">
|
||||||
|
<div class="icon">
|
||||||
|
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16"><path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/></svg>
|
||||||
|
</div>
|
||||||
|
<input id="search" name="q" type="text" maxlength="128" autocomplete="off" tabindex="1">
|
||||||
|
<input type="submit" hidden />
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
<div class="main">
|
||||||
|
<div class="uploaders">
|
||||||
|
</div>
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th class="cell-name">Name</th>
|
||||||
|
<th class="cell-mtime">Date modify</th>
|
||||||
|
<th class="cell-size">Size</th>
|
||||||
|
<th class="cell-actions">Actions</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
window.addEventListener("DOMContentLoaded", ready);
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
247
assets/index.js
Normal file
247
assets/index.js
Normal file
@@ -0,0 +1,247 @@
|
|||||||
|
let $tbody, $uploaders;
|
||||||
|
let baseDir;
|
||||||
|
|
||||||
|
class Uploader {
|
||||||
|
idx;
|
||||||
|
file;
|
||||||
|
name;
|
||||||
|
$elem;
|
||||||
|
static globalIdx = 0;
|
||||||
|
constructor(file, dirs) {
|
||||||
|
this.name = [...dirs, file.name].join("/");
|
||||||
|
this.idx = Uploader.globalIdx++;
|
||||||
|
this.file = file;
|
||||||
|
}
|
||||||
|
|
||||||
|
upload() {
|
||||||
|
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}">${name} (0%)</a>
|
||||||
|
</div>`);
|
||||||
|
this.$elem = document.getElementById(`file${idx}`);
|
||||||
|
|
||||||
|
const ajax = new XMLHttpRequest();
|
||||||
|
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
||||||
|
ajax.addEventListener("readystatechange", () => {
|
||||||
|
if(ajax.readyState === 4) {
|
||||||
|
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.send(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
progress(event) {
|
||||||
|
const percent = (event.loaded / event.total) * 100;
|
||||||
|
this.$elem.innerHTML = `${this.name} (${percent.toFixed(2)}%)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
complete() {
|
||||||
|
this.$elem.innerHTML = `${this.name}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
this.$elem.innerHTML = `<strike>${this.name}</strike>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addBreadcrumb(value) {
|
||||||
|
const $breadcrumb = document.querySelector(".breadcrumb");
|
||||||
|
const parts = value.split("/").filter(v => !!v);
|
||||||
|
const len = parts.length;
|
||||||
|
let path = "";
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
const name = parts[i];
|
||||||
|
if (i > 0) {
|
||||||
|
path += "/" + name;
|
||||||
|
}
|
||||||
|
if (i === len - 1) {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<b>${name}</b>`);
|
||||||
|
baseDir = name;
|
||||||
|
} else if (i === 0) {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="/"><b>${name}</b></a>`);
|
||||||
|
} else {
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="${encodeURI(path)}">${name}</a>`);
|
||||||
|
}
|
||||||
|
$breadcrumb.insertAdjacentHTML("beforeend", `<span class="separator">/</span>`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function addPath(file, index) {
|
||||||
|
const url = getUrl(file.name)
|
||||||
|
let actionDelete = "";
|
||||||
|
let actionDownload = "";
|
||||||
|
if (file.path_type.endsWith("Dir")) {
|
||||||
|
actionDownload = `
|
||||||
|
<div class="action-btn">
|
||||||
|
<a href="${url}?zip" title="Download folder as a .zip 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 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>`;
|
||||||
|
} else {
|
||||||
|
actionDownload = `
|
||||||
|
<div class="action-btn" >
|
||||||
|
<a href="${url}" title="Download file" download>
|
||||||
|
<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>`;
|
||||||
|
}
|
||||||
|
if (DATA.allow_delete) {
|
||||||
|
actionDelete = `
|
||||||
|
<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>
|
||||||
|
</div>`;
|
||||||
|
}
|
||||||
|
let actionCell = `
|
||||||
|
<td class="cell-actions">
|
||||||
|
${actionDownload}
|
||||||
|
${actionDelete}
|
||||||
|
</td>`
|
||||||
|
|
||||||
|
$tbody.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}
|
||||||
|
</tr>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deletePath(index) {
|
||||||
|
const file = DATA.paths[index];
|
||||||
|
if (!file) return;
|
||||||
|
|
||||||
|
if (!confirm(`Delete \`${file.name}\`?`)) return;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const res = await fetch(getUrl(file.name), {
|
||||||
|
method: "DELETE",
|
||||||
|
});
|
||||||
|
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) {
|
||||||
|
let url = location.href.split('?')[0];
|
||||||
|
if (!url.endsWith("/")) url += "/";
|
||||||
|
url += encodeURI(name);
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getSvg(path_type) {
|
||||||
|
switch (path_type) {
|
||||||
|
case "Dir":
|
||||||
|
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"></path></svg>`;
|
||||||
|
case "File":
|
||||||
|
return `<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>`;
|
||||||
|
case "SymlinkDir":
|
||||||
|
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM1 3h5v1H1V3zm6 9v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73C4.86 8.43 5.82 8 7.01 8V6l4 3-4 3H7z"></path></svg>`;
|
||||||
|
default:
|
||||||
|
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM6 4.5l4 3-4 3v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73.73-.84 1.69-1.27 2.88-1.27v-2H6z"></path></svg>`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMtime(mtime) {
|
||||||
|
if (!mtime) return ""
|
||||||
|
const date = new Date(mtime);
|
||||||
|
const year = date.getFullYear();
|
||||||
|
const month = padZero(date.getMonth() + 1, 2);
|
||||||
|
const day = padZero(date.getDate(), 2);
|
||||||
|
const hours = padZero(date.getHours(), 2);
|
||||||
|
const minutes = padZero(date.getMinutes(), 2);
|
||||||
|
return `${year}/${month}/${day} ${hours}:${minutes}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function padZero(value, size) {
|
||||||
|
return ("0".repeat(size) + value).slice(-1 * size)
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSize(size) {
|
||||||
|
if (!size) return ""
|
||||||
|
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
|
||||||
|
if (size == 0) return '0 Byte';
|
||||||
|
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
|
||||||
|
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
function ready() {
|
||||||
|
$tbody = document.querySelector(".main tbody");
|
||||||
|
$uploaders = document.querySelector(".uploaders");
|
||||||
|
|
||||||
|
addBreadcrumb(DATA.breadcrumb);
|
||||||
|
if (Array.isArray(DATA.paths)) {
|
||||||
|
const len = DATA.paths.length;
|
||||||
|
for (let i = 0; i < len; i++) {
|
||||||
|
addPath(DATA.paths[i], i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (DATA.allow_upload) {
|
||||||
|
dropzone();
|
||||||
|
document.querySelector(".upload-control").classList.remove(["hidden"]);
|
||||||
|
document.getElementById("file").addEventListener("change", e => {
|
||||||
|
const files = e.target.files;
|
||||||
|
for (let file of files) {
|
||||||
|
new Uploader(file, []).upload();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
196
src/args.rs
196
src/args.rs
@@ -1,56 +1,105 @@
|
|||||||
use clap::crate_description;
|
use clap::crate_description;
|
||||||
use clap::{Arg, ArgMatches};
|
use clap::{Arg, ArgMatches};
|
||||||
use std::env;
|
use rustls::{Certificate, PrivateKey};
|
||||||
use std::fs::canonicalize;
|
|
||||||
use std::net::SocketAddr;
|
use std::net::SocketAddr;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::{env, fs, io};
|
||||||
|
|
||||||
use crate::BoxResult;
|
use crate::BoxResult;
|
||||||
|
|
||||||
const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline.
|
const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline.
|
||||||
|
|
||||||
fn app() -> clap::Command<'static> {
|
fn app() -> clap::Command<'static> {
|
||||||
let arg_port = Arg::new("port")
|
clap::command!()
|
||||||
.short('p')
|
.about(ABOUT)
|
||||||
.long("port")
|
.arg(
|
||||||
.default_value("5000")
|
Arg::new("address")
|
||||||
.help("Specify port to listen on")
|
|
||||||
.value_name("port");
|
|
||||||
|
|
||||||
let arg_address = Arg::new("address")
|
|
||||||
.short('b')
|
.short('b')
|
||||||
.long("bind")
|
.long("bind")
|
||||||
.default_value("127.0.0.1")
|
.default_value("127.0.0.1")
|
||||||
.help("Specify bind address")
|
.help("Specify bind address")
|
||||||
.value_name("address");
|
.value_name("address"),
|
||||||
|
)
|
||||||
let arg_path = Arg::new("path")
|
.arg(
|
||||||
|
Arg::new("port")
|
||||||
|
.short('p')
|
||||||
|
.long("port")
|
||||||
|
.default_value("5000")
|
||||||
|
.help("Specify port to listen on")
|
||||||
|
.value_name("port"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
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"),
|
||||||
|
)
|
||||||
let arg_static = Arg::new("static")
|
.arg(
|
||||||
.long("static")
|
Arg::new("path-prefix")
|
||||||
.help("Only serve static files, not allowed to upload or delete file");
|
.long("path-prefix")
|
||||||
|
.value_name("path")
|
||||||
let arg_auth = Arg::new("auth")
|
.help("Specify an url path prefix"),
|
||||||
|
)
|
||||||
|
.arg(
|
||||||
|
Arg::new("allow-all")
|
||||||
|
.short('A')
|
||||||
|
.long("allow-all")
|
||||||
|
.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::new("auth")
|
||||||
.short('a')
|
.short('a')
|
||||||
.long("auth")
|
.long("auth")
|
||||||
.help("Authenticate with user and pass")
|
.help("Use HTTP authentication for all operations")
|
||||||
.value_name("user:pass");
|
.value_name("user:pass"),
|
||||||
|
)
|
||||||
let arg_no_log = Arg::new("no-log")
|
.arg(
|
||||||
.long("--no-log")
|
Arg::new("no-auth-read")
|
||||||
.help("Don't log any request/response information.");
|
.long("no-auth-read")
|
||||||
|
.help("Do not authenticate read operations like static serving"),
|
||||||
clap::command!()
|
)
|
||||||
.about(ABOUT)
|
.arg(
|
||||||
.arg(arg_address)
|
Arg::new("cors")
|
||||||
.arg(arg_port)
|
.long("cors")
|
||||||
.arg(arg_path)
|
.help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
|
||||||
.arg(arg_static)
|
)
|
||||||
.arg(arg_auth)
|
.arg(
|
||||||
.arg(arg_no_log)
|
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 {
|
pub fn matches() -> ArgMatches {
|
||||||
@@ -62,9 +111,16 @@ 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 path_prefix: Option<String>,
|
||||||
pub auth: Option<String>,
|
pub auth: Option<String>,
|
||||||
pub log: 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 tls: Option<(Vec<Certificate>, PrivateKey)>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Args {
|
impl Args {
|
||||||
@@ -75,19 +131,39 @@ 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 path_prefix = matches.value_of("path-prefix").map(|v| v.to_owned());
|
||||||
let readonly = matches.is_present("static");
|
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 log = !matches.is_present("no-log");
|
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");
|
||||||
|
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 {
|
Ok(Args {
|
||||||
address,
|
address,
|
||||||
port,
|
port,
|
||||||
path,
|
path,
|
||||||
readonly,
|
path_prefix,
|
||||||
auth,
|
auth,
|
||||||
log,
|
no_auth_read,
|
||||||
|
cors,
|
||||||
|
allow_delete,
|
||||||
|
allow_upload,
|
||||||
|
allow_symlink,
|
||||||
|
render_index,
|
||||||
|
render_spa,
|
||||||
|
tls,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,7 +177,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!(
|
||||||
@@ -126,3 +202,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()))
|
||||||
|
}
|
||||||
|
|||||||
231
src/index.html
231
src/index.html
@@ -1,231 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html>
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="utf-8" />
|
|
||||||
<meta name="viewport" content="width=device-width" />
|
|
||||||
<title>Duf</title>
|
|
||||||
__STYLE__
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<div class="head">
|
|
||||||
<div class="breadcrumb"></div>
|
|
||||||
<div>
|
|
||||||
<a href="?zip" title="Download folder as a .zip 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 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>
|
|
||||||
<div class="main">
|
|
||||||
<div class="uploaders">
|
|
||||||
</div>
|
|
||||||
<table>
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th class="cell-name">Name</th>
|
|
||||||
<th class="cell-mtime">Date modify</th>
|
|
||||||
<th class="cell-size">Size</th>
|
|
||||||
<th class="cell-actions">Actions</th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
<script>
|
|
||||||
|
|
||||||
const $head = document.querySelector(".head");
|
|
||||||
const $tbody = document.querySelector(".main tbody");
|
|
||||||
const $breadcrumb = document.querySelector(".breadcrumb");
|
|
||||||
const $uploaders = document.querySelector(".uploaders");
|
|
||||||
const $uploadControl = document.querySelector(".upload-control");
|
|
||||||
const { breadcrumb, paths, readonly } = __DATA__;
|
|
||||||
let uploaderIdx = 0;
|
|
||||||
|
|
||||||
class Uploader {
|
|
||||||
idx = 0;
|
|
||||||
file;
|
|
||||||
path;
|
|
||||||
$elem;
|
|
||||||
constructor(idx, file) {
|
|
||||||
this.idx = idx;
|
|
||||||
this.file = file;
|
|
||||||
this.path = location.pathname + "/" + file.name;
|
|
||||||
}
|
|
||||||
|
|
||||||
upload() {
|
|
||||||
const { file, idx, path } = this;
|
|
||||||
$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="${path}" id="file${idx}">${file.name} (0%)</a>
|
|
||||||
</div>`);
|
|
||||||
this.$elem = document.getElementById(`file${idx}`);
|
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
|
||||||
ajax.upload.addEventListener("progress", e => this.progress(e), false);
|
|
||||||
ajax.addEventListener("load", e => this.complete(e), false);
|
|
||||||
ajax.addEventListener("error", e => this.fail(e), false);
|
|
||||||
ajax.addEventListener("abort", e => this.fail(e), false);
|
|
||||||
ajax.open("PUT", path);
|
|
||||||
ajax.send(file);
|
|
||||||
}
|
|
||||||
|
|
||||||
progress(event) {
|
|
||||||
const percent = (event.loaded / event.total) * 100;
|
|
||||||
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`;
|
|
||||||
}
|
|
||||||
|
|
||||||
complete(event) {
|
|
||||||
this.$elem.innerHTML = `${this.file.name}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
fail(event) {
|
|
||||||
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addBreadcrumb(value) {
|
|
||||||
const parts = value.split("/").filter(v => !!v);
|
|
||||||
const len = parts.length;
|
|
||||||
let path = "";
|
|
||||||
for (let i = 0; i < len; i++) {
|
|
||||||
const name = parts[i];
|
|
||||||
if (i > 0) {
|
|
||||||
path += "/" + name;
|
|
||||||
}
|
|
||||||
if (i === len - 1) {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<b>${name}</b>`);
|
|
||||||
} else if (i === 0) {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="/"><b>${name}</b></a>`);
|
|
||||||
} else {
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<a href="${encodeURI(path)}">${name}</a>`);
|
|
||||||
}
|
|
||||||
$breadcrumb.insertAdjacentHTML("beforeend", `<span class="separator">/</span>`);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function addPath(file, index) {
|
|
||||||
const url = encodeURI(file.path);
|
|
||||||
let actionDelete = "";
|
|
||||||
let actionDownload = "";
|
|
||||||
if (file.path_type.endsWith("Dir")) {
|
|
||||||
actionDownload = `
|
|
||||||
<div class="action-btn">
|
|
||||||
<a href="${url}?zip" title="Download folder as a .zip 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 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>`;
|
|
||||||
} else {
|
|
||||||
actionDownload = `
|
|
||||||
<div class="action-btn" >
|
|
||||||
<a href="${url}" title="Download file" download>
|
|
||||||
<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>`;
|
|
||||||
}
|
|
||||||
if (!readonly) {
|
|
||||||
actionDelete = `
|
|
||||||
<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>
|
|
||||||
</div>`;
|
|
||||||
}
|
|
||||||
const actionCell = `
|
|
||||||
<td class="cell-actions">
|
|
||||||
${actionDownload}
|
|
||||||
${actionDelete}
|
|
||||||
</td>`
|
|
||||||
|
|
||||||
$tbody.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}
|
|
||||||
</tr>`)
|
|
||||||
}
|
|
||||||
|
|
||||||
async function deletePath(index) {
|
|
||||||
const file = paths[index];
|
|
||||||
if (!file) return;
|
|
||||||
|
|
||||||
const ajax = new XMLHttpRequest();
|
|
||||||
ajax.open("DELETE", encodeURI(file.path));
|
|
||||||
ajax.addEventListener("readystatechange", function() {
|
|
||||||
if(ajax.readyState === 4 && ajax.status === 200) {
|
|
||||||
document.getElementById(`addPath${index}`).remove();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
ajax.send();
|
|
||||||
}
|
|
||||||
|
|
||||||
function addUploadControl() {
|
|
||||||
$head.insertAdjacentHTML("beforeend", `
|
|
||||||
<div class="upload-control" title="Upload 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>
|
|
||||||
</label>
|
|
||||||
<input type="file" id="file" name="file" multiple>
|
|
||||||
</div>
|
|
||||||
`);
|
|
||||||
}
|
|
||||||
|
|
||||||
function getSvg(path_type) {
|
|
||||||
switch (path_type) {
|
|
||||||
case "Dir":
|
|
||||||
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM6 4H1V3h5v1z"></path></svg>`;
|
|
||||||
case "File":
|
|
||||||
return `<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>`;
|
|
||||||
case "SymlinkDir":
|
|
||||||
return `<svg height="16" viewBox="0 0 14 16" width="14"><path fill-rule="evenodd" d="M13 4H7V3c0-.66-.31-1-1-1H1c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V5c0-.55-.45-1-1-1zM1 3h5v1H1V3zm6 9v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73C4.86 8.43 5.82 8 7.01 8V6l4 3-4 3H7z"></path></svg>`;
|
|
||||||
default:
|
|
||||||
return `<svg height="16" viewBox="0 0 12 16" width="12"><path fill-rule="evenodd" d="M8.5 1H1c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h10c.55 0 1-.45 1-1V4.5L8.5 1zM11 14H1V2h7l3 3v9zM6 4.5l4 3-4 3v-2c-.98-.02-1.84.22-2.55.7-.71.48-1.19 1.25-1.45 2.3.02-1.64.39-2.88 1.13-3.73.73-.84 1.69-1.27 2.88-1.27v-2H6z"></path></svg>`;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatMtime(mtime) {
|
|
||||||
if (!mtime) return ""
|
|
||||||
const date = new Date(mtime);
|
|
||||||
const year = date.getFullYear();
|
|
||||||
const month = padZero(date.getMonth() + 1, 2);
|
|
||||||
const day = padZero(date.getDate(), 2);
|
|
||||||
const hours = padZero(date.getHours(), 2);
|
|
||||||
const minutes = padZero(date.getMinutes(), 2);
|
|
||||||
return `${year}/${month}/${day} ${hours}:${minutes}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function padZero(value, size) {
|
|
||||||
return ("0".repeat(size) + value).slice(-1 * size)
|
|
||||||
}
|
|
||||||
|
|
||||||
function formatSize(size) {
|
|
||||||
if (!size) return ""
|
|
||||||
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
|
|
||||||
if (size == 0) return '0 Byte';
|
|
||||||
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
|
|
||||||
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
document.addEventListener('DOMContentLoaded', () => {
|
|
||||||
addBreadcrumb(breadcrumb);
|
|
||||||
paths.forEach((file, index) => addPath(file, index));
|
|
||||||
if (!readonly) {
|
|
||||||
addUploadControl();
|
|
||||||
document.getElementById("file").addEventListener("change", e => {
|
|
||||||
const files = e.target.files;
|
|
||||||
for (const file of files) {
|
|
||||||
uploaderIdx += 1;
|
|
||||||
const uploader = new Uploader(uploaderIdx, file);
|
|
||||||
uploader.upload();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
});
|
|
||||||
</script>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
14
src/main.rs
14
src/main.rs
@@ -4,16 +4,11 @@ macro_rules! bail {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[macro_use]
|
|
||||||
extern crate log;
|
|
||||||
|
|
||||||
mod args;
|
mod args;
|
||||||
mod server;
|
mod server;
|
||||||
|
|
||||||
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>;
|
pub type BoxResult<T> = Result<T, Box<dyn std::error::Error>>;
|
||||||
|
|
||||||
use log::LevelFilter;
|
|
||||||
|
|
||||||
use crate::args::{matches, Args};
|
use crate::args::{matches, Args};
|
||||||
use crate::server::serve;
|
use crate::server::serve;
|
||||||
|
|
||||||
@@ -24,15 +19,6 @@ async fn main() {
|
|||||||
|
|
||||||
async fn run() -> BoxResult<()> {
|
async fn run() -> BoxResult<()> {
|
||||||
let args = Args::parse(matches())?;
|
let args = Args::parse(matches())?;
|
||||||
|
|
||||||
let level = if args.log {
|
|
||||||
LevelFilter::Info
|
|
||||||
} else {
|
|
||||||
LevelFilter::Error
|
|
||||||
};
|
|
||||||
simple_logger::SimpleLogger::default()
|
|
||||||
.with_level(level)
|
|
||||||
.init()?;
|
|
||||||
serve(args).await
|
serve(args).await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
763
src/server.rs
763
src/server.rs
@@ -1,136 +1,252 @@
|
|||||||
use crate::{Args, BoxResult};
|
use crate::{Args, BoxResult};
|
||||||
|
|
||||||
use async_walkdir::WalkDir;
|
use async_walkdir::WalkDir;
|
||||||
|
use async_zip::read::seek::ZipFileReader;
|
||||||
use async_zip::write::{EntryOptions, ZipFileWriter};
|
use async_zip::write::{EntryOptions, ZipFileWriter};
|
||||||
use async_zip::Compression;
|
use async_zip::Compression;
|
||||||
|
use chrono::Local;
|
||||||
use futures::stream::StreamExt;
|
use futures::stream::StreamExt;
|
||||||
use futures::TryStreamExt;
|
use futures::TryStreamExt;
|
||||||
use hyper::header::HeaderValue;
|
use get_if_addrs::get_if_addrs;
|
||||||
|
use headers::{
|
||||||
|
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::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 rustls::ServerConfig;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use std::convert::Infallible;
|
use std::convert::Infallible;
|
||||||
|
use std::fs::Metadata;
|
||||||
|
use std::net::IpAddr;
|
||||||
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::net::TcpListener;
|
||||||
use tokio::{fs, io};
|
use tokio::{fs, io};
|
||||||
|
use tokio_rustls::TlsAcceptor;
|
||||||
use tokio_util::codec::{BytesCodec, FramedRead};
|
use tokio_util::codec::{BytesCodec, FramedRead};
|
||||||
use tokio_util::io::ReaderStream;
|
use tokio_util::io::{ReaderStream, StreamReader};
|
||||||
use tokio_util::io::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!("index.html");
|
|
||||||
const INDEX_CSS: &str = include_str!("index.css");
|
|
||||||
|
|
||||||
pub async fn serve(args: Args) -> BoxResult<()> {
|
pub async fn serve(args: Args) -> BoxResult<()> {
|
||||||
let address = args.address()?;
|
let args = Arc::new(args);
|
||||||
let inner = Arc::new(InnerService::new(args));
|
let socket_addr = args.address()?;
|
||||||
let make_svc = make_service_fn(move |_| {
|
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.unwrap();
|
||||||
|
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();
|
let inner = inner.clone();
|
||||||
async {
|
async move {
|
||||||
Ok::<_, Infallible>(service_fn(move |req| {
|
Ok::<_, Infallible>(service_fn(move |req| {
|
||||||
let inner = inner.clone();
|
let inner = inner.clone();
|
||||||
inner.call(req)
|
inner.call(req)
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
});
|
}));
|
||||||
|
print_listening(args.address.as_str(), args.port, true);
|
||||||
let server = hyper::Server::try_bind(&address)?.serve(make_svc);
|
|
||||||
let address = server.local_addr();
|
|
||||||
eprintln!("Files served on http://{}", address);
|
|
||||||
server.await?;
|
server.await?;
|
||||||
|
} else {
|
||||||
|
let server = hyper::Server::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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
struct InnerService {
|
struct InnerService {
|
||||||
args: Args,
|
args: Arc<Args>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InnerService {
|
impl InnerService {
|
||||||
pub fn new(args: Args) -> Self {
|
pub fn new(args: Arc<Args>) -> Self {
|
||||||
Self { args }
|
Self { args }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn call(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> {
|
pub async fn call(self: Arc<Self>, req: Request) -> Result<Response, hyper::Error> {
|
||||||
let method = req.method().clone();
|
let method = req.method().clone();
|
||||||
let uri = req.uri().clone();
|
let uri = req.uri().clone();
|
||||||
let res = self
|
let cors = self.args.cors;
|
||||||
.handle(req)
|
|
||||||
.await
|
let timestamp = Local::now().format("%d/%b/%Y %H:%M:%S");
|
||||||
.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR));
|
let mut res = match self.handle(req).await {
|
||||||
info!(r#""{} {}" - {}"#, method, uri, res.status());
|
Ok(res) => {
|
||||||
|
println!(r#"[{}] "{} {}" - {}"#, timestamp, method, uri, res.status());
|
||||||
|
res
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
let mut res = Response::default();
|
||||||
|
let status = StatusCode::INTERNAL_SERVER_ERROR;
|
||||||
|
status!(res, status);
|
||||||
|
eprintln!(
|
||||||
|
r#"[{}] "{} {}" - {} {}"#,
|
||||||
|
timestamp, method, uri, status, err
|
||||||
|
);
|
||||||
|
res
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
if cors {
|
||||||
|
add_cors(&mut res);
|
||||||
|
}
|
||||||
Ok(res)
|
Ok(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
if req.method() == Method::GET {
|
let req_path = req.uri().path();
|
||||||
self.handle_static(req).await
|
|
||||||
} else if req.method() == Method::PUT {
|
|
||||||
if self.args.readonly {
|
|
||||||
return Ok(status_code!(StatusCode::FORBIDDEN));
|
|
||||||
}
|
|
||||||
self.handle_upload(req).await
|
|
||||||
} else if req.method() == Method::DELETE {
|
|
||||||
self.handle_delete(req).await
|
|
||||||
} else {
|
|
||||||
return Ok(status_code!(StatusCode::NOT_FOUND));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn handle_static(&self, req: Request) -> BoxResult<Response> {
|
let path = match self.extract_path(req_path) {
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
Some(v) => v,
|
||||||
Some(path) => path,
|
None => {
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
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();
|
||||||
if req.uri().query().map(|v| v == "zip").unwrap_or_default() {
|
|
||||||
self.handle_send_dir_zip(path.as_path()).await
|
let meta = fs::metadata(path).await.ok();
|
||||||
} else {
|
|
||||||
self.handle_send_dir(path.as_path()).await
|
let is_miss = meta.is_none();
|
||||||
}
|
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default();
|
||||||
} else {
|
let is_file = !is_miss && !is_dir;
|
||||||
self.handle_send_file(path.as_path()).await
|
|
||||||
}
|
let allow_upload = self.args.allow_upload;
|
||||||
}
|
let allow_delete = self.args.allow_delete;
|
||||||
Err(_) => Ok(status_code!(StatusCode::NOT_FOUND)),
|
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);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_upload(&self, mut req: Request) -> BoxResult<Response> {
|
match *req.method() {
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
Method::GET => {
|
||||||
Some(path) => path,
|
let headers = req.headers();
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
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::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)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
Ok(meta) => meta.is_dir(),
|
||||||
|
Err(_) => {
|
||||||
|
fs::create_dir_all(parent).await?;
|
||||||
|
true
|
||||||
|
}
|
||||||
|
},
|
||||||
|
None => false,
|
||||||
};
|
};
|
||||||
|
if !ensure_parent {
|
||||||
if !fs::metadata(&path.parent().unwrap()).await?.is_dir() {
|
status!(res, StatusCode::FORBIDDEN);
|
||||||
return Ok(status_code!(StatusCode::FORBIDDEN));
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut file = fs::File::create(path).await?;
|
let mut file = fs::File::create(&path).await?;
|
||||||
|
|
||||||
let body_with_io_error = req
|
let body_with_io_error = req
|
||||||
.body_mut()
|
.body_mut()
|
||||||
@@ -142,158 +258,360 @@ impl InnerService {
|
|||||||
|
|
||||||
io::copy(&mut body_reader, &mut file).await?;
|
io::copy(&mut body_reader, &mut file).await?;
|
||||||
|
|
||||||
return Ok(status_code!(StatusCode::OK));
|
let query = req.uri().query().unwrap_or_default();
|
||||||
}
|
if query == "unzip" {
|
||||||
|
let root = path.parent().unwrap();
|
||||||
async fn handle_delete(&self, req: Request) -> BoxResult<Response> {
|
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
|
||||||
let path = match self.get_file_path(req.uri().path())? {
|
for i in 0..zip.entries().len() {
|
||||||
Some(path) => path,
|
let entry = &zip.entries()[i];
|
||||||
None => return Ok(status_code!(StatusCode::FORBIDDEN)),
|
let entry_name = entry.name();
|
||||||
};
|
let entry_path = root.join(entry_name);
|
||||||
|
if entry_name.ends_with('/') {
|
||||||
let meta = fs::metadata(&path).await?;
|
fs::create_dir_all(entry_path).await?;
|
||||||
if meta.is_file() {
|
|
||||||
fs::remove_file(path).await?;
|
|
||||||
} else {
|
} else {
|
||||||
fs::remove_dir_all(path).await?;
|
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
|
||||||
|
continue;
|
||||||
}
|
}
|
||||||
Ok(status_code!(StatusCode::OK))
|
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?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
fs::remove_file(&path).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir(&self, path: &Path) -> BoxResult<Response> {
|
Ok(())
|
||||||
let mut rd = fs::read_dir(path).await?;
|
}
|
||||||
|
|
||||||
|
async fn handle_delete(&self, path: &Path, is_dir: bool) -> BoxResult<()> {
|
||||||
|
match is_dir {
|
||||||
|
true => fs::remove_dir_all(path).await?,
|
||||||
|
false => fs::remove_file(path).await?,
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
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) = self.get_path_item(entry_path).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, res)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn handle_query_dir(
|
||||||
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
query: &str,
|
||||||
|
res: &mut Response,
|
||||||
|
) -> BoxResult<()> {
|
||||||
|
let mut paths: Vec<PathItem> = vec![];
|
||||||
|
let mut walkdir = WalkDir::new(path);
|
||||||
|
while let Some(entry) = walkdir.next().await {
|
||||||
|
if let Ok(entry) = entry {
|
||||||
|
if !entry
|
||||||
|
.file_name()
|
||||||
|
.to_string_lossy()
|
||||||
|
.to_lowercase()
|
||||||
|
.contains(&query.to_lowercase())
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if fs::symlink_metadata(entry.path()).await.is_err() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Ok(Some(item)) = self.to_pathitem(entry.path(), path.to_path_buf()).await {
|
||||||
|
paths.push(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.send_index(path, paths, res)
|
||||||
|
}
|
||||||
|
|
||||||
|
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) = 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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
};
|
||||||
|
res.headers_mut().typed_insert(last_modified);
|
||||||
|
res.headers_mut().typed_insert(etag.clone());
|
||||||
|
if cached {
|
||||||
|
status!(res, StatusCode::NOT_MODIFIED);
|
||||||
|
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() {
|
||||||
|
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());
|
||||||
|
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(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn send_index(
|
||||||
|
&self,
|
||||||
|
path: &Path,
|
||||||
|
mut paths: Vec<PathItem>,
|
||||||
|
res: &mut Response,
|
||||||
|
) -> BoxResult<()> {
|
||||||
paths.sort_unstable();
|
paths.sort_unstable();
|
||||||
let breadcrumb = self.get_breadcrumb(path);
|
let rel_path = match self.args.path.parent() {
|
||||||
let data = SendDirData {
|
Some(p) => path.strip_prefix(p).unwrap(),
|
||||||
breadcrumb,
|
None => path,
|
||||||
|
};
|
||||||
|
let data = IndexData {
|
||||||
|
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(
|
||||||
|
"__SLOT__",
|
||||||
|
&format!(
|
||||||
|
r#"
|
||||||
|
<title>Files in {}/ - Duf</title>
|
||||||
|
<style>{}</style>
|
||||||
|
<script>var DATA = {}; {}</script>
|
||||||
|
"#,
|
||||||
|
rel_path.display(),
|
||||||
|
INDEX_CSS,
|
||||||
|
data,
|
||||||
|
INDEX_JS
|
||||||
|
),
|
||||||
|
);
|
||||||
|
*res.body_mut() = output.into();
|
||||||
|
|
||||||
let mut output =
|
Ok(())
|
||||||
INDEX_HTML.replace("__STYLE__", &format!("<style>\n{}</style>", INDEX_CSS));
|
|
||||||
output = output.replace("__DATA__", &data);
|
|
||||||
|
|
||||||
Ok(hyper::Response::builder().body(output.into()).unwrap())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_dir_zip(&self, path: &Path) -> BoxResult<Response> {
|
fn auth_guard(&self, req: &Request, res: &mut Response) -> bool {
|
||||||
let (mut writer, reader) = tokio::io::duplex(65536);
|
let pass = {
|
||||||
dir_zip(&mut writer, path).await?;
|
match &self.args.auth {
|
||||||
let stream = ReaderStream::new(reader);
|
None => true,
|
||||||
let body = Body::wrap_stream(stream);
|
Some(auth) => match req.headers().get(AUTHORIZATION) {
|
||||||
Ok(Response::new(body))
|
Some(value) => match value.to_str().ok().map(|v| {
|
||||||
|
let mut it = v.split(' ');
|
||||||
|
(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,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn handle_send_file(&self, path: &Path) -> BoxResult<Response> {
|
|
||||||
let file = fs::File::open(path).await?;
|
|
||||||
let stream = FramedRead::new(file, BytesCodec::new());
|
|
||||||
let body = Body::wrap_stream(stream);
|
|
||||||
Ok(Response::new(body))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn auth_guard(&self, req: &Request) -> BoxResult<bool> {
|
|
||||||
if let Some(auth) = &self.args.auth {
|
|
||||||
if let Some(value) = req.headers().get("Authorization") {
|
|
||||||
let value = value.to_str()?;
|
|
||||||
let value = if value.contains("Basic ") {
|
|
||||||
&value[6..]
|
|
||||||
} else {
|
|
||||||
return Ok(false);
|
|
||||||
};
|
};
|
||||||
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"));
|
||||||
return Ok(false);
|
|
||||||
}
|
}
|
||||||
}
|
pass
|
||||||
Ok(true)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn get_path_item<P: AsRef<Path>>(&self, path: P) -> BoxResult<PathItem> {
|
async fn is_root_contained(&self, path: &Path) -> bool {
|
||||||
|
fs::canonicalize(path)
|
||||||
|
.await
|
||||||
|
.ok()
|
||||||
|
.map(|v| v.starts_with(&self.args.path))
|
||||||
|
.unwrap_or_default()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn extract_path(&self, path: &str) -> Option<PathBuf> {
|
||||||
|
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
|
||||||
|
let slashes_switched = if cfg!(windows) {
|
||||||
|
decoded_path.replace('/', "\\")
|
||||||
|
} else {
|
||||||
|
decoded_path.into_owned()
|
||||||
|
};
|
||||||
|
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 path = path.as_ref();
|
||||||
let base_path = &self.args.path;
|
|
||||||
let rel_path = path.strip_prefix(base_path).unwrap();
|
let rel_path = path.strip_prefix(base_path).unwrap();
|
||||||
let meta = fs::metadata(&path).await?;
|
let (meta, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
|
||||||
let s_meta = fs::symlink_metadata(&path).await?;
|
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 is_dir = meta.is_dir();
|
||||||
let is_symlink = s_meta.file_type().is_symlink();
|
|
||||||
let path_type = match (is_symlink, is_dir) {
|
let path_type = match (is_symlink, is_dir) {
|
||||||
(true, true) => PathType::SymlinkDir,
|
(true, true) => PathType::SymlinkDir,
|
||||||
(false, true) => PathType::Dir,
|
(false, true) => PathType::Dir,
|
||||||
(true, false) => PathType::SymlinkFile,
|
(true, false) => PathType::SymlinkFile,
|
||||||
(false, false) => PathType::File,
|
(false, false) => PathType::File,
|
||||||
};
|
};
|
||||||
let mtime = meta
|
let mtime = to_timestamp(&meta.modified()?);
|
||||||
.modified()?
|
|
||||||
.duration_since(SystemTime::UNIX_EPOCH)
|
|
||||||
.ok()
|
|
||||||
.map(|v| v.as_millis() as u64);
|
|
||||||
let size = match path_type {
|
let size = match path_type {
|
||||||
PathType::Dir | PathType::SymlinkDir => None,
|
PathType::Dir | PathType::SymlinkDir => None,
|
||||||
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
PathType::File | PathType::SymlinkFile => Some(meta.len()),
|
||||||
};
|
};
|
||||||
let name = rel_path
|
let name = normalize_path(rel_path);
|
||||||
.file_name()
|
Ok(Some(PathItem {
|
||||||
.and_then(|v| v.to_str())
|
|
||||||
.unwrap_or_default()
|
|
||||||
.to_owned();
|
|
||||||
Ok(PathItem {
|
|
||||||
path_type,
|
path_type,
|
||||||
name,
|
name,
|
||||||
path: format!("/{}", normalize_path(rel_path)),
|
|
||||||
mtime,
|
mtime,
|
||||||
size,
|
size,
|
||||||
})
|
}))
|
||||||
}
|
|
||||||
|
|
||||||
fn get_breadcrumb(&self, path: &Path) -> String {
|
|
||||||
let path = match self.args.path.parent() {
|
|
||||||
Some(p) => path.strip_prefix(p).unwrap(),
|
|
||||||
None => path,
|
|
||||||
};
|
|
||||||
normalize_path(path)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn get_file_path(&self, path: &str) -> BoxResult<Option<PathBuf>> {
|
|
||||||
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?;
|
|
||||||
let slashes_switched = if cfg!(windows) {
|
|
||||||
decoded_path.replace('/', "\\")
|
|
||||||
} else {
|
|
||||||
decoded_path.into_owned()
|
|
||||||
};
|
|
||||||
let path = self.args.path.join(&slashes_switched);
|
|
||||||
if path.starts_with(&self.args.path) {
|
|
||||||
Ok(Some(path))
|
|
||||||
} else {
|
|
||||||
Ok(None)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
|
||||||
struct SendDirData {
|
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)]
|
||||||
struct PathItem {
|
struct PathItem {
|
||||||
path_type: PathType,
|
path_type: PathType,
|
||||||
name: String,
|
name: String,
|
||||||
path: String,
|
mtime: u64,
|
||||||
mtime: Option<u64>,
|
|
||||||
size: Option<u64>,
|
size: Option<u64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -305,6 +623,12 @@ enum PathType {
|
|||||||
SymlinkFile,
|
SymlinkFile,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn to_timestamp(time: &SystemTime) -> u64 {
|
||||||
|
time.duration_since(SystemTime::UNIX_EPOCH)
|
||||||
|
.unwrap()
|
||||||
|
.as_millis() as u64
|
||||||
|
}
|
||||||
|
|
||||||
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
||||||
let path = path.as_ref().to_str().unwrap_or_default();
|
let path = path.as_ref().to_str().unwrap_or_default();
|
||||||
if cfg!(windows) {
|
if cfg!(windows) {
|
||||||
@@ -314,26 +638,107 @@ fn normalize_path<P: AsRef<Path>>(path: P) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
|
fn add_cors(res: &mut Response) {
|
||||||
|
res.headers_mut()
|
||||||
|
.typed_insert(AccessControlAllowOrigin::ANY);
|
||||||
|
res.headers_mut().typed_insert(
|
||||||
|
vec![RANGE, CONTENT_TYPE, ACCEPT, ORIGIN, WWW_AUTHENTICATE]
|
||||||
|
.into_iter()
|
||||||
|
.collect::<AccessControlAllowHeaders>(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 meta = fs::symlink_metadata(entry.path()).await?;
|
let entry_path = entry.path();
|
||||||
if meta.is_file() {
|
let meta = match fs::symlink_metadata(entry.path()).await {
|
||||||
let filepath = entry.path();
|
Ok(meta) => meta,
|
||||||
let filename = match filepath.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
|
Err(_) => continue,
|
||||||
|
};
|
||||||
|
if !meta.is_file() {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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()]
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user