On 23/04/2024 14.08, 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> > --- > 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. Hm, actually, since the values of F_OFD_ are the same across all architectures, and the API is pretty old already, I think it would be simpler to just drop the configure time probing and all the HAVE_ guards, and simply add five lines #ifndef F_OFD_GETLK #define F_OFD_GETLK 36 #define F_OFD_SETLK 37 #define F_OFD_SETLKW 38 #endif after the #include s. After all, whether or not the constants are in the headers util-linux is being built against doesn't really say whether the kernel it ends up being run on has support or not. Then I'll just include a note in the documentation that use of --fcntl only works on kernels >= 3.14 (besides, it would be really cumbersome, maybe even impossible, to have the man page not mention --fcntl even if flock was built without that option in its --help output). Rasmus