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..1becf519008 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, PathBuf}; +use uucore::display::Quotable; +use uucore::error::{FromIo, UError, USimpleError, strip_errno}; use uucore::translate; #[derive(Debug, thiserror::Error)] @@ -29,3 +32,188 @@ 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 + /// contextualized as "cannot move 'source' to 'target': {err}" or + /// "cannot overwrite 'target': Directory not empty". + #[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 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) -> 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) -> 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) -> Box + '_ { + move |err| { + Box::new(Self::CannotCreateRegularFile { + 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) -> 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) -> Box + '_ { + move |err| { + Box::new(Self::ErrorWriting { + 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, + }) + } + } + + pub fn into_uerror(self, source: &Path, target: &Path) -> Box { + match self { + Self::PromptDeclined => 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}")) + } + } + other => USimpleError::new(1, other.to_string()), + } + } +} diff --git a/src/uu/mv/src/mv.rs b/src/uu/mv/src/mv.rs index 4b042c015c8..3437a1e2dc7 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}; #[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, RenameResult}; /// 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(), @@ -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))?; } } } @@ -490,15 +492,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 +657,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 +777,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 matches!(*e, RenameError::PromptDeclined) => 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 +806,7 @@ fn rename( #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, #[cfg(not(unix))] _hardlink_tracker: Option<()>, #[cfg(not(unix))] _hardlink_scanner: Option<()>, -) -> io::Result<()> { +) -> RenameResult { let mut backup_path = None; // The destination entry itself is replaced, so look at it without @@ -840,7 +835,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 +887,8 @@ fn rename( return Err(io::Error::new( io::ErrorKind::DirectoryNotEmpty, translate!("mv-error-directory-not-empty"), - )); + ) + .into()); } } } @@ -936,10 +932,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 +944,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 +953,85 @@ 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)), - ) +) -> 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 = io_err.kind() == io::ErrorKind::CrossesDevices + || (io_err.kind() == io::ErrorKind::PermissionDenied + && from.is_file() + && can_delete_file(from)); + if !should_fallback { + return Err(io_err.into()); } - #[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) -> RenameResult { 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::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))?; - fs::remove_file(from) + nix::unistd::mkfifo(to, nix::sys::stat::Mode::from_bits_truncate(0o666)) + .map_err(|e| Box::new(RenameError::Io(e.into())))?; + fs::remove_file(from).map_err(RenameError::cannot_remove(from))?; + Ok(()) } #[cfg(not(unix))] @@ -1054,14 +1039,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) -> 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) -> io::Result<()> { +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 @@ -1073,11 +1058,15 @@ 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) + && err.kind() != io::ErrorKind::NotFound + { + return Err(RenameError::inter_device_move_failed(from, to)(err)); + } unix::fs::symlink(&path_symlink_points_to, to)?; } } - Err(e) => return Err(e), + Err(e) => return Err(e.into()), } #[cfg(any( target_os = "freebsd", @@ -1092,10 +1081,11 @@ 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(RenameError::cannot_remove(from))?; + Ok(()) } #[cfg(windows)] -fn rename_symlink_fallback(from: &Path, to: &Path) -> io::Result<()> { +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() { @@ -1103,18 +1093,20 @@ 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(RenameError::cannot_remove(from))?; + 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) -> RenameResult { + Err(io::Error::other(translate!("mv-error-no-symlink-support")).into()) } fn rename_dir_fallback( @@ -1124,11 +1116,11 @@ fn rename_dir_fallback( verbose: bool, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> io::Result<()> { +) -> RenameResult { // 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(RenameError::cannot_remove(to))?; } // Calculate total size of directory @@ -1165,7 +1157,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 +1167,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 @@ -1196,16 +1188,13 @@ fn rename_dir_fallback( 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(RenameError::cannot_remove(from))?; Ok(()) } @@ -1219,19 +1208,19 @@ 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) -> 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 { - io::Error::new( + Box::new(RenameError::Io(io::Error::new( io::ErrorKind::AlreadyExists, translate!("mv-error-dest-appeared", "path" => path.quote()), - ) + ))) } else { - e + RenameError::cannot_create_directory(path)(e) } }) } @@ -1262,7 +1251,7 @@ fn copy_dir_contents( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> io::Result<()> { +) -> RenameResult { // Create the destination directory create_dir_fail_closed(to)?; @@ -1299,7 +1288,7 @@ fn copy_dir_contents_recursive( verbose: bool, progress_bar: Option<&ProgressBar>, display_manager: Option<&MultiProgress>, -) -> io::Result<()> { +) -> RenameResult { // Helper closure to print verbose messages let print_verbose = |from: &Path, to: &Path| { if verbose { @@ -1314,10 +1303,10 @@ fn copy_dir_contents_recursive( } }; - let entries = fs::read_dir(from_dir)?; + let entries = fs::read_dir(from_dir).map_err(RenameError::cannot_access(from_dir))?; for entry in entries { - let entry = entry?; + 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); @@ -1382,7 +1371,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 +1444,7 @@ fn copy_file_with_hardlinks_helper( to: &Path, hardlink_tracker: &mut HardlinkTracker, hardlink_scanner: &HardlinkGroupScanner, -) -> io::Result<()> { +) -> RenameResult { // Check if this file should be a hardlink to an already-copied file use crate::hardlink::HardlinkOptions; let hardlink_options = HardlinkOptions::default(); @@ -1463,7 +1452,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)?; + fs::hard_link(&existing_target, to).map_err(RenameError::cannot_create_regular_file(to))?; return Ok(()); } @@ -1471,31 +1460,68 @@ 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(RenameError::cannot_access(from))? + .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::cannot_create_regular_file(to)(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) -> RenameResult { + 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(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(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", + 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) -> RenameResult { + fs::copy(from, to).map_err(|err| { + if from.exists() { + RenameError::cannot_create_regular_file(to)(err) + } else { + RenameError::cannot_open_for_reading(from)(err) + } + })?; Ok(()) } @@ -1504,16 +1530,14 @@ fn rename_file_fallback( to: &Path, #[cfg(unix)] hardlink_tracker: Option<&mut HardlinkTracker>, #[cfg(unix)] hardlink_scanner: Option<&HardlinkGroupScanner>, -) -> io::Result<()> { +) -> RenameResult { // 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::inter_device_move_failed(from, to)(err)), + } } // Check if this file is part of a hardlink group and if so, create a hardlink instead of copying @@ -1527,59 +1551,15 @@ 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(RenameError::cannot_remove(from))?; 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(RenameError::cannot_remove(from))?; Ok(()) } @@ -1728,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) -> io::Result<()> { +fn prompt_overwrite(to: &Path, cached_mode: Option) -> RenameResult { if !prompt_yes!("{}", get_interactive_prompt(to, cached_mode)) { - return Err(io::Error::other("")); + return Err(Box::new(RenameError::PromptDeclined)); } Ok(()) } diff --git a/tests/by-util/test_mv.rs b/tests/by-util/test_mv.rs index e828d29a2e2..134d8433ec8 100644 --- a/tests/by-util/test_mv.rs +++ b/tests/by-util/test_mv.rs @@ -2964,6 +2964,176 @@ fn test_mv_cross_device_permission_denied() { .expect("Unable to restore directory permissions"); } +#[cfg(target_os = "linux")] +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; + + let scene = TestScenario::new(util_name!()); + let at = &scene.fixtures; + let other_fs_tempdir = + TempDir::new_in("/dev/shm/").expect("Unable to create temp directory in /dev/shm"); + + let (src, dst, restore_path, restore_mode, expected_stderr) = + setup(at, other_fs_tempdir.path()); + + 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_source_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + + 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) + }); +} + +#[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; + + 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)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_source_directory_unwritable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + + 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)] +#[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; + + 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)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dir_file_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + + 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)] +#[test] +#[cfg(target_os = "linux")] +fn test_mv_cross_device_dir_subdir_unreadable() { + use std::fs::set_permissions; + use std::os::unix::fs::PermissionsExt; + + 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 /// 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