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