Compare commits

..

21 Commits

Author SHA1 Message Date
sigoden
f103e15e15 chore(release): version v0.11.0 2022-06-03 11:19:57 +08:00
sigoden
9dda55b7c8 feat: listen 0.0.0.0 by default 2022-06-03 11:19:16 +08:00
sigoden
c3dd0f0ec5 feat: support gracefully shutdown server 2022-06-03 11:00:12 +08:00
sigoden
4167e5c07e chore(ci): publish to docker
* ci: publish to docker

* update release.yaml

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

13
.dockerignore Normal file
View File

@@ -0,0 +1,13 @@
# Directories
/.git/
/.github/
/target/
/examples/
/docs/
/benches/
/tmp/
# Files
.gitignore
*.md
LICENSE*

View File

@@ -6,8 +6,10 @@ on:
- v[0-9]+.[0-9]+.[0-9]+* - v[0-9]+.[0-9]+.[0-9]+*
jobs: jobs:
all: release:
name: All name: Publish to Github Reelases
outputs:
rc: ${{ steps.check-tag.outputs.rc }}
strategy: strategy:
matrix: matrix:
@@ -124,3 +126,40 @@ jobs:
prerelease: ${{ steps.check-tag.outputs.rc == 'true' }} prerelease: ${{ steps.check-tag.outputs.rc == 'true' }}
env: env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
docker:
name: Publish to Docker Hub
if: startsWith(github.ref, 'refs/tags/')
runs-on: ubuntu-latest
needs: release
steps:
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v1
- name: Login to DockerHub
uses: docker/login-action@v1
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push
id: docker_build
uses: docker/build-push-action@v2
with:
push: ${{ needs.release.outputs.rc == 'false' }}
tags: sigoden/duf:latest, sigoden/duf:${{ github.ref_name }}
publish-crate:
name: Publish to crates.io
if: ${{ needs.release.outputs.rc == 'false' }}
runs-on: ubuntu-latest
needs: release
steps:
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
profile: minimal
toolchain: stable
- name: Publish
env:
CARGO_REGISTRY_TOKEN: ${{ secrets.CRATES_IO_API_TOKEN }}
run: cargo publish

180
CHANGELOG.md Normal file
View File

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

291
Cargo.lock generated
View File

@@ -101,17 +101,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" 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"
@@ -153,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"
@@ -180,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"
@@ -210,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]]
@@ -236,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"
@@ -296,22 +286,26 @@ dependencies = [
[[package]] [[package]]
name = "duf" name = "duf"
version = "0.8.0" version = "0.11.0"
dependencies = [ dependencies = [
"async-walkdir", "async-walkdir",
"async_zip", "async_zip",
"base64", "base64",
"chrono",
"clap", "clap",
"futures", "futures",
"get_if_addrs",
"headers", "headers",
"hyper", "hyper",
"log",
"mime_guess", "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",
] ]
@@ -452,6 +446,12 @@ dependencies = [
"slab", "slab",
] ]
[[package]]
name = "gcc"
version = "0.3.55"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f5f3913fa0bfe7ee1fd8248b6b9f42a5af4b9d65ec2dd2c3c26132b950ecfc2"
[[package]] [[package]]
name = "generic-array" name = "generic-array"
version = "0.14.5" version = "0.14.5"
@@ -462,6 +462,28 @@ dependencies = [
"version_check", "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"
@@ -593,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"
@@ -697,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"
@@ -766,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"
@@ -815,16 +883,12 @@ dependencies = [
] ]
[[package]] [[package]]
name = "simple_logger" name = "signal-hook-registry"
version = "2.1.0" version = "1.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c75a9723083573ace81ad0cdfc50b858aa3c366c48636edb4109d73122a0c0ea" checksum = "e51e73328dc4ac0c7ccbda3a494dfa03df1de2f46018127f60c693f2648455b0"
dependencies = [ dependencies = [
"atty", "libc",
"colored",
"log",
"time 0.3.9",
"winapi",
] ]
[[package]] [[package]]
@@ -840,9 +904,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"
@@ -888,27 +958,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"
@@ -922,9 +974,10 @@ dependencies = [
"num_cpus", "num_cpus",
"once_cell", "once_cell",
"pin-project-lite", "pin-project-lite",
"signal-hook-registry",
"socket2", "socket2",
"tokio-macros", "tokio-macros",
"winapi", "winapi 0.3.9",
] ]
[[package]] [[package]]
@@ -938,6 +991,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"
@@ -1017,6 +1092,12 @@ 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]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.4" version = "0.9.4"
@@ -1051,6 +1132,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"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "duf" name = "duf"
version = "0.8.0" version = "0.11.0"
edition = "2021" edition = "2021"
authors = ["sigoden <sigoden@gmail.com>"] authors = ["sigoden <sigoden@gmail.com>"]
description = "Duf is a fully functional file server." description = "Duf is a fully functional file server."
@@ -13,20 +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"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util"]} chrono = "0.4"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util", "signal"]}
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" headers = "0.3.7"
mime_guess = "2.0.4" 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

