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