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.7 2004/12/18 21:43:38 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"
95 void handle(sig_t, ...);
96 void delset(sigset_t *, ...);
98 void stall(char *, ...);
99 void warning(char *, ...);
100 void emergency(char *, ...);
103 int runshutdown(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)(void);
111 typedef state_func_t (*state_t)(void);
113 state_func_t single_user(void);
114 state_func_t runcom(void);
115 state_func_t read_ttys(void);
116 state_func_t multi_user(void);
117 state_func_t clean_ttys(void);
118 state_func_t catatonia(void);
119 state_func_t death(void);
121 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
126 int howto = RB_AUTOBOOT;
128 void transition(state_t);
129 state_t requested_transition = runcom;
131 void setctty(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(session_t *);
154 session_t *new_session(session_t *, int, struct ttyent *);
157 char **construct_argv(char *);
158 void start_window_system(session_t *);
159 void collect_child(pid_t);
160 pid_t start_getty(session_t *);
161 void transition_handler(int);
162 void alrm_handler(int);
163 void setsecuritylevel(int);
164 int getsecuritylevel(void);
165 char *get_chroot(void);
166 int setupargv(session_t *, struct ttyent *);
168 void setprocresources(const char *);
172 void clear_session_logs(session_t *);
174 int start_session_db(void);
175 void add_session(session_t *);
176 void del_session(session_t *);
177 session_t *find_session(pid_t);
181 * The mother of all processes.
184 main(int argc, char **argv)
193 /* Dispose of random users. */
195 errx(1, "%s", strerror(EPERM));
197 /* System V users like to reexec init. */
199 #ifdef COMPAT_SYSV_INIT
200 /* So give them what they want */
202 if (strlen(argv[1]) == 1) {
203 register char runlevel = *argv[1];
207 case '0': /* halt + poweroff */
210 case '1': /* single-user */
213 case '6': /* reboot */
216 case 'c': /* block further logins */
219 case 'q': /* rescan /etc/ttys */
229 errx(1, "invalid run-level ``%s''", argv[1]);
232 errx(1, "already running");
235 * Note that this does NOT open a file...
236 * Does 'init' deserve its own facility number?
238 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
241 * If chroot has been requested by the boot loader,
242 * do it now. Try to be robust: If the directory
243 * doesn't exist, continue anyway.
245 init_chroot = get_chroot();
246 if (init_chroot != NULL) {
247 if (chdir(init_chroot) == -1 || chroot(".") == -1)
248 warning("can't chroot to %s: %m", init_chroot);
253 * Create an initial session.
256 warning("initial setsid() failed: %m");
259 * Establish an initial user so that programs running
260 * single user do not freak out and die (like passwd).
262 if (setlogin("root") < 0)
263 warning("setlogin() failed: %m");
265 if (stat("/dev/null", &sts) < 0) {
266 warning("/dev MAY BE CORRUPT! /dev/null is missing!\n");
271 * This code assumes that we always get arguments through flags,
272 * never through bits set in some random machine register.
274 while ((c = getopt(argc, argv, "dsf")) != -1)
277 /* We don't support DEVFS. */
280 requested_transition = single_user;
283 runcom_mode = FASTBOOT;
286 warning("unrecognized flag '-%c'", c);
291 warning("ignoring excess arguments");
294 * We catch or block signals rather than ignore them,
295 * so that they get reset on exec.
297 handle(badsys, SIGSYS, 0);
298 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
299 SIGBUS, SIGXCPU, SIGXFSZ, 0);
300 handle(transition_handler, SIGHUP, SIGINT, SIGTERM, SIGTSTP,
301 SIGUSR1, SIGUSR2, 0);
302 handle(alrm_handler, SIGALRM, 0);
304 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
305 SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGTERM, SIGTSTP, SIGALRM,
306 SIGUSR1, SIGUSR2, 0);
307 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
308 sigemptyset(&sa.sa_mask);
310 sa.sa_handler = SIG_IGN;
311 sigaction(SIGTTIN, &sa, (struct sigaction *)0);
312 sigaction(SIGTTOU, &sa, (struct sigaction *)0);
322 * Start the state machine.
324 transition(requested_transition);
327 * Should never reach here.
333 * Associate a function with a signal handler.
336 handle(sig_t handler, ...)
340 sigset_t mask_everything;
343 va_start(ap, handler);
345 sa.sa_handler = handler;
346 sigfillset(&mask_everything);
348 while ((sig = va_arg(ap, int)) != NULL) {
349 sa.sa_mask = mask_everything;
350 /* XXX SA_RESTART? */
351 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
352 sigaction(sig, &sa, (struct sigaction *) 0);
358 * Delete a set of signals from a mask.
361 delset(sigset_t *maskp, ...)
368 while ((sig = va_arg(ap, int)) != NULL)
369 sigdelset(maskp, sig);
374 * Log a message and sleep for a while (to give someone an opportunity
375 * to read it and to save log or hardcopy output if the problem is chronic).
376 * NB: should send a message to the session logger to avoid blocking.
379 stall(char *message, ...)
383 va_start(ap, message);
385 vsyslog(LOG_ALERT, message, ap);
387 sleep(STALL_TIMEOUT);
391 * Like stall(), but doesn't sleep.
392 * If cpp had variadic macros, the two functions could be #defines for another.
393 * NB: should send a message to the session logger to avoid blocking.
396 warning(char *message, ...)
400 va_start(ap, message);
402 vsyslog(LOG_ALERT, message, ap);
407 * Log an emergency message.
408 * NB: should send a message to the session logger to avoid blocking.
411 emergency(char *message, ...)
415 va_start(ap, message);
417 vsyslog(LOG_EMERG, message, ap);
422 * Catch a SIGSYS signal.
424 * These may arise if a system does not support sysctl.
425 * We tolerate up to 25 of these, then throw in the towel.
430 static int badcount = 0;
438 * Catch an unexpected signal.
443 emergency("fatal signal: %s",
444 (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
446 sleep(STALL_TIMEOUT);
447 _exit(sig); /* reboot */
451 * Get the security level of the kernel.
454 getsecuritylevel(void)
456 #ifdef KERN_SECURELVL
457 int name[2], curlevel;
461 name[1] = KERN_SECURELVL;
462 len = sizeof curlevel;
463 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
464 emergency("cannot get kernel security level: %s",
475 * Get the value of the "init_chroot" variable from the
476 * kernel environment (or NULL if not set).
477 * (Most of this has been copied from src/usr.bin/kenv/kenv.c.)
482 const char * const ichname = "init_chroot="; /* includes '=' */
483 const int ichlen = strlen(ichname);
484 int real_oid[CTL_MAXNAME+4];
493 n2oid_oid[0] = 0; /* This is magic & undocumented! */
495 oidlen = sizeof(real_oid);
496 name = "kern.environment";
498 if (sysctl(n2oid_oid, 2, real_oid, &oidlen, name, strlen(name)) < 0) {
499 warning("cannot find kern.environment base sysctl OID");
502 oidlen /= sizeof(int);
503 if (oidlen >= CTL_MAXNAME) {
504 warning("kern.environment OID is too large!");
508 real_oid[oidlen] = 0;
511 real_oid[oidlen + 1] = i;
513 if (sysctl(real_oid, oidlen + 2, sbuf, &slen, NULL, 0) < 0) {
515 warning("sysctl kern.environment.%d: %m", i);
520 * slen includes the terminating \0, but do a few sanity
526 if (strncmp(sbuf, ichname, ichlen) != 0)
529 res = strdup(sbuf + ichlen);
536 * Set the security level of the kernel.
539 setsecuritylevel(int newlevel)
541 #ifdef KERN_SECURELVL
542 int name[2], curlevel;
544 curlevel = getsecuritylevel();
545 if (newlevel == curlevel)
548 name[1] = KERN_SECURELVL;
549 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
551 "cannot change kernel security level from %d to %d: %s",
552 curlevel, newlevel, strerror(errno));
556 warning("kernel security level changed from %d to %d",
563 * Change states in the finite state machine.
564 * The initial state is passed as an argument.
567 transition(state_t s)
570 s = (state_t) (*s)();
574 * Close out the accounting files for a login session.
575 * NB: should send a message to the session logger to avoid blocking.
578 clear_session_logs(session_t *sp)
580 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
583 logwtmp(line, "", "");
587 * Start a session and allocate a controlling terminal.
588 * Only called by children of init after forking.
596 if ((fd = open(name, O_RDWR)) == -1) {
597 stall("can't open %s: %m", name);
600 if (login_tty(fd) == -1) {
601 stall("can't get %s for controlling terminal: %m", name);
607 * Bring the system up single user.
615 char *shell = _PATH_BSHELL;
620 static const char banner[] =
621 "Enter root password, or ^D to go multi-user\n";
622 char *clear, *password;
629 /* Instead of going single user, let's reboot the machine */
637 if ((pid = fork()) == 0) {
639 * Start the single user session.
641 setctty(_PATH_CONSOLE);
645 * Check the root password.
646 * We don't care if the console is 'on' by default;
647 * it's the only tty that can be 'off' and 'secure'.
649 typ = getttynam("console");
650 pp = getpwnam("root");
651 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
652 pp && *pp->pw_passwd) {
653 write(2, banner, sizeof banner - 1);
655 clear = getpass("Password:");
656 if (clear == 0 || *clear == '\0')
658 password = crypt(clear, pp->pw_passwd);
659 bzero(clear, _PASSWORD_LEN);
660 if (strcmp(password, pp->pw_passwd) == 0)
662 warning("single-user login failed\n");
675 "Enter full pathname of shell or RETURN for " _PATH_BSHELL ": "
676 write(STDERR_FILENO, SHREQUEST, sizeof(SHREQUEST) - 1);
677 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
678 num != 0 && *cp != '\n' && cp < &altshell[127])
681 if (altshell[0] != '\0')
684 #endif /* DEBUGSHELL */
688 * We catch all the interesting ones,
689 * and those are reset to SIG_DFL on exec.
692 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
696 * If the default one doesn't work, try the Bourne shell.
701 emergency("can't exec %s for single user: %m", shell);
702 execv(_PATH_BSHELL, argv);
703 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
704 sleep(STALL_TIMEOUT);
710 * We are seriously hosed. Do our best.
712 emergency("can't fork single-user shell, trying again");
713 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
715 return (state_func_t) single_user;
718 requested_transition = 0;
720 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
725 warning("wait for single-user shell failed: %m; restarting");
726 return (state_func_t) single_user;
728 if (wpid == pid && WIFSTOPPED(status)) {
729 warning("init: shell stopped, restarting\n");
733 } while (wpid != pid && !requested_transition);
735 if (requested_transition)
736 return (state_func_t) requested_transition;
738 if (!WIFEXITED(status)) {
739 if (WTERMSIG(status) == SIGKILL) {
741 * reboot(8) killed shell?
743 warning("single user shell terminated.");
744 sleep(STALL_TIMEOUT);
747 warning("single user shell terminated, restarting");
748 return (state_func_t) single_user;
752 runcom_mode = FASTBOOT;
753 return (state_func_t) runcom;
757 * Run the system startup script.
767 if ((pid = fork()) == 0) {
768 sigemptyset(&sa.sa_mask);
770 sa.sa_handler = SIG_IGN;
771 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
772 sigaction(SIGHUP, &sa, (struct sigaction *)0);
774 setctty(_PATH_CONSOLE);
777 argv[1] = _PATH_RUNCOM;
778 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
781 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
784 setprocresources(RESOURCE_RC);
786 execv(_PATH_BSHELL, argv);
787 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
788 _exit(1); /* force single user mode */
792 emergency("can't fork for %s on %s: %m",
793 _PATH_BSHELL, _PATH_RUNCOM);
794 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
796 sleep(STALL_TIMEOUT);
797 return (state_func_t) single_user;
801 * Copied from single_user(). This is a bit paranoid.
803 requested_transition = 0;
805 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
808 if (requested_transition == death)
809 return (state_func_t) death;
812 warning("wait for %s on %s failed: %m; going to single user mode",
813 _PATH_BSHELL, _PATH_RUNCOM);
814 return (state_func_t) single_user;
816 if (wpid == pid && WIFSTOPPED(status)) {
817 warning("init: %s on %s stopped, restarting\n",
818 _PATH_BSHELL, _PATH_RUNCOM);
822 } while (wpid != pid);
824 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
825 requested_transition == catatonia) {
826 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
834 if (!WIFEXITED(status)) {
835 warning("%s on %s terminated abnormally, going to single user mode",
836 _PATH_BSHELL, _PATH_RUNCOM);
837 return (state_func_t) single_user;
840 if (WEXITSTATUS(status))
841 return (state_func_t) single_user;
843 runcom_mode = AUTOBOOT; /* the default */
844 /* NB: should send a message to the session logger to avoid blocking. */
845 logwtmp("~", "reboot", "");
846 return (state_func_t) read_ttys;
850 * Open the session database.
852 * NB: We could pass in the size here; is it necessary?
855 start_session_db(void)
857 if (session_db && (*session_db->close)(session_db))
858 emergency("session database close: %s", strerror(errno));
859 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
860 emergency("session database open: %s", strerror(errno));
868 * Add a new login session.
871 add_session(session_t *sp)
876 key.data = &sp->se_process;
877 key.size = sizeof sp->se_process;
879 data.size = sizeof sp;
881 if ((*session_db->put)(session_db, &key, &data, 0))
882 emergency("insert %d: %s", sp->se_process, strerror(errno));
886 * Delete an old login session.
889 del_session(session_t *sp)
893 key.data = &sp->se_process;
894 key.size = sizeof sp->se_process;
896 if ((*session_db->del)(session_db, &key, 0))
897 emergency("delete %d: %s", sp->se_process, strerror(errno));
901 * Look up a login session by pid.
904 find_session(pid_t pid)
911 key.size = sizeof pid;
912 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
914 bcopy(data.data, (char *)&ret, sizeof(ret));
919 * Construct an argument vector from a command line.
922 construct_argv(char *command)
925 register int argc = 0;
926 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
929 if ((argv[argc++] = strk(command)) == 0) {
933 while ((argv[argc++] = strk((char *) 0)) != NULL)
939 * Deallocate a session descriptor.
942 free_session(register session_t *sp)
947 free(sp->se_getty_argv_space);
948 free(sp->se_getty_argv);
952 free(sp->se_window_argv_space);
953 free(sp->se_window_argv);
961 * Allocate a new session descriptor.
962 * Mark it SE_PRESENT.
965 new_session(session_t *sprev, int session_index, register struct ttyent *typ)
967 register session_t *sp;
970 if ((typ->ty_status & TTY_ON) == 0 ||
975 sp = (session_t *) calloc(1, sizeof (session_t));
977 sp->se_index = session_index;
978 sp->se_flags |= SE_PRESENT;
980 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
981 sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
984 * Attempt to open the device, if we get "device not configured"
985 * then don't add the device to the session list.
987 if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
988 if (errno == ENXIO) {
995 if (setupargv(sp, typ) == 0) {
1005 sprev->se_next = sp;
1006 sp->se_prev = sprev;
1013 * Calculate getty and if useful window argv vectors.
1016 setupargv(session_t *sp, struct ttyent *typ)
1021 free(sp->se_getty_argv_space);
1022 free(sp->se_getty_argv);
1024 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1025 sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1026 sp->se_getty_argv_space = strdup(sp->se_getty);
1027 sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1028 if (sp->se_getty_argv == 0) {
1029 warning("can't parse getty for port %s", sp->se_device);
1031 free(sp->se_getty_argv_space);
1032 sp->se_getty = sp->se_getty_argv_space = 0;
1035 if (sp->se_window) {
1036 free(sp->se_window);
1037 free(sp->se_window_argv_space);
1038 free(sp->se_window_argv);
1040 sp->se_window = sp->se_window_argv_space = 0;
1041 sp->se_window_argv = 0;
1042 if (typ->ty_window) {
1043 sp->se_window = strdup(typ->ty_window);
1044 sp->se_window_argv_space = strdup(sp->se_window);
1045 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1046 if (sp->se_window_argv == 0) {
1047 warning("can't parse window for port %s",
1049 free(sp->se_window_argv_space);
1050 free(sp->se_window);
1051 sp->se_window = sp->se_window_argv_space = 0;
1057 sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1062 * Walk the list of ttys and create sessions for each active line.
1067 int session_index = 0;
1068 register session_t *sp, *snext;
1069 register struct ttyent *typ;
1072 * Destroy any previous session state.
1073 * There shouldn't be any, but just in case...
1075 for (sp = sessions; sp; sp = snext) {
1077 clear_session_logs(sp);
1078 snext = sp->se_next;
1082 if (start_session_db())
1083 return (state_func_t) single_user;
1086 * Allocate a session entry for each active port.
1087 * Note that sp starts at 0.
1089 while ((typ = getttyent()) != NULL)
1090 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1095 return (state_func_t) multi_user;
1099 * Start a window system running.
1102 start_window_system(session_t *sp)
1106 char term[64], *env[2];
1108 if ((pid = fork()) == -1) {
1109 emergency("can't fork for window system on port %s: %m",
1111 /* hope that getty fails and we can try again */
1119 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1122 emergency("setsid failed (window) %m");
1125 setprocresources(RESOURCE_WINDOW);
1128 /* Don't use malloc after fork */
1129 strcpy(term, "TERM=");
1130 strncat(term, sp->se_type, sizeof(term) - 6);
1136 execve(sp->se_window_argv[0], sp->se_window_argv, env);
1137 stall("can't exec window system '%s' for port %s: %m",
1138 sp->se_window_argv[0], sp->se_device);
1143 * Start a login session running.
1146 start_getty(session_t *sp)
1150 time_t current_time = time((time_t *) 0);
1152 char term[64], *env[2];
1154 if (current_time >= sp->se_started &&
1155 current_time - sp->se_started < GETTY_SPACING) {
1156 if (++sp->se_nspace > GETTY_NSPACE) {
1164 * fork(), not vfork() -- we can't afford to block.
1166 if ((pid = fork()) == -1) {
1167 emergency("can't fork for getty on port %s: %m", sp->se_device);
1175 warning("getty repeating too quickly on port %s, sleeping %d secs",
1176 sp->se_device, GETTY_SLEEP);
1177 sleep((unsigned) GETTY_SLEEP);
1180 if (sp->se_window) {
1181 start_window_system(sp);
1186 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1189 setprocresources(RESOURCE_GETTY);
1192 /* Don't use malloc after fork */
1193 strcpy(term, "TERM=");
1194 strncat(term, sp->se_type, sizeof(term) - 6);
1200 execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1201 stall("can't exec getty '%s' for port %s: %m",
1202 sp->se_getty_argv[0], sp->se_device);
1207 * Collect exit status for a child.
1208 * If an exiting login, start a new login running.
1211 collect_child(pid_t pid)
1213 register session_t *sp, *sprev, *snext;
1218 if (! (sp = find_session(pid)))
1221 clear_session_logs(sp);
1225 if (sp->se_flags & SE_SHUTDOWN) {
1226 if ((sprev = sp->se_prev) != NULL)
1227 sprev->se_next = sp->se_next;
1229 sessions = sp->se_next;
1230 if ((snext = sp->se_next) != NULL)
1231 snext->se_prev = sp->se_prev;
1236 if ((pid = start_getty(sp)) == -1) {
1237 /* serious trouble */
1238 requested_transition = clean_ttys;
1242 sp->se_process = pid;
1243 sp->se_started = time((time_t *) 0);
1248 * Catch a signal and request a state transition.
1251 transition_handler(int sig)
1256 requested_transition = clean_ttys;
1259 howto = RB_POWEROFF;
1265 requested_transition = death;
1268 requested_transition = catatonia;
1271 requested_transition = 0;
1277 * Take the system multiuser.
1283 register session_t *sp;
1285 requested_transition = 0;
1288 * If the administrator has not set the security level to -1
1289 * to indicate that the kernel should not run multiuser in secure
1290 * mode, and the run script has not set a higher level of security
1291 * than level 1, then put the kernel into secure mode.
1293 if (getsecuritylevel() == 0)
1294 setsecuritylevel(1);
1296 for (sp = sessions; sp; sp = sp->se_next) {
1299 if ((pid = start_getty(sp)) == -1) {
1300 /* serious trouble */
1301 requested_transition = clean_ttys;
1304 sp->se_process = pid;
1305 sp->se_started = time((time_t *) 0);
1309 while (!requested_transition)
1310 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1313 return (state_func_t) requested_transition;
1317 * This is an (n*2)+(n^2) algorithm. We hope it isn't run often...
1322 register session_t *sp, *sprev;
1323 register struct ttyent *typ;
1324 register int session_index = 0;
1325 register int devlen;
1326 char *old_getty, *old_window, *old_type;
1329 return (state_func_t) multi_user;
1332 * mark all sessions for death, (!SE_PRESENT)
1333 * as we find or create new ones they'll be marked as keepers,
1334 * we'll later nuke all the ones not found in /etc/ttys
1336 for (sp = sessions; sp != NULL; sp = sp->se_next)
1337 sp->se_flags &= ~SE_PRESENT;
1339 devlen = sizeof(_PATH_DEV) - 1;
1340 while ((typ = getttyent()) != NULL) {
1343 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1344 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1348 /* we want this one to live */
1349 sp->se_flags |= SE_PRESENT;
1350 if (sp->se_index != session_index) {
1351 warning("port %s changed utmp index from %d to %d",
1352 sp->se_device, sp->se_index,
1354 sp->se_index = session_index;
1356 if ((typ->ty_status & TTY_ON) == 0 ||
1357 typ->ty_getty == 0) {
1358 sp->se_flags |= SE_SHUTDOWN;
1359 kill(sp->se_process, SIGHUP);
1362 sp->se_flags &= ~SE_SHUTDOWN;
1363 old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1364 old_window = sp->se_window ? strdup(sp->se_window) : 0;
1365 old_type = sp->se_type ? strdup(sp->se_type) : 0;
1366 if (setupargv(sp, typ) == 0) {
1367 warning("can't parse getty for port %s",
1369 sp->se_flags |= SE_SHUTDOWN;
1370 kill(sp->se_process, SIGHUP);
1372 else if ( !old_getty
1373 || (!old_type && sp->se_type)
1374 || (old_type && !sp->se_type)
1375 || (!old_window && sp->se_window)
1376 || (old_window && !sp->se_window)
1377 || (strcmp(old_getty, sp->se_getty) != 0)
1378 || (old_window && strcmp(old_window, sp->se_window) != 0)
1379 || (old_type && strcmp(old_type, sp->se_type) != 0)
1381 /* Don't set SE_SHUTDOWN here */
1384 kill(sp->se_process, SIGHUP);
1395 new_session(sprev, session_index, typ);
1401 * sweep through and kill all deleted sessions
1402 * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1404 for (sp = sessions; sp != NULL; sp = sp->se_next) {
1405 if ((sp->se_flags & SE_PRESENT) == 0) {
1406 sp->se_flags |= SE_SHUTDOWN;
1407 kill(sp->se_process, SIGHUP);
1411 return (state_func_t) multi_user;
1415 * Block further logins.
1420 register session_t *sp;
1422 for (sp = sessions; sp; sp = sp->se_next)
1423 sp->se_flags |= SE_SHUTDOWN;
1425 return (state_func_t) multi_user;
1432 alrm_handler(int sig)
1439 * Bring the system down to single user.
1444 register session_t *sp;
1447 static const int death_sigs[2] = { SIGTERM, SIGKILL };
1449 /* NB: should send a message to the session logger to avoid blocking. */
1450 logwtmp("~", "shutdown", "");
1452 for (sp = sessions; sp; sp = sp->se_next) {
1453 sp->se_flags |= SE_SHUTDOWN;
1454 kill(sp->se_process, SIGHUP);
1457 /* Try to run the rc.shutdown script within a period of time */
1460 for (i = 0; i < 2; ++i) {
1461 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1462 return (state_func_t) single_user;
1467 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1469 while (clang == 0 && errno != ECHILD);
1471 if (errno == ECHILD)
1472 return (state_func_t) single_user;
1475 warning("some processes would not die; ps axl advised");
1477 return (state_func_t) single_user;
1481 * Run the system shutdown script.
1483 * Exit codes: XXX I should document more
1484 * -2 shutdown script terminated abnormally
1485 * -1 fatal error - can't run script
1487 * >0 some error (exit code)
1494 int shutdowntimeout;
1497 struct sigaction sa;
1501 * rc.shutdown is optional, so to prevent any unnecessary
1502 * complaints from the shell we simply don't run it if the
1503 * file does not exist. If the stat() here fails for other
1504 * reasons, we'll let the shell complain.
1506 if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1509 if ((pid = fork()) == 0) {
1512 /* Assume that init already grab console as ctty before */
1514 sigemptyset(&sa.sa_mask);
1516 sa.sa_handler = SIG_IGN;
1517 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1518 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1520 if ((fd = open(_PATH_CONSOLE, O_RDWR)) == -1)
1521 warning("can't open %s: %m", _PATH_CONSOLE);
1531 * Run the shutdown script.
1534 argv[1] = _PATH_RUNDOWN;
1541 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1544 setprocresources(RESOURCE_RC);
1546 execv(_PATH_BSHELL, argv);
1547 warning("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNDOWN);
1548 _exit(1); /* force single user mode */
1552 emergency("can't fork for %s on %s: %m",
1553 _PATH_BSHELL, _PATH_RUNDOWN);
1554 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1556 sleep(STALL_TIMEOUT);
1560 len = sizeof(shutdowntimeout);
1561 if (sysctlbyname("kern.shutdown_timeout",
1563 &len, NULL, 0) == -1 || shutdowntimeout < 2)
1564 shutdowntimeout = DEATH_SCRIPT;
1565 alarm(shutdowntimeout);
1568 * Copied from single_user(). This is a bit paranoid.
1569 * Use the same ALRM handler.
1572 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1573 collect_child(wpid);
1575 /* we were waiting for the sub-shell */
1576 kill(wpid, SIGTERM);
1577 warning("timeout expired for %s on %s: %m; going to single user mode",
1578 _PATH_BSHELL, _PATH_RUNDOWN);
1584 warning("wait for %s on %s failed: %m; going to single user mode",
1585 _PATH_BSHELL, _PATH_RUNDOWN);
1588 if (wpid == pid && WIFSTOPPED(status)) {
1589 warning("init: %s on %s stopped, restarting\n",
1590 _PATH_BSHELL, _PATH_RUNDOWN);
1594 } while (wpid != pid && !clang);
1596 /* Turn off the alarm */
1599 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1600 requested_transition == catatonia) {
1602 * /etc/rc.shutdown executed /sbin/reboot;
1603 * wait for the end quietly
1612 if (!WIFEXITED(status)) {
1613 warning("%s on %s terminated abnormally, going to single user mode",
1614 _PATH_BSHELL, _PATH_RUNDOWN);
1618 if ((status = WEXITSTATUS(status)) != 0)
1619 warning("%s returned status %d", _PATH_RUNDOWN, status);
1637 while (c == ' ' || c == '\t' )
1647 while (c && c != '\'')
1649 if (!c) /* unterminated string */
1654 while (c && c != ' ' && c != '\t' )
1665 setprocresources(const char *cname)
1668 if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1669 setusercontext(lc, (struct passwd*)NULL, 0, LOGIN_SETPRIORITY|LOGIN_SETRESOURCES);