xref: /freebsd/sbin/init/init.c (revision 6486b015fc84e96725fef22b0e3363351399ae83)
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 	/*
576 	 * Try to open /dev/console.  Open the device with O_NONBLOCK to
577 	 * prevent potential blocking on a carrier.
578 	 */
579 	revoke(_PATH_CONSOLE);
580 	if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
581 		(void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
582 		if (login_tty(fd) == 0)
583 			return;
584 		close(fd);
585 	}
586 
587 	/* No luck.  Log output to file if possible. */
588 	if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
589 		stall("cannot open null device.");
590 		_exit(1);
591 	}
592 	if (fd != STDIN_FILENO) {
593 		dup2(fd, STDIN_FILENO);
594 		close(fd);
595 	}
596 	fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
597 	if (fd == -1)
598 		dup2(STDIN_FILENO, STDOUT_FILENO);
599 	else if (fd != STDOUT_FILENO) {
600 		dup2(fd, STDOUT_FILENO);
601 		close(fd);
602 	}
603 	dup2(STDOUT_FILENO, STDERR_FILENO);
604 }
605 
606 static const char *
607 get_shell(void)
608 {
609 	static char kenv_value[PATH_MAX];
610 
611 	if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
612 		return kenv_value;
613 	else
614 		return _PATH_BSHELL;
615 }
616 
617 static void
618 write_stderr(const char *message)
619 {
620 
621 	write(STDERR_FILENO, message, strlen(message));
622 }
623 
624 /*
625  * Bring the system up single user.
626  */
627 static state_func_t
628 single_user(void)
629 {
630 	pid_t pid, wpid;
631 	int status;
632 	sigset_t mask;
633 	const char *shell;
634 	char *argv[2];
635 #ifdef SECURE
636 	struct ttyent *typ;
637 	struct passwd *pp;
638 	static const char banner[] =
639 		"Enter root password, or ^D to go multi-user\n";
640 	char *clear, *password;
641 #endif
642 #ifdef DEBUGSHELL
643 	char altshell[128];
644 #endif
645 
646 	if (Reboot) {
647 		/* Instead of going single user, let's reboot the machine */
648 		sync();
649 		alarm(2);
650 		pause();
651 		reboot(howto);
652 		_exit(0);
653 	}
654 
655 	shell = get_shell();
656 
657 	if ((pid = fork()) == 0) {
658 		/*
659 		 * Start the single user session.
660 		 */
661 		open_console();
662 
663 #ifdef SECURE
664 		/*
665 		 * Check the root password.
666 		 * We don't care if the console is 'on' by default;
667 		 * it's the only tty that can be 'off' and 'secure'.
668 		 */
669 		typ = getttynam("console");
670 		pp = getpwnam("root");
671 		if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
672 		    pp && *pp->pw_passwd) {
673 			write_stderr(banner);
674 			for (;;) {
675 				clear = getpass("Password:");
676 				if (clear == 0 || *clear == '\0')
677 					_exit(0);
678 				password = crypt(clear, pp->pw_passwd);
679 				bzero(clear, _PASSWORD_LEN);
680 				if (password == NULL ||
681 				    strcmp(password, pp->pw_passwd) == 0)
682 					break;
683 				warning("single-user login failed\n");
684 			}
685 		}
686 		endttyent();
687 		endpwent();
688 #endif /* SECURE */
689 
690 #ifdef DEBUGSHELL
691 		{
692 			char *cp = altshell;
693 			int num;
694 
695 #define	SHREQUEST "Enter full pathname of shell or RETURN for "
696 			write_stderr(SHREQUEST);
697 			write_stderr(shell);
698 			write_stderr(": ");
699 			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
700 			    num != 0 && *cp != '\n' && cp < &altshell[127])
701 				cp++;
702 			*cp = '\0';
703 			if (altshell[0] != '\0')
704 				shell = altshell;
705 		}
706 #endif /* DEBUGSHELL */
707 
708 		/*
709 		 * Unblock signals.
710 		 * We catch all the interesting ones,
711 		 * and those are reset to SIG_DFL on exec.
712 		 */
713 		sigemptyset(&mask);
714 		sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
715 
716 		/*
717 		 * Fire off a shell.
718 		 * If the default one doesn't work, try the Bourne shell.
719 		 */
720 
721 		char name[] = "-sh";
722 
723 		argv[0] = name;
724 		argv[1] = 0;
725 		execv(shell, argv);
726 		emergency("can't exec %s for single user: %m", shell);
727 		execv(_PATH_BSHELL, argv);
728 		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
729 		sleep(STALL_TIMEOUT);
730 		_exit(1);
731 	}
732 
733 	if (pid == -1) {
734 		/*
735 		 * We are seriously hosed.  Do our best.
736 		 */
737 		emergency("can't fork single-user shell, trying again");
738 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
739 			continue;
740 		return (state_func_t) single_user;
741 	}
742 
743 	requested_transition = 0;
744 	do {
745 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
746 			collect_child(wpid);
747 		if (wpid == -1) {
748 			if (errno == EINTR)
749 				continue;
750 			warning("wait for single-user shell failed: %m; restarting");
751 			return (state_func_t) single_user;
752 		}
753 		if (wpid == pid && WIFSTOPPED(status)) {
754 			warning("init: shell stopped, restarting\n");
755 			kill(pid, SIGCONT);
756 			wpid = -1;
757 		}
758 	} while (wpid != pid && !requested_transition);
759 
760 	if (requested_transition)
761 		return (state_func_t) requested_transition;
762 
763 	if (!WIFEXITED(status)) {
764 		if (WTERMSIG(status) == SIGKILL) {
765 			/*
766 			 *  reboot(8) killed shell?
767 			 */
768 			warning("single user shell terminated.");
769 			sleep(STALL_TIMEOUT);
770 			_exit(0);
771 		} else {
772 			warning("single user shell terminated, restarting");
773 			return (state_func_t) single_user;
774 		}
775 	}
776 
777 	runcom_mode = FASTBOOT;
778 	return (state_func_t) runcom;
779 }
780 
781 /*
782  * Run the system startup script.
783  */
784 static state_func_t
785 runcom(void)
786 {
787 	state_func_t next_transition;
788 
789 	if ((next_transition = run_script(_PATH_RUNCOM)) != 0)
790 		return next_transition;
791 
792 	runcom_mode = AUTOBOOT;		/* the default */
793 	return (state_func_t) read_ttys;
794 }
795 
796 /*
797  * Run a shell script.
798  * Returns 0 on success, otherwise the next transition to enter:
799  *  - single_user if fork/execv/waitpid failed, or if the script
800  *    terminated with a signal or exit code != 0.
801  *  - death_single if a SIGTERM was delivered to init(8).
802  */
803 static state_func_t
804 run_script(const char *script)
805 {
806 	pid_t pid, wpid;
807 	int status;
808 	char *argv[4];
809 	const char *shell;
810 	struct sigaction sa;
811 
812 	shell = get_shell();
813 
814 	if ((pid = fork()) == 0) {
815 		sigemptyset(&sa.sa_mask);
816 		sa.sa_flags = 0;
817 		sa.sa_handler = SIG_IGN;
818 		sigaction(SIGTSTP, &sa, (struct sigaction *)0);
819 		sigaction(SIGHUP, &sa, (struct sigaction *)0);
820 
821 		open_console();
822 
823 		char _sh[]		= "sh";
824 		char _autoboot[]	= "autoboot";
825 
826 		argv[0] = _sh;
827 		argv[1] = __DECONST(char *, script);
828 		argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
829 		argv[3] = 0;
830 
831 		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
832 
833 #ifdef LOGIN_CAP
834 		setprocresources(RESOURCE_RC);
835 #endif
836 		execv(shell, argv);
837 		stall("can't exec %s for %s: %m", shell, script);
838 		_exit(1);	/* force single user mode */
839 	}
840 
841 	if (pid == -1) {
842 		emergency("can't fork for %s on %s: %m", shell, script);
843 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
844 			continue;
845 		sleep(STALL_TIMEOUT);
846 		return (state_func_t) single_user;
847 	}
848 
849 	/*
850 	 * Copied from single_user().  This is a bit paranoid.
851 	 */
852 	requested_transition = 0;
853 	do {
854 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
855 			collect_child(wpid);
856 		if (wpid == -1) {
857 			if (requested_transition == death_single)
858 				return (state_func_t) death_single;
859 			if (errno == EINTR)
860 				continue;
861 			warning("wait for %s on %s failed: %m; going to "
862 			    "single user mode", shell, script);
863 			return (state_func_t) single_user;
864 		}
865 		if (wpid == pid && WIFSTOPPED(status)) {
866 			warning("init: %s on %s stopped, restarting\n",
867 			    shell, script);
868 			kill(pid, SIGCONT);
869 			wpid = -1;
870 		}
871 	} while (wpid != pid);
872 
873 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
874 	    requested_transition == catatonia) {
875 		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
876 		sigset_t s;
877 
878 		sigfillset(&s);
879 		for (;;)
880 			sigsuspend(&s);
881 	}
882 
883 	if (!WIFEXITED(status)) {
884 		warning("%s on %s terminated abnormally, going to single "
885 		    "user mode", shell, script);
886 		return (state_func_t) single_user;
887 	}
888 
889 	if (WEXITSTATUS(status))
890 		return (state_func_t) single_user;
891 
892 	return (state_func_t) 0;
893 }
894 
895 /*
896  * Open the session database.
897  *
898  * NB: We could pass in the size here; is it necessary?
899  */
900 static int
901 start_session_db(void)
902 {
903 	if (session_db && (*session_db->close)(session_db))
904 		emergency("session database close: %s", strerror(errno));
905 	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
906 		emergency("session database open: %s", strerror(errno));
907 		return (1);
908 	}
909 	return (0);
910 
911 }
912 
913 /*
914  * Add a new login session.
915  */
916 static void
917 add_session(session_t *sp)
918 {
919 	DBT key;
920 	DBT data;
921 
922 	key.data = &sp->se_process;
923 	key.size = sizeof sp->se_process;
924 	data.data = &sp;
925 	data.size = sizeof sp;
926 
927 	if ((*session_db->put)(session_db, &key, &data, 0))
928 		emergency("insert %d: %s", sp->se_process, strerror(errno));
929 }
930 
931 /*
932  * Delete an old login session.
933  */
934 static void
935 del_session(session_t *sp)
936 {
937 	DBT key;
938 
939 	key.data = &sp->se_process;
940 	key.size = sizeof sp->se_process;
941 
942 	if ((*session_db->del)(session_db, &key, 0))
943 		emergency("delete %d: %s", sp->se_process, strerror(errno));
944 }
945 
946 /*
947  * Look up a login session by pid.
948  */
949 static session_t *
950 find_session(pid_t pid)
951 {
952 	DBT key;
953 	DBT data;
954 	session_t *ret;
955 
956 	key.data = &pid;
957 	key.size = sizeof pid;
958 	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
959 		return 0;
960 	bcopy(data.data, (char *)&ret, sizeof(ret));
961 	return ret;
962 }
963 
964 /*
965  * Construct an argument vector from a command line.
966  */
967 static char **
968 construct_argv(char *command)
969 {
970 	int argc = 0;
971 	char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
972 						* sizeof (char *));
973 
974 	if ((argv[argc++] = strk(command)) == 0) {
975 		free(argv);
976 		return (NULL);
977 	}
978 	while ((argv[argc++] = strk((char *) 0)) != NULL)
979 		continue;
980 	return argv;
981 }
982 
983 /*
984  * Deallocate a session descriptor.
985  */
986 static void
987 free_session(session_t *sp)
988 {
989 	free(sp->se_device);
990 	if (sp->se_getty) {
991 		free(sp->se_getty);
992 		free(sp->se_getty_argv_space);
993 		free(sp->se_getty_argv);
994 	}
995 	if (sp->se_window) {
996 		free(sp->se_window);
997 		free(sp->se_window_argv_space);
998 		free(sp->se_window_argv);
999 	}
1000 	if (sp->se_type)
1001 		free(sp->se_type);
1002 	free(sp);
1003 }
1004 
1005 /*
1006  * Allocate a new session descriptor.
1007  * Mark it SE_PRESENT.
1008  */
1009 static session_t *
1010 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1011 {
1012 	session_t *sp;
1013 	int fd;
1014 
1015 	if ((typ->ty_status & TTY_ON) == 0 ||
1016 	    typ->ty_name == 0 ||
1017 	    typ->ty_getty == 0)
1018 		return 0;
1019 
1020 	sp = (session_t *) calloc(1, sizeof (session_t));
1021 
1022 	sp->se_index = session_index;
1023 	sp->se_flags |= SE_PRESENT;
1024 
1025 	sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1026 	sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1027 
1028 	/*
1029 	 * Attempt to open the device, if we get "device not configured"
1030 	 * then don't add the device to the session list.
1031 	 */
1032 	if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1033 		if (errno == ENXIO) {
1034 			free_session(sp);
1035 			return (0);
1036 		}
1037 	} else
1038 		close(fd);
1039 
1040 	if (setupargv(sp, typ) == 0) {
1041 		free_session(sp);
1042 		return (0);
1043 	}
1044 
1045 	sp->se_next = 0;
1046 	if (sprev == 0) {
1047 		sessions = sp;
1048 		sp->se_prev = 0;
1049 	} else {
1050 		sprev->se_next = sp;
1051 		sp->se_prev = sprev;
1052 	}
1053 
1054 	return sp;
1055 }
1056 
1057 /*
1058  * Calculate getty and if useful window argv vectors.
1059  */
1060 static int
1061 setupargv(session_t *sp, struct ttyent *typ)
1062 {
1063 
1064 	if (sp->se_getty) {
1065 		free(sp->se_getty);
1066 		free(sp->se_getty_argv_space);
1067 		free(sp->se_getty_argv);
1068 	}
1069 	sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1070 	sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1071 	sp->se_getty_argv_space = strdup(sp->se_getty);
1072 	sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1073 	if (sp->se_getty_argv == 0) {
1074 		warning("can't parse getty for port %s", sp->se_device);
1075 		free(sp->se_getty);
1076 		free(sp->se_getty_argv_space);
1077 		sp->se_getty = sp->se_getty_argv_space = 0;
1078 		return (0);
1079 	}
1080 	if (sp->se_window) {
1081 		free(sp->se_window);
1082 		free(sp->se_window_argv_space);
1083 		free(sp->se_window_argv);
1084 	}
1085 	sp->se_window = sp->se_window_argv_space = 0;
1086 	sp->se_window_argv = 0;
1087 	if (typ->ty_window) {
1088 		sp->se_window = strdup(typ->ty_window);
1089 		sp->se_window_argv_space = strdup(sp->se_window);
1090 		sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1091 		if (sp->se_window_argv == 0) {
1092 			warning("can't parse window for port %s",
1093 			    sp->se_device);
1094 			free(sp->se_window_argv_space);
1095 			free(sp->se_window);
1096 			sp->se_window = sp->se_window_argv_space = 0;
1097 			return (0);
1098 		}
1099 	}
1100 	if (sp->se_type)
1101 		free(sp->se_type);
1102 	sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1103 	return (1);
1104 }
1105 
1106 /*
1107  * Walk the list of ttys and create sessions for each active line.
1108  */
1109 static state_func_t
1110 read_ttys(void)
1111 {
1112 	int session_index = 0;
1113 	session_t *sp, *snext;
1114 	struct ttyent *typ;
1115 
1116 	/*
1117 	 * Destroy any previous session state.
1118 	 * There shouldn't be any, but just in case...
1119 	 */
1120 	for (sp = sessions; sp; sp = snext) {
1121 		snext = sp->se_next;
1122 		free_session(sp);
1123 	}
1124 	sessions = 0;
1125 	if (start_session_db())
1126 		return (state_func_t) single_user;
1127 
1128 	/*
1129 	 * Allocate a session entry for each active port.
1130 	 * Note that sp starts at 0.
1131 	 */
1132 	while ((typ = getttyent()) != NULL)
1133 		if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1134 			sp = snext;
1135 
1136 	endttyent();
1137 
1138 	return (state_func_t) multi_user;
1139 }
1140 
1141 /*
1142  * Start a window system running.
1143  */
1144 static void
1145 start_window_system(session_t *sp)
1146 {
1147 	pid_t pid;
1148 	sigset_t mask;
1149 	char term[64], *env[2];
1150 	int status;
1151 
1152 	if ((pid = fork()) == -1) {
1153 		emergency("can't fork for window system on port %s: %m",
1154 		    sp->se_device);
1155 		/* hope that getty fails and we can try again */
1156 		return;
1157 	}
1158 	if (pid) {
1159 		waitpid(-1, &status, 0);
1160 		return;
1161 	}
1162 
1163 	/* reparent window process to the init to not make a zombie on exit */
1164 	if ((pid = fork()) == -1) {
1165 		emergency("can't fork for window system on port %s: %m",
1166 		    sp->se_device);
1167 		_exit(1);
1168 	}
1169 	if (pid)
1170 		_exit(0);
1171 
1172 	sigemptyset(&mask);
1173 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1174 
1175 	if (setsid() < 0)
1176 		emergency("setsid failed (window) %m");
1177 
1178 #ifdef LOGIN_CAP
1179 	setprocresources(RESOURCE_WINDOW);
1180 #endif
1181 	if (sp->se_type) {
1182 		/* Don't use malloc after fork */
1183 		strcpy(term, "TERM=");
1184 		strncat(term, sp->se_type, sizeof(term) - 6);
1185 		env[0] = term;
1186 		env[1] = 0;
1187 	}
1188 	else
1189 		env[0] = 0;
1190 	execve(sp->se_window_argv[0], sp->se_window_argv, env);
1191 	stall("can't exec window system '%s' for port %s: %m",
1192 		sp->se_window_argv[0], sp->se_device);
1193 	_exit(1);
1194 }
1195 
1196 /*
1197  * Start a login session running.
1198  */
1199 static pid_t
1200 start_getty(session_t *sp)
1201 {
1202 	pid_t pid;
1203 	sigset_t mask;
1204 	time_t current_time = time((time_t *) 0);
1205 	int too_quick = 0;
1206 	char term[64], *env[2];
1207 
1208 	if (current_time >= sp->se_started &&
1209 	    current_time - sp->se_started < GETTY_SPACING) {
1210 		if (++sp->se_nspace > GETTY_NSPACE) {
1211 			sp->se_nspace = 0;
1212 			too_quick = 1;
1213 		}
1214 	} else
1215 		sp->se_nspace = 0;
1216 
1217 	/*
1218 	 * fork(), not vfork() -- we can't afford to block.
1219 	 */
1220 	if ((pid = fork()) == -1) {
1221 		emergency("can't fork for getty on port %s: %m", sp->se_device);
1222 		return -1;
1223 	}
1224 
1225 	if (pid)
1226 		return pid;
1227 
1228 	if (too_quick) {
1229 		warning("getty repeating too quickly on port %s, sleeping %d secs",
1230 		    sp->se_device, GETTY_SLEEP);
1231 		sleep((unsigned) GETTY_SLEEP);
1232 	}
1233 
1234 	if (sp->se_window) {
1235 		start_window_system(sp);
1236 		sleep(WINDOW_WAIT);
1237 	}
1238 
1239 	sigemptyset(&mask);
1240 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1241 
1242 #ifdef LOGIN_CAP
1243 	setprocresources(RESOURCE_GETTY);
1244 #endif
1245 	if (sp->se_type) {
1246 		/* Don't use malloc after fork */
1247 		strcpy(term, "TERM=");
1248 		strncat(term, sp->se_type, sizeof(term) - 6);
1249 		env[0] = term;
1250 		env[1] = 0;
1251 	} else
1252 		env[0] = 0;
1253 	execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1254 	stall("can't exec getty '%s' for port %s: %m",
1255 		sp->se_getty_argv[0], sp->se_device);
1256 	_exit(1);
1257 }
1258 
1259 /*
1260  * Collect exit status for a child.
1261  * If an exiting login, start a new login running.
1262  */
1263 static void
1264 collect_child(pid_t pid)
1265 {
1266 	session_t *sp, *sprev, *snext;
1267 
1268 	if (! sessions)
1269 		return;
1270 
1271 	if (! (sp = find_session(pid)))
1272 		return;
1273 
1274 	del_session(sp);
1275 	sp->se_process = 0;
1276 
1277 	if (sp->se_flags & SE_SHUTDOWN) {
1278 		if ((sprev = sp->se_prev) != NULL)
1279 			sprev->se_next = sp->se_next;
1280 		else
1281 			sessions = sp->se_next;
1282 		if ((snext = sp->se_next) != NULL)
1283 			snext->se_prev = sp->se_prev;
1284 		free_session(sp);
1285 		return;
1286 	}
1287 
1288 	if ((pid = start_getty(sp)) == -1) {
1289 		/* serious trouble */
1290 		requested_transition = clean_ttys;
1291 		return;
1292 	}
1293 
1294 	sp->se_process = pid;
1295 	sp->se_started = time((time_t *) 0);
1296 	add_session(sp);
1297 }
1298 
1299 /*
1300  * Catch a signal and request a state transition.
1301  */
1302 static void
1303 transition_handler(int sig)
1304 {
1305 
1306 	switch (sig) {
1307 	case SIGHUP:
1308 		if (current_state == read_ttys || current_state == multi_user ||
1309 		    current_state == clean_ttys || current_state == catatonia)
1310 			requested_transition = clean_ttys;
1311 		break;
1312 	case SIGUSR2:
1313 		howto = RB_POWEROFF;
1314 	case SIGUSR1:
1315 		howto |= RB_HALT;
1316 	case SIGINT:
1317 		Reboot = TRUE;
1318 	case SIGTERM:
1319 		if (current_state == read_ttys || current_state == multi_user ||
1320 		    current_state == clean_ttys || current_state == catatonia)
1321 			requested_transition = death;
1322 		else
1323 			requested_transition = death_single;
1324 		break;
1325 	case SIGTSTP:
1326 		if (current_state == runcom || current_state == read_ttys ||
1327 		    current_state == clean_ttys ||
1328 		    current_state == multi_user || current_state == catatonia)
1329 			requested_transition = catatonia;
1330 		break;
1331 	default:
1332 		requested_transition = 0;
1333 		break;
1334 	}
1335 }
1336 
1337 /*
1338  * Take the system multiuser.
1339  */
1340 static state_func_t
1341 multi_user(void)
1342 {
1343 	pid_t pid;
1344 	session_t *sp;
1345 
1346 	requested_transition = 0;
1347 
1348 	/*
1349 	 * If the administrator has not set the security level to -1
1350 	 * to indicate that the kernel should not run multiuser in secure
1351 	 * mode, and the run script has not set a higher level of security
1352 	 * than level 1, then put the kernel into secure mode.
1353 	 */
1354 	if (getsecuritylevel() == 0)
1355 		setsecuritylevel(1);
1356 
1357 	for (sp = sessions; sp; sp = sp->se_next) {
1358 		if (sp->se_process)
1359 			continue;
1360 		if ((pid = start_getty(sp)) == -1) {
1361 			/* serious trouble */
1362 			requested_transition = clean_ttys;
1363 			break;
1364 		}
1365 		sp->se_process = pid;
1366 		sp->se_started = time((time_t *) 0);
1367 		add_session(sp);
1368 	}
1369 
1370 	while (!requested_transition)
1371 		if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1372 			collect_child(pid);
1373 
1374 	return (state_func_t) requested_transition;
1375 }
1376 
1377 /*
1378  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1379  */
1380 static state_func_t
1381 clean_ttys(void)
1382 {
1383 	session_t *sp, *sprev;
1384 	struct ttyent *typ;
1385 	int session_index = 0;
1386 	int devlen;
1387 	char *old_getty, *old_window, *old_type;
1388 
1389 	/*
1390 	 * mark all sessions for death, (!SE_PRESENT)
1391 	 * as we find or create new ones they'll be marked as keepers,
1392 	 * we'll later nuke all the ones not found in /etc/ttys
1393 	 */
1394 	for (sp = sessions; sp != NULL; sp = sp->se_next)
1395 		sp->se_flags &= ~SE_PRESENT;
1396 
1397 	devlen = sizeof(_PATH_DEV) - 1;
1398 	while ((typ = getttyent()) != NULL) {
1399 		++session_index;
1400 
1401 		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1402 			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1403 				break;
1404 
1405 		if (sp) {
1406 			/* we want this one to live */
1407 			sp->se_flags |= SE_PRESENT;
1408 			if (sp->se_index != session_index) {
1409 				warning("port %s changed utmp index from %d to %d",
1410 				       sp->se_device, sp->se_index,
1411 				       session_index);
1412 				sp->se_index = session_index;
1413 			}
1414 			if ((typ->ty_status & TTY_ON) == 0 ||
1415 			    typ->ty_getty == 0) {
1416 				sp->se_flags |= SE_SHUTDOWN;
1417 				kill(sp->se_process, SIGHUP);
1418 				continue;
1419 			}
1420 			sp->se_flags &= ~SE_SHUTDOWN;
1421 			old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1422 			old_window = sp->se_window ? strdup(sp->se_window) : 0;
1423 			old_type = sp->se_type ? strdup(sp->se_type) : 0;
1424 			if (setupargv(sp, typ) == 0) {
1425 				warning("can't parse getty for port %s",
1426 					sp->se_device);
1427 				sp->se_flags |= SE_SHUTDOWN;
1428 				kill(sp->se_process, SIGHUP);
1429 			}
1430 			else if (   !old_getty
1431 				 || (!old_type && sp->se_type)
1432 				 || (old_type && !sp->se_type)
1433 				 || (!old_window && sp->se_window)
1434 				 || (old_window && !sp->se_window)
1435 				 || (strcmp(old_getty, sp->se_getty) != 0)
1436 				 || (old_window && strcmp(old_window, sp->se_window) != 0)
1437 				 || (old_type && strcmp(old_type, sp->se_type) != 0)
1438 				) {
1439 				/* Don't set SE_SHUTDOWN here */
1440 				sp->se_nspace = 0;
1441 				sp->se_started = 0;
1442 				kill(sp->se_process, SIGHUP);
1443 			}
1444 			if (old_getty)
1445 				free(old_getty);
1446 			if (old_window)
1447 				free(old_window);
1448 			if (old_type)
1449 				free(old_type);
1450 			continue;
1451 		}
1452 
1453 		new_session(sprev, session_index, typ);
1454 	}
1455 
1456 	endttyent();
1457 
1458 	/*
1459 	 * sweep through and kill all deleted sessions
1460 	 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1461 	 */
1462 	for (sp = sessions; sp != NULL; sp = sp->se_next) {
1463 		if ((sp->se_flags & SE_PRESENT) == 0) {
1464 			sp->se_flags |= SE_SHUTDOWN;
1465 			kill(sp->se_process, SIGHUP);
1466 		}
1467 	}
1468 
1469 	return (state_func_t) multi_user;
1470 }
1471 
1472 /*
1473  * Block further logins.
1474  */
1475 static state_func_t
1476 catatonia(void)
1477 {
1478 	session_t *sp;
1479 
1480 	for (sp = sessions; sp; sp = sp->se_next)
1481 		sp->se_flags |= SE_SHUTDOWN;
1482 
1483 	return (state_func_t) multi_user;
1484 }
1485 
1486 /*
1487  * Note SIGALRM.
1488  */
1489 static void
1490 alrm_handler(int sig)
1491 {
1492 
1493 	(void)sig;
1494 	clang = 1;
1495 }
1496 
1497 /*
1498  * Bring the system down to single user.
1499  */
1500 static state_func_t
1501 death(void)
1502 {
1503 	session_t *sp;
1504 
1505 	/*
1506 	 * Also revoke the TTY here.  Because runshutdown() may reopen
1507 	 * the TTY whose getty we're killing here, there is no guarantee
1508 	 * runshutdown() will perform the initial open() call, causing
1509 	 * the terminal attributes to be misconfigured.
1510 	 */
1511 	for (sp = sessions; sp; sp = sp->se_next) {
1512 		sp->se_flags |= SE_SHUTDOWN;
1513 		kill(sp->se_process, SIGHUP);
1514 		revoke(sp->se_device);
1515 	}
1516 
1517 	/* Try to run the rc.shutdown script within a period of time */
1518 	runshutdown();
1519 
1520 	return (state_func_t) death_single;
1521 }
1522 
1523 /*
1524  * Do what is necessary to reinitialize single user mode or reboot
1525  * from an incomplete state.
1526  */
1527 static state_func_t
1528 death_single(void)
1529 {
1530 	int i;
1531 	pid_t pid;
1532 	static const int death_sigs[2] = { SIGTERM, SIGKILL };
1533 
1534 	revoke(_PATH_CONSOLE);
1535 
1536 	for (i = 0; i < 2; ++i) {
1537 		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1538 			return (state_func_t) single_user;
1539 
1540 		clang = 0;
1541 		alarm(DEATH_WATCH);
1542 		do
1543 			if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1544 				collect_child(pid);
1545 		while (clang == 0 && errno != ECHILD);
1546 
1547 		if (errno == ECHILD)
1548 			return (state_func_t) single_user;
1549 	}
1550 
1551 	warning("some processes would not die; ps axl advised");
1552 
1553 	return (state_func_t) single_user;
1554 }
1555 
1556 /*
1557  * Run the system shutdown script.
1558  *
1559  * Exit codes:      XXX I should document more
1560  * -2       shutdown script terminated abnormally
1561  * -1       fatal error - can't run script
1562  * 0        good.
1563  * >0       some error (exit code)
1564  */
1565 static int
1566 runshutdown(void)
1567 {
1568 	pid_t pid, wpid;
1569 	int status;
1570 	int shutdowntimeout;
1571 	size_t len;
1572 	char *argv[4];
1573 	const char *shell;
1574 	struct sigaction sa;
1575 	struct stat sb;
1576 
1577 	/*
1578 	 * rc.shutdown is optional, so to prevent any unnecessary
1579 	 * complaints from the shell we simply don't run it if the
1580 	 * file does not exist. If the stat() here fails for other
1581 	 * reasons, we'll let the shell complain.
1582 	 */
1583 	if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1584 		return 0;
1585 
1586 	shell = get_shell();
1587 
1588 	if ((pid = fork()) == 0) {
1589 		sigemptyset(&sa.sa_mask);
1590 		sa.sa_flags = 0;
1591 		sa.sa_handler = SIG_IGN;
1592 		sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1593 		sigaction(SIGHUP, &sa, (struct sigaction *)0);
1594 
1595 		open_console();
1596 
1597 		char _sh[]	= "sh";
1598 		char _reboot[]	= "reboot";
1599 		char _single[]	= "single";
1600 		char _path_rundown[] = _PATH_RUNDOWN;
1601 
1602 		argv[0] = _sh;
1603 		argv[1] = _path_rundown;
1604 		argv[2] = Reboot ? _reboot : _single;
1605 		argv[3] = 0;
1606 
1607 		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1608 
1609 #ifdef LOGIN_CAP
1610 		setprocresources(RESOURCE_RC);
1611 #endif
1612 		execv(shell, argv);
1613 		warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1614 		_exit(1);	/* force single user mode */
1615 	}
1616 
1617 	if (pid == -1) {
1618 		emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1619 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1620 			continue;
1621 		sleep(STALL_TIMEOUT);
1622 		return -1;
1623 	}
1624 
1625 	len = sizeof(shutdowntimeout);
1626 	if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1627 	    NULL, 0) == -1 || shutdowntimeout < 2)
1628 		shutdowntimeout = DEATH_SCRIPT;
1629 	alarm(shutdowntimeout);
1630 	clang = 0;
1631 	/*
1632 	 * Copied from single_user().  This is a bit paranoid.
1633 	 * Use the same ALRM handler.
1634 	 */
1635 	do {
1636 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1637 			collect_child(wpid);
1638 		if (clang == 1) {
1639 			/* we were waiting for the sub-shell */
1640 			kill(wpid, SIGTERM);
1641 			warning("timeout expired for %s on %s: %m; going to "
1642 			    "single user mode", shell, _PATH_RUNDOWN);
1643 			return -1;
1644 		}
1645 		if (wpid == -1) {
1646 			if (errno == EINTR)
1647 				continue;
1648 			warning("wait for %s on %s failed: %m; going to "
1649 			    "single user mode", shell, _PATH_RUNDOWN);
1650 			return -1;
1651 		}
1652 		if (wpid == pid && WIFSTOPPED(status)) {
1653 			warning("init: %s on %s stopped, restarting\n",
1654 				shell, _PATH_RUNDOWN);
1655 			kill(pid, SIGCONT);
1656 			wpid = -1;
1657 		}
1658 	} while (wpid != pid && !clang);
1659 
1660 	/* Turn off the alarm */
1661 	alarm(0);
1662 
1663 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1664 	    requested_transition == catatonia) {
1665 		/*
1666 		 * /etc/rc.shutdown executed /sbin/reboot;
1667 		 * wait for the end quietly
1668 		 */
1669 		sigset_t s;
1670 
1671 		sigfillset(&s);
1672 		for (;;)
1673 			sigsuspend(&s);
1674 	}
1675 
1676 	if (!WIFEXITED(status)) {
1677 		warning("%s on %s terminated abnormally, going to "
1678 		    "single user mode", shell, _PATH_RUNDOWN);
1679 		return -2;
1680 	}
1681 
1682 	if ((status = WEXITSTATUS(status)) != 0)
1683 		warning("%s returned status %d", _PATH_RUNDOWN, status);
1684 
1685 	return status;
1686 }
1687 
1688 static char *
1689 strk(char *p)
1690 {
1691 	static char *t;
1692 	char *q;
1693 	int c;
1694 
1695 	if (p)
1696 		t = p;
1697 	if (!t)
1698 		return 0;
1699 
1700 	c = *t;
1701 	while (c == ' ' || c == '\t' )
1702 		c = *++t;
1703 	if (!c) {
1704 		t = 0;
1705 		return 0;
1706 	}
1707 	q = t;
1708 	if (c == '\'') {
1709 		c = *++t;
1710 		q = t;
1711 		while (c && c != '\'')
1712 			c = *++t;
1713 		if (!c)  /* unterminated string */
1714 			q = t = 0;
1715 		else
1716 			*t++ = 0;
1717 	} else {
1718 		while (c && c != ' ' && c != '\t' )
1719 			c = *++t;
1720 		*t++ = 0;
1721 		if (!c)
1722 			t = 0;
1723 	}
1724 	return q;
1725 }
1726 
1727 #ifdef LOGIN_CAP
1728 static void
1729 setprocresources(const char *cname)
1730 {
1731 	login_cap_t *lc;
1732 	if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1733 		setusercontext(lc, (struct passwd*)NULL, 0,
1734 		    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES);
1735 		login_close(lc);
1736 	}
1737 }
1738 #endif
1739