commit 1c97c010969ea80c771be31a7a99a4a80b9aff8c Author: sigoden Date: Thu May 26 16:17:55 2022 +0800 init commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +/target diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..40c1f3f --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,639 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "autocfg" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bytes" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4872d67bab6358e59559027aa3b9157c53d9358c51423c17554809a8858e0f8" + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "clap" +version = "3.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2dbdf4bdacb33466e854ce889eee8dfd5729abf7ccd7664d0a2d60cd384440b" +dependencies = [ + "bitflags", + "clap_lex", + "indexmap", + "lazy_static", + "textwrap", +] + +[[package]] +name = "clap_lex" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a37c35f1112dad5e6e0b1adaff798507497a18fceeb30cceb3bae7d1427b9213" +dependencies = [ + "os_str_bytes", +] + +[[package]] +name = "duf2" +version = "0.1.0" +dependencies = [ + "clap", + "futures", + "hyper", + "once_cell", + "percent-encoding", + "serde", + "serde_json", + "tempfile", + "tokio", + "tokio-util", +] + +[[package]] +name = "fastrand" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3fcf0cee53519c866c09b5de1f6c56ff9d647101f81c1964fa632e148896cdf" +dependencies = [ + "instant", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "futures" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f73fe65f54d1e12b726f517d3e2135ca3125a437b6d998caf1962961f7172d9e" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3083ce4b914124575708913bca19bfe887522d6e2e6d0952943f5eac4a74010" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c09fd04b7e4073ac7156a9539b57a484a8ea920f79c7c675d05d289ab6110d3" + +[[package]] +name = "futures-executor" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9420b90cfa29e327d0429f19be13e7ddb68fa1cccb09d65e5706b8c7a749b8a6" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4045962a5a5e935ee2fdedaa4e08284547402885ab326734432bed5d12966b" + +[[package]] +name = "futures-macro" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33c1e13800337f4d4d7a316bf45a567dbcb6ffe087f16424852d97e97a91f512" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21163e139fa306126e6eedaf49ecdb4588f939600f0b1e770f4205ee4b7fa868" + +[[package]] +name = "futures-task" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c66a976bf5909d801bbef33416c41372779507e7a6b3a5e25e4749c58f776a" + +[[package]] +name = "futures-util" +version = "0.3.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b7abd5d659d9b90c8cba917f6ec750a74e2dc23902ef9cd4cc8c8b22e6036a" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "pin-utils", + "slab", +] + +[[package]] +name = "hashbrown" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab5ef0d4909ef3724cc8cce6ccc8572c5c817592e9285f5464f8e86f8bd3726e" + +[[package]] +name = "hermit-abi" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" +dependencies = [ + "libc", +] + +[[package]] +name = "http" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff8670570af52249509a86f5e3e18a08c60b177071826898fde8997cf5f6bfbb" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + +[[package]] +name = "http-body" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" +dependencies = [ + "bytes", + "http", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "496ce29bb5a52785b44e0f7ca2847ae0bb839c9bd28f69acac9b99d461c0c04c" + +[[package]] +name = "httpdate" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421" + +[[package]] +name = "hyper" +version = "0.14.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b26ae0a80afebe130861d90abf98e3814a4f28a4c6ffeb5ab8ebb2be311e0ef2" +dependencies = [ + "bytes", + "futures-channel", + "futures-core", + "futures-util", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", + "want", +] + +[[package]] +name = "indexmap" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f647032dfaa1f8b6dc29bd3edb7bbef4861b8b8007ebb118d6db284fd59f6ee" +dependencies = [ + "autocfg", + "hashbrown", +] + +[[package]] +name = "instant" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5bbe824c507c5da5956355e86a746d82e0e1464f65d862cc5e71da70e94b2c" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "itoa" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112c678d4050afce233f4f2852bb2eb519230b3cf12f33585275537d7e41578d" + +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" + +[[package]] +name = "libc" +version = "0.2.126" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "349d5a591cd28b49e1d1037471617a32ddcda5731b99419008085f72d5a53836" + +[[package]] +name = "log" +version = "0.4.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "memchr" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" + +[[package]] +name = "mio" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "713d550d9b44d89174e066b7a6217ae06234c10cb47819a88290d2b353c31799" +dependencies = [ + "libc", + "log", + "wasi", + "windows-sys", +] + +[[package]] +name = "num_cpus" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19e64526ebdee182341572e50e9ad03965aa510cd94427a4549448f285e957a1" +dependencies = [ + "hermit-abi", + "libc", +] + +[[package]] +name = "once_cell" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7709cef83f0c1f58f666e746a08b21e0085f7440fa6a29cc194d68aac97a4225" + +[[package]] +name = "os_str_bytes" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "029d8d0b2f198229de29dca79676f2738ff952edf3fde542eb8bf94d8c21b435" + +[[package]] +name = "percent-encoding" +version = "2.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fd5641d01c8f18a23da7b6fe29298ff4b55afcccdf78973b24cf3175fee32e" + +[[package]] +name = "pin-project-lite" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" + +[[package]] +name = "pin-utils" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" + +[[package]] +name = "proc-macro2" +version = "1.0.39" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c54b25569025b7fc9651de43004ae593a75ad88543b17178aa5e1b9c4f15f56f" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1feb54ed693b93a84e14094943b84b7c4eae204c512b7ccb95ab0c66d278ad1" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "redox_syscall" +version = "0.2.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62f25bc4c7e55e0b0b7a1d43fb893f4fa1361d0abe38b9ce4f323c2adfe6ef42" +dependencies = [ + "bitflags", +] + +[[package]] +name = "remove_dir_all" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acd125665422973a33ac9d3dd2df85edad0f4ae9b00dafb1a05e43a9f5ef8e7" +dependencies = [ + "winapi", +] + +[[package]] +name = "ryu" +version = "1.0.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3f6f92acf49d1b98f7a81226834412ada05458b7364277387724a237f062695" + +[[package]] +name = "serde" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ea8d54c77f8315140a05f4c7237403bf38b72704d031543aa1d16abbf517d1" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.137" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f26faba0c3959972377d3b2d306ee9f71faee9714294e41bb777f83f88578be" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b7ce2b32a1aed03c558dc61a5cd328f15aff2dbc17daad8fb8af04d2100e15c" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "slab" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb703cfe953bccee95685111adeedb76fabe4e97549a58d16f03ea7b9367bb32" + +[[package]] +name = "socket2" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66d72b759436ae32898a2af0a14218dbf55efde3feeb170eb623637db85ee1e0" +dependencies = [ + "libc", + "winapi", +] + +[[package]] +name = "syn" +version = "1.0.95" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbaf6116ab8924f39d52792136fb74fd60a80194cf1b1c6ffa6453eef1c3f942" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "tempfile" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cdb1ef4eaeeaddc8fbd371e5017057064af0911902ef36b39801f67cc6d79e4" +dependencies = [ + "cfg-if", + "fastrand", + "libc", + "redox_syscall", + "remove_dir_all", + "winapi", +] + +[[package]] +name = "textwrap" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1141d4d61095b28419e22cb0bbf02755f5e54e0526f97f1e3d1d160e60885fb" + +[[package]] +name = "tokio" +version = "1.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4903bf0427cf68dddd5aa6a93220756f8be0c34fcfa9f5e6191e103e15a31395" +dependencies = [ + "bytes", + "libc", + "memchr", + "mio", + "num_cpus", + "once_cell", + "pin-project-lite", + "socket2", + "tokio-macros", + "winapi", +] + +[[package]] +name = "tokio-macros" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b557f72f448c511a979e2564e55d74e6c4432fc96ff4f6241bc6bded342643b7" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-util" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f988a1a1adc2fb21f9c12aa96441da33a1728193ae0b95d2be22dbd17fcb4e5c" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", + "tracing", +] + +[[package]] +name = "tower-service" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "360dfd1d6d30e05fda32ace2c8c70e9c0a9da713275777f5a4dbb8a1893930c6" + +[[package]] +name = "tracing" +version = "0.1.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0ecdcb44a79f0fe9844f0c4f33a342cbcbb5117de8001e6ba0dc2351327d09" +dependencies = [ + "cfg-if", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc6b8ad3567499f98a1db7a752b07a7c8c7c7c34c332ec00effb2b0027974b7c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f54c8ca710e81886d498c2fd3331b56c93aa248d49de2222ad2742247c60072f" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "try-lock" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642" + +[[package]] +name = "unicode-ident" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d22af068fba1eb5edcb4aea19d382b2a3deb4c8f9d475c589b6ada9e0fd493ee" + +[[package]] +name = "want" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ce8a968cb1cd110d136ff8b819a556d6fb6d919363c61534f6860c7eb172ba0" +dependencies = [ + "log", + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows-sys" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2" +dependencies = [ + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47" + +[[package]] +name = "windows_i686_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6" + +[[package]] +name = "windows_i686_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.36.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..a318849 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "duf2" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +clap = { version = "3", default-features = false, features = ["std", "cargo"] } +tokio = { version = "1", features = ["rt-multi-thread", "macros", "fs", "io-util"]} +hyper = { version = "0.14", features = ["http1", "server", "tcp", "stream"] } +percent-encoding = "2.1" +serde = { version = "1", features = ["derive"] } +serde_json = "1" +tokio-util = { version = "0.7", features = ["codec", "io-util"] } +futures = "0.3" + +[dev-dependencies] +tempfile = "3" +once_cell = "1" + +[profile.release] +lto = true +strip = true +opt-level = "z" diff --git a/src/args.rs b/src/args.rs new file mode 100644 index 0000000..bae2811 --- /dev/null +++ b/src/args.rs @@ -0,0 +1,102 @@ +use clap::crate_description; +use clap::{Arg, ArgMatches}; +use std::env; +use std::fs::canonicalize; +use std::net::SocketAddr; +use std::path::{Path, PathBuf}; + +use crate::BoxResult; + +const ABOUT: &str = concat!("\n", crate_description!()); // Add extra newline. + +fn app() -> clap::Command<'static> { + let arg_port = Arg::new("port") + .short('p') + .long("port") + .default_value("5000") + .help("Specify port to listen on") + .value_name("port"); + + let arg_address = Arg::new("address") + .short('b') + .long("bind") + .default_value("127.0.0.1") + .help("Specify bind address") + .value_name("address"); + + let arg_path = Arg::new("path") + .default_value(".") + .allow_invalid_utf8(true) + .help("Path to a directory for serving files"); + + clap::command!() + .about(ABOUT) + .arg(arg_address) + .arg(arg_port) + .arg(arg_path) +} + +pub fn matches() -> ArgMatches { + app().get_matches() +} + +#[derive(Debug, Clone, Eq, PartialEq)] +pub struct Args { + pub address: String, + pub port: u16, + pub path: PathBuf, +} + +impl Args { + /// Parse command-line arguments. + /// + /// If a parsing error ocurred, exit the process and print out informative + /// error message to user. + pub fn parse(matches: ArgMatches) -> BoxResult { + let address = matches.value_of("address").unwrap_or_default().to_owned(); + let port = matches.value_of_t::("port")?; + let path = matches.value_of_os("path").unwrap_or_default(); + let path = Args::parse_path(path)?; + + Ok(Args { + address, + port, + path, + }) + } + + /// Parse path. + fn parse_path>(path: P) -> BoxResult { + let path = path.as_ref(); + if !path.exists() { + bail!("error: path \"{}\" doesn't exist", path.display()); + } + + env::current_dir() + .and_then(|mut p| { + p.push(path); // If path is absolute, it replaces the current path. + canonicalize(p) + }) + .or_else(|err| { + bail!( + "error: failed to access path \"{}\": {}", + path.display(), + err, + ) + }) + } + + /// Construct socket address from arguments. + pub fn address(&self) -> BoxResult { + format!("{}:{}", self.address, self.port) + .parse() + .or_else(|err| { + bail!( + "error: invalid address {}:{} : {}", + self.address, + self.port, + err, + ) + }) + } +} diff --git a/src/index.css b/src/index.css new file mode 100644 index 0000000..d92d9c6 --- /dev/null +++ b/src/index.css @@ -0,0 +1,102 @@ +html { + font-family: -apple-system,BlinkMacSystemFont,Helvetica,Arial,sans-serif; + line-height: 1.5; + color: #24292e; +} + +.head { + display: flex; + align-items: baseline; + padding: 2.5em 2.5em 0; +} + +.head input { + display: none; +} + +.breadcrumb { + font-size: 1.25em; +} + +.breadcrumb > a { + color: #0366d6; + text-decoration: none; +} + +.breadcrumb > a:hover { + text-decoration: underline; +} + +/* final breadcrumb */ +.breadcrumb > b { + color: #24292e; +} + +.breadcrumb > .separator { + color: #586069; + padding: 0 0.25em; +} + +.breadcrumb svg { + height: 100%; + fill: rgba(3,47,98,0.5); + padding-right: 0.5em; + padding-left: 0.5em; +} + +.action { + cursor: pointer; +} + +.main { + padding: 0 2.5em; +} + +.main th { + text-align: left; + font-weight: unset; + color: #5c5c5c; +} + +.main .cell-name { + max-width: 300px; +} + +.main .cell-size { + text-align: right; + width: 80px; +} + +.path svg { + height: 100%; + fill: rgba(3,47,98,0.5); + padding-right: 0.5em; +} + +.path { + display: flex; + list-style: none; +} + +.path a { + color: #0366d6; + text-overflow: ellipsis; + white-space: nowrap; + overflow: hidden; + display: block; + text-decoration: none; +} + +.path a:hover { + text-decoration: underline; +} + +.uploaders { + display: flex; + flex-wrap: wrap; + padding: 0.5em 0; +} + +.uploader { + padding-right: 2em; +} \ No newline at end of file diff --git a/src/index.html b/src/index.html new file mode 100644 index 0000000..2c67065 --- /dev/null +++ b/src/index.html @@ -0,0 +1,175 @@ + + + + + + + Duf + __STYLE__ + + +
+ +
+ + +
+
+
+
+
+ + + + + + + + + + +
NameDate modifySize
+
+ + + \ No newline at end of file diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..5e5f174 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,27 @@ +macro_rules! bail { + ($($tt:tt)*) => { + return Err(From::from(format!($($tt)*))) + } +} + +mod args; +mod server; + +pub type BoxResult = Result>; + +use crate::args::{matches, Args}; +use crate::server::serve; + +#[tokio::main] +async fn main() { + Args::parse(matches()) + .map(serve) + .unwrap_or_else(handle_err) + .await + .unwrap_or_else(handle_err); +} + +fn handle_err(err: Box) -> T { + eprintln!("Server error: {}", err); + std::process::exit(1); +} diff --git a/src/server.rs b/src/server.rs new file mode 100644 index 0000000..8433203 --- /dev/null +++ b/src/server.rs @@ -0,0 +1,239 @@ +use crate::{Args, BoxResult}; + +use futures::TryStreamExt; +use hyper::service::{make_service_fn, service_fn}; +use hyper::{Body, Method, StatusCode}; +use percent_encoding::percent_decode; +use serde::Serialize; +use std::convert::Infallible; +use std::path::{Path, PathBuf}; +use std::sync::Arc; +use std::time::SystemTime; +use tokio::{fs, io}; +use tokio_util::codec::{BytesCodec, FramedRead}; +use tokio_util::io::StreamReader; + +type Request = hyper::Request; +type Response = hyper::Response; + +macro_rules! status_code { + ($status:expr) => { + hyper::Response::builder() + .status($status) + .body($status.canonical_reason().unwrap_or_default().into()) + .unwrap() + }; +} + +const INDEX_HTML: &str = include_str!("index.html"); +const INDEX_CSS: &str = include_str!("index.css"); + +pub async fn serve(args: Args) -> BoxResult<()> { + let address = args.address()?; + let inner = Arc::new(InnerService::new(args)); + let make_svc = make_service_fn(move |_| { + let inner = inner.clone(); + async { + Ok::<_, Infallible>(service_fn(move |req| { + let inner = inner.clone(); + inner.handle(req) + })) + } + }); + + let server = hyper::Server::try_bind(&address)?.serve(make_svc); + let address = server.local_addr(); + eprintln!("Files served on http://{}", address); + server.await?; + + Ok(()) +} + +struct InnerService { + args: Args, +} + +impl InnerService { + pub fn new(args: Args) -> Self { + Self { args } + } + + pub async fn handle(self: Arc, req: Request) -> Result { + let res = if req.method() == Method::GET { + self.handle_static(req).await + } else if req.method() == Method::PUT { + self.handle_upload(req).await + } else { + return Ok(status_code!(StatusCode::NOT_FOUND)); + }; + Ok(res.unwrap_or_else(|_| status_code!(StatusCode::INTERNAL_SERVER_ERROR))) + } + + async fn handle_static(&self, req: Request) -> BoxResult { + let path = match self.get_file_path(req.uri().path())? { + Some(path) => path, + None => return Ok(status_code!(StatusCode::FORBIDDEN)), + }; + match fs::metadata(&path).await { + Ok(meta) => { + if meta.is_dir() { + self.handle_send_dir(path.as_path()).await + } else { + self.handle_send_file(path.as_path()).await + } + } + Err(_) => return Ok(status_code!(StatusCode::NOT_FOUND)), + } + } + + async fn handle_upload(&self, mut req: Request) -> BoxResult { + let path = match self.get_file_path(req.uri().path())? { + Some(path) => path, + None => return Ok(status_code!(StatusCode::FORBIDDEN)), + }; + + if !fs::metadata(&path.parent().unwrap()).await?.is_dir() { + return Ok(status_code!(StatusCode::FORBIDDEN)); + } + + let mut file = fs::File::create(path).await?; + + let body_with_io_error = req + .body_mut() + .map_err(|err| io::Error::new(io::ErrorKind::Other, err)); + + let body_reader = StreamReader::new(body_with_io_error); + + futures::pin_mut!(body_reader); + + io::copy(&mut body_reader, &mut file).await?; + + return Ok(status_code!(StatusCode::OK)); + } + + async fn handle_send_dir(&self, path: &Path) -> BoxResult { + let base_path = &self.args.path; + let mut rd = fs::read_dir(path).await?; + let mut paths: Vec = vec![]; + if self.args.path != path { + paths.push(PathItem { + path_type: PathType::Dir, + name: "..".to_owned(), + path: format!( + "/{}", + normalize_path(path.parent().unwrap().strip_prefix(base_path).unwrap()) + ), + mtime: None, + size: None, + }) + } + while let Some(entry) = rd.next_entry().await? { + let entry_path = entry.path(); + let rel_path = entry_path.strip_prefix(base_path).unwrap(); + let meta = fs::metadata(&entry_path).await?; + let s_meta = fs::symlink_metadata(&entry_path).await?; + let is_dir = meta.is_dir(); + let is_symlink = s_meta.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 = meta + .modified()? + .duration_since(SystemTime::UNIX_EPOCH) + .ok() + .map(|v| v.as_millis() as u64); + let size = match path_type { + PathType::Dir | PathType::SymlinkDir => None, + PathType::File | PathType::SymlinkFile => Some(meta.len()), + }; + let name = rel_path + .file_name() + .and_then(|v| v.to_str()) + .unwrap_or_default() + .to_owned(); + paths.push(PathItem { + path_type, + name, + path: format!("/{}", normalize_path(rel_path)), + mtime, + size, + }) + } + + paths.sort_unstable(); + let breadcrumb = self.get_breadcrumb(path); + let data = SendDirData { breadcrumb, paths }; + let data = serde_json::to_string(&data).unwrap(); + + let mut output = + INDEX_HTML.replace("__STYLE__", &format!("", INDEX_CSS)); + output = output.replace("__DATA__", &data); + + Ok(hyper::Response::builder().body(output.into()).unwrap()) + } + + async fn handle_send_file(&self, path: &Path) -> BoxResult { + let file = fs::File::open(path).await?; + let stream = FramedRead::new(file, BytesCodec::new()); + let body = Body::wrap_stream(stream); + Ok(Response::new(body)) + } + + fn get_breadcrumb(&self, path: &Path) -> String { + let path = match self.args.path.parent() { + Some(p) => path.strip_prefix(p).unwrap(), + None => path, + }; + normalize_path(path) + } + + fn get_file_path(&self, path: &str) -> BoxResult> { + let decoded_path = percent_decode(path[1..].as_bytes()).decode_utf8()?; + let slashes_switched = if cfg!(windows) { + decoded_path.replace('/', "\\") + } else { + decoded_path.into_owned() + }; + let path = self.args.path.join(&slashes_switched); + if path.starts_with(&self.args.path) { + Ok(Some(path)) + } else { + Ok(None) + } + } +} + +#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] +struct SendDirData { + breadcrumb: String, + paths: Vec, +} + +#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] +struct PathItem { + path_type: PathType, + name: String, + path: String, + mtime: Option, + size: Option, +} + +#[derive(Debug, Serialize, Eq, PartialEq, Ord, PartialOrd)] +enum PathType { + Dir, + SymlinkDir, + File, + SymlinkFile, +} + +fn normalize_path>(path: P) -> String { + let path = path.as_ref().to_str().unwrap_or_default(); + if cfg!(windows) { + path.replace('\\', "/") + } else { + path.to_string() + } +}