[svn:qpsmtpd] rev 524 - branches/0.31

[email protected] 29 Jul 2005 06:42:01 -0000
Newsgroups perl.cvs.qpsmtpd
Message-ID <[email protected]>
Author: aqua
Date: Thu Jul 28 23:42:00 2005
New Revision: 524

Modified:
   branches/0.31/qpsmtpd-forkserver
Log:
Add --detach commandline option to forkserver; if supplied, daemonize just
prior to entering the main accept loop.

Split handling of --pid-file so that preexisting pid files are dealt with and
the file is opened before priveleges are dropped, but the writing out of the
new file happens after dropping privs and (if applicable) forking the
daemonized process, so the correct PID is recorded.


Modified: branches/0.31/qpsmtpd-forkserver
==============================================================================
--- branches/0.31/qpsmtpd-forkserver	(original)
+++ branches/0.31/qpsmtpd-forkserver	Thu Jul 28 23:42:00 2005
@@ -24,6 +24,7 @@ my @LOCALADDR;                       # i
 my $USER      = 'smtpd';             # user to suid to
 my $MAXCONNIP = 5;                   # max simultaneous connections from one IP
 my $PID_FILE   = '';
+my $DETACH;                          # daemonize on startup
 
 sub usage {
         print <<"EOT";
@@ -36,6 +37,7 @@ usage: qpsmtpd-forkserver [ options ]
  -u, --user U              : run as a particular user (default 'smtpd')
  -m, --max-from-ip M       : limit connections from a single IP; default 5
      --pid-file P          : print main servers PID to file P
+ -d, --detach              : detach from controlling terminal (daemonize)
 EOT
         exit 0;
 }
@@ -47,6 +49,7 @@ GetOptions('h|help' => \&usage,
            'p|port=i' => \$PORT,
            'u|user=s' => \$USER,
            'pid-file=s' => \$PID_FILE,
+           'd|detach' => \$DETACH,
 	  ) || &usage;
 
 # detaint the commandline
@@ -119,8 +122,6 @@ if ($PID_FILE) {
     open PID, ">$PID_FILE"
       or die "open pid_file: $!\n";
   }
-  print PID $$,"\n";
-  close PID;
 }
 
 # Load plugins here
@@ -151,6 +152,20 @@ $> = $quid;
 	', group '.
 	(getgrgid($)) || $)));
 
+if ($DETACH) {
+  open STDIN, '/dev/null' or die "/dev/null: $!";
+  open STDOUT, '>/dev/null' or die "/dev/null: $!";
+  open STDERR, '>&STDOUT' or die "open(stderr): $!";
+  defined (my $pid = fork) or die "fork: $!";
+  exit 0 if $pid;
+  POSIX::setsid or die "setsid: $!";
+}
+
+if ($PID_FILE) {
+  print PID $$,"\n";
+  close PID;
+}
+
 while (1) {
   REAPER();
   my $running = scalar keys %childstatus;