snj doesn't like my accent, so use proper English month names.
[netbsd-mini2440.git] / sbin / init / init.c
blob1e29052ea6b1cda300cb9d8a39418928986bbc35
1 /* $NetBSD: init.c,v 1.97 2009/01/18 00:25:13 lukem Exp $ */
3 /*-
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
12 * are met:
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
32 * SUCH DAMAGE.
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\
38 The Regents of the University of California. All rights reserved.");
39 #endif /* not lint */
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)init.c 8.2 (Berkeley) 4/28/95";
44 #else
45 __RCSID("$NetBSD: init.c,v 1.97 2009/01/18 00:25:13 lukem Exp $");
46 #endif
47 #endif /* not lint */
49 #include <sys/param.h>
50 #include <sys/sysctl.h>
51 #include <sys/wait.h>
52 #include <sys/mman.h>
53 #include <sys/stat.h>
54 #include <sys/mount.h>
55 #include <machine/cpu.h>
57 #include <db.h>
58 #include <errno.h>
59 #include <fcntl.h>
60 #include <signal.h>
61 #include <stdio.h>
62 #include <stdlib.h>
63 #include <string.h>
64 #include <syslog.h>
65 #include <time.h>
66 #include <ttyent.h>
67 #include <unistd.h>
68 #include <util.h>
69 #include <paths.h>
70 #include <err.h>
72 #include <stdarg.h>
74 #ifdef SECURE
75 #include <pwd.h>
76 #endif
78 #include "pathnames.h"
80 #define XSTR(x) #x
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
98 #else
99 #define INIT_BSHELL _PATH_BSHELL
100 #define INIT_MOUNT_MFS "/sbin/mount_mfs"
101 #define INIT_PATH _PATH_STDPATH
102 #endif
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)));
115 void disaster(int);
116 void badsys(int);
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);
126 #define DEATH 'd'
127 #define SINGLE_USER 's'
128 #define RUNCOM 'r'
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;
161 } session_t;
163 void free_session(session_t *);
164 session_t *new_session(session_t *, int, struct ttyent *);
165 session_t *sessions;
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 *);
176 int clang;
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);
182 DB *session_db;
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);
191 #ifdef SUPPORT_UTMPX
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);
199 #endif
201 #ifdef CHROOT
202 int did_multiuser_chroot = 0;
203 char rootdir[PATH_MAX];
204 int shouldchroot(void);
205 int createsysctlnode(void);
206 #endif /* CHROOT */
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);
216 #endif
219 * The mother of all processes.
222 main(int argc, char **argv)
224 struct sigaction sa;
225 sigset_t mask;
226 #ifndef LETS_GET_SMALL
227 int c;
229 #ifdef SUPPORT_UTMPX
230 (void)gettimeofday(&boot_time, NULL);
231 #endif /* SUPPORT_UTMPX */
233 /* Dispose of random users. */
234 if (getuid() != 0) {
235 errno = EPERM;
236 err(1, NULL);
239 /* System V users like to reexec init. */
240 if (getpid() != 1)
241 errx(1, "already running");
242 #endif
245 * Create an initial session.
247 if (setsid() < 0)
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
259 if (mfs_dev() == -1)
260 requested_transition = single_user;
261 #endif
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)
278 switch (c) {
279 case 's':
280 requested_transition = single_user;
281 break;
282 case 'f':
283 runcom_mode = FASTBOOT;
284 break;
285 default:
286 warning("unrecognized flag `%c'", c);
287 break;
290 if (optind != argc)
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);
310 sa.sa_flags = 0;
311 sa.sa_handler = SIG_IGN;
312 (void)sigaction(SIGTTIN, &sa, NULL);
313 (void)sigaction(SIGTTOU, &sa, NULL);
316 * Paranoia.
318 (void)close(0);
319 (void)close(1);
320 (void)close(2);
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.
335 return 1;
339 * Associate a function with a signal handler.
341 void
342 handle(sig_t handler, ...)
344 int sig;
345 struct sigaction sa;
346 sigset_t mask_everything;
347 va_list ap;
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);
360 va_end(ap);
364 * Delete a set of signals from a mask.
366 void
367 delset(sigset_t *maskp, ...)
369 int sig;
370 va_list ap;
372 va_start(ap, maskp);
374 while ((sig = va_arg(ap, int)) != 0)
375 (void)sigdelset(maskp, sig);
376 va_end(ap);
379 #if 0 /* Enable to get error messages from init ! */
380 #define vsyslog(level, fmt, ap) print_console(level, fmt, ap)
381 #define closelog()
383 static void
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>
392 char errbuf[1024];
393 int fd, len;
395 /* We can't do anything on errors, anyway... */
396 fd = open(_PATH_CONSOLE, O_WRONLY);
397 if (fd == -1)
398 return ;
400 /* %m will get lost... */
401 len = vsnprintf(errbuf, sizeof(errbuf), message, ap);
402 (void)write(fd, (void *)errbuf, len);
403 (void)close(fd);
405 #endif
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.
412 void
413 stall(const char *message, ...)
415 va_list ap;
417 va_start(ap, message);
418 vsyslog(LOG_ALERT, message, ap);
419 va_end(ap);
420 closelog();
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.
429 void
430 warning(const char *message, ...)
432 va_list ap;
434 va_start(ap, message);
435 vsyslog(LOG_ALERT, message, ap);
436 va_end(ap);
437 closelog();
441 * Log an emergency message.
442 * NB: should send a message to the session logger to avoid blocking.
444 void
445 emergency(const char *message, ...)
447 va_list ap;
449 va_start(ap, message);
450 vsyslog(LOG_EMERG, message, ap);
451 va_end(ap);
452 closelog();
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.
461 void
462 badsys(int sig)
464 static int badcount = 0;
466 if (badcount++ < 25)
467 return;
468 disaster(sig);
472 * Catch an unexpected signal.
474 void
475 disaster(int sig)
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;
491 size_t len;
493 name[0] = CTL_KERN;
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");
498 return -1;
500 return curlevel;
501 #else
502 return -1;
503 #endif
507 * Set the security level of the kernel.
509 void
510 setsecuritylevel(int newlevel)
512 #ifdef KERN_SECURELVL
513 int name[2], curlevel;
515 curlevel = getsecuritylevel();
516 if (newlevel == curlevel)
517 return;
518 name[0] = CTL_KERN;
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);
523 return;
525 #ifdef SECURE
526 warning("kernel security level changed from %d to %d",
527 curlevel, newlevel);
528 #endif
529 #endif
533 * Change states in the finite state machine.
534 * The initial state is passed as an argument.
536 void
537 transition(state_t s)
540 if (s == NULL)
541 return;
542 for (;;) {
543 #ifdef SUPPORT_UTMPX
544 #ifndef LETS_GET_SMALL
545 utmpx_set_runlevel(get_runlevel(current_state),
546 get_runlevel(s));
547 current_state = s;
548 #endif
549 #endif
550 s = (state_t)(*s)();
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.
559 void
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;
564 #endif
566 #ifdef SUPPORT_UTMPX
567 if (logoutx(line, status, DEAD_PROCESS))
568 logwtmpx(line, "", "", status, DEAD_PROCESS);
569 #endif
570 #ifdef SUPPORT_UTMP
571 if (logout(line))
572 logwtmp(line, "", "");
573 #endif
575 #endif
578 * Start a session and allocate a controlling terminal.
579 * Only called by children of init after forking.
581 void
582 setctty(const char *name)
584 int fd;
586 (void)revoke(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);
590 _exit(1);
592 if (login_tty(fd) == -1) {
593 stall("can't get %s for controlling terminal: %m", name);
594 _exit(2);
599 * Bring the system up single user.
601 state_func_t
602 single_user(void)
604 pid_t pid, wpid;
605 int status;
606 int from_securitylevel;
607 sigset_t mask;
608 struct sigaction sa, satstp, sahup;
609 #ifdef ALTSHELL
610 const char *shell = INIT_BSHELL;
611 #endif
612 const char *argv[2];
613 #ifdef SECURE
614 struct ttyent *typ;
615 struct passwd *pp;
616 char *clear, *password;
617 #endif
618 #ifdef ALTSHELL
619 char altshell[128];
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)
632 setsecuritylevel(0);
634 (void)sigemptyset(&sa.sa_mask);
635 sa.sa_flags = 0;
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);
645 else
646 setctty(_PATH_CONSOLE);
648 #ifdef SECURE
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");
660 for (;;) {
661 clear = getpass("Password:");
662 if (clear == 0 || *clear == '\0')
663 _exit(0);
664 password = crypt(clear, pp->pw_passwd);
665 (void)memset(clear, 0, _PASSWORD_LEN);
666 if (strcmp(password, pp->pw_passwd) == 0)
667 break;
668 warning("single-user login failed");
671 (void)endttyent();
672 endpwent();
673 #endif /* SECURE */
675 #ifdef ALTSHELL
676 (void)fprintf(stderr,
677 "Enter pathname of shell or RETURN for %s: ", shell);
678 if (fgets(altshell, sizeof(altshell), stdin) == NULL) {
679 altshell[0] = '\0';
680 } else {
681 /* nuke \n */
682 char *p;
684 if ((p = strchr(altshell, '\n')) != NULL)
685 *p = '\0';
688 if (altshell[0])
689 shell = altshell;
690 #endif /* ALTSHELL */
693 * Unblock signals.
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);
701 * Fire off a shell.
702 * If the default one doesn't work, try the Bourne shell.
704 argv[0] = "-sh";
705 argv[1] = 0;
706 (void)setenv("PATH", INIT_PATH, 1);
707 #ifdef ALTSHELL
708 if (altshell[0])
709 argv[0] = altshell;
710 (void)execv(shell, __UNCONST(argv));
711 emergency("can't exec `%s' for single user: %m", shell);
712 argv[0] = "-sh";
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);
717 _exit(3);
720 if (pid == -1) {
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)
726 continue;
727 (void)sigaction(SIGTSTP, &satstp, NULL);
728 (void)sigaction(SIGHUP, &sahup, NULL);
729 return (state_func_t)single_user;
732 requested_transition = 0;
733 do {
734 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
735 collect_child(wpid, status);
736 if (wpid == -1) {
737 if (errno == EINTR)
738 continue;
739 warning("wait for single-user shell failed: %m; "
740 "restarting");
741 return (state_func_t)single_user;
743 if (wpid == pid && WIFSTOPPED(status)) {
744 warning("shell stopped, restarting");
745 (void)kill(pid, SIGCONT);
746 wpid = -1;
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 */
759 sigset_t s;
761 (void)sigfillset(&s);
762 for (;;)
763 (void)sigsuspend(&s);
764 } else {
765 warning("single user shell terminated (%x), restarting",
766 status);
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
785 /* ARGSUSED */
786 state_func_t
787 runetcrc(int trychroot)
789 pid_t pid, wpid;
790 int status;
791 const char *argv[4];
792 struct sigaction sa;
794 switch ((pid = fork())) {
795 case 0:
796 (void)sigemptyset(&sa.sa_mask);
797 sa.sa_flags = 0;
798 sa.sa_handler = SIG_IGN;
799 (void)sigaction(SIGTSTP, &sa, NULL);
800 (void)sigaction(SIGHUP, &sa, NULL);
802 setctty(_PATH_CONSOLE);
804 argv[0] = "sh";
805 argv[1] = _PATH_RUNCOM;
806 argv[2] = (runcom_mode == AUTOBOOT ? "autoboot" : 0);
807 argv[3] = 0;
809 (void)sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
811 #ifdef CHROOT
812 if (trychroot)
813 if (chroot(rootdir) != 0) {
814 warning("failed to chroot to `%s': %m",
815 rootdir);
816 _exit(4); /* force single user mode */
818 #endif /* CHROOT */
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 */
823 /*NOTREACHED*/
824 case -1:
825 emergency("can't fork for `%s' on `%s': %m", INIT_BSHELL,
826 _PATH_RUNCOM);
827 while (waitpid(-1, NULL, WNOHANG) > 0)
828 continue;
829 (void)sleep(STALL_TIMEOUT);
830 return (state_func_t)single_user;
831 default:
832 break;
836 * Copied from single_user(). This is a bit paranoid.
838 do {
839 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
840 collect_child(wpid, status);
841 if (wpid == -1) {
842 if (errno == EINTR)
843 continue;
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);
852 wpid = -1;
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 */
859 sigset_t s;
861 (void)sigfillset(&s);
862 for (;;)
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.
881 state_func_t
882 runcom(void)
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;
891 #ifdef CHROOT
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
895 * where to go.
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;
903 } else {
904 did_multiuser_chroot = 0;
906 #endif /* CHROOT */
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. */
914 #ifdef SUPPORT_UTMPX
915 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
916 #endif
917 #ifdef SUPPORT_UTMP
918 logwtmp("~", "reboot", "");
919 #endif
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");
936 return 1;
938 return 0;
943 * Add a new login session.
945 void
946 add_session(session_t *sp)
948 DBT key;
949 DBT data;
951 if (session_db == NULL)
952 return;
954 key.data = &sp->se_process;
955 key.size = sizeof sp->se_process;
956 data.data = &sp;
957 data.size = sizeof sp;
959 if ((*session_db->put)(session_db, &key, &data, 0))
960 emergency("insert %d: %m", sp->se_process);
961 #ifdef SUPPORT_UTMPX
962 session_utmpx(sp, 1);
963 #endif
967 * Delete an old login session.
969 void
970 del_session(session_t *sp)
972 DBT key;
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);
979 #ifdef SUPPORT_UTMPX
980 session_utmpx(sp, 0);
981 #endif
985 * Look up a login session by pid.
987 session_t *
988 find_session(pid_t pid)
990 DBT key;
991 DBT data;
992 session_t *ret;
994 if (session_db == NULL)
995 return NULL;
997 key.data = &pid;
998 key.size = sizeof pid;
999 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1000 return 0;
1001 (void)memmove(&ret, data.data, sizeof(ret));
1002 return ret;
1006 * Construct an argument vector from a command line.
1008 char **
1009 construct_argv(char *command)
1011 int argc = 0;
1012 char **argv = malloc(((strlen(command) + 1) / 2 + 1) * sizeof (char *));
1013 static const char separators[] = " \t";
1015 if (argv == NULL)
1016 return NULL;
1018 if ((argv[argc++] = strtok(command, separators)) == 0) {
1019 free(argv);
1020 return NULL;
1022 while ((argv[argc++] = strtok(NULL, separators)) != NULL)
1023 continue;
1024 return argv;
1028 * Deallocate a session descriptor.
1030 void
1031 free_session(session_t *sp)
1034 free(sp->se_device);
1035 if (sp->se_getty) {
1036 free(sp->se_getty);
1037 free(sp->se_getty_argv);
1039 if (sp->se_window) {
1040 free(sp->se_window);
1041 free(sp->se_window_argv);
1043 free(sp);
1047 * Allocate a new session descriptor.
1049 session_t *
1050 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1052 session_t *sp;
1054 if ((typ->ty_status & TTY_ON) == 0 || typ->ty_name == NULL ||
1055 typ->ty_getty == NULL)
1056 return NULL;
1058 sp = malloc(sizeof (session_t));
1059 if (sp == NULL)
1060 return NULL;
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);
1067 if (!sp->se_device)
1068 return NULL;
1070 if (setupargv(sp, typ) == 0) {
1071 free_session(sp);
1072 return NULL;
1075 sp->se_next = NULL;
1076 if (sprev == NULL) {
1077 sessions = sp;
1078 sp->se_prev = NULL;
1079 } else {
1080 sprev->se_next = sp;
1081 sp->se_prev = sprev;
1084 return sp;
1088 * Calculate getty and if useful window argv vectors.
1091 setupargv(session_t *sp, struct ttyent *typ)
1094 if (sp->se_getty) {
1095 free(sp->se_getty);
1096 free(sp->se_getty_argv);
1098 (void)asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1099 if (!sp->se_getty)
1100 return 0;
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);
1104 free(sp->se_getty);
1105 sp->se_getty = NULL;
1106 return 0;
1108 if (typ->ty_window) {
1109 if (sp->se_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'",
1115 sp->se_device);
1116 free(sp->se_window);
1117 sp->se_window = NULL;
1118 return 0;
1121 return 1;
1125 * Walk the list of ttys and create sessions for each active line.
1127 state_func_t
1128 read_ttys(void)
1130 int session_index = 0;
1131 session_t *sp, *snext;
1132 struct ttyent *typ;
1134 #ifdef SUPPORT_UTMPX
1135 if (sessions == NULL) {
1136 struct stat st;
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);
1152 #endif
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
1159 if (sp->se_process)
1160 clear_session_logs(sp, 0);
1161 #endif
1162 snext = sp->se_next;
1163 free_session(sp);
1165 sessions = NULL;
1167 if (start_session_db()) {
1168 warning("start_session_db failed, death");
1169 #ifdef CHROOT
1170 /* If /etc/rc ran in chroot, we want to kill any survivors. */
1171 if (did_multiuser_chroot)
1172 return (state_func_t)death;
1173 else
1174 #endif /* CHROOT */
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)
1186 sp = snext;
1187 (void)endttyent();
1189 return (state_func_t)multi_user;
1193 * Start a window system running.
1195 void
1196 start_window_system(session_t *sp)
1198 pid_t pid;
1199 sigset_t mask;
1201 if ((pid = fork()) == -1) {
1202 emergency("can't fork for window system on port `%s': %m",
1203 sp->se_device);
1204 /* hope that getty fails and we can try again */
1205 return;
1208 if (pid)
1209 return;
1211 (void)sigemptyset(&mask);
1212 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
1214 if (setsid() < 0)
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);
1220 _exit(6);
1224 * Start a login session running.
1226 pid_t
1227 start_getty(session_t *sp)
1229 pid_t pid;
1230 sigset_t mask;
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",
1238 sp->se_device);
1239 return -1;
1242 if (pid)
1243 return pid;
1245 #ifdef CHROOT
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);
1251 _exit(7);
1253 #endif /* CHROOT */
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",
1258 sp->se_device);
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);
1273 _exit(8);
1274 /*NOTREACHED*/
1276 #ifdef SUPPORT_UTMPX
1277 static void
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);
1288 static void
1289 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1290 const struct timeval *tv, int session)
1292 struct utmpx ut;
1293 const char *eline;
1295 (void)memset(&ut, 0, sizeof(ut));
1296 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1297 ut.ut_type = type;
1298 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1299 ut.ut_pid = pid;
1300 if (tv)
1301 ut.ut_tv = *tv;
1302 else
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);
1313 endutxent();
1316 static char
1317 get_runlevel(const state_t s)
1319 if (s == (state_t)single_user)
1320 return SINGLE_USER;
1321 if (s == (state_t)runcom)
1322 return RUNCOM;
1323 if (s == (state_t)read_ttys)
1324 return READ_TTYS;
1325 if (s == (state_t)multi_user)
1326 return MULTI_USER;
1327 if (s == (state_t)clean_ttys)
1328 return CLEAN_TTYS;
1329 if (s == (state_t)catatonia)
1330 return CATATONIA;
1331 return DEATH;
1334 static void
1335 utmpx_set_runlevel(char old, char new)
1337 struct utmpx ut;
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)
1345 return;
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");
1355 endutxent();
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.
1365 void
1366 collect_child(pid_t pid, int status)
1368 #ifndef LETS_GET_SMALL
1369 session_t *sp, *sprev, *snext;
1371 if (! sessions)
1372 return;
1374 if ((sp = find_session(pid)) == NULL)
1375 return;
1377 clear_session_logs(sp, status);
1378 del_session(sp);
1379 sp->se_process = 0;
1381 if (sp->se_flags & SE_SHUTDOWN) {
1382 if ((sprev = sp->se_prev) != NULL)
1383 sprev->se_next = sp->se_next;
1384 else
1385 sessions = sp->se_next;
1386 if ((snext = sp->se_next) != NULL)
1387 snext->se_prev = sp->se_prev;
1388 free_session(sp);
1389 return;
1392 if ((pid = start_getty(sp)) == -1) {
1393 /* serious trouble */
1394 requested_transition = clean_ttys;
1395 return;
1398 sp->se_process = pid;
1399 (void)gettimeofday(&sp->se_started, NULL);
1400 add_session(sp);
1401 #endif /* LETS_GET_SMALL */
1405 * Catch a signal and request a state transition.
1407 void
1408 transition_handler(int sig)
1411 switch (sig) {
1412 #ifndef LETS_GET_SMALL
1413 case SIGHUP:
1414 requested_transition = clean_ttys;
1415 break;
1416 case SIGTERM:
1417 requested_transition = death;
1418 break;
1419 case SIGTSTP:
1420 requested_transition = catatonia;
1421 break;
1422 #endif /* LETS_GET_SMALL */
1423 default:
1424 requested_transition = 0;
1425 break;
1429 #ifndef LETS_GET_SMALL
1431 * Take the system multiuser.
1433 state_func_t
1434 multi_user(void)
1436 pid_t pid;
1437 int status;
1438 session_t *sp;
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) {
1452 if (sp->se_process)
1453 continue;
1454 if ((pid = start_getty(sp)) == -1) {
1455 /* serious trouble */
1456 requested_transition = clean_ttys;
1457 break;
1459 sp->se_process = pid;
1460 (void)gettimeofday(&sp->se_started, NULL);
1461 add_session(sp);
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...
1474 state_func_t
1475 clean_ttys(void)
1477 session_t *sp, *sprev;
1478 struct ttyent *typ;
1479 int session_index = 0;
1480 int devlen;
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) {
1489 ++session_index;
1491 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1492 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1493 break;
1495 if (sp) {
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,
1500 session_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);
1508 continue;
1510 sp->se_flags &= ~SE_SHUTDOWN;
1511 if (setupargv(sp, typ) == 0) {
1512 warning("can't parse getty for port `%s'",
1513 sp->se_device);
1514 sp->se_flags |= SE_SHUTDOWN;
1515 if (sp->se_process != 0)
1516 (void)kill(sp->se_process, SIGHUP);
1518 continue;
1521 (void)new_session(sprev, session_index, typ);
1524 (void)endttyent();
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.
1539 state_func_t
1540 catatonia(void)
1542 session_t *sp;
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 */
1552 * Note SIGALRM.
1554 void
1555 /*ARGSUSED*/
1556 alrm_handler(int sig)
1559 clang = 1;
1562 #ifndef LETS_GET_SMALL
1564 * Bring the system down to single user.
1566 state_func_t
1567 death(void)
1569 session_t *sp;
1570 int i, status;
1571 pid_t pid;
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);
1580 #endif
1581 #ifdef SUPPORT_UTMP
1582 logwtmp("~", "shutdown", "");
1583 #endif
1585 for (i = 0; i < 3; ++i) {
1586 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1587 return (state_func_t)single_user;
1589 clang = 0;
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
1608 static int
1609 mfs_dev(void)
1612 * We cannot print errors so we bail out silently...
1614 pid_t pid;
1615 int status;
1617 /* If we have /dev/console, assume all is OK */
1618 if (access(_PATH_CONSOLE, F_OK) == 0)
1619 return 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())) {
1624 case 0:
1625 (void)execl(INIT_MOUNT_MFS, "mount_mfs",
1626 "-b", "4096", "-f", "512",
1627 "-s", 64, "-n", 10,
1628 "-p", "0755",
1629 "swap", "/mnt", NULL);
1630 _exit(9);
1631 /*NOTREACHED*/
1633 case -1:
1634 return(-1);
1636 default:
1637 if (waitpid(pid, &status, 0) == -1)
1638 return(-1);
1639 if (status != 0)
1640 return(-1);
1641 break;
1645 dev_t dev;
1646 #ifdef CPU_CONSDEV
1647 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1648 size_t olen;
1649 olen = sizeof(dev);
1650 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
1651 NULL, 0) == -1)
1652 #endif
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)
1657 return(-1);
1658 (void)freopen("/mnt/console", "a", stderr);
1661 #endif
1663 /* Run the makedev script to create devices */
1664 switch ((pid = fork())) {
1665 case 0:
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);
1672 _exit(10);
1673 /* NOTREACHED */
1675 case -1:
1676 break;
1678 default:
1679 if (waitpid(pid, &status, 0) == -1)
1680 break;
1681 if (status != 0)
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)
1688 return 0;
1689 _exit(11);
1691 warn("Unable to run MAKEDEV");
1692 _exit(12);
1694 #endif
1697 do_setttyent(void)
1699 (void)endttyent();
1700 #ifdef CHROOT
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);
1707 } else
1708 #endif /* CHROOT */
1709 return setttyent();
1712 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
1715 createsysctlnode()
1717 struct sysctlnode node;
1718 int mib[2];
1719 size_t len;
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");
1736 return -1;
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");
1756 return -1;
1759 return 0;
1763 shouldchroot()
1765 struct sysctlnode node;
1766 size_t len, cnt;
1767 int mib;
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;
1781 mib = CTL_DESTROY;
1783 (void)sysctl(&mib, 1, NULL, NULL, &node,
1784 sizeof(node));
1787 (void)createsysctlnode();
1790 /* We certainly won't chroot. */
1791 return 0;
1794 if (rootdir[len] != '\0' || strlen(rootdir) != len - 1) {
1795 warning("init.root is not a string");
1796 return 0;
1799 if (strcmp(rootdir, "/") == 0)
1800 return 0;
1802 return 1;
1805 #endif /* !LETS_GET_SMALL && CHROOT */