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