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