2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
43 static const char rcsid[] =
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
50 #include <sys/mount.h>
51 #include <sys/sysctl.h>
70 #include <sys/reboot.h>
80 #include <login_cap.h>
84 #include "pathnames.h"
87 * Sleep times; used to prevent thrashing.
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"
100 static void handle(sig_t, ...);
101 static void delset(sigset_t *, ...);
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 badsys(int);
108 static void revoke_ttys(void);
109 static int runshutdown(void);
110 static char *strk(char *);
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.
117 typedef long (*state_func_t)(void);
118 typedef state_func_t (*state_t)(void);
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);
131 static state_func_t run_script(const char *);
133 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
137 static int Reboot = FALSE;
138 static int howto = RB_AUTOBOOT;
141 static char *init_path_argv0;
143 static void transition(state_t);
144 static state_t requested_transition;
145 static state_t current_state = death_single;
147 static void open_console(void);
148 static const char *get_shell(void);
149 static void write_stderr(const char *message);
151 typedef struct init_session {
152 pid_t se_process; /* controlling process */
153 time_t se_started; /* used to avoid thrashing */
154 int se_flags; /* status of session */
155 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
156 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
157 int se_nspace; /* spacing count */
158 char *se_device; /* filename of port */
159 char *se_getty; /* what to run on that port */
160 char *se_getty_argv_space; /* pre-parsed argument array space */
161 char **se_getty_argv; /* pre-parsed argument array */
162 char *se_window; /* window system (started only once) */
163 char *se_window_argv_space; /* pre-parsed argument array space */
164 char **se_window_argv; /* pre-parsed argument array */
165 char *se_type; /* default terminal type */
166 struct init_session *se_prev;
167 struct init_session *se_next;
170 static void free_session(session_t *);
171 static session_t *new_session(session_t *, struct ttyent *);
172 static session_t *sessions;
174 static char **construct_argv(char *);
175 static void start_window_system(session_t *);
176 static void collect_child(pid_t);
177 static pid_t start_getty(session_t *);
178 static void transition_handler(int);
179 static void alrm_handler(int);
180 static void setsecuritylevel(int);
181 static int getsecuritylevel(void);
182 static int setupargv(session_t *, struct ttyent *);
184 static void setprocresources(const char *);
188 static int start_session_db(void);
189 static void add_session(session_t *);
190 static void del_session(session_t *);
191 static session_t *find_session(pid_t);
192 static DB *session_db;
195 * The mother of all processes.
198 main(int argc, char *argv[])
200 state_t initial_transition = runcom;
201 char kenv_value[PATH_MAX];
206 /* Dispose of random users. */
208 errx(1, "%s", strerror(EPERM));
210 /* System V users like to reexec init. */
212 #ifdef COMPAT_SYSV_INIT
213 /* So give them what they want */
215 if (strlen(argv[1]) == 1) {
216 char runlevel = *argv[1];
220 case '0': /* halt + poweroff */
223 case '1': /* single-user */
226 case '6': /* reboot */
229 case 'c': /* block further logins */
232 case 'q': /* rescan /etc/ttys */
235 case 'r': /* remount root */
245 errx(1, "invalid run-level ``%s''", argv[1]);
248 errx(1, "already running");
251 init_path_argv0 = strdup(argv[0]);
252 if (init_path_argv0 == NULL)
256 * Note that this does NOT open a file...
257 * Does 'init' deserve its own facility number?
259 openlog("init", LOG_CONS, LOG_AUTH);
262 * Create an initial session.
264 if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
265 warning("initial setsid() failed: %m");
268 * Establish an initial user so that programs running
269 * single user do not freak out and die (like passwd).
271 if (setlogin("root") < 0)
272 warning("setlogin() failed: %m");
275 * This code assumes that we always get arguments through flags,
276 * never through bits set in some random machine register.
278 while ((c = getopt(argc, argv, "dsfr")) != -1)
284 initial_transition = single_user;
287 runcom_mode = FASTBOOT;
290 initial_transition = reroot_phase_two;
293 warning("unrecognized flag '-%c'", c);
298 warning("ignoring excess arguments");
301 * We catch or block signals rather than ignore them,
302 * so that they get reset on exec.
304 handle(badsys, SIGSYS, 0);
305 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
307 handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
308 SIGUSR1, SIGUSR2, 0);
309 handle(alrm_handler, SIGALRM, 0);
311 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
312 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
313 SIGALRM, SIGUSR1, SIGUSR2, 0);
314 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
315 sigemptyset(&sa.sa_mask);
317 sa.sa_handler = SIG_IGN;
318 sigaction(SIGTTIN, &sa, (struct sigaction *)0);
319 sigaction(SIGTTOU, &sa, (struct sigaction *)0);
328 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
329 state_func_t next_transition;
331 if ((next_transition = run_script(kenv_value)) != NULL)
332 initial_transition = (state_t) next_transition;
335 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
336 if (chdir(kenv_value) != 0 || chroot(".") != 0)
337 warning("Can't chroot to %s: %m", kenv_value);
341 * Additional check if devfs needs to be mounted:
342 * If "/" and "/dev" have the same device number,
343 * then it hasn't been mounted yet.
350 root_devno = stst.st_dev;
351 if (stat("/dev", &stst) != 0)
352 warning("Can't stat /dev: %m");
353 else if (stst.st_dev == root_devno)
362 char _fstype[] = "fstype";
363 char _devfs[] = "devfs";
364 char _fspath[] = "fspath";
365 char _path_dev[]= _PATH_DEV;
367 iov[0].iov_base = _fstype;
368 iov[0].iov_len = sizeof(_fstype);
369 iov[1].iov_base = _devfs;
370 iov[1].iov_len = sizeof(_devfs);
371 iov[2].iov_base = _fspath;
372 iov[2].iov_len = sizeof(_fspath);
374 * Try to avoid the trailing slash in _PATH_DEV.
375 * Be *very* defensive.
377 s = strdup(_PATH_DEV);
380 if (i > 0 && s[i - 1] == '/')
383 iov[3].iov_len = strlen(s) + 1;
385 iov[3].iov_base = _path_dev;
386 iov[3].iov_len = sizeof(_path_dev);
393 if (initial_transition != reroot_phase_two) {
395 * Unmount reroot leftovers. This runs after init(8)
396 * gets reexecuted after reroot_phase_two() is done.
398 error = unmount(_PATH_REROOT, MNT_FORCE);
399 if (error != 0 && errno != EINVAL)
400 warning("Cannot unmount %s: %m", _PATH_REROOT);
404 * Start the state machine.
406 transition(initial_transition);
409 * Should never reach here.
415 * Associate a function with a signal handler.
418 handle(sig_t handler, ...)
422 sigset_t mask_everything;
424 va_start(ap, handler);
426 sa.sa_handler = handler;
427 sigfillset(&mask_everything);
429 while ((sig = va_arg(ap, int)) != 0) {
430 sa.sa_mask = mask_everything;
431 /* XXX SA_RESTART? */
432 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
433 sigaction(sig, &sa, (struct sigaction *) 0);
439 * Delete a set of signals from a mask.
442 delset(sigset_t *maskp, ...)
448 while ((sig = va_arg(ap, int)) != 0)
449 sigdelset(maskp, sig);
454 * Log a message and sleep for a while (to give someone an opportunity
455 * to read it and to save log or hardcopy output if the problem is chronic).
456 * NB: should send a message to the session logger to avoid blocking.
459 stall(const char *message, ...)
462 va_start(ap, message);
464 vsyslog(LOG_ALERT, message, ap);
466 sleep(STALL_TIMEOUT);
470 * Like stall(), but doesn't sleep.
471 * If cpp had variadic macros, the two functions could be #defines for another.
472 * NB: should send a message to the session logger to avoid blocking.
475 warning(const char *message, ...)
478 va_start(ap, message);
480 vsyslog(LOG_ALERT, message, ap);
485 * Log an emergency message.
486 * NB: should send a message to the session logger to avoid blocking.
489 emergency(const char *message, ...)
492 va_start(ap, message);
494 vsyslog(LOG_EMERG, message, ap);
499 * Catch a SIGSYS signal.
501 * These may arise if a system does not support sysctl.
502 * We tolerate up to 25 of these, then throw in the towel.
507 static int badcount = 0;
515 * Catch an unexpected signal.
521 emergency("fatal signal: %s",
522 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
524 sleep(STALL_TIMEOUT);
525 _exit(sig); /* reboot */
529 * Get the security level of the kernel.
532 getsecuritylevel(void)
534 #ifdef KERN_SECURELVL
535 int name[2], curlevel;
539 name[1] = KERN_SECURELVL;
540 len = sizeof curlevel;
541 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
542 emergency("cannot get kernel security level: %s",
553 * Set the security level of the kernel.
556 setsecuritylevel(int newlevel)
558 #ifdef KERN_SECURELVL
559 int name[2], curlevel;
561 curlevel = getsecuritylevel();
562 if (newlevel == curlevel)
565 name[1] = KERN_SECURELVL;
566 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
568 "cannot change kernel security level from %d to %d: %s",
569 curlevel, newlevel, strerror(errno));
573 warning("kernel security level changed from %d to %d",
580 * Change states in the finite state machine.
581 * The initial state is passed as an argument.
584 transition(state_t s)
589 current_state = (state_t) (*current_state)();
593 * Start a session and allocate a controlling terminal.
594 * Only called by children of init after forking.
602 * Try to open /dev/console. Open the device with O_NONBLOCK to
603 * prevent potential blocking on a carrier.
605 revoke(_PATH_CONSOLE);
606 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
607 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
608 if (login_tty(fd) == 0)
613 /* No luck. Log output to file if possible. */
614 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
615 stall("cannot open null device.");
618 if (fd != STDIN_FILENO) {
619 dup2(fd, STDIN_FILENO);
622 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
624 dup2(STDIN_FILENO, STDOUT_FILENO);
625 else if (fd != STDOUT_FILENO) {
626 dup2(fd, STDOUT_FILENO);
629 dup2(STDOUT_FILENO, STDERR_FILENO);
635 static char kenv_value[PATH_MAX];
637 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
644 write_stderr(const char *message)
647 write(STDERR_FILENO, message, strlen(message));
651 read_file(const char *path, void **bufp, size_t *bufsizep)
659 fd = open(path, O_RDONLY);
661 emergency("%s: %s", path, strerror(errno));
665 error = fstat(fd, &sb);
667 emergency("fstat: %s", strerror(errno));
672 bufsize = sb.st_size;
673 buf = malloc(bufsize);
675 emergency("malloc: %s", strerror(errno));
680 nbytes = read(fd, buf, bufsize);
681 if (nbytes != (ssize_t)bufsize) {
682 emergency("read: %s", strerror(errno));
690 emergency("close: %s", strerror(errno));
702 create_file(const char *path, const void *buf, size_t bufsize)
707 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
709 emergency("%s: %s", path, strerror(errno));
713 nbytes = write(fd, buf, bufsize);
714 if (nbytes != (ssize_t)bufsize) {
715 emergency("write: %s", strerror(errno));
722 emergency("close: %s", strerror(errno));
730 mount_tmpfs(const char *fspath)
738 memset(errmsg, 0, sizeof(errmsg));
739 build_iovec(&iov, &iovlen, "fstype",
740 __DECONST(void *, "tmpfs"), (size_t)-1);
741 build_iovec(&iov, &iovlen, "fspath",
742 __DECONST(void *, fspath), (size_t)-1);
743 build_iovec(&iov, &iovlen, "errmsg",
744 errmsg, sizeof(errmsg));
746 error = nmount(iov, iovlen, 0);
748 if (*errmsg != '\0') {
749 emergency("cannot mount tmpfs on %s: %s: %s",
750 fspath, errmsg, strerror(errno));
752 emergency("cannot mount tmpfs on %s: %s",
753 fspath, strerror(errno));
774 * Make sure nobody can interfere with our scheme.
775 * Ignore ESRCH, which can apparently happen when
776 * there are no processes to kill.
778 error = kill(-1, SIGKILL);
779 if (error != 0 && errno != ESRCH) {
780 emergency("kill(2) failed: %s", strerror(errno));
785 * Copy the init binary into tmpfs, so that we can unmount
786 * the old rootfs without committing suicide.
788 error = read_file(init_path_argv0, &buf, &bufsize);
791 error = mount_tmpfs(_PATH_REROOT);
794 error = create_file(_PATH_REROOT_INIT, buf, bufsize);
799 * Execute the temporary init.
801 execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
802 emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
805 emergency("reroot failed; going to single user mode");
807 return (state_func_t) single_user;
811 reroot_phase_two(void)
813 char init_path[PATH_MAX], *path, *path_component;
814 size_t init_path_len;
818 * Ask the kernel to mount the new rootfs.
820 error = reboot(RB_REROOT);
822 emergency("RB_REBOOT failed: %s", strerror(errno));
827 * Figure out where the destination init(8) binary is. Note that
828 * the path could be different than what we've started with. Use
829 * the value from kenv, if set, or the one from sysctl otherwise.
830 * The latter defaults to a hardcoded value, but can be overridden
831 * by a build time option.
833 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
835 init_path_len = sizeof(init_path);
836 error = sysctlbyname("kern.init_path",
837 init_path, &init_path_len, NULL, 0);
839 emergency("failed to retrieve kern.init_path: %s",
846 * Repeat the init search logic from sys/kern/init_path.c
848 path_component = init_path;
849 while ((path = strsep(&path_component, ":")) != NULL) {
851 * Execute init(8) from the new rootfs.
853 execl(path, path, NULL);
855 emergency("cannot exec init from %s: %s", init_path, strerror(errno));
858 emergency("reroot failed; going to single user mode");
859 return (state_func_t) single_user;
863 * Bring the system up single user.
873 struct timeval tv, tn;
877 static const char banner[] =
878 "Enter root password, or ^D to go multi-user\n";
879 char *clear, *password;
886 /* Instead of going single user, let's reboot the machine */
888 if (reboot(howto) == -1) {
889 emergency("reboot(%#x) failed, %s", howto,
891 _exit(1); /* panic and reboot */
893 warning("reboot(%#x) returned", howto);
894 _exit(0); /* panic as well */
899 if ((pid = fork()) == 0) {
901 * Start the single user session.
907 * Check the root password.
908 * We don't care if the console is 'on' by default;
909 * it's the only tty that can be 'off' and 'secure'.
911 typ = getttynam("console");
912 pp = getpwnam("root");
913 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
914 pp && *pp->pw_passwd) {
915 write_stderr(banner);
917 clear = getpass("Password:");
918 if (clear == NULL || *clear == '\0')
920 password = crypt(clear, pp->pw_passwd);
921 bzero(clear, _PASSWORD_LEN);
922 if (password == NULL ||
923 strcmp(password, pp->pw_passwd) == 0)
925 warning("single-user login failed\n");
937 #define SHREQUEST "Enter full pathname of shell or RETURN for "
938 write_stderr(SHREQUEST);
941 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
942 num != 0 && *cp != '\n' && cp < &altshell[127])
945 if (altshell[0] != '\0')
948 #endif /* DEBUGSHELL */
952 * We catch all the interesting ones,
953 * and those are reset to SIG_DFL on exec.
956 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
960 * If the default one doesn't work, try the Bourne shell.
968 emergency("can't exec %s for single user: %m", shell);
969 execv(_PATH_BSHELL, argv);
970 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
971 sleep(STALL_TIMEOUT);
977 * We are seriously hosed. Do our best.
979 emergency("can't fork single-user shell, trying again");
980 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
982 return (state_func_t) single_user;
985 requested_transition = 0;
987 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
992 warning("wait for single-user shell failed: %m; restarting");
993 return (state_func_t) single_user;
995 if (wpid == pid && WIFSTOPPED(status)) {
996 warning("init: shell stopped, restarting\n");
1000 } while (wpid != pid && !requested_transition);
1002 if (requested_transition)
1003 return (state_func_t) requested_transition;
1005 if (!WIFEXITED(status)) {
1006 if (WTERMSIG(status) == SIGKILL) {
1008 * reboot(8) killed shell?
1010 warning("single user shell terminated.");
1011 gettimeofday(&tv, NULL);
1013 tv.tv_sec += STALL_TIMEOUT;
1014 while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1015 tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1017 gettimeofday(&tn, NULL);
1021 warning("single user shell terminated, restarting");
1022 return (state_func_t) single_user;
1026 runcom_mode = FASTBOOT;
1027 return (state_func_t) runcom;
1031 * Run the system startup script.
1036 state_func_t next_transition;
1038 if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1039 return next_transition;
1041 runcom_mode = AUTOBOOT; /* the default */
1042 return (state_func_t) read_ttys;
1046 * Run a shell script.
1047 * Returns 0 on success, otherwise the next transition to enter:
1048 * - single_user if fork/execv/waitpid failed, or if the script
1049 * terminated with a signal or exit code != 0.
1050 * - death_single if a SIGTERM was delivered to init(8).
1053 run_script(const char *script)
1059 struct sigaction sa;
1061 shell = get_shell();
1063 if ((pid = fork()) == 0) {
1064 sigemptyset(&sa.sa_mask);
1066 sa.sa_handler = SIG_IGN;
1067 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1068 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1073 char _autoboot[] = "autoboot";
1076 argv[1] = __DECONST(char *, script);
1077 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1080 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1083 setprocresources(RESOURCE_RC);
1086 stall("can't exec %s for %s: %m", shell, script);
1087 _exit(1); /* force single user mode */
1091 emergency("can't fork for %s on %s: %m", shell, script);
1092 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1094 sleep(STALL_TIMEOUT);
1095 return (state_func_t) single_user;
1099 * Copied from single_user(). This is a bit paranoid.
1101 requested_transition = 0;
1103 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1104 collect_child(wpid);
1106 if (requested_transition == death_single ||
1107 requested_transition == reroot)
1108 return (state_func_t) requested_transition;
1111 warning("wait for %s on %s failed: %m; going to "
1112 "single user mode", shell, script);
1113 return (state_func_t) single_user;
1115 if (wpid == pid && WIFSTOPPED(status)) {
1116 warning("init: %s on %s stopped, restarting\n",
1121 } while (wpid != pid);
1123 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1124 requested_transition == catatonia) {
1125 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1133 if (!WIFEXITED(status)) {
1134 warning("%s on %s terminated abnormally, going to single "
1135 "user mode", shell, script);
1136 return (state_func_t) single_user;
1139 if (WEXITSTATUS(status))
1140 return (state_func_t) single_user;
1142 return (state_func_t) 0;
1146 * Open the session database.
1148 * NB: We could pass in the size here; is it necessary?
1151 start_session_db(void)
1153 if (session_db && (*session_db->close)(session_db))
1154 emergency("session database close: %s", strerror(errno));
1155 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1156 emergency("session database open: %s", strerror(errno));
1164 * Add a new login session.
1167 add_session(session_t *sp)
1172 key.data = &sp->se_process;
1173 key.size = sizeof sp->se_process;
1175 data.size = sizeof sp;
1177 if ((*session_db->put)(session_db, &key, &data, 0))
1178 emergency("insert %d: %s", sp->se_process, strerror(errno));
1182 * Delete an old login session.
1185 del_session(session_t *sp)
1189 key.data = &sp->se_process;
1190 key.size = sizeof sp->se_process;
1192 if ((*session_db->del)(session_db, &key, 0))
1193 emergency("delete %d: %s", sp->se_process, strerror(errno));
1197 * Look up a login session by pid.
1200 find_session(pid_t pid)
1207 key.size = sizeof pid;
1208 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1210 bcopy(data.data, (char *)&ret, sizeof(ret));
1215 * Construct an argument vector from a command line.
1218 construct_argv(char *command)
1221 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1224 if ((argv[argc++] = strk(command)) == NULL) {
1228 while ((argv[argc++] = strk((char *) 0)) != NULL)
1234 * Deallocate a session descriptor.
1237 free_session(session_t *sp)
1239 free(sp->se_device);
1242 free(sp->se_getty_argv_space);
1243 free(sp->se_getty_argv);
1245 if (sp->se_window) {
1246 free(sp->se_window);
1247 free(sp->se_window_argv_space);
1248 free(sp->se_window_argv);
1256 * Allocate a new session descriptor.
1257 * Mark it SE_PRESENT.
1260 new_session(session_t *sprev, struct ttyent *typ)
1265 if ((typ->ty_status & TTY_ON) == 0 ||
1266 typ->ty_name == 0 ||
1270 sp = (session_t *) calloc(1, sizeof (session_t));
1272 sp->se_flags |= SE_PRESENT;
1274 if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1278 * Attempt to open the device, if we get "device not configured"
1279 * then don't add the device to the session list.
1281 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1282 if (errno == ENXIO) {
1289 if (setupargv(sp, typ) == 0) {
1295 if (sprev == NULL) {
1299 sprev->se_next = sp;
1300 sp->se_prev = sprev;
1307 * Calculate getty and if useful window argv vectors.
1310 setupargv(session_t *sp, struct ttyent *typ)
1315 free(sp->se_getty_argv_space);
1316 free(sp->se_getty_argv);
1318 if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1320 sp->se_getty_argv_space = strdup(sp->se_getty);
1321 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1322 if (sp->se_getty_argv == NULL) {
1323 warning("can't parse getty for port %s", sp->se_device);
1325 free(sp->se_getty_argv_space);
1326 sp->se_getty = sp->se_getty_argv_space = 0;
1329 if (sp->se_window) {
1330 free(sp->se_window);
1331 free(sp->se_window_argv_space);
1332 free(sp->se_window_argv);
1334 sp->se_window = sp->se_window_argv_space = 0;
1335 sp->se_window_argv = 0;
1336 if (typ->ty_window) {
1337 sp->se_window = strdup(typ->ty_window);
1338 sp->se_window_argv_space = strdup(sp->se_window);
1339 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1340 if (sp->se_window_argv == NULL) {
1341 warning("can't parse window for port %s",
1343 free(sp->se_window_argv_space);
1344 free(sp->se_window);
1345 sp->se_window = sp->se_window_argv_space = 0;
1351 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1356 * Walk the list of ttys and create sessions for each active line.
1361 session_t *sp, *snext;
1365 * Destroy any previous session state.
1366 * There shouldn't be any, but just in case...
1368 for (sp = sessions; sp; sp = snext) {
1369 snext = sp->se_next;
1373 if (start_session_db())
1374 return (state_func_t) single_user;
1377 * Allocate a session entry for each active port.
1378 * Note that sp starts at 0.
1380 while ((typ = getttyent()) != NULL)
1381 if ((snext = new_session(sp, typ)) != NULL)
1386 return (state_func_t) multi_user;
1390 * Start a window system running.
1393 start_window_system(session_t *sp)
1397 char term[64], *env[2];
1400 if ((pid = fork()) == -1) {
1401 emergency("can't fork for window system on port %s: %m",
1403 /* hope that getty fails and we can try again */
1407 waitpid(-1, &status, 0);
1411 /* reparent window process to the init to not make a zombie on exit */
1412 if ((pid = fork()) == -1) {
1413 emergency("can't fork for window system on port %s: %m",
1421 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1424 emergency("setsid failed (window) %m");
1427 setprocresources(RESOURCE_WINDOW);
1430 /* Don't use malloc after fork */
1431 strcpy(term, "TERM=");
1432 strlcat(term, sp->se_type, sizeof(term));
1438 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1439 stall("can't exec window system '%s' for port %s: %m",
1440 sp->se_window_argv[0], sp->se_device);
1445 * Start a login session running.
1448 start_getty(session_t *sp)
1452 time_t current_time = time((time_t *) 0);
1454 char term[64], *env[2];
1456 if (current_time >= sp->se_started &&
1457 current_time - sp->se_started < GETTY_SPACING) {
1458 if (++sp->se_nspace > GETTY_NSPACE) {
1466 * fork(), not vfork() -- we can't afford to block.
1468 if ((pid = fork()) == -1) {
1469 emergency("can't fork for getty on port %s: %m", sp->se_device);
1477 warning("getty repeating too quickly on port %s, sleeping %d secs",
1478 sp->se_device, GETTY_SLEEP);
1479 sleep((unsigned) GETTY_SLEEP);
1482 if (sp->se_window) {
1483 start_window_system(sp);
1488 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1491 setprocresources(RESOURCE_GETTY);
1494 /* Don't use malloc after fork */
1495 strcpy(term, "TERM=");
1496 strlcat(term, sp->se_type, sizeof(term));
1501 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1502 stall("can't exec getty '%s' for port %s: %m",
1503 sp->se_getty_argv[0], sp->se_device);
1508 * Collect exit status for a child.
1509 * If an exiting login, start a new login running.
1512 collect_child(pid_t pid)
1514 session_t *sp, *sprev, *snext;
1519 if (! (sp = find_session(pid)))
1525 if (sp->se_flags & SE_SHUTDOWN) {
1526 if ((sprev = sp->se_prev) != NULL)
1527 sprev->se_next = sp->se_next;
1529 sessions = sp->se_next;
1530 if ((snext = sp->se_next) != NULL)
1531 snext->se_prev = sp->se_prev;
1536 if ((pid = start_getty(sp)) == -1) {
1537 /* serious trouble */
1538 requested_transition = clean_ttys;
1542 sp->se_process = pid;
1543 sp->se_started = time((time_t *) 0);
1548 * Catch a signal and request a state transition.
1551 transition_handler(int sig)
1556 if (current_state == read_ttys || current_state == multi_user ||
1557 current_state == clean_ttys || current_state == catatonia)
1558 requested_transition = clean_ttys;
1561 howto = RB_POWEROFF;
1567 if (current_state == read_ttys || current_state == multi_user ||
1568 current_state == clean_ttys || current_state == catatonia)
1569 requested_transition = death;
1571 requested_transition = death_single;
1574 if (current_state == runcom || current_state == read_ttys ||
1575 current_state == clean_ttys ||
1576 current_state == multi_user || current_state == catatonia)
1577 requested_transition = catatonia;
1580 requested_transition = reroot;
1583 requested_transition = 0;
1589 * Take the system multiuser.
1597 requested_transition = 0;
1600 * If the administrator has not set the security level to -1
1601 * to indicate that the kernel should not run multiuser in secure
1602 * mode, and the run script has not set a higher level of security
1603 * than level 1, then put the kernel into secure mode.
1605 if (getsecuritylevel() == 0)
1606 setsecuritylevel(1);
1608 for (sp = sessions; sp; sp = sp->se_next) {
1611 if ((pid = start_getty(sp)) == -1) {
1612 /* serious trouble */
1613 requested_transition = clean_ttys;
1616 sp->se_process = pid;
1617 sp->se_started = time((time_t *) 0);
1621 while (!requested_transition)
1622 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1625 return (state_func_t) requested_transition;
1629 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1634 session_t *sp, *sprev;
1637 char *old_getty, *old_window, *old_type;
1640 * mark all sessions for death, (!SE_PRESENT)
1641 * as we find or create new ones they'll be marked as keepers,
1642 * we'll later nuke all the ones not found in /etc/ttys
1644 for (sp = sessions; sp != NULL; sp = sp->se_next)
1645 sp->se_flags &= ~SE_PRESENT;
1647 devlen = sizeof(_PATH_DEV) - 1;
1648 while ((typ = getttyent()) != NULL) {
1649 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1650 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1654 /* we want this one to live */
1655 sp->se_flags |= SE_PRESENT;
1656 if ((typ->ty_status & TTY_ON) == 0 ||
1657 typ->ty_getty == 0) {
1658 sp->se_flags |= SE_SHUTDOWN;
1659 kill(sp->se_process, SIGHUP);
1662 sp->se_flags &= ~SE_SHUTDOWN;
1663 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1664 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1665 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1666 if (setupargv(sp, typ) == 0) {
1667 warning("can't parse getty for port %s",
1669 sp->se_flags |= SE_SHUTDOWN;
1670 kill(sp->se_process, SIGHUP);
1672 else if ( !old_getty
1673 || (!old_type && sp->se_type)
1674 || (old_type && !sp->se_type)
1675 || (!old_window && sp->se_window)
1676 || (old_window && !sp->se_window)
1677 || (strcmp(old_getty, sp->se_getty) != 0)
1678 || (old_window && strcmp(old_window, sp->se_window) != 0)
1679 || (old_type && strcmp(old_type, sp->se_type) != 0)
1681 /* Don't set SE_SHUTDOWN here */
1684 kill(sp->se_process, SIGHUP);
1695 new_session(sprev, typ);
1701 * sweep through and kill all deleted sessions
1702 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1704 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1705 if ((sp->se_flags & SE_PRESENT) == 0) {
1706 sp->se_flags |= SE_SHUTDOWN;
1707 kill(sp->se_process, SIGHUP);
1711 return (state_func_t) multi_user;
1715 * Block further logins.
1722 for (sp = sessions; sp; sp = sp->se_next)
1723 sp->se_flags |= SE_SHUTDOWN;
1725 return (state_func_t) multi_user;
1732 alrm_handler(int sig)
1740 * Bring the system down to single user.
1748 /* Temporarily block suspend. */
1749 len = sizeof(blocked);
1751 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1752 &block, sizeof(block)) == -1)
1756 * Also revoke the TTY here. Because runshutdown() may reopen
1757 * the TTY whose getty we're killing here, there is no guarantee
1758 * runshutdown() will perform the initial open() call, causing
1759 * the terminal attributes to be misconfigured.
1763 /* Try to run the rc.shutdown script within a period of time */
1766 /* Unblock suspend if we blocked it. */
1768 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1769 &blocked, sizeof(blocked));
1771 return (state_func_t) death_single;
1775 * Do what is necessary to reinitialize single user mode or reboot
1776 * from an incomplete state.
1783 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1785 revoke(_PATH_CONSOLE);
1787 for (i = 0; i < 2; ++i) {
1788 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1789 return (state_func_t) single_user;
1794 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1796 while (clang == 0 && errno != ECHILD);
1798 if (errno == ECHILD)
1799 return (state_func_t) single_user;
1802 warning("some processes would not die; ps axl advised");
1804 return (state_func_t) single_user;
1812 for (sp = sessions; sp; sp = sp->se_next) {
1813 sp->se_flags |= SE_SHUTDOWN;
1814 kill(sp->se_process, SIGHUP);
1815 revoke(sp->se_device);
1820 * Run the system shutdown script.
1822 * Exit codes: XXX I should document more
1823 * -2 shutdown script terminated abnormally
1824 * -1 fatal error - can't run script
1826 * >0 some error (exit code)
1833 int shutdowntimeout;
1837 struct sigaction sa;
1841 * rc.shutdown is optional, so to prevent any unnecessary
1842 * complaints from the shell we simply don't run it if the
1843 * file does not exist. If the stat() here fails for other
1844 * reasons, we'll let the shell complain.
1846 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1849 shell = get_shell();
1851 if ((pid = fork()) == 0) {
1852 sigemptyset(&sa.sa_mask);
1854 sa.sa_handler = SIG_IGN;
1855 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1856 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1861 char _reboot[] = "reboot";
1862 char _single[] = "single";
1863 char _path_rundown[] = _PATH_RUNDOWN;
1866 argv[1] = _path_rundown;
1867 argv[2] = Reboot ? _reboot : _single;
1870 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1873 setprocresources(RESOURCE_RC);
1876 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1877 _exit(1); /* force single user mode */
1881 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1882 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1884 sleep(STALL_TIMEOUT);
1888 len = sizeof(shutdowntimeout);
1889 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1890 NULL, 0) == -1 || shutdowntimeout < 2)
1891 shutdowntimeout = DEATH_SCRIPT;
1892 alarm(shutdowntimeout);
1895 * Copied from single_user(). This is a bit paranoid.
1896 * Use the same ALRM handler.
1899 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1900 collect_child(wpid);
1902 /* we were waiting for the sub-shell */
1903 kill(wpid, SIGTERM);
1904 warning("timeout expired for %s on %s: %m; going to "
1905 "single user mode", shell, _PATH_RUNDOWN);
1911 warning("wait for %s on %s failed: %m; going to "
1912 "single user mode", shell, _PATH_RUNDOWN);
1915 if (wpid == pid && WIFSTOPPED(status)) {
1916 warning("init: %s on %s stopped, restarting\n",
1917 shell, _PATH_RUNDOWN);
1921 } while (wpid != pid && !clang);
1923 /* Turn off the alarm */
1926 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1927 requested_transition == catatonia) {
1929 * /etc/rc.shutdown executed /sbin/reboot;
1930 * wait for the end quietly
1939 if (!WIFEXITED(status)) {
1940 warning("%s on %s terminated abnormally, going to "
1941 "single user mode", shell, _PATH_RUNDOWN);
1945 if ((status = WEXITSTATUS(status)) != 0)
1946 warning("%s returned status %d", _PATH_RUNDOWN, status);
1964 while (c == ' ' || c == '\t' )
1974 while (c && c != '\'')
1976 if (!c) /* unterminated string */
1981 while (c && c != ' ' && c != '\t' )
1992 setprocresources(const char *cname)
1995 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1996 setusercontext(lc, (struct passwd*)NULL, 0,
1997 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
1998 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);