mirror of
https://github.com/ivabus/urouter
synced 2025-06-07 15:50:30 +03:00
Compare commits
2 commits
Author | SHA1 | Date | |
---|---|---|---|
0451d494c5 | |||
653b41a67f |
5 changed files with 91 additions and 82 deletions
14
Cargo.toml
14
Cargo.toml
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "urouter"
|
||||
version = "0.6.0"
|
||||
version = "0.7.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
repository = "https://github.com/ivabus/urouter"
|
||||
|
@ -9,11 +9,11 @@ description = "Small HTTP router"
|
|||
|
||||
[dependencies]
|
||||
rocket = "0.5.0"
|
||||
serde = { version = "1.0.193", features = ["derive"] }
|
||||
serde_json = "1.0.108"
|
||||
serde = { version = "1.0.197", features = ["derive"] }
|
||||
serde_json = "1.0.114"
|
||||
url-escape = "0.1.1"
|
||||
smurf = "0.3.0"
|
||||
clap = { version = "4.4.11", features = ["derive"] }
|
||||
regex = "1.10.2"
|
||||
ureq = { version = "2.9.1", features = ["brotli", "native-certs"] }
|
||||
once_cell = "1.19"
|
||||
clap = { version = "4.5.3", features = ["derive"] }
|
||||
regex = "1.10.3"
|
||||
ureq = { version = "2.9.6", features = ["brotli", "native-certs"] }
|
||||
users = "0.11.0"
|
|
@ -21,6 +21,7 @@ Each set contains 2 necessary elements and 1 optional.
|
|||
- `url` (string) - redirect to URL with HTTP 303 See Other
|
||||
- `file` (string) - read file from path `--dir/file` where `--dir` is option (default: `.`, see `--help`) and respond with HTTP 200 OK with `content-type: text/plain`
|
||||
- `text` (string) - plain text with HTTP 200 OK with `content-type: text/plain`
|
||||
- `html` (string) - plain text with HTTP 200 OK with `content-type: text/html`
|
||||
- `external` (set) - download (every time) file using `ureq` HTTP library and response with contents of downloaded resource with HTTP 200 OK and extracted `content-type` from response
|
||||
- `url` (string) - URL to download
|
||||
- `headers` (set, optional) - headers to include with request
|
||||
|
|
|
@ -17,7 +17,7 @@
|
|||
{
|
||||
"uri":"text",
|
||||
"alias": {
|
||||
"text": "sometext"
|
||||
"html": "sometext"
|
||||
},
|
||||
"agent": {
|
||||
"regex": "^curl/[0-9].[0-9].[0-9]$",
|
||||
|
|
137
src/main.rs
137
src/main.rs
|
@ -6,27 +6,62 @@ Global comments:
|
|||
500 Internal Server Error
|
||||
*/
|
||||
|
||||
#![forbid(unsafe_code)]
|
||||
|
||||
mod structs;
|
||||
use structs::*;
|
||||
|
||||
#[macro_use]
|
||||
extern crate rocket;
|
||||
|
||||
use rocket::http::{ContentType, Status};
|
||||
use std::{
|
||||
cell::OnceCell, collections::HashMap, hint::unreachable_unchecked, path::PathBuf, time::Instant,
|
||||
};
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::{collections::HashMap, path::PathBuf, time::Instant};
|
||||
|
||||
use rocket::http::{ContentType, Status};
|
||||
use rocket::{
|
||||
figment::Figment,
|
||||
response::{content::RawText, Redirect},
|
||||
response::{content::RawHtml, content::RawText, Redirect},
|
||||
};
|
||||
|
||||
use clap::Parser;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
|
||||
static mut ALIAS: OnceCell<Vec<Alias>> = OnceCell::new();
|
||||
static mut COMPILED_REGEXES: OnceCell<HashMap<String, Regex>> = OnceCell::new();
|
||||
static ALIAS: Lazy<Arc<Vec<Alias>>> = Lazy::new(|| {
|
||||
let mut args = Args::parse();
|
||||
if args.alias_file.is_none() {
|
||||
args.alias_file = Some(get_config_file_location());
|
||||
}
|
||||
|
||||
let file = std::fs::File::open(args.alias_file.unwrap()).unwrap();
|
||||
let alias: Vec<Alias> = if args.alias_file_is_set_not_a_list {
|
||||
serde_json::from_reader::<std::fs::File, NixJson>(file).unwrap().alias
|
||||
} else {
|
||||
serde_json::from_reader::<std::fs::File, Vec<Alias>>(file).unwrap()
|
||||
};
|
||||
Arc::new(alias)
|
||||
});
|
||||
static COMPILED_REGEXES: Lazy<Arc<HashMap<String, Regex>>> = Lazy::new(|| {
|
||||
let compilation_start = Instant::now();
|
||||
let mut regexes_len = 0;
|
||||
// Precompile all regexes
|
||||
let mut compiled_regexes: HashMap<String, Regex> = HashMap::new();
|
||||
for i in &**ALIAS {
|
||||
if let Some(agent) = &i.agent {
|
||||
compiled_regexes.insert(agent.regex.clone(), Regex::new(&agent.regex).unwrap());
|
||||
regexes_len += 1;
|
||||
}
|
||||
}
|
||||
if regexes_len != 0 {
|
||||
println!(
|
||||
"Compiled {} regexes in {} ms",
|
||||
regexes_len,
|
||||
(Instant::now() - compilation_start).as_secs_f64() * 1000.0
|
||||
);
|
||||
}
|
||||
Arc::new(compiled_regexes)
|
||||
});
|
||||
|
||||
fn get_return(alias: &Alias) -> Response {
|
||||
let args = Args::parse();
|
||||
|
@ -35,9 +70,10 @@ fn get_return(alias: &Alias) -> Response {
|
|||
AliasType::Url(url) => Response::Redirect(Box::from(Redirect::to(url.clone()))),
|
||||
AliasType::File(path) => {
|
||||
dir.push(&PathBuf::from(&path));
|
||||
Response::Text(Box::new(RawText(smurf::io::read_file_str(&dir).unwrap())))
|
||||
Response::Text(Box::new(RawText(std::fs::read_to_string(&dir).unwrap())))
|
||||
}
|
||||
AliasType::Text(text) => Response::Text(Box::new(RawText(text.clone()))),
|
||||
AliasType::Html(html) => Response::Html(Box::new(RawHtml(html.clone()))),
|
||||
AliasType::External(source) => {
|
||||
let mut request = ureq::get(&source.url);
|
||||
for (header, value) in &source.headers {
|
||||
|
@ -57,19 +93,12 @@ fn get_return(alias: &Alias) -> Response {
|
|||
fn get_page(page: &str, user_agent: UserAgent) -> Response {
|
||||
let mut decoded_page = String::new();
|
||||
url_escape::decode_to_string(page, &mut decoded_page);
|
||||
let alias = unsafe { ALIAS.get().unwrap() };
|
||||
let mut pages = Vec::new();
|
||||
for i in alias {
|
||||
for i in &**ALIAS {
|
||||
if i.uri == decoded_page {
|
||||
if let Some(agent) = &i.agent {
|
||||
unsafe {
|
||||
let regexes = COMPILED_REGEXES.get_mut();
|
||||
let re = if let Some(r) = regexes {
|
||||
// Unwrapping safely, guaranteed to be generated during initialization
|
||||
r.get(&agent.regex).unwrap()
|
||||
} else {
|
||||
unreachable_unchecked()
|
||||
};
|
||||
let regexes = &COMPILED_REGEXES;
|
||||
let re = regexes.get(&agent.regex).unwrap();
|
||||
|
||||
if re.is_match(&user_agent.0) {
|
||||
return get_return(i);
|
||||
|
@ -79,7 +108,7 @@ fn get_page(page: &str, user_agent: UserAgent) -> Response {
|
|||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pages.push(i);
|
||||
}
|
||||
}
|
||||
|
@ -95,55 +124,31 @@ async fn index(user_agent: UserAgent) -> Response {
|
|||
get_page("/", user_agent)
|
||||
}
|
||||
|
||||
fn get_config_file_location() -> PathBuf {
|
||||
if users::get_effective_uid() == 0 {
|
||||
return "/etc/urouter/alias.json".parse().unwrap();
|
||||
}
|
||||
|
||||
if let Ok(config_home) = std::env::var("XDG_CONFIG_HOME") {
|
||||
return format!("{}/urouter/alias.json", config_home).parse().unwrap();
|
||||
}
|
||||
|
||||
if let Ok(home) = std::env::var("HOME") {
|
||||
return format!("{}/.config/urouter/alias.json", home).parse().unwrap();
|
||||
}
|
||||
|
||||
if !std::path::Path::new("alias.json").exists() {
|
||||
let mut file = std::fs::File::create("alias.json").unwrap();
|
||||
file.write_all(b"[]").unwrap();
|
||||
}
|
||||
"alias.json".parse().unwrap()
|
||||
}
|
||||
|
||||
#[rocket::main]
|
||||
async fn main() -> Result<(), rocket::Error> {
|
||||
let mut args = Args::parse();
|
||||
args.alias_file = match args.alias_file {
|
||||
Some(f) => Some(f),
|
||||
None => Some(
|
||||
match users::get_effective_uid() {
|
||||
0 => "/etc/urouter/alias.json".to_string(),
|
||||
_ => match std::env::var("XDG_CONFIG_HOME") {
|
||||
Ok(config_home) => format!("{}/urouter/alias.json", config_home),
|
||||
Err(_) => match std::env::var("HOME") {
|
||||
Ok(home) => format!("{}/.config/urouter/alias.json", home),
|
||||
Err(_) => {
|
||||
panic!("Could not get config location, see README")
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
.into(),
|
||||
),
|
||||
};
|
||||
let file = std::fs::File::open(args.alias_file.unwrap()).unwrap();
|
||||
let alias: Vec<Alias> = if args.alias_file_is_set_not_a_list {
|
||||
serde_json::from_reader::<std::fs::File, NixJson>(file).unwrap().alias
|
||||
} else {
|
||||
serde_json::from_reader::<std::fs::File, Vec<Alias>>(file).unwrap()
|
||||
};
|
||||
unsafe {
|
||||
ALIAS.set(alias).unwrap();
|
||||
|
||||
let compilation_start = Instant::now();
|
||||
let mut regexes_len = 0;
|
||||
// Precompile all regexes
|
||||
let mut compiled_regexes: HashMap<String, Regex> = HashMap::new();
|
||||
for i in ALIAS.get().unwrap() {
|
||||
if let Some(agent) = &i.agent {
|
||||
compiled_regexes.insert(agent.regex.clone(), Regex::new(&agent.regex).unwrap());
|
||||
regexes_len += 1;
|
||||
}
|
||||
}
|
||||
if regexes_len != 0 {
|
||||
println!(
|
||||
"Compiled {} regexes in {} ms",
|
||||
regexes_len,
|
||||
(Instant::now() - compilation_start).as_secs_f64() * 1000.0
|
||||
);
|
||||
}
|
||||
COMPILED_REGEXES.set(compiled_regexes).unwrap();
|
||||
}
|
||||
let args = Args::parse();
|
||||
let _alias = &**ALIAS;
|
||||
let _regex = &**COMPILED_REGEXES;
|
||||
|
||||
let figment = Figment::from(rocket::Config::default())
|
||||
.merge(("ident", format!("urouter/{}", env!("CARGO_PKG_VERSION"))))
|
||||
|
|
|
@ -3,7 +3,7 @@
|
|||
use clap::Parser;
|
||||
use rocket::http::{ContentType, Status};
|
||||
use rocket::request::{FromRequest, Outcome};
|
||||
use rocket::response::content::RawText;
|
||||
use rocket::response::content::{RawHtml, RawText};
|
||||
use rocket::response::{Redirect, Responder};
|
||||
use rocket::Request;
|
||||
use serde::Deserialize;
|
||||
|
@ -53,6 +53,8 @@ pub enum AliasType {
|
|||
File(String),
|
||||
#[serde(alias = "text")]
|
||||
Text(String),
|
||||
#[serde(alias = "html")]
|
||||
Html(String),
|
||||
#[serde(alias = "external")]
|
||||
External(External),
|
||||
}
|
||||
|
@ -73,6 +75,7 @@ pub struct External {
|
|||
#[derive(Responder)]
|
||||
pub enum Response {
|
||||
Text(Box<RawText<String>>),
|
||||
Html(Box<RawHtml<String>>),
|
||||
Redirect(Box<Redirect>),
|
||||
Status(Status),
|
||||
Custom(Box<(ContentType, RawText<String>)>),
|
||||
|
|
Loading…
Reference in a new issue