9fc0f6
From b6fbffe3d4a9435cc8560ee0271c7e6e763e89c1 Mon Sep 17 00:00:00 2001
9fc0f6
From: Harald Hoyer <harald@redhat.com>
9fc0f6
Date: Thu, 6 Mar 2014 09:12:57 +0100
9fc0f6
Subject: [PATCH] util: add files_same() helper function
9fc0f6
9fc0f6
files_same() returns
9fc0f6
     1, if the files are the same
9fc0f6
     0, if the files have different inode/dev numbers
9fc0f6
 errno, for any stat error
9fc0f6
9fc0f6
 (cherry picked from commit 9d9951a460a90ef0e1e0384742cefdcf85193f8c)
9fc0f6
9fc0f6
 Related: #1111199
9fc0f6
---
9fc0f6
 src/shared/util.c | 24 ++++++++++++++++--------
9fc0f6
 src/shared/util.h |  2 ++
9fc0f6
 2 files changed, 18 insertions(+), 8 deletions(-)
9fc0f6
9fc0f6
diff --git a/src/shared/util.c b/src/shared/util.c
9fc0f6
index 2974c2a..fb1e6d1 100644
9fc0f6
--- a/src/shared/util.c
9fc0f6
+++ b/src/shared/util.c
9fc0f6
@@ -3311,19 +3311,27 @@ bool on_tty(void) {
9fc0f6
         return cached_on_tty;
9fc0f6
 }
9fc0f6
 
9fc0f6
-int running_in_chroot(void) {
9fc0f6
-        struct stat a = {}, b = {};
9fc0f6
+int files_same(const char *filea, const char *fileb) {
9fc0f6
+        struct stat a, b;
9fc0f6
 
9fc0f6
-        /* Only works as root */
9fc0f6
-        if (stat("/proc/1/root", &a) < 0)
9fc0f6
+        if (stat(filea, &a) < 0)
9fc0f6
                 return -errno;
9fc0f6
 
9fc0f6
-        if (stat("/", &b) < 0)
9fc0f6
+        if (stat(fileb, &b) < 0)
9fc0f6
                 return -errno;
9fc0f6
 
9fc0f6
-        return
9fc0f6
-                a.st_dev != b.st_dev ||
9fc0f6
-                a.st_ino != b.st_ino;
9fc0f6
+        return a.st_dev == b.st_dev &&
9fc0f6
+               a.st_ino == b.st_ino;
9fc0f6
+}
9fc0f6
+
9fc0f6
+int running_in_chroot(void) {
9fc0f6
+        int ret;
9fc0f6
+
9fc0f6
+        ret = files_same("/proc/1/root", "/");
9fc0f6
+        if (ret < 0)
9fc0f6
+                return ret;
9fc0f6
+
9fc0f6
+        return ret == 0;
9fc0f6
 }
9fc0f6
 
9fc0f6
 char *ellipsize_mem(const char *s, size_t old_length, size_t new_length, unsigned percent) {
9fc0f6
diff --git a/src/shared/util.h b/src/shared/util.h
9fc0f6
index e577ef0..631a385 100644
9fc0f6
--- a/src/shared/util.h
9fc0f6
+++ b/src/shared/util.h
9fc0f6
@@ -403,6 +403,8 @@ static inline const char *ansi_highlight_off(void) {
9fc0f6
         return on_tty() ? ANSI_HIGHLIGHT_OFF : "";
9fc0f6
 }
9fc0f6
 
9fc0f6
+int files_same(const char *filea, const char *fileb);
9fc0f6
+
9fc0f6
 int running_in_chroot(void);
9fc0f6
 
9fc0f6
 char *ellipsize(const char *s, size_t length, unsigned percent);