fix(core): replace the packaged core through one elevated run on Linux (#8688)

* fix(core): replace the packaged core through one elevated run on Linux

Distribution packages install the core beside the app in a root-owned
directory such as /usr/bin, so an in-app upgrade died creating its staging
file there:

    failed to create /usr/bin/.verge-mihomo.513755.1.tmp: Permission denied (os error 13)

The upgrade now re-executes the app's own binary through pkexec with
--replace-core. That run verifies the caller's digest, stages the bytes as
.verge-mihomo.next beside the target and renames them over it, so a core
that is still executing keeps its inode and an interrupted copy leaves the
live path untouched. It then hands the same file to the service installer,
which is already root and does not ask again: one prompt covers the
packaged core and, when one is installed, the Service's approved copy.

The privileged mode trusts nothing from its caller: the target must be one
of the two core names and must live in the directory the binary was started
from, and the source must match the attested sha256.

A sidecar session with a Service installed now refreshes the approved copy
too, so switching back cannot run the core this upgrade replaced. The
previous bytes are kept in user data and restored by the same elevated run,
and a refused Service copy is reported apart from an unpublished core, so
only the former is rolled back.

Fixes #8037
Fixes #8390

* docs(changelog): note Linux core upgrade fix

Assisted-by: Copilot Fusion (Standard) > GPT-6 Luna
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>

---------

Signed-off-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: venti1112 <3788365896@qq.com>
Co-authored-by: ❤是纱雾酱哟~ <49941141+Dragon1573@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
Ptilopsis
2026-11-25 16:09:40 +00:00
committed by GitHub
co-authored by Copilot venti1112 ❤是纱雾酱哟~
parent 8fe3cc1fe3
commit 1dba31c6af
5 changed files with 514 additions and 39 deletions
+1
View File
@@ -59,6 +59,7 @@
**🐧 Linux**
- 修复 Linux OpenRC 环境下服务安装失败
- 修复 Linux 安装版 Mihomo 内核升级因权限不足而失败
</details>
+230 -39
View File
@@ -5,11 +5,20 @@
//! (clash-verge-rev#6834). Verge downloads the release itself instead, stages a verified
//! copy beside the managed core and renames it into place: `rename` never touches the inode
//! the running core is executing from, so no page validation can fail.
//!
//! Package installs break that assumption: distribution packages put the core beside the app in
//! a root-owned directory such as `/usr/bin`, which the desktop user cannot write. Those stage in
//! user data and publish through the elevated helper, which keeps the same copy-then-rename shape.
#[cfg(not(windows))]
use crate::core::service::{SERVICE_MANAGER, ServiceStatus};
use crate::{
config::Config,
core::{CoreManager, manager::RunningMode},
utils::network::{NetworkManager, ProxyType},
utils::{
dirs,
network::{NetworkManager, ProxyType},
},
};
use anyhow::{Context as _, Result, anyhow, bail};
use clash_verge_logging::{Type, logging};
@@ -29,6 +38,8 @@ const VERSION_TIMEOUT_SECS: u64 = 20;
const PACKAGE_TIMEOUT_SECS: u64 = 300;
/// Well above any real core package, low enough that a wrong response cannot exhaust memory.
const MAX_PACKAGE_BYTES: usize = 64 * 1024 * 1024;
/// User data root for the staging and rollback copies of a core the app cannot write in place.
const CORE_STAGING_DIR: &str = "core-upgrade";
static STAGING_GENERATION: AtomicU64 = AtomicU64::new(0);
/// `.rollback` and `.old` are fixed paths, so two upgrades must not overlap.
@@ -65,34 +76,31 @@ pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
let package = download_package(proxy, alpha, &latest).await?;
let staged = stage_core(&target, &package, &latest)?;
let elevated = staged.elevated;
// A hard link keeps the previous core reachable without touching the inode the running
// core executes from, so publishing below stays one atomic rename.
let rollback = target.with_file_name(format!(".{core}.rollback"));
// core executes from, so publishing below stays one atomic rename. A root-owned target
// cannot take a link beside it, so those installs keep the copy in user data instead.
let rollback = rollback_path(&target, elevated)?;
let _ = std::fs::remove_file(&rollback);
// Nothing to roll back to when the core we are replacing could not report a version.
let restorable = !installed.is_empty() && std::fs::hard_link(&target, &rollback).is_ok();
let restorable = !installed.is_empty() && stage_rollback(&target, &rollback, elevated);
// Decided before anything can crash: after a failed restart the mode reads NotRunning, which
// says nothing about whether this upgrade went through the Service.
let service_mode = matches!(*CoreManager::global().get_running_mode(), RunningMode::Service);
// A sidecar session still owes the Service its copy when one is installed, or a later switch
// would keep running the core this upgrade replaced while the app reports the new version.
// Windows keeps its previous behaviour: staging there would add a UAC prompt to an upgrade
// that never asked for one.
#[cfg(windows)]
let service_present = service_mode;
#[cfg(not(windows))]
let service_present = service_mode || service_installed().await;
let mut result = staged.publish(&target);
// The Service executes its own administrator-approved copy, never this file; hand the new
// bytes over before the restart below asks for them, or a service-mode restart would keep
// running the previous core while the app reports the new version. Sidecar mode runs the
// file directly and gets no elevation prompt.
let service_staging = if result.is_ok() && service_mode {
result =
crate::core::service::stage_approved_core(&target).context("core replaced but not accepted by the service");
if result.is_ok() {
ServiceStaging::Succeeded
} else {
ServiceStaging::Refused
}
} else {
ServiceStaging::NotAttempted
};
// bytes over before the restart below asks for them.
let (mut result, service_staging) = publish_core(&staged, &target, service_present);
if result.is_ok() {
result = CoreManager::global()
.restart_core()
@@ -106,18 +114,19 @@ pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
// new core also restores: leaving the new file would make a retry read the new version
// and report nothing to do while the service keeps running the old core.
let core_is_down = matches!(*CoreManager::global().get_running_mode(), RunningMode::NotRunning);
let restore_service = matches!(service_staging, ServiceStaging::Succeeded);
if restorable
&& (matches!(service_staging, ServiceStaging::Refused) || core_is_down || !target.exists())
&& std::fs::rename(&rollback, &target).is_ok()
&& restore_core(&rollback, &target, elevated, restore_service)
{
logging!(warn, Type::Core, "core upgrade: rolled back to {installed:?}");
// Only a staging that SUCCEEDED left the failing bytes in the approved copy, and only
// then must the restore reach it too — otherwise the restart below would spawn the
// very core that just failed. Refused or never-attempted staging left the approved
// copy untouched, and re-staging would raise an elevation prompt for a no-op. This is
// deliberately not gated on the current running mode, which reads NotRunning after
// the very crash being rolled back.
if matches!(service_staging, ServiceStaging::Succeeded)
// The elevated restore already wrote the Service copy in the same run; a local one
// only touched the file beside the app, and re-staging would raise an elevation
// prompt for a no-op when nothing was published. This is deliberately not gated on
// the current running mode, which reads NotRunning after the very crash being
// rolled back.
if !elevated
&& restore_service
&& let Err(stage_error) = crate::core::service::stage_approved_core(&target)
{
logging!(
@@ -149,11 +158,10 @@ pub async fn upgrade_core(force: bool) -> Result<CoreUpgradeReport> {
/// Whether this upgrade handed bytes to the Service's approved core directory.
///
/// Three states matter, not two: a staging that never ran (publish failed, or sidecar mode) left
/// the approved copy alone just like a refused one, but only a SUCCEEDED staging obliges the
/// rollback path to restore that copy as well. A user who upgrades in sidecar mode and later
/// switches to service mode runs the previously approved core until the next elevated
/// (re)install or upgrade; the Service logs that drift on every spawn.
/// Three states matter, not two: a staging that never ran (publish failed, or no Service is
/// installed) left the approved copy alone just like a refused one, but only a SUCCEEDED staging
/// obliges the rollback path to restore that copy as well. A sidecar session with an installed
/// Service stages too, so switching back cannot run the core this upgrade replaced.
#[derive(Clone, Copy)]
enum ServiceStaging {
NotAttempted,
@@ -161,6 +169,19 @@ enum ServiceStaging {
Refused,
}
/// True when a Service is registered, whatever its current health: its approved copy outlives
/// this session, so an upgrade in sidecar mode still has to refresh it.
#[cfg(not(windows))]
async fn service_installed() -> bool {
!matches!(
SERVICE_MANAGER.current().await,
ServiceStatus::Checking
| ServiceStatus::NotInstalled
| ServiceStatus::InstallRequired
| ServiceStatus::SidecarAllowed
)
}
/// The sidecar next to the app executable. On macOS development builds the Service runs a
/// staged copy of this file, so writing here is what makes an upgrade survive the next start.
fn managed_core_path(core: &str) -> Result<PathBuf> {
@@ -291,6 +312,8 @@ async fn download_package(proxy: ProxyType, alpha: bool, version: &str) -> Resul
/// A staged core that is removed unless publishing renamed it away.
struct StagedCore {
path: PathBuf,
/// The target directory is root-owned, so publishing has to go through the elevated helper.
elevated: bool,
}
impl Drop for StagedCore {
@@ -311,15 +334,14 @@ impl Drop for StagedCore {
/// Unpacks, permits, signs and runs the new core before it is allowed anywhere near the
/// live path, so a bad download can never replace a working core.
fn stage_core(target: &Path, package: &[u8], version: &str) -> Result<StagedCore> {
let directory = target
.parent()
.with_context(|| format!("the managed core has no parent directory: {}", target.display()))?;
let elevated = publish_requires_elevation(target);
let directory = staging_directory(target, elevated)?;
let core_name = target
.file_name()
.with_context(|| format!("the managed core has no file name: {}", target.display()))?;
let (path, mut file) = create_staging_file(directory, core_name)?;
let staged = StagedCore { path };
let (path, mut file) = create_staging_file(&directory, core_name)?;
let staged = StagedCore { path, elevated };
unpack(package, &mut file).with_context(|| format!("failed to unpack the core package for {version}"))?;
@@ -393,13 +415,14 @@ fn unpack(package: &[u8], out: &mut File) -> Result<()> {
impl StagedCore {
#[cfg(not(windows))]
fn publish(self, target: &Path) -> Result<()> {
fn publish(&self, target: &Path) -> Result<()> {
std::fs::rename(&self.path, target)
.with_context(|| format!("failed to publish the core to {}", target.display()))
}
#[cfg(windows)]
fn publish(self, target: &Path) -> Result<()> {
fn publish(&self, target: &Path) -> Result<()> {
debug_assert!(!self.elevated);
if std::fs::rename(&self.path, target).is_ok() {
return Ok(());
}
@@ -429,6 +452,174 @@ impl StagedCore {
}
}
/// Publishing next to the target needs write access to its directory. Distribution packages
/// install the core in a root-owned directory such as `/usr/bin`, so those publish through the
/// elevated helper.
#[cfg(target_os = "linux")]
fn publish_requires_elevation(target: &Path) -> bool {
target
.parent()
.is_some_and(|directory| !directory_is_writable(directory))
}
/// Only Linux installs the core into a directory the desktop user cannot write.
#[cfg(not(target_os = "linux"))]
const fn publish_requires_elevation(_target: &Path) -> bool {
false
}
#[cfg(target_os = "linux")]
fn directory_is_writable(path: &Path) -> bool {
use std::os::unix::ffi::OsStrExt as _;
let Ok(path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
return false;
};
// SAFETY: a valid NUL-terminated path is readable for the duration of the call.
unsafe { libc::access(path.as_ptr(), libc::W_OK) == 0 }
}
fn staging_directory(target: &Path, elevated: bool) -> Result<PathBuf> {
if !elevated {
return target
.parent()
.map(Path::to_path_buf)
.with_context(|| format!("the managed core has no parent directory: {}", target.display()));
}
let directory = dirs::app_home_dir()?.join(CORE_STAGING_DIR);
std::fs::create_dir_all(&directory)
.with_context(|| format!("failed to create the core staging directory {}", directory.display()))?;
Ok(directory)
}
fn rollback_path(target: &Path, elevated: bool) -> Result<PathBuf> {
let name = target
.file_name()
.with_context(|| format!("the managed core has no file name: {}", target.display()))?;
let name = format!(".{}.rollback", name.to_string_lossy());
if elevated {
Ok(dirs::app_home_dir()?.join(CORE_STAGING_DIR).join(name))
} else {
Ok(target.with_file_name(name))
}
}
/// Keeps the previous bytes reachable for the rollback. A hard link cannot be created beside a
/// root-owned target, so those copies are read into user data instead.
fn stage_rollback(target: &Path, rollback: &Path, elevated: bool) -> bool {
if elevated {
std::fs::copy(target, rollback).is_ok()
} else {
std::fs::hard_link(target, rollback).is_ok()
}
}
/// Publishes the verified core, then the Service's approved copy when one is installed.
///
/// A refused Service copy leaves the new core on disk, so it is reported apart from a replacement
/// that never happened: only the former restores the Service copy during rollback.
fn publish_core(staged: &StagedCore, target: &Path, service_present: bool) -> (Result<()>, ServiceStaging) {
if staged.elevated {
return match publish_elevated(&staged.path, target, service_present) {
Ok(ElevatedOutcome::Published) => (
Ok(()),
if service_present {
ServiceStaging::Succeeded
} else {
ServiceStaging::NotAttempted
},
),
Ok(ElevatedOutcome::ServiceFailed(error)) => (
Err(error.context("core replaced but not accepted by the service")),
ServiceStaging::Refused,
),
Err(error) => (Err(error), ServiceStaging::NotAttempted),
};
}
if let Err(error) = staged.publish(target) {
return (Err(error), ServiceStaging::NotAttempted);
}
if !service_present {
return (Ok(()), ServiceStaging::NotAttempted);
}
match crate::core::service::stage_approved_core(target) {
Ok(()) => (Ok(()), ServiceStaging::Succeeded),
Err(error) => (
Err(error.context("core replaced but not accepted by the service")),
ServiceStaging::Refused,
),
}
}
/// How far an elevated replacement got, without tying the upgrade to the platform's module.
///
/// Only Linux reaches this path: elsewhere the core never lands in a directory the user cannot
/// write, so neither variant is ever constructed.
#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
enum ElevatedOutcome {
Published,
ServiceFailed(anyhow::Error),
}
#[cfg(target_os = "linux")]
fn publish_elevated(staged: &Path, target: &Path, publish_service: bool) -> Result<ElevatedOutcome> {
logging!(
info,
Type::Core,
"core upgrade: requesting elevation to replace {}",
target.display()
);
Ok(
match crate::utils::elevated::replace_root_owned_file(staged, target, publish_service)? {
crate::utils::elevated::Outcome::Published => ElevatedOutcome::Published,
crate::utils::elevated::Outcome::ServiceFailed(error) => ElevatedOutcome::ServiceFailed(error),
},
)
}
#[cfg(not(target_os = "linux"))]
fn publish_elevated(staged: &Path, target: &Path, _publish_service: bool) -> Result<ElevatedOutcome> {
bail!(
"replacing the root-owned core {} is not supported on this platform (staged at {})",
target.display(),
staged.display()
)
}
fn restore_core(rollback: &Path, target: &Path, elevated: bool, publish_service: bool) -> bool {
if !elevated {
return std::fs::rename(rollback, target).is_ok();
}
match publish_elevated(rollback, target, publish_service) {
Ok(ElevatedOutcome::Published) => true,
// The previous core is back in place; only the Service copy is stale, and the next
// successful publish repairs it.
Ok(ElevatedOutcome::ServiceFailed(error)) => {
logging!(
warn,
Type::Core,
"core upgrade: restored {} but not the service copy: {error:#}",
target.display()
);
true
}
Err(error) => {
logging!(
warn,
Type::Core,
"core upgrade: failed to restore {}: {error:#}",
target.display()
);
false
}
}
}
/// Keeps the `-v` probe and codesign from flashing a console window.
#[cfg(windows)]
fn new_command(program: impl AsRef<OsStr>) -> Command {
+6
View File
@@ -15,6 +15,12 @@ fn main() -> ExitCode {
#[cfg(not(all(feature = "perf-harness", target_os = "macos")))]
fn main() -> ExitCode {
// The privileged replacement must run before the runtime, the singleton check or any window.
#[cfg(target_os = "linux")]
if let Some(code) = app_lib::utils::elevated::run_if_requested() {
return code;
}
let default_parallelism = std::thread::available_parallelism().map_or(1, |n| n.get());
let worker_limit = std::cmp::min(default_parallelism, 4);
let blocking_limit = 2 * worker_limit;
+275
View File
@@ -0,0 +1,275 @@
//! Replacing a root-owned core through one elevated run.
//!
//! Distribution packages install the core beside the app in a root-owned directory such as
//! `/usr/bin`, which the desktop user cannot write. The app re-executes its own binary through
//! pkexec with `--replace-core`: that run stages the attested bytes beside the target, renames
//! them over it, and hands the same file to the Service installer.
//!
//! The privileged mode trusts nothing from its caller: the target must be one of the two core
//! names in the directory the binary was started from, and the source must match the digest the
//! caller attested. `rename` never touches the inode a running core executes from, and a copy
//! interrupted before it leaves the live path exactly as it was.
use anyhow::{Context as _, Result, bail};
use std::{
ffi::{OsStr, OsString},
fs::{File, OpenOptions},
path::{Path, PathBuf},
process::{Command, ExitCode, Output},
};
const MODE_FLAG: &str = "--replace-core";
const SOURCE_FLAG: &str = "--source";
const TARGET_FLAG: &str = "--target";
const SHA256_FLAG: &str = "--sha256";
const SERVICE_FLAG: &str = "--publish-service";
/// Printed once the live path holds the new bytes, so the caller can tell a refused Service copy
/// from a replacement that never happened.
const REPLACED_MARKER: &str = "CLASH_VERGE_CORE_REPLACED_V1=1";
const CORE_NAMES: [&str; 2] = ["verge-mihomo", "verge-mihomo-alpha"];
/// How far an elevated replacement got.
pub enum Outcome {
/// The core was replaced; the Service copy was updated or not requested.
Published,
/// The core was replaced, but the Service refused the same bytes.
ServiceFailed(anyhow::Error),
}
/// Replaces `target` with `staged`, asking for elevation once.
pub fn replace_root_owned_file(staged: &Path, target: &Path, publish_service: bool) -> Result<Outcome> {
let executable = std::env::current_exe().context("failed to locate the current executable")?;
let digest = clash_verge_service_ipc::management::sha256_file(staged)
.with_context(|| format!("failed to hash {}", staged.display()))?;
let mut arguments: Vec<OsString> = vec![
MODE_FLAG.into(),
SOURCE_FLAG.into(),
staged.as_os_str().to_owned(),
TARGET_FLAG.into(),
target.as_os_str().to_owned(),
SHA256_FLAG.into(),
digest.into(),
];
if publish_service {
arguments.push(SERVICE_FLAG.into());
}
let output = run_elevated(&executable, &arguments)?;
if output.status.success() {
return Ok(Outcome::Published);
}
let error = failure(&executable, &output);
let replaced = String::from_utf8_lossy(&output.stdout)
.lines()
.any(|line| line == REPLACED_MARKER);
if replaced && publish_service {
return Ok(Outcome::ServiceFailed(error));
}
Err(error)
}
/// Handles the privileged mode before Tauri, the singleton check or any window exists.
pub fn run_if_requested() -> Option<ExitCode> {
let mut arguments = std::env::args_os().skip(1);
if arguments.next().as_deref() != Some(OsStr::new(MODE_FLAG)) {
return None;
}
Some(match replace(arguments) {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("{error:#}");
ExitCode::FAILURE
}
})
}
fn replace(arguments: impl Iterator<Item = OsString>) -> Result<()> {
let request = Request::parse(arguments)?;
if !running_as_root() {
bail!("{MODE_FLAG} must run as root");
}
let directory = request.target.parent().context("the target has no parent directory")?;
let name = request.target.file_name().context("the target has no file name")?;
if !CORE_NAMES.iter().any(|core| OsStr::new(core) == name) {
bail!("refusing to replace {name:?}: not a core name");
}
let executable = std::env::current_exe().context("failed to locate the running executable")?;
let own_directory = executable
.parent()
.context("the running executable has no parent directory")?;
if std::fs::canonicalize(directory)? != std::fs::canonicalize(own_directory)? {
bail!("refusing to replace a core outside {}", own_directory.display());
}
if clash_verge_service_ipc::management::sha256_file(&request.source)? != request.sha256 {
bail!("{} does not match the attested sha256", request.source.display());
}
publish(&request.source, &request.target, &request.sha256)?;
println!("{REPLACED_MARKER}");
if request.publish_service {
publish_service_core(own_directory, &request.target)?;
}
Ok(())
}
/// The staged bytes land under the installer's `.next` name and only the rename touches the live
/// path, so a core that is still executing keeps its inode and a failure leaves the target alone.
fn publish(source: &Path, target: &Path, digest: &str) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
let next = target.with_extension(clash_verge_service_ipc::CORE_STAGING_EXTENSION);
remove_stale_staging(&next)?;
let mut input = File::open(source).with_context(|| format!("failed to open {}", source.display()))?;
let mut output = OpenOptions::new()
.write(true)
.create_new(true)
.open(&next)
.with_context(|| format!("failed to create {}", next.display()))?;
std::io::copy(&mut input, &mut output).with_context(|| format!("failed to stage {}", next.display()))?;
output
.set_permissions(std::fs::Permissions::from_mode(0o755))
.with_context(|| format!("failed to permit {}", next.display()))?;
output
.sync_all()
.with_context(|| format!("failed to flush {}", next.display()))?;
drop(output);
if clash_verge_service_ipc::management::sha256_file(&next)? != digest {
let _ = std::fs::remove_file(&next);
bail!("{} changed while it was copied", source.display());
}
std::fs::rename(&next, target).with_context(|| format!("failed to replace {}", target.display()))?;
// The rename is only durable once its directory entry is flushed.
if let Ok(directory) = File::open(target.parent().context("the target has no parent directory")?) {
let _ = directory.sync_all();
}
Ok(())
}
fn remove_stale_staging(path: &Path) -> Result<()> {
match std::fs::symlink_metadata(path) {
Ok(_) => std::fs::remove_file(path).with_context(|| format!("failed to remove stale {}", path.display())),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),
Err(error) => Err(error).with_context(|| format!("failed to inspect {}", path.display())),
}
}
fn publish_service_core(directory: &Path, target: &Path) -> Result<()> {
let name = target
.file_name()
.context("the target has no file name")?
.to_string_lossy()
.into_owned();
let installer = directory.join(format!("clash-verge-service-install{}", std::env::consts::EXE_SUFFIX));
// SAFETY: getgid has no preconditions and cannot fail.
let gid = unsafe { libc::getgid() };
// Already root, so the installer publishes without asking for elevation a second time.
clash_verge_service_ipc::management::install(
&installer,
&[clash_verge_service_ipc::management::CoreSource {
name,
path: target.to_path_buf(),
}],
true,
Some(gid),
"Install the Clash Verge core",
)
}
fn run_elevated(program: &Path, arguments: &[OsString]) -> Result<Output> {
if running_as_root() {
return Command::new(program)
.args(arguments)
.output()
.context("failed to run the replacement");
}
let elevator = crate::utils::help::linux_elevator();
let mut command = Command::new(&elevator);
if elevator.contains("pkexec") {
command.arg("--disable-internal-agent");
}
let output = command.arg(program).args(arguments).output()?;
if output.status.success() {
return Ok(output);
}
// pkexec has no agent to ask (exit 127) on minimal desktops; sudo covers that case. A failure
// here still reports the pkexec attempt, which is the one the user acted on.
if elevator.contains("pkexec")
&& let Ok(sudo) = Command::new("sudo").arg(program).args(arguments).output()
&& sudo.status.success()
{
return Ok(sudo);
}
Ok(output)
}
fn running_as_root() -> bool {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() == 0 }
}
fn failure(program: &Path, output: &Output) -> anyhow::Error {
let stderr = String::from_utf8_lossy(&output.stderr);
let stderr = stderr.trim();
if stderr.is_empty() {
anyhow::anyhow!("{} failed with {}", program.display(), output.status)
} else {
anyhow::anyhow!("{} failed with {}: {stderr}", program.display(), output.status)
}
}
struct Request {
source: PathBuf,
target: PathBuf,
sha256: String,
publish_service: bool,
}
impl Request {
fn parse(mut arguments: impl Iterator<Item = OsString>) -> Result<Self> {
let mut source = None;
let mut target = None;
let mut sha256 = None;
let mut publish_service = false;
while let Some(argument) = arguments.next() {
match argument.to_str() {
Some(SOURCE_FLAG) => source = Some(PathBuf::from(value(&mut arguments, SOURCE_FLAG)?)),
Some(TARGET_FLAG) => target = Some(PathBuf::from(value(&mut arguments, TARGET_FLAG)?)),
Some(SHA256_FLAG) => {
sha256 = Some(
value(&mut arguments, SHA256_FLAG)?
.into_string()
.map_err(|_| anyhow::anyhow!("{SHA256_FLAG} is not valid UTF-8"))?,
);
}
Some(SERVICE_FLAG) => publish_service = true,
_ => bail!("unknown argument: {argument:?}"),
}
}
Ok(Self {
source: source.context(format!("{SOURCE_FLAG} is required"))?,
target: target.context(format!("{TARGET_FLAG} is required"))?,
sha256: sha256.context(format!("{SHA256_FLAG} is required"))?,
publish_service,
})
}
}
fn value(arguments: &mut impl Iterator<Item = OsString>, flag: &str) -> Result<OsString> {
arguments.next().with_context(|| format!("{flag} requires a value"))
}
+2
View File
@@ -1,6 +1,8 @@
#[cfg(target_os = "macos")]
pub mod connections_stream;
pub mod dirs;
#[cfg(target_os = "linux")]
pub mod elevated;
pub mod help;
pub mod init;
#[cfg(target_os = "linux")]