Avoid mkfs interactive mode extra hard 16/323616/2
authorMichal Bloch <m.bloch@samsung.com>
Wed, 30 Apr 2025 18:37:33 +0000 (20:37 +0200)
committerKarol Lewandowski <k.lewandowsk@samsung.com>
Wed, 7 May 2025 19:20:52 +0000 (21:20 +0200)
Change-Id: I9b8e12abd0dd1225bc7dc7d32fa31cf7f5588e57

src/service/src/dir_backend_fixed_size.cpp
src/service/src/os_ops.cpp
src/service/src/os_ops.hpp

index 7b13edb9b3d3ee27d30c7bf8f421696626e514b2..fde65d96ccddda9fdc00be70405d85a8e8b2c51c 100644 (file)
@@ -47,6 +47,10 @@ static void do_mkfs(const fs::path& image_path, int uid, int gid, uint64_t size_
 {
        const auto child_pid = OS::throwing_fork();
        if (child_pid == 0) {
+
+               /* Avoid interactive mode, just in case. */
+               OS::close_stdin();
+
                const auto mkfs = "/usr/sbin/mkfs.ext4"sv;
 
                /* Would ideally be std::format instead of this ugly stack,
index b45367f32328a08e2987747f8d5bb5a916f3e4a8..cca9637e3e7178bb078068b7d02df1c76b498617 100644 (file)
 #include <optional>
 #include <vector>
 
+#include <fcntl.h>
 #include <grp.h>
 #include <pwd.h>
 #include <sys/smack.h>
 #include <sys/stat.h>
 #include <sys/sysmacros.h>
+#include <sys/types.h>
 #include <sys/wait.h>
 #include <unistd.h>
 
@@ -60,6 +62,25 @@ int OS::throwing_fork()
        return child_pid;
 }
 
+void OS::close_stdin()
+{
+       /* Some programs go into "interactive" modes by looking
+        * at various traits of the input stream. Apparently we
+        * can sometimes avoid this by redirecting to /dev/null.
+        * This is largely for use with the fork-exec pattern. */
+       const int fd = open("/dev/null", O_RDONLY);
+       if (fd == -1) {
+               close(STDIN_FILENO);
+               return;
+       }
+
+       const int r = dup2(fd, STDIN_FILENO);
+       if (r == -1)
+               close(STDIN_FILENO);
+
+       close(fd);
+}
+
 void OS::throw_if_child_failed(int child_pid, std::string_view message_on_fail)
 {
        int status;
index 7c551177c6e0a563d8927565a7c49c48b0733f7f..83482e781dfb1325798932cc113c1ccf4909b59f 100644 (file)
@@ -11,6 +11,8 @@ namespace fs = std::filesystem;
 namespace OS {
        int throwing_fork();
 
+       void close_stdin();
+
        void throw_if_child_failed(int child_pid, std::string_view message_on_fail);
 
        std::string get_home_dir_by_user_id(const int uid);