2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Donn Seeley at Berkeley Software Design, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
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.
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
35 #include <sys/param.h>
36 #include <sys/boottrace.h>
37 #include <sys/ioctl.h>
39 #include <sys/mount.h>
40 #include <sys/reboot.h>
42 #include <sys/sysctl.h>
69 #include <login_cap.h>
73 #include "pathnames.h"
76 * Sleep times; used to prevent thrashing.
78 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
79 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
80 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
81 #define WINDOW_WAIT 3 /* wait N secs after starting window */
82 #define STALL_TIMEOUT 30 /* wait N secs after warning */
83 #define DEATH_WATCH 10 /* wait N secs for procs to die */
84 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
85 #define RESOURCE_RC "daemon"
86 #define RESOURCE_WINDOW "default"
87 #define RESOURCE_GETTY "default"
88 #define SCRIPT_ARGV_SIZE 3 /* size of argv passed to execute_script, can be increased if needed */
90 static void handle(sig_t, ...);
91 static void delset(sigset_t *, ...);
93 static void stall(const char *, ...) __printflike(1, 2);
94 static void warning(const char *, ...) __printflike(1, 2);
95 static void emergency(const char *, ...) __printflike(1, 2);
96 static void disaster(int);
97 static void revoke_ttys(void);
98 static int runshutdown(void);
99 static char *strk(char *);
100 static void runfinal(void);
103 * We really need a recursive typedef...
104 * The following at least guarantees that the return type of (*state_t)()
105 * is sufficiently wide to hold a function pointer.
107 typedef long (*state_func_t)(void);
108 typedef state_func_t (*state_t)(void);
110 static state_func_t single_user(void);
111 static state_func_t runcom(void);
112 static state_func_t read_ttys(void);
113 static state_func_t multi_user(void);
114 static state_func_t clean_ttys(void);
115 static state_func_t catatonia(void);
116 static state_func_t death(void);
117 static state_func_t death_single(void);
118 static state_func_t reroot(void);
119 static state_func_t reroot_phase_two(void);
121 static state_func_t run_script(const char *);
123 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
125 static bool Reboot = false;
126 static int howto = RB_AUTOBOOT;
128 static bool devfs = false;
129 static char *init_path_argv0;
131 static void transition(state_t);
132 static state_t requested_transition;
133 static state_t current_state = death_single;
135 static void execute_script(char *argv[]);
136 static void open_console(void);
137 static const char *get_shell(void);
138 static void replace_init(char *path);
139 static void write_stderr(const char *message);
141 typedef struct init_session {
142 pid_t se_process; /* controlling process */
143 time_t se_started; /* used to avoid thrashing */
144 int se_flags; /* status of session */
145 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
146 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
147 #define SE_IFEXISTS 0x4 /* session defined as "onifexists" */
148 #define SE_IFCONSOLE 0x8 /* session defined as "onifconsole" */
149 int se_nspace; /* spacing count */
150 char *se_device; /* filename of port */
151 char *se_getty; /* what to run on that port */
152 char *se_getty_argv_space; /* pre-parsed argument array space */
153 char **se_getty_argv; /* pre-parsed argument array */
154 char *se_window; /* window system (started only once) */
155 char *se_window_argv_space; /* pre-parsed argument array space */
156 char **se_window_argv; /* pre-parsed argument array */
157 char *se_type; /* default terminal type */
158 struct init_session *se_prev;
159 struct init_session *se_next;
162 static void free_session(session_t *);
163 static session_t *new_session(session_t *, struct ttyent *);
164 static session_t *sessions;
166 static char **construct_argv(char *);
167 static void start_window_system(session_t *);
168 static void collect_child(pid_t);
169 static pid_t start_getty(session_t *);
170 static void transition_handler(int);
171 static void alrm_handler(int);
172 static void setsecuritylevel(int);
173 static int getsecuritylevel(void);
174 static int setupargv(session_t *, struct ttyent *);
176 static void setprocresources(const char *);
180 static int start_session_db(void);
181 static void add_session(session_t *);
182 static void del_session(session_t *);
183 static session_t *find_session(pid_t);
184 static DB *session_db;
187 * The mother of all processes.
190 main(int argc, char *argv[])
192 state_t initial_transition = runcom;
193 char kenv_value[PATH_MAX];
198 /* Dispose of random users. */
200 errx(1, "%s", strerror(EPERM));
202 BOOTTRACE("init(8) starting...");
204 /* System V users like to reexec init. */
206 #ifdef COMPAT_SYSV_INIT
207 /* So give them what they want */
209 if (strlen(argv[1]) == 1) {
210 char runlevel = *argv[1];
214 case '0': /* halt + poweroff */
217 case '1': /* single-user */
220 case '6': /* reboot */
223 case 'c': /* block further logins */
226 case 'q': /* rescan /etc/ttys */
229 case 'r': /* remount root */
239 errx(1, "invalid run-level ``%s''", argv[1]);
242 errx(1, "already running");
245 init_path_argv0 = strdup(argv[0]);
246 if (init_path_argv0 == NULL)
250 * Note that this does NOT open a file...
251 * Does 'init' deserve its own facility number?
253 openlog("init", LOG_CONS, LOG_AUTH);
256 * Create an initial session.
258 if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
259 warning("initial setsid() failed: %m");
262 * Establish an initial user so that programs running
263 * single user do not freak out and die (like passwd).
265 if (setlogin("root") < 0)
266 warning("setlogin() failed: %m");
269 * This code assumes that we always get arguments through flags,
270 * never through bits set in some random machine register.
272 while ((c = getopt(argc, argv, "dsfr")) != -1)
278 initial_transition = single_user;
281 runcom_mode = FASTBOOT;
284 initial_transition = reroot_phase_two;
287 warning("unrecognized flag '-%c'", c);
292 warning("ignoring excess arguments");
295 * We catch or block signals rather than ignore them,
296 * so that they get reset on exec.
298 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
299 SIGXCPU, SIGXFSZ, 0);
300 handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
301 SIGUSR1, SIGUSR2, SIGWINCH, 0);
302 handle(alrm_handler, SIGALRM, 0);
304 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
305 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
306 SIGALRM, SIGUSR1, SIGUSR2, SIGWINCH, 0);
307 sigprocmask(SIG_SETMASK, &mask, NULL);
308 sigemptyset(&sa.sa_mask);
310 sa.sa_handler = SIG_IGN;
311 sigaction(SIGTTIN, &sa, NULL);
312 sigaction(SIGTTOU, &sa, NULL);
321 if (kenv(KENV_GET, "init_exec", kenv_value, sizeof(kenv_value)) > 0) {
322 replace_init(kenv_value);
323 _exit(0); /* reboot */
326 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
327 state_func_t next_transition;
329 if ((next_transition = run_script(kenv_value)) != NULL)
330 initial_transition = (state_t) next_transition;
333 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
334 if (chdir(kenv_value) != 0 || chroot(".") != 0)
335 warning("Can't chroot to %s: %m", kenv_value);
339 * Additional check if devfs needs to be mounted:
340 * If "/" and "/dev" have the same device number,
341 * then it hasn't been mounted yet.
348 root_devno = stst.st_dev;
349 if (stat("/dev", &stst) != 0)
350 warning("Can't stat /dev: %m");
351 else if (stst.st_dev == root_devno)
360 char _fstype[] = "fstype";
361 char _devfs[] = "devfs";
362 char _fspath[] = "fspath";
363 char _path_dev[]= _PATH_DEV;
365 iov[0].iov_base = _fstype;
366 iov[0].iov_len = sizeof(_fstype);
367 iov[1].iov_base = _devfs;
368 iov[1].iov_len = sizeof(_devfs);
369 iov[2].iov_base = _fspath;
370 iov[2].iov_len = sizeof(_fspath);
372 * Try to avoid the trailing slash in _PATH_DEV.
373 * Be *very* defensive.
375 s = strdup(_PATH_DEV);
378 if (i > 0 && s[i - 1] == '/')
381 iov[3].iov_len = strlen(s) + 1;
383 iov[3].iov_base = _path_dev;
384 iov[3].iov_len = sizeof(_path_dev);
391 if (initial_transition != reroot_phase_two) {
393 * Unmount reroot leftovers. This runs after init(8)
394 * gets reexecuted after reroot_phase_two() is done.
396 error = unmount(_PATH_REROOT, MNT_FORCE);
397 if (error != 0 && errno != EINVAL)
398 warning("Cannot unmount %s: %m", _PATH_REROOT);
402 * Start the state machine.
404 transition(initial_transition);
407 * Should never reach here.
413 * Associate a function with a signal handler.
416 handle(sig_t handler, ...)
420 sigset_t mask_everything;
422 va_start(ap, handler);
424 sa.sa_handler = handler;
425 sigfillset(&mask_everything);
427 while ((sig = va_arg(ap, int)) != 0) {
428 sa.sa_mask = mask_everything;
429 /* XXX SA_RESTART? */
430 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
431 sigaction(sig, &sa, NULL);
437 * Delete a set of signals from a mask.
440 delset(sigset_t *maskp, ...)
446 while ((sig = va_arg(ap, int)) != 0)
447 sigdelset(maskp, sig);
452 * Log a message and sleep for a while (to give someone an opportunity
453 * to read it and to save log or hardcopy output if the problem is chronic).
454 * NB: should send a message to the session logger to avoid blocking.
457 stall(const char *message, ...)
460 va_start(ap, message);
462 vsyslog(LOG_ALERT, message, ap);
464 sleep(STALL_TIMEOUT);
468 * Like stall(), but doesn't sleep.
469 * If cpp had variadic macros, the two functions could be #defines for another.
470 * NB: should send a message to the session logger to avoid blocking.
473 warning(const char *message, ...)
476 va_start(ap, message);
478 vsyslog(LOG_ALERT, message, ap);
483 * Log an emergency message.
484 * NB: should send a message to the session logger to avoid blocking.
487 emergency(const char *message, ...)
490 va_start(ap, message);
492 vsyslog(LOG_EMERG, message, ap);
497 * Catch an unexpected signal.
503 emergency("fatal signal: %s",
504 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
506 sleep(STALL_TIMEOUT);
507 _exit(sig); /* reboot */
511 * Get the security level of the kernel.
514 getsecuritylevel(void)
516 #ifdef KERN_SECURELVL
517 int name[2], curlevel;
521 name[1] = KERN_SECURELVL;
522 len = sizeof curlevel;
523 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
524 emergency("cannot get kernel security level: %m");
534 * Set the security level of the kernel.
537 setsecuritylevel(int newlevel)
539 #ifdef KERN_SECURELVL
540 int name[2], curlevel;
542 curlevel = getsecuritylevel();
543 if (newlevel == curlevel)
546 name[1] = KERN_SECURELVL;
547 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
549 "cannot change kernel security level from %d to %d: %m",
554 warning("kernel security level changed from %d to %d",
561 * Change states in the finite state machine.
562 * The initial state is passed as an argument.
565 transition(state_t s)
570 current_state = (state_t) (*current_state)();
574 * Start a session and allocate a controlling terminal.
575 * Only called by children of init after forking.
583 * Try to open /dev/console. Open the device with O_NONBLOCK to
584 * prevent potential blocking on a carrier.
586 revoke(_PATH_CONSOLE);
587 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
588 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
589 if (login_tty(fd) == 0)
594 /* No luck. Log output to file if possible. */
595 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
596 stall("cannot open null device.");
599 if (fd != STDIN_FILENO) {
600 dup2(fd, STDIN_FILENO);
603 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
605 dup2(STDIN_FILENO, STDOUT_FILENO);
606 else if (fd != STDOUT_FILENO) {
607 dup2(fd, STDOUT_FILENO);
610 dup2(STDOUT_FILENO, STDERR_FILENO);
616 static char kenv_value[PATH_MAX];
618 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
625 write_stderr(const char *message)
628 write(STDERR_FILENO, message, strlen(message));
632 read_file(const char *path, void **bufp, size_t *bufsizep)
640 fd = open(path, O_RDONLY);
642 emergency("%s: %m", path);
646 error = fstat(fd, &sb);
648 emergency("fstat: %m");
653 bufsize = sb.st_size;
654 buf = malloc(bufsize);
656 emergency("malloc: %m");
661 nbytes = read(fd, buf, bufsize);
662 if (nbytes != (ssize_t)bufsize) {
663 emergency("read: %m");
671 emergency("close: %m");
683 create_file(const char *path, const void *buf, size_t bufsize)
688 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
690 emergency("%s: %m", path);
694 nbytes = write(fd, buf, bufsize);
695 if (nbytes != (ssize_t)bufsize) {
696 emergency("write: %m");
703 emergency("close: %m");
711 mount_tmpfs(const char *fspath)
719 memset(errmsg, 0, sizeof(errmsg));
720 build_iovec(&iov, &iovlen, "fstype",
721 __DECONST(void *, "tmpfs"), (size_t)-1);
722 build_iovec(&iov, &iovlen, "fspath",
723 __DECONST(void *, fspath), (size_t)-1);
724 build_iovec(&iov, &iovlen, "errmsg",
725 errmsg, sizeof(errmsg));
727 error = nmount(iov, iovlen, 0);
729 if (*errmsg != '\0') {
730 emergency("cannot mount tmpfs on %s: %s: %m",
733 emergency("cannot mount tmpfs on %s: %m",
755 * Make sure nobody can interfere with our scheme.
756 * Ignore ESRCH, which can apparently happen when
757 * there are no processes to kill.
759 error = kill(-1, SIGKILL);
760 if (error != 0 && errno != ESRCH) {
761 emergency("kill(2) failed: %m");
766 * Copy the init binary into tmpfs, so that we can unmount
767 * the old rootfs without committing suicide.
769 error = read_file(init_path_argv0, &buf, &bufsize);
772 error = mount_tmpfs(_PATH_REROOT);
775 error = create_file(_PATH_REROOT_INIT, buf, bufsize);
780 * Execute the temporary init.
782 execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
783 emergency("cannot exec %s: %m", _PATH_REROOT_INIT);
786 emergency("reroot failed; going to single user mode");
788 return (state_func_t) single_user;
792 reroot_phase_two(void)
794 char init_path[PATH_MAX], *path, *path_component;
795 size_t init_path_len;
799 * Ask the kernel to mount the new rootfs.
801 error = reboot(RB_REROOT);
803 emergency("RB_REBOOT failed: %m");
808 * Figure out where the destination init(8) binary is. Note that
809 * the path could be different than what we've started with. Use
810 * the value from kenv, if set, or the one from sysctl otherwise.
811 * The latter defaults to a hardcoded value, but can be overridden
812 * by a build time option.
814 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
816 init_path_len = sizeof(init_path);
817 error = sysctlbyname("kern.init_path",
818 init_path, &init_path_len, NULL, 0);
820 emergency("failed to retrieve kern.init_path: %m");
826 * Repeat the init search logic from sys/kern/init_path.c
828 path_component = init_path;
829 while ((path = strsep(&path_component, ":")) != NULL) {
831 * Execute init(8) from the new rootfs.
833 execl(path, path, NULL);
835 emergency("cannot exec init from %s: %m", init_path);
838 emergency("reroot failed; going to single user mode");
839 return (state_func_t) single_user;
843 * Bring the system up single user.
853 struct timeval tv, tn;
857 static const char banner[] =
858 "Enter root password, or ^D to go multi-user\n";
859 char *clear, *password;
866 /* Instead of going single user, let's reboot the machine */
867 BOOTTRACE("shutting down the system");
869 /* Run scripts after all processes have been terminated. */
871 if (reboot(howto) == -1) {
872 emergency("reboot(%#x) failed, %m", howto);
873 _exit(1); /* panic and reboot */
875 warning("reboot(%#x) returned", howto);
876 _exit(0); /* panic as well */
879 BOOTTRACE("going to single user mode");
882 if ((pid = fork()) == 0) {
884 * Start the single user session.
890 * Check the root password.
891 * We don't care if the console is 'on' by default;
892 * it's the only tty that can be 'off' and 'secure'.
894 typ = getttynam("console");
895 pp = getpwnam("root");
896 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
897 pp && *pp->pw_passwd) {
898 write_stderr(banner);
900 clear = getpass("Password:");
901 if (clear == NULL || *clear == '\0')
903 password = crypt(clear, pp->pw_passwd);
904 explicit_bzero(clear, _PASSWORD_LEN);
905 if (password != NULL &&
906 strcmp(password, pp->pw_passwd) == 0)
908 warning("single-user login failed\n");
920 #define SHREQUEST "Enter full pathname of shell or RETURN for "
921 write_stderr(SHREQUEST);
924 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
925 num != 0 && *cp != '\n' && cp < &altshell[127])
928 if (altshell[0] != '\0')
931 #endif /* DEBUGSHELL */
935 * We catch all the interesting ones,
936 * and those are reset to SIG_DFL on exec.
939 sigprocmask(SIG_SETMASK, &mask, NULL);
943 * If the default one doesn't work, try the Bourne shell.
951 emergency("can't exec %s for single user: %m", shell);
952 execv(_PATH_BSHELL, argv);
953 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
954 sleep(STALL_TIMEOUT);
960 * We are seriously hosed. Do our best.
962 emergency("can't fork single-user shell, trying again");
963 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
965 return (state_func_t) single_user;
968 requested_transition = 0;
970 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
975 warning("wait for single-user shell failed: %m; restarting");
976 return (state_func_t) single_user;
978 if (wpid == pid && WIFSTOPPED(status)) {
979 warning("init: shell stopped, restarting\n");
983 } while (wpid != pid && !requested_transition);
985 if (requested_transition)
986 return (state_func_t) requested_transition;
988 if (!WIFEXITED(status)) {
989 if (WTERMSIG(status) == SIGKILL) {
991 * reboot(8) killed shell?
993 warning("single user shell terminated.");
994 gettimeofday(&tv, NULL);
996 tv.tv_sec += STALL_TIMEOUT;
997 while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
998 tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1000 gettimeofday(&tn, NULL);
1004 warning("single user shell terminated, restarting");
1005 return (state_func_t) single_user;
1009 runcom_mode = FASTBOOT;
1010 return (state_func_t) runcom;
1014 * Run the system startup script.
1019 state_func_t next_transition;
1021 BOOTTRACE("/etc/rc starting...");
1022 if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1023 return next_transition;
1024 BOOTTRACE("/etc/rc finished");
1026 runcom_mode = AUTOBOOT; /* the default */
1027 return (state_func_t) read_ttys;
1031 execute_script(char *argv[])
1033 struct sigaction sa;
1034 char* sh_argv[3 + SCRIPT_ARGV_SIZE];
1035 const char *shell, *script;
1036 int error, sh_argv_len, i;
1038 bzero(&sa, sizeof(sa));
1039 sigemptyset(&sa.sa_mask);
1040 sa.sa_handler = SIG_IGN;
1041 sigaction(SIGTSTP, &sa, NULL);
1042 sigaction(SIGHUP, &sa, NULL);
1046 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1048 setprocresources(RESOURCE_RC);
1052 * Try to directly execute the script first. If it
1053 * fails, try the old method of passing the script path
1054 * to sh(1). Don't complain if it fails because of
1055 * the missing execute bit.
1058 error = access(script, X_OK);
1060 execv(script, argv);
1061 warning("can't directly exec %s: %m", script);
1062 } else if (errno != EACCES) {
1063 warning("can't access %s: %m", script);
1066 shell = get_shell();
1067 sh_argv[0] = __DECONST(char*, shell);
1070 if (strcmp(shell, _PATH_BSHELL) == 0) {
1071 sh_argv[1] = __DECONST(char*, "-o");
1072 sh_argv[2] = __DECONST(char*, "verify");
1076 for (i = 0; i != SCRIPT_ARGV_SIZE; ++i)
1077 sh_argv[i + sh_argv_len] = argv[i];
1078 execv(shell, sh_argv);
1079 stall("can't exec %s for %s: %m", shell, script);
1083 * Execute binary, replacing init(8) as PID 1.
1086 replace_init(char *path)
1088 char *argv[SCRIPT_ARGV_SIZE];
1093 execute_script(argv);
1097 * Run a shell script.
1098 * Returns 0 on success, otherwise the next transition to enter:
1099 * - single_user if fork/execv/waitpid failed, or if the script
1100 * terminated with a signal or exit code != 0.
1101 * - death_single if a SIGTERM was delivered to init(8).
1104 run_script(const char *script)
1108 char *argv[SCRIPT_ARGV_SIZE];
1111 shell = get_shell();
1113 if ((pid = fork()) == 0) {
1115 char _autoboot[] = "autoboot";
1117 argv[0] = __DECONST(char *, script);
1118 argv[1] = runcom_mode == AUTOBOOT ? _autoboot : NULL;
1121 execute_script(argv);
1122 sleep(STALL_TIMEOUT);
1123 _exit(1); /* force single user mode */
1127 emergency("can't fork for %s on %s: %m", shell, script);
1128 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1130 sleep(STALL_TIMEOUT);
1131 return (state_func_t) single_user;
1135 * Copied from single_user(). This is a bit paranoid.
1137 requested_transition = 0;
1139 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1140 collect_child(wpid);
1141 if (requested_transition == death_single ||
1142 requested_transition == reroot)
1143 return (state_func_t) requested_transition;
1147 warning("wait for %s on %s failed: %m; going to "
1148 "single user mode", shell, script);
1149 return (state_func_t) single_user;
1151 if (wpid == pid && WIFSTOPPED(status)) {
1152 warning("init: %s on %s stopped, restarting\n",
1157 } while (wpid != pid);
1159 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1160 requested_transition == catatonia) {
1161 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1169 if (!WIFEXITED(status)) {
1170 warning("%s on %s terminated abnormally, going to single "
1171 "user mode", shell, script);
1172 return (state_func_t) single_user;
1175 if (WEXITSTATUS(status))
1176 return (state_func_t) single_user;
1178 return (state_func_t) 0;
1182 * Open the session database.
1184 * NB: We could pass in the size here; is it necessary?
1187 start_session_db(void)
1189 if (session_db && (*session_db->close)(session_db))
1190 emergency("session database close: %m");
1191 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1192 emergency("session database open: %m");
1200 * Add a new login session.
1203 add_session(session_t *sp)
1208 key.data = &sp->se_process;
1209 key.size = sizeof sp->se_process;
1211 data.size = sizeof sp;
1213 if ((*session_db->put)(session_db, &key, &data, 0))
1214 emergency("insert %d: %m", sp->se_process);
1218 * Delete an old login session.
1221 del_session(session_t *sp)
1225 key.data = &sp->se_process;
1226 key.size = sizeof sp->se_process;
1228 if ((*session_db->del)(session_db, &key, 0))
1229 emergency("delete %d: %m", sp->se_process);
1233 * Look up a login session by pid.
1236 find_session(pid_t pid)
1243 key.size = sizeof pid;
1244 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1246 bcopy(data.data, (char *)&ret, sizeof(ret));
1251 * Construct an argument vector from a command line.
1254 construct_argv(char *command)
1257 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1260 if ((argv[argc++] = strk(command)) == NULL) {
1264 while ((argv[argc++] = strk((char *) 0)) != NULL)
1270 * Deallocate a session descriptor.
1273 free_session(session_t *sp)
1275 free(sp->se_device);
1278 free(sp->se_getty_argv_space);
1279 free(sp->se_getty_argv);
1281 if (sp->se_window) {
1282 free(sp->se_window);
1283 free(sp->se_window_argv_space);
1284 free(sp->se_window_argv);
1292 * Allocate a new session descriptor.
1293 * Mark it SE_PRESENT.
1296 new_session(session_t *sprev, struct ttyent *typ)
1300 if ((typ->ty_status & TTY_ON) == 0 ||
1301 typ->ty_name == 0 ||
1305 sp = (session_t *) calloc(1, sizeof (session_t));
1307 sp->se_flags |= SE_PRESENT;
1309 if ((typ->ty_status & TTY_IFEXISTS) != 0)
1310 sp->se_flags |= SE_IFEXISTS;
1312 if ((typ->ty_status & TTY_IFCONSOLE) != 0)
1313 sp->se_flags |= SE_IFCONSOLE;
1315 if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1318 if (setupargv(sp, typ) == 0) {
1324 if (sprev == NULL) {
1328 sprev->se_next = sp;
1329 sp->se_prev = sprev;
1336 * Calculate getty and if useful window argv vectors.
1339 setupargv(session_t *sp, struct ttyent *typ)
1344 free(sp->se_getty_argv_space);
1345 free(sp->se_getty_argv);
1347 if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1349 sp->se_getty_argv_space = strdup(sp->se_getty);
1350 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1351 if (sp->se_getty_argv == NULL) {
1352 warning("can't parse getty for port %s", sp->se_device);
1354 free(sp->se_getty_argv_space);
1355 sp->se_getty = sp->se_getty_argv_space = 0;
1358 if (sp->se_window) {
1359 free(sp->se_window);
1360 free(sp->se_window_argv_space);
1361 free(sp->se_window_argv);
1363 sp->se_window = sp->se_window_argv_space = 0;
1364 sp->se_window_argv = 0;
1365 if (typ->ty_window) {
1366 sp->se_window = strdup(typ->ty_window);
1367 sp->se_window_argv_space = strdup(sp->se_window);
1368 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1369 if (sp->se_window_argv == NULL) {
1370 warning("can't parse window for port %s",
1372 free(sp->se_window_argv_space);
1373 free(sp->se_window);
1374 sp->se_window = sp->se_window_argv_space = 0;
1380 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1385 * Walk the list of ttys and create sessions for each active line.
1390 session_t *sp, *snext;
1394 * Destroy any previous session state.
1395 * There shouldn't be any, but just in case...
1397 for (sp = sessions; sp; sp = snext) {
1398 snext = sp->se_next;
1402 if (start_session_db())
1403 return (state_func_t) single_user;
1406 * Allocate a session entry for each active port.
1407 * Note that sp starts at 0.
1409 while ((typ = getttyent()) != NULL)
1410 if ((snext = new_session(sp, typ)) != NULL)
1415 return (state_func_t) multi_user;
1419 * Start a window system running.
1422 start_window_system(session_t *sp)
1426 char term[64], *env[2];
1429 if ((pid = fork()) == -1) {
1430 emergency("can't fork for window system on port %s: %m",
1432 /* hope that getty fails and we can try again */
1436 waitpid(-1, &status, 0);
1440 /* reparent window process to the init to not make a zombie on exit */
1441 if ((pid = fork()) == -1) {
1442 emergency("can't fork for window system on port %s: %m",
1450 sigprocmask(SIG_SETMASK, &mask, NULL);
1453 emergency("setsid failed (window) %m");
1456 setprocresources(RESOURCE_WINDOW);
1459 /* Don't use malloc after fork */
1460 strcpy(term, "TERM=");
1461 strlcat(term, sp->se_type, sizeof(term));
1467 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1468 stall("can't exec window system '%s' for port %s: %m",
1469 sp->se_window_argv[0], sp->se_device);
1474 * Start a login session running.
1477 start_getty(session_t *sp)
1481 time_t current_time = time((time_t *) 0);
1483 char term[64], *env[2];
1485 if (current_time >= sp->se_started &&
1486 current_time - sp->se_started < GETTY_SPACING) {
1487 if (++sp->se_nspace > GETTY_NSPACE) {
1495 * fork(), not vfork() -- we can't afford to block.
1497 if ((pid = fork()) == -1) {
1498 emergency("can't fork for getty on port %s: %m", sp->se_device);
1506 warning("getty repeating too quickly on port %s, sleeping %d secs",
1507 sp->se_device, GETTY_SLEEP);
1508 sleep((unsigned) GETTY_SLEEP);
1511 if (sp->se_window) {
1512 start_window_system(sp);
1517 sigprocmask(SIG_SETMASK, &mask, NULL);
1520 setprocresources(RESOURCE_GETTY);
1523 /* Don't use malloc after fork */
1524 strcpy(term, "TERM=");
1525 strlcat(term, sp->se_type, sizeof(term));
1530 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1531 stall("can't exec getty '%s' for port %s: %m",
1532 sp->se_getty_argv[0], sp->se_device);
1537 * Return 1 if the session is defined as "onifexists"
1538 * or "onifconsole" and the device node does not exist.
1541 session_has_no_tty(session_t *sp)
1545 if ((sp->se_flags & SE_IFEXISTS) == 0 &&
1546 (sp->se_flags & SE_IFCONSOLE) == 0)
1549 fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0);
1551 if (errno == ENOENT)
1561 * Collect exit status for a child.
1562 * If an exiting login, start a new login running.
1565 collect_child(pid_t pid)
1567 session_t *sp, *sprev, *snext;
1572 if (! (sp = find_session(pid)))
1578 if (sp->se_flags & SE_SHUTDOWN ||
1579 session_has_no_tty(sp)) {
1580 if ((sprev = sp->se_prev) != NULL)
1581 sprev->se_next = sp->se_next;
1583 sessions = sp->se_next;
1584 if ((snext = sp->se_next) != NULL)
1585 snext->se_prev = sp->se_prev;
1590 if ((pid = start_getty(sp)) == -1) {
1591 /* serious trouble */
1592 requested_transition = clean_ttys;
1596 sp->se_process = pid;
1597 sp->se_started = time((time_t *) 0);
1602 get_current_state(void)
1605 if (current_state == single_user)
1606 return ("single-user");
1607 if (current_state == runcom)
1609 if (current_state == read_ttys)
1610 return ("read-ttys");
1611 if (current_state == multi_user)
1612 return ("multi-user");
1613 if (current_state == clean_ttys)
1614 return ("clean-ttys");
1615 if (current_state == catatonia)
1616 return ("catatonia");
1617 if (current_state == death)
1619 if (current_state == death_single)
1620 return ("death-single");
1625 boottrace_transition(int sig)
1631 action = "halt & poweroff";
1640 action = "powercycle";
1643 action = Reboot ? "reboot" : "single-user";
1646 BOOTTRACE("signal %d from %s", sig, get_current_state());
1650 /* Trace the shutdown reason. */
1651 SHUTTRACE("%s from %s", action, get_current_state());
1655 * Catch a signal and request a state transition.
1658 transition_handler(int sig)
1661 boottrace_transition(sig);
1664 if (current_state == read_ttys || current_state == multi_user ||
1665 current_state == clean_ttys || current_state == catatonia)
1666 requested_transition = clean_ttys;
1669 howto = RB_POWEROFF;
1674 if (sig == SIGWINCH)
1675 howto |= RB_POWERCYCLE;
1678 if (current_state == read_ttys || current_state == multi_user ||
1679 current_state == clean_ttys || current_state == catatonia)
1680 requested_transition = death;
1682 requested_transition = death_single;
1685 if (current_state == runcom || current_state == read_ttys ||
1686 current_state == clean_ttys ||
1687 current_state == multi_user || current_state == catatonia)
1688 requested_transition = catatonia;
1691 requested_transition = reroot;
1694 requested_transition = 0;
1700 * Take the system multiuser.
1705 static bool inmultiuser = false;
1709 requested_transition = 0;
1712 * If the administrator has not set the security level to -1
1713 * to indicate that the kernel should not run multiuser in secure
1714 * mode, and the run script has not set a higher level of security
1715 * than level 1, then put the kernel into secure mode.
1717 if (getsecuritylevel() == 0)
1718 setsecuritylevel(1);
1720 for (sp = sessions; sp; sp = sp->se_next) {
1723 if (session_has_no_tty(sp))
1725 if ((pid = start_getty(sp)) == -1) {
1726 /* serious trouble */
1727 requested_transition = clean_ttys;
1730 sp->se_process = pid;
1731 sp->se_started = time((time_t *) 0);
1735 if (requested_transition == 0 && !inmultiuser) {
1737 /* This marks the change from boot-time tracing to run-time. */
1738 RUNTRACE("multi-user start");
1740 while (!requested_transition)
1741 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1744 return (state_func_t) requested_transition;
1748 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1753 session_t *sp, *sprev;
1756 char *old_getty, *old_window, *old_type;
1759 * mark all sessions for death, (!SE_PRESENT)
1760 * as we find or create new ones they'll be marked as keepers,
1761 * we'll later nuke all the ones not found in /etc/ttys
1763 for (sp = sessions; sp != NULL; sp = sp->se_next)
1764 sp->se_flags &= ~SE_PRESENT;
1766 devlen = sizeof(_PATH_DEV) - 1;
1767 while ((typ = getttyent()) != NULL) {
1768 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1769 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1773 /* we want this one to live */
1774 sp->se_flags |= SE_PRESENT;
1775 if ((typ->ty_status & TTY_ON) == 0 ||
1776 typ->ty_getty == 0) {
1777 sp->se_flags |= SE_SHUTDOWN;
1778 kill(sp->se_process, SIGHUP);
1781 sp->se_flags &= ~SE_SHUTDOWN;
1782 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1783 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1784 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1785 if (setupargv(sp, typ) == 0) {
1786 warning("can't parse getty for port %s",
1788 sp->se_flags |= SE_SHUTDOWN;
1789 kill(sp->se_process, SIGHUP);
1791 else if ( !old_getty
1792 || (!old_type && sp->se_type)
1793 || (old_type && !sp->se_type)
1794 || (!old_window && sp->se_window)
1795 || (old_window && !sp->se_window)
1796 || (strcmp(old_getty, sp->se_getty) != 0)
1797 || (old_window && strcmp(old_window, sp->se_window) != 0)
1798 || (old_type && strcmp(old_type, sp->se_type) != 0)
1800 /* Don't set SE_SHUTDOWN here */
1803 kill(sp->se_process, SIGHUP);
1814 new_session(sprev, typ);
1820 * sweep through and kill all deleted sessions
1821 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1823 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1824 if ((sp->se_flags & SE_PRESENT) == 0) {
1825 sp->se_flags |= SE_SHUTDOWN;
1826 kill(sp->se_process, SIGHUP);
1830 return (state_func_t) multi_user;
1834 * Block further logins.
1841 for (sp = sessions; sp; sp = sp->se_next)
1842 sp->se_flags |= SE_SHUTDOWN;
1844 return (state_func_t) multi_user;
1851 alrm_handler(int sig)
1859 * Bring the system down to single user.
1867 /* Temporarily block suspend. */
1868 len = sizeof(blocked);
1870 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1871 &block, sizeof(block)) == -1)
1875 * Also revoke the TTY here. Because runshutdown() may reopen
1876 * the TTY whose getty we're killing here, there is no guarantee
1877 * runshutdown() will perform the initial open() call, causing
1878 * the terminal attributes to be misconfigured.
1882 /* Try to run the rc.shutdown script within a period of time */
1885 /* Unblock suspend if we blocked it. */
1887 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1888 &blocked, sizeof(blocked));
1890 return (state_func_t) death_single;
1894 * Do what is necessary to reinitialize single user mode or reboot
1895 * from an incomplete state.
1902 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1904 revoke(_PATH_CONSOLE);
1906 BOOTTRACE("start killing user processes");
1907 for (i = 0; i < 2; ++i) {
1908 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1909 return (state_func_t) single_user;
1914 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1916 while (!clang && errno != ECHILD);
1918 if (errno == ECHILD)
1919 return (state_func_t) single_user;
1922 warning("some processes would not die; ps axl advised");
1924 return (state_func_t) single_user;
1932 for (sp = sessions; sp; sp = sp->se_next) {
1933 sp->se_flags |= SE_SHUTDOWN;
1934 kill(sp->se_process, SIGHUP);
1935 revoke(sp->se_device);
1940 * Run the system shutdown script.
1942 * Exit codes: XXX I should document more
1943 * -2 shutdown script terminated abnormally
1944 * -1 fatal error - can't run script
1946 * >0 some error (exit code)
1953 int shutdowntimeout;
1955 char *argv[SCRIPT_ARGV_SIZE];
1958 BOOTTRACE("init(8): start rc.shutdown");
1961 * rc.shutdown is optional, so to prevent any unnecessary
1962 * complaints from the shell we simply don't run it if the
1963 * file does not exist. If the stat() here fails for other
1964 * reasons, we'll let the shell complain.
1966 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1969 if ((pid = fork()) == 0) {
1970 char _reboot[] = "reboot";
1971 char _single[] = "single";
1972 char _path_rundown[] = _PATH_RUNDOWN;
1974 argv[0] = _path_rundown;
1975 argv[1] = Reboot ? _reboot : _single;
1978 execute_script(argv);
1979 _exit(1); /* force single user mode */
1983 emergency("can't fork for %s: %m", _PATH_RUNDOWN);
1984 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1986 sleep(STALL_TIMEOUT);
1990 len = sizeof(shutdowntimeout);
1991 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1992 NULL, 0) == -1 || shutdowntimeout < 2)
1993 shutdowntimeout = DEATH_SCRIPT;
1994 alarm(shutdowntimeout);
1997 * Copied from single_user(). This is a bit paranoid.
1998 * Use the same ALRM handler.
2001 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
2002 collect_child(wpid);
2004 /* we were waiting for the sub-shell */
2005 kill(wpid, SIGTERM);
2006 warning("timeout expired for %s: %m; going to "
2007 "single user mode", _PATH_RUNDOWN);
2008 BOOTTRACE("rc.shutdown's %d sec timeout expired",
2015 warning("wait for %s failed: %m; going to "
2016 "single user mode", _PATH_RUNDOWN);
2019 if (wpid == pid && WIFSTOPPED(status)) {
2020 warning("init: %s stopped, restarting\n",
2025 } while (wpid != pid && !clang);
2027 /* Turn off the alarm */
2030 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
2031 requested_transition == catatonia) {
2033 * /etc/rc.shutdown executed /sbin/reboot;
2034 * wait for the end quietly
2043 if (!WIFEXITED(status)) {
2044 warning("%s terminated abnormally, going to "
2045 "single user mode", _PATH_RUNDOWN);
2049 if ((status = WEXITSTATUS(status)) != 0)
2050 warning("%s returned status %d", _PATH_RUNDOWN, status);
2068 while (c == ' ' || c == '\t' )
2078 while (c && c != '\'')
2080 if (!c) /* unterminated string */
2085 while (c && c != ' ' && c != '\t' )
2096 setprocresources(const char *cname)
2099 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2100 setusercontext(lc, (struct passwd*)NULL, 0,
2102 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2103 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);
2110 * Run /etc/rc.final to execute scripts after all user processes have been
2117 pid_t other_pid, pid;
2120 /* Avoid any surprises. */
2123 /* rc.final is optional. */
2124 if (stat(_PATH_RUNFINAL, &sb) == -1 && errno == ENOENT)
2126 if (access(_PATH_RUNFINAL, X_OK) != 0) {
2127 warning("%s exists, but not executable", _PATH_RUNFINAL);
2134 * Reopen stdin/stdout/stderr so that scripts can write to
2138 open(_PATH_DEVNULL, O_RDONLY);
2144 sigprocmask(SIG_SETMASK, &mask, NULL);
2145 signal(SIGCHLD, SIG_DFL);
2146 execl(_PATH_RUNFINAL, _PATH_RUNFINAL, NULL);
2147 perror("execl(" _PATH_RUNFINAL ") failed");
2151 /* Wait for rc.final script to exit */
2152 while ((other_pid = waitpid(-1, NULL, 0)) != pid && other_pid > 0) {