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