2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 4. Neither the name of the University nor the names of its contributors
17 * may be used to endorse or promote products derived from this software
18 * without specific prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36 The Regents of the University of California. All rights reserved.\n";
41 static char sccsid[] = "@(#)init.c 8.1 (Berkeley) 7/15/93";
43 static const char rcsid[] =
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/mount.h>
50 #include <sys/sysctl.h>
68 #include <sys/reboot.h>
78 #include <login_cap.h>
81 #include "pathnames.h"
84 * Sleep times; used to prevent thrashing.
86 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
87 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
88 #define GETTY_NSPACE 3 /* max. spacing count to bring reaction */
89 #define WINDOW_WAIT 3 /* wait N secs after starting window */
90 #define STALL_TIMEOUT 30 /* wait N secs after warning */
91 #define DEATH_WATCH 10 /* wait N secs for procs to die */
92 #define DEATH_SCRIPT 120 /* wait for 2min for /etc/rc.shutdown */
93 #define RESOURCE_RC "daemon"
94 #define RESOURCE_WINDOW "default"
95 #define RESOURCE_GETTY "default"
97 void handle(sig_t, ...);
98 void delset(sigset_t *, ...);
100 void stall(const char *, ...) __printflike(1, 2);
101 void warning(const char *, ...) __printflike(1, 2);
102 void emergency(const char *, ...) __printflike(1, 2);
105 int runshutdown(void);
106 static char *strk(char *);
109 * We really need a recursive typedef...
110 * The following at least guarantees that the return type of (*state_t)()
111 * is sufficiently wide to hold a function pointer.
113 typedef long (*state_func_t)(void);
114 typedef state_func_t (*state_t)(void);
116 state_func_t single_user(void);
117 state_func_t runcom(void);
118 state_func_t read_ttys(void);
119 state_func_t multi_user(void);
120 state_func_t clean_ttys(void);
121 state_func_t catatonia(void);
122 state_func_t death(void);
124 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
129 int howto = RB_AUTOBOOT;
133 void transition(state_t);
134 state_t requested_transition = runcom;
136 void setctty(const char *);
138 typedef struct init_session {
139 int se_index; /* index of entry in ttys file */
140 pid_t se_process; /* controlling process */
141 time_t se_started; /* used to avoid thrashing */
142 int se_flags; /* status of session */
143 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
144 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
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(session_t *);
159 session_t *new_session(session_t *, int, struct ttyent *);
162 char **construct_argv(char *);
163 void start_window_system(session_t *);
164 void collect_child(pid_t);
165 pid_t start_getty(session_t *);
166 void transition_handler(int);
167 void alrm_handler(int);
168 void setsecuritylevel(int);
169 int getsecuritylevel(void);
170 int setupargv(session_t *, struct ttyent *);
172 void setprocresources(const char *);
176 void clear_session_logs(session_t *);
178 int start_session_db(void);
179 void add_session(session_t *);
180 void del_session(session_t *);
181 session_t *find_session(pid_t);
185 * The mother of all processes.
188 main(int argc, char *argv[])
195 /* Dispose of random users. */
197 errx(1, "%s", strerror(EPERM));
199 /* System V users like to reexec init. */
201 #ifdef COMPAT_SYSV_INIT
202 /* So give them what they want */
204 if (strlen(argv[1]) == 1) {
205 char runlevel = *argv[1];
209 case '0': /* halt + poweroff */
212 case '1': /* single-user */
215 case '6': /* reboot */
218 case 'c': /* block further logins */
221 case 'q': /* rescan /etc/ttys */
231 errx(1, "invalid run-level ``%s''", argv[1]);
234 errx(1, "already running");
237 * Note that this does NOT open a file...
238 * Does 'init' deserve its own facility number?
240 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
243 * Create an initial session.
246 warning("initial setsid() failed: %m");
249 * Establish an initial user so that programs running
250 * single user do not freak out and die (like passwd).
252 if (setlogin("root") < 0)
253 warning("setlogin() failed: %m");
256 * This code assumes that we always get arguments through flags,
257 * never through bits set in some random machine register.
259 while ((c = getopt(argc, argv, "dsf")) != -1)
265 requested_transition = single_user;
268 runcom_mode = FASTBOOT;
271 warning("unrecognized flag '-%c'", c);
276 warning("ignoring excess arguments");
283 char _fstype[] = "fstype";
284 char _devfs[] = "devfs";
285 char _fspath[] = "fspath";
286 char _path_dev[]= _PATH_DEV;
288 iov[0].iov_base = _fstype;
289 iov[0].iov_len = sizeof(_fstype);
290 iov[1].iov_base = _devfs;
291 iov[1].iov_len = sizeof(_devfs);
292 iov[2].iov_base = _fspath;
293 iov[2].iov_len = sizeof(_fspath);
295 * Try to avoid the trailing slash in _PATH_DEV.
296 * Be *very* defensive.
298 s = strdup(_PATH_DEV);
301 if (i > 0 && s[i - 1] == '/')
304 iov[3].iov_len = strlen(s) + 1;
306 iov[3].iov_base = _path_dev;
307 iov[3].iov_len = sizeof(_path_dev);
315 * We catch or block signals rather than ignore them,
316 * so that they get reset on exec.
318 handle(badsys, SIGSYS, 0);
319 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
320 SIGBUS, SIGXCPU, SIGXFSZ, 0);
321 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
322 SIGUSR1, SIGUSR2, 0);
323 handle(alrm_handler, SIGALRM, 0);
325 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
326 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
327 SIGUSR1, SIGUSR2, 0);
328 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
329 sigemptyset(&sa.sa_mask);
331 sa.sa_handler = SIG_IGN;
332 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
333 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
343 * Start the state machine.
345 transition(requested_transition);
348 * Should never reach here.
354 * Associate a function with a signal handler.
357 handle(sig_t handler, ...)
361 sigset_t mask_everything;
363 va_start(ap, handler);
365 sa.sa_handler = handler;
366 sigfillset(&mask_everything);
368 while ((sig = va_arg(ap, int)) != 0) {
369 sa.sa_mask = mask_everything;
370 /* XXX SA_RESTART? */
371 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
372 sigaction(sig, &sa, (struct sigaction *) 0);
378 * Delete a set of signals from a mask.
381 delset(sigset_t *maskp, ...)
387 while ((sig = va_arg(ap, int)) != 0)
388 sigdelset(maskp, sig);
393 * Log a message and sleep for a while (to give someone an opportunity
394 * to read it and to save log or hardcopy output if the problem is chronic).
395 * NB: should send a message to the session logger to avoid blocking.
398 stall(const char *message, ...)
401 va_start(ap, message);
403 vsyslog(LOG_ALERT, message, ap);
405 sleep(STALL_TIMEOUT);
409 * Like stall(), but doesn't sleep.
410 * If cpp had variadic macros, the two functions could be #defines for another.
411 * NB: should send a message to the session logger to avoid blocking.
414 warning(const char *message, ...)
417 va_start(ap, message);
419 vsyslog(LOG_ALERT, message, ap);
424 * Log an emergency message.
425 * NB: should send a message to the session logger to avoid blocking.
428 emergency(const char *message, ...)
431 va_start(ap, message);
433 vsyslog(LOG_EMERG, message, ap);
438 * Catch a SIGSYS signal.
440 * These may arise if a system does not support sysctl.
441 * We tolerate up to 25 of these, then throw in the towel.
446 static int badcount = 0;
454 * Catch an unexpected signal.
459 emergency("fatal signal: %s",
460 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
462 sleep(STALL_TIMEOUT);
463 _exit(sig); /* reboot */
467 * Get the security level of the kernel.
470 getsecuritylevel(void)
472 #ifdef KERN_SECURELVL
473 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(int newlevel)
496 #ifdef KERN_SECURELVL
497 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.
522 transition(state_t s)
525 s = (state_t) (*s)();
529 * Close out the accounting files for a login session.
530 * NB: should send a message to the session logger to avoid blocking.
533 clear_session_logs(session_t *sp)
535 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
538 logwtmp(line, "", "");
542 * Start a session and allocate a controlling terminal.
543 * Only called by children of init after forking.
546 setctty(const char *name)
551 if ((fd = open(name, O_RDWR)) == -1) {
552 stall("can't open %s: %m", name);
555 if (login_tty(fd) == -1) {
556 stall("can't get %s for controlling terminal: %m", name);
562 * Bring the system up single user.
570 const char *shell = _PATH_BSHELL;
575 static const char banner[] =
576 "Enter root password, or ^D to go multi-user\n";
577 char *clear, *password;
584 /* Instead of going single user, let's reboot the machine */
592 if ((pid = fork()) == 0) {
594 * Start the single user session.
596 setctty(_PATH_CONSOLE);
600 * Check the root password.
601 * We don't care if the console is 'on' by default;
602 * it's the only tty that can be 'off' and 'secure'.
604 typ = getttynam("console");
605 pp = getpwnam("root");
606 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
607 pp && *pp->pw_passwd) {
608 write(STDERR_FILENO, banner, sizeof banner - 1);
610 clear = getpass("Password:");
611 if (clear == 0 || *clear == '\0')
613 password = crypt(clear, pp->pw_passwd);
614 bzero(clear, _PASSWORD_LEN);
615 if (strcmp(password, pp->pw_passwd) == 0)
617 warning("single-user login failed\n");
630 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
631 (void)write(STDERR_FILENO,
632 SHREQUEST, sizeof(SHREQUEST) - 1);
633 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
634 num != 0 && *cp != '\n' && cp < &altshell[127])
637 if (altshell[0] != '\0')
640 #endif /* DEBUGSHELL */
644 * We catch all the interesting ones,
645 * and those are reset to SIG_DFL on exec.
648 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
652 * If the default one doesn't work, try the Bourne shell.
660 emergency("can't exec %s for single user: %m", shell);
661 execv(_PATH_BSHELL, argv);
662 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
663 sleep(STALL_TIMEOUT);
669 * We are seriously hosed. Do our best.
671 emergency("can't fork single-user shell, trying again");
672 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
674 return (state_func_t) single_user;
677 requested_transition = 0;
679 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
684 warning("wait for single-user shell failed: %m; restarting");
685 return (state_func_t) single_user;
687 if (wpid == pid && WIFSTOPPED(status)) {
688 warning("init: shell stopped, restarting\n");
692 } while (wpid != pid && !requested_transition);
694 if (requested_transition)
695 return (state_func_t) requested_transition;
697 if (!WIFEXITED(status)) {
698 if (WTERMSIG(status) == SIGKILL) {
700 * reboot(8) killed shell?
702 warning("single user shell terminated.");
703 sleep(STALL_TIMEOUT);
706 warning("single user shell terminated, restarting");
707 return (state_func_t) single_user;
711 runcom_mode = FASTBOOT;
712 return (state_func_t) runcom;
716 * Run the system startup script.
726 if ((pid = fork()) == 0) {
727 sigemptyset(&sa.sa_mask);
729 sa.sa_handler = SIG_IGN;
730 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
731 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
733 setctty(_PATH_CONSOLE);
736 char _path_runcom[] = _PATH_RUNCOM;
737 char _autoboot[] = "autoboot";
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.
766 requested_transition = 0;
768 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
771 if (requested_transition == death)
772 return (state_func_t) death;
775 warning("wait for %s on %s failed: %m; going to single user mode",
776 _PATH_BSHELL, _PATH_RUNCOM);
777 return (state_func_t) single_user;
779 if (wpid == pid && WIFSTOPPED(status)) {
780 warning("init: %s on %s stopped, restarting\n",
781 _PATH_BSHELL, _PATH_RUNCOM);
785 } while (wpid != pid);
787 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
788 requested_transition == catatonia) {
789 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
797 if (!WIFEXITED(status)) {
798 warning("%s on %s terminated abnormally, going to single user mode",
799 _PATH_BSHELL, _PATH_RUNCOM);
800 return (state_func_t) single_user;
803 if (WEXITSTATUS(status))
804 return (state_func_t) single_user;
806 runcom_mode = AUTOBOOT; /* the default */
807 /* NB: should send a message to the session logger to avoid blocking. */
808 logwtmp("~", "reboot", "");
809 return (state_func_t) read_ttys;
813 * Open the session database.
815 * NB: We could pass in the size here; is it necessary?
818 start_session_db(void)
820 if (session_db && (*session_db->close)(session_db))
821 emergency("session database close: %s", strerror(errno));
822 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
823 emergency("session database open: %s", strerror(errno));
831 * Add a new login session.
834 add_session(session_t *sp)
839 key.data = &sp->se_process;
840 key.size = sizeof sp->se_process;
842 data.size = sizeof sp;
844 if ((*session_db->put)(session_db, &key, &data, 0))
845 emergency("insert %d: %s", sp->se_process, strerror(errno));
849 * Delete an old login session.
852 del_session(session_t *sp)
856 key.data = &sp->se_process;
857 key.size = sizeof sp->se_process;
859 if ((*session_db->del)(session_db, &key, 0))
860 emergency("delete %d: %s", sp->se_process, strerror(errno));
864 * Look up a login session by pid.
867 find_session(pid_t pid)
874 key.size = sizeof pid;
875 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
877 bcopy(data.data, (char *)&ret, sizeof(ret));
882 * Construct an argument vector from a command line.
885 construct_argv(char *command)
888 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
891 if ((argv[argc++] = strk(command)) == 0) {
895 while ((argv[argc++] = strk((char *) 0)) != NULL)
901 * Deallocate a session descriptor.
904 free_session(session_t *sp)
909 free(sp->se_getty_argv_space);
910 free(sp->se_getty_argv);
914 free(sp->se_window_argv_space);
915 free(sp->se_window_argv);
923 * Allocate a new session descriptor.
924 * Mark it SE_PRESENT.
927 new_session(session_t *sprev, int session_index, struct ttyent *typ)
932 if ((typ->ty_status & TTY_ON) == 0 ||
937 sp = (session_t *) calloc(1, sizeof (session_t));
939 sp->se_index = session_index;
940 sp->se_flags |= SE_PRESENT;
942 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
943 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
946 * Attempt to open the device, if we get "device not configured"
947 * then don't add the device to the session list.
949 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
950 if (errno == ENXIO) {
957 if (setupargv(sp, typ) == 0) {
975 * Calculate getty and if useful window argv vectors.
978 setupargv(session_t *sp, struct ttyent *typ)
983 free(sp->se_getty_argv_space);
984 free(sp->se_getty_argv);
986 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
987 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
988 sp->se_getty_argv_space = strdup(sp->se_getty);
989 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
990 if (sp->se_getty_argv == 0) {
991 warning("can't parse getty for port %s", sp->se_device);
993 free(sp->se_getty_argv_space);
994 sp->se_getty = sp->se_getty_argv_space = 0;
999 free(sp->se_window_argv_space);
1000 free(sp->se_window_argv);
1002 sp->se_window = sp->se_window_argv_space = 0;
1003 sp->se_window_argv = 0;
1004 if (typ->ty_window) {
1005 sp->se_window = strdup(typ->ty_window);
1006 sp->se_window_argv_space = strdup(sp->se_window);
1007 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1008 if (sp->se_window_argv == 0) {
1009 warning("can't parse window for port %s",
1011 free(sp->se_window_argv_space);
1012 free(sp->se_window);
1013 sp->se_window = sp->se_window_argv_space = 0;
1019 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1024 * Walk the list of ttys and create sessions for each active line.
1029 int session_index = 0;
1030 session_t *sp, *snext;
1034 * Destroy any previous session state.
1035 * There shouldn't be any, but just in case...
1037 for (sp = sessions; sp; sp = snext) {
1039 clear_session_logs(sp);
1040 snext = sp->se_next;
1044 if (start_session_db())
1045 return (state_func_t) single_user;
1048 * Allocate a session entry for each active port.
1049 * Note that sp starts at 0.
1051 while ((typ = getttyent()) != NULL)
1052 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1057 return (state_func_t) multi_user;
1061 * Start a window system running.
1064 start_window_system(session_t *sp)
1068 char term[64], *env[2];
1071 if ((pid = fork()) == -1) {
1072 emergency("can't fork for window system on port %s: %m",
1074 /* hope that getty fails and we can try again */
1079 waitpid(-1, &status, 0);
1083 /* reparent window process to the init to not make a zombie on exit */
1084 if ((pid = fork()) == -1) {
1085 emergency("can't fork for window system on port %s: %m",
1093 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1096 emergency("setsid failed (window) %m");
1099 setprocresources(RESOURCE_WINDOW);
1102 /* Don't use malloc after fork */
1103 strcpy(term, "TERM=");
1104 strncat(term, sp->se_type, sizeof(term) - 6);
1110 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1111 stall("can't exec window system '%s' for port %s: %m",
1112 sp->se_window_argv[0], sp->se_device);
1117 * Start a login session running.
1120 start_getty(session_t *sp)
1124 time_t current_time = time((time_t *) 0);
1126 char term[64], *env[2];
1128 if (current_time >= sp->se_started &&
1129 current_time - sp->se_started < GETTY_SPACING) {
1130 if (++sp->se_nspace > GETTY_NSPACE) {
1138 * fork(), not vfork() -- we can't afford to block.
1140 if ((pid = fork()) == -1) {
1141 emergency("can't fork for getty on port %s: %m", sp->se_device);
1149 warning("getty repeating too quickly on port %s, sleeping %d secs",
1150 sp->se_device, GETTY_SLEEP);
1151 sleep((unsigned) GETTY_SLEEP);
1154 if (sp->se_window) {
1155 start_window_system(sp);
1160 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1163 setprocresources(RESOURCE_GETTY);
1166 /* Don't use malloc after fork */
1167 strcpy(term, "TERM=");
1168 strncat(term, sp->se_type, sizeof(term) - 6);
1174 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1175 stall("can't exec getty '%s' for port %s: %m",
1176 sp->se_getty_argv[0], sp->se_device);
1181 * Collect exit status for a child.
1182 * If an exiting login, start a new login running.
1185 collect_child(pid_t pid)
1187 session_t *sp, *sprev, *snext;
1192 if (! (sp = find_session(pid)))
1195 clear_session_logs(sp);
1199 if (sp->se_flags & SE_SHUTDOWN) {
1200 if ((sprev = sp->se_prev) != NULL)
1201 sprev->se_next = sp->se_next;
1203 sessions = sp->se_next;
1204 if ((snext = sp->se_next) != NULL)
1205 snext->se_prev = sp->se_prev;
1210 if ((pid = start_getty(sp)) == -1) {
1211 /* serious trouble */
1212 requested_transition = clean_ttys;
1216 sp->se_process = pid;
1217 sp->se_started = time((time_t *) 0);
1222 * Catch a signal and request a state transition.
1225 transition_handler(int sig)
1230 requested_transition = clean_ttys;
1233 howto = RB_POWEROFF;
1239 requested_transition = death;
1242 requested_transition = catatonia;
1245 requested_transition = 0;
1251 * Take the system multiuser.
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*2)+(n^2) algorithm. We hope it isn't run often...
1296 session_t *sp, *sprev;
1298 int session_index = 0;
1300 char *old_getty, *old_window, *old_type;
1303 * mark all sessions for death, (!SE_PRESENT)
1304 * as we find or create new ones they'll be marked as keepers,
1305 * we'll later nuke all the ones not found in /etc/ttys
1307 for (sp = sessions; sp != NULL; sp = sp->se_next)
1308 sp->se_flags &= ~SE_PRESENT;
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 /* we want this one to live */
1320 sp->se_flags |= SE_PRESENT;
1321 if (sp->se_index != session_index) {
1322 warning("port %s changed utmp index from %d to %d",
1323 sp->se_device, sp->se_index,
1325 sp->se_index = session_index;
1327 if ((typ->ty_status & TTY_ON) == 0 ||
1328 typ->ty_getty == 0) {
1329 sp->se_flags |= SE_SHUTDOWN;
1330 kill(sp->se_process, SIGHUP);
1333 sp->se_flags &= ~SE_SHUTDOWN;
1334 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1335 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1336 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1337 if (setupargv(sp, typ) == 0) {
1338 warning("can't parse getty for port %s",
1340 sp->se_flags |= SE_SHUTDOWN;
1341 kill(sp->se_process, SIGHUP);
1343 else if ( !old_getty
1344 || (!old_type && sp->se_type)
1345 || (old_type && !sp->se_type)
1346 || (!old_window && sp->se_window)
1347 || (old_window && !sp->se_window)
1348 || (strcmp(old_getty, sp->se_getty) != 0)
1349 || (old_window && strcmp(old_window, sp->se_window) != 0)
1350 || (old_type && strcmp(old_type, sp->se_type) != 0)
1352 /* Don't set SE_SHUTDOWN here */
1355 kill(sp->se_process, SIGHUP);
1366 new_session(sprev, session_index, typ);
1372 * sweep through and kill all deleted sessions
1373 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1375 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1376 if ((sp->se_flags & SE_PRESENT) == 0) {
1377 sp->se_flags |= SE_SHUTDOWN;
1378 kill(sp->se_process, SIGHUP);
1382 return (state_func_t) multi_user;
1386 * Block further logins.
1393 for (sp = sessions; sp; sp = sp->se_next)
1394 sp->se_flags |= SE_SHUTDOWN;
1396 return (state_func_t) multi_user;
1403 alrm_handler(int sig)
1410 * Bring the system down to single user.
1418 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1420 /* NB: should send a message to the session logger to avoid blocking. */
1421 logwtmp("~", "shutdown", "");
1423 for (sp = sessions; sp; sp = sp->se_next) {
1424 sp->se_flags |= SE_SHUTDOWN;
1425 kill(sp->se_process, SIGHUP);
1428 /* Try to run the rc.shutdown script within a period of time */
1429 (void) runshutdown();
1431 for (i = 0; i < 2; ++i) {
1432 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1433 return (state_func_t) single_user;
1438 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1440 while (clang == 0 && errno != ECHILD);
1442 if (errno == ECHILD)
1443 return (state_func_t) single_user;
1446 warning("some processes would not die; ps axl advised");
1448 return (state_func_t) single_user;
1452 * Run the system shutdown script.
1454 * Exit codes: XXX I should document more
1455 * -2 shutdown script terminated abnormally
1456 * -1 fatal error - can't run script
1458 * >0 some error (exit code)
1465 int shutdowntimeout;
1468 struct sigaction sa;
1472 * rc.shutdown is optional, so to prevent any unnecessary
1473 * complaints from the shell we simply don't run it if the
1474 * file does not exist. If the stat() here fails for other
1475 * reasons, we'll let the shell complain.
1477 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1480 if ((pid = fork()) == 0) {
1483 /* Assume that init already grab console as ctty before */
1485 sigemptyset(&sa.sa_mask);
1487 sa.sa_handler = SIG_IGN;
1488 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1489 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
1491 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1492 warning("can't open %s: %m", _PATH_CONSOLE);
1502 * Run the shutdown script.
1506 char _reboot[] = "reboot";
1507 char _single[] = "single";
1508 char _path_rundown[] = _PATH_RUNDOWN;
1511 argv[1] = _path_rundown;
1512 argv[2] = Reboot ? _reboot : _single;
1515 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1518 setprocresources(RESOURCE_RC);
1520 execv(_PATH_BSHELL, argv);
1521 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1522 _exit(1); /* force single user mode */
1526 emergency("can't fork for %s on %s: %m",
1527 _PATH_BSHELL, _PATH_RUNDOWN);
1528 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1530 sleep(STALL_TIMEOUT);
1534 len = sizeof(shutdowntimeout);
1535 if (sysctlbyname("kern.init_shutdown_timeout",
1537 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1538 shutdowntimeout = DEATH_SCRIPT;
1539 alarm(shutdowntimeout);
1542 * Copied from single_user(). This is a bit paranoid.
1543 * Use the same ALRM handler.
1546 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1547 collect_child(wpid);
1549 /* we were waiting for the sub-shell */
1550 kill(wpid, SIGTERM);
1551 warning("timeout expired for %s on %s: %m; going to single user mode",
1552 _PATH_BSHELL, _PATH_RUNDOWN);
1558 warning("wait for %s on %s failed: %m; going to single user mode",
1559 _PATH_BSHELL, _PATH_RUNDOWN);
1562 if (wpid == pid && WIFSTOPPED(status)) {
1563 warning("init: %s on %s stopped, restarting\n",
1564 _PATH_BSHELL, _PATH_RUNDOWN);
1568 } while (wpid != pid && !clang);
1570 /* Turn off the alarm */
1573 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1574 requested_transition == catatonia) {
1576 * /etc/rc.shutdown executed /sbin/reboot;
1577 * wait for the end quietly
1586 if (!WIFEXITED(status)) {
1587 warning("%s on %s terminated abnormally, going to single user mode",
1588 _PATH_BSHELL, _PATH_RUNDOWN);
1592 if ((status = WEXITSTATUS(status)) != 0)
1593 warning("%s returned status %d", _PATH_RUNDOWN, status);
1611 while (c == ' ' || c == '\t' )
1621 while (c && c != '\'')
1623 if (!c) /* unterminated string */
1628 while (c && c != ' ' && c != '\t' )
1639 setprocresources(const char *cname)
1642 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1643 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);