mirror of
https://github.com/Tim-Paik/srv.git
synced 2024-10-13 00:29:43 +00:00
Compare commits
11 Commits
v1.0.0-rc.
...
v1.0.0
Author | SHA1 | Date | |
---|---|---|---|
0217f3f1f6
|
|||
c575147891
|
|||
9d81ee2291 | |||
d6f7ec2380 | |||
b4c980db32 | |||
3953820138 | |||
92a69aa058
|
|||
fa3ca96fb7
|
|||
edc7fad925
|
|||
fd3c93a8d4
|
|||
2c1cdc5720 |
@ -1,2 +1,5 @@
|
||||
[target.x86_64-pc-windows-msvc]
|
||||
rustflags = ["-C", "target-feature=+crt-static"]
|
||||
|
||||
[target.aarch64-unknown-linux-musl]
|
||||
linker = "aarch64-linux-musl-gcc"
|
5
.github/workflows/release.yml
vendored
5
.github/workflows/release.yml
vendored
@ -18,8 +18,12 @@ jobs:
|
||||
strategy:
|
||||
matrix:
|
||||
include:
|
||||
- target: aarch64-unknown-linux-musl
|
||||
os: ubuntu-latest
|
||||
- target: x86_64-unknown-linux-musl
|
||||
os: ubuntu-latest
|
||||
- target: aarch64-apple-darwin
|
||||
os: macos-latest
|
||||
- target: x86_64-apple-darwin
|
||||
os: macos-latest
|
||||
- target: x86_64-pc-windows-msvc
|
||||
@ -30,6 +34,7 @@ jobs:
|
||||
- uses: taiki-e/upload-rust-binary-action@v1
|
||||
with:
|
||||
bin: srv
|
||||
archive: $bin-$tag-$target
|
||||
target: ${{ matrix.target }}
|
||||
tar: unix
|
||||
zip: windows
|
||||
|
1642
Cargo.lock
generated
1642
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
21
Cargo.toml
21
Cargo.toml
@ -3,24 +3,23 @@ authors = ["Tim_Paik <timpaikc@outlook.com>"]
|
||||
description = "simple http server written in rust"
|
||||
edition = "2018"
|
||||
name = "srv"
|
||||
version = "1.0.0-rc"
|
||||
version = "1.0.0"
|
||||
|
||||
[dependencies]
|
||||
actix-files = "0.5"
|
||||
actix-http = "2.2"
|
||||
actix-web = {version = "3.3", features = ["rustls"]}
|
||||
actix-web-httpauth = "0.5"
|
||||
actix-files = "0.6"
|
||||
actix-web = {version = "4.0", features = ["rustls"]}
|
||||
actix-web-httpauth = "0.6"
|
||||
chrono = "0.4"
|
||||
clap = {version = "3.0.0-beta.5", features = ["wrap_help", "color"]}
|
||||
clap = {version = "3.1", features = ["wrap_help", "color", "cargo"]}
|
||||
env_logger = "0.9"
|
||||
lazy_static = "1.4"
|
||||
log = "0.4"
|
||||
mime_guess = "2.0"
|
||||
regex = "1.5"
|
||||
rustls = "0.18"
|
||||
serde = "1.0"
|
||||
sha2 = "0.9"
|
||||
tera = "1.13"
|
||||
rustls = "0.20"
|
||||
rustls-pemfile = "1.0"
|
||||
serde = {version = "1.0", features = ["derive"]}
|
||||
sha2 = "0.10"
|
||||
tera = "1.15"
|
||||
toml = "0.5"
|
||||
urlencoding = "2.1"
|
||||
|
||||
|
179
src/main.rs
179
src/main.rs
@ -2,8 +2,6 @@
|
||||
* 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/. */
|
||||
|
||||
#[macro_use]
|
||||
extern crate clap;
|
||||
#[macro_use]
|
||||
extern crate lazy_static;
|
||||
|
||||
@ -15,6 +13,7 @@ use actix_web::{
|
||||
use clap::Arg;
|
||||
use env_logger::fmt::Color;
|
||||
use log::{error, info};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Digest;
|
||||
use std::{
|
||||
env::{set_var, var},
|
||||
@ -156,23 +155,23 @@ fn get_file_type(from: &Path) -> String {
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[derive(Deserialize)]
|
||||
struct Package {
|
||||
name: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
#[derive(Deserialize)]
|
||||
struct CargoToml {
|
||||
package: Package,
|
||||
}
|
||||
|
||||
#[derive(Eq, Ord, PartialEq, PartialOrd, serde::Serialize)]
|
||||
#[derive(Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
struct Dir {
|
||||
name: String,
|
||||
modified: String,
|
||||
}
|
||||
|
||||
#[derive(Eq, Ord, PartialEq, PartialOrd, serde::Serialize)]
|
||||
#[derive(Eq, Ord, PartialEq, PartialOrd, Serialize)]
|
||||
struct File {
|
||||
name: String,
|
||||
size: u64,
|
||||
@ -180,7 +179,7 @@ struct File {
|
||||
modified: String,
|
||||
}
|
||||
|
||||
#[derive(serde::Serialize)]
|
||||
#[derive(Serialize)]
|
||||
struct IndexContext {
|
||||
title: String,
|
||||
paths: Vec<String>,
|
||||
@ -195,13 +194,9 @@ fn render_index(
|
||||
let mut index = dir.path.clone();
|
||||
index.push("index.html");
|
||||
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)
|
||||
.into_response(req)
|
||||
{
|
||||
Ok(res) => res,
|
||||
Err(e) => return Err(Error::new(ErrorKind::Other, e.to_string())),
|
||||
};
|
||||
.into_response(req);
|
||||
return Ok(ServiceResponse::new(req.clone(), res));
|
||||
}
|
||||
if var("NOINDEX").unwrap_or_else(|_| "false".to_string()) == "true" {
|
||||
@ -381,34 +376,30 @@ async fn main() -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
};
|
||||
let matches = clap::App::new(crate_name!())
|
||||
.version(crate_version!())
|
||||
.author(crate_authors!())
|
||||
.about(crate_description!())
|
||||
.arg(Arg::new("noindex").long("noindex").about("Disable automatic index page generation"))
|
||||
.arg(Arg::new("compress").short('c').long("compress").about("Enable streaming compression (Content-length/segment download will be disabled)"))
|
||||
.arg(Arg::new("nocache").long("nocache").about("Disable HTTP cache"))
|
||||
.arg(Arg::new("nocolor").long("nocolor").about("Disable cli colors"))
|
||||
.arg(Arg::new("cors").long("cors").takes_value(true).min_values(0).max_values(1).about("Enable CORS [with custom value]"))
|
||||
.arg(Arg::new("spa").long("spa").about("Enable Single-Page Application mode (always serve /index.html when the file is not found)"))
|
||||
.arg(Arg::new("dotfiles").short('d').long("dotfiles").about("Show dotfiles"))
|
||||
.arg(Arg::new("open").short('o').long("open").about("Open the page in the default browser"))
|
||||
.arg(Arg::new("quiet").short('q').long("quiet").about("Disable access log output"))
|
||||
.arg(Arg::new("quietall").long("quietall").about("Disable all output"))
|
||||
.arg(Arg::new("ROOT").default_value(".").validator(check_does_dir_exits).about("Root directory"))
|
||||
.arg(Arg::new("address").short('a').long("address").default_value("0.0.0.0").takes_value(true).validator(check_is_ip_addr).about("IP address to serve on"))
|
||||
.arg(Arg::new("port").short('p').long("port").default_value("8000").takes_value(true).validator(check_is_port_num).about("Port to serve on"))
|
||||
.arg(Arg::new("auth").long("auth").takes_value(true).validator(check_is_auth).about("HTTP Auth (username:password)"))
|
||||
.arg(Arg::new("cert").long("cert").takes_value(true).validator(check_does_file_exits).about("Path of TLS/SSL public key (certificate)"))
|
||||
.arg(Arg::new("key").long("key").takes_value(true).validator(check_does_file_exits).about("Path of TLS/SSL private key"))
|
||||
.subcommand(clap::App::new("doc")
|
||||
let matches = clap::command!()
|
||||
.arg(Arg::new("noindex").long("noindex").help("Disable automatic index page generation"))
|
||||
.arg(Arg::new("nocache").long("nocache").help("Disable HTTP cache"))
|
||||
.arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
|
||||
.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"))
|
||||
.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"))
|
||||
.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"))
|
||||
.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(Arg::new("auth").long("auth").takes_value(true).validator(check_is_auth).help("HTTP Auth (username:password)"))
|
||||
.arg(Arg::new("cert").long("cert").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL public key (certificate)"))
|
||||
.arg(Arg::new("key").long("key").takes_value(true).validator(check_does_file_exits).help("Path of TLS/SSL private key"))
|
||||
.subcommand(clap::Command::new("doc")
|
||||
.about("Open cargo doc via local server (Need cargo installation)")
|
||||
.arg(Arg::new("nocolor").long("nocolor").about("Disable cli colors"))
|
||||
.arg(Arg::new("noopen").long("noopen").about("Do not open the page in the default browser"))
|
||||
.arg(Arg::new("log").long("log").about("Enable access log output [default: disabled]"))
|
||||
.arg(Arg::new("quietall").long("quietall").about("Disable all output"))
|
||||
.arg(Arg::new("address").short('a').long("address").default_value("0.0.0.0").takes_value(true).validator(check_is_ip_addr).about("IP address to serve on"))
|
||||
.arg(Arg::new("port").short('p').long("port").default_value("8000").takes_value(true).validator(check_is_port_num).about("Port to serve on"))
|
||||
.arg(Arg::new("nocolor").long("nocolor").help("Disable cli colors"))
|
||||
.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"))
|
||||
.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"))
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
@ -421,7 +412,6 @@ async fn main() -> std::io::Result<()> {
|
||||
set_var("SPA", matches.is_present("spa").to_string());
|
||||
set_var("DOTFILES", matches.is_present("dotfiles").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") {
|
||||
set_var("RUST_LOG", "info,actix_web::middleware::logger=off");
|
||||
@ -444,7 +434,7 @@ async fn main() -> std::io::Result<()> {
|
||||
set_var("ENABLE_CORS", matches.is_present("cors").to_string());
|
||||
match matches.value_of("cors") {
|
||||
Some(str) => {
|
||||
set_var("CORS", str.to_string());
|
||||
set_var("CORS", str);
|
||||
}
|
||||
None => {
|
||||
set_var("CORS", "*");
|
||||
@ -457,11 +447,7 @@ async fn main() -> std::io::Result<()> {
|
||||
.value_of("address")
|
||||
.unwrap_or("127.0.0.1")
|
||||
.to_string();
|
||||
let addr = format!(
|
||||
"{}:{}",
|
||||
ip,
|
||||
matches.value_of("port").unwrap_or("8000").to_string()
|
||||
);
|
||||
let addr = format!("{}:{}", ip, matches.value_of("port").unwrap_or("8000"));
|
||||
let url = format!(
|
||||
"{}{}:{}",
|
||||
if enable_tls {
|
||||
@ -470,7 +456,7 @@ async fn main() -> std::io::Result<()> {
|
||||
"http://".to_string()
|
||||
},
|
||||
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| {
|
||||
@ -549,15 +535,11 @@ async fn main() -> std::io::Result<()> {
|
||||
.value_of("address")
|
||||
.unwrap_or("127.0.0.1")
|
||||
.to_string();
|
||||
let addr = format!(
|
||||
"{}:{}",
|
||||
ip,
|
||||
matches.value_of("port").unwrap_or("8000").to_string()
|
||||
);
|
||||
let addr = format!("{}:{}", ip, matches.value_of("port").unwrap_or("8000"));
|
||||
let url = format!(
|
||||
"http://{}:{}/{}/index.html",
|
||||
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,
|
||||
);
|
||||
if !matches.is_present("noopen") {
|
||||
@ -577,8 +559,9 @@ async fn main() -> std::io::Result<()> {
|
||||
addr
|
||||
};
|
||||
|
||||
let addr_copy = addr.clone();
|
||||
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 mut style = buf.style();
|
||||
let blue = style.set_color(Color::Cyan);
|
||||
@ -589,7 +572,8 @@ async fn main() -> std::io::Result<()> {
|
||||
if record.target() == "actix_web::middleware::logger" {
|
||||
let data: Vec<&str> = data.splitn(5, '^').collect();
|
||||
let time = blue.value(
|
||||
chrono::NaiveDateTime::from_str(data[0])
|
||||
data[0]
|
||||
.parse::<chrono::DateTime<chrono::Utc>>()
|
||||
.unwrap()
|
||||
.format("%Y/%m/%d %H:%M:%S")
|
||||
.to_string(),
|
||||
@ -621,30 +605,27 @@ async fn main() -> std::io::Result<()> {
|
||||
time, ipaddr, status_code, process_time, content
|
||||
);
|
||||
} else if record.target() == "actix_server::builder" {
|
||||
if data.starts_with("SIGINT received, exiting") {
|
||||
return writeln!(buf, "\r{}", green.value("[INFO] SIGINT received, exiting"));
|
||||
// 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_else(|_| ".".to_string()),
|
||||
addr
|
||||
);
|
||||
return writeln!(buf, "\r{}", green.value(data));
|
||||
}
|
||||
if data.starts_with("Starting ") && data.ends_with(" workers") {
|
||||
return Ok(());
|
||||
}
|
||||
} 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]")
|
||||
|| data.starts_with("TLS alert")
|
||||
@ -658,11 +639,6 @@ async fn main() -> std::io::Result<()> {
|
||||
.init();
|
||||
|
||||
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()
|
||||
.wrap_fn(|req, srv| {
|
||||
let paths = PathBuf::from_str(req.path()).unwrap_or_default();
|
||||
@ -678,28 +654,26 @@ async fn main() -> std::io::Result<()> {
|
||||
if var("NOCACHE").unwrap_or_else(|_| "false".to_string()) == "true" {
|
||||
head.headers_mut().insert(
|
||||
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" {
|
||||
let cors = var("CORS").unwrap_or_else(|_| "*".to_string());
|
||||
let cors = http::HeaderValue::from_str(&cors)
|
||||
.unwrap_or_else(|_| http::HeaderValue::from_static("*"));
|
||||
let cors = http::header::HeaderValue::from_str(&cors)
|
||||
.unwrap_or_else(|_| http::header::HeaderValue::from_static("*"));
|
||||
head.headers_mut()
|
||||
.insert(http::header::ACCESS_CONTROL_ALLOW_ORIGIN, cors);
|
||||
}
|
||||
if isdotfile
|
||||
&& var("DOTFILES").unwrap_or_else(|_| "false".to_string()) != "true"
|
||||
{
|
||||
head.status = http::StatusCode::FORBIDDEN;
|
||||
*head.headers_mut() = http::HeaderMap::new();
|
||||
return dev::ResponseBody::Other(actix_web::body::Body::None);
|
||||
return dev::Response::new(http::StatusCode::FORBIDDEN).into_body();
|
||||
}
|
||||
body
|
||||
}))
|
||||
}
|
||||
})
|
||||
.wrap(middleware::Compress::new(compress))
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(middleware::Condition::new(
|
||||
var("ENABLE_AUTH").unwrap_or_else(|_| "false".to_string()) == "true",
|
||||
actix_web_httpauth::middleware::HttpAuthentication::basic(validator),
|
||||
@ -720,7 +694,7 @@ async fn main() -> std::io::Result<()> {
|
||||
&& path.is_file()
|
||||
&& 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));
|
||||
}
|
||||
Ok(ServiceResponse::new(
|
||||
@ -738,10 +712,23 @@ async fn main() -> std::io::Result<()> {
|
||||
let key = &mut BufReader::new(
|
||||
std::fs::File::open(Path::new(matches.value_of("key").unwrap())).unwrap(),
|
||||
);
|
||||
let mut config = rustls::ServerConfig::new(rustls::NoClientAuth::new());
|
||||
let cert_chain = rustls::internal::pemfile::certs(cert).unwrap();
|
||||
let mut keys = rustls::internal::pemfile::pkcs8_private_keys(key).unwrap();
|
||||
config.set_single_cert(cert_chain, keys.remove(0)).unwrap();
|
||||
let cert = rustls_pemfile::certs(cert)
|
||||
.unwrap()
|
||||
.iter()
|
||||
.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)
|
||||
} else {
|
||||
server.bind(addr)
|
||||
|
Reference in New Issue
Block a user