From: Fabian Keil <fk@fabiankeil.de>
Date: Sat, 26 Dec 2009 11:34:01 +0000 (+0000)
Subject: When in daemon mode, bind fd 0, 1 and 2 to /dev/null.
X-Git-Tag: v_3_0_16~96
X-Git-Url: http://www.privoxy.org/gitweb/%22https:/@default-cgi@/faq/static/developer-manual/@default-cgi@show-url-info?a=commitdiff_plain;h=6bfe4c4632ff644bc1ab4676594ba18b0fe2b2fa;p=privoxy.git

When in daemon mode, bind fd 0, 1 and 2 to /dev/null.
---

diff --git a/errlog.c b/errlog.c
index 2455d237..ca2a4e58 100644
--- a/errlog.c
+++ b/errlog.c
@@ -1,4 +1,4 @@
-const char errlog_rcs[] = "$Id: errlog.c,v 1.97 2009/06/14 15:59:56 fabiankeil Exp $";
+const char errlog_rcs[] = "$Id: errlog.c,v 1.98 2009/07/08 23:18:05 ler762 Exp $";
 /*********************************************************************
  *
  * File        :  $Source: /cvsroot/ijbswa/current/errlog.c,v $
@@ -342,6 +342,21 @@ void init_error_log(const char *prog_name, const char *logfname)
    {
       fclose(logfp);
    }
+#ifdef unix
+   if (!no_daemon && (logfp == stderr))
+   {
+      if (dup2(1, 2) == -1)
+      {
+         /*
+          * We only use fatal_error() to clear the pid
+          * file and to exit. Given that stderr has just
+          * been closed, the user will not see the error
+          * message.
+          */
+         fatal_error("Failed to reserve fd 2.");
+      }
+   }
+#endif
    logfp = fp;
    unlock_logfile();
 
diff --git a/jcc.c b/jcc.c
index 048a3f4a..d17bce32 100644
--- a/jcc.c
+++ b/jcc.c
@@ -1,4 +1,4 @@
-const char jcc_rcs[] = "$Id: jcc.c,v 1.306 2009/12/22 13:04:10 fabiankeil Exp $";
+const char jcc_rcs[] = "$Id: jcc.c,v 1.307 2009/12/26 11:32:54 fabiankeil Exp $";
 /*********************************************************************
  *
  * File        :  $Source: /cvsroot/ijbswa/current/jcc.c,v $
@@ -3121,6 +3121,8 @@ int main(int argc, char **argv)
 
    if (!no_daemon)
    {
+      int fd;
+
       pid  = fork();
 
       if ( pid < 0 ) /* error */
@@ -3152,9 +3154,36 @@ int main(int argc, char **argv)
        * stderr (fd 2) will be closed later on,
        * when the config file has been parsed.
        */
+      close(0);
+      close(1);
+
+      /*
+       * Reserve fd 0 and 1 to prevent abort() and friends
+       * from sending stuff to the clients or servers.
+       */
+      fd = open("/dev/null", O_RDONLY);
+      if (fd > 0)
+      {
+         if (dup2(fd, 0) == -1)
+         {
+            log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 0: %E");
+         }
+         close(fd);
+         fd = open("/dev/null", O_WRONLY);
+         if ((fd >= 0) && (fd != 1))
+         {
+            if (dup2(fd, 1) == -1)
+            {
+               log_error(LOG_LEVEL_FATAL, "Failed to reserve fd 1: %E");
+            }
+            close(fd);
+         }
+      }
+      if (fd == -1)
+      {
+         log_error(LOG_LEVEL_FATAL, "Failed to open /dev/null: %E");
+      }
 
-      close( 0 );
-      close( 1 );
       chdir("/");
 
    } /* -END- if (!no_daemon) */