3 Commits

5 changed files with 666 additions and 1237 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,6 +18,8 @@ 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: x86_64-apple-darwin - target: x86_64-apple-darwin

1655
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -6,21 +6,22 @@ name = "srv"
version = "1.0.0-rc" version = "1.0.0-rc"
[dependencies] [dependencies]
actix-files = "0.5" actix-files = "0.6"
actix-http = "2.2" actix-http = "3.0"
actix-web = {version = "3.3", features = ["rustls"]} actix-web = {version = "4.0", features = ["rustls"]}
actix-web-httpauth = "0.5" actix-web-httpauth = "0.6"
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" regex = "1.5"
rustls = "0.18" rustls = "0.20"
serde = "1" rustls-pemfile = "1.0"
sha2 = "0.9" serde = {version = "1.0", features = ["derive"]}
tera = "1" sha2 = "0.10"
tera = "1.15"
toml = "0.5" toml = "0.5"
urlencoding = "2.1" urlencoding = "2.1"

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,13 +194,9 @@ 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_else(|_| "false".to_string()) == "true" { if var("NOINDEX").unwrap_or_else(|_| "false".to_string()) == "true" {
@ -342,23 +338,7 @@ 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!())
(author: crate_authors!())
(about: crate_description!())
(@arg noindex: --noindex "Disable automatic index page generation")
(@arg compress: -c --compress "Enable streaming compression (Content-length/segment download will be disabled)")
// (@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) => { Ok(meta) => {
if meta.is_dir() { if meta.is_dir() {
Ok(()) Ok(())
@ -367,22 +347,26 @@ async fn main() -> std::io::Result<()> {
} }
} }
Err(e) => Err(e.to_string()), Err(e) => Err(e.to_string()),
};
let check_does_file_exits = |path: &str| match std::fs::metadata(path) {
Ok(metadata) => {
if metadata.is_file() {
Ok(())
} else {
Err("Parameter is not a file".to_owned())
} }
} "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) { };
let check_is_ip_addr = |s: &str| match IpAddr::from_str(s) {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(e.to_string()), Err(e) => Err(e.to_string()),
} };
} "IP address to serve on") let check_is_port_num = |s: &str| match s.parse::<u16>() {
(@arg port: -p --port +takes_value default_value["8000"] {
|s| match s.parse::<u16>() {
Ok(_) => Ok(()), Ok(_) => Ok(()),
Err(e) => Err(e.to_string()), Err(e) => Err(e.to_string()),
} };
} "Port to serve on") let check_is_auth = |s: &str| {
(@arg auth: --auth +takes_value {
|s| {
let parts = s.splitn(2, ':').collect::<Vec<&str>>(); let parts = s.splitn(2, ':').collect::<Vec<&str>>();
if parts.len() < 2 || parts.len() >= 2 && parts[1].is_empty() { if parts.len() < 2 || parts.len() >= 2 && parts[1].is_empty() {
Err("Password not found".to_owned()) Err("Password not found".to_owned())
@ -391,51 +375,31 @@ async fn main() -> std::io::Result<()> {
} else { } else {
Ok(()) Ok(())
} }
} };
} "HTTP Auth (username:password)") let matches = clap::command!()
(@arg cert: --cert +takes_value { .arg(Arg::new("noindex").long("noindex").help("Disable automatic index page generation"))
|s| match std::fs::metadata(s) { .arg(Arg::new("nocache").long("nocache").help("Disable HTTP cache"))
Ok(metadata) => { .arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
if metadata.is_file() { .arg(Arg::new("cors").long("cors").takes_value(true).min_values(0).max_values(1).help("Enable CORS [with custom value]"))
Ok(()) .arg(Arg::new("spa").long("spa").help("Enable Single-Page Application mode (always serve /index.html when the file is not found)"))
} else { .arg(Arg::new("dotfiles").short('d').long("dotfiles").help("Show dotfiles"))
Err("Parameter is not a file".to_owned()) .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"))
} .arg(Arg::new("quietall").long("quietall").help("Disable all output"))
Err(e) => Err(e.to_string()), .arg(Arg::new("ROOT").default_value(".").validator(check_does_dir_exits).help("Root directory"))
} .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"))
} "Path of TLS/SSL public key (certificate)") .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 key: --key +takes_value { .arg(Arg::new("auth").long("auth").takes_value(true).validator(check_is_auth).help("HTTP Auth (username:password)"))
|s| match std::fs::metadata(s) { .arg(Arg::new("cert").long("cert").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL public key (certificate)"))
Ok(metadata) => { .arg(Arg::new("key").long("key").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL private key"))
if metadata.is_file() { .subcommand(clap::Command::new("doc")
Ok(()) .about("Open cargo doc via local server (Need cargo installation)")
} else { .arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
Err("Parameter is not a file".to_owned()) .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]"))
} .arg(Arg::new("quietall").long("quietall").help("Disable all output"))
Err(e) => Err(e.to_string()), .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"))
} .arg(Arg::new("port").short('p').long("port").default_value("8000").takes_value(true).validator(check_is_port_num).help("Port to serve on"))
} "Path of TLS/SSL private key")
(@subcommand doc =>
(about: "Open cargo doc via local server (Need cargo installation)")
(@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();
@ -471,7 +435,7 @@ async fn main() -> std::io::Result<()> {
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", "*");
@ -487,7 +451,7 @@ async fn main() -> std::io::Result<()> {
let addr = format!( let addr = format!(
"{}:{}", "{}:{}",
ip, ip,
matches.value_of("port").unwrap_or("8000").to_string() matches.value_of("port").unwrap_or("8000")
); );
let url = format!( let url = format!(
"{}{}:{}", "{}{}:{}",
@ -497,7 +461,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| {
@ -579,12 +543,12 @@ async fn main() -> std::io::Result<()> {
let addr = format!( let addr = format!(
"{}:{}", "{}:{}",
ip, ip,
matches.value_of("port").unwrap_or("8000").to_string() matches.value_of("port").unwrap_or("8000")
); );
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") {
@ -608,11 +572,11 @@ async fn main() -> std::io::Result<()> {
.format(|buf, record| { .format(|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(
@ -685,11 +649,6 @@ 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_else(|_| "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_default(); let paths = PathBuf::from_str(req.path()).unwrap_or_default();
@ -705,28 +664,26 @@ async fn main() -> std::io::Result<()> {
if var("NOCACHE").unwrap_or_else(|_| "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_else(|_| "false".to_string()) == "true" { if var("ENABLE_CORS").unwrap_or_else(|_| "false".to_string()) == "true" {
let cors = var("CORS").unwrap_or_else(|_| "*".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_else(|_| 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 if isdotfile
&& var("DOTFILES").unwrap_or_else(|_| "false".to_string()) != "true" && 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_else(|_| "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),
@ -747,7 +704,7 @@ async fn main() -> std::io::Result<()> {
&& path.is_file() && path.is_file()
&& var("SPA").unwrap_or_else(|_| "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));
} }
Ok(ServiceResponse::new( Ok(ServiceResponse::new(
@ -765,10 +722,13 @@ 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).unwrap().iter().map(|x| rustls::Certificate(x.to_vec())).collect::<Vec<_>>();
let cert_chain = rustls::internal::pemfile::certs(cert).unwrap(); let key = rustls::PrivateKey(rustls_pemfile::pkcs8_private_keys(key).unwrap().first().expect("no private key found").to_owned());
let mut keys = rustls::internal::pemfile::pkcs8_private_keys(key).unwrap(); let config = rustls::ServerConfig::builder()
config.set_single_cert(cert_chain, keys.remove(0)).unwrap(); .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)