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