2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36 * $Id: init.c,v 1.26 1997/08/06 16:34:51 ache Exp $
40 static char copyright[] =
41 "@(#) Copyright (c) 1991, 1993\n\
42 The Regents of the University of California. All rights reserved.\n";
46 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
51 #include <sys/mount.h>
52 #include <sys/sysctl.h>
54 #include <sys/types.h>
69 #include <sys/reboot.h>
83 #include <login_cap.h>
86 #include "pathnames.h"
89 * Sleep times; used to prevent thrashing.
91 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
92 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
93 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
94 #define WINDOW_WAIT 3 /* wait N secs after starting window */
95 #define STALL_TIMEOUT 30 /* wait N secs after warning */
96 #define DEATH_WATCH 10 /* wait N secs for procs to die */
97 #define DEATH_SCRIPT 120 /* wait for 2mn for /etc/rc.shutdown */
98 #define RESOURCE_RC "daemon"
99 #define RESOURCE_WINDOW "default"
100 #define RESOURCE_GETTY "default"
102 void handle __P((sig_t, ...));
103 void delset __P((sigset_t *, ...));
105 void stall __P((char *, ...));
106 void warning __P((char *, ...));
107 void emergency __P((char *, ...));
108 void disaster __P((int));
109 void badsys __P((int));
110 int runshutdown __P((void));
113 * We really need a recursive typedef...
114 * The following at least guarantees that the return type of (*state_t)()
115 * is sufficiently wide to hold a function pointer.
117 typedef long (*state_func_t) __P((void));
118 typedef state_func_t (*state_t) __P((void));
120 state_func_t single_user __P((void));
121 state_func_t runcom __P((void));
122 state_func_t read_ttys __P((void));
123 state_func_t multi_user __P((void));
124 state_func_t clean_ttys __P((void));
125 state_func_t catatonia __P((void));
126 state_func_t death __P((void));
128 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
136 void transition __P((state_t));
137 state_t requested_transition = runcom;
139 void setctty __P((char *));
141 typedef struct init_session {
142 int se_index; /* index of entry in ttys file */
143 pid_t se_process; /* controlling process */
144 time_t se_started; /* used to avoid thrashing */
145 int se_flags; /* status of session */
146 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
147 int se_nspace; /* spacing count */
148 char *se_device; /* filename of port */
149 char *se_getty; /* what to run on that port */
150 char *se_getty_argv_space; /* pre-parsed argument array space */
151 char **se_getty_argv; /* pre-parsed argument array */
152 char *se_window; /* window system (started only once) */
153 char *se_window_argv_space; /* pre-parsed argument array space */
154 char **se_window_argv; /* pre-parsed argument array */
155 char *se_type; /* default terminal type */
156 struct init_session *se_prev;
157 struct init_session *se_next;
160 void free_session __P((session_t *));
161 session_t *new_session __P((session_t *, int, struct ttyent *));
164 char **construct_argv __P((char *));
165 void start_window_system __P((session_t *));
166 void collect_child __P((pid_t));
167 pid_t start_getty __P((session_t *));
168 void transition_handler __P((int));
169 void alrm_handler __P((int));
170 void setsecuritylevel __P((int));
171 int getsecuritylevel __P((void));
172 int setupargv __P((session_t *, struct ttyent *));
174 void setprocresources __P((const char *));
178 void clear_session_logs __P((session_t *));
180 int start_session_db __P((void));
181 void add_session __P((session_t *));
182 void del_session __P((session_t *));
183 session_t *find_session __P((pid_t));
187 * The mother of all processes.
199 /* Dispose of random users. */
201 errx(1, "%s", strerror(EPERM));
203 /* System V users like to reexec init. */
205 errx(1, "already running");
208 * Note that this does NOT open a file...
209 * Does 'init' deserve its own facility number?
211 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
214 * Create an initial session.
217 warning("initial setsid() failed: %m");
220 * Establish an initial user so that programs running
221 * single user do not freak out and die (like passwd).
223 if (setlogin("root") < 0)
224 warning("setlogin() failed: %m");
227 * This code assumes that we always get arguments through flags,
228 * never through bits set in some random machine register.
230 while ((c = getopt(argc, argv, "dsf")) != -1)
236 requested_transition = single_user;
239 runcom_mode = FASTBOOT;
242 warning("unrecognized flag '-%c'", c);
247 warning("ignoring excess arguments");
250 mount("devfs", "/dev", MNT_NOEXEC|MNT_RDONLY, 0);
254 * We catch or block signals rather than ignore them,
255 * so that they get reset on exec.
257 handle(badsys, SIGSYS, 0);
258 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
259 SIGBUS, SIGXCPU, SIGXFSZ, 0);
260 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP, 0);
261 handle(alrm_handler, SIGALRM, 0);
263 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
264 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM, 0);
265 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
266 sigemptyset(&sa.sa_mask);
268 sa.sa_handler = SIG_IGN;
269 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
270 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
280 * Start the state machine.
282 transition(requested_transition);
285 * Should never reach here.
291 * Associate a function with a signal handler.
295 handle(sig_t handler, ...)
309 handler = va_arg(ap, sig_t);
311 va_start(ap, handler);
314 sa.sa_handler = handler;
315 sigfillset(&mask_everything);
317 while ((sig = va_arg(ap, int)) != NULL) {
318 sa.sa_mask = mask_everything;
319 /* XXX SA_RESTART? */
320 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
321 sigaction(sig, &sa, (struct sigaction *) 0);
327 * Delete a set of signals from a mask.
331 delset(sigset_t *maskp, ...)
343 maskp = va_arg(ap, sigset_t *);
348 while ((sig = va_arg(ap, int)) != NULL)
349 sigdelset(maskp, sig);
354 * Log a message and sleep for a while (to give someone an opportunity
355 * to read it and to save log or hardcopy output if the problem is chronic).
356 * NB: should send a message to the session logger to avoid blocking.
360 stall(char *message, ...)
371 message = va_arg(ap, char *);
373 va_start(ap, message);
376 vsyslog(LOG_ALERT, message, ap);
378 sleep(STALL_TIMEOUT);
382 * Like stall(), but doesn't sleep.
383 * If cpp had variadic macros, the two functions could be #defines for another.
384 * NB: should send a message to the session logger to avoid blocking.
388 warning(char *message, ...)
399 message = va_arg(ap, char *);
401 va_start(ap, message);
404 vsyslog(LOG_ALERT, message, ap);
409 * Log an emergency message.
410 * NB: should send a message to the session logger to avoid blocking.
414 emergency(char *message, ...)
425 message = va_arg(ap, char *);
427 va_start(ap, message);
430 vsyslog(LOG_EMERG, message, ap);
435 * Catch a SIGSYS signal.
437 * These may arise if a system does not support sysctl.
438 * We tolerate up to 25 of these, then throw in the towel.
444 static int badcount = 0;
452 * Catch an unexpected signal.
458 emergency("fatal signal: %s",
459 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
461 sleep(STALL_TIMEOUT);
462 _exit(sig); /* reboot */
466 * Get the security level of the kernel.
471 #ifdef KERN_SECURELVL
472 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 * Set the security level of the kernel.
494 setsecuritylevel(newlevel)
497 #ifdef KERN_SECURELVL
498 int name[2], curlevel;
501 curlevel = getsecuritylevel();
502 if (newlevel == curlevel)
505 name[1] = KERN_SECURELVL;
506 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
508 "cannot change kernel security level from %d to %d: %s",
509 curlevel, newlevel, strerror(errno));
513 warning("kernel security level changed from %d to %d",
520 * Change states in the finite state machine.
521 * The initial state is passed as an argument.
528 s = (state_t) (*s)();
532 * Close out the accounting files for a login session.
533 * NB: should send a message to the session logger to avoid blocking.
536 clear_session_logs(sp)
539 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
542 logwtmp(line, "", "");
546 * Start a session and allocate a controlling terminal.
547 * Only called by children of init after forking.
556 if ((fd = open(name, O_RDWR)) == -1) {
557 stall("can't open %s: %m", name);
560 if (login_tty(fd) == -1) {
561 stall("can't get %s for controlling terminal: %m", name);
567 * Bring the system up single user.
575 char *shell = _PATH_BSHELL;
580 static const char banner[] =
581 "Enter root password, or ^D to go multi-user\n";
582 char *clear, *password;
586 * If the kernel is in secure mode, downgrade it to insecure mode.
588 if (getsecuritylevel() > 0)
592 /* Instead of going single user, let's halt the machine */
600 if ((pid = fork()) == 0) {
602 * Start the single user session.
604 setctty(_PATH_CONSOLE);
608 * Check the root password.
609 * We don't care if the console is 'on' by default;
610 * it's the only tty that can be 'off' and 'secure'.
612 typ = getttynam("console");
613 pp = getpwnam("root");
614 if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp && *pp->pw_passwd) {
615 write(2, banner, sizeof banner - 1);
617 clear = getpass("Password:");
618 if (clear == 0 || *clear == '\0')
620 password = crypt(clear, pp->pw_passwd);
621 bzero(clear, _PASSWORD_LEN);
622 if (strcmp(password, pp->pw_passwd) == 0)
624 warning("single-user login failed\n");
633 char altshell[128], *cp = altshell;
637 "Enter pathname of shell or RETURN for sh: "
638 (void)write(STDERR_FILENO,
639 SHREQUEST, sizeof(SHREQUEST) - 1);
640 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
641 num != 0 && *cp != '\n' && cp < &altshell[127])
644 if (altshell[0] != '\0')
647 #endif /* DEBUGSHELL */
651 * We catch all the interesting ones,
652 * and those are reset to SIG_DFL on exec.
655 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
659 * If the default one doesn't work, try the Bourne shell.
664 emergency("can't exec %s for single user: %m", shell);
665 execv(_PATH_BSHELL, argv);
666 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
667 sleep(STALL_TIMEOUT);
673 * We are seriously hosed. Do our best.
675 emergency("can't fork single-user shell, trying again");
676 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
678 return (state_func_t) single_user;
681 requested_transition = 0;
683 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
688 warning("wait for single-user shell failed: %m; restarting");
689 return (state_func_t) single_user;
691 if (wpid == pid && WIFSTOPPED(status)) {
692 warning("init: shell stopped, restarting\n");
696 } while (wpid != pid && !requested_transition);
698 if (requested_transition)
699 return (state_func_t) requested_transition;
701 if (!WIFEXITED(status)) {
702 if (WTERMSIG(status) == SIGKILL) {
704 * reboot(8) killed shell?
706 warning("single user shell terminated.");
707 sleep(STALL_TIMEOUT);
710 warning("single user shell terminated, restarting");
711 return (state_func_t) single_user;
715 runcom_mode = FASTBOOT;
716 return (state_func_t) runcom;
720 * Run the system startup script.
730 if ((pid = fork()) == 0) {
731 sigemptyset(&sa.sa_mask);
733 sa.sa_handler = SIG_IGN;
734 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
735 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
737 setctty(_PATH_CONSOLE);
740 argv[1] = _PATH_RUNCOM;
741 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
744 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
747 setprocresources(RESOURCE_RC);
749 execv(_PATH_BSHELL, argv);
750 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
751 _exit(1); /* force single user mode */
755 emergency("can't fork for %s on %s: %m",
756 _PATH_BSHELL, _PATH_RUNCOM);
757 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
759 sleep(STALL_TIMEOUT);
760 return (state_func_t) single_user;
764 * Copied from single_user(). This is a bit paranoid.
767 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
772 warning("wait for %s on %s failed: %m; going to single user mode",
773 _PATH_BSHELL, _PATH_RUNCOM);
774 return (state_func_t) single_user;
776 if (wpid == pid && WIFSTOPPED(status)) {
777 warning("init: %s on %s stopped, restarting\n",
778 _PATH_BSHELL, _PATH_RUNCOM);
782 } while (wpid != pid);
784 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
785 requested_transition == catatonia) {
786 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
794 if (!WIFEXITED(status)) {
795 warning("%s on %s terminated abnormally, going to single user mode",
796 _PATH_BSHELL, _PATH_RUNCOM);
797 return (state_func_t) single_user;
800 if (WEXITSTATUS(status))
801 return (state_func_t) single_user;
803 runcom_mode = AUTOBOOT; /* the default */
804 /* NB: should send a message to the session logger to avoid blocking. */
805 logwtmp("~", "reboot", "");
806 return (state_func_t) read_ttys;
810 * Open the session database.
812 * NB: We could pass in the size here; is it necessary?
817 if (session_db && (*session_db->close)(session_db))
818 emergency("session database close: %s", strerror(errno));
819 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
820 emergency("session database open: %s", strerror(errno));
828 * Add a new login session.
837 key.data = &sp->se_process;
838 key.size = sizeof sp->se_process;
840 data.size = sizeof sp;
842 if ((*session_db->put)(session_db, &key, &data, 0))
843 emergency("insert %d: %s", sp->se_process, strerror(errno));
847 * Delete an old login session.
855 key.data = &sp->se_process;
856 key.size = sizeof sp->se_process;
858 if ((*session_db->del)(session_db, &key, 0))
859 emergency("delete %d: %s", sp->se_process, strerror(errno));
863 * Look up a login session by pid.
867 find_session(pid_t pid)
878 key.size = sizeof pid;
879 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
881 bcopy(data.data, (char *)&ret, sizeof(ret));
886 * Construct an argument vector from a command line.
889 construct_argv(command)
893 register int argc = 0;
894 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
897 if ((argv[argc++] = strk(command)) == 0)
899 while ((argv[argc++] = strk((char *) 0)) != NULL)
905 * Deallocate a session descriptor.
909 register session_t *sp;
914 free(sp->se_getty_argv_space);
915 free(sp->se_getty_argv);
919 free(sp->se_window_argv_space);
920 free(sp->se_window_argv);
928 * Allocate a new session descriptor.
931 new_session(sprev, session_index, typ)
934 register struct ttyent *typ;
936 register session_t *sp;
939 if ((typ->ty_status & TTY_ON) == 0 ||
944 sp = (session_t *) calloc(1, sizeof (session_t));
946 sp->se_index = session_index;
948 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
949 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
952 * Attempt to open the device, if we get "device not configured"
953 * then don't add the device to the session list.
955 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
956 if (errno == ENXIO) {
963 if (setupargv(sp, typ) == 0) {
981 * Calculate getty and if useful window argv vectors.
991 free(sp->se_getty_argv_space);
992 free(sp->se_getty_argv);
994 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
995 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
996 sp->se_getty_argv_space = strdup(sp->se_getty);
997 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
998 if (sp->se_getty_argv == 0) {
999 warning("can't parse getty for port %s", sp->se_device);
1001 free(sp->se_getty_argv_space);
1002 sp->se_getty = sp->se_getty_argv_space = 0;
1005 if (sp->se_window) {
1006 free(sp->se_window);
1007 free(sp->se_window_argv_space);
1008 free(sp->se_window_argv);
1010 sp->se_window = sp->se_window_argv_space = 0;
1011 sp->se_window_argv = 0;
1012 if (typ->ty_window) {
1013 sp->se_window = strdup(typ->ty_window);
1014 sp->se_window_argv_space = strdup(sp->se_window);
1015 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1016 if (sp->se_window_argv == 0) {
1017 warning("can't parse window for port %s",
1019 free(sp->se_window_argv_space);
1020 free(sp->se_window);
1021 sp->se_window = sp->se_window_argv_space = 0;
1027 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1032 * Walk the list of ttys and create sessions for each active line.
1037 int session_index = 0;
1038 register session_t *sp, *snext;
1039 register struct ttyent *typ;
1042 * Destroy any previous session state.
1043 * There shouldn't be any, but just in case...
1045 for (sp = sessions; sp; sp = snext) {
1047 clear_session_logs(sp);
1048 snext = sp->se_next;
1052 if (start_session_db())
1053 return (state_func_t) single_user;
1056 * Allocate a session entry for each active port.
1057 * Note that sp starts at 0.
1059 while ((typ = getttyent()) != NULL)
1060 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1065 return (state_func_t) multi_user;
1069 * Start a window system running.
1072 start_window_system(sp)
1077 char term[64], *env[2];
1079 if ((pid = fork()) == -1) {
1080 emergency("can't fork for window system on port %s: %m",
1082 /* hope that getty fails and we can try again */
1090 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1093 emergency("setsid failed (window) %m");
1096 setprocresources(RESOURCE_WINDOW);
1099 /* Don't use malloc after fork */
1100 strcpy(term, "TERM=");
1101 strncat(term, sp->se_type, sizeof(term) - 6);
1107 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1108 stall("can't exec window system '%s' for port %s: %m",
1109 sp->se_window_argv[0], sp->se_device);
1114 * Start a login session running.
1122 time_t current_time = time((time_t *) 0);
1124 char term[64], *env[2];
1126 if (current_time >= sp->se_started &&
1127 current_time - sp->se_started < GETTY_SPACING) {
1128 if (++sp->se_nspace > GETTY_NSPACE) {
1136 * fork(), not vfork() -- we can't afford to block.
1138 if ((pid = fork()) == -1) {
1139 emergency("can't fork for getty on port %s: %m", sp->se_device);
1147 warning("getty repeating too quickly on port %s, sleeping %d secs",
1148 sp->se_device, GETTY_SLEEP);
1149 sleep((unsigned) GETTY_SLEEP);
1152 if (sp->se_window) {
1153 start_window_system(sp);
1158 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1161 setprocresources(RESOURCE_GETTY);
1164 /* Don't use malloc after fork */
1165 strcpy(term, "TERM=");
1166 strncat(term, sp->se_type, sizeof(term) - 6);
1172 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1173 stall("can't exec getty '%s' for port %s: %m",
1174 sp->se_getty_argv[0], sp->se_device);
1179 * Collect exit status for a child.
1180 * If an exiting login, start a new login running.
1184 collect_child(pid_t pid)
1190 register session_t *sp, *sprev, *snext;
1195 if (! (sp = find_session(pid)))
1198 clear_session_logs(sp);
1202 if (sp->se_flags & SE_SHUTDOWN) {
1203 if ((sprev = sp->se_prev) != NULL)
1204 sprev->se_next = sp->se_next;
1206 sessions = sp->se_next;
1207 if ((snext = sp->se_next) != NULL)
1208 snext->se_prev = sp->se_prev;
1213 if ((pid = start_getty(sp)) == -1) {
1214 /* serious trouble */
1215 requested_transition = clean_ttys;
1219 sp->se_process = pid;
1220 sp->se_started = time((time_t *) 0);
1225 * Catch a signal and request a state transition.
1228 transition_handler(sig)
1234 requested_transition = clean_ttys;
1239 requested_transition = death;
1242 requested_transition = catatonia;
1245 requested_transition = 0;
1251 * Take the system multiuser.
1257 register session_t *sp;
1259 requested_transition = 0;
1262 * If the administrator has not set the security level to -1
1263 * to indicate that the kernel should not run multiuser in secure
1264 * mode, and the run script has not set a higher level of security
1265 * than level 1, then put the kernel into secure mode.
1267 if (getsecuritylevel() == 0)
1268 setsecuritylevel(1);
1270 for (sp = sessions; sp; sp = sp->se_next) {
1273 if ((pid = start_getty(sp)) == -1) {
1274 /* serious trouble */
1275 requested_transition = clean_ttys;
1278 sp->se_process = pid;
1279 sp->se_started = time((time_t *) 0);
1283 while (!requested_transition)
1284 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1287 return (state_func_t) requested_transition;
1291 * This is an n-squared algorithm. We hope it isn't run often...
1296 register session_t *sp, *sprev;
1297 register struct ttyent *typ;
1298 register int session_index = 0;
1299 register int devlen;
1300 char *old_getty, *old_window, *old_type;
1303 return (state_func_t) multi_user;
1305 devlen = sizeof(_PATH_DEV) - 1;
1306 while ((typ = getttyent()) != NULL) {
1309 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1310 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1314 if (sp->se_index != session_index) {
1315 warning("port %s changed utmp index from %d to %d",
1316 sp->se_device, sp->se_index,
1318 sp->se_index = session_index;
1320 if ((typ->ty_status & TTY_ON) == 0 ||
1321 typ->ty_getty == 0) {
1322 sp->se_flags |= SE_SHUTDOWN;
1323 kill(sp->se_process, SIGHUP);
1326 sp->se_flags &= ~SE_SHUTDOWN;
1327 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1328 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1329 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1330 if (setupargv(sp, typ) == 0) {
1331 warning("can't parse getty for port %s",
1333 sp->se_flags |= SE_SHUTDOWN;
1334 kill(sp->se_process, SIGHUP);
1336 else if ( !old_getty
1337 || (!old_type && sp->se_type)
1338 || (old_type && !sp->se_type)
1339 || (!old_window && sp->se_window)
1340 || (old_window && !sp->se_window)
1341 || (strcmp(old_getty, sp->se_getty) != 0)
1342 || (old_window && strcmp(old_window, sp->se_window) != 0)
1343 || (old_type && strcmp(old_type, sp->se_type) != 0)
1345 /* Don't set SE_SHUTDOWN here */
1348 kill(sp->se_process, SIGHUP);
1359 new_session(sprev, session_index, typ);
1364 return (state_func_t) multi_user;
1368 * Block further logins.
1373 register session_t *sp;
1375 for (sp = sessions; sp; sp = sp->se_next)
1376 sp->se_flags |= SE_SHUTDOWN;
1378 return (state_func_t) multi_user;
1393 * Bring the system down to single user.
1398 register session_t *sp;
1401 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1403 /* NB: should send a message to the session logger to avoid blocking. */
1404 logwtmp("~", "shutdown", "");
1406 for (sp = sessions; sp; sp = sp->se_next) {
1407 sp->se_flags |= SE_SHUTDOWN;
1408 kill(sp->se_process, SIGHUP);
1411 /* Try to run the rc.shutdown script within a period of time */
1412 (void) runshutdown();
1414 for (i = 0; i < 2; ++i) {
1415 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1416 return (state_func_t) single_user;
1421 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1423 while (clang == 0 && errno != ECHILD);
1425 if (errno == ECHILD)
1426 return (state_func_t) single_user;
1429 warning("some processes would not die; ps axl advised");
1431 return (state_func_t) single_user;
1435 * Run the system shutdown script.
1437 * Exit codes: XXX I should document more
1438 * -2 shutdown script terminated abnormally
1439 * -1 fatal error - can't run script
1441 * >0 some error (exit code)
1448 int shutdowntimeout;
1451 struct sigaction sa;
1455 * rc.shutdown is optional, so to prevent any unnecessary
1456 * complaints from the shell we simply don't run it if the
1457 * file does not exist. If the stat() here fails for other
1458 * reasons, we'll let the shell complain.
1460 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1463 if ((pid = fork()) == 0) {
1466 /* Assume that init already grab console as ctty before */
1468 sigemptyset(&sa.sa_mask);
1470 sa.sa_handler = SIG_IGN;
1471 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1472 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1474 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1475 warning("can't open %s: %m", _PATH_CONSOLE);
1485 * Run the shutdown script.
1488 argv[1] = _PATH_RUNDOWN;
1491 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1494 setprocresources(RESOURCE_RC);
1496 execv(_PATH_BSHELL, argv);
1497 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1498 _exit(1); /* force single user mode */
1502 emergency("can't fork for %s on %s: %m",
1503 _PATH_BSHELL, _PATH_RUNDOWN);
1504 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1506 sleep(STALL_TIMEOUT);
1510 len = sizeof(shutdowntimeout);
1511 if (sysctlbyname("kern.shutdown_timeout",
1513 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1514 shutdowntimeout = DEATH_SCRIPT;
1515 alarm(shutdowntimeout);
1518 * Copied from single_user(). This is a bit paranoid.
1519 * Use the same ALRM handler.
1522 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1523 collect_child(wpid);
1525 /* we were waiting for the sub-shell */
1526 kill(wpid, SIGTERM);
1527 warning("timeout expired for %s on %s: %m; going to single used mode",
1528 _PATH_BSHELL, _PATH_RUNDOWN);
1534 warning("wait for %s on %s failed: %m; going to single user mode",
1535 _PATH_BSHELL, _PATH_RUNDOWN);
1538 if (wpid == pid && WIFSTOPPED(status)) {
1539 warning("init: %s on %s stopped, restarting\n",
1540 _PATH_BSHELL, _PATH_RUNDOWN);
1544 } while (wpid != pid && !clang);
1546 /* Turn off the alarm */
1549 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1550 requested_transition == catatonia) {
1552 * /etc/rc.shutdown executed /sbin/reboot;
1553 * wait for the end quietly
1562 if (!WIFEXITED(status)) {
1563 warning("%s on %s terminated abnormally, going to single user mode",
1564 _PATH_BSHELL, _PATH_RUNDOWN);
1568 if ((status = WEXITSTATUS(status)) != 0)
1569 warning("%s returned status %d", _PATH_RUNDOWN, status);
1587 while (c == ' ' || c == '\t' )
1597 while (c && c != '\'')
1599 if (!c) /* unterminated string */
1604 while (c && c != ' ' && c != '\t' )
1615 setprocresources(cname)
1619 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1620 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);