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