2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California. All rights reserved.
37 * @(#)init.c 8.1 (Berkeley) 7/15/93
38 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
41 #include <sys/param.h>
42 #include <sys/ioctl.h>
43 #include <sys/mount.h>
44 #include <sys/sysctl.h>
62 #include <sys/reboot.h>
72 #include <login_cap.h>
75 #include "pathnames.h"
78 * Sleep times; used to prevent thrashing.
80 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
81 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
82 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
83 #define WINDOW_WAIT 3 /* wait N secs after starting window */
84 #define STALL_TIMEOUT 30 /* wait N secs after warning */
85 #define DEATH_WATCH 10 /* wait N secs for procs to die */
86 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
87 #define RESOURCE_RC "daemon"
88 #define RESOURCE_WINDOW "default"
89 #define RESOURCE_GETTY "default"
92 * We really need a recursive typedef...
93 * The following at least guarantees that the return type of (*state_t)()
94 * is sufficiently wide to hold a function pointer.
96 typedef long (*state_func_t)(void);
97 typedef state_func_t (*state_t)(void);
99 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
103 static void setctty(const char *);
105 typedef struct init_session {
106 int se_index; /* index of entry in ttys file */
107 pid_t se_process; /* controlling process */
108 struct timeval se_started; /* used to avoid thrashing */
109 int se_flags; /* status of session */
110 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
111 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
112 int se_nspace; /* spacing count */
113 char *se_device; /* filename of port */
114 char *se_getty; /* what to run on that port */
115 char *se_getty_argv_space; /* pre-parsed argument array space */
116 char **se_getty_argv; /* pre-parsed argument array */
117 char *se_window; /* window system (started only once) */
118 char *se_window_argv_space; /* pre-parsed argument array space */
119 char **se_window_argv; /* pre-parsed argument array */
120 char *se_type; /* default terminal type */
121 struct init_session *se_prev;
122 struct init_session *se_next;
125 static void handle(sig_t, ...);
126 static void delset(sigset_t *, ...);
128 static void stall(const char *, ...) __printflike(1, 2);
129 static void warning(const char *, ...) __printflike(1, 2);
130 static void emergency(const char *, ...) __printflike(1, 2);
131 static void disaster(int);
132 static void badsys(int);
133 static int runshutdown(void);
134 static char *strk(char *);
137 #define SINGLE_USER 's'
139 #define READ_TTYS 't'
140 #define MULTI_USER 'm'
141 #define CLEAN_TTYS 'T'
142 #define CATATONIA 'c'
144 static state_func_t single_user(void);
145 static state_func_t runcom(void);
146 static state_func_t read_ttys(void);
147 static state_func_t multi_user(void);
148 static state_func_t clean_ttys(void);
149 static state_func_t catatonia(void);
150 static state_func_t death(void);
152 static void transition(state_t);
154 static void free_session(session_t *);
155 static session_t *new_session(session_t *, int, struct ttyent *);
157 static char **construct_argv(char *);
158 static void start_window_system(session_t *);
159 static void collect_child(pid_t);
160 static pid_t start_getty(session_t *);
161 static void transition_handler(int);
162 static void alrm_handler(int);
163 static void setsecuritylevel(int);
164 static int getsecuritylevel(void);
165 static char *get_chroot(void);
166 static int setupargv(session_t *, struct ttyent *);
168 static void setprocresources(const char *);
171 static void clear_session_logs(session_t *);
173 static int start_session_db(void);
174 static void add_session(session_t *);
175 static void del_session(session_t *);
176 static session_t *find_session(pid_t);
179 static struct timeval boot_time;
180 state_t current_state = death;
181 static void session_utmpx(const session_t *, int);
182 static void make_utmpx(const char *, const char *, int, pid_t,
183 const struct timeval *, int);
184 static char get_runlevel(const state_t);
185 static void utmpx_set_runlevel(char, char);
188 static int Reboot = FALSE;
189 static int howto = RB_AUTOBOOT;
191 static DB *session_db;
192 static volatile sig_atomic_t clang;
193 static session_t *sessions;
194 state_t requested_transition = runcom;
198 * The mother of all processes.
201 main(int argc, char **argv)
210 (void)gettimeofday(&boot_time, NULL);
211 #endif /* SUPPORT_UTMPX */
213 /* Dispose of random users. */
215 errx(1, "%s", strerror(EPERM));
217 /* System V users like to reexec init. */
219 #ifdef COMPAT_SYSV_INIT
220 /* So give them what they want */
222 if (strlen(argv[1]) == 1) {
223 char runlevel = *argv[1];
227 case '0': /* halt + poweroff */
230 case '1': /* single-user */
233 case '6': /* reboot */
236 case 'c': /* block further logins */
239 case 'q': /* rescan /etc/ttys */
249 errx(1, "invalid run-level ``%s''", argv[1]);
252 errx(1, "already running");
255 * Note that this does NOT open a file...
256 * Does 'init' deserve its own facility number?
258 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
261 * If chroot has been requested by the boot loader,
262 * do it now. Try to be robust: If the directory
263 * doesn't exist, continue anyway.
265 init_chroot = get_chroot();
266 if (init_chroot != NULL) {
267 if (chdir(init_chroot) == -1 || chroot(".") == -1)
268 warning("can't chroot to %s: %m", init_chroot);
273 * Create an initial session.
276 warning("initial setsid() failed: %m");
279 * Establish an initial user so that programs running
280 * single user do not freak out and die (like passwd).
282 if (setlogin("root") < 0)
283 warning("setlogin() failed: %m");
285 if (stat("/dev/null", &sts) < 0) {
286 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
291 * This code assumes that we always get arguments through flags,
292 * never through bits set in some random machine register.
294 while ((c = getopt(argc, argv, "dsf")) != -1)
297 /* We don't support DEVFS. */
300 requested_transition = single_user;
303 runcom_mode = FASTBOOT;
306 warning("unrecognized flag '-%c'", c);
311 warning("ignoring excess arguments");
314 * We catch or block signals rather than ignore them,
315 * so that they get reset on exec.
317 handle(badsys, SIGSYS, 0);
318 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
319 SIGBUS, SIGXCPU, SIGXFSZ, 0);
320 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
321 SIGUSR1, SIGUSR2, 0);
322 handle(alrm_handler, SIGALRM, 0);
324 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
325 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
326 SIGUSR1, SIGUSR2, 0);
327 sigprocmask(SIG_SETMASK, &mask, NULL);
328 sigemptyset(&sa.sa_mask);
330 sa.sa_handler = SIG_IGN;
331 sigaction(SIGTTIN, &sa, NULL);
332 sigaction(SIGTTOU, &sa, NULL);
342 * Start the state machine.
344 transition(requested_transition);
347 * Should never reach here.
353 * Associate a function with a signal handler.
356 handle(sig_t handler, ...)
360 sigset_t mask_everything;
363 va_start(ap, handler);
365 sa.sa_handler = handler;
366 sigfillset(&mask_everything);
368 while ((sig = va_arg(ap, int)) != 0) {
369 sa.sa_mask = mask_everything;
370 /* XXX SA_RESTART? */
371 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
372 sigaction(sig, &sa, NULL);
378 * Delete a set of signals from a mask.
381 delset(sigset_t *maskp, ...)
388 while ((sig = va_arg(ap, int)) != 0)
389 sigdelset(maskp, sig);
394 * Log a message and sleep for a while (to give someone an opportunity
395 * to read it and to save log or hardcopy output if the problem is chronic).
396 * NB: should send a message to the session logger to avoid blocking.
399 stall(const char *message, ...)
403 va_start(ap, message);
405 vsyslog(LOG_ALERT, message, ap);
407 sleep(STALL_TIMEOUT);
411 * Like stall(), but doesn't sleep.
412 * If cpp had variadic macros, the two functions could be #defines for another.
413 * NB: should send a message to the session logger to avoid blocking.
416 warning(const char *message, ...)
420 va_start(ap, message);
422 vsyslog(LOG_ALERT, message, ap);
427 * Log an emergency message.
428 * NB: should send a message to the session logger to avoid blocking.
431 emergency(const char *message, ...)
435 va_start(ap, message);
437 vsyslog(LOG_EMERG, message, ap);
442 * Catch a SIGSYS signal.
444 * These may arise if a system does not support sysctl.
445 * We tolerate up to 25 of these, then throw in the towel.
450 static int badcount = 0;
458 * Catch an unexpected signal.
463 emergency("fatal signal: %s",
464 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
466 sleep(STALL_TIMEOUT);
467 _exit(sig); /* reboot */
471 * Get the security level of the kernel.
474 getsecuritylevel(void)
476 #ifdef KERN_SECURELVL
477 int name[2], curlevel;
481 name[1] = KERN_SECURELVL;
482 len = sizeof curlevel;
483 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
484 emergency("cannot get kernel security level: %s",
495 * Get the value of the "init_chroot" variable from the
496 * kernel environment (or NULL if not set).
502 static const char ichname[] = "init_chroot="; /* includes '=' */
503 const int ichlen = strlen(ichname);
504 int real_oid[CTL_MAXNAME];
510 oidlen = __arysize(real_oid);
511 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
512 warning("cannot find kern.environment base sysctl OID");
515 if (oidlen + 1 >= __arysize(real_oid)) {
516 warning("kern.environment OID is too large!");
520 real_oid[oidlen] = 0;
523 real_oid[oidlen + 1] = i;
525 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
527 warning("sysctl kern.environment.%d: %m", i);
532 * slen includes the terminating \0, but do a few sanity
538 if (strncmp(sbuf, ichname, ichlen) != 0)
541 res = strdup(sbuf + ichlen);
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)
583 utmpx_set_runlevel(get_runlevel(current_state),
587 s = (state_t) (*s)();
592 * Close out the accounting files for a login session.
593 * NB: should send a message to the session logger to avoid blocking.
596 clear_session_logs(session_t *sp)
598 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
601 if (logoutx(line, 0, DEAD_PROCESS))
602 logwtmpx(line, "", "", 0, DEAD_PROCESS);
605 logwtmp(line, "", "");
609 * Start a session and allocate a controlling terminal.
610 * Only called by children of init after forking.
613 setctty(const char *name)
618 if ((fd = open(name, O_RDWR)) == -1) {
619 stall("can't open %s: %m", name);
622 if (login_tty(fd) == -1) {
623 stall("can't get %s for controlling terminal: %m", name);
629 * Bring the system up single user.
637 const char *shell = _PATH_BSHELL;
642 static const char banner[] =
643 "Enter root password, or ^D to go multi-user\n";
644 char *clear, *password;
651 /* Instead of going single user, let's reboot the machine */
659 if ((pid = fork()) == 0) {
661 * Start the single user session.
663 setctty(_PATH_CONSOLE);
667 * Check the root password.
668 * We don't care if the console is 'on' by default;
669 * it's the only tty that can be 'off' and 'secure'.
671 typ = getttynam("console");
672 pp = getpwnam("root");
673 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
674 pp && *pp->pw_passwd) {
675 write(2, banner, sizeof banner - 1);
677 clear = getpass("Password:");
678 if (clear == NULL || *clear == '\0')
680 password = crypt(clear, pp->pw_passwd);
681 bzero(clear, _PASSWORD_LEN);
682 if (strcmp(password, pp->pw_passwd) == 0)
684 warning("single-user login failed\n");
697 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
698 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
699 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
700 num != 0 && *cp != '\n' && cp < &altshell[127])
703 if (altshell[0] != '\0')
706 #endif /* DEBUGSHELL */
710 * We catch all the interesting ones,
711 * and those are reset to SIG_DFL on exec.
714 sigprocmask(SIG_SETMASK, &mask, NULL);
718 * If the default one doesn't work, try the Bourne shell.
722 execv(shell, __DECONST(char **, argv));
723 emergency("can't exec %s for single user: %m", shell);
724 execv(_PATH_BSHELL, __DECONST(char **, 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, NULL, WNOHANG) > 0)
737 return (state_func_t) single_user;
740 requested_transition = NULL;
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.
789 if ((pid = fork()) == 0) {
790 sigemptyset(&sa.sa_mask);
792 sa.sa_handler = SIG_IGN;
793 sigaction(SIGTSTP, &sa, NULL);
794 sigaction(SIGHUP, &sa, NULL);
796 setctty(_PATH_CONSOLE);
799 argv[1] = _PATH_RUNCOM;
800 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
803 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
806 setprocresources(RESOURCE_RC);
808 execv(_PATH_BSHELL, __DECONST(char **, argv));
809 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
810 _exit(1); /* force single user mode */
814 emergency("can't fork for %s on %s: %m",
815 _PATH_BSHELL, _PATH_RUNCOM);
816 while (waitpid(-1, NULL, WNOHANG) > 0)
818 sleep(STALL_TIMEOUT);
819 return (state_func_t) single_user;
823 * Copied from single_user(). This is a bit paranoid.
825 requested_transition = NULL;
827 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
830 if (requested_transition == death)
831 return (state_func_t) death;
834 warning("wait for %s on %s failed: %m; going to single user mode",
835 _PATH_BSHELL, _PATH_RUNCOM);
836 return (state_func_t) single_user;
838 if (wpid == pid && WIFSTOPPED(status)) {
839 warning("init: %s on %s stopped, restarting\n",
840 _PATH_BSHELL, _PATH_RUNCOM);
844 } while (wpid != pid);
846 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
847 requested_transition == catatonia) {
848 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
856 if (!WIFEXITED(status)) {
857 warning("%s on %s terminated abnormally, going to single user mode",
858 _PATH_BSHELL, _PATH_RUNCOM);
859 return (state_func_t) single_user;
862 if (WEXITSTATUS(status))
863 return (state_func_t) single_user;
865 runcom_mode = AUTOBOOT; /* the default */
866 /* NB: should send a message to the session logger to avoid blocking. */
868 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
870 logwtmp("~", "reboot", "");
871 return (state_func_t) read_ttys;
875 * Open the session database.
877 * NB: We could pass in the size here; is it necessary?
880 start_session_db(void)
882 if (session_db && (*session_db->close)(session_db))
883 emergency("session database close: %s", strerror(errno));
884 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
885 emergency("session database open: %s", strerror(errno));
893 * Add a new login session.
896 add_session(session_t *sp)
901 key.data = &sp->se_process;
902 key.size = sizeof sp->se_process;
904 data.size = sizeof sp;
906 if ((*session_db->put)(session_db, &key, &data, 0))
907 emergency("insert %d: %s", sp->se_process, strerror(errno));
909 session_utmpx(sp, 1);
914 * Delete an old login session.
917 del_session(session_t *sp)
921 key.data = &sp->se_process;
922 key.size = sizeof sp->se_process;
924 if ((*session_db->del)(session_db, &key, 0))
925 emergency("delete %d: %s", sp->se_process, strerror(errno));
927 session_utmpx(sp, 0);
932 * Look up a login session by pid.
935 find_session(pid_t pid)
942 key.size = sizeof pid;
943 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
945 bcopy(data.data, (char *)&ret, sizeof(ret));
950 * Construct an argument vector from a command line.
953 construct_argv(char *command)
956 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
959 if ((argv[argc++] = strk(command)) == NULL) {
963 while ((argv[argc++] = strk(NULL)) != NULL)
969 * Deallocate a session descriptor.
972 free_session(session_t *sp)
977 free(sp->se_getty_argv_space);
978 free(sp->se_getty_argv);
982 free(sp->se_window_argv_space);
983 free(sp->se_window_argv);
991 * Allocate a new session descriptor.
992 * Mark it SE_PRESENT.
995 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1000 if ((typ->ty_status & TTY_ON) == 0 ||
1001 typ->ty_name == 0 ||
1005 sp = (session_t *) calloc(1, sizeof (session_t));
1007 sp->se_index = session_index;
1008 sp->se_flags |= SE_PRESENT;
1010 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1011 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1014 * Attempt to open the device, if we get "device not configured"
1015 * then don't add the device to the session list.
1017 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1018 if (errno == ENXIO) {
1025 if (setupargv(sp, typ) == 0) {
1031 if (sprev == NULL) {
1035 sprev->se_next = sp;
1036 sp->se_prev = sprev;
1043 * Calculate getty and if useful window argv vectors.
1046 setupargv(session_t *sp, struct ttyent *typ)
1051 free(sp->se_getty_argv_space);
1052 free(sp->se_getty_argv);
1054 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1055 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1056 sp->se_getty_argv_space = strdup(sp->se_getty);
1057 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1058 if (sp->se_getty_argv == NULL) {
1059 warning("can't parse getty for port %s", sp->se_device);
1061 free(sp->se_getty_argv_space);
1062 sp->se_getty = sp->se_getty_argv_space = NULL;
1065 if (sp->se_window) {
1066 free(sp->se_window);
1067 free(sp->se_window_argv_space);
1068 free(sp->se_window_argv);
1070 sp->se_window = sp->se_window_argv_space = NULL;
1071 sp->se_window_argv = NULL;
1072 if (typ->ty_window) {
1073 sp->se_window = strdup(typ->ty_window);
1074 sp->se_window_argv_space = strdup(sp->se_window);
1075 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1076 if (sp->se_window_argv == NULL) {
1077 warning("can't parse window for port %s",
1079 free(sp->se_window_argv_space);
1080 free(sp->se_window);
1081 sp->se_window = sp->se_window_argv_space = NULL;
1087 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1092 * Walk the list of ttys and create sessions for each active line.
1097 int session_index = 0;
1098 session_t *sp, *snext;
1101 #ifdef SUPPORT_UTMPX
1102 if (sessions == NULL) {
1105 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1108 * If wtmpx is not empty, pick the down time from there
1110 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1111 struct timeval down_time;
1113 TIMESPEC_TO_TIMEVAL(&down_time,
1114 st.st_atime > st.st_mtime ?
1115 &st.st_atimespec : &st.st_mtimespec);
1116 make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1121 * Destroy any previous session state.
1122 * There shouldn't be any, but just in case...
1124 for (sp = sessions; sp; sp = snext) {
1126 clear_session_logs(sp);
1127 snext = sp->se_next;
1131 if (start_session_db())
1132 return (state_func_t) single_user;
1135 * Allocate a session entry for each active port.
1136 * Note that sp starts at 0.
1138 while ((typ = getttyent()) != NULL)
1139 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1144 return (state_func_t) multi_user;
1148 * Start a window system running.
1151 start_window_system(session_t *sp)
1155 char term[64], *env[2];
1157 if ((pid = fork()) == -1) {
1158 emergency("can't fork for window system on port %s: %m",
1160 /* hope that getty fails and we can try again */
1168 sigprocmask(SIG_SETMASK, &mask, NULL);
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(NULL);
1201 char term[64], *env[2];
1203 if (current_time >= sp->se_started.tv_sec &&
1204 current_time - sp->se_started.tv_sec < 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, NULL);
1238 setprocresources(RESOURCE_GETTY);
1241 /* Don't use malloc after fork */
1242 strcpy(term, "TERM=");
1243 strncat(term, sp->se_type, sizeof(term) - 6);
1249 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1250 stall("can't exec getty '%s' for port %s: %m",
1251 sp->se_getty_argv[0], sp->se_device);
1256 * Collect exit status for a child.
1257 * If an exiting login, start a new login running.
1260 collect_child(pid_t pid)
1262 session_t *sp, *sprev, *snext;
1267 if (! (sp = find_session(pid)))
1270 clear_session_logs(sp);
1274 if (sp->se_flags & SE_SHUTDOWN) {
1275 if ((sprev = sp->se_prev) != NULL)
1276 sprev->se_next = sp->se_next;
1278 sessions = sp->se_next;
1279 if ((snext = sp->se_next) != NULL)
1280 snext->se_prev = sp->se_prev;
1285 if ((pid = start_getty(sp)) == -1) {
1286 /* serious trouble */
1287 requested_transition = clean_ttys;
1291 sp->se_process = pid;
1292 gettimeofday(&sp->se_started, NULL);
1297 * Catch a signal and request a state transition.
1300 transition_handler(int sig)
1305 requested_transition = clean_ttys;
1308 howto = RB_POWEROFF;
1314 requested_transition = death;
1317 requested_transition = catatonia;
1320 requested_transition = NULL;
1326 * Take the system multiuser.
1334 requested_transition = NULL;
1337 * If the administrator has not set the security level to -1
1338 * to indicate that the kernel should not run multiuser in secure
1339 * mode, and the run script has not set a higher level of security
1340 * than level 1, then put the kernel into secure mode.
1342 if (getsecuritylevel() == 0)
1343 setsecuritylevel(1);
1345 for (sp = sessions; sp; sp = sp->se_next) {
1348 if ((pid = start_getty(sp)) == -1) {
1349 /* serious trouble */
1350 requested_transition = clean_ttys;
1353 sp->se_process = pid;
1354 gettimeofday(&sp->se_started, NULL);
1358 while (!requested_transition)
1359 if ((pid = waitpid(-1, NULL, 0)) != -1)
1362 return (state_func_t) requested_transition;
1366 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1371 session_t *sp, *sprev;
1373 int session_index = 0;
1375 char *old_getty, *old_window, *old_type;
1378 return (state_func_t) multi_user;
1381 * mark all sessions for death, (!SE_PRESENT)
1382 * as we find or create new ones they'll be marked as keepers,
1383 * we'll later nuke all the ones not found in /etc/ttys
1385 for (sp = sessions; sp != NULL; sp = sp->se_next)
1386 sp->se_flags &= ~SE_PRESENT;
1388 devlen = sizeof(_PATH_DEV) - 1;
1389 while ((typ = getttyent()) != NULL) {
1392 for (sprev = NULL, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1393 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1397 /* we want this one to live */
1398 sp->se_flags |= SE_PRESENT;
1399 if (sp->se_index != session_index) {
1400 warning("port %s changed utmp index from %d to %d",
1401 sp->se_device, sp->se_index,
1403 sp->se_index = session_index;
1405 if ((typ->ty_status & TTY_ON) == 0 ||
1406 typ->ty_getty == 0) {
1407 sp->se_flags |= SE_SHUTDOWN;
1408 kill(sp->se_process, SIGHUP);
1411 sp->se_flags &= ~SE_SHUTDOWN;
1412 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1413 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1414 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1415 if (setupargv(sp, typ) == 0) {
1416 warning("can't parse getty for port %s",
1418 sp->se_flags |= SE_SHUTDOWN;
1419 kill(sp->se_process, SIGHUP);
1421 else if ( !old_getty
1422 || (!old_type && sp->se_type)
1423 || (old_type && !sp->se_type)
1424 || (!old_window && sp->se_window)
1425 || (old_window && !sp->se_window)
1426 || (strcmp(old_getty, sp->se_getty) != 0)
1427 || (old_window && strcmp(old_window, sp->se_window) != 0)
1428 || (old_type && strcmp(old_type, sp->se_type) != 0)
1430 /* Don't set SE_SHUTDOWN here */
1432 sp->se_started.tv_sec = sp->se_started.tv_usec = 0;
1433 kill(sp->se_process, SIGHUP);
1444 new_session(sprev, session_index, typ);
1450 * sweep through and kill all deleted sessions
1451 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1453 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1454 if ((sp->se_flags & SE_PRESENT) == 0) {
1455 sp->se_flags |= SE_SHUTDOWN;
1456 kill(sp->se_process, SIGHUP);
1460 return (state_func_t) multi_user;
1464 * Block further logins.
1471 for (sp = sessions; sp; sp = sp->se_next)
1472 sp->se_flags |= SE_SHUTDOWN;
1474 return (state_func_t) multi_user;
1481 alrm_handler(int sig __unused)
1487 * Bring the system down to single user.
1495 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1497 /* NB: should send a message to the session logger to avoid blocking. */
1498 #ifdef SUPPORT_UTMPX
1499 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1501 logwtmp("~", "shutdown", "");
1503 for (sp = sessions; sp; sp = sp->se_next) {
1504 sp->se_flags |= SE_SHUTDOWN;
1505 kill(sp->se_process, SIGHUP);
1508 /* Try to run the rc.shutdown script within a period of time */
1511 for (i = 0; i < 2; ++i) {
1512 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1513 return (state_func_t) single_user;
1518 if ((pid = waitpid(-1, NULL, 0)) != -1)
1520 while (clang == 0 && errno != ECHILD);
1522 if (errno == ECHILD)
1523 return (state_func_t) single_user;
1526 warning("some processes would not die; ps axl advised");
1528 return (state_func_t) single_user;
1532 * Run the system shutdown script.
1534 * Exit codes: XXX I should document more
1535 * -2 shutdown script terminated abnormally
1536 * -1 fatal error - can't run script
1538 * >0 some error (exit code)
1545 int shutdowntimeout;
1547 const char *argv[4];
1548 struct sigaction sa;
1552 * rc.shutdown is optional, so to prevent any unnecessary
1553 * complaints from the shell we simply don't run it if the
1554 * file does not exist. If the stat() here fails for other
1555 * reasons, we'll let the shell complain.
1557 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1560 if ((pid = fork()) == 0) {
1563 /* Assume that init already grab console as ctty before */
1565 sigemptyset(&sa.sa_mask);
1567 sa.sa_handler = SIG_IGN;
1568 sigaction(SIGTSTP, &sa, NULL);
1569 sigaction(SIGHUP, &sa, NULL);
1571 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1572 warning("can't open %s: %m", _PATH_CONSOLE);
1582 * Run the shutdown script.
1585 argv[1] = _PATH_RUNDOWN;
1592 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1595 setprocresources(RESOURCE_RC);
1597 execv(_PATH_BSHELL, __DECONST(char **, argv));
1598 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1599 _exit(1); /* force single user mode */
1603 emergency("can't fork for %s on %s: %m",
1604 _PATH_BSHELL, _PATH_RUNDOWN);
1605 while (waitpid(-1, NULL, WNOHANG) > 0)
1607 sleep(STALL_TIMEOUT);
1611 len = sizeof(shutdowntimeout);
1612 if (sysctlbyname("kern.shutdown_timeout",
1614 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1615 shutdowntimeout = DEATH_SCRIPT;
1616 alarm(shutdowntimeout);
1619 * Copied from single_user(). This is a bit paranoid.
1620 * Use the same ALRM handler.
1623 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1624 collect_child(wpid);
1626 /* we were waiting for the sub-shell */
1627 kill(wpid, SIGTERM);
1628 warning("timeout expired for %s on %s: %m; going to single user mode",
1629 _PATH_BSHELL, _PATH_RUNDOWN);
1635 warning("wait for %s on %s failed: %m; going to single user mode",
1636 _PATH_BSHELL, _PATH_RUNDOWN);
1639 if (wpid == pid && WIFSTOPPED(status)) {
1640 warning("init: %s on %s stopped, restarting\n",
1641 _PATH_BSHELL, _PATH_RUNDOWN);
1645 } while (wpid != pid && !clang);
1647 /* Turn off the alarm */
1650 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1651 requested_transition == catatonia) {
1653 * /etc/rc.shutdown executed /sbin/reboot;
1654 * wait for the end quietly
1663 if (!WIFEXITED(status)) {
1664 warning("%s on %s terminated abnormally, going to single user mode",
1665 _PATH_BSHELL, _PATH_RUNDOWN);
1669 if ((status = WEXITSTATUS(status)) != 0)
1670 warning("%s returned status %d", _PATH_RUNDOWN, status);
1688 while (c == ' ' || c == '\t' )
1698 while (c && c != '\'')
1700 if (!c) /* unterminated string */
1705 while (c && c != ' ' && c != '\t' )
1716 setprocresources(const char *cname)
1719 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1720 setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1726 #ifdef SUPPORT_UTMPX
1728 session_utmpx(const session_t *sp, int add)
1730 const char *name = sp->se_getty ? sp->se_getty :
1731 (sp->se_window ? sp->se_window : "");
1732 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1734 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1735 sp->se_process, &sp->se_started, sp->se_index);
1739 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1740 const struct timeval *tv, int session)
1745 (void)memset(&ut, 0, sizeof(ut));
1746 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1748 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1753 (void)gettimeofday(&ut.ut_tv, NULL);
1754 ut.ut_session = session;
1756 eline = line + strlen(line);
1757 if ((size_t)(eline - line) >= sizeof(ut.ut_id))
1758 line = eline - sizeof(ut.ut_id);
1759 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1761 if (pututxline(&ut) == NULL)
1762 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1767 get_runlevel(const state_t s)
1769 if (s == (state_t)single_user)
1771 if (s == (state_t)runcom)
1773 if (s == (state_t)read_ttys)
1775 if (s == (state_t)multi_user)
1777 if (s == (state_t)clean_ttys)
1779 if (s == (state_t)catatonia)
1785 utmpx_set_runlevel(char old, char new)
1790 * Don't record any transitions until we did the first transition
1791 * to read ttys, which is when we are guaranteed to have a read-write
1792 * /var. Perhaps use a different variable for this?
1794 if (sessions == NULL)
1797 (void)memset(&ut, 0, sizeof(ut));
1798 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1799 ut.ut_type = RUN_LVL;
1800 (void)gettimeofday(&ut.ut_tv, NULL);
1801 ut.ut_exit.e_exit = old;
1802 ut.ut_exit.e_termination = new;
1803 if (pututxline(&ut) == NULL)
1804 warning("can't add utmpx record for `runlevel': %m");