From bff6152427f424ae2cc442119dcc5f18eea6ba4c Mon Sep 17 00:00:00 2001 From: Afnan Mojumder Date: Sat, 14 Nov 2026 13:31:44 +0600 Subject: [PATCH 1/3] mv: report specific errors instead of generic permission denied on cross-device fallback Previously, rename_file_fallback unconditionally mapped errors during cross-device fallback moves to translate!("mv-error-permission-denied"), causing misleading errors such as "Permission denied" when the disk is full (ENOSPC), or missing contextual path information (e.g. "cannot open ... for reading", "cannot create regular file ...", "cannot remove ..."). Additionally, when moving directories across devices, rename_dir_fallback previously attempted to open the destination directory for applying xattrs before checking if copy_dir_contents succeeded, and directory/entry errors were reported against the top-level move rather than the failing path. - Introduce RenameError to distinguish raw I/O errors from pre-formatted diagnostics, and preserve synthetic non-OS I/O messages as-is. - Report accurate GNU Coreutils-compatible messages for cross-device fallback failures (unreadable source, unwritable dest dir, ENOSPC, unremovable source or target, cannot create directory, cannot access subdirectory). - Unify regular file copying in copy_regular_file so fallback paths use fd-pinned safe copying while preserving xattrs and setuid/setgid rules. - Handle declined interactive prompts cleanly without printing empty errors. - Add regression tests covering cross-device file and directory permission failures. Fixes #15939 Closes #9458 --- src/uu/mv/locales/en-US.ftl | 6 + src/uu/mv/locales/fr-FR.ftl | 6 + src/uu/mv/src/error.rs | 86 +++++- src/uu/mv/src/mv.rs | 510 +++++++++++++++++++++--------------- tests/by-util/test_mv.rs | 208 +++++++++++++++ 5 files changed, 611 insertions(+), 205 deletions(-) diff --git a/src/uu/mv/locales/en-US.ftl b/src/uu/mv/locales/en-US.ftl index e03965d436f..bda3daf4957 100644 --- a/src/uu/mv/locales/en-US.ftl +++ b/src/uu/mv/locales/en-US.ftl @@ -38,6 +38,12 @@ mv-error-dangling-symlink = can't determine symlink type, since it is dangling mv-error-no-symlink-support = your operating system does not support symlinks mv-error-permission-denied = Permission denied mv-error-inter-device-move-failed = inter-device move failed: {$from} to {$to}; unable to remove target: {$err} +mv-error-cannot-open-for-reading = cannot open {$from} for reading: {$err} +mv-error-cannot-create-regular-file = cannot create regular file {$to}: {$err} +mv-error-cannot-create-directory = cannot create directory {$path}: {$err} +mv-error-cannot-access = cannot access {$path}: {$err} +mv-error-error-writing = error writing {$to}: {$err} +mv-error-cannot-remove = cannot remove {$from}: {$err} mv-error-setting-attribute = setting attribute {$name}: {$err} mv-error-setting-attributes = setting attributes for {$path}: {$err} mv-error-exchange-two-operands = --exchange requires exactly two operands diff --git a/src/uu/mv/locales/fr-FR.ftl b/src/uu/mv/locales/fr-FR.ftl index 84d89ea3703..30709414437 100644 --- a/src/uu/mv/locales/fr-FR.ftl +++ b/src/uu/mv/locales/fr-FR.ftl @@ -38,6 +38,12 @@ mv-error-dangling-symlink = impossible de déterminer le type de lien symbolique mv-error-no-symlink-support = votre système d'exploitation ne prend pas en charge les liens symboliques mv-error-permission-denied = Permission refusée mv-error-inter-device-move-failed = échec du déplacement inter-périphérique : {$from} vers {$to} ; impossible de supprimer la cible : {$err} +mv-error-cannot-open-for-reading = impossible d'ouvrir {$from} en lecture : {$err} +mv-error-cannot-create-regular-file = impossible de créer le fichier standard {$to} : {$err} +mv-error-cannot-create-directory = impossible de créer le répertoire {$path} : {$err} +mv-error-cannot-access = impossible d'accéder à {$path} : {$err} +mv-error-error-writing = erreur d'écriture de {$to} : {$err} +mv-error-cannot-remove = impossible de supprimer {$from} : {$err} mv-error-setting-attribute = définition de l'attribut {$name} : {$err} mv-error-setting-attributes = définition des attributs pour {$path} : {$err} mv-error-exchange-two-operands = --exchange nécessite exactement deux opérandes diff --git a/src/uu/mv/src/error.rs b/src/uu/mv/src/error.rs index aa94b81b90f..4eacb3759e1 100644 --- a/src/uu/mv/src/error.rs +++ b/src/uu/mv/src/error.rs @@ -3,7 +3,10 @@ // For the full copyright and license information, please view the LICENSE // file that was distributed with this source code. -use uucore::error::UError; +use std::io; +use std::path::Path; +use uucore::display::Quotable; +use uucore::error::{FromIo, UError, USimpleError}; use uucore::translate; #[derive(Debug, thiserror::Error)] @@ -29,3 +32,84 @@ pub enum MvError { } impl UError for MvError {} + +#[derive(Debug)] +pub enum RenameError { + /// A raw I/O error from `fs::rename` (or general failure) that should be + /// contextualized as "cannot move 'source' to 'target': {err}" or + /// "cannot overwrite 'target': Directory not empty". + Io(io::Error), + /// A specific diagnostic that already includes the file path and operation, + /// such as "cannot open 'src' for reading: Permission denied" or + /// "error writing 'dst': No space left on device". + Formatted(String), +} + +impl std::fmt::Display for RenameError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + Self::Io(e) => write!(f, "{e}"), + Self::Formatted(s) => write!(f, "{s}"), + } + } +} + +impl std::error::Error for RenameError { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + match self { + Self::Io(e) => Some(e), + Self::Formatted(_) => None, + } + } +} + +impl From for RenameError { + fn from(err: io::Error) -> Self { + Self::Io(err) + } +} + +impl From for io::Error { + fn from(err: RenameError) -> Self { + match err { + RenameError::Io(e) => e, + RenameError::Formatted(s) => Self::other(s), + } + } +} + +impl RenameError { + pub fn is_empty(&self) -> bool { + match self { + Self::Io(e) => e.to_string().is_empty(), + Self::Formatted(s) => s.is_empty(), + } + } + + pub fn into_uerror(self, source: &Path, target: &Path) -> Box { + match self { + Self::Formatted(s) => USimpleError::new(1, s), + Self::Io(e) if e.to_string().is_empty() => USimpleError::new(1, ""), + Self::Io(e) => { + if e.kind() == io::ErrorKind::DirectoryNotEmpty { + e.map_err_context(|| { + translate!( + "mv-error-cannot-overwrite-non-empty-directory", + "target" => target.quote() + ) + }) + } else if e.raw_os_error().is_some() { + e.map_err_context(|| { + translate!( + "mv-error-cannot-move", + "source" => source.quote(), + "target" => target.quote() + ) + }) + } else { + USimpleError::new(1, format!("{e}")) + } + } + } + } +} diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index 4b042c015c8..4c741f0b6fd 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -44,7 +44,7 @@ use crate::hardlink::{ }; use uucore::backup_control::{self, backup_would_destroy_source}; use uucore::display::Quotable; -use uucore::error::{FromIo, UError, UResult, USimpleError, UUsageError, set_exit_code}; +use uucore::error::{UResult, USimpleError, UUsageError, set_exit_code, strip_errno}; #[cfg(unix)] use uucore::fs::display_permissions_unix; use uucore::fs::{ @@ -71,7 +71,7 @@ use uucore::update_control; pub use uucore::{backup_control::BackupMode, update_control::UpdateMode}; use uucore::{format_usage, prompt_yes, show}; -use crate::error::MvError; +use crate::error::{MvError, RenameError}; /// Options contains all the possible behaviors and flags for mv. /// @@ -446,7 +446,7 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()> hardlink_params.0, hardlink_params.1, ) - .map_err(|e| cannot_move_error(e, source, target)) + .map_err(|e| e.into_uerror(source, target)) } else { Err(MvError::DirectoryToNonDirectory( target.quote().to_string(), @@ -490,15 +490,7 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()> hardlink_params.0, hardlink_params.1, ) - .map_err(|e| -> Box { - // OS errors get the same "cannot move" context as GNU; our own - // messages (e.g. "not replacing") are already complete. - if e.raw_os_error().is_some() { - cannot_move_error(e, source, target) - } else { - USimpleError::new(1, format!("{e}")) - } - }) + .map_err(|e| e.into_uerror(source, target)) } } @@ -663,6 +655,7 @@ fn exchange_paths(paths: &[PathBuf], opts: &Options) -> UResult<()> { #[cfg(any(target_os = "linux", target_os = "android"))] fn exchange_two_paths(from: &Path, to: &Path, opts: &Options) -> UResult<()> { use rustix::fs::{CWD, RenameFlags, renameat_with}; + use uucore::error::FromIo; let canonicalize_or_absolute = |p: &Path| { canonicalize(absolute(p)?, MissingHandling::Normal, ResolveMode::Logical) @@ -782,13 +775,13 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, options: &Options) hardlink_params.0, hardlink_params.1, ) { - Err(e) if e.to_string().is_empty() => set_exit_code(1), + Err(e) if e.is_empty() => set_exit_code(1), Err(e) => { - let e = cannot_move_error(e, sourcepath, &targetpath); + let uerr = e.into_uerror(sourcepath, &targetpath); if let Some(ref pb) = display_manager { - pb.suspend(|| show!(e)); + pb.suspend(|| show!(uerr)); } else { - show!(e); + show!(uerr); } } Ok(()) => { @@ -811,7 +804,7 @@ fn rename( #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, #[cfg(not(unix))] _hardlink_tracker: Option<()>, #[cfg(not(unix))] _hardlink_scanner: Option<()>, -) -> io::Result<()> { +) -> Result<(), RenameError> { let mut backup_path = None; // The destination entry itself is replaced, so look at it without @@ -840,7 +833,7 @@ fn rename( if opts.update == UpdateMode::NoneFail { let err_msg = translate!("mv-error-not-replacing", "target" => to.quote()); - return Err(io::Error::other(err_msg)); + return Err(io::Error::other(err_msg).into()); } match opts.overwrite { @@ -892,7 +885,8 @@ fn rename( return Err(io::Error::new( io::ErrorKind::DirectoryNotEmpty, translate!("mv-error-directory-not-empty"), - )); + ) + .into()); } } } @@ -936,10 +930,6 @@ fn rename( Ok(()) } -fn is_directory_not_empty_error(err: &io::Error) -> bool { - err.kind() == io::ErrorKind::DirectoryNotEmpty -} - #[cfg(unix)] fn is_fifo(filetype: fs::FileType) -> bool { filetype.is_fifo() @@ -952,24 +942,6 @@ fn is_fifo(_filetype: fs::FileType) -> bool { /// A wrapper around `fs::rename`, so that if it fails, we try falling back on /// copying and removing. -/// Add GNU's "cannot move" (or "cannot overwrite" for a non-empty -/// directory) context to an error from `rename`. -fn cannot_move_error(e: io::Error, source: &Path, target: &Path) -> Box { - let message = if is_directory_not_empty_error(&e) { - translate!( - "mv-error-cannot-overwrite-non-empty-directory", - "target" => target.quote() - ) - } else { - translate!( - "mv-error-cannot-move", - "source" => source.quote(), - "target" => target.quote() - ) - }; - e.map_err_context(|| message) -} - fn rename_with_fallback( from: &Path, to: &Path, @@ -979,74 +951,102 @@ fn rename_with_fallback( #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, #[cfg(not(unix))] _hardlink_tracker: Option<()>, #[cfg(not(unix))] _hardlink_scanner: Option<()>, -) -> io::Result<()> { - fs::rename(from, to).or_else(|err| { - // We will only copy if: - // 1. Files are on different devices (CrossesDevices / EXDEV error) - // 2. On Windows, if the target file exists and source file is opened by another process - // (MoveFileExW fails with "Access Denied" even if the source file has FILE_SHARE_DELETE permission) - let should_fallback = err.kind() == io::ErrorKind::CrossesDevices - || (err.kind() == io::ErrorKind::PermissionDenied - && from.is_file() - && can_delete_file(from)); - if !should_fallback { - return Err(err); - } - // Get metadata without following symlinks - let metadata = from.symlink_metadata()?; - let file_type = metadata.file_type(); - if file_type.is_symlink() { - rename_symlink_fallback(from, to) - } else if file_type.is_dir() { - #[cfg(unix)] - { - with_optional_hardlink_context( - hardlink_tracker, - hardlink_scanner, - |tracker, scanner| { - rename_dir_fallback( - from, - to, - display_manager, - verbose, - Some(tracker), - Some(scanner), - ) - }, - ) - } - #[cfg(not(unix))] - { - rename_dir_fallback(from, to, display_manager, verbose) - } - } else if is_fifo(file_type) { - rename_fifo_fallback(from, to) - } else { - #[cfg(unix)] - { - with_optional_hardlink_context( - hardlink_tracker, - hardlink_scanner, - |tracker, scanner| rename_file_fallback(from, to, Some(tracker), Some(scanner)), - ) +) -> Result<(), RenameError> { + fs::rename(from, to) + .map_err(RenameError::Io) + .or_else(|err| { + // We will only copy if: + // 1. Files are on different devices (CrossesDevices / EXDEV error) + // 2. On Windows, if the target file exists and source file is opened by another process + // (MoveFileExW fails with "Access Denied" even if the source file has FILE_SHARE_DELETE permission) + let should_fallback = match &err { + RenameError::Io(io_err) => { + io_err.kind() == io::ErrorKind::CrossesDevices + || (io_err.kind() == io::ErrorKind::PermissionDenied + && from.is_file() + && can_delete_file(from)) + } + RenameError::Formatted(_) => false, + }; + if !should_fallback { + return Err(err); } - #[cfg(not(unix))] - { - rename_file_fallback(from, to) + // Get metadata without following symlinks + let metadata = from.symlink_metadata()?; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + rename_symlink_fallback(from, to) + } else if file_type.is_dir() { + #[cfg(unix)] + { + with_optional_hardlink_context( + hardlink_tracker, + hardlink_scanner, + |tracker, scanner| { + rename_dir_fallback( + from, + to, + display_manager, + verbose, + Some(tracker), + Some(scanner), + ) + }, + ) + } + #[cfg(not(unix))] + { + rename_dir_fallback(from, to, display_manager, verbose) + } + } else if is_fifo(file_type) { + rename_fifo_fallback(from, to) + } else { + #[cfg(unix)] + { + with_optional_hardlink_context( + hardlink_tracker, + hardlink_scanner, + |tracker, scanner| { + rename_file_fallback(from, to, Some(tracker), Some(scanner)) + }, + ) + } + #[cfg(not(unix))] + { + rename_file_fallback(from, to) + } } - } - }) + }) } /// Replace the destination with a new pipe with the same name as the source. #[cfg(unix)] -fn rename_fifo_fallback(from: &Path, to: &Path) -> io::Result<()> { +fn rename_fifo_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { if to.try_exists()? { - fs::remove_file(to)?; + match fs::remove_file(to) { + Ok(()) => {} + Err(ref err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => { + return Err(RenameError::Formatted(translate!( + "mv-error-inter-device-move-failed", + "from" => from.quote(), + "to" => to.quote(), + "err" => strip_errno(&err) + ))); + } + } } // rustix::fs::mkfifoat is linux only - nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666))?; - fs::remove_file(from) + nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)) + .map_err(|e| RenameError::Io(e.into()))?; + fs::remove_file(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; + Ok(()) } #[cfg(not(unix))] @@ -1054,14 +1054,14 @@ fn rename_fifo_fallback(from: &Path, to: &Path) -> io::Result<()> { clippy::unnecessary_wraps, reason = "fn sig must match on all platforms" )] -fn rename_fifo_fallback(_from: &Path, _to: &Path) -> io::Result<()> { +fn rename_fifo_fallback(_from: &Path, _to: &Path) -> Result<(), RenameError> { Ok(()) } /// Move the given symlink to the given destination. On Windows, dangling /// symlinks return an error. #[cfg(unix)] -fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { +fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { let path_symlink_points_to = fs::read_link(from)?; // On AlreadyExists, fall through to atomic temp-and-rename so the @@ -1073,11 +1073,20 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { uucore::fs::replace_link(&path_symlink_points_to, to, true)?; #[cfg(target_os = "redox")] { - fs::remove_file(to)?; + if let Err(err) = fs::remove_file(to) { + if err.kind() != io::ErrorKind::NotFound { + return Err(RenameError::Formatted(translate!( + "mv-error-inter-device-move-failed", + "from" => from.quote(), + "to" => to.quote(), + "err" => strip_errno(&err) + ))); + } + } unix::fs::symlink(&path_symlink_points_to, to)?; } } - Err(e) => return Err(e), + Err(e) => return Err(RenameError::Io(e)), } #[cfg(any( target_os = "freebsd", @@ -1092,10 +1101,17 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { } } let _ = preserve_ownership(from, to); - fs::remove_file(from) + fs::remove_file(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; + Ok(()) } #[cfg(windows)] -fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { +fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { let path_symlink_points_to = fs::read_link(from)?; if path_symlink_points_to.exists() { if path_symlink_points_to.is_dir() { @@ -1103,18 +1119,26 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { } else { windows::fs::symlink_file(&path_symlink_points_to, to)?; } - fs::remove_file(from) + fs::remove_file(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; + Ok(()) } else { Err(io::Error::new( io::ErrorKind::NotFound, translate!("mv-error-dangling-symlink"), - )) + ) + .into()) } } #[cfg(target_os = "wasi")] -fn rename_symlink_fallback(_from: &Path, _to: &Path) -> io::Result<()> { - Err(io::Error::other(translate!("mv-error-no-symlink-support"))) +fn rename_symlink_fallback(_from: &Path, _to: &Path) -> Result<(), RenameError> { + Err(io::Error::other(translate!("mv-error-no-symlink-support")).into()) } fn rename_dir_fallback( @@ -1124,11 +1148,17 @@ fn rename_dir_fallback( verbose: bool, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> io::Result<()> { +) -> Result<(), RenameError> { // We remove the destination directory if it exists to match the // behavior of `fs::rename`. if to.exists() { - fs::remove_dir_all(to)?; + fs::remove_dir_all(to).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => to.quote(), + "err" => strip_errno(&err) + )) + })?; } // Calculate total size of directory @@ -1165,7 +1195,7 @@ fn rename_dir_fallback( }; // Use directory copying (with or without hardlink support) - let result = copy_dir_contents( + copy_dir_contents( from, to, #[cfg(unix)] @@ -1175,7 +1205,7 @@ fn rename_dir_fallback( verbose, progress_bar.as_ref(), display_manager, - ); + )?; // Apply xattrs using a file descriptor to avoid TOCTOU races, ignoring // ENOTSUP/EOPNOTSUPP (filesystem without xattr support, which is expected @@ -1192,20 +1222,24 @@ fn rename_dir_fallback( ))] { use std::fs::File; - let dest = File::open(to)?; - fsxattr::apply_xattrs_fd_ignore_unsupported(&dest, xattrs)?; + if let Ok(dest) = File::open(to) { + let _ = fsxattr::apply_xattrs_fd_ignore_unsupported(&dest, xattrs); + } } - result?; - // As for subdirectories, the mode goes on last. #[cfg(unix)] if let (Ok(src), Ok(dst)) = (open_dir_nofollow(from), open_dir_nofollow(to)) { copy_dir_mode(&src, &dst); } - // Remove the source directory after successful copy - fs::remove_dir_all(from)?; + fs::remove_dir_all(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; Ok(()) } @@ -1219,19 +1253,23 @@ fn rename_dir_fallback( /// The directory starts private (0700): its real mode is applied only after its /// contents are copied, and until then, or for good if the copy fails, the /// umask-based 0755 would expose entries that a 0700 source kept hidden. -fn create_dir_fail_closed(path: &Path) -> io::Result<()> { +fn create_dir_fail_closed(path: &Path) -> Result<(), RenameError> { #[cfg(unix)] let created = unix::fs::DirBuilderExt::mode(&mut fs::DirBuilder::new(), 0o700).create(path); #[cfg(not(unix))] let created = fs::create_dir(path); created.map_err(|e| { if e.kind() == io::ErrorKind::AlreadyExists { - io::Error::new( + RenameError::Io(io::Error::new( io::ErrorKind::AlreadyExists, translate!("mv-error-dest-appeared", "path" => path.quote()), - ) + )) } else { - e + RenameError::Formatted(translate!( + "mv-error-cannot-create-directory", + "path" => path.quote(), + "err" => strip_errno(&e) + )) } }) } @@ -1262,7 +1300,7 @@ fn copy_dir_contents( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> io::Result<()> { +) -> Result<(), RenameError> { // Create the destination directory create_dir_fail_closed(to)?; @@ -1299,7 +1337,7 @@ fn copy_dir_contents_recursive( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> io::Result<()> { +) -> Result<(), RenameError> { // Helper closure to print verbose messages let print_verbose = |from: &Path, to: &Path| { if verbose { @@ -1314,10 +1352,22 @@ fn copy_dir_contents_recursive( } }; - let entries = fs::read_dir(from_dir)?; + let entries = fs::read_dir(from_dir).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-access", + "path" => from_dir.quote(), + "err" => strip_errno(&err) + )) + })?; for entry in entries { - let entry = entry?; + let entry = entry.map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-access", + "path" => from_dir.quote(), + "err" => strip_errno(&err) + )) + })?; let from_path = entry.path(); let file_name = from_path.file_name().unwrap(); let to_path = to_dir.join(file_name); @@ -1382,7 +1432,7 @@ fn copy_dir_contents_recursive( #[cfg(not(unix))] { // Symlinks are already handled above, so this is always a regular file - fs::copy(&from_path, &to_path)?; + copy_regular_file(&from_path, &to_path)?; } print_verbose(&from_path, &to_path); @@ -1455,7 +1505,7 @@ fn copy_file_with_hardlinks_helper( to: &Path, hardlink_tracker: &mut HardlinkTracker, hardlink_scanner: &HardlinkGroupScanner, -) -> io::Result<()> { +) -> Result<(), RenameError> { // Check if this file should be a hardlink to an already-copied file use crate::hardlink::HardlinkOptions; let hardlink_options = HardlinkOptions::default(); @@ -1463,7 +1513,13 @@ fn copy_file_with_hardlinks_helper( if let Some(existing_target) = hardlink_tracker.check_hardlink(from, to, hardlink_scanner, &hardlink_options) { - fs::hard_link(&existing_target, to)?; + fs::hard_link(&existing_target, to).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-create-regular-file", + "to" => to.quote(), + "err" => strip_errno(&err) + )) + })?; return Ok(()); } @@ -1471,31 +1527,104 @@ fn copy_file_with_hardlinks_helper( // Copy a symlink file (no-follow). // rename_symlink_fallback already preserves ownership and removes the source. rename_symlink_fallback(from, to)?; - } else if is_fifo(from.symlink_metadata()?.file_type()) { + } else if is_fifo( + from.symlink_metadata() + .map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-access", + "path" => from.quote(), + "err" => strip_errno(&err) + )) + })? + .file_type(), + ) { // rustix::fs::mkfifoat is linux only - nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666))?; + nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)).map_err( + |err| { + RenameError::Formatted(translate!( + "mv-error-cannot-create-regular-file", + "to" => to.quote(), + "err" => strip_errno(&err.into()) + )) + }, + )?; // Preserve ownership (uid/gid) from the source let _ = preserve_ownership(from, to); } else { // Copy a regular file. - fs::copy(from, to)?; - // Copy xattrs, ignoring ENOTSUP errors (filesystem doesn't support xattrs) - #[cfg(any( - target_os = "freebsd", - target_os = "hurd", - target_os = "linux", - target_os = "android", - target_os = "netbsd" - ))] - { - if let Ok(failed) = fsxattr::copy_xattrs_ignore_unsupported(from, to) { - show_xattr_failures(None, failed); - } + copy_regular_file(from, to)?; + } + + Ok(()) +} + +#[cfg(unix)] +fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { + use std::fs::Permissions; + use std::os::unix::fs::{MetadataExt, PermissionsExt}; + use uucore::safe_copy::{create_dest_restrictive, open_source}; + + let src_file = open_source(from, /* nofollow */ true).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-open-for-reading", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; + let src_mode = src_file.metadata()?.mode(); + let mut dst_file = create_dest_restrictive(to, /* nofollow */ true).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-create-regular-file", + "to" => to.quote(), + "err" => strip_errno(&err) + )) + })?; + uucore::buf_copy::copy_fast(&mut &src_file, &mut dst_file).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-error-writing", + "to" => to.quote(), + "err" => strip_errno(&err) + )) + })?; + + #[cfg(any( + target_os = "freebsd", + target_os = "hurd", + target_os = "linux", + target_os = "android", + target_os = "netbsd" + ))] + { + if let Ok(failed) = fsxattr::copy_xattrs_fd(&src_file, &dst_file) { + show_xattr_failures(Some(to), failed); } - // Preserve ownership (uid/gid) from the source - let _ = preserve_ownership(from, to); } + // chown before chmod: chown(2) clears setuid/setgid for non-root, + // so the final mode must be applied last to preserve those bits. + let ownership_preserved = preserve_ownership(from, to).unwrap_or(false); + let dest_mode = preserved_mode(src_mode, ownership_preserved); + let _ = dst_file.set_permissions(Permissions::from_mode(dest_mode)); + Ok(()) +} + +#[cfg(not(unix))] +fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { + fs::copy(from, to).map_err(|err| { + if from.exists() { + RenameError::Formatted(translate!( + "mv-error-cannot-create-regular-file", + "to" => to.quote(), + "err" => strip_errno(&err) + )) + } else { + RenameError::Formatted(translate!( + "mv-error-cannot-open-for-reading", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + } + })?; Ok(()) } @@ -1504,16 +1633,21 @@ fn rename_file_fallback( to: &Path, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> io::Result<()> { +) -> Result<(), RenameError> { // Remove existing target file if it exists - if to.is_symlink() { - fs::remove_file(to).map_err(|err| { - let inter_device_msg = translate!("mv-error-inter-device-move-failed", "from" => from.quote(), "to" => to.quote(), "err" => err); - io::Error::new(err.kind(), inter_device_msg) - })?; - } else if to.exists() { - // For non-symlinks, just remove the file without special error handling - fs::remove_file(to)?; + if to.is_symlink() || to.exists() { + match fs::remove_file(to) { + Ok(()) => {} + Err(ref err) if err.kind() == io::ErrorKind::NotFound => {} + Err(err) => { + return Err(RenameError::Formatted(translate!( + "mv-error-inter-device-move-failed", + "from" => from.quote(), + "to" => to.quote(), + "err" => strip_errno(&err) + ))); + } + } } // Check if this file is part of a hardlink group and if so, create a hardlink instead of copying @@ -1527,59 +1661,27 @@ fn rename_file_fallback( { // Create a hardlink to the first moved file instead of copying fs::hard_link(&existing_target, to)?; - fs::remove_file(from)?; + fs::remove_file(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; return Ok(()); } } } - // Open src/dst with O_NOFOLLOW and keep the fds alive across copy, - // chown, xattr, and chmod so a concurrent path-swap can't redirect any - // step to a different inode. - #[cfg(unix)] - { - use std::fs::Permissions; - use std::os::unix::fs::{MetadataExt, PermissionsExt}; - use uucore::safe_copy::{create_dest_restrictive, open_source}; - let src_file = open_source(from, /* nofollow */ true) - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))?; - let src_mode = src_file - .metadata() - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))? - .mode(); - let mut dst_file = create_dest_restrictive(to, /* nofollow */ true) - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))?; - uucore::buf_copy::copy_fast(&mut &src_file, &mut dst_file) - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))?; - - #[cfg(any( - target_os = "freebsd", - target_os = "hurd", - target_os = "linux", - target_os = "android", - target_os = "netbsd" - ))] - { - if let Ok(failed) = fsxattr::copy_xattrs_fd(&src_file, &dst_file) { - show_xattr_failures(Some(to), failed); - } - } - - // chown before chmod: chown(2) clears setuid/setgid for non-root, - // so the final mode must be applied last to preserve those bits. - let ownership_preserved = preserve_ownership(from, to).unwrap_or(false); - let dest_mode = preserved_mode(src_mode, ownership_preserved); - let _ = dst_file.set_permissions(Permissions::from_mode(dest_mode)); - } - - #[cfg(not(unix))] - { - fs::copy(from, to) - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))?; - } + copy_regular_file(from, to)?; - fs::remove_file(from) - .map_err(|err| io::Error::new(err.kind(), translate!("mv-error-permission-denied")))?; + fs::remove_file(from).map_err(|err| { + RenameError::Formatted(translate!( + "mv-error-cannot-remove", + "from" => from.quote(), + "err" => strip_errno(&err) + )) + })?; Ok(()) } diff --git a/tests/by-util/test_mv.rs b/tests/by-util/test_mv.rs index e828d29a2e2..0ebde7390f6 100644 --- a/tests/by-util/test_mv.rs +++ b/tests/by-util/test_mv.rs @@ -2964,6 +2964,214 @@ fn test_mv_cross_device_permission_denied() { .expect("Unable to restore directory permissions"); } +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_source_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.write("unreadable_src", "source content"); + set_permissions(at.plus("unreadable_src"), PermissionsExt::from_mode(0o000)) + .expect("Unable to set permissions"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + let target = other_fs_tempdir.path().join("target"); + + scene + .ucmd() + .arg(at.plus("unreadable_src")) + .arg(&target) + .fails() + .stderr_contains("cannot open") + .stderr_contains("for reading: Permission denied"); + + set_permissions(at.plus("unreadable_src"), PermissionsExt::from_mode(0o644)) + .expect("Unable to restore permissions"); +} + +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dest_directory_unwritable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.write("src_file", "source content"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + let target = other_fs_tempdir.path().join("nonexistent_target"); + + scene + .ucmd() + .arg(at.plus("src_file")) + .arg(&target) + .fails() + .stderr_contains("cannot create regular file") + .stderr_contains("Permission denied"); + + set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o755)) + .expect("Unable to restore directory permissions"); +} + +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_source_directory_unwritable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.mkdir("readonly_dir"); + at.write("readonly_dir/src", "source content"); + set_permissions(at.plus("readonly_dir"), PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + let target = other_fs_tempdir.path().join("target"); + + scene + .ucmd() + .arg(at.plus("readonly_dir/src")) + .arg(&target) + .fails() + .stderr_contains("cannot remove") + .stderr_contains("Permission denied"); + + set_permissions(at.plus("readonly_dir"), PermissionsExt::from_mode(0o755)) + .expect("Unable to restore directory permissions"); +} + +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dir_dest_directory_unwritable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.mkdir("src_dir"); + at.write("src_dir/file", "content"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + let target = other_fs_tempdir.path().join("dest_dir"); + + scene + .ucmd() + .arg(at.plus("src_dir")) + .arg(&target) + .fails() + .stderr_contains("cannot create directory") + .stderr_contains("Permission denied"); + + set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o755)) + .expect("Unable to restore directory permissions"); +} + +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dir_file_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.mkdir("src_dir"); + at.write("src_dir/unreadable_file", "content"); + set_permissions( + at.plus("src_dir/unreadable_file"), + PermissionsExt::from_mode(0o000), + ) + .expect("Unable to set permissions"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + let target = other_fs_tempdir.path().join("dest_dir"); + + scene + .ucmd() + .arg(at.plus("src_dir")) + .arg(&target) + .fails() + .stderr_contains("cannot open") + .stderr_contains("for reading: Permission denied"); + + set_permissions( + at.plus("src_dir/unreadable_file"), + PermissionsExt::from_mode(0o644), + ) + .expect("Unable to restore permissions"); +} + +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dir_subdir_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + use tempfile::TempDir; + use uutests::util::TestScenario; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + + at.mkdir("src_dir"); + at.mkdir("src_dir/unreadable_subdir"); + set_permissions( + at.plus("src_dir/unreadable_subdir"), + PermissionsExt::from_mode(0o000), + ) + .expect("Unable to set permissions"); + + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + let target = other_fs_tempdir.path().join("dest_dir"); + + scene + .ucmd() + .arg(at.plus("src_dir")) + .arg(&target) + .fails() + .stderr_contains("cannot access") + .stderr_contains("Permission denied"); + + set_permissions( + at.plus("src_dir/unreadable_subdir"), + PermissionsExt::from_mode(0o755), + ) + .expect("Unable to restore permissions"); +} + /// Regression for #10015. The cross-device fallback unlinks the destination /// and then creates a new file at the same path. An attacker who can write /// to the destination directory could race to plant a symlink in that From 524247e80f303c0986749da0998d79daf35f8949 Mon Sep 17 00:00:00 2001 From: Afnan Mojumder Date: Mon, 30 Nov 2026 13:26:08 +0600 Subject: [PATCH 2/3] mv: address review feedback on RenameError and tests --- src/uu/mv/src/error.rs | 156 +++++++++++++++++------ src/uu/mv/src/mv.rs | 196 ++++++----------------------- tests/by-util/test_mv.rs | 258 +++++++++++++++++---------------------- 3 files changed, 268 insertions(+), 342 deletions(-) diff --git a/src/uu/mv/src/error.rs b/src/uu/mv/src/error.rs index 4eacb3759e1..64962ee6515 100644 --- a/src/uu/mv/src/error.rs +++ b/src/uu/mv/src/error.rs @@ -4,9 +4,9 @@ // file that was distributed with this source code. use std::io; -use std::path::Path; +use std::path::{Path, PathBuf}; use uucore::display::Quotable; -use uucore::error::{FromIo, UError, USimpleError}; +use uucore::error::{FromIo, UError, USimpleError, strip_errno}; use uucore::translate; #[derive(Debug, thiserror::Error)] @@ -33,63 +33,144 @@ pub enum MvError { impl UError for MvError {} -#[derive(Debug)] +#[derive(Debug, thiserror::Error)] pub enum RenameError { /// A raw I/O error from `fs::rename` (or general failure) that should be /// contextualized as "cannot move 'source' to 'target': {err}" or /// "cannot overwrite 'target': Directory not empty". - Io(io::Error), - /// A specific diagnostic that already includes the file path and operation, - /// such as "cannot open 'src' for reading: Permission denied" or - /// "error writing 'dst': No space left on device". - Formatted(String), + #[error("{0}")] + Io(#[from] io::Error), + #[error("")] + PromptDeclined, + #[error( + "{}", + translate!( + "mv-error-inter-device-move-failed", + "from" => .from.quote(), + "to" => .to.quote(), + "err" => strip_errno(.err) + ) + )] + InterDeviceMoveFailed { + from: PathBuf, + to: PathBuf, + err: io::Error, + }, + #[error( + "{}", + translate!( + "mv-error-cannot-open-for-reading", + "from" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + CannotOpenForReading { path: PathBuf, err: io::Error }, + #[error( + "{}", + translate!( + "mv-error-cannot-create-regular-file", + "to" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + CannotCreateRegularFile { path: PathBuf, err: io::Error }, + #[error( + "{}", + translate!( + "mv-error-cannot-create-directory", + "path" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + CannotCreateDirectory { path: PathBuf, err: io::Error }, + #[error( + "{}", + translate!( + "mv-error-cannot-access", + "path" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + CannotAccess { path: PathBuf, err: io::Error }, + #[cfg(unix)] + #[error( + "{}", + translate!( + "mv-error-error-writing", + "to" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + ErrorWriting { path: PathBuf, err: io::Error }, + #[error( + "{}", + translate!( + "mv-error-cannot-remove", + "from" => .path.quote(), + "err" => strip_errno(.err) + ) + )] + CannotRemove { path: PathBuf, err: io::Error }, } -impl std::fmt::Display for RenameError { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - match self { - Self::Io(e) => write!(f, "{e}"), - Self::Formatted(s) => write!(f, "{s}"), +impl RenameError { + pub fn inter_device_move_failed<'a>( + from: &'a Path, + to: &'a Path, + ) -> impl FnOnce(io::Error) -> Self + 'a { + move |err| Self::InterDeviceMoveFailed { + from: from.to_path_buf(), + to: to.to_path_buf(), + err, } } -} -impl std::error::Error for RenameError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - match self { - Self::Io(e) => Some(e), - Self::Formatted(_) => None, + pub fn cannot_open_for_reading(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::CannotOpenForReading { + path: path.to_path_buf(), + err, } } -} -impl From for RenameError { - fn from(err: io::Error) -> Self { - Self::Io(err) + pub fn cannot_create_regular_file(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::CannotCreateRegularFile { + path: path.to_path_buf(), + err, + } } -} -impl From for io::Error { - fn from(err: RenameError) -> Self { - match err { - RenameError::Io(e) => e, - RenameError::Formatted(s) => Self::other(s), + pub fn cannot_create_directory(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::CannotCreateDirectory { + path: path.to_path_buf(), + err, } } -} -impl RenameError { - pub fn is_empty(&self) -> bool { - match self { - Self::Io(e) => e.to_string().is_empty(), - Self::Formatted(s) => s.is_empty(), + pub fn cannot_access(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::CannotAccess { + path: path.to_path_buf(), + err, + } + } + + #[cfg(unix)] + pub fn error_writing(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::ErrorWriting { + path: path.to_path_buf(), + err, + } + } + + pub fn cannot_remove(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { + move |err| Self::CannotRemove { + path: path.to_path_buf(), + err, } } pub fn into_uerror(self, source: &Path, target: &Path) -> Box { match self { - Self::Formatted(s) => USimpleError::new(1, s), - Self::Io(e) if e.to_string().is_empty() => USimpleError::new(1, ""), + Self::PromptDeclined => USimpleError::new(1, ""), Self::Io(e) => { if e.kind() == io::ErrorKind::DirectoryNotEmpty { e.map_err_context(|| { @@ -110,6 +191,7 @@ impl RenameError { USimpleError::new(1, format!("{e}")) } } + other => USimpleError::new(1, other.to_string()), } } } diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index 4c741f0b6fd..e39155b734b 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -44,7 +44,7 @@ use crate::hardlink::{ }; use uucore::backup_control::{self, backup_would_destroy_source}; use uucore::display::Quotable; -use uucore::error::{UResult, USimpleError, UUsageError, set_exit_code, strip_errno}; +use uucore::error::{UResult, USimpleError, UUsageError, set_exit_code}; #[cfg(unix)] use uucore::fs::display_permissions_unix; use uucore::fs::{ @@ -460,12 +460,14 @@ fn handle_two_paths(source: &Path, target: &Path, opts: &Options) -> UResult<()> } else if source_is_dir && target.symlink_metadata().is_ok() { match opts.overwrite { OverwriteMode::NoClobber => return Ok(()), - OverwriteMode::Interactive => prompt_overwrite(target, None)?, + OverwriteMode::Interactive => { + prompt_overwrite(target, None).map_err(|e| e.into_uerror(source, target))?; + } OverwriteMode::Force => {} OverwriteMode::Default => { let (writable, mode) = is_writable(target); if !writable && io::stdin().is_terminal() { - prompt_overwrite(target, mode)?; + prompt_overwrite(target, mode).map_err(|e| e.into_uerror(source, target))?; } } } @@ -775,7 +777,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, options: &Options) hardlink_params.0, hardlink_params.1, ) { - Err(e) if e.is_empty() => set_exit_code(1), + Err(RenameError::PromptDeclined) => set_exit_code(1), Err(e) => { let uerr = e.into_uerror(sourcepath, &targetpath); if let Some(ref pb) = display_manager { @@ -966,7 +968,7 @@ fn rename_with_fallback( && from.is_file() && can_delete_file(from)) } - RenameError::Formatted(_) => false, + _ => false, }; if !should_fallback { return Err(err); @@ -1026,26 +1028,13 @@ fn rename_fifo_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { match fs::remove_file(to) { Ok(()) => {} Err(ref err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => { - return Err(RenameError::Formatted(translate!( - "mv-error-inter-device-move-failed", - "from" => from.quote(), - "to" => to.quote(), - "err" => strip_errno(&err) - ))); - } + Err(err) => return Err(RenameError::inter_device_move_failed(from, to)(err)), } } // rustix::fs::mkfifoat is linux only nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)) .map_err(|e| RenameError::Io(e.into()))?; - fs::remove_file(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } @@ -1073,15 +1062,10 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { uucore::fs::replace_link(&path_symlink_points_to, to, true)?; #[cfg(target_os = "redox")] { - if let Err(err) = fs::remove_file(to) { - if err.kind() != io::ErrorKind::NotFound { - return Err(RenameError::Formatted(translate!( - "mv-error-inter-device-move-failed", - "from" => from.quote(), - "to" => to.quote(), - "err" => strip_errno(&err) - ))); - } + if let Err(err) = fs::remove_file(to) + && err.kind() != io::ErrorKind::NotFound + { + return Err(RenameError::inter_device_move_failed(from, to)(err)); } unix::fs::symlink(&path_symlink_points_to, to)?; } @@ -1101,13 +1085,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { } } let _ = preserve_ownership(from, to); - fs::remove_file(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } #[cfg(windows)] @@ -1119,13 +1097,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { } else { windows::fs::symlink_file(&path_symlink_points_to, to)?; } - fs::remove_file(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } else { Err(io::Error::new( @@ -1152,13 +1124,7 @@ fn rename_dir_fallback( // We remove the destination directory if it exists to match the // behavior of `fs::rename`. if to.exists() { - fs::remove_dir_all(to).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => to.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_dir_all(to).map_err(RenameError::cannot_remove(to))?; } // Calculate total size of directory @@ -1222,9 +1188,8 @@ fn rename_dir_fallback( ))] { use std::fs::File; - if let Ok(dest) = File::open(to) { - let _ = fsxattr::apply_xattrs_fd_ignore_unsupported(&dest, xattrs); - } + let dest = File::open(to)?; + fsxattr::apply_xattrs_fd_ignore_unsupported(&dest, xattrs)?; } // As for subdirectories, the mode goes on last. @@ -1233,13 +1198,7 @@ fn rename_dir_fallback( copy_dir_mode(&src, &dst); } // Remove the source directory after successful copy - fs::remove_dir_all(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_dir_all(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } @@ -1265,11 +1224,7 @@ fn create_dir_fail_closed(path: &Path) -> Result<(), RenameError> { translate!("mv-error-dest-appeared", "path" => path.quote()), )) } else { - RenameError::Formatted(translate!( - "mv-error-cannot-create-directory", - "path" => path.quote(), - "err" => strip_errno(&e) - )) + RenameError::cannot_create_directory(path)(e) } }) } @@ -1352,22 +1307,10 @@ fn copy_dir_contents_recursive( } }; - let entries = fs::read_dir(from_dir).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-access", - "path" => from_dir.quote(), - "err" => strip_errno(&err) - )) - })?; + let entries = fs::read_dir(from_dir).map_err(RenameError::cannot_access(from_dir))?; for entry in entries { - let entry = entry.map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-access", - "path" => from_dir.quote(), - "err" => strip_errno(&err) - )) - })?; + let entry = entry.map_err(RenameError::cannot_access(from_dir))?; let from_path = entry.path(); let file_name = from_path.file_name().unwrap(); let to_path = to_dir.join(file_name); @@ -1513,13 +1456,7 @@ fn copy_file_with_hardlinks_helper( if let Some(existing_target) = hardlink_tracker.check_hardlink(from, to, hardlink_scanner, &hardlink_options) { - fs::hard_link(&existing_target, to).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-create-regular-file", - "to" => to.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::hard_link(&existing_target, to).map_err(RenameError::cannot_create_regular_file(to))?; return Ok(()); } @@ -1529,25 +1466,12 @@ fn copy_file_with_hardlinks_helper( rename_symlink_fallback(from, to)?; } else if is_fifo( from.symlink_metadata() - .map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-access", - "path" => from.quote(), - "err" => strip_errno(&err) - )) - })? + .map_err(RenameError::cannot_access(from))? .file_type(), ) { // rustix::fs::mkfifoat is linux only - nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)).map_err( - |err| { - RenameError::Formatted(translate!( - "mv-error-cannot-create-regular-file", - "to" => to.quote(), - "err" => strip_errno(&err.into()) - )) - }, - )?; + nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)) + .map_err(|err| RenameError::cannot_create_regular_file(to)(err.into()))?; // Preserve ownership (uid/gid) from the source let _ = preserve_ownership(from, to); } else { @@ -1564,28 +1488,13 @@ fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { use std::os::unix::fs::{MetadataExt, PermissionsExt}; use uucore::safe_copy::{create_dest_restrictive, open_source}; - let src_file = open_source(from, /* nofollow */ true).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-open-for-reading", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + let src_file = open_source(from, /* nofollow */ true) + .map_err(RenameError::cannot_open_for_reading(from))?; let src_mode = src_file.metadata()?.mode(); - let mut dst_file = create_dest_restrictive(to, /* nofollow */ true).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-create-regular-file", - "to" => to.quote(), - "err" => strip_errno(&err) - )) - })?; - uucore::buf_copy::copy_fast(&mut &src_file, &mut dst_file).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-error-writing", - "to" => to.quote(), - "err" => strip_errno(&err) - )) - })?; + let mut dst_file = create_dest_restrictive(to, /* nofollow */ true) + .map_err(RenameError::cannot_create_regular_file(to))?; + uucore::buf_copy::copy_fast(&mut &src_file, &mut dst_file) + .map_err(RenameError::error_writing(to))?; #[cfg(any( target_os = "freebsd", @@ -1612,17 +1521,9 @@ fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { fs::copy(from, to).map_err(|err| { if from.exists() { - RenameError::Formatted(translate!( - "mv-error-cannot-create-regular-file", - "to" => to.quote(), - "err" => strip_errno(&err) - )) + RenameError::cannot_create_regular_file(to)(err) } else { - RenameError::Formatted(translate!( - "mv-error-cannot-open-for-reading", - "from" => from.quote(), - "err" => strip_errno(&err) - )) + RenameError::cannot_open_for_reading(from)(err) } })?; Ok(()) @@ -1639,14 +1540,7 @@ fn rename_file_fallback( match fs::remove_file(to) { Ok(()) => {} Err(ref err) if err.kind() == io::ErrorKind::NotFound => {} - Err(err) => { - return Err(RenameError::Formatted(translate!( - "mv-error-inter-device-move-failed", - "from" => from.quote(), - "to" => to.quote(), - "err" => strip_errno(&err) - ))); - } + Err(err) => return Err(RenameError::inter_device_move_failed(from, to)(err)), } } @@ -1661,13 +1555,7 @@ fn rename_file_fallback( { // Create a hardlink to the first moved file instead of copying fs::hard_link(&existing_target, to)?; - fs::remove_file(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; return Ok(()); } } @@ -1675,13 +1563,7 @@ fn rename_file_fallback( copy_regular_file(from, to)?; - fs::remove_file(from).map_err(|err| { - RenameError::Formatted(translate!( - "mv-error-cannot-remove", - "from" => from.quote(), - "err" => strip_errno(&err) - )) - })?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } @@ -1830,9 +1712,9 @@ fn get_interactive_prompt(to: &Path, _cached_mode: Option) -> String { } /// Prompts the user for confirmation and returns an error if declined. -fn prompt_overwrite(to: &Path, cached_mode: Option) -> io::Result<()> { +fn prompt_overwrite(to: &Path, cached_mode: Option) -> Result<(), RenameError> { if !prompt_yes!("{}", get_interactive_prompt(to, cached_mode)) { - return Err(io::Error::other("")); + return Err(RenameError::PromptDeclined); } Ok(()) } diff --git a/tests/by-util/test_mv.rs b/tests/by-util/test_mv.rs index 0ebde7390f6..134d8433ec8 100644 --- a/tests/by-util/test_mv.rs +++ b/tests/by-util/test_mv.rs @@ -2964,68 +2964,83 @@ fn test_mv_cross_device_permission_denied() { .expect("Unable to restore directory permissions"); } -#[uutests::wasi_ignore(HostPathsNotVisible)] -#[test] #[cfg(target_os = "linux")] -fn test_mv_cross_device_source_unreadable() { +fn assert_cross_device_mv_permission_error( + setup: impl FnOnce( + &uutests::util::AtPath, + &Path, + ) -> ( + std::path::PathBuf, + std::path::PathBuf, + std::path::PathBuf, + u32, + String, + ), +) { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; use tempfile::TempDir; - use uutests::util::TestScenario; let scene = TestScenario::new(util_name!()); let at = &scene.fixtures; - - at.write("unreadable_src", "source content"); - set_permissions(at.plus("unreadable_src"), PermissionsExt::from_mode(0o000)) - .expect("Unable to set permissions"); - let other_fs_tempdir = TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - let target = other_fs_tempdir.path().join("target"); - scene - .ucmd() - .arg(at.plus("unreadable_src")) - .arg(&target) - .fails() - .stderr_contains("cannot open") - .stderr_contains("for reading: Permission denied"); + let (src, dst, restore_path, restore_mode, expected_stderr) = + setup(at, other_fs_tempdir.path()); - set_permissions(at.plus("unreadable_src"), PermissionsExt::from_mode(0o644)) + let result = scene.ucmd().arg(&src).arg(&dst).run(); + + set_permissions(&restore_path, PermissionsExt::from_mode(restore_mode)) .expect("Unable to restore permissions"); + + result.failure().stderr_is(expected_stderr); } #[uutests::wasi_ignore(HostPathsNotVisible)] #[test] #[cfg(target_os = "linux")] -fn test_mv_cross_device_dest_directory_unwritable() { +fn test_mv_cross_device_source_unreadable() { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; - use tempfile::TempDir; - use uutests::util::TestScenario; - - let scene = TestScenario::new(util_name!()); - let at = &scene.fixtures; - at.write("src_file", "source content"); - - let other_fs_tempdir = - TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555)) - .expect("Unable to set directory permissions"); - let target = other_fs_tempdir.path().join("nonexistent_target"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.write("unreadable_src", "source content"); + let src = at.plus("unreadable_src"); + set_permissions(&src, PermissionsExt::from_mode(0o000)).expect("Unable to set permissions"); + let dst = other_fs.join("target"); + let expected = format!( + "mv: cannot open '{}' for reading: Permission denied\n", + src.display() + ); + (src.clone(), dst, src, 0o644, expected) + }); +} - scene - .ucmd() - .arg(at.plus("src_file")) - .arg(&target) - .fails() - .stderr_contains("cannot create regular file") - .stderr_contains("Permission denied"); +#[uutests::wasi_ignore(HostPathsNotVisible)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dest_directory_unwritable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; - set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o755)) - .expect("Unable to restore directory permissions"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.write("src_file", "source content"); + set_permissions(other_fs, PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + let dst = other_fs.join("nonexistent_target"); + let expected = format!( + "mv: cannot create regular file '{}': Permission denied\n", + dst.display() + ); + ( + at.plus("src_file"), + dst, + other_fs.to_path_buf(), + 0o755, + expected, + ) + }); } #[uutests::wasi_ignore(HostPathsNotVisible)] @@ -3034,31 +3049,18 @@ fn test_mv_cross_device_dest_directory_unwritable() { fn test_mv_cross_device_source_directory_unwritable() { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; - use tempfile::TempDir; - use uutests::util::TestScenario; - let scene = TestScenario::new(util_name!()); - let at = &scene.fixtures; - - at.mkdir("readonly_dir"); - at.write("readonly_dir/src", "source content"); - set_permissions(at.plus("readonly_dir"), PermissionsExt::from_mode(0o555)) - .expect("Unable to set directory permissions"); - - let other_fs_tempdir = - TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - let target = other_fs_tempdir.path().join("target"); - - scene - .ucmd() - .arg(at.plus("readonly_dir/src")) - .arg(&target) - .fails() - .stderr_contains("cannot remove") - .stderr_contains("Permission denied"); - - set_permissions(at.plus("readonly_dir"), PermissionsExt::from_mode(0o755)) - .expect("Unable to restore directory permissions"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.mkdir("readonly_dir"); + at.write("readonly_dir/src", "source content"); + let readonly_dir = at.plus("readonly_dir"); + set_permissions(&readonly_dir, PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + let src = at.plus("readonly_dir/src"); + let dst = other_fs.join("target"); + let expected = format!("mv: cannot remove '{}': Permission denied\n", src.display()); + (src, dst, readonly_dir, 0o755, expected) + }); } #[uutests::wasi_ignore(HostPathsNotVisible)] @@ -3067,31 +3069,25 @@ fn test_mv_cross_device_source_directory_unwritable() { fn test_mv_cross_device_dir_dest_directory_unwritable() { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; - use tempfile::TempDir; - use uutests::util::TestScenario; - let scene = TestScenario::new(util_name!()); - let at = &scene.fixtures; - - at.mkdir("src_dir"); - at.write("src_dir/file", "content"); - - let other_fs_tempdir = - TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o555)) - .expect("Unable to set directory permissions"); - let target = other_fs_tempdir.path().join("dest_dir"); - - scene - .ucmd() - .arg(at.plus("src_dir")) - .arg(&target) - .fails() - .stderr_contains("cannot create directory") - .stderr_contains("Permission denied"); - - set_permissions(other_fs_tempdir.path(), PermissionsExt::from_mode(0o755)) - .expect("Unable to restore directory permissions"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.mkdir("src_dir"); + at.write("src_dir/file", "content"); + set_permissions(other_fs, PermissionsExt::from_mode(0o555)) + .expect("Unable to set directory permissions"); + let dst = other_fs.join("dest_dir"); + let expected = format!( + "mv: cannot create directory '{}': Permission denied\n", + dst.display() + ); + ( + at.plus("src_dir"), + dst, + other_fs.to_path_buf(), + 0o755, + expected, + ) + }); } #[uutests::wasi_ignore(HostPathsNotVisible)] @@ -3100,37 +3096,20 @@ fn test_mv_cross_device_dir_dest_directory_unwritable() { fn test_mv_cross_device_dir_file_unreadable() { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; - use tempfile::TempDir; - use uutests::util::TestScenario; - - let scene = TestScenario::new(util_name!()); - let at = &scene.fixtures; - - at.mkdir("src_dir"); - at.write("src_dir/unreadable_file", "content"); - set_permissions( - at.plus("src_dir/unreadable_file"), - PermissionsExt::from_mode(0o000), - ) - .expect("Unable to set permissions"); - let other_fs_tempdir = - TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - let target = other_fs_tempdir.path().join("dest_dir"); - - scene - .ucmd() - .arg(at.plus("src_dir")) - .arg(&target) - .fails() - .stderr_contains("cannot open") - .stderr_contains("for reading: Permission denied"); - - set_permissions( - at.plus("src_dir/unreadable_file"), - PermissionsExt::from_mode(0o644), - ) - .expect("Unable to restore permissions"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.mkdir("src_dir"); + at.write("src_dir/unreadable_file", "content"); + let unreadable = at.plus("src_dir/unreadable_file"); + set_permissions(&unreadable, PermissionsExt::from_mode(0o000)) + .expect("Unable to set permissions"); + let dst = other_fs.join("dest_dir"); + let expected = format!( + "mv: cannot open '{}' for reading: Permission denied\n", + unreadable.display() + ); + (at.plus("src_dir"), dst, unreadable, 0o644, expected) + }); } #[uutests::wasi_ignore(HostPathsNotVisible)] @@ -3139,37 +3118,20 @@ fn test_mv_cross_device_dir_file_unreadable() { fn test_mv_cross_device_dir_subdir_unreadable() { use std::fs::set_permissions; use std::os::unix::fs::PermissionsExt; - use tempfile::TempDir; - use uutests::util::TestScenario; - - let scene = TestScenario::new(util_name!()); - let at = &scene.fixtures; - at.mkdir("src_dir"); - at.mkdir("src_dir/unreadable_subdir"); - set_permissions( - at.plus("src_dir/unreadable_subdir"), - PermissionsExt::from_mode(0o000), - ) - .expect("Unable to set permissions"); - - let other_fs_tempdir = - TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); - let target = other_fs_tempdir.path().join("dest_dir"); - - scene - .ucmd() - .arg(at.plus("src_dir")) - .arg(&target) - .fails() - .stderr_contains("cannot access") - .stderr_contains("Permission denied"); - - set_permissions( - at.plus("src_dir/unreadable_subdir"), - PermissionsExt::from_mode(0o755), - ) - .expect("Unable to restore permissions"); + assert_cross_device_mv_permission_error(|at, other_fs| { + at.mkdir("src_dir"); + at.mkdir("src_dir/unreadable_subdir"); + let unreadable_dir = at.plus("src_dir/unreadable_subdir"); + set_permissions(&unreadable_dir, PermissionsExt::from_mode(0o000)) + .expect("Unable to set permissions"); + let dst = other_fs.join("dest_dir"); + let expected = format!( + "mv: cannot access '{}': Permission denied\n", + unreadable_dir.display() + ); + (at.plus("src_dir"), dst, unreadable_dir, 0o755, expected) + }); } /// Regression for #10015. The cross-device fallback unlinks the destination From 0721134ee5403014640ea8188b9ef470fa5b1d23 Mon Sep 17 00:00:00 2001 From: Afnan Mojumder Date: Tue, 1 Dec 2026 21:08:09 +0600 Subject: [PATCH 3/3] mv: box RenameError to keep hot-path Result size small --- src/uu/mv/src/error.rs | 80 +++++++++++++++++++++++++++--------------- src/uu/mv/src/mv.rs | 70 +++++++++++++++++------------------- 2 files changed, 84 insertions(+), 66 deletions(-) diff --git a/src/uu/mv/src/error.rs b/src/uu/mv/src/error.rs index 64962ee6515..1becf519008 100644 --- a/src/uu/mv/src/error.rs +++ b/src/uu/mv/src/error.rs @@ -33,6 +33,8 @@ pub enum MvError { impl UError for MvError {} +pub type RenameResult = Result>; + #[derive(Debug, thiserror::Error)] pub enum RenameError { /// A raw I/O error from `fs::rename` (or general failure) that should be @@ -113,58 +115,78 @@ pub enum RenameError { CannotRemove { path: PathBuf, err: io::Error }, } +impl From for Box { + fn from(err: io::Error) -> Self { + Self::new(RenameError::Io(err)) + } +} + impl RenameError { pub fn inter_device_move_failed<'a>( from: &'a Path, to: &'a Path, - ) -> impl FnOnce(io::Error) -> Self + 'a { - move |err| Self::InterDeviceMoveFailed { - from: from.to_path_buf(), - to: to.to_path_buf(), - err, + ) -> impl FnOnce(io::Error) -> Box + 'a { + move |err| { + Box::new(Self::InterDeviceMoveFailed { + from: from.to_path_buf(), + to: to.to_path_buf(), + err, + }) } } - pub fn cannot_open_for_reading(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::CannotOpenForReading { - path: path.to_path_buf(), - err, + pub fn cannot_open_for_reading(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::CannotOpenForReading { + path: path.to_path_buf(), + err, + }) } } - pub fn cannot_create_regular_file(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::CannotCreateRegularFile { - path: path.to_path_buf(), - err, + pub fn cannot_create_regular_file(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::CannotCreateRegularFile { + path: path.to_path_buf(), + err, + }) } } - pub fn cannot_create_directory(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::CannotCreateDirectory { - path: path.to_path_buf(), - err, + pub fn cannot_create_directory(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::CannotCreateDirectory { + path: path.to_path_buf(), + err, + }) } } - pub fn cannot_access(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::CannotAccess { - path: path.to_path_buf(), - err, + pub fn cannot_access(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::CannotAccess { + path: path.to_path_buf(), + err, + }) } } #[cfg(unix)] - pub fn error_writing(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::ErrorWriting { - path: path.to_path_buf(), - err, + pub fn error_writing(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::ErrorWriting { + path: path.to_path_buf(), + err, + }) } } - pub fn cannot_remove(path: &Path) -> impl FnOnce(io::Error) -> Self + '_ { - move |err| Self::CannotRemove { - path: path.to_path_buf(), - err, + pub fn cannot_remove(path: &Path) -> impl FnOnce(io::Error) -> Box + '_ { + move |err| { + Box::new(Self::CannotRemove { + path: path.to_path_buf(), + err, + }) } } diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index e39155b734b..3437a1e2dc7 100644 --- a/src/uu/mv/src/mv.rs +++ b/src/uu/mv/src/mv.rs @@ -71,7 +71,7 @@ use uucore::update_control; pub use uucore::{backup_control::BackupMode, update_control::UpdateMode}; use uucore::{format_usage, prompt_yes, show}; -use crate::error::{MvError, RenameError}; +use crate::error::{MvError, RenameError, RenameResult}; /// Options contains all the possible behaviors and flags for mv. /// @@ -777,7 +777,7 @@ fn move_files_into_dir(files: &[PathBuf], target_dir: &Path, options: &Options) hardlink_params.0, hardlink_params.1, ) { - Err(RenameError::PromptDeclined) => set_exit_code(1), + Err(e) if matches!(*e, RenameError::PromptDeclined) => set_exit_code(1), Err(e) => { let uerr = e.into_uerror(sourcepath, &targetpath); if let Some(ref pb) = display_manager { @@ -806,7 +806,7 @@ fn rename( #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, #[cfg(not(unix))] _hardlink_tracker: Option<()>, #[cfg(not(unix))] _hardlink_scanner: Option<()>, -) -> Result<(), RenameError> { +) -> RenameResult { let mut backup_path = None; // The destination entry itself is replaced, so look at it without @@ -953,25 +953,20 @@ fn rename_with_fallback( #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, #[cfg(not(unix))] _hardlink_tracker: Option<()>, #[cfg(not(unix))] _hardlink_scanner: Option<()>, -) -> Result<(), RenameError> { - fs::rename(from, to) - .map_err(RenameError::Io) - .or_else(|err| { +) -> RenameResult { + match fs::rename(from, to) { + Ok(()) => Ok(()), + Err(io_err) => { // We will only copy if: // 1. Files are on different devices (CrossesDevices / EXDEV error) // 2. On Windows, if the target file exists and source file is opened by another process // (MoveFileExW fails with "Access Denied" even if the source file has FILE_SHARE_DELETE permission) - let should_fallback = match &err { - RenameError::Io(io_err) => { - io_err.kind() == io::ErrorKind::CrossesDevices - || (io_err.kind() == io::ErrorKind::PermissionDenied - && from.is_file() - && can_delete_file(from)) - } - _ => false, - }; + let should_fallback = io_err.kind() == io::ErrorKind::CrossesDevices + || (io_err.kind() == io::ErrorKind::PermissionDenied + && from.is_file() + && can_delete_file(from)); if !should_fallback { - return Err(err); + return Err(io_err.into()); } // Get metadata without following symlinks let metadata = from.symlink_metadata()?; @@ -1018,12 +1013,13 @@ fn rename_with_fallback( rename_file_fallback(from, to) } } - }) + } + } } /// Replace the destination with a new pipe with the same name as the source. #[cfg(unix)] -fn rename_fifo_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { +fn rename_fifo_fallback(from: &Path, to: &Path) -> RenameResult { if to.try_exists()? { match fs::remove_file(to) { Ok(()) => {} @@ -1033,7 +1029,7 @@ fn rename_fifo_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { } // rustix::fs::mkfifoat is linux only nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)) - .map_err(|e| RenameError::Io(e.into()))?; + .map_err(|e| Box::new(RenameError::Io(e.into())))?; fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; Ok(()) } @@ -1043,14 +1039,14 @@ fn rename_fifo_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { clippy::unnecessary_wraps, reason = "fn sig must match on all platforms" )] -fn rename_fifo_fallback(_from: &Path, _to: &Path) -> Result<(), RenameError> { +fn rename_fifo_fallback(_from: &Path, _to: &Path) -> RenameResult { Ok(()) } /// Move the given symlink to the given destination. On Windows, dangling /// symlinks return an error. #[cfg(unix)] -fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { +fn rename_symlink_fallback(from: &Path, to: &Path) -> RenameResult { let path_symlink_points_to = fs::read_link(from)?; // On AlreadyExists, fall through to atomic temp-and-rename so the @@ -1070,7 +1066,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { unix::fs::symlink(&path_symlink_points_to, to)?; } } - Err(e) => return Err(RenameError::Io(e)), + Err(e) => return Err(e.into()), } #[cfg(any( target_os = "freebsd", @@ -1089,7 +1085,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { Ok(()) } #[cfg(windows)] -fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { +fn rename_symlink_fallback(from: &Path, to: &Path) -> RenameResult { let path_symlink_points_to = fs::read_link(from)?; if path_symlink_points_to.exists() { if path_symlink_points_to.is_dir() { @@ -1109,7 +1105,7 @@ fn rename_symlink_fallback(from: &Path, to: &Path) -> Result<(), RenameError> { } #[cfg(target_os = "wasi")] -fn rename_symlink_fallback(_from: &Path, _to: &Path) -> Result<(), RenameError> { +fn rename_symlink_fallback(_from: &Path, _to: &Path) -> RenameResult { Err(io::Error::other(translate!("mv-error-no-symlink-support")).into()) } @@ -1120,7 +1116,7 @@ fn rename_dir_fallback( verbose: bool, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> Result<(), RenameError> { +) -> RenameResult { // We remove the destination directory if it exists to match the // behavior of `fs::rename`. if to.exists() { @@ -1212,17 +1208,17 @@ fn rename_dir_fallback( /// The directory starts private (0700): its real mode is applied only after its /// contents are copied, and until then, or for good if the copy fails, the /// umask-based 0755 would expose entries that a 0700 source kept hidden. -fn create_dir_fail_closed(path: &Path) -> Result<(), RenameError> { +fn create_dir_fail_closed(path: &Path) -> RenameResult { #[cfg(unix)] let created = unix::fs::DirBuilderExt::mode(&mut fs::DirBuilder::new(), 0o700).create(path); #[cfg(not(unix))] let created = fs::create_dir(path); created.map_err(|e| { if e.kind() == io::ErrorKind::AlreadyExists { - RenameError::Io(io::Error::new( + Box::new(RenameError::Io(io::Error::new( io::ErrorKind::AlreadyExists, translate!("mv-error-dest-appeared", "path" => path.quote()), - )) + ))) } else { RenameError::cannot_create_directory(path)(e) } @@ -1255,7 +1251,7 @@ fn copy_dir_contents( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> Result<(), RenameError> { +) -> RenameResult { // Create the destination directory create_dir_fail_closed(to)?; @@ -1292,7 +1288,7 @@ fn copy_dir_contents_recursive( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> Result<(), RenameError> { +) -> RenameResult { // Helper closure to print verbose messages let print_verbose = |from: &Path, to: &Path| { if verbose { @@ -1448,7 +1444,7 @@ fn copy_file_with_hardlinks_helper( to: &Path, hardlink_tracker: &mut HardlinkTracker, hardlink_scanner: &HardlinkGroupScanner, -) -> Result<(), RenameError> { +) -> RenameResult { // Check if this file should be a hardlink to an already-copied file use crate::hardlink::HardlinkOptions; let hardlink_options = HardlinkOptions::default(); @@ -1483,7 +1479,7 @@ fn copy_file_with_hardlinks_helper( } #[cfg(unix)] -fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { +fn copy_regular_file(from: &Path, to: &Path) -> RenameResult { use std::fs::Permissions; use std::os::unix::fs::{MetadataExt, PermissionsExt}; use uucore::safe_copy::{create_dest_restrictive, open_source}; @@ -1518,7 +1514,7 @@ fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { } #[cfg(not(unix))] -fn copy_regular_file(from: &Path, to: &Path) -> Result<(), RenameError> { +fn copy_regular_file(from: &Path, to: &Path) -> RenameResult { fs::copy(from, to).map_err(|err| { if from.exists() { RenameError::cannot_create_regular_file(to)(err) @@ -1534,7 +1530,7 @@ fn rename_file_fallback( to: &Path, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> Result<(), RenameError> { +) -> RenameResult { // Remove existing target file if it exists if to.is_symlink() || to.exists() { match fs::remove_file(to) { @@ -1712,9 +1708,9 @@ fn get_interactive_prompt(to: &Path, _cached_mode: Option) -> String { } /// Prompts the user for confirmation and returns an error if declined. -fn prompt_overwrite(to: &Path, cached_mode: Option) -> Result<(), RenameError> { +fn prompt_overwrite(to: &Path, cached_mode: Option) -> RenameResult { if !prompt_yes!("{}", get_interactive_prompt(to, cached_mode)) { - return Err(RenameError::PromptDeclined); + return Err(Box::new(RenameError::PromptDeclined)); } Ok(()) }