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 */
85 * User-based resource limits.
87 #define RESOURCE_RC "daemon"
88 #define RESOURCE_WINDOW "default"
89 #define RESOURCE_GETTY "default"
92 #define DEFAULT_STATE runcom
105 typedef state_t (*state_func_t)(void);
107 static state_t f_single_user(void);
108 static state_t f_runcom(void);
109 static state_t f_read_ttys(void);
110 static state_t f_multi_user(void);
111 static state_t f_clean_ttys(void);
112 static state_t f_catatonia(void);
113 static state_t f_death(void);
115 state_func_t state_funcs[] = {
126 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
130 static void transition(state_t);
131 static volatile sig_atomic_t requested_transition = DEFAULT_STATE;
133 static void setctty(const char *);
135 typedef struct init_session {
136 int se_index; /* index of entry in ttys file */
137 pid_t se_process; /* controlling process */
138 struct timeval se_started; /* used to avoid thrashing */
139 int se_flags; /* status of session */
140 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
141 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
142 int se_nspace; /* spacing count */
143 char *se_device; /* filename of port */
144 char *se_getty; /* what to run on that port */
145 char *se_getty_argv_space; /* pre-parsed argument array space */
146 char **se_getty_argv; /* pre-parsed argument array */
147 char *se_window; /* window system (started only once) */
148 char *se_window_argv_space; /* pre-parsed argument array space */
149 char **se_window_argv; /* pre-parsed argument array */
150 char *se_type; /* default terminal type */
151 struct init_session *se_prev;
152 struct init_session *se_next;
155 static void handle(sig_t, ...);
156 static void delset(sigset_t *, ...);
158 static void stall(const char *, ...) __printflike(1, 2);
159 static void warning(const char *, ...) __printflike(1, 2);
160 static void emergency(const char *, ...) __printflike(1, 2);
161 static void disaster(int);
162 static void badsys(int);
163 static int runshutdown(void);
164 static char *strk(char *);
167 #define SINGLE_USER 's'
169 #define READ_TTYS 't'
170 #define MULTI_USER 'm'
171 #define CLEAN_TTYS 'T'
172 #define CATATONIA 'c'
174 static void free_session(session_t *);
175 static session_t *new_session(session_t *, int, struct ttyent *);
176 static void adjttyent(struct ttyent *typ);
178 static char **construct_argv(char *);
179 static void start_window_system(session_t *);
180 static void collect_child(pid_t, int);
181 static pid_t start_getty(session_t *);
182 static void transition_handler(int);
183 static void alrm_handler(int);
184 static void setsecuritylevel(int);
185 static int getsecuritylevel(void);
186 static char *get_chroot(void);
187 static int setupargv(session_t *, struct ttyent *);
189 static void setprocresources(const char *);
192 static void clear_session_logs(session_t *, int);
194 static int start_session_db(void);
195 static void add_session(session_t *);
196 static void del_session(session_t *);
197 static session_t *find_session(pid_t);
199 static struct timeval boot_time;
200 state_t current_state = death;
201 static void session_utmpx(const session_t *, int);
202 static void make_utmpx(const char *, const char *, int, pid_t,
203 const struct timeval *, int);
204 static char get_runlevel(const state_t);
205 static void utmpx_set_runlevel(char, char);
207 static int Reboot = FALSE;
208 static int howto = RB_AUTOBOOT;
210 static DB *session_db;
211 static volatile sig_atomic_t clang;
212 static session_t *sessions;
215 * The mother of all processes.
218 main(int argc, char *argv[])
226 (void)gettimeofday(&boot_time, NULL);
228 /* Dispose of random users. */
230 errx(1, "%s", strerror(EPERM));
232 /* System V users like to reexec init. */
234 #ifdef COMPAT_SYSV_INIT
235 /* So give them what they want */
237 if (strlen(argv[1]) == 1) {
238 char runlevel = *argv[1];
242 case '0': /* halt + poweroff */
245 case '1': /* single-user */
248 case '6': /* reboot */
251 case 'c': /* block further logins */
254 case 'q': /* rescan /etc/ttys */
264 errx(1, "invalid run-level ``%s''", argv[1]);
267 errx(1, "already running");
270 * Note that this does NOT open a file...
271 * Does 'init' deserve its own facility number?
273 openlog("init", LOG_CONS, LOG_AUTH);
276 * If chroot has been requested by the boot loader,
277 * do it now. Try to be robust: If the directory
278 * doesn't exist, continue anyway.
280 init_chroot = get_chroot();
281 if (init_chroot != NULL) {
282 if (chdir(init_chroot) == -1 || chroot(".") == -1)
283 warning("can't chroot to %s: %m", init_chroot);
288 * Create an initial session.
291 warning("initial setsid() failed: %m");
294 * Establish an initial user so that programs running
295 * single user do not freak out and die (like passwd).
297 if (setlogin("root") < 0)
298 warning("setlogin() failed: %m");
300 if (stat("/dev/null", &sts) < 0) {
301 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
306 * This code assumes that we always get arguments through flags,
307 * never through bits set in some random machine register.
309 while ((c = getopt(argc, argv, "dsf")) != -1)
312 /* We don't support DEVFS. */
315 requested_transition = single_user;
318 runcom_mode = FASTBOOT;
321 warning("unrecognized flag '-%c'", c);
326 warning("ignoring excess arguments");
329 * We catch or block signals rather than ignore them,
330 * so that they get reset on exec.
332 handle(badsys, SIGSYS, 0);
333 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
334 SIGBUS, SIGXCPU, SIGXFSZ, 0);
335 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
336 SIGUSR1, SIGUSR2, 0);
337 handle(alrm_handler, SIGALRM, 0);
339 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
340 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
341 SIGUSR1, SIGUSR2, 0);
342 sigprocmask(SIG_SETMASK, &mask, NULL);
343 sigemptyset(&sa.sa_mask);
345 sa.sa_handler = SIG_IGN;
346 sigaction(SIGTTIN, &sa, NULL);
347 sigaction(SIGTTOU, &sa, NULL);
357 * Start the state machine.
359 transition(requested_transition);
362 * Should never reach here.
368 * Associate a function with a signal handler.
371 handle(sig_t handler, ...)
375 sigset_t mask_everything;
378 va_start(ap, handler);
380 sa.sa_handler = handler;
381 sigfillset(&mask_everything);
383 while ((sig = va_arg(ap, int)) != 0) {
384 sa.sa_mask = mask_everything;
385 /* XXX SA_RESTART? */
386 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
387 sigaction(sig, &sa, NULL);
393 * Delete a set of signals from a mask.
396 delset(sigset_t *maskp, ...)
403 while ((sig = va_arg(ap, int)) != 0)
404 sigdelset(maskp, sig);
409 * Log a message and sleep for a while (to give someone an opportunity
410 * to read it and to save log or hardcopy output if the problem is chronic).
413 stall(const char *message, ...)
417 va_start(ap, message);
419 vsyslog(LOG_ALERT, message, ap);
421 sleep(STALL_TIMEOUT);
425 * Like stall(), but doesn't sleep.
426 * If cpp had variadic macros, the two functions could be #defines for another.
429 warning(const char *message, ...)
433 va_start(ap, message);
435 vsyslog(LOG_ALERT, message, ap);
440 * Log an emergency message.
443 emergency(const char *message, ...)
447 va_start(ap, message);
449 vsyslog(LOG_EMERG, message, ap);
454 * Catch a SIGSYS signal.
456 * These may arise if a system does not support sysctl.
457 * We tolerate up to 25 of these, then throw in the towel.
462 static int badcount = 0;
470 * Catch an unexpected signal.
475 emergency("fatal signal: %s",
476 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
478 sleep(STALL_TIMEOUT);
479 _exit(sig); /* reboot */
483 * Get the security level of the kernel.
486 getsecuritylevel(void)
488 #ifdef KERN_SECURELVL
489 int name[2], curlevel;
493 name[1] = KERN_SECURELVL;
494 len = sizeof curlevel;
495 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
496 emergency("cannot get kernel security level: %s",
507 * Get the value of the "init_chroot" variable from the
508 * kernel environment (or NULL if not set).
514 static const char ichname[] = "init_chroot="; /* includes '=' */
515 const int ichlen = strlen(ichname);
516 int real_oid[CTL_MAXNAME];
522 oidlen = NELEM(real_oid);
523 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
524 warning("cannot find kern.environment base sysctl OID");
527 if (oidlen + 1 >= NELEM(real_oid)) {
528 warning("kern.environment OID is too large!");
532 real_oid[oidlen] = 0;
535 real_oid[oidlen + 1] = i;
537 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
539 warning("sysctl kern.environment.%d: %m", i);
544 * slen includes the terminating \0, but do a few sanity
550 if (strncmp(sbuf, ichname, ichlen) != 0)
553 res = strdup(sbuf + ichlen);
560 * Set the security level of the kernel.
563 setsecuritylevel(int newlevel)
565 #ifdef KERN_SECURELVL
566 int name[2], curlevel;
568 curlevel = getsecuritylevel();
569 if (newlevel == curlevel)
572 name[1] = KERN_SECURELVL;
573 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
575 "cannot change kernel security level from %d to %d: %s",
576 curlevel, newlevel, strerror(errno));
580 warning("kernel security level changed from %d to %d",
587 * Change states in the finite state machine.
588 * The initial state is passed as an argument.
591 transition(state_t s)
594 utmpx_set_runlevel(get_runlevel(current_state),
597 s = (*state_funcs[s])();
602 * Close out the accounting files for a login session.
605 clear_session_logs(session_t *sp, int status)
607 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
609 if (logoutx(line, status, DEAD_PROCESS))
610 logwtmpx(line, "", "", status, DEAD_PROCESS);
614 * Start a session and allocate a controlling terminal.
615 * Only called by children of init after forking.
618 setctty(const char *name)
623 if ((fd = open(name, O_RDWR)) == -1) {
624 stall("can't open %s: %m", name);
627 if (login_tty(fd) == -1) {
628 stall("can't get %s for controlling terminal: %m", name);
634 * Bring the system up single user.
642 const char *shell = _PATH_BSHELL;
647 static const char banner[] =
648 "Enter root password, or ^D to go multi-user\n";
649 char *clear, *password;
656 /* Instead of going single user, let's reboot the machine */
664 if ((pid = fork()) == 0) {
666 * Start the single user session.
668 setctty(_PATH_CONSOLE);
672 * Check the root password.
673 * We don't care if the console is 'on' by default;
674 * it's the only tty that can be 'off' and 'secure'.
676 typ = getttynam("console");
677 pp = getpwnam("root");
678 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
679 pp && *pp->pw_passwd) {
680 write(2, banner, sizeof banner - 1);
682 clear = getpass("Password:");
683 if (clear == NULL || *clear == '\0')
685 password = crypt(clear, pp->pw_passwd);
686 bzero(clear, _PASSWORD_LEN);
687 if (password != NULL && strcmp(password, pp->pw_passwd) == 0)
689 warning("single-user login failed\n");
702 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
703 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
704 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
705 num != 0 && *cp != '\n' && cp < &altshell[127])
708 if (altshell[0] != '\0')
711 #endif /* DEBUGSHELL */
715 * We catch all the interesting ones,
716 * and those are reset to SIG_DFL on exec.
719 sigprocmask(SIG_SETMASK, &mask, NULL);
723 * If the default one doesn't work, try the Bourne shell.
727 execv(shell, __DECONST(char **, argv));
728 emergency("can't exec %s for single user: %m", shell);
729 execv(_PATH_BSHELL, __DECONST(char **, argv));
730 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
731 sleep(STALL_TIMEOUT);
737 * We are seriously hosed. Do our best.
739 emergency("can't fork single-user shell, trying again");
740 while (waitpid(-1, NULL, WNOHANG) > 0)
745 requested_transition = 0;
747 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
748 collect_child(wpid, status);
752 warning("wait for single-user shell failed: %m; restarting");
755 if (wpid == pid && WIFSTOPPED(status)) {
756 warning("init: shell stopped, restarting\n");
760 } while (wpid != pid && !requested_transition);
762 if (requested_transition)
763 return requested_transition;
765 if (!WIFEXITED(status)) {
766 if (WTERMSIG(status) == SIGKILL) {
768 * reboot(8) killed shell?
770 warning("single user shell terminated.");
771 sleep(STALL_TIMEOUT);
774 warning("single user shell terminated, restarting");
779 runcom_mode = FASTBOOT;
784 * Run the system startup script.
794 if ((pid = fork()) == 0) {
795 sigemptyset(&sa.sa_mask);
797 sa.sa_handler = SIG_IGN;
798 sigaction(SIGTSTP, &sa, NULL);
799 sigaction(SIGHUP, &sa, NULL);
801 setctty(_PATH_CONSOLE);
804 argv[1] = _PATH_RUNCOM;
805 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
808 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
811 setprocresources(RESOURCE_RC);
813 execv(_PATH_BSHELL, __DECONST(char **, argv));
814 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
815 _exit(1); /* force single user mode */
819 emergency("can't fork for %s on %s: %m",
820 _PATH_BSHELL, _PATH_RUNCOM);
821 while (waitpid(-1, NULL, WNOHANG) > 0)
823 sleep(STALL_TIMEOUT);
828 * Copied from single_user(). This is a bit paranoid.
830 requested_transition = 0;
832 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
833 collect_child(wpid, status);
835 if (requested_transition == death)
839 warning("wait for %s on %s failed: %m; going to single user mode",
840 _PATH_BSHELL, _PATH_RUNCOM);
843 if (wpid == pid && WIFSTOPPED(status)) {
844 warning("init: %s on %s stopped, restarting\n",
845 _PATH_BSHELL, _PATH_RUNCOM);
849 } while (wpid != pid);
851 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
852 requested_transition == catatonia) {
853 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
861 if (!WIFEXITED(status)) {
862 warning("%s on %s terminated abnormally, going to single user mode",
863 _PATH_BSHELL, _PATH_RUNCOM);
867 if (WEXITSTATUS(status))
870 runcom_mode = AUTOBOOT; /* the default */
871 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
876 * Open the session database.
878 * NB: We could pass in the size here; is it necessary?
881 start_session_db(void)
883 if (session_db && (*session_db->close)(session_db))
884 emergency("session database close: %s", strerror(errno));
885 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
886 emergency("session database open: %s", strerror(errno));
894 * Add a new login session.
897 add_session(session_t *sp)
902 key.data = &sp->se_process;
903 key.size = sizeof sp->se_process;
905 data.size = sizeof sp;
907 if ((*session_db->put)(session_db, &key, &data, 0))
908 emergency("insert %d: %s", sp->se_process, strerror(errno));
909 session_utmpx(sp, 1);
913 * Delete an old login session.
916 del_session(session_t *sp)
920 key.data = &sp->se_process;
921 key.size = sizeof sp->se_process;
923 if ((*session_db->del)(session_db, &key, 0))
924 emergency("delete %d: %s", sp->se_process, strerror(errno));
925 session_utmpx(sp, 0);
929 * Look up a login session by pid.
932 find_session(pid_t pid)
939 key.size = sizeof pid;
940 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
942 bcopy(data.data, (char *)&ret, sizeof(ret));
947 * Construct an argument vector from a command line.
950 construct_argv(char *command)
953 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
956 if ((argv[argc++] = strk(command)) == NULL) {
960 while ((argv[argc++] = strk(NULL)) != NULL)
966 * Deallocate a session descriptor.
969 free_session(session_t *sp)
974 free(sp->se_getty_argv_space);
975 free(sp->se_getty_argv);
979 free(sp->se_window_argv_space);
980 free(sp->se_window_argv);
989 adjttyent(struct ttyent *typ)
994 size_t rdev_size = sizeof(rdev);
996 if (typ->ty_name == NULL)
1000 * IFCONSOLE option forces tty off if not the console.
1002 if (typ->ty_status & TTY_IFCONSOLE) {
1003 asprintf(&devpath, "%s%s", _PATH_DEV, typ->ty_name);
1004 if (stat(devpath, &st) < 0 ||
1005 sysctlbyname("kern.console_rdev",
1008 /* device does not exist or no sysctl, disable */
1009 typ->ty_status &= ~TTY_ON;
1010 } else if (rdev != st.st_rdev) {
1011 typ->ty_status &= ~TTY_ON;
1018 * Allocate a new session descriptor.
1019 * Mark it SE_PRESENT.
1022 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1027 if (typ->ty_name == NULL || typ->ty_getty == NULL)
1030 if ((typ->ty_status & TTY_ON) == 0)
1033 sp = (session_t *) calloc(1, sizeof (session_t));
1035 asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1036 sp->se_index = session_index;
1037 sp->se_flags |= SE_PRESENT;
1040 * Attempt to open the device, if we get "device not configured"
1041 * then don't add the device to the session list.
1043 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1044 if (errno == ENXIO) {
1051 if (setupargv(sp, typ) == 0) {
1057 if (sprev == NULL) {
1061 sprev->se_next = sp;
1062 sp->se_prev = sprev;
1069 * Calculate getty and if useful window argv vectors.
1072 setupargv(session_t *sp, struct ttyent *typ)
1077 free(sp->se_getty_argv_space);
1078 free(sp->se_getty_argv);
1080 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1081 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1082 sp->se_getty_argv_space = strdup(sp->se_getty);
1083 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1084 if (sp->se_getty_argv == NULL) {
1085 warning("can't parse getty for port %s", sp->se_device);
1087 free(sp->se_getty_argv_space);
1088 sp->se_getty = sp->se_getty_argv_space = NULL;
1091 if (sp->se_window) {
1092 free(sp->se_window);
1093 free(sp->se_window_argv_space);
1094 free(sp->se_window_argv);
1096 sp->se_window = sp->se_window_argv_space = NULL;
1097 sp->se_window_argv = NULL;
1098 if (typ->ty_window) {
1099 sp->se_window = strdup(typ->ty_window);
1100 sp->se_window_argv_space = strdup(sp->se_window);
1101 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1102 if (sp->se_window_argv == NULL) {
1103 warning("can't parse window for port %s",
1105 free(sp->se_window_argv_space);
1106 free(sp->se_window);
1107 sp->se_window = sp->se_window_argv_space = NULL;
1113 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1118 * Walk the list of ttys and create sessions for each active line.
1123 int session_index = 0;
1124 session_t *sp, *snext;
1127 if (sessions == NULL) {
1130 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1133 * If wtmpx is not empty, pick the down time from there
1135 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1136 struct timeval down_time;
1138 TIMESPEC_TO_TIMEVAL(&down_time,
1139 st.st_atime > st.st_mtime ?
1140 &st.st_atimespec : &st.st_mtimespec);
1141 make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1145 * Destroy any previous session state.
1146 * There shouldn't be any, but just in case...
1148 for (sp = sessions; sp; sp = snext) {
1150 clear_session_logs(sp, 0);
1151 snext = sp->se_next;
1155 if (start_session_db())
1159 * Allocate a session entry for each active port.
1160 * Note that sp starts at 0.
1162 while ((typ = getttyent()) != NULL) {
1164 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1174 * Start a window system running.
1177 start_window_system(session_t *sp)
1181 char term[64], *env[2];
1183 if ((pid = fork()) == -1) {
1184 emergency("can't fork for window system on port %s: %m",
1186 /* hope that getty fails and we can try again */
1194 sigprocmask(SIG_SETMASK, &mask, NULL);
1197 emergency("setsid failed (window) %m");
1200 setprocresources(RESOURCE_WINDOW);
1203 /* Don't use malloc after fork */
1204 strcpy(term, "TERM=");
1205 strncat(term, sp->se_type, sizeof(term) - 6);
1211 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1212 stall("can't exec window system '%s' for port %s: %m",
1213 sp->se_window_argv[0], sp->se_device);
1218 * Start a login session running.
1221 start_getty(session_t *sp)
1225 time_t current_time = time(NULL);
1227 char term[64], *env[2];
1229 if (current_time >= sp->se_started.tv_sec &&
1230 current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1231 if (++sp->se_nspace > GETTY_NSPACE) {
1239 * fork(), not vfork() -- we can't afford to block.
1241 if ((pid = fork()) == -1) {
1242 emergency("can't fork for getty on port %s: %m", sp->se_device);
1250 warning("getty repeating too quickly on port %s, sleeping %d secs",
1251 sp->se_device, GETTY_SLEEP);
1252 sleep((unsigned) GETTY_SLEEP);
1255 if (sp->se_window) {
1256 start_window_system(sp);
1261 sigprocmask(SIG_SETMASK, &mask, NULL);
1264 setprocresources(RESOURCE_GETTY);
1267 /* Don't use malloc after fork */
1268 strcpy(term, "TERM=");
1269 strncat(term, sp->se_type, sizeof(term) - 6);
1275 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1276 stall("can't exec getty '%s' for port %s: %m",
1277 sp->se_getty_argv[0], sp->se_device);
1282 * Collect exit status for a child.
1283 * If an exiting login, start a new login running.
1286 collect_child(pid_t pid, int status)
1288 session_t *sp, *sprev, *snext;
1293 if (! (sp = find_session(pid)))
1296 clear_session_logs(sp, status);
1300 if (sp->se_flags & SE_SHUTDOWN) {
1301 if ((sprev = sp->se_prev) != NULL)
1302 sprev->se_next = sp->se_next;
1304 sessions = sp->se_next;
1305 if ((snext = sp->se_next) != NULL)
1306 snext->se_prev = sp->se_prev;
1311 if ((pid = start_getty(sp)) == -1) {
1312 /* serious trouble */
1313 requested_transition = clean_ttys;
1317 sp->se_process = pid;
1318 gettimeofday(&sp->se_started, NULL);
1323 * Catch a signal and request a state transition.
1326 transition_handler(int sig)
1331 requested_transition = clean_ttys;
1334 howto = RB_POWEROFF;
1343 requested_transition = death;
1346 requested_transition = catatonia;
1349 requested_transition = 0;
1355 * Take the system multiuser.
1364 requested_transition = 0;
1367 * If the administrator has not set the security level to -1
1368 * to indicate that the kernel should not run multiuser in secure
1369 * mode, and the run script has not set a higher level of security
1370 * than level 1, then put the kernel into secure mode.
1372 if (getsecuritylevel() == 0)
1373 setsecuritylevel(1);
1375 for (sp = sessions; sp; sp = sp->se_next) {
1378 if ((pid = start_getty(sp)) == -1) {
1379 /* serious trouble */
1380 requested_transition = clean_ttys;
1383 sp->se_process = pid;
1384 gettimeofday(&sp->se_started, NULL);
1388 while (!requested_transition)
1389 if ((pid = waitpid(-1, &status, 0)) != -1)
1390 collect_child(pid, status);
1392 return requested_transition;
1396 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1401 session_t *sp, *sprev;
1403 int session_index = 0;
1405 char *old_getty, *old_window, *old_type;
1411 * mark all sessions for death, (!SE_PRESENT)
1412 * as we find or create new ones they'll be marked as keepers,
1413 * we'll later nuke all the ones not found in /etc/ttys
1415 for (sp = sessions; sp != NULL; sp = sp->se_next)
1416 sp->se_flags &= ~SE_PRESENT;
1418 devlen = sizeof(_PATH_DEV) - 1;
1419 while ((typ = getttyent()) != NULL) {
1423 for (sprev = NULL, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1424 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1428 /* we want this one to live */
1429 sp->se_flags |= SE_PRESENT;
1430 if (sp->se_index != session_index) {
1431 warning("port %s changed utmpx index from %d to %d",
1432 sp->se_device, sp->se_index,
1434 sp->se_index = session_index;
1436 if ((typ->ty_status & TTY_ON) == 0 ||
1437 typ->ty_getty == 0) {
1438 sp->se_flags |= SE_SHUTDOWN;
1439 kill(sp->se_process, SIGHUP);
1442 sp->se_flags &= ~SE_SHUTDOWN;
1443 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1444 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1445 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1446 if (setupargv(sp, typ) == 0) {
1447 warning("can't parse getty for port %s",
1449 sp->se_flags |= SE_SHUTDOWN;
1450 kill(sp->se_process, SIGHUP);
1452 else if ( !old_getty
1453 || (!old_type && sp->se_type)
1454 || (old_type && !sp->se_type)
1455 || (!old_window && sp->se_window)
1456 || (old_window && !sp->se_window)
1457 || (strcmp(old_getty, sp->se_getty) != 0)
1458 || (old_window && strcmp(old_window, sp->se_window) != 0)
1459 || (old_type && strcmp(old_type, sp->se_type) != 0)
1461 /* Don't set SE_SHUTDOWN here */
1463 sp->se_started.tv_sec = sp->se_started.tv_usec = 0;
1464 kill(sp->se_process, SIGHUP);
1475 new_session(sprev, session_index, typ);
1481 * sweep through and kill all deleted sessions
1482 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1484 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1485 if ((sp->se_flags & SE_PRESENT) == 0) {
1486 sp->se_flags |= SE_SHUTDOWN;
1487 kill(sp->se_process, SIGHUP);
1495 * Block further logins.
1502 for (sp = sessions; sp; sp = sp->se_next)
1503 sp->se_flags |= SE_SHUTDOWN;
1512 alrm_handler(int sig __unused)
1518 * Bring the system down to single user.
1527 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1529 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1531 for (sp = sessions; sp; sp = sp->se_next) {
1532 sp->se_flags |= SE_SHUTDOWN;
1533 kill(sp->se_process, SIGHUP);
1536 /* Try to run the rc.shutdown script within a period of time */
1539 for (i = 0; i < 2; ++i) {
1540 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1546 if ((pid = waitpid(-1, &status, 0)) != -1)
1547 collect_child(pid, status);
1548 while (clang == 0 && errno != ECHILD);
1550 if (errno == ECHILD)
1554 warning("some processes would not die; ps axl advised");
1560 * Run the system shutdown script.
1562 * Exit codes: XXX I should document more
1563 * -2 shutdown script terminated abnormally
1564 * -1 fatal error - can't run script
1566 * >0 some error (exit code)
1573 int shutdowntimeout;
1575 const char *argv[4];
1576 struct sigaction sa;
1580 * rc.shutdown is optional, so to prevent any unnecessary
1581 * complaints from the shell we simply don't run it if the
1582 * file does not exist. If the stat() here fails for other
1583 * reasons, we'll let the shell complain.
1585 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1588 if ((pid = fork()) == 0) {
1591 /* Assume that init already grab console as ctty before */
1593 sigemptyset(&sa.sa_mask);
1595 sa.sa_handler = SIG_IGN;
1596 sigaction(SIGTSTP, &sa, NULL);
1597 sigaction(SIGHUP, &sa, NULL);
1599 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1600 warning("can't open %s: %m", _PATH_CONSOLE);
1610 * Run the shutdown script.
1613 argv[1] = _PATH_RUNDOWN;
1620 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1623 setprocresources(RESOURCE_RC);
1625 execv(_PATH_BSHELL, __DECONST(char **, argv));
1626 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1627 _exit(1); /* force single user mode */
1631 emergency("can't fork for %s on %s: %m",
1632 _PATH_BSHELL, _PATH_RUNDOWN);
1633 while (waitpid(-1, NULL, WNOHANG) > 0)
1635 sleep(STALL_TIMEOUT);
1639 len = sizeof(shutdowntimeout);
1640 if (sysctlbyname("kern.init_shutdown_timeout",
1642 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1643 shutdowntimeout = DEATH_SCRIPT;
1644 alarm(shutdowntimeout);
1647 * Copied from single_user(). This is a bit paranoid.
1648 * Use the same ALRM handler.
1651 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1652 collect_child(wpid, status);
1654 /* we were waiting for the sub-shell */
1655 kill(wpid, SIGTERM);
1656 warning("timeout expired for %s on %s: %m; going to single user mode",
1657 _PATH_BSHELL, _PATH_RUNDOWN);
1663 warning("wait for %s on %s failed: %m; going to single user mode",
1664 _PATH_BSHELL, _PATH_RUNDOWN);
1667 if (wpid == pid && WIFSTOPPED(status)) {
1668 warning("init: %s on %s stopped, restarting\n",
1669 _PATH_BSHELL, _PATH_RUNDOWN);
1673 } while (wpid != pid && !clang);
1675 /* Turn off the alarm */
1678 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1679 requested_transition == catatonia) {
1681 * /etc/rc.shutdown executed /sbin/reboot;
1682 * wait for the end quietly
1691 if (!WIFEXITED(status)) {
1692 warning("%s on %s terminated abnormally, going to single user mode",
1693 _PATH_BSHELL, _PATH_RUNDOWN);
1697 if ((status = WEXITSTATUS(status)) != 0)
1698 warning("%s returned status %d", _PATH_RUNDOWN, status);
1716 while (c == ' ' || c == '\t' )
1726 while (c && c != '\'')
1728 if (!c) /* unterminated string */
1733 while (c && c != ' ' && c != '\t' )
1744 setprocresources(const char *cname)
1747 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1748 setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);
1755 session_utmpx(const session_t *sp, int add)
1757 const char *name = sp->se_getty ? sp->se_getty :
1758 (sp->se_window ? sp->se_window : "");
1759 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1761 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1762 sp->se_process, &sp->se_started, sp->se_index);
1766 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1767 const struct timeval *tv, int session)
1772 (void)memset(&ut, 0, sizeof(ut));
1773 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1775 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1780 (void)gettimeofday(&ut.ut_tv, NULL);
1781 ut.ut_session = session;
1783 eline = line + strlen(line);
1784 if ((size_t)(eline - line) >= sizeof(ut.ut_id))
1785 line = eline - sizeof(ut.ut_id);
1786 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1788 if (pututxline(&ut) == NULL)
1789 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1794 get_runlevel(const state_t s)
1796 if (s == single_user)
1802 if (s == multi_user)
1804 if (s == clean_ttys)
1812 utmpx_set_runlevel(char old, char new)
1817 * Don't record any transitions until we did the first transition
1818 * to read ttys, which is when we are guaranteed to have a read-write
1819 * /var. Perhaps use a different variable for this?
1821 if (sessions == NULL)
1824 (void)memset(&ut, 0, sizeof(ut));
1825 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1826 ut.ut_type = RUN_LVL;
1827 (void)gettimeofday(&ut.ut_tv, NULL);
1828 ut.ut_exit.e_exit = old;
1829 ut.ut_exit.e_termination = new;
1830 if (pututxline(&ut) == NULL)
1831 warning("can't add utmpx record for `runlevel': %m");