Files
LTEDongle/flasher/src/adb.rs
T
nixevol d951535e30 feat: 面板加入网页终端,并自带离线依赖
只更新面板、不重刷系统时,终端和热点仍能用包里的 ttyd 与 hostapd。
2026-11-30 18:07:35 +08:00

546 lines
19 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use std::io::Read;
use std::process::Stdio;
use std::sync::Mutex;
use std::time::Duration;
use super::command;
#[derive(Clone, Debug)]
pub struct AdbDevice {
pub serial: String,
pub transport: String,
pub chip: String,
pub port: String,
pub cores: String,
pub memory: String,
pub disk: String,
pub system: String,
pub marked: String,
pub host: String,
pub board_model: String,
pub mark_chip: String,
pub panel_version: String,
pub status: String,
/// 这次刷新已经从设备读到硬件信息。版本另查,避免查版本失败时把整行丢掉。
pub probed: bool,
}
pub fn list_devices() -> Vec<AdbDevice> {
let _guard = adb_lock();
let text = match adb_output(&["devices", "-l"]) {
Ok(text) => text,
Err(_) => return Vec::new(),
};
let mut found = Vec::new();
for line in text.lines().skip(1) {
let line = line.trim();
if line.is_empty() {
continue;
}
let mut parts = line.split_whitespace();
let Some(serial) = parts.next() else { continue };
let Some(state) = parts.next() else { continue };
if state == "device" || state == "unauthorized" || state == "offline" {
let transport = line
.split_whitespace()
.find_map(|part| part.strip_prefix("transport_id:"))
.unwrap_or("")
.to_string();
found.push((serial.to_string(), state.to_string(), transport));
}
}
found
.into_iter()
.map(|(serial, state, transport)| {
let mut device = if state == "device" {
probe(&serial, &transport).unwrap_or_else(|_| AdbDevice::bare(serial.clone(), transport.clone()))
} else {
let mut device = AdbDevice::bare(serial.clone(), transport.clone());
device.marked = match state.as_str() {
"unauthorized" => "未授权".into(),
_ => "离线".into(),
};
device
};
if device.port.is_empty() {
device.port = windows_port(&serial);
}
device
})
.collect()
}
impl AdbDevice {
fn bare(serial: String, transport: String) -> Self {
Self {
serial,
transport,
chip: String::new(),
port: String::new(),
cores: String::new(),
memory: String::new(),
disk: String::new(),
system: String::new(),
marked: "未标记".into(),
host: String::new(),
board_model: String::new(),
mark_chip: String::new(),
panel_version: String::new(),
status: String::new(),
probed: false,
}
}
}
pub fn mark(device: &AdbDevice, _chip_serial: &str, _model_id: &str) -> Result<String, String> {
let _guard = adb_lock();
let text = shell(device, &devinfo_script())?;
let chip_serial = devinfo_chip(&text);
if chip_serial.len() < 4
|| chip_serial.len() > 16
|| !chip_serial.chars().all(|ch| ch.is_ascii_hexdigit())
{
return Err("devinfo 里没有芯片号".into());
}
// gc 每次开机都把序列号写成 0123456789,管理脚本里的那一行并不会被执行。
// 在 gc 完成后再改序列号并重新绑定。不能在当前这条 ADB 里直接改,断开 USB 会把脚本一起杀掉。
shell(device, &install_serial_service())?;
Ok(chip_serial)
}
fn install_serial_service() -> String {
r#"
mkdir -p /usr/local/sbin /etc/systemd/system
cat > /usr/local/sbin/flasher-serial.sh << 'EOF'
#!/bin/sh
part=/dev/disk/by-partlabel/devinfo
if [ ! -b "$part" ]; then
exit 0
fi
sz=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
if [ "$sz" -le 0 ]; then
exit 0
fi
chip=$(dd if="$part" bs=512 skip=$((sz - 1)) count=1 status=none 2>/dev/null | tr -d '\000' | sed -n 's/^chip_serial=//p' | head -n 1)
echo "$chip" | grep -Eq '^[0-9A-Fa-f]{4,16}$' || exit 0
gadget=/sys/kernel/config/usb_gadget/g1
strings=$gadget/strings/0x409
i=0
while [ ! -d "$strings" ] && [ "$i" -lt 20 ]; do
sleep 0.5
i=$((i + 1))
done
if [ ! -d "$strings" ]; then
exit 0
fi
current=$(cat "$strings/serialnumber" 2>/dev/null || true)
if [ "$current" = "$chip" ]; then
exit 0
fi
udc=$(cat "$gadget/UDC" 2>/dev/null || true)
rebind() {
if [ -n "$udc" ]; then
now=$(cat "$gadget/UDC" 2>/dev/null || true)
if [ -z "$now" ]; then
echo "$udc" > "$gadget/UDC" || true
fi
fi
}
trap rebind EXIT
if [ -n "$udc" ]; then
echo > "$gadget/UDC" || exit 0
fi
sleep 0.2
if ! echo "$chip" > "$strings/serialnumber"; then
exit 0
fi
exit 0
EOF
chmod 755 /usr/local/sbin/flasher-serial.sh
cat > /etc/systemd/system/flasher-serial.service << 'EOF'
[Unit]
Description=Apply chip serial to USB gadget
After=openstick-gc-startup.service
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/flasher-serial.sh
[Install]
WantedBy=multi-user.target
EOF
chmod 644 /etc/systemd/system/flasher-serial.service
systemctl daemon-reload
systemctl enable flasher-serial.service
"#
.into()
}
pub fn reboot(device: &AdbDevice) -> Result<(), String> {
let _guard = adb_lock();
shell(device, "reboot")?;
Ok(())
}
fn probe(serial: &str, transport: &str) -> Result<AdbDevice, String> {
let script = r#"
printf 'CHIP=%s\n' "$(cat /sys/bus/soc/devices/soc0/machine 2>/dev/null)"
printf 'CORES=%s\n' "$(grep -c ^processor /proc/cpuinfo 2>/dev/null)"
printf 'MEM=%s\n' "$(awk '/MemTotal/ {print $2}' /proc/meminfo 2>/dev/null)"
printf 'DISK=%s\n' "$(cat /sys/block/mmcblk0/size 2>/dev/null)"
printf 'OS=%s\n' "$(. /etc/os-release 2>/dev/null; printf '%s' "$PRETTY_NAME")"
part=/dev/disk/by-partlabel/devinfo
if [ -b "$part" ]; then
sz=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
if [ "$sz" -gt 0 ]; then
data=$(dd if="$part" bs=512 skip=$((sz-1)) count=1 status=none 2>/dev/null | tr -d '\000')
printf 'DEVINFO_CHIP=%s\n' "$(printf '%s\n' "$data" | sed -n 's/^chip_serial=//p' | head -n 1)"
fi
fi
printf 'HOST=%s\n' "$(hostname 2>/dev/null)"
printf 'MODEL=%s\n' "$(tr -d '\000' < /proc/device-tree/model 2>/dev/null)"
"#;
let text = shell_on(serial, transport, script)?;
let mut device = AdbDevice::bare(serial.to_string(), transport.to_string());
for line in text.lines() {
let Some((key, value)) = line.split_once('=') else { continue };
let value = value.trim();
match key {
"CHIP" => device.chip = value.to_string(),
"CORES" => device.cores = value.to_string(),
"MEM" => device.memory = format_kb(value),
"DISK" => device.disk = format_sectors(value),
"OS" => device.system = value.to_string(),
"HOST" => device.host = value.to_string(),
"MODEL" => device.board_model = value.to_string(),
"DEVINFO_CHIP" => device.mark_chip = value.to_string(),
_ => {}
}
}
if device.mark_chip.is_empty() {
device.marked = "无记录".into();
} else if device.serial.eq_ignore_ascii_case(&device.mark_chip) {
device.marked = "已标记".into();
} else {
device.marked = "未标记".into();
}
device.probed = true;
Ok(device)
}
fn devinfo_script() -> String {
r#"
part=/dev/disk/by-partlabel/devinfo
if [ ! -b "$part" ]; then
printf 'DEVINFO_CHIP=\n'
exit 0
fi
sz=$(blockdev --getsz "$part" 2>/dev/null || echo 0)
data=$(dd if="$part" bs=512 skip=$((sz-1)) count=1 status=none 2>/dev/null | tr -d '\000')
printf 'DEVINFO_CHIP=%s\n' "$(printf '%s\n' "$data" | sed -n 's/^chip_serial=//p' | head -n 1)"
"#
.into()
}
fn devinfo_chip(text: &str) -> String {
text.lines()
.find_map(|line| line.trim().strip_prefix("DEVINFO_CHIP="))
.unwrap_or("")
.trim()
.to_string()
}
fn shell(device: &AdbDevice, script: &str) -> Result<String, String> {
shell_on(&device.serial, &device.transport, script)
}
fn shell_on(serial: &str, transport: &str, script: &str) -> Result<String, String> {
// 把脚本作为 adb shell 的参数执行。用 stdin 喂给交互式 shell 时,命令跑完进程也不退出。
let mut cmd = command("adb");
if !transport.is_empty() {
cmd.arg("-t").arg(transport);
} else {
cmd.arg("-s").arg(serial);
}
let mut child = cmd
.arg("shell")
.arg(script)
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|err| format!("无法启动 adb:{err}"))?;
let mut stdout = child.stdout.take();
let started = std::time::Instant::now();
loop {
if let Some(status) = child.try_wait().map_err(|err| err.to_string())? {
let mut text = String::new();
if let Some(out) = stdout.as_mut() {
let _ = out.read_to_string(&mut text);
}
if status.success() {
return Ok(text);
}
return Err(if text.trim().is_empty() { "adb 命令失败".into() } else { text });
}
if started.elapsed() > Duration::from_secs(12) {
let _ = child.kill();
return Err("adb 命令超时".into());
}
std::thread::sleep(Duration::from_millis(50));
}
}
fn adb_output(args: &[&str]) -> Result<String, String> {
let output = command("adb").args(args).output().map_err(|err| err.to_string())?;
if !output.status.success() && output.stdout.is_empty() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
}
Ok(String::from_utf8_lossy(&output.stdout).to_string())
}
fn windows_port(serial: &str) -> String {
if serial.is_empty() || serial.contains(['\'', '"', ';', '&']) {
return String::new();
}
let script = r#"
Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like ('*' + $env:FLASHER_ADB + '*') } | ForEach-Object {
try {
$p = Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LocationInfo
$loc = [string]$p.Data
if ($loc) { Write-Output $loc }
} catch {}
}
"#;
let output = command("powershell")
.args(["-NoProfile", "-Command", script])
.env("FLASHER_ADB", serial)
.output();
let Ok(output) = output else { return String::new() };
String::from_utf8_lossy(&output.stdout)
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("")
.to_string()
}
fn format_kb(text: &str) -> String {
let Ok(kb) = text.trim().parse::<u64>() else { return String::new() };
format_bytes(kb * 1024)
}
fn format_sectors(text: &str) -> String {
let Ok(sectors) = text.trim().parse::<u64>() else { return String::new() };
format_bytes(sectors * 512)
}
fn format_bytes(bytes: u64) -> String {
const KB: f64 = 1024.0;
const MB: f64 = 1024.0 * 1024.0;
const GB: f64 = 1024.0 * 1024.0 * 1024.0;
let value = bytes as f64;
let (scaled, unit) = if value >= GB {
(value / GB, "GB")
} else if value >= MB {
(value / MB, "MB")
} else if value >= KB {
(value / KB, "KB")
} else {
return format!("{bytes}B");
};
if scaled >= 100.0 || (scaled - scaled.round()).abs() < 0.05 {
format!("{scaled:.0}{unit}")
} else {
format!("{scaled:.1}{unit}")
}
}
pub fn install_panel(device: &AdbDevice, report: &dyn Fn(&str)) -> Result<(), String> {
let bundle = panel_bundle()?;
let _guard = adb_lock();
report("正在传程序");
shell(device, "mkdir -p /usr/local/bin /usr/local/share/mifipanel/web /usr/local/share/mifipanel/offline /etc/systemd/system /tmp")?;
push(device, &bundle.bin, "/tmp/mifipanel.new")?;
report("正在传页面");
push(device, &bundle.web, "/usr/local/share/mifipanel/")?;
push(device, &bundle.service, "/etc/systemd/system/mifipanel.service")?;
if let Some(path) = &bundle.radio {
push(device, path, "/usr/local/share/mifipanel/radio-schemes.json")?;
}
if let Some(path) = &bundle.imei {
push(device, path, "/usr/local/share/mifipanel/imei-schemes.json")?;
}
for path in &bundle.offline {
let Some(name) = path.file_name().and_then(|item| item.to_str()) else { continue };
if name.contains('/') || name.contains('\\') || name.contains("..") {
continue;
}
push(device, path, &format!("/usr/local/share/mifipanel/offline/{name}"))?;
}
report("正在启动服务");
shell(
device,
"systemctl stop mifipanel.service >/dev/null 2>&1 || true; mv /tmp/mifipanel.new /usr/local/bin/mifipanel && chmod 755 /usr/local/bin/mifipanel && chmod 644 /etc/systemd/system/mifipanel.service && { chmod 755 /usr/local/share/mifipanel/offline/ttyd >/dev/null 2>&1 || true; } && systemctl daemon-reload && systemctl enable mifipanel.service && systemctl restart mifipanel.service",
)?;
Ok(())
}
pub fn track_key(device: &AdbDevice) -> String {
if device.serial.is_empty() {
format!("#{}", device.transport)
} else {
device.serial.clone()
}
}
pub fn read_panel_version(device: &AdbDevice) -> Option<String> {
let _guard = adb_lock();
match shell_on(&device.serial, &device.transport, version_script()) {
Ok(text) => Some(panel_version_text(&text)),
Err(_) => None,
}
}
fn version_script() -> &'static str {
// 文件优先。没有再问程序。空输出当成未安装;命令失败由调用方决定要不要改界面。
r#"panel=$(cat /run/mifipanel/version 2>/dev/null | tr -d '\r' | head -n 1)
if [ -z "$panel" ]; then
panel=$(/usr/local/bin/mifipanel --version 2>/dev/null | tr -d '\r' | head -n 1)
fi
printf '%s' "$panel"
"#
}
fn panel_version_text(raw: &str) -> String {
let line = raw
.lines()
.map(str::trim)
.find(|line| !line.is_empty())
.unwrap_or("");
if line.is_empty() {
return "未安装".into();
}
let lower = line.to_ascii_lowercase();
if lower.contains("not found") || lower.contains("no such") || lower.contains("inaccessible") {
return "未安装".into();
}
line.chars().filter(|ch| !ch.is_control()).take(32).collect()
}
fn adb_lock() -> std::sync::MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap_or_else(|err| err.into_inner())
}
struct PanelBundle {
bin: std::path::PathBuf,
web: std::path::PathBuf,
service: std::path::PathBuf,
radio: Option<std::path::PathBuf>,
imei: Option<std::path::PathBuf>,
offline: Vec<std::path::PathBuf>,
}
fn panel_bundle() -> Result<PanelBundle, String> {
let mut roots = Vec::new();
if let Ok(path) = std::env::var("MIFIPANEL_DIST") {
roots.push(std::path::PathBuf::from(path));
}
let app = super::app_dir();
roots.push(app.join("panel"));
roots.push(app.join("..").join("mifipanel"));
roots.push(std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..").join("mifipanel"));
for root in roots {
let bin = if root.join("mifipanel").is_file() {
root.join("mifipanel")
} else {
root.join("target").join("aarch64-unknown-linux-gnu").join("release").join("mifipanel")
};
let web = root.join("web");
let service = root.join("mifipanel.service");
if bin.is_file() && web.is_dir() && service.is_file() {
let offline_dir = root.join("offline");
let mut offline = std::fs::read_dir(&offline_dir).ok().map(|entries| {
let mut files: Vec<_> = entries.flatten().map(|entry| entry.path()).filter(|path| path.is_file()).collect();
files.sort();
files
}).unwrap_or_default();
// 终端程序有时和离线包分开放。两种位置都带走,避免只更新面板时丢掉它。
let beside = root.join("ttyd");
if beside.is_file() && !offline.iter().any(|path| path.file_name() == beside.file_name()) {
offline.push(beside);
}
return Ok(PanelBundle {
bin,
web,
service,
radio: root.join("radio-schemes.json").is_file().then(|| root.join("radio-schemes.json")),
imei: root.join("imei-schemes.json").is_file().then(|| root.join("imei-schemes.json")),
offline,
});
}
}
Err("未找到 MiFiPanel 安装文件".into())
}
fn push(device: &AdbDevice, local: &std::path::Path, remote: &str) -> Result<(), String> {
let mut cmd = command("adb");
if !device.transport.is_empty() {
cmd.arg("-t").arg(&device.transport);
} else {
cmd.arg("-s").arg(&device.serial);
}
let output = cmd.arg("push").arg(local).arg(remote).output().map_err(|err| format!("无法启动 adb:{err}"))?;
if output.status.success() {
return Ok(());
}
let err = String::from_utf8_lossy(&output.stderr);
let err = err.trim();
if err.is_empty() { Err("传输 MiFiPanel 失败".into()) } else { Err(err.chars().take(180).collect()) }
}
#[cfg(test)]
mod tests {
use super::panel_version_text;
#[test]
fn version_text_keeps_number() {
assert_eq!(panel_version_text("0.9\n"), "0.9");
assert_eq!(panel_version_text(" 0.9\r\n"), "0.9");
}
#[test]
fn version_text_missing_is_uninstalled() {
assert_eq!(panel_version_text(""), "未安装");
assert_eq!(panel_version_text("\n"), "未安装");
assert_eq!(panel_version_text("sh: /usr/local/bin/mifipanel: not found\n"), "未安装");
}
/// 真机检查,平时不跑。接上设备后:
/// `$env:FLASHER_LIVE_SERIAL = "<adb 序列号>"; cargo test -- --ignored live_install`
/// 会用 flasher\panel 里的文件给这台设备重装一遍面板。
#[test]
#[ignore]
fn live_install_reports_progress_and_version() {
let serial = std::env::var("FLASHER_LIVE_SERIAL").expect("先设置 FLASHER_LIVE_SERIAL");
let device = super::list_devices().into_iter().find(|item| item.serial == serial).expect("没有找到这台设备");
assert!(device.probed, "没读到设备信息");
let steps = std::sync::Mutex::new(Vec::new());
super::install_panel(&device, &|text| steps.lock().unwrap().push(text.to_string())).expect("安装失败");
assert_eq!(*steps.lock().unwrap(), vec!["正在传程序", "正在传页面", "正在启动服务"]);
std::thread::sleep(std::time::Duration::from_secs(5));
let version = super::read_panel_version(&device).expect("没读到版本");
println!("chip={} system={} marked={} version={version}", device.chip, device.system, device.marked);
assert!(version.chars().next().is_some_and(|ch| ch.is_ascii_digit()), "版本号不对:{version}");
}
#[test]
fn version_script_reads_file_before_binary() {
let script = super::version_script();
let file = script.find("/run/mifipanel/version").expect("version file");
let bin = script.find("/usr/local/bin/mifipanel --version").expect("binary");
assert!(file < bin);
}
}