init.c revision 123157
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 123157 2003-12-05 04:28:03Z imp $";
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_BSHELL, argv);
741		stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
742		_exit(1);	/* force single user mode */
743	}
744
745	if (pid == -1) {
746		emergency("can't fork for %s on %s: %m",
747			_PATH_BSHELL, _PATH_RUNCOM);
748		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
749			continue;
750		sleep(STALL_TIMEOUT);
751		return (state_func_t) single_user;
752	}
753
754	/*
755	 * Copied from single_user().  This is a bit paranoid.
756	 */
757	requested_transition = 0;
758	do {
759		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
760			collect_child(wpid);
761		if (wpid == -1) {
762			if (requested_transition == death)
763				return (state_func_t) death;
764			if (errno == EINTR)
765				continue;
766			warning("wait for %s on %s failed: %m; going to single user mode",
767				_PATH_BSHELL, _PATH_RUNCOM);
768			return (state_func_t) single_user;
769		}
770		if (wpid == pid && WIFSTOPPED(status)) {
771			warning("init: %s on %s stopped, restarting\n",
772				_PATH_BSHELL, _PATH_RUNCOM);
773			kill(pid, SIGCONT);
774			wpid = -1;
775		}
776	} while (wpid != pid);
777
778	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
779	    requested_transition == catatonia) {
780		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
781		sigset_t s;
782
783		sigfillset(&s);
784		for (;;)
785			sigsuspend(&s);
786	}
787
788	if (!WIFEXITED(status)) {
789		warning("%s on %s terminated abnormally, going to single user mode",
790			_PATH_BSHELL, _PATH_RUNCOM);
791		return (state_func_t) single_user;
792	}
793
794	if (WEXITSTATUS(status))
795		return (state_func_t) single_user;
796
797	runcom_mode = AUTOBOOT;		/* the default */
798	/* NB: should send a message to the session logger to avoid blocking. */
799	logwtmp("~", "reboot", "");
800	return (state_func_t) read_ttys;
801}
802
803/*
804 * Open the session database.
805 *
806 * NB: We could pass in the size here; is it necessary?
807 */
808int
809start_session_db(void)
810{
811	if (session_db && (*session_db->close)(session_db))
812		emergency("session database close: %s", strerror(errno));
813	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
814		emergency("session database open: %s", strerror(errno));
815		return (1);
816	}
817	return (0);
818
819}
820
821/*
822 * Add a new login session.
823 */
824void
825add_session(session_t *sp)
826{
827	DBT key;
828	DBT data;
829
830	key.data = &sp->se_process;
831	key.size = sizeof sp->se_process;
832	data.data = &sp;
833	data.size = sizeof sp;
834
835	if ((*session_db->put)(session_db, &key, &data, 0))
836		emergency("insert %d: %s", sp->se_process, strerror(errno));
837}
838
839/*
840 * Delete an old login session.
841 */
842void
843del_session(session_t *sp)
844{
845	DBT key;
846
847	key.data = &sp->se_process;
848	key.size = sizeof sp->se_process;
849
850	if ((*session_db->del)(session_db, &key, 0))
851		emergency("delete %d: %s", sp->se_process, strerror(errno));
852}
853
854/*
855 * Look up a login session by pid.
856 */
857session_t *
858find_session(pid_t pid)
859{
860	DBT key;
861	DBT data;
862	session_t *ret;
863
864	key.data = &pid;
865	key.size = sizeof pid;
866	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
867		return 0;
868	bcopy(data.data, (char *)&ret, sizeof(ret));
869	return ret;
870}
871
872/*
873 * Construct an argument vector from a command line.
874 */
875char **
876construct_argv(char *command)
877{
878	char *strk (char *);
879	int argc = 0;
880	char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
881						* sizeof (char *));
882
883	if ((argv[argc++] = strk(command)) == 0) {
884		free(argv);
885		return (NULL);
886	}
887	while ((argv[argc++] = strk((char *) 0)) != NULL)
888		continue;
889	return argv;
890}
891
892/*
893 * Deallocate a session descriptor.
894 */
895void
896free_session(session_t *sp)
897{
898	free(sp->se_device);
899	if (sp->se_getty) {
900		free(sp->se_getty);
901		free(sp->se_getty_argv_space);
902		free(sp->se_getty_argv);
903	}
904	if (sp->se_window) {
905		free(sp->se_window);
906		free(sp->se_window_argv_space);
907		free(sp->se_window_argv);
908	}
909	if (sp->se_type)
910		free(sp->se_type);
911	free(sp);
912}
913
914/*
915 * Allocate a new session descriptor.
916 * Mark it SE_PRESENT.
917 */
918session_t *
919new_session(session_t *sprev, int session_index, struct ttyent *typ)
920{
921	session_t *sp;
922	int fd;
923
924	if ((typ->ty_status & TTY_ON) == 0 ||
925	    typ->ty_name == 0 ||
926	    typ->ty_getty == 0)
927		return 0;
928
929	sp = (session_t *) calloc(1, sizeof (session_t));
930
931	sp->se_index = session_index;
932	sp->se_flags |= SE_PRESENT;
933
934	sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
935	(void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
936
937	/*
938	 * Attempt to open the device, if we get "device not configured"
939	 * then don't add the device to the session list.
940	 */
941	if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
942		if (errno == ENXIO || errno == ENOENT) {
943			free_session(sp);
944			return (0);
945		}
946	} else
947		close(fd);
948
949	if (setupargv(sp, typ) == 0) {
950		free_session(sp);
951		return (0);
952	}
953
954	sp->se_next = 0;
955	if (sprev == 0) {
956		sessions = sp;
957		sp->se_prev = 0;
958	} else {
959		sprev->se_next = sp;
960		sp->se_prev = sprev;
961	}
962
963	return sp;
964}
965
966/*
967 * Calculate getty and if useful window argv vectors.
968 */
969int
970setupargv(session_t *sp, struct ttyent *typ)
971{
972
973	if (sp->se_getty) {
974		free(sp->se_getty);
975		free(sp->se_getty_argv_space);
976		free(sp->se_getty_argv);
977	}
978	sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
979	(void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
980	sp->se_getty_argv_space = strdup(sp->se_getty);
981	sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
982	if (sp->se_getty_argv == 0) {
983		warning("can't parse getty for port %s", sp->se_device);
984		free(sp->se_getty);
985		free(sp->se_getty_argv_space);
986		sp->se_getty = sp->se_getty_argv_space = 0;
987		return (0);
988	}
989	if (sp->se_window) {
990		free(sp->se_window);
991		free(sp->se_window_argv_space);
992		free(sp->se_window_argv);
993	}
994	sp->se_window = sp->se_window_argv_space = 0;
995	sp->se_window_argv = 0;
996	if (typ->ty_window) {
997		sp->se_window = strdup(typ->ty_window);
998		sp->se_window_argv_space = strdup(sp->se_window);
999		sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1000		if (sp->se_window_argv == 0) {
1001			warning("can't parse window for port %s",
1002				sp->se_device);
1003			free(sp->se_window_argv_space);
1004			free(sp->se_window);
1005			sp->se_window = sp->se_window_argv_space = 0;
1006			return (0);
1007		}
1008	}
1009	if (sp->se_type)
1010		free(sp->se_type);
1011	sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1012	return (1);
1013}
1014
1015/*
1016 * Walk the list of ttys and create sessions for each active line.
1017 */
1018state_func_t
1019read_ttys(void)
1020{
1021	int session_index = 0;
1022	session_t *sp, *snext;
1023	struct ttyent *typ;
1024
1025	/*
1026	 * Destroy any previous session state.
1027	 * There shouldn't be any, but just in case...
1028	 */
1029	for (sp = sessions; sp; sp = snext) {
1030		if (sp->se_process)
1031			clear_session_logs(sp);
1032		snext = sp->se_next;
1033		free_session(sp);
1034	}
1035	sessions = 0;
1036	if (start_session_db())
1037		return (state_func_t) single_user;
1038
1039	/*
1040	 * Allocate a session entry for each active port.
1041	 * Note that sp starts at 0.
1042	 */
1043	while ((typ = getttyent()) != NULL)
1044		if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1045			sp = snext;
1046
1047	endttyent();
1048
1049	return (state_func_t) multi_user;
1050}
1051
1052/*
1053 * Start a window system running.
1054 */
1055void
1056start_window_system(session_t *sp)
1057{
1058	pid_t pid;
1059	sigset_t mask;
1060	char term[64], *env[2];
1061
1062	if ((pid = fork()) == -1) {
1063		emergency("can't fork for window system on port %s: %m",
1064			sp->se_device);
1065		/* hope that getty fails and we can try again */
1066		return;
1067	}
1068
1069	if (pid)
1070		return;
1071
1072	sigemptyset(&mask);
1073	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1074
1075	if (setsid() < 0)
1076		emergency("setsid failed (window) %m");
1077
1078#ifdef LOGIN_CAP
1079	setprocresources(RESOURCE_WINDOW);
1080#endif
1081	if (sp->se_type) {
1082		/* Don't use malloc after fork */
1083		strcpy(term, "TERM=");
1084		strncat(term, sp->se_type, sizeof(term) - 6);
1085		env[0] = term;
1086		env[1] = 0;
1087	}
1088	else
1089		env[0] = 0;
1090	execve(sp->se_window_argv[0], sp->se_window_argv, env);
1091	stall("can't exec window system '%s' for port %s: %m",
1092		sp->se_window_argv[0], sp->se_device);
1093	_exit(1);
1094}
1095
1096/*
1097 * Start a login session running.
1098 */
1099pid_t
1100start_getty(session_t *sp)
1101{
1102	pid_t pid;
1103	sigset_t mask;
1104	time_t current_time = time((time_t *) 0);
1105	int too_quick = 0;
1106	char term[64], *env[2];
1107
1108	if (current_time >= sp->se_started &&
1109	    current_time - sp->se_started < GETTY_SPACING) {
1110		if (++sp->se_nspace > GETTY_NSPACE) {
1111			sp->se_nspace = 0;
1112			too_quick = 1;
1113		}
1114	} else
1115		sp->se_nspace = 0;
1116
1117	/*
1118	 * fork(), not vfork() -- we can't afford to block.
1119	 */
1120	if ((pid = fork()) == -1) {
1121		emergency("can't fork for getty on port %s: %m", sp->se_device);
1122		return -1;
1123	}
1124
1125	if (pid)
1126		return pid;
1127
1128	if (too_quick) {
1129		warning("getty repeating too quickly on port %s, sleeping %d secs",
1130			sp->se_device, GETTY_SLEEP);
1131		sleep((unsigned) GETTY_SLEEP);
1132	}
1133
1134	if (sp->se_window) {
1135		start_window_system(sp);
1136		sleep(WINDOW_WAIT);
1137	}
1138
1139	sigemptyset(&mask);
1140	sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1141
1142#ifdef LOGIN_CAP
1143	setprocresources(RESOURCE_GETTY);
1144#endif
1145	if (sp->se_type) {
1146		/* Don't use malloc after fork */
1147		strcpy(term, "TERM=");
1148		strncat(term, sp->se_type, sizeof(term) - 6);
1149		env[0] = term;
1150		env[1] = 0;
1151	}
1152	else
1153		env[0] = 0;
1154	execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1155	stall("can't exec getty '%s' for port %s: %m",
1156		sp->se_getty_argv[0], sp->se_device);
1157	_exit(1);
1158}
1159
1160/*
1161 * Collect exit status for a child.
1162 * If an exiting login, start a new login running.
1163 */
1164void
1165collect_child(pid_t pid)
1166{
1167	session_t *sp, *sprev, *snext;
1168
1169	if (! sessions)
1170		return;
1171
1172	if (! (sp = find_session(pid)))
1173		return;
1174
1175	clear_session_logs(sp);
1176	del_session(sp);
1177	sp->se_process = 0;
1178
1179	if (sp->se_flags & SE_SHUTDOWN) {
1180		if ((sprev = sp->se_prev) != NULL)
1181			sprev->se_next = sp->se_next;
1182		else
1183			sessions = sp->se_next;
1184		if ((snext = sp->se_next) != NULL)
1185			snext->se_prev = sp->se_prev;
1186		free_session(sp);
1187		return;
1188	}
1189
1190	if ((pid = start_getty(sp)) == -1) {
1191		/* serious trouble */
1192		requested_transition = clean_ttys;
1193		return;
1194	}
1195
1196	sp->se_process = pid;
1197	sp->se_started = time((time_t *) 0);
1198	add_session(sp);
1199}
1200
1201/*
1202 * Catch a signal and request a state transition.
1203 */
1204void
1205transition_handler(int sig)
1206{
1207
1208	switch (sig) {
1209	case SIGHUP:
1210		requested_transition = clean_ttys;
1211		break;
1212	case SIGUSR2:
1213		howto = RB_POWEROFF;
1214	case SIGUSR1:
1215		howto |= RB_HALT;
1216	case SIGINT:
1217		Reboot = TRUE;
1218	case SIGTERM:
1219		requested_transition = death;
1220		break;
1221	case SIGTSTP:
1222		requested_transition = catatonia;
1223		break;
1224	default:
1225		requested_transition = 0;
1226		break;
1227	}
1228}
1229
1230/*
1231 * Take the system multiuser.
1232 */
1233state_func_t
1234multi_user(void)
1235{
1236	pid_t pid;
1237	session_t *sp;
1238
1239	requested_transition = 0;
1240
1241	/*
1242	 * If the administrator has not set the security level to -1
1243	 * to indicate that the kernel should not run multiuser in secure
1244	 * mode, and the run script has not set a higher level of security
1245	 * than level 1, then put the kernel into secure mode.
1246	 */
1247	if (getsecuritylevel() == 0)
1248		setsecuritylevel(1);
1249
1250	for (sp = sessions; sp; sp = sp->se_next) {
1251		if (sp->se_process)
1252			continue;
1253		if ((pid = start_getty(sp)) == -1) {
1254			/* serious trouble */
1255			requested_transition = clean_ttys;
1256			break;
1257		}
1258		sp->se_process = pid;
1259		sp->se_started = time((time_t *) 0);
1260		add_session(sp);
1261	}
1262
1263	while (!requested_transition)
1264		if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1265			collect_child(pid);
1266
1267	return (state_func_t) requested_transition;
1268}
1269
1270/*
1271 * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1272 */
1273state_func_t
1274clean_ttys(void)
1275{
1276	session_t *sp, *sprev;
1277	struct ttyent *typ;
1278	int session_index = 0;
1279	int devlen;
1280	char *old_getty, *old_window, *old_type;
1281
1282	/*
1283	 * mark all sessions for death, (!SE_PRESENT)
1284	 * as we find or create new ones they'll be marked as keepers,
1285	 * we'll later nuke all the ones not found in /etc/ttys
1286	 */
1287	for (sp = sessions; sp != NULL; sp = sp->se_next)
1288		sp->se_flags &= ~SE_PRESENT;
1289
1290	devlen = sizeof(_PATH_DEV) - 1;
1291	while ((typ = getttyent()) != NULL) {
1292		++session_index;
1293
1294		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1295			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1296				break;
1297
1298		if (sp) {
1299			/* we want this one to live */
1300			sp->se_flags |= SE_PRESENT;
1301			if (sp->se_index != session_index) {
1302				warning("port %s changed utmp index from %d to %d",
1303				       sp->se_device, sp->se_index,
1304				       session_index);
1305				sp->se_index = session_index;
1306			}
1307			if ((typ->ty_status & TTY_ON) == 0 ||
1308			    typ->ty_getty == 0) {
1309				sp->se_flags |= SE_SHUTDOWN;
1310				kill(sp->se_process, SIGHUP);
1311				continue;
1312			}
1313			sp->se_flags &= ~SE_SHUTDOWN;
1314			old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1315			old_window = sp->se_window ? strdup(sp->se_window) : 0;
1316			old_type = sp->se_type ? strdup(sp->se_type) : 0;
1317			if (setupargv(sp, typ) == 0) {
1318				warning("can't parse getty for port %s",
1319					sp->se_device);
1320				sp->se_flags |= SE_SHUTDOWN;
1321				kill(sp->se_process, SIGHUP);
1322			}
1323			else if (   !old_getty
1324				 || (!old_type && sp->se_type)
1325				 || (old_type && !sp->se_type)
1326				 || (!old_window && sp->se_window)
1327				 || (old_window && !sp->se_window)
1328				 || (strcmp(old_getty, sp->se_getty) != 0)
1329				 || (old_window && strcmp(old_window, sp->se_window) != 0)
1330				 || (old_type && strcmp(old_type, sp->se_type) != 0)
1331				) {
1332				/* Don't set SE_SHUTDOWN here */
1333				sp->se_nspace = 0;
1334				sp->se_started = 0;
1335				kill(sp->se_process, SIGHUP);
1336			}
1337			if (old_getty)
1338				free(old_getty);
1339			if (old_window)
1340				free(old_window);
1341			if (old_type)
1342				free(old_type);
1343			continue;
1344		}
1345
1346		new_session(sprev, session_index, typ);
1347	}
1348
1349	endttyent();
1350
1351	/*
1352	 * sweep through and kill all deleted sessions
1353	 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1354	 */
1355	for (sp = sessions; sp != NULL; sp = sp->se_next) {
1356		if ((sp->se_flags & SE_PRESENT) == 0) {
1357			sp->se_flags |= SE_SHUTDOWN;
1358			kill(sp->se_process, SIGHUP);
1359		}
1360	}
1361
1362	return (state_func_t) multi_user;
1363}
1364
1365/*
1366 * Block further logins.
1367 */
1368state_func_t
1369catatonia(void)
1370{
1371	session_t *sp;
1372
1373	for (sp = sessions; sp; sp = sp->se_next)
1374		sp->se_flags |= SE_SHUTDOWN;
1375
1376	return (state_func_t) multi_user;
1377}
1378
1379/*
1380 * Note SIGALRM.
1381 */
1382void
1383alrm_handler(int sig)
1384{
1385	(void)sig;
1386	clang = 1;
1387}
1388
1389/*
1390 * Bring the system down to single user.
1391 */
1392state_func_t
1393death(void)
1394{
1395	session_t *sp;
1396	int i;
1397	pid_t pid;
1398	static const int death_sigs[2] = { SIGTERM, SIGKILL };
1399
1400	/* NB: should send a message to the session logger to avoid blocking. */
1401	logwtmp("~", "shutdown", "");
1402
1403	for (sp = sessions; sp; sp = sp->se_next) {
1404		sp->se_flags |= SE_SHUTDOWN;
1405		kill(sp->se_process, SIGHUP);
1406	}
1407
1408	/* Try to run the rc.shutdown script within a period of time */
1409	(void) runshutdown();
1410
1411	for (i = 0; i < 2; ++i) {
1412		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1413			return (state_func_t) single_user;
1414
1415		clang = 0;
1416		alarm(DEATH_WATCH);
1417		do
1418			if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1419				collect_child(pid);
1420		while (clang == 0 && errno != ECHILD);
1421
1422		if (errno == ECHILD)
1423			return (state_func_t) single_user;
1424	}
1425
1426	warning("some processes would not die; ps axl advised");
1427
1428	return (state_func_t) single_user;
1429}
1430
1431/*
1432 * Run the system shutdown script.
1433 *
1434 * Exit codes:      XXX I should document more
1435 * -2       shutdown script terminated abnormally
1436 * -1       fatal error - can't run script
1437 * 0        good.
1438 * >0       some error (exit code)
1439 */
1440int
1441runshutdown(void)
1442{
1443	pid_t pid, wpid;
1444	int status;
1445	int shutdowntimeout;
1446	size_t len;
1447	char *argv[4];
1448	struct sigaction sa;
1449	struct stat sb;
1450
1451	/*
1452	 * rc.shutdown is optional, so to prevent any unnecessary
1453	 * complaints from the shell we simply don't run it if the
1454	 * file does not exist. If the stat() here fails for other
1455	 * reasons, we'll let the shell complain.
1456	 */
1457	if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1458		return 0;
1459
1460	if ((pid = fork()) == 0) {
1461		int	fd;
1462
1463		/* Assume that init already grab console as ctty before */
1464
1465		sigemptyset(&sa.sa_mask);
1466		sa.sa_flags = 0;
1467		sa.sa_handler = SIG_IGN;
1468		(void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1469		(void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1470
1471		if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1472		    warning("can't open %s: %m", _PATH_CONSOLE);
1473		else {
1474		    (void) dup2(fd, 0);
1475		    (void) dup2(fd, 1);
1476		    (void) dup2(fd, 2);
1477		    if (fd > 2)
1478			close(fd);
1479		}
1480
1481		/*
1482		 * Run the shutdown script.
1483		 */
1484		argv[0] = "sh";
1485		argv[1] = _PATH_RUNDOWN;
1486		if (Reboot)
1487			argv[2] = "reboot";
1488		else
1489			argv[2] = "single";
1490		argv[3] = 0;
1491
1492		sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1493
1494#ifdef LOGIN_CAP
1495		setprocresources(RESOURCE_RC);
1496#endif
1497		execv(_PATH_BSHELL, argv);
1498		warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1499		_exit(1);	/* force single user mode */
1500	}
1501
1502	if (pid == -1) {
1503		emergency("can't fork for %s on %s: %m",
1504			_PATH_BSHELL, _PATH_RUNDOWN);
1505		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1506			continue;
1507		sleep(STALL_TIMEOUT);
1508		return -1;
1509	}
1510
1511	len = sizeof(shutdowntimeout);
1512	if (sysctlbyname("kern.shutdown_timeout",
1513			 &shutdowntimeout,
1514			 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1515	    shutdowntimeout = DEATH_SCRIPT;
1516	alarm(shutdowntimeout);
1517	clang = 0;
1518	/*
1519	 * Copied from single_user().  This is a bit paranoid.
1520	 * Use the same ALRM handler.
1521	 */
1522	do {
1523		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1524			collect_child(wpid);
1525		if (clang == 1) {
1526			/* we were waiting for the sub-shell */
1527			kill(wpid, SIGTERM);
1528			warning("timeout expired for %s on %s: %m; going to single user mode",
1529				_PATH_BSHELL, _PATH_RUNDOWN);
1530			return -1;
1531		}
1532		if (wpid == -1) {
1533			if (errno == EINTR)
1534				continue;
1535			warning("wait for %s on %s failed: %m; going to single user mode",
1536				_PATH_BSHELL, _PATH_RUNDOWN);
1537			return -1;
1538		}
1539		if (wpid == pid && WIFSTOPPED(status)) {
1540			warning("init: %s on %s stopped, restarting\n",
1541				_PATH_BSHELL, _PATH_RUNDOWN);
1542			kill(pid, SIGCONT);
1543			wpid = -1;
1544		}
1545	} while (wpid != pid && !clang);
1546
1547	/* Turn off the alarm */
1548	alarm(0);
1549
1550	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1551	    requested_transition == catatonia) {
1552		/*
1553		 * /etc/rc.shutdown executed /sbin/reboot;
1554		 * wait for the end quietly
1555		 */
1556		sigset_t s;
1557
1558		sigfillset(&s);
1559		for (;;)
1560			sigsuspend(&s);
1561	}
1562
1563	if (!WIFEXITED(status)) {
1564		warning("%s on %s terminated abnormally, going to single user mode",
1565			_PATH_BSHELL, _PATH_RUNDOWN);
1566		return -2;
1567	}
1568
1569	if ((status = WEXITSTATUS(status)) != 0)
1570		warning("%s returned status %d", _PATH_RUNDOWN, status);
1571
1572	return status;
1573}
1574
1575char *
1576strk (char *p)
1577{
1578    static char *t;
1579    char *q;
1580    int c;
1581
1582    if (p)
1583	t = p;
1584    if (!t)
1585	return 0;
1586
1587    c = *t;
1588    while (c == ' ' || c == '\t' )
1589	c = *++t;
1590    if (!c) {
1591	t = 0;
1592	return 0;
1593    }
1594    q = t;
1595    if (c == '\'') {
1596	c = *++t;
1597	q = t;
1598	while (c && c != '\'')
1599	    c = *++t;
1600	if (!c)  /* unterminated string */
1601	    q = t = 0;
1602	else
1603	    *t++ = 0;
1604    } else {
1605	while (c && c != ' ' && c != '\t' )
1606	    c = *++t;
1607	*t++ = 0;
1608	if (!c)
1609	    t = 0;
1610    }
1611    return q;
1612}
1613
1614#ifdef LOGIN_CAP
1615void
1616setprocresources(const char *cname)
1617{
1618	login_cap_t *lc;
1619	if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1620		setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1621		login_close(lc);
1622	}
1623}
1624#endif
1625