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