srv/src/main.rs

283 lines
8.9 KiB
Rust
Raw Normal View History

2021-08-03 17:09:59 +00:00
#[macro_use]
extern crate clap;
#[macro_use]
extern crate rocket;
2021-08-01 11:57:26 +00:00
2021-08-03 17:09:59 +00:00
use colored::*;
use rocket::fairing::{Fairing, Info, Kind};
use rocket::{config::TlsConfig, fs::NamedFile};
2021-08-04 14:04:26 +00:00
use rocket_dyn_templates::Template;
2021-08-03 17:09:59 +00:00
use std::net::IpAddr;
use std::path::Path;
2021-08-01 11:57:26 +00:00
use std::str::FromStr;
#[get("/<path..>")]
2021-08-04 14:04:26 +00:00
async fn file_server(path: std::path::PathBuf) -> Option<NamedFile> {
2021-08-12 07:02:03 +00:00
let mut path = Path::new(&std::env::var("ROOT").unwrap_or(".".to_string())).join(path);
2021-08-04 14:04:26 +00:00
if path.is_dir() {
path.push("index.html")
}
2021-08-01 11:57:26 +00:00
NamedFile::open(path).await.ok()
}
2021-08-04 14:04:26 +00:00
#[derive(rocket::serde::Serialize)]
#[serde(crate = "rocket::serde")]
struct IndexContext<'r> {
title: &'r String,
}
2021-08-12 07:02:03 +00:00
#[derive(Responder)]
enum Resp {
#[response(status = 200)]
Index(Template),
#[response(status = 404)]
NotFound(String),
#[response(status = 200)]
File(NamedFile),
}
2021-08-03 17:09:59 +00:00
#[catch(404)]
2021-08-12 07:02:03 +00:00
async fn not_found(request: &rocket::Request<'_>) -> Resp {
let root = std::env::var("ROOT").unwrap_or(".".to_string());
let root = Path::new(&root);
let localpath = request.uri().path().to_string();
let localpath = localpath[1..localpath.len()].to_string();
// Remove the / in front of the path, if the path with / is spliced, the previous path will be ignored
2021-08-12 07:02:03 +00:00
let localpath = &root.join(localpath);
// Single-Page Application support
if root.join("index.html").is_file()
&& std::env::var("SPA").unwrap_or("false".to_string()) == "true"
{
return Resp::File(
NamedFile::open(&root.join("index.html"))
.await
.ok()
.unwrap(),
);
}
if !localpath.is_dir() {
return Resp::NotFound("".to_string());
// Need to have file 404.tera as a placeholder
2021-08-04 14:04:26 +00:00
}
let context = &IndexContext {
title: &"title?".to_string(),
};
2021-08-12 07:02:03 +00:00
Resp::Index(Template::render("index", context))
2021-08-04 14:04:26 +00:00
}
2021-08-03 17:09:59 +00:00
struct Logger {}
#[rocket::async_trait]
impl Fairing for Logger {
fn info(&self) -> Info {
Info {
name: "Logger",
kind: Kind::Liftoff | Kind::Response,
}
}
async fn on_liftoff(&self, rocket: &rocket::Rocket<rocket::Orbit>) {
println!(
"{}",
format!(
2021-08-04 14:04:26 +00:00
"Serving {} on {}{}:{}",
2021-08-03 17:09:59 +00:00
std::env::var("ROOT").unwrap_or("[Get Path Error]".to_string()),
2021-08-04 14:04:26 +00:00
if rocket.config().tls_enabled() {
"https://"
} else {
"http://"
},
2021-08-03 17:09:59 +00:00
rocket.config().address.to_string(),
rocket.config().port.to_string()
)
.bright_green()
);
}
async fn on_response<'r>(
&self,
request: &'r rocket::Request<'_>,
response: &mut rocket::Response<'r>,
) {
2021-08-04 14:04:26 +00:00
println!(
2021-08-03 17:09:59 +00:00
"[{}] {} | {} | {} {}",
chrono::Local::now()
.format("%Y/%m/%d %H:%M:%S")
.to_string()
2021-08-12 07:02:03 +00:00
.bright_blue(),
2021-08-03 17:09:59 +00:00
request
.client_ip()
.unwrap_or(IpAddr::from([0, 0, 0, 0]))
.to_string()
2021-08-12 07:02:03 +00:00
.bright_blue(),
2021-08-03 17:09:59 +00:00
if response.status().code < 400 {
response.status().code.to_string().bright_green()
} else {
response.status().code.to_string().bright_red()
},
request.method().to_string().bright_blue(),
request.uri().to_string().bright_blue()
);
2021-08-04 14:04:26 +00:00
}
}
fn display_path(path: &std::path::Path) -> String {
let root = Path::canonicalize(path).unwrap().display().to_string();
if root.starts_with("\\\\?\\") {
root[4..root.len()].to_string()
} else {
root.to_string()
2021-08-03 17:09:59 +00:00
}
}
2021-08-01 11:57:26 +00:00
#[rocket::main]
async fn main() {
2021-08-03 17:09:59 +00:00
let matches = clap_app!((crate_name!()) =>
2021-08-01 11:57:26 +00:00
(version: crate_version!())
(author: crate_authors!())
(about: crate_description!())
(@arg index: -i --index "Enable automatic index page generation")
(@arg upload: -u --upload "Enable file upload")
(@arg nocache: --nocache "Disable HTTP cache")
(@arg nocolor: --nocolor "Disable cli colors")
(@arg cors: --cors "Enable CORS")
(@arg spa: --spa "Enable Single-Page Application mode (always serve /index.html when the file is not found)")
(@arg open: -o --open "Open the page in the default browser")
(@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")
2021-08-03 17:09:59 +00:00
(@arg address: -a --address +takes_value default_value["127.0.0.1"] {
|s| match IpAddr::from_str(&s) {
2021-08-01 11:57:26 +00:00
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
2021-08-03 17:09:59 +00:00
} "IP address to serve on")
(@arg port: -p --port +takes_value default_value["8000"] {
2021-08-01 11:57:26 +00:00
|s| match s.parse::<u16>() {
Ok(_) => Ok(()),
Err(e) => Err(e.to_string()),
}
2021-08-03 17:09:59 +00:00
} "Port to serve on")
2021-08-01 11:57:26 +00:00
(@arg auth: --auth +takes_value {
|s| {
let parts = s.splitn(2, ':').collect::<Vec<&str>>();
if parts.len() < 2 || parts.len() >= 2 && parts[1].is_empty() {
Err("Password not found".to_owned())
} else if parts[0].is_empty() {
Err("Username not found".to_owned())
} else {
Ok(())
}
}
} "HTTP Auth (username:password)")
(@arg cert: --cert +takes_value {
|s| match std::fs::metadata(s) {
Ok(metadata) => {
if metadata.is_file() {
Ok(())
} else {
Err("Parameter is not a file".to_owned())
}
}
Err(e) => Err(e.to_string()),
}
} "Path of TLS/SSL public key (certificate)")
(@arg key: --key +takes_value {
|s| match std::fs::metadata(s) {
Ok(metadata) => {
if metadata.is_file() {
Ok(())
} else {
Err("Parameter is not a file".to_owned())
}
}
Err(e) => Err(e.to_string()),
}
} "Path of TLS/SSL private key")
)
.get_matches();
2021-08-03 17:09:59 +00:00
2021-08-04 14:04:26 +00:00
std::env::set_var(
"ROOT",
display_path(Path::new(matches.value_of("ROOT").unwrap())),
);
2021-08-03 17:09:59 +00:00
2021-08-12 07:02:03 +00:00
std::env::set_var("SPA", matches.is_present("spa").to_string());
2021-08-03 17:09:59 +00:00
if matches.is_present("nocolor") {
colored::control::set_override(false);
}
let figment = rocket::Config::figment()
.merge((
"address",
IpAddr::from_str(matches.value_of("address").unwrap())
.unwrap_or(IpAddr::from([127, 0, 0, 1])),
))
.merge((
"port",
matches
.value_of("port")
.unwrap()
.parse::<u16>()
.unwrap_or(8000),
))
.merge((
"ident",
2021-08-12 07:02:03 +00:00
std::env::var("WEB_SERVER_NAME").unwrap_or("timpaik'web server".to_string()),
2021-08-03 17:09:59 +00:00
))
.merge(("cli_colors", matches.is_present("color")))
.merge(("log_level", "off"));
let enable_tls = matches.is_present("cert") && matches.is_present("key");
let figment = if enable_tls {
let cert = Path::new(matches.value_of("cert").unwrap());
let key = Path::new(matches.value_of("key").unwrap());
figment.merge(("tls", TlsConfig::from_paths(cert, key)))
} else {
figment
};
if matches.is_present("open") {
2021-08-04 14:04:26 +00:00
let url = format!(
"{}{}:{}",
if enable_tls {
"https://".to_string()
} else {
"http://".to_string()
},
matches.value_of("address").unwrap().to_string(),
matches.value_of("port").unwrap().to_string()
);
2021-08-03 17:09:59 +00:00
if cfg!(target_os = "windows") {
std::process::Command::new("explorer").arg(url).spawn().ok();
} else if cfg!(target_os = "macos") {
std::process::Command::new("open").arg(url).spawn().ok();
} else if cfg!(target_os = "linux") {
std::process::Command::new("xdg-open").arg(url).spawn().ok();
}
}
2021-08-04 14:04:26 +00:00
match rocket::custom(figment)
2021-08-03 17:09:59 +00:00
.attach(Logger {})
2021-08-04 14:04:26 +00:00
.attach(Template::fairing())
.mount("/", routes![file_server])
2021-08-03 17:09:59 +00:00
.register("/", catchers![not_found])
2021-08-01 11:57:26 +00:00
.launch()
.await
2021-08-04 14:04:26 +00:00
{
Ok(_) => {}
Err(e) => {
println!("{}", format!("[Error] {}", e.to_string()).bright_red());
}
};
2021-08-01 11:57:26 +00:00
}