init.c revision 1.56
1/*	$OpenBSD: init.c,v 1.56 2015/12/10 17:27:00 mmcc Exp $	*/
2/*	$NetBSD: init.c,v 1.22 1996/05/15 23:29:33 jtc Exp $	*/
3
4/*-
5 * Copyright (c) 1991, 1993
6 *	The Regents of the University of California.  All rights reserved.
7 *
8 * This code is derived from software contributed to Berkeley by
9 * Donn Seeley at Berkeley Software Design, Inc.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 *    notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 *    notice, this list of conditions and the following disclaimer in the
18 *    documentation and/or other materials provided with the distribution.
19 * 3. Neither the name of the University nor the names of its contributors
20 *    may be used to endorse or promote products derived from this software
21 *    without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * SUCH DAMAGE.
34 */
35
36#include <sys/types.h>
37#include <sys/sysctl.h>
38#include <sys/wait.h>
39#include <sys/reboot.h>
40#include <machine/cpu.h>
41
42#include <db.h>
43#include <err.h>
44#include <errno.h>
45#include <fcntl.h>
46#include <signal.h>
47#include <stdarg.h>
48#include <stdio.h>
49#include <stdlib.h>
50#include <string.h>
51#include <syslog.h>
52#include <time.h>
53#include <ttyent.h>
54#include <unistd.h>
55#include <util.h>
56
57#ifdef SECURE
58#include <pwd.h>
59#endif
60
61#ifdef LOGIN_CAP
62#include <login_cap.h>
63#endif
64
65#include "pathnames.h"
66
67/*
68 * Sleep times; used to prevent thrashing.
69 */
70#define	GETTY_SPACING		 5	/* N secs minimum getty spacing */
71#define	GETTY_SLEEP		30	/* sleep N secs after spacing problem */
72#define	WINDOW_WAIT		 3	/* wait N secs after starting window */
73#define	STALL_TIMEOUT		30	/* wait N secs after warning */
74#define	DEATH_WATCH		10	/* wait N secs for procs to die */
75
76/*
77 * User-based resource limits.
78 */
79#define RESOURCE_RC		"daemon"
80#define RESOURCE_WINDOW		"default"
81#define RESOURCE_GETTY		"default"
82
83#ifndef DEFAULT_STATE
84#define DEFAULT_STATE		runcom
85#endif
86
87void handle(sig_t, ...);
88void delset(sigset_t *, ...);
89
90void stall(char *, ...);
91void warning(char *, ...);
92void emergency(char *, ...);
93void disaster(int);
94void badsys(int);
95
96typedef enum {
97	invalid_state,
98	single_user,
99	runcom,
100	read_ttys,
101	multi_user,
102	clean_ttys,
103	catatonia,
104	death,
105	do_reboot,
106	hard_death,
107	nice_death
108} state_t;
109typedef state_t (*state_func_t)(void);
110
111state_t f_single_user(void);
112state_t f_runcom(void);
113state_t f_read_ttys(void);
114state_t f_multi_user(void);
115state_t f_clean_ttys(void);
116state_t f_catatonia(void);
117state_t f_death(void);
118state_t f_do_reboot(void);
119state_t f_hard_death(void);
120state_t f_nice_death(void);
121
122state_func_t state_funcs[] = {
123	NULL,
124	f_single_user,
125	f_runcom,
126	f_read_ttys,
127	f_multi_user,
128	f_clean_ttys,
129	f_catatonia,
130	f_death,
131	f_do_reboot,
132	f_hard_death,
133	f_nice_death
134};
135
136enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
137
138void transition(state_t);
139volatile sig_atomic_t requested_transition = DEFAULT_STATE;
140
141void setctty(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#define	SE_DEVEXISTS	0x4		/* open does not result in ENODEV */
151	char	*se_device;		/* filename of port */
152	char	*se_getty;		/* what to run on that port */
153	char	**se_getty_argv;	/* pre-parsed argument array */
154	char	*se_window;		/* window system (started only once) */
155	char	**se_window_argv;	/* pre-parsed argument array */
156	struct	init_session *se_prev;
157	struct	init_session *se_next;
158} session_t;
159
160void free_session(session_t *);
161session_t *new_session(session_t *, int, struct ttyent *);
162session_t *sessions;
163
164char **construct_argv(char *);
165void start_window_system(session_t *);
166void collect_child(pid_t);
167pid_t start_getty(session_t *);
168void transition_handler(int);
169void alrm_handler(int);
170void setsecuritylevel(int);
171int getsecuritylevel(void);
172int setupargv(session_t *, struct ttyent *);
173int clang;
174
175#ifdef LOGIN_CAP
176void setprocresources(char *);
177#else
178#define setprocresources(p)
179#endif
180
181void clear_session_logs(session_t *);
182
183int start_session_db(void);
184void add_session(session_t *);
185void del_session(session_t *);
186session_t *find_session(pid_t);
187DB *session_db;
188
189/*
190 * The mother of all processes.
191 */
192int
193main(int argc, char *argv[])
194{
195	int c;
196	struct sigaction sa;
197	sigset_t mask;
198
199	/* Dispose of random users. */
200	if (getuid() != 0) {
201		(void)fprintf(stderr, "init: %s\n", strerror(EPERM));
202		exit (1);
203	}
204
205	/* System V users like to reexec init. */
206	if (getpid() != 1) {
207		(void)fprintf(stderr, "init: already running\n");
208		exit (1);
209	}
210
211	/*
212	 * Note that this does NOT open a file...
213	 * Does 'init' deserve its own facility number?
214	 */
215	openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
216
217	/*
218	 * Create an initial session.
219	 */
220	if (setsid() < 0)
221		warning("initial setsid() failed: %m");
222
223	/*
224	 * Establish an initial user so that programs running
225	 * single user do not freak out and die (like passwd).
226	 */
227	if (setlogin("root") < 0)
228		warning("setlogin() failed: %m");
229
230	/*
231	 * This code assumes that we always get arguments through flags,
232	 * never through bits set in some random machine register.
233	 */
234	while ((c = getopt(argc, argv, "sf")) != -1)
235		switch (c) {
236		case 's':
237			requested_transition = single_user;
238			break;
239		case 'f':
240			runcom_mode = FASTBOOT;
241			break;
242		default:
243			warning("unrecognized flag '-%c'", c);
244			break;
245		}
246
247	if (optind != argc)
248		warning("ignoring excess arguments");
249
250	/*
251	 * We catch or block signals rather than ignore them,
252	 * so that they get reset on exec.
253	 */
254	handle(badsys, SIGSYS, 0);
255	handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
256	    SIGBUS, SIGXCPU, SIGXFSZ, 0);
257	handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
258            SIGUSR1, SIGUSR2, 0);
259	handle(alrm_handler, SIGALRM, 0);
260	sigfillset(&mask);
261	delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
262	    SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGUSR1, SIGUSR2,
263	    SIGTSTP, SIGALRM, 0);
264	sigprocmask(SIG_SETMASK, &mask, NULL);
265	memset(&sa, 0, sizeof sa);
266	sigemptyset(&sa.sa_mask);
267	sa.sa_flags = 0;
268	sa.sa_handler = SIG_IGN;
269	(void) sigaction(SIGTTIN, &sa, NULL);
270	(void) sigaction(SIGTTOU, &sa, NULL);
271
272	/*
273	 * Paranoia.
274	 */
275	close(STDIN_FILENO);
276	close(STDOUT_FILENO);
277	close(STDERR_FILENO);
278
279	/*
280	 * Start the state machine.
281	 */
282	transition(requested_transition);
283
284	/*
285	 * Should never reach here.
286	 */
287	exit(1);
288}
289
290/*
291 * Associate a function with a signal handler.
292 */
293void
294handle(sig_t handler, ...)
295{
296	int sig;
297	struct sigaction sa;
298	sigset_t mask_everything;
299	va_list ap;
300
301	va_start(ap, handler);
302
303	memset(&sa, 0, sizeof sa);
304	sa.sa_handler = handler;
305	sigfillset(&mask_everything);
306
307	while ((sig = va_arg(ap, int))) {
308		sa.sa_mask = mask_everything;
309		/* XXX SA_RESTART? */
310		sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
311		sigaction(sig, &sa, NULL);
312	}
313	va_end(ap);
314}
315
316/*
317 * Delete a set of signals from a mask.
318 */
319void
320delset(sigset_t *maskp, ...)
321{
322	int sig;
323	va_list ap;
324
325	va_start(ap, maskp);
326	while ((sig = va_arg(ap, int)))
327		sigdelset(maskp, sig);
328	va_end(ap);
329}
330
331/*
332 * Log a message and sleep for a while (to give someone an opportunity
333 * to read it and to save log or hardcopy output if the problem is chronic).
334 * NB: should send a message to the session logger to avoid blocking.
335 */
336void
337stall(char *message, ...)
338{
339	va_list ap;
340
341	va_start(ap, message);
342	vsyslog(LOG_ALERT, message, ap);
343	va_end(ap);
344	closelog();
345	sleep(STALL_TIMEOUT);
346}
347
348/*
349 * Like stall(), but doesn't sleep.
350 * If cpp had variadic macros, the two functions could be #defines for another.
351 * NB: should send a message to the session logger to avoid blocking.
352 */
353void
354warning(char *message, ...)
355{
356	va_list ap;
357
358	va_start(ap, message);
359	vsyslog(LOG_ALERT, message, ap);
360	va_end(ap);
361	closelog();
362}
363
364/*
365 * Log an emergency message.
366 * NB: should send a message to the session logger to avoid blocking.
367 */
368void
369emergency(char *message, ...)
370{
371	struct syslog_data sdata = SYSLOG_DATA_INIT;
372	va_list ap;
373
374	va_start(ap, message);
375	vsyslog_r(LOG_EMERG, &sdata, message, ap);
376	va_end(ap);
377}
378
379/*
380 * Catch a SIGSYS signal.
381 *
382 * These may arise if a system does not support sysctl.
383 * We tolerate up to 25 of these, then throw in the towel.
384 */
385void
386badsys(int sig)
387{
388	static int badcount = 0;
389
390	if (badcount++ < 25)
391		return;
392	disaster(sig);
393}
394
395/*
396 * Catch an unexpected signal.
397 */
398void
399disaster(int sig)
400{
401	emergency("fatal signal: %s", strsignal(sig));
402
403	sleep(STALL_TIMEOUT);
404	_exit(sig);		/* reboot */
405}
406
407/*
408 * Get the security level of the kernel.
409 */
410int
411getsecuritylevel(void)
412{
413#ifdef KERN_SECURELVL
414	int name[2], curlevel;
415	size_t len;
416
417	name[0] = CTL_KERN;
418	name[1] = KERN_SECURELVL;
419	len = sizeof curlevel;
420	if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
421		emergency("cannot get kernel security level: %s",
422		    strerror(errno));
423		return (-1);
424	}
425	return (curlevel);
426#else
427	return (-1);
428#endif
429}
430
431/*
432 * Set the security level of the kernel.
433 */
434void
435setsecuritylevel(int newlevel)
436{
437#ifdef KERN_SECURELVL
438	int name[2], curlevel;
439
440	curlevel = getsecuritylevel();
441	if (newlevel == curlevel)
442		return;
443	name[0] = CTL_KERN;
444	name[1] = KERN_SECURELVL;
445	if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
446		emergency(
447		    "cannot change kernel security level from %d to %d: %s",
448		    curlevel, newlevel, strerror(errno));
449		return;
450	}
451#ifdef SECURE
452	warning("kernel security level changed from %d to %d",
453	    curlevel, newlevel);
454#endif
455#endif
456}
457
458/*
459 * Change states in the finite state machine.
460 * The initial state is passed as an argument.
461 */
462void
463transition(state_t s)
464{
465	for (;;)
466		s = (*state_funcs[s])();
467}
468
469/*
470 * Close out the accounting files for a login session.
471 * NB: should send a message to the session logger to avoid blocking.
472 */
473void
474clear_session_logs(session_t *sp)
475{
476	char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
477
478	if (logout(line))
479		logwtmp(line, "", "");
480}
481
482/*
483 * Start a session and allocate a controlling terminal.
484 * Only called by children of init after forking.
485 */
486void
487setctty(char *name)
488{
489	int fd;
490
491	(void) revoke(name);
492	sleep(2);			/* leave DTR low */
493	if ((fd = open(name, O_RDWR)) == -1) {
494		stall("can't open %s: %m", name);
495		_exit(1);
496	}
497	if (login_tty(fd) == -1) {
498		stall("can't get %s for controlling terminal: %m", name);
499		_exit(1);
500	}
501}
502
503/*
504 * Bring the system up single user.
505 */
506state_t
507f_single_user(void)
508{
509	pid_t pid, wpid;
510	int status;
511	sigset_t mask;
512	char shell[PATH_MAX];		/* Allocate space here */
513	char name[PATH_MAX];		/* Name (argv[0]) of shell */
514	char *argv[2];
515#ifdef SECURE
516	struct ttyent *typ;
517	struct passwd *pp;
518	static const char banner[] =
519		"Enter root password, or ^D to go multi-user\n";
520	char *clear, *password;
521#endif
522
523	/* Init shell and name */
524	strlcpy(shell, _PATH_BSHELL, sizeof shell);
525	strlcpy(name, "-sh", sizeof name);
526
527	/*
528	 * If the kernel is in secure mode, downgrade it to insecure mode.
529	 */
530	if (getsecuritylevel() > 0)
531		setsecuritylevel(0);
532
533	if ((pid = fork()) == 0) {
534		/*
535		 * Start the single user session.
536		 */
537		setctty(_PATH_CONSOLE);
538
539#ifdef SECURE
540		/*
541		 * Check the root password.
542		 * We don't care if the console is 'on' by default;
543		 * it's the only tty that can be 'off' and 'secure'.
544		 */
545		typ = getttynam("console");
546		pp = getpwnam_shadow("root");
547		if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp &&
548		    *pp->pw_passwd) {
549			write(STDERR_FILENO, banner, sizeof banner - 1);
550			for (;;) {
551				int ok = 0;
552				clear = getpass("Password:");
553				if (clear == NULL || *clear == '\0')
554					_exit(0);
555				if (crypt_checkpass(clear, pp->pw_passwd) == 0)
556					ok = 1;
557				memset(clear, 0, strlen(clear));
558				if (ok)
559					break;
560				warning("single-user login failed\n");
561			}
562		}
563		endttyent();
564		endpwent();
565#endif /* SECURE */
566
567#ifdef DEBUGSHELL
568		{
569			char altshell[128], *cp = altshell;
570			int num;
571
572#define	SHREQUEST \
573	"Enter pathname of shell or RETURN for sh: "
574
575			(void)write(STDERR_FILENO,
576			    SHREQUEST, sizeof(SHREQUEST) - 1);
577			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
578			    num != 0 && *cp != '\n' && cp < &altshell[127])
579				cp++;
580			*cp = '\0';
581
582			/* Copy in alternate shell */
583			if (altshell[0] != '\0'){
584				char *p;
585
586				/* Binary to exec */
587				strlcpy(shell, altshell, sizeof shell);
588
589				/* argv[0] */
590				p = strrchr(altshell, '/');
591				if(p == NULL) p = altshell;
592				else p++;
593
594				name[0] = '-';
595				strlcpy(&name[1], p, sizeof name -1);
596			}
597		}
598#endif /* DEBUGSHELL */
599
600		/*
601		 * Unblock signals.
602		 * We catch all the interesting ones,
603		 * and those are reset to SIG_DFL on exec.
604		 */
605		sigemptyset(&mask);
606		sigprocmask(SIG_SETMASK, &mask, NULL);
607
608		/*
609		 * Fire off a shell.
610		 * If the default one doesn't work, try the Bourne shell.
611		 */
612		argv[0] = name;
613		argv[1] = NULL;
614		setenv("PATH", _PATH_STDPATH, 1);
615		execv(shell, argv);
616		emergency("can't exec %s for single user: %m", shell);
617
618		argv[0] = "-sh";
619		argv[1] = NULL;
620		execv(_PATH_BSHELL, argv);
621		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
622		sleep(STALL_TIMEOUT);
623		_exit(1);
624	}
625
626	if (pid == -1) {
627		/*
628		 * We are seriously hosed.  Do our best.
629		 */
630		emergency("can't fork single-user shell, trying again");
631		while (waitpid(-1, NULL, WNOHANG) > 0)
632			continue;
633		return single_user;
634	}
635
636	requested_transition = 0;
637	do {
638		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
639			collect_child(wpid);
640		if (wpid == -1) {
641			if (errno == EINTR)
642				continue;
643			warning("wait for single-user shell failed: %m; restarting");
644			return single_user;
645		}
646		if (wpid == pid && WIFSTOPPED(status)) {
647			warning("init: shell stopped, restarting\n");
648			kill(pid, SIGCONT);
649			wpid = -1;
650		}
651	} while (wpid != pid && !requested_transition);
652
653	if (requested_transition)
654		return requested_transition;
655
656	if (!WIFEXITED(status)) {
657		if (WTERMSIG(status) == SIGKILL) {
658			/*
659			 *  reboot(8) killed shell?
660			 */
661			warning("single user shell terminated.");
662			sleep(STALL_TIMEOUT);
663			_exit(0);
664		} else {
665			warning("single user shell terminated, restarting");
666			return single_user;
667		}
668	}
669
670	runcom_mode = FASTBOOT;
671	return runcom;
672}
673
674/*
675 * Run the system startup script.
676 */
677state_t
678f_runcom(void)
679{
680	pid_t pid, wpid;
681	int status;
682	char *argv[4];
683	struct sigaction sa;
684
685	if ((pid = fork()) == 0) {
686		memset(&sa, 0, sizeof sa);
687		sigemptyset(&sa.sa_mask);
688		sa.sa_flags = 0;
689		sa.sa_handler = SIG_IGN;
690		(void) sigaction(SIGTSTP, &sa, NULL);
691		(void) sigaction(SIGHUP, &sa, NULL);
692
693		setctty(_PATH_CONSOLE);
694
695		argv[0] = "sh";
696		argv[1] = _PATH_RUNCOM;
697		argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
698		argv[3] = 0;
699
700		sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
701
702		setprocresources(RESOURCE_RC);
703
704		execv(_PATH_BSHELL, argv);
705		stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
706		_exit(1);	/* force single user mode */
707	}
708
709	if (pid == -1) {
710		emergency("can't fork for %s on %s: %m",
711			_PATH_BSHELL, _PATH_RUNCOM);
712		while (waitpid(-1, NULL, WNOHANG) > 0)
713			continue;
714		sleep(STALL_TIMEOUT);
715		return single_user;
716	}
717
718	/*
719	 * Copied from single_user().  This is a bit paranoid.
720	 */
721	do {
722		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
723			collect_child(wpid);
724		if (wpid == -1) {
725			if (errno == EINTR)
726				continue;
727			warning("wait for %s on %s failed: %m; going to single user mode",
728			    _PATH_BSHELL, _PATH_RUNCOM);
729			return single_user;
730		}
731		if (wpid == pid && WIFSTOPPED(status)) {
732			warning("init: %s on %s stopped, restarting\n",
733			    _PATH_BSHELL, _PATH_RUNCOM);
734			kill(pid, SIGCONT);
735			wpid = -1;
736		}
737	} while (wpid != pid);
738
739	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
740	    requested_transition == catatonia) {
741		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
742		sigset_t s;
743
744		sigfillset(&s);
745		for (;;)
746			sigsuspend(&s);
747	}
748
749	if (!WIFEXITED(status)) {
750		warning("%s on %s terminated abnormally, going to single user mode",
751		    _PATH_BSHELL, _PATH_RUNCOM);
752		return single_user;
753	}
754
755	if (WEXITSTATUS(status))
756		return single_user;
757
758	runcom_mode = AUTOBOOT;		/* the default */
759	/* NB: should send a message to the session logger to avoid blocking. */
760	logwtmp("~", "reboot", "");
761	return read_ttys;
762}
763
764/*
765 * Open the session database.
766 *
767 * NB: We could pass in the size here; is it necessary?
768 */
769int
770start_session_db(void)
771{
772	if (session_db && (*session_db->close)(session_db))
773		emergency("session database close: %s", strerror(errno));
774	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
775		emergency("session database open: %s", strerror(errno));
776		return (1);
777	}
778	return (0);
779}
780
781/*
782 * Add a new login session.
783 */
784void
785add_session(session_t *sp)
786{
787	DBT key;
788	DBT data;
789
790	key.data = &sp->se_process;
791	key.size = sizeof sp->se_process;
792	data.data = &sp;
793	data.size = sizeof sp;
794
795	if ((*session_db->put)(session_db, &key, &data, 0))
796		emergency("insert %d: %s", sp->se_process, strerror(errno));
797}
798
799/*
800 * Delete an old login session.
801 */
802void
803del_session(session_t *sp)
804{
805	DBT key;
806
807	key.data = &sp->se_process;
808	key.size = sizeof sp->se_process;
809
810	if ((*session_db->del)(session_db, &key, 0))
811		emergency("delete %d: %s", sp->se_process, strerror(errno));
812}
813
814/*
815 * Look up a login session by pid.
816 */
817session_t *
818find_session(pid_t pid)
819{
820	DBT key;
821	DBT data;
822	session_t *ret;
823
824	key.data = &pid;
825	key.size = sizeof pid;
826	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
827		return (0);
828	memcpy(&ret, data.data, sizeof(ret));
829	return (ret);
830}
831
832/*
833 * Construct an argument vector from a command line.
834 */
835char **
836construct_argv(char *command)
837{
838	int argc = 0;
839	char **argv = calloc((strlen(command) + 1) / 2 + 1, sizeof (char *));
840	static const char separators[] = " \t";
841
842	if (argv == NULL)
843		return (0);
844
845	if ((argv[argc++] = strtok(command, separators)) == 0) {
846		free(argv);
847		return (0);
848	}
849	while ((argv[argc++] = strtok(NULL, separators)))
850		continue;
851	return (argv);
852}
853
854/*
855 * Deallocate a session descriptor.
856 */
857void
858free_session(session_t *sp)
859{
860	free(sp->se_device);
861	if (sp->se_getty) {
862		free(sp->se_getty);
863		free(sp->se_getty_argv);
864	}
865	if (sp->se_window) {
866		free(sp->se_window);
867		free(sp->se_window_argv);
868	}
869	free(sp);
870}
871
872/*
873 * Allocate a new session descriptor.
874 */
875session_t *
876new_session(session_t *sprev, int session_index, struct ttyent *typ)
877{
878	session_t *sp;
879
880	if ((typ->ty_status & TTY_ON) == 0 ||
881	    typ->ty_name == 0 ||
882	    typ->ty_getty == 0)
883		return (0);
884
885	sp = calloc(1, sizeof (session_t));
886	if (sp == NULL)
887		err(1, "calloc");
888
889	sp->se_flags = SE_PRESENT;
890	sp->se_index = session_index;
891
892	if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) == -1)
893		err(1, "asprintf");
894
895	if (setupargv(sp, typ) == 0) {
896		free_session(sp);
897		return (0);
898	}
899
900	sp->se_next = 0;
901	if (sprev == 0) {
902		sessions = sp;
903		sp->se_prev = 0;
904	} else {
905		sprev->se_next = sp;
906		sp->se_prev = sprev;
907	}
908
909	return (sp);
910}
911
912/*
913 * Calculate getty and if useful window argv vectors.
914 */
915int
916setupargv(session_t *sp, struct ttyent *typ)
917{
918	if (sp->se_getty) {
919		free(sp->se_getty);
920		free(sp->se_getty_argv);
921	}
922	if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) == -1)
923		err(1, "asprintf");
924	sp->se_getty_argv = construct_argv(sp->se_getty);
925	if (sp->se_getty_argv == 0) {
926		warning("can't parse getty for port %s", sp->se_device);
927		free(sp->se_getty);
928		sp->se_getty = 0;
929		return (0);
930	}
931	if (typ->ty_window) {
932		free(sp->se_window);
933		sp->se_window = strdup(typ->ty_window);
934		if (sp->se_window == NULL) {
935			warning("can't allocate window");
936			return (0);
937		}
938		sp->se_window_argv = construct_argv(sp->se_window);
939		if (sp->se_window_argv == NULL) {
940			warning("can't parse window for port %s",
941			    sp->se_device);
942			free(sp->se_window);
943			sp->se_window = NULL;
944			return (0);
945		}
946	}
947	return (1);
948}
949
950/*
951 * Walk the list of ttys and create sessions for each active line.
952 */
953state_t
954f_read_ttys(void)
955{
956	int session_index = 0;
957	session_t *sp, *snext;
958	struct ttyent *typ;
959
960	/*
961	 * Destroy any previous session state.
962	 * There shouldn't be any, but just in case...
963	 */
964	for (sp = sessions; sp; sp = snext) {
965		if (sp->se_process)
966			clear_session_logs(sp);
967		snext = sp->se_next;
968		free_session(sp);
969	}
970	sessions = 0;
971	if (start_session_db())
972		return single_user;
973
974	/*
975	 * Allocate a session entry for each active port.
976	 * Note that sp starts at 0.
977	 */
978	while ((typ = getttyent()))
979		if ((snext = new_session(sp, ++session_index, typ)))
980			sp = snext;
981
982	endttyent();
983
984	return multi_user;
985}
986
987/*
988 * Start a window system running.
989 */
990void
991start_window_system(session_t *sp)
992{
993	pid_t pid;
994	sigset_t mask;
995
996	if ((pid = fork()) == -1) {
997		emergency("can't fork for window system on port %s: %m",
998		    sp->se_device);
999		/* hope that getty fails and we can try again */
1000		return;
1001	}
1002
1003	if (pid)
1004		return;
1005
1006	sigemptyset(&mask);
1007	sigprocmask(SIG_SETMASK, &mask, NULL);
1008
1009	if (setsid() < 0)
1010		emergency("setsid failed (window) %m");
1011
1012	setprocresources(RESOURCE_WINDOW);
1013
1014	execv(sp->se_window_argv[0], sp->se_window_argv);
1015	stall("can't exec window system '%s' for port %s: %m",
1016	    sp->se_window_argv[0], sp->se_device);
1017	_exit(1);
1018}
1019
1020/*
1021 * Start a login session running.
1022 * For first open, man-handle tty directly to determine if it
1023 * really exists. It is not efficient to spawn gettys on devices
1024 * that do not exist.
1025 */
1026pid_t
1027start_getty(session_t *sp)
1028{
1029	pid_t pid;
1030	sigset_t mask;
1031	time_t current_time = time(NULL);
1032	int p[2], new = 1;
1033
1034	if (sp->se_flags & SE_DEVEXISTS)
1035		new = 0;
1036
1037	if (new) {
1038		if (pipe(p) == -1)
1039			return (-1);
1040	}
1041
1042	/*
1043	 * fork(), not vfork() -- we can't afford to block.
1044	 */
1045	if ((pid = fork()) == -1) {
1046		emergency("can't fork for getty on port %s: %m", sp->se_device);
1047		return (-1);
1048	}
1049
1050	if (pid) {
1051		if (new) {
1052			char c;
1053
1054			close(p[1]);
1055			if (read(p[0], &c, 1) != 1) {
1056				close(p[0]);
1057				return (-1);
1058			}
1059			close(p[0]);
1060			if (c == '1')
1061				sp->se_flags |= SE_DEVEXISTS;
1062			else
1063				sp->se_flags |= SE_SHUTDOWN;
1064		}
1065		return (pid);
1066	}
1067	if (new) {
1068		int fd;
1069
1070		close(p[0]);
1071		fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0666);
1072		if (fd == -1 && (errno == ENXIO || errno == ENOENT ||
1073		    errno == EISDIR)) {
1074			(void)write(p[1], "0", 1);
1075			close(p[1]);
1076			_exit(1);
1077		}
1078		(void)write(p[1], "1", 1);
1079		close(p[1]);
1080		close(fd);
1081		sleep(1);
1082	}
1083
1084	if (current_time > sp->se_started &&
1085	    current_time - sp->se_started < GETTY_SPACING) {
1086		warning("getty repeating too quickly on port %s, sleeping",
1087		    sp->se_device);
1088		sleep(GETTY_SLEEP);
1089	}
1090
1091	if (sp->se_window) {
1092		start_window_system(sp);
1093		sleep(WINDOW_WAIT);
1094	}
1095
1096	sigemptyset(&mask);
1097	sigprocmask(SIG_SETMASK, &mask, NULL);
1098
1099	setprocresources(RESOURCE_GETTY);
1100
1101	execv(sp->se_getty_argv[0], sp->se_getty_argv);
1102	stall("can't exec getty '%s' for port %s: %m",
1103	    sp->se_getty_argv[0], sp->se_device);
1104	_exit(1);
1105}
1106
1107/*
1108 * Collect exit status for a child.
1109 * If an exiting login, start a new login running.
1110 */
1111void
1112collect_child(pid_t pid)
1113{
1114	session_t *sp, *sprev, *snext;
1115
1116	if (sessions == NULL)
1117		return;
1118
1119	if ((sp = find_session(pid)) == NULL)
1120		return;
1121
1122	clear_session_logs(sp);
1123	login_fbtab(sp->se_device + sizeof(_PATH_DEV) - 1, 0, 0);
1124	del_session(sp);
1125	sp->se_process = 0;
1126
1127	if (sp->se_flags & SE_SHUTDOWN) {
1128		if ((sprev = sp->se_prev))
1129			sprev->se_next = sp->se_next;
1130		else
1131			sessions = sp->se_next;
1132		if ((snext = sp->se_next))
1133			snext->se_prev = sp->se_prev;
1134		free_session(sp);
1135		return;
1136	}
1137
1138	if ((pid = start_getty(sp)) == -1) {
1139		/* serious trouble */
1140		requested_transition = clean_ttys;
1141		return;
1142	}
1143
1144	sp->se_process = pid;
1145	sp->se_started = time(NULL);
1146	add_session(sp);
1147}
1148
1149/*
1150 * Catch a signal and request a state transition.
1151 */
1152void
1153transition_handler(int sig)
1154{
1155
1156	switch (sig) {
1157	case SIGHUP:
1158		requested_transition = clean_ttys;
1159		break;
1160	case SIGINT:
1161		requested_transition = do_reboot;
1162		break;
1163	case SIGTERM:
1164		requested_transition = death;
1165		break;
1166	case SIGUSR1:
1167		requested_transition = nice_death;
1168		break;
1169	case SIGUSR2:
1170		requested_transition = hard_death;
1171		break;
1172	case SIGTSTP:
1173		requested_transition = catatonia;
1174		break;
1175	default:
1176		requested_transition = 0;
1177		break;
1178	}
1179}
1180
1181/*
1182 * Take the system multiuser.
1183 */
1184state_t
1185f_multi_user(void)
1186{
1187	pid_t pid;
1188	session_t *sp;
1189
1190	/*
1191	 * If the administrator has not set the security level to -1
1192	 * to indicate that the kernel should not run multiuser in secure
1193	 * mode, and the run script has not set a higher level of security
1194	 * than level 1, then put the kernel into secure mode.
1195	 */
1196	if (requested_transition != catatonia) {
1197		if (getsecuritylevel() == 0)
1198			setsecuritylevel(1);
1199	}
1200
1201	requested_transition = 0;
1202
1203	for (sp = sessions; sp; sp = sp->se_next) {
1204		if (sp->se_process)
1205			continue;
1206		if ((pid = start_getty(sp)) == -1) {
1207			/* serious trouble */
1208			requested_transition = clean_ttys;
1209			break;
1210		}
1211		sp->se_process = pid;
1212		sp->se_started = time(NULL);
1213		add_session(sp);
1214	}
1215
1216	while (!requested_transition)
1217		if ((pid = waitpid(-1, NULL, 0)) != -1)
1218			collect_child(pid);
1219
1220	return requested_transition;
1221}
1222
1223/*
1224 * This is an n-squared algorithm.  We hope it isn't run often...
1225 */
1226state_t
1227f_clean_ttys(void)
1228{
1229	session_t *sp, *sprev;
1230	struct ttyent *typ;
1231	int session_index = 0;
1232	int devlen;
1233
1234	for (sp = sessions; sp; sp = sp->se_next)
1235		sp->se_flags &= ~SE_PRESENT;
1236
1237	devlen = sizeof(_PATH_DEV) - 1;
1238	while ((typ = getttyent())) {
1239		++session_index;
1240
1241		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1242			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1243				break;
1244
1245		if (sp) {
1246			sp->se_flags |= SE_PRESENT;
1247			if (sp->se_index != session_index) {
1248				warning("port %s changed utmp index from %d to %d",
1249				    sp->se_device, sp->se_index,
1250				    session_index);
1251				sp->se_index = session_index;
1252			}
1253			if ((typ->ty_status & TTY_ON) == 0 ||
1254			    typ->ty_getty == 0) {
1255				sp->se_flags |= SE_SHUTDOWN;
1256				kill(sp->se_process, SIGHUP);
1257				continue;
1258			}
1259			sp->se_flags &= ~SE_SHUTDOWN;
1260			if (setupargv(sp, typ) == 0) {
1261				warning("can't parse getty for port %s",
1262				    sp->se_device);
1263				sp->se_flags |= SE_SHUTDOWN;
1264				kill(sp->se_process, SIGHUP);
1265			}
1266			continue;
1267		}
1268
1269		new_session(sprev, session_index, typ);
1270	}
1271
1272	endttyent();
1273
1274	for (sp = sessions; sp; sp = sp->se_next)
1275		if ((sp->se_flags & SE_PRESENT) == 0) {
1276			sp->se_flags |= SE_SHUTDOWN;
1277			kill(sp->se_process, SIGHUP);
1278		}
1279
1280	return multi_user;
1281}
1282
1283/*
1284 * Block further logins.
1285 */
1286state_t
1287f_catatonia(void)
1288{
1289	session_t *sp;
1290
1291	for (sp = sessions; sp; sp = sp->se_next)
1292		sp->se_flags |= SE_SHUTDOWN;
1293
1294	return multi_user;
1295}
1296
1297/*
1298 * Note SIGALRM.
1299 */
1300void
1301alrm_handler(int sig)
1302{
1303	clang = 1;
1304}
1305
1306int death_howto = RB_HALT;
1307
1308/*
1309 * Reboot the system.
1310 */
1311state_t
1312f_do_reboot(void)
1313{
1314	death_howto = RB_AUTOBOOT;
1315	return nice_death;
1316}
1317
1318/*
1319 * Bring the system down nicely, then we must powerdown because something
1320 * is very wrong.
1321 */
1322state_t
1323f_hard_death(void)
1324{
1325	death_howto |= RB_POWERDOWN;
1326	return nice_death;
1327}
1328
1329/*
1330 * Bring the system down to single user nicely, after run the shutdown script.
1331 */
1332state_t
1333f_nice_death(void)
1334{
1335	session_t *sp;
1336	int i;
1337	pid_t pid;
1338	static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1339	int status;
1340
1341#ifdef CPU_LIDSUSPEND
1342	int lidsuspend_mib[] = {CTL_MACHDEP, CPU_LIDSUSPEND};
1343	int dontsuspend = 0;
1344
1345	if ((death_howto & RB_POWERDOWN) &&
1346	    (sysctl(lidsuspend_mib, 2, NULL, NULL, &dontsuspend,
1347		    sizeof(dontsuspend)) == -1) && (errno != EOPNOTSUPP))
1348			warning("cannot disable lid suspend");
1349#endif
1350
1351	for (sp = sessions; sp; sp = sp->se_next) {
1352		sp->se_flags &= ~SE_PRESENT;
1353		sp->se_flags |= SE_SHUTDOWN;
1354		kill(sp->se_process, SIGHUP);
1355	}
1356
1357	/* terminate the accounting process */
1358	acct(NULL);
1359
1360	/* NB: should send a message to the session logger to avoid blocking. */
1361	logwtmp("~", "shutdown", "");
1362
1363	if (access(_PATH_RUNCOM, R_OK) != -1) {
1364		struct sigaction sa;
1365
1366		switch ((pid = fork())) {
1367		case -1:
1368			break;
1369		case 0:
1370
1371			memset(&sa, 0, sizeof sa);
1372			sigemptyset(&sa.sa_mask);
1373			sa.sa_flags = 0;
1374			sa.sa_handler = SIG_IGN;
1375			(void) sigaction(SIGTSTP, &sa, NULL);
1376			(void) sigaction(SIGHUP, &sa, NULL);
1377
1378			setctty(_PATH_CONSOLE);
1379
1380			sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1381
1382			execl(_PATH_BSHELL, "sh", _PATH_RUNCOM, "shutdown",
1383			    (char *)NULL);
1384			stall("can't exec %s for %s %s: %m", _PATH_BSHELL,
1385			    _PATH_RUNCOM, "shutdown");
1386			_exit(1);
1387		default:
1388			waitpid(pid, &status, 0);
1389			if (WIFEXITED(status) && WEXITSTATUS(status) == 2)
1390				death_howto |= RB_POWERDOWN;
1391		}
1392	}
1393
1394	for (i = 0; i < 3; ++i) {
1395		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1396			goto die;
1397
1398		clang = 0;
1399		alarm(DEATH_WATCH);
1400		do {
1401			if ((pid = waitpid(-1, NULL, 0)) != -1)
1402				collect_child(pid);
1403		} while (clang == 0 && errno != ECHILD);
1404
1405		if (errno == ECHILD)
1406			goto die;
1407	}
1408
1409	warning("some processes would not die; ps axl advised");
1410
1411die:
1412	reboot(death_howto);
1413
1414	/* ... and if that fails.. oh well */
1415	return single_user;
1416}
1417
1418/*
1419 * Bring the system down to single user.
1420 */
1421state_t
1422f_death(void)
1423{
1424	session_t *sp;
1425	int i;
1426	pid_t pid;
1427	static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1428
1429	/* terminate the accounting process */
1430	acct(NULL);
1431
1432	for (sp = sessions; sp; sp = sp->se_next)
1433		sp->se_flags |= SE_SHUTDOWN;
1434
1435	/* NB: should send a message to the session logger to avoid blocking. */
1436	logwtmp("~", "shutdown", "");
1437
1438	for (i = 0; i < 3; ++i) {
1439		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1440			return single_user;
1441
1442		clang = 0;
1443		alarm(DEATH_WATCH);
1444		do {
1445			if ((pid = waitpid(-1, NULL, 0)) != -1)
1446				collect_child(pid);
1447		} while (clang == 0 && errno != ECHILD);
1448
1449		if (errno == ECHILD)
1450			return single_user;
1451	}
1452
1453	warning("some processes would not die; ps axl advised");
1454
1455	return single_user;
1456}
1457
1458#ifdef LOGIN_CAP
1459void
1460setprocresources(char *class)
1461{
1462	login_cap_t *lc;
1463
1464	if ((lc = login_getclass(class)) != NULL) {
1465		setusercontext(lc, NULL, 0,
1466		    LOGIN_SETPRIORITY|LOGIN_SETRESOURCES|LOGIN_SETUMASK);
1467		login_close(lc);
1468	}
1469}
1470#endif
1471