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