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