Subject: bug#39236: [musl] coreutils cp mishandles error return from lchmod

From: Paul Eggert <[email-masked]>
Date: Wed, 22 Jan 2020 13:55:57 -0800

On 1/22/20 7:08 AM, Florian Weimer wrote:
> I think you misread what I wrote: lchmod*always*  returns ENOSYS.  Even
> if the file is not a symbolic link.  Likewise, fchmodat with
> AT_SYMLINK_NOFOLLOW *always* returns ENOTSUP.

That's too bad, because coreutils (and many other applications, I 
expect) assume that lchmod (and fchmodat with AT_SYMLINK_NOFOLLOW) to 
act like chmod except not follow symlinks, in order to make it less 
likely that the application will run afoul of a symlink race and chmod 
the wrong file. Isn't that how the Linux fstatat call behaves? And if 
so, why does glibc fstatat refuse to support this behavior?

To work around this bug, I suppose coreutils etc. should do something 
like the following:

1. Never use lchmod since the porting nightmare is bad enough without it.

2. On non-glibc systems (or glibc systems where the bug is fixed), use 
fchmodat with AT_SYMLINK_NOFOLLOW.

3. On glibc systems with the bug, use openat with AT_SYMLINK_NOFOLLOW 
and O_PATH, and then fchmod the resulting file descriptor.

Does this sound right? Or is there some O_PATH gotcha that I haven't 
thought about?

Come to think of it, perhaps the best thing would be to change Gnulib's 
lchmod and fchmodat modules so that they do what applications expect, 
even on buggy glibc systems. (Which would be ironic, since Gnulib's main 
goal is to put wrappers around other libraries so that they look more 
like glibc.)