10
Dockerfile Normal file
View File

@@ -0,0 +1,10 @@
FROM rust:1.61 as builder
RUN rustup target add x86_64-unknown-linux-musl
RUN apt-get update && apt-get install --no-install-recommends -y musl-tools
WORKDIR /app
COPY . .
RUN cargo build --target x86_64-unknown-linux-musl --release
FROM alpine
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/duf /bin/
ENTRYPOINT ["/bin/duf"]

View File

@@ -5,17 +5,19 @@
Duf is a fully functional file server. Duf is a fully functional file server.
![demo](https://user-images.githubusercontent.com/4012553/170853369-dfcdc4c7-4864-4401-bf49-6e41ffe05df3.png) ![demo](https://user-images.githubusercontent.com/4012553/171526189-09afc2de-793f-4216-b3d5-31ea408d3610.png)
## Features ## Features
- Serve static files - Serve static files
- Download folder as zip file - Download folder as zip file
- Search files - Search files
- Upload files and folders - Upload files and folders (Drag & Drop)
- Delete files - Delete files
- Basic authentication - Basic authentication
- Upload zip file then unzip - Upload zip file then unzip
- Partial responses (Parallel/Resume download)
- Support https/tls
- Easy to use with curl - Easy to use with curl
## Install ## Install
@@ -26,11 +28,47 @@ Duf is a fully functional file server.
cargo install duf cargo install duf
``` ```
### With docker
```
docker run -v /tmp:/tmp -p 5000:5000 --rm -it docker.io/sigoden/duf /tmp
```
### Binaries on macOS, Linux, Windows ### Binaries on macOS, Linux, Windows
Download from [Github Releases](https://github.com/sigoden/duf/releases), unzip and add duf to your $PATH. Download from [Github Releases](https://github.com/sigoden/duf/releases), unzip and add duf to your $PATH.
## Usage ## CLI
```
Duf is a fully functional file server.
USAGE:
duf [OPTIONS] [path]
ARGS:
<path> Path to a root directory for serving files [default: .]
OPTIONS:
-a, --auth <user:pass> Use HTTP authentication
--no-auth-access Not required auth when access static files
-A, --allow-all Allow all operations
--allow-delete Allow delete files/folders
--allow-symlink Allow symlink to files/folders outside root directory
--allow-upload Allow upload files/folders
-b, --bind <address> Specify bind address [default: 0.0.0.0]
--cors Enable CORS, sets `Access-Control-Allow-Origin: *`
-h, --help Print help information
-p, --port <port> Specify port to listen on [default: 5000]
--path-prefix <path> Specify an url path prefix
--render-index Render index.html when requesting a directory
--render-spa Render for single-page application
--tls-cert <path> Path to an SSL/TLS certificate to serve with HTTPS
--tls-key <path> Path to the SSL/TLS certificate's private key
-V, --version Print version information
```
## Examples
You can run this command to start serving your current working directory on 127.0.0.1:5000 by default. You can run this command to start serving your current working directory on 127.0.0.1:5000 by default.
@@ -46,23 +84,29 @@ duf folder_name
Allow all operations such as upload, delete Allow all operations such as upload, delete
``` ```sh
duf --allow-all duf --allow-all
``` ```
Only allow upload operations Only allow upload operation
``` ```
duf --allow-upload duf --allow-upload
``` ```
Use http authentication Serve a single page application (SPA)
``` ```
duf --auth user:pass duf --render-spa
``` ```
### Api Use https
```
duf --tls-cert my.crt --tls-key my.key
```
## API
Download a file Download a file
``` ```

View File

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

View File

@@ -31,9 +31,15 @@
</form> </form>
</div> </div>
<div class="main"> <div class="main">
<div class="uploaders"> <table class="uploaders-table hidden">
</div> <thead>
<table> <tr>
<th class="cell-name">Name</th>
<th class="cell-status">Status</th>
</tr>
</thead>
</table>
<table class="paths-table hidden">
<thead> <thead>
<tr> <tr>
<th class="cell-name">Name</th> <th class="cell-name">Name</th>

View File

@@ -1,11 +1,17 @@
let $tbody, $uploaders; /**
* @type Element
*/
let $pathsTable, $pathsTableBody, $uploadersTable;
/**
* @type string
*/
let baseDir; let baseDir;
class Uploader { class Uploader {
idx; idx;
file; file;
name; name;
$elem; $uploadStatus;
static globalIdx = 0; static globalIdx = 0;
constructor(file, dirs) { constructor(file, dirs) {
this.name = [...dirs, file.name].join("/"); this.name = [...dirs, file.name].join("/");
@@ -19,12 +25,16 @@ class Uploader {
if (file.name == baseDir + ".zip") { if (file.name == baseDir + ".zip") {
url += "?unzip"; url += "?unzip";
} }
$uploaders.insertAdjacentHTML("beforeend", ` $uploadersTable.insertAdjacentHTML("beforeend", `
<div class="uploader path"> <tr id="upload${idx}" class="uploader">
<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> <td class="path cell-name">
<a href="${url}" id="file${idx}">${name} (0%)</a> <div>${getSvg("File")}</div>
</div>`); <a href="${url}">${name}</a>
this.$elem = document.getElementById(`file${idx}`); </td>
<td class="cell-status" id="uploadStatus${idx}"></td>
</tr>`);
$uploadersTable.classList.remove("hidden");
this.$uploadStatus = document.getElementById(`uploadStatus${idx}`);
const ajax = new XMLHttpRequest(); const ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", e => this.progress(e), false); ajax.upload.addEventListener("progress", e => this.progress(e), false);
@@ -45,15 +55,15 @@ class Uploader {
progress(event) { progress(event) {
const percent = (event.loaded / event.total) * 100; const percent = (event.loaded / event.total) * 100;
this.$elem.innerHTML = `${this.name} (${percent.toFixed(2)}%)`; this.$uploadStatus.innerHTML = `${percent.toFixed(2)}%`;
} }
complete() { complete() {
this.$elem.innerHTML = `${this.name}`; this.$uploadStatus.innerHTML = ``;
} }
fail() { fail() {
this.$elem.innerHTML = `<strike>${this.name}</strike>`; this.$uploadStatus.innerHTML = ``;
} }
} }
@@ -110,15 +120,15 @@ function addPath(file, index) {
${actionDelete} ${actionDelete}
</td>` </td>`
$tbody.insertAdjacentHTML("beforeend", ` $pathsTableBody.insertAdjacentHTML("beforeend", `
<tr id="addPath${index}"> <tr id="addPath${index}">
<td class="path cell-name"> <td class="path cell-name">
<div>${getSvg(file.path_type)}</div> <div>${getSvg(file.path_type)}</div>
<a href="${url}" title="${file.name}">${file.name}</a> <a href="${url}" title="${file.name}">${file.name}</a>
</td> </td>
<td class="cell-mtime">${formatMtime(file.mtime)}</td> <td class="cell-mtime">${formatMtime(file.mtime)}</td>
<td class="cell-size">${formatSize(file.size)}</td> <td class="cell-size">${formatSize(file.size)}</td>
${actionCell} ${actionCell}
</tr>`) </tr>`)
} }
@@ -134,6 +144,10 @@ async function deletePath(index) {
}); });
if (res.status === 200) { if (res.status === 200) {
document.getElementById(`addPath${index}`).remove(); document.getElementById(`addPath${index}`).remove();
DATA.paths[index] = null;
if (!DATA.paths.find(v => !!v)) {
$pathsTable.classList.add("hidden");
}
} else { } else {
throw new Error(await res.text()) throw new Error(await res.text())
} }
@@ -224,19 +238,23 @@ function formatSize(size) {
} }
function ready() { function ready() {
$tbody = document.querySelector(".main tbody"); $pathsTable = document.querySelector(".paths-table")
$uploaders = document.querySelector(".uploaders"); $pathsTableBody = document.querySelector(".paths-table tbody");
$uploadersTable = document.querySelector(".uploaders-table");
addBreadcrumb(DATA.breadcrumb); addBreadcrumb(DATA.breadcrumb);
if (Array.isArray(DATA.paths)) { if (Array.isArray(DATA.paths)) {
const len = DATA.paths.length; const len = DATA.paths.length;
if (len > 0) {
$pathsTable.classList.remove("hidden");
}
for (let i = 0; i < len; i++) { for (let i = 0; i < len; i++) {
addPath(DATA.paths[i], i); addPath(DATA.paths[i], i);
} }
} }
if (DATA.allow_upload) { if (DATA.allow_upload) {
dropzone(); dropzone();
document.querySelector(".upload-control").classList.remove(["hidden"]); document.querySelector(".upload-control").classList.remove("hidden");
document.getElementById("file").addEventListener("change", e => { document.getElementById("file").addEventListener("change", e => {
const files = e.target.files; const files = e.target.files;
for (let file of files) { for (let file of files) {

View File

@@ -1,8 +1,9 @@
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::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;
@@ -15,7 +16,7 @@ fn app() -> clap::Command<'static> {
Arg::new("address") Arg::new("address")
.short('b') .short('b')
.long("bind") .long("bind")
.default_value("127.0.0.1") .default_value("0.0.0.0")
.help("Specify bind address") .help("Specify bind address")
.value_name("address"), .value_name("address"),
) )
@@ -33,6 +34,12 @@ fn app() -> clap::Command<'static> {
.allow_invalid_utf8(true) .allow_invalid_utf8(true)
.help("Path to a root directory for serving files"), .help("Path to a root directory for serving files"),
) )
.arg(
Arg::new("path-prefix")
.long("path-prefix")
.value_name("path")
.help("Specify an url path prefix"),
)
.arg( .arg(
Arg::new("allow-all") Arg::new("allow-all")
.short('A') .short('A')
@@ -42,45 +49,59 @@ fn app() -> clap::Command<'static> {
.arg( .arg(
Arg::new("allow-upload") Arg::new("allow-upload")
.long("allow-upload") .long("allow-upload")
.help("Allow upload operation"), .help("Allow upload files/folders"),
) )
.arg( .arg(
Arg::new("allow-delete") Arg::new("allow-delete")
.long("allow-delete") .long("allow-delete")
.help("Allow delete operation"), .help("Allow delete files/folders"),
) )
.arg( .arg(
Arg::new("allow-symlink") Arg::new("allow-symlink")
.long("allow-symlink") .long("allow-symlink")
.help("Allow symlink to directories/files outside root directory"), .help("Allow symlink to files/folders outside root directory"),
) )
.arg( .arg(
Arg::new("render-index") Arg::new("render-index")
.long("render-index") .long("render-index")
.help("Render existing index.html when requesting a directory"), .help("Render index.html when requesting a directory"),
) )
.arg( .arg(
Arg::new("render-spa") Arg::new("render-spa")
.long("render-spa") .long("render-spa")
.help("Render spa, rewrite all not-found requests to `index.html"), .help("Render for single-page application"),
) )
.arg( .arg(
Arg::new("auth") Arg::new("auth")
.short('a') .short('a')
.display_order(1)
.long("auth") .long("auth")
.help("Use HTTP authentication for all operations") .help("Use HTTP authentication")
.value_name("user:pass"), .value_name("user:pass"),
) )
.arg( .arg(
Arg::new("no-auth-read") Arg::new("no-auth-access")
.long("no-auth-read") .display_order(1)
.help("Do not authenticate read operations like static serving"), .long("no-auth-access")
.help("Not required auth when access static files"),
) )
.arg( .arg(
Arg::new("cors") Arg::new("cors")
.long("cors") .long("cors")
.help("Enable CORS, sets `Access-Control-Allow-Origin: *`"), .help("Enable CORS, sets `Access-Control-Allow-Origin: *`"),
) )
.arg(
Arg::new("tls-cert")
.long("tls-cert")
.value_name("path")
.help("Path to an SSL/TLS certificate to serve with HTTPS"),
)
.arg(
Arg::new("tls-key")
.long("tls-key")
.value_name("path")
.help("Path to the SSL/TLS certificate's private key"),
)
} }
pub fn matches() -> ArgMatches { pub fn matches() -> ArgMatches {
@@ -92,14 +113,16 @@ pub struct Args {
pub address: String, pub address: String,
pub port: u16, pub port: u16,
pub path: PathBuf, pub path: PathBuf,
pub path_prefix: Option<String>,
pub auth: Option<String>, pub auth: Option<String>,
pub no_auth_read: bool, pub no_auth_access: bool,
pub allow_upload: bool, pub allow_upload: bool,
pub allow_delete: bool, pub allow_delete: bool,
pub allow_symlink: bool, pub allow_symlink: bool,
pub render_index: bool, pub render_index: bool,
pub render_spa: bool, pub render_spa: bool,
pub cors: bool, pub cors: bool,
pub tls: Option<(Vec<Certificate>, PrivateKey)>,
} }
impl Args { impl Args {
@@ -111,27 +134,38 @@ impl 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 = Args::parse_path(matches.value_of_os("path").unwrap_or_default())?; let path = Args::parse_path(matches.value_of_os("path").unwrap_or_default())?;
let path_prefix = matches.value_of("path-prefix").map(|v| v.to_owned());
let cors = matches.is_present("cors"); let cors = matches.is_present("cors");
let auth = matches.value_of("auth").map(|v| v.to_owned()); let auth = matches.value_of("auth").map(|v| v.to_owned());
let no_auth_read = matches.is_present("no-auth-read"); let no_auth_access = matches.is_present("no-auth-access");
let allow_upload = matches.is_present("allow-all") || matches.is_present("allow-upload"); let allow_upload = matches.is_present("allow-all") || matches.is_present("allow-upload");
let allow_delete = matches.is_present("allow-all") || matches.is_present("allow-delete"); let allow_delete = matches.is_present("allow-all") || matches.is_present("allow-delete");
let allow_symlink = matches.is_present("allow-all") || matches.is_present("allow-symlink"); let allow_symlink = matches.is_present("allow-all") || matches.is_present("allow-symlink");
let render_index = matches.is_present("render-index"); let render_index = matches.is_present("render-index");
let render_spa = matches.is_present("render-spa"); 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,
path_prefix,
auth, auth,
no_auth_read, no_auth_access,
cors, cors,
allow_delete, allow_delete,
allow_upload, allow_upload,
allow_symlink, allow_symlink,
render_index, render_index,
render_spa, render_spa,
tls,
}) })
} }
@@ -139,7 +173,7 @@ impl Args {
fn parse_path<P: AsRef<Path>>(path: P) -> BoxResult<PathBuf> { fn parse_path<P: AsRef<Path>>(path: P) -> BoxResult<PathBuf> {
let path = path.as_ref(); let path = path.as_ref();
if !path.exists() { if !path.exists() {
bail!("error: path \"{}\" doesn't exist", path.display()); return Err(format!("Path `{}` doesn't exist", path.display()).into());
} }
env::current_dir() env::current_dir()
@@ -147,26 +181,45 @@ impl Args {
p.push(path); // If path is absolute, it replaces the current path. p.push(path); // If path is absolute, it replaces the current path.
std::fs::canonicalize(p) std::fs::canonicalize(p)
}) })
.or_else(|err| { .map_err(|err| format!("Failed to access path `{}`: {}", path.display(), err,).into())
bail!(
"error: failed to access path \"{}\": {}",
path.display(),
err,
)
})
} }
/// Construct socket address from arguments. /// Construct socket address from arguments.
pub fn address(&self) -> BoxResult<SocketAddr> { pub fn address(&self) -> BoxResult<SocketAddr> {
format!("{}:{}", self.address, self.port) format!("{}:{}", self.address, self.port)
.parse() .parse()
.or_else(|err| { .map_err(|_| format!("Invalid bind address `{}:{}`", self.address, self.port).into())
bail!(
"error: invalid address {}:{} : {}",
self.address,
self.port,
err,
)
})
} }
} }
// Load public certificate from file.
pub fn load_certs(filename: &str) -> BoxResult<Vec<Certificate>> {
// Open certificate file.
let certfile =
fs::File::open(&filename).map_err(|e| format!("Failed to open {}: {}", &filename, e))?;
let mut reader = io::BufReader::new(certfile);
// Load and return certificate.
let certs = rustls_pemfile::certs(&mut reader).map_err(|_| "Failed to load certificate")?;
if certs.is_empty() {
return Err("Expected at least one certificate".into());
}
Ok(certs.into_iter().map(Certificate).collect())
}
// Load private key from file.
pub fn load_private_key(filename: &str) -> BoxResult<PrivateKey> {
// Open keyfile.
let keyfile =
fs::File::open(&filename).map_err(|e| format!("Failed to open {}: {}", &filename, e))?;
let mut reader = io::BufReader::new(keyfile);
// Load and return a single private key.
let keys = rustls_pemfile::rsa_private_keys(&mut reader)
.map_err(|e| format!("There was a problem with reading private key: {:?}", e))?;
if keys.len() != 1 {
return Err("Expected a single private key".into());
}
Ok(PrivateKey(keys[0].to_owned()))
}

