]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.sbin/daemon/daemon.c
Implement pci_enable_msi() and pci_disable_msi() in the LinuxKPI.
[FreeBSD/FreeBSD.git] / usr.sbin / daemon / daemon.c
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1999 Berkeley Software Design, Inc. All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. Berkeley Software Design Inc's name may not be used to endorse or
15  *    promote products derived from this software without specific prior
16  *    written permission.
17  *
18  * THIS SOFTWARE IS PROVIDED BY BERKELEY SOFTWARE DESIGN INC ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL BERKELEY SOFTWARE DESIGN INC BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  *      From BSDI: daemon.c,v 1.2 1996/08/15 01:11:09 jch Exp
31  */
32
33 #include <sys/cdefs.h>
34 __FBSDID("$FreeBSD$");
35
36 #include <sys/param.h>
37 #include <sys/mman.h>
38 #include <sys/wait.h>
39
40 #include <fcntl.h>
41 #include <err.h>
42 #include <errno.h>
43 #include <libutil.h>
44 #include <login_cap.h>
45 #include <pwd.h>
46 #include <signal.h>
47 #include <stdio.h>
48 #include <stdlib.h>
49 #include <unistd.h>
50 #include <string.h>
51 #include <strings.h>
52 #define SYSLOG_NAMES
53 #include <syslog.h>
54 #include <time.h>
55 #include <assert.h>
56
57 #define LBUF_SIZE 4096
58
59 struct log_params {
60         int dosyslog;
61         int logpri;
62         int noclose;
63         int outfd;
64 };
65
66 static void restrict_process(const char *);
67 static void handle_term(int);
68 static void handle_chld(int);
69 static int  listen_child(int, struct log_params *);
70 static int  get_log_mapping(const char *, const CODE *);
71 static void open_pid_files(const char *, const char *, struct pidfh **,
72                            struct pidfh **);
73 static void do_output(const unsigned char *, size_t, struct log_params *);
74 static void daemon_sleep(time_t, long);
75 static void usage(void);
76
77 static volatile sig_atomic_t terminate = 0, child_gone = 0, pid = 0;
78
79 int
80 main(int argc, char *argv[])
81 {
82         const char *pidfile, *ppidfile, *title, *user, *outfn, *logtag;
83         int ch, nochdir, noclose, restart, dosyslog, child_eof;
84         sigset_t mask_susp, mask_orig, mask_read, mask_term;
85         struct log_params logpar;
86         int pfd[2] = { -1, -1 }, outfd = -1;
87         int stdmask, logpri, logfac;
88         struct pidfh *ppfh, *pfh;
89         char *p;
90
91         memset(&logpar, 0, sizeof(logpar));
92         stdmask = STDOUT_FILENO | STDERR_FILENO;
93         ppidfile = pidfile = user = NULL;
94         nochdir = noclose = 1;
95         logpri = LOG_NOTICE;
96         logfac = LOG_DAEMON;
97         logtag = "daemon";
98         restart = 0;
99         dosyslog = 0;
100         outfn = NULL;
101         title = NULL;
102         while ((ch = getopt(argc, argv, "cfSp:P:ru:o:s:l:t:l:m:R:T:")) != -1) {
103                 switch (ch) {
104                 case 'c':
105                         nochdir = 0;
106                         break;
107                 case 'f':
108                         noclose = 0;
109                         break;
110                 case 'l':
111                         logfac = get_log_mapping(optarg, facilitynames);
112                         if (logfac == -1)
113                                 errx(5, "unrecognized syslog facility");
114                         dosyslog = 1;
115                         break;
116                 case 'm':
117                         stdmask = strtol(optarg, &p, 10);
118                         if (p == optarg || stdmask < 0 || stdmask > 3)
119                                 errx(6, "unrecognized listening mask");
120                         break;
121                 case 'o':
122                         outfn = optarg;
123                         break;
124                 case 'p':
125                         pidfile = optarg;
126                         break;
127                 case 'P':
128                         ppidfile = optarg;
129                         break;
130                 case 'r':
131                         restart = 1;
132                         break;
133                 case 'R':
134                         restart = strtol(optarg, &p, 0);
135                         if (p == optarg || restart < 1)
136                                 errx(6, "invalid restart delay");
137                         break;
138                 case 's':
139                         logpri = get_log_mapping(optarg, prioritynames);
140                         if (logpri == -1)
141                                 errx(4, "unrecognized syslog priority");
142                         dosyslog = 1;
143                         break;
144                 case 'S':
145                         dosyslog = 1;
146                         break;
147                 case 't':
148                         title = optarg;
149                         break;
150                 case 'T':
151                         logtag = optarg;
152                         dosyslog = 1;
153                         break;
154                 case 'u':
155                         user = optarg;
156                         break;
157                 default:
158                         usage();
159                 }
160         }
161         argc -= optind;
162         argv += optind;
163
164         if (argc == 0)
165                 usage();
166
167         if (!title)
168                 title = argv[0];
169
170         if (outfn) {
171                 outfd = open(outfn, O_CREAT | O_WRONLY | O_APPEND | O_CLOEXEC, 0600);
172                 if (outfd == -1)
173                         err(7, "open");
174         }
175         
176         if (dosyslog)
177                 openlog(logtag, LOG_PID | LOG_NDELAY, logfac);
178
179         ppfh = pfh = NULL;
180         /*
181          * Try to open the pidfile before calling daemon(3),
182          * to be able to report the error intelligently
183          */
184         open_pid_files(pidfile, ppidfile, &pfh, &ppfh);
185         if (daemon(nochdir, noclose) == -1) {
186                 warn("daemon");
187                 goto exit;
188         }
189         /* Write out parent pidfile if needed. */
190         pidfile_write(ppfh);
191         /*
192          * If the pidfile or restart option is specified the daemon
193          * executes the command in a forked process and wait on child
194          * exit to remove the pidfile or restart the command. Normally
195          * we don't want the monitoring daemon to be terminated
196          * leaving the running process and the stale pidfile, so we
197          * catch SIGTERM and forward it to the children expecting to
198          * get SIGCHLD eventually. We also must fork() to obtain a
199          * readable pipe with the child for writing to a log file
200          * and syslog.
201          */
202         pid = -1;
203         if (pidfile || ppidfile || restart || outfd != -1 || dosyslog) {
204                 struct sigaction act_term, act_chld;
205
206                 /* Avoid PID racing with SIGCHLD and SIGTERM. */
207                 memset(&act_term, 0, sizeof(act_term));
208                 act_term.sa_handler = handle_term;
209                 sigemptyset(&act_term.sa_mask);
210                 sigaddset(&act_term.sa_mask, SIGCHLD);
211
212                 memset(&act_chld, 0, sizeof(act_chld));
213                 act_chld.sa_handler = handle_chld;
214                 sigemptyset(&act_chld.sa_mask);
215                 sigaddset(&act_chld.sa_mask, SIGTERM);
216
217                 /* Block these when avoiding racing before sigsuspend(). */
218                 sigemptyset(&mask_susp);
219                 sigaddset(&mask_susp, SIGTERM);
220                 sigaddset(&mask_susp, SIGCHLD);
221                 /* Block SIGTERM when we lack a valid child PID. */
222                 sigemptyset(&mask_term);
223                 sigaddset(&mask_term, SIGTERM);
224                 /*
225                  * When reading, we wish to avoid SIGCHLD. SIGTERM
226                  * has to be caught, otherwise we'll be stuck until
227                  * the read() returns - if it returns.
228                  */
229                 sigemptyset(&mask_read);
230                 sigaddset(&mask_read, SIGCHLD);
231                 /* Block SIGTERM to avoid racing until we have forked. */
232                 if (sigprocmask(SIG_BLOCK, &mask_term, &mask_orig)) {
233                         warn("sigprocmask");
234                         goto exit;
235                 }
236                 if (sigaction(SIGTERM, &act_term, NULL) == -1) {
237                         warn("sigaction");
238                         goto exit;
239                 }
240                 if (sigaction(SIGCHLD, &act_chld, NULL) == -1) {
241                         warn("sigaction");
242                         goto exit;
243                 }
244                 /*
245                  * Try to protect against pageout kill. Ignore the
246                  * error, madvise(2) will fail only if a process does
247                  * not have superuser privileges.
248                  */
249                 (void)madvise(NULL, 0, MADV_PROTECT);
250                 logpar.outfd = outfd;
251                 logpar.dosyslog = dosyslog;
252                 logpar.logpri = logpri;
253                 logpar.noclose = noclose;
254 restart:
255                 if (pipe(pfd))
256                         err(1, "pipe");
257                 /*
258                  * Spawn a child to exec the command.
259                  */
260                 child_gone = 0;
261                 pid = fork();
262                 if (pid == -1) {
263                         warn("fork");
264                         goto exit;
265                 } else if (pid > 0) {
266                         /*
267                          * Unblock SIGTERM after we know we have a valid
268                          * child PID to signal.
269                          */
270                         if (sigprocmask(SIG_UNBLOCK, &mask_term, NULL)) {
271                                 warn("sigprocmask");
272                                 goto exit;
273                         }
274                         close(pfd[1]);
275                         pfd[1] = -1;
276                 }
277         }
278         if (pid <= 0) {
279                 /* Now that we are the child, write out the pid. */
280                 pidfile_write(pfh);
281
282                 if (user != NULL)
283                         restrict_process(user);
284                 /*
285                  * When forking, the child gets the original sigmask,
286                  * and dup'd pipes.
287                  */
288                 if (pid == 0) {
289                         close(pfd[0]);
290                         if (sigprocmask(SIG_SETMASK, &mask_orig, NULL))
291                                 err(1, "sigprogmask");
292                         if (stdmask & STDERR_FILENO) {
293                                 if (dup2(pfd[1], STDERR_FILENO) == -1)
294                                         err(1, "dup2");
295                         }
296                         if (stdmask & STDOUT_FILENO) {
297                                 if (dup2(pfd[1], STDOUT_FILENO) == -1)
298                                         err(1, "dup2");
299                         }
300                         if (pfd[1] != STDERR_FILENO &&
301                             pfd[1] != STDOUT_FILENO)
302                                 close(pfd[1]);
303                 }
304                 execvp(argv[0], argv);
305                 /*
306                  * execvp() failed -- report the error. The child is
307                  * now running, so the exit status doesn't matter.
308                  */
309                 err(1, "%s", argv[0]);
310         }
311         setproctitle("%s[%d]", title, (int)pid);
312         /*
313          * As we have closed the write end of pipe for parent process,
314          * we might detect the child's exit by reading EOF. The child
315          * might have closed its stdout and stderr, so we must wait for
316          * the SIGCHLD to ensure that the process is actually gone.
317          */
318         child_eof = 0;
319         for (;;) {
320                 /*
321                  * We block SIGCHLD when listening, but SIGTERM we accept
322                  * so the read() won't block if we wish to depart.
323                  *
324                  * Upon receiving SIGTERM, we have several options after
325                  * sending the SIGTERM to our child:
326                  * - read until EOF
327                  * - read until EOF but only for a while
328                  * - bail immediately
329                  *
330                  * We go for the third, as otherwise we have no guarantee
331                  * that we won't block indefinitely if the child refuses
332                  * to depart. To handle the second option, a different
333                  * approach would be needed (procctl()?)
334                  */
335                 if (child_gone && child_eof) {
336                         break;
337                 } else if (terminate) {
338                         goto exit;
339                 } else if (!child_eof) {
340                         if (sigprocmask(SIG_BLOCK, &mask_read, NULL)) {
341                                 warn("sigprocmask");
342                                 goto exit;
343                         }
344                         child_eof = !listen_child(pfd[0], &logpar);
345                         if (sigprocmask(SIG_UNBLOCK, &mask_read, NULL)) {
346                                 warn("sigprocmask");
347                                 goto exit;
348                         }
349                 } else {
350                         if (sigprocmask(SIG_BLOCK, &mask_susp, NULL)) {
351                                 warn("sigprocmask");
352                                 goto exit;
353                         }
354                         while (!terminate && !child_gone)
355                                 sigsuspend(&mask_orig);
356                         if (sigprocmask(SIG_UNBLOCK, &mask_susp, NULL)) {
357                                 warn("sigprocmask");
358                                 goto exit;
359                         }
360                 }
361         }
362         if (restart && !terminate)
363                 daemon_sleep(restart, 0);
364         if (sigprocmask(SIG_BLOCK, &mask_term, NULL)) {
365                 warn("sigprocmask");
366                 goto exit;
367         }
368         if (restart && !terminate) {
369                 close(pfd[0]);
370                 pfd[0] = -1;
371                 goto restart;
372         }
373 exit:
374         close(outfd);
375         close(pfd[0]);
376         close(pfd[1]);
377         if (dosyslog)
378                 closelog();
379         pidfile_remove(pfh);
380         pidfile_remove(ppfh);
381         exit(1); /* If daemon(3) succeeded exit status does not matter. */
382 }
383
384 static void
385 daemon_sleep(time_t secs, long nsecs)
386 {
387         struct timespec ts = { secs, nsecs };
388
389         while (!terminate && nanosleep(&ts, &ts) == -1) {
390                 if (errno != EINTR)
391                         err(1, "nanosleep");
392         }
393 }
394
395 static void
396 open_pid_files(const char *pidfile, const char *ppidfile,
397                struct pidfh **pfh, struct pidfh **ppfh)
398 {
399         pid_t fpid;
400         int serrno;
401
402         if (pidfile) {
403                 *pfh = pidfile_open(pidfile, 0600, &fpid);
404                 if (*pfh == NULL) {
405                         if (errno == EEXIST) {
406                                 errx(3, "process already running, pid: %d",
407                                     fpid);
408                         }
409                         err(2, "pidfile ``%s''", pidfile);
410                 }
411         }
412         /* Do the same for the actual daemon process. */
413         if (ppidfile) {
414                 *ppfh = pidfile_open(ppidfile, 0600, &fpid);
415                 if (*ppfh == NULL) {
416                         serrno = errno;
417                         pidfile_remove(*pfh);
418                         errno = serrno;
419                         if (errno == EEXIST) {
420                                 errx(3, "process already running, pid: %d",
421                                      fpid);
422                         }
423                         err(2, "ppidfile ``%s''", ppidfile);
424                 }
425         }
426 }
427
428 static int
429 get_log_mapping(const char *str, const CODE *c)
430 {
431         const CODE *cp;
432         for (cp = c; cp->c_name; cp++)
433                 if (strcmp(cp->c_name, str) == 0)
434                         return cp->c_val;
435         return -1;
436 }
437
438 static void
439 restrict_process(const char *user)
440 {
441         struct passwd *pw = NULL;
442
443         pw = getpwnam(user);
444         if (pw == NULL)
445                 errx(1, "unknown user: %s", user);
446
447         if (setusercontext(NULL, pw, pw->pw_uid, LOGIN_SETALL) != 0)
448                 errx(1, "failed to set user environment");
449 }
450
451 /*
452  * We try to collect whole lines terminated by '\n'. Otherwise we collect a
453  * full buffer, and then output it.
454  *
455  * Return value of 0 is assumed to mean EOF or error, and 1 indicates to
456  * continue reading.
457  */
458 static int
459 listen_child(int fd, struct log_params *logpar)
460 {
461         static unsigned char buf[LBUF_SIZE];
462         static size_t bytes_read = 0;
463         int rv;
464
465         assert(logpar);
466         assert(bytes_read < LBUF_SIZE - 1);
467
468         rv = read(fd, buf + bytes_read, LBUF_SIZE - bytes_read - 1);
469         if (rv > 0) {
470                 unsigned char *cp;
471
472                 bytes_read += rv;
473                 assert(bytes_read <= LBUF_SIZE - 1);
474                 /* Always NUL-terminate just in case. */
475                 buf[LBUF_SIZE - 1] = '\0';
476                 /*
477                  * Chomp line by line until we run out of buffer.
478                  * This does not take NUL characters into account.
479                  */
480                 while ((cp = memchr(buf, '\n', bytes_read)) != NULL) {
481                         size_t bytes_line = cp - buf + 1;
482                         assert(bytes_line <= bytes_read);
483                         do_output(buf, bytes_line, logpar);
484                         bytes_read -= bytes_line;
485                         memmove(buf, cp + 1, bytes_read);
486                 }
487                 /* Wait until the buffer is full. */
488                 if (bytes_read < LBUF_SIZE - 1)
489                         return 1;
490                 do_output(buf, bytes_read, logpar);
491                 bytes_read = 0;
492                 return 1;
493         } else if (rv == -1) {
494                 /* EINTR should trigger another read. */
495                 if (errno == EINTR) {
496                         return 1;
497                 } else {
498                         warn("read");
499                         return 0;
500                 }
501         }
502         /* Upon EOF, we have to flush what's left of the buffer. */
503         if (bytes_read > 0) {
504                 do_output(buf, bytes_read, logpar);
505                 bytes_read = 0;
506         }
507         return 0;
508 }
509
510 /*
511  * The default behavior is to stay silent if the user wants to redirect
512  * output to a file and/or syslog. If neither are provided, then we bounce
513  * everything back to parent's stdout.
514  */
515 static void
516 do_output(const unsigned char *buf, size_t len, struct log_params *logpar)
517 {
518         assert(len <= LBUF_SIZE);
519         assert(logpar);
520
521         if (len < 1)
522                 return;
523         if (logpar->dosyslog)
524                 syslog(logpar->logpri, "%.*s", (int)len, buf);
525         if (logpar->outfd != -1) {
526                 if (write(logpar->outfd, buf, len) == -1)
527                         warn("write");
528         }
529         if (logpar->noclose && !logpar->dosyslog && logpar->outfd == -1)
530                 printf("%.*s", (int)len, buf);
531 }
532
533 /*
534  * We use the global PID acquired directly from fork. If there is no valid
535  * child pid, the handler should be blocked and/or child_gone == 1.
536  */
537 static void
538 handle_term(int signo)
539 {
540         if (pid > 0 && !child_gone)
541                 kill(pid, signo);
542         terminate = 1;
543 }
544
545 static void
546 handle_chld(int signo)
547 {
548         (void)signo;
549         for (;;) {
550                 int rv = waitpid(-1, NULL, WNOHANG);
551                 if (pid == rv) {
552                         child_gone = 1;
553                         break;
554                 } else if (rv == -1 && errno != EINTR) {
555                         warn("waitpid");
556                         return;
557                 }
558         }
559 }
560
561 static void
562 usage(void)
563 {
564         (void)fprintf(stderr,
565             "usage: daemon [-cfrS] [-p child_pidfile] [-P supervisor_pidfile]\n"
566             "              [-u user] [-o output_file] [-t title]\n"
567             "              [-l syslog_facility] [-s syslog_priority]\n"
568             "              [-T syslog_tag] [-m output_mask] [-R restart_delay_secs]\n"
569             "command arguments ...\n");
570         exit(1);
571 }