Generally use NULL instead of explicitly casting 0 to some pointer type (part2).
[dragonfly.git] / sbin / init / init.c
CommitLineData
984263bc
MD
1/*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
1de703da
MD
35 *
36 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California. All rights reserved.
37 * @(#)init.c 8.1 (Berkeley) 7/15/93
38 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
eecd52b2 39 * $DragonFly: src/sbin/init/init.c,v 1.10 2007/11/25 18:10:07 swildner Exp $
984263bc
MD
40 */
41
984263bc
MD
42#include <sys/param.h>
43#include <sys/ioctl.h>
44#include <sys/mount.h>
45#include <sys/sysctl.h>
46#include <sys/wait.h>
47#include <sys/stat.h>
48
49#include <db.h>
50#include <errno.h>
51#include <fcntl.h>
52#include <libutil.h>
53#include <paths.h>
54#include <signal.h>
55#include <stdio.h>
56#include <stdlib.h>
57#include <string.h>
58#include <syslog.h>
59#include <time.h>
60#include <ttyent.h>
61#include <unistd.h>
62#include <sys/reboot.h>
63#include <err.h>
64
65#ifdef __STDC__
66#include <stdarg.h>
67#else
68#include <varargs.h>
69#endif
70
71#ifdef SECURE
72#include <pwd.h>
73#endif
74
75#ifdef LOGIN_CAP
76#include <login_cap.h>
77#endif
78
79#include "pathnames.h"
80
81/*
82 * Sleep times; used to prevent thrashing.
83 */
84#define GETTY_SPACING 5 /* N secs minimum getty spacing */
85#define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
86#define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
87#define WINDOW_WAIT 3 /* wait N secs after starting window */
88#define STALL_TIMEOUT 30 /* wait N secs after warning */
89#define DEATH_WATCH 10 /* wait N secs for procs to die */
90#define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
91#define RESOURCE_RC "daemon"
92#define RESOURCE_WINDOW "default"
93#define RESOURCE_GETTY "default"
94
984263bc
MD
95/*
96 * We really need a recursive typedef...
97 * The following at least guarantees that the return type of (*state_t)()
98 * is sufficiently wide to hold a function pointer.
99 */
9a76cd75
DR
100typedef long (*state_func_t)(void);
101typedef state_func_t (*state_t)(void);
984263bc 102
984263bc
MD
103enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
104#define FALSE 0
105#define TRUE 1
106
b87f28fc 107static void setctty(const char *);
984263bc
MD
108
109typedef struct init_session {
110 int se_index; /* index of entry in ttys file */
111 pid_t se_process; /* controlling process */
112 time_t se_started; /* used to avoid thrashing */
113 int se_flags; /* status of session */
114#define SE_SHUTDOWN 0x1 /* session won't be restarted */
115#define SE_PRESENT 0x2 /* session is in /etc/ttys */
116 int se_nspace; /* spacing count */
117 char *se_device; /* filename of port */
118 char *se_getty; /* what to run on that port */
119 char *se_getty_argv_space; /* pre-parsed argument array space */
120 char **se_getty_argv; /* pre-parsed argument array */
121 char *se_window; /* window system (started only once) */
122 char *se_window_argv_space; /* pre-parsed argument array space */
123 char **se_window_argv; /* pre-parsed argument array */
124 char *se_type; /* default terminal type */
125 struct init_session *se_prev;
126 struct init_session *se_next;
127} session_t;
128
b87f28fc
JS
129static void handle(sig_t, ...);
130static void delset(sigset_t *, ...);
131
132static void stall(const char *, ...);
133static void warning(const char *, ...);
134static void emergency(const char *, ...);
135static void disaster(int);
136static void badsys(int);
137static int runshutdown(void);
138static char *strk(char *);
139
140static state_func_t single_user(void);
141static state_func_t runcom(void);
142static state_func_t read_ttys(void);
143static state_func_t multi_user(void);
144static state_func_t clean_ttys(void);
145static state_func_t catatonia(void);
146static state_func_t death(void);
147
148static void transition(state_t);
149
150static void free_session(session_t *);
151static session_t *new_session(session_t *, int, struct ttyent *);
152
153static char **construct_argv(char *);
154static void start_window_system(session_t *);
155static void collect_child(pid_t);
156static pid_t start_getty(session_t *);
157static void transition_handler(int);
158static void alrm_handler(int);
159static void setsecuritylevel(int);
160static int getsecuritylevel(void);
161static char *get_chroot(void);
162static int setupargv(session_t *, struct ttyent *);
984263bc 163#ifdef LOGIN_CAP
b87f28fc 164static void setprocresources(const char *);
984263bc 165#endif
984263bc 166
b87f28fc
JS
167static void clear_session_logs(session_t *);
168
169static int start_session_db(void);
170static void add_session(session_t *);
171static void del_session(session_t *);
172static session_t *find_session(pid_t);
984263bc 173
b87f28fc
JS
174static int Reboot = FALSE;
175static int howto = RB_AUTOBOOT;
176
177static DB *session_db;
178static volatile sig_atomic_t clang;
179static session_t *sessions;
180state_t requested_transition = runcom;
984263bc
MD
181
182/*
183 * The mother of all processes.
184 */
185int
b5744197 186main(int argc, char **argv)
984263bc 187{
0aeef1e8 188 char *init_chroot;
984263bc
MD
189 int c;
190 struct sigaction sa;
191 sigset_t mask;
75e1b5ea 192 struct stat sts;
984263bc
MD
193
194
195 /* Dispose of random users. */
196 if (getuid() != 0)
197 errx(1, "%s", strerror(EPERM));
198
199 /* System V users like to reexec init. */
200 if (getpid() != 1) {
201#ifdef COMPAT_SYSV_INIT
202 /* So give them what they want */
203 if (argc > 1) {
204 if (strlen(argv[1]) == 1) {
92b053c8
SW
205 char runlevel = *argv[1];
206 int sig;
984263bc
MD
207
208 switch (runlevel) {
209 case '0': /* halt + poweroff */
210 sig = SIGUSR2;
211 break;
212 case '1': /* single-user */
213 sig = SIGTERM;
214 break;
215 case '6': /* reboot */
216 sig = SIGINT;
217 break;
218 case 'c': /* block further logins */
219 sig = SIGTSTP;
220 break;
221 case 'q': /* rescan /etc/ttys */
222 sig = SIGHUP;
223 break;
224 default:
225 goto invalid;
226 }
227 kill(1, sig);
228 _exit(0);
229 } else
230invalid:
231 errx(1, "invalid run-level ``%s''", argv[1]);
232 } else
233#endif
234 errx(1, "already running");
235 }
236 /*
237 * Note that this does NOT open a file...
238 * Does 'init' deserve its own facility number?
239 */
240 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
241
0aeef1e8
MD
242 /*
243 * If chroot has been requested by the boot loader,
244 * do it now. Try to be robust: If the directory
245 * doesn't exist, continue anyway.
246 */
247 init_chroot = get_chroot();
248 if (init_chroot != NULL) {
249 if (chdir(init_chroot) == -1 || chroot(".") == -1)
250 warning("can't chroot to %s: %m", init_chroot);
251 free(init_chroot);
252 }
253
984263bc
MD
254 /*
255 * Create an initial session.
256 */
257 if (setsid() < 0)
258 warning("initial setsid() failed: %m");
259
260 /*
261 * Establish an initial user so that programs running
262 * single user do not freak out and die (like passwd).
263 */
264 if (setlogin("root") < 0)
265 warning("setlogin() failed: %m");
266
75e1b5ea
DR
267 if (stat("/dev/null", &sts) < 0) {
268 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
269 sleep(5);
270 }
271
984263bc
MD
272 /*
273 * This code assumes that we always get arguments through flags,
274 * never through bits set in some random machine register.
275 */
276 while ((c = getopt(argc, argv, "dsf")) != -1)
277 switch (c) {
278 case 'd':
279 /* We don't support DEVFS. */
280 break;
281 case 's':
282 requested_transition = single_user;
283 break;
284 case 'f':
285 runcom_mode = FASTBOOT;
286 break;
287 default:
288 warning("unrecognized flag '-%c'", c);
289 break;
290 }
291
292 if (optind != argc)
293 warning("ignoring excess arguments");
294
295 /*
296 * We catch or block signals rather than ignore them,
297 * so that they get reset on exec.
298 */
299 handle(badsys, SIGSYS, 0);
300 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
301 SIGBUS, SIGXCPU, SIGXFSZ, 0);
302 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
303 SIGUSR1, SIGUSR2, 0);
304 handle(alrm_handler, SIGALRM, 0);
305 sigfillset(&mask);
306 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
307 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
308 SIGUSR1, SIGUSR2, 0);
902ec341 309 sigprocmask(SIG_SETMASK, &mask, NULL);
984263bc
MD
310 sigemptyset(&sa.sa_mask);
311 sa.sa_flags = 0;
312 sa.sa_handler = SIG_IGN;
60233e58
SW
313 sigaction(SIGTTIN, &sa, NULL);
314 sigaction(SIGTTOU, &sa, NULL);
984263bc
MD
315
316 /*
317 * Paranoia.
318 */
319 close(0);
320 close(1);
321 close(2);
322
323 /*
324 * Start the state machine.
325 */
326 transition(requested_transition);
327
328 /*
329 * Should never reach here.
330 */
331 return 1;
332}
333
334/*
335 * Associate a function with a signal handler.
336 */
b87f28fc 337static void
984263bc 338handle(sig_t handler, ...)
984263bc
MD
339{
340 int sig;
341 struct sigaction sa;
342 sigset_t mask_everything;
343 va_list ap;
984263bc 344
984263bc 345 va_start(ap, handler);
984263bc
MD
346
347 sa.sa_handler = handler;
348 sigfillset(&mask_everything);
349
eecd52b2 350 while ((sig = va_arg(ap, int)) != 0) {
984263bc
MD
351 sa.sa_mask = mask_everything;
352 /* XXX SA_RESTART? */
353 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
902ec341 354 sigaction(sig, &sa, NULL);
984263bc
MD
355 }
356 va_end(ap);
357}
358
359/*
360 * Delete a set of signals from a mask.
361 */
b87f28fc 362static void
984263bc 363delset(sigset_t *maskp, ...)
984263bc
MD
364{
365 int sig;
366 va_list ap;
984263bc 367
984263bc 368 va_start(ap, maskp);
984263bc 369
eecd52b2 370 while ((sig = va_arg(ap, int)) != 0)
984263bc
MD
371 sigdelset(maskp, sig);
372 va_end(ap);
373}
374
375/*
376 * Log a message and sleep for a while (to give someone an opportunity
377 * to read it and to save log or hardcopy output if the problem is chronic).
378 * NB: should send a message to the session logger to avoid blocking.
379 */
b87f28fc
JS
380static void
381stall(const char *message, ...)
984263bc
MD
382{
383 va_list ap;
984263bc 384
984263bc 385 va_start(ap, message);
984263bc
MD
386
387 vsyslog(LOG_ALERT, message, ap);
388 va_end(ap);
389 sleep(STALL_TIMEOUT);
390}
391
392/*
393 * Like stall(), but doesn't sleep.
394 * If cpp had variadic macros, the two functions could be #defines for another.
395 * NB: should send a message to the session logger to avoid blocking.
396 */
b87f28fc
JS
397static void
398warning(const char *message, ...)
984263bc
MD
399{
400 va_list ap;
984263bc 401
984263bc 402 va_start(ap, message);
984263bc
MD
403
404 vsyslog(LOG_ALERT, message, ap);
405 va_end(ap);
406}
407
408/*
409 * Log an emergency message.
410 * NB: should send a message to the session logger to avoid blocking.
411 */
b87f28fc
JS
412static void
413emergency(const char *message, ...)
984263bc
MD
414{
415 va_list ap;
984263bc 416
984263bc 417 va_start(ap, message);
984263bc
MD
418
419 vsyslog(LOG_EMERG, message, ap);
420 va_end(ap);
421}
422
423/*
424 * Catch a SIGSYS signal.
425 *
426 * These may arise if a system does not support sysctl.
427 * We tolerate up to 25 of these, then throw in the towel.
428 */
b87f28fc 429static void
b5744197 430badsys(int sig)
984263bc
MD
431{
432 static int badcount = 0;
433
434 if (badcount++ < 25)
435 return;
436 disaster(sig);
437}
438
439/*
440 * Catch an unexpected signal.
441 */
b87f28fc 442static void
b5744197 443disaster(int sig)
984263bc
MD
444{
445 emergency("fatal signal: %s",
446 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
447
448 sleep(STALL_TIMEOUT);
449 _exit(sig); /* reboot */
450}
451
452/*
453 * Get the security level of the kernel.
454 */
b87f28fc 455static int
b5744197 456getsecuritylevel(void)
984263bc
MD
457{
458#ifdef KERN_SECURELVL
459 int name[2], curlevel;
460 size_t len;
461
462 name[0] = CTL_KERN;
463 name[1] = KERN_SECURELVL;
464 len = sizeof curlevel;
465 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
466 emergency("cannot get kernel security level: %s",
467 strerror(errno));
468 return (-1);
469 }
470 return (curlevel);
471#else
472 return (-1);
473#endif
474}
475
0aeef1e8
MD
476/*
477 * Get the value of the "init_chroot" variable from the
478 * kernel environment (or NULL if not set).
0aeef1e8 479 */
b87f28fc
JS
480
481static char *
0aeef1e8
MD
482get_chroot(void)
483{
b87f28fc 484 static const char ichname[] = "init_chroot="; /* includes '=' */
0aeef1e8 485 const int ichlen = strlen(ichname);
b87f28fc 486 int real_oid[CTL_MAXNAME];
0aeef1e8 487 char sbuf[1024];
66e99e68 488 size_t oidlen, slen;
0aeef1e8 489 char *res;
0aeef1e8
MD
490 int i;
491
b87f28fc
JS
492 oidlen = __arysize(real_oid);
493 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
0aeef1e8
MD
494 warning("cannot find kern.environment base sysctl OID");
495 return NULL;
496 }
b87f28fc 497 if (oidlen + 1 >= __arysize(real_oid)) {
0aeef1e8
MD
498 warning("kern.environment OID is too large!");
499 return NULL;
500 }
501 res = NULL;
502 real_oid[oidlen] = 0;
503
504 for (i = 0; ; i++) {
505 real_oid[oidlen + 1] = i;
506 slen = sizeof(sbuf);
507 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
508 if (errno != ENOENT)
509 warning("sysctl kern.environment.%d: %m", i);
510 break;
511 }
512
513 /*
514 * slen includes the terminating \0, but do a few sanity
515 * checks anyway.
516 */
517 if (slen == 0)
518 continue;
519 sbuf[slen - 1] = 0;
520 if (strncmp(sbuf, ichname, ichlen) != 0)
521 continue;
522 if (sbuf[ichlen])
523 res = strdup(sbuf + ichlen);
524 break;
525 }
526 return (res);
527}
528
984263bc
MD
529/*
530 * Set the security level of the kernel.
531 */
b87f28fc 532static void
b5744197 533setsecuritylevel(int newlevel)
984263bc
MD
534{
535#ifdef KERN_SECURELVL
536 int name[2], curlevel;
537
538 curlevel = getsecuritylevel();
539 if (newlevel == curlevel)
540 return;
541 name[0] = CTL_KERN;
542 name[1] = KERN_SECURELVL;
543 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
544 emergency(
545 "cannot change kernel security level from %d to %d: %s",
546 curlevel, newlevel, strerror(errno));
547 return;
548 }
549#ifdef SECURE
550 warning("kernel security level changed from %d to %d",
551 curlevel, newlevel);
552#endif
553#endif
554}
555
556/*
557 * Change states in the finite state machine.
558 * The initial state is passed as an argument.
559 */
b87f28fc 560static void
b5744197 561transition(state_t s)
984263bc
MD
562{
563 for (;;)
564 s = (state_t) (*s)();
565}
566
567/*
568 * Close out the accounting files for a login session.
569 * NB: should send a message to the session logger to avoid blocking.
570 */
b87f28fc 571static void
b5744197 572clear_session_logs(session_t *sp)
984263bc
MD
573{
574 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
575
576 if (logout(line))
577 logwtmp(line, "", "");
578}
579
580/*
581 * Start a session and allocate a controlling terminal.
582 * Only called by children of init after forking.
583 */
b87f28fc
JS
584static void
585setctty(const char *name)
984263bc
MD
586{
587 int fd;
588
7cee7052 589 revoke(name);
984263bc
MD
590 if ((fd = open(name, O_RDWR)) == -1) {
591 stall("can't open %s: %m", name);
592 _exit(1);
593 }
594 if (login_tty(fd) == -1) {
595 stall("can't get %s for controlling terminal: %m", name);
596 _exit(1);
597 }
598}
599
600/*
601 * Bring the system up single user.
602 */
b87f28fc 603static state_func_t
b5744197 604single_user(void)
984263bc
MD
605{
606 pid_t pid, wpid;
607 int status;
608 sigset_t mask;
b87f28fc
JS
609 const char *shell = _PATH_BSHELL;
610 const char *argv[2];
984263bc
MD
611#ifdef SECURE
612 struct ttyent *typ;
613 struct passwd *pp;
614 static const char banner[] =
615 "Enter root password, or ^D to go multi-user\n";
616 char *clear, *password;
617#endif
618#ifdef DEBUGSHELL
619 char altshell[128];
620#endif
621
622 if (Reboot) {
623 /* Instead of going single user, let's reboot the machine */
624 sync();
625 alarm(2);
626 pause();
627 reboot(howto);
628 _exit(0);
629 }
630
631 if ((pid = fork()) == 0) {
632 /*
633 * Start the single user session.
634 */
635 setctty(_PATH_CONSOLE);
636
637#ifdef SECURE
638 /*
639 * Check the root password.
640 * We don't care if the console is 'on' by default;
641 * it's the only tty that can be 'off' and 'secure'.
642 */
643 typ = getttynam("console");
644 pp = getpwnam("root");
645 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
646 pp && *pp->pw_passwd) {
647 write(2, banner, sizeof banner - 1);
648 for (;;) {
649 clear = getpass("Password:");
650 if (clear == 0 || *clear == '\0')
651 _exit(0);
652 password = crypt(clear, pp->pw_passwd);
653 bzero(clear, _PASSWORD_LEN);
654 if (strcmp(password, pp->pw_passwd) == 0)
655 break;
656 warning("single-user login failed\n");
657 }
658 }
659 endttyent();
660 endpwent();
661#endif /* SECURE */
662
663#ifdef DEBUGSHELL
664 {
665 char *cp = altshell;
666 int num;
667
668#define SHREQUEST \
669 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
7cee7052 670 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
984263bc
MD
671 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
672 num != 0 && *cp != '\n' && cp < &altshell[127])
673 cp++;
674 *cp = '\0';
675 if (altshell[0] != '\0')
676 shell = altshell;
677 }
678#endif /* DEBUGSHELL */
679
680 /*
681 * Unblock signals.
682 * We catch all the interesting ones,
683 * and those are reset to SIG_DFL on exec.
684 */
685 sigemptyset(&mask);
902ec341 686 sigprocmask(SIG_SETMASK, &mask, NULL);
984263bc
MD
687
688 /*
689 * Fire off a shell.
690 * If the default one doesn't work, try the Bourne shell.
691 */
692 argv[0] = "-sh";
693 argv[1] = 0;
b87f28fc 694 execv(shell, __DECONST(char **, argv));
984263bc 695 emergency("can't exec %s for single user: %m", shell);
b87f28fc 696 execv(_PATH_BSHELL, __DECONST(char **, argv));
984263bc
MD
697 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
698 sleep(STALL_TIMEOUT);
699 _exit(1);
700 }
701
702 if (pid == -1) {
703 /*
704 * We are seriously hosed. Do our best.
705 */
706 emergency("can't fork single-user shell, trying again");
902ec341 707 while (waitpid(-1, NULL, WNOHANG) > 0)
984263bc
MD
708 continue;
709 return (state_func_t) single_user;
710 }
711
712 requested_transition = 0;
713 do {
714 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
715 collect_child(wpid);
716 if (wpid == -1) {
717 if (errno == EINTR)
718 continue;
719 warning("wait for single-user shell failed: %m; restarting");
720 return (state_func_t) single_user;
721 }
722 if (wpid == pid && WIFSTOPPED(status)) {
723 warning("init: shell stopped, restarting\n");
724 kill(pid, SIGCONT);
725 wpid = -1;
726 }
727 } while (wpid != pid && !requested_transition);
728
729 if (requested_transition)
730 return (state_func_t) requested_transition;
731
732 if (!WIFEXITED(status)) {
733 if (WTERMSIG(status) == SIGKILL) {
734 /*
735 * reboot(8) killed shell?
736 */
737 warning("single user shell terminated.");
738 sleep(STALL_TIMEOUT);
739 _exit(0);
740 } else {
741 warning("single user shell terminated, restarting");
742 return (state_func_t) single_user;
743 }
744 }
745
746 runcom_mode = FASTBOOT;
747 return (state_func_t) runcom;
748}
749
750/*
751 * Run the system startup script.
752 */
b87f28fc 753static state_func_t
b5744197 754runcom(void)
984263bc
MD
755{
756 pid_t pid, wpid;
757 int status;
b87f28fc 758 const char *argv[4];
984263bc
MD
759 struct sigaction sa;
760
761 if ((pid = fork()) == 0) {
762 sigemptyset(&sa.sa_mask);
763 sa.sa_flags = 0;
764 sa.sa_handler = SIG_IGN;
60233e58
SW
765 sigaction(SIGTSTP, &sa, NULL);
766 sigaction(SIGHUP, &sa, NULL);
984263bc
MD
767
768 setctty(_PATH_CONSOLE);
769
770 argv[0] = "sh";
771 argv[1] = _PATH_RUNCOM;
772 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
773 argv[3] = 0;
774
902ec341 775 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
984263bc
MD
776
777#ifdef LOGIN_CAP
778 setprocresources(RESOURCE_RC);
779#endif
b87f28fc 780 execv(_PATH_BSHELL, __DECONST(char **, argv));
984263bc
MD
781 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
782 _exit(1); /* force single user mode */
783 }
784
785 if (pid == -1) {
786 emergency("can't fork for %s on %s: %m",
787 _PATH_BSHELL, _PATH_RUNCOM);
902ec341 788 while (waitpid(-1, NULL, WNOHANG) > 0)
984263bc
MD
789 continue;
790 sleep(STALL_TIMEOUT);
791 return (state_func_t) single_user;
792 }
793
794 /*
795 * Copied from single_user(). This is a bit paranoid.
796 */
797 requested_transition = 0;
798 do {
799 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
800 collect_child(wpid);
801 if (wpid == -1) {
802 if (requested_transition == death)
803 return (state_func_t) death;
804 if (errno == EINTR)
805 continue;
806 warning("wait for %s on %s failed: %m; going to single user mode",
807 _PATH_BSHELL, _PATH_RUNCOM);
808 return (state_func_t) single_user;
809 }
810 if (wpid == pid && WIFSTOPPED(status)) {
811 warning("init: %s on %s stopped, restarting\n",
812 _PATH_BSHELL, _PATH_RUNCOM);
813 kill(pid, SIGCONT);
814 wpid = -1;
815 }
816 } while (wpid != pid);
817
818 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
819 requested_transition == catatonia) {
820 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
821 sigset_t s;
822
823 sigfillset(&s);
824 for (;;)
825 sigsuspend(&s);
826 }
827
828 if (!WIFEXITED(status)) {
829 warning("%s on %s terminated abnormally, going to single user mode",
830 _PATH_BSHELL, _PATH_RUNCOM);
831 return (state_func_t) single_user;
832 }
833
834 if (WEXITSTATUS(status))
835 return (state_func_t) single_user;
836
837 runcom_mode = AUTOBOOT; /* the default */
838 /* NB: should send a message to the session logger to avoid blocking. */
839 logwtmp("~", "reboot", "");
840 return (state_func_t) read_ttys;
841}
842
843/*
844 * Open the session database.
845 *
846 * NB: We could pass in the size here; is it necessary?
847 */
b87f28fc 848static int
b5744197 849start_session_db(void)
984263bc
MD
850{
851 if (session_db && (*session_db->close)(session_db))
852 emergency("session database close: %s", strerror(errno));
853 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
854 emergency("session database open: %s", strerror(errno));
855 return (1);
856 }
857 return (0);
858
859}
860
861/*
862 * Add a new login session.
863 */
b87f28fc 864static void
b5744197 865add_session(session_t *sp)
984263bc
MD
866{
867 DBT key;
868 DBT data;
869
870 key.data = &sp->se_process;
871 key.size = sizeof sp->se_process;
872 data.data = &sp;
873 data.size = sizeof sp;
874
875 if ((*session_db->put)(session_db, &key, &data, 0))
876 emergency("insert %d: %s", sp->se_process, strerror(errno));
877}
878
879/*
880 * Delete an old login session.
881 */
b87f28fc 882static void
b5744197 883del_session(session_t *sp)
984263bc
MD
884{
885 DBT key;
886
887 key.data = &sp->se_process;
888 key.size = sizeof sp->se_process;
889
890 if ((*session_db->del)(session_db, &key, 0))
891 emergency("delete %d: %s", sp->se_process, strerror(errno));
892}
893
894/*
895 * Look up a login session by pid.
896 */
b87f28fc 897static session_t *
984263bc 898find_session(pid_t pid)
984263bc
MD
899{
900 DBT key;
901 DBT data;
902 session_t *ret;
903
904 key.data = &pid;
905 key.size = sizeof pid;
906 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
907 return 0;
908 bcopy(data.data, (char *)&ret, sizeof(ret));
909 return ret;
910}
911
912/*
913 * Construct an argument vector from a command line.
914 */
b87f28fc 915static char **
b5744197 916construct_argv(char *command)
984263bc 917{
b87f28fc
JS
918 int argc = 0;
919 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
984263bc
MD
920 * sizeof (char *));
921
922 if ((argv[argc++] = strk(command)) == 0) {
923 free(argv);
924 return (NULL);
925 }
902ec341 926 while ((argv[argc++] = strk(NULL)) != NULL)
984263bc
MD
927 continue;
928 return argv;
929}
930
931/*
932 * Deallocate a session descriptor.
933 */
b87f28fc 934static void
92b053c8 935free_session(session_t *sp)
984263bc
MD
936{
937 free(sp->se_device);
938 if (sp->se_getty) {
939 free(sp->se_getty);
940 free(sp->se_getty_argv_space);
941 free(sp->se_getty_argv);
942 }
943 if (sp->se_window) {
944 free(sp->se_window);
945 free(sp->se_window_argv_space);
946 free(sp->se_window_argv);
947 }
948 if (sp->se_type)
949 free(sp->se_type);
950 free(sp);
951}
952
953/*
954 * Allocate a new session descriptor.
955 * Mark it SE_PRESENT.
956 */
b87f28fc 957static session_t *
92b053c8 958new_session(session_t *sprev, int session_index, struct ttyent *typ)
984263bc 959{
92b053c8 960 session_t *sp;
984263bc
MD
961 int fd;
962
963 if ((typ->ty_status & TTY_ON) == 0 ||
964 typ->ty_name == 0 ||
965 typ->ty_getty == 0)
966 return 0;
967
968 sp = (session_t *) calloc(1, sizeof (session_t));
969
970 sp->se_index = session_index;
971 sp->se_flags |= SE_PRESENT;
972
973 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
7cee7052 974 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
984263bc
MD
975
976 /*
977 * Attempt to open the device, if we get "device not configured"
978 * then don't add the device to the session list.
979 */
980 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
981 if (errno == ENXIO) {
982 free_session(sp);
983 return (0);
984 }
985 } else
986 close(fd);
987
988 if (setupargv(sp, typ) == 0) {
989 free_session(sp);
990 return (0);
991 }
992
993 sp->se_next = 0;
994 if (sprev == 0) {
995 sessions = sp;
996 sp->se_prev = 0;
997 } else {
998 sprev->se_next = sp;
999 sp->se_prev = sprev;
1000 }
1001
1002 return sp;
1003}
1004
1005/*
1006 * Calculate getty and if useful window argv vectors.
1007 */
b87f28fc 1008static int
b5744197 1009setupargv(session_t *sp, struct ttyent *typ)
984263bc
MD
1010{
1011
1012 if (sp->se_getty) {
1013 free(sp->se_getty);
1014 free(sp->se_getty_argv_space);
1015 free(sp->se_getty_argv);
1016 }
1017 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
7cee7052 1018 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
984263bc
MD
1019 sp->se_getty_argv_space = strdup(sp->se_getty);
1020 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1021 if (sp->se_getty_argv == 0) {
1022 warning("can't parse getty for port %s", sp->se_device);
1023 free(sp->se_getty);
1024 free(sp->se_getty_argv_space);
1025 sp->se_getty = sp->se_getty_argv_space = 0;
1026 return (0);
1027 }
1028 if (sp->se_window) {
1029 free(sp->se_window);
1030 free(sp->se_window_argv_space);
1031 free(sp->se_window_argv);
1032 }
1033 sp->se_window = sp->se_window_argv_space = 0;
1034 sp->se_window_argv = 0;
1035 if (typ->ty_window) {
1036 sp->se_window = strdup(typ->ty_window);
1037 sp->se_window_argv_space = strdup(sp->se_window);
1038 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1039 if (sp->se_window_argv == 0) {
1040 warning("can't parse window for port %s",
1041 sp->se_device);
1042 free(sp->se_window_argv_space);
1043 free(sp->se_window);
1044 sp->se_window = sp->se_window_argv_space = 0;
1045 return (0);
1046 }
1047 }
1048 if (sp->se_type)
1049 free(sp->se_type);
1050 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1051 return (1);
1052}
1053
1054/*
1055 * Walk the list of ttys and create sessions for each active line.
1056 */
b87f28fc 1057static state_func_t
b5744197 1058read_ttys(void)
984263bc
MD
1059{
1060 int session_index = 0;
92b053c8
SW
1061 session_t *sp, *snext;
1062 struct ttyent *typ;
984263bc
MD
1063
1064 /*
1065 * Destroy any previous session state.
1066 * There shouldn't be any, but just in case...
1067 */
1068 for (sp = sessions; sp; sp = snext) {
1069 if (sp->se_process)
1070 clear_session_logs(sp);
1071 snext = sp->se_next;
1072 free_session(sp);
1073 }
1074 sessions = 0;
1075 if (start_session_db())
1076 return (state_func_t) single_user;
1077
1078 /*
1079 * Allocate a session entry for each active port.
1080 * Note that sp starts at 0.
1081 */
1082 while ((typ = getttyent()) != NULL)
1083 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1084 sp = snext;
1085
1086 endttyent();
1087
1088 return (state_func_t) multi_user;
1089}
1090
1091/*
1092 * Start a window system running.
1093 */
b87f28fc 1094static void
b5744197 1095start_window_system(session_t *sp)
984263bc
MD
1096{
1097 pid_t pid;
1098 sigset_t mask;
1099 char term[64], *env[2];
1100
1101 if ((pid = fork()) == -1) {
1102 emergency("can't fork for window system on port %s: %m",
1103 sp->se_device);
1104 /* hope that getty fails and we can try again */
1105 return;
1106 }
1107
1108 if (pid)
1109 return;
1110
1111 sigemptyset(&mask);
902ec341 1112 sigprocmask(SIG_SETMASK, &mask, NULL);
984263bc
MD
1113
1114 if (setsid() < 0)
1115 emergency("setsid failed (window) %m");
1116
1117#ifdef LOGIN_CAP
1118 setprocresources(RESOURCE_WINDOW);
1119#endif
1120 if (sp->se_type) {
1121 /* Don't use malloc after fork */
1122 strcpy(term, "TERM=");
1123 strncat(term, sp->se_type, sizeof(term) - 6);
1124 env[0] = term;
1125 env[1] = 0;
1126 }
1127 else
1128 env[0] = 0;
1129 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1130 stall("can't exec window system '%s' for port %s: %m",
1131 sp->se_window_argv[0], sp->se_device);
1132 _exit(1);
1133}
1134
1135/*
1136 * Start a login session running.
1137 */
b87f28fc 1138static pid_t
b5744197 1139start_getty(session_t *sp)
984263bc
MD
1140{
1141 pid_t pid;
1142 sigset_t mask;
902ec341 1143 time_t current_time = time(NULL);
984263bc
MD
1144 int too_quick = 0;
1145 char term[64], *env[2];
1146
1147 if (current_time >= sp->se_started &&
1148 current_time - sp->se_started < GETTY_SPACING) {
1149 if (++sp->se_nspace > GETTY_NSPACE) {
1150 sp->se_nspace = 0;
1151 too_quick = 1;
1152 }
1153 } else
1154 sp->se_nspace = 0;
1155
1156 /*
1157 * fork(), not vfork() -- we can't afford to block.
1158 */
1159 if ((pid = fork()) == -1) {
1160 emergency("can't fork for getty on port %s: %m", sp->se_device);
1161 return -1;
1162 }
1163
1164 if (pid)
1165 return pid;
1166
1167 if (too_quick) {
1168 warning("getty repeating too quickly on port %s, sleeping %d secs",
1169 sp->se_device, GETTY_SLEEP);
1170 sleep((unsigned) GETTY_SLEEP);
1171 }
1172
1173 if (sp->se_window) {
1174 start_window_system(sp);
1175 sleep(WINDOW_WAIT);
1176 }
1177
1178 sigemptyset(&mask);
902ec341 1179 sigprocmask(SIG_SETMASK, &mask, NULL);
984263bc
MD
1180
1181#ifdef LOGIN_CAP
1182 setprocresources(RESOURCE_GETTY);
1183#endif
1184 if (sp->se_type) {
1185 /* Don't use malloc after fork */
1186 strcpy(term, "TERM=");
1187 strncat(term, sp->se_type, sizeof(term) - 6);
1188 env[0] = term;
1189 env[1] = 0;
1190 }
1191 else
1192 env[0] = 0;
1193 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1194 stall("can't exec getty '%s' for port %s: %m",
1195 sp->se_getty_argv[0], sp->se_device);
1196 _exit(1);
1197}
1198
1199/*
1200 * Collect exit status for a child.
1201 * If an exiting login, start a new login running.
1202 */
b87f28fc 1203static void
984263bc 1204collect_child(pid_t pid)
984263bc 1205{
92b053c8 1206 session_t *sp, *sprev, *snext;
984263bc
MD
1207
1208 if (! sessions)
1209 return;
1210
1211 if (! (sp = find_session(pid)))
1212 return;
1213
1214 clear_session_logs(sp);
1215 del_session(sp);
1216 sp->se_process = 0;
1217
1218 if (sp->se_flags & SE_SHUTDOWN) {
1219 if ((sprev = sp->se_prev) != NULL)
1220 sprev->se_next = sp->se_next;
1221 else
1222 sessions = sp->se_next;
1223 if ((snext = sp->se_next) != NULL)
1224 snext->se_prev = sp->se_prev;
1225 free_session(sp);
1226 return;
1227 }
1228
1229 if ((pid = start_getty(sp)) == -1) {
1230 /* serious trouble */
1231 requested_transition = clean_ttys;
1232 return;
1233 }
1234
1235 sp->se_process = pid;
902ec341 1236 sp->se_started = time(NULL);
984263bc
MD
1237 add_session(sp);
1238}
1239
1240/*
1241 * Catch a signal and request a state transition.
1242 */
b87f28fc 1243static void
b5744197 1244transition_handler(int sig)
984263bc
MD
1245{
1246
1247 switch (sig) {
1248 case SIGHUP:
1249 requested_transition = clean_ttys;
1250 break;
1251 case SIGUSR2:
1252 howto = RB_POWEROFF;
1253 case SIGUSR1:
1254 howto |= RB_HALT;
1255 case SIGINT:
1256 Reboot = TRUE;
1257 case SIGTERM:
1258 requested_transition = death;
1259 break;
1260 case SIGTSTP:
1261 requested_transition = catatonia;
1262 break;
1263 default:
1264 requested_transition = 0;
1265 break;
1266 }
1267}
1268
1269/*
1270 * Take the system multiuser.
1271 */
b87f28fc 1272static state_func_t
b5744197 1273multi_user(void)
984263bc
MD
1274{
1275 pid_t pid;
92b053c8 1276 session_t *sp;
984263bc
MD
1277
1278 requested_transition = 0;
1279
1280 /*
1281 * If the administrator has not set the security level to -1
1282 * to indicate that the kernel should not run multiuser in secure
1283 * mode, and the run script has not set a higher level of security
1284 * than level 1, then put the kernel into secure mode.
1285 */
1286 if (getsecuritylevel() == 0)
1287 setsecuritylevel(1);
1288
1289 for (sp = sessions; sp; sp = sp->se_next) {
1290 if (sp->se_process)
1291 continue;
1292 if ((pid = start_getty(sp)) == -1) {
1293 /* serious trouble */
1294 requested_transition = clean_ttys;
1295 break;
1296 }
1297 sp->se_process = pid;
902ec341 1298 sp->se_started = time(NULL);
984263bc
MD
1299 add_session(sp);
1300 }
1301
1302 while (!requested_transition)
902ec341 1303 if ((pid = waitpid(-1, NULL, 0)) != -1)
984263bc
MD
1304 collect_child(pid);
1305
1306 return (state_func_t) requested_transition;
1307}
1308
1309/*
1310 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1311 */
b87f28fc 1312static state_func_t
b5744197 1313clean_ttys(void)
984263bc 1314{
92b053c8
SW
1315 session_t *sp, *sprev;
1316 struct ttyent *typ;
1317 int session_index = 0;
1318 int devlen;
984263bc
MD
1319 char *old_getty, *old_window, *old_type;
1320
1321 if (! sessions)
1322 return (state_func_t) multi_user;
1323
1324 /*
1325 * mark all sessions for death, (!SE_PRESENT)
1326 * as we find or create new ones they'll be marked as keepers,
1327 * we'll later nuke all the ones not found in /etc/ttys
1328 */
1329 for (sp = sessions; sp != NULL; sp = sp->se_next)
1330 sp->se_flags &= ~SE_PRESENT;
1331
1332 devlen = sizeof(_PATH_DEV) - 1;
1333 while ((typ = getttyent()) != NULL) {
1334 ++session_index;
1335
1336 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1337 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1338 break;
1339
1340 if (sp) {
1341 /* we want this one to live */
1342 sp->se_flags |= SE_PRESENT;
1343 if (sp->se_index != session_index) {
1344 warning("port %s changed utmp index from %d to %d",
1345 sp->se_device, sp->se_index,
1346 session_index);
1347 sp->se_index = session_index;
1348 }
1349 if ((typ->ty_status & TTY_ON) == 0 ||
1350 typ->ty_getty == 0) {
1351 sp->se_flags |= SE_SHUTDOWN;
1352 kill(sp->se_process, SIGHUP);
1353 continue;
1354 }
1355 sp->se_flags &= ~SE_SHUTDOWN;
1356 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1357 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1358 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1359 if (setupargv(sp, typ) == 0) {
1360 warning("can't parse getty for port %s",
1361 sp->se_device);
1362 sp->se_flags |= SE_SHUTDOWN;
1363 kill(sp->se_process, SIGHUP);
1364 }
1365 else if ( !old_getty
1366 || (!old_type && sp->se_type)
1367 || (old_type && !sp->se_type)
1368 || (!old_window && sp->se_window)
1369 || (old_window && !sp->se_window)
1370 || (strcmp(old_getty, sp->se_getty) != 0)
1371 || (old_window && strcmp(old_window, sp->se_window) != 0)
1372 || (old_type && strcmp(old_type, sp->se_type) != 0)
1373 ) {
1374 /* Don't set SE_SHUTDOWN here */
1375 sp->se_nspace = 0;
1376 sp->se_started = 0;
1377 kill(sp->se_process, SIGHUP);
1378 }
1379 if (old_getty)
1380 free(old_getty);
1381 if (old_window)
1382 free(old_window);
1383 if (old_type)
1384 free(old_type);
1385 continue;
1386 }
1387
1388 new_session(sprev, session_index, typ);
1389 }
1390
1391 endttyent();
1392
1393 /*
1394 * sweep through and kill all deleted sessions
1395 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1396 */
1397 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1398 if ((sp->se_flags & SE_PRESENT) == 0) {
1399 sp->se_flags |= SE_SHUTDOWN;
1400 kill(sp->se_process, SIGHUP);
1401 }
1402 }
1403
1404 return (state_func_t) multi_user;
1405}
1406
1407/*
1408 * Block further logins.
1409 */
b87f28fc 1410static state_func_t
b5744197 1411catatonia(void)
984263bc 1412{
92b053c8 1413 session_t *sp;
984263bc
MD
1414
1415 for (sp = sessions; sp; sp = sp->se_next)
1416 sp->se_flags |= SE_SHUTDOWN;
1417
1418 return (state_func_t) multi_user;
1419}
1420
1421/*
1422 * Note SIGALRM.
1423 */
b87f28fc
JS
1424static void
1425alrm_handler(int sig __unused)
984263bc 1426{
984263bc
MD
1427 clang = 1;
1428}
1429
1430/*
1431 * Bring the system down to single user.
1432 */
b87f28fc 1433static state_func_t
b5744197 1434death(void)
984263bc 1435{
b87f28fc
JS
1436 session_t *sp;
1437 int i;
984263bc
MD
1438 pid_t pid;
1439 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1440
1441 /* NB: should send a message to the session logger to avoid blocking. */
1442 logwtmp("~", "shutdown", "");
1443
1444 for (sp = sessions; sp; sp = sp->se_next) {
1445 sp->se_flags |= SE_SHUTDOWN;
1446 kill(sp->se_process, SIGHUP);
1447 }
1448
1449 /* Try to run the rc.shutdown script within a period of time */
7cee7052 1450 runshutdown();
984263bc
MD
1451
1452 for (i = 0; i < 2; ++i) {
1453 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1454 return (state_func_t) single_user;
1455
1456 clang = 0;
1457 alarm(DEATH_WATCH);
1458 do
60233e58 1459 if ((pid = waitpid(-1, NULL, 0)) != -1)
984263bc
MD
1460 collect_child(pid);
1461 while (clang == 0 && errno != ECHILD);
1462
1463 if (errno == ECHILD)
1464 return (state_func_t) single_user;
1465 }
1466
1467 warning("some processes would not die; ps axl advised");
1468
1469 return (state_func_t) single_user;
1470}
1471
1472/*
1473 * Run the system shutdown script.
1474 *
1475 * Exit codes: XXX I should document more
1476 * -2 shutdown script terminated abnormally
1477 * -1 fatal error - can't run script
1478 * 0 good.
1479 * >0 some error (exit code)
1480 */
b87f28fc 1481static int
b5744197 1482runshutdown(void)
984263bc
MD
1483{
1484 pid_t pid, wpid;
1485 int status;
1486 int shutdowntimeout;
1487 size_t len;
b87f28fc 1488 const char *argv[4];
984263bc
MD
1489 struct sigaction sa;
1490 struct stat sb;
1491
1492 /*
1493 * rc.shutdown is optional, so to prevent any unnecessary
1494 * complaints from the shell we simply don't run it if the
1495 * file does not exist. If the stat() here fails for other
1496 * reasons, we'll let the shell complain.
1497 */
1498 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1499 return 0;
1500
1501 if ((pid = fork()) == 0) {
1502 int fd;
1503
1504 /* Assume that init already grab console as ctty before */
1505
1506 sigemptyset(&sa.sa_mask);
1507 sa.sa_flags = 0;
1508 sa.sa_handler = SIG_IGN;
60233e58
SW
1509 sigaction(SIGTSTP, &sa, NULL);
1510 sigaction(SIGHUP, &sa, NULL);
984263bc
MD
1511
1512 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1513 warning("can't open %s: %m", _PATH_CONSOLE);
1514 else {
7cee7052
SW
1515 dup2(fd, 0);
1516 dup2(fd, 1);
1517 dup2(fd, 2);
984263bc
MD
1518 if (fd > 2)
1519 close(fd);
1520 }
1521
1522 /*
1523 * Run the shutdown script.
1524 */
1525 argv[0] = "sh";
1526 argv[1] = _PATH_RUNDOWN;
1527 if (Reboot)
1528 argv[2] = "reboot";
1529 else
1530 argv[2] = "single";
1531 argv[3] = 0;
1532
902ec341 1533 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
984263bc
MD
1534
1535#ifdef LOGIN_CAP
1536 setprocresources(RESOURCE_RC);
1537#endif
b87f28fc 1538 execv(_PATH_BSHELL, __DECONST(char **, argv));
984263bc
MD
1539 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1540 _exit(1); /* force single user mode */
1541 }
1542
1543 if (pid == -1) {
1544 emergency("can't fork for %s on %s: %m",
1545 _PATH_BSHELL, _PATH_RUNDOWN);
902ec341 1546 while (waitpid(-1, NULL, WNOHANG) > 0)
984263bc
MD
1547 continue;
1548 sleep(STALL_TIMEOUT);
1549 return -1;
1550 }
1551
1552 len = sizeof(shutdowntimeout);
1553 if (sysctlbyname("kern.shutdown_timeout",
1554 &shutdowntimeout,
1555 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1556 shutdowntimeout = DEATH_SCRIPT;
1557 alarm(shutdowntimeout);
1558 clang = 0;
1559 /*
1560 * Copied from single_user(). This is a bit paranoid.
1561 * Use the same ALRM handler.
1562 */
1563 do {
1564 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1565 collect_child(wpid);
1566 if (clang == 1) {
1567 /* we were waiting for the sub-shell */
1568 kill(wpid, SIGTERM);
1569 warning("timeout expired for %s on %s: %m; going to single user mode",
1570 _PATH_BSHELL, _PATH_RUNDOWN);
1571 return -1;
1572 }
1573 if (wpid == -1) {
1574 if (errno == EINTR)
1575 continue;
1576 warning("wait for %s on %s failed: %m; going to single user mode",
1577 _PATH_BSHELL, _PATH_RUNDOWN);
1578 return -1;
1579 }
1580 if (wpid == pid && WIFSTOPPED(status)) {
1581 warning("init: %s on %s stopped, restarting\n",
1582 _PATH_BSHELL, _PATH_RUNDOWN);
1583 kill(pid, SIGCONT);
1584 wpid = -1;
1585 }
1586 } while (wpid != pid && !clang);
1587
1588 /* Turn off the alarm */
1589 alarm(0);
1590
1591 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1592 requested_transition == catatonia) {
1593 /*
1594 * /etc/rc.shutdown executed /sbin/reboot;
1595 * wait for the end quietly
1596 */
1597 sigset_t s;
1598
1599 sigfillset(&s);
1600 for (;;)
1601 sigsuspend(&s);
1602 }
1603
1604 if (!WIFEXITED(status)) {
1605 warning("%s on %s terminated abnormally, going to single user mode",
1606 _PATH_BSHELL, _PATH_RUNDOWN);
1607 return -2;
1608 }
1609
1610 if ((status = WEXITSTATUS(status)) != 0)
1611 warning("%s returned status %d", _PATH_RUNDOWN, status);
1612
1613 return status;
1614}
1615
b87f28fc
JS
1616static char *
1617strk(char *p)
984263bc
MD
1618{
1619 static char *t;
1620 char *q;
1621 int c;
1622
1623 if (p)
1624 t = p;
1625 if (!t)
1626 return 0;
1627
1628 c = *t;
1629 while (c == ' ' || c == '\t' )
1630 c = *++t;
1631 if (!c) {
1632 t = 0;
1633 return 0;
1634 }
1635 q = t;
1636 if (c == '\'') {
1637 c = *++t;
1638 q = t;
1639 while (c && c != '\'')
1640 c = *++t;
1641 if (!c) /* unterminated string */
1642 q = t = 0;
1643 else
1644 *t++ = 0;
1645 } else {
1646 while (c && c != ' ' && c != '\t' )
1647 c = *++t;
1648 *t++ = 0;
1649 if (!c)
1650 t = 0;
1651 }
1652 return q;
1653}
1654
1655#ifdef LOGIN_CAP
b87f28fc 1656static void
b5744197 1657setprocresources(const char *cname)
984263bc
MD
1658{
1659 login_cap_t *lc;
1660 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1661 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1662 login_close(lc);
1663 }
1664}
1665#endif