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 * 4. 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 execute_script(char *argv[]);
148 static void open_console(void);
149 static const char *get_shell(void);
150 static void replace_init(char *path);
151 static void write_stderr(const char *message);
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, 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, 0);
318 sigprocmask(SIG_SETMASK, &mask, NULL);
319 sigemptyset(&sa.sa_mask);
321 sa.sa_handler = SIG_IGN;
322 sigaction(SIGTTIN, &sa, NULL);
323 sigaction(SIGTTOU, &sa, NULL);
332 if (kenv(KENV_GET, "init_exec", kenv_value, sizeof(kenv_value)) > 0) {
333 replace_init(kenv_value);
334 _exit(0); /* reboot */
337 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
338 state_func_t next_transition;
340 if ((next_transition = run_script(kenv_value)) != NULL)
341 initial_transition = (state_t) next_transition;
344 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
345 if (chdir(kenv_value) != 0 || chroot(".") != 0)
346 warning("Can't chroot to %s: %m", kenv_value);
350 * Additional check if devfs needs to be mounted:
351 * If "/" and "/dev" have the same device number,
352 * then it hasn't been mounted yet.
359 root_devno = stst.st_dev;
360 if (stat("/dev", &stst) != 0)
361 warning("Can't stat /dev: %m");
362 else if (stst.st_dev == root_devno)
371 char _fstype[] = "fstype";
372 char _devfs[] = "devfs";
373 char _fspath[] = "fspath";
374 char _path_dev[]= _PATH_DEV;
376 iov[0].iov_base = _fstype;
377 iov[0].iov_len = sizeof(_fstype);
378 iov[1].iov_base = _devfs;
379 iov[1].iov_len = sizeof(_devfs);
380 iov[2].iov_base = _fspath;
381 iov[2].iov_len = sizeof(_fspath);
383 * Try to avoid the trailing slash in _PATH_DEV.
384 * Be *very* defensive.
386 s = strdup(_PATH_DEV);
389 if (i > 0 && s[i - 1] == '/')
392 iov[3].iov_len = strlen(s) + 1;
394 iov[3].iov_base = _path_dev;
395 iov[3].iov_len = sizeof(_path_dev);
402 if (initial_transition != reroot_phase_two) {
404 * Unmount reroot leftovers. This runs after init(8)
405 * gets reexecuted after reroot_phase_two() is done.
407 error = unmount(_PATH_REROOT, MNT_FORCE);
408 if (error != 0 && errno != EINVAL)
409 warning("Cannot unmount %s: %m", _PATH_REROOT);
413 * Start the state machine.
415 transition(initial_transition);
418 * Should never reach here.
424 * Associate a function with a signal handler.
427 handle(sig_t handler, ...)
431 sigset_t mask_everything;
433 va_start(ap, handler);
435 sa.sa_handler = handler;
436 sigfillset(&mask_everything);
438 while ((sig = va_arg(ap, int)) != 0) {
439 sa.sa_mask = mask_everything;
440 /* XXX SA_RESTART? */
441 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
442 sigaction(sig, &sa, NULL);
448 * Delete a set of signals from a mask.
451 delset(sigset_t *maskp, ...)
457 while ((sig = va_arg(ap, int)) != 0)
458 sigdelset(maskp, sig);
463 * Log a message and sleep for a while (to give someone an opportunity
464 * to read it and to save log or hardcopy output if the problem is chronic).
465 * NB: should send a message to the session logger to avoid blocking.
468 stall(const char *message, ...)
471 va_start(ap, message);
473 vsyslog(LOG_ALERT, message, ap);
475 sleep(STALL_TIMEOUT);
479 * Like stall(), but doesn't sleep.
480 * If cpp had variadic macros, the two functions could be #defines for another.
481 * NB: should send a message to the session logger to avoid blocking.
484 warning(const char *message, ...)
487 va_start(ap, message);
489 vsyslog(LOG_ALERT, message, ap);
494 * Log an emergency message.
495 * NB: should send a message to the session logger to avoid blocking.
498 emergency(const char *message, ...)
501 va_start(ap, message);
503 vsyslog(LOG_EMERG, message, ap);
508 * Catch a SIGSYS signal.
510 * These may arise if a system does not support sysctl.
511 * We tolerate up to 25 of these, then throw in the towel.
516 static int badcount = 0;
524 * Catch an unexpected signal.
530 emergency("fatal signal: %s",
531 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
533 sleep(STALL_TIMEOUT);
534 _exit(sig); /* reboot */
538 * Get the security level of the kernel.
541 getsecuritylevel(void)
543 #ifdef KERN_SECURELVL
544 int name[2], curlevel;
548 name[1] = KERN_SECURELVL;
549 len = sizeof curlevel;
550 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
551 emergency("cannot get kernel security level: %s",
562 * Set the security level of the kernel.
565 setsecuritylevel(int newlevel)
567 #ifdef KERN_SECURELVL
568 int name[2], curlevel;
570 curlevel = getsecuritylevel();
571 if (newlevel == curlevel)
574 name[1] = KERN_SECURELVL;
575 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
577 "cannot change kernel security level from %d to %d: %s",
578 curlevel, newlevel, strerror(errno));
582 warning("kernel security level changed from %d to %d",
589 * Change states in the finite state machine.
590 * The initial state is passed as an argument.
593 transition(state_t s)
598 current_state = (state_t) (*current_state)();
602 * Start a session and allocate a controlling terminal.
603 * Only called by children of init after forking.
611 * Try to open /dev/console. Open the device with O_NONBLOCK to
612 * prevent potential blocking on a carrier.
614 revoke(_PATH_CONSOLE);
615 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
616 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
617 if (login_tty(fd) == 0)
622 /* No luck. Log output to file if possible. */
623 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
624 stall("cannot open null device.");
627 if (fd != STDIN_FILENO) {
628 dup2(fd, STDIN_FILENO);
631 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
633 dup2(STDIN_FILENO, STDOUT_FILENO);
634 else if (fd != STDOUT_FILENO) {
635 dup2(fd, STDOUT_FILENO);
638 dup2(STDOUT_FILENO, STDERR_FILENO);
644 static char kenv_value[PATH_MAX];
646 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
653 write_stderr(const char *message)
656 write(STDERR_FILENO, message, strlen(message));
660 read_file(const char *path, void **bufp, size_t *bufsizep)
668 fd = open(path, O_RDONLY);
670 emergency("%s: %s", path, strerror(errno));
674 error = fstat(fd, &sb);
676 emergency("fstat: %s", strerror(errno));
681 bufsize = sb.st_size;
682 buf = malloc(bufsize);
684 emergency("malloc: %s", strerror(errno));
689 nbytes = read(fd, buf, bufsize);
690 if (nbytes != (ssize_t)bufsize) {
691 emergency("read: %s", strerror(errno));
699 emergency("close: %s", strerror(errno));
711 create_file(const char *path, const void *buf, size_t bufsize)
716 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
718 emergency("%s: %s", path, strerror(errno));
722 nbytes = write(fd, buf, bufsize);
723 if (nbytes != (ssize_t)bufsize) {
724 emergency("write: %s", strerror(errno));
731 emergency("close: %s", strerror(errno));
739 mount_tmpfs(const char *fspath)
747 memset(errmsg, 0, sizeof(errmsg));
748 build_iovec(&iov, &iovlen, "fstype",
749 __DECONST(void *, "tmpfs"), (size_t)-1);
750 build_iovec(&iov, &iovlen, "fspath",
751 __DECONST(void *, fspath), (size_t)-1);
752 build_iovec(&iov, &iovlen, "errmsg",
753 errmsg, sizeof(errmsg));
755 error = nmount(iov, iovlen, 0);
757 if (*errmsg != '\0') {
758 emergency("cannot mount tmpfs on %s: %s: %s",
759 fspath, errmsg, strerror(errno));
761 emergency("cannot mount tmpfs on %s: %s",
762 fspath, strerror(errno));
783 * Make sure nobody can interfere with our scheme.
784 * Ignore ESRCH, which can apparently happen when
785 * there are no processes to kill.
787 error = kill(-1, SIGKILL);
788 if (error != 0 && errno != ESRCH) {
789 emergency("kill(2) failed: %s", strerror(errno));
794 * Copy the init binary into tmpfs, so that we can unmount
795 * the old rootfs without committing suicide.
797 error = read_file(init_path_argv0, &buf, &bufsize);
800 error = mount_tmpfs(_PATH_REROOT);
803 error = create_file(_PATH_REROOT_INIT, buf, bufsize);
808 * Execute the temporary init.
810 execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
811 emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
814 emergency("reroot failed; going to single user mode");
816 return (state_func_t) single_user;
820 reroot_phase_two(void)
822 char init_path[PATH_MAX], *path, *path_component;
823 size_t init_path_len;
827 * Ask the kernel to mount the new rootfs.
829 error = reboot(RB_REROOT);
831 emergency("RB_REBOOT failed: %s", strerror(errno));
836 * Figure out where the destination init(8) binary is. Note that
837 * the path could be different than what we've started with. Use
838 * the value from kenv, if set, or the one from sysctl otherwise.
839 * The latter defaults to a hardcoded value, but can be overridden
840 * by a build time option.
842 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
844 init_path_len = sizeof(init_path);
845 error = sysctlbyname("kern.init_path",
846 init_path, &init_path_len, NULL, 0);
848 emergency("failed to retrieve kern.init_path: %s",
855 * Repeat the init search logic from sys/kern/init_path.c
857 path_component = init_path;
858 while ((path = strsep(&path_component, ":")) != NULL) {
860 * Execute init(8) from the new rootfs.
862 execl(path, path, NULL);
864 emergency("cannot exec init from %s: %s", init_path, strerror(errno));
867 emergency("reroot failed; going to single user mode");
868 return (state_func_t) single_user;
872 * Bring the system up single user.
882 struct timeval tv, tn;
886 static const char banner[] =
887 "Enter root password, or ^D to go multi-user\n";
888 char *clear, *password;
895 /* Instead of going single user, let's reboot the machine */
897 if (reboot(howto) == -1) {
898 emergency("reboot(%#x) failed, %s", howto,
900 _exit(1); /* panic and reboot */
902 warning("reboot(%#x) returned", howto);
903 _exit(0); /* panic as well */
908 if ((pid = fork()) == 0) {
910 * Start the single user session.
916 * Check the root password.
917 * We don't care if the console is 'on' by default;
918 * it's the only tty that can be 'off' and 'secure'.
920 typ = getttynam("console");
921 pp = getpwnam("root");
922 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
923 pp && *pp->pw_passwd) {
924 write_stderr(banner);
926 clear = getpass("Password:");
927 if (clear == NULL || *clear == '\0')
929 password = crypt(clear, pp->pw_passwd);
930 bzero(clear, _PASSWORD_LEN);
931 if (password == NULL ||
932 strcmp(password, pp->pw_passwd) == 0)
934 warning("single-user login failed\n");
946 #define SHREQUEST "Enter full pathname of shell or RETURN for "
947 write_stderr(SHREQUEST);
950 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
951 num != 0 && *cp != '\n' && cp < &altshell[127])
954 if (altshell[0] != '\0')
957 #endif /* DEBUGSHELL */
961 * We catch all the interesting ones,
962 * and those are reset to SIG_DFL on exec.
965 sigprocmask(SIG_SETMASK, &mask, NULL);
969 * If the default one doesn't work, try the Bourne shell.
977 emergency("can't exec %s for single user: %m", shell);
978 execv(_PATH_BSHELL, argv);
979 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
980 sleep(STALL_TIMEOUT);
986 * We are seriously hosed. Do our best.
988 emergency("can't fork single-user shell, trying again");
989 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
991 return (state_func_t) single_user;
994 requested_transition = 0;
996 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1001 warning("wait for single-user shell failed: %m; restarting");
1002 return (state_func_t) single_user;
1004 if (wpid == pid && WIFSTOPPED(status)) {
1005 warning("init: shell stopped, restarting\n");
1009 } while (wpid != pid && !requested_transition);
1011 if (requested_transition)
1012 return (state_func_t) requested_transition;
1014 if (!WIFEXITED(status)) {
1015 if (WTERMSIG(status) == SIGKILL) {
1017 * reboot(8) killed shell?
1019 warning("single user shell terminated.");
1020 gettimeofday(&tv, NULL);
1022 tv.tv_sec += STALL_TIMEOUT;
1023 while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1024 tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1026 gettimeofday(&tn, NULL);
1030 warning("single user shell terminated, restarting");
1031 return (state_func_t) single_user;
1035 runcom_mode = FASTBOOT;
1036 return (state_func_t) runcom;
1040 * Run the system startup script.
1045 state_func_t next_transition;
1047 if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1048 return next_transition;
1050 runcom_mode = AUTOBOOT; /* the default */
1051 return (state_func_t) read_ttys;
1055 execute_script(char *argv[])
1057 struct sigaction sa;
1058 const char *shell, *script;
1061 bzero(&sa, sizeof(sa));
1062 sigemptyset(&sa.sa_mask);
1063 sa.sa_handler = SIG_IGN;
1064 sigaction(SIGTSTP, &sa, NULL);
1065 sigaction(SIGHUP, &sa, NULL);
1069 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1071 setprocresources(RESOURCE_RC);
1075 * Try to directly execute the script first. If it
1076 * fails, try the old method of passing the script path
1077 * to sh(1). Don't complain if it fails because of
1078 * the missing execute bit.
1081 error = access(script, X_OK);
1083 execv(script, argv + 1);
1084 warning("can't exec %s: %m", script);
1085 } else if (errno != EACCES) {
1086 warning("can't access %s: %m", script);
1089 shell = get_shell();
1091 stall("can't exec %s for %s: %m", shell, script);
1095 * Execute binary, replacing init(8) as PID 1.
1098 replace_init(char *path)
1107 execute_script(argv);
1111 * Run a shell script.
1112 * Returns 0 on success, otherwise the next transition to enter:
1113 * - single_user if fork/execv/waitpid failed, or if the script
1114 * terminated with a signal or exit code != 0.
1115 * - death_single if a SIGTERM was delivered to init(8).
1118 run_script(const char *script)
1125 shell = get_shell();
1127 if ((pid = fork()) == 0) {
1130 char _autoboot[] = "autoboot";
1133 argv[1] = __DECONST(char *, script);
1134 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1137 execute_script(argv);
1138 sleep(STALL_TIMEOUT);
1139 _exit(1); /* force single user mode */
1143 emergency("can't fork for %s on %s: %m", shell, script);
1144 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1146 sleep(STALL_TIMEOUT);
1147 return (state_func_t) single_user;
1151 * Copied from single_user(). This is a bit paranoid.
1153 requested_transition = 0;
1155 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1156 collect_child(wpid);
1158 if (requested_transition == death_single ||
1159 requested_transition == reroot)
1160 return (state_func_t) requested_transition;
1163 warning("wait for %s on %s failed: %m; going to "
1164 "single user mode", shell, script);
1165 return (state_func_t) single_user;
1167 if (wpid == pid && WIFSTOPPED(status)) {
1168 warning("init: %s on %s stopped, restarting\n",
1173 } while (wpid != pid);
1175 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1176 requested_transition == catatonia) {
1177 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1185 if (!WIFEXITED(status)) {
1186 warning("%s on %s terminated abnormally, going to single "
1187 "user mode", shell, script);
1188 return (state_func_t) single_user;
1191 if (WEXITSTATUS(status))
1192 return (state_func_t) single_user;
1194 return (state_func_t) 0;
1198 * Open the session database.
1200 * NB: We could pass in the size here; is it necessary?
1203 start_session_db(void)
1205 if (session_db && (*session_db->close)(session_db))
1206 emergency("session database close: %s", strerror(errno));
1207 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1208 emergency("session database open: %s", strerror(errno));
1216 * Add a new login session.
1219 add_session(session_t *sp)
1224 key.data = &sp->se_process;
1225 key.size = sizeof sp->se_process;
1227 data.size = sizeof sp;
1229 if ((*session_db->put)(session_db, &key, &data, 0))
1230 emergency("insert %d: %s", sp->se_process, strerror(errno));
1234 * Delete an old login session.
1237 del_session(session_t *sp)
1241 key.data = &sp->se_process;
1242 key.size = sizeof sp->se_process;
1244 if ((*session_db->del)(session_db, &key, 0))
1245 emergency("delete %d: %s", sp->se_process, strerror(errno));
1249 * Look up a login session by pid.
1252 find_session(pid_t pid)
1259 key.size = sizeof pid;
1260 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1262 bcopy(data.data, (char *)&ret, sizeof(ret));
1267 * Construct an argument vector from a command line.
1270 construct_argv(char *command)
1273 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1276 if ((argv[argc++] = strk(command)) == NULL) {
1280 while ((argv[argc++] = strk((char *) 0)) != NULL)
1286 * Deallocate a session descriptor.
1289 free_session(session_t *sp)
1291 free(sp->se_device);
1294 free(sp->se_getty_argv_space);
1295 free(sp->se_getty_argv);
1297 if (sp->se_window) {
1298 free(sp->se_window);
1299 free(sp->se_window_argv_space);
1300 free(sp->se_window_argv);
1308 * Allocate a new session descriptor.
1309 * Mark it SE_PRESENT.
1312 new_session(session_t *sprev, struct ttyent *typ)
1316 if ((typ->ty_status & TTY_ON) == 0 ||
1317 typ->ty_name == 0 ||
1321 sp = (session_t *) calloc(1, sizeof (session_t));
1323 sp->se_flags |= SE_PRESENT;
1325 if ((typ->ty_status & TTY_IFEXISTS) != 0)
1326 sp->se_flags |= SE_IFEXISTS;
1328 if ((typ->ty_status & TTY_IFCONSOLE) != 0)
1329 sp->se_flags |= SE_IFCONSOLE;
1331 if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1334 if (setupargv(sp, typ) == 0) {
1340 if (sprev == NULL) {
1344 sprev->se_next = sp;
1345 sp->se_prev = sprev;
1352 * Calculate getty and if useful window argv vectors.
1355 setupargv(session_t *sp, struct ttyent *typ)
1360 free(sp->se_getty_argv_space);
1361 free(sp->se_getty_argv);
1363 if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1365 sp->se_getty_argv_space = strdup(sp->se_getty);
1366 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1367 if (sp->se_getty_argv == NULL) {
1368 warning("can't parse getty for port %s", sp->se_device);
1370 free(sp->se_getty_argv_space);
1371 sp->se_getty = sp->se_getty_argv_space = 0;
1374 if (sp->se_window) {
1375 free(sp->se_window);
1376 free(sp->se_window_argv_space);
1377 free(sp->se_window_argv);
1379 sp->se_window = sp->se_window_argv_space = 0;
1380 sp->se_window_argv = 0;
1381 if (typ->ty_window) {
1382 sp->se_window = strdup(typ->ty_window);
1383 sp->se_window_argv_space = strdup(sp->se_window);
1384 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1385 if (sp->se_window_argv == NULL) {
1386 warning("can't parse window for port %s",
1388 free(sp->se_window_argv_space);
1389 free(sp->se_window);
1390 sp->se_window = sp->se_window_argv_space = 0;
1396 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1401 * Walk the list of ttys and create sessions for each active line.
1406 session_t *sp, *snext;
1410 * Destroy any previous session state.
1411 * There shouldn't be any, but just in case...
1413 for (sp = sessions; sp; sp = snext) {
1414 snext = sp->se_next;
1418 if (start_session_db())
1419 return (state_func_t) single_user;
1422 * Allocate a session entry for each active port.
1423 * Note that sp starts at 0.
1425 while ((typ = getttyent()) != NULL)
1426 if ((snext = new_session(sp, typ)) != NULL)
1431 return (state_func_t) multi_user;
1435 * Start a window system running.
1438 start_window_system(session_t *sp)
1442 char term[64], *env[2];
1445 if ((pid = fork()) == -1) {
1446 emergency("can't fork for window system on port %s: %m",
1448 /* hope that getty fails and we can try again */
1452 waitpid(-1, &status, 0);
1456 /* reparent window process to the init to not make a zombie on exit */
1457 if ((pid = fork()) == -1) {
1458 emergency("can't fork for window system on port %s: %m",
1466 sigprocmask(SIG_SETMASK, &mask, NULL);
1469 emergency("setsid failed (window) %m");
1472 setprocresources(RESOURCE_WINDOW);
1475 /* Don't use malloc after fork */
1476 strcpy(term, "TERM=");
1477 strlcat(term, sp->se_type, sizeof(term));
1483 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1484 stall("can't exec window system '%s' for port %s: %m",
1485 sp->se_window_argv[0], sp->se_device);
1490 * Start a login session running.
1493 start_getty(session_t *sp)
1497 time_t current_time = time((time_t *) 0);
1499 char term[64], *env[2];
1501 if (current_time >= sp->se_started &&
1502 current_time - sp->se_started < GETTY_SPACING) {
1503 if (++sp->se_nspace > GETTY_NSPACE) {
1511 * fork(), not vfork() -- we can't afford to block.
1513 if ((pid = fork()) == -1) {
1514 emergency("can't fork for getty on port %s: %m", sp->se_device);
1522 warning("getty repeating too quickly on port %s, sleeping %d secs",
1523 sp->se_device, GETTY_SLEEP);
1524 sleep((unsigned) GETTY_SLEEP);
1527 if (sp->se_window) {
1528 start_window_system(sp);
1533 sigprocmask(SIG_SETMASK, &mask, NULL);
1536 setprocresources(RESOURCE_GETTY);
1539 /* Don't use malloc after fork */
1540 strcpy(term, "TERM=");
1541 strlcat(term, sp->se_type, sizeof(term));
1546 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1547 stall("can't exec getty '%s' for port %s: %m",
1548 sp->se_getty_argv[0], sp->se_device);
1553 * Return 1 if the session is defined as "onifexists"
1554 * or "onifconsole" and the device node does not exist.
1557 session_has_no_tty(session_t *sp)
1561 if ((sp->se_flags & SE_IFEXISTS) == 0 &&
1562 (sp->se_flags & SE_IFCONSOLE) == 0)
1565 fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0);
1567 if (errno == ENOENT)
1577 * Collect exit status for a child.
1578 * If an exiting login, start a new login running.
1581 collect_child(pid_t pid)
1583 session_t *sp, *sprev, *snext;
1588 if (! (sp = find_session(pid)))
1594 if (sp->se_flags & SE_SHUTDOWN ||
1595 session_has_no_tty(sp)) {
1596 if ((sprev = sp->se_prev) != NULL)
1597 sprev->se_next = sp->se_next;
1599 sessions = sp->se_next;
1600 if ((snext = sp->se_next) != NULL)
1601 snext->se_prev = sp->se_prev;
1606 if ((pid = start_getty(sp)) == -1) {
1607 /* serious trouble */
1608 requested_transition = clean_ttys;
1612 sp->se_process = pid;
1613 sp->se_started = time((time_t *) 0);
1618 * Catch a signal and request a state transition.
1621 transition_handler(int sig)
1626 if (current_state == read_ttys || current_state == multi_user ||
1627 current_state == clean_ttys || current_state == catatonia)
1628 requested_transition = clean_ttys;
1631 howto = RB_POWEROFF;
1637 if (current_state == read_ttys || current_state == multi_user ||
1638 current_state == clean_ttys || current_state == catatonia)
1639 requested_transition = death;
1641 requested_transition = death_single;
1644 if (current_state == runcom || current_state == read_ttys ||
1645 current_state == clean_ttys ||
1646 current_state == multi_user || current_state == catatonia)
1647 requested_transition = catatonia;
1650 requested_transition = reroot;
1653 requested_transition = 0;
1659 * Take the system multiuser.
1667 requested_transition = 0;
1670 * If the administrator has not set the security level to -1
1671 * to indicate that the kernel should not run multiuser in secure
1672 * mode, and the run script has not set a higher level of security
1673 * than level 1, then put the kernel into secure mode.
1675 if (getsecuritylevel() == 0)
1676 setsecuritylevel(1);
1678 for (sp = sessions; sp; sp = sp->se_next) {
1681 if (session_has_no_tty(sp))
1683 if ((pid = start_getty(sp)) == -1) {
1684 /* serious trouble */
1685 requested_transition = clean_ttys;
1688 sp->se_process = pid;
1689 sp->se_started = time((time_t *) 0);
1693 while (!requested_transition)
1694 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1697 return (state_func_t) requested_transition;
1701 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1706 session_t *sp, *sprev;
1709 char *old_getty, *old_window, *old_type;
1712 * mark all sessions for death, (!SE_PRESENT)
1713 * as we find or create new ones they'll be marked as keepers,
1714 * we'll later nuke all the ones not found in /etc/ttys
1716 for (sp = sessions; sp != NULL; sp = sp->se_next)
1717 sp->se_flags &= ~SE_PRESENT;
1719 devlen = sizeof(_PATH_DEV) - 1;
1720 while ((typ = getttyent()) != NULL) {
1721 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1722 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1726 /* we want this one to live */
1727 sp->se_flags |= SE_PRESENT;
1728 if ((typ->ty_status & TTY_ON) == 0 ||
1729 typ->ty_getty == 0) {
1730 sp->se_flags |= SE_SHUTDOWN;
1731 kill(sp->se_process, SIGHUP);
1734 sp->se_flags &= ~SE_SHUTDOWN;
1735 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1736 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1737 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1738 if (setupargv(sp, typ) == 0) {
1739 warning("can't parse getty for port %s",
1741 sp->se_flags |= SE_SHUTDOWN;
1742 kill(sp->se_process, SIGHUP);
1744 else if ( !old_getty
1745 || (!old_type && sp->se_type)
1746 || (old_type && !sp->se_type)
1747 || (!old_window && sp->se_window)
1748 || (old_window && !sp->se_window)
1749 || (strcmp(old_getty, sp->se_getty) != 0)
1750 || (old_window && strcmp(old_window, sp->se_window) != 0)
1751 || (old_type && strcmp(old_type, sp->se_type) != 0)
1753 /* Don't set SE_SHUTDOWN here */
1756 kill(sp->se_process, SIGHUP);
1767 new_session(sprev, typ);
1773 * sweep through and kill all deleted sessions
1774 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1776 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1777 if ((sp->se_flags & SE_PRESENT) == 0) {
1778 sp->se_flags |= SE_SHUTDOWN;
1779 kill(sp->se_process, SIGHUP);
1783 return (state_func_t) multi_user;
1787 * Block further logins.
1794 for (sp = sessions; sp; sp = sp->se_next)
1795 sp->se_flags |= SE_SHUTDOWN;
1797 return (state_func_t) multi_user;
1804 alrm_handler(int sig)
1812 * Bring the system down to single user.
1820 /* Temporarily block suspend. */
1821 len = sizeof(blocked);
1823 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1824 &block, sizeof(block)) == -1)
1828 * Also revoke the TTY here. Because runshutdown() may reopen
1829 * the TTY whose getty we're killing here, there is no guarantee
1830 * runshutdown() will perform the initial open() call, causing
1831 * the terminal attributes to be misconfigured.
1835 /* Try to run the rc.shutdown script within a period of time */
1838 /* Unblock suspend if we blocked it. */
1840 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1841 &blocked, sizeof(blocked));
1843 return (state_func_t) death_single;
1847 * Do what is necessary to reinitialize single user mode or reboot
1848 * from an incomplete state.
1855 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1857 revoke(_PATH_CONSOLE);
1859 for (i = 0; i < 2; ++i) {
1860 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1861 return (state_func_t) single_user;
1866 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1868 while (clang == 0 && errno != ECHILD);
1870 if (errno == ECHILD)
1871 return (state_func_t) single_user;
1874 warning("some processes would not die; ps axl advised");
1876 return (state_func_t) single_user;
1884 for (sp = sessions; sp; sp = sp->se_next) {
1885 sp->se_flags |= SE_SHUTDOWN;
1886 kill(sp->se_process, SIGHUP);
1887 revoke(sp->se_device);
1892 * Run the system shutdown script.
1894 * Exit codes: XXX I should document more
1895 * -2 shutdown script terminated abnormally
1896 * -1 fatal error - can't run script
1898 * >0 some error (exit code)
1905 int shutdowntimeout;
1911 * rc.shutdown is optional, so to prevent any unnecessary
1912 * complaints from the shell we simply don't run it if the
1913 * file does not exist. If the stat() here fails for other
1914 * reasons, we'll let the shell complain.
1916 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1919 if ((pid = fork()) == 0) {
1921 char _reboot[] = "reboot";
1922 char _single[] = "single";
1923 char _path_rundown[] = _PATH_RUNDOWN;
1926 argv[1] = _path_rundown;
1927 argv[2] = Reboot ? _reboot : _single;
1930 execute_script(argv);
1931 _exit(1); /* force single user mode */
1935 emergency("can't fork for %s: %m", _PATH_RUNDOWN);
1936 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1938 sleep(STALL_TIMEOUT);
1942 len = sizeof(shutdowntimeout);
1943 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1944 NULL, 0) == -1 || shutdowntimeout < 2)
1945 shutdowntimeout = DEATH_SCRIPT;
1946 alarm(shutdowntimeout);
1949 * Copied from single_user(). This is a bit paranoid.
1950 * Use the same ALRM handler.
1953 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1954 collect_child(wpid);
1956 /* we were waiting for the sub-shell */
1957 kill(wpid, SIGTERM);
1958 warning("timeout expired for %s: %m; going to "
1959 "single user mode", _PATH_RUNDOWN);
1965 warning("wait for %s failed: %m; going to "
1966 "single user mode", _PATH_RUNDOWN);
1969 if (wpid == pid && WIFSTOPPED(status)) {
1970 warning("init: %s stopped, restarting\n",
1975 } while (wpid != pid && !clang);
1977 /* Turn off the alarm */
1980 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1981 requested_transition == catatonia) {
1983 * /etc/rc.shutdown executed /sbin/reboot;
1984 * wait for the end quietly
1993 if (!WIFEXITED(status)) {
1994 warning("%s terminated abnormally, going to "
1995 "single user mode", _PATH_RUNDOWN);
1999 if ((status = WEXITSTATUS(status)) != 0)
2000 warning("%s returned status %d", _PATH_RUNDOWN, status);
2018 while (c == ' ' || c == '\t' )
2028 while (c && c != '\'')
2030 if (!c) /* unterminated string */
2035 while (c && c != ' ' && c != '\t' )
2046 setprocresources(const char *cname)
2049 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2050 setusercontext(lc, (struct passwd*)NULL, 0,
2051 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2052 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);