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