Compare commits

..

53 Commits

Author SHA1 Message Date
sigoden
7481db5071 chore(release): version v0.13.2 2022-06-06 08:03:00 +08:00
sigoden
b0cc901416 fix: escape path-prefix/url-prefix different 2022-06-06 08:00:26 +08:00
Joe Koop
ce154d9ebc fix: filename xml escaping 2022-06-06 07:54:12 +08:00
sigoden
7c4c264206 chore(release): version v0.13.1 2022-06-06 07:15:48 +08:00
sigoden
c1e0c6bb2f refactor: use logger (#22) 2022-06-06 07:13:22 +08:00
sigoden
f138915f20 fix: escape filename (#21)
close #19
2022-06-06 06:51:35 +08:00
sigoden
a0b413ef30 chore(release): version v0.13.0 2022-06-05 09:33:10 +08:00
sigoden
fc13d41c17 chore(docker): use scratch as docker base image 2022-06-05 09:30:26 +08:00
sigoden
882a9ae716 fix: ctrl+c not exit sometimes 2022-06-05 09:22:24 +08:00
sigoden
5578ee9190 feat: add webdav proppatch handler (#18) 2022-06-05 07:35:05 +08:00
Ryan Russell
916602ae2d chore: fix typos (#17)
* chore(server.rs): fix `retrieve_listening_addrs`

Signed-off-by: Ryan Russell <git@ryanrussell.org>

* docs(index.js): Fix `breadcrumb`

Signed-off-by: Ryan Russell <git@ryanrussell.org>
2022-06-05 06:12:37 +08:00
sigoden
2f40313a54 feat: use digest auth (#14)
* feat: switch to digest auth

* implement digest auth

* cargo fmt

* no lock
2022-06-05 00:09:21 +08:00
sigoden
05155aa532 feat: implement more webdav methods (#13)
Now you can mount the server as webdav driver on windows.
2022-06-04 19:08:18 +08:00
sigoden
4605701366 chore(release): version v0.12.1 2022-06-04 13:39:03 +08:00
sigoden
b7c550e09b chore(release): version v0.12.0 2022-06-04 13:21:46 +08:00
sigoden
fff8fc3ac5 chore: incorrect icon of uploaded file 2022-06-04 13:20:39 +08:00
sigoden
0616602659 feat: remove unzip uploaded feature (#11)
Use drag&drop/webdav to upload folders
2022-06-04 13:01:17 +08:00
sigoden
0a64762df4 feat: support webdav (#10) 2022-06-04 12:51:56 +08:00
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
sigoden
605c6c56c4 chore: upgrade version 2022-06-01 23:12:52 +08:00
sigoden
8718562889 chore: update description 2022-06-01 22:55:11 +08:00
sigoden
830d3343f4 feat: support render-index/render-spa
closes #5
2022-06-01 22:49:55 +08:00
sigoden
1fe391f9d9 chore: move src/assets out of src 2022-06-01 20:26:03 +08:00
sigoden
b88381167b feat: add some headers to res 2022-06-01 20:02:35 +08:00
sigoden
35ed4394df fix: caught 500 if no permission to access dir
releated #4
2022-06-01 19:59:35 +08:00
sigoden
f43d0b646d fix: some typos
close #6
2022-05-31 22:38:00 +08:00
sigoden
a9294f602c feat: cli add allow-symlink option 2022-05-31 21:22:44 +08:00
sigoden
584d33940a chore: upgrade version 2022-05-31 17:02:55 +08:00
sigoden
fc090b6930 fix: not found dir when allow_upload is false 2022-05-31 16:55:52 +08:00
sigoden
19d7b36462 feat: drag and drop uploads, upload folder
close #3
2022-05-31 16:47:06 +08:00
sigoden
755554d3f2 fix: miss file 500 2022-05-31 16:32:50 +08:00
sigoden
6a097e0496 fix: unzip override existed file in uploadonly mode 2022-05-31 15:20:47 +08:00
sigoden
412d42e338 fix: downloaded zip file has no.zip ext in firefox
close #2
2022-05-31 14:39:07 +08:00
14 changed files with 1815 additions and 375 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:
@@ -123,4 +125,41 @@ jobs:
files: ${{ steps.package.outputs.archive }} files: ${{ steps.package.outputs.archive }}
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

216
CHANGELOG.md Normal file
View File

@@ -0,0 +1,216 @@
# Changelog
All notable changes to this project will be documented in this file.
## [0.13.2] - 2022-06-06
### Bug Fixes
- Filename xml escaping
- Escape path-prefix/url-prefix different
## [0.13.1] - 2022-06-05
### Bug Fixes
- Escape filename ([#21](https://github.com/sigoden/duf/issues/21))
### Refactor
- Use logger ([#22](https://github.com/sigoden/duf/issues/22))
## [0.13.0] - 2022-06-05
### Bug Fixes
- Ctrl+c not exit sometimes
### Features
- Implement more webdav methods ([#13](https://github.com/sigoden/duf/issues/13))
- Use digest auth ([#14](https://github.com/sigoden/duf/issues/14))
- Add webdav proppatch handler ([#18](https://github.com/sigoden/duf/issues/18))
## [0.12.1] - 2022-06-04
### Features
- Support webdav ([#10](https://github.com/sigoden/duf/issues/10))
- Remove unzip uploaded feature ([#11](https://github.com/sigoden/duf/issues/11))
## [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 -->

387
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,23 +286,44 @@ dependencies = [
[[package]] [[package]]
name = "duf" name = "duf"
version = "0.6.0" version = "0.13.2"
dependencies = [ dependencies = [
"async-walkdir", "async-walkdir",
"async_zip", "async_zip",
"base64", "base64",
"chrono",
"clap", "clap",
"env_logger",
"futures", "futures",
"get_if_addrs",
"headers", "headers",
"hyper", "hyper",
"lazy_static",
"log", "log",
"md5",
"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",
"urlencoding",
"uuid",
"xml-rs",
]
[[package]]
name = "env_logger"
version = "0.9.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0b2cf0344971ee6c64c31be0d530793fba457d322dfec2810c453d0ef228f9c3"
dependencies = [
"humantime",
"log",
] ]
[[package]] [[package]]
@@ -452,6 +463,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 +479,39 @@ 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]]
name = "getrandom"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9be70c98951c83b8d2f8f60d7065fa6d5146873094452a1008da8c2f1e4205ad"
dependencies = [
"cfg-if",
"libc",
"wasi 0.10.0+wasi-snapshot-preview1",
]
[[package]] [[package]]
name = "hashbrown" name = "hashbrown"
version = "0.11.2" version = "0.11.2"
@@ -536,6 +586,12 @@ version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"
[[package]]
name = "humantime"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4"
[[package]] [[package]]
name = "hyper" name = "hyper"
version = "0.14.19" version = "0.14.19"
@@ -593,6 +649,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"
@@ -625,6 +690,12 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "md5"
version = "0.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]] [[package]]
name = "memchr" name = "memchr"
version = "2.5.0" version = "2.5.0"
@@ -697,15 +768,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"
@@ -748,6 +810,12 @@ version = "0.3.25"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae" checksum = "1df8c4ec4b0627e53bdf214615ad287367e482558cf84b109250b37464dc03ae"
[[package]]
name = "ppv-lite86"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eb9f9e6e233e5c4a35559a617bf40a4ec447db2e84c20b55a6f83167b7e57872"
[[package]] [[package]]
name = "proc-macro2" name = "proc-macro2"
version = "1.0.39" version = "1.0.39"
@@ -766,12 +834,88 @@ dependencies = [
"proc-macro2", "proc-macro2",
] ]
[[package]]
name = "rand"
version = "0.8.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
dependencies = [
"libc",
"rand_chacha",
"rand_core",
]
[[package]]
name = "rand_chacha"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
dependencies = [
"ppv-lite86",
"rand_core",
]
[[package]]
name = "rand_core"
version = "0.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d34f1408f55294453790c48b2f1ebbb1c5b4b7563eb1f418bcfcfdbb06ebb4e7"
dependencies = [
"getrandom",
]
[[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 +959,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 +980,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 +1034,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 +1050,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 +1067,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 +1168,28 @@ 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 = "urlencoding"
version = "2.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "68b90931029ab9b034b300b797048cf23723400aa757e8a2bfb9d748102f9821"
[[package]]
name = "uuid"
version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c6d5d669b51467dcf7b2f1a796ce0f955f05f01cafda6c19d6e95f730df29238"
dependencies = [
"getrandom",
"rand",
]
[[package]] [[package]]
name = "version_check" name = "version_check"
version = "0.9.4" version = "0.9.4"
@@ -1051,6 +1224,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"
@@ -1116,6 +1369,12 @@ version = "0.36.1"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
[[package]]
name = "xml-rs"
version = "0.8.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d2d7d3948613f75c98fd9328cfdcc45acc4d360655289d0a7d4ec931392200a3"
[[package]] [[package]]
name = "xz2" name = "xz2"
version = "0.1.6" version = "0.1.6"

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "duf" name = "duf"
version = "0.6.0" version = "0.13.2"
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 simple file server."
@@ -9,24 +9,35 @@ homepage = "https://github.com/sigoden/duf"
repository = "https://github.com/sigoden/duf" repository = "https://github.com/sigoden/duf"
autotests = false autotests = false
categories = ["command-line-utilities", "web-programming::http-server"] categories = ["command-line-utilities", "web-programming::http-server"]
keywords = ["static", "file", "server", "http", "cli"] keywords = ["static", "file", "server", "webdav", "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"
md5 = "0.7.0"
lazy_static = "1.4.0"
uuid = { version = "1.1.1", features = ["v4", "fast-rng"] }
urlencoding = "2.1.0"
xml-rs = "0.8"
env_logger = { version = "0.9.0", default-features = false, features = ["humantime"] }
log = "0.4.17"
[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 scratch
COPY --from=builder /app/target/x86_64-unknown-linux-musl/release/duf /bin/
ENTRYPOINT ["/bin/duf"]

View File

@@ -3,19 +3,20 @@
[![CI](https://github.com/sigoden/duf/actions/workflows/ci.yaml/badge.svg)](https://github.com/sigoden/duf/actions/workflows/ci.yaml) [![CI](https://github.com/sigoden/duf/actions/workflows/ci.yaml/badge.svg)](https://github.com/sigoden/duf/actions/workflows/ci.yaml)
[![Crates](https://img.shields.io/crates/v/duf.svg)](https://crates.io/crates/duf) [![Crates](https://img.shields.io/crates/v/duf.svg)](https://crates.io/crates/duf)
Duf is a simple file server. Duf is a simple file server. Support static serve, search, upload, webdav...
![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
- Upload files and folders (Drag & Drop)
- Search files - Search files
- Upload files - Partial responses (Parallel/Resume download)
- Delete files - Authentication
- Basic authentication - Support https
- Unzip zip file when upload - Support webdav
- Easy to use with curl - Easy to use with curl
## Install ## Install
@@ -26,11 +27,47 @@ Duf is a simple 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 simple 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,29 +83,33 @@ 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
``` ```
curl http://127.0.0.1:5000/some-file curl http://127.0.0.1:5000/some-file
curl -o some-file2 http://127.0.0.1:5000/some-file
``` ```
Download a folder as zip file Download a folder as zip file
@@ -83,12 +124,6 @@ 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
``` ```

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,9 +166,7 @@ body {
padding-left: 0.4em; padding-left: 0.4em;
} }
.uploaders { .uploaders-table {
display: flex;
flex-wrap: wrap;
padding: 0.5em 0; padding: 0.5em 0;
} }

View File

@@ -15,7 +15,7 @@
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg> <svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z"/></svg>
</a> </a>
</div> </div>
<div class="upload-control hidden" title="Upload file"> <div class="upload-control hidden" title="Upload files">
<label for="file"> <label for="file">
<svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg> <svg width="16" height="16" viewBox="0 0 16 16"><path d="M.5 9.9a.5.5 0 0 1 .5.5v2.5a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-2.5a.5.5 0 0 1 1 0v2.5a2 2 0 0 1-2 2H2a2 2 0 0 1-2-2v-2.5a.5.5 0 0 1 .5-.5z"/><path d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z"/></svg>
</label> </label>
@@ -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,35 +1,65 @@
let $tbody, $uploaders; /**
let uploaderIdx = 0; * @typedef {object} PathItem
* @property {"Dir"|"SymlinkDir"|"File"|"SymlinkFile"} path_type
* @property {boolean} is_symlink
* @property {string} name
* @property {number} mtime
* @property {number} size
*/
/**
* @type Element
*/
let $pathsTable, $pathsTableBody, $uploadersTable;
/**
* @type string
*/
let baseDir; let baseDir;
class Uploader { class Uploader {
idx = 0; /**
* @type number
*/
idx;
/**
* @type File
*/
file; file;
$elem; /**
constructor(idx, file) { * @type string
this.idx = idx; */
name;
/**
* @type Element
*/
$uploadStatus;
static globalIdx = 0;
constructor(file, dirs) {
this.name = [...dirs, file.name].join("/");
this.idx = Uploader.globalIdx++;
this.file = file; this.file = file;
} }
upload() { upload() {
const { file, idx } = this; const { file, idx, name } = this;
let url = getUrl(file.name); let url = getUrl(name);
if (file.name == baseDir + ".zip") { $uploadersTable.insertAdjacentHTML("beforeend", `
url += "?unzip"; <tr id="upload${idx}" class="uploader">
} <td class="path cell-name">
$uploaders.insertAdjacentHTML("beforeend", ` <div>${getSvg("File")}</div>
<div class="uploader path"> <a href="${url}">${name}</a>
<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>
<a href="${url}" id="file${idx}">${file.name} (0%)</a> <td class="cell-status" id="uploadStatus${idx}"></td>
</div>`); </tr>`);
this.$elem = document.getElementById(`file${idx}`); $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);
ajax.addEventListener("readystatechange", () => { ajax.addEventListener("readystatechange", () => {
console.log(ajax.readyState, ajax.status)
if(ajax.readyState === 4) { if(ajax.readyState === 4) {
if (ajax.status == 200) { if (ajax.status >= 200 && ajax.status < 300) {
this.complete(); this.complete();
} else { } else {
this.fail(); this.fail();
@@ -44,18 +74,22 @@ class Uploader {
progress(event) { progress(event) {
const percent = (event.loaded / event.total) * 100; const percent = (event.loaded / event.total) * 100;
this.$elem.innerHTML = `${this.file.name} (${percent.toFixed(2)}%)`; this.$uploadStatus.innerHTML = `${percent.toFixed(2)}%`;
} }
complete() { complete() {
this.$elem.innerHTML = `${this.file.name}`; this.$uploadStatus.innerHTML = ``;
} }
fail() { fail() {
this.$elem.innerHTML = `<strike>${this.file.name}</strike>`; this.$uploadStatus.innerHTML = ``;
} }
} }
/**
* Add breadcrumb
* @param {string} value
*/
function addBreadcrumb(value) { function addBreadcrumb(value) {
const $breadcrumb = document.querySelector(".breadcrumb"); const $breadcrumb = document.querySelector(".breadcrumb");
const parts = value.split("/").filter(v => !!v); const parts = value.split("/").filter(v => !!v);
@@ -78,6 +112,11 @@ function addBreadcrumb(value) {
} }
} }
/**
* Add pathitem
* @param {PathItem} file
* @param {number} index
*/
function addPath(file, index) { function addPath(file, index) {
const url = getUrl(file.name) const url = getUrl(file.name)
let actionDelete = ""; let actionDelete = "";
@@ -109,18 +148,23 @@ 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>`)
} }
/**
* Delete pathitem
* @param {number} index
* @returns
*/
async function deletePath(index) { async function deletePath(index) {
const file = DATA.paths[index]; const file = DATA.paths[index];
if (!file) return; if (!file) return;
@@ -131,8 +175,12 @@ async function deletePath(index) {
const res = await fetch(getUrl(file.name), { const res = await fetch(getUrl(file.name), {
method: "DELETE", method: "DELETE",
}); });
if (res.status === 200) { if (res.status >= 200 && res.status < 300) {
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())
} }
@@ -141,6 +189,44 @@ async function deletePath(index) {
} }
} }
function dropzone() {
["drag", "dragstart", "dragend", "dragover", "dragenter", "dragleave", "drop"].forEach(name => {
document.addEventListener(name, e => {
e.preventDefault();
e.stopPropagation();
});
});
document.addEventListener("drop", e => {
if (!e.dataTransfer.items[0].webkitGetAsEntry) {
const files = e.dataTransfer.files.filter(v => v.size > 0);
for (const file of files) {
new Uploader(file, []).upload();
}
} else {
const entries = [];
const len = e.dataTransfer.items.length;
for (let i = 0; i < len; i++) {
entries.push(e.dataTransfer.items[i].webkitGetAsEntry());
}
addFileEntries(entries, [])
}
});
}
async function addFileEntries(entries, dirs) {
for (const entry of entries) {
if (entry.isFile) {
entry.file(file => {
new Uploader(file, dirs).upload();
});
} else if (entry.isDirectory) {
const dirReader = entry.createReader()
dirReader.readEntries(entries => addFileEntries(entries, [...dirs, entry.name]));
}
}
}
function getUrl(name) { function getUrl(name) {
let url = location.href.split('?')[0]; let url = location.href.split('?')[0];
if (!url.endsWith("/")) url += "/"; if (!url.endsWith("/")) url += "/";
@@ -184,22 +270,29 @@ function formatSize(size) {
return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i]; return Math.round(size / Math.pow(1024, i), 2) + ' ' + sizes[i];
} }
function ready() { function ready() {
$tbody = document.querySelector(".main tbody"); $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);
DATA.paths.forEach((file, index) => addPath(file, index)); if (Array.isArray(DATA.paths)) {
const len = DATA.paths.length;
if (len > 0) {
$pathsTable.classList.remove("hidden");
}
for (let i = 0; i < len; i++) {
addPath(DATA.paths[i], i);
}
}
if (DATA.allow_upload) { if (DATA.allow_upload) {
document.querySelector(".upload-control").classList.remove(["hidden"]); dropzone();
document.querySelector(".upload-control").classList.remove("hidden");
document.getElementById("file").addEventListener("change", e => { document.getElementById("file").addEventListener("change", e => {
const files = e.target.files; const files = e.target.files;
for (let file of files) { for (let file of files) {
uploaderIdx += 1; new Uploader(file, []).upload();
const uploader = new Uploader(uploaderIdx, file);
uploader.upload();
} }
}); });
} }
} }

View File

@@ -1,10 +1,11 @@
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::auth::parse_auth;
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.
@@ -16,7 +17,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"),
) )
@@ -32,7 +33,13 @@ fn app() -> clap::Command<'static> {
Arg::new("path") Arg::new("path")
.default_value(".") .default_value(".")
.allow_invalid_utf8(true) .allow_invalid_utf8(true)
.help("Path to a directory for serving files"), .help("Path to a root directory for serving files"),
)
.arg(
Arg::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")
@@ -43,30 +50,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("allo-delete") .long("allow-delete")
.help("Allow delete operation"), .help("Allow delete files/folders"),
)
.arg(
Arg::new("allow-symlink")
.long("allow-symlink")
.help("Allow symlink to files/folders outside root directory"),
)
.arg(
Arg::new("render-index")
.long("render-index")
.help("Render index.html when requesting a directory"),
)
.arg(
Arg::new("render-spa")
.long("render-spa")
.help("Render for single-page application"),
) )
.arg( .arg(
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 {
@@ -78,11 +114,17 @@ pub struct Args {
pub address: String, pub address: String,
pub port: u16, pub port: u16,
pub path: PathBuf, pub path: PathBuf,
pub auth: Option<String>, pub path_prefix: String,
pub no_auth_read: bool, pub uri_prefix: String,
pub auth: Option<(String, String)>,
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 render_index: bool,
pub render_spa: bool,
pub cors: bool, pub cors: bool,
pub tls: Option<(Vec<Certificate>, PrivateKey)>,
} }
impl Args { impl Args {
@@ -94,21 +136,50 @@ 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.trim_matches('/').to_owned())
.unwrap_or_default();
let uri_prefix = if path_prefix.is_empty() {
"/".to_owned()
} else {
format!("/{}/", &path_prefix)
};
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 = match matches.value_of("auth") {
let no_auth_read = matches.is_present("no-auth-read"); Some(auth) => Some(parse_auth(auth)?),
None => None,
};
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 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,
path_prefix,
uri_prefix,
auth, auth,
no_auth_read, no_auth_access,
cors, cors,
allow_delete, allow_delete,
allow_upload, allow_upload,
allow_symlink,
render_index,
render_spa,
tls,
}) })
} }
@@ -116,34 +187,53 @@ 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()
.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| {
bail!(
"error: failed to access path \"{}\": {}",
path.display(),
err,
)
}) })
.map_err(|err| format!("Failed to access path `{}`: {}", path.display(), err,).into())
} }
/// 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()))
}

209
src/auth.rs Normal file
View File

@@ -0,0 +1,209 @@
use headers::HeaderValue;
use lazy_static::lazy_static;
use md5::Context;
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use uuid::Uuid;
use crate::BoxResult;
const REALM: &str = "DUF";
lazy_static! {
static ref NONCESTARTHASH: Context = {
let mut h = Context::new();
h.consume(Uuid::new_v4().as_bytes());
h.consume(std::process::id().to_be_bytes());
h
};
}
pub fn generate_www_auth(stale: bool) -> String {
let str_stale = if stale { "stale=true," } else { "" };
format!(
"Digest realm=\"{}\",nonce=\"{}\",{}qop=\"auth\",algorithm=\"MD5\"",
REALM,
create_nonce(),
str_stale
)
}
pub fn parse_auth(auth: &str) -> BoxResult<(String, String)> {
let p: Vec<&str> = auth.trim().split(':').collect();
let err = "Invalid auth value";
if p.len() != 2 {
return Err(err.into());
}
let user = p[0];
let pass = p[1];
let mut h = Context::new();
h.consume(format!("{}:{}:{}", user, REALM, pass).as_bytes());
Ok((user.to_owned(), format!("{:x}", h.compute())))
}
pub fn valid_digest(
header_value: &HeaderValue,
method: &str,
auth_user: &str,
auth_pass: &str,
) -> Option<()> {
let digest_value = strip_prefix(header_value.as_bytes(), b"Digest ")?;
let user_vals = to_headermap(digest_value).ok()?;
if let (Some(username), Some(nonce), Some(user_response)) = (
user_vals
.get(b"username".as_ref())
.and_then(|b| std::str::from_utf8(*b).ok()),
user_vals.get(b"nonce".as_ref()),
user_vals.get(b"response".as_ref()),
) {
match validate_nonce(nonce) {
Ok(true) => {}
_ => return None,
}
if auth_user != username {
return None;
}
let mut ha = Context::new();
ha.consume(method);
ha.consume(b":");
if let Some(uri) = user_vals.get(b"uri".as_ref()) {
ha.consume(uri);
}
let ha = format!("{:x}", ha.compute());
let mut correct_response = None;
if let Some(qop) = user_vals.get(b"qop".as_ref()) {
if qop == &b"auth".as_ref() || qop == &b"auth-int".as_ref() {
correct_response = Some({
let mut c = Context::new();
c.consume(&auth_pass);
c.consume(b":");
c.consume(nonce);
c.consume(b":");
if let Some(nc) = user_vals.get(b"nc".as_ref()) {
c.consume(nc);
}
c.consume(b":");
if let Some(cnonce) = user_vals.get(b"cnonce".as_ref()) {
c.consume(cnonce);
}
c.consume(b":");
c.consume(qop);
c.consume(b":");
c.consume(&*ha);
format!("{:x}", c.compute())
});
}
}
let correct_response = match correct_response {
Some(r) => r,
None => {
let mut c = Context::new();
c.consume(&auth_pass);
c.consume(b":");
c.consume(nonce);
c.consume(b":");
c.consume(&*ha);
format!("{:x}", c.compute())
}
};
if correct_response.as_bytes() == *user_response {
// grant access
return Some(());
}
}
None
}
/// Check if a nonce is still valid.
/// Return an error if it was never valid
fn validate_nonce(nonce: &[u8]) -> Result<bool, ()> {
if nonce.len() != 34 {
return Err(());
}
//parse hex
if let Ok(n) = std::str::from_utf8(nonce) {
//get time
if let Ok(secs_nonce) = u32::from_str_radix(&n[..8], 16) {
//check time
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let secs_now = now.as_secs() as u32;
if let Some(dur) = secs_now.checked_sub(secs_nonce) {
//check hash
let mut h = NONCESTARTHASH.clone();
h.consume(secs_nonce.to_be_bytes());
let h = format!("{:x}", h.compute());
if h[..26] == n[8..34] {
return Ok(dur < 300); // from the last 5min
//Authentication-Info ?
}
}
}
}
Err(())
}
fn strip_prefix<'a>(search: &'a [u8], prefix: &[u8]) -> Option<&'a [u8]> {
let l = prefix.len();
if search.len() < l {
return None;
}
if &search[..l] == prefix {
Some(&search[l..])
} else {
None
}
}
fn to_headermap(header: &[u8]) -> Result<HashMap<&[u8], &[u8]>, ()> {
let mut sep = Vec::new();
let mut asign = Vec::new();
let mut i: usize = 0;
let mut esc = false;
for c in header {
match (c, esc) {
(b'=', false) => asign.push(i),
(b',', false) => sep.push(i),
(b'"', false) => esc = true,
(b'"', true) => esc = false,
_ => {}
}
i += 1;
}
sep.push(i); // same len for both Vecs
i = 0;
let mut ret = HashMap::new();
for (&k, &a) in sep.iter().zip(asign.iter()) {
while header[i] == b' ' {
i += 1;
}
if a <= i || k <= 1 + a {
//keys and vals must contain one char
return Err(());
}
let key = &header[i..a];
let val = if header[1 + a] == b'"' && header[k - 1] == b'"' {
//escaped
&header[2 + a..k - 1]
} else {
//not escaped
&header[1 + a..k]
};
i = 1 + k;
ret.insert(key, val);
}
Ok(ret)
}
fn create_nonce() -> String {
let now = SystemTime::now().duration_since(UNIX_EPOCH).unwrap();
let secs = now.as_secs() as u32;
let mut h = NONCESTARTHASH.clone();
h.consume(secs.to_be_bytes());
let n = format!("{:08x}{:032x}", secs, h.compute());
n[..34].to_string()
}

View File

@@ -1,18 +1,14 @@
macro_rules! bail { mod args;
($($tt:tt)*) => { mod auth;
return Err(From::from(format!($($tt)*))) mod server;
}
}
#[macro_use] #[macro_use]
extern crate log; extern crate log;
mod args;
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 std::env;
use std::io::Write;
use crate::args::{matches, Args}; use crate::args::{matches, Args};
use crate::server::serve; use crate::server::serve;
@@ -23,19 +19,34 @@ async fn main() {
} }
async fn run() -> BoxResult<()> { async fn run() -> BoxResult<()> {
let args = Args::parse(matches())?; if env::var("RUST_LOG").is_err() {
env::set_var("RUST_LOG", "info")
if std::env::var("RUST_LOG").is_ok() { }
simple_logger::init()?; env_logger::builder()
} else { .format(|buf, record| {
simple_logger::SimpleLogger::default() let timestamp = buf.timestamp();
.with_level(LevelFilter::Info) writeln!(buf, "[{} {}] {}", timestamp, record.level(), record.args())
.init()?; })
.init();
let args = Args::parse(matches())?;
tokio::select! {
ret = serve(args) => {
ret
},
_ = shutdown_signal() => {
Ok(())
},
} }
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);
} }
async fn shutdown_signal() {
tokio::signal::ctrl_c()
.await
.expect("Failed to install CTRL+C signal handler")
}

View File

@@ -1,37 +1,50 @@
use crate::auth::{generate_www_auth, valid_digest};
use crate::{Args, BoxResult}; use crate::{Args, BoxResult};
use xml::escape::escape_str_pcdata;
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::{TimeZone, Utc};
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::{
AccessControlAllowHeaders, AccessControlAllowOrigin, ContentRange, ContentType, ETag, AcceptRanges, AccessControlAllowHeaders, AccessControlAllowOrigin, ContentLength, ContentRange,
HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange, LastModified, Range, ContentType, ETag, HeaderMap, HeaderMapExt, IfModifiedSince, IfNoneMatch, IfRange,
LastModified, Range,
};
use hyper::header::{
HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_DISPOSITION, CONTENT_TYPE, ORIGIN, RANGE,
WWW_AUTHENTICATE,
}; };
use hyper::header::{HeaderValue, ACCEPT, CONTENT_TYPE, ORIGIN, RANGE, WWW_AUTHENTICATE};
use hyper::service::{make_service_fn, service_fn}; use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method, StatusCode}; use hyper::{Body, Method, StatusCode, Uri};
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};
use uuid::Uuid;
type Request = hyper::Request<Body>; type Request = hyper::Request<Body>;
type Response = hyper::Response<Body>; type Response = hyper::Response<Body>;
const INDEX_HTML: &str = include_str!("assets/index.html"); const INDEX_HTML: &str = include_str!("../assets/index.html");
const INDEX_CSS: &str = include_str!("assets/index.css"); const INDEX_CSS: &str = include_str!("../assets/index.css");
const INDEX_JS: &str = include_str!("assets/index.js"); const INDEX_JS: &str = include_str!("../assets/index.js");
const INDEX_NAME: &str = "index.html";
const BUF_SIZE: usize = 1024 * 16; const BUF_SIZE: usize = 1024 * 16;
macro_rules! status { macro_rules! status {
@@ -42,32 +55,64 @@ macro_rules! status {
} }
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()));
let inner = inner.clone(); match args.tls.clone() {
async { Some((certs, key)) => {
Ok::<_, Infallible>(service_fn(move |req| { 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();
inner.call(req) async move {
})) Ok::<_, Infallible>(service_fn(move |req| {
let inner = inner.clone();
inner.call(req)
}))
}
}));
print_listening(args.address.as_str(), args.port, &args.uri_prefix, true);
server.await?;
} }
}); None => {
let server = hyper::Server::try_bind(&socket_addr)?.serve(make_service_fn(move |_| {
let server = hyper::Server::try_bind(&address)?.serve(make_svc); let inner = inner.clone();
let address = server.local_addr(); async move {
eprintln!("Files served on http://{}", address); Ok::<_, Infallible>(service_fn(move |req| {
server.await?; let inner = inner.clone();
inner.call(req)
}))
}
}));
print_listening(args.address.as_str(), args.port, &args.uri_prefix, 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 }
} }
@@ -83,8 +128,9 @@ impl InnerService {
} }
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);
error!(r#""{} {}" - {} {}"#, method, uri, status, err);
res res
} }
}; };
@@ -102,59 +148,129 @@ impl InnerService {
return Ok(res); return Ok(res);
} }
let path = req.uri().path(); let req_path = req.uri().path();
let filepath = match self.extract_path(path) { let path = match self.extract_path(req_path) {
Some(v) => v, Some(v) => v,
None => { None => {
status!(res, StatusCode::FORBIDDEN); status!(res, StatusCode::FORBIDDEN);
return Ok(res); return Ok(res);
} }
}; };
let filepath = filepath.as_path(); let path = path.as_path();
let query = req.uri().query().unwrap_or_default(); let query = req.uri().query().unwrap_or_default();
let meta = fs::metadata(filepath).await.ok(); let (is_miss, is_dir, is_file, size) = match fs::metadata(path).await.ok() {
let is_miss = meta.is_none(); Some(meta) => (false, meta.is_dir(), meta.is_file(), meta.len()),
let is_dir = meta.map(|v| v.is_dir()).unwrap_or_default(); None => (true, false, false, 0),
let is_file = !is_miss && !is_dir; };
let allow_upload = self.args.allow_upload; let allow_upload = self.args.allow_upload;
let allow_delete = self.args.allow_delete; let allow_delete = self.args.allow_delete;
let render_index = self.args.render_index;
let render_spa = self.args.render_spa;
match *req.method() { if !self.args.allow_symlink && !is_miss && !self.is_root_contained(path).await {
Method::GET if is_dir && query == "zip" => { status!(res, StatusCode::NOT_FOUND);
self.handle_zip_dir(filepath, &mut res).await? return Ok(res);
}
Method::GET if is_dir && query.starts_with("q=") => {
self.handle_query_dir(filepath, &query[3..], &mut res)
.await?
}
Method::GET if is_file => {
self.handle_send_file(filepath, req.headers(), &mut res)
.await?
}
Method::GET if is_miss && path.ends_with('/') => {
self.handle_ls_dir(filepath, false, &mut res).await?
}
Method::GET => self.handle_ls_dir(filepath, true, &mut res).await?,
Method::OPTIONS => {
status!(res, StatusCode::NO_CONTENT);
}
Method::PUT if !allow_upload || (!allow_delete && is_file) => {
status!(res, StatusCode::FORBIDDEN);
}
Method::PUT => self.handle_upload(filepath, req, &mut res).await?,
Method::DELETE if !allow_delete => {
status!(res, StatusCode::FORBIDDEN);
}
Method::DELETE if !is_miss => self.handle_delete(filepath, is_dir).await?,
_ => {
status!(res, StatusCode::NOT_FOUND);
}
} }
let headers = req.headers();
match req.method() {
&Method::GET => {
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 => {
self.handle_method_options(&mut res);
}
&Method::PUT => {
if !allow_upload || (!allow_delete && is_file && size > 0) {
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, &mut res).await?
} else {
status!(res, StatusCode::NOT_FOUND);
}
}
&Method::HEAD => {
if is_miss {
status!(res, StatusCode::NOT_FOUND);
} else {
status!(res, StatusCode::OK);
}
}
method => match method.as_str() {
"PROPFIND" => {
if is_dir {
self.handle_propfind_dir(path, headers, &mut res).await?;
} else if is_file {
self.handle_propfind_file(path, &mut res).await?;
} else {
status!(res, StatusCode::NOT_FOUND);
}
}
"PROPPATCH" => {
if is_file {
self.handle_proppatch(req_path, &mut res).await?;
} else {
status!(res, StatusCode::NOT_FOUND);
}
}
"MKCOL" if allow_upload && is_miss => self.handle_mkcol(path, &mut res).await?,
"COPY" if allow_upload && !is_miss => {
self.handle_copy(path, headers, &mut res).await?
}
"MOVE" if allow_upload && allow_delete && !is_miss => {
self.handle_move(path, headers, &mut res).await?
}
"LOCK" => {
// Fake lock
if is_file {
self.handle_lock(req_path, &mut res).await?;
} else {
status!(res, StatusCode::NOT_FOUND);
}
}
"UNLOCK" => {
// Fake unlock
if is_miss {
status!(res, StatusCode::NOT_FOUND);
} else {
status!(res, StatusCode::OK);
}
}
_ => {
status!(res, StatusCode::METHOD_NOT_ALLOWED);
}
},
}
Ok(res) Ok(res)
} }
@@ -164,20 +280,7 @@ impl InnerService {
mut req: Request, mut req: Request,
res: &mut Response, res: &mut Response,
) -> BoxResult<()> { ) -> BoxResult<()> {
let ensure_parent = match path.parent() { ensure_path_parent(path).await?;
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 {
status!(res, StatusCode::FORBIDDEN);
return Ok(());
}
let mut file = fs::File::create(&path).await?; let mut file = fs::File::create(&path).await?;
@@ -191,52 +294,31 @@ impl InnerService {
io::copy(&mut body_reader, &mut file).await?; io::copy(&mut body_reader, &mut file).await?;
let req_query = req.uri().query().unwrap_or_default(); status!(res, StatusCode::CREATED);
if req_query == "unzip" {
let root = path.parent().unwrap();
let mut zip = ZipFileReader::new(File::open(&path).await?).await?;
for i in 0..zip.entries().len() {
let entry = &zip.entries()[i];
let entry_name = entry.name();
let entry_path = root.join(entry_name);
if entry_name.ends_with('/') {
fs::create_dir_all(entry_path).await?;
} else {
if let Some(parent) = entry_path.parent() {
if fs::symlink_metadata(parent).await.is_err() {
fs::create_dir_all(&parent).await?;
}
}
let mut outfile = fs::File::create(&entry_path).await?;
let mut reader = zip.entry_reader(i).await?;
io::copy(&mut reader, &mut outfile).await?;
}
}
fs::remove_file(&path).await?;
}
Ok(()) Ok(())
} }
async fn handle_delete(&self, path: &Path, is_dir: bool) -> BoxResult<()> { async fn handle_delete(&self, path: &Path, is_dir: bool, res: &mut Response) -> BoxResult<()> {
match is_dir { match is_dir {
true => fs::remove_dir_all(path).await?, true => fs::remove_dir_all(path).await?,
false => fs::remove_file(path).await?, false => fs::remove_file(path).await?,
} }
status!(res, StatusCode::NO_CONTENT);
Ok(()) Ok(())
} }
async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> { async fn handle_ls_dir(&self, path: &Path, exist: bool, res: &mut Response) -> BoxResult<()> {
let mut paths: Vec<PathItem> = vec![]; let mut paths = vec![];
if exist { if exist {
let mut rd = fs::read_dir(path).await?; paths = match self.list_dir(path, path).await {
while let Some(entry) = rd.next_entry().await? { Ok(paths) => paths,
let entry_path = entry.path(); Err(_) => {
if let Ok(item) = to_pathitem(entry_path, path.to_path_buf()).await { status!(res, StatusCode::FORBIDDEN);
paths.push(item); return Ok(());
} }
} }
} };
self.send_index(path, paths, res) self.send_index(path, paths, res)
} }
@@ -261,7 +343,7 @@ impl InnerService {
if fs::symlink_metadata(entry.path()).await.is_err() { if fs::symlink_metadata(entry.path()).await.is_err() {
continue; continue;
} }
if let Ok(item) = to_pathitem(entry.path(), path.to_path_buf()).await { if let Ok(Some(item)) = self.to_pathitem(entry.path(), path.to_path_buf()).await {
paths.push(item); paths.push(item);
} }
} }
@@ -271,14 +353,61 @@ impl InnerService {
async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> { async fn handle_zip_dir(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
let (mut writer, reader) = tokio::io::duplex(BUF_SIZE); let (mut writer, reader) = tokio::io::duplex(BUF_SIZE);
let filename = path
.file_name()
.and_then(|v| v.to_str())
.ok_or_else(|| format!("Failed to get name of `{}`", path.display()))?;
let path = path.to_owned(); let path = path.to_owned();
tokio::spawn(async move { tokio::spawn(async move {
if let Err(e) = dir_zip(&mut writer, &path).await { if let Err(e) = zip_dir(&mut writer, &path).await {
error!("Fail to zip {}, {}", path.display(), e.to_string()); error!("Failed to zip {}, {}", path.display(), e);
} }
}); });
let stream = ReaderStream::new(reader); let stream = ReaderStream::new(reader);
*res.body_mut() = Body::wrap_stream(stream); *res.body_mut() = Body::wrap_stream(stream);
res.headers_mut().insert(
CONTENT_DISPOSITION,
HeaderValue::from_str(&format!(
"attachment; filename=\"{}.zip\"",
encode_uri(filename),
))
.unwrap(),
);
Ok(())
}
async fn handle_render_index(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
let path = path.join(INDEX_NAME);
if fs::metadata(&path)
.await
.ok()
.map(|v| v.is_file())
.unwrap_or_default()
{
self.handle_send_file(&path, headers, res).await?;
} else {
status!(res, StatusCode::NOT_FOUND);
}
Ok(())
}
async fn handle_render_spa(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
if path.extension().is_none() {
let path = self.args.path.join(INDEX_NAME);
self.handle_send_file(&path, headers, res).await?;
} else {
status!(res, StatusCode::NOT_FOUND);
}
Ok(()) Ok(())
} }
@@ -343,10 +472,168 @@ impl InnerService {
Body::wrap_stream(stream) Body::wrap_stream(stream)
}; };
*res.body_mut() = body; *res.body_mut() = body;
res.headers_mut().typed_insert(AcceptRanges::bytes());
res.headers_mut()
.typed_insert(ContentLength(meta.len() as u64));
Ok(()) Ok(())
} }
fn handle_method_options(&self, res: &mut Response) {
res.headers_mut().insert(
"Allow",
"GET,HEAD,PUT,OPTIONS,DELETE,PROPFIND,COPY,MOVE"
.parse()
.unwrap(),
);
res.headers_mut().insert("DAV", "1".parse().unwrap());
status!(res, StatusCode::NO_CONTENT);
}
async fn handle_propfind_dir(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
let depth: u32 = match headers.get("depth") {
Some(v) => match v.to_str().ok().and_then(|v| v.parse().ok()) {
Some(v) => v,
None => {
status!(res, StatusCode::BAD_REQUEST);
return Ok(());
}
},
None => 0,
};
let mut paths = vec![self.to_pathitem(path, &self.args.path).await?.unwrap()];
if depth > 0 {
match self.list_dir(path, &self.args.path).await {
Ok(child) => paths.extend(child),
Err(_) => {
status!(res, StatusCode::FORBIDDEN);
return Ok(());
}
}
}
let output = paths
.iter()
.map(|v| v.to_dav_xml(self.args.uri_prefix.as_str()))
.fold(String::new(), |mut acc, v| {
acc.push_str(&v);
acc
});
res_multistatus(res, &output);
Ok(())
}
async fn handle_propfind_file(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
if let Some(pathitem) = self.to_pathitem(path, &self.args.path).await? {
res_multistatus(res, &pathitem.to_dav_xml(self.args.uri_prefix.as_str()));
} else {
status!(res, StatusCode::NOT_FOUND);
}
Ok(())
}
async fn handle_mkcol(&self, path: &Path, res: &mut Response) -> BoxResult<()> {
fs::create_dir_all(path).await?;
status!(res, StatusCode::CREATED);
Ok(())
}
async fn handle_copy(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
let dest = match self.extract_dest(headers) {
Some(dest) => dest,
None => {
status!(res, StatusCode::BAD_REQUEST);
return Ok(());
}
};
let meta = fs::symlink_metadata(path).await?;
if meta.is_dir() {
status!(res, StatusCode::BAD_REQUEST);
return Ok(());
}
ensure_path_parent(&dest).await?;
fs::copy(path, &dest).await?;
status!(res, StatusCode::NO_CONTENT);
Ok(())
}
async fn handle_move(
&self,
path: &Path,
headers: &HeaderMap<HeaderValue>,
res: &mut Response,
) -> BoxResult<()> {
let dest = match self.extract_dest(headers) {
Some(dest) => dest,
None => {
status!(res, StatusCode::BAD_REQUEST);
return Ok(());
}
};
ensure_path_parent(&dest).await?;
fs::rename(path, &dest).await?;
status!(res, StatusCode::NO_CONTENT);
Ok(())
}
async fn handle_lock(&self, req_path: &str, res: &mut Response) -> BoxResult<()> {
let token = if self.args.auth.is_none() {
Utc::now().timestamp().to_string()
} else {
format!("opaquelocktoken:{}", Uuid::new_v4())
};
res.headers_mut().insert(
"content-type",
"application/xml; charset=utf-8".parse().unwrap(),
);
res.headers_mut()
.insert("lock-token", format!("<{}>", token).parse().unwrap());
*res.body_mut() = Body::from(format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<D:prop xmlns:D="DAV:"><D:lockdiscovery><D:activelock>
<D:locktoken><D:href>{}</D:href></D:locktoken>
<D:lockroot><D:href>{}</D:href></D:lockroot>
</D:activelock></D:lockdiscovery></D:prop>"#,
token, req_path
));
Ok(())
}
async fn handle_proppatch(&self, req_path: &str, res: &mut Response) -> BoxResult<()> {
let output = format!(
r#"<D:response>
<D:href>{}</D:href>
<D:propstat>
<D:prop>
</D:prop>
<D:status>HTTP/1.1 403 Forbidden</D:status>
</D:propstat>
</D:response>"#,
req_path
);
res_multistatus(res, &output);
Ok(())
}
fn send_index( fn send_index(
&self, &self,
path: &Path, path: &Path,
@@ -385,33 +672,47 @@ impl InnerService {
} }
fn auth_guard(&self, req: &Request, res: &mut Response) -> bool { fn auth_guard(&self, req: &Request, res: &mut Response) -> bool {
let method = req.method();
let pass = { let pass = {
match &self.args.auth { match &self.args.auth {
None => true, None => true,
Some(auth) => match req.headers().get("Authorization") { Some((user, pass)) => match req.headers().get(AUTHORIZATION) {
Some(value) => match value.to_str().ok().map(|v| { Some(value) => {
let mut it = v.split(' '); valid_digest(value, method.as_str(), user.as_str(), pass.as_str()).is_some()
(it.next(), it.next()) }
}) { None => {
Some((Some("Basic"), Some(tail))) => base64::decode(tail) self.args.no_auth_access
.ok() && (method == Method::GET
.and_then(|v| String::from_utf8(v).ok()) || method == Method::OPTIONS
.map(|v| v.as_str() == auth) || method == Method::HEAD
.unwrap_or_default(), || method.as_str() == "PROPFIND")
_ => false, }
},
None => self.args.no_auth_read && req.method() == Method::GET,
}, },
} }
}; };
if !pass { if !pass {
let value = generate_www_auth(false);
status!(res, StatusCode::UNAUTHORIZED); status!(res, StatusCode::UNAUTHORIZED);
res.headers_mut() res.headers_mut()
.insert(WWW_AUTHENTICATE, HeaderValue::from_static("Basic")); .insert(WWW_AUTHENTICATE, value.parse().unwrap());
} }
pass pass
} }
async fn is_root_contained(&self, path: &Path) -> bool {
fs::canonicalize(path)
.await
.ok()
.map(|v| v.starts_with(&self.args.path))
.unwrap_or_default()
}
fn extract_dest(&self, headers: &HeaderMap<HeaderValue>) -> Option<PathBuf> {
let dest = headers.get("Destination")?.to_str().ok()?;
let uri: Uri = dest.parse().ok()?;
self.extract_path(uri.path())
}
fn extract_path(&self, path: &str) -> Option<PathBuf> { fn extract_path(&self, path: &str) -> Option<PathBuf> {
let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?; let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8().ok()?;
let slashes_switched = if cfg!(windows) { let slashes_switched = if cfg!(windows) {
@@ -419,16 +720,76 @@ impl InnerService {
} else { } else {
decoded_path.into_owned() decoded_path.into_owned()
}; };
let full_path = self.args.path.join(&slashes_switched); let stripped_path = match self.strip_path_prefix(&slashes_switched) {
if full_path.starts_with(&self.args.path) { Some(path) => path,
Some(full_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();
if self.args.path_prefix.is_empty() {
Some(path)
} else { } else {
None path.strip_prefix(&self.args.path_prefix).ok()
} }
} }
async fn list_dir(&self, entry_path: &Path, base_path: &Path) -> BoxResult<Vec<PathItem>> {
let mut paths: Vec<PathItem> = vec![];
let mut rd = fs::read_dir(entry_path).await?;
while let Ok(Some(entry)) = rd.next_entry().await {
let entry_path = entry.path();
if let Ok(Some(item)) = self.to_pathitem(entry_path.as_path(), base_path).await {
paths.push(item);
}
}
Ok(paths)
}
async fn to_pathitem<P: AsRef<Path>>(
&self,
path: P,
base_path: P,
) -> BoxResult<Option<PathItem>> {
let path = path.as_ref();
let rel_path = path.strip_prefix(base_path).unwrap();
let (meta, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
let (meta, meta2) = (meta?, meta2?);
let is_symlink = meta2.is_symlink();
if !self.args.allow_symlink && is_symlink && !self.is_root_contained(path).await {
return Ok(None);
}
let is_dir = meta.is_dir();
let path_type = match (is_symlink, is_dir) {
(true, true) => PathType::SymlinkDir,
(false, true) => PathType::Dir,
(true, false) => PathType::SymlinkFile,
(false, false) => PathType::File,
};
let mtime = to_timestamp(&meta.modified()?);
let size = match path_type {
PathType::Dir | PathType::SymlinkDir => None,
PathType::File | PathType::SymlinkFile => Some(meta.len()),
};
let base_name = rel_path
.file_name()
.and_then(|v| v.to_str())
.unwrap_or("/")
.to_owned();
let name = normalize_path(rel_path);
Ok(Some(PathItem {
path_type,
base_name,
name,
mtime,
size,
}))
}
} }
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Serialize)]
struct IndexData { struct IndexData {
breadcrumb: String, breadcrumb: String,
paths: Vec<PathItem>, paths: Vec<PathItem>,
@@ -439,11 +800,56 @@ struct IndexData {
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
struct PathItem { struct PathItem {
path_type: PathType, path_type: PathType,
base_name: String,
name: String, name: String,
mtime: u64, mtime: u64,
size: Option<u64>, size: Option<u64>,
} }
impl PathItem {
pub fn to_dav_xml(&self, prefix: &str) -> String {
let mtime = Utc.timestamp_millis(self.mtime as i64).to_rfc2822();
match self.path_type {
PathType::Dir | PathType::SymlinkDir => format!(
r#"<D:response>
<D:href>{}{}</D:href>
<D:propstat>
<D:prop>
<D:displayname>{}</D:displayname>
<D:getlastmodified>{}</D:getlastmodified>
<D:resourcetype><D:collection/></D:resourcetype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>"#,
escape_str_pcdata(prefix),
escape_str_pcdata(&self.name),
escape_str_pcdata(&self.base_name),
mtime
),
PathType::File | PathType::SymlinkFile => format!(
r#"<D:response>
<D:href>{}{}</D:href>
<D:propstat>
<D:prop>
<D:displayname>{}</D:displayname>
<D:getcontentlength>{}</D:getcontentlength>
<D:getlastmodified>{}</D:getlastmodified>
<D:resourcetype></D:resourcetype>
</D:prop>
<D:status>HTTP/1.1 200 OK</D:status>
</D:propstat>
</D:response>"#,
escape_str_pcdata(prefix),
escape_str_pcdata(&self.name),
escape_str_pcdata(&self.base_name),
self.size.unwrap_or_default(),
mtime
),
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)]
enum PathType { enum PathType {
Dir, Dir,
@@ -452,33 +858,6 @@ enum PathType {
SymlinkFile, SymlinkFile,
} }
async fn to_pathitem<P: AsRef<Path>>(path: P, base_path: P) -> BoxResult<PathItem> {
let path = path.as_ref();
let rel_path = path.strip_prefix(base_path).unwrap();
let (meta, meta2) = tokio::join!(fs::metadata(&path), fs::symlink_metadata(&path));
let (meta, meta2) = (meta?, meta2?);
let is_dir = meta.is_dir();
let is_symlink = meta2.file_type().is_symlink();
let path_type = match (is_symlink, is_dir) {
(true, true) => PathType::SymlinkDir,
(false, true) => PathType::Dir,
(true, false) => PathType::SymlinkFile,
(false, false) => PathType::File,
};
let mtime = to_timestamp(&meta.modified()?);
let size = match path_type {
PathType::Dir | PathType::SymlinkDir => None,
PathType::File | PathType::SymlinkFile => Some(meta.len()),
};
let name = normalize_path(rel_path);
Ok(PathItem {
path_type,
name,
mtime,
size,
})
}
fn to_timestamp(time: &SystemTime) -> u64 { fn to_timestamp(time: &SystemTime) -> u64 {
time.duration_since(SystemTime::UNIX_EPOCH) time.duration_since(SystemTime::UNIX_EPOCH)
.unwrap() .unwrap()
@@ -494,6 +873,15 @@ fn normalize_path<P: AsRef<Path>>(path: P) -> String {
} }
} }
async fn ensure_path_parent(path: &Path) -> BoxResult<()> {
if let Some(parent) = path.parent() {
if fs::symlink_metadata(parent).await.is_err() {
fs::create_dir_all(&parent).await?;
}
}
Ok(())
}
fn add_cors(res: &mut Response) { fn add_cors(res: &mut Response) {
res.headers_mut() res.headers_mut()
.typed_insert(AccessControlAllowOrigin::ANY); .typed_insert(AccessControlAllowOrigin::ANY);
@@ -504,27 +892,43 @@ fn add_cors(res: &mut Response) {
); );
} }
async fn dir_zip<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> { fn res_multistatus(res: &mut Response, content: &str) {
*res.status_mut() = StatusCode::MULTI_STATUS;
res.headers_mut().insert(
"content-type",
"application/xml; charset=utf-8".parse().unwrap(),
);
*res.body_mut() = Body::from(format!(
r#"<?xml version="1.0" encoding="utf-8" ?>
<D:multistatus xmlns:D="DAV:">
{}
</D:multistatus>"#,
content,
));
}
async fn zip_dir<W: AsyncWrite + Unpin>(writer: &mut W, dir: &Path) -> BoxResult<()> {
let mut writer = ZipFileWriter::new(writer); let mut writer = ZipFileWriter::new(writer);
let mut walkdir = WalkDir::new(dir); let mut walkdir = WalkDir::new(dir);
while let Some(entry) = walkdir.next().await { while let Some(entry) = walkdir.next().await {
if let Ok(entry) = entry { if let Ok(entry) = entry {
let entry_path = entry.path();
let meta = match fs::symlink_metadata(entry.path()).await { let meta = match fs::symlink_metadata(entry.path()).await {
Ok(meta) => meta, Ok(meta) => meta,
Err(_) => continue, Err(_) => continue,
}; };
if meta.is_file() { if !meta.is_file() {
let filepath = entry.path(); continue;
let filename = match filepath.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
Some(v) => v,
None => continue,
};
let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate);
let mut file = File::open(&filepath).await?;
let mut file_writer = writer.write_entry_stream(entry_options).await?;
io::copy(&mut file, &mut file_writer).await?;
file_writer.close().await?;
} }
let filename = match entry_path.strip_prefix(dir).ok().and_then(|v| v.to_str()) {
Some(v) => v,
None => continue,
};
let entry_options = EntryOptions::new(filename.to_owned(), Compression::Deflate);
let mut file = File::open(&entry_path).await?;
let mut file_writer = writer.write_entry_stream(entry_options).await?;
io::copy(&mut file, &mut file_writer).await?;
file_writer.close().await?;
} }
} }
writer.close().await?; writer.close().await?;
@@ -569,3 +973,41 @@ fn to_content_range(range: &Range, complete_length: u64) -> Option<ContentRange>
_ => None, _ => None,
}) })
} }
fn print_listening(address: &str, port: u16, prefix: &str, tls: bool) {
let prefix = encode_uri(prefix.trim_end_matches('/'));
let addrs = retrieve_listening_addrs(address);
let protocol = if tls { "https" } else { "http" };
if addrs.len() == 1 {
eprintln!(
"Listening on {}://{}:{}{}",
protocol, addrs[0], port, prefix
);
} else {
eprintln!("Listening on:");
for addr in addrs {
eprintln!(" {}://{}:{}{}", protocol, addr, port, prefix);
}
eprintln!();
}
}
fn retrieve_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()]
}
fn encode_uri(v: &str) -> String {
let parts: Vec<_> = v.split('/').map(urlencoding::encode).collect();
parts.join("/")
}