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