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