Commit 5a79e104 5a79e104e2b745587db5532ec730d1c99384d111 by Alain Magloire

Most daemon will share the same code to daemonize(), we use

	a generic one, lib/daemon.c, so any bug fix will impact the
	others and reduce maintainance/duplication.

	* lib/Makefile.am: Addition daemon.c
	* lib/daemon.c: New file.
	* pop3d/pop3d.c (pop3d_daemon_init): Use lib/daemon.c:daemon() code
	instead.
	* imap4d/imap4d.c (imap4d_daemon_init): Use lib/daemon.c:daemon code
	instead.
	* comstat/comstat.c (comstat_daemon_init): Use lib/daemon.c:daemon code
	instead. Remove trailing spaces.
1 parent 97f85b62
2001-11-11 Alain Magloire
Most daemon will share the same code to daemonize(), we use
a generic one, lib/daemon.c, so any bug fix will impact the
others and reduce maintainance/duplication.
* lib/Makefile.am: Addition daemon.c
* lib/daemon.c: New file.
* pop3d/pop3d.c (pop3d_daemon_init): Use lib/daemon.c:daemon() code
instead.
* imap4d/imap4d.c (imap4d_daemon_init): Use lib/daemon.c:daemon code
instead.
* comstat/comstat.c (comstat_daemon_init): Use lib/daemon.c:daemon code
instead. Remove trailing spaces.
2001-11-11 Sergey Poznyakoff
* comsat/action.c: (new) User-defined actions for comsat.
......
......@@ -21,7 +21,7 @@
#ifndef PATH_DEV
# define PATH_DEV "/dev"
#endif
#endif
#ifndef PATH_TTY_PFX
# define PATH_TTY_PFX PATH_DEV
#endif
......@@ -96,7 +96,7 @@ main(int argc, char **argv)
{
int c;
char *config_file = NULL;
while ((c = getopt_long (argc, argv, short_options, long_options, NULL))
!= -1)
{
......@@ -171,7 +171,7 @@ sig_hup (int sig)
syslog (LOG_ERR, "can't restart: not started with absolute pathname");
else
execvp (xargv[0], xargv);
signal (sig, sig_hup);
}
......@@ -185,7 +185,7 @@ comsat_init ()
list_append (bookie, path_record);
gethostname (hostname, sizeof hostname);
/* Set signal handlers */
signal (SIGTTOU, SIG_IGN);
signal (SIGCHLD, SIG_IGN);
......@@ -196,46 +196,15 @@ comsat_init ()
static void
comsat_daemon_init (void)
{
pid_t pid;
pid = fork ();
if (pid == -1)
{
perror ("fork failed:");
exit (EXIT_FAILURE);
}
else if (pid > 0)
exit (EXIT_SUCCESS); /* Parent exits. */
/* Child: */
signal (SIGHUP, sig_hup);
extern int daemon (int, int);
setsid (); /* Become session leader. */
/* The second fork is to guarantee that the daemon cannot acquire a
controlling terminal. */
pid = fork ();
if (pid == -1)
/* Become a daemon. Take care to close inherited fds and to hold
first three one, in, out, err. Do not do the chdir("/"). */
if (daemon (1, 0) < 0)
{
perror("fork failed");
perror ("failed to become a daemon:");
exit (EXIT_FAILURE);
}
else if (pid > 0)
exit (EXIT_SUCCESS); /* Parent exits. */
/* Close inherited file descriptors. */
{
size_t i, fdmax;
#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
fdmax = sysconf(_SC_OPEN_MAX);
#elif defined(HAVE_GETDTABLESIZE)
fdmax = getdtablesize ();*/
#else
fdmax = 64;
#endif
for (i = 0; i < fdmax; ++i)
close (i);
}
}
unsigned maxrequests = 16; /* Maximum number of request allowed per
......@@ -256,14 +225,14 @@ comsat_daemon (int port)
unsigned overflow_count = 0; /* Number of overflows achieved during
the current interval */
time_t now;
fd = socket (AF_INET, SOCK_DGRAM, 0);
if (fd == -1)
{
syslog (LOG_CRIT, "socket: %m");
exit (1);
}
memset (&local_sin, 0, sizeof local_sin);
local_sin.sin_family = AF_INET;
local_sin.sin_addr.s_addr = INADDR_ANY; /*FIXME*/
......@@ -276,13 +245,13 @@ comsat_daemon (int port)
}
syslog (LOG_NOTICE, "GNU comsat started");
last_request_time = last_overflow_time = time (NULL);
while (1)
{
fd_set fdset;
int rc;
FD_ZERO (&fdset);
FD_SET (fd, &fdset);
rc = select (fd+1, &fdset, NULL, NULL, NULL);
......@@ -316,7 +285,7 @@ comsat_daemon (int port)
overflow_count = 0;
last_overflow_time = time (NULL);
}
if (now - last_request_time <= request_control_interval)
reqcount++;
else
......@@ -341,7 +310,7 @@ comsat_main (int fd)
char *p, *endp;
size_t offset;
char *path = NULL;
len = sizeof sin_from;
rdlen = recvfrom (fd, buffer, sizeof buffer, 0,
(struct sockaddr*)&sin_from, &len);
......@@ -359,9 +328,9 @@ comsat_main (int fd)
inet_ntoa (sin_from.sin_addr));
return 1;
}
syslog (LOG_INFO, "%d bytes from %s", rdlen, inet_ntoa (sin_from.sin_addr));
buffer[rdlen] = 0;
/* Parse the buffer */
......@@ -399,7 +368,7 @@ comsat_main (int fd)
syslog (LOG_ERR, "fork: %m");
return 1;
}
if (pid > 0)
{
struct timeval tv;
......@@ -408,7 +377,7 @@ comsat_main (int fd)
select (0, NULL, NULL, NULL, &tv);
kill (pid, SIGKILL); /* Just in case the child is hung */
return 0;
}
}
/* Child: do actual I/O */
notify_user (buffer, tty, path, offset);
......@@ -420,7 +389,7 @@ get_newline_str (FILE *fp)
{
#if defined(OPOST) && defined(ONLCR)
struct termios tbuf;
tcgetattr (fileno (fp), &tbuf);
if ((tbuf.c_oflag & OPOST) && (tbuf.c_oflag & ONLCR))
return "\n";
......@@ -484,7 +453,7 @@ notify_user (char *user, char *device, char *path, off_t offset)
path, strerror (status));
return;
}
/* Read headers */
size -= offset;
blurb = malloc (size + 1);
......@@ -514,7 +483,7 @@ notify_user (char *user, char *device, char *path, off_t offset)
mailbox_set_stream (tmp, stream);
mailbox_messages_count (tmp, &count);
mailbox_get_message (tmp, 1, &msg);
run_user_action (fp, cr, msg);
fclose (fp);
}
......@@ -624,7 +593,7 @@ mailbox_path (const char *user)
{
struct passwd *pw;
char *mailbox_name;
pw = mu_getpwnam (user);
if (!pw)
{
......@@ -638,7 +607,7 @@ mailbox_path (const char *user)
+ strlen (pw->pw_name) + 1, 1);
sprintf (mailbox_name, "%s/%s", _PATH_MAILDIR, pw->pw_name);
}
else
else
{
mailbox_name = calloc (strlen (pw->pw_dir) + strlen ("/INBOX"), 1);
sprintf (mailbox_name, "%s/INBOX", pw->pw_dir);
......
......@@ -102,7 +102,7 @@ main (int argc, char **argv)
case 'S':
set_namespace (NS_SHARED, optarg);
break;
case 't':
timeout = strtoul (optarg, NULL, 10);
break;
......@@ -145,7 +145,7 @@ main (int argc, char **argv)
#ifdef USE_VIRTUAL_DOMAINS
mu_register_getpwnam (getpwnam_virtual);
#endif
/* Set the signal handlers. */
signal (SIGINT, imap4d_signal);
signal (SIGQUIT, imap4d_signal);
......@@ -161,9 +161,11 @@ main (int argc, char **argv)
if (mode == DAEMON)
imap4d_daemon_init ();
/* Make sure we are in the root. */
chdir ("/");
else
{
/* Make sure we are in the root. */
chdir ("/");
}
/* Set up for syslog. */
openlog ("gnu-imap4d", LOG_PID, LOG_FACILITY);
......@@ -203,7 +205,7 @@ imap4d_mainloop (int infile, int outfile)
imap4d_bye (ERR_NO_OFILE);
setvbuf(ofile, NULL, _IOLBF, 0);
syslog (LOG_INFO, "Incoming connection opened");
/* log information on the connecting client */
......@@ -240,43 +242,15 @@ imap4d_mainloop (int infile, int outfile)
static void
imap4d_daemon_init (void)
{
pid_t pid;
extern int daemon (int, int);
pid = fork ();
if (pid == -1)
{
perror ("fork failed:");
exit (1);
}
else if (pid > 0)
exit (0); /* Parent exits. */
setsid (); /* Become session leader. */
signal (SIGHUP, SIG_IGN); /* Ignore SIGHUP. */
/* The second fork is to guarantee that the daemon cannot acquire a
controlling terminal. */
pid = fork ();
if (pid == -1)
/* Become a daemon. Take care to close inherited fds and to hold
first three one, in, out, err */
if (daemon (0, 0) < 0)
{
perror("fork failed:");
exit (1);
}
else if (pid > 0)
exit (0); /* Parent exits. */
/* Close inherited file descriptors. */
{
size_t i;
#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
size_t fdlimit = sysconf(_SC_OPEN_MAX);
#else
size_t fdlimit = 64;
#endif
for (i = 0; i < fdlimit; ++i)
close (i);
}
/* SIGCHLD is not ignore but rather use to do some simple load balancing. */
#ifdef HAVE_SIGACTION
......
......@@ -3,9 +3,9 @@ noinst_LIBRARIES = libmailutils.a
SUBDIRS = posix
INCLUDES = -I${top_srcdir}/include
libmailutils_a_SOURCES = basename.c getopt.c getopt1.c md5.c mu_dbm.c getline.c \
xstrdup.c xmalloc.c argcv.c
INCLUDES = -I${top_srcdir}/include
libmailutils_a_SOURCES = basename.c daemon.c getopt.c getopt1.c md5.c \
mu_dbm.c getline.c xstrdup.c xmalloc.c argcv.c
EXTRA_DIST = alloca.c fnmatch.c setenv.c snprintf.c strchrnul.c strndup.c \
strnlen.c strtok_r.c strsignal.c xstrtol.c vasprintf.c malloc.c realloc.c \
......
/*-
* Copyright (c) 1990, 1993
* The Regents of the University of California. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <config.h>
#include <fcntl.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#ifdef HAVE_PATHS_H
# include <paths.h>
#endif
#ifndef _PATH_DEVNULL
# define _PATH_DEVNULL "/dev/null"
#endif
/*
According to Unix-FAQ maintained by Andrew Gierth:
1.fork() so the parent can exit, this returns control to the command
line or shell invoking your program. This step is required so that the
new process is guaranteed not to be a process group leader. The next
step, setsid(), fails if you're a process group leader.
2.setsid() to become a process group and session group leader. Since a
controlling terminal is associated with a session, and this new session
has not yet acquired a controlling terminal our process now has no
controlling terminal, which is a Good Thing for daemons.
3.fork() again so the parent, (the session group leader), can exit. This
means that we, as a non-session group leader, can never regain a
controlling terminal.
4.chdir("/") to ensure that our process doesn't keep any directory in use.
Failure to do this could make it so that an administrator couldn't unmount
a filesystem, because it was our current directory.
[Equivalently, we could change to any directory containing files important
to the daemon's operation.]
5.umask(0) so that we have complete control over the permissions of
anything we write. We don't know what umask we may have inherited.
[This step is optional]
6.close() fds 0, 1, and 2. This releases the standard in, out, and error
we inherited from our parent process. We have no way of knowing where
these fds might have been redirected to. Note that many daemons use
sysconf() to determine the limit _SC_OPEN_MAX. _SC_OPEN_MAX tells you the
maximun open files/process. Then in a loop, the daemon can close all
possible file descriptors. You have to decide if you need to do this or not.
If you think that there might be file-descriptors open you should close
them, since there's a limit on number of concurrent file descriptors.
7.Establish new open descriptors for stdin, stdout and stderr. Even if
you don't plan to use them, it is still a good idea to have them open.
The precise handling of these is a matter of taste; if you have a logfile,
for example, you might wish to open it as stdout or stderr, and open
`/dev/null' as stdin; alternatively, you could open `/dev/console' as
stderr and/or stdout, and `/dev/null' as stdin, or any other combination
that makes sense for your particular daemon. */
#define MAXFD 64
void
waitdaemon_timeout (int signo)
{
int left;
(void)signo;
left = alarm (0);
signal (SIGALRM, SIG_DFL);
if (left == 0)
errx (1, "timed out waiting for child");
}
/* waitdaemon is like daemon, but optionally the parent pause up
until maxwait before exiting. Return -1, on error, otherwise
waitdaemon will return the pid of the parent. */
int
waitdaemon (int nochdir, int noclose, int maxwait)
{
int fd;
pid_t childpid;
pid_t ppid;
ppid = getpid ();
switch (childpid = fork ())
{
case -1: /* Something went wrong. */
return (-1);
case 0: /* In the child. */
break;
default: /* In the parent. */
if (maxwait > 0)
{
signal (SIGALRM, waitdaemon_timeout);
alarm (maxwait);
pause ();
}
_exit(0);
}
if (setsid () == -1)
return -1;
/* SIGHUP is ignore because when the session leader terminates
all process in the session (the second child) are sent the SIGHUP. */
signal (SIGHUP, SIG_IGN);
switch (fork ())
{
case 0:
break;
case -1:
return -1;
default:
_exit (0);
}
if (!nochdir)
chdir ("/");
if (!noclose)
{
int i;
long fdlimit = -1;
#if defined (HAVE_SYSCONF) && defined (_SC_OPEN_MAX)
fdlimit = sysconf (_SC_OPEN_MAX);
#elif defined (HAVE_GETDTABLESIZE)
fdlimit = getdtablesize ();
#endif
if (fdlimit == -1)
fdlimit = MAXFD;
for (i = 0; i < fdlimit; i++)
close (i);
fd = open (_PATH_DEVNULL, O_RDWR, 0);
if (fd != -1)
{
dup2 (fd, STDIN_FILENO);
dup2 (fd, STDOUT_FILENO);
dup2 (fd, STDERR_FILENO);
if (fd > 2)
close (fd);
}
}
return ppid;
}
int
daemon (int nochdir, int noclose)
{
return (waitdaemon (nochdir, noclose, 0) == -1) ? -1 : 0;
}
......@@ -151,9 +151,11 @@ main (int argc, char **argv)
if (mode == DAEMON)
pop3d_daemon_init ();
/* Make sure we are in the root directory. */
chdir ("/");
else
{
/* Make sure we are in the root directory. */
chdir ("/");
}
/* Set up for syslog. */
openlog ("gnu-pop3d", LOG_PID, LOG_FACILITY);
......@@ -179,43 +181,15 @@ main (int argc, char **argv)
static void
pop3d_daemon_init (void)
{
pid_t pid;
pid = fork ();
if (pid == -1)
{
perror ("fork failed:");
exit (EXIT_FAILURE);
}
else if (pid > 0)
exit (EXIT_SUCCESS); /* Parent exits. */
setsid (); /* Become session leader. */
extern int daemon (int, int);
signal (SIGHUP, SIG_IGN); /* Ignore SIGHUP. */
/* The second fork is to guarantee that the daemon cannot acquire a
controlling terminal. */
pid = fork ();
if (pid == -1)
/* Become a daemon. Take care to close inherited fds and to hold
first three one, in, out, err */
if (daemon (0, 0) < 0)
{
perror("fork failed:");
perror ("failed to become a daemon:");
exit (EXIT_FAILURE);
}
else if (pid > 0)
exit (EXIT_SUCCESS); /* Parent exits. */
/* Close inherited file descriptors. */
{
size_t i;
#if defined(HAVE_SYSCONF) && defined(_SC_OPEN_MAX)
size_t fdlimit = sysconf(_SC_OPEN_MAX);
#else
size_t fdlimit = 64;
#endif
for (i = 0; i < fdlimit; ++i)
close (i);
}
/* SIGCHLD is not ignore but rather use to do some simple load balancing. */
#ifdef HAVE_SIGACTION
......