add option to forward environment to pipestream
[libi2ncommon] / src / pipestream.cpp
index 7a89be2..fcd8161 100644 (file)
@@ -53,7 +53,7 @@ on this file might be covered by the GNU General Public License.
 template <typename CmdT>
 std::string capture_exec(CmdT command, ExecResult &rescode,
                          const bool out, const bool err,
-                         const bool path)
+                         const bool path, const bool env)
 {
     std::string output;
 
@@ -67,7 +67,7 @@ std::string capture_exec(CmdT command, ExecResult &rescode,
     try
     {
         {
-            inpipestream ips(command, out, err, path);
+            inpipestream ips(command, out, err, path, env);
 
             ips.store_exit_status(&exit_set, &exit_status_waitpid);
 
@@ -115,7 +115,7 @@ std::string capture_exec(CmdT command, ExecResult &rescode,
  *                    passed.
  */
 std::string capture_exec (const std::string &command, ExecResult &res)
-{ return capture_exec<const std::string &>(command, res, true, false, false); }
+{ return capture_exec<const std::string &>(command, res, true, false, false, false); }
 
 /** @brief      Instantiation of \c capture_exec for argument lists. The
  *              pipestream used to run the command will not shell out.
@@ -134,8 +134,9 @@ std::string capture_exec (const std::string &command, ExecResult &res)
  *  @returns          Captured output, combined into one string.
  */
 std::string capture_exec (const char *const *command, ExecResult &res,
-                          const bool out, const bool err, const bool path)
-{ return capture_exec<const char *const *>(command, res, out, err, path); }
+                          const bool out, const bool err, const bool path,
+                          const bool env)
+{ return capture_exec<const char *const *>(command, res, out, err, path, env); }
 
 /** @brief      Instantiation of \c capture_exec for argument lists. The
  *              pipestream used to run the command will not shell out.
@@ -153,10 +154,11 @@ std::string capture_exec (const char *const *command, ExecResult &res,
  *  @returns          Captured output, combined into one string.
  */
 std::string capture_exec (const std::vector<std::string> &command, ExecResult &res,
-                          const bool out, const bool err, const bool path)
+                          const bool out, const bool err, const bool path,
+                          const bool env)
 {
     return capture_exec<const std::vector<std::string> &>
-        (command, res, out, err, path);
+        (command, res, out, err, path, env);
 }
 
 #define PIPE_CTOR_FAIL(where) \
@@ -210,22 +212,26 @@ mk_argv (const std::vector<std::string> &command)
  *              acquire one.
  *
  *  @param fd         The open file descriptor to operate on.
+ *  @param save_errno Out parameter: stores errno here after a syscall failure.
  *
  *  @returns          \c true on success, \c false otherwise (the call to
- *                    either \c open(2) or \c dup2(2) failed).
+ *                    either \c open(2) or \c dup2(2) failed), with errno
+ *                    communicated through saved_errno.
  */
 static bool
-redirect_devnull (const int fd)
+redirect_devnull (const int fd, int &save_errno)
 {
     static int nullfd = -1;
     
     errno = 0;
     if (nullfd == -1 && (nullfd = open ("/dev/null", O_RDWR)) == -1) {
+        save_errno = errno;
         return false;
     }
 
     errno = 0;
     if (dup2 (nullfd, fd) == -1) {
+        save_errno = errno;
         return false;
     }
 
@@ -245,11 +251,14 @@ std::pair <pid_t, FILE *>
 inpipebuf::init_without_shell (const char *const *argv,
                                const bool out,
                                const bool err,
-                               const bool path) const
+                               const bool path,
+                               const bool env) const
 {
     FILE *pipeobj = NULL;
-    int pipefd [2];
+    int pipefd [2]; /* for reading output from the child */
+    int errfd  [2]; /* for determining a successful exec() */
     sigset_t oldmask, newmask;
+    char *const *envp = env ? environ : NULL;
 
     if (!out && !err) {
         errno = EINVAL;
@@ -257,8 +266,9 @@ inpipebuf::init_without_shell (const char *const *argv,
     }
 
     errno = 0;
-    if (::pipe (pipefd) == -1) {
-        PIPE_CTOR_FAIL("pipe");
+    if (   ::pipe2 (pipefd, O_CLOEXEC) == -1
+        || ::pipe2 (errfd , O_CLOEXEC) == -1) {
+        PIPE_CTOR_FAIL("pipe2");
     }
 
     sigfillset (&newmask);
@@ -274,25 +284,29 @@ inpipebuf::init_without_shell (const char *const *argv,
         }
         case 0: {
             close (pipefd [0]);
+            close (errfd  [0]);
 
+            fcntl (pipefd [1], F_SETFD, 0);
+
+            int save_errno = 0;
             if (!out) {
-                if (!redirect_devnull (STDOUT_FILENO)) {
-                    fprintf(stderr, "redirect_devnull/stdout: %m\n");
-                    /* XXX should we bail here? */
+                if (!redirect_devnull (STDOUT_FILENO, save_errno)) {
+                    (void)write (errfd [1], (char *)&save_errno, sizeof(save_errno));
+                    exit (EXIT_FAILURE);
                 }
             } else if (dup2 (pipefd[1], STDOUT_FILENO) == -1) {
-                fprintf(stderr, "dup2/stdout: %m\n");
-                exit(EXIT_FAILURE);
+                (void)write (errfd [1], (char *)&save_errno, sizeof(save_errno));
+                exit (EXIT_FAILURE);
             }
 
             if (!err) {
-                if (!redirect_devnull (STDERR_FILENO)) {
-                    fprintf(stderr, "redirect_devnull/stderr: %m\n");
-                    /* XXX should we bail here? */
+                if (!redirect_devnull (STDERR_FILENO, save_errno)) {
+                    (void)write (errfd [1], (char *)&save_errno, sizeof(save_errno));
+                    exit (EXIT_FAILURE);
                 }
             } else if (dup2 (pipefd[1], STDERR_FILENO) == -1) {
-                fprintf(stderr, "dup2/stderr: %m\n");
-                exit(EXIT_FAILURE);
+                (void)write (errfd [1], (char *)&save_errno, sizeof(save_errno));
+                exit (EXIT_FAILURE);
             }
 
             close (pipefd [1]);
@@ -301,33 +315,77 @@ inpipebuf::init_without_shell (const char *const *argv,
 
             errno = 0;
             if (path) {
-                execvpe (argv [0], const_cast <char *const *>(argv), environ);
+                execvpe (argv [0], const_cast <char *const *>(argv), envp);
             } else {
-                execve (argv [0], const_cast <char *const *>(argv), NULL);
+                execve (argv [0], const_cast <char *const *>(argv), envp);
             }
-            exit(EXIT_FAILURE);
+
+            (void)write (errfd [1], (char *)&errno, sizeof(errno));
+            exit (EXIT_FAILURE);
             break;
         }
         default: {
-            close (pipefd [1]);
-
-            sigprocmask (SIG_SETMASK, &oldmask, NULL);
-
-            errno = 0;
-            if ((pipeobj = fdopen (pipefd [0], "r")) == NULL) {
-                PIPE_CTOR_FAIL("fdopen");
-            }
             break;
         }
     }
 
+    close (pipefd [1]);
+    close (errfd  [1]);
+
+    /*
+     * Check whether the child exec()’ed by reading from the error pipe.
+     * The call to read(2) will block, uninterruptible due to signals being
+     * blocked. If all went well, the read(2) will return zero bytes and we can
+     * ditch the error channel.
+     *
+     * Otherwise either the read(2) failed or we actually received something
+     * through the error pipe. Both cases are treated as errors and cause an
+     * exit from the ctor.
+     */
+    char buf [sizeof (errno)];
+    int ret;
+    memset (buf, 0, sizeof (buf));
+    errno = 0;
+    if ((ret = read (errfd [0], buf, sizeof (buf))) != 0) {
+        close (pipefd [0]);
+        close (errfd  [0]);
+        sigprocmask (SIG_SETMASK, &oldmask, NULL);
+        if (ret == - 1) {
+            /* read(2) failed */
+            PIPE_CTOR_FAIL("read");
+        } else {
+            /*
+             * We received data on the error channel indicating the child
+             * process never successfully exec()’ed. We grab the error code
+             * from the buffer and bail.
+             */
+            errno = *((int *)&buf[0]);
+            PIPE_CTOR_FAIL("child failed to exec()");
+        }
+    }
+
+    /*
+     * read(2) yielded zero bytes; it’s safe to use the pipe so close our end
+     * and continue.
+     */
+    close (errfd [0]);
+
+    sigprocmask (SIG_SETMASK, &oldmask, NULL);
+
+    errno = 0;
+    if ((pipeobj = fdopen (pipefd [0], "r")) == NULL) {
+        close (pipefd [0]);
+        PIPE_CTOR_FAIL("fdopen");
+    }
+
     return std::make_pair (childpid, pipeobj);
 }
 
 inpipebuf::inpipebuf(const char *const *command,
                      const bool out,
                      const bool err,
-                     const bool path)
+                     const bool path,
+                     const bool env)
     : pipe (NULL) /* brr: shadowing global ident */
     , pid (-1)
     , status_set (NULL)
@@ -338,7 +396,7 @@ inpipebuf::inpipebuf(const char *const *command,
     }
 
     std::pair <pid_t, FILE *> tmp =
-        this->init_without_shell (command, out, err, path);
+        this->init_without_shell (command, out, err, path, env);
     this->pid  = tmp.first; /* no std::tie :/ */
     this->pipe = tmp.second;
 
@@ -348,7 +406,8 @@ inpipebuf::inpipebuf(const char *const *command,
 inpipebuf::inpipebuf(const std::vector<std::string> &command,
                      const bool out,
                      const bool err,
-                     const bool path)
+                     const bool path,
+                     const bool env)
     : pipe (NULL) /* brr: shadowing global ident */
     , pid (-1)
     , status_set (NULL)
@@ -364,7 +423,7 @@ inpipebuf::inpipebuf(const std::vector<std::string> &command,
     }
 
     std::pair <pid_t, FILE *> tmp =
-        this->init_without_shell (argv.get (), out, err, path);
+        this->init_without_shell (argv.get (), out, err, path, env);
     this->pid  = tmp.first;
     this->pipe = tmp.second;
 
@@ -374,7 +433,8 @@ inpipebuf::inpipebuf(const std::vector<std::string> &command,
 inpipebuf::inpipebuf(const std::string& command,
                      const bool _ignored_out,
                      const bool _ignored_err,
-                     const bool _ignored_path)
+                     const bool _ignored_path,
+                     const bool _ignored_env)
     : pid (-1)
     , status_set (NULL)
     , exit_status (NULL)