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;
142 static void transition(state_t);
143 static state_t requested_transition;
144 static state_t current_state = death_single;
146 static void open_console(void);
147 static const char *get_shell(void);
148 static void write_stderr(const char *message);
150 typedef struct init_session {
151 int se_index; /* index of entry in ttys file */
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 *, int, 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 * Note that this does NOT open a file...
252 * Does 'init' deserve its own facility number?
254 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
257 * Create an initial session.
259 if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
260 warning("initial setsid() failed: %m");
263 * Establish an initial user so that programs running
264 * single user do not freak out and die (like passwd).
266 if (setlogin("root") < 0)
267 warning("setlogin() failed: %m");
270 * This code assumes that we always get arguments through flags,
271 * never through bits set in some random machine register.
273 while ((c = getopt(argc, argv, "dsfr")) != -1)
279 initial_transition = single_user;
282 runcom_mode = FASTBOOT;
285 initial_transition = reroot_phase_two;
288 warning("unrecognized flag '-%c'", c);
293 warning("ignoring excess arguments");
296 * We catch or block signals rather than ignore them,
297 * so that they get reset on exec.
299 handle(badsys, SIGSYS, 0);
300 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
302 handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
303 SIGUSR1, SIGUSR2, 0);
304 handle(alrm_handler, SIGALRM, 0);
306 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
307 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
308 SIGALRM, SIGUSR1, SIGUSR2, 0);
309 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
310 sigemptyset(&sa.sa_mask);
312 sa.sa_handler = SIG_IGN;
313 sigaction(SIGTTIN, &sa, (struct sigaction *)0);
314 sigaction(SIGTTOU, &sa, (struct sigaction *)0);
323 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
324 state_func_t next_transition;
326 if ((next_transition = run_script(kenv_value)) != 0)
327 initial_transition = (state_t) next_transition;
330 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
331 if (chdir(kenv_value) != 0 || chroot(".") != 0)
332 warning("Can't chroot to %s: %m", kenv_value);
336 * Additional check if devfs needs to be mounted:
337 * If "/" and "/dev" have the same device number,
338 * then it hasn't been mounted yet.
345 root_devno = stst.st_dev;
346 if (stat("/dev", &stst) != 0)
347 warning("Can't stat /dev: %m");
348 else if (stst.st_dev == root_devno)
357 char _fstype[] = "fstype";
358 char _devfs[] = "devfs";
359 char _fspath[] = "fspath";
360 char _path_dev[]= _PATH_DEV;
362 iov[0].iov_base = _fstype;
363 iov[0].iov_len = sizeof(_fstype);
364 iov[1].iov_base = _devfs;
365 iov[1].iov_len = sizeof(_devfs);
366 iov[2].iov_base = _fspath;
367 iov[2].iov_len = sizeof(_fspath);
369 * Try to avoid the trailing slash in _PATH_DEV.
370 * Be *very* defensive.
372 s = strdup(_PATH_DEV);
375 if (i > 0 && s[i - 1] == '/')
378 iov[3].iov_len = strlen(s) + 1;
380 iov[3].iov_base = _path_dev;
381 iov[3].iov_len = sizeof(_path_dev);
388 if (initial_transition != reroot_phase_two) {
390 * Unmount reroot leftovers. This runs after init(8)
391 * gets reexecuted after reroot_phase_two() is done.
393 error = unmount(_PATH_REROOT, MNT_FORCE);
394 if (error != 0 && errno != EINVAL)
395 warning("Cannot unmount %s: %m", _PATH_REROOT);
399 * Start the state machine.
401 transition(initial_transition);
404 * Should never reach here.
410 * Associate a function with a signal handler.
413 handle(sig_t handler, ...)
417 sigset_t mask_everything;
419 va_start(ap, handler);
421 sa.sa_handler = handler;
422 sigfillset(&mask_everything);
424 while ((sig = va_arg(ap, int)) != 0) {
425 sa.sa_mask = mask_everything;
426 /* XXX SA_RESTART? */
427 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
428 sigaction(sig, &sa, (struct sigaction *) 0);
434 * Delete a set of signals from a mask.
437 delset(sigset_t *maskp, ...)
443 while ((sig = va_arg(ap, int)) != 0)
444 sigdelset(maskp, sig);
449 * Log a message and sleep for a while (to give someone an opportunity
450 * to read it and to save log or hardcopy output if the problem is chronic).
451 * NB: should send a message to the session logger to avoid blocking.
454 stall(const char *message, ...)
457 va_start(ap, message);
459 vsyslog(LOG_ALERT, message, ap);
461 sleep(STALL_TIMEOUT);
465 * Like stall(), but doesn't sleep.
466 * If cpp had variadic macros, the two functions could be #defines for another.
467 * NB: should send a message to the session logger to avoid blocking.
470 warning(const char *message, ...)
473 va_start(ap, message);
475 vsyslog(LOG_ALERT, message, ap);
480 * Log an emergency message.
481 * NB: should send a message to the session logger to avoid blocking.
484 emergency(const char *message, ...)
487 va_start(ap, message);
489 vsyslog(LOG_EMERG, message, ap);
494 * Catch a SIGSYS signal.
496 * These may arise if a system does not support sysctl.
497 * We tolerate up to 25 of these, then throw in the towel.
502 static int badcount = 0;
510 * Catch an unexpected signal.
516 emergency("fatal signal: %s",
517 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
519 sleep(STALL_TIMEOUT);
520 _exit(sig); /* reboot */
524 * Get the security level of the kernel.
527 getsecuritylevel(void)
529 #ifdef KERN_SECURELVL
530 int name[2], curlevel;
534 name[1] = KERN_SECURELVL;
535 len = sizeof curlevel;
536 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
537 emergency("cannot get kernel security level: %s",
548 * Set the security level of the kernel.
551 setsecuritylevel(int newlevel)
553 #ifdef KERN_SECURELVL
554 int name[2], curlevel;
556 curlevel = getsecuritylevel();
557 if (newlevel == curlevel)
560 name[1] = KERN_SECURELVL;
561 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
563 "cannot change kernel security level from %d to %d: %s",
564 curlevel, newlevel, strerror(errno));
568 warning("kernel security level changed from %d to %d",
575 * Change states in the finite state machine.
576 * The initial state is passed as an argument.
579 transition(state_t s)
584 current_state = (state_t) (*current_state)();
588 * Start a session and allocate a controlling terminal.
589 * Only called by children of init after forking.
597 * Try to open /dev/console. Open the device with O_NONBLOCK to
598 * prevent potential blocking on a carrier.
600 revoke(_PATH_CONSOLE);
601 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
602 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
603 if (login_tty(fd) == 0)
608 /* No luck. Log output to file if possible. */
609 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
610 stall("cannot open null device.");
613 if (fd != STDIN_FILENO) {
614 dup2(fd, STDIN_FILENO);
617 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
619 dup2(STDIN_FILENO, STDOUT_FILENO);
620 else if (fd != STDOUT_FILENO) {
621 dup2(fd, STDOUT_FILENO);
624 dup2(STDOUT_FILENO, STDERR_FILENO);
630 static char kenv_value[PATH_MAX];
632 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
639 write_stderr(const char *message)
642 write(STDERR_FILENO, message, strlen(message));
646 read_file(const char *path, void **bufp, size_t *bufsizep)
654 fd = open(path, O_RDONLY);
656 emergency("%s: %s", path, strerror(errno));
660 error = fstat(fd, &sb);
662 emergency("fstat: %s", strerror(errno));
667 bufsize = sb.st_size;
668 buf = malloc(bufsize);
670 emergency("malloc: %s", strerror(errno));
675 nbytes = read(fd, buf, bufsize);
676 if (nbytes != (ssize_t)bufsize) {
677 emergency("read: %s", strerror(errno));
685 emergency("close: %s", strerror(errno));
697 create_file(const char *path, const void *buf, size_t bufsize)
702 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
704 emergency("%s: %s", path, strerror(errno));
708 nbytes = write(fd, buf, bufsize);
709 if (nbytes != (ssize_t)bufsize) {
710 emergency("write: %s", strerror(errno));
717 emergency("close: %s", strerror(errno));
725 mount_tmpfs(const char *fspath)
733 memset(errmsg, 0, sizeof(errmsg));
734 build_iovec(&iov, &iovlen, "fstype",
735 __DECONST(void *, "tmpfs"), (size_t)-1);
736 build_iovec(&iov, &iovlen, "fspath",
737 __DECONST(void *, fspath), (size_t)-1);
738 build_iovec(&iov, &iovlen, "errmsg",
739 errmsg, sizeof(errmsg));
741 error = nmount(iov, iovlen, 0);
743 if (*errmsg != '\0') {
744 emergency("cannot mount tmpfs on %s: %s: %s",
745 fspath, errmsg, strerror(errno));
747 emergency("cannot mount tmpfs on %s: %s",
748 fspath, strerror(errno));
759 char init_path[PATH_MAX];
760 size_t bufsize, init_path_len;
768 name[2] = KERN_PROC_PATHNAME;
770 init_path_len = sizeof(init_path);
771 error = sysctl(name, 4, init_path, &init_path_len, NULL, 0);
773 emergency("failed to get kern.proc.pathname: %s",
782 * Make sure nobody can interfere with our scheme.
784 error = kill(-1, SIGKILL);
786 emergency("kill(2) failed: %s", strerror(errno));
791 * Copy the init binary into tmpfs, so that we can unmount
792 * the old rootfs without committing suicide.
794 error = read_file(init_path, &buf, &bufsize);
797 error = mount_tmpfs(_PATH_REROOT);
800 error = create_file(_PATH_REROOT_INIT, buf, bufsize);
805 * Execute the temporary init.
807 execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
808 emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
811 emergency("reroot failed; going to single user mode");
813 return (state_func_t) single_user;
817 reroot_phase_two(void)
819 char init_path[PATH_MAX], *path, *path_component;
820 size_t init_path_len;
824 * Ask the kernel to mount the new rootfs.
826 error = reboot(RB_REROOT);
828 emergency("RB_REBOOT failed: %s", strerror(errno));
833 * Figure out where the destination init(8) binary is. Note that
834 * the path could be different than what we've started with. Use
835 * the value from kenv, if set, or the one from sysctl otherwise.
836 * The latter defaults to a hardcoded value, but can be overridden
837 * by a build time option.
839 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
841 init_path_len = sizeof(init_path);
842 error = sysctlbyname("kern.init_path",
843 init_path, &init_path_len, NULL, 0);
845 emergency("failed to retrieve kern.init_path: %s",
852 * Repeat the init search logic from sys/kern/init_path.c
854 path_component = init_path;
855 while ((path = strsep(&path_component, ":")) != NULL) {
857 * Execute init(8) from the new rootfs.
859 execl(path, path, NULL);
861 emergency("cannot exec init from %s: %s", init_path, strerror(errno));
864 emergency("reroot failed; going to single user mode");
865 return (state_func_t) single_user;
869 * Bring the system up single user.
879 struct timeval tv, tn;
883 static const char banner[] =
884 "Enter root password, or ^D to go multi-user\n";
885 char *clear, *password;
892 /* Instead of going single user, let's reboot the machine */
894 if (reboot(howto) == -1) {
895 emergency("reboot(%#x) failed, %s", howto,
897 _exit(1); /* panic and reboot */
899 warning("reboot(%#x) returned", howto);
900 _exit(0); /* panic as well */
905 if ((pid = fork()) == 0) {
907 * Start the single user session.
913 * Check the root password.
914 * We don't care if the console is 'on' by default;
915 * it's the only tty that can be 'off' and 'secure'.
917 typ = getttynam("console");
918 pp = getpwnam("root");
919 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
920 pp && *pp->pw_passwd) {
921 write_stderr(banner);
923 clear = getpass("Password:");
924 if (clear == 0 || *clear == '\0')
926 password = crypt(clear, pp->pw_passwd);
927 bzero(clear, _PASSWORD_LEN);
928 if (password == NULL ||
929 strcmp(password, pp->pw_passwd) == 0)
931 warning("single-user login failed\n");
943 #define SHREQUEST "Enter full pathname of shell or RETURN for "
944 write_stderr(SHREQUEST);
947 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
948 num != 0 && *cp != '\n' && cp < &altshell[127])
951 if (altshell[0] != '\0')
954 #endif /* DEBUGSHELL */
958 * We catch all the interesting ones,
959 * and those are reset to SIG_DFL on exec.
962 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
966 * If the default one doesn't work, try the Bourne shell.
974 emergency("can't exec %s for single user: %m", shell);
975 execv(_PATH_BSHELL, argv);
976 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
977 sleep(STALL_TIMEOUT);
983 * We are seriously hosed. Do our best.
985 emergency("can't fork single-user shell, trying again");
986 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
988 return (state_func_t) single_user;
991 requested_transition = 0;
993 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
998 warning("wait for single-user shell failed: %m; restarting");
999 return (state_func_t) single_user;
1001 if (wpid == pid && WIFSTOPPED(status)) {
1002 warning("init: shell stopped, restarting\n");
1006 } while (wpid != pid && !requested_transition);
1008 if (requested_transition)
1009 return (state_func_t) requested_transition;
1011 if (!WIFEXITED(status)) {
1012 if (WTERMSIG(status) == SIGKILL) {
1014 * reboot(8) killed shell?
1016 warning("single user shell terminated.");
1017 gettimeofday(&tv, NULL);
1019 tv.tv_sec += STALL_TIMEOUT;
1020 while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1021 tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1023 gettimeofday(&tn, NULL);
1027 warning("single user shell terminated, restarting");
1028 return (state_func_t) single_user;
1032 runcom_mode = FASTBOOT;
1033 return (state_func_t) runcom;
1037 * Run the system startup script.
1042 state_func_t next_transition;
1044 if ((next_transition = run_script(_PATH_RUNCOM)) != 0)
1045 return next_transition;
1047 runcom_mode = AUTOBOOT; /* the default */
1048 return (state_func_t) read_ttys;
1052 * Run a shell script.
1053 * Returns 0 on success, otherwise the next transition to enter:
1054 * - single_user if fork/execv/waitpid failed, or if the script
1055 * terminated with a signal or exit code != 0.
1056 * - death_single if a SIGTERM was delivered to init(8).
1059 run_script(const char *script)
1065 struct sigaction sa;
1067 shell = get_shell();
1069 if ((pid = fork()) == 0) {
1070 sigemptyset(&sa.sa_mask);
1072 sa.sa_handler = SIG_IGN;
1073 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1074 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1079 char _autoboot[] = "autoboot";
1082 argv[1] = __DECONST(char *, script);
1083 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1086 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1089 setprocresources(RESOURCE_RC);
1092 stall("can't exec %s for %s: %m", shell, script);
1093 _exit(1); /* force single user mode */
1097 emergency("can't fork for %s on %s: %m", shell, script);
1098 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1100 sleep(STALL_TIMEOUT);
1101 return (state_func_t) single_user;
1105 * Copied from single_user(). This is a bit paranoid.
1107 requested_transition = 0;
1109 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1110 collect_child(wpid);
1112 if (requested_transition == death_single ||
1113 requested_transition == reroot)
1114 return (state_func_t) requested_transition;
1117 warning("wait for %s on %s failed: %m; going to "
1118 "single user mode", shell, script);
1119 return (state_func_t) single_user;
1121 if (wpid == pid && WIFSTOPPED(status)) {
1122 warning("init: %s on %s stopped, restarting\n",
1127 } while (wpid != pid);
1129 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1130 requested_transition == catatonia) {
1131 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1139 if (!WIFEXITED(status)) {
1140 warning("%s on %s terminated abnormally, going to single "
1141 "user mode", shell, script);
1142 return (state_func_t) single_user;
1145 if (WEXITSTATUS(status))
1146 return (state_func_t) single_user;
1148 return (state_func_t) 0;
1152 * Open the session database.
1154 * NB: We could pass in the size here; is it necessary?
1157 start_session_db(void)
1159 if (session_db && (*session_db->close)(session_db))
1160 emergency("session database close: %s", strerror(errno));
1161 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
1162 emergency("session database open: %s", strerror(errno));
1170 * Add a new login session.
1173 add_session(session_t *sp)
1178 key.data = &sp->se_process;
1179 key.size = sizeof sp->se_process;
1181 data.size = sizeof sp;
1183 if ((*session_db->put)(session_db, &key, &data, 0))
1184 emergency("insert %d: %s", sp->se_process, strerror(errno));
1188 * Delete an old login session.
1191 del_session(session_t *sp)
1195 key.data = &sp->se_process;
1196 key.size = sizeof sp->se_process;
1198 if ((*session_db->del)(session_db, &key, 0))
1199 emergency("delete %d: %s", sp->se_process, strerror(errno));
1203 * Look up a login session by pid.
1206 find_session(pid_t pid)
1213 key.size = sizeof pid;
1214 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1216 bcopy(data.data, (char *)&ret, sizeof(ret));
1221 * Construct an argument vector from a command line.
1224 construct_argv(char *command)
1227 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1230 if ((argv[argc++] = strk(command)) == 0) {
1234 while ((argv[argc++] = strk((char *) 0)) != NULL)
1240 * Deallocate a session descriptor.
1243 free_session(session_t *sp)
1245 free(sp->se_device);
1248 free(sp->se_getty_argv_space);
1249 free(sp->se_getty_argv);
1251 if (sp->se_window) {
1252 free(sp->se_window);
1253 free(sp->se_window_argv_space);
1254 free(sp->se_window_argv);
1262 * Allocate a new session descriptor.
1263 * Mark it SE_PRESENT.
1266 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1271 if ((typ->ty_status & TTY_ON) == 0 ||
1272 typ->ty_name == 0 ||
1276 sp = (session_t *) calloc(1, sizeof (session_t));
1278 sp->se_index = session_index;
1279 sp->se_flags |= SE_PRESENT;
1281 if (asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name) < 0)
1285 * Attempt to open the device, if we get "device not configured"
1286 * then don't add the device to the session list.
1288 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1289 if (errno == ENXIO) {
1296 if (setupargv(sp, typ) == 0) {
1306 sprev->se_next = sp;
1307 sp->se_prev = sprev;
1314 * Calculate getty and if useful window argv vectors.
1317 setupargv(session_t *sp, struct ttyent *typ)
1322 free(sp->se_getty_argv_space);
1323 free(sp->se_getty_argv);
1325 if (asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name) < 0)
1327 sp->se_getty_argv_space = strdup(sp->se_getty);
1328 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1329 if (sp->se_getty_argv == 0) {
1330 warning("can't parse getty for port %s", sp->se_device);
1332 free(sp->se_getty_argv_space);
1333 sp->se_getty = sp->se_getty_argv_space = 0;
1336 if (sp->se_window) {
1337 free(sp->se_window);
1338 free(sp->se_window_argv_space);
1339 free(sp->se_window_argv);
1341 sp->se_window = sp->se_window_argv_space = 0;
1342 sp->se_window_argv = 0;
1343 if (typ->ty_window) {
1344 sp->se_window = strdup(typ->ty_window);
1345 sp->se_window_argv_space = strdup(sp->se_window);
1346 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1347 if (sp->se_window_argv == 0) {
1348 warning("can't parse window for port %s",
1350 free(sp->se_window_argv_space);
1351 free(sp->se_window);
1352 sp->se_window = sp->se_window_argv_space = 0;
1358 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1363 * Walk the list of ttys and create sessions for each active line.
1368 int session_index = 0;
1369 session_t *sp, *snext;
1373 * Destroy any previous session state.
1374 * There shouldn't be any, but just in case...
1376 for (sp = sessions; sp; sp = snext) {
1377 snext = sp->se_next;
1381 if (start_session_db())
1382 return (state_func_t) single_user;
1385 * Allocate a session entry for each active port.
1386 * Note that sp starts at 0.
1388 while ((typ = getttyent()) != NULL)
1389 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1394 return (state_func_t) multi_user;
1398 * Start a window system running.
1401 start_window_system(session_t *sp)
1405 char term[64], *env[2];
1408 if ((pid = fork()) == -1) {
1409 emergency("can't fork for window system on port %s: %m",
1411 /* hope that getty fails and we can try again */
1415 waitpid(-1, &status, 0);
1419 /* reparent window process to the init to not make a zombie on exit */
1420 if ((pid = fork()) == -1) {
1421 emergency("can't fork for window system on port %s: %m",
1429 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1432 emergency("setsid failed (window) %m");
1435 setprocresources(RESOURCE_WINDOW);
1438 /* Don't use malloc after fork */
1439 strcpy(term, "TERM=");
1440 strlcat(term, sp->se_type, sizeof(term));
1446 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1447 stall("can't exec window system '%s' for port %s: %m",
1448 sp->se_window_argv[0], sp->se_device);
1453 * Start a login session running.
1456 start_getty(session_t *sp)
1460 time_t current_time = time((time_t *) 0);
1462 char term[64], *env[2];
1464 if (current_time >= sp->se_started &&
1465 current_time - sp->se_started < GETTY_SPACING) {
1466 if (++sp->se_nspace > GETTY_NSPACE) {
1474 * fork(), not vfork() -- we can't afford to block.
1476 if ((pid = fork()) == -1) {
1477 emergency("can't fork for getty on port %s: %m", sp->se_device);
1485 warning("getty repeating too quickly on port %s, sleeping %d secs",
1486 sp->se_device, GETTY_SLEEP);
1487 sleep((unsigned) GETTY_SLEEP);
1490 if (sp->se_window) {
1491 start_window_system(sp);
1496 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1499 setprocresources(RESOURCE_GETTY);
1502 /* Don't use malloc after fork */
1503 strcpy(term, "TERM=");
1504 strlcat(term, sp->se_type, sizeof(term));
1509 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1510 stall("can't exec getty '%s' for port %s: %m",
1511 sp->se_getty_argv[0], sp->se_device);
1516 * Collect exit status for a child.
1517 * If an exiting login, start a new login running.
1520 collect_child(pid_t pid)
1522 session_t *sp, *sprev, *snext;
1527 if (! (sp = find_session(pid)))
1533 if (sp->se_flags & SE_SHUTDOWN) {
1534 if ((sprev = sp->se_prev) != NULL)
1535 sprev->se_next = sp->se_next;
1537 sessions = sp->se_next;
1538 if ((snext = sp->se_next) != NULL)
1539 snext->se_prev = sp->se_prev;
1544 if ((pid = start_getty(sp)) == -1) {
1545 /* serious trouble */
1546 requested_transition = clean_ttys;
1550 sp->se_process = pid;
1551 sp->se_started = time((time_t *) 0);
1556 * Catch a signal and request a state transition.
1559 transition_handler(int sig)
1564 if (current_state == read_ttys || current_state == multi_user ||
1565 current_state == clean_ttys || current_state == catatonia)
1566 requested_transition = clean_ttys;
1569 howto = RB_POWEROFF;
1575 if (current_state == read_ttys || current_state == multi_user ||
1576 current_state == clean_ttys || current_state == catatonia)
1577 requested_transition = death;
1579 requested_transition = death_single;
1582 if (current_state == runcom || current_state == read_ttys ||
1583 current_state == clean_ttys ||
1584 current_state == multi_user || current_state == catatonia)
1585 requested_transition = catatonia;
1588 requested_transition = reroot;
1591 requested_transition = 0;
1597 * Take the system multiuser.
1605 requested_transition = 0;
1608 * If the administrator has not set the security level to -1
1609 * to indicate that the kernel should not run multiuser in secure
1610 * mode, and the run script has not set a higher level of security
1611 * than level 1, then put the kernel into secure mode.
1613 if (getsecuritylevel() == 0)
1614 setsecuritylevel(1);
1616 for (sp = sessions; sp; sp = sp->se_next) {
1619 if ((pid = start_getty(sp)) == -1) {
1620 /* serious trouble */
1621 requested_transition = clean_ttys;
1624 sp->se_process = pid;
1625 sp->se_started = time((time_t *) 0);
1629 while (!requested_transition)
1630 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1633 return (state_func_t) requested_transition;
1637 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1642 session_t *sp, *sprev;
1644 int session_index = 0;
1646 char *old_getty, *old_window, *old_type;
1649 * mark all sessions for death, (!SE_PRESENT)
1650 * as we find or create new ones they'll be marked as keepers,
1651 * we'll later nuke all the ones not found in /etc/ttys
1653 for (sp = sessions; sp != NULL; sp = sp->se_next)
1654 sp->se_flags &= ~SE_PRESENT;
1656 devlen = sizeof(_PATH_DEV) - 1;
1657 while ((typ = getttyent()) != NULL) {
1660 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1661 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1665 /* we want this one to live */
1666 sp->se_flags |= SE_PRESENT;
1667 if (sp->se_index != session_index) {
1668 warning("port %s changed utmp index from %d to %d",
1669 sp->se_device, sp->se_index,
1671 sp->se_index = session_index;
1673 if ((typ->ty_status & TTY_ON) == 0 ||
1674 typ->ty_getty == 0) {
1675 sp->se_flags |= SE_SHUTDOWN;
1676 kill(sp->se_process, SIGHUP);
1679 sp->se_flags &= ~SE_SHUTDOWN;
1680 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1681 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1682 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1683 if (setupargv(sp, typ) == 0) {
1684 warning("can't parse getty for port %s",
1686 sp->se_flags |= SE_SHUTDOWN;
1687 kill(sp->se_process, SIGHUP);
1689 else if ( !old_getty
1690 || (!old_type && sp->se_type)
1691 || (old_type && !sp->se_type)
1692 || (!old_window && sp->se_window)
1693 || (old_window && !sp->se_window)
1694 || (strcmp(old_getty, sp->se_getty) != 0)
1695 || (old_window && strcmp(old_window, sp->se_window) != 0)
1696 || (old_type && strcmp(old_type, sp->se_type) != 0)
1698 /* Don't set SE_SHUTDOWN here */
1701 kill(sp->se_process, SIGHUP);
1712 new_session(sprev, session_index, typ);
1718 * sweep through and kill all deleted sessions
1719 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1721 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1722 if ((sp->se_flags & SE_PRESENT) == 0) {
1723 sp->se_flags |= SE_SHUTDOWN;
1724 kill(sp->se_process, SIGHUP);
1728 return (state_func_t) multi_user;
1732 * Block further logins.
1739 for (sp = sessions; sp; sp = sp->se_next)
1740 sp->se_flags |= SE_SHUTDOWN;
1742 return (state_func_t) multi_user;
1749 alrm_handler(int sig)
1757 * Bring the system down to single user.
1765 /* Temporarily block suspend. */
1766 len = sizeof(blocked);
1768 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1769 &block, sizeof(block)) == -1)
1773 * Also revoke the TTY here. Because runshutdown() may reopen
1774 * the TTY whose getty we're killing here, there is no guarantee
1775 * runshutdown() will perform the initial open() call, causing
1776 * the terminal attributes to be misconfigured.
1780 /* Try to run the rc.shutdown script within a period of time */
1783 /* Unblock suspend if we blocked it. */
1785 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1786 &blocked, sizeof(blocked));
1788 return (state_func_t) death_single;
1792 * Do what is necessary to reinitialize single user mode or reboot
1793 * from an incomplete state.
1800 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1802 revoke(_PATH_CONSOLE);
1804 for (i = 0; i < 2; ++i) {
1805 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1806 return (state_func_t) single_user;
1811 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1813 while (clang == 0 && errno != ECHILD);
1815 if (errno == ECHILD)
1816 return (state_func_t) single_user;
1819 warning("some processes would not die; ps axl advised");
1821 return (state_func_t) single_user;
1829 for (sp = sessions; sp; sp = sp->se_next) {
1830 sp->se_flags |= SE_SHUTDOWN;
1831 kill(sp->se_process, SIGHUP);
1832 revoke(sp->se_device);
1837 * Run the system shutdown script.
1839 * Exit codes: XXX I should document more
1840 * -2 shutdown script terminated abnormally
1841 * -1 fatal error - can't run script
1843 * >0 some error (exit code)
1850 int shutdowntimeout;
1854 struct sigaction sa;
1858 * rc.shutdown is optional, so to prevent any unnecessary
1859 * complaints from the shell we simply don't run it if the
1860 * file does not exist. If the stat() here fails for other
1861 * reasons, we'll let the shell complain.
1863 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1866 shell = get_shell();
1868 if ((pid = fork()) == 0) {
1869 sigemptyset(&sa.sa_mask);
1871 sa.sa_handler = SIG_IGN;
1872 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1873 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1878 char _reboot[] = "reboot";
1879 char _single[] = "single";
1880 char _path_rundown[] = _PATH_RUNDOWN;
1883 argv[1] = _path_rundown;
1884 argv[2] = Reboot ? _reboot : _single;
1887 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1890 setprocresources(RESOURCE_RC);
1893 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1894 _exit(1); /* force single user mode */
1898 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1899 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1901 sleep(STALL_TIMEOUT);
1905 len = sizeof(shutdowntimeout);
1906 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1907 NULL, 0) == -1 || shutdowntimeout < 2)
1908 shutdowntimeout = DEATH_SCRIPT;
1909 alarm(shutdowntimeout);
1912 * Copied from single_user(). This is a bit paranoid.
1913 * Use the same ALRM handler.
1916 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1917 collect_child(wpid);
1919 /* we were waiting for the sub-shell */
1920 kill(wpid, SIGTERM);
1921 warning("timeout expired for %s on %s: %m; going to "
1922 "single user mode", shell, _PATH_RUNDOWN);
1928 warning("wait for %s on %s failed: %m; going to "
1929 "single user mode", shell, _PATH_RUNDOWN);
1932 if (wpid == pid && WIFSTOPPED(status)) {
1933 warning("init: %s on %s stopped, restarting\n",
1934 shell, _PATH_RUNDOWN);
1938 } while (wpid != pid && !clang);
1940 /* Turn off the alarm */
1943 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1944 requested_transition == catatonia) {
1946 * /etc/rc.shutdown executed /sbin/reboot;
1947 * wait for the end quietly
1956 if (!WIFEXITED(status)) {
1957 warning("%s on %s terminated abnormally, going to "
1958 "single user mode", shell, _PATH_RUNDOWN);
1962 if ((status = WEXITSTATUS(status)) != 0)
1963 warning("%s returned status %d", _PATH_RUNDOWN, status);
1981 while (c == ' ' || c == '\t' )
1991 while (c && c != '\'')
1993 if (!c) /* unterminated string */
1998 while (c && c != ' ' && c != '\t' )
2009 setprocresources(const char *cname)
2012 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
2013 setusercontext(lc, (struct passwd*)NULL, 0,
2014 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2015 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);