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