xref: /freebsd-13-stable/sbin/init/init.c (revision de270f81b246e154640c0d250696c458ff1c0e3b)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Donn Seeley at Berkeley Software Design, Inc.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  */
34 
35 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1991, 1993\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)init.c	8.1 (Berkeley) 7/15/93";
44 #endif
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/mman.h>
50 #include <sys/mount.h>
51 #include <sys/sysctl.h>
52 #include <sys/wait.h>
53 #include <sys/stat.h>
54 #include <sys/uio.h>
55 
56 #include <db.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <kenv.h>
60 #include <libutil.h>
61 #include <paths.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <syslog.h>
67 #include <time.h>
68 #include <ttyent.h>
69 #include <unistd.h>
70 #include <sys/reboot.h>
71 #include <err.h>
72 
73 #include <stdarg.h>
74 
75 #ifdef SECURE
76 #include <pwd.h>
77 #endif
78 
79 #ifdef LOGIN_CAP
80 #include <login_cap.h>
81 #endif
82 
83 #include "mntopts.h"
84 #include "pathnames.h"
85 
86 /*
87  * Sleep times; used to prevent thrashing.
88  */
89 #define	GETTY_SPACING		 5	/* N secs minimum getty spacing */
90 #define	GETTY_SLEEP		30	/* sleep N secs after spacing problem */
91 #define	GETTY_NSPACE		 3	/* max. spacing count to bring reaction */
92 #define	WINDOW_WAIT		 3	/* wait N secs after starting window */
93 #define	STALL_TIMEOUT		30	/* wait N secs after warning */
94 #define	DEATH_WATCH		10	/* wait N secs for procs to die */
95 #define	DEATH_SCRIPT		120	/* wait for 2min for /etc/rc.shutdown */
96 #define	RESOURCE_RC		"daemon"
97 #define	RESOURCE_WINDOW		"default"
98 #define	RESOURCE_GETTY		"default"
99 
100 static void handle(sig_t, ...);
101 static void delset(sigset_t *, ...);
102 
103 static void stall(const char *, ...) __printflike(1, 2);
104 static void warning(const char *, ...) __printflike(1, 2);
105 static void emergency(const char *, ...) __printflike(1, 2);
106 static void disaster(int);
107 static void revoke_ttys(void);
108 static int  runshutdown(void);
109 static char *strk(char *);
110 static void runfinal(void);
111 
112 /*
113  * We really need a recursive typedef...
114  * The following at least guarantees that the return type of (*state_t)()
115  * is sufficiently wide to hold a function pointer.
116  */
117 typedef long (*state_func_t)(void);
118 typedef state_func_t (*state_t)(void);
119 
120 static state_func_t single_user(void);
121 static state_func_t runcom(void);
122 static state_func_t read_ttys(void);
123 static state_func_t multi_user(void);
124 static state_func_t clean_ttys(void);
125 static state_func_t catatonia(void);
126 static state_func_t death(void);
127 static state_func_t death_single(void);
128 static state_func_t reroot(void);
129 static state_func_t reroot_phase_two(void);
130 
131 static state_func_t run_script(const char *);
132 
133 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
134 #define FALSE	0
135 #define TRUE	1
136 
137 static int Reboot = FALSE;
138 static int howto = RB_AUTOBOOT;
139 
140 static int devfs;
141 static char *init_path_argv0;
142 
143 static void transition(state_t);
144 static state_t requested_transition;
145 static state_t current_state = death_single;
146 
147 static void execute_script(char *argv[]);
148 static void open_console(void);
149 static const char *get_shell(void);
150 static void replace_init(char *path);
151 static void write_stderr(const char *message);
152 
153 typedef struct init_session {
154 	pid_t	se_process;		/* controlling process */
155 	time_t	se_started;		/* used to avoid thrashing */
156 	int	se_flags;		/* status of session */
157 #define	SE_SHUTDOWN	0x1		/* session won't be restarted */
158 #define	SE_PRESENT	0x2		/* session is in /etc/ttys */
159 #define	SE_IFEXISTS	0x4		/* session defined as "onifexists" */
160 #define	SE_IFCONSOLE	0x8		/* session defined as "onifconsole" */
161 	int	se_nspace;		/* spacing count */
162 	char	*se_device;		/* filename of port */
163 	char	*se_getty;		/* what to run on that port */
164 	char	*se_getty_argv_space;   /* pre-parsed argument array space */
165 	char	**se_getty_argv;	/* pre-parsed argument array */
166 	char	*se_window;		/* window system (started only once) */
167 	char	*se_window_argv_space;  /* pre-parsed argument array space */
168 	char	**se_window_argv;	/* pre-parsed argument array */
169 	char	*se_type;		/* default terminal type */
170 	struct	init_session *se_prev;
171 	struct	init_session *se_next;
172 } session_t;
173 
174 static void free_session(session_t *);
175 static session_t *new_session(session_t *, struct ttyent *);
176 static session_t *sessions;
177 
178 static char **construct_argv(char *);
179 static void start_window_system(session_t *);
180 static void collect_child(pid_t);
181 static pid_t start_getty(session_t *);
182 static void transition_handler(int);
183 static void alrm_handler(int);
184 static void setsecuritylevel(int);
185 static int getsecuritylevel(void);
186 static int setupargv(session_t *, struct ttyent *);
187 #ifdef LOGIN_CAP
188 static void setprocresources(const char *);
189 #endif
190 static int clang;
191 
192 static int start_session_db(void);
193 static void add_session(session_t *);
194 static void del_session(session_t *);
195 static session_t *find_session(pid_t);
196 static DB *session_db;
197 
198 /*
199  * The mother of all processes.
200  */
201 int
main(int argc,char * argv[])202 main(int argc, char *argv[])
203 {
204 	state_t initial_transition = runcom;
205 	char kenv_value[PATH_MAX];
206 	int c, error;
207 	struct sigaction sa;
208 	sigset_t mask;
209 
210 	/* Dispose of random users. */
211 	if (getuid() != 0)
212 		errx(1, "%s", strerror(EPERM));
213 
214 	/* System V users like to reexec init. */
215 	if (getpid() != 1) {
216 #ifdef COMPAT_SYSV_INIT
217 		/* So give them what they want */
218 		if (argc > 1) {
219 			if (strlen(argv[1]) == 1) {
220 				char runlevel = *argv[1];
221 				int sig;
222 
223 				switch (runlevel) {
224 				case '0': /* halt + poweroff */
225 					sig = SIGUSR2;
226 					break;
227 				case '1': /* single-user */
228 					sig = SIGTERM;
229 					break;
230 				case '6': /* reboot */
231 					sig = SIGINT;
232 					break;
233 				case 'c': /* block further logins */
234 					sig = SIGTSTP;
235 					break;
236 				case 'q': /* rescan /etc/ttys */
237 					sig = SIGHUP;
238 					break;
239 				case 'r': /* remount root */
240 					sig = SIGEMT;
241 					break;
242 				default:
243 					goto invalid;
244 				}
245 				kill(1, sig);
246 				_exit(0);
247 			} else
248 invalid:
249 				errx(1, "invalid run-level ``%s''", argv[1]);
250 		} else
251 #endif
252 			errx(1, "already running");
253 	}
254 
255 	init_path_argv0 = strdup(argv[0]);
256 	if (init_path_argv0 == NULL)
257 		err(1, "strdup");
258 
259 	/*
260 	 * Note that this does NOT open a file...
261 	 * Does 'init' deserve its own facility number?
262 	 */
263 	openlog("init", LOG_CONS, LOG_AUTH);
264 
265 	/*
266 	 * Create an initial session.
267 	 */
268 	if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
269 		warning("initial setsid() failed: %m");
270 
271 	/*
272 	 * Establish an initial user so that programs running
273 	 * single user do not freak out and die (like passwd).
274 	 */
275 	if (setlogin("root") < 0)
276 		warning("setlogin() failed: %m");
277 
278 	/*
279 	 * This code assumes that we always get arguments through flags,
280 	 * never through bits set in some random machine register.
281 	 */
282 	while ((c = getopt(argc, argv, "dsfr")) != -1)
283 		switch (c) {
284 		case 'd':
285 			devfs = 1;
286 			break;
287 		case 's':
288 			initial_transition = single_user;
289 			break;
290 		case 'f':
291 			runcom_mode = FASTBOOT;
292 			break;
293 		case 'r':
294 			initial_transition = reroot_phase_two;
295 			break;
296 		default:
297 			warning("unrecognized flag '-%c'", c);
298 			break;
299 		}
300 
301 	if (optind != argc)
302 		warning("ignoring excess arguments");
303 
304 	/*
305 	 * We catch or block signals rather than ignore them,
306 	 * so that they get reset on exec.
307 	 */
308 	handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
309 	    SIGXCPU, SIGXFSZ, 0);
310 	handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
311 	    SIGUSR1, SIGUSR2, SIGWINCH, 0);
312 	handle(alrm_handler, SIGALRM, 0);
313 	sigfillset(&mask);
314 	delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
315 	    SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
316 	    SIGALRM, SIGUSR1, SIGUSR2, SIGWINCH, 0);
317 	sigprocmask(SIG_SETMASK, &mask, NULL);
318 	sigemptyset(&sa.sa_mask);
319 	sa.sa_flags = 0;
320 	sa.sa_handler = SIG_IGN;
321 	sigaction(SIGTTIN, &sa, NULL);
322 	sigaction(SIGTTOU, &sa, NULL);
323 
324 	/*
325 	 * Paranoia.
326 	 */
327 	close(0);
328 	close(1);
329 	close(2);
330 
331 	if (kenv(KENV_GET, "init_exec", kenv_value, sizeof(kenv_value)) > 0) {
332 		replace_init(kenv_value);
333 		_exit(0); /* reboot */
334 	}
335 
336 	if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
337 		state_func_t next_transition;
338 
339 		if ((next_transition = run_script(kenv_value)) != NULL)
340 			initial_transition = (state_t) next_transition;
341 	}
342 
343 	if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
344 		if (chdir(kenv_value) != 0 || chroot(".") != 0)
345 			warning("Can't chroot to %s: %m", kenv_value);
346 	}
347 
348 	/*
349 	 * Additional check if devfs needs to be mounted:
350 	 * If "/" and "/dev" have the same device number,
351 	 * then it hasn't been mounted yet.
352 	 */
353 	if (!devfs) {
354 		struct stat stst;
355 		dev_t root_devno;
356 
357 		stat("/", &stst);
358 		root_devno = stst.st_dev;
359 		if (stat("/dev", &stst) != 0)
360 			warning("Can't stat /dev: %m");
361 		else if (stst.st_dev == root_devno)
362 			devfs++;
363 	}
364 
365 	if (devfs) {
366 		struct iovec iov[4];
367 		char *s;
368 		int i;
369 
370 		char _fstype[]	= "fstype";
371 		char _devfs[]	= "devfs";
372 		char _fspath[]	= "fspath";
373 		char _path_dev[]= _PATH_DEV;
374 
375 		iov[0].iov_base = _fstype;
376 		iov[0].iov_len = sizeof(_fstype);
377 		iov[1].iov_base = _devfs;
378 		iov[1].iov_len = sizeof(_devfs);
379 		iov[2].iov_base = _fspath;
380 		iov[2].iov_len = sizeof(_fspath);
381 		/*
382 		 * Try to avoid the trailing slash in _PATH_DEV.
383 		 * Be *very* defensive.
384 		 */
385 		s = strdup(_PATH_DEV);
386 		if (s != NULL) {
387 			i = strlen(s);
388 			if (i > 0 && s[i - 1] == '/')
389 				s[i - 1] = '\0';
390 			iov[3].iov_base = s;
391 			iov[3].iov_len = strlen(s) + 1;
392 		} else {
393 			iov[3].iov_base = _path_dev;
394 			iov[3].iov_len = sizeof(_path_dev);
395 		}
396 		nmount(iov, 4, 0);
397 		if (s != NULL)
398 			free(s);
399 	}
400 
401 	if (initial_transition != reroot_phase_two) {
402 		/*
403 		 * Unmount reroot leftovers.  This runs after init(8)
404 		 * gets reexecuted after reroot_phase_two() is done.
405 		 */
406 		error = unmount(_PATH_REROOT, MNT_FORCE);
407 		if (error != 0 && errno != EINVAL)
408 			warning("Cannot unmount %s: %m", _PATH_REROOT);
409 	}
410 
411 	/*
412 	 * Start the state machine.
413 	 */
414 	transition(initial_transition);
415 
416 	/*
417 	 * Should never reach here.
418 	 */
419 	return 1;
420 }
421 
422 /*
423  * Associate a function with a signal handler.
424  */
425 static void
handle(sig_t handler,...)426 handle(sig_t handler, ...)
427 {
428 	int sig;
429 	struct sigaction sa;
430 	sigset_t mask_everything;
431 	va_list ap;
432 	va_start(ap, handler);
433 
434 	sa.sa_handler = handler;
435 	sigfillset(&mask_everything);
436 
437 	while ((sig = va_arg(ap, int)) != 0) {
438 		sa.sa_mask = mask_everything;
439 		/* XXX SA_RESTART? */
440 		sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
441 		sigaction(sig, &sa, NULL);
442 	}
443 	va_end(ap);
444 }
445 
446 /*
447  * Delete a set of signals from a mask.
448  */
449 static void
delset(sigset_t * maskp,...)450 delset(sigset_t *maskp, ...)
451 {
452 	int sig;
453 	va_list ap;
454 	va_start(ap, maskp);
455 
456 	while ((sig = va_arg(ap, int)) != 0)
457 		sigdelset(maskp, sig);
458 	va_end(ap);
459 }
460 
461 /*
462  * Log a message and sleep for a while (to give someone an opportunity
463  * to read it and to save log or hardcopy output if the problem is chronic).
464  * NB: should send a message to the session logger to avoid blocking.
465  */
466 static void
stall(const char * message,...)467 stall(const char *message, ...)
468 {
469 	va_list ap;
470 	va_start(ap, message);
471 
472 	vsyslog(LOG_ALERT, message, ap);
473 	va_end(ap);
474 	sleep(STALL_TIMEOUT);
475 }
476 
477 /*
478  * Like stall(), but doesn't sleep.
479  * If cpp had variadic macros, the two functions could be #defines for another.
480  * NB: should send a message to the session logger to avoid blocking.
481  */
482 static void
warning(const char * message,...)483 warning(const char *message, ...)
484 {
485 	va_list ap;
486 	va_start(ap, message);
487 
488 	vsyslog(LOG_ALERT, message, ap);
489 	va_end(ap);
490 }
491 
492 /*
493  * Log an emergency message.
494  * NB: should send a message to the session logger to avoid blocking.
495  */
496 static void
emergency(const char * message,...)497 emergency(const char *message, ...)
498 {
499 	va_list ap;
500 	va_start(ap, message);
501 
502 	vsyslog(LOG_EMERG, message, ap);
503 	va_end(ap);
504 }
505 
506 /*
507  * Catch an unexpected signal.
508  */
509 static void
disaster(int sig)510 disaster(int sig)
511 {
512 
513 	emergency("fatal signal: %s",
514 	    (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
515 
516 	sleep(STALL_TIMEOUT);
517 	_exit(sig);		/* reboot */
518 }
519 
520 /*
521  * Get the security level of the kernel.
522  */
523 static int
getsecuritylevel(void)524 getsecuritylevel(void)
525 {
526 #ifdef KERN_SECURELVL
527 	int name[2], curlevel;
528 	size_t len;
529 
530 	name[0] = CTL_KERN;
531 	name[1] = KERN_SECURELVL;
532 	len = sizeof curlevel;
533 	if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
534 		emergency("cannot get kernel security level: %m");
535 		return (-1);
536 	}
537 	return (curlevel);
538 #else
539 	return (-1);
540 #endif
541 }
542 
543 /*
544  * Set the security level of the kernel.
545  */
546 static void
setsecuritylevel(int newlevel)547 setsecuritylevel(int newlevel)
548 {
549 #ifdef KERN_SECURELVL
550 	int name[2], curlevel;
551 
552 	curlevel = getsecuritylevel();
553 	if (newlevel == curlevel)
554 		return;
555 	name[0] = CTL_KERN;
556 	name[1] = KERN_SECURELVL;
557 	if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
558 		emergency(
559 		    "cannot change kernel security level from %d to %d: %m",
560 		    curlevel, newlevel);
561 		return;
562 	}
563 #ifdef SECURE
564 	warning("kernel security level changed from %d to %d",
565 	    curlevel, newlevel);
566 #endif
567 #endif
568 }
569 
570 /*
571  * Change states in the finite state machine.
572  * The initial state is passed as an argument.
573  */
574 static void
transition(state_t s)575 transition(state_t s)
576 {
577 
578 	current_state = s;
579 	for (;;)
580 		current_state = (state_t) (*current_state)();
581 }
582 
583 /*
584  * Start a session and allocate a controlling terminal.
585  * Only called by children of init after forking.
586  */
587 static void
open_console(void)588 open_console(void)
589 {
590 	int fd;
591 
592 	/*
593 	 * Try to open /dev/console.  Open the device with O_NONBLOCK to
594 	 * prevent potential blocking on a carrier.
595 	 */
596 	revoke(_PATH_CONSOLE);
597 	if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
598 		(void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
599 		if (login_tty(fd) == 0)
600 			return;
601 		close(fd);
602 	}
603 
604 	/* No luck.  Log output to file if possible. */
605 	if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
606 		stall("cannot open null device.");
607 		_exit(1);
608 	}
609 	if (fd != STDIN_FILENO) {
610 		dup2(fd, STDIN_FILENO);
611 		close(fd);
612 	}
613 	fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
614 	if (fd == -1)
615 		dup2(STDIN_FILENO, STDOUT_FILENO);
616 	else if (fd != STDOUT_FILENO) {
617 		dup2(fd, STDOUT_FILENO);
618 		close(fd);
619 	}
620 	dup2(STDOUT_FILENO, STDERR_FILENO);
621 }
622 
623 static const char *
get_shell(void)624 get_shell(void)
625 {
626 	static char kenv_value[PATH_MAX];
627 
628 	if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
629 		return kenv_value;
630 	else
631 		return _PATH_BSHELL;
632 }
633 
634 static void
write_stderr(const char * message)635 write_stderr(const char *message)
636 {
637 
638 	write(STDERR_FILENO, message, strlen(message));
639 }
640 
641 static int
read_file(const char * path,void ** bufp,size_t * bufsizep)642 read_file(const char *path, void **bufp, size_t *bufsizep)
643 {
644 	struct stat sb;
645 	size_t bufsize;
646 	void *buf;
647 	ssize_t nbytes;
648 	int error, fd;
649 
650 	fd = open(path, O_RDONLY);
651 	if (fd < 0) {
652 		emergency("%s: %m", path);
653 		return (-1);
654 	}
655 
656 	error = fstat(fd, &sb);
657 	if (error != 0) {
658 		emergency("fstat: %m");
659 		close(fd);
660 		return (error);
661 	}
662 
663 	bufsize = sb.st_size;
664 	buf = malloc(bufsize);
665 	if (buf == NULL) {
666 		emergency("malloc: %m");
667 		close(fd);
668 		return (error);
669 	}
670 
671 	nbytes = read(fd, buf, bufsize);
672 	if (nbytes != (ssize_t)bufsize) {
673 		emergency("read: %m");
674 		close(fd);
675 		free(buf);
676 		return (error);
677 	}
678 
679 	error = close(fd);
680 	if (error != 0) {
681 		emergency("close: %m");
682 		free(buf);
683 		return (error);
684 	}
685 
686 	*bufp = buf;
687 	*bufsizep = bufsize;
688 
689 	return (0);
690 }
691 
692 static int
create_file(const char * path,const void * buf,size_t bufsize)693 create_file(const char *path, const void *buf, size_t bufsize)
694 {
695 	ssize_t nbytes;
696 	int error, fd;
697 
698 	fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
699 	if (fd < 0) {
700 		emergency("%s: %m", path);
701 		return (-1);
702 	}
703 
704 	nbytes = write(fd, buf, bufsize);
705 	if (nbytes != (ssize_t)bufsize) {
706 		emergency("write: %m");
707 		close(fd);
708 		return (-1);
709 	}
710 
711 	error = close(fd);
712 	if (error != 0) {
713 		emergency("close: %m");
714 		return (-1);
715 	}
716 
717 	return (0);
718 }
719 
720 static int
mount_tmpfs(const char * fspath)721 mount_tmpfs(const char *fspath)
722 {
723 	struct iovec *iov;
724 	char errmsg[255];
725 	int error, iovlen;
726 
727 	iov = NULL;
728 	iovlen = 0;
729 	memset(errmsg, 0, sizeof(errmsg));
730 	build_iovec(&iov, &iovlen, "fstype",
731 	    __DECONST(void *, "tmpfs"), (size_t)-1);
732 	build_iovec(&iov, &iovlen, "fspath",
733 	    __DECONST(void *, fspath), (size_t)-1);
734 	build_iovec(&iov, &iovlen, "errmsg",
735 	    errmsg, sizeof(errmsg));
736 
737 	error = nmount(iov, iovlen, 0);
738 	if (error != 0) {
739 		if (*errmsg != '\0') {
740 			emergency("cannot mount tmpfs on %s: %s: %m",
741 			    fspath, errmsg);
742 		} else {
743 			emergency("cannot mount tmpfs on %s: %m",
744 			    fspath);
745 		}
746 		return (error);
747 	}
748 	return (0);
749 }
750 
751 static state_func_t
reroot(void)752 reroot(void)
753 {
754 	void *buf;
755 	size_t bufsize;
756 	int error;
757 
758 	buf = NULL;
759 	bufsize = 0;
760 
761 	revoke_ttys();
762 	runshutdown();
763 
764 	/*
765 	 * Make sure nobody can interfere with our scheme.
766 	 * Ignore ESRCH, which can apparently happen when
767 	 * there are no processes to kill.
768 	 */
769 	error = kill(-1, SIGKILL);
770 	if (error != 0 && errno != ESRCH) {
771 		emergency("kill(2) failed: %m");
772 		goto out;
773 	}
774 
775 	/*
776 	 * Copy the init binary into tmpfs, so that we can unmount
777 	 * the old rootfs without committing suicide.
778 	 */
779 	error = read_file(init_path_argv0, &buf, &bufsize);
780 	if (error != 0)
781 		goto out;
782 	error = mount_tmpfs(_PATH_REROOT);
783 	if (error != 0)
784 		goto out;
785 	error = create_file(_PATH_REROOT_INIT, buf, bufsize);
786 	if (error != 0)
787 		goto out;
788 
789 	/*
790 	 * Execute the temporary init.
791 	 */
792 	execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
793 	emergency("cannot exec %s: %m", _PATH_REROOT_INIT);
794 
795 out:
796 	emergency("reroot failed; going to single user mode");
797 	free(buf);
798 	return (state_func_t) single_user;
799 }
800 
801 static state_func_t
reroot_phase_two(void)802 reroot_phase_two(void)
803 {
804 	char init_path[PATH_MAX], *path, *path_component;
805 	size_t init_path_len;
806 	int nbytes, error;
807 
808 	/*
809 	 * Ask the kernel to mount the new rootfs.
810 	 */
811 	error = reboot(RB_REROOT);
812 	if (error != 0) {
813 		emergency("RB_REBOOT failed: %m");
814 		goto out;
815 	}
816 
817 	/*
818 	 * Figure out where the destination init(8) binary is.  Note that
819 	 * the path could be different than what we've started with.  Use
820 	 * the value from kenv, if set, or the one from sysctl otherwise.
821 	 * The latter defaults to a hardcoded value, but can be overridden
822 	 * by a build time option.
823 	 */
824 	nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
825 	if (nbytes <= 0) {
826 		init_path_len = sizeof(init_path);
827 		error = sysctlbyname("kern.init_path",
828 		    init_path, &init_path_len, NULL, 0);
829 		if (error != 0) {
830 			emergency("failed to retrieve kern.init_path: %m");
831 			goto out;
832 		}
833 	}
834 
835 	/*
836 	 * Repeat the init search logic from sys/kern/init_path.c
837 	 */
838 	path_component = init_path;
839 	while ((path = strsep(&path_component, ":")) != NULL) {
840 		/*
841 		 * Execute init(8) from the new rootfs.
842 		 */
843 		execl(path, path, NULL);
844 	}
845 	emergency("cannot exec init from %s: %m", init_path);
846 
847 out:
848 	emergency("reroot failed; going to single user mode");
849 	return (state_func_t) single_user;
850 }
851 
852 /*
853  * Bring the system up single user.
854  */
855 static state_func_t
single_user(void)856 single_user(void)
857 {
858 	pid_t pid, wpid;
859 	int status;
860 	sigset_t mask;
861 	const char *shell;
862 	char *argv[2];
863 	struct timeval tv, tn;
864 #ifdef SECURE
865 	struct ttyent *typ;
866 	struct passwd *pp;
867 	static const char banner[] =
868 		"Enter root password, or ^D to go multi-user\n";
869 	char *clear, *password;
870 #endif
871 #ifdef DEBUGSHELL
872 	char altshell[128];
873 #endif
874 
875 	if (Reboot) {
876 		/* Instead of going single user, let's reboot the machine */
877 		sync();
878 		/* Run scripts after all processes have been terminated. */
879 		runfinal();
880 		if (reboot(howto) == -1) {
881 			emergency("reboot(%#x) failed, %m", howto);
882 			_exit(1); /* panic and reboot */
883 		}
884 		warning("reboot(%#x) returned", howto);
885 		_exit(0); /* panic as well */
886 	}
887 
888 	shell = get_shell();
889 
890 	if ((pid = fork()) == 0) {
891 		/*
892 		 * Start the single user session.
893 		 */
894 		open_console();
895 
896 #ifdef SECURE
897 		/*
898 		 * Check the root password.
899 		 * We don't care if the console is 'on' by default;
900 		 * it's the only tty that can be 'off' and 'secure'.
901 		 */
902 		typ = getttynam("console");
903 		pp = getpwnam("root");
904 		if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
905 		    pp && *pp->pw_passwd) {
906 			write_stderr(banner);
907 			for (;;) {
908 				clear = getpass("Password:");
909 				if (clear == NULL || *clear == '\0')
910 					_exit(0);
911 				password = crypt(clear, pp->pw_passwd);
912 				explicit_bzero(clear, _PASSWORD_LEN);
913 				if (password != NULL &&
914 				    strcmp(password, pp->pw_passwd) == 0)
915 					break;
916 				warning("single-user login failed\n");
917 			}
918 		}
919 		endttyent();
920 		endpwent();
921 #endif /* SECURE */
922 
923 #ifdef DEBUGSHELL
924 		{
925 			char *cp = altshell;
926 			int num;
927 
928 #define	SHREQUEST "Enter full pathname of shell or RETURN for "
929 			write_stderr(SHREQUEST);
930 			write_stderr(shell);
931 			write_stderr(": ");
932 			while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
933 			    num != 0 && *cp != '\n' && cp < &altshell[127])
934 				cp++;
935 			*cp = '\0';
936 			if (altshell[0] != '\0')
937 				shell = altshell;
938 		}
939 #endif /* DEBUGSHELL */
940 
941 		/*
942 		 * Unblock signals.
943 		 * We catch all the interesting ones,
944 		 * and those are reset to SIG_DFL on exec.
945 		 */
946 		sigemptyset(&mask);
947 		sigprocmask(SIG_SETMASK, &mask, NULL);
948 
949 		/*
950 		 * Fire off a shell.
951 		 * If the default one doesn't work, try the Bourne shell.
952 		 */
953 
954 		char name[] = "-sh";
955 
956 		argv[0] = name;
957 		argv[1] = NULL;
958 		execv(shell, argv);
959 		emergency("can't exec %s for single user: %m", shell);
960 		execv(_PATH_BSHELL, argv);
961 		emergency("can't exec %s for single user: %m", _PATH_BSHELL);
962 		sleep(STALL_TIMEOUT);
963 		_exit(1);
964 	}
965 
966 	if (pid == -1) {
967 		/*
968 		 * We are seriously hosed.  Do our best.
969 		 */
970 		emergency("can't fork single-user shell, trying again");
971 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
972 			continue;
973 		return (state_func_t) single_user;
974 	}
975 
976 	requested_transition = 0;
977 	do {
978 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
979 			collect_child(wpid);
980 		if (wpid == -1) {
981 			if (errno == EINTR)
982 				continue;
983 			warning("wait for single-user shell failed: %m; restarting");
984 			return (state_func_t) single_user;
985 		}
986 		if (wpid == pid && WIFSTOPPED(status)) {
987 			warning("init: shell stopped, restarting\n");
988 			kill(pid, SIGCONT);
989 			wpid = -1;
990 		}
991 	} while (wpid != pid && !requested_transition);
992 
993 	if (requested_transition)
994 		return (state_func_t) requested_transition;
995 
996 	if (!WIFEXITED(status)) {
997 		if (WTERMSIG(status) == SIGKILL) {
998 			/*
999 			 *  reboot(8) killed shell?
1000 			 */
1001 			warning("single user shell terminated.");
1002 			gettimeofday(&tv, NULL);
1003 			tn = tv;
1004 			tv.tv_sec += STALL_TIMEOUT;
1005 			while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1006 			    tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1007 				sleep(1);
1008 				gettimeofday(&tn, NULL);
1009 			}
1010 			_exit(0);
1011 		} else {
1012 			warning("single user shell terminated, restarting");
1013 			return (state_func_t) single_user;
1014 		}
1015 	}
1016 
1017 	runcom_mode = FASTBOOT;
1018 	return (state_func_t) runcom;
1019 }
1020 
1021 /*
1022  * Run the system startup script.
1023  */
1024 static state_func_t
runcom(void)1025 runcom(void)
1026 {
1027 	state_func_t next_transition;
1028 
1029 	if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1030 		return next_transition;
1031 
1032 	runcom_mode = AUTOBOOT;		/* the default */
1033 	return (state_func_t) read_ttys;
1034 }
1035 
1036 static void
execute_script(char * argv[])1037 execute_script(char *argv[])
1038 {
1039 	struct sigaction sa;
1040 	const char *shell, *script;
1041 	int error;
1042 
1043 	bzero(&sa, sizeof(sa));
1044 	sigemptyset(&sa.sa_mask);
1045 	sa.sa_handler = SIG_IGN;
1046 	sigaction(SIGTSTP, &sa, NULL);
1047 	sigaction(SIGHUP, &sa, NULL);
1048 
1049 	open_console();
1050 
1051 	sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1052 #ifdef LOGIN_CAP
1053 	setprocresources(RESOURCE_RC);
1054 #endif
1055 
1056 	/*
1057 	 * Try to directly execute the script first.  If it
1058 	 * fails, try the old method of passing the script path
1059 	 * to sh(1).  Don't complain if it fails because of
1060 	 * the missing execute bit.
1061 	 */
1062 	script = argv[1];
1063 	error = access(script, X_OK);
1064 	if (error == 0) {
1065 		execv(script, argv + 1);
1066 		warning("can't directly exec %s: %m", script);
1067 	} else if (errno != EACCES) {
1068 		warning("can't access %s: %m", script);
1069 	}
1070 
1071 	shell = get_shell();
1072 	execv(shell, argv);
1073 	stall("can't exec %s for %s: %m", shell, script);
1074 }
1075 
1076 /*
1077  * Execute binary, replacing init(8) as PID 1.
1078  */
1079 static void
replace_init(char * path)1080 replace_init(char *path)
1081 {
1082 	char *argv[3];
1083 	char sh[] = "sh";
1084 
1085 	argv[0] = sh;
1086 	argv[1] = path;
1087 	argv[2] = NULL;
1088 
1089 	execute_script(argv);
1090 }
1091 
1092 /*
1093  * Run a shell script.
1094  * Returns 0 on success, otherwise the next transition to enter:
1095  *  - single_user if fork/execv/waitpid failed, or if the script
1096  *    terminated with a signal or exit code != 0.
1097  *  - death_single if a SIGTERM was delivered to init(8).
1098  */
1099 static state_func_t
run_script(const char * script)1100 run_script(const char *script)
1101 {
1102 	pid_t pid, wpid;
1103 	int status;
1104 	char *argv[4];
1105 	const char *shell;
1106 
1107 	shell = get_shell();
1108 
1109 	if ((pid = fork()) == 0) {
1110 
1111 		char _sh[]		= "sh";
1112 		char _autoboot[]	= "autoboot";
1113 
1114 		argv[0] = _sh;
1115 		argv[1] = __DECONST(char *, script);
1116 		argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1117 		argv[3] = NULL;
1118 
1119 		execute_script(argv);
1120 		sleep(STALL_TIMEOUT);
1121 		_exit(1);	/* force single user mode */
1122 	}
1123 
1124 	if (pid == -1) {
1125 		emergency("can't fork for %s on %s: %m", shell, script);
1126 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1127 			continue;
1128 		sleep(STALL_TIMEOUT);
1129 		return (state_func_t) single_user;
1130 	}
1131 
1132 	/*
1133 	 * Copied from single_user().  This is a bit paranoid.
1134 	 */
1135 	requested_transition = 0;
1136 	do {
1137 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1138 			collect_child(wpid);
1139 		if (requested_transition == death_single ||
1140 		    requested_transition == reroot)
1141 			return (state_func_t) requested_transition;
1142 		if (wpid == -1) {
1143 			if (errno == EINTR)
1144 				continue;
1145 			warning("wait for %s on %s failed: %m; going to "
1146 			    "single user mode", shell, script);
1147 			return (state_func_t) single_user;
1148 		}
1149 		if (wpid == pid && WIFSTOPPED(status)) {
1150 			warning("init: %s on %s stopped, restarting\n",
1151 			    shell, script);
1152 			kill(pid, SIGCONT);
1153 			wpid = -1;
1154 		}
1155 	} while (wpid != pid);
1156 
1157 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1158 	    requested_transition == catatonia) {
1159 		/* /etc/rc executed /sbin/reboot; wait for the end quietly */
1160 		sigset_t s;
1161 
1162 		sigfillset(&s);
1163 		for (;;)
1164 			sigsuspend(&s);
1165 	}
1166 
1167 	if (!WIFEXITED(status)) {
1168 		warning("%s on %s terminated abnormally, going to single "
1169 		    "user mode", shell, script);
1170 		return (state_func_t) single_user;
1171 	}
1172 
1173 	if (WEXITSTATUS(status))
1174 		return (state_func_t) single_user;
1175 
1176 	return (state_func_t) 0;
1177 }
1178 
1179 /*
1180  * Open the session database.
1181  *
1182  * NB: We could pass in the size here; is it necessary?
1183  */
1184 static int
start_session_db(void)1185 start_session_db(void)
1186 {
1187 	if (session_db && (*session_db->close)(session_db))
1188 		emergency("session database close: %m");
1189 	if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1190 		emergency("session database open: %m");
1191 		return (1);
1192 	}
1193 	return (0);
1194 
1195 }
1196 
1197 /*
1198  * Add a new login session.
1199  */
1200 static void
add_session(session_t * sp)1201 add_session(session_t *sp)
1202 {
1203 	DBT key;
1204 	DBT data;
1205 
1206 	key.data = &sp->se_process;
1207 	key.size = sizeof sp->se_process;
1208 	data.data = &sp;
1209 	data.size = sizeof sp;
1210 
1211 	if ((*session_db->put)(session_db, &key, &data, 0))
1212 		emergency("insert %d: %m", sp->se_process);
1213 }
1214 
1215 /*
1216  * Delete an old login session.
1217  */
1218 static void
del_session(session_t * sp)1219 del_session(session_t *sp)
1220 {
1221 	DBT key;
1222 
1223 	key.data = &sp->se_process;
1224 	key.size = sizeof sp->se_process;
1225 
1226 	if ((*session_db->del)(session_db, &key, 0))
1227 		emergency("delete %d: %m", sp->se_process);
1228 }
1229 
1230 /*
1231  * Look up a login session by pid.
1232  */
1233 static session_t *
find_session(pid_t pid)1234 find_session(pid_t pid)
1235 {
1236 	DBT key;
1237 	DBT data;
1238 	session_t *ret;
1239 
1240 	key.data = &pid;
1241 	key.size = sizeof pid;
1242 	if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1243 		return 0;
1244 	bcopy(data.data, (char *)&ret, sizeof(ret));
1245 	return ret;
1246 }
1247 
1248 /*
1249  * Construct an argument vector from a command line.
1250  */
1251 static char **
construct_argv(char * command)1252 construct_argv(char *command)
1253 {
1254 	int argc = 0;
1255 	char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1256 						* sizeof (char *));
1257 
1258 	if ((argv[argc++] = strk(command)) == NULL) {
1259 		free(argv);
1260 		return (NULL);
1261 	}
1262 	while ((argv[argc++] = strk((char *) 0)) != NULL)
1263 		continue;
1264 	return argv;
1265 }
1266 
1267 /*
1268  * Deallocate a session descriptor.
1269  */
1270 static void
free_session(session_t * sp)1271 free_session(session_t *sp)
1272 {
1273 	free(sp->se_device);
1274 	if (sp->se_getty) {
1275 		free(sp->se_getty);
1276 		free(sp->se_getty_argv_space);
1277 		free(sp->se_getty_argv);
1278 	}
1279 	if (sp->se_window) {
1280 		free(sp->se_window);
1281 		free(sp->se_window_argv_space);
1282 		free(sp->se_window_argv);
1283 	}
1284 	if (sp->se_type)
1285 		free(sp->se_type);
1286 	free(sp);
1287 }
1288 
1289 /*
1290  * Allocate a new session descriptor.
1291  * Mark it SE_PRESENT.
1292  */
1293 static session_t *
new_session(session_t * sprev,struct ttyent * typ)1294 new_session(session_t *sprev, struct ttyent *typ)
1295 {
1296 	session_t *sp;
1297 
1298 	if ((typ->ty_status & TTY_ON) == 0 ||
1299 	    typ->ty_name == 0 ||
1300 	    typ->ty_getty == 0)
1301 		return 0;
1302 
1303 	sp = (session_t *) calloc(1, sizeof (session_t));
1304 
1305 	sp->se_flags |= SE_PRESENT;
1306 
1307 	if ((typ->ty_status & TTY_IFEXISTS) != 0)
1308 		sp->se_flags |= SE_IFEXISTS;
1309 
1310 	if ((typ->ty_status & TTY_IFCONSOLE) != 0)
1311 		sp->se_flags |= SE_IFCONSOLE;
1312 
1313 	if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1314 		err(1, "asprintf");
1315 
1316 	if (setupargv(sp, typ) == 0) {
1317 		free_session(sp);
1318 		return (0);
1319 	}
1320 
1321 	sp->se_next = 0;
1322 	if (sprev == NULL) {
1323 		sessions = sp;
1324 		sp->se_prev = 0;
1325 	} else {
1326 		sprev->se_next = sp;
1327 		sp->se_prev = sprev;
1328 	}
1329 
1330 	return sp;
1331 }
1332 
1333 /*
1334  * Calculate getty and if useful window argv vectors.
1335  */
1336 static int
setupargv(session_t * sp,struct ttyent * typ)1337 setupargv(session_t *sp, struct ttyent *typ)
1338 {
1339 
1340 	if (sp->se_getty) {
1341 		free(sp->se_getty);
1342 		free(sp->se_getty_argv_space);
1343 		free(sp->se_getty_argv);
1344 	}
1345 	if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1346 		err(1, "asprintf");
1347 	sp->se_getty_argv_space = strdup(sp->se_getty);
1348 	sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1349 	if (sp->se_getty_argv == NULL) {
1350 		warning("can't parse getty for port %s", sp->se_device);
1351 		free(sp->se_getty);
1352 		free(sp->se_getty_argv_space);
1353 		sp->se_getty = sp->se_getty_argv_space = 0;
1354 		return (0);
1355 	}
1356 	if (sp->se_window) {
1357 		free(sp->se_window);
1358 		free(sp->se_window_argv_space);
1359 		free(sp->se_window_argv);
1360 	}
1361 	sp->se_window = sp->se_window_argv_space = 0;
1362 	sp->se_window_argv = 0;
1363 	if (typ->ty_window) {
1364 		sp->se_window = strdup(typ->ty_window);
1365 		sp->se_window_argv_space = strdup(sp->se_window);
1366 		sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1367 		if (sp->se_window_argv == NULL) {
1368 			warning("can't parse window for port %s",
1369 			    sp->se_device);
1370 			free(sp->se_window_argv_space);
1371 			free(sp->se_window);
1372 			sp->se_window = sp->se_window_argv_space = 0;
1373 			return (0);
1374 		}
1375 	}
1376 	if (sp->se_type)
1377 		free(sp->se_type);
1378 	sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1379 	return (1);
1380 }
1381 
1382 /*
1383  * Walk the list of ttys and create sessions for each active line.
1384  */
1385 static state_func_t
read_ttys(void)1386 read_ttys(void)
1387 {
1388 	session_t *sp, *snext;
1389 	struct ttyent *typ;
1390 
1391 	/*
1392 	 * Destroy any previous session state.
1393 	 * There shouldn't be any, but just in case...
1394 	 */
1395 	for (sp = sessions; sp; sp = snext) {
1396 		snext = sp->se_next;
1397 		free_session(sp);
1398 	}
1399 	sessions = 0;
1400 	if (start_session_db())
1401 		return (state_func_t) single_user;
1402 
1403 	/*
1404 	 * Allocate a session entry for each active port.
1405 	 * Note that sp starts at 0.
1406 	 */
1407 	while ((typ = getttyent()) != NULL)
1408 		if ((snext = new_session(sp, typ)) != NULL)
1409 			sp = snext;
1410 
1411 	endttyent();
1412 
1413 	return (state_func_t) multi_user;
1414 }
1415 
1416 /*
1417  * Start a window system running.
1418  */
1419 static void
start_window_system(session_t * sp)1420 start_window_system(session_t *sp)
1421 {
1422 	pid_t pid;
1423 	sigset_t mask;
1424 	char term[64], *env[2];
1425 	int status;
1426 
1427 	if ((pid = fork()) == -1) {
1428 		emergency("can't fork for window system on port %s: %m",
1429 		    sp->se_device);
1430 		/* hope that getty fails and we can try again */
1431 		return;
1432 	}
1433 	if (pid) {
1434 		waitpid(-1, &status, 0);
1435 		return;
1436 	}
1437 
1438 	/* reparent window process to the init to not make a zombie on exit */
1439 	if ((pid = fork()) == -1) {
1440 		emergency("can't fork for window system on port %s: %m",
1441 		    sp->se_device);
1442 		_exit(1);
1443 	}
1444 	if (pid)
1445 		_exit(0);
1446 
1447 	sigemptyset(&mask);
1448 	sigprocmask(SIG_SETMASK, &mask, NULL);
1449 
1450 	if (setsid() < 0)
1451 		emergency("setsid failed (window) %m");
1452 
1453 #ifdef LOGIN_CAP
1454 	setprocresources(RESOURCE_WINDOW);
1455 #endif
1456 	if (sp->se_type) {
1457 		/* Don't use malloc after fork */
1458 		strcpy(term, "TERM=");
1459 		strlcat(term, sp->se_type, sizeof(term));
1460 		env[0] = term;
1461 		env[1] = NULL;
1462 	}
1463 	else
1464 		env[0] = NULL;
1465 	execve(sp->se_window_argv[0], sp->se_window_argv, env);
1466 	stall("can't exec window system '%s' for port %s: %m",
1467 		sp->se_window_argv[0], sp->se_device);
1468 	_exit(1);
1469 }
1470 
1471 /*
1472  * Start a login session running.
1473  */
1474 static pid_t
start_getty(session_t * sp)1475 start_getty(session_t *sp)
1476 {
1477 	pid_t pid;
1478 	sigset_t mask;
1479 	time_t current_time = time((time_t *) 0);
1480 	int too_quick = 0;
1481 	char term[64], *env[2];
1482 
1483 	if (current_time >= sp->se_started &&
1484 	    current_time - sp->se_started < GETTY_SPACING) {
1485 		if (++sp->se_nspace > GETTY_NSPACE) {
1486 			sp->se_nspace = 0;
1487 			too_quick = 1;
1488 		}
1489 	} else
1490 		sp->se_nspace = 0;
1491 
1492 	/*
1493 	 * fork(), not vfork() -- we can't afford to block.
1494 	 */
1495 	if ((pid = fork()) == -1) {
1496 		emergency("can't fork for getty on port %s: %m", sp->se_device);
1497 		return -1;
1498 	}
1499 
1500 	if (pid)
1501 		return pid;
1502 
1503 	if (too_quick) {
1504 		warning("getty repeating too quickly on port %s, sleeping %d secs",
1505 		    sp->se_device, GETTY_SLEEP);
1506 		sleep((unsigned) GETTY_SLEEP);
1507 	}
1508 
1509 	if (sp->se_window) {
1510 		start_window_system(sp);
1511 		sleep(WINDOW_WAIT);
1512 	}
1513 
1514 	sigemptyset(&mask);
1515 	sigprocmask(SIG_SETMASK, &mask, NULL);
1516 
1517 #ifdef LOGIN_CAP
1518 	setprocresources(RESOURCE_GETTY);
1519 #endif
1520 	if (sp->se_type) {
1521 		/* Don't use malloc after fork */
1522 		strcpy(term, "TERM=");
1523 		strlcat(term, sp->se_type, sizeof(term));
1524 		env[0] = term;
1525 		env[1] = NULL;
1526 	} else
1527 		env[0] = NULL;
1528 	execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1529 	stall("can't exec getty '%s' for port %s: %m",
1530 		sp->se_getty_argv[0], sp->se_device);
1531 	_exit(1);
1532 }
1533 
1534 /*
1535  * Return 1 if the session is defined as "onifexists"
1536  * or "onifconsole" and the device node does not exist.
1537  */
1538 static int
session_has_no_tty(session_t * sp)1539 session_has_no_tty(session_t *sp)
1540 {
1541 	int fd;
1542 
1543 	if ((sp->se_flags & SE_IFEXISTS) == 0 &&
1544 	    (sp->se_flags & SE_IFCONSOLE) == 0)
1545 		return (0);
1546 
1547 	fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0);
1548 	if (fd < 0) {
1549 		if (errno == ENOENT)
1550 			return (1);
1551 		return (0);
1552 	}
1553 
1554 	close(fd);
1555 	return (0);
1556 }
1557 
1558 /*
1559  * Collect exit status for a child.
1560  * If an exiting login, start a new login running.
1561  */
1562 static void
collect_child(pid_t pid)1563 collect_child(pid_t pid)
1564 {
1565 	session_t *sp, *sprev, *snext;
1566 
1567 	if (! sessions)
1568 		return;
1569 
1570 	if (! (sp = find_session(pid)))
1571 		return;
1572 
1573 	del_session(sp);
1574 	sp->se_process = 0;
1575 
1576 	if (sp->se_flags & SE_SHUTDOWN ||
1577 	    session_has_no_tty(sp)) {
1578 		if ((sprev = sp->se_prev) != NULL)
1579 			sprev->se_next = sp->se_next;
1580 		else
1581 			sessions = sp->se_next;
1582 		if ((snext = sp->se_next) != NULL)
1583 			snext->se_prev = sp->se_prev;
1584 		free_session(sp);
1585 		return;
1586 	}
1587 
1588 	if ((pid = start_getty(sp)) == -1) {
1589 		/* serious trouble */
1590 		requested_transition = clean_ttys;
1591 		return;
1592 	}
1593 
1594 	sp->se_process = pid;
1595 	sp->se_started = time((time_t *) 0);
1596 	add_session(sp);
1597 }
1598 
1599 /*
1600  * Catch a signal and request a state transition.
1601  */
1602 static void
transition_handler(int sig)1603 transition_handler(int sig)
1604 {
1605 
1606 	switch (sig) {
1607 	case SIGHUP:
1608 		if (current_state == read_ttys || current_state == multi_user ||
1609 		    current_state == clean_ttys || current_state == catatonia)
1610 			requested_transition = clean_ttys;
1611 		break;
1612 	case SIGUSR2:
1613 		howto = RB_POWEROFF;
1614 	case SIGUSR1:
1615 		howto |= RB_HALT;
1616 	case SIGWINCH:
1617 	case SIGINT:
1618 		if (sig == SIGWINCH)
1619 			howto |= RB_POWERCYCLE;
1620 		Reboot = TRUE;
1621 	case SIGTERM:
1622 		if (current_state == read_ttys || current_state == multi_user ||
1623 		    current_state == clean_ttys || current_state == catatonia)
1624 			requested_transition = death;
1625 		else
1626 			requested_transition = death_single;
1627 		break;
1628 	case SIGTSTP:
1629 		if (current_state == runcom || current_state == read_ttys ||
1630 		    current_state == clean_ttys ||
1631 		    current_state == multi_user || current_state == catatonia)
1632 			requested_transition = catatonia;
1633 		break;
1634 	case SIGEMT:
1635 		requested_transition = reroot;
1636 		break;
1637 	default:
1638 		requested_transition = 0;
1639 		break;
1640 	}
1641 }
1642 
1643 /*
1644  * Take the system multiuser.
1645  */
1646 static state_func_t
multi_user(void)1647 multi_user(void)
1648 {
1649 	pid_t pid;
1650 	session_t *sp;
1651 
1652 	requested_transition = 0;
1653 
1654 	/*
1655 	 * If the administrator has not set the security level to -1
1656 	 * to indicate that the kernel should not run multiuser in secure
1657 	 * mode, and the run script has not set a higher level of security
1658 	 * than level 1, then put the kernel into secure mode.
1659 	 */
1660 	if (getsecuritylevel() == 0)
1661 		setsecuritylevel(1);
1662 
1663 	for (sp = sessions; sp; sp = sp->se_next) {
1664 		if (sp->se_process)
1665 			continue;
1666 		if (session_has_no_tty(sp))
1667 			continue;
1668 		if ((pid = start_getty(sp)) == -1) {
1669 			/* serious trouble */
1670 			requested_transition = clean_ttys;
1671 			break;
1672 		}
1673 		sp->se_process = pid;
1674 		sp->se_started = time((time_t *) 0);
1675 		add_session(sp);
1676 	}
1677 
1678 	while (!requested_transition)
1679 		if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1680 			collect_child(pid);
1681 
1682 	return (state_func_t) requested_transition;
1683 }
1684 
1685 /*
1686  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1687  */
1688 static state_func_t
clean_ttys(void)1689 clean_ttys(void)
1690 {
1691 	session_t *sp, *sprev;
1692 	struct ttyent *typ;
1693 	int devlen;
1694 	char *old_getty, *old_window, *old_type;
1695 
1696 	/*
1697 	 * mark all sessions for death, (!SE_PRESENT)
1698 	 * as we find or create new ones they'll be marked as keepers,
1699 	 * we'll later nuke all the ones not found in /etc/ttys
1700 	 */
1701 	for (sp = sessions; sp != NULL; sp = sp->se_next)
1702 		sp->se_flags &= ~SE_PRESENT;
1703 
1704 	devlen = sizeof(_PATH_DEV) - 1;
1705 	while ((typ = getttyent()) != NULL) {
1706 		for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1707 			if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1708 				break;
1709 
1710 		if (sp) {
1711 			/* we want this one to live */
1712 			sp->se_flags |= SE_PRESENT;
1713 			if ((typ->ty_status & TTY_ON) == 0 ||
1714 			    typ->ty_getty == 0) {
1715 				sp->se_flags |= SE_SHUTDOWN;
1716 				kill(sp->se_process, SIGHUP);
1717 				continue;
1718 			}
1719 			sp->se_flags &= ~SE_SHUTDOWN;
1720 			old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1721 			old_window = sp->se_window ? strdup(sp->se_window) : 0;
1722 			old_type = sp->se_type ? strdup(sp->se_type) : 0;
1723 			if (setupargv(sp, typ) == 0) {
1724 				warning("can't parse getty for port %s",
1725 					sp->se_device);
1726 				sp->se_flags |= SE_SHUTDOWN;
1727 				kill(sp->se_process, SIGHUP);
1728 			}
1729 			else if (   !old_getty
1730 				 || (!old_type && sp->se_type)
1731 				 || (old_type && !sp->se_type)
1732 				 || (!old_window && sp->se_window)
1733 				 || (old_window && !sp->se_window)
1734 				 || (strcmp(old_getty, sp->se_getty) != 0)
1735 				 || (old_window && strcmp(old_window, sp->se_window) != 0)
1736 				 || (old_type && strcmp(old_type, sp->se_type) != 0)
1737 				) {
1738 				/* Don't set SE_SHUTDOWN here */
1739 				sp->se_nspace = 0;
1740 				sp->se_started = 0;
1741 				kill(sp->se_process, SIGHUP);
1742 			}
1743 			if (old_getty)
1744 				free(old_getty);
1745 			if (old_window)
1746 				free(old_window);
1747 			if (old_type)
1748 				free(old_type);
1749 			continue;
1750 		}
1751 
1752 		new_session(sprev, typ);
1753 	}
1754 
1755 	endttyent();
1756 
1757 	/*
1758 	 * sweep through and kill all deleted sessions
1759 	 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1760 	 */
1761 	for (sp = sessions; sp != NULL; sp = sp->se_next) {
1762 		if ((sp->se_flags & SE_PRESENT) == 0) {
1763 			sp->se_flags |= SE_SHUTDOWN;
1764 			kill(sp->se_process, SIGHUP);
1765 		}
1766 	}
1767 
1768 	return (state_func_t) multi_user;
1769 }
1770 
1771 /*
1772  * Block further logins.
1773  */
1774 static state_func_t
catatonia(void)1775 catatonia(void)
1776 {
1777 	session_t *sp;
1778 
1779 	for (sp = sessions; sp; sp = sp->se_next)
1780 		sp->se_flags |= SE_SHUTDOWN;
1781 
1782 	return (state_func_t) multi_user;
1783 }
1784 
1785 /*
1786  * Note SIGALRM.
1787  */
1788 static void
alrm_handler(int sig)1789 alrm_handler(int sig)
1790 {
1791 
1792 	(void)sig;
1793 	clang = 1;
1794 }
1795 
1796 /*
1797  * Bring the system down to single user.
1798  */
1799 static state_func_t
death(void)1800 death(void)
1801 {
1802 	int block, blocked;
1803 	size_t len;
1804 
1805 	/* Temporarily block suspend. */
1806 	len = sizeof(blocked);
1807 	block = 1;
1808 	if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1809 	    &block, sizeof(block)) == -1)
1810 		blocked = 0;
1811 
1812 	/*
1813 	 * Also revoke the TTY here.  Because runshutdown() may reopen
1814 	 * the TTY whose getty we're killing here, there is no guarantee
1815 	 * runshutdown() will perform the initial open() call, causing
1816 	 * the terminal attributes to be misconfigured.
1817 	 */
1818 	revoke_ttys();
1819 
1820 	/* Try to run the rc.shutdown script within a period of time */
1821 	runshutdown();
1822 
1823 	/* Unblock suspend if we blocked it. */
1824 	if (!blocked)
1825 		sysctlbyname("kern.suspend_blocked", NULL, NULL,
1826 		    &blocked, sizeof(blocked));
1827 
1828 	return (state_func_t) death_single;
1829 }
1830 
1831 /*
1832  * Do what is necessary to reinitialize single user mode or reboot
1833  * from an incomplete state.
1834  */
1835 static state_func_t
death_single(void)1836 death_single(void)
1837 {
1838 	int i;
1839 	pid_t pid;
1840 	static const int death_sigs[2] = { SIGTERM, SIGKILL };
1841 
1842 	revoke(_PATH_CONSOLE);
1843 
1844 	for (i = 0; i < 2; ++i) {
1845 		if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1846 			return (state_func_t) single_user;
1847 
1848 		clang = 0;
1849 		alarm(DEATH_WATCH);
1850 		do
1851 			if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1852 				collect_child(pid);
1853 		while (clang == 0 && errno != ECHILD);
1854 
1855 		if (errno == ECHILD)
1856 			return (state_func_t) single_user;
1857 	}
1858 
1859 	warning("some processes would not die; ps axl advised");
1860 
1861 	return (state_func_t) single_user;
1862 }
1863 
1864 static void
revoke_ttys(void)1865 revoke_ttys(void)
1866 {
1867 	session_t *sp;
1868 
1869 	for (sp = sessions; sp; sp = sp->se_next) {
1870 		sp->se_flags |= SE_SHUTDOWN;
1871 		kill(sp->se_process, SIGHUP);
1872 		revoke(sp->se_device);
1873 	}
1874 }
1875 
1876 /*
1877  * Run the system shutdown script.
1878  *
1879  * Exit codes:      XXX I should document more
1880  * -2       shutdown script terminated abnormally
1881  * -1       fatal error - can't run script
1882  * 0        good.
1883  * >0       some error (exit code)
1884  */
1885 static int
runshutdown(void)1886 runshutdown(void)
1887 {
1888 	pid_t pid, wpid;
1889 	int status;
1890 	int shutdowntimeout;
1891 	size_t len;
1892 	char *argv[4];
1893 	struct stat sb;
1894 
1895 	/*
1896 	 * rc.shutdown is optional, so to prevent any unnecessary
1897 	 * complaints from the shell we simply don't run it if the
1898 	 * file does not exist. If the stat() here fails for other
1899 	 * reasons, we'll let the shell complain.
1900 	 */
1901 	if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1902 		return 0;
1903 
1904 	if ((pid = fork()) == 0) {
1905 		char _sh[]	= "sh";
1906 		char _reboot[]	= "reboot";
1907 		char _single[]	= "single";
1908 		char _path_rundown[] = _PATH_RUNDOWN;
1909 
1910 		argv[0] = _sh;
1911 		argv[1] = _path_rundown;
1912 		argv[2] = Reboot ? _reboot : _single;
1913 		argv[3] = NULL;
1914 
1915 		execute_script(argv);
1916 		_exit(1);	/* force single user mode */
1917 	}
1918 
1919 	if (pid == -1) {
1920 		emergency("can't fork for %s: %m", _PATH_RUNDOWN);
1921 		while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1922 			continue;
1923 		sleep(STALL_TIMEOUT);
1924 		return -1;
1925 	}
1926 
1927 	len = sizeof(shutdowntimeout);
1928 	if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1929 	    NULL, 0) == -1 || shutdowntimeout < 2)
1930 		shutdowntimeout = DEATH_SCRIPT;
1931 	alarm(shutdowntimeout);
1932 	clang = 0;
1933 	/*
1934 	 * Copied from single_user().  This is a bit paranoid.
1935 	 * Use the same ALRM handler.
1936 	 */
1937 	do {
1938 		if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1939 			collect_child(wpid);
1940 		if (clang == 1) {
1941 			/* we were waiting for the sub-shell */
1942 			kill(wpid, SIGTERM);
1943 			warning("timeout expired for %s: %m; going to "
1944 			    "single user mode", _PATH_RUNDOWN);
1945 			return -1;
1946 		}
1947 		if (wpid == -1) {
1948 			if (errno == EINTR)
1949 				continue;
1950 			warning("wait for %s failed: %m; going to "
1951 			    "single user mode", _PATH_RUNDOWN);
1952 			return -1;
1953 		}
1954 		if (wpid == pid && WIFSTOPPED(status)) {
1955 			warning("init: %s stopped, restarting\n",
1956 			    _PATH_RUNDOWN);
1957 			kill(pid, SIGCONT);
1958 			wpid = -1;
1959 		}
1960 	} while (wpid != pid && !clang);
1961 
1962 	/* Turn off the alarm */
1963 	alarm(0);
1964 
1965 	if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1966 	    requested_transition == catatonia) {
1967 		/*
1968 		 * /etc/rc.shutdown executed /sbin/reboot;
1969 		 * wait for the end quietly
1970 		 */
1971 		sigset_t s;
1972 
1973 		sigfillset(&s);
1974 		for (;;)
1975 			sigsuspend(&s);
1976 	}
1977 
1978 	if (!WIFEXITED(status)) {
1979 		warning("%s terminated abnormally, going to "
1980 		    "single user mode", _PATH_RUNDOWN);
1981 		return -2;
1982 	}
1983 
1984 	if ((status = WEXITSTATUS(status)) != 0)
1985 		warning("%s returned status %d", _PATH_RUNDOWN, status);
1986 
1987 	return status;
1988 }
1989 
1990 static char *
strk(char * p)1991 strk(char *p)
1992 {
1993 	static char *t;
1994 	char *q;
1995 	int c;
1996 
1997 	if (p)
1998 		t = p;
1999 	if (!t)
2000 		return 0;
2001 
2002 	c = *t;
2003 	while (c == ' ' || c == '\t' )
2004 		c = *++t;
2005 	if (!c) {
2006 		t = 0;
2007 		return 0;
2008 	}
2009 	q = t;
2010 	if (c == '\'') {
2011 		c = *++t;
2012 		q = t;
2013 		while (c && c != '\'')
2014 			c = *++t;
2015 		if (!c)  /* unterminated string */
2016 			q = t = 0;
2017 		else
2018 			*t++ = 0;
2019 	} else {
2020 		while (c && c != ' ' && c != '\t' )
2021 			c = *++t;
2022 		*t++ = 0;
2023 		if (!c)
2024 			t = 0;
2025 	}
2026 	return q;
2027 }
2028 
2029 #ifdef LOGIN_CAP
2030 static void
setprocresources(const char * cname)2031 setprocresources(const char *cname)
2032 {
2033 	login_cap_t *lc;
2034 	if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2035 		setusercontext(lc, (struct passwd*)NULL, 0,
2036 		    LOGIN_SETENV |
2037 		    LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2038 		    LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);
2039 		login_close(lc);
2040 	}
2041 }
2042 #endif
2043 
2044 /*
2045  * Run /etc/rc.final to execute scripts after all user processes have been
2046  * terminated.
2047  */
2048 static void
runfinal(void)2049 runfinal(void)
2050 {
2051 	struct stat sb;
2052 	pid_t other_pid, pid;
2053 	sigset_t mask;
2054 
2055 	/* Avoid any surprises. */
2056 	alarm(0);
2057 
2058 	/* rc.final is optional. */
2059 	if (stat(_PATH_RUNFINAL, &sb) == -1 && errno == ENOENT)
2060 		return;
2061 	if (access(_PATH_RUNFINAL, X_OK) != 0) {
2062 		warning("%s exists, but not executable", _PATH_RUNFINAL);
2063 		return;
2064 	}
2065 
2066 	pid = fork();
2067 	if (pid == 0) {
2068 		/*
2069 		 * Reopen stdin/stdout/stderr so that scripts can write to
2070 		 * console.
2071 		 */
2072 		close(0);
2073 		open(_PATH_DEVNULL, O_RDONLY);
2074 		close(1);
2075 		close(2);
2076 		open_console();
2077 		dup2(1, 2);
2078 		sigemptyset(&mask);
2079 		sigprocmask(SIG_SETMASK, &mask, NULL);
2080 		signal(SIGCHLD, SIG_DFL);
2081 		execl(_PATH_RUNFINAL, _PATH_RUNFINAL, NULL);
2082 		perror("execl(" _PATH_RUNFINAL ") failed");
2083 		exit(1);
2084 	}
2085 
2086 	/* Wait for rc.final script to exit */
2087 	while ((other_pid = waitpid(-1, NULL, 0)) != pid && other_pid > 0) {
2088 		continue;
2089 	}
2090 }
2091