diff --git a/.gitignore b/.gitignore index 2c000cd..a808b60 100644 --- a/.gitignore +++ b/.gitignore @@ -4,12 +4,21 @@ Temp/ temp/ *.tmp +# 交叉编译产物 +tools/imei/imeitool + # modemst / EFS 备份(含 IMEI 与 RF 校准,禁止提交) backup/ **/modemst*.bin **/fsg*.bin **/fsc*.bin +# 刷机工具离线运行时(镜像、edl、Python,体积大,本机保留) +flasher/images/ +flasher/runtime/ +flasher/target/ +dist/ + # 设备侧配置与敏感产物 etc/imei.conf **/imei.conf diff --git a/flasher/Cargo.lock b/flasher/Cargo.lock new file mode 100644 index 0000000..6435c0e --- /dev/null +++ b/flasher/Cargo.lock @@ -0,0 +1,121 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + +[[package]] +name = "cmk" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd5de2a10e31b3ec3e8d75e7ccf8281ab3ee55de68f7ab6ffa9e21be8d82f22" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flasher" +version = "0.1.0" +dependencies = [ + "fltk", +] + +[[package]] +name = "fltk" +version = "1.5.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6acfa51a6d98065984e5f6f21fca6d421791b7b8b6a1351d1966c9799d2c7c60" +dependencies = [ + "bitflags", + "crossbeam-channel", + "fltk-sys", + "minipaste", + "once_cell", +] + +[[package]] +name = "fltk-sys" +version = "1.5.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c4875e000369874f50a6c09abf99f08ff45b867daa340ffe5965122a849c83b" +dependencies = [ + "cmake", + "cmk", +] + +[[package]] +name = "minipaste" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bbcafc6544efab7decec8e8e63d6e7cbaac0a699a4adead308a80f9c302d6ae" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" diff --git a/flasher/Cargo.toml b/flasher/Cargo.toml new file mode 100644 index 0000000..91cc31a --- /dev/null +++ b/flasher/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "flasher" +version = "0.1.0" +edition = "2021" +description = "9008 离线刷机工具" + +[dependencies] +fltk = { version = "1.5", features = ["fltk-bundled"] } diff --git a/flasher/drivers/QHSUSB__BULK.cat b/flasher/drivers/QHSUSB__BULK.cat new file mode 100644 index 0000000..b7d94f8 Binary files /dev/null and b/flasher/drivers/QHSUSB__BULK.cat differ diff --git a/flasher/drivers/ensure-driver.ps1 b/flasher/drivers/ensure-driver.ps1 new file mode 100644 index 0000000..e37cd64 --- /dev/null +++ b/flasher/drivers/ensure-driver.ps1 @@ -0,0 +1,62 @@ +param([switch]$Install) + +$ErrorActionPreference = 'Stop' +$inf = Join-Path $PSScriptRoot 'qhsusb.inf' +$cer = Join-Path $PSScriptRoot 'qhsusb.cer' + +function Test-QhsusbInstalled { + $files = @(Get-ChildItem 'C:\Windows\INF\oem*.inf' -ErrorAction SilentlyContinue) + foreach ($file in $files) { + try { + $text = Get-Content -LiteralPath $file.FullName -Raw -ErrorAction Stop + } catch { + continue + } + if ($text -match 'QHSUSB__BULK' -and $text -match 'VID_05C6&PID_9008') { + return $true + } + } + return $false +} + +function Test-Admin { + $identity = [Security.Principal.WindowsIdentity]::GetCurrent() + $principal = New-Object Security.Principal.WindowsPrincipal($identity) + return $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) +} + +if (-not $Install) { + if (Test-QhsusbInstalled) { + Write-Output "DRIVER`tREADY" + } else { + Write-Output "DRIVER`tMISSING" + } + exit 0 +} + +if (-not (Test-Admin)) { + $arg = "-NoProfile -ExecutionPolicy Bypass -File `"$PSCommandPath`" -Install" + try { + Start-Process -FilePath powershell.exe -ArgumentList $arg -Verb RunAs -Wait | Out-Null + } catch { + Write-Output "DRIVER`tFAIL`tcancel" + exit 1 + } + if (Test-QhsusbInstalled) { + Write-Output "DRIVER`tINSTALLED" + exit 0 + } + Write-Output "DRIVER`tFAIL" + exit 1 +} + +if (Test-Path -LiteralPath $cer) { + & certutil.exe -addstore -f TrustedPublisher $cer | Out-Null +} +$proc = Start-Process -FilePath "$env:SystemRoot\System32\pnputil.exe" -ArgumentList @('/add-driver', $inf, '/install') -Wait -PassThru -NoNewWindow +if (Test-QhsusbInstalled) { + Write-Output "DRIVER`tINSTALLED" + exit 0 +} +Write-Output ("DRIVER`tFAIL`t" + $proc.ExitCode) +exit 1 diff --git a/flasher/drivers/qhsusb.cer b/flasher/drivers/qhsusb.cer new file mode 100644 index 0000000..f8703fd Binary files /dev/null and b/flasher/drivers/qhsusb.cer differ diff --git a/flasher/drivers/qhsusb.inf b/flasher/drivers/qhsusb.inf new file mode 100644 index 0000000..7b42e2f Binary files /dev/null and b/flasher/drivers/qhsusb.inf differ diff --git a/flasher/drivers/switch-winusb.ps1 b/flasher/drivers/switch-winusb.ps1 new file mode 100644 index 0000000..9c4d4d9 --- /dev/null +++ b/flasher/drivers/switch-winusb.ps1 @@ -0,0 +1,107 @@ +param( + [Parameter(Mandatory = $true)][string]$InstanceId +) +$ErrorActionPreference = 'Stop' +$inf = (Resolve-Path (Join-Path $PSScriptRoot 'qhsusb.inf')).Path +if (-not (Test-Path -LiteralPath $inf)) { + throw '找不到 WinUSB 驱动描述' +} + +Add-Type -TypeDefinition @" +using System; +using System.Runtime.InteropServices; +using System.Text; + +public static class QhsusbOne { + public const uint DIGCF_PRESENT = 0x2; + public const uint DIGCF_ALLCLASSES = 0x4; + public const uint DI_ENUMSINGLEINF = 0x00010000; + public const uint DIF_SELECTBESTCOMPATDRV = 0x17; + public const uint DIF_INSTALLDEVICE = 0x2; + public const uint SPDIT_COMPATDRIVER = 2; + + [StructLayout(LayoutKind.Sequential)] + public struct SP_DEVINFO_DATA { + public int cbSize; + public Guid ClassGuid; + public uint DevInst; + public IntPtr Reserved; + } + + [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] + public struct SP_DEVINSTALL_PARAMS { + public int cbSize; + public int Flags; + public int FlagsEx; + public IntPtr hwndParent; + public IntPtr InstallMsgHandler; + public IntPtr InstallMsgHandlerContext; + public IntPtr FileQueue; + public IntPtr ClassInstallReserved; + public int Reserved; + [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] + public string DriverPath; + } + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern IntPtr SetupDiGetClassDevs(IntPtr classGuid, string enumerator, IntPtr hwnd, uint flags); + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetupDiOpenDeviceInfo(IntPtr deviceInfoSet, string deviceInstanceId, IntPtr hwnd, uint flags, ref SP_DEVINFO_DATA data); + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetupDiGetDeviceInstallParams(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, ref SP_DEVINSTALL_PARAMS parms); + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetupDiSetDeviceInstallParams(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, ref SP_DEVINSTALL_PARAMS parms); + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetupDiBuildDriverInfoList(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, uint type); + + [DllImport("setupapi.dll", CharSet = CharSet.Unicode, SetLastError = true)] + public static extern bool SetupDiCallClassInstaller(uint installFunction, IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data); + + [DllImport("setupapi.dll", SetLastError = true)] + public static extern bool SetupDiDestroyDriverInfoList(IntPtr deviceInfoSet, ref SP_DEVINFO_DATA data, uint type); + + [DllImport("setupapi.dll", SetLastError = true)] + public static extern bool SetupDiDestroyDeviceInfoList(IntPtr deviceInfoSet); +} + +"@ + +function Throw-IfFailed([bool]$ok, [string]$step) { + if ($ok) { return } + $code = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + throw ($step + ' 失败,Win32 错误 ' + $code) +} + +$set = [QhsusbOne]::SetupDiGetClassDevs([IntPtr]::Zero, 'USB', [IntPtr]::Zero, [QhsusbOne]::DIGCF_PRESENT -bor [QhsusbOne]::DIGCF_ALLCLASSES) +Throw-IfFailed (-not ($set -eq [IntPtr]::Zero -or $set -eq [IntPtr]-1)) '打开设备列表' +$dev = New-Object QhsusbOne+SP_DEVINFO_DATA +$dev.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($dev) +try { + $ok = [QhsusbOne]::SetupDiOpenDeviceInfo($set, $InstanceId, [IntPtr]::Zero, 0, [ref]$dev) + Throw-IfFailed $ok '定位这一台设备' + $parms = New-Object QhsusbOne+SP_DEVINSTALL_PARAMS + $parms.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($parms) + $ok = [QhsusbOne]::SetupDiGetDeviceInstallParams($set, [ref]$dev, [ref]$parms) + Throw-IfFailed $ok '读取安装参数' + $parms.Flags = $parms.Flags -bor [QhsusbOne]::DI_ENUMSINGLEINF + $parms.DriverPath = $inf + $ok = [QhsusbOne]::SetupDiSetDeviceInstallParams($set, [ref]$dev, [ref]$parms) + Throw-IfFailed $ok '指定驱动文件' + $ok = [QhsusbOne]::SetupDiBuildDriverInfoList($set, [ref]$dev, [QhsusbOne]::SPDIT_COMPATDRIVER) + Throw-IfFailed $ok '建立驱动列表' + try { + $ok = [QhsusbOne]::SetupDiCallClassInstaller([QhsusbOne]::DIF_SELECTBESTCOMPATDRV, $set, [ref]$dev) + Throw-IfFailed $ok '选择驱动' + $ok = [QhsusbOne]::SetupDiCallClassInstaller([QhsusbOne]::DIF_INSTALLDEVICE, $set, [ref]$dev) + Throw-IfFailed $ok '安装驱动' + } finally { + [void][QhsusbOne]::SetupDiDestroyDriverInfoList($set, [ref]$dev, [QhsusbOne]::SPDIT_COMPATDRIVER) + } +} finally { + [void][QhsusbOne]::SetupDiDestroyDeviceInfoList($set) +} +Write-Output 'OK' diff --git a/flasher/src/main.rs b/flasher/src/main.rs new file mode 100644 index 0000000..bb0d197 --- /dev/null +++ b/flasher/src/main.rs @@ -0,0 +1,1067 @@ +#![windows_subsystem = "windows"] + +use fltk::app::{self, MouseButton}; +use fltk::button::{Button, CheckButton}; +use fltk::enums::{Align, Color, Event, Font, FrameType, LabelType, Shortcut}; +use fltk::table::{TableContext, TableRow, TableRowSelectFlag, TableRowSelectMode}; +use fltk::frame::Frame; +use fltk::menu::{CMenuItem, MenuFlag, MenuItem}; +use fltk::prelude::*; +use fltk::window::Window; +use std::collections::VecDeque; +use std::io::{BufRead, BufReader}; +use std::path::PathBuf; +use std::os::windows::process::CommandExt; +use std::process::{Command, Stdio}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{mpsc, Arc, Mutex}; +use std::thread; +use std::time::{Duration, Instant}; + +const COLUMNS: [&str; 7] = ["", "序列号", "芯片型号", "端口", "硬盘", "状态", "进度"]; +const DONE: &str = "写入完成,设备正在重启进入系统"; +const WAIT: &str = "请拔出设备后重新按复位键接入电脑"; +const INSTALLING_DRIVER: &str = "正在安装驱动,请稍后"; +const UNPLUGGED: &str = "设备已拔出,操作失败"; +const CREATE_NO_WINDOW: u32 = 0x08000000; + +fn command(program: impl AsRef) -> Command { + let mut cmd = Command::new(program); + cmd.creation_flags(CREATE_NO_WINDOW); + cmd +} + +#[derive(Clone, Copy, PartialEq, Eq)] +enum JobKind { + Info, + Backup, + Flash, +} + +struct Device { + location: String, + port_num: String, + service: String, + instance_id: String, + serial: String, + chip: String, + disk: String, + status: String, + rate: String, + progress: i32, + pending: Option, + queued: bool, + present: bool, + checked: bool, + info_done: bool, + missing_scans: u8, +} + +enum EventMsg { + Serial(String, String), + Chip(String, String), + Disk(String, String), + Progress(String, i32), + Status(String, String), + Rate(String, String), + Finished(String, &'static str), + Failed(String, String), + Driver(String), +} + +struct WorkerOut { + serial: String, + disk: String, +} + +struct Job { + location: String, + kind: JobKind, + resume: bool, +} + +fn app_dir() -> PathBuf { + if let Ok(exe) = std::env::current_exe() { + let mut dir = exe.parent().map(|path| path.to_path_buf()); + for _ in 0..4 { + if let Some(path) = &dir { + if path.join("runtime").join("worker.py").is_file() { + return path.clone(); + } + dir = path.parent().map(|parent| parent.to_path_buf()); + } + } + } + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn python() -> PathBuf { + let bundled = app_dir().join("runtime").join("python").join("python.exe"); + if bundled.is_file() { + return bundled; + } + app_dir().join("runtime").join("python").join("Scripts").join("python.exe") +} + +fn worker_script() -> PathBuf { + app_dir().join("runtime").join("worker.py") +} + +fn backup_root() -> PathBuf { + app_dir().join("backup") +} + +fn stamp() -> String { + let output = command("powershell") + .args(["-NoProfile", "-Command", "Get-Date -Format yyyyMMdd-HHmmss"]) + .output(); + if let Ok(output) = output { + let text = String::from_utf8_lossy(&output.stdout).trim().to_string(); + if !text.is_empty() { + return text; + } + } + "unknown-time".into() +} + +fn port_num(location: &str) -> String { + let Some(rest) = location.split("Port_#").nth(1) else { + return String::new(); + }; + let raw = rest.split('.').next().unwrap_or(""); + let trimmed = raw.trim_start_matches('0'); + if trimmed.is_empty() { "0".into() } else { trimmed.into() } +} + +fn is_winusb(service: &str) -> bool { + service.eq_ignore_ascii_case("WinUSB") +} + +fn task_running(dev: &Device) -> bool { + dev.queued + || dev.status == WAIT + || dev.status == "正在识别" + || dev.status == "备份中" + || dev.status == "正在备份整盘" + || dev.status == "写入中" + || dev.status == INSTALLING_DRIVER + || dev.status.starts_with("正在写入") + || dev.status.starts_with("正在写回") +} + +fn scan_9008() -> Result, String> { + let script = r#" +Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -match 'VID_05C6&PID_9008' } | ForEach-Object { + $loc = '' + $svc = '' + $usb = '' + try { + $props = Get-PnpDeviceProperty -InstanceId $_.InstanceId -KeyName DEVPKEY_Device_LocationInfo,DEVPKEY_Device_Service,DEVPKEY_Device_LocationPaths + foreach ($p in $props) { + if ($p.KeyName -eq 'DEVPKEY_Device_LocationInfo') { $loc = [string]$p.Data } + if ($p.KeyName -eq 'DEVPKEY_Device_Service') { $svc = [string]$p.Data } + if ($p.KeyName -eq 'DEVPKEY_Device_LocationPaths') { + foreach ($item in @($p.Data)) { + $text = [string]$item + if ($text -match 'USBROOT') { + $nums = [regex]::Matches($text, 'USB\((\d+)\)') | ForEach-Object { $_.Groups[1].Value } + $usb = ($nums -join '.') + } + } + } + } + } catch {} + if (-not $svc) { $svc = [string]$_.Service } + if (-not $loc) { $loc = $_.InstanceId } + Write-Output ($loc + "`t" + $svc + "`t" + $_.InstanceId + "`t" + $usb) +} +"#; + let output = command("powershell") + .args(["-NoProfile", "-Command", script]) + .output() + .map_err(|err| err.to_string())?; + if !output.status.success() && output.stdout.is_empty() { + let err = String::from_utf8_lossy(&output.stderr).trim().to_string(); + return Err(if err.is_empty() { "扫描设备失败".into() } else { err }); + } + Ok(String::from_utf8_lossy(&output.stdout) + .lines() + .filter_map(|line| { + let mut parts = line.split('\t'); + let location = parts.next()?.trim().to_string(); + if location.is_empty() { + return None; + } + let service = parts.next().unwrap_or("").trim().to_string(); + let instance_id = parts.next().unwrap_or("").trim().to_string(); + let usb_path = parts.next().unwrap_or("").trim().to_string(); + Some((location, service, instance_id, usb_path)) + }) + .collect()) +} + +fn confirm_port(location: &str) -> Result<(), String> { + match scan_9008() { + Ok(found) if found.iter().any(|(loc, _, _, _)| loc == location) => Ok(()), + Ok(_) => Err("设备已拔出".into()), + Err(_) => Ok(()), + } +} + +fn run_powershell(args: &[String]) -> Result, String> { + let output = command("powershell") + .args(args) + .output() + .map_err(|err| err.to_string())?; + let lines: Vec = String::from_utf8_lossy(&output.stdout) + .lines() + .map(|line| line.trim().to_string()) + .filter(|line| !line.is_empty()) + .collect(); + if output.status.success() || lines.iter().any(|line| line.starts_with("DRIVER\t")) { + Ok(lines) + } else { + let err = String::from_utf8_lossy(&output.stderr).trim().to_string(); + Err(if err.is_empty() { "驱动检查失败".into() } else { err }) + } +} + +fn driver_message(kind: &str, extra: &str) -> String { + match kind { + "READY" => "驱动:9008 已就绪".into(), + "INSTALLED" => "驱动:9008 已安装".into(), + "MISSING" => "驱动:未安装".into(), + "FAIL" if extra == "cancel" => "驱动:安装被取消".into(), + "FAIL" if extra.is_empty() => "驱动:安装失败".into(), + "FAIL" => format!("驱动:安装失败({extra})"), + _ => "驱动:检查失败".into(), + } +} + +fn driver_text(lines: &[String]) -> Option<(String, String)> { + let line = lines.iter().rev().find(|line| line.starts_with("DRIVER\t"))?; + let mut parts = line.splitn(3, '\t'); + parts.next(); + Some((parts.next().unwrap_or("").to_string(), parts.next().unwrap_or("").to_string())) +} + +fn ensure_driver(tx: mpsc::Sender) { + let _ = tx.send(EventMsg::Driver("驱动:正在检查".into())); + let script = app_dir().join("drivers").join("ensure-driver.ps1"); + let script = script.to_string_lossy().to_string(); + let checked = run_powershell(&[ + "-NoProfile".into(), + "-ExecutionPolicy".into(), + "Bypass".into(), + "-File".into(), + script.clone(), + ]); + let Ok(lines) = checked else { + let _ = tx.send(EventMsg::Driver("驱动:检查失败".into())); + return; + }; + let Some((kind, text)) = driver_text(&lines) else { + let _ = tx.send(EventMsg::Driver("驱动:检查失败".into())); + return; + }; + if kind == "READY" { + let _ = tx.send(EventMsg::Driver("驱动:9008 已就绪".into())); + return; + } + if kind != "MISSING" { + let _ = tx.send(EventMsg::Driver(driver_message(&kind, &text))); + return; + } + let _ = tx.send(EventMsg::Driver("驱动:正在安装".into())); + match run_powershell(&[ + "-NoProfile".into(), + "-ExecutionPolicy".into(), + "Bypass".into(), + "-File".into(), + script, + "-Install".into(), + ]) { + Ok(lines) => { + let text = driver_text(&lines) + .map(|(kind, extra)| driver_message(&kind, &extra)) + .unwrap_or_else(|| "驱动:安装没有返回结果".into()); + let _ = tx.send(EventMsg::Driver(text)); + } + Err(err) => { + let _ = tx.send(EventMsg::Driver(format!("驱动:{err}"))); + } + } +} + +fn switch_driver(instance_id: &str) -> Result<(), String> { + let script = app_dir().join("drivers").join("switch-winusb.ps1"); + let output = command("powershell") + .args([ + "-NoProfile", + "-ExecutionPolicy", + "Bypass", + "-File", + &script.to_string_lossy(), + "-InstanceId", + instance_id, + ]) + .output() + .map_err(|err| err.to_string())?; + if output.status.success() { + Ok(()) + } else { + Err(format!( + "{}{}", + String::from_utf8_lossy(&output.stderr), + String::from_utf8_lossy(&output.stdout) + )) + } +} + +fn apply_line(line: &str, out: &mut WorkerOut, tx: &mpsc::Sender, location: &str) -> Result<(), String> { + let mut parts = line.splitn(3, '\t'); + if parts.next() != Some("FLASHER") { + return Ok(()); + } + let key = parts.next().unwrap_or(""); + let value = parts.next().unwrap_or("").to_string(); + match key { + "SERIAL" => { + out.serial = value.clone(); + let _ = tx.send(EventMsg::Serial(location.to_string(), value)); + } + "CHIP" => { + let _ = tx.send(EventMsg::Chip(location.to_string(), value)); + } + "DISK" => { + out.disk = value.clone(); + let _ = tx.send(EventMsg::Disk(location.to_string(), value)); + } + "PROGRESS" => { + if let Ok(n) = value.parse::() { + let _ = tx.send(EventMsg::Progress(location.to_string(), n)); + } + } + "STATUS" => { + let _ = tx.send(EventMsg::Status(location.to_string(), value)); + } + "RATE" => { + let _ = tx.send(EventMsg::Rate(location.to_string(), value)); + } + "FAIL" => return Err(value), + _ => {} + } + Ok(()) +} + +fn run_worker(_port: &str, args: &[&str], tx: &mpsc::Sender, location: &str) -> Result { + let mut child = command(python()) + .arg(worker_script()) + .args(args) + .env("PYTHONUTF8", "1") + .env("PYTHONIOENCODING", "utf-8") + .current_dir(app_dir().join("runtime")) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .map_err(|err| format!("无法启动 edl:{err}"))?; + let stdout = child.stdout.take().ok_or("没有读取到 edl 输出")?; + let (line_tx, line_rx) = mpsc::channel::(); + thread::spawn(move || { + for line in BufReader::new(stdout).lines().map_while(Result::ok) { + if line_tx.send(line).is_err() { + break; + } + } + }); + let limit = if args.iter().any(|arg| *arg == "--full") { + Duration::from_secs(45 * 60) + } else if args.first() == Some(&"flash") { + Duration::from_secs(20 * 60) + } else { + Duration::from_secs(90) + }; + let mut out = WorkerOut { serial: String::new(), disk: String::new() }; + let mut last = Instant::now(); + loop { + match line_rx.recv_timeout(Duration::from_secs(1)) { + Ok(line) => { + if let Err(err) = apply_line(&line, &mut out, tx, location) { + let _ = child.kill(); + let _ = child.wait(); + return Err(err); + } + if line.starts_with("FLASHER\t") { + last = Instant::now(); + } + } + Err(mpsc::RecvTimeoutError::Timeout) => { + if last.elapsed() > limit { + let _ = child.kill(); + let _ = child.wait(); + return Err("等待 9008 超时".into()); + } + if child.try_wait().map_err(|err| err.to_string())?.is_some() { + while let Ok(line) = line_rx.try_recv() { + if let Err(err) = apply_line(&line, &mut out, tx, location) { + let _ = child.kill(); + let _ = child.wait(); + return Err(err); + } + } + break; + } + } + Err(mpsc::RecvTimeoutError::Disconnected) => break, + } + } + let status = child.wait().map_err(|err| err.to_string())?; + if status.success() { + Ok(out) + } else { + Err("edl 异常退出".into()) + } +} + +fn execute(location: &str, port: &str, known_serial: &str, kind: JobKind, full: bool, parts: bool, resume: bool, tx: &mpsc::Sender) -> Result<&'static str, String> { + confirm_port(location)?; + let _ = tx.send(EventMsg::Status(location.to_string(), "正在识别".into())); + let info = run_worker(port, &["info", "--port", port], tx, location)?; + if resume && !known_serial.is_empty() && !info.serial.is_empty() && info.serial != known_serial { + return Err("插回的不是原来的芯片,已停止原来的任务".into()); + } + if kind == JobKind::Info { + return Ok("info"); + } + let backup_efs = kind == JobKind::Backup || parts; + let do_backup = backup_efs || full; + let mut restore_dir = String::new(); + if do_backup { + confirm_port(location)?; + let serial = if !info.serial.is_empty() { + info.serial + } else if !known_serial.is_empty() { + known_serial.to_string() + } else { + format!("port-{port}") + }; + let folder = backup_root().join(&serial).join(stamp()); + std::fs::create_dir_all(&folder).map_err(|err| err.to_string())?; + let dest = folder.to_string_lossy().to_string(); + let mut backup_args = vec!["backup", "--port", port, "--dest", dest.as_str()]; + if full { + backup_args.push("--full"); + } + if !backup_efs { + backup_args.push("--no-efs"); + } + let status = if full && !backup_efs { "正在备份整盘" } else { "备份中" }; + let _ = tx.send(EventMsg::Status(location.to_string(), status.into())); + run_worker(port, &backup_args, tx, location)?; + if kind == JobKind::Backup { + return Ok("backup"); + } + if backup_efs { + restore_dir = dest; + } + } + confirm_port(location)?; + let _ = tx.send(EventMsg::Status(location.to_string(), "写入中".into())); + let _ = tx.send(EventMsg::Progress(location.to_string(), 0)); + if restore_dir.is_empty() { + run_worker(port, &["flash", "--port", port], tx, location)?; + } else { + run_worker(port, &["flash", "--port", port, "--dest", restore_dir.as_str()], tx, location)?; + } + Ok("flash") +} + +fn main() { + let devices = Arc::new(Mutex::new(Vec::::new())); + let queue: Arc>> = Arc::new(Mutex::new(VecDeque::new())); + let full_disk = Arc::new(Mutex::new(false)); + let backup_parts = Arc::new(Mutex::new(true)); + let refresh_now = Arc::new(AtomicBool::new(false)); + let (tx, rx) = mpsc::channel::(); + let (scan_tx, scan_rx) = mpsc::channel::<(Option>, bool)>(); + + { + let devices = Arc::clone(&devices); + let queue = Arc::clone(&queue); + let full_disk = Arc::clone(&full_disk); + let backup_parts = Arc::clone(&backup_parts); + let tx = tx.clone(); + thread::spawn(move || loop { + let next = queue.lock().unwrap().pop_front(); + let Some(Job { location, kind, resume }) = next else { + thread::sleep(Duration::from_millis(200)); + continue; + }; + let (port, service, serial, instance_id) = { + let list = devices.lock().unwrap(); + match list.iter().find(|d| d.location == location) { + Some(d) => { + let route = if d.port_num.contains('.') || !d.port_num.is_empty() { + d.port_num.clone() + } else { + port_num(&d.location) + }; + (route, d.service.clone(), d.serial.clone(), d.instance_id.clone()) + } + None => { + let _ = tx.send(EventMsg::Failed(location, "设备已不在列表中".into())); + continue; + } + } + }; + if confirm_port(&location).is_err() { + let _ = tx.send(EventMsg::Failed(location, "设备已拔出".into())); + continue; + } + if !is_winusb(&service) { + let _ = tx.send(EventMsg::Status(location.clone(), INSTALLING_DRIVER.into())); + if let Err(err) = switch_driver(&instance_id) { + let _ = tx.send(EventMsg::Failed(location, err)); + continue; + } + if let Some(dev) = devices.lock().unwrap().iter_mut().find(|d| d.location == location) { + dev.pending = Some(kind); + dev.queued = false; + dev.status = WAIT.into(); + } + let _ = tx.send(EventMsg::Status(location, WAIT.into())); + continue; + } + let full = *full_disk.lock().unwrap(); + let parts = *backup_parts.lock().unwrap(); + match execute(&location, &port, &serial, kind, full, parts, resume, &tx) { + Ok(done) => { + let _ = tx.send(EventMsg::Finished(location, done)); + } + Err(err) => { + let unplugged = err == "设备已拔出" || confirm_port(&location).is_err(); + let still_there = devices + .lock() + .unwrap() + .iter() + .find(|d| d.location == location) + .is_some_and(|d| d.present); + if unplugged { + let _ = tx.send(EventMsg::Failed(location, "设备已拔出".into())); + } else if still_there { + let _ = tx.send(EventMsg::Failed(location, err)); + } else if let Some(dev) = devices.lock().unwrap().iter_mut().find(|d| d.location == location) { + dev.pending = Some(kind); + dev.queued = false; + dev.status = WAIT.into(); + let _ = tx.send(EventMsg::Status(location, WAIT.into())); + } + } + } + }); + } + + let app = app::App::default().with_scheme(app::Scheme::Gtk); + if let Ok(font) = Font::load_font("C:/Windows/Fonts/msyh.ttc") { + Font::set_font(Font::Helvetica, &font); + } + let mut window = Window::default().with_size(980, 640).with_label("UFI003_MB_V02 Flasher"); + let mut driver_label = Frame::default() + .with_pos(16, 16) + .with_size(800, 28) + .with_label("驱动:正在检查"); + driver_label.set_label_size(15); + driver_label.set_align(Align::Left | Align::Inside); + let mut refresh_btn = Button::default() + .with_pos(836, 14) + .with_size(128, 32) + .with_label("刷新设备"); + refresh_btn.set_label_size(15); + let mut table = TableRow::new(16, 56, 948, 492, ""); + table.set_cols(COLUMNS.len() as i32); + table.set_rows(0); + table.set_col_header(true); + table.set_col_header_height(28); + table.set_row_header(false); + table.set_row_height_all(28); + table.set_col_resize(true); + table.set_col_resize_min(48); + table.set_type(TableRowSelectMode::Single); + for (index, width) in [46, 110, 110, 210, 100, 250, 70].into_iter().enumerate() { + table.set_col_width(index as i32, width); + } + table.end(); + let devices_draw = Arc::clone(&devices); + table.draw_cell(move |table, ctx, row, col, x, y, w, h| { + match ctx { + TableContext::ColHeader => { + fltk::draw::push_clip(x, y, w, h); + fltk::draw::draw_box(FrameType::ThinUpBox, x, y, w, h, Color::FrameDefault); + fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120)); + fltk::draw::draw_rect(x, y, w, h); + if col == 0 { + let list = devices_draw.lock().unwrap(); + let all = !list.is_empty() && list.iter().all(|dev| dev.checked); + draw_mark(all, x, y, w, h); + } else { + fltk::draw::set_draw_color(Color::Foreground); + fltk::draw::set_font(Font::Helvetica, 15); + let title = COLUMNS.get(col as usize).copied().unwrap_or(""); + fltk::draw::draw_text2(title, x, y, w, h, Align::Center); + } + fltk::draw::pop_clip(); + } + TableContext::Cell => { + let selected = table.row_selected(row); + let background = if selected { Color::Selection } else { Color::White }; + fltk::draw::push_clip(x, y, w, h); + fltk::draw::draw_box(FrameType::FlatBox, x, y, w, h, background); + fltk::draw::set_draw_color(Color::from_rgb(120, 120, 120)); + fltk::draw::draw_rect(x, y, w, h); + if col == 0 { + let checked = devices_draw.lock().unwrap().get(row as usize).is_some_and(|dev| dev.checked); + draw_mark(checked, x, y, w, h); + } else { + fltk::draw::set_draw_color(if selected { Color::White } else { Color::Foreground }); + fltk::draw::set_font(Font::Helvetica, 15); + let text = cell_text(&devices_draw, row, col); + fltk::draw::draw_text2(&text, x, y, w, h, Align::Center); + } + fltk::draw::pop_clip(); + } + _ => {} + } + }); + let mut hint = Frame::default() + .with_pos(16, 560) + .with_size(460, 60) + .with_label("设备请按住复位键然后插入电脑,列表只显示9008设备。"); + hint.set_label_size(15); + hint.set_align(Align::Left | Align::Inside | Align::Wrap); + let mut parts = CheckButton::default() + .with_pos(490, 560) + .with_size(300, 28) + .with_label("刷机前备份基带四分区"); + parts.set_label_size(15); + parts.set_value(true); + let mut full = CheckButton::default() + .with_pos(490, 592) + .with_size(300, 28) + .with_label("同时备份整盘 eMMC"); + full.set_label_size(15); + let mut batch_btn = Button::default() + .with_pos(804, 560) + .with_size(160, 60) + .with_label("批量刷机"); + batch_btn.set_label_size(15); + batch_btn.deactivate(); + window.end(); + window.show(); + + { + let full_disk = Arc::clone(&full_disk); + full.set_callback(move |button| *full_disk.lock().unwrap() = button.value()); + } + { + let backup_parts = Arc::clone(&backup_parts); + parts.set_callback(move |button| *backup_parts.lock().unwrap() = button.value()); + } + { + let refresh_now = Arc::clone(&refresh_now); + refresh_btn.set_callback(move |button| { + button.deactivate(); + refresh_now.store(true, Ordering::SeqCst); + }); + } + { + let devices = Arc::clone(&devices); + let queue = Arc::clone(&queue); + batch_btn.set_callback(move |_| enqueue_checked(&queue, &devices)); + } + { + let refresh_now = Arc::clone(&refresh_now); + thread::spawn(move || loop { + let manual = refresh_now.swap(false, Ordering::SeqCst); + let found = scan_9008().ok(); + if scan_tx.send((found, manual)).is_err() { + break; + } + let mut waited = 0; + while waited < 1500 { + if refresh_now.load(Ordering::SeqCst) { + break; + } + thread::sleep(Duration::from_millis(100)); + waited += 100; + } + }); + } + + { + let tx = tx.clone(); + thread::spawn(move || ensure_driver(tx)); + } + + table.handle({ + let devices = Arc::clone(&devices); + let queue = Arc::clone(&queue); + move |table, ev| { + if ev == Event::Released && app::event_button() == MouseButton::Left as i32 { + let Some((ctx, row, col, _)) = table.cursor2rowcol() else { + return false; + }; + if col != 0 { + return false; + } + if ctx == TableContext::ColHeader { + toggle_all(&devices); + table.redraw(); + return true; + } + if ctx == TableContext::Cell && row >= 0 { + toggle_row(&devices, row); + table.redraw(); + return true; + } + return false; + } + if ev != Event::Released || app::event_button() != MouseButton::Right as i32 { + return false; + } + let (pointer_x, pointer_y) = (app::event_x(), app::event_y()); + let Some((ctx, row, _, _)) = table.cursor2rowcol() else { + return false; + }; + if ctx != TableContext::Cell || row < 0 { + return false; + } + let _ = table.select_row(row, TableRowSelectFlag::Select); + let location = devices.lock().unwrap().get(row as usize).map(|dev| dev.location.clone()); + let Some(location) = location else { return true }; + let is_busy = devices.lock().unwrap().iter().find(|dev| dev.location == location).is_some_and(task_running); + popup_menu(&queue, &devices, &location, is_busy, pointer_x, pointer_y); + true + } + }); + + app::add_timeout3(0.5, { + let devices = Arc::clone(&devices); + let queue = Arc::clone(&queue); + let mut table = table.clone(); + let mut driver_label = driver_label.clone(); + let mut refresh_btn = refresh_btn.clone(); + let mut batch_btn = batch_btn.clone(); + move |handle| { + while let Ok((found, manual)) = scan_rx.try_recv() { + let Some(found) = found else { + if manual { + refresh_btn.activate(); + } + continue; + }; + apply_found(&found, &devices, &queue); + if manual { + let alive = { + let mut list = devices.lock().unwrap(); + list.retain(|dev| dev.present); + for dev in list.iter_mut() { + let retry = dev.serial.is_empty() + && (dev.status.starts_with("失败") + || dev.status.starts_with("重新进入") + || dev.status == UNPLUGGED); + if retry && !task_running(dev) { + dev.info_done = false; + dev.status = "9008".into(); + } + } + list.iter().map(|dev| dev.location.clone()).collect::>() + }; + queue.lock().unwrap().retain(|job| alive.iter().any(|loc| loc == &job.location)); + refresh_btn.activate(); + } + } + while let Ok(msg) = rx.try_recv() { + if let EventMsg::Driver(text) = msg { + driver_label.set_label(&text); + driver_label.redraw(); + } else { + apply(&devices, msg); + } + } + refresh_table(&mut table, &devices); + ensure_identify(&queue, &devices); + let can_batch = devices.lock().unwrap().iter().any(|dev| dev.checked && !task_running(dev)); + if can_batch { + batch_btn.activate(); + } else { + batch_btn.deactivate(); + } + app::repeat_timeout3(0.2, handle); + } + }); + + app.run().unwrap(); +} + +fn toggle_row(devices: &Arc>>, row: i32) { + let mut list = devices.lock().unwrap(); + if let Some(dev) = list.get_mut(row as usize) { + dev.checked = !dev.checked; + } +} + +fn toggle_all(devices: &Arc>>) { + let mut list = devices.lock().unwrap(); + let check = list.iter().any(|dev| !dev.checked); + for dev in list.iter_mut() { + dev.checked = check; + } +} + +fn enqueue_checked(queue: &Arc>>, devices: &Arc>>) { + let locations: Vec = devices + .lock() + .unwrap() + .iter() + .filter(|dev| dev.checked && !task_running(dev)) + .map(|dev| dev.location.clone()) + .collect(); + for location in locations { + enqueue(queue, devices, &location, JobKind::Flash); + } +} + +fn job_status(kind: JobKind) -> &'static str { + match kind { + JobKind::Info => "正在识别", + JobKind::Backup => "备份中", + JobKind::Flash => "写入中", + } +} + +fn ensure_identify(queue: &Arc>>, devices: &Arc>>) { + let locations: Vec = devices + .lock() + .unwrap() + .iter() + .filter(|dev| { + dev.present + && dev.serial.is_empty() + && !dev.info_done + && !dev.status.starts_with("失败") + && dev.status != DONE + && !task_running(dev) + }) + .map(|dev| dev.location.clone()) + .collect(); + for location in locations { + enqueue(queue, devices, &location, JobKind::Info); + } +} + +fn enqueue(queue: &Arc>>, devices: &Arc>>, location: &str, kind: JobKind) { + let mut list = devices.lock().unwrap(); + let Some(dev) = list.iter_mut().find(|d| d.location == location) else { return }; + if task_running(dev) { + return; + } + dev.queued = true; + dev.pending = Some(kind); + dev.progress = 0; + dev.status = job_status(kind).into(); + queue.lock().unwrap().push_back(Job { location: location.to_string(), kind, resume: false }); +} + +fn popup_menu(queue: &Arc>>, devices: &Arc>>, location: &str, is_busy: bool, x: i32, y: i32) { + let flag = if is_busy { MenuFlag::Inactive } else { MenuFlag::Normal }; + let item = |text| CMenuItem { + text: Some(text), + flags: flag, + shortcut: Shortcut::None, + cb: None, + labeltype: LabelType::Normal, + labelfont: Font::Helvetica, + labelsize: 15, + labelcolor: Color::Foreground, + }; + let menu = MenuItem::new_from_cmenu(&[item("备份"), item("刷机")]); + let Some(item) = menu.popup(x, y) else { return }; + if is_busy { + return; + } + match item.label().unwrap_or_default().as_str() { + "备份" => enqueue(queue, devices, location, JobKind::Backup), + "刷机" => enqueue(queue, devices, location, JobKind::Flash), + _ => {} + } +} + +fn apply_found(found: &[(String, String, String, String)], devices: &Arc>>, queue: &Arc>>) { + let mut list = devices.lock().unwrap(); + for (location, service, instance_id, usb_path) in found { + let route = if usb_path.is_empty() { port_num(location) } else { usb_path.clone() }; + if let Some(dev) = list.iter_mut().find(|d| &d.location == location) { + dev.service = service.clone(); + dev.instance_id = instance_id.clone(); + dev.port_num = route; + if dev.status == WAIT && is_winusb(service) { + if let Some(kind) = dev.pending.take() { + if !dev.queued { + dev.queued = true; + dev.status = job_status(kind).into(); + queue.lock().unwrap().push_back(Job { + location: dev.location.clone(), + kind, + resume: true, + }); + } + } + } + } else { + list.push(Device { + location: location.clone(), + port_num: route, + service: service.clone(), + instance_id: instance_id.clone(), + serial: String::new(), + chip: String::new(), + disk: String::new(), + status: "9008".into(), + rate: String::new(), + progress: 0, + pending: None, + queued: false, + present: true, + checked: false, + info_done: false, + missing_scans: 0, + }); + } + } + for dev in list.iter_mut() { + let present = found.iter().any(|(location, _, _, _)| location == &dev.location); + dev.present = present; + if present { + let returned = dev.missing_scans > 0; + dev.missing_scans = 0; + if !task_running(dev) && (dev.status == UNPLUGGED || (returned && dev.serial.is_empty())) { + if dev.serial.is_empty() { + dev.info_done = false; + } + dev.status = "9008".into(); + dev.progress = 0; + } + } else { + dev.missing_scans = dev.missing_scans.saturating_add(1); + } + } +} + +fn cell_text(devices: &Mutex>, row: i32, col: i32) -> String { + let list = devices.lock().unwrap(); + let Some(dev) = list.get(row as usize) else { + return String::new(); + }; + match col { + 1 if dev.serial.is_empty() => "-".into(), + 1 => dev.serial.clone(), + 2 if dev.chip.is_empty() => "-".into(), + 2 => dev.chip.clone(), + 3 => dev.location.clone(), + 4 if dev.disk.is_empty() => "-".into(), + 4 => dev.disk.clone(), + 5 if dev.rate.is_empty() => dev.status.clone(), + 5 => format!("{} {}", dev.status, dev.rate), + 6 => format!("{}%", dev.progress), + _ => String::new(), + } +} + +fn draw_mark(checked: bool, x: i32, y: i32, w: i32, h: i32) { + let size = 16; + let left = x + (w - size) / 2; + let top = y + (h - size) / 2; + fltk::draw::draw_box(FrameType::ThinDownBox, left, top, size, size, Color::White); + if checked { + fltk::draw::draw_check(left, top, size, size, Color::Black); + } +} + +fn refresh_table(table: &mut TableRow, devices: &Arc>>) { + let count = devices.lock().unwrap().len() as i32; + if table.rows() != count { + table.set_rows(count); + } + table.redraw(); +} + +fn apply(devices: &Arc>>, msg: EventMsg) { + let mut list = devices.lock().unwrap(); + match msg { + EventMsg::Serial(location, serial) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.serial = serial; + } + } + EventMsg::Chip(location, chip) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.chip = chip; + } + } + EventMsg::Disk(location, disk) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.disk = disk; + } + } + EventMsg::Progress(location, value) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.progress = value; + } + } + EventMsg::Status(location, status) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.status = status; + dev.rate.clear(); + } + } + EventMsg::Rate(location, rate) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.rate = rate; + } + } + EventMsg::Finished(location, kind) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.queued = false; + dev.pending = None; + dev.rate.clear(); + if kind == "info" { + dev.info_done = true; + dev.progress = 0; + if dev.serial.is_empty() && dev.chip.is_empty() { + dev.status = "重新进入9008后可读序列号".into(); + } else { + dev.status = "9008".into(); + } + } else { + dev.progress = 100; + dev.status = if kind == "flash" { DONE.into() } else { "备份完成".into() }; + } + } + } + EventMsg::Failed(location, err) => { + if let Some(dev) = list.iter_mut().find(|d| d.location == location) { + dev.queued = false; + dev.pending = None; + dev.rate.clear(); + dev.info_done = true; + if err == "设备已拔出" { + dev.present = false; + dev.status = UNPLUGGED.into(); + } else { + dev.status = format!("失败:{err}"); + } + } + } + EventMsg::Driver(_) => {} + } +} diff --git a/tools/imei/go.mod b/tools/imei/go.mod new file mode 100644 index 0000000..7c818d1 --- /dev/null +++ b/tools/imei/go.mod @@ -0,0 +1,3 @@ +module ltedongle/imei + +go 1.22 diff --git a/tools/imei/imei-manager.init b/tools/imei/imei-manager.init new file mode 100644 index 0000000..11c03ba --- /dev/null +++ b/tools/imei/imei-manager.init @@ -0,0 +1,10 @@ +#!/bin/sh /etc/rc.common +# 开机时按 /etc/imei.conf 重写基带 IMEI。此固件只保留在内存里。 +START=65 +STOP=10 + +start() { + [ -s /etc/imei.conf ] || return 0 + sleep 8 + /usr/bin/imeitool save +} diff --git a/tools/imei/log.txt b/tools/imei/log.txt new file mode 100644 index 0000000..e69de29 diff --git a/tools/imei/main.go b/tools/imei/main.go new file mode 100644 index 0000000..aa0ef3d --- /dev/null +++ b/tools/imei/main.go @@ -0,0 +1,529 @@ +package main + +import ( + "bytes" + "fmt" + "os" + "os/exec" + "path/filepath" + "sort" + "strconv" + "strings" + "syscall" + "time" + "unsafe" +) + +const ( + rpmsgCtrl = "/dev/rpmsg_ctrl2" + rpmsgCreateEpt = 0x4028b501 + imeiConf = "/etc/imei.conf" + nvItemIMEI = 550 + diagNvRead = 0x26 + diagNvWrite = 0x27 + diagSpc = 0x41 +) + +type rpmsgEptInfo struct { + Name [32]byte + Src uint32 + Dst uint32 +} + +func main() { + cmd := "" + if len(os.Args) > 1 { + cmd = os.Args[1] + } + switch cmd { + case "ftm-test": + if err := ftmWriteSame(); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + case "persist": + if err := persistIMEI(); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + case "read": + imei, err := readIMEI() + if err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + fmt.Println(imei) + case "save": + imei := "" + if len(os.Args) > 2 { + imei = strings.TrimSpace(os.Args[2]) + } else if b, err := os.ReadFile(imeiConf); err == nil { + imei = strings.TrimSpace(string(b)) + } + if len(imei) != 15 || strings.IndexFunc(imei, func(r rune) bool { return r < '0' || r > '9' }) >= 0 { + fmt.Fprintf(os.Stderr, "用法: imeitool save <15位IMEI>\n 或把 IMEI 写入 %s 后执行 imeitool save\n", imeiConf) + os.Exit(2) + } + if err := saveIMEI(imei); err != nil { + fmt.Fprintf(os.Stderr, "%v\n", err) + os.Exit(1) + } + fmt.Println(imei) + default: + fmt.Fprintf(os.Stderr, "imeitool - 读取或写入基带 IMEI\n\n用法:\n imeitool read\n imeitool save <15位IMEI>\n") + os.Exit(2) + } +} + +func persistIMEI() error { + fd, err := openDiag() + if err != nil { + return err + } + defer fd.Close() + spcUnlock(fd) + data, err := nvRead(fd, nvItemIMEI) + if err != nil { + return err + } + imei, _ := nv550ToIMEI(data) + fmt.Fprintf(os.Stderr, "当前 RAM IMEI: %s\n", orNA(imei)) + payload := data[:9] + if err := efsHello(fd); err != nil { + return err + } + paths := []string{"/nvm/num/550", "/nvm/num/00550", "/nv/item_files/modem/uim/imei"} + for _, path := range paths { + st, err := efsStat(fd, path) + if err != nil { + fmt.Printf("STAT %s %v\n", path, err) + } else { + fmt.Printf("STAT %s %s\n", path, hexBytes(st)) + } + for _, oflag := range []uint32{2, 0x41, 0x301} { + err := efsPut(fd, path, payload, oflag) + fmt.Printf("PUT %s oflag=0x%x %v\n", path, oflag, err) + if err == nil { + break + } + } + } + if err := efsSync(fd); err != nil { + fmt.Printf("SYNC %v\n", err) + } + return nil +} + +func ftmWriteSame() error { + fd, err := openDiag() + if err != nil { + return err + } + defer fd.Close() + imei, err := readIMEIFrom(fd) + if err != nil { + return err + } + fmt.Fprintf(os.Stderr, "当前 IMEI: %s\n", imei) + resp, err := diagCmd(fd, []byte{0x29, 0x03}, 3*time.Second) + fmt.Printf("FTM %s %v\n", hexBytes(resp), err) + spcUnlock(fd) + if err := nvWrite(fd, nvItemIMEI, imeiToNV550(imei)); err != nil { + fmt.Printf("NV写 %v\n", err) + } else { + fmt.Printf("NV写 完成\n") + } + if err := efsSync(fd); err != nil { + fmt.Printf("SYNC %v\n", err) + } + resp, err = diagCmd(fd, []byte{0x29, 0x04}, 3*time.Second) + fmt.Printf("ONLINE %s %v\n", hexBytes(resp), err) + return nil +} + +func readIMEIFrom(fd *os.File) (string, error) { + data, err := nvRead(fd, nvItemIMEI) + if err != nil { + return "", err + } + imei, ok := nv550ToIMEI(data) + if !ok { + return "", fmt.Errorf("无法解析 NV 550") + } + return imei, nil +} + +func readIMEI() (string, error) { + fd, err := openDiag() + if err != nil { + return "", err + } + defer fd.Close() + data, err := nvRead(fd, nvItemIMEI) + if err != nil { + return "", err + } + imei, ok := nv550ToIMEI(data) + if !ok { + return "", fmt.Errorf("无法解析 NV 550") + } + return imei, nil +} + +func saveIMEI(imei string) error { + fd, err := openDiag() + if err != nil { + return err + } + curData, err := nvRead(fd, nvItemIMEI) + if err != nil { + fd.Close() + return err + } + cur, _ := nv550ToIMEI(curData) + fmt.Fprintf(os.Stderr, "当前 IMEI: %s\n", orNA(cur)) + wrote := false + if cur == imei && os.Getenv("IMEITOOL_FORCE") != "1" { + fmt.Fprintf(os.Stderr, "IMEI 已一致,不重复写入。\n") + } else { + spcUnlock(fd) + fmt.Fprintf(os.Stderr, "正在写入 IMEI %s ...\n", imei) + if err := nvWrite(fd, nvItemIMEI, imeiToNV550(imei)); err != nil { + fd.Close() + return err + } + gotData, err := nvRead(fd, nvItemIMEI) + if err != nil { + fd.Close() + return err + } + got, _ := nv550ToIMEI(gotData) + if got != imei { + fd.Close() + return fmt.Errorf("写后校验失败,读回 %s", orNA(got)) + } + fmt.Fprintf(os.Stderr, "NV 写入已校验。\n") + wrote = true + } + fd.Close() + if err := os.WriteFile(imeiConf, []byte(imei+"\n"), 0644); err != nil { + return fmt.Errorf("写入 %s: %w", imeiConf, err) + } + fmt.Fprintf(os.Stderr, "已保存到 %s,开机后会重新写入。\n", imeiConf) + if wrote { + restartModemManager() + } + fmt.Fprintf(os.Stderr, "完成。当前 IMEI 为 %s\n", imei) + return nil +} + +func orNA(s string) string { + if s == "" { + return "N/A" + } + return s +} + +func openDiag() (*os.File, error) { + before := rpmsgNodes() + ctrl, err := os.OpenFile(rpmsgCtrl, os.O_RDWR, 0) + if err != nil { + return nil, fmt.Errorf("打开 %s: %w", rpmsgCtrl, err) + } + info := rpmsgEptInfo{Src: 0xFFFFFFFF, Dst: 0xFFFFFFFF} + copy(info.Name[:], "DIAG") + _, _, errno := syscall.Syscall(syscall.SYS_IOCTL, ctrl.Fd(), uintptr(rpmsgCreateEpt), uintptr(unsafe.Pointer(&info))) + ctrl.Close() + if errno != 0 { + return nil, fmt.Errorf("创建 DIAG 端点: %w", errno) + } + var dev string + for i := 0; i < 20; i++ { + for n := range rpmsgNodes() { + if !before[n] { + dev = n + } + } + if dev != "" { + break + } + time.Sleep(300 * time.Millisecond) + } + if dev == "" { + return nil, fmt.Errorf("未出现新的 rpmsg 端点") + } + fd, err := os.OpenFile(dev, os.O_RDWR, 0) + if err != nil { + return nil, fmt.Errorf("打开 %s: %w", dev, err) + } + _ = fd.SetReadDeadline(time.Now().Add(200 * time.Millisecond)) + buf := make([]byte, 4096) + for { + if _, err := fd.Read(buf); err != nil { + break + } + } + return fd, nil +} + +func rpmsgNodes() map[string]bool { + matches, _ := filepath.Glob("/dev/rpmsg[0-9]*") + sort.Slice(matches, func(i, j int) bool { + return rpmsgNum(matches[i]) < rpmsgNum(matches[j]) + }) + out := make(map[string]bool, len(matches)) + for _, m := range matches { + base := filepath.Base(m) + if strings.Contains(base, "ctrl") { + continue + } + out[m] = true + } + return out +} + +func rpmsgNum(path string) int { + base := filepath.Base(path) + n, _ := strconv.Atoi(strings.TrimPrefix(base, "rpmsg")) + return n +} + +func diagCmd(fd *os.File, pkt []byte, timeout time.Duration) ([]byte, error) { + if _, err := fd.Write(pkt); err != nil { + return nil, err + } + deadline := time.Now().Add(timeout) + buf := make([]byte, 8192) + for { + left := time.Until(deadline) + if left <= 0 { + return nil, fmt.Errorf("超时") + } + _ = fd.SetReadDeadline(time.Now().Add(left)) + n, err := fd.Read(buf) + if err != nil { + return nil, err + } + resp := append([]byte(nil), buf[:n]...) + if len(resp) > 1 && resp[0] != pkt[0] && resp[1] == pkt[0] { + resp = resp[1:] + } + if len(resp) == 0 || resp[0] != pkt[0] { + continue + } + if pkt[0] == 0x4B && len(pkt) >= 4 && len(resp) >= 4 { + want := int(pkt[2]) | int(pkt[3])<<8 + got := int(resp[2]) | int(resp[3])<<8 + if got != want { + continue + } + } + // rpmsg 有时会把刚写出去的请求原样读回,继续等基带的真正应答。 + if len(resp) <= len(pkt) && bytes.Equal(resp, pkt[:len(resp)]) { + continue + } + if len(resp) >= 4 && resp[len(resp)-1] == 0x7e { + resp = resp[:len(resp)-3] + } + return resp, nil + } +} + +func putU16(b []byte, v int) { + b[0] = byte(v) + b[1] = byte(v >> 8) +} + +func putU32(b []byte, v uint32) { + b[0] = byte(v) + b[1] = byte(v >> 8) + b[2] = byte(v >> 16) + b[3] = byte(v >> 24) +} + +func u32(b []byte) uint32 { + return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 +} + +func efsHeader(subcmd int) []byte { + b := []byte{0x4B, 0x13, 0, 0} + putU16(b[2:], subcmd) + return b +} + +func efsHello(fd *os.File) error { + pkt := append(efsHeader(0), make([]byte, 28)...) + putU32(pkt[4:], 0x100) + putU32(pkt[8:], 0x10) + putU32(pkt[12:], 0x100) + putU32(pkt[16:], 0x10) + putU32(pkt[20:], 1) + putU32(pkt[24:], 1) + putU32(pkt[28:], 0xFFFFFFFF) + resp, err := diagCmd(fd, pkt, 3*time.Second) + if err != nil { + return fmt.Errorf("EFS HELLO: %w", err) + } + fmt.Printf("HELLO %s\n", hexBytes(resp)) + return nil +} + +func efsSync(fd *os.File) error { + pkt := append(efsHeader(26), 0, 0, 0, 0) + resp, err := diagCmd(fd, pkt, 3*time.Second) + if err != nil { + return err + } + fmt.Printf("SYNC %s\n", hexBytes(resp)) + return nil +} + +func efsStat(fd *os.File, path string) ([]byte, error) { + pkt := append(efsHeader(15), path...) + pkt = append(pkt, 0) + return diagCmd(fd, pkt, 3*time.Second) +} + +func efsPut(fd *os.File, path string, data []byte, oflag uint32) error { + pkt := append(efsHeader(2), 0, 0, 0, 0, 0, 0, 0, 0) + putU32(pkt[4:], oflag) + putU32(pkt[8:], 0644) + pkt = append(pkt, path...) + pkt = append(pkt, 0) + resp, err := diagCmd(fd, pkt, 3*time.Second) + if err != nil { + return fmt.Errorf("打开超时: %w", err) + } + if len(resp) < 12 { + return fmt.Errorf("打开响应过短 %s", hexBytes(resp)) + } + fdnum := u32(resp[4:8]) + errno := u32(resp[8:12]) + if errno != 0 || fdnum > 64 { + return fmt.Errorf("打开失败 fd=%d err=%d len=%d %s", fdnum, errno, len(resp), hexBytes(resp)) + } + wp := append(efsHeader(5), 0, 0, 0, 0, 0, 0, 0, 0) + putU32(wp[4:], fdnum) + putU32(wp[8:], 0) + wp = append(wp, data...) + wr, err := diagCmd(fd, wp, 3*time.Second) + cp := append(efsHeader(3), 0, 0, 0, 0) + putU32(cp[4:], fdnum) + _, _ = diagCmd(fd, cp, 2*time.Second) + if err != nil { + return fmt.Errorf("写入超时: %w", err) + } + if len(wr) >= 12 && u32(wr[8:12]) != 0 && u32(wr[4:8]) == 0 { + return fmt.Errorf("写入失败 %s", hexBytes(wr[:16])) + } + fmt.Printf("WRITE %s\n", hexBytes(wr)) + return nil +} + +func hexBytes(b []byte) string { + if len(b) > 48 { + b = b[:48] + } + s := make([]byte, 0, len(b)*2) + const hexd = "0123456789abcdef" + for _, c := range b { + s = append(s, hexd[c>>4], hexd[c&0x0f]) + } + return string(s) +} + +func nvRead(fd *os.File, item int) ([]byte, error) { + pkt := make([]byte, 133) + pkt[0] = diagNvRead + pkt[1] = byte(item) + pkt[2] = byte(item >> 8) + resp, err := diagCmd(fd, pkt, 5*time.Second) + if err != nil { + return nil, fmt.Errorf("读 NV %d: %w", item, err) + } + if len(resp) >= 2 && resp[0] != diagNvRead && resp[1] == diagNvRead { + resp = resp[1:] + } + if len(resp) < 133 { + return nil, fmt.Errorf("读 NV %d: 响应过短 (%d)", item, len(resp)) + } + status := int(resp[131]) | int(resp[132])<<8 + if resp[0] != diagNvRead || status != 0 { + return nil, fmt.Errorf("读 NV %d 失败: cmd=0x%02x status=%d", item, resp[0], status) + } + out := make([]byte, 128) + copy(out, resp[3:131]) + return out, nil +} + +func nvWrite(fd *os.File, item int, data []byte) error { + pkt := make([]byte, 133) + pkt[0] = diagNvWrite + pkt[1] = byte(item) + pkt[2] = byte(item >> 8) + copy(pkt[3:131], data) + resp, err := diagCmd(fd, pkt, 5*time.Second) + if err != nil { + return fmt.Errorf("写 NV %d: %w", item, err) + } + if len(resp) >= 2 && resp[0] != diagNvWrite && resp[1] == diagNvWrite { + resp = resp[1:] + } + if len(resp) < 133 { + return fmt.Errorf("写 NV %d: 响应过短 (%d)", item, len(resp)) + } + status := int(resp[131]) | int(resp[132])<<8 + if resp[0] != diagNvWrite || status != 0 { + return fmt.Errorf("写 NV %d 失败: cmd=0x%02x status=%d", item, resp[0], status) + } + return nil +} + +func spcUnlock(fd *os.File) { + pkt := make([]byte, 8) + pkt[0] = diagSpc + copy(pkt[1:], "000000") + resp, err := diagCmd(fd, pkt, 5*time.Second) + if err != nil || len(resp) < 2 || resp[1] != 1 { + fmt.Fprintf(os.Stderr, "SPC 解锁未确认,继续尝试写入。\n") + } +} + +func imeiToNV550(imei string) []byte { + d := imei + nv := []byte{0x08, byte((d[0]-'0')<<4) | 0x0A} + for i := 0; i < 7; i++ { + nv = append(nv, byte((d[2+i*2]-'0')<<4)|byte(d[1+i*2]-'0')) + } + return nv +} + +func nv550ToIMEI(nv []byte) (string, bool) { + if len(nv) < 9 || nv[0] != 0x08 { + return "", false + } + var b strings.Builder + b.WriteByte('0' + (nv[1] >> 4)) + for i := 2; i <= 8; i++ { + b.WriteByte('0' + (nv[i] & 0x0F)) + b.WriteByte('0' + (nv[i] >> 4)) + } + s := b.String() + if len(s) < 15 { + return "", false + } + return s[:15], true +} + +func restartModemManager() { + script := "/etc/init.d/modemmanager" + if _, err := os.Stat(script); err == nil { + fmt.Fprintf(os.Stderr, "正在重启 ModemManager...\n") + _ = exec.Command(script, "restart").Run() + return + } + if exec.Command("systemctl", "is-active", "--quiet", "ModemManager").Run() == nil { + fmt.Fprintf(os.Stderr, "正在重启 ModemManager...\n") + _ = exec.Command("systemctl", "restart", "ModemManager").Run() + } +}