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.10 2007/11/25 18:10:07 swildner 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"
96 * We really need a recursive typedef...
97 * The following at least guarantees that the return type of (*state_t)()
98 * is sufficiently wide to hold a function pointer.
100 typedef long (*state_func_t)(void);
101 typedef state_func_t (*state_t)(void);
103 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
107 static void setctty(const char *);
109 typedef struct init_session {
110 int se_index; /* index of entry in ttys file */
111 pid_t se_process; /* controlling process */
112 time_t se_started; /* used to avoid thrashing */
113 int se_flags; /* status of session */
114 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
115 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
116 int se_nspace; /* spacing count */
117 char *se_device; /* filename of port */
118 char *se_getty; /* what to run on that port */
119 char *se_getty_argv_space; /* pre-parsed argument array space */
120 char **se_getty_argv; /* pre-parsed argument array */
121 char *se_window; /* window system (started only once) */
122 char *se_window_argv_space; /* pre-parsed argument array space */
123 char **se_window_argv; /* pre-parsed argument array */
124 char *se_type; /* default terminal type */
125 struct init_session *se_prev;
126 struct init_session *se_next;
129 static void handle(sig_t, ...);
130 static void delset(sigset_t *, ...);
132 static void stall(const char *, ...);
133 static void warning(const char *, ...);
134 static void emergency(const char *, ...);
135 static void disaster(int);
136 static void badsys(int);
137 static int runshutdown(void);
138 static char *strk(char *);
140 static state_func_t single_user(void);
141 static state_func_t runcom(void);
142 static state_func_t read_ttys(void);
143 static state_func_t multi_user(void);
144 static state_func_t clean_ttys(void);
145 static state_func_t catatonia(void);
146 static state_func_t death(void);
148 static void transition(state_t);
150 static void free_session(session_t *);
151 static session_t *new_session(session_t *, int, struct ttyent *);
153 static char **construct_argv(char *);
154 static void start_window_system(session_t *);
155 static void collect_child(pid_t);
156 static pid_t start_getty(session_t *);
157 static void transition_handler(int);
158 static void alrm_handler(int);
159 static void setsecuritylevel(int);
160 static int getsecuritylevel(void);
161 static char *get_chroot(void);
162 static int setupargv(session_t *, struct ttyent *);
164 static void setprocresources(const char *);
167 static void clear_session_logs(session_t *);
169 static int start_session_db(void);
170 static void add_session(session_t *);
171 static void del_session(session_t *);
172 static session_t *find_session(pid_t);
174 static int Reboot = FALSE;
175 static int howto = RB_AUTOBOOT;
177 static DB *session_db;
178 static volatile sig_atomic_t clang;
179 static session_t *sessions;
180 state_t requested_transition = runcom;
183 * The mother of all processes.
186 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 * If chroot has been requested by the boot loader,
244 * do it now. Try to be robust: If the directory
245 * doesn't exist, continue anyway.
247 init_chroot = get_chroot();
248 if (init_chroot != NULL) {
249 if (chdir(init_chroot) == -1 || chroot(".") == -1)
250 warning("can't chroot to %s: %m", init_chroot);
255 * Create an initial session.
258 warning("initial setsid() failed: %m");
261 * Establish an initial user so that programs running
262 * single user do not freak out and die (like passwd).
264 if (setlogin("root") < 0)
265 warning("setlogin() failed: %m");
267 if (stat("/dev/null", &sts) < 0) {
268 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
273 * This code assumes that we always get arguments through flags,
274 * never through bits set in some random machine register.
276 while ((c = getopt(argc, argv, "dsf")) != -1)
279 /* We don't support DEVFS. */
282 requested_transition = single_user;
285 runcom_mode = FASTBOOT;
288 warning("unrecognized flag '-%c'", c);
293 warning("ignoring excess arguments");
296 * We catch or block signals rather than ignore them,
297 * so that they get reset on exec.
299 handle(badsys, SIGSYS, 0);
300 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
301 SIGBUS, SIGXCPU, SIGXFSZ, 0);
302 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
303 SIGUSR1, SIGUSR2, 0);
304 handle(alrm_handler, SIGALRM, 0);
306 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
307 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
308 SIGUSR1, SIGUSR2, 0);
309 sigprocmask(SIG_SETMASK, &mask, NULL);
310 sigemptyset(&sa.sa_mask);
312 sa.sa_handler = SIG_IGN;
313 sigaction(SIGTTIN, &sa, NULL);
314 sigaction(SIGTTOU, &sa, NULL);
324 * Start the state machine.
326 transition(requested_transition);
329 * Should never reach here.
335 * Associate a function with a signal handler.
338 handle(sig_t handler, ...)
342 sigset_t mask_everything;
345 va_start(ap, handler);
347 sa.sa_handler = handler;
348 sigfillset(&mask_everything);
350 while ((sig = va_arg(ap, int)) != 0) {
351 sa.sa_mask = mask_everything;
352 /* XXX SA_RESTART? */
353 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
354 sigaction(sig, &sa, NULL);
360 * Delete a set of signals from a mask.
363 delset(sigset_t *maskp, ...)
370 while ((sig = va_arg(ap, int)) != 0)
371 sigdelset(maskp, sig);
376 * Log a message and sleep for a while (to give someone an opportunity
377 * to read it and to save log or hardcopy output if the problem is chronic).
378 * NB: should send a message to the session logger to avoid blocking.
381 stall(const char *message, ...)
385 va_start(ap, message);
387 vsyslog(LOG_ALERT, message, ap);
389 sleep(STALL_TIMEOUT);
393 * Like stall(), but doesn't sleep.
394 * If cpp had variadic macros, the two functions could be #defines for another.
395 * NB: should send a message to the session logger to avoid blocking.
398 warning(const char *message, ...)
402 va_start(ap, message);
404 vsyslog(LOG_ALERT, message, ap);
409 * Log an emergency message.
410 * NB: should send a message to the session logger to avoid blocking.
413 emergency(const char *message, ...)
417 va_start(ap, message);
419 vsyslog(LOG_EMERG, message, ap);
424 * Catch a SIGSYS signal.
426 * These may arise if a system does not support sysctl.
427 * We tolerate up to 25 of these, then throw in the towel.
432 static int badcount = 0;
440 * Catch an unexpected signal.
445 emergency("fatal signal: %s",
446 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
448 sleep(STALL_TIMEOUT);
449 _exit(sig); /* reboot */
453 * Get the security level of the kernel.
456 getsecuritylevel(void)
458 #ifdef KERN_SECURELVL
459 int name[2], curlevel;
463 name[1] = KERN_SECURELVL;
464 len = sizeof curlevel;
465 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
466 emergency("cannot get kernel security level: %s",
477 * Get the value of the "init_chroot" variable from the
478 * kernel environment (or NULL if not set).
484 static const char ichname[] = "init_chroot="; /* includes '=' */
485 const int ichlen = strlen(ichname);
486 int real_oid[CTL_MAXNAME];
492 oidlen = __arysize(real_oid);
493 if (sysctlnametomib("kern.environment", real_oid, &oidlen)) {
494 warning("cannot find kern.environment base sysctl OID");
497 if (oidlen + 1 >= __arysize(real_oid)) {
498 warning("kern.environment OID is too large!");
502 real_oid[oidlen] = 0;
505 real_oid[oidlen + 1] = i;
507 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
509 warning("sysctl kern.environment.%d: %m", i);
514 * slen includes the terminating \0, but do a few sanity
520 if (strncmp(sbuf, ichname, ichlen) != 0)
523 res = strdup(sbuf + ichlen);
530 * Set the security level of the kernel.
533 setsecuritylevel(int newlevel)
535 #ifdef KERN_SECURELVL
536 int name[2], curlevel;
538 curlevel = getsecuritylevel();
539 if (newlevel == curlevel)
542 name[1] = KERN_SECURELVL;
543 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
545 "cannot change kernel security level from %d to %d: %s",
546 curlevel, newlevel, strerror(errno));
550 warning("kernel security level changed from %d to %d",
557 * Change states in the finite state machine.
558 * The initial state is passed as an argument.
561 transition(state_t s)
564 s = (state_t) (*s)();
568 * Close out the accounting files for a login session.
569 * NB: should send a message to the session logger to avoid blocking.
572 clear_session_logs(session_t *sp)
574 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
577 logwtmp(line, "", "");
581 * Start a session and allocate a controlling terminal.
582 * Only called by children of init after forking.
585 setctty(const char *name)
590 if ((fd = open(name, O_RDWR)) == -1) {
591 stall("can't open %s: %m", name);
594 if (login_tty(fd) == -1) {
595 stall("can't get %s for controlling terminal: %m", name);
601 * Bring the system up single user.
609 const char *shell = _PATH_BSHELL;
614 static const char banner[] =
615 "Enter root password, or ^D to go multi-user\n";
616 char *clear, *password;
623 /* Instead of going single user, let's reboot the machine */
631 if ((pid = fork()) == 0) {
633 * Start the single user session.
635 setctty(_PATH_CONSOLE);
639 * Check the root password.
640 * We don't care if the console is 'on' by default;
641 * it's the only tty that can be 'off' and 'secure'.
643 typ = getttynam("console");
644 pp = getpwnam("root");
645 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
646 pp && *pp->pw_passwd) {
647 write(2, banner, sizeof banner - 1);
649 clear = getpass("Password:");
650 if (clear == 0 || *clear == '\0')
652 password = crypt(clear, pp->pw_passwd);
653 bzero(clear, _PASSWORD_LEN);
654 if (strcmp(password, pp->pw_passwd) == 0)
656 warning("single-user login failed\n");
669 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
670 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
671 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
672 num != 0 && *cp != '\n' && cp < &altshell[127])
675 if (altshell[0] != '\0')
678 #endif /* DEBUGSHELL */
682 * We catch all the interesting ones,
683 * and those are reset to SIG_DFL on exec.
686 sigprocmask(SIG_SETMASK, &mask, NULL);
690 * If the default one doesn't work, try the Bourne shell.
694 execv(shell, __DECONST(char **, argv));
695 emergency("can't exec %s for single user: %m", shell);
696 execv(_PATH_BSHELL, __DECONST(char **, argv));
697 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
698 sleep(STALL_TIMEOUT);
704 * We are seriously hosed. Do our best.
706 emergency("can't fork single-user shell, trying again");
707 while (waitpid(-1, NULL, WNOHANG) > 0)
709 return (state_func_t) single_user;
712 requested_transition = 0;
714 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
719 warning("wait for single-user shell failed: %m; restarting");
720 return (state_func_t) single_user;
722 if (wpid == pid && WIFSTOPPED(status)) {
723 warning("init: shell stopped, restarting\n");
727 } while (wpid != pid && !requested_transition);
729 if (requested_transition)
730 return (state_func_t) requested_transition;
732 if (!WIFEXITED(status)) {
733 if (WTERMSIG(status) == SIGKILL) {
735 * reboot(8) killed shell?
737 warning("single user shell terminated.");
738 sleep(STALL_TIMEOUT);
741 warning("single user shell terminated, restarting");
742 return (state_func_t) single_user;
746 runcom_mode = FASTBOOT;
747 return (state_func_t) runcom;
751 * Run the system startup script.
761 if ((pid = fork()) == 0) {
762 sigemptyset(&sa.sa_mask);
764 sa.sa_handler = SIG_IGN;
765 sigaction(SIGTSTP, &sa, NULL);
766 sigaction(SIGHUP, &sa, NULL);
768 setctty(_PATH_CONSOLE);
771 argv[1] = _PATH_RUNCOM;
772 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
775 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
778 setprocresources(RESOURCE_RC);
780 execv(_PATH_BSHELL, __DECONST(char **, argv));
781 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
782 _exit(1); /* force single user mode */
786 emergency("can't fork for %s on %s: %m",
787 _PATH_BSHELL, _PATH_RUNCOM);
788 while (waitpid(-1, NULL, WNOHANG) > 0)
790 sleep(STALL_TIMEOUT);
791 return (state_func_t) single_user;
795 * Copied from single_user(). This is a bit paranoid.
797 requested_transition = 0;
799 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
802 if (requested_transition == death)
803 return (state_func_t) death;
806 warning("wait for %s on %s failed: %m; going to single user mode",
807 _PATH_BSHELL, _PATH_RUNCOM);
808 return (state_func_t) single_user;
810 if (wpid == pid && WIFSTOPPED(status)) {
811 warning("init: %s on %s stopped, restarting\n",
812 _PATH_BSHELL, _PATH_RUNCOM);
816 } while (wpid != pid);
818 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
819 requested_transition == catatonia) {
820 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
828 if (!WIFEXITED(status)) {
829 warning("%s on %s terminated abnormally, going to single user mode",
830 _PATH_BSHELL, _PATH_RUNCOM);
831 return (state_func_t) single_user;
834 if (WEXITSTATUS(status))
835 return (state_func_t) single_user;
837 runcom_mode = AUTOBOOT; /* the default */
838 /* NB: should send a message to the session logger to avoid blocking. */
839 logwtmp("~", "reboot", "");
840 return (state_func_t) read_ttys;
844 * Open the session database.
846 * NB: We could pass in the size here; is it necessary?
849 start_session_db(void)
851 if (session_db && (*session_db->close)(session_db))
852 emergency("session database close: %s", strerror(errno));
853 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
854 emergency("session database open: %s", strerror(errno));
862 * Add a new login session.
865 add_session(session_t *sp)
870 key.data = &sp->se_process;
871 key.size = sizeof sp->se_process;
873 data.size = sizeof sp;
875 if ((*session_db->put)(session_db, &key, &data, 0))
876 emergency("insert %d: %s", sp->se_process, strerror(errno));
880 * Delete an old login session.
883 del_session(session_t *sp)
887 key.data = &sp->se_process;
888 key.size = sizeof sp->se_process;
890 if ((*session_db->del)(session_db, &key, 0))
891 emergency("delete %d: %s", sp->se_process, strerror(errno));
895 * Look up a login session by pid.
898 find_session(pid_t pid)
905 key.size = sizeof pid;
906 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
908 bcopy(data.data, (char *)&ret, sizeof(ret));
913 * Construct an argument vector from a command line.
916 construct_argv(char *command)
919 char **argv = malloc(((strlen(command) + 1) / 2 + 1)
922 if ((argv[argc++] = strk(command)) == 0) {
926 while ((argv[argc++] = strk(NULL)) != NULL)
932 * Deallocate a session descriptor.
935 free_session(session_t *sp)
940 free(sp->se_getty_argv_space);
941 free(sp->se_getty_argv);
945 free(sp->se_window_argv_space);
946 free(sp->se_window_argv);
954 * Allocate a new session descriptor.
955 * Mark it SE_PRESENT.
958 new_session(session_t *sprev, int session_index, struct ttyent *typ)
963 if ((typ->ty_status & TTY_ON) == 0 ||
968 sp = (session_t *) calloc(1, sizeof (session_t));
970 sp->se_index = session_index;
971 sp->se_flags |= SE_PRESENT;
973 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
974 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
977 * Attempt to open the device, if we get "device not configured"
978 * then don't add the device to the session list.
980 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
981 if (errno == ENXIO) {
988 if (setupargv(sp, typ) == 0) {
1006 * Calculate getty and if useful window argv vectors.
1009 setupargv(session_t *sp, struct ttyent *typ)
1014 free(sp->se_getty_argv_space);
1015 free(sp->se_getty_argv);
1017 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1018 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1019 sp->se_getty_argv_space = strdup(sp->se_getty);
1020 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1021 if (sp->se_getty_argv == 0) {
1022 warning("can't parse getty for port %s", sp->se_device);
1024 free(sp->se_getty_argv_space);
1025 sp->se_getty = sp->se_getty_argv_space = 0;
1028 if (sp->se_window) {
1029 free(sp->se_window);
1030 free(sp->se_window_argv_space);
1031 free(sp->se_window_argv);
1033 sp->se_window = sp->se_window_argv_space = 0;
1034 sp->se_window_argv = 0;
1035 if (typ->ty_window) {
1036 sp->se_window = strdup(typ->ty_window);
1037 sp->se_window_argv_space = strdup(sp->se_window);
1038 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1039 if (sp->se_window_argv == 0) {
1040 warning("can't parse window for port %s",
1042 free(sp->se_window_argv_space);
1043 free(sp->se_window);
1044 sp->se_window = sp->se_window_argv_space = 0;
1050 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1055 * Walk the list of ttys and create sessions for each active line.
1060 int session_index = 0;
1061 session_t *sp, *snext;
1065 * Destroy any previous session state.
1066 * There shouldn't be any, but just in case...
1068 for (sp = sessions; sp; sp = snext) {
1070 clear_session_logs(sp);
1071 snext = sp->se_next;
1075 if (start_session_db())
1076 return (state_func_t) single_user;
1079 * Allocate a session entry for each active port.
1080 * Note that sp starts at 0.
1082 while ((typ = getttyent()) != NULL)
1083 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1088 return (state_func_t) multi_user;
1092 * Start a window system running.
1095 start_window_system(session_t *sp)
1099 char term[64], *env[2];
1101 if ((pid = fork()) == -1) {
1102 emergency("can't fork for window system on port %s: %m",
1104 /* hope that getty fails and we can try again */
1112 sigprocmask(SIG_SETMASK, &mask, NULL);
1115 emergency("setsid failed (window) %m");
1118 setprocresources(RESOURCE_WINDOW);
1121 /* Don't use malloc after fork */
1122 strcpy(term, "TERM=");
1123 strncat(term, sp->se_type, sizeof(term) - 6);
1129 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1130 stall("can't exec window system '%s' for port %s: %m",
1131 sp->se_window_argv[0], sp->se_device);
1136 * Start a login session running.
1139 start_getty(session_t *sp)
1143 time_t current_time = time(NULL);
1145 char term[64], *env[2];
1147 if (current_time >= sp->se_started &&
1148 current_time - sp->se_started < GETTY_SPACING) {
1149 if (++sp->se_nspace > GETTY_NSPACE) {
1157 * fork(), not vfork() -- we can't afford to block.
1159 if ((pid = fork()) == -1) {
1160 emergency("can't fork for getty on port %s: %m", sp->se_device);
1168 warning("getty repeating too quickly on port %s, sleeping %d secs",
1169 sp->se_device, GETTY_SLEEP);
1170 sleep((unsigned) GETTY_SLEEP);
1173 if (sp->se_window) {
1174 start_window_system(sp);
1179 sigprocmask(SIG_SETMASK, &mask, NULL);
1182 setprocresources(RESOURCE_GETTY);
1185 /* Don't use malloc after fork */
1186 strcpy(term, "TERM=");
1187 strncat(term, sp->se_type, sizeof(term) - 6);
1193 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1194 stall("can't exec getty '%s' for port %s: %m",
1195 sp->se_getty_argv[0], sp->se_device);
1200 * Collect exit status for a child.
1201 * If an exiting login, start a new login running.
1204 collect_child(pid_t pid)
1206 session_t *sp, *sprev, *snext;
1211 if (! (sp = find_session(pid)))
1214 clear_session_logs(sp);
1218 if (sp->se_flags & SE_SHUTDOWN) {
1219 if ((sprev = sp->se_prev) != NULL)
1220 sprev->se_next = sp->se_next;
1222 sessions = sp->se_next;
1223 if ((snext = sp->se_next) != NULL)
1224 snext->se_prev = sp->se_prev;
1229 if ((pid = start_getty(sp)) == -1) {
1230 /* serious trouble */
1231 requested_transition = clean_ttys;
1235 sp->se_process = pid;
1236 sp->se_started = time(NULL);
1241 * Catch a signal and request a state transition.
1244 transition_handler(int sig)
1249 requested_transition = clean_ttys;
1252 howto = RB_POWEROFF;
1258 requested_transition = death;
1261 requested_transition = catatonia;
1264 requested_transition = 0;
1270 * Take the system multiuser.
1278 requested_transition = 0;
1281 * If the administrator has not set the security level to -1
1282 * to indicate that the kernel should not run multiuser in secure
1283 * mode, and the run script has not set a higher level of security
1284 * than level 1, then put the kernel into secure mode.
1286 if (getsecuritylevel() == 0)
1287 setsecuritylevel(1);
1289 for (sp = sessions; sp; sp = sp->se_next) {
1292 if ((pid = start_getty(sp)) == -1) {
1293 /* serious trouble */
1294 requested_transition = clean_ttys;
1297 sp->se_process = pid;
1298 sp->se_started = time(NULL);
1302 while (!requested_transition)
1303 if ((pid = waitpid(-1, NULL, 0)) != -1)
1306 return (state_func_t) requested_transition;
1310 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1315 session_t *sp, *sprev;
1317 int session_index = 0;
1319 char *old_getty, *old_window, *old_type;
1322 return (state_func_t) multi_user;
1325 * mark all sessions for death, (!SE_PRESENT)
1326 * as we find or create new ones they'll be marked as keepers,
1327 * we'll later nuke all the ones not found in /etc/ttys
1329 for (sp = sessions; sp != NULL; sp = sp->se_next)
1330 sp->se_flags &= ~SE_PRESENT;
1332 devlen = sizeof(_PATH_DEV) - 1;
1333 while ((typ = getttyent()) != NULL) {
1336 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1337 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1341 /* we want this one to live */
1342 sp->se_flags |= SE_PRESENT;
1343 if (sp->se_index != session_index) {
1344 warning("port %s changed utmp index from %d to %d",
1345 sp->se_device, sp->se_index,
1347 sp->se_index = session_index;
1349 if ((typ->ty_status & TTY_ON) == 0 ||
1350 typ->ty_getty == 0) {
1351 sp->se_flags |= SE_SHUTDOWN;
1352 kill(sp->se_process, SIGHUP);
1355 sp->se_flags &= ~SE_SHUTDOWN;
1356 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1357 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1358 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1359 if (setupargv(sp, typ) == 0) {
1360 warning("can't parse getty for port %s",
1362 sp->se_flags |= SE_SHUTDOWN;
1363 kill(sp->se_process, SIGHUP);
1365 else if ( !old_getty
1366 || (!old_type && sp->se_type)
1367 || (old_type && !sp->se_type)
1368 || (!old_window && sp->se_window)
1369 || (old_window && !sp->se_window)
1370 || (strcmp(old_getty, sp->se_getty) != 0)
1371 || (old_window && strcmp(old_window, sp->se_window) != 0)
1372 || (old_type && strcmp(old_type, sp->se_type) != 0)
1374 /* Don't set SE_SHUTDOWN here */
1377 kill(sp->se_process, SIGHUP);
1388 new_session(sprev, session_index, typ);
1394 * sweep through and kill all deleted sessions
1395 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1397 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1398 if ((sp->se_flags & SE_PRESENT) == 0) {
1399 sp->se_flags |= SE_SHUTDOWN;
1400 kill(sp->se_process, SIGHUP);
1404 return (state_func_t) multi_user;
1408 * Block further logins.
1415 for (sp = sessions; sp; sp = sp->se_next)
1416 sp->se_flags |= SE_SHUTDOWN;
1418 return (state_func_t) multi_user;
1425 alrm_handler(int sig __unused)
1431 * Bring the system down to single user.
1439 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1441 /* NB: should send a message to the session logger to avoid blocking. */
1442 logwtmp("~", "shutdown", "");
1444 for (sp = sessions; sp; sp = sp->se_next) {
1445 sp->se_flags |= SE_SHUTDOWN;
1446 kill(sp->se_process, SIGHUP);
1449 /* Try to run the rc.shutdown script within a period of time */
1452 for (i = 0; i < 2; ++i) {
1453 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1454 return (state_func_t) single_user;
1459 if ((pid = waitpid(-1, NULL, 0)) != -1)
1461 while (clang == 0 && errno != ECHILD);
1463 if (errno == ECHILD)
1464 return (state_func_t) single_user;
1467 warning("some processes would not die; ps axl advised");
1469 return (state_func_t) single_user;
1473 * Run the system shutdown script.
1475 * Exit codes: XXX I should document more
1476 * -2 shutdown script terminated abnormally
1477 * -1 fatal error - can't run script
1479 * >0 some error (exit code)
1486 int shutdowntimeout;
1488 const char *argv[4];
1489 struct sigaction sa;
1493 * rc.shutdown is optional, so to prevent any unnecessary
1494 * complaints from the shell we simply don't run it if the
1495 * file does not exist. If the stat() here fails for other
1496 * reasons, we'll let the shell complain.
1498 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1501 if ((pid = fork()) == 0) {
1504 /* Assume that init already grab console as ctty before */
1506 sigemptyset(&sa.sa_mask);
1508 sa.sa_handler = SIG_IGN;
1509 sigaction(SIGTSTP, &sa, NULL);
1510 sigaction(SIGHUP, &sa, NULL);
1512 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1513 warning("can't open %s: %m", _PATH_CONSOLE);
1523 * Run the shutdown script.
1526 argv[1] = _PATH_RUNDOWN;
1533 sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
1536 setprocresources(RESOURCE_RC);
1538 execv(_PATH_BSHELL, __DECONST(char **, argv));
1539 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1540 _exit(1); /* force single user mode */
1544 emergency("can't fork for %s on %s: %m",
1545 _PATH_BSHELL, _PATH_RUNDOWN);
1546 while (waitpid(-1, NULL, WNOHANG) > 0)
1548 sleep(STALL_TIMEOUT);
1552 len = sizeof(shutdowntimeout);
1553 if (sysctlbyname("kern.shutdown_timeout",
1555 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1556 shutdowntimeout = DEATH_SCRIPT;
1557 alarm(shutdowntimeout);
1560 * Copied from single_user(). This is a bit paranoid.
1561 * Use the same ALRM handler.
1564 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1565 collect_child(wpid);
1567 /* we were waiting for the sub-shell */
1568 kill(wpid, SIGTERM);
1569 warning("timeout expired for %s on %s: %m; going to single user mode",
1570 _PATH_BSHELL, _PATH_RUNDOWN);
1576 warning("wait for %s on %s failed: %m; going to single user mode",
1577 _PATH_BSHELL, _PATH_RUNDOWN);
1580 if (wpid == pid && WIFSTOPPED(status)) {
1581 warning("init: %s on %s stopped, restarting\n",
1582 _PATH_BSHELL, _PATH_RUNDOWN);
1586 } while (wpid != pid && !clang);
1588 /* Turn off the alarm */
1591 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1592 requested_transition == catatonia) {
1594 * /etc/rc.shutdown executed /sbin/reboot;
1595 * wait for the end quietly
1604 if (!WIFEXITED(status)) {
1605 warning("%s on %s terminated abnormally, going to single user mode",
1606 _PATH_BSHELL, _PATH_RUNDOWN);
1610 if ((status = WEXITSTATUS(status)) != 0)
1611 warning("%s returned status %d", _PATH_RUNDOWN, status);
1629 while (c == ' ' || c == '\t' )
1639 while (c && c != '\'')
1641 if (!c) /* unterminated string */
1646 while (c && c != ' ' && c != '\t' )
1657 setprocresources(const char *cname)
1660 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1661 setusercontext(lc, NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);