From: Yu Watanabe Date: Thu, 15 Feb 2024 10:16:36 +0000 (+0900) Subject: stat-util: introduce {stat,fd}_verify_linked() X-Git-Tag: v256-rc1~835^2~4 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=a6d0cf939c6aa7c7133122b62e3dd0048bb32e34;p=thirdparty%2Fsystemd.git stat-util: introduce {stat,fd}_verify_linked() --- diff --git a/src/basic/stat-util.c b/src/basic/stat-util.c index b42af71ce10..6a8ec1ba2a7 100644 --- a/src/basic/stat-util.c +++ b/src/basic/stat-util.c @@ -260,6 +260,26 @@ int path_is_network_fs(const char *path) { return is_network_fs(&s); } +int stat_verify_linked(const struct stat *st) { + assert(st); + + if (st->st_nlink <= 0) + return -EIDRM; /* recognizable error. */ + + return 0; +} + +int fd_verify_linked(int fd) { + struct stat st; + + assert(fd >= 0); + + if (fstat(fd, &st) < 0) + return -errno; + + return stat_verify_linked(&st); +} + int stat_verify_regular(const struct stat *st) { assert(st); diff --git a/src/basic/stat-util.h b/src/basic/stat-util.h index dc11a85f626..bab54153572 100644 --- a/src/basic/stat-util.h +++ b/src/basic/stat-util.h @@ -72,6 +72,9 @@ int path_is_network_fs(const char *path); */ #define F_TYPE_EQUAL(a, b) (a == (typeof(a)) b) +int stat_verify_linked(const struct stat *st); +int fd_verify_linked(int fd); + int stat_verify_regular(const struct stat *st); int fd_verify_regular(int fd); int verify_regular_at(int dir_fd, const char *path, bool follow); diff --git a/src/test/test-stat-util.c b/src/test/test-stat-util.c index 3fc83fc043f..272cd4c0d34 100644 --- a/src/test/test-stat-util.c +++ b/src/test/test-stat-util.c @@ -195,6 +195,25 @@ TEST(inode_type_from_string) { assert_se(inode_type_from_string(inode_type_to_string(*m)) == *m); } +TEST(fd_verify_linked) { + _cleanup_(rm_rf_physical_and_freep) char *t = NULL; + _cleanup_close_ int tfd = -EBADF, fd = -EBADF; + _cleanup_free_ char *p = NULL; + + tfd = mkdtemp_open(NULL, O_PATH, &t); + assert_se(tfd >= 0); + + assert_se(p = path_join(t, "hoge")); + assert_se(touch(p) >= 0); + + fd = open(p, O_CLOEXEC | O_PATH); + assert_se(fd >= 0); + + assert_se(fd_verify_linked(fd) >= 0); + assert_se(unlinkat(tfd, "hoge", 0) >= 0); + assert_se(fd_verify_linked(fd) == -EIDRM); +} + static int intro(void) { log_show_color(true); return EXIT_SUCCESS;