daemon.c revision 255521
135124Sjb/*-
235124Sjb * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
335124Sjb *
435124Sjb * Redistribution and use in source and binary forms, with or without
535124Sjb * modification, are permitted provided that the following conditions
635124Sjb * are met:
735124Sjb * 1. Redistributions of source code must retain the above copyright
835124Sjb *    notice, this list of conditions and the following disclaimer.
935124Sjb * 2. Redistributions in binary form must reproduce the above copyright
1035124Sjb *    notice, this list of conditions and the following disclaimer in the
1135124Sjb *    documentation and/or other materials provided with the distribution.
1235124Sjb * 3. Berkeley Software Design Inc's name may not be used to endorse or
1335124Sjb *    promote products derived from this software without specific prior
1435124Sjb *    written permission.
1535124Sjb *
1635124Sjb * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
1735124Sjb * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1835124Sjb * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
1935124Sjb * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
2035124Sjb * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2135124Sjb * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2235124Sjb * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2335124Sjb * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2435124Sjb * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
2535124Sjb * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
2635124Sjb * SUCH DAMAGE.
2735124Sjb *
2835124Sjb *	From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
2935124Sjb */
3035124Sjb
3135124Sjb#include <sys/cdefs.h>
3250476Speter__FBSDID("$FreeBSD: head/usr.sbin/daemon/daemon.c 255521 2013-09-13 16:57:28Z jmg $");
3335124Sjb
3435124Sjb#include <sys/param.h>
3535124Sjb#include <sys/mman.h>
3635124Sjb#include <sys/wait.h>
3735124Sjb
3835124Sjb#include <err.h>
3935124Sjb#include <errno.h>
4035124Sjb#include <libutil.h>
4135124Sjb#include <login_cap.h>
4235124Sjb#include <pwd.h>
4335124Sjb#include <signal.h>
4435124Sjb#include <stdio.h>
4535124Sjb#include <stdlib.h>
4635124Sjb#include <unistd.h>
4735124Sjb
4835124Sjbstatic void dummy_sighandler(int);
4935124Sjbstatic void restrict_process(const char *);
5035124Sjbstatic int  wait_child(pid_t pid, sigset_t *mask);
5135124Sjbstatic void usage(void);
5235124Sjb
5335124Sjbint
5435124Sjbmain(int argc, char *argv[])
5535124Sjb{
5671579Sdeischen	struct pidfh  *ppfh, *pfh;
5735124Sjb	sigset_t mask, oldmask;
5835124Sjb	int ch, nochdir, noclose, restart;
5935124Sjb	const char *pidfile, *ppidfile,  *user;
6035124Sjb	pid_t otherpid, pid;
6135124Sjb
6235124Sjb	nochdir = noclose = 1;
6335124Sjb	restart = 0;
6471579Sdeischen	ppfh = pfh = NULL;
6535124Sjb	ppidfile = pidfile = user = NULL;
6693399Smarkm	while ((ch = getopt(argc, argv, "cfp:P:ru:")) != -1) {
67106866Sdeischen		switch (ch) {
68106866Sdeischen		case 'c':
69106866Sdeischen			nochdir = 0;
70106866Sdeischen			break;
71106866Sdeischen		case 'f':
72106866Sdeischen			noclose = 0;
73106866Sdeischen			break;
74106866Sdeischen		case 'p':
75106866Sdeischen			pidfile = optarg;
76106866Sdeischen			break;
77106866Sdeischen		case 'P':
78106866Sdeischen			ppidfile = optarg;
79106866Sdeischen			break;
80106866Sdeischen		case 'r':
81106866Sdeischen			restart = 1;
82106866Sdeischen			break;
83106866Sdeischen		case 'u':
84106866Sdeischen			user = optarg;
85106866Sdeischen			break;
86106866Sdeischen		default:
87106866Sdeischen			usage();
88106866Sdeischen		}
89106866Sdeischen	}
90106866Sdeischen	argc -= optind;
91106866Sdeischen	argv += optind;
92106866Sdeischen
93106866Sdeischen	if (argc == 0)
94106866Sdeischen		usage();
95106866Sdeischen
96106866Sdeischen	ppfh = pfh = NULL;
97106866Sdeischen	/*
98106866Sdeischen	 * Try to open the pidfile before calling daemon(3),
99106866Sdeischen	 * to be able to report the error intelligently
100106866Sdeischen	 */
101106866Sdeischen	if (pidfile != NULL) {
102106866Sdeischen		pfh = pidfile_open(pidfile, 0600, &otherpid);
103106866Sdeischen		if (pfh == NULL) {
104106870Sdeischen			if (errno == EEXIST) {
105106880Sdeischen				errx(3, "process already running, pid: %d",
106106866Sdeischen				    otherpid);
107106880Sdeischen			}
108106866Sdeischen			err(2, "pidfile ``%s''", pidfile);
109106866Sdeischen		}
110111618Snectar	}
111111618Snectar
112111618Snectar	/* do same for actual daemon process */
113111618Snectar	if (ppidfile != NULL) {
114111618Snectar		ppfh = pidfile_open(ppidfile, 0600, &otherpid);
115111618Snectar		if (ppfh == NULL) {
116111618Snectar			if (errno == EEXIST) {
117111618Snectar				errx(3, "process already running, pid: %d",
11893399Smarkm				     otherpid);
11993399Smarkm			}
12093399Smarkm			err(2, "ppidfile ``%s''", ppidfile);
12193399Smarkm		}
12293399Smarkm	}
12335124Sjb
124	if (daemon(nochdir, noclose) == -1)
125		err(1, NULL);
126
127	/*
128	 * If the pidfile or restart option is specified the daemon
129	 * executes the command in a forked process and wait on child
130	 * exit to remove the pidfile or restart the command. Normally
131	 * we don't want the monitoring daemon to be terminated
132	 * leaving the running process and the stale pidfile, so we
133	 * catch SIGTERM and forward it to the children expecting to
134	 * get SIGCHLD eventually.
135	 */
136	pid = -1;
137	if (pidfile != NULL || restart) {
138		/*
139		 * Restore default action for SIGTERM in case the
140		 * parent process decided to ignore it.
141		 */
142		if (signal(SIGTERM, SIG_DFL) == SIG_ERR)
143			err(1, "signal");
144		/*
145		 * Because SIGCHLD is ignored by default, setup dummy handler
146		 * for it, so we can mask it.
147		 */
148		if (signal(SIGCHLD, dummy_sighandler) == SIG_ERR)
149			err(1, "signal");
150		/*
151		 * Block interesting signals.
152		 */
153		sigemptyset(&mask);
154		sigaddset(&mask, SIGTERM);
155		sigaddset(&mask, SIGCHLD);
156		if (sigprocmask(SIG_SETMASK, &mask, &oldmask) == -1)
157			err(1, "sigprocmask");
158		/*
159		 * Try to protect against pageout kill. Ignore the
160		 * error, madvise(2) will fail only if a process does
161		 * not have superuser privileges.
162		 */
163		(void)madvise(NULL, 0, MADV_PROTECT);
164restart:
165		/*
166		 * Spawn a child to exec the command, so in the parent
167		 * we could wait for it to exit and remove pidfile.
168		 */
169		pid = fork();
170		if (pid == -1) {
171			pidfile_remove(pfh);
172			err(1, "fork");
173		}
174	}
175	if (pid <= 0) {
176		if (pid == 0) {
177			/* Restore old sigmask in the child. */
178			if (sigprocmask(SIG_SETMASK, &oldmask, NULL) == -1)
179				err(1, "sigprocmask");
180		}
181		/* Now that we are the child, write out the pid. */
182		pidfile_write(pfh);
183
184		if (user != NULL)
185			restrict_process(user);
186
187		execvp(argv[0], argv);
188
189		/*
190		 * execvp() failed -- report the error. The child is
191		 * now running, so the exit status doesn't matter.
192		 */
193		err(1, "%s", argv[0]);
194	}
195	/* write out parent pidfile if needed */
196	if (ppidfile != NULL)
197		pidfile_write(ppfh);
198
199	setproctitle("%s[%d]", argv[0], pid);
200	if (wait_child(pid, &mask) == 0 && restart) {
201		sleep(1);
202		goto restart;
203	}
204	pidfile_remove(pfh);
205	pidfile_remove(ppfh);
206	exit(0); /* Exit status does not matter. */
207}
208
209static void
210dummy_sighandler(int sig __unused)
211{
212	/* Nothing to do. */
213}
214
215static void
216restrict_process(const char *user)
217{
218	struct passwd *pw = NULL;
219
220	pw = getpwnam(user);
221	if (pw == NULL)
222		errx(1, "unknown user: %s", user);
223
224	if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
225		errx(1, "failed to set user environment");
226}
227
228static int
229wait_child(pid_t pid, sigset_t *mask)
230{
231	int terminate, signo;
232
233	terminate = 0;
234	for (;;) {
235		if (sigwait(mask, &signo) == -1) {
236			warn("sigwaitinfo");
237			return (-1);
238		}
239		switch (signo) {
240		case SIGCHLD:
241			if (waitpid(pid, NULL, WNOHANG) == -1) {
242				warn("waitpid");
243				return (-1);
244			}
245			return (terminate);
246		case SIGTERM:
247			terminate = 1;
248			if (kill(pid, signo) == -1) {
249				warn("kill");
250				return (-1);
251			}
252			continue;
253		default:
254			warnx("sigwaitinfo: invalid signal: %d", signo);
255			return (-1);
256		}
257	}
258}
259
260static void
261usage(void)
262{
263	(void)fprintf(stderr,
264	    "usage: daemon [-cfr] [-p child_pidfile] [-P supervisor_pidfile] "
265	    "[-u user]\n              command arguments ...\n");
266	exit(1);
267}
268