xref: /freebsd/sbin/init/init.c (revision 8ef24a0d4b28fe230e20637f56869cc4148cd2ca)
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36 	The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38 
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)init.c	8.1 (Berkeley) 7/15/93";
42 #endif
43 static const char rcsid[] =
44   "$FreeBSD$";
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/mman.h>
50 #include <sys/mount.h>
51 #include <sys/sysctl.h>
52 #include <sys/wait.h>
53 #include <sys/stat.h>
54 #include <sys/uio.h>
55 
56 #include <db.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <kenv.h>
60 #include <libutil.h>
61 #include <paths.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <syslog.h>
67 #include <time.h>
68 #include <ttyent.h>
69 #include <unistd.h>
70 #include <sys/reboot.h>
71 #include <err.h>
72 
73 #include <stdarg.h>
74 
75 #ifdef SECURE
76 #include <pwd.h>
77 #endif
78 
79 #ifdef LOGIN_CAP
80 #include <login_cap.h>
81 #endif
82 
83 #include "mntopts.h"
84 #include "pathnames.h"
85 
86 /*
87  * Sleep times; used to prevent thrashing.
88  */
89 #define	GETTY_SPACING		 5	/* N secs minimum getty spacing */
90 #define	GETTY_SLEEP		30	/* sleep N secs after spacing problem */
91 #define	GETTY_NSPACE		 3	/* max. spacing count to bring reaction */
92 #define	WINDOW_WAIT		 3	/* wait N secs after starting window */
93 #define	STALL_TIMEOUT		30	/* wait N secs after warning */
94 #define	DEATH_WATCH		10	/* wait N secs for procs to die */
95 #define	DEATH_SCRIPT		120	/* wait for 2min for /etc/rc.shutdown */
96 #define	RESOURCE_RC		"daemon"
97 #define	RESOURCE_WINDOW		"default"
98 #define	RESOURCE_GETTY		"default"
99 
100 static void handle(sig_t, ...);
101 static void delset(sigset_t *, ...);
102 
103 static void stall(const char *, ...) __printflike(1, 2);
104 static void warning(const char *, ...) __printflike(1, 2);
105 static void emergency(const char *, ...) __printflike(1, 2);
106 static void disaster(int);
107 static void badsys(int);
108 static void revoke_ttys(void);
109 static int  runshutdown(void);
110 static char *strk(char *);
111 
112 /*
113  * We really need a recursive typedef...
114  * The following at least guarantees that the return type of (*state_t)()
115  * is sufficiently wide to hold a function pointer.
116  */
117 typedef long (*state_func_t)(void);
118 typedef state_func_t (*state_t)(void);
119 
120 static state_func_t single_user(void);
121 static state_func_t runcom(void);
122 static state_func_t read_ttys(void);
123 static state_func_t multi_user(void);
124 static state_func_t clean_ttys(void);
125 static state_func_t catatonia(void);
126 static state_func_t death(void);
127 static state_func_t death_single(void);
128 static state_func_t reroot(void);
129 static state_func_t reroot_phase_two(void);
130 
131 static state_func_t run_script(const char *);
132 
133 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
134 #define FALSE	0
135 #define TRUE	1
136 
137 static int Reboot = FALSE;
138 static int howto = RB_AUTOBOOT;
139 
140 static int devfs;
141 static char *init_path_argv0;
142 
143 static void transition(state_t);
144 static state_t requested_transition;
145 static state_t current_state = death_single;
146 
147 static void open_console(void);
148 static const char *get_shell(void);
149 static void write_stderr(const char *message);
150 
151 typedef struct init_session {
152 	pid_t	se_process;		/* controlling process */
153 	time_t	se_started;		/* used to avoid thrashing */
154 	int	se_flags;		/* status of session */
155 #define	SE_SHUTDOWN	0x1		/* session won't be restarted */
156 #define	SE_PRESENT	0x2		/* session is in /etc/ttys */
157 	int	se_nspace;		/* spacing count */
158 	char	*se_device;		/* filename of port */
159 	char	*se_getty;		/* what to run on that port */
160 	char	*se_getty_argv_space;   /* pre-parsed argument array space */
161 	char	**se_getty_argv;	/* pre-parsed argument array */
162 	char	*se_window;		/* window system (started only once) */
163 	char	*se_window_argv_space;  /* pre-parsed argument array space */
164 	char	**se_window_argv;	/* pre-parsed argument array */
165 	char	*se_type;		/* default terminal type */
166 	struct	init_session *se_prev;
167 	struct	init_session *se_next;
168 } session_t;
169 
170 static void free_session(session_t *);
171 static session_t *new_session(session_t *, struct ttyent *);
172 static session_t *sessions;
173 
174 static char **construct_argv(char *);
175 static void start_window_system(session_t *);
176 static void collect_child(pid_t);
177 static pid_t start_getty(session_t *);
178 static void transition_handler(int);
179 static void alrm_handler(int);
180 static void setsecuritylevel(int);
181 static int getsecuritylevel(void);
182 static int setupargv(session_t *, struct ttyent *);
183 #ifdef LOGIN_CAP
184 static void setprocresources(const char *);
185 #endif
186 static int clang;
187 
188 static int start_session_db(void);
189 static void add_session(session_t *);
190 static void del_session(session_t *);
191 static session_t *find_session(pid_t);
192 static DB *session_db;
193 
194 /*
195  * The mother of all processes.
196  */
197 int
198 main(int argc, char *argv[])
199 {
200 	state_t initial_transition = runcom;
201 	char kenv_value[PATH_MAX];
202 	int c, error;
203 	struct sigaction sa;
204 	sigset_t mask;
205 
206 	/* Dispose of random users. */
207 	if (getuid() != 0)
208 		errx(1, "%s", strerror(EPERM));
209 
210 	/* System V users like to reexec init. */
211 	if (getpid() != 1) {
212 #ifdef COMPAT_SYSV_INIT
213 		/* So give them what they want */
214 		if (argc > 1) {
215 			if (strlen(argv[1]) == 1) {
216 				char runlevel = *argv[1];
217 				int sig;
218 
219 				switch (runlevel) {
220 				case '0': /* halt + poweroff */
221 					sig = SIGUSR2;
222 					break;
223 				case '1': /* single-user */
224 					sig = SIGTERM;
225 					break;
226 				case '6': /* reboot */
227 					sig = SIGINT;
228 					break;
229 				case 'c': /* block further logins */
230 					sig = SIGTSTP;
231 					break;
232 				case 'q': /* rescan /etc/ttys */
233 					sig = SIGHUP;
234 					break;
235 				case 'r': /* remount root */
236 					sig = SIGEMT;
237 					break;
238 				default:
239 					goto invalid;
240 				}
241 				kill(1, sig);
242 				_exit(0);
243 			} else
244 invalid:
245 				errx(1, "invalid run-level ``%s''", argv[1]);
246 		} else
247 #endif
248 			errx(1, "already running");
249 	}
250 
251 	init_path_argv0 = strdup(argv[0]);
252 	if (init_path_argv0 == NULL)
253 		err(1, "strdup");
254 
255 	/*
256 	 * Note that this does NOT open a file...
257 	 * Does 'init' deserve its own facility number?
258 	 */
259 	openlog("init", LOG_CONS, LOG_AUTH);
260 
261 	/*
262 	 * Create an initial session.
263 	 */
264 	if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
265 		warning("initial setsid() failed: %m");
266 
267 	/*
268 	 * Establish an initial user so that programs running
269 	 * single user do not freak out and die (like passwd).
270 	 */
271 	if (setlogin("root") < 0)
272 		warning("setlogin() failed: %m");
273 
274 	/*
275 	 * This code assumes that we always get arguments through flags,
276 	 * never through bits set in some random machine register.
277 	 */
278 	while ((c = getopt(argc, argv, "dsfr")) != -1)
279 		switch (c) {
280 		case 'd':
281 			devfs = 1;
282 			break;
283 		case 's':
284 			initial_transition = single_user;
285 			break;
286 		case 'f':
287 			runcom_mode = FASTBOOT;
288 			break;
289 		case 'r':
290 			initial_transition = reroot_phase_two;
291 			break;
292 		default:
293 			warning("unrecognized flag '-%c'", c);
294 			break;
295 		}
296 
297 	if (optind != argc)
298 		warning("ignoring excess arguments");
299 
300 	/*
301 	 * We catch or block signals rather than ignore them,
302 	 * so that they get reset on exec.
303 	 */
304 	handle(badsys, SIGSYS, 0);
305 	handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
306 	    SIGXFSZ, 0);
307 	handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
308 	    SIGUSR1, SIGUSR2, 0);
309 	handle(alrm_handler, SIGALRM, 0);
310 	sigfillset(&mask);
311 	delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
312 	    SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
313 	    SIGALRM, SIGUSR1, SIGUSR2, 0);
314 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
315 	sigemptyset(&sa.sa_mask);
316 	sa.sa_flags = 0;
317 	sa.sa_handler = SIG_IGN;
318 	sigaction(SIGTTIN, &sa, (struct sigaction *)0);
319 	sigaction(SIGTTOU, &sa, (struct sigaction *)0);
320 
321 	/*
322 	 * Paranoia.
323 	 */
324 	close(0);
325 	close(1);
326 	close(2);
327 
328 	if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
329 		state_func_t next_transition;
330 
331 		if ((next_transition = run_script(kenv_value)) != NULL)
332 			initial_transition = (state_t) next_transition;
333 	}
334 
335 	if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
336 		if (chdir(kenv_value) != 0 || chroot(".") != 0)
337 			warning("Can't chroot to %s: %m", kenv_value);
338 	}
339 
340 	/*
341 	 * Additional check if devfs needs to be mounted:
342 	 * If "/" and "/dev" have the same device number,
343 	 * then it hasn't been mounted yet.
344 	 */
345 	if (!devfs) {
346 		struct stat stst;
347 		dev_t root_devno;
348 
349 		stat("/", &stst);
350 		root_devno = stst.st_dev;
351 		if (stat("/dev", &stst) != 0)
352 			warning("Can't stat /dev: %m");
353 		else if (stst.st_dev == root_devno)
354 			devfs++;
355 	}
356 
357 	if (devfs) {
358 		struct iovec iov[4];
359 		char *s;
360 		int i;
361 
362 		char _fstype[]	= "fstype";
363 		char _devfs[]	= "devfs";
364 		char _fspath[]	= "fspath";
365 		char _path_dev[]= _PATH_DEV;
366 
367 		iov[0].iov_base = _fstype;
368 		iov[0].iov_len = sizeof(_fstype);
369 		iov[1].iov_base = _devfs;
370 		iov[1].iov_len = sizeof(_devfs);
371 		iov[2].iov_base = _fspath;
372 		iov[2].iov_len = sizeof(_fspath);
373 		/*
374 		 * Try to avoid the trailing slash in _PATH_DEV.
375 		 * Be *very* defensive.
376 		 */
377 		s = strdup(_PATH_DEV);
378 		if (s != NULL) {
379 			i = strlen(s);
380 			if (i > 0 && s[i - 1] == '/')
381 				s[i - 1] = '\0';
382 			iov[3].iov_base = s;
383 			iov[3].iov_len = strlen(s) + 1;
384 		} else {
385 			iov[3].iov_base = _path_dev;
386 			iov[3].iov_len = sizeof(_path_dev);
387 		}
388 		nmount(iov, 4, 0);
389 		if (s != NULL)
390 			free(s);
391 	}
392 
393 	if (initial_transition != reroot_phase_two) {
394 		/*
395 		 * Unmount reroot leftovers.  This runs after init(8)
396 		 * gets reexecuted after reroot_phase_two() is done.
397 		 */
398 		error = unmount(_PATH_REROOT, MNT_FORCE);
399 		if (error != 0 && errno != EINVAL)
400 			warning("Cannot unmount %s: %m", _PATH_REROOT);
401 	}
402 
403 	/*
404 	 * Start the state machine.
405 	 */
406 	transition(initial_transition);
407 
408 	/*
409 	 * Should never reach here.
410 	 */
411 	return 1;
412 }
413 
414 /*
415  * Associate a function with a signal handler.
416  */
417 static void
418 handle(sig_t handler, ...)
419 {
420 	int sig;
421 	struct sigaction sa;
422 	sigset_t mask_everything;
423 	va_list ap;
424 	va_start(ap, handler);
425 
426 	sa.sa_handler = handler;
427 	sigfillset(&mask_everything);
428 
429 	while ((sig = va_arg(ap, int)) != 0) {
430 		sa.sa_mask = mask_everything;
431 		/* XXX SA_RESTART? */
432 		sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
433 		sigaction(sig, &sa, (struct sigaction *) 0);
434 	}
435 	va_end(ap);
436 }
437 
438 /*
439  * Delete a set of signals from a mask.
440  */
441 static void
442 delset(sigset_t *maskp, ...)
443 {
444 	int sig;
445 	va_list ap;
446 	va_start(ap, maskp);
447 
448 	while ((sig = va_arg(ap, int)) != 0)
449 		sigdelset(maskp, sig);
450 	va_end(ap);
451 }
452 
453 /*
454  * Log a message and sleep for a while (to give someone an opportunity
455  * to read it and to save log or hardcopy output if the problem is chronic).
456  * NB: should send a message to the session logger to avoid blocking.
457  */
458 static void
459 stall(const char *message, ...)
460 {
461 	va_list ap;
462 	va_start(ap, message);
463 
464 	vsyslog(LOG_ALERT, message, ap);
465 	va_end(ap);
466 	sleep(STALL_TIMEOUT);
467 }
468 
469 /*
470  * Like stall(), but doesn't sleep.
471  * If cpp had variadic macros, the two functions could be #defines for another.
472  * NB: should send a message to the session logger to avoid blocking.
473  */
474 static void
475 warning(const char *message, ...)
476 {
477 	va_list ap;
478 	va_start(ap, message);
479 
480 	vsyslog(LOG_ALERT, message, ap);
481 	va_end(ap);
482 }
483 
484 /*
485  * Log an emergency message.
486  * NB: should send a message to the session logger to avoid blocking.
487  */
488 static void
489 emergency(const char *message, ...)
490 {
491 	va_list ap;
492 	va_start(ap, message);
493 
494 	vsyslog(LOG_EMERG, message, ap);
495 	va_end(ap);
496 }
497 
498 /*
499  * Catch a SIGSYS signal.
500  *
501  * These may arise if a system does not support sysctl.
502  * We tolerate up to 25 of these, then throw in the towel.
503  */
504 static void
505 badsys(int sig)
506 {
507 	static int badcount = 0;
508 
509 	if (badcount++ < 25)
510 		return;
511 	disaster(sig);
512 }
513 
514 /*
515  * Catch an unexpected signal.
516  */
517 static void
518 disaster(int sig)
519 {
520 
521 	emergency("fatal signal: %s",
522 	    (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
523 
524 	sleep(STALL_TIMEOUT);
525 	_exit(sig);		/* reboot */
526 }
527 
528 /*
529  * Get the security level of the kernel.
530  */
531 static int
532 getsecuritylevel(void)
533 {
534 #ifdef KERN_SECURELVL
535 	int name[2], curlevel;
536 	size_t len;
537 
538 	name[0] = CTL_KERN;
539 	name[1] = KERN_SECURELVL;
540 	len = sizeof curlevel;
541 	if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
542 		emergency("cannot get kernel security level: %s",
543 		    strerror(errno));
544 		return (-1);
545 	}
546 	return (curlevel);
547 #else
548 	return (-1);
549 #endif
550 }
551 
552 /*
553  * Set the security level of the kernel.
554  */
555 static void
556 setsecuritylevel(int newlevel)
557 {
558 #ifdef KERN_SECURELVL
559 	int name[2], curlevel;
560 
561 	curlevel = getsecuritylevel();
562 	if (newlevel == curlevel)
563 		return;
564 	name[0] = CTL_KERN;
565 	name[1] = KERN_SECURELVL;
566 	if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
567 		emergency(
568 		    "cannot change kernel security level from %d to %d: %s",
569 		    curlevel, newlevel, strerror(errno));
570 		return;
571 	}
572 #ifdef SECURE
573 	warning("kernel security level changed from %d to %d",
574 	    curlevel, newlevel);
575 #endif
576 #endif
577 }
578 
579 /*
580  * Change states in the finite state machine.
581  * The initial state is passed as an argument.
582  */
583 static void
584 transition(state_t s)
585 {
586 
587 	current_state = s;
588 	for (;;)
589 		current_state = (state_t) (*current_state)();
590 }
591 
592 /*
593  * Start a session and allocate a controlling terminal.
594  * Only called by children of init after forking.
595  */
596 static void
597 open_console(void)
598 {
599 	int fd;
600 
601 	/*
602 	 * Try to open /dev/console.  Open the device with O_NONBLOCK to
603 	 * prevent potential blocking on a carrier.
604 	 */
605 	revoke(_PATH_CONSOLE);
606 	if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
607 		(void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
608 		if (login_tty(fd) == 0)
609 			return;
610 		close(fd);
611 	}
612 
613 	/* No luck.  Log output to file if possible. */
614 	if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
615 		stall("cannot open null device.");
616 		_exit(1);
617 	}
618 	if (fd != STDIN_FILENO) {
619 		dup2(fd, STDIN_FILENO);
620 		close(fd);
621 	}
622 	fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
623 	if (fd == -1)
624 		dup2(STDIN_FILENO, STDOUT_FILENO);
625 	else if (fd != STDOUT_FILENO) {
626 		dup2(fd, STDOUT_FILENO);
627 		close(fd);
628 	}
629 	dup2(STDOUT_FILENO, STDERR_FILENO);
630 }
631 
632 static const char *
633 get_shell(void)
634 {
635 	static char kenv_value[PATH_MAX];
636 
637 	if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
638 		return kenv_value;
639 	else
640 		return _PATH_BSHELL;
641 }
642 
643 static void
644 write_stderr(const char *message)
645 {
646 
647 	write(STDERR_FILENO, message, strlen(message));
648 }
649 
650 static int
651 read_file(const char *path, void **bufp, size_t *bufsizep)
652 {
653 	struct stat sb;
654 	size_t bufsize;
655 	void *buf;
656 	ssize_t nbytes;
657 	int error, fd;
658 
659 	fd = open(path, O_RDONLY);
660 	if (fd < 0) {
661 		emergency("%s: %s", path, strerror(errno));
662 		return (-1);
663 	}
664 
665 	error = fstat(fd, &sb);
666 	if (error != 0) {
667 		emergency("fstat: %s", strerror(errno));
668 		close(fd);
669 		return (error);
670 	}
671 
672 	bufsize = sb.st_size;
673 	buf = malloc(bufsize);
674 	if (buf == NULL) {
675 		emergency("malloc: %s", strerror(errno));
676 		close(fd);
677 		return (error);
678 	}
679 
680 	nbytes = read(fd, buf, bufsize);
681 	if (nbytes != (ssize_t)bufsize) {
682 		emergency("read: %s", strerror(errno));
683 		close(fd);
684 		free(buf);
685 		return (error);
686 	}
687 
688 	error = close(fd);
689 	if (error != 0) {
690 		emergency("close: %s", strerror(errno));
691 		free(buf);
692 		return (error);
693 	}
694 
695 	*bufp = buf;
696 	*bufsizep = bufsize;
697 
698 	return (0);
699 }
700 
701 static int
702 create_file(const char *path, const void *buf, size_t bufsize)
703 {
704 	ssize_t nbytes;
705 	int error, fd;
706 
707 	fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
708 	if (fd < 0) {
709 		emergency("%s: %s", path, strerror(errno));
710 		return (-1);
711 	}
712 
713 	nbytes = write(fd, buf, bufsize);
714 	if (nbytes != (ssize_t)bufsize) {
715 		emergency("write: %s", strerror(errno));
716 		close(fd);
717 		return (-1);
718 	}
719 
720 	error = close(fd);
721 	if (error != 0) {
722 		emergency("close: %s", strerror(errno));
723 		return (-1);
724 	}
725 
726 	return (0);
727 }
728 
729 static int
730 mount_tmpfs(const char *fspath)
731 {
732 	struct iovec *iov;
733 	char errmsg[255];
734 	int error, iovlen;
735 
736 	iov = NULL;
737 	iovlen = 0;
738 	memset(errmsg, 0, sizeof(errmsg));
739 	build_iovec(&iov, &iovlen, "fstype",
740 	    __DECONST(void *, "tmpfs"), (size_t)-1);
741 	build_iovec(&iov, &iovlen, "fspath",
742 	    __DECONST(void *, fspath), (size_t)-1);
743 	build_iovec(&iov, &iovlen, "errmsg",
744 	    errmsg, sizeof(errmsg));
745 
746 	error = nmount(iov, iovlen, 0);
747 	if (error != 0) {
748 		if (*errmsg != '\0') {
749 			emergency("cannot mount tmpfs on %s: %s: %s",
750 			    fspath, errmsg, strerror(errno));
751 		} else {
752 			emergency("cannot mount tmpfs on %s: %s",
753 			    fspath, strerror(errno));
754 		}
755 		return (error);
756 	}
757 	return (0);
758 }
759 
760 static state_func_t
761 reroot(void)
762 {
763 	void *buf;
764 	size_t bufsize;
765 	int error;
766 
767 	buf = NULL;
768 	bufsize = 0;
769 
770 	revoke_ttys();
771 	runshutdown();
772 
773 	/*
774 	 * Make sure nobody can interfere with our scheme.
775 	 * Ignore ESRCH, which can apparently happen when
776 	 * there are no processes to kill.
777 	 */
778 	error = kill(-1, SIGKILL);
779 	if (error != 0 && errno != ESRCH) {
780 		emergency("kill(2) failed: %s", strerror(errno));
781 		goto out;
782 	}
783 
784 	/*
785 	 * Copy the init binary into tmpfs, so that we can unmount
786 	 * the old rootfs without committing suicide.
787 	 */
788 	error = read_file(init_path_argv0, &buf, &bufsize);
789 	if (error != 0)
790 		goto out;
791 	error = mount_tmpfs(_PATH_REROOT);
792 	if (error != 0)
793 		goto out;
794 	error = create_file(_PATH_REROOT_INIT, buf, bufsize);
795 	if (error != 0)
796 		goto out;
797 
798 	/*
799 	 * Execute the temporary init.
800 	 */
801 	execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
802 	emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
803 
804 out:
805 	emergency("reroot failed; going to single user mode");
806 	free(buf);
807 	return (state_func_t) single_user;
808 }
809 
810 static state_func_t
811 reroot_phase_two(void)
812 {
813 	char init_path[PATH_MAX], *path, *path_component;
814 	size_t init_path_len;
815 	int nbytes, error;
816 
817 	/*
818 	 * Ask the kernel to mount the new rootfs.
819 	 */
820 	error = reboot(RB_REROOT);
821 	if (error != 0) {
822 		emergency("RB_REBOOT failed: %s", strerror(errno));
823 		goto out;
824 	}
825 
826 	/*
827 	 * Figure out where the destination init(8) binary is.  Note that
828 	 * the path could be different than what we've started with.  Use
829 	 * the value from kenv, if set, or the one from sysctl otherwise.
830 	 * The latter defaults to a hardcoded value, but can be overridden
831 	 * by a build time option.
832 	 */
833 	nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
834 	if (nbytes <= 0) {
835 		init_path_len = sizeof(init_path);
836 		error = sysctlbyname("kern.init_path",
837 		    init_path, &init_path_len, NULL, 0);
838 		if (error != 0) {
839 			emergency("failed to retrieve kern.init_path: %s",
840 			    strerror(errno));
841 			goto out;
842 		}
843 	}
844 
845 	/*
846 	 * Repeat the init search logic from sys/kern/init_path.c
847 	 */
848 	path_component = init_path;
849 	while ((path = strsep(&path_component, ":")) != NULL) {
850 		/*
851 		 * Execute init(8) from the new rootfs.
852 		 */
853 		execl(path, path, NULL);
854 	}
855 	emergency("cannot exec init from %s: %s", init_path, strerror(errno));
856 
857 out:
858 	emergency("reroot failed; going to single user mode");
859 	return (state_func_t) single_user;
860 }
861 
862 /*
863  * Bring the system up single user.
864  */
865 static state_func_t
866 single_user(void)
867 {
868 	pid_t pid, wpid;
869 	int status;
870 	sigset_t mask;
871 	const char *shell;
872 	char *argv[2];
873 #ifdef SECURE
874 	struct ttyent *typ;
875 	struct passwd *pp;
876 	static const char banner[] =
877 		"Enter root password, or ^D to go multi-user\n";
878 	char *clear, *password;
879 #endif
880 #ifdef DEBUGSHELL
881 	char altshell[128];
882 #endif
883 
884 	if (Reboot) {
885 		/* Instead of going single user, let's reboot the machine */
886 		sync();
887 		reboot(howto);
888 		_exit(0);
889 	}
890 
891 	shell = get_shell();
892 
893 	if ((pid = fork()) == 0) {
894 		/*
895 		 * Start the single user session.
896 		 */
897 		open_console();
898 
899 #ifdef SECURE
900 		/*
901 		 * Check the root password.
902 		 * We don't care if the console is 'on' by default;
903 		 * it's the only tty that can be 'off' and 'secure'.
904 		 */
905 		typ = getttynam("console");
906 		pp = getpwnam("root");
907 		if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
908 		    pp && *pp->pw_passwd) {
909 			write_stderr(banner);
910 			for (;;) {
911 				clear = getpass("Password:");
912 				if (clear == NULL || *clear == '\0')
913 					_exit(0);
914 				password = crypt(clear, pp->pw_passwd);
915 				bzero(clear, _PASSWORD_LEN);
916 				if (password == NULL ||
917 				    strcmp(password, pp->pw_passwd) == 0)
918 					break;
919 				warning("single-user login failed\n");
920 			}
921 		}
922 		endttyent();
923 		endpwent();
924 #endif /* SECURE */
925 
926 #ifdef DEBUGSHELL
927 		{
928 			char *cp = altshell;
929 			int num;
930 
931 #define	SHREQUEST "Enter full pathname of shell or RETURN for "
932 			write_stderr(SHREQUEST);
933 			write_stderr(shell);
934 			write_stderr(": ");
935 			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
936 			    num != 0 && *cp != '\n' && cp < &altshell[127])
937 				cp++;
938 			*cp = '\0';
939 			if (altshell[0] != '\0')
940 				shell = altshell;
941 		}
942 #endif /* DEBUGSHELL */
943 
944 		/*
945 		 * Unblock signals.
946 		 * We catch all the interesting ones,
947 		 * and those are reset to SIG_DFL on exec.
948 		 */
949 		sigemptyset(&mask);
950 		sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
951 
952 		/*
953 		 * Fire off a shell.
954 		 * If the default one doesn't work, try the Bourne shell.
955 		 */
956 
957 		char name[] = "-sh";
958 
959 		argv[0] = name;
960 		argv[1] = 0;
961 		execv(shell, argv);
962 		emergency("can't exec %s for single user: %m", shell);
963 		execv(_PATH_BSHELL, argv);
964 		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
965 		sleep(STALL_TIMEOUT);
966 		_exit(1);
967 	}
968 
969 	if (pid == -1) {
970 		/*
971 		 * We are seriously hosed.  Do our best.
972 		 */
973 		emergency("can't fork single-user shell, trying again");
974 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
975 			continue;
976 		return (state_func_t) single_user;
977 	}
978 
979 	requested_transition = 0;
980 	do {
981 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
982 			collect_child(wpid);
983 		if (wpid == -1) {
984 			if (errno == EINTR)
985 				continue;
986 			warning("wait for single-user shell failed: %m; restarting");
987 			return (state_func_t) single_user;
988 		}
989 		if (wpid == pid && WIFSTOPPED(status)) {
990 			warning("init: shell stopped, restarting\n");
991 			kill(pid, SIGCONT);
992 			wpid = -1;
993 		}
994 	} while (wpid != pid && !requested_transition);
995 
996 	if (requested_transition)
997 		return (state_func_t) requested_transition;
998 
999 	if (!WIFEXITED(status)) {
1000 		if (WTERMSIG(status) == SIGKILL) {
1001 			/*
1002 			 *  reboot(8) killed shell?
1003 			 */
1004 			warning("single user shell terminated.");
1005 			sleep(STALL_TIMEOUT);
1006 			_exit(0);
1007 		} else {
1008 			warning("single user shell terminated, restarting");
1009 			return (state_func_t) single_user;
1010 		}
1011 	}
1012 
1013 	runcom_mode = FASTBOOT;
1014 	return (state_func_t) runcom;
1015 }
1016 
1017 /*
1018  * Run the system startup script.
1019  */
1020 static state_func_t
1021 runcom(void)
1022 {
1023 	state_func_t next_transition;
1024 
1025 	if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1026 		return next_transition;
1027 
1028 	runcom_mode = AUTOBOOT;		/* the default */
1029 	return (state_func_t) read_ttys;
1030 }
1031 
1032 /*
1033  * Run a shell script.
1034  * Returns 0 on success, otherwise the next transition to enter:
1035  *  - single_user if fork/execv/waitpid failed, or if the script
1036  *    terminated with a signal or exit code != 0.
1037  *  - death_single if a SIGTERM was delivered to init(8).
1038  */
1039 static state_func_t
1040 run_script(const char *script)
1041 {
1042 	pid_t pid, wpid;
1043 	int status;
1044 	char *argv[4];
1045 	const char *shell;
1046 	struct sigaction sa;
1047 
1048 	shell = get_shell();
1049 
1050 	if ((pid = fork()) == 0) {
1051 		sigemptyset(&sa.sa_mask);
1052 		sa.sa_flags = 0;
1053 		sa.sa_handler = SIG_IGN;
1054 		sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1055 		sigaction(SIGHUP, &sa, (struct sigaction *)0);
1056 
1057 		open_console();
1058 
1059 		char _sh[]		= "sh";
1060 		char _autoboot[]	= "autoboot";
1061 
1062 		argv[0] = _sh;
1063 		argv[1] = __DECONST(char *, script);
1064 		argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1065 		argv[3] = 0;
1066 
1067 		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1068 
1069 #ifdef LOGIN_CAP
1070 		setprocresources(RESOURCE_RC);
1071 #endif
1072 		execv(shell, argv);
1073 		stall("can't exec %s for %s: %m", shell, script);
1074 		_exit(1);	/* force single user mode */
1075 	}
1076 
1077 	if (pid == -1) {
1078 		emergency("can't fork for %s on %s: %m", shell, script);
1079 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1080 			continue;
1081 		sleep(STALL_TIMEOUT);
1082 		return (state_func_t) single_user;
1083 	}
1084 
1085 	/*
1086 	 * Copied from single_user().  This is a bit paranoid.
1087 	 */
1088 	requested_transition = 0;
1089 	do {
1090 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1091 			collect_child(wpid);
1092 		if (wpid == -1) {
1093 			if (requested_transition == death_single ||
1094 			    requested_transition == reroot)
1095 				return (state_func_t) requested_transition;
1096 			if (errno == EINTR)
1097 				continue;
1098 			warning("wait for %s on %s failed: %m; going to "
1099 			    "single user mode", shell, script);
1100 			return (state_func_t) single_user;
1101 		}
1102 		if (wpid == pid && WIFSTOPPED(status)) {
1103 			warning("init: %s on %s stopped, restarting\n",
1104 			    shell, script);
1105 			kill(pid, SIGCONT);
1106 			wpid = -1;
1107 		}
1108 	} while (wpid != pid);
1109 
1110 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1111 	    requested_transition == catatonia) {
1112 		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
1113 		sigset_t s;
1114 
1115 		sigfillset(&s);
1116 		for (;;)
1117 			sigsuspend(&s);
1118 	}
1119 
1120 	if (!WIFEXITED(status)) {
1121 		warning("%s on %s terminated abnormally, going to single "
1122 		    "user mode", shell, script);
1123 		return (state_func_t) single_user;
1124 	}
1125 
1126 	if (WEXITSTATUS(status))
1127 		return (state_func_t) single_user;
1128 
1129 	return (state_func_t) 0;
1130 }
1131 
1132 /*
1133  * Open the session database.
1134  *
1135  * NB: We could pass in the size here; is it necessary?
1136  */
1137 static int
1138 start_session_db(void)
1139 {
1140 	if (session_db && (*session_db->close)(session_db))
1141 		emergency("session database close: %s", strerror(errno));
1142 	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1143 		emergency("session database open: %s", strerror(errno));
1144 		return (1);
1145 	}
1146 	return (0);
1147 
1148 }
1149 
1150 /*
1151  * Add a new login session.
1152  */
1153 static void
1154 add_session(session_t *sp)
1155 {
1156 	DBT key;
1157 	DBT data;
1158 
1159 	key.data = &sp->se_process;
1160 	key.size = sizeof sp->se_process;
1161 	data.data = &sp;
1162 	data.size = sizeof sp;
1163 
1164 	if ((*session_db->put)(session_db, &key, &data, 0))
1165 		emergency("insert %d: %s", sp->se_process, strerror(errno));
1166 }
1167 
1168 /*
1169  * Delete an old login session.
1170  */
1171 static void
1172 del_session(session_t *sp)
1173 {
1174 	DBT key;
1175 
1176 	key.data = &sp->se_process;
1177 	key.size = sizeof sp->se_process;
1178 
1179 	if ((*session_db->del)(session_db, &key, 0))
1180 		emergency("delete %d: %s", sp->se_process, strerror(errno));
1181 }
1182 
1183 /*
1184  * Look up a login session by pid.
1185  */
1186 static session_t *
1187 find_session(pid_t pid)
1188 {
1189 	DBT key;
1190 	DBT data;
1191 	session_t *ret;
1192 
1193 	key.data = &pid;
1194 	key.size = sizeof pid;
1195 	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1196 		return 0;
1197 	bcopy(data.data, (char *)&ret, sizeof(ret));
1198 	return ret;
1199 }
1200 
1201 /*
1202  * Construct an argument vector from a command line.
1203  */
1204 static char **
1205 construct_argv(char *command)
1206 {
1207 	int argc = 0;
1208 	char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1209 						* sizeof (char *));
1210 
1211 	if ((argv[argc++] = strk(command)) == NULL) {
1212 		free(argv);
1213 		return (NULL);
1214 	}
1215 	while ((argv[argc++] = strk((char *) 0)) != NULL)
1216 		continue;
1217 	return argv;
1218 }
1219 
1220 /*
1221  * Deallocate a session descriptor.
1222  */
1223 static void
1224 free_session(session_t *sp)
1225 {
1226 	free(sp->se_device);
1227 	if (sp->se_getty) {
1228 		free(sp->se_getty);
1229 		free(sp->se_getty_argv_space);
1230 		free(sp->se_getty_argv);
1231 	}
1232 	if (sp->se_window) {
1233 		free(sp->se_window);
1234 		free(sp->se_window_argv_space);
1235 		free(sp->se_window_argv);
1236 	}
1237 	if (sp->se_type)
1238 		free(sp->se_type);
1239 	free(sp);
1240 }
1241 
1242 /*
1243  * Allocate a new session descriptor.
1244  * Mark it SE_PRESENT.
1245  */
1246 static session_t *
1247 new_session(session_t *sprev, struct ttyent *typ)
1248 {
1249 	session_t *sp;
1250 	int fd;
1251 
1252 	if ((typ->ty_status & TTY_ON) == 0 ||
1253 	    typ->ty_name == 0 ||
1254 	    typ->ty_getty == 0)
1255 		return 0;
1256 
1257 	sp = (session_t *) calloc(1, sizeof (session_t));
1258 
1259 	sp->se_flags |= SE_PRESENT;
1260 
1261 	sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1262 	sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1263 
1264 	/*
1265 	 * Attempt to open the device, if we get "device not configured"
1266 	 * then don't add the device to the session list.
1267 	 */
1268 	if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1269 		if (errno == ENXIO) {
1270 			free_session(sp);
1271 			return (0);
1272 		}
1273 	} else
1274 		close(fd);
1275 
1276 	if (setupargv(sp, typ) == 0) {
1277 		free_session(sp);
1278 		return (0);
1279 	}
1280 
1281 	sp->se_next = 0;
1282 	if (sprev == NULL) {
1283 		sessions = sp;
1284 		sp->se_prev = 0;
1285 	} else {
1286 		sprev->se_next = sp;
1287 		sp->se_prev = sprev;
1288 	}
1289 
1290 	return sp;
1291 }
1292 
1293 /*
1294  * Calculate getty and if useful window argv vectors.
1295  */
1296 static int
1297 setupargv(session_t *sp, struct ttyent *typ)
1298 {
1299 
1300 	if (sp->se_getty) {
1301 		free(sp->se_getty);
1302 		free(sp->se_getty_argv_space);
1303 		free(sp->se_getty_argv);
1304 	}
1305 	sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1306 	sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1307 	sp->se_getty_argv_space = strdup(sp->se_getty);
1308 	sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1309 	if (sp->se_getty_argv == NULL) {
1310 		warning("can't parse getty for port %s", sp->se_device);
1311 		free(sp->se_getty);
1312 		free(sp->se_getty_argv_space);
1313 		sp->se_getty = sp->se_getty_argv_space = 0;
1314 		return (0);
1315 	}
1316 	if (sp->se_window) {
1317 		free(sp->se_window);
1318 		free(sp->se_window_argv_space);
1319 		free(sp->se_window_argv);
1320 	}
1321 	sp->se_window = sp->se_window_argv_space = 0;
1322 	sp->se_window_argv = 0;
1323 	if (typ->ty_window) {
1324 		sp->se_window = strdup(typ->ty_window);
1325 		sp->se_window_argv_space = strdup(sp->se_window);
1326 		sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1327 		if (sp->se_window_argv == NULL) {
1328 			warning("can't parse window for port %s",
1329 			    sp->se_device);
1330 			free(sp->se_window_argv_space);
1331 			free(sp->se_window);
1332 			sp->se_window = sp->se_window_argv_space = 0;
1333 			return (0);
1334 		}
1335 	}
1336 	if (sp->se_type)
1337 		free(sp->se_type);
1338 	sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1339 	return (1);
1340 }
1341 
1342 /*
1343  * Walk the list of ttys and create sessions for each active line.
1344  */
1345 static state_func_t
1346 read_ttys(void)
1347 {
1348 	session_t *sp, *snext;
1349 	struct ttyent *typ;
1350 
1351 	/*
1352 	 * Destroy any previous session state.
1353 	 * There shouldn't be any, but just in case...
1354 	 */
1355 	for (sp = sessions; sp; sp = snext) {
1356 		snext = sp->se_next;
1357 		free_session(sp);
1358 	}
1359 	sessions = 0;
1360 	if (start_session_db())
1361 		return (state_func_t) single_user;
1362 
1363 	/*
1364 	 * Allocate a session entry for each active port.
1365 	 * Note that sp starts at 0.
1366 	 */
1367 	while ((typ = getttyent()) != NULL)
1368 		if ((snext = new_session(sp, typ)) != NULL)
1369 			sp = snext;
1370 
1371 	endttyent();
1372 
1373 	return (state_func_t) multi_user;
1374 }
1375 
1376 /*
1377  * Start a window system running.
1378  */
1379 static void
1380 start_window_system(session_t *sp)
1381 {
1382 	pid_t pid;
1383 	sigset_t mask;
1384 	char term[64], *env[2];
1385 	int status;
1386 
1387 	if ((pid = fork()) == -1) {
1388 		emergency("can't fork for window system on port %s: %m",
1389 		    sp->se_device);
1390 		/* hope that getty fails and we can try again */
1391 		return;
1392 	}
1393 	if (pid) {
1394 		waitpid(-1, &status, 0);
1395 		return;
1396 	}
1397 
1398 	/* reparent window process to the init to not make a zombie on exit */
1399 	if ((pid = fork()) == -1) {
1400 		emergency("can't fork for window system on port %s: %m",
1401 		    sp->se_device);
1402 		_exit(1);
1403 	}
1404 	if (pid)
1405 		_exit(0);
1406 
1407 	sigemptyset(&mask);
1408 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1409 
1410 	if (setsid() < 0)
1411 		emergency("setsid failed (window) %m");
1412 
1413 #ifdef LOGIN_CAP
1414 	setprocresources(RESOURCE_WINDOW);
1415 #endif
1416 	if (sp->se_type) {
1417 		/* Don't use malloc after fork */
1418 		strcpy(term, "TERM=");
1419 		strncat(term, sp->se_type, sizeof(term) - 6);
1420 		env[0] = term;
1421 		env[1] = 0;
1422 	}
1423 	else
1424 		env[0] = 0;
1425 	execve(sp->se_window_argv[0], sp->se_window_argv, env);
1426 	stall("can't exec window system '%s' for port %s: %m",
1427 		sp->se_window_argv[0], sp->se_device);
1428 	_exit(1);
1429 }
1430 
1431 /*
1432  * Start a login session running.
1433  */
1434 static pid_t
1435 start_getty(session_t *sp)
1436 {
1437 	pid_t pid;
1438 	sigset_t mask;
1439 	time_t current_time = time((time_t *) 0);
1440 	int too_quick = 0;
1441 	char term[64], *env[2];
1442 
1443 	if (current_time >= sp->se_started &&
1444 	    current_time - sp->se_started < GETTY_SPACING) {
1445 		if (++sp->se_nspace > GETTY_NSPACE) {
1446 			sp->se_nspace = 0;
1447 			too_quick = 1;
1448 		}
1449 	} else
1450 		sp->se_nspace = 0;
1451 
1452 	/*
1453 	 * fork(), not vfork() -- we can't afford to block.
1454 	 */
1455 	if ((pid = fork()) == -1) {
1456 		emergency("can't fork for getty on port %s: %m", sp->se_device);
1457 		return -1;
1458 	}
1459 
1460 	if (pid)
1461 		return pid;
1462 
1463 	if (too_quick) {
1464 		warning("getty repeating too quickly on port %s, sleeping %d secs",
1465 		    sp->se_device, GETTY_SLEEP);
1466 		sleep((unsigned) GETTY_SLEEP);
1467 	}
1468 
1469 	if (sp->se_window) {
1470 		start_window_system(sp);
1471 		sleep(WINDOW_WAIT);
1472 	}
1473 
1474 	sigemptyset(&mask);
1475 	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1476 
1477 #ifdef LOGIN_CAP
1478 	setprocresources(RESOURCE_GETTY);
1479 #endif
1480 	if (sp->se_type) {
1481 		/* Don't use malloc after fork */
1482 		strcpy(term, "TERM=");
1483 		strncat(term, sp->se_type, sizeof(term) - 6);
1484 		env[0] = term;
1485 		env[1] = 0;
1486 	} else
1487 		env[0] = 0;
1488 	execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1489 	stall("can't exec getty '%s' for port %s: %m",
1490 		sp->se_getty_argv[0], sp->se_device);
1491 	_exit(1);
1492 }
1493 
1494 /*
1495  * Collect exit status for a child.
1496  * If an exiting login, start a new login running.
1497  */
1498 static void
1499 collect_child(pid_t pid)
1500 {
1501 	session_t *sp, *sprev, *snext;
1502 
1503 	if (! sessions)
1504 		return;
1505 
1506 	if (! (sp = find_session(pid)))
1507 		return;
1508 
1509 	del_session(sp);
1510 	sp->se_process = 0;
1511 
1512 	if (sp->se_flags & SE_SHUTDOWN) {
1513 		if ((sprev = sp->se_prev) != NULL)
1514 			sprev->se_next = sp->se_next;
1515 		else
1516 			sessions = sp->se_next;
1517 		if ((snext = sp->se_next) != NULL)
1518 			snext->se_prev = sp->se_prev;
1519 		free_session(sp);
1520 		return;
1521 	}
1522 
1523 	if ((pid = start_getty(sp)) == -1) {
1524 		/* serious trouble */
1525 		requested_transition = clean_ttys;
1526 		return;
1527 	}
1528 
1529 	sp->se_process = pid;
1530 	sp->se_started = time((time_t *) 0);
1531 	add_session(sp);
1532 }
1533 
1534 /*
1535  * Catch a signal and request a state transition.
1536  */
1537 static void
1538 transition_handler(int sig)
1539 {
1540 
1541 	switch (sig) {
1542 	case SIGHUP:
1543 		if (current_state == read_ttys || current_state == multi_user ||
1544 		    current_state == clean_ttys || current_state == catatonia)
1545 			requested_transition = clean_ttys;
1546 		break;
1547 	case SIGUSR2:
1548 		howto = RB_POWEROFF;
1549 	case SIGUSR1:
1550 		howto |= RB_HALT;
1551 	case SIGINT:
1552 		Reboot = TRUE;
1553 	case SIGTERM:
1554 		if (current_state == read_ttys || current_state == multi_user ||
1555 		    current_state == clean_ttys || current_state == catatonia)
1556 			requested_transition = death;
1557 		else
1558 			requested_transition = death_single;
1559 		break;
1560 	case SIGTSTP:
1561 		if (current_state == runcom || current_state == read_ttys ||
1562 		    current_state == clean_ttys ||
1563 		    current_state == multi_user || current_state == catatonia)
1564 			requested_transition = catatonia;
1565 		break;
1566 	case SIGEMT:
1567 		requested_transition = reroot;
1568 		break;
1569 	default:
1570 		requested_transition = 0;
1571 		break;
1572 	}
1573 }
1574 
1575 /*
1576  * Take the system multiuser.
1577  */
1578 static state_func_t
1579 multi_user(void)
1580 {
1581 	pid_t pid;
1582 	session_t *sp;
1583 
1584 	requested_transition = 0;
1585 
1586 	/*
1587 	 * If the administrator has not set the security level to -1
1588 	 * to indicate that the kernel should not run multiuser in secure
1589 	 * mode, and the run script has not set a higher level of security
1590 	 * than level 1, then put the kernel into secure mode.
1591 	 */
1592 	if (getsecuritylevel() == 0)
1593 		setsecuritylevel(1);
1594 
1595 	for (sp = sessions; sp; sp = sp->se_next) {
1596 		if (sp->se_process)
1597 			continue;
1598 		if ((pid = start_getty(sp)) == -1) {
1599 			/* serious trouble */
1600 			requested_transition = clean_ttys;
1601 			break;
1602 		}
1603 		sp->se_process = pid;
1604 		sp->se_started = time((time_t *) 0);
1605 		add_session(sp);
1606 	}
1607 
1608 	while (!requested_transition)
1609 		if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1610 			collect_child(pid);
1611 
1612 	return (state_func_t) requested_transition;
1613 }
1614 
1615 /*
1616  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1617  */
1618 static state_func_t
1619 clean_ttys(void)
1620 {
1621 	session_t *sp, *sprev;
1622 	struct ttyent *typ;
1623 	int devlen;
1624 	char *old_getty, *old_window, *old_type;
1625 
1626 	/*
1627 	 * mark all sessions for death, (!SE_PRESENT)
1628 	 * as we find or create new ones they'll be marked as keepers,
1629 	 * we'll later nuke all the ones not found in /etc/ttys
1630 	 */
1631 	for (sp = sessions; sp != NULL; sp = sp->se_next)
1632 		sp->se_flags &= ~SE_PRESENT;
1633 
1634 	devlen = sizeof(_PATH_DEV) - 1;
1635 	while ((typ = getttyent()) != NULL) {
1636 		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1637 			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1638 				break;
1639 
1640 		if (sp) {
1641 			/* we want this one to live */
1642 			sp->se_flags |= SE_PRESENT;
1643 			if ((typ->ty_status & TTY_ON) == 0 ||
1644 			    typ->ty_getty == 0) {
1645 				sp->se_flags |= SE_SHUTDOWN;
1646 				kill(sp->se_process, SIGHUP);
1647 				continue;
1648 			}
1649 			sp->se_flags &= ~SE_SHUTDOWN;
1650 			old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1651 			old_window = sp->se_window ? strdup(sp->se_window) : 0;
1652 			old_type = sp->se_type ? strdup(sp->se_type) : 0;
1653 			if (setupargv(sp, typ) == 0) {
1654 				warning("can't parse getty for port %s",
1655 					sp->se_device);
1656 				sp->se_flags |= SE_SHUTDOWN;
1657 				kill(sp->se_process, SIGHUP);
1658 			}
1659 			else if (   !old_getty
1660 				 || (!old_type && sp->se_type)
1661 				 || (old_type && !sp->se_type)
1662 				 || (!old_window && sp->se_window)
1663 				 || (old_window && !sp->se_window)
1664 				 || (strcmp(old_getty, sp->se_getty) != 0)
1665 				 || (old_window && strcmp(old_window, sp->se_window) != 0)
1666 				 || (old_type && strcmp(old_type, sp->se_type) != 0)
1667 				) {
1668 				/* Don't set SE_SHUTDOWN here */
1669 				sp->se_nspace = 0;
1670 				sp->se_started = 0;
1671 				kill(sp->se_process, SIGHUP);
1672 			}
1673 			if (old_getty)
1674 				free(old_getty);
1675 			if (old_window)
1676 				free(old_window);
1677 			if (old_type)
1678 				free(old_type);
1679 			continue;
1680 		}
1681 
1682 		new_session(sprev, typ);
1683 	}
1684 
1685 	endttyent();
1686 
1687 	/*
1688 	 * sweep through and kill all deleted sessions
1689 	 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1690 	 */
1691 	for (sp = sessions; sp != NULL; sp = sp->se_next) {
1692 		if ((sp->se_flags & SE_PRESENT) == 0) {
1693 			sp->se_flags |= SE_SHUTDOWN;
1694 			kill(sp->se_process, SIGHUP);
1695 		}
1696 	}
1697 
1698 	return (state_func_t) multi_user;
1699 }
1700 
1701 /*
1702  * Block further logins.
1703  */
1704 static state_func_t
1705 catatonia(void)
1706 {
1707 	session_t *sp;
1708 
1709 	for (sp = sessions; sp; sp = sp->se_next)
1710 		sp->se_flags |= SE_SHUTDOWN;
1711 
1712 	return (state_func_t) multi_user;
1713 }
1714 
1715 /*
1716  * Note SIGALRM.
1717  */
1718 static void
1719 alrm_handler(int sig)
1720 {
1721 
1722 	(void)sig;
1723 	clang = 1;
1724 }
1725 
1726 /*
1727  * Bring the system down to single user.
1728  */
1729 static state_func_t
1730 death(void)
1731 {
1732 	int block, blocked;
1733 	size_t len;
1734 
1735 	/* Temporarily block suspend. */
1736 	len = sizeof(blocked);
1737 	block = 1;
1738 	if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1739 	    &block, sizeof(block)) == -1)
1740 		blocked = 0;
1741 
1742 	/*
1743 	 * Also revoke the TTY here.  Because runshutdown() may reopen
1744 	 * the TTY whose getty we're killing here, there is no guarantee
1745 	 * runshutdown() will perform the initial open() call, causing
1746 	 * the terminal attributes to be misconfigured.
1747 	 */
1748 	revoke_ttys();
1749 
1750 	/* Try to run the rc.shutdown script within a period of time */
1751 	runshutdown();
1752 
1753 	/* Unblock suspend if we blocked it. */
1754 	if (!blocked)
1755 		sysctlbyname("kern.suspend_blocked", NULL, NULL,
1756 		    &blocked, sizeof(blocked));
1757 
1758 	return (state_func_t) death_single;
1759 }
1760 
1761 /*
1762  * Do what is necessary to reinitialize single user mode or reboot
1763  * from an incomplete state.
1764  */
1765 static state_func_t
1766 death_single(void)
1767 {
1768 	int i;
1769 	pid_t pid;
1770 	static const int death_sigs[2] = { SIGTERM, SIGKILL };
1771 
1772 	revoke(_PATH_CONSOLE);
1773 
1774 	for (i = 0; i < 2; ++i) {
1775 		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1776 			return (state_func_t) single_user;
1777 
1778 		clang = 0;
1779 		alarm(DEATH_WATCH);
1780 		do
1781 			if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1782 				collect_child(pid);
1783 		while (clang == 0 && errno != ECHILD);
1784 
1785 		if (errno == ECHILD)
1786 			return (state_func_t) single_user;
1787 	}
1788 
1789 	warning("some processes would not die; ps axl advised");
1790 
1791 	return (state_func_t) single_user;
1792 }
1793 
1794 static void
1795 revoke_ttys(void)
1796 {
1797 	session_t *sp;
1798 
1799 	for (sp = sessions; sp; sp = sp->se_next) {
1800 		sp->se_flags |= SE_SHUTDOWN;
1801 		kill(sp->se_process, SIGHUP);
1802 		revoke(sp->se_device);
1803 	}
1804 }
1805 
1806 /*
1807  * Run the system shutdown script.
1808  *
1809  * Exit codes:      XXX I should document more
1810  * -2       shutdown script terminated abnormally
1811  * -1       fatal error - can't run script
1812  * 0        good.
1813  * >0       some error (exit code)
1814  */
1815 static int
1816 runshutdown(void)
1817 {
1818 	pid_t pid, wpid;
1819 	int status;
1820 	int shutdowntimeout;
1821 	size_t len;
1822 	char *argv[4];
1823 	const char *shell;
1824 	struct sigaction sa;
1825 	struct stat sb;
1826 
1827 	/*
1828 	 * rc.shutdown is optional, so to prevent any unnecessary
1829 	 * complaints from the shell we simply don't run it if the
1830 	 * file does not exist. If the stat() here fails for other
1831 	 * reasons, we'll let the shell complain.
1832 	 */
1833 	if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1834 		return 0;
1835 
1836 	shell = get_shell();
1837 
1838 	if ((pid = fork()) == 0) {
1839 		sigemptyset(&sa.sa_mask);
1840 		sa.sa_flags = 0;
1841 		sa.sa_handler = SIG_IGN;
1842 		sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1843 		sigaction(SIGHUP, &sa, (struct sigaction *)0);
1844 
1845 		open_console();
1846 
1847 		char _sh[]	= "sh";
1848 		char _reboot[]	= "reboot";
1849 		char _single[]	= "single";
1850 		char _path_rundown[] = _PATH_RUNDOWN;
1851 
1852 		argv[0] = _sh;
1853 		argv[1] = _path_rundown;
1854 		argv[2] = Reboot ? _reboot : _single;
1855 		argv[3] = 0;
1856 
1857 		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1858 
1859 #ifdef LOGIN_CAP
1860 		setprocresources(RESOURCE_RC);
1861 #endif
1862 		execv(shell, argv);
1863 		warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1864 		_exit(1);	/* force single user mode */
1865 	}
1866 
1867 	if (pid == -1) {
1868 		emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1869 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1870 			continue;
1871 		sleep(STALL_TIMEOUT);
1872 		return -1;
1873 	}
1874 
1875 	len = sizeof(shutdowntimeout);
1876 	if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1877 	    NULL, 0) == -1 || shutdowntimeout < 2)
1878 		shutdowntimeout = DEATH_SCRIPT;
1879 	alarm(shutdowntimeout);
1880 	clang = 0;
1881 	/*
1882 	 * Copied from single_user().  This is a bit paranoid.
1883 	 * Use the same ALRM handler.
1884 	 */
1885 	do {
1886 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1887 			collect_child(wpid);
1888 		if (clang == 1) {
1889 			/* we were waiting for the sub-shell */
1890 			kill(wpid, SIGTERM);
1891 			warning("timeout expired for %s on %s: %m; going to "
1892 			    "single user mode", shell, _PATH_RUNDOWN);
1893 			return -1;
1894 		}
1895 		if (wpid == -1) {
1896 			if (errno == EINTR)
1897 				continue;
1898 			warning("wait for %s on %s failed: %m; going to "
1899 			    "single user mode", shell, _PATH_RUNDOWN);
1900 			return -1;
1901 		}
1902 		if (wpid == pid && WIFSTOPPED(status)) {
1903 			warning("init: %s on %s stopped, restarting\n",
1904 				shell, _PATH_RUNDOWN);
1905 			kill(pid, SIGCONT);
1906 			wpid = -1;
1907 		}
1908 	} while (wpid != pid && !clang);
1909 
1910 	/* Turn off the alarm */
1911 	alarm(0);
1912 
1913 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1914 	    requested_transition == catatonia) {
1915 		/*
1916 		 * /etc/rc.shutdown executed /sbin/reboot;
1917 		 * wait for the end quietly
1918 		 */
1919 		sigset_t s;
1920 
1921 		sigfillset(&s);
1922 		for (;;)
1923 			sigsuspend(&s);
1924 	}
1925 
1926 	if (!WIFEXITED(status)) {
1927 		warning("%s on %s terminated abnormally, going to "
1928 		    "single user mode", shell, _PATH_RUNDOWN);
1929 		return -2;
1930 	}
1931 
1932 	if ((status = WEXITSTATUS(status)) != 0)
1933 		warning("%s returned status %d", _PATH_RUNDOWN, status);
1934 
1935 	return status;
1936 }
1937 
1938 static char *
1939 strk(char *p)
1940 {
1941 	static char *t;
1942 	char *q;
1943 	int c;
1944 
1945 	if (p)
1946 		t = p;
1947 	if (!t)
1948 		return 0;
1949 
1950 	c = *t;
1951 	while (c == ' ' || c == '\t' )
1952 		c = *++t;
1953 	if (!c) {
1954 		t = 0;
1955 		return 0;
1956 	}
1957 	q = t;
1958 	if (c == '\'') {
1959 		c = *++t;
1960 		q = t;
1961 		while (c && c != '\'')
1962 			c = *++t;
1963 		if (!c)  /* unterminated string */
1964 			q = t = 0;
1965 		else
1966 			*t++ = 0;
1967 	} else {
1968 		while (c && c != ' ' && c != '\t' )
1969 			c = *++t;
1970 		*t++ = 0;
1971 		if (!c)
1972 			t = 0;
1973 	}
1974 	return q;
1975 }
1976 
1977 #ifdef LOGIN_CAP
1978 static void
1979 setprocresources(const char *cname)
1980 {
1981 	login_cap_t *lc;
1982 	if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1983 		setusercontext(lc, (struct passwd*)NULL, 0,
1984 		    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
1985 		    LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);
1986 		login_close(lc);
1987 	}
1988 }
1989 #endif
1990