From 77a8682a6ee41a92aa1e07b557607c65e94d904b Mon Sep 17 00:00:00 2001
From: Lily Foster <lily@lily.flowers>
Date: Wed, 25 Jan 2023 18:52:06 -0500
Subject: [PATCH] fstab-generator: add SYSTEMD_SYSFS_CHECK env var

This forces processing of /dev entries in fstab when running in a
container is detected (checked as the existence of read-only /sys).

(cherry picked from commit 905dd992f8fbfe486e68808ce88e1662c970ab35)

Related: #2190226
---
 docs/ENVIRONMENT.md                   |  4 ++++
 src/fstab-generator/fstab-generator.c | 14 +++++++++++---
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.md
index 70fac2e361..f1a4692b59 100644
--- a/docs/ENVIRONMENT.md
+++ b/docs/ENVIRONMENT.md
@@ -54,6 +54,10 @@ All tools:
 * `$SYSTEMD_SYSROOT_FSTAB` — if set, use this path instead of
   `/sysroot/etc/fstab`. Only useful for debugging `systemd-fstab-generator`.
 
+* `$SYSTEMD_SYSFS_CHECK` — takes a boolean. If set, overrides sysfs container
+  detection that ignores `/dev/` entries in fstab. Only useful for debugging
+  `systemd-fstab-generator`.
+
 * `$SYSTEMD_CRYPTTAB` — if set, use this path instead of `/etc/crypttab`. Only
   useful for debugging. Currently only supported by
   `systemd-cryptsetup-generator`.
diff --git a/src/fstab-generator/fstab-generator.c b/src/fstab-generator/fstab-generator.c
index 9bf5f04d1d..bbd669e477 100644
--- a/src/fstab-generator/fstab-generator.c
+++ b/src/fstab-generator/fstab-generator.c
@@ -8,6 +8,7 @@
 #include "bus-error.h"
 #include "bus-locator.h"
 #include "chase-symlinks.h"
+#include "env-util.h"
 #include "fd-util.h"
 #include "fileio.h"
 #include "fstab-util.h"
@@ -650,7 +651,7 @@ static int parse_fstab(bool initrd) {
         _cleanup_endmntent_ FILE *f = NULL;
         const char *fstab;
         struct mntent *me;
-        int r = 0;
+        int r = 0, sysfs_check = -1;
 
         if (initrd)
                 fstab = sysroot_fstab_path();
@@ -688,8 +689,15 @@ static int parse_fstab(bool initrd) {
                                 continue;
                         }
 
-                        if (is_device_path(what)) {
-                                log_info("Running in a container, ignoring fstab device entry for %s.", what);
+                        if (sysfs_check < 0) {
+                                r = getenv_bool_secure("SYSTEMD_SYSFS_CHECK");
+                                if (r < 0 && r != -ENXIO)
+                                        log_debug_errno(r, "Failed to parse $SYSTEMD_SYSFS_CHECK, ignoring: %m");
+                                sysfs_check = r != 0;
+                        }
+
+                        if (sysfs_check && is_device_path(what)) {
+                                log_info("/sys/ is read-only (running in a container?), ignoring fstab device entry for %s.", what);
                                 continue;
                         }
                 }