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));
666 bufsize = sb.st_size;
667 buf = malloc(bufsize);
669 emergency("malloc: %s", strerror(errno));
673 nbytes = read(fd, buf, bufsize);
674 if (nbytes != (ssize_t)bufsize) {
675 emergency("read: %s", strerror(errno));
682 emergency("close: %s", strerror(errno));
694 create_file(const char *path, void *buf, size_t bufsize)
699 fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
701 emergency("%s: %s", path, strerror(errno));
705 nbytes = write(fd, buf, bufsize);
706 if (nbytes != (ssize_t)bufsize) {
707 emergency("write: %s", strerror(errno));
713 emergency("close: %s", strerror(errno));
722 mount_tmpfs(const char *fspath)
730 memset(errmsg, 0, sizeof(errmsg));
731 build_iovec(&iov, &iovlen, "fstype",
732 __DECONST(void *, "tmpfs"), (size_t)-1);
733 build_iovec(&iov, &iovlen, "fspath",
734 __DECONST(void *, fspath), (size_t)-1);
735 build_iovec(&iov, &iovlen, "errmsg",
736 errmsg, sizeof(errmsg));
738 error = nmount(iov, iovlen, 0);
740 if (*errmsg != '\0') {
741 emergency("cannot mount tmpfs on %s: %s: %s",
742 fspath, errmsg, strerror(errno));
744 emergency("cannot mount tmpfs on %s: %s",
745 fspath, strerror(errno));
756 char init_path[PATH_MAX];
757 size_t bufsize, init_path_len;
762 name[2] = KERN_PROC_PATHNAME;
764 init_path_len = sizeof(init_path);
765 error = sysctl(name, 4, init_path, &init_path_len, NULL, 0);
767 emergency("failed to get kern.proc.pathname: %s",
776 * Make sure nobody can interfere with our scheme.
778 error = kill(-1, SIGKILL);
780 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");
812 return (state_func_t) single_user;
816 reroot_phase_two(void)
818 char init_path[PATH_MAX], *path, *path_component;
819 size_t init_path_len;
823 * Ask the kernel to mount the new rootfs.
825 error = reboot(RB_REROOT);
827 emergency("RB_REBOOT failed: %s", strerror(errno));
832 * Figure out where the destination init(8) binary is. Note that
833 * the path could be different than what we've started with. Use
834 * the value from kenv, if set, or the one from sysctl otherwise.
835 * The latter defaults to a hardcoded value, but can be overridden
836 * by a build time option.
838 nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
840 init_path_len = sizeof(init_path);
841 error = sysctlbyname("kern.init_path",
842 init_path, &init_path_len, NULL, 0);
844 emergency("failed to retrieve kern.init_path: %s",
851 * Repeat the init search logic from sys/kern/init_path.c
853 path_component = init_path;
854 while ((path = strsep(&path_component, ":")) != NULL) {
856 * Execute init(8) from the new rootfs.
858 execl(path, path, NULL);
860 emergency("cannot exec init from %s: %s", init_path, strerror(errno));
863 emergency("reroot failed; going to single user mode");
864 return (state_func_t) single_user;
868 * Bring the system up single user.
881 static const char banner[] =
882 "Enter root password, or ^D to go multi-user\n";
883 char *clear, *password;
890 /* Instead of going single user, let's reboot the machine */
898 if ((pid = fork()) == 0) {
900 * Start the single user session.
906 * Check the root password.
907 * We don't care if the console is 'on' by default;
908 * it's the only tty that can be 'off' and 'secure'.
910 typ = getttynam("console");
911 pp = getpwnam("root");
912 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
913 pp && *pp->pw_passwd) {
914 write_stderr(banner);
916 clear = getpass("Password:");
917 if (clear == 0 || *clear == '\0')
919 password = crypt(clear, pp->pw_passwd);
920 bzero(clear, _PASSWORD_LEN);
921 if (password == NULL ||
922 strcmp(password, pp->pw_passwd) == 0)
924 warning("single-user login failed\n");
936 #define SHREQUEST "Enter full pathname of shell or RETURN for "
937 write_stderr(SHREQUEST);
940 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
941 num != 0 && *cp != '\n' && cp < &altshell[127])
944 if (altshell[0] != '\0')
947 #endif /* DEBUGSHELL */
951 * We catch all the interesting ones,
952 * and those are reset to SIG_DFL on exec.
955 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
959 * If the default one doesn't work, try the Bourne shell.
967 emergency("can't exec %s for single user: %m", shell);
968 execv(_PATH_BSHELL, argv);
969 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
970 sleep(STALL_TIMEOUT);
976 * We are seriously hosed. Do our best.
978 emergency("can't fork single-user shell, trying again");
979 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
981 return (state_func_t) single_user;
984 requested_transition = 0;
986 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
991 warning("wait for single-user shell failed: %m; restarting");
992 return (state_func_t) single_user;
994 if (wpid == pid && WIFSTOPPED(status)) {
995 warning("init: shell stopped, restarting\n");
999 } while (wpid != pid && !requested_transition);
1001 if (requested_transition)
1002 return (state_func_t) requested_transition;
1004 if (!WIFEXITED(status)) {
1005 if (WTERMSIG(status) == SIGKILL) {
1007 * reboot(8) killed shell?
1009 warning("single user shell terminated.");
1010 sleep(STALL_TIMEOUT);
1013 warning("single user shell terminated, restarting");
1014 return (state_func_t) single_user;
1018 runcom_mode = FASTBOOT;
1019 return (state_func_t) runcom;
1023 * Run the system startup script.
1028 state_func_t next_transition;
1030 if ((next_transition = run_script(_PATH_RUNCOM)) != 0)
1031 return next_transition;
1033 runcom_mode = AUTOBOOT; /* the default */
1034 return (state_func_t) read_ttys;
1038 * Run a shell script.
1039 * Returns 0 on success, otherwise the next transition to enter:
1040 * - single_user if fork/execv/waitpid failed, or if the script
1041 * terminated with a signal or exit code != 0.
1042 * - death_single if a SIGTERM was delivered to init(8).
1045 run_script(const char *script)
1051 struct sigaction sa;
1053 shell = get_shell();
1055 if ((pid = fork()) == 0) {
1056 sigemptyset(&sa.sa_mask);
1058 sa.sa_handler = SIG_IGN;
1059 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1060 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1065 char _autoboot[] = "autoboot";
1068 argv[1] = __DECONST(char *, script);
1069 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1072 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1075 setprocresources(RESOURCE_RC);
1078 stall("can't exec %s for %s: %m", shell, script);
1079 _exit(1); /* force single user mode */
1083 emergency("can't fork for %s on %s: %m", shell, script);
1084 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1086 sleep(STALL_TIMEOUT);
1087 return (state_func_t) single_user;
1091 * Copied from single_user(). This is a bit paranoid.
1093 requested_transition = 0;
1095 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1096 collect_child(wpid);
1098 if (requested_transition == death_single ||
1099 requested_transition == reroot)
1100 return (state_func_t) requested_transition;
1103 warning("wait for %s on %s failed: %m; going to "
1104 "single user mode", shell, script);
1105 return (state_func_t) single_user;
1107 if (wpid == pid && WIFSTOPPED(status)) {
1108 warning("init: %s on %s stopped, restarting\n",
1113 } while (wpid != pid);
1115 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1116 requested_transition == catatonia) {
1117 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1125 if (!WIFEXITED(status)) {
1126 warning("%s on %s terminated abnormally, going to single "
1127 "user mode", shell, script);
1128 return (state_func_t) single_user;
1131 if (WEXITSTATUS(status))
1132 return (state_func_t) single_user;
1134 return (state_func_t) 0;
1138 * Open the session database.
1140 * NB: We could pass in the size here; is it necessary?
1143 start_session_db(void)
1145 if (session_db && (*session_db->close)(session_db))
1146 emergency("session database close: %s", strerror(errno));
1147 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
1148 emergency("session database open: %s", strerror(errno));
1156 * Add a new login session.
1159 add_session(session_t *sp)
1164 key.data = &sp->se_process;
1165 key.size = sizeof sp->se_process;
1167 data.size = sizeof sp;
1169 if ((*session_db->put)(session_db, &key, &data, 0))
1170 emergency("insert %d: %s", sp->se_process, strerror(errno));
1174 * Delete an old login session.
1177 del_session(session_t *sp)
1181 key.data = &sp->se_process;
1182 key.size = sizeof sp->se_process;
1184 if ((*session_db->del)(session_db, &key, 0))
1185 emergency("delete %d: %s", sp->se_process, strerror(errno));
1189 * Look up a login session by pid.
1192 find_session(pid_t pid)
1199 key.size = sizeof pid;
1200 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1202 bcopy(data.data, (char *)&ret, sizeof(ret));
1207 * Construct an argument vector from a command line.
1210 construct_argv(char *command)
1213 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1216 if ((argv[argc++] = strk(command)) == 0) {
1220 while ((argv[argc++] = strk((char *) 0)) != NULL)
1226 * Deallocate a session descriptor.
1229 free_session(session_t *sp)
1231 free(sp->se_device);
1234 free(sp->se_getty_argv_space);
1235 free(sp->se_getty_argv);
1237 if (sp->se_window) {
1238 free(sp->se_window);
1239 free(sp->se_window_argv_space);
1240 free(sp->se_window_argv);
1248 * Allocate a new session descriptor.
1249 * Mark it SE_PRESENT.
1252 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1257 if ((typ->ty_status & TTY_ON) == 0 ||
1258 typ->ty_name == 0 ||
1262 sp = (session_t *) calloc(1, sizeof (session_t));
1264 sp->se_index = session_index;
1265 sp->se_flags |= SE_PRESENT;
1267 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1268 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1271 * Attempt to open the device, if we get "device not configured"
1272 * then don't add the device to the session list.
1274 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1275 if (errno == ENXIO) {
1282 if (setupargv(sp, typ) == 0) {
1292 sprev->se_next = sp;
1293 sp->se_prev = sprev;
1300 * Calculate getty and if useful window argv vectors.
1303 setupargv(session_t *sp, struct ttyent *typ)
1308 free(sp->se_getty_argv_space);
1309 free(sp->se_getty_argv);
1311 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1312 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1313 sp->se_getty_argv_space = strdup(sp->se_getty);
1314 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1315 if (sp->se_getty_argv == 0) {
1316 warning("can't parse getty for port %s", sp->se_device);
1318 free(sp->se_getty_argv_space);
1319 sp->se_getty = sp->se_getty_argv_space = 0;
1322 if (sp->se_window) {
1323 free(sp->se_window);
1324 free(sp->se_window_argv_space);
1325 free(sp->se_window_argv);
1327 sp->se_window = sp->se_window_argv_space = 0;
1328 sp->se_window_argv = 0;
1329 if (typ->ty_window) {
1330 sp->se_window = strdup(typ->ty_window);
1331 sp->se_window_argv_space = strdup(sp->se_window);
1332 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1333 if (sp->se_window_argv == 0) {
1334 warning("can't parse window for port %s",
1336 free(sp->se_window_argv_space);
1337 free(sp->se_window);
1338 sp->se_window = sp->se_window_argv_space = 0;
1344 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1349 * Walk the list of ttys and create sessions for each active line.
1354 int session_index = 0;
1355 session_t *sp, *snext;
1359 * Destroy any previous session state.
1360 * There shouldn't be any, but just in case...
1362 for (sp = sessions; sp; sp = snext) {
1363 snext = sp->se_next;
1367 if (start_session_db())
1368 return (state_func_t) single_user;
1371 * Allocate a session entry for each active port.
1372 * Note that sp starts at 0.
1374 while ((typ = getttyent()) != NULL)
1375 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1380 return (state_func_t) multi_user;
1384 * Start a window system running.
1387 start_window_system(session_t *sp)
1391 char term[64], *env[2];
1394 if ((pid = fork()) == -1) {
1395 emergency("can't fork for window system on port %s: %m",
1397 /* hope that getty fails and we can try again */
1401 waitpid(-1, &status, 0);
1405 /* reparent window process to the init to not make a zombie on exit */
1406 if ((pid = fork()) == -1) {
1407 emergency("can't fork for window system on port %s: %m",
1415 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1418 emergency("setsid failed (window) %m");
1421 setprocresources(RESOURCE_WINDOW);
1424 /* Don't use malloc after fork */
1425 strcpy(term, "TERM=");
1426 strncat(term, sp->se_type, sizeof(term) - 6);
1432 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1433 stall("can't exec window system '%s' for port %s: %m",
1434 sp->se_window_argv[0], sp->se_device);
1439 * Start a login session running.
1442 start_getty(session_t *sp)
1446 time_t current_time = time((time_t *) 0);
1448 char term[64], *env[2];
1450 if (current_time >= sp->se_started &&
1451 current_time - sp->se_started < GETTY_SPACING) {
1452 if (++sp->se_nspace > GETTY_NSPACE) {
1460 * fork(), not vfork() -- we can't afford to block.
1462 if ((pid = fork()) == -1) {
1463 emergency("can't fork for getty on port %s: %m", sp->se_device);
1471 warning("getty repeating too quickly on port %s, sleeping %d secs",
1472 sp->se_device, GETTY_SLEEP);
1473 sleep((unsigned) GETTY_SLEEP);
1476 if (sp->se_window) {
1477 start_window_system(sp);
1482 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1485 setprocresources(RESOURCE_GETTY);
1488 /* Don't use malloc after fork */
1489 strcpy(term, "TERM=");
1490 strncat(term, sp->se_type, sizeof(term) - 6);
1495 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1496 stall("can't exec getty '%s' for port %s: %m",
1497 sp->se_getty_argv[0], sp->se_device);
1502 * Collect exit status for a child.
1503 * If an exiting login, start a new login running.
1506 collect_child(pid_t pid)
1508 session_t *sp, *sprev, *snext;
1513 if (! (sp = find_session(pid)))
1519 if (sp->se_flags & SE_SHUTDOWN) {
1520 if ((sprev = sp->se_prev) != NULL)
1521 sprev->se_next = sp->se_next;
1523 sessions = sp->se_next;
1524 if ((snext = sp->se_next) != NULL)
1525 snext->se_prev = sp->se_prev;
1530 if ((pid = start_getty(sp)) == -1) {
1531 /* serious trouble */
1532 requested_transition = clean_ttys;
1536 sp->se_process = pid;
1537 sp->se_started = time((time_t *) 0);
1542 * Catch a signal and request a state transition.
1545 transition_handler(int sig)
1550 if (current_state == read_ttys || current_state == multi_user ||
1551 current_state == clean_ttys || current_state == catatonia)
1552 requested_transition = clean_ttys;
1555 howto = RB_POWEROFF;
1561 if (current_state == read_ttys || current_state == multi_user ||
1562 current_state == clean_ttys || current_state == catatonia)
1563 requested_transition = death;
1565 requested_transition = death_single;
1568 if (current_state == runcom || current_state == read_ttys ||
1569 current_state == clean_ttys ||
1570 current_state == multi_user || current_state == catatonia)
1571 requested_transition = catatonia;
1574 requested_transition = reroot;
1577 requested_transition = 0;
1583 * Take the system multiuser.
1591 requested_transition = 0;
1594 * If the administrator has not set the security level to -1
1595 * to indicate that the kernel should not run multiuser in secure
1596 * mode, and the run script has not set a higher level of security
1597 * than level 1, then put the kernel into secure mode.
1599 if (getsecuritylevel() == 0)
1600 setsecuritylevel(1);
1602 for (sp = sessions; sp; sp = sp->se_next) {
1605 if ((pid = start_getty(sp)) == -1) {
1606 /* serious trouble */
1607 requested_transition = clean_ttys;
1610 sp->se_process = pid;
1611 sp->se_started = time((time_t *) 0);
1615 while (!requested_transition)
1616 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1619 return (state_func_t) requested_transition;
1623 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1628 session_t *sp, *sprev;
1630 int session_index = 0;
1632 char *old_getty, *old_window, *old_type;
1635 * mark all sessions for death, (!SE_PRESENT)
1636 * as we find or create new ones they'll be marked as keepers,
1637 * we'll later nuke all the ones not found in /etc/ttys
1639 for (sp = sessions; sp != NULL; sp = sp->se_next)
1640 sp->se_flags &= ~SE_PRESENT;
1642 devlen = sizeof(_PATH_DEV) - 1;
1643 while ((typ = getttyent()) != NULL) {
1646 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1647 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1651 /* we want this one to live */
1652 sp->se_flags |= SE_PRESENT;
1653 if (sp->se_index != session_index) {
1654 warning("port %s changed utmp index from %d to %d",
1655 sp->se_device, sp->se_index,
1657 sp->se_index = session_index;
1659 if ((typ->ty_status & TTY_ON) == 0 ||
1660 typ->ty_getty == 0) {
1661 sp->se_flags |= SE_SHUTDOWN;
1662 kill(sp->se_process, SIGHUP);
1665 sp->se_flags &= ~SE_SHUTDOWN;
1666 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1667 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1668 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1669 if (setupargv(sp, typ) == 0) {
1670 warning("can't parse getty for port %s",
1672 sp->se_flags |= SE_SHUTDOWN;
1673 kill(sp->se_process, SIGHUP);
1675 else if ( !old_getty
1676 || (!old_type && sp->se_type)
1677 || (old_type && !sp->se_type)
1678 || (!old_window && sp->se_window)
1679 || (old_window && !sp->se_window)
1680 || (strcmp(old_getty, sp->se_getty) != 0)
1681 || (old_window && strcmp(old_window, sp->se_window) != 0)
1682 || (old_type && strcmp(old_type, sp->se_type) != 0)
1684 /* Don't set SE_SHUTDOWN here */
1687 kill(sp->se_process, SIGHUP);
1698 new_session(sprev, session_index, typ);
1704 * sweep through and kill all deleted sessions
1705 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1707 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1708 if ((sp->se_flags & SE_PRESENT) == 0) {
1709 sp->se_flags |= SE_SHUTDOWN;
1710 kill(sp->se_process, SIGHUP);
1714 return (state_func_t) multi_user;
1718 * Block further logins.
1725 for (sp = sessions; sp; sp = sp->se_next)
1726 sp->se_flags |= SE_SHUTDOWN;
1728 return (state_func_t) multi_user;
1735 alrm_handler(int sig)
1743 * Bring the system down to single user.
1751 /* Temporarily block suspend. */
1752 len = sizeof(blocked);
1754 if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1755 &block, sizeof(block)) == -1)
1759 * Also revoke the TTY here. Because runshutdown() may reopen
1760 * the TTY whose getty we're killing here, there is no guarantee
1761 * runshutdown() will perform the initial open() call, causing
1762 * the terminal attributes to be misconfigured.
1766 /* Try to run the rc.shutdown script within a period of time */
1769 /* Unblock suspend if we blocked it. */
1771 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1772 &blocked, sizeof(blocked));
1774 return (state_func_t) death_single;
1778 * Do what is necessary to reinitialize single user mode or reboot
1779 * from an incomplete state.
1786 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1788 revoke(_PATH_CONSOLE);
1790 for (i = 0; i < 2; ++i) {
1791 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1792 return (state_func_t) single_user;
1797 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1799 while (clang == 0 && errno != ECHILD);
1801 if (errno == ECHILD)
1802 return (state_func_t) single_user;
1805 warning("some processes would not die; ps axl advised");
1807 return (state_func_t) single_user;
1815 for (sp = sessions; sp; sp = sp->se_next) {
1816 sp->se_flags |= SE_SHUTDOWN;
1817 kill(sp->se_process, SIGHUP);
1818 revoke(sp->se_device);
1823 * Run the system shutdown script.
1825 * Exit codes: XXX I should document more
1826 * -2 shutdown script terminated abnormally
1827 * -1 fatal error - can't run script
1829 * >0 some error (exit code)
1836 int shutdowntimeout;
1840 struct sigaction sa;
1844 * rc.shutdown is optional, so to prevent any unnecessary
1845 * complaints from the shell we simply don't run it if the
1846 * file does not exist. If the stat() here fails for other
1847 * reasons, we'll let the shell complain.
1849 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1852 shell = get_shell();
1854 if ((pid = fork()) == 0) {
1855 sigemptyset(&sa.sa_mask);
1857 sa.sa_handler = SIG_IGN;
1858 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1859 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1864 char _reboot[] = "reboot";
1865 char _single[] = "single";
1866 char _path_rundown[] = _PATH_RUNDOWN;
1869 argv[1] = _path_rundown;
1870 argv[2] = Reboot ? _reboot : _single;
1873 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1876 setprocresources(RESOURCE_RC);
1879 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1880 _exit(1); /* force single user mode */
1884 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1885 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1887 sleep(STALL_TIMEOUT);
1891 len = sizeof(shutdowntimeout);
1892 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1893 NULL, 0) == -1 || shutdowntimeout < 2)
1894 shutdowntimeout = DEATH_SCRIPT;
1895 alarm(shutdowntimeout);
1898 * Copied from single_user(). This is a bit paranoid.
1899 * Use the same ALRM handler.
1902 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1903 collect_child(wpid);
1905 /* we were waiting for the sub-shell */
1906 kill(wpid, SIGTERM);
1907 warning("timeout expired for %s on %s: %m; going to "
1908 "single user mode", shell, _PATH_RUNDOWN);
1914 warning("wait for %s on %s failed: %m; going to "
1915 "single user mode", shell, _PATH_RUNDOWN);
1918 if (wpid == pid && WIFSTOPPED(status)) {
1919 warning("init: %s on %s stopped, restarting\n",
1920 shell, _PATH_RUNDOWN);
1924 } while (wpid != pid && !clang);
1926 /* Turn off the alarm */
1929 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1930 requested_transition == catatonia) {
1932 * /etc/rc.shutdown executed /sbin/reboot;
1933 * wait for the end quietly
1942 if (!WIFEXITED(status)) {
1943 warning("%s on %s terminated abnormally, going to "
1944 "single user mode", shell, _PATH_RUNDOWN);
1948 if ((status = WEXITSTATUS(status)) != 0)
1949 warning("%s returned status %d", _PATH_RUNDOWN, status);
1967 while (c == ' ' || c == '\t' )
1977 while (c && c != '\'')
1979 if (!c) /* unterminated string */
1984 while (c && c != ' ' && c != '\t' )
1995 setprocresources(const char *cname)
1998 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1999 setusercontext(lc, (struct passwd*)NULL, 0,
2000 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
2001 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);