the Chat sweep

This commit is contained in:
lda
2026-04-04 02:36:33 +07:00 Unverified
parent b5972196ee
commit 6302e71076
24 changed files with 798 additions and 873 deletions
+1 -65
View File
@@ -1,65 +1 @@
use std::collections::HashSet;
// /// 50ms
// pub async fn get_dev() -> HashSet<String> {
// use lda_ipjs::subcommands::address::json as ipjs_json;
// let mut devs: HashSet<String> = HashSet::new();
// if let Ok(items) = ipjs_json::get(None).await {
// for item in items {
// if item.ifname != "lo" && !item.ifname.is_empty() {
// devs.insert(item.ifname);
// }
// }
// }
// devs
// }
/// 3ms
pub async fn get_dev() -> HashSet<String> {
use std::fs;
fn get_dev() -> HashSet<String> {
let mut devs: HashSet<String> = HashSet::new();
if let Ok(rd) = std::fs::read_dir("/sys/class/net") {
for e in rd.flatten() {
if e.file_type()
.map(|ft| {
if ft.is_symlink() {
// true
fs::metadata(e.path()).map(|m| m.is_dir()).unwrap_or(false)
} else {
ft.is_dir()
}
})
.unwrap_or(false)
&& let Ok(name) = e.file_name().into_string()
&& name != "lo"
&& !name.is_empty()
{
devs.insert(name);
}
}
} else if let Ok(txt) = std::fs::read_to_string("/proc/net/dev") {
for line in txt.lines().skip(2) {
if let Some((name, _rest)) = line.split_once(':') {
let n = name.trim().to_string();
if n != "lo" && !n.is_empty() {
devs.insert(n);
}
}
}
}
devs
}
tokio::task::spawn_blocking(get_dev)
.await
.unwrap_or_default()
}
pub async fn devs_sorted() -> Vec<String> {
let mut v: Vec<String> = get_dev().await.into_iter().collect();
v.sort();
v
}
pub async fn has_dev(name: &str) -> bool {
get_dev().await.contains(name)
}
pub use wakey_linux::devices::{devs_sorted, has_dev};
+2 -43
View File
@@ -1,43 +1,2 @@
use crate::arpparse::NUDState;
use crate::dhcpparse::DhcpLeaseLine;
use crate::utils::query::get_macs;
use serde_with::skip_serializing_none;
use std::net::IpAddr;
#[skip_serializing_none]
#[derive(Debug, Clone, serde::Serialize)]
pub struct DhcpLeaseOut {
#[serde(flatten)]
pub lease_line: DhcpLeaseLine,
pub nud_state: Option<NUDState>,
}
/// Enrich DHCP leases with NUD state and rank using get_macs
pub async fn enrich_leases_with_nud_state(leases: Vec<DhcpLeaseLine>) -> Vec<DhcpLeaseOut> {
let ips: Vec<IpAddr> = leases.iter().map(|l| l.ip).collect();
let mut map: std::collections::HashMap<IpAddr, NUDState> = std::collections::HashMap::new();
if let Ok(rows) = get_macs(&[] as &[&str], &ips, &[] as &[&str], &[], &[]).await {
for row in rows {
let state = row.state;
let r = state.rank();
map.entry(row.ip)
.and_modify(|e| {
let er = e.rank();
if r > er {
*e = state
}
})
.or_insert(state);
}
}
leases
.into_iter()
.map(|lease_line| {
let nud_state = map.get(&lease_line.ip).copied();
DhcpLeaseOut {
lease_line,
nud_state,
}
})
.collect()
}
pub use wakey_core::DhcpLeaseWithState as DhcpLeaseOut;
pub use wakey_linux::dhcp::enrich_leases_with_nud_state;
+7 -63
View File
@@ -1,71 +1,22 @@
use lda_ipjs::subcommands::neighbor;
use macaddr::MacAddr;
use crate::arpparse::{IpNeighLine, NUDState};
use anyhow::{Context, Result};
use std::collections::HashSet;
use anyhow::Result;
use std::net::IpAddr;
use crate::arpparse::{IpNeighLine, NUDState};
pub async fn get_ips(machine_name: &str) -> Result<impl Iterator<Item = IpAddr>> {
Ok(tokio::net::lookup_host((machine_name, 0))
.await
.with_context(|| format!("DNS resolve failed for {machine_name}"))?
.map(|c| c.ip()))
wakey_linux::devices::get_ips(machine_name).await
}
/// Query neighbor table with multi-filters. Empty slice = no filter.
pub async fn get_macs(
machine_names: &[impl AsRef<str>],
ips: &[IpAddr],
devs: &[impl AsRef<str>],
state: &[NUDState],
macs: &[MacAddr],
macs: &[macaddr::MacAddr],
) -> Result<Vec<IpNeighLine>> {
// Resolve machine names to IPs
let resolved_ips: HashSet<IpAddr> = if !machine_names.is_empty() {
futures::future::try_join_all(machine_names.iter().map(|n| get_ips(n.as_ref())))
.await?
.into_iter()
.flatten()
.collect()
} else {
HashSet::new()
};
// Merge provided IPs with resolved IPs
let ip_filter: Vec<IpAddr> = if ips.is_empty() && resolved_ips.is_empty() {
vec![]
} else if ips.is_empty() {
resolved_ips.into_iter().collect()
} else if resolved_ips.is_empty() {
ips.iter().map(|ip| ip.to_canonical()).collect()
} else {
// Intersection: only IPs that appear in both
ips.iter()
.map(|ip| ip.to_canonical())
.filter(|ip| resolved_ips.contains(ip))
.collect()
};
// Convert state filter
let nud_filter: Vec<neighbor::NUDState> = state.iter().copied().map(Into::into).collect();
// Convert devs to &str for nl::get
let dev_strs: Vec<&str> = devs.iter().map(AsRef::as_ref).collect();
// Single rtnetlink call with all filters
let results: Vec<IpNeighLine> = neighbor::nl::get(&ip_filter, &dev_strs, &nud_filter, macs)
.await
.context("rtnetlink failed")?
.into_iter()
.map(Into::into)
.collect();
Ok(results)
wakey_linux::devices::get_neighbors(machine_names, ips, devs, state, macs).await
}
/// Legacy single-filter wrapper. Use get_macs for multi-filter.
#[allow(dead_code)]
pub async fn get_mac(
ip: Option<IpAddr>,
dev: Option<&str>,
@@ -73,12 +24,5 @@ pub async fn get_mac(
) -> Result<Vec<IpNeighLine>> {
let ips: Vec<IpAddr> = ip.into_iter().collect();
let devs: Vec<&str> = dev.into_iter().collect();
let nud: Vec<neighbor::NUDState> = state.iter().copied().map(Into::into).collect();
Ok(neighbor::nl::get(&ips, &devs, &nud, &[])
.await
.context("rtnetlink failed")?
.into_iter()
.map(Into::into)
.collect())
get_macs(&[] as &[&str], &ips, &devs, state, &[]).await
}
+2 -41
View File
@@ -1,44 +1,5 @@
use std::net::IpAddr;
use macaddr::MacAddr;
use crate::{arpparse::NUDState, utils::query::dev::has_dev};
pub enum QueryType {
Ip(IpAddr),
Mac(MacAddr),
Dev(String),
Nud(NUDState),
Unknown(String),
}
pub use wakey_core::QueryInput as QueryType;
pub async fn parse_query(q: String) -> QueryType {
let s = if cfg!(feature = "very-smart-parsing") {
crate::utils::parse::extract_host(&q)
} else {
q.trim()
};
// 1) IP
let ip = if cfg!(feature = "very-smart-parsing") {
crate::utils::parse::parse_numeric_ipv4(s).or_else(|| s.parse::<IpAddr>().ok())
} else {
s.parse::<IpAddr>().ok()
};
if let Some(ip) = ip {
return QueryType::Ip(ip);
}
// 2) MAC
if let Ok(mac) = s.parse::<MacAddr>() {
return QueryType::Mac(mac);
}
// 3) NUD state (reachable, stale, ...)
if let Ok(state) = s.parse::<NUDState>() {
return QueryType::Nud(state);
}
// 4) Known device? prefer dev first
if has_dev(s).await {
return QueryType::Dev(s.to_string());
}
// Default: name last // it will fail also
QueryType::Unknown(s.to_string())
wakey_linux::devices::classify_query(q).await
}
+7 -93
View File
@@ -1,95 +1,9 @@
//! why did my Head Ass split these into two.
use std::{io, net::IpAddr};
use futures::TryFutureExt;
use macaddr::MacAddr;
use tokio::net::UdpSocket;
use crate::route::wake::WakeTarget as RouteWakeTarget;
#[derive(Debug, Clone, Copy, Hash)]
pub struct WakeTarget {
pub ip: IpAddr,
pub mac: MacAddr,
}
#[derive(Debug, Clone, Copy, Hash)]
pub struct WakeTargetResult {
pub target: WakeTarget,
pub status: WakeStatus,
}
#[derive(Debug, Clone, Copy, Hash)]
pub enum WakeStatus {
Success,
NonexistentAddress,
WrongSize,
}
impl WakeTarget {
const fn _new(ip: IpAddr, mac: MacAddr) -> Self {
Self { ip, mac }
}
const fn good(self) -> WakeTargetResult {
WakeTargetResult::new(self, WakeStatus::Success)
}
const fn bad(self) -> WakeTargetResult {
WakeTargetResult::new(self, WakeStatus::WrongSize)
}
const fn errored(self) -> WakeTargetResult {
WakeTargetResult::new(self, WakeStatus::NonexistentAddress)
}
pub async fn wake_one(
sock: &tokio::net::UdpSocket,
t: wakey_linux::wake::CompleteWakeTarget,
) -> wakey_core::WakeTargetResult {
wakey_linux::wake::wake_one(sock, t).await
}
#[derive(Debug, Clone, Copy)]
pub struct Incomplete;
impl TryFrom<RouteWakeTarget> for WakeTarget {
type Error = Incomplete;
fn try_from(value: RouteWakeTarget) -> Result<Self, Self::Error> {
if let RouteWakeTarget {
ip: Some(ip),
mac: Some(mac),
} = value
{
Ok(Self { ip, mac })
} else {
Err(Incomplete)
}
}
}
impl WakeTargetResult {
const fn new(target: WakeTarget, status: WakeStatus) -> Self {
Self { target, status }
}
}
// its time. we have the ip; the macs. we dont need to send to the uh the broadcast anymore???
pub async fn _wake_multi(
targets: impl IntoIterator<Item = WakeTarget>,
) -> io::Result<Vec<WakeTargetResult>> {
let sock = UdpSocket::bind("[::]:0")
.or_else(|_| UdpSocket::bind(":0"))
.await?;
sock.set_broadcast(true)?;
let fs = targets.into_iter().map(|t| wake_one(&sock, t));
Ok(futures::future::join_all(fs).await)
}
pub async fn wake_one(sock: &UdpSocket, t: WakeTarget) -> WakeTargetResult {
let mac = t.mac;
let mb = mac.as_bytes();
let mut pac = [0; 6 + 6 * 16];
pac[..6].fill(0xff);
for i in 1..=16 {
pac[i * 6..(i + 1) * 6].copy_from_slice(mb);
}
let ip = t.ip;
let port = 9;
match sock.send_to(&pac, (ip, port)).await {
Ok(n) if n == pac.len() => t.good(),
Ok(_) => t.bad(),
Err(_) => t.errored(),
}
}
// pub async fn wake_query();
pub use wakey_linux::wake::{CompleteWakeTarget as WakeTarget, wake_many as _wake_multi};
pub use wakey_core::{WakeStatus, WakeTargetResult};