Home | History | Annotate | Line # | Download | only in init
init.c revision 1.12
      1 /*-
      2  * Copyright (c) 1991 The Regents of the University of California.
      3  * All rights reserved.
      4  *
      5  * This code is derived from software contributed to Berkeley by
      6  * Donn Seeley at Berkeley Software Design, Inc.
      7  *
      8  * Redistribution and use in source and binary forms, with or without
      9  * modification, are permitted provided that the following conditions
     10  * are met:
     11  * 1. Redistributions of source code must retain the above copyright
     12  *    notice, this list of conditions and the following disclaimer.
     13  * 2. Redistributions in binary form must reproduce the above copyright
     14  *    notice, this list of conditions and the following disclaimer in the
     15  *    documentation and/or other materials provided with the distribution.
     16  * 3. All advertising materials mentioning features or use of this software
     17  *    must display the following acknowledgement:
     18  *	This product includes software developed by the University of
     19  *	California, Berkeley and its contributors.
     20  * 4. Neither the name of the University nor the names of its contributors
     21  *    may be used to endorse or promote products derived from this software
     22  *    without specific prior written permission.
     23  *
     24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     34  * SUCH DAMAGE.
     35  */
     36 
     37 #ifndef lint
     38 char copyright[] =
     39 "@(#) Copyright (c) 1991 The Regents of the University of California.\n\
     40  All rights reserved.\n";
     41 #endif /* not lint */
     42 
     43 #ifndef lint
     44 /*static char sccsid[] = "from: @(#)init.c	6.22 (Berkeley) 6/2/93";*/
     45 static char rcsid[] = "$Id: init.c,v 1.12 1994/03/01 00:32:20 cgd Exp $";
     46 #endif /* not lint */
     47 
     48 #include <sys/param.h>
     49 #ifndef NOSYSCTL
     50 #include <sys/sysctl.h>
     51 #endif
     52 #include <sys/wait.h>
     53 
     54 #include <db.h>
     55 #include <errno.h>
     56 #include <fcntl.h>
     57 #include <signal.h>
     58 #include <stdio.h>
     59 #include <stdlib.h>
     60 #include <string.h>
     61 #include <syslog.h>
     62 #include <time.h>
     63 #include <ttyent.h>
     64 #include <unistd.h>
     65 
     66 #ifdef __STDC__
     67 #include <stdarg.h>
     68 #else
     69 #include <varargs.h>
     70 #endif
     71 
     72 #ifdef SECURE
     73 #include <pwd.h>
     74 #endif
     75 
     76 #include "pathnames.h"
     77 
     78 /*
     79  * Until the mythical util.h arrives...
     80  */
     81 extern int login_tty __P((int));
     82 extern int logout __P((const char *));
     83 extern void logwtmp __P((const char *, const char *, const char *));
     84 
     85 /*
     86  * Sleep times; used to prevent thrashing.
     87  */
     88 #define	GETTY_SPACING		 5	/* N secs minimum getty spacing */
     89 #define	GETTY_SLEEP		30	/* sleep N secs after spacing problem */
     90 #define	WINDOW_WAIT		 3	/* wait N secs after starting window */
     91 #define	STALL_TIMEOUT		30	/* wait N secs after warning */
     92 #define	DEATH_WATCH		10	/* wait N secs for procs to die */
     93 
     94 void handle __P((sig_t, ...));
     95 void delset __P((sigset_t *, ...));
     96 
     97 void stall __P((char *, ...));
     98 void warning __P((char *, ...));
     99 void emergency __P((char *, ...));
    100 void disaster __P((int));
    101 void badsys __P((int));
    102 
    103 /*
    104  * We really need a recursive typedef...
    105  * The following at least guarantees that the return type of (*state_t)()
    106  * is sufficiently wide to hold a function pointer.
    107  */
    108 typedef long (*state_func_t) __P((void));
    109 typedef state_func_t (*state_t) __P((void));
    110 
    111 state_func_t single_user __P((void));
    112 state_func_t runcom __P((void));
    113 state_func_t read_ttys __P((void));
    114 state_func_t multi_user __P((void));
    115 state_func_t clean_ttys __P((void));
    116 state_func_t catatonia __P((void));
    117 state_func_t death __P((void));
    118 
    119 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
    120 
    121 void transition __P((state_t));
    122 state_t requested_transition = runcom;
    123 
    124 void setctty __P((char *));
    125 
    126 typedef struct init_session {
    127 	int	se_index;		/* index of entry in ttys file */
    128 	pid_t	se_process;		/* controlling process */
    129 	time_t	se_started;		/* used to avoid thrashing */
    130 	int	se_flags;		/* status of session */
    131 #define	SE_SHUTDOWN	0x1		/* session won't be restarted */
    132 	char	*se_device;		/* filename of port */
    133 	char	*se_getty;		/* what to run on that port */
    134 	char	**se_getty_argv;	/* pre-parsed argument array */
    135 	char	*se_window;		/* window system (started only once) */
    136 	char	**se_window_argv;	/* pre-parsed argument array */
    137 	struct	init_session *se_prev;
    138 	struct	init_session *se_next;
    139 } session_t;
    140 
    141 void free_session __P((session_t *));
    142 session_t *new_session __P((session_t *, int, struct ttyent *));
    143 session_t *sessions;
    144 
    145 char **construct_argv __P((char *));
    146 void start_window_system __P((session_t *));
    147 void collect_child __P((pid_t));
    148 pid_t start_getty __P((session_t *));
    149 void transition_handler __P((int));
    150 void alrm_handler __P((int));
    151 void setsecuritylevel __P((int));
    152 int getsecuritylevel __P((void));
    153 int setupargv __P((session_t *, struct ttyent *));
    154 int clang;
    155 
    156 void clear_session_logs __P((session_t *));
    157 
    158 int start_session_db __P((void));
    159 void add_session __P((session_t *));
    160 void del_session __P((session_t *));
    161 session_t *find_session __P((pid_t));
    162 DB *session_db;
    163 
    164 /*
    165  * The mother of all processes.
    166  */
    167 int
    168 main(argc, argv)
    169 	int argc;
    170 	char **argv;
    171 {
    172 	int c;
    173 	struct sigaction sa;
    174 	sigset_t mask;
    175 
    176 
    177 	/* Dispose of random users. */
    178 	if (getuid() != 0) {
    179 		(void)fprintf(stderr, "init: %s\n", strerror(EPERM));
    180 		exit (1);
    181 	}
    182 
    183 	/* System V users like to reexec init. */
    184 	if (getpid() != 1) {
    185 		(void)fprintf(stderr, "init: already running\n");
    186 		exit (1);
    187 	}
    188 
    189 	/*
    190 	 * Note that this does NOT open a file...
    191 	 * Does 'init' deserve its own facility number?
    192 	 */
    193 	openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
    194 
    195 	/*
    196 	 * Create an initial session.
    197 	 */
    198 	if (setsid() < 0)
    199 		warning("initial setsid() failed: %m");
    200 
    201 	/*
    202 	 * Establish an initial user so that programs running
    203 	 * single user do not freak out and die (like passwd).
    204 	 */
    205 	if (setlogin("root") < 0)
    206 		warning("setlogin() failed: %m");
    207 
    208 	/*
    209 	 * This code assumes that we always get arguments through flags,
    210 	 * never through bits set in some random machine register.
    211 	 */
    212 	while ((c = getopt(argc, argv, "sf")) != -1)
    213 		switch (c) {
    214 		case 's':
    215 			requested_transition = single_user;
    216 			break;
    217 		case 'f':
    218 			runcom_mode = FASTBOOT;
    219 			break;
    220 		default:
    221 			warning("unrecognized flag '-%c'", c);
    222 			break;
    223 		}
    224 
    225 	if (optind != argc)
    226 		warning("ignoring excess arguments");
    227 
    228 	/*
    229 	 * We catch or block signals rather than ignore them,
    230 	 * so that they get reset on exec.
    231 	 */
    232 	handle(badsys, SIGSYS, 0);
    233 	handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
    234 	       SIGBUS, SIGXCPU, SIGXFSZ, 0);
    235 	handle(transition_handler, SIGHUP, SIGTERM, SIGTSTP, 0);
    236 	handle(alrm_handler, SIGALRM, 0);
    237 	sigfillset(&mask);
    238 	delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
    239 		SIGXCPU, SIGXFSZ, SIGHUP, SIGTERM, SIGTSTP, SIGALRM, 0);
    240 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
    241 	sigemptyset(&sa.sa_mask);
    242 	sa.sa_flags = 0;
    243 	sa.sa_handler = SIG_IGN;
    244 	(void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
    245 	(void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
    246 
    247 	/*
    248 	 * Paranoia.
    249 	 */
    250 	close(0);
    251 	close(1);
    252 	close(2);
    253 
    254 	/*
    255 	 * Start the state machine.
    256 	 */
    257 	transition(requested_transition);
    258 
    259 	/*
    260 	 * Should never reach here.
    261 	 */
    262 	return 1;
    263 }
    264 
    265 /*
    266  * Associate a function with a signal handler.
    267  */
    268 void
    269 #ifdef __STDC__
    270 handle(sig_t handler, ...)
    271 #else
    272 handle(va_alist)
    273 	va_dcl
    274 #endif
    275 {
    276 	int sig;
    277 	struct sigaction sa;
    278 	int mask_everything;
    279 	va_list ap;
    280 #ifndef __STDC__
    281 	sig_t handler;
    282 
    283 	va_start(ap);
    284 	handler = va_arg(ap, sig_t);
    285 #else
    286 	va_start(ap, handler);
    287 #endif
    288 
    289 	sa.sa_handler = handler;
    290 	sigfillset(&mask_everything);
    291 
    292 	while (sig = va_arg(ap, int)) {
    293 		sa.sa_mask = mask_everything;
    294 		/* XXX SA_RESTART? */
    295 		sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
    296 		sigaction(sig, &sa, (struct sigaction *) 0);
    297 	}
    298 	va_end(ap);
    299 }
    300 
    301 /*
    302  * Delete a set of signals from a mask.
    303  */
    304 void
    305 #ifdef __STDC__
    306 delset(sigset_t *maskp, ...)
    307 #else
    308 delset(va_alist)
    309 	va_dcl
    310 #endif
    311 {
    312 	int sig;
    313 	va_list ap;
    314 #ifndef __STDC__
    315 	sigset_t *maskp;
    316 
    317 	va_start(ap);
    318 	maskp = va_arg(ap, sigset_t *);
    319 #else
    320 	va_start(ap, maskp);
    321 #endif
    322 
    323 	while (sig = va_arg(ap, int))
    324 		sigdelset(maskp, sig);
    325 	va_end(ap);
    326 }
    327 
    328 /*
    329  * Log a message and sleep for a while (to give someone an opportunity
    330  * to read it and to save log or hardcopy output if the problem is chronic).
    331  * NB: should send a message to the session logger to avoid blocking.
    332  */
    333 void
    334 #ifdef __STDC__
    335 stall(char *message, ...)
    336 #else
    337 stall(va_alist)
    338 	va_dcl
    339 #endif
    340 {
    341 	va_list ap;
    342 #ifndef __STDC__
    343 	char *message;
    344 
    345 	va_start(ap);
    346 	message = va_arg(ap, char *);
    347 #else
    348 	va_start(ap, message);
    349 #endif
    350 
    351 	vsyslog(LOG_ALERT, message, ap);
    352 	va_end(ap);
    353 	sleep(STALL_TIMEOUT);
    354 }
    355 
    356 /*
    357  * Like stall(), but doesn't sleep.
    358  * If cpp had variadic macros, the two functions could be #defines for another.
    359  * NB: should send a message to the session logger to avoid blocking.
    360  */
    361 void
    362 #ifdef __STDC__
    363 warning(char *message, ...)
    364 #else
    365 warning(va_alist)
    366 	va_dcl
    367 #endif
    368 {
    369 	va_list ap;
    370 #ifndef __STDC__
    371 	char *message;
    372 
    373 	va_start(ap);
    374 	message = va_arg(ap, char *);
    375 #else
    376 	va_start(ap, message);
    377 #endif
    378 
    379 	vsyslog(LOG_ALERT, message, ap);
    380 	va_end(ap);
    381 }
    382 
    383 /*
    384  * Log an emergency message.
    385  * NB: should send a message to the session logger to avoid blocking.
    386  */
    387 void
    388 #ifdef __STDC__
    389 emergency(char *message, ...)
    390 #else
    391 emergency(va_alist)
    392 	va_dcl
    393 #endif
    394 {
    395 	va_list ap;
    396 #ifndef __STDC__
    397 	char *message;
    398 
    399 	va_start(ap);
    400 	message = va_arg(ap, char *);
    401 #else
    402 	va_start(ap, message);
    403 #endif
    404 
    405 	vsyslog(LOG_EMERG, message, ap);
    406 	va_end(ap);
    407 }
    408 
    409 /*
    410  * Catch a SIGSYS signal.
    411  *
    412  * These may arise if a system does not support sysctl.
    413  * We tolerate up to 25 of these, then throw in the towel.
    414  */
    415 void
    416 badsys(sig)
    417 	int sig;
    418 {
    419 	static int badcount = 0;
    420 
    421 	if (badcount++ < 25)
    422 		return;
    423 	disaster(sig);
    424 }
    425 
    426 /*
    427  * Catch an unexpected signal.
    428  */
    429 void
    430 disaster(sig)
    431 	int sig;
    432 {
    433 	emergency("fatal signal: %s",
    434 		sig < (unsigned) NSIG ? sys_siglist[sig] : "unknown signal");
    435 
    436 	sleep(STALL_TIMEOUT);
    437 	_exit(sig);		/* reboot */
    438 }
    439 
    440 /*
    441  * Get the security level of the kernel.
    442  */
    443 int
    444 getsecuritylevel()
    445 {
    446 #ifdef KERN_SECURELVL
    447 	int name[2], curlevel;
    448 	size_t len;
    449 	extern int errno;
    450 
    451 	name[0] = CTL_KERN;
    452 	name[1] = KERN_SECURELVL;
    453 	len = sizeof curlevel;
    454 	if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
    455 		emergency("cannot get kernel security level: %s",
    456 		    strerror(errno));
    457 		return (-1);
    458 	}
    459 	return (curlevel);
    460 #else
    461 	return (-1);
    462 #endif
    463 }
    464 
    465 /*
    466  * Set the security level of the kernel.
    467  */
    468 void
    469 setsecuritylevel(newlevel)
    470 	int newlevel;
    471 {
    472 #ifdef KERN_SECURELVL
    473 	int name[2], curlevel;
    474 	extern int errno;
    475 
    476 	curlevel = getsecuritylevel();
    477 	if (newlevel == curlevel)
    478 		return;
    479 	name[0] = CTL_KERN;
    480 	name[1] = KERN_SECURELVL;
    481 	if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
    482 		emergency(
    483 		    "cannot change kernel security level from %d to %d: %s",
    484 		    curlevel, newlevel, strerror(errno));
    485 		return;
    486 	}
    487 #ifdef SECURE
    488 	warning("kernel security level changed from %d to %d",
    489 	    curlevel, newlevel);
    490 #endif
    491 #endif
    492 }
    493 
    494 /*
    495  * Change states in the finite state machine.
    496  * The initial state is passed as an argument.
    497  */
    498 void
    499 transition(s)
    500 	state_t s;
    501 {
    502 	for (;;)
    503 		s = (state_t) (*s)();
    504 }
    505 
    506 /*
    507  * Close out the accounting files for a login session.
    508  * NB: should send a message to the session logger to avoid blocking.
    509  */
    510 void
    511 clear_session_logs(sp)
    512 	session_t *sp;
    513 {
    514 	char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
    515 
    516 	if (logout(line))
    517 		logwtmp(line, "", "");
    518 }
    519 
    520 /*
    521  * Start a session and allocate a controlling terminal.
    522  * Only called by children of init after forking.
    523  */
    524 void
    525 setctty(name)
    526 	char *name;
    527 {
    528 	int fd;
    529 
    530 	(void) revoke(name);
    531 	sleep (2);			/* leave DTR low */
    532 	if ((fd = open(name, O_RDWR)) == -1) {
    533 		stall("can't open %s: %m", name);
    534 		_exit(1);
    535 	}
    536 	if (login_tty(fd) == -1) {
    537 		stall("can't get %s for controlling terminal: %m", name);
    538 		_exit(1);
    539 	}
    540 }
    541 
    542 /*
    543  * Bring the system up single user.
    544  */
    545 state_func_t
    546 single_user()
    547 {
    548 	pid_t pid, wpid;
    549 	int status;
    550 	sigset_t mask;
    551 	char *shell = _PATH_BSHELL;
    552 	char *argv[2];
    553 #ifdef SECURE
    554 	struct ttyent *typ;
    555 	struct passwd *pp;
    556 	static const char banner[] =
    557 		"Enter root password, or ^D to go multi-user\n";
    558 	char *clear, *password;
    559 #endif
    560 
    561 	/*
    562 	 * If the kernel is in secure mode, downgrade it to insecure mode.
    563 	 */
    564 	if (getsecuritylevel() > 0)
    565 		setsecuritylevel(0);
    566 
    567 	if ((pid = fork()) == 0) {
    568 		/*
    569 		 * Start the single user session.
    570 		 */
    571 		setctty(_PATH_CONSOLE);
    572 
    573 #ifdef SECURE
    574 		/*
    575 		 * Check the root password.
    576 		 * We don't care if the console is 'on' by default;
    577 		 * it's the only tty that can be 'off' and 'secure'.
    578 		 */
    579 		typ = getttynam("console");
    580 		pp = getpwnam("root");
    581 		if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp) {
    582 			write(2, banner, sizeof banner - 1);
    583 			for (;;) {
    584 				clear = getpass("Password:");
    585 				if (clear == 0 || *clear == '\0')
    586 					_exit(0);
    587 				password = crypt(clear, pp->pw_passwd);
    588 				bzero(clear, _PASSWORD_LEN);
    589 				if (strcmp(password, pp->pw_passwd) == 0)
    590 					break;
    591 				warning("single-user login failed\n");
    592 			}
    593 		}
    594 		endttyent();
    595 		endpwent();
    596 #endif /* SECURE */
    597 
    598 #ifdef DEBUGSHELL
    599 		{
    600 			char altshell[128], *cp = altshell;
    601 			int num;
    602 
    603 #define	SHREQUEST \
    604 	"Enter pathname of shell or RETURN for sh: "
    605 			(void)write(STDERR_FILENO,
    606 			    SHREQUEST, sizeof(SHREQUEST) - 1);
    607 			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
    608 			    num != 0 && *cp != '\n' && cp < &altshell[127])
    609 					cp++;
    610 			*cp = '\0';
    611 			if (altshell[0] != '\0')
    612 				shell = altshell;
    613 		}
    614 #endif /* DEBUGSHELL */
    615 
    616 		/*
    617 		 * Unblock signals.
    618 		 * We catch all the interesting ones,
    619 		 * and those are reset to SIG_DFL on exec.
    620 		 */
    621 		sigemptyset(&mask);
    622 		sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
    623 
    624 		/*
    625 		 * Fire off a shell.
    626 		 * If the default one doesn't work, try the Bourne shell.
    627 		 */
    628 		argv[0] = "-sh";
    629 		argv[1] = 0;
    630 		execv(shell, argv);
    631 		emergency("can't exec %s for single user: %m", shell);
    632 		execv(_PATH_BSHELL, argv);
    633 		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
    634 		sleep(STALL_TIMEOUT);
    635 		_exit(1);
    636 	}
    637 
    638 	if (pid == -1) {
    639 		/*
    640 		 * We are seriously hosed.  Do our best.
    641 		 */
    642 		emergency("can't fork single-user shell, trying again");
    643 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
    644 			continue;
    645 		return (state_func_t) single_user;
    646 	}
    647 
    648 	requested_transition = 0;
    649 	do {
    650 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
    651 			collect_child(wpid);
    652 		if (wpid == -1) {
    653 			if (errno == EINTR)
    654 				continue;
    655 			warning("wait for single-user shell failed: %m; restarting");
    656 			return (state_func_t) single_user;
    657 		}
    658 		if (wpid == pid && WIFSTOPPED(status)) {
    659 			warning("init: shell stopped, restarting\n");
    660 			kill(pid, SIGCONT);
    661 			wpid = -1;
    662 		}
    663 	} while (wpid != pid && !requested_transition);
    664 
    665 	if (requested_transition)
    666 		return (state_func_t) requested_transition;
    667 
    668 	if (!WIFEXITED(status)) {
    669 		if (WTERMSIG(status) == SIGKILL) {
    670 			/*
    671 			 *  reboot(8) killed shell?
    672 			 */
    673 			warning("single user shell terminated.");
    674 			sleep(STALL_TIMEOUT);
    675 			_exit(0);
    676 		} else {
    677 			warning("single user shell terminated, restarting");
    678 			return (state_func_t) single_user;
    679 		}
    680 	}
    681 
    682 	runcom_mode = FASTBOOT;
    683 	return (state_func_t) runcom;
    684 }
    685 
    686 /*
    687  * Run the system startup script.
    688  */
    689 state_func_t
    690 runcom()
    691 {
    692 	pid_t pid, wpid;
    693 	int status;
    694 	char *argv[4];
    695 	struct sigaction sa;
    696 
    697 	if ((pid = fork()) == 0) {
    698 		sigemptyset(&sa.sa_mask);
    699 		sa.sa_flags = 0;
    700 		sa.sa_handler = SIG_IGN;
    701 		(void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
    702 		(void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
    703 
    704 		setctty(_PATH_CONSOLE);
    705 
    706 		argv[0] = "sh";
    707 		argv[1] = _PATH_RUNCOM;
    708 		argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
    709 		argv[3] = 0;
    710 
    711 		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
    712 
    713 		execv(_PATH_BSHELL, argv);
    714 		stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
    715 		_exit(1);	/* force single user mode */
    716 	}
    717 
    718 	if (pid == -1) {
    719 		emergency("can't fork for %s on %s: %m",
    720 			_PATH_BSHELL, _PATH_RUNCOM);
    721 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
    722 			continue;
    723 		sleep(STALL_TIMEOUT);
    724 		return (state_func_t) single_user;
    725 	}
    726 
    727 	/*
    728 	 * Copied from single_user().  This is a bit paranoid.
    729 	 */
    730 	do {
    731 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
    732 			collect_child(wpid);
    733 		if (wpid == -1) {
    734 			if (errno == EINTR)
    735 				continue;
    736 			warning("wait for %s on %s failed: %m; going to single user mode",
    737 				_PATH_BSHELL, _PATH_RUNCOM);
    738 			return (state_func_t) single_user;
    739 		}
    740 		if (wpid == pid && WIFSTOPPED(status)) {
    741 			warning("init: %s on %s stopped, restarting\n",
    742 				_PATH_BSHELL, _PATH_RUNCOM);
    743 			kill(pid, SIGCONT);
    744 			wpid = -1;
    745 		}
    746 	} while (wpid != pid);
    747 
    748 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
    749 	    requested_transition == catatonia) {
    750 		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
    751 		sigset_t s;
    752 
    753 		sigfillset(&s);
    754 		for (;;)
    755 			sigsuspend(&s);
    756 	}
    757 
    758 	if (!WIFEXITED(status)) {
    759 		warning("%s on %s terminated abnormally, going to single user mode",
    760 			_PATH_BSHELL, _PATH_RUNCOM);
    761 		return (state_func_t) single_user;
    762 	}
    763 
    764 	if (WEXITSTATUS(status))
    765 		return (state_func_t) single_user;
    766 
    767 	runcom_mode = AUTOBOOT;		/* the default */
    768 	/* NB: should send a message to the session logger to avoid blocking. */
    769 	logwtmp("~", "reboot", "");
    770 	return (state_func_t) read_ttys;
    771 }
    772 
    773 /*
    774  * Open the session database.
    775  *
    776  * NB: We could pass in the size here; is it necessary?
    777  */
    778 int
    779 start_session_db()
    780 {
    781 	if (session_db && (*session_db->close)(session_db))
    782 		emergency("session database close: %s", strerror(errno));
    783 	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
    784 		emergency("session database open: %s", strerror(errno));
    785 		return (1);
    786 	}
    787 	return (0);
    788 
    789 }
    790 
    791 /*
    792  * Add a new login session.
    793  */
    794 void
    795 add_session(sp)
    796 	session_t *sp;
    797 {
    798 	DBT key;
    799 	DBT data;
    800 
    801 	key.data = &sp->se_process;
    802 	key.size = sizeof sp->se_process;
    803 	data.data = &sp;
    804 	data.size = sizeof sp;
    805 
    806 	if ((*session_db->put)(session_db, &key, &data, 0))
    807 		emergency("insert %d: %s", sp->se_process, strerror(errno));
    808 }
    809 
    810 /*
    811  * Delete an old login session.
    812  */
    813 void
    814 del_session(sp)
    815 	session_t *sp;
    816 {
    817 	DBT key;
    818 
    819 	key.data = &sp->se_process;
    820 	key.size = sizeof sp->se_process;
    821 
    822 	if ((*session_db->del)(session_db, &key, 0))
    823 		emergency("delete %d: %s", sp->se_process, strerror(errno));
    824 }
    825 
    826 /*
    827  * Look up a login session by pid.
    828  */
    829 session_t *
    830 #ifdef __STDC__
    831 find_session(pid_t pid)
    832 #else
    833 find_session(pid)
    834 	pid_t pid;
    835 #endif
    836 {
    837 	DBT key;
    838 	DBT data;
    839 	session_t *ret;
    840 
    841 	key.data = &pid;
    842 	key.size = sizeof pid;
    843 	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
    844 		return 0;
    845 	bcopy(data.data, (char *)&ret, sizeof(ret));
    846 	return ret;
    847 }
    848 
    849 /*
    850  * Construct an argument vector from a command line.
    851  */
    852 char **
    853 construct_argv(command)
    854 	char *command;
    855 {
    856 	register int argc = 0;
    857 	register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
    858 						* sizeof (char *));
    859 	static const char separators[] = " \t";
    860 
    861 	if ((argv[argc++] = strtok(command, separators)) == 0)
    862 		return 0;
    863 	while (argv[argc++] = strtok((char *) 0, separators))
    864 		continue;
    865 	return argv;
    866 }
    867 
    868 /*
    869  * Deallocate a session descriptor.
    870  */
    871 void
    872 free_session(sp)
    873 	register session_t *sp;
    874 {
    875 	free(sp->se_device);
    876 	if (sp->se_getty) {
    877 		free(sp->se_getty);
    878 		free(sp->se_getty_argv);
    879 	}
    880 	if (sp->se_window) {
    881 		free(sp->se_window);
    882 		free(sp->se_window_argv);
    883 	}
    884 	free(sp);
    885 }
    886 
    887 /*
    888  * Allocate a new session descriptor.
    889  */
    890 session_t *
    891 new_session(sprev, session_index, typ)
    892 	session_t *sprev;
    893 	int session_index;
    894 	register struct ttyent *typ;
    895 {
    896 	register session_t *sp;
    897 
    898 	if ((typ->ty_status & TTY_ON) == 0 ||
    899 	    typ->ty_name == 0 ||
    900 	    typ->ty_getty == 0)
    901 		return 0;
    902 
    903 	sp = (session_t *) malloc(sizeof (session_t));
    904 	bzero(sp, sizeof *sp);
    905 
    906 	sp->se_index = session_index;
    907 
    908 	sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
    909 	(void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
    910 
    911 	if (setupargv(sp, typ) == 0) {
    912 		free_session(sp);
    913 		return (0);
    914 	}
    915 
    916 	sp->se_next = 0;
    917 	if (sprev == 0) {
    918 		sessions = sp;
    919 		sp->se_prev = 0;
    920 	} else {
    921 		sprev->se_next = sp;
    922 		sp->se_prev = sprev;
    923 	}
    924 
    925 	return sp;
    926 }
    927 
    928 /*
    929  * Calculate getty and if useful window argv vectors.
    930  */
    931 int
    932 setupargv(sp, typ)
    933 	session_t *sp;
    934 	struct ttyent *typ;
    935 {
    936 
    937 	if (sp->se_getty) {
    938 		free(sp->se_getty);
    939 		free(sp->se_getty_argv);
    940 	}
    941 	sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
    942 	(void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
    943 	sp->se_getty_argv = construct_argv(sp->se_getty);
    944 	if (sp->se_getty_argv == 0) {
    945 		warning("can't parse getty for port %s", sp->se_device);
    946 		free(sp->se_getty);
    947 		sp->se_getty = 0;
    948 		return (0);
    949 	}
    950 	if (typ->ty_window) {
    951 		if (sp->se_window)
    952 			free(sp->se_window);
    953 		sp->se_window = strdup(typ->ty_window);
    954 		sp->se_window_argv = construct_argv(sp->se_window);
    955 		if (sp->se_window_argv == 0) {
    956 			warning("can't parse window for port %s",
    957 				sp->se_device);
    958 			free(sp->se_window);
    959 			sp->se_window = 0;
    960 			return (0);
    961 		}
    962 	}
    963 	return (1);
    964 }
    965 
    966 /*
    967  * Walk the list of ttys and create sessions for each active line.
    968  */
    969 state_func_t
    970 read_ttys()
    971 {
    972 	int session_index = 0;
    973 	register session_t *sp, *snext;
    974 	register struct ttyent *typ;
    975 
    976 	/*
    977 	 * Destroy any previous session state.
    978 	 * There shouldn't be any, but just in case...
    979 	 */
    980 	for (sp = sessions; sp; sp = snext) {
    981 		if (sp->se_process)
    982 			clear_session_logs(sp);
    983 		snext = sp->se_next;
    984 		free_session(sp);
    985 	}
    986 	sessions = 0;
    987 	if (start_session_db())
    988 		return (state_func_t) single_user;
    989 
    990 	/*
    991 	 * Allocate a session entry for each active port.
    992 	 * Note that sp starts at 0.
    993 	 */
    994 	while (typ = getttyent())
    995 		if (snext = new_session(sp, ++session_index, typ))
    996 			sp = snext;
    997 
    998 	endttyent();
    999 
   1000 	return (state_func_t) multi_user;
   1001 }
   1002 
   1003 /*
   1004  * Start a window system running.
   1005  */
   1006 void
   1007 start_window_system(sp)
   1008 	session_t *sp;
   1009 {
   1010 	pid_t pid;
   1011 	sigset_t mask;
   1012 
   1013 	if ((pid = fork()) == -1) {
   1014 		emergency("can't fork for window system on port %s: %m",
   1015 			sp->se_device);
   1016 		/* hope that getty fails and we can try again */
   1017 		return;
   1018 	}
   1019 
   1020 	if (pid)
   1021 		return;
   1022 
   1023 	sigemptyset(&mask);
   1024 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
   1025 
   1026 	if (setsid() < 0)
   1027 		emergency("setsid failed (window) %m");
   1028 
   1029 	execv(sp->se_window_argv[0], sp->se_window_argv);
   1030 	stall("can't exec window system '%s' for port %s: %m",
   1031 		sp->se_window_argv[0], sp->se_device);
   1032 	_exit(1);
   1033 }
   1034 
   1035 /*
   1036  * Start a login session running.
   1037  */
   1038 pid_t
   1039 start_getty(sp)
   1040 	session_t *sp;
   1041 {
   1042 	pid_t pid;
   1043 	sigset_t mask;
   1044 	time_t current_time = time((time_t *) 0);
   1045 
   1046 	/*
   1047 	 * fork(), not vfork() -- we can't afford to block.
   1048 	 */
   1049 	if ((pid = fork()) == -1) {
   1050 		emergency("can't fork for getty on port %s: %m", sp->se_device);
   1051 		return -1;
   1052 	}
   1053 
   1054 	if (pid)
   1055 		return pid;
   1056 
   1057 	if (current_time > sp->se_started &&
   1058 	    current_time - sp->se_started < GETTY_SPACING) {
   1059 		warning("getty repeating too quickly on port %s, sleeping",
   1060 		        sp->se_device);
   1061 		sleep((unsigned) GETTY_SLEEP);
   1062 	}
   1063 
   1064 	if (sp->se_window) {
   1065 		start_window_system(sp);
   1066 		sleep(WINDOW_WAIT);
   1067 	}
   1068 
   1069 	sigemptyset(&mask);
   1070 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
   1071 
   1072 	execv(sp->se_getty_argv[0], sp->se_getty_argv);
   1073 	stall("can't exec getty '%s' for port %s: %m",
   1074 		sp->se_getty_argv[0], sp->se_device);
   1075 	_exit(1);
   1076 }
   1077 
   1078 /*
   1079  * Collect exit status for a child.
   1080  * If an exiting login, start a new login running.
   1081  */
   1082 void
   1083 #ifdef __STDC__
   1084 collect_child(pid_t pid)
   1085 #else
   1086 collect_child(pid)
   1087 	pid_t pid;
   1088 #endif
   1089 {
   1090 	register session_t *sp, *sprev, *snext;
   1091 
   1092 	if (! sessions)
   1093 		return;
   1094 
   1095 	if (! (sp = find_session(pid)))
   1096 		return;
   1097 
   1098 	clear_session_logs(sp);
   1099 	del_session(sp);
   1100 	sp->se_process = 0;
   1101 
   1102 	if (sp->se_flags & SE_SHUTDOWN) {
   1103 		if (sprev = sp->se_prev)
   1104 			sprev->se_next = sp->se_next;
   1105 		else
   1106 			sessions = sp->se_next;
   1107 		if (snext = sp->se_next)
   1108 			snext->se_prev = sp->se_prev;
   1109 		free_session(sp);
   1110 		return;
   1111 	}
   1112 
   1113 	if ((pid = start_getty(sp)) == -1) {
   1114 		/* serious trouble */
   1115 		requested_transition = clean_ttys;
   1116 		return;
   1117 	}
   1118 
   1119 	sp->se_process = pid;
   1120 	sp->se_started = time((time_t *) 0);
   1121 	add_session(sp);
   1122 }
   1123 
   1124 /*
   1125  * Catch a signal and request a state transition.
   1126  */
   1127 void
   1128 transition_handler(sig)
   1129 	int sig;
   1130 {
   1131 
   1132 	switch (sig) {
   1133 	case SIGHUP:
   1134 		requested_transition = clean_ttys;
   1135 		break;
   1136 	case SIGTERM:
   1137 		requested_transition = death;
   1138 		break;
   1139 	case SIGTSTP:
   1140 		requested_transition = catatonia;
   1141 		break;
   1142 	default:
   1143 		requested_transition = 0;
   1144 		break;
   1145 	}
   1146 }
   1147 
   1148 /*
   1149  * Take the system multiuser.
   1150  */
   1151 state_func_t
   1152 multi_user()
   1153 {
   1154 	pid_t pid;
   1155 	register session_t *sp;
   1156 
   1157 	requested_transition = 0;
   1158 
   1159 	/*
   1160 	 * If the administrator has not set the security level to -1
   1161 	 * to indicate that the kernel should not run multiuser in secure
   1162 	 * mode, and the run script has not set a higher level of security
   1163 	 * than level 1, then put the kernel into secure mode.
   1164 	 */
   1165 	if (getsecuritylevel() == 0)
   1166 		setsecuritylevel(1);
   1167 
   1168 	for (sp = sessions; sp; sp = sp->se_next) {
   1169 		if (sp->se_process)
   1170 			continue;
   1171 		if ((pid = start_getty(sp)) == -1) {
   1172 			/* serious trouble */
   1173 			requested_transition = clean_ttys;
   1174 			break;
   1175 		}
   1176 		sp->se_process = pid;
   1177 		sp->se_started = time((time_t *) 0);
   1178 		add_session(sp);
   1179 	}
   1180 
   1181 	while (!requested_transition)
   1182 		if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
   1183 			collect_child(pid);
   1184 
   1185 	return (state_func_t) requested_transition;
   1186 }
   1187 
   1188 /*
   1189  * This is an n-squared algorithm.  We hope it isn't run often...
   1190  */
   1191 state_func_t
   1192 clean_ttys()
   1193 {
   1194 	register session_t *sp, *sprev;
   1195 	register struct ttyent *typ;
   1196 	register int session_index = 0;
   1197 	register int devlen;
   1198 
   1199 	if (! sessions)
   1200 		return (state_func_t) multi_user;
   1201 
   1202 	devlen = sizeof(_PATH_DEV) - 1;
   1203 	while (typ = getttyent()) {
   1204 		++session_index;
   1205 
   1206 		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
   1207 			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
   1208 				break;
   1209 
   1210 		if (sp) {
   1211 			if (sp->se_index != session_index) {
   1212 				warning("port %s changed utmp index from %d to %d",
   1213 				       sp->se_device, sp->se_index,
   1214 				       session_index);
   1215 				sp->se_index = session_index;
   1216 			}
   1217 			if ((typ->ty_status & TTY_ON) == 0 ||
   1218 			    typ->ty_getty == 0) {
   1219 				sp->se_flags |= SE_SHUTDOWN;
   1220 				kill(sp->se_process, SIGHUP);
   1221 				continue;
   1222 			}
   1223 			sp->se_flags &= ~SE_SHUTDOWN;
   1224 			if (setupargv(sp, typ) == 0) {
   1225 				warning("can't parse getty for port %s",
   1226 					sp->se_device);
   1227 				sp->se_flags |= SE_SHUTDOWN;
   1228 				kill(sp->se_process, SIGHUP);
   1229 			}
   1230 			continue;
   1231 		}
   1232 
   1233 		new_session(sprev, session_index, typ);
   1234 	}
   1235 
   1236 	endttyent();
   1237 
   1238 	return (state_func_t) multi_user;
   1239 }
   1240 
   1241 /*
   1242  * Block further logins.
   1243  */
   1244 state_func_t
   1245 catatonia()
   1246 {
   1247 	register session_t *sp;
   1248 
   1249 	for (sp = sessions; sp; sp = sp->se_next)
   1250 		sp->se_flags |= SE_SHUTDOWN;
   1251 
   1252 	return (state_func_t) multi_user;
   1253 }
   1254 
   1255 /*
   1256  * Note SIGALRM.
   1257  */
   1258 void
   1259 alrm_handler(sig)
   1260 	int sig;
   1261 {
   1262 	clang = 1;
   1263 }
   1264 
   1265 /*
   1266  * Bring the system down to single user.
   1267  */
   1268 state_func_t
   1269 death()
   1270 {
   1271 	register session_t *sp;
   1272 	register int i;
   1273 	pid_t pid;
   1274 	static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
   1275 
   1276 	for (sp = sessions; sp; sp = sp->se_next)
   1277 		sp->se_flags |= SE_SHUTDOWN;
   1278 
   1279 	/* NB: should send a message to the session logger to avoid blocking. */
   1280 	logwtmp("~", "shutdown", "");
   1281 
   1282 	for (i = 0; i < 3; ++i) {
   1283 		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
   1284 			return (state_func_t) single_user;
   1285 
   1286 		clang = 0;
   1287 		alarm(DEATH_WATCH);
   1288 		do
   1289 			if ((pid = waitpid(-1, (int *)0, 0)) != -1)
   1290 				collect_child(pid);
   1291 		while (clang == 0 && errno != ECHILD);
   1292 
   1293 		if (errno == ECHILD)
   1294 			return (state_func_t) single_user;
   1295 	}
   1296 
   1297 	warning("some processes would not die; ps axl advised");
   1298 
   1299 	return (state_func_t) single_user;
   1300 }
   1301