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