14 Commits

Author SHA1 Message Date
d1d849d93b update deps and reduce binary size 2022-06-07 11:35:06 +08:00
0217f3f1f6 Release 1.0.0 2022-06-07 11:06:42 +08:00
c575147891 update deps 2022-06-07 10:25:45 +08:00
9d81ee2291 Merge pull request #2 from Tim-Paik/dependabot/cargo/regex-1.5.5
Bump regex from 1.5.4 to 1.5.5
2022-06-07 10:10:03 +08:00
d6f7ec2380 Merge pull request #1 from Tim-Paik/dependabot/cargo/crossbeam-utils-0.8.8
Bump crossbeam-utils from 0.8.6 to 0.8.8
2022-06-07 10:08:52 +08:00
b4c980db32 Bump regex from 1.5.4 to 1.5.5
Bumps [regex](https://github.com/rust-lang/regex) from 1.5.4 to 1.5.5.
- [Release notes](https://github.com/rust-lang/regex/releases)
- [Changelog](https://github.com/rust-lang/regex/blob/master/CHANGELOG.md)
- [Commits](https://github.com/rust-lang/regex/compare/1.5.4...1.5.5)

---
updated-dependencies:
- dependency-name: regex
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-06 22:02:34 +00:00
3953820138 Bump crossbeam-utils from 0.8.6 to 0.8.8
Bumps [crossbeam-utils](https://github.com/crossbeam-rs/crossbeam) from 0.8.6 to 0.8.8.
- [Release notes](https://github.com/crossbeam-rs/crossbeam/releases)
- [Changelog](https://github.com/crossbeam-rs/crossbeam/blob/master/CHANGELOG.md)
- [Commits](https://github.com/crossbeam-rs/crossbeam/compare/crossbeam-utils-0.8.6...crossbeam-utils-0.8.8)

---
updated-dependencies:
- dependency-name: crossbeam-utils
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-06-06 21:10:58 +00:00
92a69aa058 bug fixs 2022-06-06 18:23:20 +08:00
fa3ca96fb7 bug fixs 2022-06-06 14:27:56 +08:00
edc7fad925 add aarch64 support 2022-06-06 13:19:34 +08:00
fd3c93a8d4 add update deps 2022-06-06 13:01:22 +08:00
2c1cdc5720 v1.0.0-rc.8 Update clap to 3.0.0, ready to release 2022-01-02 22:12:19 +08:00
02b6c26874 v1.0.0-rc.7 Update clap dependency, rewrite deprecated code, now has better color output 2021-10-24 21:46:08 +08:00
027d336643 v1.0.0-rc.6 Optimize the code and supplement the readme 2021-09-05 11:52:26 +08:00
6 changed files with 807 additions and 1377 deletions

View File

@ -1,2 +1,5 @@
[target.x86_64-pc-windows-msvc] [target.x86_64-pc-windows-msvc]
rustflags = ["-C", "target-feature=+crt-static"] rustflags = ["-C", "target-feature=+crt-static"]
[target.aarch64-unknown-linux-musl]
linker = "aarch64-linux-musl-gcc"

View File

@ -18,8 +18,12 @@ jobs:
strategy: strategy:
matrix: matrix:
include: include:
- target: aarch64-unknown-linux-musl
os: ubuntu-latest
- target: x86_64-unknown-linux-musl - target: x86_64-unknown-linux-musl
os: ubuntu-latest os: ubuntu-latest
- target: aarch64-apple-darwin
os: macos-latest
- target: x86_64-apple-darwin - target: x86_64-apple-darwin
os: macos-latest os: macos-latest
- target: x86_64-pc-windows-msvc - target: x86_64-pc-windows-msvc
@ -30,6 +34,7 @@ jobs:
- uses: taiki-e/upload-rust-binary-action@v1 - uses: taiki-e/upload-rust-binary-action@v1
with: with:
bin: srv bin: srv
archive: $bin-$tag-$target
target: ${{ matrix.target }} target: ${{ matrix.target }}
tar: unix tar: unix
zip: windows zip: windows

1734
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -3,27 +3,27 @@ authors = ["Tim_Paik <timpaikc@outlook.com>"]
description = "simple http server written in rust" description = "simple http server written in rust"
edition = "2018" edition = "2018"
name = "srv" name = "srv"
version = "1.0.0-rc" version = "1.0.1"
[dependencies] [dependencies]
actix-files = "0.5" actix-files = "0.6"
actix-http = "2.2" actix-web = {version = "4.0", features = ["rustls"]}
actix-web = {version = "3.3", features = ["rustls"]} actix-web-httpauth = "0.6"
actix-web-httpauth = "0.5"
chrono = "0.4" chrono = "0.4"
clap = {version = "3.0.0-beta.4", features = ["wrap_help", "color"]} clap = {version = "3.1", features = ["wrap_help", "color", "cargo"]}
env_logger = "0.9" env_logger = "0.9"
lazy_static = "1.4" lazy_static = "1.4"
log = "0.4" log = "0.4"
mime_guess = "2" mime_guess = "2.0"
regex = "1.5" rustls = "0.20"
rustls = "0.18" rustls-pemfile = "1.0"
serde = "1" serde = {version = "1.0", features = ["derive"]}
sha2 = "0.9" sha2 = "0.10"
tera = "1" tera = "1.15"
toml = "0.5" toml = "0.5"
urlencoding = "2.1" urlencoding = "2.1"
[profile.release] [profile.release]
lto = true lto = true
opt-level = "z" opt-level = "z"
strip = true

View File

@ -32,4 +32,67 @@ This is a simple HTTP Server for use in a development environment, inspired by [
- HTTP Basic Authentication Support - HTTP Basic Authentication Support
- TLS/SSL support, HTTP/2 support - TLS/SSL support, HTTP/2 support
- One click to enable CORS, custom CORS header support - One click to enable CORS, custom CORS header support
- cargo doc support - cargo doc support
## Install
### Pre-compiled Version
#### Linux
##### Archlinux
```shell
yay -S srv-bin
```
##### Other Linux
Download the pre-compiled `srv-x86_64-unknown-linux-musl.tar.gz` on the [releases](https://github.com/Tim-Paik/srv/releases/latest), and copy the srv file in the compressed package to `/usr/bin` as a ROOT user with 755 permissions.
```shell
wget https://github.com/Tim-Paik/srv/releases/download/v1.0.0-rc.6/srv-x86_64-unknown-linux-musl.tar.gz
tar -xzvf srv-x86_64-unknown-linux-musl.tar.gz
install -Dm0755 -t /usr/bin/ srv
rm srv srv-x86_64-unknown-linux-musl.tar.gz
```
for reference only
#### MacOS
I'm sorry I don't have the corresponding equipment, but I can only provide `srv-x86_64-apple-darwin.tar.gz` (Of course, if someone can sponsor me a Mac I would be very grateful)
#### Windows
Download the pre-compiled `srv-x86_64-pc-windows-msvc.zip` in the [releases](https://github.com/Tim-Paik/srv/releases/latest), unzip the srv.exe and copy it to your `%PATH%` (if you dont know what this is, move `srv.exe` to `%SystemRoot%\System32`)
### Compile and Install
You Need:
- Rust & Cargo Installation
- Git Installation
- Gcc/Msvc Toolchain Installation
```shell
git clone git@github.com:Tim-Paik/srv.git
cd srv
cargo build --release
strip target/release/srv
```
Then you can find the compiled executable file named `srv` in the `target/release/` folder.
## Usage
Execute `srv --help` to get all the usage methods
Waiting to be added...
## License
```text
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
```

View File

@ -2,8 +2,6 @@
* License, v. 2.0. If a copy of the MPL was not distributed with this * License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */ * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
#[macro_use]
extern crate clap;
#[macro_use] #[macro_use]
extern crate lazy_static; extern crate lazy_static;
@ -12,8 +10,10 @@ use actix_web::{
dev::{self, Service, ServiceResponse}, dev::{self, Service, ServiceResponse},
http, middleware, App, HttpResponse, HttpServer, http, middleware, App, HttpResponse, HttpServer,
}; };
use clap::Arg;
use env_logger::fmt::Color; use env_logger::fmt::Color;
use log::{error, info}; use log::{error, info};
use serde::{Deserialize, Serialize};
use sha2::Digest; use sha2::Digest;
use std::{ use std::{
env::{set_var, var}, env::{set_var, var},
@ -155,23 +155,23 @@ fn get_file_type(from: &Path) -> String {
.to_string() .to_string()
} }
#[derive(serde::Deserialize)] #[derive(Deserialize)]
struct Package { struct Package {
name: String, name: String,
} }
#[derive(serde::Deserialize)] #[derive(Deserialize)]
struct CargoToml { struct CargoToml {
package: Package, package: Package,
} }
#[derive(Eq, Ord, PartialEq, PartialOrd, serde::Serialize)] #[derive(Eq, Ord, PartialEq, PartialOrd, Serialize)]
struct Dir { struct Dir {
name: String, name: String,
modified: String, modified: String,
} }
#[derive(Eq, Ord, PartialEq, PartialOrd, serde::Serialize)] #[derive(Eq, Ord, PartialEq, PartialOrd, Serialize)]
struct File { struct File {
name: String, name: String,
size: u64, size: u64,
@ -179,7 +179,7 @@ struct File {
modified: String, modified: String,
} }
#[derive(serde::Serialize)] #[derive(Serialize)]
struct IndexContext { struct IndexContext {
title: String, title: String,
paths: Vec<String>, paths: Vec<String>,
@ -194,22 +194,18 @@ fn render_index(
let mut index = dir.path.clone(); let mut index = dir.path.clone();
index.push("index.html"); index.push("index.html");
if index.exists() && index.is_file() { if index.exists() && index.is_file() {
let res = match actix_files::NamedFile::open(index)? let res = actix_files::NamedFile::open(index)?
.set_content_type(mime_guess::mime::TEXT_HTML_UTF_8) .set_content_type(mime_guess::mime::TEXT_HTML_UTF_8)
.into_response(req) .into_response(req);
{
Ok(res) => res,
Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
};
return Ok(ServiceResponse::new(req.clone(), res)); return Ok(ServiceResponse::new(req.clone(), res));
} }
if var("NOINDEX").unwrap_or("false".to_string()) == "true" { if var("NOINDEX").unwrap_or_else(|_| "false".to_string()) == "true" {
return Ok(ServiceResponse::new( return Ok(ServiceResponse::new(
req.clone(), req.clone(),
HttpResponse::NotFound().body(""), HttpResponse::NotFound().body(""),
)); ));
} }
let show_dot_files = var("DOTFILES").unwrap_or("false".to_string()) == "true"; let show_dot_files = var("DOTFILES").unwrap_or_else(|_| "false".to_string()) == "true";
let mut context = IndexContext { let mut context = IndexContext {
title: "".to_string(), title: "".to_string(),
paths: vec![], paths: vec![],
@ -217,7 +213,7 @@ fn render_index(
files: vec![], files: vec![],
}; };
for path in req.path().split('/') { for path in req.path().split('/') {
if path == "" { if path.is_empty() {
continue; continue;
} }
let path = let path =
@ -245,7 +241,7 @@ fn render_index(
continue; continue;
} }
}; };
if !show_dot_files && name.starts_with(".") { if !show_dot_files && name.starts_with('.') {
continue; continue;
} }
let metadata = match path.metadata() { let metadata = match path.metadata() {
@ -292,7 +288,7 @@ fn render_index(
}; };
let index = TEMPLATE let index = TEMPLATE
.render("index", &content) .render("index", &content)
.unwrap_or("TEMPLATE RENDER ERROR".to_string()); .unwrap_or_else(|_| "TEMPLATE RENDER ERROR".to_string());
let res = HttpResponse::Ok() let res = HttpResponse::Ok()
.content_type("text/html; charset=utf-8") .content_type("text/html; charset=utf-8")
.body(index); .body(index);
@ -305,7 +301,7 @@ fn display_path(path: &Path) -> String {
if root.starts_with("\\\\?\\") { if root.starts_with("\\\\?\\") {
root[4..root.len()].to_string() root[4..root.len()].to_string()
} else { } else {
root.to_string() root
} }
} }
@ -321,9 +317,14 @@ async fn validator(
req: dev::ServiceRequest, req: dev::ServiceRequest,
auth: actix_web_httpauth::extractors::basic::BasicAuth, auth: actix_web_httpauth::extractors::basic::BasicAuth,
) -> Result<dev::ServiceRequest, actix_web::Error> { ) -> Result<dev::ServiceRequest, actix_web::Error> {
if auth.user_id() == var("AUTH_USERNAME").unwrap_or("".to_string()).as_str() if auth.user_id()
== var("AUTH_USERNAME")
.unwrap_or_else(|_| "".to_string())
.as_str()
&& hash(auth.password().unwrap_or(&std::borrow::Cow::from(""))) && hash(auth.password().unwrap_or(&std::borrow::Cow::from("")))
== var("AUTH_PASSWORD").unwrap_or("".to_string()).as_str() == var("AUTH_PASSWORD")
.unwrap_or_else(|_| "".to_string())
.as_str()
{ {
return Ok(req); return Ok(req);
} }
@ -337,102 +338,70 @@ async fn validator(
#[actix_web::main] #[actix_web::main]
async fn main() -> std::io::Result<()> { async fn main() -> std::io::Result<()> {
let matches = clap_app!((crate_name!()) => let check_does_dir_exits = |path: &str| match std::fs::metadata(path) {
(version: crate_version!()) Ok(meta) => {
(author: crate_authors!()) if meta.is_dir() {
(about: crate_description!()) Ok(())
(@arg noindex: --noindex "Disable automatic index page generation") } else {
(@arg compress: -c --compress "Enable streaming compression (Content-length/segment download will be disabled)") Err("Parameter is not a directory".to_owned())
// (@arg upload: -u --upload "Enable file upload")
(@arg nocache: --nocache "Disable HTTP cache")
(@arg nocolor: --nocolor "Disable cli colors")
(@arg cors: --cors [VALUE] min_values(0) max_values(1) "Enable CORS")
(@arg spa: --spa "Enable Single-Page Application mode (always serve /index.html when the file is not found)")
(@arg dotfiles: -d --dotfiles "Show dotfiles")
(@arg open: -o --open "Open the page in the default browser")
(@arg quiet: -q --quiet "Disable access log output")
(@arg quietall: --quietall "Disable all output")
(@arg ROOT: default_value["."] {
|path| match std::fs::metadata(path) {
Ok(meta) => {
if meta.is_dir() {
Ok(())
} else {
Err("Parameter is not a directory".to_owned())
}
}
Err(e) => Err(e.to_string()),
} }
} "Root directory") }
(@arg address: -a --address +takes_value default_value["0.0.0.0"] { Err(e) => Err(e.to_string()),
|s| match IpAddr::from_str(&s) { };
Ok(_) => Ok(()), let check_does_file_exits = |path: &str| match std::fs::metadata(path) {
Err(e) => Err(e.to_string()), Ok(metadata) => {
if metadata.is_file() {
Ok(())
} else {
Err("Parameter is not a file".to_owned())
} }
} "IP address to serve on") }
(@arg port: -p --port +takes_value default_value["8000"] { Err(e) => Err(e.to_string()),
|s| match s.parse::<u16>() { };
Ok(_) => Ok(()), let check_is_ip_addr = |s: &str| match IpAddr::from_str(s) {
Err(e) => Err(e.to_string()), Ok(_) => Ok(()),
} Err(e) => Err(e.to_string()),
} "Port to serve on") };
(@arg auth: --auth +takes_value { let check_is_port_num = |s: &str| match s.parse::<u16>() {
|s| { Ok(_) => Ok(()),
let parts = s.splitn(2, ':').collect::<Vec<&str>>(); Err(e) => Err(e.to_string()),
if parts.len() < 2 || parts.len() >= 2 && parts[1].is_empty() { };
Err("Password not found".to_owned()) let check_is_auth = |s: &str| {
} else if parts[0].is_empty() { let parts = s.splitn(2, ':').collect::<Vec<&str>>();
Err("Username not found".to_owned()) if parts.len() < 2 || parts.len() >= 2 && parts[1].is_empty() {
} else { Err("Password not found".to_owned())
Ok(()) } else if parts[0].is_empty() {
} Err("Username not found".to_owned())
} } else {
} "HTTP Auth (username:password)") Ok(())
(@arg cert: --cert +takes_value { }
|s| match std::fs::metadata(s) { };
Ok(metadata) => { let matches = clap::command!()
if metadata.is_file() { .arg(Arg::new("noindex").long("noindex").help("Disable automatic index page generation"))
Ok(()) .arg(Arg::new("nocache").long("nocache").help("Disable HTTP cache"))
} else { .arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
Err("Parameter is not a file".to_owned()) .arg(Arg::new("cors").long("cors").takes_value(true).min_values(0).max_values(1).help("Enable CORS [with custom value]"))
} .arg(Arg::new("spa").long("spa").help("Enable Single-Page Application mode (always serve /index.html when the file is not found)"))
} .arg(Arg::new("dotfiles").short('d').long("dotfiles").help("Show dotfiles"))
Err(e) => Err(e.to_string()), .arg(Arg::new("open").short('o').long("open").help("Open the page in the default browser"))
} .arg(Arg::new("quiet").short('q').long("quiet").help("Disable access log output"))
} "Path of TLS/SSL public key (certificate)") .arg(Arg::new("quietall").long("quietall").help("Disable all output"))
(@arg key: --key +takes_value { .arg(Arg::new("ROOT").default_value(".").validator(check_does_dir_exits).help("Root directory"))
|s| match std::fs::metadata(s) { .arg(Arg::new("address").short('a').long("address").default_value("0.0.0.0").takes_value(true).validator(check_is_ip_addr).help("IP address to serve on"))
Ok(metadata) => { .arg(Arg::new("port").short('p').long("port").default_value("8000").takes_value(true).validator(check_is_port_num).help("Port to serve on"))
if metadata.is_file() { .arg(Arg::new("auth").long("auth").takes_value(true).validator(check_is_auth).help("HTTP Auth (username:password)"))
Ok(()) .arg(Arg::new("cert").long("cert").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL public key (certificate)"))
} else { .arg(Arg::new("key").long("key").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL private key"))
Err("Parameter is not a file".to_owned()) .subcommand(clap::Command::new("doc")
} .about("Open cargo doc via local server (Need cargo installation)")
} .arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
Err(e) => Err(e.to_string()), .arg(Arg::new("noopen").long("noopen").help("Do not open the page in the default browser"))
} .arg(Arg::new("log").long("log").help("Enable access log output [default: disabled]"))
} "Path of TLS/SSL private key") .arg(Arg::new("quietall").long("quietall").help("Disable all output"))
(@subcommand doc => .arg(Arg::new("address").short('a').long("address").default_value("0.0.0.0").takes_value(true).validator(check_is_ip_addr).help("IP address to serve on"))
(about: "Open cargo doc via local server (Need cargo installation)") .arg(Arg::new("port").short('p').long("port").default_value("8000").takes_value(true).validator(check_is_port_num).help("Port to serve on"))
(@arg nocolor: --nocolor "Disable cli colors")
(@arg noopen: -no --noopen "Do not open the page in the default browser")
(@arg log: --log "Enable access log output [default: false]")
(@arg quietall: --quietall "Disable all output")
(@arg address: -a --address +takes_value default_value["0.0.0.0"] {
|s| match IpAddr::from_str(&s) {
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
} "IP address to serve on")
(@arg port: -p --port +takes_value default_value["8000"] {
|s| match s.parse::<u16>() {
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
} "Port to serve on")
) )
) .get_matches();
.get_matches();
set_var( set_var(
"ROOT", "ROOT",
@ -443,7 +412,6 @@ async fn main() -> std::io::Result<()> {
set_var("SPA", matches.is_present("spa").to_string()); set_var("SPA", matches.is_present("spa").to_string());
set_var("DOTFILES", matches.is_present("dotfiles").to_string()); set_var("DOTFILES", matches.is_present("dotfiles").to_string());
set_var("NOCACHE", matches.is_present("nocache").to_string()); set_var("NOCACHE", matches.is_present("nocache").to_string());
set_var("COMPRESS", matches.is_present("compress").to_string());
if matches.is_present("quiet") { if matches.is_present("quiet") {
set_var("RUST_LOG", "info,actix_web::middleware::logger=off"); set_var("RUST_LOG", "info,actix_web::middleware::logger=off");
@ -455,21 +423,18 @@ async fn main() -> std::io::Result<()> {
set_var("RUST_LOG_STYLE", "never"); set_var("RUST_LOG_STYLE", "never");
} }
match matches.value_of("auth") { if let Some(s) = matches.value_of("auth") {
Some(s) => { set_var("ENABLE_AUTH", matches.is_present("auth").to_string());
set_var("ENABLE_AUTH", matches.is_present("auth").to_string()); let parts = s.splitn(2, ':').collect::<Vec<&str>>();
let parts = s.splitn(2, ':').collect::<Vec<&str>>(); set_var("AUTH_USERNAME", parts[0]);
set_var("AUTH_USERNAME", parts[0]); set_var("AUTH_PASSWORD", hash(parts[1]));
set_var("AUTH_PASSWORD", hash(parts[1]));
}
None => {}
} }
if matches.is_present("cors") { if matches.is_present("cors") {
set_var("ENABLE_CORS", matches.is_present("cors").to_string()); set_var("ENABLE_CORS", matches.is_present("cors").to_string());
match matches.value_of("cors") { match matches.value_of("cors") {
Some(str) => { Some(str) => {
set_var("CORS", str.to_string()); set_var("CORS", str);
} }
None => { None => {
set_var("CORS", "*"); set_var("CORS", "*");
@ -482,11 +447,7 @@ async fn main() -> std::io::Result<()> {
.value_of("address") .value_of("address")
.unwrap_or("127.0.0.1") .unwrap_or("127.0.0.1")
.to_string(); .to_string();
let addr = format!( let addr = format!("{}:{}", ip, matches.value_of("port").unwrap_or("8000"));
"{}:{}",
ip,
matches.value_of("port").unwrap_or("8000").to_string()
);
let url = format!( let url = format!(
"{}{}:{}", "{}{}:{}",
if enable_tls { if enable_tls {
@ -495,7 +456,7 @@ async fn main() -> std::io::Result<()> {
"http://".to_string() "http://".to_string()
}, },
if ip == "0.0.0.0" { "127.0.0.1" } else { &ip }, if ip == "0.0.0.0" { "127.0.0.1" } else { &ip },
matches.value_of("port").unwrap_or("8000").to_string() matches.value_of("port").unwrap_or("8000")
); );
let open_in_browser = |url: &str| { let open_in_browser = |url: &str| {
@ -574,15 +535,11 @@ async fn main() -> std::io::Result<()> {
.value_of("address") .value_of("address")
.unwrap_or("127.0.0.1") .unwrap_or("127.0.0.1")
.to_string(); .to_string();
let addr = format!( let addr = format!("{}:{}", ip, matches.value_of("port").unwrap_or("8000"));
"{}:{}",
ip,
matches.value_of("port").unwrap_or("8000").to_string()
);
let url = format!( let url = format!(
"http://{}:{}/{}/index.html", "http://{}:{}/{}/index.html",
if ip == "0.0.0.0" { "127.0.0.1" } else { &ip }, if ip == "0.0.0.0" { "127.0.0.1" } else { &ip },
matches.value_of("port").unwrap_or("8000").to_string(), matches.value_of("port").unwrap_or("8000"),
crate_name, crate_name,
); );
if !matches.is_present("noopen") { if !matches.is_present("noopen") {
@ -602,19 +559,21 @@ async fn main() -> std::io::Result<()> {
addr addr
}; };
let addr_copy = addr.clone();
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")) env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.format(|buf, record| { .format(move |buf, record| {
let data = record.args().to_string(); let data = record.args().to_string();
let mut style = buf.style(); let mut style = buf.style();
let blue = style.set_color(Color::Rgb(52, 152, 219)); let blue = style.set_color(Color::Cyan);
let mut style = buf.style(); let mut style = buf.style();
let red = style.set_color(Color::Rgb(231, 76, 60)); let red = style.set_color(Color::Red);
let mut style = buf.style(); let mut style = buf.style();
let green = style.set_color(Color::Rgb(76, 175, 80)); let green = style.set_color(Color::Green);
if record.target() == "actix_web::middleware::logger" { if record.target() == "actix_web::middleware::logger" {
let data: Vec<&str> = data.splitn(5, "^").collect(); let data: Vec<&str> = data.splitn(5, '^').collect();
let time = blue.value( let time = blue.value(
chrono::NaiveDateTime::from_str(data[0]) data[0]
.parse::<chrono::DateTime<chrono::Utc>>()
.unwrap() .unwrap()
.format("%Y/%m/%d %H:%M:%S") .format("%Y/%m/%d %H:%M:%S")
.to_string(), .to_string(),
@ -626,7 +585,7 @@ async fn main() -> std::io::Result<()> {
} else { } else {
red.value(status_code) red.value(status_code)
}; };
let process_time: Vec<&str> = data[3].splitn(2, ".").collect(); let process_time: Vec<&str> = data[3].splitn(2, '.').collect();
let process_time = process_time[0].to_string() + "ms"; let process_time = process_time[0].to_string() + "ms";
let process_time = blue.value(if process_time.len() == 3 { let process_time = blue.value(if process_time.len() == 3 {
" ".to_string() + &process_time " ".to_string() + &process_time
@ -646,30 +605,27 @@ async fn main() -> std::io::Result<()> {
time, ipaddr, status_code, process_time, content time, ipaddr, status_code, process_time, content
); );
} else if record.target() == "actix_server::builder" { } else if record.target() == "actix_server::builder" {
if data.starts_with("SIGINT received, exiting") { if data.starts_with("Starting ") && data.ends_with(" workers") {
return writeln!(buf, "\r{}", green.value("[INFO] SIGINT received, exiting")); return Ok(());
// Add '\r' to remove the input ^C
} else {
let data = data.replace("actix-web-service-", "");
let re1 = regex::Regex::new("Starting (.*) workers").unwrap();
if re1.is_match(&data) {
return Ok(());
}
let re2 = regex::Regex::new("Starting \"(.*)\" service on (.*)").unwrap();
if re2.is_match(&data) {
let addr = re2
.captures(&data)
.unwrap()
.get(1)
.map_or("", |m| m.as_str());
let data = format!(
"[INFO] Serving {} on {}",
var("ROOT").unwrap_or(".".to_string()),
addr
);
return writeln!(buf, "\r{}", green.value(data));
}
} }
} else if record.target() == "actix_server::server" {
if data == "Actix runtime found; starting in Actix runtime" {
let data = format!(
"[INFO] Serving {} on {}",
var("ROOT").unwrap_or_else(|_| ".".to_string()),
addr_copy
);
return writeln!(buf, "\r{}", green.value(data));
}
if data == "SIGINT received; starting forced shutdown" {
return writeln!(buf, "\r{}", green.value("[INFO] SIGINT received; starting forced shutdown"));
// Add '\r' to remove the input ^C
}
return Ok(());
} else if record.target() == "actix_server::worker"
|| record.target() == "actix_server::accept"
{
return Ok(());
} }
if data.starts_with("[ERROR]") if data.starts_with("[ERROR]")
|| data.starts_with("TLS alert") || data.starts_with("TLS alert")
@ -683,14 +639,9 @@ async fn main() -> std::io::Result<()> {
.init(); .init();
let server = HttpServer::new(move || { let server = HttpServer::new(move || {
let compress = if var("COMPRESS").unwrap_or("false".to_string()) == "true" {
http::header::ContentEncoding::Auto
} else {
http::header::ContentEncoding::Identity
};
let app = App::new() let app = App::new()
.wrap_fn(|req, srv| { .wrap_fn(|req, srv| {
let paths = PathBuf::from_str(req.path()).unwrap_or(PathBuf::default()); let paths = PathBuf::from_str(req.path()).unwrap_or_default();
let mut isdotfile = false; let mut isdotfile = false;
for path in paths.iter() { for path in paths.iter() {
if path.to_string_lossy().starts_with('.') { if path.to_string_lossy().starts_with('.') {
@ -700,36 +651,35 @@ async fn main() -> std::io::Result<()> {
let fut = srv.call(req); let fut = srv.call(req);
async move { async move {
Ok(fut.await?.map_body(|head, body| { Ok(fut.await?.map_body(|head, body| {
if var("NOCACHE").unwrap_or("false".to_string()) == "true" { if var("NOCACHE").unwrap_or_else(|_| "false".to_string()) == "true" {
head.headers_mut().insert( head.headers_mut().insert(
http::header::CACHE_CONTROL, http::header::CACHE_CONTROL,
http::HeaderValue::from_static("no-store"), http::header::HeaderValue::from_static("no-store"),
); );
} }
if var("ENABLE_CORS").unwrap_or("false".to_string()) == "true" { if var("ENABLE_CORS").unwrap_or_else(|_| "false".to_string()) == "true" {
let cors = var("CORS").unwrap_or("*".to_string()); let cors = var("CORS").unwrap_or_else(|_| "*".to_string());
let cors = http::HeaderValue::from_str(&cors) let cors = http::header::HeaderValue::from_str(&cors)
.unwrap_or(http::HeaderValue::from_static("*")); .unwrap_or_else(|_| http::header::HeaderValue::from_static("*"));
head.headers_mut() head.headers_mut()
.insert(http::header::ACCESS_CONTROL_ALLOW_ORIGIN, cors); .insert(http::header::ACCESS_CONTROL_ALLOW_ORIGIN, cors);
} }
if isdotfile && !(var("DOTFILES").unwrap_or("false".to_string()) == "true") if isdotfile
&& var("DOTFILES").unwrap_or_else(|_| "false".to_string()) != "true"
{ {
head.status = http::StatusCode::FORBIDDEN; return dev::Response::new(http::StatusCode::FORBIDDEN).into_body();
*head.headers_mut() = http::HeaderMap::new();
return dev::ResponseBody::Other(actix_web::body::Body::None);
} }
body body
})) }))
} }
}) })
.wrap(middleware::Compress::new(compress)) .wrap(middleware::Compress::default())
.wrap(middleware::Condition::new( .wrap(middleware::Condition::new(
var("ENABLE_AUTH").unwrap_or("false".to_string()) == "true", var("ENABLE_AUTH").unwrap_or_else(|_| "false".to_string()) == "true",
actix_web_httpauth::middleware::HttpAuthentication::basic(validator), actix_web_httpauth::middleware::HttpAuthentication::basic(validator),
)) ))
.wrap(middleware::Logger::new("%t^%a^%s^%D^%r")); .wrap(middleware::Logger::new("%t^%a^%s^%D^%r"));
let files = fs::Files::new("/", var("ROOT").unwrap_or(".".to_string())) let files = fs::Files::new("/", var("ROOT").unwrap_or_else(|_| ".".to_string()))
.use_hidden_files() .use_hidden_files()
.prefer_utf8(true) .prefer_utf8(true)
.show_files_listing() .show_files_listing()
@ -737,23 +687,23 @@ async fn main() -> std::io::Result<()> {
.default_handler(|req: dev::ServiceRequest| { .default_handler(|req: dev::ServiceRequest| {
let (http_req, _payload) = req.into_parts(); let (http_req, _payload) = req.into_parts();
async { async {
let path = var("ROOT").unwrap_or(".".to_string()); let path = var("ROOT").unwrap_or_else(|_| ".".to_string());
let mut path = Path::new(&path).to_path_buf(); let mut path = Path::new(&path).to_path_buf();
path.push("index.html"); path.push("index.html");
if path.exists() if path.exists()
&& path.is_file() && path.is_file()
&& var("SPA").unwrap_or("false".to_string()) == "true" && var("SPA").unwrap_or_else(|_| "false".to_string()) == "true"
{ {
let res = fs::NamedFile::open(path)?.into_response(&http_req)?; let res = fs::NamedFile::open(path)?.into_response(&http_req);
return Ok(ServiceResponse::new(http_req, res)); return Ok(ServiceResponse::new(http_req, res));
} }
return Ok(ServiceResponse::new( Ok(ServiceResponse::new(
http_req, http_req,
HttpResponse::NotFound().body(""), HttpResponse::NotFound().body(""),
)); ))
} }
}); });
return app.service(files); app.service(files)
}); });
let server = if enable_tls { let server = if enable_tls {
let cert = &mut BufReader::new( let cert = &mut BufReader::new(
@ -762,10 +712,23 @@ async fn main() -> std::io::Result<()> {
let key = &mut BufReader::new( let key = &mut BufReader::new(
std::fs::File::open(Path::new(matches.value_of("key").unwrap())).unwrap(), std::fs::File::open(Path::new(matches.value_of("key").unwrap())).unwrap(),
); );
let mut config = rustls::ServerConfig::new(rustls::NoClientAuth::new()); let cert = rustls_pemfile::certs(cert)
let cert_chain = rustls::internal::pemfile::certs(cert).unwrap(); .unwrap()
let mut keys = rustls::internal::pemfile::pkcs8_private_keys(key).unwrap(); .iter()
config.set_single_cert(cert_chain, keys.remove(0)).unwrap(); .map(|x| rustls::Certificate(x.to_vec()))
.collect::<Vec<_>>();
let key = rustls::PrivateKey(
rustls_pemfile::pkcs8_private_keys(key)
.unwrap()
.first()
.expect("no private key found")
.to_owned(),
);
let config = rustls::ServerConfig::builder()
.with_safe_defaults()
.with_no_client_auth()
.with_single_cert(cert, key)
.expect("bad certificate/key");
server.bind_rustls(addr, config) server.bind_rustls(addr, config)
} else { } else {
server.bind(addr) server.bind(addr)