From 8dd896f362b3dfd42040de06fb46a33011d37754 Mon Sep 17 00:00:00 2001 From: Derrors <33656531+Derrors@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:27:11 +0800 Subject: [PATCH] fix(i18n): local times with their zone, translated update errors Times in the event log, `status` / `doctor` ("last re-sign") and the re-sign message were UTC without saying so. They are now local time with the UTC offset (`2026-11-24 16:08:52 +08:00`, offset from localtime_r, so DST is right). The legacy `last_resign` sentence old versions read stays UTC. About 120 errors of the updater, the background service and the update schedule were English only and reached Chinese users through `iphone-control update` and the control page's update panel. They are now tr!/trf! pairs; outcome.json's `status` field, which the page keys on, is unchanged. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + CHANGELOG.zh-CN.md | 5 + apps/iphone-control/src/main.rs | 2 +- apps/iphone-control/src/schedule.rs | 46 +++- apps/iphone-control/src/service.rs | 77 +++++-- apps/iphone-control/src/update.rs | 9 +- apps/iphone-control/src/update/archive.rs | 52 +++-- apps/iphone-control/src/update/channel.rs | 95 +++++--- apps/iphone-control/src/update/install.rs | 49 +++- apps/iphone-control/src/update/release.rs | 2 +- apps/iphone-control/src/update/transaction.rs | 212 ++++++++++++++---- crates/ictl-daemon/src/core.rs | 18 +- crates/ictl-daemon/src/eventlog.rs | 54 ++++- crates/ictl-daemon/src/supervise.rs | 10 +- docs/dev/regression-cases.md | 2 + 15 files changed, 490 insertions(+), 148 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 40f72abf..7596db05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,11 @@ What changed in each release, one line per change. Versions follow [Semantic Ver ## [Unreleased] +### Fixes + +- Times in `status`, `doctor` and the event log are shown in local time with the time zone; they were UTC without saying so. +- Errors from `iphone-control update`, `service` and the update panel on the control page follow the chosen language; they were always in English. + ## [0.2.14] - 2026-11-24 ### New diff --git a/CHANGELOG.zh-CN.md b/CHANGELOG.zh-CN.md index 3cde6485..19cf2d16 100644 --- a/CHANGELOG.zh-CN.md +++ b/CHANGELOG.zh-CN.md @@ -6,6 +6,11 @@ ## [Unreleased] +### 修复 + +- `status`、`doctor` 和事件日志里的时间改为本地时间并标明时区,之前显示的是 UTC 却没有说明。 +- `iphone-control update`、`service` 和控制台更新面板里的报错跟随界面语言,之前总是英文。 + ## [0.2.14] - 2026-11-24 ### 新功能 diff --git a/apps/iphone-control/src/main.rs b/apps/iphone-control/src/main.rs index 793d95eb..d668b967 100644 --- a/apps/iphone-control/src/main.rs +++ b/apps/iphone-control/src/main.rs @@ -400,7 +400,7 @@ async fn update_command(action: UpdateAction, socket: &Path) -> anyhow::Result<( println!("{report}"); } if let Some(code) = report.error_code { - bail!("Update check failed: {code}") + bail!("{}", ictl_l10n::trf!("检查更新失败:{code}", "Update check failed: {code}")) } Ok(()) } diff --git a/apps/iphone-control/src/schedule.rs b/apps/iphone-control/src/schedule.rs index 31979aab..505cf88a 100644 --- a/apps/iphone-control/src/schedule.rs +++ b/apps/iphone-control/src/schedule.rs @@ -20,7 +20,13 @@ pub fn set_policy(socket: &Path, policy: update::Policy) -> Result<()> { if let Err(e) = configure_job(socket, policy) { // A partial timer install must not later run with unintended permission to replace files. update::set_policy(update::Policy::Manual)?; - bail!("Update policy is manual; could not configure the user job: {e:#}") + bail!( + "{}", + ictl_l10n::trf!( + "更新策略已改为手动:配置不了自动更新任务:{e:#}", + "Update policy is manual; could not configure the user job: {e:#}" + ) + ) } println!( "{}: {}", @@ -44,7 +50,8 @@ fn configuration_locks() -> Result<(File, File)> { .custom_flags(libc::O_NOFOLLOW) .open(config.join("update-schedule.lock"))?; if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX) } != 0 { - return Err(std::io::Error::last_os_error()).context("could not lock the update schedule"); + return Err(std::io::Error::last_os_error()) + .context(ictl_l10n::tr!("锁不住自动更新的设置", "could not lock the update schedule")); } Ok((lock, ictl_daemon::maintenance::shared()?)) } @@ -55,7 +62,7 @@ pub fn configure(socket: &Path) -> Result<()> { } fn write_file(path: &Path, bytes: &[u8]) -> Result<()> { - fs::create_dir_all(path.parent().context("invalid job path")?)?; + fs::create_dir_all(path.parent().context(ictl_l10n::tr!("自动更新任务的路径不对", "invalid job path"))?)?; crate::update::write_atomic(path, bytes) } @@ -71,15 +78,19 @@ fn run(program: &str, args: &[&str]) -> Result<()> { } fn path_str(path: &Path) -> Result<&str> { - let s = path.to_str().context("non UTF-8 update job path")?; - ensure!(path.is_absolute() && !s.contains(['\r', '\n']), "expected an absolute update job path"); + let s = path.to_str().context(ictl_l10n::tr!("自动更新任务的路径不是 UTF-8", "non UTF-8 update job path"))?; + ensure!( + path.is_absolute() && !s.contains(['\r', '\n']), + "{}", + ictl_l10n::tr!("自动更新任务的路径要是绝对路径", "expected an absolute update job path") + ); Ok(s) } fn launcher(exe: &Path, socket: &Path, config: &Path) -> Result { let exe = shell_quote(path_str(exe)?); let sock = shell_quote(path_str(socket)?); - let xdg = shell_quote(path_str(config.parent().context("missing config home")?)?); + let xdg = shell_quote(path_str(config.parent().context(ictl_l10n::tr!("找不到配置目录", "missing config home"))?)?); // launchd and the interactive shell often have different XDG environments. The timer // must see the same release cache as Viewer, including a custom cache location. let mut xdg_env = String::new(); @@ -111,7 +122,7 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { let jobs = if mac { envfile::home().join("Library/LaunchAgents") } else { - config.parent().context("missing config home")?.join("systemd/user") + config.parent().context(ictl_l10n::tr!("找不到配置目录", "missing config home"))?.join("systemd/user") }; let job = jobs.join(if mac { format!("{LABEL}.plist") } else { UNIT.into() }); let timer = jobs.join(TIMER); @@ -121,15 +132,24 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { if launcher_file.try_exists()? { ensure!( fs::read_to_string(&launcher_file)?.lines().nth(2) == Some(owner.as_str()), - "the updater job belongs to a different executable" + "{}", + ictl_l10n::tr!("自动更新任务属于另一个程序", "the updater job belongs to a different executable") ); } else { - ensure!(!job.try_exists()? && (mac || !timer.try_exists()?), "an unrecognized update job already exists"); + ensure!( + !job.try_exists()? && (mac || !timer.try_exists()?), + "{}", + ictl_l10n::tr!("已经有一个认不出来的自动更新任务", "an unrecognized update job already exists") + ); if !enabled { return Ok(()); } } - ensure!(!ictl_daemon::protocol::running_as_root(), "only user update jobs are supported"); + ensure!( + !ictl_daemon::protocol::running_as_root(), + "{}", + ictl_l10n::tr!("只支持用户级的自动更新任务", "only user update jobs are supported") + ); if enabled { write_file(&launcher_file, launcher(&service::stable_exe()?, socket, &config)?.as_bytes())?; } @@ -140,7 +160,11 @@ fn configure_job(socket: &Path, policy: update::Policy) -> Result<()> { let loaded = if loaded.status.success() { let listing = std::str::from_utf8(&loaded.stdout)?; let path = listing.lines().find_map(|line| line.strip_prefix('\t')?.strip_prefix("path = ")); - ensure!(path.map(Path::new) == Some(&job), "launchd loaded a different updater plist"); + ensure!( + path.map(Path::new) == Some(&job), + "{}", + ictl_l10n::tr!("launchd 载入的是另一个自动更新 plist", "launchd loaded a different updater plist") + ); true } else { false diff --git a/apps/iphone-control/src/service.rs b/apps/iphone-control/src/service.rs index 995bd99d..92ef2555 100644 --- a/apps/iphone-control/src/service.rs +++ b/apps/iphone-control/src/service.rs @@ -131,16 +131,24 @@ pub fn managed(exe: &Path, method: &str) -> anyhow::Result { (our_plist(), Service::Launchd { label: LABEL.into(), plist: our_plist(), ours: true }) } "systemd" if cfg!(target_os = "linux") => (our_unit(), Service::Systemd { unit: UNIT.into(), ours: true }), - _ => bail!("a script-managed user service is required"), + _ => bail!("{}", ictl_l10n::tr!("需要由安装脚本管理的用户服务", "a script-managed user service is required")), }; let meta = file.symlink_metadata()?; - ensure!(meta.is_file() && meta.uid() == uid() && meta.mode() & 0o022 == 0, "untrusted service file"); - let exe = exe.to_str().context("invalid executable path")?; + ensure!( + meta.is_file() && meta.uid() == uid() && meta.mode() & 0o022 == 0, + "{}", + ictl_l10n::tr!("后台服务文件不可信", "untrusted service file") + ); + let exe = exe.to_str().context(ictl_l10n::tr!("程序路径不对", "invalid executable path"))?; match &service { Service::Launchd { label, .. } => { let plist = plist::Value::from_file(&file)?; - let dict = plist.as_dictionary().context("invalid service plist")?; - let args = dict.get("ProgramArguments").and_then(|v| v.as_array()).context("missing service arguments")?; + let dict = + plist.as_dictionary().context(ictl_l10n::tr!("后台服务的 plist 不对", "invalid service plist"))?; + let args = dict + .get("ProgramArguments") + .and_then(|v| v.as_array()) + .context(ictl_l10n::tr!("后台服务缺少启动参数", "missing service arguments"))?; let script = format!( r#"set -a; f="$HOME/.config/iphone-control/env"; [ -f "$f" ] && . "$f"; set +a; exec "{exe}" daemon"# ); @@ -149,18 +157,26 @@ pub fn managed(exe: &Path, method: &str) -> anyhow::Result { && !dict.contains_key("Program") && (args.iter().map(|v| v.as_string()).eq([Some(exe), Some("daemon")]) || args.iter().map(|v| v.as_string()).eq([Some("/bin/sh"), Some("-c"), Some(script.as_str())])), - "the launch agent does not start the recorded binary" + "{}", + ictl_l10n::tr!( + "launchd 服务启动的不是记录里的程序", + "the launch agent does not start the recorded binary" + ) ); } Service::Systemd { .. } => { let unit = std::fs::read_to_string(&file)?; let mut commands = unit.lines().filter_map(|line| line.trim().strip_prefix("ExecStart=")); - let command = commands.next().context("missing ExecStart")?; + let command = commands.next().context(ictl_l10n::tr!("缺少 ExecStart", "missing ExecStart"))?; ensure!( commands.next().is_none() && (command == format!(r#""{exe}" daemon"#) || (!exe.contains(char::is_whitespace) && command == format!("{exe} daemon"))), - "the systemd unit does not start the recorded binary" + "{}", + ictl_l10n::tr!( + "systemd 服务启动的不是记录里的程序", + "the systemd unit does not start the recorded binary" + ) ); } } @@ -179,7 +195,8 @@ pub fn managed_pid(service: &Service, stopping: bool) -> anyhow::Result anyhow::Result anyhow::Result Ok(None), - (Some("active"), Some(pid)) => { - Ok(Some(pid.parse::().ok().filter(|p| *p > 0).context("missing MainPID")?)) - } + (Some("active"), Some(pid)) => Ok(Some( + pid.parse::() + .ok() + .filter(|p| *p > 0) + .context(ictl_l10n::tr!("缺少 MainPID", "missing MainPID"))?, + )), (_, Some(pid)) if stopping => Ok(pid.parse::().ok().filter(|p| *p > 0)), - _ => bail!("systemd service is transitioning"), + _ => bail!("{}", ictl_l10n::tr!("systemd 服务正在启动或停止", "systemd service is transitioning")), } } } @@ -222,19 +247,31 @@ pub fn managed_pid(service: &Service, stopping: bool) -> anyhow::Result anyhow::Result> { let field = |key: &str| info.lines().find_map(|line| line.strip_prefix('\t')?.strip_prefix(key)); - ensure!(field("path = ").map(Path::new) == Some(plist), "launchd loaded a different plist"); + ensure!( + field("path = ").map(Path::new) == Some(plist), + "{}", + ictl_l10n::tr!("launchd 载入的是另一个 plist", "launchd loaded a different plist") + ); let pid = field("pid = "); if pid.is_none() && (stopping || field("state = ") == Some("not running")) { return Ok(None); } - ensure!(stopping || field("state = ") == Some("running"), "launchd service is transitioning"); - Ok(Some(pid.context("no launchd PID")?.parse()?)) + ensure!( + stopping || field("state = ") == Some("running"), + "{}", + ictl_l10n::tr!("launchd 服务正在启动或停止", "launchd service is transitioning") + ); + Ok(Some(pid.context(ictl_l10n::tr!("launchd 没有给出进程号", "no launchd PID"))?.parse()?)) } /// Restart exactly the service we stopped without changing the user's enable-at-login setting. pub fn start_managed(s: &Service) -> anyhow::Result<()> { if let Service::Systemd { unit, .. } = s { - ensure!(systemctl(&["start", unit]), "could not start systemd user service"); + ensure!( + systemctl(&["start", unit]), + "{}", + ictl_l10n::tr!("启动不了 systemd 用户服务", "could not start systemd user service") + ); Ok(()) } else { start(s) @@ -570,7 +607,7 @@ pub fn pause_viewer() -> anyhow::Result> { std::thread::sleep(std::time::Duration::from_millis(200)); } let _ = start(&s); - bail!("busy: the viewer service didn't stop") + bail!("{}", ictl_l10n::tr!("正忙:控制台服务没有停下", "busy: the viewer service didn't stop")) } /// Starts the control page's service again after [`pause_viewer`]; a failure is only reported diff --git a/apps/iphone-control/src/update.rs b/apps/iphone-control/src/update.rs index 6d44e952..fe1e0aae 100644 --- a/apps/iphone-control/src/update.rs +++ b/apps/iphone-control/src/update.rs @@ -124,7 +124,9 @@ impl Report { /// (the updater's store is private and checked, see `transaction::Store::open`) pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> { use std::io::Write; - let dir = path.parent().ok_or_else(|| anyhow::anyhow!("no parent directory: {}", path.display()))?; + let dir = path.parent().ok_or_else(|| { + anyhow::anyhow!("{}", ictl_l10n::trf!("没有上级目录:{}", "no parent directory: {}", path.display())) + })?; let mut tmp = tempfile::NamedTempFile::new_in(dir)?; tmp.write_all(bytes)?; tmp.as_file().sync_all()?; @@ -490,7 +492,10 @@ pub async fn upgrade(socket: &Path, report: Report, yes: bool) -> Result<()> { if !confirm(&report, yes)? { return Ok(()); } - let version = report.available_version.clone().ok_or_else(|| anyhow::anyhow!("missing release version"))?; + let version = report + .available_version + .clone() + .ok_or_else(|| anyhow::anyhow!("{}", ictl_l10n::tr!("缺少发布版本号", "missing release version")))?; transaction::apply(socket, false, report).await?; println!("{}", trf!("已升级到 {version}。", "Updated to {version}.")); } diff --git a/apps/iphone-control/src/update/archive.rs b/apps/iphone-control/src/update/archive.rs index a49e5cdb..dcc3c839 100644 --- a/apps/iphone-control/src/update/archive.rs +++ b/apps/iphone-control/src/update/archive.rs @@ -75,11 +75,15 @@ pub(super) fn client() -> anyhow::Result { pub(super) async fn download(client: &Client, url: &str, max: u64, mut out: impl Write) -> anyhow::Result { let mut response = client.get(url).send().await.and_then(|r| r.error_for_status()).map_err(reqwest::Error::without_url)?; - ensure!(response.content_length().is_none_or(|s| s <= max), "release asset exceeds size limit"); + ensure!( + response.content_length().is_none_or(|s| s <= max), + "{}", + ictl_l10n::tr!("发布文件超过大小上限", "release asset exceeds size limit") + ); let mut size = 0; while let Some(chunk) = response.chunk().await.map_err(reqwest::Error::without_url)? { size += chunk.len() as u64; - ensure!(size <= max, "release asset exceeds size limit"); + ensure!(size <= max, "{}", ictl_l10n::tr!("发布文件超过大小上限", "release asset exceeds size limit")); out.write_all(&chunk)?; } Ok(size) @@ -98,7 +102,9 @@ fn key_bytes(key: &str) -> Option<[u8; 32]> { /// The release signing keys this build trusts (`ICTL_UPDATE_PUBLIC_KEYS`) pub(super) fn keys() -> anyhow::Result<&'static str> { - option_env!("ICTL_UPDATE_PUBLIC_KEYS").filter(|s| !s.is_empty()).context("this build has no update trust key") + option_env!("ICTL_UPDATE_PUBLIC_KEYS") + .filter(|s| !s.is_empty()) + .context(ictl_l10n::tr!("这个版本没有内置更新用的公钥", "this build has no update trust key")) } /// Downloads `.manifest.json` and its signature from release `version` of `publisher` and checks both @@ -134,18 +140,21 @@ fn verify( ) -> anyhow::Result { ensure!( keys.split(',').filter_map(key_bytes).any(|key| UnparsedPublicKey::new(&ED25519, key).verify(raw, sig).is_ok()), - "invalid release signature" + "{}", + ictl_l10n::tr!("发布签名不对", "invalid release signature") ); let m: Manifest = serde_json::from_slice(raw)?; ensure!( m.schema == 1 && m.publisher == publisher && m.target == target && m.version == version && m.asset == asset, - "manifest does not match this release" + "{}", + ictl_l10n::tr!("清单和这个版本对不上", "manifest does not match this release") ); ensure!( (1..=MAX_ARCHIVE).contains(&m.size) && key_bytes(&m.sha256).is_some() && m.sha256.bytes().all(|b| !b.is_ascii_uppercase()), - "invalid signed digest or size" + "{}", + ictl_l10n::tr!("签名里的摘要或大小不对", "invalid signed digest or size") ); Ok(m) } @@ -157,21 +166,30 @@ fn extract(archive: &Path, root: &str, candidate: &Path) -> anyhow::Result<()> { let mut tar = tar::Archive::new(gzip.take(MAX_EXPANDED + 1)); let mut found = false; for (n, item) in tar.entries()?.enumerate() { - ensure!(n < 32, "too many archive entries"); + ensure!(n < 32, "{}", ictl_l10n::tr!("压缩包里的文件太多", "too many archive entries")); let mut item = item?; let name = item.path()?; let kind = item.header().entry_type(); if name == Path::new(root) && kind.is_dir() { continue; } - ensure!(name.parent() == Some(Path::new(root)) && kind.is_file(), "unexpected path or link in release archive"); + ensure!( + name.parent() == Some(Path::new(root)) && kind.is_file(), + "{}", + ictl_l10n::tr!("发布包里有不该有的路径或链接", "unexpected path or link in release archive") + ); if name.file_name().is_some_and(|n| n == "iphone-control") { ensure!( !found && (1..=MAX_EXPANDED).contains(&item.size()) && item.header().mode()? & 0o111 != 0, - "invalid executable entry" + "{}", + ictl_l10n::tr!("压缩包里的程序条目不对", "invalid executable entry") ); let mut out = File::create_new(candidate)?; - ensure!(std::io::copy(&mut item, &mut out)? == item.size(), "truncated executable"); + ensure!( + std::io::copy(&mut item, &mut out)? == item.size(), + "{}", + ictl_l10n::tr!("程序文件不完整", "truncated executable") + ); out.set_permissions(std::fs::Permissions::from_mode(0o755))?; out.sync_all()?; found = true; @@ -179,7 +197,11 @@ fn extract(archive: &Path, root: &str, candidate: &Path) -> anyhow::Result<()> { } let mut decoder = tar.into_inner(); std::io::copy(&mut decoder, &mut std::io::sink())?; - ensure!(decoder.limit() > 0 && found, "invalid expanded archive size or missing executable"); + ensure!( + decoder.limit() > 0 && found, + "{}", + ictl_l10n::tr!("解压后的大小不对,或者缺少程序", "invalid expanded archive size or missing executable") + ); Ok(()) } @@ -187,7 +209,8 @@ fn unpack(m: &Manifest, stage: &Path) -> anyhow::Result { let archive = stage.join("archive"); ensure!( archive.metadata()?.len() == m.size && super::digest(&archive)? == m.sha256, - "release archive digest or size mismatch" + "{}", + ictl_l10n::tr!("发布包的摘要或大小对不上", "release archive digest or size mismatch") ); let candidate = stage.join("candidate"); extract(&archive, m.asset.trim_end_matches(".tar.gz"), &candidate)?; @@ -222,7 +245,7 @@ pub(super) async fn preflight(candidate: &Path, version: &str) -> anyhow::Result cmd.arg("--version").kill_on_drop(true); match tokio::time::timeout(Duration::from_secs(10), cmd.output()) .await - .context("candidate --version timed out")? + .context(ictl_l10n::tr!("新版本程序运行 --version 超时", "candidate --version timed out"))? { Err(e) if e.raw_os_error() == Some(libc::ETXTBSY) && busy < 20 => { busy += 1; @@ -233,7 +256,8 @@ pub(super) async fn preflight(candidate: &Path, version: &str) -> anyhow::Result }; ensure!( out.status.success() && std::str::from_utf8(&out.stdout)?.trim() == format!("iphone-control {version}"), - "unexpected candidate --version" + "{}", + ictl_l10n::tr!("新版本程序 --version 的输出不对", "unexpected candidate --version") ); Ok(()) } diff --git a/apps/iphone-control/src/update/channel.rs b/apps/iphone-control/src/update/channel.rs index ae5e127e..ff3c23c0 100644 --- a/apps/iphone-control/src/update/channel.rs +++ b/apps/iphone-control/src/update/channel.rs @@ -17,14 +17,23 @@ use super::{Availability, InstallMethod, Report, archive, deb_asset, digest, ins const DEB_UNIT: &str = "/usr/lib/systemd/user/iphone-control.service"; pub(super) async fn apply(socket: &Path, report: &Report) -> Result<()> { - let exe = report.executable.as_deref().context("missing installation path")?; - let latest = report.available_version.as_deref().context("missing release version")?; - ensure!(release::stable_tag(&format!("v{latest}")).is_some(), "invalid stable release version"); + let exe = report.executable.as_deref().context(ictl_l10n::tr!("缺少安装路径", "missing installation path"))?; + let latest = + report.available_version.as_deref().context(ictl_l10n::tr!("缺少发布版本号", "missing release version"))?; + ensure!( + release::stable_tag(&format!("v{latest}")).is_some(), + "{}", + ictl_l10n::tr!("正式版的版本号不对", "invalid stable release version") + ); match (report.install_method, report.availability) { (InstallMethod::Homebrew, Availability::BrewCheck) => { - let cellar = exe.ancestors().nth(4).context("missing Homebrew Cellar")?; - let tap = tap().context("missing Homebrew tap")?; - let brew = install::brew_program(cellar).context("cannot locate the Homebrew executable")?; + let cellar = exe + .ancestors() + .nth(4) + .context(ictl_l10n::tr!("找不到 Homebrew 的 Cellar", "missing Homebrew Cellar"))?; + let tap = tap().context(ictl_l10n::tr!("缺少 Homebrew tap", "missing Homebrew tap"))?; + let brew = install::brew_program(cellar) + .context(ictl_l10n::tr!("找不到 Homebrew 程序", "cannot locate the Homebrew executable"))?; if homebrew(&brew, cellar, tap, latest).await? { let running = brew_service_running(&brew).await; restart( @@ -39,8 +48,9 @@ pub(super) async fn apply(socket: &Path, report: &Report) -> Result<()> { Ok(()) } (InstallMethod::Debian, Availability::Available) => { - let repo = publisher().context("missing release publisher")?; - let target = super::target().context("unsupported Debian architecture")?; + let repo = publisher().context(ictl_l10n::tr!("缺少发布者", "missing release publisher"))?; + let target = + super::target().context(ictl_l10n::tr!("不支持的 Debian 架构", "unsupported Debian architecture"))?; if debian(repo, target, latest, exe).await? { let running = deb_service_running().await; restart( @@ -149,18 +159,17 @@ async fn wait_for_daemon(socket: &Path, version: &str, within: Duration) -> bool } async fn run(cmd: &mut Command) -> Result<()> { - let status = - cmd.status().await.with_context(|| format!("starting {}", cmd.as_std().get_program().to_string_lossy()))?; + let status = cmd.status().await.with_context(|| { + ictl_l10n::trf!("启动 {} 失败", "starting {}", cmd.as_std().get_program().to_string_lossy()) + })?; ensure!(status.success(), "{}: {status}", cmd.as_std().get_program().to_string_lossy()); Ok(()) } async fn output(cmd: &mut Command) -> Result { - let result = cmd - .stderr(Stdio::inherit()) - .output() - .await - .with_context(|| format!("starting {}", cmd.as_std().get_program().to_string_lossy()))?; + let result = cmd.stderr(Stdio::inherit()).output().await.with_context(|| { + ictl_l10n::trf!("启动 {} 失败", "starting {}", cmd.as_std().get_program().to_string_lossy()) + })?; ensure!(result.status.success(), "{}: {}", cmd.as_std().get_program().to_string_lossy(), result.status); Ok(String::from_utf8(result.stdout)?) } @@ -168,13 +177,15 @@ async fn output(cmd: &mut Command) -> Result { /// True when it upgraded (false: Homebrew already had `latest`) async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result { let formula = format!("{tap}/iphone-control"); - let active = cellar.parent().context("invalid Homebrew prefix")?.join("opt/iphone-control/bin/iphone-control"); + let active = cellar + .parent() + .context(ictl_l10n::tr!("Homebrew 的安装前缀不对", "invalid Homebrew prefix"))? + .join("opt/iphone-control/bin/iphone-control"); let installed = || { - active - .canonicalize() - .ok() - .and_then(|exe| install::brew_keg(&exe, cellar, tap)) - .context("Homebrew's active keg does not match this installation and tap") + active.canonicalize().ok().and_then(|exe| install::brew_keg(&exe, cellar, tap)).context(ictl_l10n::tr!( + "Homebrew 当前启用的版本和这个安装、tap 对不上", + "Homebrew's active keg does not match this installation and tap" + )) }; let before = semver::Version::parse(&installed()?)?; if before >= semver::Version::parse(latest)? { @@ -193,7 +204,8 @@ async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result let f = &info["formulae"][0]; ensure!( f["full_name"].as_str().is_some_and(|s| s.eq_ignore_ascii_case(&formula)), - "Homebrew formula identity changed" + "{}", + ictl_l10n::tr!("Homebrew formula 的身份变了", "Homebrew formula identity changed") ); ensure!(f["pinned"] == false, "{}", tr!("Homebrew 已固定此版本。", "This formula is pinned in Homebrew.")); ensure!( @@ -205,7 +217,11 @@ async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result ) ); run(cmd().args(["upgrade", "--formula", &formula])).await?; - ensure!(installed()? == latest, "Homebrew did not activate {latest}"); + ensure!( + installed()? == latest, + "{}", + ictl_l10n::trf!("Homebrew 没有启用 {latest}", "Homebrew did not activate {latest}") + ); println!("{}", ictl_l10n::trf!("Homebrew 已升级至 {latest}。", "Homebrew upgraded to {latest}.")); Ok(true) } @@ -213,14 +229,19 @@ async fn homebrew(brew: &Path, cellar: &Path, tap: &str, latest: &str) -> Result fn check_deb_metadata<'a>(fields: &'a str, version: &str, arch: &str) -> Result<&'a str> { let mut lines = fields.lines(); let (name, package_version, architecture) = (lines.next(), lines.next(), lines.next()); - let package_version = package_version.context("missing Debian package version")?; + let package_version = + package_version.context(ictl_l10n::tr!("缺少 Debian 包的版本号", "missing Debian package version"))?; // cargo-deb adds its Debian revision to the upstream package version. ensure!( name == Some("iphone-control") && architecture == Some(arch) && lines.next().is_none() && (package_version == version || package_version.strip_suffix("-1") == Some(version)), - "Debian package metadata does not match iphone-control {version} {arch}" + "{}", + ictl_l10n::trf!( + "Debian 包的信息和 iphone-control {version} {arch} 对不上", + "Debian package metadata does not match iphone-control {version} {arch}" + ) ); Ok(package_version) } @@ -251,8 +272,12 @@ async fn check_apt_candidate(apt_cache: &mut Command, path: &Path, deb_version: /// True when it upgraded (false: APT already had `latest`) async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result { - let asset = deb_asset(latest, target).context("unsupported Debian architecture")?; - let arch = asset.rsplit_once('_').and_then(|(_, s)| s.strip_suffix(".deb")).context("invalid Debian asset name")?; + let asset = + deb_asset(latest, target).context(ictl_l10n::tr!("不支持的 Debian 架构", "unsupported Debian architecture"))?; + let arch = asset + .rsplit_once('_') + .and_then(|(_, s)| s.strip_suffix(".deb")) + .context(ictl_l10n::tr!("Debian 包的文件名不对", "invalid Debian asset name"))?; let client = archive::client()?; let signed = archive::signed_manifest(&client, repo, target, latest, &asset).await?; let temp = tempfile::tempdir()?; @@ -261,12 +286,19 @@ async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result= semver::Version::parse(latest)? { println!("{}", ictl_l10n::trf!("APT 当前版本为 {current}。", "APT already has {current}.")); return Ok(false); @@ -298,7 +330,8 @@ async fn debian(repo: &str, target: &str, latest: &str, exe: &Path) -> Result PathBuf { } pub fn read_receipt() -> Result { - let file = File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(receipt_path()).context("No readable script installation receipt; run iphone-control update check for the upgrade instructions for this installation")?; + let file = File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(receipt_path()).context(ictl_l10n::tr!("读不到脚本安装的记录;运行 iphone-control update check,查看这种安装方式怎么升级", "No readable script installation receipt; run iphone-control update check for the upgrade instructions for this installation"))?; let meta = file.metadata()?; - ensure!(user_owned(&meta) && meta.is_file() && meta.len() < 16 * 1024, "invalid installation receipt file"); + ensure!( + user_owned(&meta) && meta.is_file() && meta.len() < 16 * 1024, + "{}", + ictl_l10n::tr!("安装记录文件不对", "invalid installation receipt file") + ); let r: Receipt = serde_json::from_reader(file)?; ensure!( r.schema == 1 && Some(r.publisher.as_str()) == publisher() && Some(r.target.as_str()) == target(), - "receipt does not match this build" + "{}", + ictl_l10n::tr!("安装记录和这个版本对不上", "receipt does not match this build") + ); + ensure!( + matches!(r.service.as_str(), "none" | "launchd" | "systemd"), + "{}", + ictl_l10n::tr!("安装记录里的后台服务不对", "invalid service in receipt") ); - ensure!(matches!(r.service.as_str(), "none" | "launchd" | "systemd"), "invalid service in receipt"); ensure!( r.binary_path.is_absolute() && r.binary_path.file_name().is_some_and(|n| n == "iphone-control"), - "invalid binary path" + "{}", + ictl_l10n::tr!("程序路径不对", "invalid binary path") + ); + ensure!( + Version::parse(&r.version).is_ok(), + "{}", + ictl_l10n::tr!("安装记录里的版本号不对", "invalid receipt version") ); - ensure!(Version::parse(&r.version).is_ok(), "invalid receipt version"); ensure!( r.sha256.len() == 64 && r.sha256.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()), - "invalid binary digest" + "{}", + ictl_l10n::tr!("程序摘要不对", "invalid binary digest") ); Ok(r) } @@ -59,13 +74,22 @@ fn user_owned(meta: &Metadata) -> bool { fn receipt_file(r: &Receipt, exe: &Path) -> Result { ensure!( exe.canonicalize()? == r.binary_path && r.binary_path.canonicalize()? == r.binary_path, - "receipt belongs to another executable" + "{}", + ictl_l10n::tr!("安装记录是另一个程序的", "receipt belongs to another executable") + ); + let parent = r.binary_path.parent().context(ictl_l10n::tr!("安装目录不存在", "missing install directory"))?; + ensure!( + user_owned(&fs::metadata(parent)?), + "{}", + ictl_l10n::tr!("安装目录的所有者或权限不安全", "unsafe install directory ownership or permissions") ); - let parent = r.binary_path.parent().context("missing install directory")?; - ensure!(user_owned(&fs::metadata(parent)?), "unsafe install directory ownership or permissions"); let file = File::options().read(true).custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).open(&r.binary_path)?; let meta = file.metadata()?; - ensure!(meta.is_file() && user_owned(&meta) && meta.mode() & 0o100 != 0, "unsafe installed executable"); + ensure!( + meta.is_file() && user_owned(&meta) && meta.mode() & 0o100 != 0, + "{}", + ictl_l10n::tr!("已安装的程序文件不安全", "unsafe installed executable") + ); Ok(file) } @@ -90,7 +114,8 @@ pub fn digest(path: &Path) -> Result { pub fn validate_receipt(receipt: &Receipt, expected_exe: &Path) -> Result<()> { ensure!( hash(receipt_file(receipt, expected_exe)?)? == receipt.sha256, - "installed binary digest differs from receipt" + "{}", + ictl_l10n::tr!("已安装程序的摘要和安装记录不同", "installed binary digest differs from receipt") ); Ok(()) } diff --git a/apps/iphone-control/src/update/release.rs b/apps/iphone-control/src/update/release.rs index 79ea56e6..073c8c8d 100644 --- a/apps/iphone-control/src/update/release.rs +++ b/apps/iphone-control/src/update/release.rs @@ -129,7 +129,7 @@ pub(super) fn read(dir: &Path) -> Result { } pub(super) fn write_json(path: &Path, data: &impl Serialize) -> Result<()> { - fs::create_dir_all(path.parent().context("missing update state directory")?)?; + fs::create_dir_all(path.parent().context(ictl_l10n::tr!("缺少更新的状态目录", "missing update state directory"))?)?; super::write_json_atomic(path, data) } diff --git a/apps/iphone-control/src/update/transaction.rs b/apps/iphone-control/src/update/transaction.rs index 70928fc8..76e2f43d 100644 --- a/apps/iphone-control/src/update/transaction.rs +++ b/apps/iphone-control/src/update/transaction.rs @@ -45,7 +45,10 @@ struct Transaction { const LEGACY_PREVIOUS: [&str; 2] = ["previous", "previous.json"]; fn state_dir(exe: &Path) -> Result { - Ok(exe.parent().context("invalid installation path")?.join(".iphone-control-update")) + Ok(exe + .parent() + .context(ictl_l10n::tr!("安装路径不对", "invalid installation path"))? + .join(".iphone-control-update")) } fn read_json(path: &Path) -> Result> { @@ -54,7 +57,11 @@ fn read_json(path: &Path) -> Result> { Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(None), Err(e) => return Err(e.into()), }; - ensure!(file.metadata()?.is_file() && file.metadata()?.len() <= 64 * 1024, "invalid updater state file"); + ensure!( + file.metadata()?.is_file() && file.metadata()?.len() <= 64 * 1024, + "{}", + ictl_l10n::tr!("更新器的状态文件不对", "invalid updater state file") + ); Ok(Some(serde_json::from_reader(file)?)) } @@ -71,12 +78,13 @@ struct Store { impl Store { fn open(binary: &Path, receipt: PathBuf) -> Result { - let parent = binary.parent().context("invalid installation path")?; + let parent = binary.parent().context(ictl_l10n::tr!("安装路径不对", "invalid installation path"))?; let uid = unsafe { libc::geteuid() }; let meta = parent.metadata()?; ensure!( uid != 0 && binary.canonicalize()? == binary && meta.uid() == uid && meta.mode() & 0o022 == 0, - "unsafe installation directory" + "{}", + ictl_l10n::tr!("安装目录不安全(所有者或权限不对)", "unsafe installation directory") ); let lock = File::options() .read(true) @@ -87,9 +95,14 @@ impl Store { .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK) .open(parent.join(".iphone-control-update.lock"))?; let meta = lock.metadata()?; - ensure!(meta.is_file() && meta.uid() == uid && meta.mode() & 0o077 == 0, "unsafe updater lock"); + ensure!( + meta.is_file() && meta.uid() == uid && meta.mode() & 0o077 == 0, + "{}", + ictl_l10n::tr!("更新器的锁文件不安全", "unsafe updater lock") + ); if unsafe { libc::flock(lock.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) } != 0 { - return Err(io::Error::last_os_error()).context("another installation transaction is running"); + return Err(io::Error::last_os_error()) + .context(ictl_l10n::tr!("另一个安装正在进行", "another installation transaction is running")); } let dir = state_dir(binary)?; match fs::DirBuilder::new().mode(0o700).create(&dir) { @@ -98,7 +111,11 @@ impl Store { Err(e) => return Err(e.into()), } let meta = dir.symlink_metadata()?; - ensure!(meta.is_dir() && meta.uid() == uid && meta.mode() & 0o077 == 0, "unsafe updater directory"); + ensure!( + meta.is_dir() && meta.uid() == uid && meta.mode() & 0o077 == 0, + "{}", + ictl_l10n::tr!("更新器的目录不安全", "unsafe updater directory") + ); Ok(Self { binary: binary.into(), receipt, dir, _lock: lock }) } @@ -135,7 +152,8 @@ impl Store { } fs::hard_link(source, &tmp)?; fs::rename(&tmp, dest)?; - File::open(dest.parent().context("missing destination directory")?)?.sync_all()?; + File::open(dest.parent().context(ictl_l10n::tr!("目标目录不存在", "missing destination directory"))?)? + .sync_all()?; File::open(&self.dir)?.sync_all()?; Ok(()) } @@ -180,7 +198,7 @@ fn process_path(pid: u32) -> Result { use std::os::unix::ffi::OsStrExt; let mut buf = [0u8; libc::PROC_PIDPATHINFO_MAXSIZE as usize]; let n = unsafe { libc::proc_pidpath(pid as i32, buf.as_mut_ptr().cast(), buf.len() as u32) }; - ensure!(n > 0, "cannot identify daemon process"); + ensure!(n > 0, "{}", ictl_l10n::tr!("认不出守护进程是哪个程序", "cannot identify daemon process")); Ok(PathBuf::from(std::ffi::OsStr::from_bytes(&buf[..n as usize]))) } @@ -193,21 +211,32 @@ fn check_clients(daemon: Option) -> Result<()> { // Older binaries don't take a shared lease. Refuse an existing client (also an installation // using a different socket) before restarting the service. let output = std::process::Command::new("ps").args(["-A", "-o", "uid=,pid=,comm="]).env("LC_ALL", "C").output()?; - ensure!(output.status.success(), "cannot enumerate running clients"); + ensure!( + output.status.success(), + "{}", + ictl_l10n::tr!("列不出正在运行的客户端", "cannot enumerate running clients") + ); let uid = unsafe { libc::geteuid() }; for line in std::str::from_utf8(&output.stdout)?.lines() { let mut parts = line.split_whitespace(); if parts.next().and_then(|s| s.parse::().ok()) != Some(uid) { continue; } - let pid = parts.next().and_then(|s| s.parse::().ok()).context("invalid process list")?; + let pid = parts + .next() + .and_then(|s| s.parse::().ok()) + .context(ictl_l10n::tr!("进程列表读不懂", "invalid process list"))?; if daemon == Some(pid) || pid == std::process::id() { continue; } let command = parts.collect::>().join(" "); ensure!( !Path::new(&command).file_name().is_some_and(|s| s == "iphone-control"), - "busy: another iphone-control process ({pid}) is running" + "{}", + ictl_l10n::trf!( + "正忙:另一个 iphone-control 进程({pid})在运行", + "busy: another iphone-control process ({pid}) is running" + ) ); } Ok(()) @@ -228,8 +257,16 @@ impl Host<'_> { match tokio::net::UnixStream::connect(self.socket).await { Ok(s) => { let cred = s.peer_cred()?; - ensure!(cred.uid() == unsafe { libc::geteuid() }, "unexpected daemon socket owner"); - Ok(Some(cred.pid().context("unknown daemon socket PID")?.try_into()?)) + ensure!( + cred.uid() == unsafe { libc::geteuid() }, + "{}", + ictl_l10n::tr!("控制接口的所有者不对", "unexpected daemon socket owner") + ); + Ok(Some( + cred.pid() + .context(ictl_l10n::tr!("不知道控制接口是哪个进程在服务", "unknown daemon socket PID"))? + .try_into()?, + )) } Err(e) if matches!(e.kind(), io::ErrorKind::NotFound | io::ErrorKind::ConnectionRefused) => Ok(None), Err(e) => Err(e.into()), @@ -249,8 +286,10 @@ impl Services for Host<'_> { Ok(ictl_daemon::maintenance::mark_pending(journal)?) } fn exclusive(&self) -> Result { - ictl_daemon::maintenance::exclusive() - .context("busy; retry in a minute (the automatic job tries again next hour)") + ictl_daemon::maintenance::exclusive().context(ictl_l10n::tr!( + "正忙,一分钟后再试(自动更新下个小时会再试)", + "busy; retry in a minute (the automatic job tries again next hour)" + )) } async fn idle(&self, current: &Receipt) -> Result { @@ -260,19 +299,32 @@ impl Services for Host<'_> { if let Some(pid) = pid { ensure!( self.socket_owner().await? == Some(pid) && self.healthy(pid, ¤t.version).await, - "busy: service and socket identity do not match" + "{}", + ictl_l10n::tr!("正忙:后台服务和控制接口对不上", "busy: service and socket identity do not match") ); } else { - ensure!(self.socket_owner().await?.is_none(), "busy: a foreground daemon is running"); + ensure!( + self.socket_owner().await?.is_none(), + "{}", + ictl_l10n::tr!("正忙:有一个在前台运行的守护进程", "busy: a foreground daemon is running") + ); } Ok(pid.is_some()) } async fn stop(&self) -> Result<()> { let pid = service::managed_pid(&self.service, true)?; - ensure!(pid.is_none_or(|p| self.owns_pid(p)), "service PID belongs to another executable"); + ensure!( + pid.is_none_or(|p| self.owns_pid(p)), + "{}", + ictl_l10n::tr!("后台服务的进程是另一个程序", "service PID belongs to another executable") + ); if let Some(peer) = self.socket_owner().await? { - ensure!(Some(peer) == pid, "busy: socket is served by a different process"); + ensure!( + Some(peer) == pid, + "{}", + ictl_l10n::tr!("正忙:控制接口由另一个进程服务", "busy: socket is served by a different process") + ); } service::stop(&self.service)?; let end = tokio::time::Instant::now() + Duration::from_secs(45); @@ -284,7 +336,11 @@ impl Services for Host<'_> { { return Ok(()); } - ensure!(tokio::time::Instant::now() < end, "timed out waiting for daemon exit"); + ensure!( + tokio::time::Instant::now() < end, + "{}", + ictl_l10n::tr!("等守护进程退出超时", "timed out waiting for daemon exit") + ); tokio::time::sleep(Duration::from_millis(200)).await; } } @@ -307,16 +363,26 @@ impl Services for Host<'_> { tokio::time::sleep(Duration::from_millis(500)).await; } }; - tokio::time::timeout(Duration::from_secs(60), poll).await.context("daemon health check timed out")?; + tokio::time::timeout(Duration::from_secs(60), poll) + .await + .context(ictl_l10n::tr!("守护进程健康检查超时", "daemon health check timed out"))?; Ok(()) } } async fn restore(store: &Store, host: &impl Services, tx: &Transaction, why: &str) -> Result<()> { let current = digest(&store.binary)?; - ensure!(current == tx.old.sha256 || current == tx.new.sha256, "installed digest unknown; recovery stopped"); + ensure!( + current == tx.old.sha256 || current == tx.new.sha256, + "{}", + ictl_l10n::tr!("不知道已安装程序的摘要,恢复已停止", "installed digest unknown; recovery stopped") + ); let backup = store.dir.join("recovery"); - ensure!(digest(&backup)? == tx.old.sha256, "recovery executable digest mismatch"); + ensure!( + digest(&backup)? == tx.old.sha256, + "{}", + ictl_l10n::tr!("用来恢复的程序摘要对不上", "recovery executable digest mismatch") + ); host.stop().await?; if current != tx.old.sha256 { store.link(&backup, &store.binary)?; @@ -340,7 +406,7 @@ async fn replace( let activity = async { let lease = host.exclusive()?; let running = host.idle(&old).await?; - ensure!(running || !auto, "busy: managed service is stopped"); + ensure!(running || !auto, "{}", ictl_l10n::tr!("正忙:后台服务已停止", "busy: managed service is stopped")); Ok::<_, anyhow::Error>((lease, running)) } .await; @@ -353,10 +419,18 @@ async fn replace( } }; if auto { - ensure!(matches!(super::cached()?.policy, super::Policy::AutoPatch), "automatic installation was disabled"); + ensure!( + matches!(super::cached()?.policy, super::Policy::AutoPatch), + "{}", + ictl_l10n::tr!("自动安装已关闭", "automatic installation was disabled") + ); } validate_receipt(&old, &store.binary)?; - ensure!(digest(candidate)? == new.sha256, "staged executable changed"); + ensure!( + digest(candidate)? == new.sha256, + "{}", + ictl_l10n::tr!("准备安装的程序被改动过", "staged executable changed") + ); eprintln!( "{} → {} ({}; {})", old.version, @@ -385,7 +459,10 @@ async fn replace( .await; if let Err(e) = swap { restore_or_report(store, host, &tx, &format!("{e:#}")).await?; - bail!("update failed; restored {}: {e:#}", tx.old.version); + bail!( + "{}", + ictl_l10n::trf!("升级失败,已恢复到 {}:{e:#}", "update failed; restored {}: {e:#}", tx.old.version) + ); } tx.phase = Phase::Confirmed; write_json(&store.journal(), &tx)?; @@ -408,17 +485,26 @@ async fn restore_or_report(store: &Store, host: &impl Services, tx: &Transaction pub(super) fn eligible(old: &str, new: &str, automatic: bool) -> Result<()> { let old = Version::parse(old)?; let new = Version::parse(new)?; - ensure!(old.pre.is_empty() && new.pre.is_empty() && new.cmp_precedence(&old).is_gt(), "no newer stable release"); + ensure!( + old.pre.is_empty() && new.pre.is_empty() && new.cmp_precedence(&old).is_gt(), + "{}", + ictl_l10n::tr!("没有更新的正式版", "no newer stable release") + ); ensure!( !automatic || (old.major == new.major && old.minor == new.minor && old.patch < new.patch), - "only patch releases can be installed automatically" + "{}", + ictl_l10n::tr!("只有补丁版本能自动安装", "only patch releases can be installed automatically") ); Ok(()) } fn managed(receipt: &Receipt) -> Result<(Store, Service)> { validate_receipt(receipt, &std::env::current_exe()?)?; - ensure!(receipt.version == env!("CARGO_PKG_VERSION"), "running updater version differs from installed version"); + ensure!( + receipt.version == env!("CARGO_PKG_VERSION"), + "{}", + ictl_l10n::tr!("正在运行的更新器和已安装的版本不同", "running updater version differs from installed version") + ); let store = Store::open(&receipt.binary_path, receipt_path())?; let reread = read_receipt()?; ensure!( @@ -426,10 +512,18 @@ fn managed(receipt: &Receipt) -> Result<(Store, Service)> { && reread.sha256 == receipt.sha256 && reread.version == receipt.version && reread.pinned == receipt.pinned, - "installation changed; retry" + "{}", + ictl_l10n::tr!("安装在这期间变了,请重试", "installation changed; retry") ); validate_receipt(receipt, &store.binary)?; - ensure!(!store.journal().try_exists()?, "interrupted update; run iphone-control update recover"); + ensure!( + !store.journal().try_exists()?, + "{}", + ictl_l10n::tr!( + "上次升级中断了,运行 iphone-control update recover", + "interrupted update; run iphone-control update recover" + ) + ); let svc = service::managed(&store.binary, &receipt.service)?; Ok((store, svc)) } @@ -437,10 +531,19 @@ fn managed(receipt: &Receipt) -> Result<(Store, Service)> { pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Result<()> { let receipt = read_receipt()?; let (store, service) = managed(&receipt)?; - ensure!(!receipt.pinned, "this installation is pinned; unpin it locally first"); - ensure!(report.error_code.is_none(), "release check failed: {:?}", report.error_code); + ensure!( + !receipt.pinned, + "{}", + ictl_l10n::tr!("这个安装固定了版本,先在本机解除固定", "this installation is pinned; unpin it locally first") + ); + ensure!( + report.error_code.is_none(), + "{}", + ictl_l10n::trf!("检查新版本失败:{:?}", "release check failed: {:?}", report.error_code) + ); ensure!(matches!(report.availability, super::Availability::Available), "{}", report.guidance); - let version = report.available_version.context("no stable release is available")?; + let version = + report.available_version.context(ictl_l10n::tr!("没有可用的正式版", "no stable release is available"))?; eligible(&receipt.version, &version, background)?; let host = Host { service, socket, binary: &store.binary }; // the control page's service is an always-running client: it would keep the update busy forever, so it stops @@ -448,11 +551,19 @@ pub async fn apply(socket: &Path, background: bool, report: super::Report) -> Re let paused = pause_viewer(socket).await?; let result = async { if background { - ensure!(matches!(report.policy, super::Policy::AutoPatch), "automatic installation is disabled"); + ensure!( + matches!(report.policy, super::Policy::AutoPatch), + "{}", + ictl_l10n::tr!("自动安装已关闭", "automatic installation is disabled") + ); let suppressed = outcome(&store.binary)?.and_then(|o| o.suppressed_version); ensure!( suppressed.as_ref() != Some(&version), - "automatic retry suppressed for {version}; run iphone-control update to retry" + "{}", + ictl_l10n::trf!( + "{version} 不再自动重试;要重试,运行 iphone-control update", + "automatic retry suppressed for {version}; run iphone-control update to retry" + ) ); // An always-open client may stay busy for days. The lease here is deliberately // short-lived; replacement reacquires it and rechecks identity after download. @@ -492,7 +603,7 @@ async fn pause_viewer(socket: &Path) -> Result> { if crate::service::viewer_find().is_some_and(|s| crate::service::running(&s)) && ictl_daemon::protocol::task_list(socket).await.is_ok_and(|l| l.iter().any(|t| t.active())) { - anyhow::bail!("busy: an AI task is running"); + anyhow::bail!("{}", ictl_l10n::tr!("正忙:有 AI 任务在进行", "busy: an AI task is running")); } service::pause_viewer() } @@ -524,7 +635,14 @@ async fn resume(store: &Store, host: &impl Services, tx: &Transaction) -> Result host.mark_pending(&store.journal())?; let current = digest(&store.binary)?; if matches!(tx.phase, Phase::Confirmed) { - ensure!(current == tx.new.sha256, "confirmed executable changed; preserving transaction"); + ensure!( + current == tx.new.sha256, + "{}", + ictl_l10n::tr!( + "已确认的程序被改动过,保留这次升级的记录", + "confirmed executable changed; preserving transaction" + ) + ); store.finish(tx) } else { restore_or_report(store, host, tx, "interrupted installation").await @@ -538,19 +656,27 @@ pub async fn recover(socket: &Path, scheduled: bool) -> Result<()> { if scheduled && outcome(&store.binary)?.is_some_and(|o| o.status == "recovery_failed" && o.target_version == tx.new.version) { - bail!("automatic recovery paused; resolve the recorded error and run update recover"); + bail!( + "{}", + ictl_l10n::tr!( + "自动恢复已暂停:先处理记下的错误,再运行 iphone-control update recover", + "automatic recovery paused; resolve the recorded error and run update recover" + ) + ); } ensure!( same_install(&receipt, &tx.old) && same_install(&receipt, &tx.new) && (receipt.sha256 == tx.old.sha256 || receipt.sha256 == tx.new.sha256), - "journal and receipt do not match" + "{}", + ictl_l10n::tr!("升级记录和安装记录对不上", "journal and receipt do not match") ); let caller = std::env::current_exe()?.canonicalize()?; let backup = store.dir.join("recovery"); ensure!( caller == store.binary || (caller == backup && digest(&backup)? == tx.old.sha256), - "invalid recovery entry point" + "{}", + ictl_l10n::tr!("恢复的入口不对", "invalid recovery entry point") ); let service = service::managed(&store.binary, &receipt.service)?; let paused = pause_viewer(socket).await?; diff --git a/crates/ictl-daemon/src/core.rs b/crates/ictl-daemon/src/core.rs index 68b3fd11..9dd1b5f9 100644 --- a/crates/ictl-daemon/src/core.rs +++ b/crates/ictl-daemon/src/core.rs @@ -236,7 +236,7 @@ impl Persisted { before != (self.detached_wdas.len(), self.detached_wda.is_some()) } - /// 记下这次重签的结果:新字段,加上旧版本认的中文整句 + /// 记下这次重签的结果:新字段,加上旧版本认的中文整句(这句照旧用 UTC,和旧版本写的一样) pub fn record_resign(&mut self, at: u64, error: Option) { let when = crate::eventlog::format_utc(at); self.last_resign = Some(match &error { @@ -249,7 +249,7 @@ impl Persisted { /// 上次重签的结果,按当前语言;只有旧格式时原样给出 pub fn last_resign_text(&self) -> Option { let Some(r) = &self.resign_result else { return self.last_resign.clone() }; - let when = crate::eventlog::format_utc(r.at); + let when = crate::eventlog::format_local(r.at); Some(match &r.error { None => ictl_l10n::trf!("{when} 成功", "{when} succeeded"), Some(e) => ictl_l10n::trf!("{when} 失败:{e}", "{when} failed: {e}"), @@ -1718,11 +1718,17 @@ pub(crate) mod tests { use ictl_l10n::{Lang, with_lang}; let mut p = Persisted::default(); p.record_resign(1_800_000_000, None); - assert_eq!(p.last_resign.as_deref(), Some("2027-01-15 08:00:00 成功")); - assert_eq!(with_lang(Lang::En, || p.last_resign_text()).as_deref(), Some("2027-01-15 08:00:00 succeeded")); - assert_eq!(with_lang(Lang::Zh, || p.last_resign_text()).as_deref(), Some("2027-01-15 08:00:00 成功")); + assert_eq!( + p.last_resign.as_deref(), + Some("2027-01-15 08:00:00 成功"), + "for old versions: UTC, as they wrote it" + ); + // shown in local time with its offset (this machine's zone, whatever it is) + let when = crate::eventlog::format_local(1_800_000_000); + assert_eq!(with_lang(Lang::En, || p.last_resign_text()), Some(format!("{when} succeeded"))); + assert_eq!(with_lang(Lang::Zh, || p.last_resign_text()), Some(format!("{when} 成功"))); p.record_resign(1_800_000_000, Some("boom".into())); - assert_eq!(with_lang(Lang::En, || p.last_resign_text()).as_deref(), Some("2027-01-15 08:00:00 failed: boom")); + assert_eq!(with_lang(Lang::En, || p.last_resign_text()), Some(format!("{when} failed: boom"))); // 旧版本写的:只有中文整句,原样显示 let old: Persisted = serde_json::from_str(r#"{"last_resign":"2026-11-07 01:11:54 成功"}"#).unwrap(); diff --git a/crates/ictl-daemon/src/eventlog.rs b/crates/ictl-daemon/src/eventlog.rs index 7976e1c8..7cfde595 100644 --- a/crates/ictl-daemon/src/eventlog.rs +++ b/crates/ictl-daemon/src/eventlog.rs @@ -63,10 +63,37 @@ impl EventLog { } } -/// UTC 时间 `YYYY-MM-DD HH:MM:SS`(不引入时间库,按公历自己算) +/// 现在的本地时间,带时区偏移(见 [`format_local`]) pub fn timestamp() -> String { let secs = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default().as_secs(); - format_utc(secs) + format_local(secs) +} + +/// 给人看的时间:本地时间加时区偏移,`2026-11-24 16:08:52 +08:00`。以前只写 UTC 又不标明,东八区的用户看到的 +/// 日志时间差 8 小时。偏移按那一刻算(夏令时前后不同);取不到本地时区时就是 UTC(`+00:00`) +pub fn format_local(secs: u64) -> String { + format_at(secs, local_offset(secs)) +} + +/// `secs` 那一刻本地时间比 UTC 快多少秒(东边为正) +fn local_offset(secs: u64) -> i64 { + let Ok(t) = libc::time_t::try_from(secs) else { return 0 }; + // SAFETY: localtime_r only writes the tm it is given; a zeroed tm is a valid value to start from + let mut tm: libc::tm = unsafe { std::mem::zeroed() }; + if unsafe { libc::localtime_r(&t, &mut tm) }.is_null() { + return 0; + } + // c_long: i64 on the 64-bit hosts we ship for, narrower elsewhere + #[allow(clippy::unnecessary_cast)] + let offset = tm.tm_gmtoff as i64; + offset +} + +/// `secs`(UTC)按偏移 `offset` 秒写成本地时间并标出偏移 +fn format_at(secs: u64, offset: i64) -> String { + let local = u64::try_from(i64::try_from(secs).unwrap_or(i64::MAX).saturating_add(offset)).unwrap_or(0); + let (sign, abs) = if offset < 0 { ('-', -offset) } else { ('+', offset) }; + format!("{} {sign}{:02}:{:02}", format_utc(local), abs / 3600, abs % 3600 / 60) } pub fn format_utc(secs: u64) -> String { @@ -88,6 +115,29 @@ pub fn format_utc(secs: u64) -> String { mod tests { use super::*; + #[test] + fn local_time_carries_its_offset() { + assert_eq!(format_at(1_793_448_000, 8 * 3600), "2026-10-31 20:00:00 +08:00"); + assert_eq!(format_at(1_793_448_000, 0), "2026-10-31 12:00:00 +00:00"); + assert_eq!(format_at(1_793_448_000, -(5 * 3600 + 1800)), "2026-10-31 06:30:00 -05:30"); + // just after midnight UTC, west of Greenwich: the day before + assert_eq!(format_at(1_793_404_860, -7 * 3600), "2026-10-30 17:01:00 -07:00"); + // whatever this machine's zone is, the shape is the same + assert!(regex_like(&format_local(1_793_448_000)), "{}", format_local(1_793_448_000)); + } + + /// `YYYY-MM-DD HH:MM:SS ±HH:MM` + fn regex_like(s: &str) -> bool { + let b = s.as_bytes(); + b.len() == 26 + && [4, 7].iter().all(|&i| b[i] == b'-') + && b[10] == b' ' + && [13, 16, 23].iter().all(|&i| b[i] == b':') + && b[19] == b' ' + && matches!(b[20], b'+' | b'-') + && s.chars().filter(char::is_ascii_digit).count() == 18 + } + #[test] fn utc_formatting() { assert_eq!(format_utc(0), "1970-01-01 00:00:00"); diff --git a/crates/ictl-daemon/src/supervise.rs b/crates/ictl-daemon/src/supervise.rs index 23c6051d..1dc9a5b7 100644 --- a/crates/ictl-daemon/src/supervise.rs +++ b/crates/ictl-daemon/src/supervise.rs @@ -1027,15 +1027,15 @@ impl Daemon { g.backoff.reset(); } g.dedup.clear("resign"); - let expires = crate::eventlog::format_utc(exp); + let expires = crate::eventlog::format_local(exp); // 事件日志按守护进程的语言,返回给调用方的按请求的语言 self.log.log(&ictl_l10n::log_trf!( - "重签完成,新描述文件到期 {expires} UTC", - "Re-signing done, the new provisioning profile expires {expires} UTC" + "重签完成,新描述文件到期 {expires}", + "Re-signing done, the new provisioning profile expires {expires}" )); Ok(ictl_l10n::trf!( - "重签完成,新描述文件到期 {expires} UTC", - "Re-signing done, the new provisioning profile expires {expires} UTC" + "重签完成,新描述文件到期 {expires}", + "Re-signing done, the new provisioning profile expires {expires}" )) } Err(e) => { diff --git a/docs/dev/regression-cases.md b/docs/dev/regression-cases.md index 56cc233b..38823a27 100644 --- a/docs/dev/regression-cases.md +++ b/docs/dev/regression-cases.md @@ -172,3 +172,5 @@ | 166 | WDA 输入后核对:替换选中的文字(搜索框保留上次的搜索并选中)时读两遍、每遍 4 个请求再等 0.3 秒,往 Spotlight 输入比 main 慢约 1.8 秒(iPad mini 5,`run.py` 第 12 步) | 复读只问聚焦的元素和它的值(2 个请求);读一次就能下结论的(替换了选中的文字)不再读第二遍 | 单测 `typing_over_a_selection_is_judged_after_one_reread` + 真机(iPad 上 `run.py --repeat 5` 和 main 对比) | | 167 | `iphone_scroll_collect` 重复收行:设置的大标题滑动时收起到导航栏,下一屏开头对不上上一屏结尾,几行被收两遍;iPad 分栏界面(WDA)只有一栏在滚,两栏的行交错;同一行的 Cell、文字和 chevron 中心差 1 点,滑动后先后顺序会变;左栏的导航栏和搜索框不动,行从它们底下滑过、夹在行中间。两屏完全对不上,整屏都算新行,滑两三次就到 150 行上限,左栏也滚不到 | 同一行的元素归成一行、行内从左到右;树里有滚动区域时只拿滚动区域里的内容比对,栏等其他元素上一屏没有同样的才算新行;没在滚的那一栏不参与比对,重叠的两头各可隔开几个元素(挪了位置的标题不算新行);`x` 指定在哪一栏滑 | 单测 `a_title_collapsing_into_the_navigation_bar_does_not_repeat_the_overlap`、`a_column_that_did_not_scroll_is_not_collected_again`、`rows_are_matched_in_the_scroll_area_one_row_at_a_time` + 真机(iPhone 设置整页收集无重复;iPad 设置默认在正中滑、`x` 在左栏滑都不重复,`x` 在左栏找到「隐私与安全」) | | 168 | 后台启动 WDA 不带环境变量,WDA 不设 `USE_IP` 时在手机的所有网卡上监听:手机连着 Wi-Fi 时,局域网里谁都能经 8100(没有认证)操作手机、经 9100 看画面 | 后台启动和 XCTest 启动都带 `USE_IP=127.0.0.1`;`state.json` 的 `loopback_wdas` 记下这样启动的进程,旧版本启动的(不在里面)不再接上而是重新启动 | 单测 `the_launch_environment_is_a_dictionary_of_strings`、`only_a_loopback_only_background_wda_is_attached_to_again` + 真机(USB 上 WDA 就绪、工具和控制台 MJPEG 画面照常;手机连 Wi-Fi 时从局域网另一台机器 `curl http://<手机IP>:8100/status`、`:9100` 连不上;升级前已在运行的后台 WDA 被重新启动) | +| 169 | 事件日志、「上次重签」、重签完成的到期时间按 UTC 显示又不标明,东八区的用户看到的时间差 8 小时 | 显示本地时间并带时区偏移(`2026-11-24 16:08:52 +08:00`);写给旧版本读的 `last_resign` 整句照旧是 UTC | 单测 `local_time_carries_its_offset`、`resign_result_is_shown_in_the_reader_language`(在 UTC、东八区、`America/St_Johns` 下都要过) | +| 170 | 更新器、后台服务、自动更新任务的报错写死英文(约 120 条),中文界面下 `iphone-control update` 和控制台更新面板显示英文 | 全部中英成对(`tr!`/`trf!`),按运行时的语言输出;`outcome.json` 的 `status` 字段不变,控制台仍按它显示状态 | 手动:`IPHONE_CONTROL_LANG=zh` 和 `en` 下各运行一次 `iphone-control update apply`(没有脚本安装记录时),报错分别是中文、英文 |