On 2024-04-25 11:44:17+0000, Rasmus Villemoes wrote: > Currently, there is no way for shell scripts to safely access > resources protected by POSIX locking (fcntl with the F_SETLK/F_SETLKW > commands). For example, the glibc function lckpwdf(), used to > protect access to the /etc/shadow database, works by taking a > F_SETLKW on /etc/.pwd.lock . > > Due to the odd semantics of POSIX locking (e.g. released when any file > descriptor associated to the inode is closed), we cannot usefully > directly expose the POSIX F_SETLK/F_SETLKW commands. However, linux > 3.15 introduced F_OFD_SETLK[W], with semantics wrt. ownership and > release better matching those of flock(2), and crucially they do > conflict with locks obtained via F_SETLK[W]. With this, a shell script > can do > > exec 4> /etc/.pwd.lock > flock --fcntl 4 > <access/modify /etc/shadow ...> > flock --fcntl --unlock 4 # or just exit > > without conflicting with passwd(1) or other utilities that > access/modify /etc/shadow. > > No single-letter shorthand is defined for the option, because this is > somewhat low-level and the user really needs to know what he is doing. > > Also, this leaves the door open for teaching --fcntl to accept an > optional argument: "ofd", the default, and "posix", should anyone find > a use for flock(1) taking a F_SETLK[W] lock. > > Signed-off-by: Rasmus Villemoes <rasmus.villemoes@xxxxxxxxx> > --- > v3: > > - Replace configure-time checking for F_OFD_ by just hard-coding the > proper values in flock.c if the system headers don't provide them. > > - Consequently, drop all HAVE_FCNTL_OFD_LOCKS guards. > > v2: > > - Shorten option name to --fcntl instead of --fcntl-ofd. > > - Use a do_lock() helper function switching on the API to use, making > the while () condition easier to read and making it simpler to add > the mentioned --fcntl=posix should the need arise. > > - Fix up places that need HAVE_FCNTL_OFD_LOCKS guarding. > > sys-utils/flock.c | 78 +++++++++++++++++++++++++++++++++++++++++++++-- Some testcases in tests/ts/misc/flock would be nice. > 1 file changed, 76 insertions(+), 2 deletions(-) > > diff --git a/sys-utils/flock.c b/sys-utils/flock.c [..]