2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
43 static const char rcsid[] =
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
68 #include <sys/reboot.h>
78 #include <login_cap.h>
81 #include "pathnames.h"
84 * Sleep times; used to prevent thrashing.
86 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
87 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
88 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
89 #define WINDOW_WAIT 3 /* wait N secs after starting window */
90 #define STALL_TIMEOUT 30 /* wait N secs after warning */
91 #define DEATH_WATCH 10 /* wait N secs for procs to die */
92 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
93 #define RESOURCE_RC "daemon"
94 #define RESOURCE_WINDOW "default"
95 #define RESOURCE_GETTY "default"
97 void handle(sig_t, ...);
98 void delset(sigset_t *, ...);
100 void stall(const char *, ...) __printflike(1, 2);
101 void warning(const char *, ...) __printflike(1, 2);
102 void emergency(const char *, ...) __printflike(1, 2);
105 int runshutdown(void);
108 * We really need a recursive typedef...
109 * The following at least guarantees that the return type of (*state_t)()
110 * is sufficiently wide to hold a function pointer.
112 typedef long (*state_func_t)(void);
113 typedef state_func_t (*state_t)(void);
115 state_func_t single_user(void);
116 state_func_t runcom(void);
117 state_func_t read_ttys(void);
118 state_func_t multi_user(void);
119 state_func_t clean_ttys(void);
120 state_func_t catatonia(void);
121 state_func_t death(void);
123 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
128 int howto = RB_AUTOBOOT;
132 void transition(state_t);
133 state_t requested_transition = runcom;
135 void setctty(char *);
137 typedef struct init_session {
138 int se_index; /* index of entry in ttys file */
139 pid_t se_process; /* controlling process */
140 time_t se_started; /* used to avoid thrashing */
141 int se_flags; /* status of session */
142 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
143 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
144 int se_nspace; /* spacing count */
145 char *se_device; /* filename of port */
146 char *se_getty; /* what to run on that port */
147 char *se_getty_argv_space; /* pre-parsed argument array space */
148 char **se_getty_argv; /* pre-parsed argument array */
149 char *se_window; /* window system (started only once) */
150 char *se_window_argv_space; /* pre-parsed argument array space */
151 char **se_window_argv; /* pre-parsed argument array */
152 char *se_type; /* default terminal type */
153 struct init_session *se_prev;
154 struct init_session *se_next;
157 void free_session(session_t *);
158 session_t *new_session(session_t *, int, struct ttyent *);
161 char **construct_argv(char *);
162 void start_window_system(session_t *);
163 void collect_child(pid_t);
164 pid_t start_getty(session_t *);
165 void transition_handler(int);
166 void alrm_handler(int);
167 void setsecuritylevel(int);
168 int getsecuritylevel(void);
169 int setupargv(session_t *, struct ttyent *);
171 void setprocresources(const char *);
175 void clear_session_logs(session_t *);
177 int start_session_db(void);
178 void add_session(session_t *);
179 void del_session(session_t *);
180 session_t *find_session(pid_t);
184 * The mother of all processes.
187 main(int argc, char *argv[])
194 /* Dispose of random users. */
196 errx(1, "%s", strerror(EPERM));
198 /* System V users like to reexec init. */
200 #ifdef COMPAT_SYSV_INIT
201 /* So give them what they want */
203 if (strlen(argv[1]) == 1) {
204 char runlevel = *argv[1];
208 case '0': /* halt + poweroff */
211 case '1': /* single-user */
214 case '6': /* reboot */
217 case 'c': /* block further logins */
220 case 'q': /* rescan /etc/ttys */
230 errx(1, "invalid run-level ``%s''", argv[1]);
233 errx(1, "already running");
236 * Note that this does NOT open a file...
237 * Does 'init' deserve its own facility number?
239 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
242 * Create an initial session.
245 warning("initial setsid() failed: %m");
248 * Establish an initial user so that programs running
249 * single user do not freak out and die (like passwd).
251 if (setlogin("root") < 0)
252 warning("setlogin() failed: %m");
255 * This code assumes that we always get arguments through flags,
256 * never through bits set in some random machine register.
258 while ((c = getopt(argc, argv, "dsf")) != -1)
264 requested_transition = single_user;
267 runcom_mode = FASTBOOT;
270 warning("unrecognized flag '-%c'", c);
275 warning("ignoring excess arguments");
282 iov[0].iov_base = "fstype";
283 iov[0].iov_len = sizeof("fstype");
284 iov[1].iov_base = "devfs";
285 iov[1].iov_len = sizeof("devfs");
286 iov[2].iov_base = "fspath";
287 iov[2].iov_len = sizeof("fspath");
289 * Try to avoid the trailing slash in _PATH_DEV.
290 * Be *very* defensive.
292 s = strdup(_PATH_DEV);
295 if (i > 0 && s[i - 1] == '/')
298 iov[3].iov_len = strlen(s) + 1;
300 iov[3].iov_base = _PATH_DEV;
301 iov[3].iov_len = sizeof(_PATH_DEV);
309 * We catch or block signals rather than ignore them,
310 * so that they get reset on exec.
312 handle(badsys, SIGSYS, 0);
313 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
314 SIGBUS, SIGXCPU, SIGXFSZ, 0);
315 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
316 SIGUSR1, SIGUSR2, 0);
317 handle(alrm_handler, SIGALRM, 0);
319 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
320 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
321 SIGUSR1, SIGUSR2, 0);
322 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
323 sigemptyset(&sa.sa_mask);
325 sa.sa_handler = SIG_IGN;
326 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
327 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
337 * Start the state machine.
339 transition(requested_transition);
342 * Should never reach here.
348 * Associate a function with a signal handler.
351 handle(sig_t handler, ...)
355 sigset_t mask_everything;
357 va_start(ap, handler);
359 sa.sa_handler = handler;
360 sigfillset(&mask_everything);
362 while ((sig = va_arg(ap, int)) != 0) {
363 sa.sa_mask = mask_everything;
364 /* XXX SA_RESTART? */
365 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
366 sigaction(sig, &sa, (struct sigaction *) 0);
372 * Delete a set of signals from a mask.
375 delset(sigset_t *maskp, ...)
381 while ((sig = va_arg(ap, int)) != 0)
382 sigdelset(maskp, sig);
387 * Log a message and sleep for a while (to give someone an opportunity
388 * to read it and to save log or hardcopy output if the problem is chronic).
389 * NB: should send a message to the session logger to avoid blocking.
392 stall(const char *message, ...)
395 va_start(ap, message);
397 vsyslog(LOG_ALERT, message, ap);
399 sleep(STALL_TIMEOUT);
403 * Like stall(), but doesn't sleep.
404 * If cpp had variadic macros, the two functions could be #defines for another.
405 * NB: should send a message to the session logger to avoid blocking.
408 warning(const char *message, ...)
411 va_start(ap, message);
413 vsyslog(LOG_ALERT, message, ap);
418 * Log an emergency message.
419 * NB: should send a message to the session logger to avoid blocking.
422 emergency(const char *message, ...)
425 va_start(ap, message);
427 vsyslog(LOG_EMERG, message, ap);
432 * Catch a SIGSYS signal.
434 * These may arise if a system does not support sysctl.
435 * We tolerate up to 25 of these, then throw in the towel.
440 static int badcount = 0;
448 * Catch an unexpected signal.
453 emergency("fatal signal: %s",
454 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
456 sleep(STALL_TIMEOUT);
457 _exit(sig); /* reboot */
461 * Get the security level of the kernel.
464 getsecuritylevel(void)
466 #ifdef KERN_SECURELVL
467 int name[2], curlevel;
471 name[1] = KERN_SECURELVL;
472 len = sizeof curlevel;
473 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
474 emergency("cannot get kernel security level: %s",
485 * Set the security level of the kernel.
488 setsecuritylevel(int newlevel)
490 #ifdef KERN_SECURELVL
491 int name[2], curlevel;
493 curlevel = getsecuritylevel();
494 if (newlevel == curlevel)
497 name[1] = KERN_SECURELVL;
498 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
500 "cannot change kernel security level from %d to %d: %s",
501 curlevel, newlevel, strerror(errno));
505 warning("kernel security level changed from %d to %d",
512 * Change states in the finite state machine.
513 * The initial state is passed as an argument.
516 transition(state_t s)
519 s = (state_t) (*s)();
523 * Close out the accounting files for a login session.
524 * NB: should send a message to the session logger to avoid blocking.
527 clear_session_logs(session_t *sp)
529 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
532 logwtmp(line, "", "");
536 * Start a session and allocate a controlling terminal.
537 * Only called by children of init after forking.
545 if ((fd = open(name, O_RDWR)) == -1) {
546 stall("can't open %s: %m", name);
549 if (login_tty(fd) == -1) {
550 stall("can't get %s for controlling terminal: %m", name);
556 * Bring the system up single user.
564 char *shell = _PATH_BSHELL;
569 static const char banner[] =
570 "Enter root password, or ^D to go multi-user\n";
571 char *clear, *password;
578 /* Instead of going single user, let's reboot the machine */
586 if ((pid = fork()) == 0) {
588 * Start the single user session.
590 setctty(_PATH_CONSOLE);
594 * Check the root password.
595 * We don't care if the console is 'on' by default;
596 * it's the only tty that can be 'off' and 'secure'.
598 typ = getttynam("console");
599 pp = getpwnam("root");
600 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
601 pp && *pp->pw_passwd) {
602 write(STDERR_FILENO, banner, sizeof banner - 1);
604 clear = getpass("Password:");
605 if (clear == 0 || *clear == '\0')
607 password = crypt(clear, pp->pw_passwd);
608 bzero(clear, _PASSWORD_LEN);
609 if (strcmp(password, pp->pw_passwd) == 0)
611 warning("single-user login failed\n");
624 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
625 (void)write(STDERR_FILENO,
626 SHREQUEST, sizeof(SHREQUEST) - 1);
627 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
628 num != 0 && *cp != '\n' && cp < &altshell[127])
631 if (altshell[0] != '\0')
634 #endif /* DEBUGSHELL */
638 * We catch all the interesting ones,
639 * and those are reset to SIG_DFL on exec.
642 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
646 * If the default one doesn't work, try the Bourne shell.
651 emergency("can't exec %s for single user: %m", shell);
652 execv(_PATH_BSHELL, argv);
653 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
654 sleep(STALL_TIMEOUT);
660 * We are seriously hosed. Do our best.
662 emergency("can't fork single-user shell, trying again");
663 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
665 return (state_func_t) single_user;
668 requested_transition = 0;
670 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
675 warning("wait for single-user shell failed: %m; restarting");
676 return (state_func_t) single_user;
678 if (wpid == pid && WIFSTOPPED(status)) {
679 warning("init: shell stopped, restarting\n");
683 } while (wpid != pid && !requested_transition);
685 if (requested_transition)
686 return (state_func_t) requested_transition;
688 if (!WIFEXITED(status)) {
689 if (WTERMSIG(status) == SIGKILL) {
691 * reboot(8) killed shell?
693 warning("single user shell terminated.");
694 sleep(STALL_TIMEOUT);
697 warning("single user shell terminated, restarting");
698 return (state_func_t) single_user;
702 runcom_mode = FASTBOOT;
703 return (state_func_t) runcom;
707 * Run the system startup script.
717 if ((pid = fork()) == 0) {
718 sigemptyset(&sa.sa_mask);
720 sa.sa_handler = SIG_IGN;
721 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
722 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
724 setctty(_PATH_CONSOLE);
727 argv[1] = _PATH_RUNCOM;
728 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
731 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
734 setprocresources(RESOURCE_RC);
736 execv(_PATH_BSHELL, argv);
737 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
738 _exit(1); /* force single user mode */
742 emergency("can't fork for %s on %s: %m",
743 _PATH_BSHELL, _PATH_RUNCOM);
744 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
746 sleep(STALL_TIMEOUT);
747 return (state_func_t) single_user;
751 * Copied from single_user(). This is a bit paranoid.
753 requested_transition = 0;
755 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
758 if (requested_transition == death)
759 return (state_func_t) death;
762 warning("wait for %s on %s failed: %m; going to single user mode",
763 _PATH_BSHELL, _PATH_RUNCOM);
764 return (state_func_t) single_user;
766 if (wpid == pid && WIFSTOPPED(status)) {
767 warning("init: %s on %s stopped, restarting\n",
768 _PATH_BSHELL, _PATH_RUNCOM);
772 } while (wpid != pid);
774 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
775 requested_transition == catatonia) {
776 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
784 if (!WIFEXITED(status)) {
785 warning("%s on %s terminated abnormally, going to single user mode",
786 _PATH_BSHELL, _PATH_RUNCOM);
787 return (state_func_t) single_user;
790 if (WEXITSTATUS(status))
791 return (state_func_t) single_user;
793 runcom_mode = AUTOBOOT; /* the default */
794 /* NB: should send a message to the session logger to avoid blocking. */
795 logwtmp("~", "reboot", "");
796 return (state_func_t) read_ttys;
800 * Open the session database.
802 * NB: We could pass in the size here; is it necessary?
805 start_session_db(void)
807 if (session_db && (*session_db->close)(session_db))
808 emergency("session database close: %s", strerror(errno));
809 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
810 emergency("session database open: %s", strerror(errno));
818 * Add a new login session.
821 add_session(session_t *sp)
826 key.data = &sp->se_process;
827 key.size = sizeof sp->se_process;
829 data.size = sizeof sp;
831 if ((*session_db->put)(session_db, &key, &data, 0))
832 emergency("insert %d: %s", sp->se_process, strerror(errno));
836 * Delete an old login session.
839 del_session(session_t *sp)
843 key.data = &sp->se_process;
844 key.size = sizeof sp->se_process;
846 if ((*session_db->del)(session_db, &key, 0))
847 emergency("delete %d: %s", sp->se_process, strerror(errno));
851 * Look up a login session by pid.
854 find_session(pid_t pid)
861 key.size = sizeof pid;
862 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
864 bcopy(data.data, (char *)&ret, sizeof(ret));
869 * Construct an argument vector from a command line.
872 construct_argv(char *command)
876 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
879 if ((argv[argc++] = strk(command)) == 0) {
883 while ((argv[argc++] = strk((char *) 0)) != NULL)
889 * Deallocate a session descriptor.
892 free_session(session_t *sp)
897 free(sp->se_getty_argv_space);
898 free(sp->se_getty_argv);
902 free(sp->se_window_argv_space);
903 free(sp->se_window_argv);
911 * Allocate a new session descriptor.
912 * Mark it SE_PRESENT.
915 new_session(session_t *sprev, int session_index, struct ttyent *typ)
920 if ((typ->ty_status & TTY_ON) == 0 ||
925 sp = (session_t *) calloc(1, sizeof (session_t));
927 sp->se_index = session_index;
928 sp->se_flags |= SE_PRESENT;
930 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
931 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
934 * Attempt to open the device, if we get "device not configured"
935 * then don't add the device to the session list.
937 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
938 if (errno == ENXIO || errno == ENOENT) {
945 if (setupargv(sp, typ) == 0) {
963 * Calculate getty and if useful window argv vectors.
966 setupargv(session_t *sp, struct ttyent *typ)
971 free(sp->se_getty_argv_space);
972 free(sp->se_getty_argv);
974 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
975 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
976 sp->se_getty_argv_space = strdup(sp->se_getty);
977 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
978 if (sp->se_getty_argv == 0) {
979 warning("can't parse getty for port %s", sp->se_device);
981 free(sp->se_getty_argv_space);
982 sp->se_getty = sp->se_getty_argv_space = 0;
987 free(sp->se_window_argv_space);
988 free(sp->se_window_argv);
990 sp->se_window = sp->se_window_argv_space = 0;
991 sp->se_window_argv = 0;
992 if (typ->ty_window) {
993 sp->se_window = strdup(typ->ty_window);
994 sp->se_window_argv_space = strdup(sp->se_window);
995 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
996 if (sp->se_window_argv == 0) {
997 warning("can't parse window for port %s",
999 free(sp->se_window_argv_space);
1000 free(sp->se_window);
1001 sp->se_window = sp->se_window_argv_space = 0;
1007 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1012 * Walk the list of ttys and create sessions for each active line.
1017 int session_index = 0;
1018 session_t *sp, *snext;
1022 * Destroy any previous session state.
1023 * There shouldn't be any, but just in case...
1025 for (sp = sessions; sp; sp = snext) {
1027 clear_session_logs(sp);
1028 snext = sp->se_next;
1032 if (start_session_db())
1033 return (state_func_t) single_user;
1036 * Allocate a session entry for each active port.
1037 * Note that sp starts at 0.
1039 while ((typ = getttyent()) != NULL)
1040 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1045 return (state_func_t) multi_user;
1049 * Start a window system running.
1052 start_window_system(session_t *sp)
1056 char term[64], *env[2];
1058 if ((pid = fork()) == -1) {
1059 emergency("can't fork for window system on port %s: %m",
1061 /* hope that getty fails and we can try again */
1069 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1072 emergency("setsid failed (window) %m");
1075 setprocresources(RESOURCE_WINDOW);
1078 /* Don't use malloc after fork */
1079 strcpy(term, "TERM=");
1080 strncat(term, sp->se_type, sizeof(term) - 6);
1086 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1087 stall("can't exec window system '%s' for port %s: %m",
1088 sp->se_window_argv[0], sp->se_device);
1093 * Start a login session running.
1096 start_getty(session_t *sp)
1100 time_t current_time = time((time_t *) 0);
1102 char term[64], *env[2];
1104 if (current_time >= sp->se_started &&
1105 current_time - sp->se_started < GETTY_SPACING) {
1106 if (++sp->se_nspace > GETTY_NSPACE) {
1114 * fork(), not vfork() -- we can't afford to block.
1116 if ((pid = fork()) == -1) {
1117 emergency("can't fork for getty on port %s: %m", sp->se_device);
1125 warning("getty repeating too quickly on port %s, sleeping %d secs",
1126 sp->se_device, GETTY_SLEEP);
1127 sleep((unsigned) GETTY_SLEEP);
1130 if (sp->se_window) {
1131 start_window_system(sp);
1136 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1139 setprocresources(RESOURCE_GETTY);
1142 /* Don't use malloc after fork */
1143 strcpy(term, "TERM=");
1144 strncat(term, sp->se_type, sizeof(term) - 6);
1150 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1151 stall("can't exec getty '%s' for port %s: %m",
1152 sp->se_getty_argv[0], sp->se_device);
1157 * Collect exit status for a child.
1158 * If an exiting login, start a new login running.
1161 collect_child(pid_t pid)
1163 session_t *sp, *sprev, *snext;
1168 if (! (sp = find_session(pid)))
1171 clear_session_logs(sp);
1175 if (sp->se_flags & SE_SHUTDOWN) {
1176 if ((sprev = sp->se_prev) != NULL)
1177 sprev->se_next = sp->se_next;
1179 sessions = sp->se_next;
1180 if ((snext = sp->se_next) != NULL)
1181 snext->se_prev = sp->se_prev;
1186 if ((pid = start_getty(sp)) == -1) {
1187 /* serious trouble */
1188 requested_transition = clean_ttys;
1192 sp->se_process = pid;
1193 sp->se_started = time((time_t *) 0);
1198 * Catch a signal and request a state transition.
1201 transition_handler(int sig)
1206 requested_transition = clean_ttys;
1209 howto = RB_POWEROFF;
1215 requested_transition = death;
1218 requested_transition = catatonia;
1221 requested_transition = 0;
1227 * Take the system multiuser.
1235 requested_transition = 0;
1238 * If the administrator has not set the security level to -1
1239 * to indicate that the kernel should not run multiuser in secure
1240 * mode, and the run script has not set a higher level of security
1241 * than level 1, then put the kernel into secure mode.
1243 if (getsecuritylevel() == 0)
1244 setsecuritylevel(1);
1246 for (sp = sessions; sp; sp = sp->se_next) {
1249 if ((pid = start_getty(sp)) == -1) {
1250 /* serious trouble */
1251 requested_transition = clean_ttys;
1254 sp->se_process = pid;
1255 sp->se_started = time((time_t *) 0);
1259 while (!requested_transition)
1260 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1263 return (state_func_t) requested_transition;
1267 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1272 session_t *sp, *sprev;
1274 int session_index = 0;
1276 char *old_getty, *old_window, *old_type;
1279 * mark all sessions for death, (!SE_PRESENT)
1280 * as we find or create new ones they'll be marked as keepers,
1281 * we'll later nuke all the ones not found in /etc/ttys
1283 for (sp = sessions; sp != NULL; sp = sp->se_next)
1284 sp->se_flags &= ~SE_PRESENT;
1286 devlen = sizeof(_PATH_DEV) - 1;
1287 while ((typ = getttyent()) != NULL) {
1290 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1291 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1295 /* we want this one to live */
1296 sp->se_flags |= SE_PRESENT;
1297 if (sp->se_index != session_index) {
1298 warning("port %s changed utmp index from %d to %d",
1299 sp->se_device, sp->se_index,
1301 sp->se_index = session_index;
1303 if ((typ->ty_status & TTY_ON) == 0 ||
1304 typ->ty_getty == 0) {
1305 sp->se_flags |= SE_SHUTDOWN;
1306 kill(sp->se_process, SIGHUP);
1309 sp->se_flags &= ~SE_SHUTDOWN;
1310 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1311 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1312 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1313 if (setupargv(sp, typ) == 0) {
1314 warning("can't parse getty for port %s",
1316 sp->se_flags |= SE_SHUTDOWN;
1317 kill(sp->se_process, SIGHUP);
1319 else if ( !old_getty
1320 || (!old_type && sp->se_type)
1321 || (old_type && !sp->se_type)
1322 || (!old_window && sp->se_window)
1323 || (old_window && !sp->se_window)
1324 || (strcmp(old_getty, sp->se_getty) != 0)
1325 || (old_window && strcmp(old_window, sp->se_window) != 0)
1326 || (old_type && strcmp(old_type, sp->se_type) != 0)
1328 /* Don't set SE_SHUTDOWN here */
1331 kill(sp->se_process, SIGHUP);
1342 new_session(sprev, session_index, typ);
1348 * sweep through and kill all deleted sessions
1349 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1351 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1352 if ((sp->se_flags & SE_PRESENT) == 0) {
1353 sp->se_flags |= SE_SHUTDOWN;
1354 kill(sp->se_process, SIGHUP);
1358 return (state_func_t) multi_user;
1362 * Block further logins.
1369 for (sp = sessions; sp; sp = sp->se_next)
1370 sp->se_flags |= SE_SHUTDOWN;
1372 return (state_func_t) multi_user;
1379 alrm_handler(int sig)
1386 * Bring the system down to single user.
1394 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1396 /* NB: should send a message to the session logger to avoid blocking. */
1397 logwtmp("~", "shutdown", "");
1399 for (sp = sessions; sp; sp = sp->se_next) {
1400 sp->se_flags |= SE_SHUTDOWN;
1401 kill(sp->se_process, SIGHUP);
1404 /* Try to run the rc.shutdown script within a period of time */
1405 (void) runshutdown();
1407 for (i = 0; i < 2; ++i) {
1408 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1409 return (state_func_t) single_user;
1414 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1416 while (clang == 0 && errno != ECHILD);
1418 if (errno == ECHILD)
1419 return (state_func_t) single_user;
1422 warning("some processes would not die; ps axl advised");
1424 return (state_func_t) single_user;
1428 * Run the system shutdown script.
1430 * Exit codes: XXX I should document more
1431 * -2 shutdown script terminated abnormally
1432 * -1 fatal error - can't run script
1434 * >0 some error (exit code)
1441 int shutdowntimeout;
1444 struct sigaction sa;
1448 * rc.shutdown is optional, so to prevent any unnecessary
1449 * complaints from the shell we simply don't run it if the
1450 * file does not exist. If the stat() here fails for other
1451 * reasons, we'll let the shell complain.
1453 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1456 if ((pid = fork()) == 0) {
1459 /* Assume that init already grab console as ctty before */
1461 sigemptyset(&sa.sa_mask);
1463 sa.sa_handler = SIG_IGN;
1464 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1465 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1467 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1468 warning("can't open %s: %m", _PATH_CONSOLE);
1478 * Run the shutdown script.
1481 argv[1] = _PATH_RUNDOWN;
1488 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1491 setprocresources(RESOURCE_RC);
1493 execv(_PATH_BSHELL, argv);
1494 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1495 _exit(1); /* force single user mode */
1499 emergency("can't fork for %s on %s: %m",
1500 _PATH_BSHELL, _PATH_RUNDOWN);
1501 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1503 sleep(STALL_TIMEOUT);
1507 len = sizeof(shutdowntimeout);
1508 if (sysctlbyname("kern.shutdown_timeout",
1510 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1511 shutdowntimeout = DEATH_SCRIPT;
1512 alarm(shutdowntimeout);
1515 * Copied from single_user(). This is a bit paranoid.
1516 * Use the same ALRM handler.
1519 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1520 collect_child(wpid);
1522 /* we were waiting for the sub-shell */
1523 kill(wpid, SIGTERM);
1524 warning("timeout expired for %s on %s: %m; going to single user mode",
1525 _PATH_BSHELL, _PATH_RUNDOWN);
1531 warning("wait for %s on %s failed: %m; going to single user mode",
1532 _PATH_BSHELL, _PATH_RUNDOWN);
1535 if (wpid == pid && WIFSTOPPED(status)) {
1536 warning("init: %s on %s stopped, restarting\n",
1537 _PATH_BSHELL, _PATH_RUNDOWN);
1541 } while (wpid != pid && !clang);
1543 /* Turn off the alarm */
1546 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1547 requested_transition == catatonia) {
1549 * /etc/rc.shutdown executed /sbin/reboot;
1550 * wait for the end quietly
1559 if (!WIFEXITED(status)) {
1560 warning("%s on %s terminated abnormally, going to single user mode",
1561 _PATH_BSHELL, _PATH_RUNDOWN);
1565 if ((status = WEXITSTATUS(status)) != 0)
1566 warning("%s returned status %d", _PATH_RUNDOWN, status);
1584 while (c == ' ' || c == '\t' )
1594 while (c && c != '\'')
1596 if (!c) /* unterminated string */
1601 while (c && c != ' ' && c != '\t' )
1612 setprocresources(const char *cname)
1615 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1616 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);