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
36 static const char copyright[] =
37 "@(#) Copyright (c) 1991, 1993\n\
38 The Regents of the University of California. All rights reserved.\n";
43 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
45 static const char rcsid[] =
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
52 #include <sys/mount.h>
53 #include <sys/sysctl.h>
72 #include <sys/reboot.h>
82 #include <login_cap.h>
86 #include "pathnames.h"
89 * Sleep times; used to prevent thrashing.
91 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
92 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
93 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
94 #define WINDOW_WAIT 3 /* wait N secs after starting window */
95 #define STALL_TIMEOUT 30 /* wait N secs after warning */
96 #define DEATH_WATCH 10 /* wait N secs for procs to die */
97 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
98 #define RESOURCE_RC "daemon"
99 #define RESOURCE_WINDOW "default"
100 #define RESOURCE_GETTY "default"
102 static void handle(sig_t, ...);
103 static void delset(sigset_t *, ...);
105 static void stall(const char *, ...) __printflike(1, 2);
106 static void warning(const char *, ...) __printflike(1, 2);
107 static void emergency(const char *, ...) __printflike(1, 2);
108 static void disaster(int);
109 static void badsys(int);
110 static void revoke_ttys(void);
111 static int runshutdown(void);
112 static char *strk(char *);
115 * We really need a recursive typedef...
116 * The following at least guarantees that the return type of (*state_t)()
117 * is sufficiently wide to hold a function pointer.
119 typedef long (*state_func_t)(void);
120 typedef state_func_t (*state_t)(void);
122 static state_func_t single_user(void);
123 static state_func_t runcom(void);
124 static state_func_t read_ttys(void);
125 static state_func_t multi_user(void);
126 static state_func_t clean_ttys(void);
127 static state_func_t catatonia(void);
128 static state_func_t death(void);
129 static state_func_t death_single(void);
130 static state_func_t reroot(void);
131 static state_func_t reroot_phase_two(void);
133 static state_func_t run_script(const char *);
135 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
139 static int Reboot = FALSE;
140 static int howto = RB_AUTOBOOT;
143 static char *init_path_argv0;
145 static void transition(state_t);
146 static state_t requested_transition;
147 static state_t current_state = death_single;
149 static void open_console(void);
150 static const char *get_shell(void);
151 static void write_stderr(const char *message);
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;
174 static void free_session(session_t *);
175 static session_t *new_session(session_t *, struct ttyent *);
176 static session_t *sessions;
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 *);
188 static void setprocresources(const char *);
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;
199 * The mother of all processes.
202 main(int argc, char *argv[])
204 state_t initial_transition = runcom;
205 char kenv_value[PATH_MAX];
210 /* Dispose of random users. */
212 errx(1, "%s", strerror(EPERM));
214 /* System V users like to reexec init. */
216 #ifdef COMPAT_SYSV_INIT
217 /* So give them what they want */
219 if (strlen(argv[1]) == 1) {
220 char runlevel = *argv[1];
224 case '0': /* halt + poweroff */
227 case '1': /* single-user */
230 case '6': /* reboot */
233 case 'c': /* block further logins */
236 case 'q': /* rescan /etc/ttys */
239 case 'r': /* remount root */
249 errx(1, "invalid run-level ``%s''", argv[1]);
252 errx(1, "already running");
255 init_path_argv0 = strdup(argv[0]);
256 if (init_path_argv0 == NULL)
260 * Note that this does NOT open a file...
261 * Does 'init' deserve its own facility number?
263 openlog("init", LOG_CONS, LOG_AUTH);
266 * Create an initial session.
268 if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
269 warning("initial setsid() failed: %m");
272 * Establish an initial user so that programs running
273 * single user do not freak out and die (like passwd).
275 if (setlogin("root") < 0)
276 warning("setlogin() failed: %m");
279 * This code assumes that we always get arguments through flags,
280 * never through bits set in some random machine register.
282 while ((c = getopt(argc, argv, "dsfr")) != -1)
288 initial_transition = single_user;
291 runcom_mode = FASTBOOT;
294 initial_transition = reroot_phase_two;
297 warning("unrecognized flag '-%c'", c);
302 warning("ignoring excess arguments");
305 * We catch or block signals rather than ignore them,
306 * so that they get reset on exec.
308 handle(badsys, SIGSYS, 0);
309 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
311 handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
312 SIGUSR1, SIGUSR2, SIGWINCH, 0);
313 handle(alrm_handler, SIGALRM, 0);
315 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
316 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
317 SIGALRM, SIGUSR1, SIGUSR2, SIGWINCH, 0);
318 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
319 sigemptyset(&sa.sa_mask);
321 sa.sa_handler = SIG_IGN;
322 sigaction(SIGTTIN, &sa, (struct sigaction *)0);
323 sigaction(SIGTTOU, &sa, (struct sigaction *)0);
332 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
333 state_func_t next_transition;
335 if ((next_transition = run_script(kenv_value)) != NULL)
336 initial_transition = (state_t) next_transition;
339 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
340 if (chdir(kenv_value) != 0 || chroot(".") != 0)
341 warning("Can't chroot to %s: %m", kenv_value);
345 * Additional check if devfs needs to be mounted:
346 * If "/" and "/dev" have the same device number,
347 * then it hasn't been mounted yet.
354 root_devno = stst.st_dev;
355 if (stat("/dev", &stst) != 0)
356 warning("Can't stat /dev: %m");
357 else if (stst.st_dev == root_devno)
366 char _fstype[] = "fstype";
367 char _devfs[] = "devfs";
368 char _fspath[] = "fspath";
369 char _path_dev[]= _PATH_DEV;
371 iov[0].iov_base = _fstype;
372 iov[0].iov_len = sizeof(_fstype);
373 iov[1].iov_base = _devfs;
374 iov[1].iov_len = sizeof(_devfs);
375 iov[2].iov_base = _fspath;
376 iov[2].iov_len = sizeof(_fspath);
378 * Try to avoid the trailing slash in _PATH_DEV.
379 * Be *very* defensive.
381 s = strdup(_PATH_DEV);
384 if (i > 0 && s[i - 1] == '/')
387 iov[3].iov_len = strlen(s) + 1;
389 iov[3].iov_base = _path_dev;
390 iov[3].iov_len = sizeof(_path_dev);
397 if (initial_transition != reroot_phase_two) {
399 * Unmount reroot leftovers. This runs after init(8)
400 * gets reexecuted after reroot_phase_two() is done.
402 error = unmount(_PATH_REROOT, MNT_FORCE);
403 if (error != 0 && errno != EINVAL)
404 warning("Cannot unmount %s: %m", _PATH_REROOT);
408 * Start the state machine.
410 transition(initial_transition);
413 * Should never reach here.
419 * Associate a function with a signal handler.
422 handle(sig_t handler, ...)
426 sigset_t mask_everything;
428 va_start(ap, handler);
430 sa.sa_handler = handler;
431 sigfillset(&mask_everything);
433 while ((sig = va_arg(ap, int)) != 0) {
434 sa.sa_mask = mask_everything;
435 /* XXX SA_RESTART? */
436 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
437 sigaction(sig, &sa, (struct sigaction *) 0);
443 * Delete a set of signals from a mask.
446 delset(sigset_t *maskp, ...)
452 while ((sig = va_arg(ap, int)) != 0)
453 sigdelset(maskp, sig);
458 * Log a message and sleep for a while (to give someone an opportunity
459 * to read it and to save log or hardcopy output if the problem is chronic).
460 * NB: should send a message to the session logger to avoid blocking.
463 stall(const char *message, ...)
466 va_start(ap, message);
468 vsyslog(LOG_ALERT, message, ap);
470 sleep(STALL_TIMEOUT);
474 * Like stall(), but doesn't sleep.
475 * If cpp had variadic macros, the two functions could be #defines for another.
476 * NB: should send a message to the session logger to avoid blocking.
479 warning(const char *message, ...)
482 va_start(ap, message);
484 vsyslog(LOG_ALERT, message, ap);
489 * Log an emergency message.
490 * NB: should send a message to the session logger to avoid blocking.
493 emergency(const char *message, ...)
496 va_start(ap, message);
498 vsyslog(LOG_EMERG, message, ap);
503 * Catch a SIGSYS signal.
505 * These may arise if a system does not support sysctl.
506 * We tolerate up to 25 of these, then throw in the towel.
511 static int badcount = 0;
519 * Catch an unexpected signal.
525 emergency("fatal signal: %s",
526 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
528 sleep(STALL_TIMEOUT);
529 _exit(sig); /* reboot */
533 * Get the security level of the kernel.
536 getsecuritylevel(void)
538 #ifdef KERN_SECURELVL
539 int name[2], curlevel;
543 name[1] = KERN_SECURELVL;
544 len = sizeof curlevel;
545 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
546 emergency("cannot get kernel security level: %s",
557 * Set the security level of the kernel.
560 setsecuritylevel(int newlevel)
562 #ifdef KERN_SECURELVL
563 int name[2], curlevel;
565 curlevel = getsecuritylevel();
566 if (newlevel == curlevel)
569 name[1] = KERN_SECURELVL;
570 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
572 "cannot change kernel security level from %d to %d: %s",
573 curlevel, newlevel, strerror(errno));
577 warning("kernel security level changed from %d to %d",
584 * Change states in the finite state machine.
585 * The initial state is passed as an argument.
588 transition(state_t s)
593 current_state = (state_t) (*current_state)();
597 * Start a session and allocate a controlling terminal.
598 * Only called by children of init after forking.
606 * Try to open /dev/console. Open the device with O_NONBLOCK to
607 * prevent potential blocking on a carrier.
609 revoke(_PATH_CONSOLE);
610 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
611 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
612 if (login_tty(fd) == 0)
617 /* No luck. Log output to file if possible. */
618 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
619 stall("cannot open null device.");
622 if (fd != STDIN_FILENO) {
623 dup2(fd, STDIN_FILENO);
626 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
628 dup2(STDIN_FILENO, STDOUT_FILENO);
629 else if (fd != STDOUT_FILENO) {
630 dup2(fd, STDOUT_FILENO);
633 dup2(STDOUT_FILENO, STDERR_FILENO);
639 static char kenv_value[PATH_MAX];
641 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
648 write_stderr(const char *message)
651 write(STDERR_FILENO, message, strlen(message));
655 read_file(const char *path, void **bufp, size_t *bufsizep)
663 fd = open(path, O_RDONLY);
665 emergency("%s: %s", path, strerror(errno));
669 error = fstat(fd, &sb);
671 emergency("fstat: %s", strerror(errno));
676 bufsize = sb.st_size;
677 buf = malloc(bufsize);
679 emergency("malloc: %s", strerror(errno));
684 nbytes = read(fd, buf, bufsize);
685 if (nbytes != (ssize_t)bufsize) {
686 emergency("read: %s", strerror(errno));
694 emergency("close: %s", strerror(errno));
706 create_file(const char *path, const void *buf, size_t bufsize)
711 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
713 emergency("%s: %s", path, strerror(errno));
717 nbytes = write(fd, buf, bufsize);
718 if (nbytes != (ssize_t)bufsize) {
719 emergency("write: %s", strerror(errno));
726 emergency("close: %s", strerror(errno));
734 mount_tmpfs(const char *fspath)
742 memset(errmsg, 0, sizeof(errmsg));
743 build_iovec(&iov, &iovlen, "fstype",
744 __DECONST(void *, "tmpfs"), (size_t)-1);
745 build_iovec(&iov, &iovlen, "fspath",
746 __DECONST(void *, fspath), (size_t)-1);
747 build_iovec(&iov, &iovlen, "errmsg",
748 errmsg, sizeof(errmsg));
750 error = nmount(iov, iovlen, 0);
752 if (*errmsg != '\0') {
753 emergency("cannot mount tmpfs on %s: %s: %s",
754 fspath, errmsg, strerror(errno));
756 emergency("cannot mount tmpfs on %s: %s",
757 fspath, strerror(errno));
778 * Make sure nobody can interfere with our scheme.
779 * Ignore ESRCH, which can apparently happen when
780 * there are no processes to kill.
782 error = kill(-1, SIGKILL);
783 if (error != 0 && errno != ESRCH) {
784 emergency("kill(2) failed: %s", strerror(errno));
789 * Copy the init binary into tmpfs, so that we can unmount
790 * the old rootfs without committing suicide.
792 error = read_file(init_path_argv0, &buf, &bufsize);
795 error = mount_tmpfs(_PATH_REROOT);
798 error = create_file(_PATH_REROOT_INIT, buf, bufsize);
803 * Execute the temporary init.
805 execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
806 emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
809 emergency("reroot failed; going to single user mode");
811 return (state_func_t) single_user;
815 reroot_phase_two(void)
817 char init_path[PATH_MAX], *path, *path_component;
818 size_t init_path_len;
822 * Ask the kernel to mount the new rootfs.
824 error = reboot(RB_REROOT);
826 emergency("RB_REBOOT failed: %s", strerror(errno));
831 * Figure out where the destination init(8) binary is. Note that
832 * the path could be different than what we've started with. Use
833 * the value from kenv, if set, or the one from sysctl otherwise.
834 * The latter defaults to a hardcoded value, but can be overridden
835 * by a build time option.
837 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
839 init_path_len = sizeof(init_path);
840 error = sysctlbyname("kern.init_path",
841 init_path, &init_path_len, NULL, 0);
843 emergency("failed to retrieve kern.init_path: %s",
850 * Repeat the init search logic from sys/kern/init_path.c
852 path_component = init_path;
853 while ((path = strsep(&path_component, ":")) != NULL) {
855 * Execute init(8) from the new rootfs.
857 execl(path, path, NULL);
859 emergency("cannot exec init from %s: %s", init_path, strerror(errno));
862 emergency("reroot failed; going to single user mode");
863 return (state_func_t) single_user;
867 * Bring the system up single user.
877 struct timeval tv, tn;
881 static const char banner[] =
882 "Enter root password, or ^D to go multi-user\n";
883 char *clear, *password;
890 /* Instead of going single user, let's reboot the machine */
892 if (reboot(howto) == -1) {
893 emergency("reboot(%#x) failed, %s", howto,
895 _exit(1); /* panic and reboot */
897 warning("reboot(%#x) returned", howto);
898 _exit(0); /* panic as well */
903 if ((pid = fork()) == 0) {
905 * Start the single user session.
911 * Check the root password.
912 * We don't care if the console is 'on' by default;
913 * it's the only tty that can be 'off' and 'secure'.
915 typ = getttynam("console");
916 pp = getpwnam("root");
917 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
918 pp && *pp->pw_passwd) {
919 write_stderr(banner);
921 clear = getpass("Password:");
922 if (clear == NULL || *clear == '\0')
924 password = crypt(clear, pp->pw_passwd);
925 bzero(clear, _PASSWORD_LEN);
926 if (password != NULL &&
927 strcmp(password, pp->pw_passwd) == 0)
929 warning("single-user login failed\n");
941 #define SHREQUEST "Enter full pathname of shell or RETURN for "
942 write_stderr(SHREQUEST);
945 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
946 num != 0 && *cp != '\n' && cp < &altshell[127])
949 if (altshell[0] != '\0')
952 #endif /* DEBUGSHELL */
956 * We catch all the interesting ones,
957 * and those are reset to SIG_DFL on exec.
960 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
964 * If the default one doesn't work, try the Bourne shell.
972 emergency("can't exec %s for single user: %m", shell);
973 execv(_PATH_BSHELL, argv);
974 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
975 sleep(STALL_TIMEOUT);
981 * We are seriously hosed. Do our best.
983 emergency("can't fork single-user shell, trying again");
984 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
986 return (state_func_t) single_user;
989 requested_transition = 0;
991 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
996 warning("wait for single-user shell failed: %m; restarting");
997 return (state_func_t) single_user;
999 if (wpid == pid && WIFSTOPPED(status)) {
1000 warning("init: shell stopped, restarting\n");
1004 } while (wpid != pid && !requested_transition);
1006 if (requested_transition)
1007 return (state_func_t) requested_transition;
1009 if (!WIFEXITED(status)) {
1010 if (WTERMSIG(status) == SIGKILL) {
1012 * reboot(8) killed shell?
1014 warning("single user shell terminated.");
1015 gettimeofday(&tv, NULL);
1017 tv.tv_sec += STALL_TIMEOUT;
1018 while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1019 tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1021 gettimeofday(&tn, NULL);
1025 warning("single user shell terminated, restarting");
1026 return (state_func_t) single_user;
1030 runcom_mode = FASTBOOT;
1031 return (state_func_t) runcom;
1035 * Run the system startup script.
1040 state_func_t next_transition;
1042 if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1043 return next_transition;
1045 runcom_mode = AUTOBOOT; /* the default */
1046 return (state_func_t) read_ttys;
1050 * Run a shell script.
1051 * Returns 0 on success, otherwise the next transition to enter:
1052 * - single_user if fork/execv/waitpid failed, or if the script
1053 * terminated with a signal or exit code != 0.
1054 * - death_single if a SIGTERM was delivered to init(8).
1057 run_script(const char *script)
1063 struct sigaction sa;
1065 shell = get_shell();
1067 if ((pid = fork()) == 0) {
1068 sigemptyset(&sa.sa_mask);
1070 sa.sa_handler = SIG_IGN;
1071 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1072 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1077 char _autoboot[] = "autoboot";
1080 argv[1] = __DECONST(char *, script);
1081 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1084 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1087 setprocresources(RESOURCE_RC);
1091 * Try to directly execute the script first. If it
1092 * fails, try the old method of passing the script path
1093 * to sh(1). Don't complain if it fails because of
1094 * the missing execute bit.
1096 error = access(script, X_OK);
1098 execv(script, argv + 1);
1099 warning("can't exec %s: %m", script);
1100 } else if (errno != EACCES) {
1101 warning("can't access %s: %m", script);
1105 stall("can't exec %s for %s: %m", shell, script);
1106 _exit(1); /* force single user mode */
1110 emergency("can't fork for %s on %s: %m", shell, script);
1111 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1113 sleep(STALL_TIMEOUT);
1114 return (state_func_t) single_user;
1118 * Copied from single_user(). This is a bit paranoid.
1120 requested_transition = 0;
1122 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1123 collect_child(wpid);
1125 if (requested_transition == death_single ||
1126 requested_transition == reroot)
1127 return (state_func_t) requested_transition;
1130 warning("wait for %s on %s failed: %m; going to "
1131 "single user mode", shell, script);
1132 return (state_func_t) single_user;
1134 if (wpid == pid && WIFSTOPPED(status)) {
1135 warning("init: %s on %s stopped, restarting\n",
1140 } while (wpid != pid);
1142 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1143 requested_transition == catatonia) {
1144 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1152 if (!WIFEXITED(status)) {
1153 warning("%s on %s terminated abnormally, going to single "
1154 "user mode", shell, script);
1155 return (state_func_t) single_user;
1158 if (WEXITSTATUS(status))
1159 return (state_func_t) single_user;
1161 return (state_func_t) 0;
1165 * Open the session database.
1167 * NB: We could pass in the size here; is it necessary?
1170 start_session_db(void)
1172 if (session_db && (*session_db->close)(session_db))
1173 emergency("session database close: %s", strerror(errno));
1174 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1175 emergency("session database open: %s", strerror(errno));
1183 * Add a new login session.
1186 add_session(session_t *sp)
1191 key.data = &sp->se_process;
1192 key.size = sizeof sp->se_process;
1194 data.size = sizeof sp;
1196 if ((*session_db->put)(session_db, &key, &data, 0))
1197 emergency("insert %d: %s", sp->se_process, strerror(errno));
1201 * Delete an old login session.
1204 del_session(session_t *sp)
1208 key.data = &sp->se_process;
1209 key.size = sizeof sp->se_process;
1211 if ((*session_db->del)(session_db, &key, 0))
1212 emergency("delete %d: %s", sp->se_process, strerror(errno));
1216 * Look up a login session by pid.
1219 find_session(pid_t pid)
1226 key.size = sizeof pid;
1227 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1229 bcopy(data.data, (char *)&ret, sizeof(ret));
1234 * Construct an argument vector from a command line.
1237 construct_argv(char *command)
1240 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1243 if ((argv[argc++] = strk(command)) == NULL) {
1247 while ((argv[argc++] = strk((char *) 0)) != NULL)
1253 * Deallocate a session descriptor.
1256 free_session(session_t *sp)
1258 free(sp->se_device);
1261 free(sp->se_getty_argv_space);
1262 free(sp->se_getty_argv);
1264 if (sp->se_window) {
1265 free(sp->se_window);
1266 free(sp->se_window_argv_space);
1267 free(sp->se_window_argv);
1275 * Allocate a new session descriptor.
1276 * Mark it SE_PRESENT.
1279 new_session(session_t *sprev, struct ttyent *typ)
1283 if ((typ->ty_status & TTY_ON) == 0 ||
1284 typ->ty_name == 0 ||
1288 sp = (session_t *) calloc(1, sizeof (session_t));
1290 sp->se_flags |= SE_PRESENT;
1292 if ((typ->ty_status & TTY_IFEXISTS) != 0)
1293 sp->se_flags |= SE_IFEXISTS;
1295 if ((typ->ty_status & TTY_IFCONSOLE) != 0)
1296 sp->se_flags |= SE_IFCONSOLE;
1298 if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1301 if (setupargv(sp, typ) == 0) {
1307 if (sprev == NULL) {
1311 sprev->se_next = sp;
1312 sp->se_prev = sprev;
1319 * Calculate getty and if useful window argv vectors.
1322 setupargv(session_t *sp, struct ttyent *typ)
1327 free(sp->se_getty_argv_space);
1328 free(sp->se_getty_argv);
1330 if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1332 sp->se_getty_argv_space = strdup(sp->se_getty);
1333 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1334 if (sp->se_getty_argv == NULL) {
1335 warning("can't parse getty for port %s", sp->se_device);
1337 free(sp->se_getty_argv_space);
1338 sp->se_getty = sp->se_getty_argv_space = 0;
1341 if (sp->se_window) {
1342 free(sp->se_window);
1343 free(sp->se_window_argv_space);
1344 free(sp->se_window_argv);
1346 sp->se_window = sp->se_window_argv_space = 0;
1347 sp->se_window_argv = 0;
1348 if (typ->ty_window) {
1349 sp->se_window = strdup(typ->ty_window);
1350 sp->se_window_argv_space = strdup(sp->se_window);
1351 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1352 if (sp->se_window_argv == NULL) {
1353 warning("can't parse window for port %s",
1355 free(sp->se_window_argv_space);
1356 free(sp->se_window);
1357 sp->se_window = sp->se_window_argv_space = 0;
1363 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1368 * Walk the list of ttys and create sessions for each active line.
1373 session_t *sp, *snext;
1377 * Destroy any previous session state.
1378 * There shouldn't be any, but just in case...
1380 for (sp = sessions; sp; sp = snext) {
1381 snext = sp->se_next;
1385 if (start_session_db())
1386 return (state_func_t) single_user;
1389 * Allocate a session entry for each active port.
1390 * Note that sp starts at 0.
1392 while ((typ = getttyent()) != NULL)
1393 if ((snext = new_session(sp, typ)) != NULL)
1398 return (state_func_t) multi_user;
1402 * Start a window system running.
1405 start_window_system(session_t *sp)
1409 char term[64], *env[2];
1412 if ((pid = fork()) == -1) {
1413 emergency("can't fork for window system on port %s: %m",
1415 /* hope that getty fails and we can try again */
1419 waitpid(-1, &status, 0);
1423 /* reparent window process to the init to not make a zombie on exit */
1424 if ((pid = fork()) == -1) {
1425 emergency("can't fork for window system on port %s: %m",
1433 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1436 emergency("setsid failed (window) %m");
1439 setprocresources(RESOURCE_WINDOW);
1442 /* Don't use malloc after fork */
1443 strcpy(term, "TERM=");
1444 strlcat(term, sp->se_type, sizeof(term));
1450 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1451 stall("can't exec window system '%s' for port %s: %m",
1452 sp->se_window_argv[0], sp->se_device);
1457 * Start a login session running.
1460 start_getty(session_t *sp)
1464 time_t current_time = time((time_t *) 0);
1466 char term[64], *env[2];
1468 if (current_time >= sp->se_started &&
1469 current_time - sp->se_started < GETTY_SPACING) {
1470 if (++sp->se_nspace > GETTY_NSPACE) {
1478 * fork(), not vfork() -- we can't afford to block.
1480 if ((pid = fork()) == -1) {
1481 emergency("can't fork for getty on port %s: %m", sp->se_device);
1489 warning("getty repeating too quickly on port %s, sleeping %d secs",
1490 sp->se_device, GETTY_SLEEP);
1491 sleep((unsigned) GETTY_SLEEP);
1494 if (sp->se_window) {
1495 start_window_system(sp);
1500 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1503 setprocresources(RESOURCE_GETTY);
1506 /* Don't use malloc after fork */
1507 strcpy(term, "TERM=");
1508 strlcat(term, sp->se_type, sizeof(term));
1513 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1514 stall("can't exec getty '%s' for port %s: %m",
1515 sp->se_getty_argv[0], sp->se_device);
1520 * Return 1 if the session is defined as "onifexists"
1521 * or "onifconsole" and the device node does not exist.
1524 session_has_no_tty(session_t *sp)
1528 if ((sp->se_flags & SE_IFEXISTS) == 0 &&
1529 (sp->se_flags & SE_IFCONSOLE) == 0)
1532 fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0);
1534 if (errno == ENOENT)
1544 * Collect exit status for a child.
1545 * If an exiting login, start a new login running.
1548 collect_child(pid_t pid)
1550 session_t *sp, *sprev, *snext;
1555 if (! (sp = find_session(pid)))
1561 if (sp->se_flags & SE_SHUTDOWN ||
1562 session_has_no_tty(sp)) {
1563 if ((sprev = sp->se_prev) != NULL)
1564 sprev->se_next = sp->se_next;
1566 sessions = sp->se_next;
1567 if ((snext = sp->se_next) != NULL)
1568 snext->se_prev = sp->se_prev;
1573 if ((pid = start_getty(sp)) == -1) {
1574 /* serious trouble */
1575 requested_transition = clean_ttys;
1579 sp->se_process = pid;
1580 sp->se_started = time((time_t *) 0);
1585 * Catch a signal and request a state transition.
1588 transition_handler(int sig)
1593 if (current_state == read_ttys || current_state == multi_user ||
1594 current_state == clean_ttys || current_state == catatonia)
1595 requested_transition = clean_ttys;
1599 howto = sig == SIGUSR2 ? RB_POWEROFF : RB_POWERCYCLE;
1605 if (current_state == read_ttys || current_state == multi_user ||
1606 current_state == clean_ttys || current_state == catatonia)
1607 requested_transition = death;
1609 requested_transition = death_single;
1612 if (current_state == runcom || current_state == read_ttys ||
1613 current_state == clean_ttys ||
1614 current_state == multi_user || current_state == catatonia)
1615 requested_transition = catatonia;
1618 requested_transition = reroot;
1621 requested_transition = 0;
1627 * Take the system multiuser.
1635 requested_transition = 0;
1638 * If the administrator has not set the security level to -1
1639 * to indicate that the kernel should not run multiuser in secure
1640 * mode, and the run script has not set a higher level of security
1641 * than level 1, then put the kernel into secure mode.
1643 if (getsecuritylevel() == 0)
1644 setsecuritylevel(1);
1646 for (sp = sessions; sp; sp = sp->se_next) {
1649 if (session_has_no_tty(sp))
1651 if ((pid = start_getty(sp)) == -1) {
1652 /* serious trouble */
1653 requested_transition = clean_ttys;
1656 sp->se_process = pid;
1657 sp->se_started = time((time_t *) 0);
1661 while (!requested_transition)
1662 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1665 return (state_func_t) requested_transition;
1669 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1674 session_t *sp, *sprev;
1677 char *old_getty, *old_window, *old_type;
1680 * mark all sessions for death, (!SE_PRESENT)
1681 * as we find or create new ones they'll be marked as keepers,
1682 * we'll later nuke all the ones not found in /etc/ttys
1684 for (sp = sessions; sp != NULL; sp = sp->se_next)
1685 sp->se_flags &= ~SE_PRESENT;
1687 devlen = sizeof(_PATH_DEV) - 1;
1688 while ((typ = getttyent()) != NULL) {
1689 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1690 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1694 /* we want this one to live */
1695 sp->se_flags |= SE_PRESENT;
1696 if ((typ->ty_status & TTY_ON) == 0 ||
1697 typ->ty_getty == 0) {
1698 sp->se_flags |= SE_SHUTDOWN;
1699 kill(sp->se_process, SIGHUP);
1702 sp->se_flags &= ~SE_SHUTDOWN;
1703 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1704 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1705 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1706 if (setupargv(sp, typ) == 0) {
1707 warning("can't parse getty for port %s",
1709 sp->se_flags |= SE_SHUTDOWN;
1710 kill(sp->se_process, SIGHUP);
1712 else if ( !old_getty
1713 || (!old_type && sp->se_type)
1714 || (old_type && !sp->se_type)
1715 || (!old_window && sp->se_window)
1716 || (old_window && !sp->se_window)
1717 || (strcmp(old_getty, sp->se_getty) != 0)
1718 || (old_window && strcmp(old_window, sp->se_window) != 0)
1719 || (old_type && strcmp(old_type, sp->se_type) != 0)
1721 /* Don't set SE_SHUTDOWN here */
1724 kill(sp->se_process, SIGHUP);
1735 new_session(sprev, typ);
1741 * sweep through and kill all deleted sessions
1742 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1744 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1745 if ((sp->se_flags & SE_PRESENT) == 0) {
1746 sp->se_flags |= SE_SHUTDOWN;
1747 kill(sp->se_process, SIGHUP);
1751 return (state_func_t) multi_user;
1755 * Block further logins.
1762 for (sp = sessions; sp; sp = sp->se_next)
1763 sp->se_flags |= SE_SHUTDOWN;
1765 return (state_func_t) multi_user;
1772 alrm_handler(int sig)
1780 * Bring the system down to single user.
1788 /* Temporarily block suspend. */
1789 len = sizeof(blocked);
1791 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1792 &block, sizeof(block)) == -1)
1796 * Also revoke the TTY here. Because runshutdown() may reopen
1797 * the TTY whose getty we're killing here, there is no guarantee
1798 * runshutdown() will perform the initial open() call, causing
1799 * the terminal attributes to be misconfigured.
1803 /* Try to run the rc.shutdown script within a period of time */
1806 /* Unblock suspend if we blocked it. */
1808 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1809 &blocked, sizeof(blocked));
1811 return (state_func_t) death_single;
1815 * Do what is necessary to reinitialize single user mode or reboot
1816 * from an incomplete state.
1823 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1825 revoke(_PATH_CONSOLE);
1827 for (i = 0; i < 2; ++i) {
1828 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1829 return (state_func_t) single_user;
1834 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1836 while (clang == 0 && errno != ECHILD);
1838 if (errno == ECHILD)
1839 return (state_func_t) single_user;
1842 warning("some processes would not die; ps axl advised");
1844 return (state_func_t) single_user;
1852 for (sp = sessions; sp; sp = sp->se_next) {
1853 sp->se_flags |= SE_SHUTDOWN;
1854 kill(sp->se_process, SIGHUP);
1855 revoke(sp->se_device);
1860 * Run the system shutdown script.
1862 * Exit codes: XXX I should document more
1863 * -2 shutdown script terminated abnormally
1864 * -1 fatal error - can't run script
1866 * >0 some error (exit code)
1873 int shutdowntimeout;
1877 struct sigaction sa;
1881 * rc.shutdown is optional, so to prevent any unnecessary
1882 * complaints from the shell we simply don't run it if the
1883 * file does not exist. If the stat() here fails for other
1884 * reasons, we'll let the shell complain.
1886 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1889 shell = get_shell();
1891 if ((pid = fork()) == 0) {
1892 sigemptyset(&sa.sa_mask);
1894 sa.sa_handler = SIG_IGN;
1895 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1896 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1901 char _reboot[] = "reboot";
1902 char _single[] = "single";
1903 char _path_rundown[] = _PATH_RUNDOWN;
1906 argv[1] = _path_rundown;
1907 argv[2] = Reboot ? _reboot : _single;
1910 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1913 setprocresources(RESOURCE_RC);
1917 * Try to directly execute the script first. If it
1918 * fails, try the old method of passing the script path
1919 * to sh(1). Don't complain if it fails because of
1920 * the missing execute bit.
1922 error = access(_path_rundown, X_OK);
1924 execv(_path_rundown, argv + 1);
1925 warning("can't exec %s: %m", _path_rundown);
1926 } else if (errno != EACCES) {
1927 warning("can't access %s: %m", _path_rundown);
1931 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1932 _exit(1); /* force single user mode */
1936 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1937 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1939 sleep(STALL_TIMEOUT);
1943 len = sizeof(shutdowntimeout);
1944 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1945 NULL, 0) == -1 || shutdowntimeout < 2)
1946 shutdowntimeout = DEATH_SCRIPT;
1947 alarm(shutdowntimeout);
1950 * Copied from single_user(). This is a bit paranoid.
1951 * Use the same ALRM handler.
1954 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1955 collect_child(wpid);
1957 /* we were waiting for the sub-shell */
1958 kill(wpid, SIGTERM);
1959 warning("timeout expired for %s on %s: %m; going to "
1960 "single user mode", shell, _PATH_RUNDOWN);
1966 warning("wait for %s on %s failed: %m; going to "
1967 "single user mode", shell, _PATH_RUNDOWN);
1970 if (wpid == pid && WIFSTOPPED(status)) {
1971 warning("init: %s on %s stopped, restarting\n",
1972 shell, _PATH_RUNDOWN);
1976 } while (wpid != pid && !clang);
1978 /* Turn off the alarm */
1981 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1982 requested_transition == catatonia) {
1984 * /etc/rc.shutdown executed /sbin/reboot;
1985 * wait for the end quietly
1994 if (!WIFEXITED(status)) {
1995 warning("%s on %s terminated abnormally, going to "
1996 "single user mode", shell, _PATH_RUNDOWN);
2000 if ((status = WEXITSTATUS(status)) != 0)
2001 warning("%s returned status %d", _PATH_RUNDOWN, status);
2019 while (c == ' ' || c == '\t' )
2029 while (c && c != '\'')
2031 if (!c) /* unterminated string */
2036 while (c && c != ' ' && c != '\t' )
2047 setprocresources(const char *cname)
2050 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2051 setusercontext(lc, (struct passwd*)NULL, 0,
2052 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2053 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);