Subject: bug#65599: mv and cp give a pointless warning when moving/copying a directory

From: Bruno Haible <[email-masked]>
Date: Tue, 29 Aug 2023 20:20:02 +0200

When I move a directory from an ext4 file system to a CIFS v1 file system,
I get a diagnostic
  mv: failed to preserve ownership for '...': Permission denied
although the owner and group of the directory after and before the move
are the same. So, there is actually nothing to warn about.

$ mv --version
mv (GNU coreutils) 9.3.147-d553ab
Copyright (C) 2023 Free Software Foundation, Inc.
...

$ mkdir dir1
$ echo foo > dir1/file1
$ ls -ld dir1
drwxrwxr-x 2 bruno bruno 4096 Aug 26 19:38 dir1
$ strace -o /tmp/mv.log mv dir1 /media/nas/bruno/dir1
mv: failed to preserve ownership for '/media/nas/bruno/dir1': Permission denied
$ echo $?
0
$ ls -ld /media/nas/bruno/dir1
drwxrwxr-x 2 bruno bruno 0 Aug 26 19:38 /media/nas/bruno/dir1

Find attached the strace log file. The essential line is
fchownat(AT_FDCWD, "/media/nas/bruno/dir1", 1000, 1000, AT_SYMLINK_NOFOLLOW) = -1 EACCES (Permission denied)

People say that "chown only works for root anyway" [1], but it's certainly
safer to try the chown nevertheless, because
  - the current user might not be root but might have non-standard capabilities.
  - the target file system may be reporting failure but may do the requested
    action nevertheless,
  - the target file system might map uids (think of NFS or CIFS [2]).

However, the diagnostic should be omitted if the 'mv' program can verify
that the uid and gid of the directory on the target file system is the same
as on the source file system.

Likewise for the 'cp' program:

$ cp --version
cp (GNU coreutils) 9.3.147-d553ab
...

Written by Torbjorn Granlund, David MacKenzie, and Jim Meyering.
$ mkdir dir2
$ echo foo > dir2/file2
$ ls -ld dir2
drwxrwxr-x 2 bruno bruno 4096 Aug 29 20:15 dir2
$ strace -o /tmp/cp.log cp dir2 /media/nas/bruno/dir2
$ strace -o /tmp/cp.log cp -a dir2 /media/nas/bruno/dir2
cp: failed to preserve ownership for '/media/nas/bruno/dir2': Permission denied
$ ls -ld /media/nas/bruno/dir2
drwx------ 2 bruno bruno 0 Aug 29 20:15 /media/nas/bruno/dir2

Here, in cp.log, the essential line is:
fchownat(AT_FDCWD, "/media/nas/bruno/dir2", 1000, 1000, AT_SYMLINK_NOFOLLOW) = -1 EACCES (Permission denied)

Bruno

[1] https://lists.gnu.org/archive/html/emacs-devel/2009-10/msg00094.html
[2] https://linux.die.net/man/8/mount.cifs