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