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
38 static const char copyright[] =
39 "@(#) Copyright (c) 1991, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
45 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
47 static const char rcsid[] =
48 "$Id: init.c,v 1.30 1998/07/06 06:56:08 charnier Exp $";
51 #include <sys/param.h>
52 #include <sys/ioctl.h>
53 #include <sys/mount.h>
54 #include <sys/sysctl.h>
56 #include <sys/types.h>
71 #include <sys/reboot.h>
85 #include <login_cap.h>
88 #include "pathnames.h"
91 * Sleep times; used to prevent thrashing.
93 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
94 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
95 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
96 #define WINDOW_WAIT 3 /* wait N secs after starting window */
97 #define STALL_TIMEOUT 30 /* wait N secs after warning */
98 #define DEATH_WATCH 10 /* wait N secs for procs to die */
99 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
100 #define RESOURCE_RC "daemon"
101 #define RESOURCE_WINDOW "default"
102 #define RESOURCE_GETTY "default"
104 void handle __P((sig_t, ...));
105 void delset __P((sigset_t *, ...));
107 void stall __P((char *, ...));
108 void warning __P((char *, ...));
109 void emergency __P((char *, ...));
110 void disaster __P((int));
111 void badsys __P((int));
112 int runshutdown __P((void));
115 * We really need a recursive typedef...
116 * The following at least guarantees that the return type of (*state_t)()
117 * is sufficiently wide to hold a function pointer.
119 typedef long (*state_func_t) __P((void));
120 typedef state_func_t (*state_t) __P((void));
122 state_func_t single_user __P((void));
123 state_func_t runcom __P((void));
124 state_func_t read_ttys __P((void));
125 state_func_t multi_user __P((void));
126 state_func_t clean_ttys __P((void));
127 state_func_t catatonia __P((void));
128 state_func_t death __P((void));
130 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
138 void transition __P((state_t));
139 state_t requested_transition = runcom;
141 void setctty __P((char *));
143 typedef struct init_session {
144 int se_index; /* index of entry in ttys file */
145 pid_t se_process; /* controlling process */
146 time_t se_started; /* used to avoid thrashing */
147 int se_flags; /* status of session */
148 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
149 int se_nspace; /* spacing count */
150 char *se_device; /* filename of port */
151 char *se_getty; /* what to run on that port */
152 char *se_getty_argv_space; /* pre-parsed argument array space */
153 char **se_getty_argv; /* pre-parsed argument array */
154 char *se_window; /* window system (started only once) */
155 char *se_window_argv_space; /* pre-parsed argument array space */
156 char **se_window_argv; /* pre-parsed argument array */
157 char *se_type; /* default terminal type */
158 struct init_session *se_prev;
159 struct init_session *se_next;
162 void free_session __P((session_t *));
163 session_t *new_session __P((session_t *, int, struct ttyent *));
166 char **construct_argv __P((char *));
167 void start_window_system __P((session_t *));
168 void collect_child __P((pid_t));
169 pid_t start_getty __P((session_t *));
170 void transition_handler __P((int));
171 void alrm_handler __P((int));
172 void setsecuritylevel __P((int));
173 int getsecuritylevel __P((void));
174 int setupargv __P((session_t *, struct ttyent *));
176 void setprocresources __P((const char *));
180 void clear_session_logs __P((session_t *));
182 int start_session_db __P((void));
183 void add_session __P((session_t *));
184 void del_session __P((session_t *));
185 session_t *find_session __P((pid_t));
189 * The mother of all processes.
201 /* Dispose of random users. */
203 errx(1, "%s", strerror(EPERM));
205 /* System V users like to reexec init. */
207 errx(1, "already running");
210 * Note that this does NOT open a file...
211 * Does 'init' deserve its own facility number?
213 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
216 * Create an initial session.
219 warning("initial setsid() failed: %m");
222 * Establish an initial user so that programs running
223 * single user do not freak out and die (like passwd).
225 if (setlogin("root") < 0)
226 warning("setlogin() failed: %m");
229 * This code assumes that we always get arguments through flags,
230 * never through bits set in some random machine register.
232 while ((c = getopt(argc, argv, "dsf")) != -1)
238 requested_transition = single_user;
241 runcom_mode = FASTBOOT;
244 warning("unrecognized flag '-%c'", c);
249 warning("ignoring excess arguments");
252 mount("devfs", "/dev", MNT_NOEXEC|MNT_RDONLY, 0);
256 * We catch or block signals rather than ignore them,
257 * so that they get reset on exec.
259 handle(badsys, SIGSYS, 0);
260 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
261 SIGBUS, SIGXCPU, SIGXFSZ, 0);
262 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP, 0);
263 handle(alrm_handler, SIGALRM, 0);
265 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
266 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM, 0);
267 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
268 sigemptyset(&sa.sa_mask);
270 sa.sa_handler = SIG_IGN;
271 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
272 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
282 * Start the state machine.
284 transition(requested_transition);
287 * Should never reach here.
293 * Associate a function with a signal handler.
297 handle(sig_t handler, ...)
305 sigset_t mask_everything;
311 handler = va_arg(ap, sig_t);
313 va_start(ap, handler);
316 sa.sa_handler = handler;
317 sigfillset(&mask_everything);
319 while ((sig = va_arg(ap, int)) != NULL) {
320 sa.sa_mask = mask_everything;
321 /* XXX SA_RESTART? */
322 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
323 sigaction(sig, &sa, (struct sigaction *) 0);
329 * Delete a set of signals from a mask.
333 delset(sigset_t *maskp, ...)
345 maskp = va_arg(ap, sigset_t *);
350 while ((sig = va_arg(ap, int)) != NULL)
351 sigdelset(maskp, sig);
356 * Log a message and sleep for a while (to give someone an opportunity
357 * to read it and to save log or hardcopy output if the problem is chronic).
358 * NB: should send a message to the session logger to avoid blocking.
362 stall(char *message, ...)
373 message = va_arg(ap, char *);
375 va_start(ap, message);
378 vsyslog(LOG_ALERT, message, ap);
380 sleep(STALL_TIMEOUT);
384 * Like stall(), but doesn't sleep.
385 * If cpp had variadic macros, the two functions could be #defines for another.
386 * NB: should send a message to the session logger to avoid blocking.
390 warning(char *message, ...)
401 message = va_arg(ap, char *);
403 va_start(ap, message);
406 vsyslog(LOG_ALERT, message, ap);
411 * Log an emergency message.
412 * NB: should send a message to the session logger to avoid blocking.
416 emergency(char *message, ...)
427 message = va_arg(ap, char *);
429 va_start(ap, message);
432 vsyslog(LOG_EMERG, message, ap);
437 * Catch a SIGSYS signal.
439 * These may arise if a system does not support sysctl.
440 * We tolerate up to 25 of these, then throw in the towel.
446 static int badcount = 0;
454 * Catch an unexpected signal.
460 emergency("fatal signal: %s",
461 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
463 sleep(STALL_TIMEOUT);
464 _exit(sig); /* reboot */
468 * Get the security level of the kernel.
473 #ifdef KERN_SECURELVL
474 int name[2], curlevel;
479 name[1] = KERN_SECURELVL;
480 len = sizeof curlevel;
481 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
482 emergency("cannot get kernel security level: %s",
493 * Set the security level of the kernel.
496 setsecuritylevel(newlevel)
499 #ifdef KERN_SECURELVL
500 int name[2], curlevel;
503 curlevel = getsecuritylevel();
504 if (newlevel == curlevel)
507 name[1] = KERN_SECURELVL;
508 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
510 "cannot change kernel security level from %d to %d: %s",
511 curlevel, newlevel, strerror(errno));
515 warning("kernel security level changed from %d to %d",
522 * Change states in the finite state machine.
523 * The initial state is passed as an argument.
530 s = (state_t) (*s)();
534 * Close out the accounting files for a login session.
535 * NB: should send a message to the session logger to avoid blocking.
538 clear_session_logs(sp)
541 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
544 logwtmp(line, "", "");
548 * Start a session and allocate a controlling terminal.
549 * Only called by children of init after forking.
558 if ((fd = open(name, O_RDWR)) == -1) {
559 stall("can't open %s: %m", name);
562 if (login_tty(fd) == -1) {
563 stall("can't get %s for controlling terminal: %m", name);
569 * Bring the system up single user.
577 char *shell = _PATH_BSHELL;
582 static const char banner[] =
583 "Enter root password, or ^D to go multi-user\n";
584 char *clear, *password;
591 * If the kernel is in secure mode, downgrade it to insecure mode.
593 if (getsecuritylevel() > 0)
597 /* Instead of going single user, let's halt the machine */
605 if ((pid = fork()) == 0) {
607 * Start the single user session.
609 setctty(_PATH_CONSOLE);
613 * Check the root password.
614 * We don't care if the console is 'on' by default;
615 * it's the only tty that can be 'off' and 'secure'.
617 typ = getttynam("console");
618 pp = getpwnam("root");
619 if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp && *pp->pw_passwd) {
620 write(2, banner, sizeof banner - 1);
622 clear = getpass("Password:");
623 if (clear == 0 || *clear == '\0')
625 password = crypt(clear, pp->pw_passwd);
626 bzero(clear, _PASSWORD_LEN);
627 if (strcmp(password, pp->pw_passwd) == 0)
629 warning("single-user login failed\n");
642 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
643 (void)write(STDERR_FILENO,
644 SHREQUEST, sizeof(SHREQUEST) - 1);
645 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
646 num != 0 && *cp != '\n' && cp < &altshell[127])
649 if (altshell[0] != '\0')
652 #endif /* DEBUGSHELL */
656 * We catch all the interesting ones,
657 * and those are reset to SIG_DFL on exec.
660 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
664 * If the default one doesn't work, try the Bourne shell.
669 emergency("can't exec %s for single user: %m", shell);
670 execv(_PATH_BSHELL, argv);
671 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
672 sleep(STALL_TIMEOUT);
678 * We are seriously hosed. Do our best.
680 emergency("can't fork single-user shell, trying again");
681 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
683 return (state_func_t) single_user;
686 requested_transition = 0;
688 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
693 warning("wait for single-user shell failed: %m; restarting");
694 return (state_func_t) single_user;
696 if (wpid == pid && WIFSTOPPED(status)) {
697 warning("init: shell stopped, restarting\n");
701 } while (wpid != pid && !requested_transition);
703 if (requested_transition)
704 return (state_func_t) requested_transition;
706 if (!WIFEXITED(status)) {
707 if (WTERMSIG(status) == SIGKILL) {
709 * reboot(8) killed shell?
711 warning("single user shell terminated.");
712 sleep(STALL_TIMEOUT);
715 warning("single user shell terminated, restarting");
716 return (state_func_t) single_user;
720 runcom_mode = FASTBOOT;
721 return (state_func_t) runcom;
725 * Run the system startup script.
735 if ((pid = fork()) == 0) {
736 sigemptyset(&sa.sa_mask);
738 sa.sa_handler = SIG_IGN;
739 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
740 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
742 setctty(_PATH_CONSOLE);
745 argv[1] = _PATH_RUNCOM;
746 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
749 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
752 setprocresources(RESOURCE_RC);
754 execv(_PATH_BSHELL, argv);
755 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
756 _exit(1); /* force single user mode */
760 emergency("can't fork for %s on %s: %m",
761 _PATH_BSHELL, _PATH_RUNCOM);
762 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
764 sleep(STALL_TIMEOUT);
765 return (state_func_t) single_user;
769 * Copied from single_user(). This is a bit paranoid.
772 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
777 warning("wait for %s on %s failed: %m; going to single user mode",
778 _PATH_BSHELL, _PATH_RUNCOM);
779 return (state_func_t) single_user;
781 if (wpid == pid && WIFSTOPPED(status)) {
782 warning("init: %s on %s stopped, restarting\n",
783 _PATH_BSHELL, _PATH_RUNCOM);
787 } while (wpid != pid);
789 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
790 requested_transition == catatonia) {
791 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
799 if (!WIFEXITED(status)) {
800 warning("%s on %s terminated abnormally, going to single user mode",
801 _PATH_BSHELL, _PATH_RUNCOM);
802 return (state_func_t) single_user;
805 if (WEXITSTATUS(status))
806 return (state_func_t) single_user;
808 runcom_mode = AUTOBOOT; /* the default */
809 /* NB: should send a message to the session logger to avoid blocking. */
810 logwtmp("~", "reboot", "");
811 return (state_func_t) read_ttys;
815 * Open the session database.
817 * NB: We could pass in the size here; is it necessary?
822 if (session_db && (*session_db->close)(session_db))
823 emergency("session database close: %s", strerror(errno));
824 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
825 emergency("session database open: %s", strerror(errno));
833 * Add a new login session.
842 key.data = &sp->se_process;
843 key.size = sizeof sp->se_process;
845 data.size = sizeof sp;
847 if ((*session_db->put)(session_db, &key, &data, 0))
848 emergency("insert %d: %s", sp->se_process, strerror(errno));
852 * Delete an old login session.
860 key.data = &sp->se_process;
861 key.size = sizeof sp->se_process;
863 if ((*session_db->del)(session_db, &key, 0))
864 emergency("delete %d: %s", sp->se_process, strerror(errno));
868 * Look up a login session by pid.
872 find_session(pid_t pid)
883 key.size = sizeof pid;
884 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
886 bcopy(data.data, (char *)&ret, sizeof(ret));
891 * Construct an argument vector from a command line.
894 construct_argv(command)
898 register int argc = 0;
899 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
902 if ((argv[argc++] = strk(command)) == 0)
904 while ((argv[argc++] = strk((char *) 0)) != NULL)
910 * Deallocate a session descriptor.
914 register session_t *sp;
919 free(sp->se_getty_argv_space);
920 free(sp->se_getty_argv);
924 free(sp->se_window_argv_space);
925 free(sp->se_window_argv);
933 * Allocate a new session descriptor.
936 new_session(sprev, session_index, typ)
939 register struct ttyent *typ;
941 register session_t *sp;
944 if ((typ->ty_status & TTY_ON) == 0 ||
949 sp = (session_t *) calloc(1, sizeof (session_t));
951 sp->se_index = session_index;
953 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
954 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
957 * Attempt to open the device, if we get "device not configured"
958 * then don't add the device to the session list.
960 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
961 if (errno == ENXIO) {
968 if (setupargv(sp, typ) == 0) {
986 * Calculate getty and if useful window argv vectors.
996 free(sp->se_getty_argv_space);
997 free(sp->se_getty_argv);
999 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1000 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1001 sp->se_getty_argv_space = strdup(sp->se_getty);
1002 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1003 if (sp->se_getty_argv == 0) {
1004 warning("can't parse getty for port %s", sp->se_device);
1006 free(sp->se_getty_argv_space);
1007 sp->se_getty = sp->se_getty_argv_space = 0;
1010 if (sp->se_window) {
1011 free(sp->se_window);
1012 free(sp->se_window_argv_space);
1013 free(sp->se_window_argv);
1015 sp->se_window = sp->se_window_argv_space = 0;
1016 sp->se_window_argv = 0;
1017 if (typ->ty_window) {
1018 sp->se_window = strdup(typ->ty_window);
1019 sp->se_window_argv_space = strdup(sp->se_window);
1020 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1021 if (sp->se_window_argv == 0) {
1022 warning("can't parse window for port %s",
1024 free(sp->se_window_argv_space);
1025 free(sp->se_window);
1026 sp->se_window = sp->se_window_argv_space = 0;
1032 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1037 * Walk the list of ttys and create sessions for each active line.
1042 int session_index = 0;
1043 register session_t *sp, *snext;
1044 register struct ttyent *typ;
1047 * Destroy any previous session state.
1048 * There shouldn't be any, but just in case...
1050 for (sp = sessions; sp; sp = snext) {
1052 clear_session_logs(sp);
1053 snext = sp->se_next;
1057 if (start_session_db())
1058 return (state_func_t) single_user;
1061 * Allocate a session entry for each active port.
1062 * Note that sp starts at 0.
1064 while ((typ = getttyent()) != NULL)
1065 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1070 return (state_func_t) multi_user;
1074 * Start a window system running.
1077 start_window_system(sp)
1082 char term[64], *env[2];
1084 if ((pid = fork()) == -1) {
1085 emergency("can't fork for window system on port %s: %m",
1087 /* hope that getty fails and we can try again */
1095 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1098 emergency("setsid failed (window) %m");
1101 setprocresources(RESOURCE_WINDOW);
1104 /* Don't use malloc after fork */
1105 strcpy(term, "TERM=");
1106 strncat(term, sp->se_type, sizeof(term) - 6);
1112 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1113 stall("can't exec window system '%s' for port %s: %m",
1114 sp->se_window_argv[0], sp->se_device);
1119 * Start a login session running.
1127 time_t current_time = time((time_t *) 0);
1129 char term[64], *env[2];
1131 if (current_time >= sp->se_started &&
1132 current_time - sp->se_started < GETTY_SPACING) {
1133 if (++sp->se_nspace > GETTY_NSPACE) {
1141 * fork(), not vfork() -- we can't afford to block.
1143 if ((pid = fork()) == -1) {
1144 emergency("can't fork for getty on port %s: %m", sp->se_device);
1152 warning("getty repeating too quickly on port %s, sleeping %d secs",
1153 sp->se_device, GETTY_SLEEP);
1154 sleep((unsigned) GETTY_SLEEP);
1157 if (sp->se_window) {
1158 start_window_system(sp);
1163 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1166 setprocresources(RESOURCE_GETTY);
1169 /* Don't use malloc after fork */
1170 strcpy(term, "TERM=");
1171 strncat(term, sp->se_type, sizeof(term) - 6);
1177 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1178 stall("can't exec getty '%s' for port %s: %m",
1179 sp->se_getty_argv[0], sp->se_device);
1184 * Collect exit status for a child.
1185 * If an exiting login, start a new login running.
1189 collect_child(pid_t pid)
1195 register session_t *sp, *sprev, *snext;
1200 if (! (sp = find_session(pid)))
1203 clear_session_logs(sp);
1207 if (sp->se_flags & SE_SHUTDOWN) {
1208 if ((sprev = sp->se_prev) != NULL)
1209 sprev->se_next = sp->se_next;
1211 sessions = sp->se_next;
1212 if ((snext = sp->se_next) != NULL)
1213 snext->se_prev = sp->se_prev;
1218 if ((pid = start_getty(sp)) == -1) {
1219 /* serious trouble */
1220 requested_transition = clean_ttys;
1224 sp->se_process = pid;
1225 sp->se_started = time((time_t *) 0);
1230 * Catch a signal and request a state transition.
1233 transition_handler(sig)
1239 requested_transition = clean_ttys;
1244 requested_transition = death;
1247 requested_transition = catatonia;
1250 requested_transition = 0;
1256 * Take the system multiuser.
1262 register session_t *sp;
1264 requested_transition = 0;
1267 * If the administrator has not set the security level to -1
1268 * to indicate that the kernel should not run multiuser in secure
1269 * mode, and the run script has not set a higher level of security
1270 * than level 1, then put the kernel into secure mode.
1272 if (getsecuritylevel() == 0)
1273 setsecuritylevel(1);
1275 for (sp = sessions; sp; sp = sp->se_next) {
1278 if ((pid = start_getty(sp)) == -1) {
1279 /* serious trouble */
1280 requested_transition = clean_ttys;
1283 sp->se_process = pid;
1284 sp->se_started = time((time_t *) 0);
1288 while (!requested_transition)
1289 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1292 return (state_func_t) requested_transition;
1296 * This is an n-squared algorithm. We hope it isn't run often...
1301 register session_t *sp, *sprev;
1302 register struct ttyent *typ;
1303 register int session_index = 0;
1304 register int devlen;
1305 char *old_getty, *old_window, *old_type;
1308 return (state_func_t) multi_user;
1310 devlen = sizeof(_PATH_DEV) - 1;
1311 while ((typ = getttyent()) != NULL) {
1314 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1315 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1319 if (sp->se_index != session_index) {
1320 warning("port %s changed utmp index from %d to %d",
1321 sp->se_device, sp->se_index,
1323 sp->se_index = session_index;
1325 if ((typ->ty_status & TTY_ON) == 0 ||
1326 typ->ty_getty == 0) {
1327 sp->se_flags |= SE_SHUTDOWN;
1328 kill(sp->se_process, SIGHUP);
1331 sp->se_flags &= ~SE_SHUTDOWN;
1332 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1333 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1334 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1335 if (setupargv(sp, typ) == 0) {
1336 warning("can't parse getty for port %s",
1338 sp->se_flags |= SE_SHUTDOWN;
1339 kill(sp->se_process, SIGHUP);
1341 else if ( !old_getty
1342 || (!old_type && sp->se_type)
1343 || (old_type && !sp->se_type)
1344 || (!old_window && sp->se_window)
1345 || (old_window && !sp->se_window)
1346 || (strcmp(old_getty, sp->se_getty) != 0)
1347 || (old_window && strcmp(old_window, sp->se_window) != 0)
1348 || (old_type && strcmp(old_type, sp->se_type) != 0)
1350 /* Don't set SE_SHUTDOWN here */
1353 kill(sp->se_process, SIGHUP);
1364 new_session(sprev, session_index, typ);
1369 return (state_func_t) multi_user;
1373 * Block further logins.
1378 register session_t *sp;
1380 for (sp = sessions; sp; sp = sp->se_next)
1381 sp->se_flags |= SE_SHUTDOWN;
1383 return (state_func_t) multi_user;
1398 * Bring the system down to single user.
1403 register session_t *sp;
1406 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1408 /* NB: should send a message to the session logger to avoid blocking. */
1409 logwtmp("~", "shutdown", "");
1411 for (sp = sessions; sp; sp = sp->se_next) {
1412 sp->se_flags |= SE_SHUTDOWN;
1413 kill(sp->se_process, SIGHUP);
1416 /* Try to run the rc.shutdown script within a period of time */
1417 (void) runshutdown();
1419 for (i = 0; i < 2; ++i) {
1420 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1421 return (state_func_t) single_user;
1426 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1428 while (clang == 0 && errno != ECHILD);
1430 if (errno == ECHILD)
1431 return (state_func_t) single_user;
1434 warning("some processes would not die; ps axl advised");
1436 return (state_func_t) single_user;
1440 * Run the system shutdown script.
1442 * Exit codes: XXX I should document more
1443 * -2 shutdown script terminated abnormally
1444 * -1 fatal error - can't run script
1446 * >0 some error (exit code)
1453 int shutdowntimeout;
1456 struct sigaction sa;
1460 * rc.shutdown is optional, so to prevent any unnecessary
1461 * complaints from the shell we simply don't run it if the
1462 * file does not exist. If the stat() here fails for other
1463 * reasons, we'll let the shell complain.
1465 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1468 if ((pid = fork()) == 0) {
1471 /* Assume that init already grab console as ctty before */
1473 sigemptyset(&sa.sa_mask);
1475 sa.sa_handler = SIG_IGN;
1476 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1477 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1479 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1480 warning("can't open %s: %m", _PATH_CONSOLE);
1490 * Run the shutdown script.
1493 argv[1] = _PATH_RUNDOWN;
1496 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1499 setprocresources(RESOURCE_RC);
1501 execv(_PATH_BSHELL, argv);
1502 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1503 _exit(1); /* force single user mode */
1507 emergency("can't fork for %s on %s: %m",
1508 _PATH_BSHELL, _PATH_RUNDOWN);
1509 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1511 sleep(STALL_TIMEOUT);
1515 len = sizeof(shutdowntimeout);
1516 if (sysctlbyname("kern.shutdown_timeout",
1518 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1519 shutdowntimeout = DEATH_SCRIPT;
1520 alarm(shutdowntimeout);
1523 * Copied from single_user(). This is a bit paranoid.
1524 * Use the same ALRM handler.
1527 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1528 collect_child(wpid);
1530 /* we were waiting for the sub-shell */
1531 kill(wpid, SIGTERM);
1532 warning("timeout expired for %s on %s: %m; going to single used mode",
1533 _PATH_BSHELL, _PATH_RUNDOWN);
1539 warning("wait for %s on %s failed: %m; going to single user mode",
1540 _PATH_BSHELL, _PATH_RUNDOWN);
1543 if (wpid == pid && WIFSTOPPED(status)) {
1544 warning("init: %s on %s stopped, restarting\n",
1545 _PATH_BSHELL, _PATH_RUNDOWN);
1549 } while (wpid != pid && !clang);
1551 /* Turn off the alarm */
1554 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1555 requested_transition == catatonia) {
1557 * /etc/rc.shutdown executed /sbin/reboot;
1558 * wait for the end quietly
1567 if (!WIFEXITED(status)) {
1568 warning("%s on %s terminated abnormally, going to single user mode",
1569 _PATH_BSHELL, _PATH_RUNDOWN);
1573 if ((status = WEXITSTATUS(status)) != 0)
1574 warning("%s returned status %d", _PATH_RUNDOWN, status);
1592 while (c == ' ' || c == '\t' )
1602 while (c && c != '\'')
1604 if (!c) /* unterminated string */
1609 while (c && c != ' ' && c != '\t' )
1620 setprocresources(cname)
1624 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1625 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);