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>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
69 #include <sys/reboot.h>
79 #include <login_cap.h>
82 #include "pathnames.h"
85 * Sleep times; used to prevent thrashing.
87 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
88 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
89 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
90 #define WINDOW_WAIT 3 /* wait N secs after starting window */
91 #define STALL_TIMEOUT 30 /* wait N secs after warning */
92 #define DEATH_WATCH 10 /* wait N secs for procs to die */
93 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
94 #define RESOURCE_RC "daemon"
95 #define RESOURCE_WINDOW "default"
96 #define RESOURCE_GETTY "default"
98 static void handle(sig_t, ...);
99 static void delset(sigset_t *, ...);
101 static void stall(const char *, ...) __printflike(1, 2);
102 static void warning(const char *, ...) __printflike(1, 2);
103 static void emergency(const char *, ...) __printflike(1, 2);
104 static void disaster(int);
105 static void badsys(int);
106 static int runshutdown(void);
107 static char *strk(char *);
110 * We really need a recursive typedef...
111 * The following at least guarantees that the return type of (*state_t)()
112 * is sufficiently wide to hold a function pointer.
114 typedef long (*state_func_t)(void);
115 typedef state_func_t (*state_t)(void);
117 static state_func_t single_user(void);
118 static state_func_t runcom(void);
119 static state_func_t read_ttys(void);
120 static state_func_t multi_user(void);
121 static state_func_t clean_ttys(void);
122 static state_func_t catatonia(void);
123 static state_func_t death(void);
124 static state_func_t death_single(void);
126 static state_func_t run_script(const char *);
128 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
132 static int Reboot = FALSE;
133 static int howto = RB_AUTOBOOT;
137 static void transition(state_t);
138 static state_t requested_transition;
139 static state_t current_state = death_single;
141 static void open_console(void);
142 static const char *get_shell(void);
143 static void write_stderr(const char *message);
145 typedef struct init_session {
146 pid_t se_process; /* controlling process */
147 time_t se_started; /* used to avoid thrashing */
148 int se_flags; /* status of session */
149 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
150 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
151 int se_nspace; /* spacing count */
152 char *se_device; /* filename of port */
153 char *se_getty; /* what to run on that port */
154 char *se_getty_argv_space; /* pre-parsed argument array space */
155 char **se_getty_argv; /* pre-parsed argument array */
156 char *se_window; /* window system (started only once) */
157 char *se_window_argv_space; /* pre-parsed argument array space */
158 char **se_window_argv; /* pre-parsed argument array */
159 char *se_type; /* default terminal type */
160 struct init_session *se_prev;
161 struct init_session *se_next;
164 static void free_session(session_t *);
165 static session_t *new_session(session_t *, struct ttyent *);
166 static session_t *sessions;
168 static char **construct_argv(char *);
169 static void start_window_system(session_t *);
170 static void collect_child(pid_t);
171 static pid_t start_getty(session_t *);
172 static void transition_handler(int);
173 static void alrm_handler(int);
174 static void setsecuritylevel(int);
175 static int getsecuritylevel(void);
176 static int setupargv(session_t *, struct ttyent *);
178 static void setprocresources(const char *);
182 static int start_session_db(void);
183 static void add_session(session_t *);
184 static void del_session(session_t *);
185 static session_t *find_session(pid_t);
186 static DB *session_db;
189 * The mother of all processes.
192 main(int argc, char *argv[])
194 state_t initial_transition = runcom;
195 char kenv_value[PATH_MAX];
200 /* Dispose of random users. */
202 errx(1, "%s", strerror(EPERM));
204 /* System V users like to reexec init. */
206 #ifdef COMPAT_SYSV_INIT
207 /* So give them what they want */
209 if (strlen(argv[1]) == 1) {
210 char runlevel = *argv[1];
214 case '0': /* halt + poweroff */
217 case '1': /* single-user */
220 case '6': /* reboot */
223 case 'c': /* block further logins */
226 case 'q': /* rescan /etc/ttys */
236 errx(1, "invalid run-level ``%s''", argv[1]);
239 errx(1, "already running");
242 * Note that this does NOT open a file...
243 * Does 'init' deserve its own facility number?
245 openlog("init", LOG_CONS, LOG_AUTH);
248 * Create an initial session.
251 warning("initial setsid() failed: %m");
254 * Establish an initial user so that programs running
255 * single user do not freak out and die (like passwd).
257 if (setlogin("root") < 0)
258 warning("setlogin() failed: %m");
261 * This code assumes that we always get arguments through flags,
262 * never through bits set in some random machine register.
264 while ((c = getopt(argc, argv, "dsf")) != -1)
270 initial_transition = single_user;
273 runcom_mode = FASTBOOT;
276 warning("unrecognized flag '-%c'", c);
281 warning("ignoring excess arguments");
284 * We catch or block signals rather than ignore them,
285 * so that they get reset on exec.
287 handle(badsys, SIGSYS, 0);
288 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
290 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGUSR1,
292 handle(alrm_handler, SIGALRM, 0);
294 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
295 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
296 SIGUSR1, SIGUSR2, 0);
297 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
298 sigemptyset(&sa.sa_mask);
300 sa.sa_handler = SIG_IGN;
301 sigaction(SIGTTIN, &sa, (struct sigaction *)0);
302 sigaction(SIGTTOU, &sa, (struct sigaction *)0);
311 if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
312 state_func_t next_transition;
314 if ((next_transition = run_script(kenv_value)) != 0)
315 initial_transition = (state_t) next_transition;
318 if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
319 if (chdir(kenv_value) != 0 || chroot(".") != 0)
320 warning("Can't chroot to %s: %m", kenv_value);
324 * Additional check if devfs needs to be mounted:
325 * If "/" and "/dev" have the same device number,
326 * then it hasn't been mounted yet.
333 root_devno = stst.st_dev;
334 if (stat("/dev", &stst) != 0)
335 warning("Can't stat /dev: %m");
336 else if (stst.st_dev == root_devno)
345 char _fstype[] = "fstype";
346 char _devfs[] = "devfs";
347 char _fspath[] = "fspath";
348 char _path_dev[]= _PATH_DEV;
350 iov[0].iov_base = _fstype;
351 iov[0].iov_len = sizeof(_fstype);
352 iov[1].iov_base = _devfs;
353 iov[1].iov_len = sizeof(_devfs);
354 iov[2].iov_base = _fspath;
355 iov[2].iov_len = sizeof(_fspath);
357 * Try to avoid the trailing slash in _PATH_DEV.
358 * Be *very* defensive.
360 s = strdup(_PATH_DEV);
363 if (i > 0 && s[i - 1] == '/')
366 iov[3].iov_len = strlen(s) + 1;
368 iov[3].iov_base = _path_dev;
369 iov[3].iov_len = sizeof(_path_dev);
377 * Start the state machine.
379 transition(initial_transition);
382 * Should never reach here.
388 * Associate a function with a signal handler.
391 handle(sig_t handler, ...)
395 sigset_t mask_everything;
397 va_start(ap, handler);
399 sa.sa_handler = handler;
400 sigfillset(&mask_everything);
402 while ((sig = va_arg(ap, int)) != 0) {
403 sa.sa_mask = mask_everything;
404 /* XXX SA_RESTART? */
405 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
406 sigaction(sig, &sa, (struct sigaction *) 0);
412 * Delete a set of signals from a mask.
415 delset(sigset_t *maskp, ...)
421 while ((sig = va_arg(ap, int)) != 0)
422 sigdelset(maskp, sig);
427 * Log a message and sleep for a while (to give someone an opportunity
428 * to read it and to save log or hardcopy output if the problem is chronic).
429 * NB: should send a message to the session logger to avoid blocking.
432 stall(const char *message, ...)
435 va_start(ap, message);
437 vsyslog(LOG_ALERT, message, ap);
439 sleep(STALL_TIMEOUT);
443 * Like stall(), but doesn't sleep.
444 * If cpp had variadic macros, the two functions could be #defines for another.
445 * NB: should send a message to the session logger to avoid blocking.
448 warning(const char *message, ...)
451 va_start(ap, message);
453 vsyslog(LOG_ALERT, message, ap);
458 * Log an emergency message.
459 * NB: should send a message to the session logger to avoid blocking.
462 emergency(const char *message, ...)
465 va_start(ap, message);
467 vsyslog(LOG_EMERG, message, ap);
472 * Catch a SIGSYS signal.
474 * These may arise if a system does not support sysctl.
475 * We tolerate up to 25 of these, then throw in the towel.
480 static int badcount = 0;
488 * Catch an unexpected signal.
494 emergency("fatal signal: %s",
495 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
497 sleep(STALL_TIMEOUT);
498 _exit(sig); /* reboot */
502 * Get the security level of the kernel.
505 getsecuritylevel(void)
507 #ifdef KERN_SECURELVL
508 int name[2], curlevel;
512 name[1] = KERN_SECURELVL;
513 len = sizeof curlevel;
514 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
515 emergency("cannot get kernel security level: %s",
526 * Set the security level of the kernel.
529 setsecuritylevel(int newlevel)
531 #ifdef KERN_SECURELVL
532 int name[2], curlevel;
534 curlevel = getsecuritylevel();
535 if (newlevel == curlevel)
538 name[1] = KERN_SECURELVL;
539 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
541 "cannot change kernel security level from %d to %d: %s",
542 curlevel, newlevel, strerror(errno));
546 warning("kernel security level changed from %d to %d",
553 * Change states in the finite state machine.
554 * The initial state is passed as an argument.
557 transition(state_t s)
562 current_state = (state_t) (*current_state)();
566 * Start a session and allocate a controlling terminal.
567 * Only called by children of init after forking.
575 * Try to open /dev/console. Open the device with O_NONBLOCK to
576 * prevent potential blocking on a carrier.
578 revoke(_PATH_CONSOLE);
579 if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
580 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
581 if (login_tty(fd) == 0)
586 /* No luck. Log output to file if possible. */
587 if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
588 stall("cannot open null device.");
591 if (fd != STDIN_FILENO) {
592 dup2(fd, STDIN_FILENO);
595 fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
597 dup2(STDIN_FILENO, STDOUT_FILENO);
598 else if (fd != STDOUT_FILENO) {
599 dup2(fd, STDOUT_FILENO);
602 dup2(STDOUT_FILENO, STDERR_FILENO);
608 static char kenv_value[PATH_MAX];
610 if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
617 write_stderr(const char *message)
620 write(STDERR_FILENO, message, strlen(message));
624 * Bring the system up single user.
637 static const char banner[] =
638 "Enter root password, or ^D to go multi-user\n";
639 char *clear, *password;
646 /* Instead of going single user, let's reboot the machine */
654 if ((pid = fork()) == 0) {
656 * Start the single user session.
662 * Check the root password.
663 * We don't care if the console is 'on' by default;
664 * it's the only tty that can be 'off' and 'secure'.
666 typ = getttynam("console");
667 pp = getpwnam("root");
668 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
669 pp && *pp->pw_passwd) {
670 write_stderr(banner);
672 clear = getpass("Password:");
673 if (clear == 0 || *clear == '\0')
675 password = crypt(clear, pp->pw_passwd);
676 bzero(clear, _PASSWORD_LEN);
677 if (password == NULL ||
678 strcmp(password, pp->pw_passwd) == 0)
680 warning("single-user login failed\n");
692 #define SHREQUEST "Enter full pathname of shell or RETURN for "
693 write_stderr(SHREQUEST);
696 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
697 num != 0 && *cp != '\n' && cp < &altshell[127])
700 if (altshell[0] != '\0')
703 #endif /* DEBUGSHELL */
707 * We catch all the interesting ones,
708 * and those are reset to SIG_DFL on exec.
711 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
715 * If the default one doesn't work, try the Bourne shell.
723 emergency("can't exec %s for single user: %m", shell);
724 execv(_PATH_BSHELL, argv);
725 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
726 sleep(STALL_TIMEOUT);
732 * We are seriously hosed. Do our best.
734 emergency("can't fork single-user shell, trying again");
735 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
737 return (state_func_t) single_user;
740 requested_transition = 0;
742 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
747 warning("wait for single-user shell failed: %m; restarting");
748 return (state_func_t) single_user;
750 if (wpid == pid && WIFSTOPPED(status)) {
751 warning("init: shell stopped, restarting\n");
755 } while (wpid != pid && !requested_transition);
757 if (requested_transition)
758 return (state_func_t) requested_transition;
760 if (!WIFEXITED(status)) {
761 if (WTERMSIG(status) == SIGKILL) {
763 * reboot(8) killed shell?
765 warning("single user shell terminated.");
766 sleep(STALL_TIMEOUT);
769 warning("single user shell terminated, restarting");
770 return (state_func_t) single_user;
774 runcom_mode = FASTBOOT;
775 return (state_func_t) runcom;
779 * Run the system startup script.
784 state_func_t next_transition;
786 if ((next_transition = run_script(_PATH_RUNCOM)) != 0)
787 return next_transition;
789 runcom_mode = AUTOBOOT; /* the default */
790 return (state_func_t) read_ttys;
794 * Run a shell script.
795 * Returns 0 on success, otherwise the next transition to enter:
796 * - single_user if fork/execv/waitpid failed, or if the script
797 * terminated with a signal or exit code != 0.
798 * - death_single if a SIGTERM was delivered to init(8).
801 run_script(const char *script)
811 if ((pid = fork()) == 0) {
812 sigemptyset(&sa.sa_mask);
814 sa.sa_handler = SIG_IGN;
815 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
816 sigaction(SIGHUP, &sa, (struct sigaction *)0);
821 char _autoboot[] = "autoboot";
824 argv[1] = __DECONST(char *, script);
825 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
828 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
831 setprocresources(RESOURCE_RC);
834 stall("can't exec %s for %s: %m", shell, script);
835 _exit(1); /* force single user mode */
839 emergency("can't fork for %s on %s: %m", shell, script);
840 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
842 sleep(STALL_TIMEOUT);
843 return (state_func_t) single_user;
847 * Copied from single_user(). This is a bit paranoid.
849 requested_transition = 0;
851 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
854 if (requested_transition == death_single)
855 return (state_func_t) death_single;
858 warning("wait for %s on %s failed: %m; going to "
859 "single user mode", shell, script);
860 return (state_func_t) single_user;
862 if (wpid == pid && WIFSTOPPED(status)) {
863 warning("init: %s on %s stopped, restarting\n",
868 } while (wpid != pid);
870 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
871 requested_transition == catatonia) {
872 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
880 if (!WIFEXITED(status)) {
881 warning("%s on %s terminated abnormally, going to single "
882 "user mode", shell, script);
883 return (state_func_t) single_user;
886 if (WEXITSTATUS(status))
887 return (state_func_t) single_user;
889 return (state_func_t) 0;
893 * Open the session database.
895 * NB: We could pass in the size here; is it necessary?
898 start_session_db(void)
900 if (session_db && (*session_db->close)(session_db))
901 emergency("session database close: %s", strerror(errno));
902 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
903 emergency("session database open: %s", strerror(errno));
911 * Add a new login session.
914 add_session(session_t *sp)
919 key.data = &sp->se_process;
920 key.size = sizeof sp->se_process;
922 data.size = sizeof sp;
924 if ((*session_db->put)(session_db, &key, &data, 0))
925 emergency("insert %d: %s", sp->se_process, strerror(errno));
929 * Delete an old login session.
932 del_session(session_t *sp)
936 key.data = &sp->se_process;
937 key.size = sizeof sp->se_process;
939 if ((*session_db->del)(session_db, &key, 0))
940 emergency("delete %d: %s", sp->se_process, strerror(errno));
944 * Look up a login session by pid.
947 find_session(pid_t pid)
954 key.size = sizeof pid;
955 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
957 bcopy(data.data, (char *)&ret, sizeof(ret));
962 * Construct an argument vector from a command line.
965 construct_argv(char *command)
968 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
971 if ((argv[argc++] = strk(command)) == 0) {
975 while ((argv[argc++] = strk((char *) 0)) != NULL)
981 * Deallocate a session descriptor.
984 free_session(session_t *sp)
989 free(sp->se_getty_argv_space);
990 free(sp->se_getty_argv);
994 free(sp->se_window_argv_space);
995 free(sp->se_window_argv);
1003 * Allocate a new session descriptor.
1004 * Mark it SE_PRESENT.
1007 new_session(session_t *sprev, struct ttyent *typ)
1012 if ((typ->ty_status & TTY_ON) == 0 ||
1013 typ->ty_name == 0 ||
1017 sp = (session_t *) calloc(1, sizeof (session_t));
1019 sp->se_flags |= SE_PRESENT;
1021 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1022 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1025 * Attempt to open the device, if we get "device not configured"
1026 * then don't add the device to the session list.
1028 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1029 if (errno == ENXIO) {
1036 if (setupargv(sp, typ) == 0) {
1046 sprev->se_next = sp;
1047 sp->se_prev = sprev;
1054 * Calculate getty and if useful window argv vectors.
1057 setupargv(session_t *sp, struct ttyent *typ)
1062 free(sp->se_getty_argv_space);
1063 free(sp->se_getty_argv);
1065 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1066 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1067 sp->se_getty_argv_space = strdup(sp->se_getty);
1068 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1069 if (sp->se_getty_argv == 0) {
1070 warning("can't parse getty for port %s", sp->se_device);
1072 free(sp->se_getty_argv_space);
1073 sp->se_getty = sp->se_getty_argv_space = 0;
1076 if (sp->se_window) {
1077 free(sp->se_window);
1078 free(sp->se_window_argv_space);
1079 free(sp->se_window_argv);
1081 sp->se_window = sp->se_window_argv_space = 0;
1082 sp->se_window_argv = 0;
1083 if (typ->ty_window) {
1084 sp->se_window = strdup(typ->ty_window);
1085 sp->se_window_argv_space = strdup(sp->se_window);
1086 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1087 if (sp->se_window_argv == 0) {
1088 warning("can't parse window for port %s",
1090 free(sp->se_window_argv_space);
1091 free(sp->se_window);
1092 sp->se_window = sp->se_window_argv_space = 0;
1098 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1103 * Walk the list of ttys and create sessions for each active line.
1108 session_t *sp, *snext;
1112 * Destroy any previous session state.
1113 * There shouldn't be any, but just in case...
1115 for (sp = sessions; sp; sp = snext) {
1116 snext = sp->se_next;
1120 if (start_session_db())
1121 return (state_func_t) single_user;
1124 * Allocate a session entry for each active port.
1125 * Note that sp starts at 0.
1127 while ((typ = getttyent()) != NULL)
1128 if ((snext = new_session(sp, typ)) != NULL)
1133 return (state_func_t) multi_user;
1137 * Start a window system running.
1140 start_window_system(session_t *sp)
1144 char term[64], *env[2];
1147 if ((pid = fork()) == -1) {
1148 emergency("can't fork for window system on port %s: %m",
1150 /* hope that getty fails and we can try again */
1154 waitpid(-1, &status, 0);
1158 /* reparent window process to the init to not make a zombie on exit */
1159 if ((pid = fork()) == -1) {
1160 emergency("can't fork for window system on port %s: %m",
1168 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1171 emergency("setsid failed (window) %m");
1174 setprocresources(RESOURCE_WINDOW);
1177 /* Don't use malloc after fork */
1178 strcpy(term, "TERM=");
1179 strncat(term, sp->se_type, sizeof(term) - 6);
1185 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1186 stall("can't exec window system '%s' for port %s: %m",
1187 sp->se_window_argv[0], sp->se_device);
1192 * Start a login session running.
1195 start_getty(session_t *sp)
1199 time_t current_time = time((time_t *) 0);
1201 char term[64], *env[2];
1203 if (current_time >= sp->se_started &&
1204 current_time - sp->se_started < GETTY_SPACING) {
1205 if (++sp->se_nspace > GETTY_NSPACE) {
1213 * fork(), not vfork() -- we can't afford to block.
1215 if ((pid = fork()) == -1) {
1216 emergency("can't fork for getty on port %s: %m", sp->se_device);
1224 warning("getty repeating too quickly on port %s, sleeping %d secs",
1225 sp->se_device, GETTY_SLEEP);
1226 sleep((unsigned) GETTY_SLEEP);
1229 if (sp->se_window) {
1230 start_window_system(sp);
1235 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1238 setprocresources(RESOURCE_GETTY);
1241 /* Don't use malloc after fork */
1242 strcpy(term, "TERM=");
1243 strncat(term, sp->se_type, sizeof(term) - 6);
1248 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1249 stall("can't exec getty '%s' for port %s: %m",
1250 sp->se_getty_argv[0], sp->se_device);
1255 * Collect exit status for a child.
1256 * If an exiting login, start a new login running.
1259 collect_child(pid_t pid)
1261 session_t *sp, *sprev, *snext;
1266 if (! (sp = find_session(pid)))
1272 if (sp->se_flags & SE_SHUTDOWN) {
1273 if ((sprev = sp->se_prev) != NULL)
1274 sprev->se_next = sp->se_next;
1276 sessions = sp->se_next;
1277 if ((snext = sp->se_next) != NULL)
1278 snext->se_prev = sp->se_prev;
1283 if ((pid = start_getty(sp)) == -1) {
1284 /* serious trouble */
1285 requested_transition = clean_ttys;
1289 sp->se_process = pid;
1290 sp->se_started = time((time_t *) 0);
1295 * Catch a signal and request a state transition.
1298 transition_handler(int sig)
1303 if (current_state == read_ttys || current_state == multi_user ||
1304 current_state == clean_ttys || current_state == catatonia)
1305 requested_transition = clean_ttys;
1308 howto = RB_POWEROFF;
1314 if (current_state == read_ttys || current_state == multi_user ||
1315 current_state == clean_ttys || current_state == catatonia)
1316 requested_transition = death;
1318 requested_transition = death_single;
1321 if (current_state == runcom || current_state == read_ttys ||
1322 current_state == clean_ttys ||
1323 current_state == multi_user || current_state == catatonia)
1324 requested_transition = catatonia;
1327 requested_transition = 0;
1333 * Take the system multiuser.
1341 requested_transition = 0;
1344 * If the administrator has not set the security level to -1
1345 * to indicate that the kernel should not run multiuser in secure
1346 * mode, and the run script has not set a higher level of security
1347 * than level 1, then put the kernel into secure mode.
1349 if (getsecuritylevel() == 0)
1350 setsecuritylevel(1);
1352 for (sp = sessions; sp; sp = sp->se_next) {
1355 if ((pid = start_getty(sp)) == -1) {
1356 /* serious trouble */
1357 requested_transition = clean_ttys;
1360 sp->se_process = pid;
1361 sp->se_started = time((time_t *) 0);
1365 while (!requested_transition)
1366 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1369 return (state_func_t) requested_transition;
1373 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1378 session_t *sp, *sprev;
1381 char *old_getty, *old_window, *old_type;
1384 * mark all sessions for death, (!SE_PRESENT)
1385 * as we find or create new ones they'll be marked as keepers,
1386 * we'll later nuke all the ones not found in /etc/ttys
1388 for (sp = sessions; sp != NULL; sp = sp->se_next)
1389 sp->se_flags &= ~SE_PRESENT;
1391 devlen = sizeof(_PATH_DEV) - 1;
1392 while ((typ = getttyent()) != NULL) {
1393 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1394 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1398 /* we want this one to live */
1399 sp->se_flags |= SE_PRESENT;
1400 if ((typ->ty_status & TTY_ON) == 0 ||
1401 typ->ty_getty == 0) {
1402 sp->se_flags |= SE_SHUTDOWN;
1403 kill(sp->se_process, SIGHUP);
1406 sp->se_flags &= ~SE_SHUTDOWN;
1407 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1408 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1409 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1410 if (setupargv(sp, typ) == 0) {
1411 warning("can't parse getty for port %s",
1413 sp->se_flags |= SE_SHUTDOWN;
1414 kill(sp->se_process, SIGHUP);
1416 else if ( !old_getty
1417 || (!old_type && sp->se_type)
1418 || (old_type && !sp->se_type)
1419 || (!old_window && sp->se_window)
1420 || (old_window && !sp->se_window)
1421 || (strcmp(old_getty, sp->se_getty) != 0)
1422 || (old_window && strcmp(old_window, sp->se_window) != 0)
1423 || (old_type && strcmp(old_type, sp->se_type) != 0)
1425 /* Don't set SE_SHUTDOWN here */
1428 kill(sp->se_process, SIGHUP);
1439 new_session(sprev, typ);
1445 * sweep through and kill all deleted sessions
1446 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1448 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1449 if ((sp->se_flags & SE_PRESENT) == 0) {
1450 sp->se_flags |= SE_SHUTDOWN;
1451 kill(sp->se_process, SIGHUP);
1455 return (state_func_t) multi_user;
1459 * Block further logins.
1466 for (sp = sessions; sp; sp = sp->se_next)
1467 sp->se_flags |= SE_SHUTDOWN;
1469 return (state_func_t) multi_user;
1476 alrm_handler(int sig)
1484 * Bring the system down to single user.
1492 * Also revoke the TTY here. Because runshutdown() may reopen
1493 * the TTY whose getty we're killing here, there is no guarantee
1494 * runshutdown() will perform the initial open() call, causing
1495 * the terminal attributes to be misconfigured.
1497 for (sp = sessions; sp; sp = sp->se_next) {
1498 sp->se_flags |= SE_SHUTDOWN;
1499 kill(sp->se_process, SIGHUP);
1500 revoke(sp->se_device);
1503 /* Try to run the rc.shutdown script within a period of time */
1506 return (state_func_t) death_single;
1510 * Do what is necessary to reinitialize single user mode or reboot
1511 * from an incomplete state.
1518 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1520 revoke(_PATH_CONSOLE);
1522 for (i = 0; i < 2; ++i) {
1523 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1524 return (state_func_t) single_user;
1529 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1531 while (clang == 0 && errno != ECHILD);
1533 if (errno == ECHILD)
1534 return (state_func_t) single_user;
1537 warning("some processes would not die; ps axl advised");
1539 return (state_func_t) single_user;
1543 * Run the system shutdown script.
1545 * Exit codes: XXX I should document more
1546 * -2 shutdown script terminated abnormally
1547 * -1 fatal error - can't run script
1549 * >0 some error (exit code)
1556 int shutdowntimeout;
1560 struct sigaction sa;
1564 * rc.shutdown is optional, so to prevent any unnecessary
1565 * complaints from the shell we simply don't run it if the
1566 * file does not exist. If the stat() here fails for other
1567 * reasons, we'll let the shell complain.
1569 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1572 shell = get_shell();
1574 if ((pid = fork()) == 0) {
1575 sigemptyset(&sa.sa_mask);
1577 sa.sa_handler = SIG_IGN;
1578 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1579 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1584 char _reboot[] = "reboot";
1585 char _single[] = "single";
1586 char _path_rundown[] = _PATH_RUNDOWN;
1589 argv[1] = _path_rundown;
1590 argv[2] = Reboot ? _reboot : _single;
1593 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1596 setprocresources(RESOURCE_RC);
1599 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1600 _exit(1); /* force single user mode */
1604 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1605 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1607 sleep(STALL_TIMEOUT);
1611 len = sizeof(shutdowntimeout);
1612 if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1613 NULL, 0) == -1 || shutdowntimeout < 2)
1614 shutdowntimeout = DEATH_SCRIPT;
1615 alarm(shutdowntimeout);
1618 * Copied from single_user(). This is a bit paranoid.
1619 * Use the same ALRM handler.
1622 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1623 collect_child(wpid);
1625 /* we were waiting for the sub-shell */
1626 kill(wpid, SIGTERM);
1627 warning("timeout expired for %s on %s: %m; going to "
1628 "single user mode", shell, _PATH_RUNDOWN);
1634 warning("wait for %s on %s failed: %m; going to "
1635 "single user mode", shell, _PATH_RUNDOWN);
1638 if (wpid == pid && WIFSTOPPED(status)) {
1639 warning("init: %s on %s stopped, restarting\n",
1640 shell, _PATH_RUNDOWN);
1644 } while (wpid != pid && !clang);
1646 /* Turn off the alarm */
1649 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1650 requested_transition == catatonia) {
1652 * /etc/rc.shutdown executed /sbin/reboot;
1653 * wait for the end quietly
1662 if (!WIFEXITED(status)) {
1663 warning("%s on %s terminated abnormally, going to "
1664 "single user mode", shell, _PATH_RUNDOWN);
1668 if ((status = WEXITSTATUS(status)) != 0)
1669 warning("%s returned status %d", _PATH_RUNDOWN, status);
1687 while (c == ' ' || c == '\t' )
1697 while (c && c != '\'')
1699 if (!c) /* unterminated string */
1704 while (c && c != ' ' && c != '\t' )
1715 setprocresources(const char *cname)
1718 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1719 setusercontext(lc, (struct passwd*)NULL, 0,
1720 LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
1721 LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);