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