From: Christian Goeschel Ndjomouo Date: Tue, 25 Nov 2025 04:26:48 +0000 (-0500) Subject: include: add helper routines for opening and validating pidfds X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=bf7166be215a473852204f74f62d3862b66d9b52;p=thirdparty%2Futil-linux.git include: add helper routines for opening and validating pidfds With the new ul_get_valid_pidfd_or_err() routine util-linux tools can now simply validate pidfd inode numbers before opening a file descriptor for a given PID. Signed-off-by: Christian Goeschel Ndjomouo --- diff --git a/include/pidfd-utils.h b/include/pidfd-utils.h index 08627ca8d..1b9f4dc4f 100644 --- a/include/pidfd-utils.h +++ b/include/pidfd-utils.h @@ -94,4 +94,6 @@ static inline int pidfd_getfd(int pidfd __attribute__((unused)), } #endif +int ul_get_valid_pidfd_or_err(pid_t pid, ino_t pfd_ino); + #endif /* UTIL_LINUX_PIDFD_UTILS */ diff --git a/lib/Makemodule.am b/lib/Makemodule.am index 1d598faa2..aeab09f76 100644 --- a/lib/Makemodule.am +++ b/lib/Makemodule.am @@ -34,6 +34,7 @@ libcommon_la_SOURCES = \ lib/netaddrq.c \ lib/netlink.c \ lib/pidutils.c \ + lib/pidfd-utils.c \ lib/pwdutils.c \ lib/randutils.c \ lib/sha1.c \ diff --git a/lib/meson.build b/lib/meson.build index cb35ecbd6..db871913d 100644 --- a/lib/meson.build +++ b/lib/meson.build @@ -20,6 +20,7 @@ lib_common_sources = ''' netaddrq.c netlink.c pidutils.c + pidfd-utils.c procfs.c pwdutils.c randutils.c diff --git a/lib/pidfd-utils.c b/lib/pidfd-utils.c new file mode 100644 index 000000000..a0cc16953 --- /dev/null +++ b/lib/pidfd-utils.c @@ -0,0 +1,54 @@ +/* + * No copyright is claimed. This code is in the public domain; do with + * it what you wish. + * + * Authors: Christian Goeschel Ndjomouo [2025] + */ +#include +#include +#include +#include +#include + +#include "c.h" +#include "nls.h" +#include "strutils.h" +#include "pidfd-utils.h" + +/* + * ul_get_valid_pidfd_or_err() - Return a valid file descriptor for a PID + * or exit the process with an error message. + * + * @pid: PID number for which to get a file descriptor + * @pfd_ino: A pidfd inode number that is expected to be the + * same as for the new file descriptor. + * + * Pass @pfd_ino as NULL, if the pidfd should not be validated. + * + * Return: On success, a file descriptor is returned. + * On failure, err() or errx() is called to + * print an error message and kill the program. + * + */ +int ul_get_valid_pidfd_or_err(pid_t pid, ino_t pfd_ino) +{ + int pfd, rc; + struct stat f; + + pfd = pidfd_open(pid, 0); + if (pfd < 0) + err(EXIT_FAILURE, _("pidfd_open() failed")); + + if (pfd_ino) { + rc = fstat(pfd, &f); + if (rc < 0) + err(EXIT_FAILURE, _("failed to fstat() pidfd")); + + if (f.st_ino != pfd_ino) { + close(pfd); + errx(EXIT_FAILURE, _("pidfd inode %"PRIu64" not found for pid %d"), + pfd_ino, pid); + } + } + return pfd; +} \ No newline at end of file