big day for the unemployed 2

we have uhhhh some shuffling around of the Shits
support of multiple queries (thanks copilot)
more idk
This commit is contained in:
lda committed 2025-08-25 00:39:25 +07:00
1 parent 9346349b43
commit a3c91ae288
15 files changed
+380 -42

No files matched your search

+23 -4
View File
@@ -12,11 +12,12 @@ use std::{net::IpAddr, str::FromStr};
use macaddr::MacAddr;
use serde::{Deserialize, Serialize, Serializer, de};
use serde_with::skip_serializing_none;
use serde_with::skip_serializing_none ;
use strum::{Display, EnumString};
use crate::arpparse::error::IPNeighParseError;
mod error;
mod r#impl; // custom (de)serialization impls
/// ip neigh has some cool shit.
/// IP
/// dev DEV | None
@@ -32,26 +33,30 @@ pub struct IpNeighLine {
/// link layer address
#[serde(serialize_with = "ser_opm")]
pub mac: Option<MacAddr>,
/// Neighbour Unreachability Detection
/// Neighbour Unreachability Detection
pub state: NUDState,
}
/// serialize an [`Option<MacAddr>`]
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)
}
/// deserialize an [`Option<MacAddr>`]
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)
.map(str::parse)
.transpose()
.map_err(de::Error::custom)
}
// NUDState custom Deserialize now lives in arpparse/impl.rs; use serde_with OneOrMany for Vec
#[derive(Debug, PartialEq, Eq, EnumString, Display, Clone, Copy, Hash, serde::Serialize)]
#[strum(serialize_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE", ascii_case_insensitive)]
#[serde(rename_all = "UPPERCASE")]
pub enum NUDState {
/// the neighbour entry is valid forever and can
@@ -92,6 +97,20 @@ pub enum NUDState {
}
impl NUDState {
/// Argument form expected by `ip neigh ... nud <state>` (lowercase)
pub const fn as_ip_neigh_arg(self) -> &'static str {
match self {
NUDState::Permanent => "permanent",
NUDState::Reachable => "reachable",
NUDState::Stale => "stale",
NUDState::Delay => "delay",
NUDState::Probe => "probe",
NUDState::Incomplete => "incomplete",
NUDState::Noarp => "noarp",
NUDState::None => "none",
NUDState::Failed => "failed",
}
}
/// dumb UI label
pub fn dumber_state(&self) -> &'static str {
match self {
+14
View File
@@ -0,0 +1,14 @@
use serde::{Deserialize, Deserializer, de};
use super::NUDState;
// Case-insensitive parsing for NUDState via manual Deserialize
impl<'de> Deserialize<'de> for NUDState {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = <&str as Deserialize>::deserialize(deserializer)?;
s.parse().map_err(de::Error::custom)
}
}
+13 -5
View File
@@ -7,12 +7,15 @@ use axum::{
};
use tokio::net::TcpListener;
mod arpparse;
mod route;
mod r#static;
mod utils;
mod route;
use crate::{
route::DeviceQuery,
utils::{ping::ping_ip, query::get_macs_2_1, wake::wake},
};
use r#static as st;
const MACHINE_NAME: &str = "lda.lan";
@@ -110,9 +113,14 @@ async fn main() -> color_eyre::Result<()> {
}
#[cfg(not(target_os = "linux"))]
fn main() {
use std::process::exit;
fn main() -> color_eyre::Result<()> {
color_eyre::install()?;
eprintln!("OS not supported! run this on your ahh router!");
exit(1)
// use crate::arpparse::NUDState;
// println!("{}", NUDState::Reachable.to_string().to_lowercase());
// println!("{:?}", std::net::TcpStream::connect("svuhuvshdv:331"));
// // Err(Os { code: 11001, kind: Uncategorized, message: "No such host is known." })
Err(color_eyre::eyre::eyre!(
"OS not supported! run this on your ahh router!"
))
}
+88 -17
View File
@@ -2,17 +2,28 @@ use std::net::IpAddr;
use axum::{
Json, Router,
extract::{Path, Query},
extract::Path,
http::{StatusCode, header},
response::{Html, IntoResponse, Redirect},
routing::get,
};
use axum_extra::extract::Query;
use macaddr::MacAddr;
use serde_with::skip_serializing_none;
use crate::{MACHINE_NAME, arpparse::{self, des_opm}, status_build, utils::query::get_macs_1};
// use serde_with::skip_serializing_none;
// use serde::{Deserialize, de};
// use serde_with::{OneOrMany, serde_as};
use crate::{
MACHINE_NAME,
arpparse::{self, NUDState, des_opm},
st, status_build,
utils::{de_many, query::get_macs},
};
pub async fn home_2() -> Html<&'static str> {
Html(include_str!("../static/home_2"))
Html(st::HOME_2)
}
async fn home_2_css() -> impl IntoResponse {
(
@@ -20,7 +31,7 @@ async fn home_2_css() -> impl IntoResponse {
(header::CONTENT_TYPE, "text/css; charset=utf-8"),
(header::CACHE_CONTROL, "public, max-age=300"),
],
include_str!("../static/assets/home_2.css"),
st::HOME_2_CSS,
)
}
async fn home_2_js() -> impl IntoResponse {
@@ -29,7 +40,7 @@ async fn home_2_js() -> impl IntoResponse {
(header::CONTENT_TYPE, "application/javascript"),
(header::CACHE_CONTROL, "public, max-age=300"),
],
include_str!("../static/assets/home_2.js"),
st::HOME_2_JS,
)
}
@@ -44,42 +55,102 @@ pub fn home_2_route() -> Router {
#[derive(Debug, Default, Clone, Hash, serde::Deserialize)]
pub struct DeviceQuery {
pub name: Option<String>,
ip: Option<IpAddr>,
// Accept single or many; ignore blanks
#[serde(default, deserialize_with = "de_many::vec_from_strs")]
ip: Vec<IpAddr>,
#[serde(default, deserialize_with = "des_opm")]
mac: Option<MacAddr>,
/// optional interface filter (e.g., br-lan)
#[serde(default, deserialize_with = "de_many::vec_from_strs")]
pub dev: Vec<String>,
/// optional NUD state filter; accepts any case (e.g., reachable, REACHABLE)
#[serde(default, deserialize_with = "de_many::vec_from_strs")]
pub nud: Vec<NUDState>,
}
#[derive(Debug, Default, Clone, Hash, serde::Deserialize)]
pub struct NamePath {
name: String,
}
#[skip_serializing_none]
#[derive(Debug, Default, serde::Serialize)]
pub struct Status {
name: String,
name: Option<String>,
table: Vec<arpparse::IpNeighLine>,
filters: Filters,
}
#[derive(Debug, Default, serde::Serialize)]
pub struct Filters {
#[serde(skip_serializing_if = "Vec::is_empty")]
ip: Vec<IpAddr>,
#[serde(skip_serializing_if = "Vec::is_empty")]
dev: Vec<String>,
#[serde(skip_serializing_if = "Vec::is_empty")]
nud: Vec<NUDState>,
}
#[skip_serializing_none]
#[derive(Debug, serde::Serialize)]
pub struct StatusError {
name: String,
name: Option<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>>,
Query(DeviceQuery { name, .. }): Query<DeviceQuery>,
Query(DeviceQuery {
name, ip, dev, nud, ..
}): Query<DeviceQuery>,
) -> impl IntoResponse {
let name = /* p
.map(|Path(n)| n.name)
.or */(name)
.unwrap_or_else(|| MACHINE_NAME.to_owned());
match get_macs_1(&name).await {
fn to_opts<T: Clone>(slice: &[T]) -> Vec<Option<T>> {
if slice.is_empty() {
vec![None]
} else {
slice.iter().cloned().map(Some).collect()
}
}
/* let name = /* p
.map(|Path(n)| n.name)
.or */(name)
// .unwrap_or_else(|| MACHINE_NAME.to_owned())
; */
// ip/dev/nud already parsed; assemble options
let ips_opt = if ip.is_empty() {
None
} else {
Some(ip.clone())
};
let dev_opts: Vec<Option<String>> = to_opts(&dev);
let nud_opts: Vec<Option<NUDState>> = to_opts(&nud);
let filters = Filters { ip, dev, nud };
// Run combinations of dev/nud and merge results
let mut tasks = Vec::new();
for d in &dev_opts {
for n in &nud_opts {
tasks.push(get_macs(
name.as_deref(),
ips_opt.as_deref(),
d.as_deref(),
*n,
));
}
}
match futures::future::try_join_all(tasks)
.await
.map(|v| v.into_iter().flatten().collect::<Vec<_>>())
{
Ok(table) => {
// let canonical = format!("/api/status?name={name}");
(
StatusCode::OK,
// [(header::LINK, format!("<{canonical}>; rel=\"canonical\""))],
Json(Status { name, table }),
Json(Status {
name,
table,
filters,
}),
)
.into_response()
}
+3
View File
@@ -0,0 +1,3 @@
pub const HOME_2: &str = include_str!("../static/home_2");
pub const HOME_2_CSS: &str = include_str!("../static/assets/home_2.css");
pub const HOME_2_JS: &str = include_str!("../static/assets/home_2.js");
+43
View File
@@ -27,3 +27,46 @@ pub async fn get_ips(machine_name: &str) -> io::Result<Vec<IpAddr>> {
pub mod cmd;
pub mod query;
mod error;
// no custom ip deserializer needed when using axum_extra::extract::Query
// but we add a generic one to ignore blanks and accept OneOrMany
pub mod de_many {
use serde::Deserialize;
use serde::de;
#[derive(Deserialize)]
#[serde(untagged)]
enum OneOrMany<T> {
One(T),
Many(Vec<T>),
}
pub fn vec_from_strs<'de, D, T>(des: D) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: std::str::FromStr,
T::Err: std::fmt::Display,
{
let raw: OneOrMany<String> = OneOrMany::<String>::deserialize(des)?;
let mut out = Vec::new();
match raw {
OneOrMany::One(s) => {
let t = s.trim();
if !t.is_empty() {
out.push(t.parse().map_err(de::Error::custom)?);
}
}
OneOrMany::Many(vs) => {
for s in vs {
let t = s.trim();
if t.is_empty() {
continue;
}
out.push(t.parse().map_err(de::Error::custom)?);
}
}
}
Ok(out)
}
}
+17
View File
@@ -0,0 +1,17 @@
use std::io;
enum cuh<T> {
DNSError(io::Error),
ToolUseError,
Other(T),
}
impl<T> From<io::Error> for cuh<T> {
fn from(value: io::Error) -> Self {
todo!()
// if matches!(value.kind(), ) {
// }
}
}
+71 -4
View File
@@ -62,12 +62,79 @@ pub async fn get_macs_1(machine_name: &str) -> io::Result<Vec<arpparse::IpNeighL
let res = futures::future::try_join_all(futures).await?; // async move block errs.
Ok(res
.into_iter()
.flatten() /* resolve double vec */
// .flatten() /* drop parse errors (flat_map cleared) */
.collect())
}
pub async fn get_macs(machine_name: Option<&str>, ips: Option<impl IntoIterator<Item = IpAddr>>, dev: Option<&str>, state: Option<NUDState>) -> io::Result<Vec<IpNeighLine>> {
todo!()
}
pub async fn get_macs(
machine_name: Option<&str>,
ips: Option<&[IpAddr]>,
dev: Option<&str>,
state: Option<NUDState>,
) -> io::Result<Vec<IpNeighLine>> {
// Collect IPs early (before any await) to avoid holding generics across await points
let ip_list: Option<Vec<IpAddr>> = ips.map(|slice| {
slice
.iter()
.copied()
.map(|ip| ip.to_canonical())
.collect()
});
// Resolve by machine name if no IPs provided but we have a name
let ip_list = match (ip_list, machine_name) {
(Some(list), _) => list,
(None, Some(name)) => get_ips(name).await?.into_iter().collect(),
(None, None) => Vec::new(),
};
// Helper to convert NUDState to the string expected by `ip neigh`
let nud_arg = state.map(NUDState::as_ip_neigh_arg);
// let nud_arg = Rc::new(state.map(|s| s.to_string().to_lowercase()));
// Build a closure to run one `ip neigh` invocation and parse results
let run_one = |to_ip: Option<IpAddr>| async move {
let mut args: Vec<String> = vec!["neigh".into(), "show".into()];
if let Some(ip) = to_ip {
args.push("to".into());
args.push(ip.to_string());
}
if let Some(d) = dev {
args.push("dev".into());
args.push(d.to_string());
}
if let Some(nud) = nud_arg {
args.push("nud".into());
args.push(nud.to_string());
}
let o = exec_command("ip", args.iter().map(String::as_str).collect::<Vec<_>>()).await?; // hope to rustc that it knows how to unfuck ts
if !o.status.success() {
return Err(io::Error::other(format!(
"`ip neigh` failed{ctx} (status: {st}): {err}",
ctx = to_ip.map(|ip| format!(" for {ip}")).unwrap_or_default(),
st = o.status,
err = String::from_utf8_lossy(&o.stderr),
)));
}
let lines = String::from_utf8_lossy(&o.stdout);
// Parse lines and, if a specific dev filter was used, stamp that dev onto rows
let parsed = lines.lines().flat_map(arpparse::parse_ip_neigh_line);
let rows: Vec<IpNeighLine> = if let Some(d) = dev {
parsed.map(IpNeighLine::with_dev(d)).collect()
} else {
parsed.collect()
};
Ok::<Vec<IpNeighLine>, io::Error>(rows)
};
// If we have specific IPs, query each; otherwise query the whole table once
if !ip_list.is_empty() {
let futures = ip_list.into_iter().map(|ip| run_one(Some(ip)));
let res = futures::future::try_join_all(futures).await?;
Ok(res.into_iter().flatten().collect())
} else {
run_one(None).await
}
}