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