From: Lennart Poettering Date: Mon, 19 Feb 2018 17:01:05 +0000 (+0100) Subject: stat-util: unify code that checks whether something is a regular file X-Git-Url: http://www.chiark.greenend.org.uk/ucgi/~ianmdlvl/git?a=commitdiff_plain;h=a9f82387ce656c98cad320372002eee70369fdb4;p=elogind.git stat-util: unify code that checks whether something is a regular file Let's add a common implementation for regular file checks, that are careful to return the right error code (EISDIR/EISLNK/EBADFD) when we are encountering a wrong file node. --- diff --git a/src/basic/stat-util.c b/src/basic/stat-util.c index 270e80fee..313ed4f2c 100644 --- a/src/basic/stat-util.c +++ b/src/basic/stat-util.c @@ -281,3 +281,32 @@ int path_is_temporary_fs(const char *path) { return fd_is_temporary_fs(fd); } #endif // 0 + +int stat_verify_regular(const struct stat *st) { + assert(st); + + /* Checks whether the specified stat() structure refers to a regular file. If not returns an appropriate error + * code. */ + + if (S_ISDIR(st->st_mode)) + return -EISDIR; + + if (S_ISLNK(st->st_mode)) + return -ELOOP; + + if (!S_ISREG(st->st_mode)) + return -EBADFD; + + return 0; +} + +int fd_verify_regular(int fd) { + struct stat st; + + assert(fd >= 0); + + if (fstat(fd, &st) < 0) + return -errno; + + return stat_verify_regular(&st); +} diff --git a/src/basic/stat-util.h b/src/basic/stat-util.h index 6e42731d9..cc21ba2aa 100644 --- a/src/basic/stat-util.h +++ b/src/basic/stat-util.h @@ -87,3 +87,6 @@ int path_is_temporary_fs(const char *path); * signed/unsigned comparison, because the magic can be 32 bit unsigned. */ #define F_TYPE_EQUAL(a, b) (a == (typeof(a)) b) + +int stat_verify_regular(const struct stat *st); +int fd_verify_regular(int fd);