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