big day for the unemployed.

add json get with errors.
add home_2 by copilot it looks so good.
add more routes.
delete ass code; produce just as ass code.
add more ideas from copilot?
linting.
This commit is contained in:
lda committed 2025-08-23 23:14:13 +07:00
1 parent 0fb1acd61a
commit 1e5bdfc225
7 files changed
+863 -78

No files matched your search

+37 -11
View File
@@ -11,6 +11,8 @@
use std::{net::IpAddr, str::FromStr};
use macaddr::MacAddr;
use serde::{Deserialize, Serialize, Serializer, de};
use serde_with::skip_serializing_none;
use strum::{Display, EnumString};
use crate::arpparse::error::IPNeighParseError;
@@ -22,19 +24,35 @@ mod error;
/// status { permanent | noarp | stale | reachable | none | incomplete | delay | probe | failed } (ip neigh help)
/// so you can see its damn good
///
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[skip_serializing_none]
#[derive(Debug, PartialEq, Eq, Clone, Hash, serde::Serialize)]
pub struct IpNeighLine {
pub ip: IpAddr,
pub dev: Option<String>,
/// link layer address
#[serde(serialize_with = "ser_opm")]
pub mac: Option<MacAddr>,
/// Neighbour Unreachability Detection
pub state: NUDState,
}
#[derive(Debug, PartialEq, Eq, EnumString, Display, Clone, Copy, Hash)]
pub fn ser_opm<S: Serializer>(bro: &Option<MacAddr>, ser: S) -> Result<S::Ok, S::Error> {
Option::<String>::serialize(&bro.as_ref().map(ToString::to_string), ser)
}
pub fn des_opm<'de, D>(des: D) -> Result<Option<MacAddr>, D::Error>
where
D: serde::Deserializer<'de>,
{
Option::<&str>::deserialize(des)?
.map(MacAddr::from_str)
.transpose()
.map_err(de::Error::custom)
}
#[derive(Debug, PartialEq, Eq, EnumString, Display, Clone, Copy, Hash, serde::Serialize)]
#[strum(serialize_all = "UPPERCASE")]
#[serde(rename_all = "UPPERCASE")]
pub enum NUDState {
/// the neighbour entry is valid forever and can
/// be only be removed administratively.
@@ -144,15 +162,19 @@ impl IpNeighLine {
pub fn set_ip(&mut self, ip: IpAddr) {
self.ip = ip;
}
pub fn set_state(&mut self, ip: IpAddr) {
self.ip = ip;
pub fn set_state(&mut self, state: NUDState) {
self.state = state;
}
pub fn ip(self, ip: IpAddr) -> Self {
Self { ip, ..self }
}
pub fn state(self, state: NUDState) -> Self {
Self { state, ..self }
}
}
// ideas from copilot:
impl NUDState {
// higher is "better"/more online
pub const fn rank(self) -> u8 {
@@ -184,9 +206,13 @@ impl IpNeighLine {
.dev
.as_deref()
.map(|d| {
if d.starts_with("br") || d.starts_with("lan") || d.starts_with("eth") { 2 }
else if d.starts_with("wlan") || d.starts_with("wl") { 1 }
else { 0 }
if d.starts_with("br") || d.starts_with("lan") || d.starts_with("eth") {
2
} else if d.starts_with("wlan") || d.starts_with("wl") {
1
} else {
0
}
})
.unwrap_or(0);
(
@@ -196,4 +222,4 @@ impl IpNeighLine {
iface,
)
}
}
}
+18 -8
View File
@@ -1,8 +1,9 @@
use axum::{Router, response::Html, routing::get};
use tokio::net::TcpListener;
mod arpparse;
mod route;
mod utils;
use route::*;
use utils::*;
const MACHINE_NAME: &str = "lda.lan";
async fn home() -> Html<String> {
@@ -30,7 +31,7 @@ async fn home() -> Html<String> {
))
}
async fn wake_handler() -> axum::response::Result< &'static str> {
async fn wake_handler() -> axum::response::Result<&'static str> {
match wake(MACHINE_NAME).await {
Ok(x) if x > 0 => Ok("Packet sent!"),
_ => Err("Wake failed".into()),
@@ -55,7 +56,11 @@ async fn status() -> Html<String> {
// }
// Err(e) => format!("<p>error getting ips: {e}</p>"),
// };
let formatted_macs = match get_macs_2_1(MACHINE_NAME).await {
Html(status_build(MACHINE_NAME).await)
}
pub async fn status_build(machine_name: &str) -> String {
let formatted_macs = match get_macs_2_1(machine_name).await {
Ok(table) => {
let the: String = table
.iter()
@@ -73,17 +78,17 @@ async fn status() -> Html<String> {
})
.collect();
format!(
r#"<p>info of {MACHINE_NAME}:</p>
r#"<p>info of {machine_name}:</p>
<table>
<tr><th>IP</th><th>MAC</th><th>State</th></tr>
{the}
</table>"#
)
}
Err(e) => format!("<p>errors getting table for {MACHINE_NAME}: {e}</p>"),
Err(e) => format!("<p>errors getting table for {machine_name}: {e}</p>"),
};
Html(format!(
format!(
r#"
<html>
<body>
@@ -91,7 +96,7 @@ async fn status() -> Html<String> {
</body>
</html>
"#,
))
)
}
#[cfg(target_os = "linux")]
#[tokio::main]
@@ -99,8 +104,13 @@ async fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
let app = Router::new()
.route("/", get(home))
.route("/home_2", get(home_2))
.route("/wake", axum::routing::post(wake_handler))
.route("/status", get(status));
// .route("/wake", axum::routing::post(wake_handler))
// .route("/status", get(status))
.route("/status", get(get_status_2))
.route("/api/status/{name}", get(get_status_json))
;
let port = TcpListener::bind("0.0.0.0:12012").await?;
axum::serve(port, app.into_make_service()).await?;
+64
View File
@@ -0,0 +1,64 @@
use axum::{
Json,
extract::{Path, Query},
http::StatusCode,
response::{Html, IntoResponse},
};
use crate::{MACHINE_NAME, arpparse, status_build, utils::get_macs_1};
pub async fn home_2() -> Html<&'static str> {
Html(include_str!("../static/home_2"))
}
#[derive(Debug, Default, Clone, Hash, serde::Deserialize)]
pub struct DeviceQuery {
name: Option<String>,
// ip: Option<IpAddr>,
// #[serde(deserialize_with = "des_opm")]
// mac: Option<MacAddr>,
}
#[derive(Debug, Default, Clone, Hash, serde::Deserialize)]
pub struct NamePath {
name: String,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct Status {
name: String,
table: Vec<arpparse::IpNeighLine>,
}
#[derive(Debug, serde::Serialize)]
pub struct StatusError {
name: String,
error: String,
}
// pub struct statuserror? table? and error? on status? what is the strat here
pub async fn get_status_json(p: Option<Path<NamePath>>) -> impl IntoResponse {
let name = match p {
Some(Path(NamePath { name })) => name,
_ => MACHINE_NAME.to_owned(),
};
match get_macs_1(&name).await {
Ok(table) => (StatusCode::OK, Json(Status { name, table })).into_response(),
Err(error) => (
StatusCode::BAD_GATEWAY,
Json(StatusError {
name,
error: error.to_string(),
}),
)
.into_response(), // holy clutch. Couldve been disasterous
}
}
pub async fn get_status_2(q: Query<DeviceQuery>) -> Html<String> {
let name = match q {
Query(DeviceQuery {
name: Some(name), ..
}) => name,
_ => MACHINE_NAME.to_string(),
};
Html(status_build(&name).await)
}
+6 -56
View File
@@ -33,7 +33,7 @@ pub async fn wake(machine_name: &str) -> io::Result<u32> {
}
Ok(sent_ok)
}
use std::{collections::HashSet, iter, net::IpAddr, str::FromStr, sync::LazyLock, time::Duration};
use std::{collections::HashSet, net::IpAddr, sync::LazyLock, time::Duration};
use macaddr::MacAddr;
use tokio::{
@@ -62,44 +62,17 @@ pub async fn get_ips(machine_name: &str) -> io::Result<Vec<IpAddr>> {
.map(|c| c.ip())
.collect())
}
// not used lets go
pub async fn get_macs(machine_name: &str) -> io::Result<Vec<(IpAddr, MacAddr)>> {
let ips = get_ips(machine_name).await?;
let futures = ips
.iter()
// .filter(|f| f.is_ipv4())
.map(|ip| {
let ip = ip.to_canonical();
async move {
let o = exec_command("ip", ["neigh", "show", "to", &ip.to_string(), "dev", "br-lan"])
.await
.ok()?;
o.status.success().then(|| {
let stdout = String::from_utf8_lossy(&o.stdout);
stdout
.lines()
.filter_map(|line| {
let mut parts = line.split_whitespace();
parts.find(|&x| x == "lladdr")?;
parts
.next()
.and_then(|mac| MacAddr::from_str(mac).ok()) // 100% correct because its ip neigh brother they know how to code.
.map(|mac| (ip, mac))
})
.collect::<Vec<_>>()
})
}
});
let results = futures::future::join_all(futures).await;
Ok(results.into_iter().flatten().flatten().collect())
}
pub async fn get_macs_1(machine_name: &str) -> io::Result<Vec<arpparse::IpNeighLine>> {
let ips = get_ips(machine_name).await?;
let futures = ips.iter().map(|ip| {
let ip = ip.to_canonical();
async move {
let o = exec_command("ip", ["neigh", "show", "to", &ip.to_string(), "dev", "br-lan"]).await?;
let o = exec_command(
"ip",
["neigh", "show", "to", &ip.to_string(), "dev", "br-lan"],
)
.await?;
if !o.status.success() {
return Err(io::Error::other(format!(
"`ip neigh` failed for {ip} (status: {st}): {err}",
@@ -130,10 +103,6 @@ async fn exec_command<S: AsRef<std::ffi::OsStr>>(
u.output().await
}
pub async fn get_macs_2(machine_name: &str) -> io::Result<HashSet<(IpAddr, MacAddr)>> {
Ok(get_macs(machine_name).await?.into_iter().collect())
}
pub async fn get_macs_2_1(machine_name: &str) -> io::Result<HashSet<(IpAddr, MacAddr, NUDState)>> {
Ok(get_macs_1(machine_name)
.await?
@@ -162,22 +131,3 @@ pub async fn get_macs_2_mac(machine_name: &str) -> io::Result<HashSet<MacAddr>>
)
.collect())
}
pub fn to_arr(macstr: &str) -> Option<[u8; 6]> {
let mut this = [0u8; 6];
let c: Vec<_> = macstr.split(':').collect();
(c.len() == 6).then(|| {
for (n, h) in this.iter_mut().zip(c) {
*n = u8::from_str_radix(h, 16).ok()?;
}
Some(this)
})?
}
pub fn back_to_str(thing: &[u8; 6]) -> String {
thing
.iter()
.map(|n| format!("{n:02x}"))
.collect::<Vec<String>>()
.join(":")
}