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