View File

@@ -1,19 +1,8 @@
macro_rules! bail {
($($tt:tt)*) => {
return Err(From::from(format!($($tt)*)))
}
}
#[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,18 +13,10 @@ async fn main() {
async fn run() -> BoxResult<()> { async fn run() -> BoxResult<()> {
let args = Args::parse(matches())?; let args = Args::parse(matches())?;
if std::env::var("RUST_LOG").is_ok() {
simple_logger::init()?;
} else {
simple_logger::SimpleLogger::default()
.with_level(LevelFilter::Info)
.init()?;
}
serve(args).await serve(args).await
} }
fn handle_err<T>(err: Box<dyn std::error::Error>) -> T { fn handle_err<T>(err: Box<dyn std::error::Error>) -> T {
eprintln!("Server error: {}", err); eprintln!("error: {}", err);
std::process::exit(1); std::process::exit(1);
} }

View File

@@ -4,8 +4,10 @@ use async_walkdir::WalkDir;
use async_zip::read::seek::ZipFileReader; 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 get_if_addrs::get_if_addrs;
use headers::{ use headers::{
AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange, AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
ContentType, ETag, HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, ContentType, ETag, HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange,
@@ -18,15 +20,19 @@ use hyper::header::{
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::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::{AsyncReadExt, AsyncSeekExt, 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, StreamReader}; use tokio_util::io::{ReaderStream, StreamReader};
@@ -47,32 +53,74 @@ macro_rules! status {
} }
pub async fn serve(args: Args) -> BoxResult<()> { pub async fn serve(args: Args) -> BoxResult<()> {
let address = args.address()?; match args.tls.as_ref() {
let inner = Arc::new(InnerService::new(args)); Some(_) => serve_https(args).await,
let make_svc = make_service_fn(move |_| { None => serve_http(args).await,
}
}
pub async fn serve_https(args: Args) -> BoxResult<()> {
let args = Arc::new(args);
let socket_addr = args.address()?;
let (certs, key) = args.tls.clone().unwrap();
let inner = Arc::new(InnerService::new(args.clone()));
let config = ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(certs, key)?;
let tls_acceptor = TlsAcceptor::from(Arc::new(config));
let arc_acceptor = Arc::new(tls_acceptor);
let listener = TcpListener::bind(&socket_addr).await?;
let incoming = tokio_stream::wrappers::TcpListenerStream::new(listener);
let incoming = hyper::server::accept::from_stream(incoming.filter_map(|socket| async {
match socket {
Ok(stream) => match arc_acceptor.clone().accept(stream).await {
Ok(val) => Some(Ok::<_, Infallible>(val)),
Err(_) => None,
},
Err(_) => None,
}
}));
let server = hyper::Server::builder(incoming).serve(make_service_fn(move |_| {
let inner = inner.clone(); 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 graceful = server.with_graceful_shutdown(shutdown_signal());
let address = server.local_addr(); graceful.await?;
eprintln!("Files served on http://{}", address); Ok(())
server.await?; }
pub async fn serve_http(args: Args) -> BoxResult<()> {
let args = Arc::new(args);
let socket_addr = args.address()?;
let inner = Arc::new(InnerService::new(args.clone()));
let server = hyper::Server::try_bind(&socket_addr)?.serve(make_service_fn(move |_| {
let inner = inner.clone();
async move {
Ok::<_, Infallible>(service_fn(move |req| {
let inner = inner.clone();
inner.call(req)
}))
}
}));
print_listening(args.address.as_str(), args.port, false);
let graceful = server.with_graceful_shutdown(shutdown_signal());
graceful.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 }
} }
@@ -81,15 +129,20 @@ impl InnerService {
let uri = req.uri().clone(); let uri = req.uri().clone();
let cors = self.args.cors; let cors = self.args.cors;
let timestamp = Local::now().format("%d/%b/%Y %H:%M:%S");
let mut res = match self.handle(req).await { let mut res = match self.handle(req).await {
Ok(res) => { Ok(res) => {
info!(r#""{} {}" - {}"#, method, uri, res.status()); println!(r#"[{}] "{} {}" - {}"#, timestamp, method, uri, res.status());
res res
} }
Err(err) => { Err(err) => {
let mut res = Response::default(); let mut res = Response::default();
status!(res, StatusCode::INTERNAL_SERVER_ERROR); let status = StatusCode::INTERNAL_SERVER_ERROR;
error!(r#""{} {}" - {} {}"#, method, uri, res.status(), err); status!(res, status);
eprintln!(
r#"[{}] "{} {}" - {} {}"#,
timestamp, method, uri, status, err
);
res res
} }
}; };
@@ -220,27 +273,9 @@ impl InnerService {
let query = req.uri().query().unwrap_or_default(); let query = req.uri().query().unwrap_or_default();
if query == "unzip" { if query == "unzip" {
let root = path.parent().unwrap(); if let Err(e) = self.unzip_file(path).await {
let mut zip = ZipFileReader::new(File::open(&path).await?).await?; eprintln!("Failed to unzip {}, {}", path.display(), e);
for i in 0..zip.entries().len() { status!(res, StatusCode::BAD_REQUEST);
let entry = &zip.entries()[i];
let entry_name = entry.name();
let entry_path = root.join(entry_name);
if entry_name.ends_with('/') {
fs::create_dir_all(entry_path).await?;
} else {
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
continue;
}
if let Some(parent) = entry_path.parent() {
if fs::symlink_metadata(parent).await.is_err() {
fs::create_dir_all(&parent).await?;
}
}
let mut outfile = fs::File::create(&entry_path).await?;
let mut reader = zip.entry_reader(i).await?;
io::copy(&mut reader, &mut outfile).await?;
}
} }
fs::remove_file(&path).await?; fs::remove_file(&path).await?;
} }
@@ -311,7 +346,7 @@ impl InnerService {
let path = path.to_owned(); let path = path.to_owned();
tokio::spawn(async move { tokio::spawn(async move {
if let Err(e) = zip_dir(&mut writer, &path).await { if let Err(e) = zip_dir(&mut writer, &path).await {
error!("Fail to zip {}, {}", path.display(), e.to_string()); eprintln!("Failed to zip {}, {}", path.display(), e);
} }
}); });
let stream = ReaderStream::new(reader); let stream = ReaderStream::new(reader);
@@ -479,7 +514,7 @@ impl InnerService {
.unwrap_or_default(), .unwrap_or_default(),
_ => false, _ => false,
}, },
None => self.args.no_auth_read && req.method() == Method::GET, None => self.args.no_auth_access && req.method() == Method::GET,
}, },
} }
}; };
@@ -499,6 +534,32 @@ impl InnerService {
.unwrap_or_default() .unwrap_or_default()
} }
async fn unzip_file(&self, path: &Path) -> BoxResult<()> {
let root = path.parent().unwrap();
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
for i in 0..zip.entries().len() {
let entry = &zip.entries()[i];
let entry_name = entry.name();
let entry_path = root.join(entry_name);
if entry_name.ends_with('/') {
fs::create_dir_all(entry_path).await?;
} else {
if !self.args.allow_delete && fs::metadata(&entry_path).await.is_ok() {
continue;
}
if let Some(parent) = entry_path.parent() {
if fs::symlink_metadata(parent).await.is_err() {
fs::create_dir_all(&parent).await?;
}
}
let mut outfile = fs::File::create(&entry_path).await?;
let mut reader = zip.entry_reader(i).await?;
io::copy(&mut reader, &mut outfile).await?;
}
}
Ok(())
}
fn extract_path(&self, path: &str) -> Option<PathBuf> { fn extract_path(&self, path: &str) -> Option<PathBuf> {
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?; let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
let slashes_switched = if cfg!(windows) { let slashes_switched = if cfg!(windows) {
@@ -506,7 +567,22 @@ impl InnerService {
} else { } else {
decoded_path.into_owned() decoded_path.into_owned()
}; };
Some(self.args.path.join(&slashes_switched)) 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>>( async fn to_pathitem<P: AsRef<Path>>(
@@ -659,3 +735,38 @@ fn to_content_range(range: &Range, complete_length: u64) -> Option<ContentRange>
_ => None, _ => None,
}) })
} }
fn print_listening(address: &str, port: u16, tls: bool) {
let addrs = retrive_listening_addrs(address);
let protocol = if tls { "https" } else { "http" };
if addrs.len() == 1 {
eprintln!("Listening on {}://{}:{}", protocol, addrs[0], port);
} else {
eprintln!("Listening on:");
for addr in addrs {
eprintln!(" {}://{}:{}", protocol, addr, port);
}
eprintln!();
}
}
fn retrive_listening_addrs(address: &str) -> Vec<String> {
if address == "0.0.0.0" {
if let Ok(interfaces) = get_if_addrs() {
let mut ifaces: Vec<IpAddr> = interfaces
.into_iter()
.map(|v| v.ip())
.filter(|v| v.is_ipv4())
.collect();
ifaces.sort();
return ifaces.into_iter().map(|v| v.to_string()).collect();
}
}
vec![address.to_owned()]
}
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("Failed to install CTRL+C signal handler")
}