From a3785327cd7b9809f881c21574c609f3532de041 Mon Sep 17 00:00:00 2001 From: Nixevol Date: Sun, 29 Nov 2026 19:56:03 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0=20WiFi=20=E7=83=AD?= =?UTF-8?q?=E7=82=B9=E7=AE=A1=E7=90=86=E5=B9=B6=E5=87=8F=E8=BD=BB=E9=A6=96?= =?UTF-8?q?=E9=A1=B5=E9=87=87=E6=A0=B7?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mifipanel/src/classic.rs | 47 +++ mifipanel/src/main.rs | 3 + mifipanel/src/mmcli.rs | 32 +- mifipanel/src/pages/mod.rs | 1 + mifipanel/src/pages/shell.html | 2 +- mifipanel/src/pages/wifi.html | 174 ++++++++ mifipanel/src/store.rs | 13 +- mifipanel/src/wifi.rs | 586 ++++++++++++++++++++++++++ mifipanel/web/i18n/locales/en.json | 43 ++ mifipanel/web/i18n/locales/kk.json | 43 ++ mifipanel/web/i18n/locales/zh-CN.json | 43 ++ mifipanel/web/i18n/locales/zh-TW.json | 43 ++ mifipanel/web/layuimini/api/init.json | 6 + 13 files changed, 1013 insertions(+), 23 deletions(-) create mode 100644 mifipanel/src/pages/wifi.html create mode 100644 mifipanel/src/wifi.rs diff --git a/mifipanel/src/classic.rs b/mifipanel/src/classic.rs index 58d773e..8934c6e 100644 --- a/mifipanel/src/classic.rs +++ b/mifipanel/src/classic.rs @@ -20,6 +20,10 @@ pub fn routes() -> Router> { .route("/Home/Welcome", get(welcome)) .route("/Home/Metrics", get(metrics)) .route("/Home/Bands", get(bands_get).post(bands_set)) + .route("/Home/Wifi", get(wifi_page)) + .route("/Home/Wifi/Status", get(wifi_status)) + .route("/Home/Wifi/Save", post(wifi_save)) + .route("/Home/Wifi/Client", post(wifi_client)) .route("/Home/KillProcess", post(kill_process)) .route("/Home/Imei", get(imei_page)) .route("/Home/Imei/Status", get(imei_status)) @@ -183,6 +187,49 @@ async fn bands_set(State(app): State>, headers: HeaderMap, axum::J } } +async fn wifi_page(State(app): State>, headers: HeaderMap) -> Response { + if require(&app, &headers).is_err() { + return expired(); + } + render(pages::WIFI, &[], &[]) +} + +async fn wifi_status(State(app): State>, headers: HeaderMap) -> Response { + if http::current_user(&app, &headers).is_none() { + return axum::Json(serde_json::json!({"error": "error.session"})).into_response(); + } + let root = app.data.clone(); + match tokio::task::spawn_blocking(move || crate::wifi::status(&root)).await { + Ok(Ok(status)) => axum::Json(status).into_response(), + Ok(Err(err)) => axum::Json(serde_json::json!({"error": err})).into_response(), + Err(err) => axum::Json(serde_json::json!({"error": err.to_string()})).into_response(), + } +} + +async fn wifi_save(State(app): State>, headers: HeaderMap, axum::Json(body): axum::Json) -> Response { + if http::current_user(&app, &headers).is_none() { + return axum::Json(serde_json::json!({"error": "error.session"})).into_response(); + } + let root = app.data.clone(); + match tokio::task::spawn_blocking(move || crate::wifi::save(&root, &body)).await { + Ok(Ok(())) => axum::Json(serde_json::json!({"ok": true})).into_response(), + Ok(Err(err)) => axum::Json(serde_json::json!({"error": err})).into_response(), + Err(err) => axum::Json(serde_json::json!({"error": err.to_string()})).into_response(), + } +} + +async fn wifi_client(State(app): State>, headers: HeaderMap, axum::Json(body): axum::Json) -> Response { + if http::current_user(&app, &headers).is_none() { + return axum::Json(serde_json::json!({"error": "error.session"})).into_response(); + } + let root = app.data.clone(); + match tokio::task::spawn_blocking(move || crate::wifi::act(&root, &body)).await { + Ok(Ok(())) => axum::Json(serde_json::json!({"ok": true})).into_response(), + Ok(Err(err)) => axum::Json(serde_json::json!({"error": err})).into_response(), + Err(err) => axum::Json(serde_json::json!({"error": err.to_string()})).into_response(), + } +} + async fn kill_process(State(app): State>, headers: HeaderMap, axum::Json(body): axum::Json) -> Response { if http::current_user(&app, &headers).is_none() { return axum::Json(serde_json::json!({"error": "error.session"})).into_response(); diff --git a/mifipanel/src/main.rs b/mifipanel/src/main.rs index 0bb20a5..bb71fe3 100644 --- a/mifipanel/src/main.rs +++ b/mifipanel/src/main.rs @@ -7,6 +7,7 @@ mod metrics; mod mmcli; mod pages; mod store; +mod wifi; use http::AppState; use std::net::SocketAddr; @@ -40,6 +41,8 @@ async fn server() -> Result<(), String> { let original_root = data.clone(); tokio::task::spawn_blocking(move || imei::capture_original(&original_root)).await.ok(); let retry_root = data.clone(); + let wifi_root = data.clone(); + tokio::task::spawn_blocking(move || wifi::restore(&wifi_root)); tokio::spawn(imei::supervise(data)); let publisher = Arc::clone(&app); tokio::spawn(async move { publish_metrics(publisher).await }); diff --git a/mifipanel/src/mmcli.rs b/mifipanel/src/mmcli.rs index 174c7f5..1dc7b8a 100644 --- a/mifipanel/src/mmcli.rs +++ b/mifipanel/src/mmcli.rs @@ -102,6 +102,25 @@ pub struct Radio { } pub fn radio(modem: u32) -> Radio { + use std::time::{Duration, Instant}; + struct Slot { + at: Instant, + modem: u32, + value: Radio, + } + static CACHE: std::sync::Mutex> = std::sync::Mutex::new(None); + let mut slot = CACHE.lock().unwrap_or_else(|err| err.into_inner()); + if let Some(cache) = slot.as_ref() { + if cache.modem == modem && cache.at.elapsed() < Duration::from_secs(10) { + return cache.value.clone(); + } + } + let value = radio_now(modem); + *slot = Some(Slot { at: Instant::now(), modem, value: value.clone() }); + value +} + +fn radio_now(modem: u32) -> Radio { let mut found = Radio::default(); if let Ok(info) = run(&["-m".into(), modem.to_string(), "-K".into()]) { let map = parse_kv(&info); @@ -280,14 +299,6 @@ fn neighbor_from_fields(rat: &str, fields: &[(String, String)]) -> Neighbor { } } -pub fn bucket(state: &str) -> &'static str { - match state { - "received" => "received", - "sent" | "sending" => "sent", - _ => "draft", - } -} - pub fn category(state: &str) -> Option<&'static str> { match state { "received" => Some("received"), @@ -908,8 +919,9 @@ mod tests { assert_eq!(sms.tel, "+8613800138000"); assert_eq!(sms.text, "你好"); assert_eq!(sms.state, "received"); - assert_eq!(bucket("unknown"), "draft"); - assert_eq!(bucket("sending"), "sent"); + assert_eq!(category("unknown"), Some("draft")); + assert_eq!(category("sent"), Some("sent")); + assert_eq!(category("sending"), None); let modem = parse_modem(" Status | state: \u{1b}[31mfailed\u{1b}[0m\n | failed reason: \u{1b}[31msim-missing\u{1b}[0m\n"); assert_eq!(modem.state, "failed"); assert_eq!(modem.reason, "sim-missing"); diff --git a/mifipanel/src/pages/mod.rs b/mifipanel/src/pages/mod.rs index 0568879..60e481c 100644 --- a/mifipanel/src/pages/mod.rs +++ b/mifipanel/src/pages/mod.rs @@ -15,6 +15,7 @@ pub const TELEGRAM: &str = include_str!("telegram.html"); pub const DINGTALK: &str = include_str!("dingtalk.html"); pub const PASSWORD: &str = include_str!("password.html"); pub const IMEI: &str = include_str!("imei.html"); +pub const WIFI: &str = include_str!("wifi.html"); pub fn render(template: &str, text: &[(&str, &str)], raw: &[(&str, &str)]) -> String { let mut out = template.to_string(); diff --git a/mifipanel/src/pages/shell.html b/mifipanel/src/pages/shell.html index f222dba..cf484be 100644 --- a/mifipanel/src/pages/shell.html +++ b/mifipanel/src/pages/shell.html @@ -189,7 +189,7 @@ layui.use(['jquery', 'layer', 'miniAdmin'], function () { }); fetch("/Home/Language", { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ lang: I18n.lang }) }).catch(function () {}); var options = { - iniUrl: "/layuimini/api/init.json?v=4",// 初始化接口 + iniUrl: "/layuimini/api/init.json?v=5",// 初始化接口 clearUrl: "/layuimini/api/clear.json", // 缓存清理接口 urlHashLocation: true, // 是否打开hash定位 bgColorDefault: false, // 主题默认配置 diff --git a/mifipanel/src/pages/wifi.html b/mifipanel/src/pages/wifi.html new file mode 100644 index 0000000..8920ae4 --- /dev/null +++ b/mifipanel/src/pages/wifi.html @@ -0,0 +1,174 @@ + + + + + WiFi + + + + + + +
+
+
+

WiFi

+ +
+
+ + + + + + + + + + +
+

+
+ +
+
+
+

Clients

+
+
+
+

Blacklist

+
+
+
+ + + + diff --git a/mifipanel/src/store.rs b/mifipanel/src/store.rs index 793cf8c..ad22812 100644 --- a/mifipanel/src/store.rs +++ b/mifipanel/src/store.rs @@ -109,17 +109,6 @@ impl Store { self.settings.username == username && self.settings.password_hash == hash_password(password) } - pub fn change_password(&mut self, old: &str, new_password: &str) -> Result<(), String> { - if !self.check_password(&self.settings.username, old) { - return Err("error.password.old".into()); - } - if new_password.is_empty() { - return Err("error.password.empty".into()); - } - self.settings.password_hash = hash_password(new_password); - self.save_settings() - } - pub fn set_password(&mut self, password: &str) -> Result<(), String> { if password.is_empty() { return Err("error.password.empty".into()); @@ -225,7 +214,7 @@ mod tests { let mut store = Store::open(root.clone()).unwrap(); assert!(store.check_password("admin", "admin")); assert!(!store.check_password("admin", "nope")); - store.change_password("admin", "abcd").unwrap(); + store.set_password("abcd").unwrap(); assert!(store.check_password("admin", "abcd")); assert!(store.remember(SavedSms { sid: "1".into(), tel: "1".into(), text: "a".into() }).unwrap()); assert!(!store.remember(SavedSms { sid: "1".into(), tel: "1".into(), text: "b".into() }).unwrap()); diff --git a/mifipanel/src/wifi.rs b/mifipanel/src/wifi.rs new file mode 100644 index 0000000..67e918c --- /dev/null +++ b/mifipanel/src/wifi.rs @@ -0,0 +1,586 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::io::Write; +use std::path::{Path, PathBuf}; +use std::process::{Command, Stdio}; +use std::sync::Mutex; + +const CONN: &str = "mifipanel"; + +#[derive(Clone, Debug, Serialize)] +pub struct Status { + pub device: String, + pub enabled: bool, + pub ssid: String, + pub password: String, + pub security: String, + pub channel: u32, + pub hidden: bool, + pub clients: Vec, + pub blacklist: Vec, +} + +#[derive(Clone, Debug, Serialize)] +pub struct Client { + pub mac: String, + pub ip: String, + pub name: String, + pub signal: String, + pub down: u32, + pub up: u32, + pub blocked: bool, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct ApForm { + pub enabled: bool, + pub ssid: String, + pub password: String, + pub security: String, + pub channel: u32, + pub hidden: bool, +} + +#[derive(Clone, Debug, Deserialize)] +pub struct ClientAction { + pub mac: String, + pub action: String, + pub down: u32, + pub up: u32, +} + +#[derive(Clone, Debug, Default, Serialize, Deserialize)] +struct Saved { + blacklist: Vec, + limits: Vec, +} + +#[derive(Clone, Debug, Serialize, Deserialize)] +struct Limit { + mac: String, + down: u32, + up: u32, +} + +pub fn status(root: &Path) -> Result { + let _busy = lock(); + let device = wifi_device()?; + let saved = load(root); + let enabled = ap_active(); + let (ssid, password, security, channel, hidden) = read_ap().unwrap_or_else(|_| ("MiFi".into(), String::new(), "wpa2".into(), 0, false)); + let mut clients = if enabled { stations(&device) } else { Vec::new() }; + merge_leases(&device, &mut clients); + for client in &mut clients { + if let Some(limit) = saved.limits.iter().find(|item| item.mac == client.mac) { + client.down = limit.down; + client.up = limit.up; + } + client.blocked = saved.blacklist.iter().any(|item| item == &client.mac); + } + if enabled { + shape(&device, &clients, &saved.limits); + } + Ok(Status { + device, + enabled, + ssid, + password, + security, + channel, + hidden, + clients, + blacklist: saved.blacklist, + }) +} + +pub fn save(root: &Path, form: &ApForm) -> Result<(), String> { + let _busy = lock(); + let device = wifi_device()?; + let ssid = clean_ssid(&form.ssid)?; + let security = clean_security(&form.security)?; + let password = clean_password(&security, &form.password)?; + let channel = clean_channel(form.channel)?; + ensure_connection(&device, &ssid)?; + let mut args = vec![ + "connection".into(), + "modify".into(), + CONN.into(), + "connection.interface-name".into(), + device.clone(), + "connection.autoconnect".into(), + if form.enabled { "yes".into() } else { "no".into() }, + "802-11-wireless.ssid".into(), + ssid, + "802-11-wireless.mode".into(), + "ap".into(), + "802-11-wireless.band".into(), + "bg".into(), + "802-11-wireless.hidden".into(), + if form.hidden { "yes".into() } else { "no".into() }, + "802-11-wireless.channel".into(), + if channel == 0 { String::new() } else { channel.to_string() }, + "802-11-wireless.powersave".into(), + "2".into(), + "ipv4.method".into(), + "shared".into(), + "ipv6.method".into(), + "disabled".into(), + ]; + if security == "open" { + args.extend(["802-11-wireless-security.key-mgmt".into(), "none".into()]); + } else { + args.extend([ + "802-11-wireless-security.key-mgmt".into(), + "wpa-psk".into(), + "802-11-wireless-security.proto".into(), + "rsn".into(), + "802-11-wireless-security.pairwise".into(), + "ccmp".into(), + "802-11-wireless-security.group".into(), + "ccmp".into(), + "802-11-wireless-security.pmf".into(), + "disable".into(), + "802-11-wireless-security.psk".into(), + password, + ]); + } + nm(&args)?; + if form.enabled { + let _ = nm(&["radio".into(), "wifi".into(), "on".into()]); + nm(&["connection".into(), "up".into(), CONN.into()])?; + } else if ap_active() { + let _ = nm(&["connection".into(), "down".into(), CONN.into()]); + } + apply_nft(&device, &load(root).blacklist); + Ok(()) +} + +pub fn act(root: &Path, action: &ClientAction) -> Result<(), String> { + let _busy = lock(); + let mac = normalize_mac(&action.mac).ok_or_else(|| "error.wifi.mac".to_string())?; + let device = wifi_device()?; + let mut saved = load(root); + match action.action.as_str() { + "kick" => kick(&device, &mac)?, + "block" => { + if !saved.blacklist.iter().any(|item| item == &mac) { + saved.blacklist.push(mac.clone()); + } + store(root, &saved)?; + apply_nft(&device, &saved.blacklist); + let _ = kick(&device, &mac); + } + "unblock" => { + saved.blacklist.retain(|item| item != &mac); + store(root, &saved)?; + apply_nft(&device, &saved.blacklist); + } + "limit" => { + if action.down > 100_000 || action.up > 100_000 { + return Err("error.wifi.rate".into()); + } + saved.limits.retain(|item| item.mac != mac); + if action.down > 0 || action.up > 0 { + saved.limits.push(Limit { mac, down: action.down, up: action.up }); + } + store(root, &saved)?; + let mut clients = stations(&device); + merge_leases(&device, &mut clients); + shape(&device, &clients, &saved.limits); + } + _ => return Err("error.wifi.action".into()), + } + Ok(()) +} + +pub fn restore(root: &Path) { + let _busy = lock(); + let Ok(device) = wifi_device() else { return }; + let saved = load(root); + apply_nft(&device, &saved.blacklist); + if ap_active() { + let mut clients = stations(&device); + merge_leases(&device, &mut clients); + shape(&device, &clients, &saved.limits); + } +} + +fn ensure_connection(device: &str, ssid: &str) -> Result<(), String> { + if connection_exists() { + return Ok(()); + } + nm(&[ + "connection".into(), + "add".into(), + "type".into(), + "wifi".into(), + "ifname".into(), + device.into(), + "con-name".into(), + CONN.into(), + "autoconnect".into(), + "no".into(), + "ssid".into(), + ssid.into(), + "802-11-wireless.mode".into(), + "ap".into(), + "ipv4.method".into(), + "shared".into(), + "ipv6.method".into(), + "disabled".into(), + ])?; + Ok(()) +} + +fn connection_exists() -> bool { + nm(&["-t".into(), "-f".into(), "NAME".into(), "connection".into(), "show".into()]) + .map(|text| text.lines().any(|line| line.trim() == CONN)) + .unwrap_or(false) +} + +fn ap_active() -> bool { + nm(&["-t".into(), "-f".into(), "NAME".into(), "connection".into(), "show".into(), "--active".into()]) + .map(|text| text.lines().any(|line| line.trim() == CONN)) + .unwrap_or(false) +} + +fn read_ap() -> Result<(String, String, String, u32, bool), String> { + let text = nm(&[ + "-s".into(), + "-t".into(), + "-f".into(), + "802-11-wireless.ssid,802-11-wireless.hidden,802-11-wireless.channel,802-11-wireless-security.key-mgmt,802-11-wireless-security.psk".into(), + "connection".into(), + "show".into(), + CONN.into(), + ])?; + let mut ssid = String::new(); + let mut hidden = false; + let mut channel = 0u32; + let mut security = "wpa2".to_string(); + let mut password = String::new(); + for line in text.lines() { + let Some((key, value)) = line.split_once(':') else { continue }; + let value = value.trim(); + match key.trim() { + "802-11-wireless.ssid" => ssid = value.to_string(), + "802-11-wireless.hidden" => hidden = value == "yes", + "802-11-wireless.channel" => channel = value.parse().unwrap_or(0), + "802-11-wireless-security.key-mgmt" => { + security = if value == "wpa-psk" { "wpa2".into() } else { "open".into() }; + } + "802-11-wireless-security.psk" if value != "--" => password = value.to_string(), + _ => {} + } + } + if ssid.is_empty() { + ssid = "MiFi".into(); + } + Ok((ssid, password, security, channel, hidden)) +} + +fn wifi_device() -> Result { + let text = nm(&["-t".into(), "-f".into(), "DEVICE,TYPE".into(), "device".into()])?; + for line in text.lines() { + let mut parts = line.split(':'); + let name = parts.next().unwrap_or("").trim(); + let kind = parts.next().unwrap_or("").trim(); + if kind == "wifi" && valid_iface(name) { + return Ok(name.to_string()); + } + } + Err("error.wifi.device".into()) +} + +fn stations(device: &str) -> Vec { + let text = run("wpa_cli", &["-i".into(), device.into(), "all_sta".into()]).unwrap_or_default(); + parse_stations(&text) +} + +fn merge_leases(device: &str, clients: &mut Vec) { + let mut leases = Vec::new(); + for dir in ["/var/lib/NetworkManager", "/run/NetworkManager"] { + let Ok(entries) = fs::read_dir(dir) else { continue }; + for entry in entries.flatten() { + let name = entry.file_name(); + let name = name.to_string_lossy(); + if name.starts_with("dnsmasq") && name.ends_with(".leases") { + if let Ok(text) = fs::read_to_string(entry.path()) { + leases.extend(parse_leases(&text)); + } + } + } + } + if let Ok(text) = run("ip", &["neigh".into(), "show".into(), "dev".into(), device.into()]) { + leases.extend(parse_neigh(&text)); + } + for (mac, ip, name) in leases { + if let Some(client) = clients.iter_mut().find(|item| item.mac == mac) { + if client.ip.is_empty() && !ip.is_empty() { + client.ip = ip; + } + if client.name.is_empty() && !name.is_empty() && name != "*" { + client.name = name; + } + } else if !ip.is_empty() { + clients.push(Client { + mac, + ip, + name: if name == "*" { String::new() } else { name }, + signal: String::new(), + down: 0, + up: 0, + blocked: false, + }); + } + } +} + +fn kick(device: &str, mac: &str) -> Result<(), String> { + let text = run("wpa_cli", &["-i".into(), device.into(), "deauthenticate".into(), mac.into()])?; + if text.to_ascii_lowercase().contains("fail") { + return Err("error.wifi.kick".into()); + } + Ok(()) +} + +fn apply_nft(device: &str, blacklist: &[String]) { + let _ = run("nft", &["delete".into(), "table".into(), "inet".into(), "mifipanel".into()]); + if blacklist.is_empty() { + return; + } + let mut script = String::from("table inet mifipanel {\n chain input {\n type filter hook input priority -10; policy accept;\n"); + for mac in blacklist { + script.push_str(&format!(" iifname \"{device}\" ether saddr {mac} drop\n")); + } + script.push_str(" }\n chain forward {\n type filter hook forward priority -10; policy accept;\n"); + for mac in blacklist { + script.push_str(&format!(" ether saddr {mac} drop\n ether daddr {mac} drop\n")); + } + script.push_str(" }\n}\n"); + let mut child = Command::new("nft"); + child.args(["-f", "-"]).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::piped()); + let Ok(mut child) = child.spawn() else { return }; + if let Some(mut stdin) = child.stdin.take() { + let _ = stdin.write_all(script.as_bytes()); + } + let _ = child.wait(); +} + +fn shape(device: &str, clients: &[Client], limits: &[Limit]) { + let rules: Vec<(String, u32, u32)> = limits + .iter() + .filter_map(|limit| { + let ip = clients.iter().find(|client| client.mac == limit.mac && is_ipv4(&client.ip)).map(|client| client.ip.clone())?; + if limit.down == 0 && limit.up == 0 { + return None; + } + Some((ip, limit.down, limit.up)) + }) + .take(32) + .collect(); + let _ = run("tc", &["qdisc".into(), "del".into(), "dev".into(), device.into(), "root".into()]); + let _ = run("tc", &["qdisc".into(), "del".into(), "dev".into(), device.into(), "ingress".into()]); + if rules.is_empty() { + return; + } + if rules.iter().any(|(_, down, _)| *down > 0) { + let _ = run("tc", &["qdisc".into(), "replace".into(), "dev".into(), device.into(), "root".into(), "handle".into(), "1:".into(), "htb".into(), "default".into(), "1".into()]); + let _ = run("tc", &["class".into(), "replace".into(), "dev".into(), device.into(), "parent".into(), "1:".into(), "classid".into(), "1:1".into(), "htb".into(), "rate".into(), "1000mbit".into()]); + } + if rules.iter().any(|(_, _, up)| *up > 0) { + let _ = run("tc", &["qdisc".into(), "replace".into(), "dev".into(), device.into(), "handle".into(), "ffff:".into(), "ingress".into()]); + } + for (index, (ip, down, up)) in rules.iter().enumerate() { + let pref = (index + 1).to_string(); + if *down > 0 { + let class = format!("1:{}", 20 + index); + let rate = format!("{}kbit", down.saturating_mul(8)); + let _ = run("tc", &["class".into(), "replace".into(), "dev".into(), device.into(), "parent".into(), "1:".into(), "classid".into(), class.clone(), "htb".into(), "rate".into(), rate.clone(), "ceil".into(), rate]); + let _ = run("tc", &["filter".into(), "replace".into(), "dev".into(), device.into(), "protocol".into(), "ip".into(), "parent".into(), "1:".into(), "prio".into(), pref.clone(), "u32".into(), "match".into(), "ip".into(), "dst".into(), format!("{ip}/32"), "flowid".into(), class]); + } + if *up > 0 { + let rate = format!("{}kbit", up.saturating_mul(8)); + let _ = run("tc", &["filter".into(), "replace".into(), "dev".into(), device.into(), "parent".into(), "ffff:".into(), "protocol".into(), "ip".into(), "prio".into(), pref, "u32".into(), "match".into(), "ip".into(), "src".into(), format!("{ip}/32"), "police".into(), "rate".into(), rate, "burst".into(), "64kb".into(), "drop".into()]); + } + } +} + +fn load(root: &Path) -> Saved { + let path = state_path(root); + let Ok(text) = fs::read_to_string(path) else { return Saved::default() }; + serde_json::from_str(&text).unwrap_or_default() +} + +fn store(root: &Path, saved: &Saved) -> Result<(), String> { + if let Some(parent) = state_path(root).parent() { + fs::create_dir_all(parent).map_err(|err| err.to_string())?; + } + let text = serde_json::to_string_pretty(saved).map_err(|err| err.to_string())?; + fs::write(state_path(root), text).map_err(|err| err.to_string()) +} + +fn state_path(root: &Path) -> PathBuf { + root.join("wifi.json") +} + +fn nm(args: &[String]) -> Result { + run(nmcli_bin(), args) +} + +fn nmcli_bin() -> &'static str { + if Path::new("/usr/bin/nmcli").exists() { "/usr/bin/nmcli" } else { "nmcli" } +} + +fn run(bin: &str, args: &[String]) -> Result { + let output = Command::new(bin).args(args).env("LANG", "C").output().map_err(|err| format!("error.wifi.start|{err}"))?; + let stdout = String::from_utf8_lossy(&output.stdout); + let stderr = String::from_utf8_lossy(&output.stderr); + let text = if stdout.trim().is_empty() { stderr.trim().to_string() } else { stdout.trim().to_string() }; + if output.status.success() { + Ok(text) + } else if text.is_empty() { + Err("error.wifi.fail".into()) + } else { + Err(text.chars().take(240).collect()) + } +} + +fn lock() -> std::sync::MutexGuard<'static, ()> { + static WIFI: Mutex<()> = Mutex::new(()); + WIFI.lock().unwrap_or_else(|err| err.into_inner()) +} + +pub(crate) fn clean_ssid(value: &str) -> Result { + let ssid = value.trim(); + if ssid.is_empty() || ssid.len() > 32 || ssid.starts_with('-') || ssid.chars().any(|ch| ch.is_control()) { + return Err("error.wifi.ssid".into()); + } + Ok(ssid.to_string()) +} + +pub(crate) fn clean_security(value: &str) -> Result { + match value { + "open" | "wpa2" => Ok(value.to_string()), + _ => Err("error.wifi.security".into()), + } +} + +pub(crate) fn clean_password(security: &str, value: &str) -> Result { + if security == "open" { + return Ok(String::new()); + } + let password = value.trim(); + if password.len() < 8 || password.len() > 63 || password.starts_with('-') || password.chars().any(|ch| ch.is_control()) { + return Err("error.wifi.password".into()); + } + Ok(password.to_string()) +} + +pub(crate) fn clean_channel(value: u32) -> Result { + if value <= 13 { Ok(value) } else { Err("error.wifi.channel".into()) } +} + +pub(crate) fn normalize_mac(value: &str) -> Option { + let bytes: Vec<&str> = value.trim().split(':').collect(); + if bytes.len() != 6 || !bytes.iter().all(|part| part.len() == 2 && part.chars().all(|ch| ch.is_ascii_hexdigit())) { + return None; + } + Some(bytes.join(":").to_ascii_uppercase()) +} + +fn valid_iface(name: &str) -> bool { + !name.is_empty() && name.len() <= 15 && name.chars().all(|ch| ch.is_ascii_alphanumeric() || ch == '_' || ch == '-') +} + +fn is_ipv4(value: &str) -> bool { + let parts: Vec<&str> = value.split('.').collect(); + parts.len() == 4 && parts.iter().all(|part| part.parse::().is_ok()) +} + +pub(crate) fn parse_stations(text: &str) -> Vec { + let mut out = Vec::new(); + let mut current: Option = None; + for line in text.lines() { + let line = line.trim(); + if line.is_empty() || line.eq_ignore_ascii_case("FAIL") { + continue; + } + if let Some(mac) = normalize_mac(line) { + if let Some(client) = current.take() { + out.push(client); + } + current = Some(Client { mac, ip: String::new(), name: String::new(), signal: String::new(), down: 0, up: 0, blocked: false }); + continue; + } + if let Some((key, value)) = line.split_once('=') { + if key == "signal" { + if let Some(client) = current.as_mut() { + client.signal = format!("{value} dBm"); + } + } + } + } + if let Some(client) = current { + out.push(client); + } + out +} + +pub(crate) fn parse_leases(text: &str) -> Vec<(String, String, String)> { + let mut out = Vec::new(); + for line in text.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + if parts.len() < 4 { + continue; + } + let Some(mac) = normalize_mac(parts[1]) else { continue }; + if !is_ipv4(parts[2]) { + continue; + } + out.push((mac, parts[2].to_string(), parts[3].to_string())); + } + out +} + +pub(crate) fn parse_neigh(text: &str) -> Vec<(String, String, String)> { + let mut out = Vec::new(); + for line in text.lines() { + let parts: Vec<&str> = line.split_whitespace().collect(); + let Some(ip) = parts.first() else { continue }; + if !is_ipv4(ip) { + continue; + } + let Some(pos) = parts.iter().position(|part| *part == "lladdr") else { continue }; + let Some(mac) = parts.get(pos + 1).and_then(|value| normalize_mac(value)) else { continue }; + out.push((mac, (*ip).to_string(), String::new())); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn checks_ap_fields_and_clients() { + assert_eq!(clean_ssid(" MiFi ").unwrap(), "MiFi"); + assert!(clean_ssid("").is_err()); + assert!(clean_ssid("-bad").is_err()); + assert_eq!(clean_security("wpa2").unwrap(), "wpa2"); + assert!(clean_security("wep").is_err()); + assert!(clean_password("wpa2", "short").is_err()); + assert_eq!(clean_password("open", "ignored").unwrap(), ""); + assert_eq!(clean_channel(0).unwrap(), 0); + assert!(clean_channel(14).is_err()); + assert_eq!(normalize_mac("aa:bb:cc:dd:ee:ff").unwrap(), "AA:BB:CC:DD:EE:FF"); + assert!(normalize_mac("aa-bb-cc-dd-ee-ff").is_none()); + let stations = parse_stations("AA:BB:CC:DD:EE:FF\nsignal=-47\nrx_bytes=10\n\nFAIL\n"); + assert_eq!(stations.len(), 1); + assert_eq!(stations[0].signal, "-47 dBm"); + let leases = parse_leases("1700 aa:bb:cc:dd:ee:ff 10.42.0.15 phone *\n"); + assert_eq!(leases, vec![("AA:BB:CC:DD:EE:FF".into(), "10.42.0.15".into(), "phone".into())]); + let neigh = parse_neigh("10.42.0.15 dev wlan0 lladdr aa:bb:cc:dd:ee:ff REACHABLE\n"); + assert_eq!(neigh[0].0, "AA:BB:CC:DD:EE:FF"); + } +} diff --git a/mifipanel/web/i18n/locales/en.json b/mifipanel/web/i18n/locales/en.json index 0321e28..b7e814c 100644 --- a/mifipanel/web/i18n/locales/en.json +++ b/mifipanel/web/i18n/locales/en.json @@ -1,6 +1,7 @@ { "nav": { "home": "Home", + "wifi": "WiFi", "imei": "IMEI Tool", "sms": "Messages", "inbox": "Inbox", @@ -173,6 +174,35 @@ "quality": "Quality" } }, + "wifi": { + "title": "WiFi", + "enable": "On", + "ssid": "Name", + "security": "Encryption", + "wpa2": "WPA2", + "open": "Open", + "password": "Password", + "channel": "Channel", + "auto": "Auto", + "hidden": "Hidden", + "save": "Save", + "saved": "Saved", + "clients": "Clients", + "blacklist": "Blacklist", + "block": "Block", + "unblock": "Remove", + "kick": "Kick", + "applyLimit": "Limit", + "none": "None", + "col": { + "mac": "MAC", + "name": "Name", + "signal": "Signal", + "down": "Down KB/s", + "up": "Up KB/s", + "action": "Action" + } + }, "imei": { "title": "IMEI Tool", "reread": "Read again", @@ -407,6 +437,19 @@ "unknown": "That band is not supported by this modem", "device": "Band lock is only available on the device", "state": "The modem is not ready for band lock" + }, + "wifi": { + "device": "No WiFi interface is available", + "ssid": "The name must be 1 to 32 characters", + "security": "Unknown encryption", + "password": "A WPA2 password must be 8 to 63 characters", + "channel": "Channel must be Auto or 1 to 13", + "mac": "Invalid MAC address", + "rate": "The speed limit is out of range", + "action": "Unsupported action", + "kick": "Could not disconnect this client", + "start": "Could not run the network command: {detail}", + "fail": "WiFi command failed" } } } diff --git a/mifipanel/web/i18n/locales/kk.json b/mifipanel/web/i18n/locales/kk.json index 532bd83..8a685e6 100644 --- a/mifipanel/web/i18n/locales/kk.json +++ b/mifipanel/web/i18n/locales/kk.json @@ -1,6 +1,7 @@ { "nav": { "home": "Басты бет", + "wifi": "WiFi", "imei": "IMEI құралы", "sms": "Хабарлама", "inbox": "Кіріс", @@ -173,6 +174,35 @@ "quality": "Сапа" } }, + "wifi": { + "title": "WiFi", + "enable": "Қосу", + "ssid": "Атауы", + "security": "Шифрлау", + "wpa2": "WPA2", + "open": "Ашық", + "password": "Құпия сөз", + "channel": "Арна", + "auto": "Авто", + "hidden": "Жасырын", + "save": "Сақтау", + "saved": "Сақталды", + "clients": "Клиенттер", + "blacklist": "Қара тізім", + "block": "Бұғаттау", + "unblock": "Шығару", + "kick": "Шығарып жіберу", + "applyLimit": "Шектеу", + "none": "Жоқ", + "col": { + "mac": "MAC", + "name": "Атауы", + "signal": "Сигнал", + "down": "Жүктеу KB/s", + "up": "Жіберу KB/s", + "action": "Әрекет" + } + }, "imei": { "title": "IMEI құралы", "reread": "Қайта оқу", @@ -407,6 +437,19 @@ "unknown": "Бұл жолақ модемде жоқ", "device": "Жиілікті бекіту тек құрылғыда қолжетімді", "state": "Модем әлі дайын емес, жиілікті бекітуге болмайды" + }, + "wifi": { + "device": "WiFi интерфейсі жоқ", + "ssid": "Атауы 1-32 таңба болуы керек", + "security": "Шифрлау түрі жарамсыз", + "password": "WPA2 құпия сөзі 8-63 таңба болуы керек", + "channel": "Арна авто немесе 1-13 болуы керек", + "mac": "MAC мекенжайы жарамсыз", + "rate": "Жылдамдық шегі тым үлкен", + "action": "Бұл әрекет қолдаулы емес", + "kick": "Клиентті ажырату мүмкін болмады", + "start": "Желі командасы іске қосылмады: {detail}", + "fail": "WiFi әрекеті сәтсіз" } } } diff --git a/mifipanel/web/i18n/locales/zh-CN.json b/mifipanel/web/i18n/locales/zh-CN.json index 391c749..353f97f 100644 --- a/mifipanel/web/i18n/locales/zh-CN.json +++ b/mifipanel/web/i18n/locales/zh-CN.json @@ -1,6 +1,7 @@ { "nav": { "home": "首页", + "wifi": "WiFi", "imei": "IMEI 工具", "sms": "短信", "inbox": "收信箱", @@ -173,6 +174,35 @@ "quality": "质量" } }, + "wifi": { + "title": "WiFi", + "enable": "开启", + "ssid": "名称", + "security": "加密", + "wpa2": "WPA2", + "open": "开放", + "password": "密码", + "channel": "信道", + "auto": "自动", + "hidden": "隐藏", + "save": "保存", + "saved": "已保存", + "clients": "接入用户", + "blacklist": "黑名单", + "block": "拉黑", + "unblock": "移出", + "kick": "踢出", + "applyLimit": "限速", + "none": "暂无", + "col": { + "mac": "MAC", + "name": "名称", + "signal": "信号", + "down": "下行 KB/s", + "up": "上行 KB/s", + "action": "操作" + } + }, "imei": { "title": "IMEI 工具", "reread": "重新读取", @@ -407,6 +437,19 @@ "unknown": "频段不在这只猫的支持列表里", "device": "锁频只能在设备上设置", "state": "调制解调器还没就绪,暂时不能锁频" + }, + "wifi": { + "device": "没有可用的 WiFi 网卡", + "ssid": "名称需为 1 到 32 个字符", + "security": "加密方式无效", + "password": "WPA2 密码需为 8 到 63 个字符", + "channel": "信道需为自动或 1 到 13", + "mac": "MAC 地址无效", + "rate": "限速超出范围", + "action": "不支持这个操作", + "kick": "暂时踢不掉这个用户", + "start": "无法运行网络命令:{detail}", + "fail": "WiFi 操作失败" } } } diff --git a/mifipanel/web/i18n/locales/zh-TW.json b/mifipanel/web/i18n/locales/zh-TW.json index de5e9ee..9c05894 100644 --- a/mifipanel/web/i18n/locales/zh-TW.json +++ b/mifipanel/web/i18n/locales/zh-TW.json @@ -1,6 +1,7 @@ { "nav": { "home": "首頁", + "wifi": "WiFi", "imei": "IMEI 工具", "sms": "簡訊", "inbox": "收件匣", @@ -173,6 +174,35 @@ "quality": "品質" } }, + "wifi": { + "title": "WiFi", + "enable": "開啟", + "ssid": "名稱", + "security": "加密", + "wpa2": "WPA2", + "open": "開放", + "password": "密碼", + "channel": "頻道", + "auto": "自動", + "hidden": "隱藏", + "save": "儲存", + "saved": "已儲存", + "clients": "連線使用者", + "blacklist": "黑名單", + "block": "封鎖", + "unblock": "移出", + "kick": "踢除", + "applyLimit": "限速", + "none": "暫無", + "col": { + "mac": "MAC", + "name": "名稱", + "signal": "訊號", + "down": "下行 KB/s", + "up": "上行 KB/s", + "action": "操作" + } + }, "imei": { "title": "IMEI 工具", "reread": "重新讀取", @@ -407,6 +437,19 @@ "unknown": "頻段不在這臺數據機的支援清單裡", "device": "鎖頻只能在裝置上設定", "state": "數據機還沒就緒,暫時不能鎖頻" + }, + "wifi": { + "device": "沒有可用的 WiFi 網卡", + "ssid": "名稱需為 1 到 32 個字元", + "security": "加密方式無效", + "password": "WPA2 密碼需為 8 到 63 個字元", + "channel": "頻道需為自動或 1 到 13", + "mac": "MAC 位址無效", + "rate": "限速超出範圍", + "action": "不支援這個操作", + "kick": "暫時踢不掉這個使用者", + "start": "無法執行網路命令:{detail}", + "fail": "WiFi 操作失敗" } } } diff --git a/mifipanel/web/layuimini/api/init.json b/mifipanel/web/layuimini/api/init.json index 14c7de2..a061e80 100644 --- a/mifipanel/web/layuimini/api/init.json +++ b/mifipanel/web/layuimini/api/init.json @@ -15,6 +15,12 @@ "href": "/Home/Welcome", "target": "_self" }, + { + "title": "nav.wifi", + "icon": "fa fa-wifi", + "href": "/Home/Wifi", + "target": "_self" + }, { "title": "nav.imei", "icon": "fa fa-barcode",