85 lines
2 KiB
Rust
85 lines
2 KiB
Rust
|
use blocking::unblock;
|
||
|
use futures_lite::*;
|
||
|
use once_cell::sync::Lazy;
|
||
|
use sled::Db;
|
||
|
|
||
|
include!(concat!(env!("OUT_DIR"), "/templates.rs"));
|
||
|
|
||
|
mod iptables;
|
||
|
mod rules;
|
||
|
mod startup;
|
||
|
|
||
|
use self::{rules::Rule, startup::Interfaces};
|
||
|
|
||
|
static INTERFACES: Lazy<Interfaces> = Lazy::new(|| {
|
||
|
let interfaces = Interfaces::init_blocking().unwrap();
|
||
|
interfaces.reset_blocking().unwrap();
|
||
|
interfaces
|
||
|
});
|
||
|
|
||
|
static DB: Lazy<Db> = Lazy::new(|| sled::open("router-db-0-34-3").unwrap());
|
||
|
|
||
|
async fn rules_page(_: tide::Request<()>) -> tide::Result {
|
||
|
let mut html = Vec::new();
|
||
|
|
||
|
let rules = unblock(move || rules::read(&DB)).await?;
|
||
|
|
||
|
templates::rules(&mut html, &rules)?;
|
||
|
|
||
|
Ok(tide::Response::builder(200)
|
||
|
.body(html)
|
||
|
.content_type(
|
||
|
"text/html;charset=utf-8"
|
||
|
.parse::<tide::http::Mime>()
|
||
|
.unwrap(),
|
||
|
)
|
||
|
.build())
|
||
|
}
|
||
|
|
||
|
async fn save_rule(mut req: tide::Request<()>) -> tide::Result {
|
||
|
let rule: Rule = req.body_form().await?;
|
||
|
|
||
|
rules::save(&DB, &rule)?;
|
||
|
rules::apply(&INTERFACES, rule).await?;
|
||
|
|
||
|
Ok(to_rules_page())
|
||
|
}
|
||
|
|
||
|
async fn delete_rule(req: tide::Request<()>) -> tide::Result {
|
||
|
let id = req.param("id")?;
|
||
|
let rule = rules::delete(&DB, id)?;
|
||
|
rules::unset(&INTERFACES, rule).await?;
|
||
|
|
||
|
Ok(to_rules_page())
|
||
|
}
|
||
|
|
||
|
fn to_rules_page() -> tide::Response {
|
||
|
tide::Response::builder(301)
|
||
|
.header("Location", "/rules")
|
||
|
.build()
|
||
|
}
|
||
|
|
||
|
fn main() -> Result<(), anyhow::Error> {
|
||
|
future::block_on(async {
|
||
|
println!("Hello, world!");
|
||
|
|
||
|
rules::apply_all(&DB, &INTERFACES).await?;
|
||
|
|
||
|
let mut app = tide::new();
|
||
|
app.at("/rules").get(rules_page).post(save_rule);
|
||
|
app.at("/rules/:id").delete(delete_rule);
|
||
|
|
||
|
let listeners: Vec<String> = INTERFACES
|
||
|
.internal
|
||
|
.iter()
|
||
|
.map(|info| format!("{}:8080", info.ip))
|
||
|
.collect();
|
||
|
|
||
|
app.listen(listeners).await?;
|
||
|
|
||
|
Ok(()) as Result<(), anyhow::Error>
|
||
|
})?;
|
||
|
|
||
|
Ok(())
|
||
|
}
|