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 * @(#) Copyright (c) 1991, 1993 The Regents of the University of California. All rights reserved.
37 * @(#)init.c 8.1 (Berkeley) 7/15/93
38 * $FreeBSD: src/sbin/init/init.c,v 1.38.2.8 2001/10/22 11:27:32 des Exp $
39 * $DragonFly: src/sbin/init/init.c,v 1.3 2003/09/28 14:39:18 hmp Exp $
42 #include <sys/param.h>
43 #include <sys/ioctl.h>
44 #include <sys/mount.h>
45 #include <sys/sysctl.h>
62 #include <sys/reboot.h>
76 #include <login_cap.h>
79 #include "pathnames.h"
82 * Sleep times; used to prevent thrashing.
84 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
85 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
86 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
87 #define WINDOW_WAIT 3 /* wait N secs after starting window */
88 #define STALL_TIMEOUT 30 /* wait N secs after warning */
89 #define DEATH_WATCH 10 /* wait N secs for procs to die */
90 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
91 #define RESOURCE_RC "daemon"
92 #define RESOURCE_WINDOW "default"
93 #define RESOURCE_GETTY "default"
95 void handle __P((sig_t, ...));
96 void delset __P((sigset_t *, ...));
98 void stall __P((char *, ...));
99 void warning __P((char *, ...));
100 void emergency __P((char *, ...));
101 void disaster __P((int));
102 void badsys __P((int));
103 int runshutdown __P((void));
106 * We really need a recursive typedef...
107 * The following at least guarantees that the return type of (*state_t)()
108 * is sufficiently wide to hold a function pointer.
110 typedef long (*state_func_t) __P((void));
111 typedef state_func_t (*state_t) __P((void));
113 state_func_t single_user __P((void));
114 state_func_t runcom __P((void));
115 state_func_t read_ttys __P((void));
116 state_func_t multi_user __P((void));
117 state_func_t clean_ttys __P((void));
118 state_func_t catatonia __P((void));
119 state_func_t death __P((void));
121 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
126 int howto = RB_AUTOBOOT;
128 void transition __P((state_t));
129 state_t requested_transition = runcom;
131 void setctty __P((char *));
133 typedef struct init_session {
134 int se_index; /* index of entry in ttys file */
135 pid_t se_process; /* controlling process */
136 time_t se_started; /* used to avoid thrashing */
137 int se_flags; /* status of session */
138 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
139 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
140 int se_nspace; /* spacing count */
141 char *se_device; /* filename of port */
142 char *se_getty; /* what to run on that port */
143 char *se_getty_argv_space; /* pre-parsed argument array space */
144 char **se_getty_argv; /* pre-parsed argument array */
145 char *se_window; /* window system (started only once) */
146 char *se_window_argv_space; /* pre-parsed argument array space */
147 char **se_window_argv; /* pre-parsed argument array */
148 char *se_type; /* default terminal type */
149 struct init_session *se_prev;
150 struct init_session *se_next;
153 void free_session __P((session_t *));
154 session_t *new_session __P((session_t *, int, struct ttyent *));
157 char **construct_argv __P((char *));
158 void start_window_system __P((session_t *));
159 void collect_child __P((pid_t));
160 pid_t start_getty __P((session_t *));
161 void transition_handler __P((int));
162 void alrm_handler __P((int));
163 void setsecuritylevel __P((int));
164 int getsecuritylevel __P((void));
165 int setupargv __P((session_t *, struct ttyent *));
167 void setprocresources __P((const char *));
171 void clear_session_logs __P((session_t *));
173 int start_session_db __P((void));
174 void add_session __P((session_t *));
175 void del_session __P((session_t *));
176 session_t *find_session __P((pid_t));
180 * The mother of all processes.
183 main(int argc, char **argv)
190 /* Dispose of random users. */
192 errx(1, "%s", strerror(EPERM));
194 /* System V users like to reexec init. */
196 #ifdef COMPAT_SYSV_INIT
197 /* So give them what they want */
199 if (strlen(argv[1]) == 1) {
200 register char runlevel = *argv[1];
204 case '0': /* halt + poweroff */
207 case '1': /* single-user */
210 case '6': /* reboot */
213 case 'c': /* block further logins */
216 case 'q': /* rescan /etc/ttys */
226 errx(1, "invalid run-level ``%s''", argv[1]);
229 errx(1, "already running");
232 * Note that this does NOT open a file...
233 * Does 'init' deserve its own facility number?
235 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
238 * Create an initial session.
241 warning("initial setsid() failed: %m");
244 * Establish an initial user so that programs running
245 * single user do not freak out and die (like passwd).
247 if (setlogin("root") < 0)
248 warning("setlogin() failed: %m");
251 * This code assumes that we always get arguments through flags,
252 * never through bits set in some random machine register.
254 while ((c = getopt(argc, argv, "dsf")) != -1)
257 /* We don't support DEVFS. */
260 requested_transition = single_user;
263 runcom_mode = FASTBOOT;
266 warning("unrecognized flag '-%c'", c);
271 warning("ignoring excess arguments");
274 * We catch or block signals rather than ignore them,
275 * so that they get reset on exec.
277 handle(badsys, SIGSYS, 0);
278 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
279 SIGBUS, SIGXCPU, SIGXFSZ, 0);
280 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
281 SIGUSR1, SIGUSR2, 0);
282 handle(alrm_handler, SIGALRM, 0);
284 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
285 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
286 SIGUSR1, SIGUSR2, 0);
287 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
288 sigemptyset(&sa.sa_mask);
290 sa.sa_handler = SIG_IGN;
291 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
292 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
302 * Start the state machine.
304 transition(requested_transition);
307 * Should never reach here.
313 * Associate a function with a signal handler.
316 handle(sig_t handler, ...)
320 sigset_t mask_everything;
323 va_start(ap, handler);
325 sa.sa_handler = handler;
326 sigfillset(&mask_everything);
328 while ((sig = va_arg(ap, int)) != NULL) {
329 sa.sa_mask = mask_everything;
330 /* XXX SA_RESTART? */
331 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
332 sigaction(sig, &sa, (struct sigaction *) 0);
338 * Delete a set of signals from a mask.
341 delset(sigset_t *maskp, ...)
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.
359 stall(char *message, ...)
363 va_start(ap, message);
365 vsyslog(LOG_ALERT, message, ap);
367 sleep(STALL_TIMEOUT);
371 * Like stall(), but doesn't sleep.
372 * If cpp had variadic macros, the two functions could be #defines for another.
373 * NB: should send a message to the session logger to avoid blocking.
376 warning(char *message, ...)
380 va_start(ap, message);
382 vsyslog(LOG_ALERT, message, ap);
387 * Log an emergency message.
388 * NB: should send a message to the session logger to avoid blocking.
391 emergency(char *message, ...)
395 va_start(ap, message);
397 vsyslog(LOG_EMERG, message, ap);
402 * Catch a SIGSYS signal.
404 * These may arise if a system does not support sysctl.
405 * We tolerate up to 25 of these, then throw in the towel.
410 static int badcount = 0;
418 * Catch an unexpected signal.
423 emergency("fatal signal: %s",
424 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
426 sleep(STALL_TIMEOUT);
427 _exit(sig); /* reboot */
431 * Get the security level of the kernel.
434 getsecuritylevel(void)
436 #ifdef KERN_SECURELVL
437 int name[2], curlevel;
441 name[1] = KERN_SECURELVL;
442 len = sizeof curlevel;
443 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
444 emergency("cannot get kernel security level: %s",
455 * Set the security level of the kernel.
458 setsecuritylevel(int newlevel)
460 #ifdef KERN_SECURELVL
461 int name[2], curlevel;
463 curlevel = getsecuritylevel();
464 if (newlevel == curlevel)
467 name[1] = KERN_SECURELVL;
468 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
470 "cannot change kernel security level from %d to %d: %s",
471 curlevel, newlevel, strerror(errno));
475 warning("kernel security level changed from %d to %d",
482 * Change states in the finite state machine.
483 * The initial state is passed as an argument.
486 transition(state_t s)
489 s = (state_t) (*s)();
493 * Close out the accounting files for a login session.
494 * NB: should send a message to the session logger to avoid blocking.
497 clear_session_logs(session_t *sp)
499 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
502 logwtmp(line, "", "");
506 * Start a session and allocate a controlling terminal.
507 * Only called by children of init after forking.
515 if ((fd = open(name, O_RDWR)) == -1) {
516 stall("can't open %s: %m", name);
519 if (login_tty(fd) == -1) {
520 stall("can't get %s for controlling terminal: %m", name);
526 * Bring the system up single user.
534 char *shell = _PATH_BSHELL;
539 static const char banner[] =
540 "Enter root password, or ^D to go multi-user\n";
541 char *clear, *password;
548 /* Instead of going single user, let's reboot the machine */
556 if ((pid = fork()) == 0) {
558 * Start the single user session.
560 setctty(_PATH_CONSOLE);
564 * Check the root password.
565 * We don't care if the console is 'on' by default;
566 * it's the only tty that can be 'off' and 'secure'.
568 typ = getttynam("console");
569 pp = getpwnam("root");
570 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
571 pp && *pp->pw_passwd) {
572 write(2, banner, sizeof banner - 1);
574 clear = getpass("Password:");
575 if (clear == 0 || *clear == '\0')
577 password = crypt(clear, pp->pw_passwd);
578 bzero(clear, _PASSWORD_LEN);
579 if (strcmp(password, pp->pw_passwd) == 0)
581 warning("single-user login failed\n");
594 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
595 (void)write(STDERR_FILENO,
596 SHREQUEST, sizeof(SHREQUEST) - 1);
597 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
598 num != 0 && *cp != '\n' && cp < &altshell[127])
601 if (altshell[0] != '\0')
604 #endif /* DEBUGSHELL */
608 * We catch all the interesting ones,
609 * and those are reset to SIG_DFL on exec.
612 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
616 * If the default one doesn't work, try the Bourne shell.
621 emergency("can't exec %s for single user: %m", shell);
622 execv(_PATH_BSHELL, argv);
623 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
624 sleep(STALL_TIMEOUT);
630 * We are seriously hosed. Do our best.
632 emergency("can't fork single-user shell, trying again");
633 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
635 return (state_func_t) single_user;
638 requested_transition = 0;
640 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
645 warning("wait for single-user shell failed: %m; restarting");
646 return (state_func_t) single_user;
648 if (wpid == pid && WIFSTOPPED(status)) {
649 warning("init: shell stopped, restarting\n");
653 } while (wpid != pid && !requested_transition);
655 if (requested_transition)
656 return (state_func_t) requested_transition;
658 if (!WIFEXITED(status)) {
659 if (WTERMSIG(status) == SIGKILL) {
661 * reboot(8) killed shell?
663 warning("single user shell terminated.");
664 sleep(STALL_TIMEOUT);
667 warning("single user shell terminated, restarting");
668 return (state_func_t) single_user;
672 runcom_mode = FASTBOOT;
673 return (state_func_t) runcom;
677 * Run the system startup script.
687 if ((pid = fork()) == 0) {
688 sigemptyset(&sa.sa_mask);
690 sa.sa_handler = SIG_IGN;
691 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
692 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
694 setctty(_PATH_CONSOLE);
697 argv[1] = _PATH_RUNCOM;
698 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
701 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
704 setprocresources(RESOURCE_RC);
706 execv(_PATH_BSHELL, argv);
707 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
708 _exit(1); /* force single user mode */
712 emergency("can't fork for %s on %s: %m",
713 _PATH_BSHELL, _PATH_RUNCOM);
714 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
716 sleep(STALL_TIMEOUT);
717 return (state_func_t) single_user;
721 * Copied from single_user(). This is a bit paranoid.
723 requested_transition = 0;
725 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
728 if (requested_transition == death)
729 return (state_func_t) death;
732 warning("wait for %s on %s failed: %m; going to single user mode",
733 _PATH_BSHELL, _PATH_RUNCOM);
734 return (state_func_t) single_user;
736 if (wpid == pid && WIFSTOPPED(status)) {
737 warning("init: %s on %s stopped, restarting\n",
738 _PATH_BSHELL, _PATH_RUNCOM);
742 } while (wpid != pid);
744 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
745 requested_transition == catatonia) {
746 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
754 if (!WIFEXITED(status)) {
755 warning("%s on %s terminated abnormally, going to single user mode",
756 _PATH_BSHELL, _PATH_RUNCOM);
757 return (state_func_t) single_user;
760 if (WEXITSTATUS(status))
761 return (state_func_t) single_user;
763 runcom_mode = AUTOBOOT; /* the default */
764 /* NB: should send a message to the session logger to avoid blocking. */
765 logwtmp("~", "reboot", "");
766 return (state_func_t) read_ttys;
770 * Open the session database.
772 * NB: We could pass in the size here; is it necessary?
775 start_session_db(void)
777 if (session_db && (*session_db->close)(session_db))
778 emergency("session database close: %s", strerror(errno));
779 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
780 emergency("session database open: %s", strerror(errno));
788 * Add a new login session.
791 add_session(session_t *sp)
796 key.data = &sp->se_process;
797 key.size = sizeof sp->se_process;
799 data.size = sizeof sp;
801 if ((*session_db->put)(session_db, &key, &data, 0))
802 emergency("insert %d: %s", sp->se_process, strerror(errno));
806 * Delete an old login session.
809 del_session(session_t *sp)
813 key.data = &sp->se_process;
814 key.size = sizeof sp->se_process;
816 if ((*session_db->del)(session_db, &key, 0))
817 emergency("delete %d: %s", sp->se_process, strerror(errno));
821 * Look up a login session by pid.
824 find_session(pid_t pid)
831 key.size = sizeof pid;
832 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
834 bcopy(data.data, (char *)&ret, sizeof(ret));
839 * Construct an argument vector from a command line.
842 construct_argv(char *command)
845 register int argc = 0;
846 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
849 if ((argv[argc++] = strk(command)) == 0) {
853 while ((argv[argc++] = strk((char *) 0)) != NULL)
859 * Deallocate a session descriptor.
862 free_session(register session_t *sp)
867 free(sp->se_getty_argv_space);
868 free(sp->se_getty_argv);
872 free(sp->se_window_argv_space);
873 free(sp->se_window_argv);
881 * Allocate a new session descriptor.
882 * Mark it SE_PRESENT.
885 new_session(session_t *sprev, int session_index, register struct ttyent *typ)
887 register session_t *sp;
890 if ((typ->ty_status & TTY_ON) == 0 ||
895 sp = (session_t *) calloc(1, sizeof (session_t));
897 sp->se_index = session_index;
898 sp->se_flags |= SE_PRESENT;
900 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
901 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
904 * Attempt to open the device, if we get "device not configured"
905 * then don't add the device to the session list.
907 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
908 if (errno == ENXIO) {
915 if (setupargv(sp, typ) == 0) {
933 * Calculate getty and if useful window argv vectors.
936 setupargv(session_t *sp, struct ttyent *typ)
941 free(sp->se_getty_argv_space);
942 free(sp->se_getty_argv);
944 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
945 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
946 sp->se_getty_argv_space = strdup(sp->se_getty);
947 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
948 if (sp->se_getty_argv == 0) {
949 warning("can't parse getty for port %s", sp->se_device);
951 free(sp->se_getty_argv_space);
952 sp->se_getty = sp->se_getty_argv_space = 0;
957 free(sp->se_window_argv_space);
958 free(sp->se_window_argv);
960 sp->se_window = sp->se_window_argv_space = 0;
961 sp->se_window_argv = 0;
962 if (typ->ty_window) {
963 sp->se_window = strdup(typ->ty_window);
964 sp->se_window_argv_space = strdup(sp->se_window);
965 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
966 if (sp->se_window_argv == 0) {
967 warning("can't parse window for port %s",
969 free(sp->se_window_argv_space);
971 sp->se_window = sp->se_window_argv_space = 0;
977 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
982 * Walk the list of ttys and create sessions for each active line.
987 int session_index = 0;
988 register session_t *sp, *snext;
989 register struct ttyent *typ;
992 * Destroy any previous session state.
993 * There shouldn't be any, but just in case...
995 for (sp = sessions; sp; sp = snext) {
997 clear_session_logs(sp);
1002 if (start_session_db())
1003 return (state_func_t) single_user;
1006 * Allocate a session entry for each active port.
1007 * Note that sp starts at 0.
1009 while ((typ = getttyent()) != NULL)
1010 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1015 return (state_func_t) multi_user;
1019 * Start a window system running.
1022 start_window_system(session_t *sp)
1026 char term[64], *env[2];
1028 if ((pid = fork()) == -1) {
1029 emergency("can't fork for window system on port %s: %m",
1031 /* hope that getty fails and we can try again */
1039 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1042 emergency("setsid failed (window) %m");
1045 setprocresources(RESOURCE_WINDOW);
1048 /* Don't use malloc after fork */
1049 strcpy(term, "TERM=");
1050 strncat(term, sp->se_type, sizeof(term) - 6);
1056 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1057 stall("can't exec window system '%s' for port %s: %m",
1058 sp->se_window_argv[0], sp->se_device);
1063 * Start a login session running.
1066 start_getty(session_t *sp)
1070 time_t current_time = time((time_t *) 0);
1072 char term[64], *env[2];
1074 if (current_time >= sp->se_started &&
1075 current_time - sp->se_started < GETTY_SPACING) {
1076 if (++sp->se_nspace > GETTY_NSPACE) {
1084 * fork(), not vfork() -- we can't afford to block.
1086 if ((pid = fork()) == -1) {
1087 emergency("can't fork for getty on port %s: %m", sp->se_device);
1095 warning("getty repeating too quickly on port %s, sleeping %d secs",
1096 sp->se_device, GETTY_SLEEP);
1097 sleep((unsigned) GETTY_SLEEP);
1100 if (sp->se_window) {
1101 start_window_system(sp);
1106 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1109 setprocresources(RESOURCE_GETTY);
1112 /* Don't use malloc after fork */
1113 strcpy(term, "TERM=");
1114 strncat(term, sp->se_type, sizeof(term) - 6);
1120 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1121 stall("can't exec getty '%s' for port %s: %m",
1122 sp->se_getty_argv[0], sp->se_device);
1127 * Collect exit status for a child.
1128 * If an exiting login, start a new login running.
1131 collect_child(pid_t pid)
1133 register session_t *sp, *sprev, *snext;
1138 if (! (sp = find_session(pid)))
1141 clear_session_logs(sp);
1145 if (sp->se_flags & SE_SHUTDOWN) {
1146 if ((sprev = sp->se_prev) != NULL)
1147 sprev->se_next = sp->se_next;
1149 sessions = sp->se_next;
1150 if ((snext = sp->se_next) != NULL)
1151 snext->se_prev = sp->se_prev;
1156 if ((pid = start_getty(sp)) == -1) {
1157 /* serious trouble */
1158 requested_transition = clean_ttys;
1162 sp->se_process = pid;
1163 sp->se_started = time((time_t *) 0);
1168 * Catch a signal and request a state transition.
1171 transition_handler(int sig)
1176 requested_transition = clean_ttys;
1179 howto = RB_POWEROFF;
1185 requested_transition = death;
1188 requested_transition = catatonia;
1191 requested_transition = 0;
1197 * Take the system multiuser.
1203 register session_t *sp;
1205 requested_transition = 0;
1208 * If the administrator has not set the security level to -1
1209 * to indicate that the kernel should not run multiuser in secure
1210 * mode, and the run script has not set a higher level of security
1211 * than level 1, then put the kernel into secure mode.
1213 if (getsecuritylevel() == 0)
1214 setsecuritylevel(1);
1216 for (sp = sessions; sp; sp = sp->se_next) {
1219 if ((pid = start_getty(sp)) == -1) {
1220 /* serious trouble */
1221 requested_transition = clean_ttys;
1224 sp->se_process = pid;
1225 sp->se_started = time((time_t *) 0);
1229 while (!requested_transition)
1230 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1233 return (state_func_t) requested_transition;
1237 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1242 register session_t *sp, *sprev;
1243 register struct ttyent *typ;
1244 register int session_index = 0;
1245 register int devlen;
1246 char *old_getty, *old_window, *old_type;
1249 return (state_func_t) multi_user;
1252 * mark all sessions for death, (!SE_PRESENT)
1253 * as we find or create new ones they'll be marked as keepers,
1254 * we'll later nuke all the ones not found in /etc/ttys
1256 for (sp = sessions; sp != NULL; sp = sp->se_next)
1257 sp->se_flags &= ~SE_PRESENT;
1259 devlen = sizeof(_PATH_DEV) - 1;
1260 while ((typ = getttyent()) != NULL) {
1263 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1264 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1268 /* we want this one to live */
1269 sp->se_flags |= SE_PRESENT;
1270 if (sp->se_index != session_index) {
1271 warning("port %s changed utmp index from %d to %d",
1272 sp->se_device, sp->se_index,
1274 sp->se_index = session_index;
1276 if ((typ->ty_status & TTY_ON) == 0 ||
1277 typ->ty_getty == 0) {
1278 sp->se_flags |= SE_SHUTDOWN;
1279 kill(sp->se_process, SIGHUP);
1282 sp->se_flags &= ~SE_SHUTDOWN;
1283 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1284 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1285 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1286 if (setupargv(sp, typ) == 0) {
1287 warning("can't parse getty for port %s",
1289 sp->se_flags |= SE_SHUTDOWN;
1290 kill(sp->se_process, SIGHUP);
1292 else if ( !old_getty
1293 || (!old_type && sp->se_type)
1294 || (old_type && !sp->se_type)
1295 || (!old_window && sp->se_window)
1296 || (old_window && !sp->se_window)
1297 || (strcmp(old_getty, sp->se_getty) != 0)
1298 || (old_window && strcmp(old_window, sp->se_window) != 0)
1299 || (old_type && strcmp(old_type, sp->se_type) != 0)
1301 /* Don't set SE_SHUTDOWN here */
1304 kill(sp->se_process, SIGHUP);
1315 new_session(sprev, session_index, typ);
1321 * sweep through and kill all deleted sessions
1322 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1324 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1325 if ((sp->se_flags & SE_PRESENT) == 0) {
1326 sp->se_flags |= SE_SHUTDOWN;
1327 kill(sp->se_process, SIGHUP);
1331 return (state_func_t) multi_user;
1335 * Block further logins.
1340 register session_t *sp;
1342 for (sp = sessions; sp; sp = sp->se_next)
1343 sp->se_flags |= SE_SHUTDOWN;
1345 return (state_func_t) multi_user;
1352 alrm_handler(int sig)
1359 * Bring the system down to single user.
1364 register session_t *sp;
1367 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1369 /* NB: should send a message to the session logger to avoid blocking. */
1370 logwtmp("~", "shutdown", "");
1372 for (sp = sessions; sp; sp = sp->se_next) {
1373 sp->se_flags |= SE_SHUTDOWN;
1374 kill(sp->se_process, SIGHUP);
1377 /* Try to run the rc.shutdown script within a period of time */
1378 (void) runshutdown();
1380 for (i = 0; i < 2; ++i) {
1381 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1382 return (state_func_t) single_user;
1387 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1389 while (clang == 0 && errno != ECHILD);
1391 if (errno == ECHILD)
1392 return (state_func_t) single_user;
1395 warning("some processes would not die; ps axl advised");
1397 return (state_func_t) single_user;
1401 * Run the system shutdown script.
1403 * Exit codes: XXX I should document more
1404 * -2 shutdown script terminated abnormally
1405 * -1 fatal error - can't run script
1407 * >0 some error (exit code)
1414 int shutdowntimeout;
1417 struct sigaction sa;
1421 * rc.shutdown is optional, so to prevent any unnecessary
1422 * complaints from the shell we simply don't run it if the
1423 * file does not exist. If the stat() here fails for other
1424 * reasons, we'll let the shell complain.
1426 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1429 if ((pid = fork()) == 0) {
1432 /* Assume that init already grab console as ctty before */
1434 sigemptyset(&sa.sa_mask);
1436 sa.sa_handler = SIG_IGN;
1437 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1438 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1440 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1441 warning("can't open %s: %m", _PATH_CONSOLE);
1451 * Run the shutdown script.
1454 argv[1] = _PATH_RUNDOWN;
1461 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1464 setprocresources(RESOURCE_RC);
1466 execv(_PATH_BSHELL, argv);
1467 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1468 _exit(1); /* force single user mode */
1472 emergency("can't fork for %s on %s: %m",
1473 _PATH_BSHELL, _PATH_RUNDOWN);
1474 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1476 sleep(STALL_TIMEOUT);
1480 len = sizeof(shutdowntimeout);
1481 if (sysctlbyname("kern.shutdown_timeout",
1483 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1484 shutdowntimeout = DEATH_SCRIPT;
1485 alarm(shutdowntimeout);
1488 * Copied from single_user(). This is a bit paranoid.
1489 * Use the same ALRM handler.
1492 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1493 collect_child(wpid);
1495 /* we were waiting for the sub-shell */
1496 kill(wpid, SIGTERM);
1497 warning("timeout expired for %s on %s: %m; going to single user mode",
1498 _PATH_BSHELL, _PATH_RUNDOWN);
1504 warning("wait for %s on %s failed: %m; going to single user mode",
1505 _PATH_BSHELL, _PATH_RUNDOWN);
1508 if (wpid == pid && WIFSTOPPED(status)) {
1509 warning("init: %s on %s stopped, restarting\n",
1510 _PATH_BSHELL, _PATH_RUNDOWN);
1514 } while (wpid != pid && !clang);
1516 /* Turn off the alarm */
1519 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1520 requested_transition == catatonia) {
1522 * /etc/rc.shutdown executed /sbin/reboot;
1523 * wait for the end quietly
1532 if (!WIFEXITED(status)) {
1533 warning("%s on %s terminated abnormally, going to single user mode",
1534 _PATH_BSHELL, _PATH_RUNDOWN);
1538 if ((status = WEXITSTATUS(status)) != 0)
1539 warning("%s returned status %d", _PATH_RUNDOWN, status);
1557 while (c == ' ' || c == '\t' )
1567 while (c && c != '\'')
1569 if (!c) /* unterminated string */
1574 while (c && c != ' ' && c != '\t' )
1585 setprocresources(const char *cname)
1588 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1589 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);