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. 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
32 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California. All rights reserved.
33 * @(#)init.c 8.1 (Berkeley) 7/15/93
34 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
37 #include <sys/param.h>
38 #include <sys/ioctl.h>
39 #include <sys/mount.h>
40 #include <sys/sysctl.h>
58 #include <sys/reboot.h>
68 #include <login_cap.h>
71 #include "pathnames.h"
74 * Sleep times; used to prevent thrashing.
76 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
77 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
78 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
79 #define WINDOW_WAIT 3 /* wait N secs after starting window */
80 #define STALL_TIMEOUT 30 /* wait N secs after warning */
81 #define DEATH_WATCH 10 /* wait N secs for procs to die */
82 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
83 #define RESOURCE_RC "daemon"
84 #define RESOURCE_WINDOW "default"
85 #define RESOURCE_GETTY "default"
88 * We really need a recursive typedef...
89 * The following at least guarantees that the return type of (*state_t)()
90 * is sufficiently wide to hold a function pointer.
92 typedef long (*state_func_t)(void);
93 typedef state_func_t (*state_t)(void);
95 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
99 static void setctty(const char *);
101 typedef struct init_session {
102 int se_index; /* index of entry in ttys file */
103 pid_t se_process; /* controlling process */
104 struct timeval se_started; /* used to avoid thrashing */
105 int se_flags; /* status of session */
106 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
107 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
108 int se_nspace; /* spacing count */
109 char *se_device; /* filename of port */
110 char *se_getty; /* what to run on that port */
111 char *se_getty_argv_space; /* pre-parsed argument array space */
112 char **se_getty_argv; /* pre-parsed argument array */
113 char *se_window; /* window system (started only once) */
114 char *se_window_argv_space; /* pre-parsed argument array space */
115 char **se_window_argv; /* pre-parsed argument array */
116 char *se_type; /* default terminal type */
117 struct init_session *se_prev;
118 struct init_session *se_next;
121 static void handle(sig_t, ...);
122 static void delset(sigset_t *, ...);
124 static void stall(const char *, ...) __printflike(1, 2);
125 static void warning(const char *, ...) __printflike(1, 2);
126 static void emergency(const char *, ...) __printflike(1, 2);
127 static void disaster(int);
128 static void badsys(int);
129 static int runshutdown(void);
130 static char *strk(char *);
133 #define SINGLE_USER 's'
135 #define READ_TTYS 't'
136 #define MULTI_USER 'm'
137 #define CLEAN_TTYS 'T'
138 #define CATATONIA 'c'
140 static state_func_t single_user(void);
141 static state_func_t runcom(void);
142 static state_func_t read_ttys(void);
143 static state_func_t multi_user(void);
144 static state_func_t clean_ttys(void);
145 static state_func_t catatonia(void);
146 static state_func_t death(void);
148 static void transition(state_t);
150 static void free_session(session_t *);
151 static session_t *new_session(session_t *, int, struct ttyent *);
153 static char **construct_argv(char *);
154 static void start_window_system(session_t *);
155 static void collect_child(pid_t);
156 static pid_t start_getty(session_t *);
157 static void transition_handler(int);
158 static void alrm_handler(int);
159 static void setsecuritylevel(int);
160 static int getsecuritylevel(void);
161 static char *get_chroot(void);
162 static int setupargv(session_t *, struct ttyent *);
164 static void setprocresources(const char *);
167 static void clear_session_logs(session_t *);
169 static int start_session_db(void);
170 static void add_session(session_t *);
171 static void del_session(session_t *);
172 static session_t *find_session(pid_t);
175 static struct timeval boot_time;
176 state_t current_state = death;
177 static void session_utmpx(const session_t *, int);
178 static void make_utmpx(const char *, const char *, int, pid_t,
179 const struct timeval *, int);
180 static char get_runlevel(const state_t);
181 static void utmpx_set_runlevel(char, char);
184 static int Reboot = FALSE;
185 static int howto = RB_AUTOBOOT;
187 static DB *session_db;
188 static volatile sig_atomic_t clang;
189 static session_t *sessions;
190 state_t requested_transition = runcom;
194 * The mother of all processes.
197 main(int argc, char **argv)
206 (void)gettimeofday(&boot_time, NULL);
207 #endif /* SUPPORT_UTMPX */
209 /* Dispose of random users. */
211 errx(1, "%s", strerror(EPERM));
213 /* System V users like to reexec init. */
215 #ifdef COMPAT_SYSV_INIT
216 /* So give them what they want */
218 if (strlen(argv[1]) == 1) {
219 char runlevel = *argv[1];
223 case '0': /* halt + poweroff */
226 case '1': /* single-user */
229 case '6': /* reboot */
232 case 'c': /* block further logins */
235 case 'q': /* rescan /etc/ttys */
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 * If chroot has been requested by the boot loader,
258 * do it now. Try to be robust: If the directory
259 * doesn't exist, continue anyway.
261 init_chroot = get_chroot();
262 if (init_chroot != NULL) {
263 if (chdir(init_chroot) == -1 || chroot(".") == -1)
264 warning("can't chroot to %s: %m", init_chroot);
269 * Create an initial session.
272 warning("initial setsid() failed: %m");
275 * Establish an initial user so that programs running
276 * single user do not freak out and die (like passwd).
278 if (setlogin("root") < 0)
279 warning("setlogin() failed: %m");
281 if (stat("/dev/null", &sts) < 0) {
282 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
287 * This code assumes that we always get arguments through flags,
288 * never through bits set in some random machine register.
290 while ((c = getopt(argc, argv, "dsf")) != -1)
293 /* We don't support DEVFS. */
296 requested_transition = single_user;
299 runcom_mode = FASTBOOT;
302 warning("unrecognized flag '-%c'", c);
307 warning("ignoring excess arguments");
310 * We catch or block signals rather than ignore them,
311 * so that they get reset on exec.
313 handle(badsys, SIGSYS, 0);
314 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
315 SIGBUS, SIGXCPU, SIGXFSZ, 0);
316 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
317 SIGUSR1, SIGUSR2, 0);
318 handle(alrm_handler, SIGALRM, 0);
320 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
321 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
322 SIGUSR1, SIGUSR2, 0);
323 sigprocmask(SIG_SETMASK, &mask, NULL);
324 sigemptyset(&sa.sa_mask);
326 sa.sa_handler = SIG_IGN;
327 sigaction(SIGTTIN, &sa, NULL);
328 sigaction(SIGTTOU, &sa, NULL);
338 * Start the state machine.
340 transition(requested_transition);
343 * Should never reach here.
349 * Associate a function with a signal handler.
352 handle(sig_t handler, ...)
356 sigset_t mask_everything;
359 va_start(ap, handler);
361 sa.sa_handler = handler;
362 sigfillset(&mask_everything);
364 while ((sig = va_arg(ap, int)) != 0) {
365 sa.sa_mask = mask_everything;
366 /* XXX SA_RESTART? */
367 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
368 sigaction(sig, &sa, NULL);
374 * Delete a set of signals from a mask.
377 delset(sigset_t *maskp, ...)
384 while ((sig = va_arg(ap, int)) != 0)
385 sigdelset(maskp, sig);
390 * Log a message and sleep for a while (to give someone an opportunity
391 * to read it and to save log or hardcopy output if the problem is chronic).
392 * NB: should send a message to the session logger to avoid blocking.
395 stall(const char *message, ...)
399 va_start(ap, message);
401 vsyslog(LOG_ALERT, message, ap);
403 sleep(STALL_TIMEOUT);
407 * Like stall(), but doesn't sleep.
408 * If cpp had variadic macros, the two functions could be #defines for another.
409 * NB: should send a message to the session logger to avoid blocking.
412 warning(const char *message, ...)
416 va_start(ap, message);
418 vsyslog(LOG_ALERT, message, ap);
423 * Log an emergency message.
424 * NB: should send a message to the session logger to avoid blocking.
427 emergency(const char *message, ...)
431 va_start(ap, message);
433 vsyslog(LOG_EMERG, message, ap);
438 * Catch a SIGSYS signal.
440 * These may arise if a system does not support sysctl.
441 * We tolerate up to 25 of these, then throw in the towel.
446 static int badcount = 0;
454 * Catch an unexpected signal.
459 emergency("fatal signal: %s",
460 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
462 sleep(STALL_TIMEOUT);
463 _exit(sig); /* reboot */
467 * Get the security level of the kernel.
470 getsecuritylevel(void)
472 #ifdef KERN_SECURELVL
473 int name[2], curlevel;
477 name[1] = KERN_SECURELVL;
478 len = sizeof curlevel;
479 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
480 emergency("cannot get kernel security level: %s",
491 * Get the value of the "init_chroot" variable from the
492 * kernel environment (or NULL if not set).
498 static const char ichname[] = "init_chroot="; /* includes '=' */
499 const int ichlen = strlen(ichname);
500 int real_oid[CTL_MAXNAME];
506 oidlen = __arysize(real_oid);
507 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
508 warning("cannot find kern.environment base sysctl OID");
511 if (oidlen + 1 >= __arysize(real_oid)) {
512 warning("kern.environment OID is too large!");
516 real_oid[oidlen] = 0;
519 real_oid[oidlen + 1] = i;
521 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
523 warning("sysctl kern.environment.%d: %m", i);
528 * slen includes the terminating \0, but do a few sanity
534 if (strncmp(sbuf, ichname, ichlen) != 0)
537 res = strdup(sbuf + ichlen);
544 * Set the security level of the kernel.
547 setsecuritylevel(int newlevel)
549 #ifdef KERN_SECURELVL
550 int name[2], curlevel;
552 curlevel = getsecuritylevel();
553 if (newlevel == curlevel)
556 name[1] = KERN_SECURELVL;
557 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
559 "cannot change kernel security level from %d to %d: %s",
560 curlevel, newlevel, strerror(errno));
564 warning("kernel security level changed from %d to %d",
571 * Change states in the finite state machine.
572 * The initial state is passed as an argument.
575 transition(state_t s)
579 utmpx_set_runlevel(get_runlevel(current_state),
583 s = (state_t) (*s)();
588 * Close out the accounting files for a login session.
589 * NB: should send a message to the session logger to avoid blocking.
592 clear_session_logs(session_t *sp)
594 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
597 if (logoutx(line, 0, DEAD_PROCESS))
598 logwtmpx(line, "", "", 0, DEAD_PROCESS);
601 logwtmp(line, "", "");
605 * Start a session and allocate a controlling terminal.
606 * Only called by children of init after forking.
609 setctty(const char *name)
614 if ((fd = open(name, O_RDWR)) == -1) {
615 stall("can't open %s: %m", name);
618 if (login_tty(fd) == -1) {
619 stall("can't get %s for controlling terminal: %m", name);
625 * Bring the system up single user.
633 const char *shell = _PATH_BSHELL;
638 static const char banner[] =
639 "Enter root password, or ^D to go multi-user\n";
640 char *clear, *password;
647 /* Instead of going single user, let's reboot the machine */
655 if ((pid = fork()) == 0) {
657 * Start the single user session.
659 setctty(_PATH_CONSOLE);
663 * Check the root password.
664 * We don't care if the console is 'on' by default;
665 * it's the only tty that can be 'off' and 'secure'.
667 typ = getttynam("console");
668 pp = getpwnam("root");
669 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
670 pp && *pp->pw_passwd) {
671 write(2, banner, sizeof banner - 1);
673 clear = getpass("Password:");
674 if (clear == NULL || *clear == '\0')
676 password = crypt(clear, pp->pw_passwd);
677 bzero(clear, _PASSWORD_LEN);
678 if (strcmp(password, pp->pw_passwd) == 0)
680 warning("single-user login failed\n");
693 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
694 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
695 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
696 num != 0 && *cp != '\n' && cp < &altshell[127])
699 if (altshell[0] != '\0')
702 #endif /* DEBUGSHELL */
706 * We catch all the interesting ones,
707 * and those are reset to SIG_DFL on exec.
710 sigprocmask(SIG_SETMASK, &mask, NULL);
714 * If the default one doesn't work, try the Bourne shell.
718 execv(shell, __DECONST(char **, argv));
719 emergency("can't exec %s for single user: %m", shell);
720 execv(_PATH_BSHELL, __DECONST(char **, argv));
721 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
722 sleep(STALL_TIMEOUT);
728 * We are seriously hosed. Do our best.
730 emergency("can't fork single-user shell, trying again");
731 while (waitpid(-1, NULL, WNOHANG) > 0)
733 return (state_func_t) single_user;
736 requested_transition = NULL;
738 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
743 warning("wait for single-user shell failed: %m; restarting");
744 return (state_func_t) single_user;
746 if (wpid == pid && WIFSTOPPED(status)) {
747 warning("init: shell stopped, restarting\n");
751 } while (wpid != pid && !requested_transition);
753 if (requested_transition)
754 return (state_func_t) requested_transition;
756 if (!WIFEXITED(status)) {
757 if (WTERMSIG(status) == SIGKILL) {
759 * reboot(8) killed shell?
761 warning("single user shell terminated.");
762 sleep(STALL_TIMEOUT);
765 warning("single user shell terminated, restarting");
766 return (state_func_t) single_user;
770 runcom_mode = FASTBOOT;
771 return (state_func_t) runcom;
775 * Run the system startup script.
785 if ((pid = fork()) == 0) {
786 sigemptyset(&sa.sa_mask);
788 sa.sa_handler = SIG_IGN;
789 sigaction(SIGTSTP, &sa, NULL);
790 sigaction(SIGHUP, &sa, NULL);
792 setctty(_PATH_CONSOLE);
795 argv[1] = _PATH_RUNCOM;
796 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
799 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
802 setprocresources(RESOURCE_RC);
804 execv(_PATH_BSHELL, __DECONST(char **, argv));
805 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
806 _exit(1); /* force single user mode */
810 emergency("can't fork for %s on %s: %m",
811 _PATH_BSHELL, _PATH_RUNCOM);
812 while (waitpid(-1, NULL, WNOHANG) > 0)
814 sleep(STALL_TIMEOUT);
815 return (state_func_t) single_user;
819 * Copied from single_user(). This is a bit paranoid.
821 requested_transition = NULL;
823 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
826 if (requested_transition == death)
827 return (state_func_t) death;
830 warning("wait for %s on %s failed: %m; going to single user mode",
831 _PATH_BSHELL, _PATH_RUNCOM);
832 return (state_func_t) single_user;
834 if (wpid == pid && WIFSTOPPED(status)) {
835 warning("init: %s on %s stopped, restarting\n",
836 _PATH_BSHELL, _PATH_RUNCOM);
840 } while (wpid != pid);
842 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
843 requested_transition == catatonia) {
844 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
852 if (!WIFEXITED(status)) {
853 warning("%s on %s terminated abnormally, going to single user mode",
854 _PATH_BSHELL, _PATH_RUNCOM);
855 return (state_func_t) single_user;
858 if (WEXITSTATUS(status))
859 return (state_func_t) single_user;
861 runcom_mode = AUTOBOOT; /* the default */
862 /* NB: should send a message to the session logger to avoid blocking. */
864 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
866 logwtmp("~", "reboot", "");
867 return (state_func_t) read_ttys;
871 * Open the session database.
873 * NB: We could pass in the size here; is it necessary?
876 start_session_db(void)
878 if (session_db && (*session_db->close)(session_db))
879 emergency("session database close: %s", strerror(errno));
880 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
881 emergency("session database open: %s", strerror(errno));
889 * Add a new login session.
892 add_session(session_t *sp)
897 key.data = &sp->se_process;
898 key.size = sizeof sp->se_process;
900 data.size = sizeof sp;
902 if ((*session_db->put)(session_db, &key, &data, 0))
903 emergency("insert %d: %s", sp->se_process, strerror(errno));
905 session_utmpx(sp, 1);
910 * Delete an old login session.
913 del_session(session_t *sp)
917 key.data = &sp->se_process;
918 key.size = sizeof sp->se_process;
920 if ((*session_db->del)(session_db, &key, 0))
921 emergency("delete %d: %s", sp->se_process, strerror(errno));
923 session_utmpx(sp, 0);
928 * Look up a login session by pid.
931 find_session(pid_t pid)
938 key.size = sizeof pid;
939 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
941 bcopy(data.data, (char *)&ret, sizeof(ret));
946 * Construct an argument vector from a command line.
949 construct_argv(char *command)
952 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
955 if ((argv[argc++] = strk(command)) == NULL) {
959 while ((argv[argc++] = strk(NULL)) != NULL)
965 * Deallocate a session descriptor.
968 free_session(session_t *sp)
973 free(sp->se_getty_argv_space);
974 free(sp->se_getty_argv);
978 free(sp->se_window_argv_space);
979 free(sp->se_window_argv);
987 * Allocate a new session descriptor.
988 * Mark it SE_PRESENT.
991 new_session(session_t *sprev, int session_index, struct ttyent *typ)
996 if ((typ->ty_status & TTY_ON) == 0 ||
1001 sp = (session_t *) calloc(1, sizeof (session_t));
1003 sp->se_index = session_index;
1004 sp->se_flags |= SE_PRESENT;
1006 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1007 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1010 * Attempt to open the device, if we get "device not configured"
1011 * then don't add the device to the session list.
1013 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1014 if (errno == ENXIO) {
1021 if (setupargv(sp, typ) == 0) {
1027 if (sprev == NULL) {
1031 sprev->se_next = sp;
1032 sp->se_prev = sprev;
1039 * Calculate getty and if useful window argv vectors.
1042 setupargv(session_t *sp, struct ttyent *typ)
1047 free(sp->se_getty_argv_space);
1048 free(sp->se_getty_argv);
1050 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1051 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1052 sp->se_getty_argv_space = strdup(sp->se_getty);
1053 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1054 if (sp->se_getty_argv == NULL) {
1055 warning("can't parse getty for port %s", sp->se_device);
1057 free(sp->se_getty_argv_space);
1058 sp->se_getty = sp->se_getty_argv_space = NULL;
1061 if (sp->se_window) {
1062 free(sp->se_window);
1063 free(sp->se_window_argv_space);
1064 free(sp->se_window_argv);
1066 sp->se_window = sp->se_window_argv_space = NULL;
1067 sp->se_window_argv = NULL;
1068 if (typ->ty_window) {
1069 sp->se_window = strdup(typ->ty_window);
1070 sp->se_window_argv_space = strdup(sp->se_window);
1071 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1072 if (sp->se_window_argv == NULL) {
1073 warning("can't parse window for port %s",
1075 free(sp->se_window_argv_space);
1076 free(sp->se_window);
1077 sp->se_window = sp->se_window_argv_space = NULL;
1083 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1088 * Walk the list of ttys and create sessions for each active line.
1093 int session_index = 0;
1094 session_t *sp, *snext;
1097 #ifdef SUPPORT_UTMPX
1098 if (sessions == NULL) {
1101 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1104 * If wtmpx is not empty, pick the down time from there
1106 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1107 struct timeval down_time;
1109 TIMESPEC_TO_TIMEVAL(&down_time,
1110 st.st_atime > st.st_mtime ?
1111 &st.st_atimespec : &st.st_mtimespec);
1112 make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1117 * Destroy any previous session state.
1118 * There shouldn't be any, but just in case...
1120 for (sp = sessions; sp; sp = snext) {
1122 clear_session_logs(sp);
1123 snext = sp->se_next;
1127 if (start_session_db())
1128 return (state_func_t) single_user;
1131 * Allocate a session entry for each active port.
1132 * Note that sp starts at 0.
1134 while ((typ = getttyent()) != NULL)
1135 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1140 return (state_func_t) multi_user;
1144 * Start a window system running.
1147 start_window_system(session_t *sp)
1151 char term[64], *env[2];
1153 if ((pid = fork()) == -1) {
1154 emergency("can't fork for window system on port %s: %m",
1156 /* hope that getty fails and we can try again */
1164 sigprocmask(SIG_SETMASK, &mask, NULL);
1167 emergency("setsid failed (window) %m");
1170 setprocresources(RESOURCE_WINDOW);
1173 /* Don't use malloc after fork */
1174 strcpy(term, "TERM=");
1175 strncat(term, sp->se_type, sizeof(term) - 6);
1181 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1182 stall("can't exec window system '%s' for port %s: %m",
1183 sp->se_window_argv[0], sp->se_device);
1188 * Start a login session running.
1191 start_getty(session_t *sp)
1195 time_t current_time = time(NULL);
1197 char term[64], *env[2];
1199 if (current_time >= sp->se_started.tv_sec &&
1200 current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1201 if (++sp->se_nspace > GETTY_NSPACE) {
1209 * fork(), not vfork() -- we can't afford to block.
1211 if ((pid = fork()) == -1) {
1212 emergency("can't fork for getty on port %s: %m", sp->se_device);
1220 warning("getty repeating too quickly on port %s, sleeping %d secs",
1221 sp->se_device, GETTY_SLEEP);
1222 sleep((unsigned) GETTY_SLEEP);
1225 if (sp->se_window) {
1226 start_window_system(sp);
1231 sigprocmask(SIG_SETMASK, &mask, NULL);
1234 setprocresources(RESOURCE_GETTY);
1237 /* Don't use malloc after fork */
1238 strcpy(term, "TERM=");
1239 strncat(term, sp->se_type, sizeof(term) - 6);
1245 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1246 stall("can't exec getty '%s' for port %s: %m",
1247 sp->se_getty_argv[0], sp->se_device);
1252 * Collect exit status for a child.
1253 * If an exiting login, start a new login running.
1256 collect_child(pid_t pid)
1258 session_t *sp, *sprev, *snext;
1263 if (! (sp = find_session(pid)))
1266 clear_session_logs(sp);
1270 if (sp->se_flags & SE_SHUTDOWN) {
1271 if ((sprev = sp->se_prev) != NULL)
1272 sprev->se_next = sp->se_next;
1274 sessions = sp->se_next;
1275 if ((snext = sp->se_next) != NULL)
1276 snext->se_prev = sp->se_prev;
1281 if ((pid = start_getty(sp)) == -1) {
1282 /* serious trouble */
1283 requested_transition = clean_ttys;
1287 sp->se_process = pid;
1288 gettimeofday(&sp->se_started, NULL);
1293 * Catch a signal and request a state transition.
1296 transition_handler(int sig)
1301 requested_transition = clean_ttys;
1304 howto = RB_POWEROFF;
1310 requested_transition = death;
1313 requested_transition = catatonia;
1316 requested_transition = NULL;
1322 * Take the system multiuser.
1330 requested_transition = NULL;
1333 * If the administrator has not set the security level to -1
1334 * to indicate that the kernel should not run multiuser in secure
1335 * mode, and the run script has not set a higher level of security
1336 * than level 1, then put the kernel into secure mode.
1338 if (getsecuritylevel() == 0)
1339 setsecuritylevel(1);
1341 for (sp = sessions; sp; sp = sp->se_next) {
1344 if ((pid = start_getty(sp)) == -1) {
1345 /* serious trouble */
1346 requested_transition = clean_ttys;
1349 sp->se_process = pid;
1350 gettimeofday(&sp->se_started, NULL);
1354 while (!requested_transition)
1355 if ((pid = waitpid(-1, NULL, 0)) != -1)
1358 return (state_func_t) requested_transition;
1362 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1367 session_t *sp, *sprev;
1369 int session_index = 0;
1371 char *old_getty, *old_window, *old_type;
1374 return (state_func_t) multi_user;
1377 * mark all sessions for death, (!SE_PRESENT)
1378 * as we find or create new ones they'll be marked as keepers,
1379 * we'll later nuke all the ones not found in /etc/ttys
1381 for (sp = sessions; sp != NULL; sp = sp->se_next)
1382 sp->se_flags &= ~SE_PRESENT;
1384 devlen = sizeof(_PATH_DEV) - 1;
1385 while ((typ = getttyent()) != NULL) {
1388 for (sprev = NULL, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1389 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1393 /* we want this one to live */
1394 sp->se_flags |= SE_PRESENT;
1395 if (sp->se_index != session_index) {
1396 warning("port %s changed utmp index from %d to %d",
1397 sp->se_device, sp->se_index,
1399 sp->se_index = session_index;
1401 if ((typ->ty_status & TTY_ON) == 0 ||
1402 typ->ty_getty == 0) {
1403 sp->se_flags |= SE_SHUTDOWN;
1404 kill(sp->se_process, SIGHUP);
1407 sp->se_flags &= ~SE_SHUTDOWN;
1408 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1409 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1410 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1411 if (setupargv(sp, typ) == 0) {
1412 warning("can't parse getty for port %s",
1414 sp->se_flags |= SE_SHUTDOWN;
1415 kill(sp->se_process, SIGHUP);
1417 else if ( !old_getty
1418 || (!old_type && sp->se_type)
1419 || (old_type && !sp->se_type)
1420 || (!old_window && sp->se_window)
1421 || (old_window && !sp->se_window)
1422 || (strcmp(old_getty, sp->se_getty) != 0)
1423 || (old_window && strcmp(old_window, sp->se_window) != 0)
1424 || (old_type && strcmp(old_type, sp->se_type) != 0)
1426 /* Don't set SE_SHUTDOWN here */
1428 sp->se_started.tv_sec = sp->se_started.tv_usec = 0;
1429 kill(sp->se_process, SIGHUP);
1440 new_session(sprev, session_index, typ);
1446 * sweep through and kill all deleted sessions
1447 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1449 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1450 if ((sp->se_flags & SE_PRESENT) == 0) {
1451 sp->se_flags |= SE_SHUTDOWN;
1452 kill(sp->se_process, SIGHUP);
1456 return (state_func_t) multi_user;
1460 * Block further logins.
1467 for (sp = sessions; sp; sp = sp->se_next)
1468 sp->se_flags |= SE_SHUTDOWN;
1470 return (state_func_t) multi_user;
1477 alrm_handler(int sig __unused)
1483 * Bring the system down to single user.
1491 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1493 /* NB: should send a message to the session logger to avoid blocking. */
1494 #ifdef SUPPORT_UTMPX
1495 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1497 logwtmp("~", "shutdown", "");
1499 for (sp = sessions; sp; sp = sp->se_next) {
1500 sp->se_flags |= SE_SHUTDOWN;
1501 kill(sp->se_process, SIGHUP);
1504 /* Try to run the rc.shutdown script within a period of time */
1507 for (i = 0; i < 2; ++i) {
1508 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1509 return (state_func_t) single_user;
1514 if ((pid = waitpid(-1, NULL, 0)) != -1)
1516 while (clang == 0 && errno != ECHILD);
1518 if (errno == ECHILD)
1519 return (state_func_t) single_user;
1522 warning("some processes would not die; ps axl advised");
1524 return (state_func_t) single_user;
1528 * Run the system shutdown script.
1530 * Exit codes: XXX I should document more
1531 * -2 shutdown script terminated abnormally
1532 * -1 fatal error - can't run script
1534 * >0 some error (exit code)
1541 int shutdowntimeout;
1543 const char *argv[4];
1544 struct sigaction sa;
1548 * rc.shutdown is optional, so to prevent any unnecessary
1549 * complaints from the shell we simply don't run it if the
1550 * file does not exist. If the stat() here fails for other
1551 * reasons, we'll let the shell complain.
1553 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1556 if ((pid = fork()) == 0) {
1559 /* Assume that init already grab console as ctty before */
1561 sigemptyset(&sa.sa_mask);
1563 sa.sa_handler = SIG_IGN;
1564 sigaction(SIGTSTP, &sa, NULL);
1565 sigaction(SIGHUP, &sa, NULL);
1567 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1568 warning("can't open %s: %m", _PATH_CONSOLE);
1578 * Run the shutdown script.
1581 argv[1] = _PATH_RUNDOWN;
1588 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1591 setprocresources(RESOURCE_RC);
1593 execv(_PATH_BSHELL, __DECONST(char **, argv));
1594 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1595 _exit(1); /* force single user mode */
1599 emergency("can't fork for %s on %s: %m",
1600 _PATH_BSHELL, _PATH_RUNDOWN);
1601 while (waitpid(-1, NULL, WNOHANG) > 0)
1603 sleep(STALL_TIMEOUT);
1607 len = sizeof(shutdowntimeout);
1608 if (sysctlbyname("kern.init_shutdown_timeout",
1610 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1611 shutdowntimeout = DEATH_SCRIPT;
1612 alarm(shutdowntimeout);
1615 * Copied from single_user(). This is a bit paranoid.
1616 * Use the same ALRM handler.
1619 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1620 collect_child(wpid);
1622 /* we were waiting for the sub-shell */
1623 kill(wpid, SIGTERM);
1624 warning("timeout expired for %s on %s: %m; going to single user mode",
1625 _PATH_BSHELL, _PATH_RUNDOWN);
1631 warning("wait for %s on %s failed: %m; going to single user mode",
1632 _PATH_BSHELL, _PATH_RUNDOWN);
1635 if (wpid == pid && WIFSTOPPED(status)) {
1636 warning("init: %s on %s stopped, restarting\n",
1637 _PATH_BSHELL, _PATH_RUNDOWN);
1641 } while (wpid != pid && !clang);
1643 /* Turn off the alarm */
1646 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1647 requested_transition == catatonia) {
1649 * /etc/rc.shutdown executed /sbin/reboot;
1650 * wait for the end quietly
1659 if (!WIFEXITED(status)) {
1660 warning("%s on %s terminated abnormally, going to single user mode",
1661 _PATH_BSHELL, _PATH_RUNDOWN);
1665 if ((status = WEXITSTATUS(status)) != 0)
1666 warning("%s returned status %d", _PATH_RUNDOWN, status);
1684 while (c == ' ' || c == '\t' )
1694 while (c && c != '\'')
1696 if (!c) /* unterminated string */
1701 while (c && c != ' ' && c != '\t' )
1712 setprocresources(const char *cname)
1715 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1716 setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1722 #ifdef SUPPORT_UTMPX
1724 session_utmpx(const session_t *sp, int add)
1726 const char *name = sp->se_getty ? sp->se_getty :
1727 (sp->se_window ? sp->se_window : "");
1728 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1730 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1731 sp->se_process, &sp->se_started, sp->se_index);
1735 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1736 const struct timeval *tv, int session)
1741 (void)memset(&ut, 0, sizeof(ut));
1742 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1744 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1749 (void)gettimeofday(&ut.ut_tv, NULL);
1750 ut.ut_session = session;
1752 eline = line + strlen(line);
1753 if ((size_t)(eline - line) >= sizeof(ut.ut_id))
1754 line = eline - sizeof(ut.ut_id);
1755 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1757 if (pututxline(&ut) == NULL)
1758 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1763 get_runlevel(const state_t s)
1765 if (s == (state_t)single_user)
1767 if (s == (state_t)runcom)
1769 if (s == (state_t)read_ttys)
1771 if (s == (state_t)multi_user)
1773 if (s == (state_t)clean_ttys)
1775 if (s == (state_t)catatonia)
1781 utmpx_set_runlevel(char old, char new)
1786 * Don't record any transitions until we did the first transition
1787 * to read ttys, which is when we are guaranteed to have a read-write
1788 * /var. Perhaps use a different variable for this?
1790 if (sessions == NULL)
1793 (void)memset(&ut, 0, sizeof(ut));
1794 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1795 ut.ut_type = RUN_LVL;
1796 (void)gettimeofday(&ut.ut_tv, NULL);
1797 ut.ut_exit.e_exit = old;
1798 ut.ut_exit.e_termination = new;
1799 if (pututxline(&ut) == NULL)
1800 warning("can't add utmpx record for `runlevel': %m");