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