1 /* $NetBSD: init.c,v 1.97 2009/01/18 00:25:13 lukem Exp $ */
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
7 * This code is derived from software contributed to Berkeley by
8 * Donn Seeley at Berkeley Software Design, Inc.
10 * Redistribution and use in source and binary forms, with or without
11 * modification, are permitted provided that the following conditions
13 * 1. Redistributions of source code must retain the above copyright
14 * notice, this list of conditions and the following disclaimer.
15 * 2. Redistributions in binary form must reproduce the above copyright
16 * notice, this list of conditions and the following disclaimer in the
17 * documentation and/or other materials provided with the distribution.
18 * 3. Neither the name of the University nor the names of its contributors
19 * may be used to endorse or promote products derived from this software
20 * without specific prior written permission.
22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 #include <sys/cdefs.h>
37 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\
38 The Regents of the University of California. All rights reserved.");
43 static char sccsid
[] = "@(#)init.c 8.2 (Berkeley) 4/28/95";
45 __RCSID("$NetBSD: init.c,v 1.97 2009/01/18 00:25:13 lukem Exp $");
49 #include <sys/param.h>
50 #include <sys/sysctl.h>
54 #include <sys/mount.h>
55 #include <machine/cpu.h>
78 #include "pathnames.h"
81 #define STR(x) XSTR(x)
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 WINDOW_WAIT 3 /* wait N secs after starting window */
89 #define STALL_TIMEOUT 30 /* wait N secs after warning */
90 #define DEATH_WATCH 10 /* wait N secs for procs to die */
92 const struct timespec dtrtime
= {.tv_sec
= 0, .tv_nsec
= 250000};
94 #if defined(RESCUEDIR)
95 #define INIT_BSHELL RESCUEDIR "/sh"
96 #define INIT_MOUNT_MFS RESCUEDIR "/mount_mfs"
97 #define INIT_PATH RESCUEDIR ":" _PATH_STDPATH
99 #define INIT_BSHELL _PATH_BSHELL
100 #define INIT_MOUNT_MFS "/sbin/mount_mfs"
101 #define INIT_PATH _PATH_STDPATH
104 int main(int, char *[]);
106 void handle(sig_t
, ...);
107 void delset(sigset_t
*, ...);
109 void stall(const char *, ...)
110 __attribute__((__format__(__printf__
,1,2)));
111 void warning(const char *, ...)
112 __attribute__((__format__(__printf__
,1,2)));
113 void emergency(const char *, ...)
114 __attribute__((__format__(__printf__
,1,2)));
119 * We really need a recursive typedef...
120 * The following at least guarantees that the return type of (*state_t)()
121 * is sufficiently wide to hold a function pointer.
123 typedef long (*state_func_t
)(void);
124 typedef state_func_t (*state_t
)(void);
127 #define SINGLE_USER 's'
129 #define READ_TTYS 't'
130 #define MULTI_USER 'm'
131 #define CLEAN_TTYS 'T'
132 #define CATATONIA 'c'
134 state_func_t
single_user(void);
135 state_func_t
runcom(void);
136 state_func_t
read_ttys(void);
137 state_func_t
multi_user(void);
138 state_func_t
clean_ttys(void);
139 state_func_t
catatonia(void);
140 state_func_t
death(void);
142 enum { AUTOBOOT
, FASTBOOT
} runcom_mode
= AUTOBOOT
;
144 void transition(state_t
);
145 void setctty(const char *);
147 typedef struct init_session
{
148 int se_index
; /* index of entry in ttys file */
149 pid_t se_process
; /* controlling process */
150 struct timeval se_started
; /* used to avoid thrashing */
151 int se_flags
; /* status of session */
152 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
153 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
154 char *se_device
; /* filename of port */
155 char *se_getty
; /* what to run on that port */
156 char **se_getty_argv
; /* pre-parsed argument array */
157 char *se_window
; /* window system (started only once) */
158 char **se_window_argv
; /* pre-parsed argument array */
159 struct init_session
*se_prev
;
160 struct init_session
*se_next
;
163 void free_session(session_t
*);
164 session_t
*new_session(session_t
*, int, struct ttyent
*);
167 char **construct_argv(char *);
168 void start_window_system(session_t
*);
169 void collect_child(pid_t
, int);
170 pid_t
start_getty(session_t
*);
171 void transition_handler(int);
172 void alrm_handler(int);
173 void setsecuritylevel(int);
174 int getsecuritylevel(void);
175 int setupargv(session_t
*, struct ttyent
*);
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
);
184 int do_setttyent(void);
186 #ifndef LETS_GET_SMALL
187 state_t requested_transition
= runcom
;
189 void clear_session_logs(session_t
*, int);
190 state_func_t
runetcrc(int);
192 static struct timeval boot_time
;
193 state_t current_state
= death
;
194 static void session_utmpx(const session_t
*, int);
195 static void make_utmpx(const char *, const char *, int, pid_t
,
196 const struct timeval
*, int);
197 static char get_runlevel(const state_t
);
198 static void utmpx_set_runlevel(char, char);
202 int did_multiuser_chroot
= 0;
203 char rootdir
[PATH_MAX
];
204 int shouldchroot(void);
205 int createsysctlnode(void);
208 #else /* LETS_GET_SMALL */
209 state_t requested_transition
= single_user
;
210 #endif /* !LETS_GET_SMALL */
212 #ifdef MFS_DEV_IF_NO_CONSOLE
214 static int mfs_dev(void);
219 * The mother of all processes.
222 main(int argc
, char **argv
)
226 #ifndef LETS_GET_SMALL
230 (void)gettimeofday(&boot_time
, NULL
);
231 #endif /* SUPPORT_UTMPX */
233 /* Dispose of random users. */
239 /* System V users like to reexec init. */
241 errx(1, "already running");
245 * Create an initial session.
248 warn("initial setsid() failed");
251 * Establish an initial user so that programs running
252 * single user do not freak out and die (like passwd).
254 if (setlogin("root") < 0)
255 warn("setlogin() failed");
258 #ifdef MFS_DEV_IF_NO_CONSOLE
260 requested_transition
= single_user
;
263 #ifndef LETS_GET_SMALL
265 * Note that this does NOT open a file...
266 * Does 'init' deserve its own facility number?
268 openlog("init", LOG_CONS
, LOG_AUTH
);
269 #endif /* LETS_GET_SMALL */
272 #ifndef LETS_GET_SMALL
274 * This code assumes that we always get arguments through flags,
275 * never through bits set in some random machine register.
277 while ((c
= getopt(argc
, argv
, "sf")) != -1)
280 requested_transition
= single_user
;
283 runcom_mode
= FASTBOOT
;
286 warning("unrecognized flag `%c'", c
);
291 warning("ignoring excess arguments");
292 #else /* LETS_GET_SMALL */
293 requested_transition
= single_user
;
294 #endif /* LETS_GET_SMALL */
297 * We catch or block signals rather than ignore them,
298 * so that they get reset on exec.
300 handle(badsys
, SIGSYS
, 0);
301 handle(disaster
, SIGABRT
, SIGFPE
, SIGILL
, SIGSEGV
,
302 SIGBUS
, SIGXCPU
, SIGXFSZ
, 0);
303 handle(transition_handler
, SIGHUP
, SIGTERM
, SIGTSTP
, 0);
304 handle(alrm_handler
, SIGALRM
, 0);
305 (void)sigfillset(&mask
);
306 delset(&mask
, SIGABRT
, SIGFPE
, SIGILL
, SIGSEGV
, SIGBUS
, SIGSYS
,
307 SIGXCPU
, SIGXFSZ
, SIGHUP
, SIGTERM
, SIGTSTP
, SIGALRM
, 0);
308 (void)sigprocmask(SIG_SETMASK
, &mask
, NULL
);
309 (void)sigemptyset(&sa
.sa_mask
);
311 sa
.sa_handler
= SIG_IGN
;
312 (void)sigaction(SIGTTIN
, &sa
, NULL
);
313 (void)sigaction(SIGTTOU
, &sa
, NULL
);
322 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
323 /* Create "init.root" sysctl node. */
324 (void)createsysctlnode();
325 #endif /* !LETS_GET_SMALL && CHROOT*/
328 * Start the state machine.
330 transition(requested_transition
);
333 * Should never reach here.
339 * Associate a function with a signal handler.
342 handle(sig_t handler
, ...)
346 sigset_t mask_everything
;
349 va_start(ap
, handler
);
351 sa
.sa_handler
= handler
;
352 (void)sigfillset(&mask_everything
);
354 while ((sig
= va_arg(ap
, int)) != 0) {
355 sa
.sa_mask
= mask_everything
;
356 /* XXX SA_RESTART? */
357 sa
.sa_flags
= sig
== SIGCHLD
? SA_NOCLDSTOP
: 0;
358 (void)sigaction(sig
, &sa
, NULL
);
364 * Delete a set of signals from a mask.
367 delset(sigset_t
*maskp
, ...)
374 while ((sig
= va_arg(ap
, int)) != 0)
375 (void)sigdelset(maskp
, sig
);
379 #if 0 /* Enable to get error messages from init ! */
380 #define vsyslog(level, fmt, ap) print_console(level, fmt, ap)
384 print_console(int level
, const char *message
, va_list ap
)
387 * XXX: syslog seems to just plain not work in console-only
388 * XXX: situation... that should be fixed. Let's leave this
389 * XXX: note + code here in case someone gets in trouble and
390 * XXX: wants to debug. -- Jachym Holecek <freza@liberouter.org>
395 /* We can't do anything on errors, anyway... */
396 fd
= open(_PATH_CONSOLE
, O_WRONLY
);
400 /* %m will get lost... */
401 len
= vsnprintf(errbuf
, sizeof(errbuf
), message
, ap
);
402 (void)write(fd
, (void *)errbuf
, len
);
408 * Log a message and sleep for a while (to give someone an opportunity
409 * to read it and to save log or hardcopy output if the problem is chronic).
410 * NB: should send a message to the session logger to avoid blocking.
413 stall(const char *message
, ...)
417 va_start(ap
, message
);
418 vsyslog(LOG_ALERT
, message
, ap
);
421 (void)sleep(STALL_TIMEOUT
);
425 * Like stall(), but doesn't sleep.
426 * If cpp had variadic macros, the two functions could be #defines for another.
427 * NB: should send a message to the session logger to avoid blocking.
430 warning(const char *message
, ...)
434 va_start(ap
, message
);
435 vsyslog(LOG_ALERT
, message
, ap
);
441 * Log an emergency message.
442 * NB: should send a message to the session logger to avoid blocking.
445 emergency(const char *message
, ...)
449 va_start(ap
, message
);
450 vsyslog(LOG_EMERG
, message
, ap
);
456 * Catch a SIGSYS signal.
458 * These may arise if a system does not support sysctl.
459 * We tolerate up to 25 of these, then throw in the towel.
464 static int badcount
= 0;
472 * Catch an unexpected signal.
478 emergency("fatal signal: %s", strsignal(sig
));
479 (void)sleep(STALL_TIMEOUT
);
480 _exit(sig
); /* reboot */
484 * Get the security level of the kernel.
487 getsecuritylevel(void)
489 #ifdef KERN_SECURELVL
490 int name
[2], curlevel
;
494 name
[1] = KERN_SECURELVL
;
495 len
= sizeof curlevel
;
496 if (sysctl(name
, 2, &curlevel
, &len
, NULL
, 0) == -1) {
497 emergency("cannot get kernel security level: %m");
507 * Set the security level of the kernel.
510 setsecuritylevel(int newlevel
)
512 #ifdef KERN_SECURELVL
513 int name
[2], curlevel
;
515 curlevel
= getsecuritylevel();
516 if (newlevel
== curlevel
)
519 name
[1] = KERN_SECURELVL
;
520 if (sysctl(name
, 2, NULL
, NULL
, &newlevel
, sizeof newlevel
) == -1) {
521 emergency("cannot change kernel security level from"
522 " %d to %d: %m", curlevel
, newlevel
);
526 warning("kernel security level changed from %d to %d",
533 * Change states in the finite state machine.
534 * The initial state is passed as an argument.
537 transition(state_t s
)
544 #ifndef LETS_GET_SMALL
545 utmpx_set_runlevel(get_runlevel(current_state
),
554 #ifndef LETS_GET_SMALL
556 * Close out the accounting files for a login session.
557 * NB: should send a message to the session logger to avoid blocking.
560 clear_session_logs(session_t
*sp
, int status
)
562 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
563 char *line
= sp
->se_device
+ sizeof(_PATH_DEV
) - 1;
567 if (logoutx(line
, status
, DEAD_PROCESS
))
568 logwtmpx(line
, "", "", status
, DEAD_PROCESS
);
572 logwtmp(line
, "", "");
578 * Start a session and allocate a controlling terminal.
579 * Only called by children of init after forking.
582 setctty(const char *name
)
587 (void)nanosleep(&dtrtime
, NULL
); /* leave DTR low for a bit */
588 if ((fd
= open(name
, O_RDWR
)) == -1) {
589 stall("can't open %s: %m", name
);
592 if (login_tty(fd
) == -1) {
593 stall("can't get %s for controlling terminal: %m", name
);
599 * Bring the system up single user.
606 int from_securitylevel
;
608 struct sigaction sa
, satstp
, sahup
;
610 const char *shell
= INIT_BSHELL
;
616 char *clear
, *password
;
620 #endif /* ALTSHELL */
622 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
623 /* Clear previous idea, just in case. */
624 did_multiuser_chroot
= 0;
625 #endif /* !LETS_GET_SMALL && CHROOT */
628 * If the kernel is in secure mode, downgrade it to insecure mode.
630 from_securitylevel
= getsecuritylevel();
631 if (from_securitylevel
> 0)
634 (void)sigemptyset(&sa
.sa_mask
);
636 sa
.sa_handler
= SIG_IGN
;
637 (void)sigaction(SIGTSTP
, &sa
, &satstp
);
638 (void)sigaction(SIGHUP
, &sa
, &sahup
);
639 if ((pid
= fork()) == 0) {
641 * Start the single user session.
643 if (access(_PATH_CONSTTY
, F_OK
) == 0)
644 setctty(_PATH_CONSTTY
);
646 setctty(_PATH_CONSOLE
);
650 * Check the root password.
651 * We don't care if the console is 'on' by default;
652 * it's the only tty that can be 'off' and 'secure'.
654 typ
= getttynam("console");
655 pp
= getpwnam("root");
656 if (typ
&& (from_securitylevel
>=2 || (typ
->ty_status
657 & TTY_SECURE
) == 0) && pp
&& *pp
->pw_passwd
!= '\0') {
658 (void)fprintf(stderr
,
659 "Enter root password, or ^D to go multi-user\n");
661 clear
= getpass("Password:");
662 if (clear
== 0 || *clear
== '\0')
664 password
= crypt(clear
, pp
->pw_passwd
);
665 (void)memset(clear
, 0, _PASSWORD_LEN
);
666 if (strcmp(password
, pp
->pw_passwd
) == 0)
668 warning("single-user login failed");
676 (void)fprintf(stderr
,
677 "Enter pathname of shell or RETURN for %s: ", shell
);
678 if (fgets(altshell
, sizeof(altshell
), stdin
) == NULL
) {
684 if ((p
= strchr(altshell
, '\n')) != NULL
)
690 #endif /* ALTSHELL */
694 * We catch all the interesting ones,
695 * and those are reset to SIG_DFL on exec.
697 (void)sigemptyset(&mask
);
698 (void)sigprocmask(SIG_SETMASK
, &mask
, NULL
);
702 * If the default one doesn't work, try the Bourne shell.
706 (void)setenv("PATH", INIT_PATH
, 1);
710 (void)execv(shell
, __UNCONST(argv
));
711 emergency("can't exec `%s' for single user: %m", shell
);
713 #endif /* ALTSHELL */
714 (void)execv(INIT_BSHELL
, __UNCONST(argv
));
715 emergency("can't exec `%s' for single user: %m", INIT_BSHELL
);
716 (void)sleep(STALL_TIMEOUT
);
722 * We are seriously hosed. Do our best.
724 emergency("can't fork single-user shell: %m, trying again");
725 while (waitpid(-1, NULL
, WNOHANG
) > 0)
727 (void)sigaction(SIGTSTP
, &satstp
, NULL
);
728 (void)sigaction(SIGHUP
, &sahup
, NULL
);
729 return (state_func_t
)single_user
;
732 requested_transition
= 0;
734 if ((wpid
= waitpid(-1, &status
, WUNTRACED
)) != -1)
735 collect_child(wpid
, status
);
739 warning("wait for single-user shell failed: %m; "
741 return (state_func_t
)single_user
;
743 if (wpid
== pid
&& WIFSTOPPED(status
)) {
744 warning("shell stopped, restarting");
745 (void)kill(pid
, SIGCONT
);
748 } while (wpid
!= pid
&& !requested_transition
);
750 if (requested_transition
) {
751 (void)sigaction(SIGTSTP
, &satstp
, NULL
);
752 (void)sigaction(SIGHUP
, &sahup
, NULL
);
753 return (state_func_t
)requested_transition
;
756 if (WIFSIGNALED(status
)) {
757 if (WTERMSIG(status
) == SIGKILL
) {
758 /* executed /sbin/reboot; wait for the end quietly */
761 (void)sigfillset(&s
);
763 (void)sigsuspend(&s
);
765 warning("single user shell terminated (%x), restarting",
767 (void)sigaction(SIGTSTP
, &satstp
, NULL
);
768 (void)sigaction(SIGHUP
, &sahup
, NULL
);
769 return (state_func_t
)single_user
;
773 runcom_mode
= FASTBOOT
;
774 (void)sigaction(SIGTSTP
, &satstp
, NULL
);
775 (void)sigaction(SIGHUP
, &sahup
, NULL
);
776 #ifndef LETS_GET_SMALL
777 return (state_func_t
)runcom
;
778 #else /* LETS_GET_SMALL */
779 return (state_func_t
)single_user
;
780 #endif /* LETS_GET_SMALL */
783 #ifndef LETS_GET_SMALL
787 runetcrc(int trychroot
)
794 switch ((pid
= fork())) {
796 (void)sigemptyset(&sa
.sa_mask
);
798 sa
.sa_handler
= SIG_IGN
;
799 (void)sigaction(SIGTSTP
, &sa
, NULL
);
800 (void)sigaction(SIGHUP
, &sa
, NULL
);
802 setctty(_PATH_CONSOLE
);
805 argv
[1] = _PATH_RUNCOM
;
806 argv
[2] = (runcom_mode
== AUTOBOOT
? "autoboot" : 0);
809 (void)sigprocmask(SIG_SETMASK
, &sa
.sa_mask
, NULL
);
813 if (chroot(rootdir
) != 0) {
814 warning("failed to chroot to `%s': %m",
816 _exit(4); /* force single user mode */
820 (void)execv(INIT_BSHELL
, __UNCONST(argv
));
821 stall("can't exec `%s' for `%s': %m", INIT_BSHELL
, _PATH_RUNCOM
);
822 _exit(5); /* force single user mode */
825 emergency("can't fork for `%s' on `%s': %m", INIT_BSHELL
,
827 while (waitpid(-1, NULL
, WNOHANG
) > 0)
829 (void)sleep(STALL_TIMEOUT
);
830 return (state_func_t
)single_user
;
836 * Copied from single_user(). This is a bit paranoid.
839 if ((wpid
= waitpid(-1, &status
, WUNTRACED
)) != -1)
840 collect_child(wpid
, status
);
844 warning("wait for `%s' on `%s' failed: %m; going to "
845 "single user mode", INIT_BSHELL
, _PATH_RUNCOM
);
846 return (state_func_t
)single_user
;
848 if (wpid
== pid
&& WIFSTOPPED(status
)) {
849 warning("`%s' on `%s' stopped, restarting",
850 INIT_BSHELL
, _PATH_RUNCOM
);
851 (void)kill(pid
, SIGCONT
);
854 } while (wpid
!= pid
);
856 if (WIFSIGNALED(status
) && WTERMSIG(status
) == SIGTERM
&&
857 requested_transition
== catatonia
) {
858 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
861 (void)sigfillset(&s
);
863 (void)sigsuspend(&s
);
866 if (!WIFEXITED(status
)) {
867 warning("`%s' on `%s' terminated abnormally, going to "
868 "single user mode", INIT_BSHELL
, _PATH_RUNCOM
);
869 return (state_func_t
)single_user
;
872 if (WEXITSTATUS(status
))
873 return (state_func_t
)single_user
;
875 return (state_func_t
)read_ttys
;
879 * Run the system startup script.
884 state_func_t next_step
;
886 /* Run /etc/rc and choose next state depending on the result. */
887 next_step
= runetcrc(0);
888 if (next_step
!= (state_func_t
)read_ttys
)
889 return (state_func_t
)next_step
;
893 * If init.root sysctl does not point to "/", we'll chroot and run
894 * The Real(tm) /etc/rc now. Global variable rootdir will tell us
897 if (shouldchroot()) {
898 next_step
= runetcrc(1);
899 if (next_step
!= (state_func_t
)read_ttys
)
900 return (state_func_t
)next_step
;
902 did_multiuser_chroot
= 1;
904 did_multiuser_chroot
= 0;
909 * Regardless of whether in chroot or not, we booted successfuly.
910 * It's time to spawn gettys (ie. next_step's value at this point).
912 runcom_mode
= AUTOBOOT
; /* the default */
913 /* NB: should send a message to the session logger to avoid blocking. */
915 logwtmpx("~", "reboot", "", 0, INIT_PROCESS
);
918 logwtmp("~", "reboot", "");
920 return (state_func_t
)read_ttys
;
924 * Open the session database.
926 * NB: We could pass in the size here; is it necessary?
929 start_session_db(void)
932 if (session_db
&& (*session_db
->close
)(session_db
))
933 emergency("session database close: %m");
934 if ((session_db
= dbopen(NULL
, O_RDWR
, 0, DB_HASH
, NULL
)) == 0) {
935 emergency("session database open: %m");
943 * Add a new login session.
946 add_session(session_t
*sp
)
951 if (session_db
== NULL
)
954 key
.data
= &sp
->se_process
;
955 key
.size
= sizeof sp
->se_process
;
957 data
.size
= sizeof sp
;
959 if ((*session_db
->put
)(session_db
, &key
, &data
, 0))
960 emergency("insert %d: %m", sp
->se_process
);
962 session_utmpx(sp
, 1);
967 * Delete an old login session.
970 del_session(session_t
*sp
)
974 key
.data
= &sp
->se_process
;
975 key
.size
= sizeof sp
->se_process
;
977 if ((*session_db
->del
)(session_db
, &key
, 0))
978 emergency("delete %d: %m", sp
->se_process
);
980 session_utmpx(sp
, 0);
985 * Look up a login session by pid.
988 find_session(pid_t pid
)
994 if (session_db
== NULL
)
998 key
.size
= sizeof pid
;
999 if ((*session_db
->get
)(session_db
, &key
, &data
, 0) != 0)
1001 (void)memmove(&ret
, data
.data
, sizeof(ret
));
1006 * Construct an argument vector from a command line.
1009 construct_argv(char *command
)
1012 char **argv
= malloc(((strlen(command
) + 1) / 2 + 1) * sizeof (char *));
1013 static const char separators
[] = " \t";
1018 if ((argv
[argc
++] = strtok(command
, separators
)) == 0) {
1022 while ((argv
[argc
++] = strtok(NULL
, separators
)) != NULL
)
1028 * Deallocate a session descriptor.
1031 free_session(session_t
*sp
)
1034 free(sp
->se_device
);
1037 free(sp
->se_getty_argv
);
1039 if (sp
->se_window
) {
1040 free(sp
->se_window
);
1041 free(sp
->se_window_argv
);
1047 * Allocate a new session descriptor.
1050 new_session(session_t
*sprev
, int session_index
, struct ttyent
*typ
)
1054 if ((typ
->ty_status
& TTY_ON
) == 0 || typ
->ty_name
== NULL
||
1055 typ
->ty_getty
== NULL
)
1058 sp
= malloc(sizeof (session_t
));
1061 (void)memset(sp
, 0, sizeof *sp
);
1063 sp
->se_flags
= SE_PRESENT
;
1064 sp
->se_index
= session_index
;
1066 (void)asprintf(&sp
->se_device
, "%s%s", _PATH_DEV
, typ
->ty_name
);
1070 if (setupargv(sp
, typ
) == 0) {
1076 if (sprev
== NULL
) {
1080 sprev
->se_next
= sp
;
1081 sp
->se_prev
= sprev
;
1088 * Calculate getty and if useful window argv vectors.
1091 setupargv(session_t
*sp
, struct ttyent
*typ
)
1096 free(sp
->se_getty_argv
);
1098 (void)asprintf(&sp
->se_getty
, "%s %s", typ
->ty_getty
, typ
->ty_name
);
1101 sp
->se_getty_argv
= construct_argv(sp
->se_getty
);
1102 if (sp
->se_getty_argv
== NULL
) {
1103 warning("can't parse getty for port `%s'", sp
->se_device
);
1105 sp
->se_getty
= NULL
;
1108 if (typ
->ty_window
) {
1110 free(sp
->se_window
);
1111 sp
->se_window
= strdup(typ
->ty_window
);
1112 sp
->se_window_argv
= construct_argv(sp
->se_window
);
1113 if (sp
->se_window_argv
== NULL
) {
1114 warning("can't parse window for port `%s'",
1116 free(sp
->se_window
);
1117 sp
->se_window
= NULL
;
1125 * Walk the list of ttys and create sessions for each active line.
1130 int session_index
= 0;
1131 session_t
*sp
, *snext
;
1134 #ifdef SUPPORT_UTMPX
1135 if (sessions
== NULL
) {
1138 make_utmpx("", BOOT_MSG
, BOOT_TIME
, 0, &boot_time
, 0);
1141 * If wtmpx is not empty, pick the the down time from there
1143 if (stat(_PATH_WTMPX
, &st
) != -1 && st
.st_size
!= 0) {
1144 struct timeval down_time
;
1146 TIMESPEC_TO_TIMEVAL(&down_time
,
1147 st
.st_atime
> st
.st_mtime
?
1148 &st
.st_atimespec
: &st
.st_mtimespec
);
1149 make_utmpx("", DOWN_MSG
, DOWN_TIME
, 0, &down_time
, 0);
1154 * Destroy any previous session state.
1155 * There shouldn't be any, but just in case...
1157 for (sp
= sessions
; sp
; sp
= snext
) {
1158 #ifndef LETS_GET_SMALL
1160 clear_session_logs(sp
, 0);
1162 snext
= sp
->se_next
;
1167 if (start_session_db()) {
1168 warning("start_session_db failed, death");
1170 /* If /etc/rc ran in chroot, we want to kill any survivors. */
1171 if (did_multiuser_chroot
)
1172 return (state_func_t
)death
;
1175 return (state_func_t
)single_user
;
1178 (void)do_setttyent();
1181 * Allocate a session entry for each active port.
1182 * Note that sp starts at 0.
1184 while ((typ
= getttyent()) != NULL
)
1185 if ((snext
= new_session(sp
, ++session_index
, typ
)) != NULL
)
1189 return (state_func_t
)multi_user
;
1193 * Start a window system running.
1196 start_window_system(session_t
*sp
)
1201 if ((pid
= fork()) == -1) {
1202 emergency("can't fork for window system on port `%s': %m",
1204 /* hope that getty fails and we can try again */
1211 (void)sigemptyset(&mask
);
1212 (void)sigprocmask(SIG_SETMASK
, &mask
, NULL
);
1215 emergency("setsid failed (window): %m");
1217 (void)execv(sp
->se_window_argv
[0], sp
->se_window_argv
);
1218 stall("can't exec window system `%s' for port `%s': %m",
1219 sp
->se_window_argv
[0], sp
->se_device
);
1224 * Start a login session running.
1227 start_getty(session_t
*sp
)
1231 time_t current_time
= time(NULL
);
1234 * fork(), not vfork() -- we can't afford to block.
1236 if ((pid
= fork()) == -1) {
1237 emergency("can't fork for getty on port `%s': %m",
1246 /* If /etc/rc did proceed inside chroot, we have to try as well. */
1247 if (did_multiuser_chroot
)
1248 if (chroot(rootdir
) != 0) {
1249 stall("can't chroot getty `%s' inside `%s': %m",
1250 sp
->se_getty_argv
[0], rootdir
);
1255 if (current_time
> sp
->se_started
.tv_sec
&&
1256 current_time
- sp
->se_started
.tv_sec
< GETTY_SPACING
) {
1257 warning("getty repeating too quickly on port `%s', sleeping",
1259 (void)sleep(GETTY_SLEEP
);
1262 if (sp
->se_window
) {
1263 start_window_system(sp
);
1264 (void)sleep(WINDOW_WAIT
);
1267 (void)sigemptyset(&mask
);
1268 (void)sigprocmask(SIG_SETMASK
, &mask
, (sigset_t
*) 0);
1270 (void)execv(sp
->se_getty_argv
[0], sp
->se_getty_argv
);
1271 stall("can't exec getty `%s' for port `%s': %m",
1272 sp
->se_getty_argv
[0], sp
->se_device
);
1276 #ifdef SUPPORT_UTMPX
1278 session_utmpx(const session_t
*sp
, int add
)
1280 const char *name
= sp
->se_getty
? sp
->se_getty
:
1281 (sp
->se_window
? sp
->se_window
: "");
1282 const char *line
= sp
->se_device
+ sizeof(_PATH_DEV
) - 1;
1284 make_utmpx(name
, line
, add
? LOGIN_PROCESS
: DEAD_PROCESS
,
1285 sp
->se_process
, &sp
->se_started
, sp
->se_index
);
1289 make_utmpx(const char *name
, const char *line
, int type
, pid_t pid
,
1290 const struct timeval
*tv
, int session
)
1295 (void)memset(&ut
, 0, sizeof(ut
));
1296 (void)strlcpy(ut
.ut_name
, name
, sizeof(ut
.ut_name
));
1298 (void)strlcpy(ut
.ut_line
, line
, sizeof(ut
.ut_line
));
1303 (void)gettimeofday(&ut
.ut_tv
, NULL
);
1304 ut
.ut_session
= session
;
1306 eline
= line
+ strlen(line
);
1307 if ((size_t)(eline
- line
) >= sizeof(ut
.ut_id
))
1308 line
= eline
- sizeof(ut
.ut_id
);
1309 (void)strncpy(ut
.ut_id
, line
, sizeof(ut
.ut_id
));
1311 if (pututxline(&ut
) == NULL
)
1312 warning("can't add utmpx record for `%s': %m", ut
.ut_line
);
1317 get_runlevel(const state_t s
)
1319 if (s
== (state_t
)single_user
)
1321 if (s
== (state_t
)runcom
)
1323 if (s
== (state_t
)read_ttys
)
1325 if (s
== (state_t
)multi_user
)
1327 if (s
== (state_t
)clean_ttys
)
1329 if (s
== (state_t
)catatonia
)
1335 utmpx_set_runlevel(char old
, char new)
1340 * Don't record any transitions until we did the first transition
1341 * to read ttys, which is when we are guaranteed to have a read-write
1342 * /var. Perhaps use a different variable for this?
1344 if (sessions
== NULL
)
1347 (void)memset(&ut
, 0, sizeof(ut
));
1348 (void)snprintf(ut
.ut_line
, sizeof(ut
.ut_line
), RUNLVL_MSG
, new);
1349 ut
.ut_type
= RUN_LVL
;
1350 (void)gettimeofday(&ut
.ut_tv
, NULL
);
1351 ut
.ut_exit
.e_exit
= old
;
1352 ut
.ut_exit
.e_termination
= new;
1353 if (pututxline(&ut
) == NULL
)
1354 warning("can't add utmpx record for `runlevel': %m");
1357 #endif /* SUPPORT_UTMPX */
1359 #endif /* LETS_GET_SMALL */
1362 * Collect exit status for a child.
1363 * If an exiting login, start a new login running.
1366 collect_child(pid_t pid
, int status
)
1368 #ifndef LETS_GET_SMALL
1369 session_t
*sp
, *sprev
, *snext
;
1374 if ((sp
= find_session(pid
)) == NULL
)
1377 clear_session_logs(sp
, status
);
1381 if (sp
->se_flags
& SE_SHUTDOWN
) {
1382 if ((sprev
= sp
->se_prev
) != NULL
)
1383 sprev
->se_next
= sp
->se_next
;
1385 sessions
= sp
->se_next
;
1386 if ((snext
= sp
->se_next
) != NULL
)
1387 snext
->se_prev
= sp
->se_prev
;
1392 if ((pid
= start_getty(sp
)) == -1) {
1393 /* serious trouble */
1394 requested_transition
= clean_ttys
;
1398 sp
->se_process
= pid
;
1399 (void)gettimeofday(&sp
->se_started
, NULL
);
1401 #endif /* LETS_GET_SMALL */
1405 * Catch a signal and request a state transition.
1408 transition_handler(int sig
)
1412 #ifndef LETS_GET_SMALL
1414 requested_transition
= clean_ttys
;
1417 requested_transition
= death
;
1420 requested_transition
= catatonia
;
1422 #endif /* LETS_GET_SMALL */
1424 requested_transition
= 0;
1429 #ifndef LETS_GET_SMALL
1431 * Take the system multiuser.
1440 requested_transition
= 0;
1443 * If the administrator has not set the security level to -1
1444 * to indicate that the kernel should not run multiuser in secure
1445 * mode, and the run script has not set a higher level of security
1446 * than level 1, then put the kernel into secure mode.
1448 if (getsecuritylevel() == 0)
1449 setsecuritylevel(1);
1451 for (sp
= sessions
; sp
; sp
= sp
->se_next
) {
1454 if ((pid
= start_getty(sp
)) == -1) {
1455 /* serious trouble */
1456 requested_transition
= clean_ttys
;
1459 sp
->se_process
= pid
;
1460 (void)gettimeofday(&sp
->se_started
, NULL
);
1464 while (!requested_transition
)
1465 if ((pid
= waitpid(-1, &status
, 0)) != -1)
1466 collect_child(pid
, status
);
1468 return (state_func_t
)requested_transition
;
1472 * This is an n-squared algorithm. We hope it isn't run often...
1477 session_t
*sp
, *sprev
;
1479 int session_index
= 0;
1482 for (sp
= sessions
; sp
; sp
= sp
->se_next
)
1483 sp
->se_flags
&= ~SE_PRESENT
;
1485 (void)do_setttyent();
1487 devlen
= sizeof(_PATH_DEV
) - 1;
1488 while ((typ
= getttyent()) != NULL
) {
1491 for (sprev
= 0, sp
= sessions
; sp
; sprev
= sp
, sp
= sp
->se_next
)
1492 if (strcmp(typ
->ty_name
, sp
->se_device
+ devlen
) == 0)
1496 sp
->se_flags
|= SE_PRESENT
;
1497 if (sp
->se_index
!= session_index
) {
1498 warning("port `%s' changed utmp index from "
1499 "%d to %d", sp
->se_device
, sp
->se_index
,
1501 sp
->se_index
= session_index
;
1503 if ((typ
->ty_status
& TTY_ON
) == 0 ||
1504 typ
->ty_getty
== 0) {
1505 sp
->se_flags
|= SE_SHUTDOWN
;
1506 if (sp
->se_process
!= 0)
1507 (void)kill(sp
->se_process
, SIGHUP
);
1510 sp
->se_flags
&= ~SE_SHUTDOWN
;
1511 if (setupargv(sp
, typ
) == 0) {
1512 warning("can't parse getty for port `%s'",
1514 sp
->se_flags
|= SE_SHUTDOWN
;
1515 if (sp
->se_process
!= 0)
1516 (void)kill(sp
->se_process
, SIGHUP
);
1521 (void)new_session(sprev
, session_index
, typ
);
1526 for (sp
= sessions
; sp
; sp
= sp
->se_next
)
1527 if ((sp
->se_flags
& SE_PRESENT
) == 0) {
1528 sp
->se_flags
|= SE_SHUTDOWN
;
1529 if (sp
->se_process
!= 0)
1530 (void)kill(sp
->se_process
, SIGHUP
);
1533 return (state_func_t
)multi_user
;
1537 * Block further logins.
1544 for (sp
= sessions
; sp
; sp
= sp
->se_next
)
1545 sp
->se_flags
|= SE_SHUTDOWN
;
1547 return (state_func_t
)multi_user
;
1549 #endif /* LETS_GET_SMALL */
1556 alrm_handler(int sig
)
1562 #ifndef LETS_GET_SMALL
1564 * Bring the system down to single user.
1572 static const int death_sigs
[3] = { SIGHUP
, SIGTERM
, SIGKILL
};
1574 for (sp
= sessions
; sp
; sp
= sp
->se_next
)
1575 sp
->se_flags
|= SE_SHUTDOWN
;
1577 /* NB: should send a message to the session logger to avoid blocking. */
1578 #ifdef SUPPORT_UTMPX
1579 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS
);
1582 logwtmp("~", "shutdown", "");
1585 for (i
= 0; i
< 3; ++i
) {
1586 if (kill(-1, death_sigs
[i
]) == -1 && errno
== ESRCH
)
1587 return (state_func_t
)single_user
;
1590 (void)alarm(DEATH_WATCH
);
1592 if ((pid
= waitpid(-1, &status
, 0)) != -1)
1593 collect_child(pid
, status
);
1594 while (clang
== 0 && errno
!= ECHILD
);
1596 if (errno
== ECHILD
)
1597 return (state_func_t
)single_user
;
1600 warning("some processes would not die; ps axl advised");
1602 return (state_func_t
)single_user
;
1604 #endif /* LETS_GET_SMALL */
1606 #ifdef MFS_DEV_IF_NO_CONSOLE
1612 * We cannot print errors so we bail out silently...
1617 /* If we have /dev/console, assume all is OK */
1618 if (access(_PATH_CONSOLE
, F_OK
) == 0)
1621 #if 0 /* Useful for testing MAKEDEV */
1622 /* Mount an mfs over /mnt so we can create a console entry */
1623 switch ((pid
= fork())) {
1625 (void)execl(INIT_MOUNT_MFS
, "mount_mfs",
1626 "-b", "4096", "-f", "512",
1629 "swap", "/mnt", NULL
);
1637 if (waitpid(pid
, &status
, 0) == -1)
1647 static int name
[2] = { CTL_MACHDEP
, CPU_CONSDEV
};
1650 if (sysctl(name
, sizeof(name
) / sizeof(name
[0]), &dev
, &olen
,
1653 dev
= makedev(0, 0);
1655 /* Make a console for us, so we can see things happening */
1656 if (mknod("/mnt/console", 0666 | S_IFCHR
, dev
) == -1)
1658 (void)freopen("/mnt/console", "a", stderr
);
1663 /* Run the makedev script to create devices */
1664 switch ((pid
= fork())) {
1666 (void)dup2(2, 1); /* Give the script stdout */
1667 if (chdir("/dev") == 0)
1668 (void)execl(INIT_BSHELL
, "sh",
1669 access("./MAKEDEV", X_OK
) == 0
1670 ? "./MAKEDEV" : "/etc/MAKEDEV",
1671 "-MM", "init", NULL
);
1679 if (waitpid(pid
, &status
, 0) == -1)
1682 warn("MAKEDEV exit status %d\n", status
);
1684 * If /dev/console got created, then return 0
1685 * regardless of MAKEDEV exit status.
1687 if (access(_PATH_CONSOLE
, F_OK
) == 0)
1691 warn("Unable to run MAKEDEV");
1701 if (did_multiuser_chroot
) {
1702 char path
[PATH_MAX
];
1704 (void)snprintf(path
, sizeof(path
), "%s/%s", rootdir
, _PATH_TTYS
);
1706 return setttyentpath(path
);
1712 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
1717 struct sysctlnode node
;
1722 * Create top-level dynamic sysctl node. Its child nodes will only
1723 * be readable by the superuser, since regular mortals should not
1724 * care ("Sssh, it's a secret!").
1726 len
= sizeof(struct sysctlnode
);
1727 mib
[0] = CTL_CREATE
;
1729 (void)memset(&node
, 0, len
);
1730 node
.sysctl_flags
= SYSCTL_VERSION
| CTLFLAG_READWRITE
|
1731 CTLFLAG_PRIVATE
| CTLTYPE_NODE
;
1732 node
.sysctl_num
= CTL_CREATE
;
1733 (void)snprintf(node
.sysctl_name
, SYSCTL_NAMELEN
, "init");
1734 if (sysctl(&mib
[0], 1, &node
, &len
, &node
, len
) == -1) {
1735 warning("could not create init node: %m");
1740 * Create second level dynamic node capable of holding pathname.
1741 * Provide "/" as the default value.
1743 len
= sizeof(struct sysctlnode
);
1744 mib
[0] = node
.sysctl_num
;
1745 mib
[1] = CTL_CREATE
;
1747 (void)memset(&node
, 0, len
);
1748 node
.sysctl_flags
= SYSCTL_VERSION
| CTLFLAG_READWRITE
|
1749 CTLTYPE_STRING
| CTLFLAG_OWNDATA
;
1750 node
.sysctl_size
= _POSIX_PATH_MAX
;
1751 node
.sysctl_data
= __UNCONST("/");
1752 node
.sysctl_num
= CTL_CREATE
;
1753 (void)snprintf(node
.sysctl_name
, SYSCTL_NAMELEN
, "root");
1754 if (sysctl(&mib
[0], 2, NULL
, NULL
, &node
, len
) == -1) {
1755 warning("could not create init.root node: %m");
1765 struct sysctlnode node
;
1769 len
= sizeof(struct sysctlnode
);
1771 if (sysctlbyname("init.root", rootdir
, &len
, NULL
, 0) == -1) {
1772 warning("could not read init.root: %m");
1774 /* Child killed our node. Recreate it. */
1775 if (errno
== ENOENT
) {
1776 /* Destroy whatever is left, recreate from scratch. */
1777 if (sysctlnametomib("init", &mib
, &cnt
) != -1) {
1778 (void)memset(&node
, 0, sizeof(node
));
1779 node
.sysctl_flags
= SYSCTL_VERSION
;
1780 node
.sysctl_num
= mib
;
1783 (void)sysctl(&mib
, 1, NULL
, NULL
, &node
,
1787 (void)createsysctlnode();
1790 /* We certainly won't chroot. */
1794 if (rootdir
[len
] != '\0' || strlen(rootdir
) != len
- 1) {
1795 warning("init.root is not a string");
1799 if (strcmp(rootdir
, "/") == 0)
1805 #endif /* !LETS_GET_SMALL && CHROOT */