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