From 28a5be3d78b0af706cca5bc4eb237dbff277c36c Mon Sep 17 00:00:00 2001 From: Nixevol Date: Mon, 30 Nov 2026 16:24:51 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E9=9D=A2=E6=9D=BF=E8=B4=9F=E8=B4=A3?= =?UTF-8?q?=E8=9C=82=E7=AA=9D=E6=8B=A8=E5=8F=B7=EF=BC=8C=E9=A6=96=E9=A1=B5?= =?UTF-8?q?=E6=98=BE=E7=A4=BA=E6=95=B0=E6=8D=AE=E8=BF=9E=E6=8E=A5=E5=B9=B6?= =?UTF-8?q?=E5=8F=AF=E5=BC=80=E5=85=B3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 网络管理器里补一条 cellular 连接,开机和断线由它自动拨号,面板每 30 秒巡检兜底。 APN 留空时由网络下发;基带 1 号配置里存着 APN 时照抄过来,否则空 APN 会被拒绝。 首页保存 APN 后同步到连接配置,基带配置变了先重新附着再重拨。 飞行模式打开时主动断开,关掉后在后台补拨。刷机镜像里预置同一份连接配置。 面板升到 1.0。 --- image/debian/UFI003_MB_V02/build-image.sh | 1 + .../UFI003_MB_V02/cellular.nmconnection | 17 + image/debian/UFI003_MB_V02/update-panel.sh | 11 + mifipanel/Cargo.lock | 2 +- mifipanel/Cargo.toml | 2 +- mifipanel/src/api_cell.rs | 21 + mifipanel/src/cellular.rs | 536 +++++++++++++++++- mifipanel/src/classic.rs | 21 +- mifipanel/src/metrics.rs | 8 + mifipanel/src/pages/welcome.html | 59 +- mifipanel/src/settings.rs | 2 +- mifipanel/web/i18n/i18n.js | 2 +- mifipanel/web/i18n/locales/en.json | 4 + mifipanel/web/i18n/locales/kk.json | 4 + mifipanel/web/i18n/locales/zh-CN.json | 4 + mifipanel/web/i18n/locales/zh-TW.json | 4 + 16 files changed, 685 insertions(+), 13 deletions(-) create mode 100644 image/debian/UFI003_MB_V02/cellular.nmconnection diff --git a/image/debian/UFI003_MB_V02/build-image.sh b/image/debian/UFI003_MB_V02/build-image.sh index 6422fdf..8347d58 100644 --- a/image/debian/UFI003_MB_V02/build-image.sh +++ b/image/debian/UFI003_MB_V02/build-image.sh @@ -270,6 +270,7 @@ install -d -m 755 /mnt/r/usr/local/sbin /mnt/r/etc/systemd/system/openstick-gc-s install -m 755 "$usb_src" /mnt/r/usr/local/sbin/mifipanel-usb.sh install -m 644 "$usb_dir/windows-rndis.conf" /mnt/r/etc/systemd/system/openstick-gc-startup.service.d/windows-rndis.conf install -m 600 "$usb_dir/usb-failsafe.nmconnection" /mnt/r/etc/NetworkManager/system-connections/usb-failsafe.nmconnection +install -m 600 "$usb_dir/cellular.nmconnection" /mnt/r/etc/NetworkManager/system-connections/cellular.nmconnection ln -sfn /dev/null /mnt/r/etc/systemd/system/openstick-sim-changer.service rm -f /mnt/r/etc/systemd/system/default.target.wants/openstick-sim-changer.service \ /mnt/r/etc/systemd/system/multi-user.target.wants/openstick-sim-changer.service \ diff --git a/image/debian/UFI003_MB_V02/cellular.nmconnection b/image/debian/UFI003_MB_V02/cellular.nmconnection new file mode 100644 index 0000000..03ac3cf --- /dev/null +++ b/image/debian/UFI003_MB_V02/cellular.nmconnection @@ -0,0 +1,17 @@ +[connection] +id=cellular +uuid=6f0c2a14-7e3b-4d58-9a1e-2b8c5d0e4f17 +type=gsm +autoconnect=true + +[gsm] +auto-config=false + +[ipv4] +method=auto + +[ipv6] +addr-gen-mode=default +method=auto + +[proxy] diff --git a/image/debian/UFI003_MB_V02/update-panel.sh b/image/debian/UFI003_MB_V02/update-panel.sh index 5a85b15..35cbdaa 100644 --- a/image/debian/UFI003_MB_V02/update-panel.sh +++ b/image/debian/UFI003_MB_V02/update-panel.sh @@ -46,6 +46,14 @@ while read -r file; do put "$PANEL/web/${file#./}" "$WEB_DEST/${file#./}" 0100644 done < /tmp/web.list +# 蜂窝拨号配置。网络管理器开机读到它,基带就绪后自动拨号。 +CELL=/recipe/cellular.nmconnection +CELL_DEST=/etc/NetworkManager/system-connections/cellular.nmconnection +[ -f "$CELL" ] || { echo "缺少 $CELL。请把 image/debian/UFI003_MB_V02 挂到 /recipe。" >&2; exit 1; } +echo "mkdir /etc/NetworkManager" >> "$cmds" +echo "mkdir /etc/NetworkManager/system-connections" >> "$cmds" +put "$CELL" "$CELL_DEST" 0100600 + # rm 和 mkdir 在目标不存在或已存在时会报错,属于正常情况;写得对不对由后面的逐个比对来判断。 debugfs -w -f "$cmds" "$IMG" >/tmp/update-panel.log 2>&1 || true @@ -70,6 +78,9 @@ while read -r file; do check "$PANEL/web/${file#./}" "$WEB_DEST/${file#./}" count=$((count + 1)) done < /tmp/web.list +check "$CELL" "$CELL_DEST" +debugfs -R "stat $CELL_DEST" "$IMG" 2>/dev/null | grep -q "Mode: 0600" \ + || { echo "蜂窝连接配置权限不是 600,网络管理器会忽略它" >&2; exit 1; } debugfs -R "stat /usr/local/bin/mifipanel" "$IMG" 2>/dev/null | awk '/Mode:/ {print "程序权限 " $0}' debugfs -R "ls /etc/systemd/system/multi-user.target.wants" "$IMG" 2>/dev/null | tr -s ' \n' ' ' | grep -q mifipanel.service \ || { echo "镜像里面板没有设成开机启动" >&2; exit 1; } diff --git a/mifipanel/Cargo.lock b/mifipanel/Cargo.lock index cad9bd2..8d8f279 100644 --- a/mifipanel/Cargo.lock +++ b/mifipanel/Cargo.lock @@ -737,7 +737,7 @@ dependencies = [ [[package]] name = "mifipanel" -version = "0.9.0" +version = "1.0.0" dependencies = [ "axum", "base64 0.22.1", diff --git a/mifipanel/Cargo.toml b/mifipanel/Cargo.toml index d071a1b..36e0f98 100644 --- a/mifipanel/Cargo.toml +++ b/mifipanel/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "mifipanel" -version = "0.9.0" +version = "1.0.0" edition = "2021" description = "随身 WiFi、CPE 和手机上的短信与设备管理面板" diff --git a/mifipanel/src/api_cell.rs b/mifipanel/src/api_cell.rs index ab2e0b6..23e274f 100644 --- a/mifipanel/src/api_cell.rs +++ b/mifipanel/src/api_cell.rs @@ -17,6 +17,7 @@ pub fn routes() -> Router> { .route("/Home/Pin", get(pin_get).post(pin_post)) .route("/Home/Modes", get(modes_get).post(modes_post)) .route("/Home/Airplane", post(airplane_post)) + .route("/Home/Wan", post(wan_post)) .route("/Home/Traffic", get(traffic_page)) .route("/Home/Traffic/Status", get(traffic_status)) .route("/Home/Traffic/Save", post(traffic_save)) @@ -25,6 +26,14 @@ pub fn routes() -> Router> { pub fn start(app: &Arc) { crate::cellular::load_airplane(&app.data); + tokio::spawn(async move { + // 第一轮尽早做:旧镜像里没有蜂窝连接,要先建好,网络管理器才会在基带就绪时自动拨号。 + tokio::time::sleep(std::time::Duration::from_secs(3)).await; + loop { + tokio::task::spawn_blocking(crate::cellular::maintain_wan).await.ok(); + tokio::time::sleep(std::time::Duration::from_secs(30)).await; + } + }); let watch = Arc::clone(app); tokio::spawn(async move { loop { @@ -138,6 +147,18 @@ struct AirBody { on: bool, } +async fn wan_post(State(app): State>, headers: HeaderMap, Json(body): Json) -> Response { + if http::current_user(&app, &headers).is_none() { + return guest(); + } + let on = body.on; + match tokio::task::spawn_blocking(move || crate::cellular::set_wan(on)).await { + Ok(Ok(())) => Json(json!({ "ok": true })).into_response(), + Ok(Err(err)) => fail(err), + Err(_) => fail("error.cell.wan".into()), + } +} + async fn airplane_post(State(app): State>, headers: HeaderMap, Json(body): Json) -> Response { if http::current_user(&app, &headers).is_none() { return guest(); diff --git a/mifipanel/src/cellular.rs b/mifipanel/src/cellular.rs index ff11a5f..7577478 100644 --- a/mifipanel/src/cellular.rs +++ b/mifipanel/src/cellular.rs @@ -1,4 +1,4 @@ -//! 飞行模式、SIM PIN 和网络模式。流量统计在 traffic.rs。 +//! 飞行模式、SIM PIN、网络模式和蜂窝拨号。流量统计在 traffic.rs。 #[path = "traffic.rs"] pub(crate) mod traffic; @@ -77,6 +77,20 @@ pub fn set_airplane(root: &Path, on: bool) -> Result<(), String> { DESIRED.store(on, Ordering::Relaxed); mark_done(&node, on); mmcli::invalidate_radio(); + if on { + drop_wan(); + } else { + // 射频回来后要等注册,不让开关接口等着,放到后台补拨。 + std::thread::spawn(|| { + for _ in 0..12 { + std::thread::sleep(std::time::Duration::from_secs(5)); + maintain_wan(); + if wan_view().state == "activated" { + break; + } + } + }); + } Ok(()) } #[cfg(not(target_os = "linux"))] @@ -479,6 +493,474 @@ fn strip_ansi(text: &str) -> String { out } +/// 蜂窝数据连接的名字。镜像里的配置和面板创建的是同一个。 +const WAN_NAME: &str = "cellular"; +const WAN_UUID: &str = "6f0c2a14-7e3b-4d58-9a1e-2b8c5d0e4f17"; +#[cfg(target_os = "linux")] +const WAN_FILE: &str = "/etc/NetworkManager/system-connections/cellular.nmconnection"; + +#[cfg(target_os = "linux")] +static WAN_LOCK: Mutex<()> = Mutex::new(()); + +#[derive(Clone, Debug, PartialEq, Eq)] +pub(crate) struct WanProfile { + pub enabled: bool, + pub apn: String, + pub ip: String, + pub user: String, + pub password: String, + pub uuid: String, +} + +impl Default for WanProfile { + fn default() -> Self { + Self { + enabled: true, + apn: String::new(), + ip: "ipv4v6".into(), + user: String::new(), + password: String::new(), + uuid: WAN_UUID.into(), + } + } +} + +#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)] +pub struct WanView { + pub enabled: bool, + pub state: String, + pub ip: String, +} + +impl Default for WanView { + fn default() -> Self { + Self { enabled: false, state: "unavailable".into(), ip: String::new() } + } +} + +/// APN 留空时不写 apn,由网络下发默认接入点。不开 auto-config:它要靠运营商资料库, +/// 镜像里没有这个库时直接拨号失败。 +pub(crate) fn render_profile(profile: &WanProfile) -> String { + let on = if profile.enabled { "true" } else { "false" }; + let mut gsm = String::from("auto-config=false\n"); + if !profile.apn.is_empty() { + gsm.push_str(&format!("apn={}\n", profile.apn)); + if !profile.user.is_empty() { + gsm.push_str(&format!("username={}\n", profile.user)); + } + // 没有密码时标成不需要,否则填了用户名的连接会一直等密码。 + if profile.password.is_empty() { + gsm.push_str("password-flags=4\n"); + } else { + gsm.push_str(&format!("password={}\npassword-flags=0\n", profile.password)); + } + } + let (v4, v6) = match profile.ip.as_str() { + "ipv4" => ("auto", "disabled"), + "ipv6" => ("disabled", "auto"), + _ => ("auto", "auto"), + }; + format!("[connection]\nid={WAN_NAME}\nuuid={}\ntype=gsm\nautoconnect={on}\n\n[gsm]\n{gsm}\n[ipv4]\nmethod={v4}\n\n[ipv6]\naddr-gen-mode=default\nmethod={v6}\n\n[proxy]\n", profile.uuid) +} + +pub(crate) fn parse_profile(text: &str) -> WanProfile { + let mut profile = WanProfile::default(); + let mut section = String::new(); + let mut v4 = String::new(); + let mut v6 = String::new(); + for raw in text.lines() { + let line = raw.trim(); + if line.is_empty() || line.starts_with('#') { + continue; + } + if line.starts_with('[') && line.ends_with(']') { + section = line[1..line.len() - 1].to_string(); + continue; + } + let Some((key, value)) = line.split_once('=') else { continue }; + let value = value.trim(); + match (section.as_str(), key.trim()) { + ("connection", "uuid") if !value.is_empty() => profile.uuid = value.to_string(), + ("connection", "autoconnect") => profile.enabled = !matches!(value, "false" | "no" | "0"), + ("gsm", "apn") => profile.apn = value.to_string(), + ("gsm", "username") => profile.user = value.to_string(), + ("gsm", "password") => profile.password = value.to_string(), + ("ipv4", "method") => v4 = value.to_string(), + ("ipv6", "method") => v6 = value.to_string(), + _ => {} + } + } + profile.ip = match (v4.as_str(), v6.as_str()) { + ("disabled", _) => "ipv6".into(), + (_, "disabled") => "ipv4".into(), + _ => "ipv4v6".into(), + }; + profile +} + +/// 读 `nmcli -t -f GENERAL.STATE,IP4.ADDRESS,IP6.ADDRESS connection show cellular` 的输出。 +/// 连接没激活时没有 GENERAL.STATE 这一行,算未连接。地址优先给 IPv4。 +pub(crate) fn parse_show(text: &str) -> (&'static str, String) { + let mut state = "disconnected"; + let mut v4 = String::new(); + let mut v6 = String::new(); + for raw in text.lines() { + let line = strip_color(raw.trim()); + let Some((key, value)) = line.split_once(':') else { continue }; + let value = value.trim().replace('\\', ""); + let addr = value.split('/').next().unwrap_or("").trim().to_string(); + if key == "GENERAL.STATE" { + state = match value.as_str() { + "activated" => "activated", + "activating" | "deactivating" => "activating", + _ => "disconnected", + }; + } else if key.starts_with("IP4.ADDRESS") && v4.is_empty() { + v4 = addr; + } else if key.starts_with("IP6.ADDRESS") && v6.is_empty() { + v6 = addr; + } + } + if state != "activated" { + return (state, String::new()); + } + (state, if v4.is_empty() { v6 } else { v4 }) +} + +/// `nmcli -t -f TYPE,STATE device` 里有一台空闲的 gsm 设备,说明基带已经交给网络管理器、可以拨号。 +pub(crate) fn gsm_idle(text: &str) -> bool { + text.lines().any(|raw| strip_color(raw.trim()) == "gsm:disconnected") +} + +fn strip_color(text: &str) -> String { + let mut out = String::new(); + let mut chars = text.chars().peekable(); + while let Some(ch) = chars.next() { + if ch == '\u{1b}' { + while let Some(next) = chars.next() { + if next.is_ascii_alphabetic() { + break; + } + } + } else { + out.push(ch); + } + } + out +} + +/// 缺连接配置就补上;该连着却没连上、基带已经注册时再拨一次。 +/// 网络管理器自己会在开机和断线时自动拨号,这里兜住它重试几次后放弃的情况。 +pub fn maintain_wan() { + #[cfg(target_os = "linux")] + maintain_wan_linux(); +} + +pub fn wan_view() -> WanView { + #[cfg(target_os = "linux")] + { + query_wan() + } + #[cfg(not(target_os = "linux"))] + { + WanView::default() + } +} + +/// 打开时先记下开关再拨号。拨不上(没信号、飞行模式)也算保存成功,之后由网络管理器和巡检接着拨。 +pub fn set_wan(on: bool) -> Result<(), String> { + #[cfg(target_os = "linux")] + { + set_wan_linux(on) + } + #[cfg(not(target_os = "linux"))] + { + let _ = on; + Err("error.cell.wan".into()) + } +} + +/// 首页保存 APN 之后,把同一份设置写进网络管理器并重拨。APN 留空则由网络下发。 +/// `modem_changed` 表示基带 1 号配置刚被改过,要重新附着一次。 +pub fn sync_wan(apn: &str, ip: &str, user: &str, password: &str, modem_changed: bool) -> Result<(), String> { + #[cfg(target_os = "linux")] + { + sync_wan_linux(apn, ip, user, password, modem_changed) + } + #[cfg(not(target_os = "linux"))] + { + let _ = (apn, ip, user, password, modem_changed); + Ok(()) + } +} + +#[cfg(target_os = "linux")] +fn maintain_wan_linux() { + let _guard = WAN_LOCK.lock().unwrap_or_else(|err| err.into_inner()); + if !nmcli_ready() { + return; + } + if !std::path::Path::new(WAN_FILE).is_file() && !nm_has_cellular() { + if write_profile(&WanProfile::default()).is_err() || load_profile().is_err() { + return; + } + clear_wan_cache(); + } + if !read_profile().enabled { + return; + } + let state = query_wan_uncached().state; + if airplane_desired() { + // 飞行模式是直接对基带下的命令,网络管理器不知道射频关了,会一直卡在“连接中”。 + if state != "disconnected" { + let _ = nmcli(&["-c", "no", "connection", "down", WAN_NAME], std::time::Duration::from_secs(15)); + clear_wan_cache(); + } + return; + } + if matches!(state.as_str(), "activated" | "activating") { + return; + } + let idle = nmcli_text(&["-c", "no", "-t", "-f", "TYPE,STATE", "device"], std::time::Duration::from_secs(5)) + .map(|text| gsm_idle(&text)) + .unwrap_or(false); + if !idle || !registered() { + return; + } + adopt_modem_apn(); + let _ = nmcli(&["-c", "no", "-w", "40", "connection", "up", WAN_NAME], std::time::Duration::from_secs(45)); + mmcli::invalidate_radio(); + clear_wan_cache(); +} + +/// 基带 1 号配置同时是 LTE 附着用的接入点。它里面存着 APN 时,基带不接受空 APN 拨号 +/// (null-apn-disallowed),所以连接配置没写 APN 就照抄基带的。基带读不出密码,只抄 APN 和用户名。 +#[cfg(target_os = "linux")] +fn adopt_modem_apn() { + let mut profile = read_profile(); + if !profile.apn.is_empty() { + return; + } + let Ok(modem) = crate::radio_adapt::apn_get() else { return }; + if modem.apn.is_empty() { + return; + } + profile.apn = modem.apn; + profile.user = modem.user; + profile.ip = modem.ip; + if write_profile(&profile).is_ok() { + let _ = load_profile(); + } +} + +#[cfg(target_os = "linux")] +fn drop_wan() { + if nmcli_ready() { + let _ = nmcli(&["-c", "no", "connection", "down", WAN_NAME], std::time::Duration::from_secs(15)); + clear_wan_cache(); + } +} + +/// 关开一次射频,让基带断开后重新附着网络。飞行模式开着就不动:射频本来就关着,关掉飞行模式时自然会重新附着。 +#[cfg(target_os = "linux")] +pub(crate) fn cycle_radio() { + let _air = AIR_LOCK.lock().unwrap_or_else(|err| err.into_inner()); + if airplane_desired() { + return; + } + let Some(node) = qmi_node() else { return }; + let _ = set_operating(&node, true); + if set_operating(&node, false).is_err() { + let _ = set_operating(&node, false); + } + mmcli::invalidate_radio(); +} + +/// 改过基带 1 号配置后让基带用新的接入点重新附着,再等它注册回来。 +/// 不这样做的话,改回空 APN 时基带还挂在旧接入点上,空 APN 拨号会被拒绝。 +#[cfg(target_os = "linux")] +fn reattach() { + if airplane_desired() { + return; + } + cycle_radio(); + for _ in 0..20 { + std::thread::sleep(std::time::Duration::from_secs(2)); + if registered() { + break; + } + } + mmcli::invalidate_radio(); +} + +#[cfg(target_os = "linux")] +fn registered() -> bool { + let Ok(modem) = mmcli::active_modem() else { return false }; + let Ok(text) = mmcli::run(&["-m".into(), modem.to_string(), "-K".into()]) else { return false }; + matches!(mmcli::facts_from_kv(&text).registration.as_str(), "home" | "roaming") +} + +#[cfg(target_os = "linux")] +fn set_wan_linux(on: bool) -> Result<(), String> { + let _guard = WAN_LOCK.lock().unwrap_or_else(|err| err.into_inner()); + if !nmcli_ready() { + return Err("error.cell.wan".into()); + } + let mut profile = read_profile(); + profile.enabled = on; + write_profile(&profile)?; + load_profile()?; + if on { + if !airplane_desired() { + let _ = nmcli(&["-c", "no", "-w", "40", "connection", "up", WAN_NAME], std::time::Duration::from_secs(45)); + } + } else { + let _ = nmcli(&["-c", "no", "connection", "down", WAN_NAME], std::time::Duration::from_secs(15)); + } + mmcli::invalidate_radio(); + clear_wan_cache(); + Ok(()) +} + +#[cfg(target_os = "linux")] +fn sync_wan_linux(apn: &str, ip: &str, user: &str, password: &str, modem_changed: bool) -> Result<(), String> { + let _guard = WAN_LOCK.lock().unwrap_or_else(|err| err.into_inner()); + if !nmcli_ready() { + return Err("error.cell.wan".into()); + } + let old = read_profile(); + let mut profile = old.clone(); + profile.apn = apn.trim().to_string(); + profile.ip = if matches!(ip, "ipv4" | "ipv6" | "ipv4v6") { ip.to_string() } else { "ipv4v6".into() }; + profile.user = user.trim().to_string(); + profile.password = password.to_string(); + // 基带和连接配置都没变而且已经连着,就不断开重拨。 + if !modem_changed && profile == old && query_wan_uncached().state == "activated" { + return Ok(()); + } + write_profile(&profile)?; + load_profile()?; + clear_wan_cache(); + if airplane_desired() { + return Ok(()); + } + if profile.enabled { + let _ = nmcli(&["-c", "no", "connection", "down", WAN_NAME], std::time::Duration::from_secs(15)); + } + if modem_changed { + reattach(); + } + if !profile.enabled { + return Ok(()); + } + let result = nmcli(&["-c", "no", "-w", "40", "connection", "up", WAN_NAME], std::time::Duration::from_secs(45)); + mmcli::invalidate_radio(); + clear_wan_cache(); + result +} + +#[cfg(target_os = "linux")] +fn read_profile() -> WanProfile { + std::fs::read_to_string(WAN_FILE).map(|text| parse_profile(&text)).unwrap_or_default() +} + +#[cfg(target_os = "linux")] +fn write_profile(profile: &WanProfile) -> Result<(), String> { + use std::io::Write; + use std::os::unix::fs::OpenOptionsExt; + let dir = std::path::Path::new("/etc/NetworkManager/system-connections"); + std::fs::create_dir_all(dir).map_err(|_| "error.cell.wan".to_string())?; + let mut file = std::fs::OpenOptions::new() + .create(true) + .write(true) + .truncate(true) + .mode(0o600) + .open(WAN_FILE) + .map_err(|_| "error.cell.wan".to_string())?; + file.write_all(render_profile(profile).as_bytes()).map_err(|_| "error.cell.wan".to_string())?; + Ok(()) +} + +#[cfg(target_os = "linux")] +fn load_profile() -> Result<(), String> { + nmcli(&["connection", "load", WAN_FILE], std::time::Duration::from_secs(8)) +} + +#[cfg(target_os = "linux")] +fn nm_has_cellular() -> bool { + nmcli_text(&["-c", "no", "-t", "-f", "NAME", "connection", "show"], std::time::Duration::from_secs(5)) + .map(|text| text.lines().any(|line| strip_color(line).trim() == WAN_NAME)) + .unwrap_or(false) +} + +#[cfg(target_os = "linux")] +fn nmcli_ready() -> bool { + std::path::Path::new("/usr/bin/nmcli").is_file() +} + +#[cfg(target_os = "linux")] +fn nmcli(args: &[&str], limit: std::time::Duration) -> Result<(), String> { + nmcli_text(args, limit).map(|_| ()) +} + +#[cfg(target_os = "linux")] +fn nmcli_text(args: &[&str], limit: std::time::Duration) -> Result { + let mut cmd = std::process::Command::new("/usr/bin/nmcli"); + cmd.args(args).env("LANG", "C"); + let output = mmcli::output_within(cmd, limit).map_err(|_| "error.cell.wan".to_string())?; + let text = strip_color(&format!("{}{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr))); + if output.status.success() { + Ok(text.trim().to_string()) + } else { + eprintln!("cellular: {}", text.trim().chars().take(180).collect::()); + Err("error.cell.wan".into()) + } +} + +#[cfg(target_os = "linux")] +struct WanSlot { + at: std::time::Instant, + view: WanView, +} + +#[cfg(target_os = "linux")] +static WAN_CACHE: Mutex> = Mutex::new(None); + +/// 首页每 2 秒采样一次,这里缓存 5 秒,免得每次都跑 nmcli。 +#[cfg(target_os = "linux")] +fn query_wan() -> WanView { + { + let slot = WAN_CACHE.lock().unwrap_or_else(|err| err.into_inner()); + if let Some(slot) = slot.as_ref() { + if slot.at.elapsed() < std::time::Duration::from_secs(5) { + return slot.view.clone(); + } + } + } + let view = query_wan_uncached(); + *WAN_CACHE.lock().unwrap_or_else(|err| err.into_inner()) = Some(WanSlot { at: std::time::Instant::now(), view: view.clone() }); + view +} + +#[cfg(target_os = "linux")] +fn clear_wan_cache() { + *WAN_CACHE.lock().unwrap_or_else(|err| err.into_inner()) = None; +} + +#[cfg(target_os = "linux")] +fn query_wan_uncached() -> WanView { + if !nmcli_ready() { + return WanView::default(); + } + let text = nmcli_text( + &["-c", "no", "-t", "-f", "GENERAL.STATE,IP4.ADDRESS,IP6.ADDRESS", "connection", "show", WAN_NAME], + std::time::Duration::from_secs(5), + ) + .unwrap_or_default(); + let (state, ip) = parse_show(&text); + WanView { enabled: read_profile().enabled, state: state.into(), ip } +} + #[cfg(test)] mod tests { use super::*; @@ -520,4 +1002,56 @@ mod tests { assert!(require_pin("1234").is_ok()); assert_eq!(require_pin("12").unwrap_err(), "error.cell.pin"); } + + #[test] + fn default_cellular_profile_autoconnects_with_network_apn() { + let text = render_profile(&WanProfile::default()); + let shipped = include_str!("../../image/debian/UFI003_MB_V02/cellular.nmconnection").replace("\r\n", "\n"); + assert_eq!(text, shipped); + assert_eq!(parse_profile(&text), WanProfile::default()); + assert!(text.contains("autoconnect=true\n")); + assert!(text.contains("auto-config=false\n")); + assert!(!text.contains("apn=")); + // nmcli 改写过的文件不写 autoconnect,默认就是自动连接。 + let rewritten = "[connection]\nid=cellular\nuuid=2fee917b-d2cf-4985-8a25-7a1f1d63c648\ntype=gsm\n\n[gsm]\n\n[ipv4]\nmethod=auto\n"; + let parsed = parse_profile(rewritten); + assert!(parsed.enabled); + assert_eq!(parsed.apn, ""); + assert_eq!(parsed.uuid, "2fee917b-d2cf-4985-8a25-7a1f1d63c648"); + } + + #[test] + fn explicit_apn_roundtrips_and_selects_ip_family() { + let profile = WanProfile { + enabled: false, + apn: "ctnet".into(), + ip: "ipv4".into(), + user: "ctnet@mycdma.cn".into(), + password: "vnet.mobi".into(), + uuid: "2fee917b-d2cf-4985-8a25-7a1f1d63c648".into(), + }; + let text = render_profile(&profile); + assert!(text.contains("auto-config=false\n")); + assert!(text.contains("autoconnect=false\n")); + assert!(text.contains("method=disabled\n")); + assert_eq!(parse_profile(&text), profile); + let open = render_profile(&WanProfile { password: String::new(), ..profile.clone() }); + assert!(open.contains("password-flags=4\n")); + assert!(!open.contains("password=")); + assert_eq!(parse_profile(&open).password, ""); + } + + #[test] + fn nmcli_show_and_device_output_are_read_from_real_samples() { + let active = "GENERAL.STATE:activated\nIP4.ADDRESS[1]:10.21.196.156/29\nIP6.ADDRESS[1]:240e:47c:56f0:f0e:69f6:b853:f50a:42fd/64\n"; + assert_eq!(parse_show(active), ("activated", "10.21.196.156".to_string())); + let v6 = "GENERAL.STATE:activated\nIP6.ADDRESS[1]:240e\\:47c\\:56f0::1/64\n"; + assert_eq!(parse_show(v6), ("activated", "240e:47c:56f0::1".to_string())); + assert_eq!(parse_show("GENERAL.STATE:activating\n"), ("activating", String::new())); + assert_eq!(parse_show(""), ("disconnected", String::new())); + let devices = "ethernet:connected\nbridge:connected (externally)\nloopback:connected (externally)\n\u{1b}[31mgsm:disconnected\u{1b}[0m\nwifi:unmanaged\n"; + assert!(gsm_idle(devices)); + assert!(!gsm_idle("gsm:unavailable\n")); + assert!(!gsm_idle("gsm:connected\n")); + } } diff --git a/mifipanel/src/classic.rs b/mifipanel/src/classic.rs index 0fd4f8f..dd1ec1d 100644 --- a/mifipanel/src/classic.rs +++ b/mifipanel/src/classic.rs @@ -245,9 +245,24 @@ async fn apn_set(State(app): State>, headers: HeaderMap, axum::Jso if http::current_user(&app, &headers).is_none() { return axum::Json(serde_json::json!({"error": "error.session"})).into_response(); } - match block_modem(Arc::clone(&app), move |_| crate::radio_adapt::apn_set(&body.apn, &body.ip, &body.user, &body.password, &body.auth)).await { - Ok(()) => axum::Json(serde_json::json!({"ok": true})).into_response(), - Err(err) => axum::Json(serde_json::json!({"error": err})).into_response(), + let wan = (body.apn.clone(), body.ip.clone(), body.user.clone(), body.password.clone()); + let changed = block_modem(Arc::clone(&app), move |_| { + let before = crate::radio_adapt::apn_get().ok(); + crate::radio_adapt::apn_set(&body.apn, &body.ip, &body.user, &body.password, &body.auth)?; + // 基带读不出密码,填了密码就当作改过。 + Ok(before.map_or(true, |old| { + old.apn != body.apn || old.ip != body.ip || old.user != body.user || old.auth != body.auth || !body.password.is_empty() + })) + }).await; + let changed = match changed { + Ok(changed) => changed, + Err(err) => return axum::Json(serde_json::json!({"error": err})).into_response(), + }; + // 重拨要几十秒,放在基带锁外面做,不挡住短信和其他基带操作。 + match tokio::task::spawn_blocking(move || crate::cellular::sync_wan(&wan.0, &wan.1, &wan.2, &wan.3, changed)).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(_) => axum::Json(serde_json::json!({"error": "error.cell.wan"})).into_response(), } } diff --git a/mifipanel/src/metrics.rs b/mifipanel/src/metrics.rs index 90b8233..588a55c 100644 --- a/mifipanel/src/metrics.rs +++ b/mifipanel/src/metrics.rs @@ -71,6 +71,10 @@ pub struct Metrics { pub sim_modes: bool, /// 飞行模式开关显示保存的期望,不跟着基带滞后的瞬时状态来回跳。 pub sim_airplane: bool, + /// 数据开关是用户期望。state 为 activated / activating / disconnected / unavailable。 + pub wan_enabled: bool, + pub wan_state: String, + pub wan_ip: String, } #[derive(Clone, Serialize)] @@ -240,6 +244,7 @@ fn linux_sample() -> Result { let system = read_uname(); let times = read_times(); let radio = crate::mmcli::radio(modem_index()); + let wan = crate::cellular::wan_view(); Ok(Metrics { load1, load_percent, @@ -307,6 +312,9 @@ fn linux_sample() -> Result { sim_present: radio.link.sim, sim_modes: radio.link.modes, sim_airplane: crate::cellular::airplane_desired(), + wan_enabled: wan.enabled, + wan_state: wan.state, + wan_ip: wan.ip, }) } diff --git a/mifipanel/src/pages/welcome.html b/mifipanel/src/pages/welcome.html index c476381..bbd589b 100644 --- a/mifipanel/src/pages/welcome.html +++ b/mifipanel/src/pages/welcome.html @@ -13,7 +13,7 @@ - +