chiark / gitweb /
stat-util: unify code that checks whether something is a regular file
authorLennart Poettering <lennart@poettering.net>
Mon, 19 Feb 2018 17:01:05 +0000 (18:01 +0100)
committerSven Eden <yamakuzure@gmx.net>
Wed, 30 May 2018 05:58:59 +0000 (07:58 +0200)
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.

src/basic/stat-util.c
src/basic/stat-util.h

index 270e80feec731db7623ceb0ffff2c0721bc772c0..313ed4f2c84769f2175590ab5950eec42e038ea5 100644 (file)
@@ -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);
+}
index 6e42731d99285223a749e9af9fd12a29ec1554f5..cc21ba2aa780f7f120384b4c10709cf09e7edd23 100644 (file)
@@ -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);