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