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.25 1997/08/06 16:07:52 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>
67 #include <sys/reboot.h>
81 #include <login_cap.h>
84 #include "pathnames.h"
87 * Sleep times; used to prevent thrashing.
89 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
90 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
91 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
92 #define WINDOW_WAIT 3 /* wait N secs after starting window */
93 #define STALL_TIMEOUT 30 /* wait N secs after warning */
94 #define DEATH_WATCH 10 /* wait N secs for procs to die */
95 #define DEATH_SCRIPT 120 /* wait for 2mn for /etc/rc.shutdown */
96 #define RESOURCE_RC "daemon"
97 #define RESOURCE_WINDOW "default"
98 #define RESOURCE_GETTY "default"
100 void handle __P((sig_t, ...));
101 void delset __P((sigset_t *, ...));
103 void stall __P((char *, ...));
104 void warning __P((char *, ...));
105 void emergency __P((char *, ...));
106 void disaster __P((int));
107 void badsys __P((int));
108 int runshutdown __P((void));
111 * We really need a recursive typedef...
112 * The following at least guarantees that the return type of (*state_t)()
113 * is sufficiently wide to hold a function pointer.
115 typedef long (*state_func_t) __P((void));
116 typedef state_func_t (*state_t) __P((void));
118 state_func_t single_user __P((void));
119 state_func_t runcom __P((void));
120 state_func_t read_ttys __P((void));
121 state_func_t multi_user __P((void));
122 state_func_t clean_ttys __P((void));
123 state_func_t catatonia __P((void));
124 state_func_t death __P((void));
126 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
134 void transition __P((state_t));
135 state_t requested_transition = runcom;
137 void setctty __P((char *));
139 typedef struct init_session {
140 int se_index; /* index of entry in ttys file */
141 pid_t se_process; /* controlling process */
142 time_t se_started; /* used to avoid thrashing */
143 int se_flags; /* status of session */
144 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
145 int se_nspace; /* spacing count */
146 char *se_device; /* filename of port */
147 char *se_getty; /* what to run on that port */
148 char *se_getty_argv_space; /* pre-parsed argument array space */
149 char **se_getty_argv; /* pre-parsed argument array */
150 char *se_window; /* window system (started only once) */
151 char *se_window_argv_space; /* pre-parsed argument array space */
152 char **se_window_argv; /* pre-parsed argument array */
153 char *se_type; /* default terminal type */
154 struct init_session *se_prev;
155 struct init_session *se_next;
158 void free_session __P((session_t *));
159 session_t *new_session __P((session_t *, int, struct ttyent *));
162 char **construct_argv __P((char *));
163 void start_window_system __P((session_t *));
164 void collect_child __P((pid_t));
165 pid_t start_getty __P((session_t *));
166 void transition_handler __P((int));
167 void alrm_handler __P((int));
168 void setsecuritylevel __P((int));
169 int getsecuritylevel __P((void));
170 int setupargv __P((session_t *, struct ttyent *));
172 void setprocresources __P((const char *));
176 void clear_session_logs __P((session_t *));
178 int start_session_db __P((void));
179 void add_session __P((session_t *));
180 void del_session __P((session_t *));
181 session_t *find_session __P((pid_t));
185 * The mother of all processes.
197 /* Dispose of random users. */
199 errx(1, "%s", strerror(EPERM));
201 /* System V users like to reexec init. */
203 errx(1, "already running");
206 * Note that this does NOT open a file...
207 * Does 'init' deserve its own facility number?
209 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
212 * Create an initial session.
215 warning("initial setsid() failed: %m");
218 * Establish an initial user so that programs running
219 * single user do not freak out and die (like passwd).
221 if (setlogin("root") < 0)
222 warning("setlogin() failed: %m");
225 * This code assumes that we always get arguments through flags,
226 * never through bits set in some random machine register.
228 while ((c = getopt(argc, argv, "dsf")) != -1)
234 requested_transition = single_user;
237 runcom_mode = FASTBOOT;
240 warning("unrecognized flag '-%c'", c);
245 warning("ignoring excess arguments");
248 mount("devfs", "/dev", MNT_NOEXEC|MNT_RDONLY, 0);
252 * We catch or block signals rather than ignore them,
253 * so that they get reset on exec.
255 handle(badsys, SIGSYS, 0);
256 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
257 SIGBUS, SIGXCPU, SIGXFSZ, 0);
258 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP, 0);
259 handle(alrm_handler, SIGALRM, 0);
261 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
262 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM, 0);
263 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
264 sigemptyset(&sa.sa_mask);
266 sa.sa_handler = SIG_IGN;
267 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
268 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
278 * Start the state machine.
280 transition(requested_transition);
283 * Should never reach here.
289 * Associate a function with a signal handler.
293 handle(sig_t handler, ...)
307 handler = va_arg(ap, sig_t);
309 va_start(ap, handler);
312 sa.sa_handler = handler;
313 sigfillset(&mask_everything);
315 while ((sig = va_arg(ap, int)) != NULL) {
316 sa.sa_mask = mask_everything;
317 /* XXX SA_RESTART? */
318 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
319 sigaction(sig, &sa, (struct sigaction *) 0);
325 * Delete a set of signals from a mask.
329 delset(sigset_t *maskp, ...)
341 maskp = va_arg(ap, sigset_t *);
346 while ((sig = va_arg(ap, int)) != NULL)
347 sigdelset(maskp, sig);
352 * Log a message and sleep for a while (to give someone an opportunity
353 * to read it and to save log or hardcopy output if the problem is chronic).
354 * NB: should send a message to the session logger to avoid blocking.
358 stall(char *message, ...)
369 message = va_arg(ap, char *);
371 va_start(ap, message);
374 vsyslog(LOG_ALERT, message, ap);
376 sleep(STALL_TIMEOUT);
380 * Like stall(), but doesn't sleep.
381 * If cpp had variadic macros, the two functions could be #defines for another.
382 * NB: should send a message to the session logger to avoid blocking.
386 warning(char *message, ...)
397 message = va_arg(ap, char *);
399 va_start(ap, message);
402 vsyslog(LOG_ALERT, message, ap);
407 * Log an emergency message.
408 * NB: should send a message to the session logger to avoid blocking.
412 emergency(char *message, ...)
423 message = va_arg(ap, char *);
425 va_start(ap, message);
428 vsyslog(LOG_EMERG, message, ap);
433 * Catch a SIGSYS signal.
435 * These may arise if a system does not support sysctl.
436 * We tolerate up to 25 of these, then throw in the towel.
442 static int badcount = 0;
450 * Catch an unexpected signal.
456 emergency("fatal signal: %s",
457 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
459 sleep(STALL_TIMEOUT);
460 _exit(sig); /* reboot */
464 * Get the security level of the kernel.
469 #ifdef KERN_SECURELVL
470 int name[2], curlevel;
475 name[1] = KERN_SECURELVL;
476 len = sizeof curlevel;
477 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
478 emergency("cannot get kernel security level: %s",
489 * Set the security level of the kernel.
492 setsecuritylevel(newlevel)
495 #ifdef KERN_SECURELVL
496 int name[2], curlevel;
499 curlevel = getsecuritylevel();
500 if (newlevel == curlevel)
503 name[1] = KERN_SECURELVL;
504 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
506 "cannot change kernel security level from %d to %d: %s",
507 curlevel, newlevel, strerror(errno));
511 warning("kernel security level changed from %d to %d",
518 * Change states in the finite state machine.
519 * The initial state is passed as an argument.
526 s = (state_t) (*s)();
530 * Close out the accounting files for a login session.
531 * NB: should send a message to the session logger to avoid blocking.
534 clear_session_logs(sp)
537 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
540 logwtmp(line, "", "");
544 * Start a session and allocate a controlling terminal.
545 * Only called by children of init after forking.
554 if ((fd = open(name, O_RDWR)) == -1) {
555 stall("can't open %s: %m", name);
558 if (login_tty(fd) == -1) {
559 stall("can't get %s for controlling terminal: %m", name);
565 * Bring the system up single user.
573 char *shell = _PATH_BSHELL;
578 static const char banner[] =
579 "Enter root password, or ^D to go multi-user\n";
580 char *clear, *password;
584 * If the kernel is in secure mode, downgrade it to insecure mode.
586 if (getsecuritylevel() > 0)
590 /* Instead of going single user, let's halt the machine */
598 if ((pid = fork()) == 0) {
600 * Start the single user session.
602 setctty(_PATH_CONSOLE);
606 * Check the root password.
607 * We don't care if the console is 'on' by default;
608 * it's the only tty that can be 'off' and 'secure'.
610 typ = getttynam("console");
611 pp = getpwnam("root");
612 if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp && *pp->pw_passwd) {
613 write(2, banner, sizeof banner - 1);
615 clear = getpass("Password:");
616 if (clear == 0 || *clear == '\0')
618 password = crypt(clear, pp->pw_passwd);
619 bzero(clear, _PASSWORD_LEN);
620 if (strcmp(password, pp->pw_passwd) == 0)
622 warning("single-user login failed\n");
631 char altshell[128], *cp = altshell;
635 "Enter pathname of shell or RETURN for sh: "
636 (void)write(STDERR_FILENO,
637 SHREQUEST, sizeof(SHREQUEST) - 1);
638 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
639 num != 0 && *cp != '\n' && cp < &altshell[127])
642 if (altshell[0] != '\0')
645 #endif /* DEBUGSHELL */
649 * We catch all the interesting ones,
650 * and those are reset to SIG_DFL on exec.
653 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
657 * If the default one doesn't work, try the Bourne shell.
662 emergency("can't exec %s for single user: %m", shell);
663 execv(_PATH_BSHELL, argv);
664 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
665 sleep(STALL_TIMEOUT);
671 * We are seriously hosed. Do our best.
673 emergency("can't fork single-user shell, trying again");
674 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
676 return (state_func_t) single_user;
679 requested_transition = 0;
681 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
686 warning("wait for single-user shell failed: %m; restarting");
687 return (state_func_t) single_user;
689 if (wpid == pid && WIFSTOPPED(status)) {
690 warning("init: shell stopped, restarting\n");
694 } while (wpid != pid && !requested_transition);
696 if (requested_transition)
697 return (state_func_t) requested_transition;
699 if (!WIFEXITED(status)) {
700 if (WTERMSIG(status) == SIGKILL) {
702 * reboot(8) killed shell?
704 warning("single user shell terminated.");
705 sleep(STALL_TIMEOUT);
708 warning("single user shell terminated, restarting");
709 return (state_func_t) single_user;
713 runcom_mode = FASTBOOT;
714 return (state_func_t) runcom;
718 * Run the system startup script.
728 if ((pid = fork()) == 0) {
729 sigemptyset(&sa.sa_mask);
731 sa.sa_handler = SIG_IGN;
732 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
733 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
735 setctty(_PATH_CONSOLE);
738 argv[1] = _PATH_RUNCOM;
739 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
742 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
745 setprocresources(RESOURCE_RC);
747 execv(_PATH_BSHELL, argv);
748 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
749 _exit(1); /* force single user mode */
753 emergency("can't fork for %s on %s: %m",
754 _PATH_BSHELL, _PATH_RUNCOM);
755 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
757 sleep(STALL_TIMEOUT);
758 return (state_func_t) single_user;
762 * Copied from single_user(). This is a bit paranoid.
765 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
770 warning("wait for %s on %s failed: %m; going to single user mode",
771 _PATH_BSHELL, _PATH_RUNCOM);
772 return (state_func_t) single_user;
774 if (wpid == pid && WIFSTOPPED(status)) {
775 warning("init: %s on %s stopped, restarting\n",
776 _PATH_BSHELL, _PATH_RUNCOM);
780 } while (wpid != pid);
782 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
783 requested_transition == catatonia) {
784 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
792 if (!WIFEXITED(status)) {
793 warning("%s on %s terminated abnormally, going to single user mode",
794 _PATH_BSHELL, _PATH_RUNCOM);
795 return (state_func_t) single_user;
798 if (WEXITSTATUS(status))
799 return (state_func_t) single_user;
801 runcom_mode = AUTOBOOT; /* the default */
802 /* NB: should send a message to the session logger to avoid blocking. */
803 logwtmp("~", "reboot", "");
804 return (state_func_t) read_ttys;
808 * Open the session database.
810 * NB: We could pass in the size here; is it necessary?
815 if (session_db && (*session_db->close)(session_db))
816 emergency("session database close: %s", strerror(errno));
817 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
818 emergency("session database open: %s", strerror(errno));
826 * Add a new login session.
835 key.data = &sp->se_process;
836 key.size = sizeof sp->se_process;
838 data.size = sizeof sp;
840 if ((*session_db->put)(session_db, &key, &data, 0))
841 emergency("insert %d: %s", sp->se_process, strerror(errno));
845 * Delete an old login session.
853 key.data = &sp->se_process;
854 key.size = sizeof sp->se_process;
856 if ((*session_db->del)(session_db, &key, 0))
857 emergency("delete %d: %s", sp->se_process, strerror(errno));
861 * Look up a login session by pid.
865 find_session(pid_t pid)
876 key.size = sizeof pid;
877 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
879 bcopy(data.data, (char *)&ret, sizeof(ret));
884 * Construct an argument vector from a command line.
887 construct_argv(command)
891 register int argc = 0;
892 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
895 if ((argv[argc++] = strk(command)) == 0)
897 while ((argv[argc++] = strk((char *) 0)) != NULL)
903 * Deallocate a session descriptor.
907 register session_t *sp;
912 free(sp->se_getty_argv_space);
913 free(sp->se_getty_argv);
917 free(sp->se_window_argv_space);
918 free(sp->se_window_argv);
926 * Allocate a new session descriptor.
929 new_session(sprev, session_index, typ)
932 register struct ttyent *typ;
934 register session_t *sp;
937 if ((typ->ty_status & TTY_ON) == 0 ||
942 sp = (session_t *) calloc(1, sizeof (session_t));
944 sp->se_index = session_index;
946 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
947 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
950 * Attempt to open the device, if we get "device not configured"
951 * then don't add the device to the session list.
953 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
954 if (errno == ENXIO) {
961 if (setupargv(sp, typ) == 0) {
979 * Calculate getty and if useful window argv vectors.
989 free(sp->se_getty_argv_space);
990 free(sp->se_getty_argv);
992 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
993 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
994 sp->se_getty_argv_space = strdup(sp->se_getty);
995 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
996 if (sp->se_getty_argv == 0) {
997 warning("can't parse getty for port %s", sp->se_device);
999 free(sp->se_getty_argv_space);
1000 sp->se_getty = sp->se_getty_argv_space = 0;
1003 if (sp->se_window) {
1004 free(sp->se_window);
1005 free(sp->se_window_argv_space);
1006 free(sp->se_window_argv);
1008 sp->se_window = sp->se_window_argv_space = 0;
1009 sp->se_window_argv = 0;
1010 if (typ->ty_window) {
1011 sp->se_window = strdup(typ->ty_window);
1012 sp->se_window_argv_space = strdup(sp->se_window);
1013 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1014 if (sp->se_window_argv == 0) {
1015 warning("can't parse window for port %s",
1017 free(sp->se_window_argv_space);
1018 free(sp->se_window);
1019 sp->se_window = sp->se_window_argv_space = 0;
1025 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1030 * Walk the list of ttys and create sessions for each active line.
1035 int session_index = 0;
1036 register session_t *sp, *snext;
1037 register struct ttyent *typ;
1040 * Destroy any previous session state.
1041 * There shouldn't be any, but just in case...
1043 for (sp = sessions; sp; sp = snext) {
1045 clear_session_logs(sp);
1046 snext = sp->se_next;
1050 if (start_session_db())
1051 return (state_func_t) single_user;
1054 * Allocate a session entry for each active port.
1055 * Note that sp starts at 0.
1057 while ((typ = getttyent()) != NULL)
1058 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1063 return (state_func_t) multi_user;
1067 * Start a window system running.
1070 start_window_system(sp)
1075 char term[64], *env[2];
1077 if ((pid = fork()) == -1) {
1078 emergency("can't fork for window system on port %s: %m",
1080 /* hope that getty fails and we can try again */
1088 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1091 emergency("setsid failed (window) %m");
1094 setprocresources(RESOURCE_WINDOW);
1097 /* Don't use malloc after fork */
1098 strcpy(term, "TERM=");
1099 strncat(term, sp->se_type, sizeof(term) - 6);
1105 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1106 stall("can't exec window system '%s' for port %s: %m",
1107 sp->se_window_argv[0], sp->se_device);
1112 * Start a login session running.
1120 time_t current_time = time((time_t *) 0);
1122 char term[64], *env[2];
1124 if (current_time >= sp->se_started &&
1125 current_time - sp->se_started < GETTY_SPACING) {
1126 if (++sp->se_nspace > GETTY_NSPACE) {
1134 * fork(), not vfork() -- we can't afford to block.
1136 if ((pid = fork()) == -1) {
1137 emergency("can't fork for getty on port %s: %m", sp->se_device);
1145 warning("getty repeating too quickly on port %s, sleeping %d secs",
1146 sp->se_device, GETTY_SLEEP);
1147 sleep((unsigned) GETTY_SLEEP);
1150 if (sp->se_window) {
1151 start_window_system(sp);
1156 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1159 setprocresources(RESOURCE_GETTY);
1162 /* Don't use malloc after fork */
1163 strcpy(term, "TERM=");
1164 strncat(term, sp->se_type, sizeof(term) - 6);
1170 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1171 stall("can't exec getty '%s' for port %s: %m",
1172 sp->se_getty_argv[0], sp->se_device);
1177 * Collect exit status for a child.
1178 * If an exiting login, start a new login running.
1182 collect_child(pid_t pid)
1188 register session_t *sp, *sprev, *snext;
1193 if (! (sp = find_session(pid)))
1196 clear_session_logs(sp);
1200 if (sp->se_flags & SE_SHUTDOWN) {
1201 if ((sprev = sp->se_prev) != NULL)
1202 sprev->se_next = sp->se_next;
1204 sessions = sp->se_next;
1205 if ((snext = sp->se_next) != NULL)
1206 snext->se_prev = sp->se_prev;
1211 if ((pid = start_getty(sp)) == -1) {
1212 /* serious trouble */
1213 requested_transition = clean_ttys;
1217 sp->se_process = pid;
1218 sp->se_started = time((time_t *) 0);
1223 * Catch a signal and request a state transition.
1226 transition_handler(sig)
1232 requested_transition = clean_ttys;
1237 requested_transition = death;
1240 requested_transition = catatonia;
1243 requested_transition = 0;
1249 * Take the system multiuser.
1255 register session_t *sp;
1257 requested_transition = 0;
1260 * If the administrator has not set the security level to -1
1261 * to indicate that the kernel should not run multiuser in secure
1262 * mode, and the run script has not set a higher level of security
1263 * than level 1, then put the kernel into secure mode.
1265 if (getsecuritylevel() == 0)
1266 setsecuritylevel(1);
1268 for (sp = sessions; sp; sp = sp->se_next) {
1271 if ((pid = start_getty(sp)) == -1) {
1272 /* serious trouble */
1273 requested_transition = clean_ttys;
1276 sp->se_process = pid;
1277 sp->se_started = time((time_t *) 0);
1281 while (!requested_transition)
1282 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1285 return (state_func_t) requested_transition;
1289 * This is an n-squared algorithm. We hope it isn't run often...
1294 register session_t *sp, *sprev;
1295 register struct ttyent *typ;
1296 register int session_index = 0;
1297 register int devlen;
1298 char *old_getty, *old_window, *old_type;
1301 return (state_func_t) multi_user;
1303 devlen = sizeof(_PATH_DEV) - 1;
1304 while ((typ = getttyent()) != NULL) {
1307 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1308 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1312 if (sp->se_index != session_index) {
1313 warning("port %s changed utmp index from %d to %d",
1314 sp->se_device, sp->se_index,
1316 sp->se_index = session_index;
1318 if ((typ->ty_status & TTY_ON) == 0 ||
1319 typ->ty_getty == 0) {
1320 sp->se_flags |= SE_SHUTDOWN;
1321 kill(sp->se_process, SIGHUP);
1324 sp->se_flags &= ~SE_SHUTDOWN;
1325 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1326 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1327 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1328 if (setupargv(sp, typ) == 0) {
1329 warning("can't parse getty for port %s",
1331 sp->se_flags |= SE_SHUTDOWN;
1332 kill(sp->se_process, SIGHUP);
1334 else if ( !old_getty
1335 || (!old_type && sp->se_type)
1336 || (old_type && !sp->se_type)
1337 || (!old_window && sp->se_window)
1338 || (old_window && !sp->se_window)
1339 || (strcmp(old_getty, sp->se_getty) != 0)
1340 || (old_window && strcmp(old_window, sp->se_window) != 0)
1341 || (old_type && strcmp(old_type, sp->se_type) != 0)
1343 /* Don't set SE_SHUTDOWN here */
1346 kill(sp->se_process, SIGHUP);
1357 new_session(sprev, session_index, typ);
1362 return (state_func_t) multi_user;
1366 * Block further logins.
1371 register session_t *sp;
1373 for (sp = sessions; sp; sp = sp->se_next)
1374 sp->se_flags |= SE_SHUTDOWN;
1376 return (state_func_t) multi_user;
1391 * Bring the system down to single user.
1396 register session_t *sp;
1399 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1401 /* NB: should send a message to the session logger to avoid blocking. */
1402 logwtmp("~", "shutdown", "");
1404 for (sp = sessions; sp; sp = sp->se_next) {
1405 sp->se_flags |= SE_SHUTDOWN;
1406 kill(sp->se_process, SIGHUP);
1409 /* Try to run the rc.shutdown script within a period of time */
1410 (void) runshutdown();
1412 for (i = 0; i < 2; ++i) {
1413 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1414 return (state_func_t) single_user;
1419 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1421 while (clang == 0 && errno != ECHILD);
1423 if (errno == ECHILD)
1424 return (state_func_t) single_user;
1427 warning("some processes would not die; ps axl advised");
1429 return (state_func_t) single_user;
1433 * Run the system shutdown script.
1435 * Exit codes: XXX I should document more
1436 * -2 shutdown script terminated abnormally
1437 * -1 fatal error - can't run script
1439 * >0 some error (exit code)
1446 int shutdowntimeout;
1449 struct sigaction sa;
1451 if ((pid = fork()) == 0) {
1454 /* Assume that init already grab console as ctty before */
1456 sigemptyset(&sa.sa_mask);
1458 sa.sa_handler = SIG_IGN;
1459 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1460 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1462 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1463 warning("can't open %s: %m", _PATH_CONSOLE);
1473 * Run the shutdown script.
1476 argv[1] = _PATH_RUNDOWN;
1479 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1482 setprocresources(RESOURCE_RC);
1484 execv(_PATH_BSHELL, argv);
1485 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1486 _exit(1); /* force single user mode */
1490 emergency("can't fork for %s on %s: %m",
1491 _PATH_BSHELL, _PATH_RUNDOWN);
1492 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1494 sleep(STALL_TIMEOUT);
1498 len = sizeof(shutdowntimeout);
1499 if (sysctlbyname("kern.shutdown_timeout",
1501 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1502 shutdowntimeout = DEATH_SCRIPT;
1503 alarm(shutdowntimeout);
1506 * Copied from single_user(). This is a bit paranoid.
1507 * Use the same ALRM handler.
1510 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1511 collect_child(wpid);
1513 /* we were waiting for the sub-shell */
1514 kill(wpid, SIGTERM);
1515 warning("timeout expired for %s on %s: %m; going to single used mode",
1516 _PATH_BSHELL, _PATH_RUNDOWN);
1522 warning("wait for %s on %s failed: %m; going to single user mode",
1523 _PATH_BSHELL, _PATH_RUNDOWN);
1526 if (wpid == pid && WIFSTOPPED(status)) {
1527 warning("init: %s on %s stopped, restarting\n",
1528 _PATH_BSHELL, _PATH_RUNDOWN);
1532 } while (wpid != pid && !clang);
1534 /* Turn off the alarm */
1537 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1538 requested_transition == catatonia) {
1540 * /etc/rc.shutdown executed /sbin/reboot;
1541 * wait for the end quietly
1550 if (!WIFEXITED(status)) {
1551 warning("%s on %s terminated abnormally, going to single user mode",
1552 _PATH_BSHELL, _PATH_RUNDOWN);
1556 if ((status = WEXITSTATUS(status)) != 0)
1557 warning("%s returned status %d", _PATH_RUNDOWN, status);
1575 while (c == ' ' || c == '\t' )
1585 while (c && c != '\'')
1587 if (!c) /* unterminated string */
1592 while (c && c != ' ' && c != '\t' )
1603 setprocresources(cname)
1607 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1608 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);