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