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