init.c revision 1.92 1 /* $NetBSD: init.c,v 1.92 2007/03/11 19:02:04 apb Exp $ */
2
3 /*-
4 * Copyright (c) 1991, 1993
5 * The Regents of the University of California. All rights reserved.
6 *
7 * This code is derived from software contributed to Berkeley by
8 * Donn Seeley at Berkeley Software Design, Inc.
9 *
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.
21 *
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.
33 */
34
35 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1991, 1993\n"
38 " The Regents of the University of California. All rights reserved.\n");
39 #endif /* not lint */
40
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.92 2007/03/11 19:02:04 apb Exp $");
46 #endif
47 #endif /* not lint */
48
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>
56
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>
71
72 #include <stdarg.h>
73
74 #ifdef SECURE
75 #include <pwd.h>
76 #endif
77
78 #include "pathnames.h"
79
80 #define XSTR(x) #x
81 #define STR(x) XSTR(x)
82
83 /*
84 * Sleep times; used to prevent thrashing.
85 */
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 */
91
92 const struct timespec dtrtime = {.tv_sec = 0, .tv_nsec = 250000};
93
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
103
104 int main(int, char *[]);
105
106 void handle(sig_t, ...);
107 void delset(sigset_t *, ...);
108
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);
117
118 /*
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.
122 */
123 typedef long (*state_func_t)(void);
124 typedef state_func_t (*state_t)(void);
125
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'
133
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);
141
142 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
143
144 void transition(state_t);
145 void setctty(const char *);
146
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;
162
163 void free_session(session_t *);
164 session_t *new_session(session_t *, int, struct ttyent *);
165 session_t *sessions;
166
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;
177
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;
183
184 int do_setttyent(void);
185
186 #ifndef LETS_GET_SMALL
187 state_t requested_transition = runcom;
188
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
200
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 */
207
208 #else /* LETS_GET_SMALL */
209 state_t requested_transition = single_user;
210 #endif /* !LETS_GET_SMALL */
211
212 #ifdef MFS_DEV_IF_NO_CONSOLE
213
214 static int mfs_dev(void);
215
216 #endif
217
218 /*
219 * The mother of all processes.
220 */
221 int
222 main(int argc, char **argv)
223 {
224 struct sigaction sa;
225 sigset_t mask;
226 #ifndef LETS_GET_SMALL
227 int c;
228
229 #ifdef SUPPORT_UTMPX
230 (void)gettimeofday(&boot_time, NULL);
231 #endif /* SUPPORT_UTMPX */
232
233 /* Dispose of random users. */
234 if (getuid() != 0) {
235 errno = EPERM;
236 err(1, NULL);
237 }
238
239 /* System V users like to reexec init. */
240 if (getpid() != 1)
241 errx(1, "already running");
242 #endif
243
244 /*
245 * Create an initial session.
246 */
247 if (setsid() < 0)
248 warn("initial setsid() failed");
249
250 /*
251 * Establish an initial user so that programs running
252 * single user do not freak out and die (like passwd).
253 */
254 if (setlogin("root") < 0)
255 warn("setlogin() failed");
256
257
258 #ifdef MFS_DEV_IF_NO_CONSOLE
259 if (mfs_dev() == -1)
260 requested_transition = single_user;
261 #endif
262
263 #ifndef LETS_GET_SMALL
264 /*
265 * Note that this does NOT open a file...
266 * Does 'init' deserve its own facility number?
267 */
268 openlog("init", LOG_CONS, LOG_AUTH);
269 #endif /* LETS_GET_SMALL */
270
271
272 #ifndef LETS_GET_SMALL
273 /*
274 * This code assumes that we always get arguments through flags,
275 * never through bits set in some random machine register.
276 */
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;
288 }
289
290 if (optind != argc)
291 warning("ignoring excess arguments");
292 #else /* LETS_GET_SMALL */
293 requested_transition = single_user;
294 #endif /* LETS_GET_SMALL */
295
296 /*
297 * We catch or block signals rather than ignore them,
298 * so that they get reset on exec.
299 */
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);
314
315 /*
316 * Paranoia.
317 */
318 (void)close(0);
319 (void)close(1);
320 (void)close(2);
321
322 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
323 /* Create "init.root" sysctl node. */
324 (void)createsysctlnode();
325 #endif /* !LETS_GET_SMALL && CHROOT*/
326
327 /*
328 * Start the state machine.
329 */
330 transition(requested_transition);
331
332 /*
333 * Should never reach here.
334 */
335 return 1;
336 }
337
338 /*
339 * Associate a function with a signal handler.
340 */
341 void
342 handle(sig_t handler, ...)
343 {
344 int sig;
345 struct sigaction sa;
346 sigset_t mask_everything;
347 va_list ap;
348
349 va_start(ap, handler);
350
351 sa.sa_handler = handler;
352 (void)sigfillset(&mask_everything);
353
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);
359 }
360 va_end(ap);
361 }
362
363 /*
364 * Delete a set of signals from a mask.
365 */
366 void
367 delset(sigset_t *maskp, ...)
368 {
369 int sig;
370 va_list ap;
371
372 va_start(ap, maskp);
373
374 while ((sig = va_arg(ap, int)) != 0)
375 (void)sigdelset(maskp, sig);
376 va_end(ap);
377 }
378
379 #if 0 /* Enable to get error messages from init ! */
380 #define vsyslog(level, fmt, ap) print_console(level, fmt, ap)
381 #define closelog()
382
383 static void
384 print_console(int level, const char *message, va_list ap)
385 {
386 /*
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 (at) liberouter.org>
391 */
392 char errbuf[1024];
393 int fd, len;
394
395 /* We can't do anything on errors, anyway... */
396 fd = open(_PATH_CONSOLE, O_WRONLY);
397 if (fd == -1)
398 return ;
399
400 /* %m will get lost... */
401 len = vsnprintf(errbuf, sizeof(errbuf), message, ap);
402 (void)write(fd, (void *)errbuf, len);
403 (void)close(fd);
404 }
405 #endif
406
407 /*
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.
411 */
412 void
413 stall(const char *message, ...)
414 {
415 va_list ap;
416
417 va_start(ap, message);
418 vsyslog(LOG_ALERT, message, ap);
419 va_end(ap);
420 closelog();
421 (void)sleep(STALL_TIMEOUT);
422 }
423
424 /*
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.
428 */
429 void
430 warning(const char *message, ...)
431 {
432 va_list ap;
433
434 va_start(ap, message);
435 vsyslog(LOG_ALERT, message, ap);
436 va_end(ap);
437 closelog();
438 }
439
440 /*
441 * Log an emergency message.
442 * NB: should send a message to the session logger to avoid blocking.
443 */
444 void
445 emergency(const char *message, ...)
446 {
447 va_list ap;
448
449 va_start(ap, message);
450 vsyslog(LOG_EMERG, message, ap);
451 va_end(ap);
452 closelog();
453 }
454
455 /*
456 * Catch a SIGSYS signal.
457 *
458 * These may arise if a system does not support sysctl.
459 * We tolerate up to 25 of these, then throw in the towel.
460 */
461 void
462 badsys(int sig)
463 {
464 static int badcount = 0;
465
466 if (badcount++ < 25)
467 return;
468 disaster(sig);
469 }
470
471 /*
472 * Catch an unexpected signal.
473 */
474 void
475 disaster(int sig)
476 {
477
478 emergency("fatal signal: %s", strsignal(sig));
479 (void)sleep(STALL_TIMEOUT);
480 _exit(sig); /* reboot */
481 }
482
483 /*
484 * Get the security level of the kernel.
485 */
486 int
487 getsecuritylevel(void)
488 {
489 #ifdef KERN_SECURELVL
490 int name[2], curlevel;
491 size_t len;
492
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);
499 }
500 return (curlevel);
501 #else
502 return (-1);
503 #endif
504 }
505
506 /*
507 * Set the security level of the kernel.
508 */
509 void
510 setsecuritylevel(int newlevel)
511 {
512 #ifdef KERN_SECURELVL
513 int name[2], curlevel;
514
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;
524 }
525 #ifdef SECURE
526 warning("kernel security level changed from %d to %d",
527 curlevel, newlevel);
528 #endif
529 #endif
530 }
531
532 /*
533 * Change states in the finite state machine.
534 * The initial state is passed as an argument.
535 */
536 void
537 transition(state_t s)
538 {
539
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)();
551 }
552 }
553
554 #ifndef LETS_GET_SMALL
555 /*
556 * Close out the accounting files for a login session.
557 * NB: should send a message to the session logger to avoid blocking.
558 */
559 void
560 clear_session_logs(session_t *sp, int status)
561 {
562 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
563 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
564 #endif
565
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
574 }
575 #endif
576
577 /*
578 * Start a session and allocate a controlling terminal.
579 * Only called by children of init after forking.
580 */
581 void
582 setctty(const char *name)
583 {
584 int fd;
585
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);
591 }
592 if (login_tty(fd) == -1) {
593 stall("can't get %s for controlling terminal: %m", name);
594 _exit(2);
595 }
596 }
597
598 /*
599 * Bring the system up single user.
600 */
601 state_func_t
602 single_user(void)
603 {
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 */
621
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 */
626
627 /*
628 * If the kernel is in secure mode, downgrade it to insecure mode.
629 */
630 from_securitylevel = getsecuritylevel();
631 if (from_securitylevel > 0)
632 setsecuritylevel(0);
633
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) {
640 /*
641 * Start the single user session.
642 */
643 if (access(_PATH_CONSTTY, F_OK) == 0)
644 setctty(_PATH_CONSTTY);
645 else
646 setctty(_PATH_CONSOLE);
647
648 #ifdef SECURE
649 /*
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'.
653 */
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");
669 }
670 }
671 (void)endttyent();
672 endpwent();
673 #endif /* SECURE */
674
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;
683
684 if ((p = strchr(altshell, '\n')) != NULL)
685 *p = '\0';
686 }
687
688 if (altshell[0])
689 shell = altshell;
690 #endif /* ALTSHELL */
691
692 /*
693 * Unblock signals.
694 * We catch all the interesting ones,
695 * and those are reset to SIG_DFL on exec.
696 */
697 (void)sigemptyset(&mask);
698 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
699
700 /*
701 * Fire off a shell.
702 * If the default one doesn't work, try the Bourne shell.
703 */
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);
718 }
719
720 if (pid == -1) {
721 /*
722 * We are seriously hosed. Do our best.
723 */
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;
730 }
731
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;
742 }
743 if (wpid == pid && WIFSTOPPED(status)) {
744 warning("shell stopped, restarting");
745 (void)kill(pid, SIGCONT);
746 wpid = -1;
747 }
748 } while (wpid != pid && !requested_transition);
749
750 if (requested_transition) {
751 (void)sigaction(SIGTSTP, &satstp, NULL);
752 (void)sigaction(SIGHUP, &sahup, NULL);
753 return (state_func_t)requested_transition;
754 }
755
756 if (WIFSIGNALED(status)) {
757 if (WTERMSIG(status) == SIGKILL) {
758 /* executed /sbin/reboot; wait for the end quietly */
759 sigset_t s;
760
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;
770 }
771 }
772
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 */
781 }
782
783 #ifndef LETS_GET_SMALL
784
785 /* ARGSUSED */
786 state_func_t
787 runetcrc(int trychroot)
788 {
789 pid_t pid, wpid;
790 int status;
791 const char *argv[4];
792 struct sigaction sa;
793
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);
801
802 setctty(_PATH_CONSOLE);
803
804 argv[0] = "sh";
805 argv[1] = _PATH_RUNCOM;
806 argv[2] = (runcom_mode == AUTOBOOT ? "autoboot" : 0);
807 argv[3] = 0;
808
809 (void)sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
810
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 */
817 }
818 #endif /* CHROOT */
819
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;
833 }
834
835 /*
836 * Copied from single_user(). This is a bit paranoid.
837 */
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;
847 }
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;
853 }
854 } while (wpid != pid);
855
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;
860
861 (void)sigfillset(&s);
862 for (;;)
863 (void)sigsuspend(&s);
864 }
865
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;
870 }
871
872 if (WEXITSTATUS(status))
873 return (state_func_t)single_user;
874
875 return (state_func_t) read_ttys;
876 }
877
878 /*
879 * Run the system startup script.
880 */
881 state_func_t
882 runcom(void)
883 {
884 state_func_t next_step;
885
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;
890
891 #ifdef CHROOT
892 /*
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.
896 */
897 if (shouldchroot()) {
898 next_step = runetcrc(1);
899 if (next_step != (state_func_t) read_ttys)
900 return (state_func_t) next_step;
901
902 did_multiuser_chroot = 1;
903 } else {
904 did_multiuser_chroot = 0;
905 }
906 #endif /* CHROOT */
907
908 /*
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).
911 */
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;
921 }
922
923 /*
924 * Open the session database.
925 *
926 * NB: We could pass in the size here; is it necessary?
927 */
928 int
929 start_session_db(void)
930 {
931
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);
937 }
938 return (0);
939
940 }
941
942 /*
943 * Add a new login session.
944 */
945 void
946 add_session(session_t *sp)
947 {
948 DBT key;
949 DBT data;
950
951 if (session_db == NULL)
952 return;
953
954 key.data = &sp->se_process;
955 key.size = sizeof sp->se_process;
956 data.data = &sp;
957 data.size = sizeof sp;
958
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
964 }
965
966 /*
967 * Delete an old login session.
968 */
969 void
970 del_session(session_t *sp)
971 {
972 DBT key;
973
974 key.data = &sp->se_process;
975 key.size = sizeof sp->se_process;
976
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
982 }
983
984 /*
985 * Look up a login session by pid.
986 */
987 session_t *
988 find_session(pid_t pid)
989 {
990 DBT key;
991 DBT data;
992 session_t *ret;
993
994 if (session_db == NULL)
995 return NULL;
996
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;
1003 }
1004
1005 /*
1006 * Construct an argument vector from a command line.
1007 */
1008 char **
1009 construct_argv(char *command)
1010 {
1011 int argc = 0;
1012 char **argv = malloc(((strlen(command) + 1) / 2 + 1) * sizeof (char *));
1013 static const char separators[] = " \t";
1014
1015 if (argv == NULL)
1016 return (NULL);
1017
1018 if ((argv[argc++] = strtok(command, separators)) == 0) {
1019 free(argv);
1020 return (NULL);
1021 }
1022 while ((argv[argc++] = strtok(NULL, separators)) != NULL)
1023 continue;
1024 return (argv);
1025 }
1026
1027 /*
1028 * Deallocate a session descriptor.
1029 */
1030 void
1031 free_session(session_t *sp)
1032 {
1033
1034 free(sp->se_device);
1035 if (sp->se_getty) {
1036 free(sp->se_getty);
1037 free(sp->se_getty_argv);
1038 }
1039 if (sp->se_window) {
1040 free(sp->se_window);
1041 free(sp->se_window_argv);
1042 }
1043 free(sp);
1044 }
1045
1046 /*
1047 * Allocate a new session descriptor.
1048 */
1049 session_t *
1050 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1051 {
1052 session_t *sp;
1053
1054 if ((typ->ty_status & TTY_ON) == 0 || typ->ty_name == NULL ||
1055 typ->ty_getty == NULL)
1056 return (NULL);
1057
1058 sp = malloc(sizeof (session_t));
1059 if (sp == NULL)
1060 return NULL;
1061 (void)memset(sp, 0, sizeof *sp);
1062
1063 sp->se_flags = SE_PRESENT;
1064 sp->se_index = session_index;
1065
1066 (void)asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1067 if (!sp->se_device)
1068 return NULL;
1069
1070 if (setupargv(sp, typ) == 0) {
1071 free_session(sp);
1072 return (NULL);
1073 }
1074
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;
1082 }
1083
1084 return (sp);
1085 }
1086
1087 /*
1088 * Calculate getty and if useful window argv vectors.
1089 */
1090 int
1091 setupargv(session_t *sp, struct ttyent *typ)
1092 {
1093
1094 if (sp->se_getty) {
1095 free(sp->se_getty);
1096 free(sp->se_getty_argv);
1097 }
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);
1107 }
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);
1119 }
1120 }
1121 return (1);
1122 }
1123
1124 /*
1125 * Walk the list of ttys and create sessions for each active line.
1126 */
1127 state_func_t
1128 read_ttys(void)
1129 {
1130 int session_index = 0;
1131 session_t *sp, *snext;
1132 struct ttyent *typ;
1133
1134 #ifdef SUPPORT_UTMPX
1135 if (sessions == NULL) {
1136 struct stat st;
1137
1138 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1139
1140 /*
1141 * If wtmpx is not empty, pick the the down time from there
1142 */
1143 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1144 struct timeval down_time;
1145
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);
1150 }
1151 }
1152 #endif
1153 /*
1154 * Destroy any previous session state.
1155 * There shouldn't be any, but just in case...
1156 */
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);
1164 }
1165 sessions = NULL;
1166
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;
1176 }
1177
1178 (void)do_setttyent();
1179
1180 /*
1181 * Allocate a session entry for each active port.
1182 * Note that sp starts at 0.
1183 */
1184 while ((typ = getttyent()) != NULL)
1185 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1186 sp = snext;
1187 (void)endttyent();
1188
1189 return (state_func_t)multi_user;
1190 }
1191
1192 /*
1193 * Start a window system running.
1194 */
1195 void
1196 start_window_system(session_t *sp)
1197 {
1198 pid_t pid;
1199 sigset_t mask;
1200
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;
1206 }
1207
1208 if (pid)
1209 return;
1210
1211 (void)sigemptyset(&mask);
1212 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
1213
1214 if (setsid() < 0)
1215 emergency("setsid failed (window): %m");
1216
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);
1221 }
1222
1223 /*
1224 * Start a login session running.
1225 */
1226 pid_t
1227 start_getty(session_t *sp)
1228 {
1229 pid_t pid;
1230 sigset_t mask;
1231 time_t current_time = time(NULL);
1232
1233 /*
1234 * fork(), not vfork() -- we can't afford to block.
1235 */
1236 if ((pid = fork()) == -1) {
1237 emergency("can't fork for getty on port `%s': %m",
1238 sp->se_device);
1239 return -1;
1240 }
1241
1242 if (pid)
1243 return pid;
1244
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);
1252 }
1253 #endif /* CHROOT */
1254
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);
1260 }
1261
1262 if (sp->se_window) {
1263 start_window_system(sp);
1264 (void)sleep(WINDOW_WAIT);
1265 }
1266
1267 (void)sigemptyset(&mask);
1268 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1269
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*/
1275 }
1276 #ifdef SUPPORT_UTMPX
1277 static void
1278 session_utmpx(const session_t *sp, int add)
1279 {
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;
1283
1284 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1285 sp->se_process, &sp->se_started, sp->se_index);
1286 }
1287
1288 static void
1289 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1290 const struct timeval *tv, int session)
1291 {
1292 struct utmpx ut;
1293 const char *eline;
1294
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;
1305
1306 eline = line + strlen(line);
1307 if (eline - line >= sizeof(ut.ut_id))
1308 line = eline - sizeof(ut.ut_id);
1309 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1310
1311 if (pututxline(&ut) == NULL)
1312 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1313 endutxent();
1314 }
1315
1316 static char
1317 get_runlevel(const state_t s)
1318 {
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;
1332 }
1333
1334 static void
1335 utmpx_set_runlevel(char old, char new)
1336 {
1337 struct utmpx ut;
1338
1339 /*
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?
1343 */
1344 if (sessions == NULL)
1345 return;
1346
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();
1356 }
1357 #endif /* SUPPORT_UTMPX */
1358
1359 #endif /* LETS_GET_SMALL */
1360
1361 /*
1362 * Collect exit status for a child.
1363 * If an exiting login, start a new login running.
1364 */
1365 void
1366 collect_child(pid_t pid, int status)
1367 {
1368 #ifndef LETS_GET_SMALL
1369 session_t *sp, *sprev, *snext;
1370
1371 if (! sessions)
1372 return;
1373
1374 if ((sp = find_session(pid)) == NULL)
1375 return;
1376
1377 clear_session_logs(sp, status);
1378 del_session(sp);
1379 sp->se_process = 0;
1380
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;
1390 }
1391
1392 if ((pid = start_getty(sp)) == -1) {
1393 /* serious trouble */
1394 requested_transition = clean_ttys;
1395 return;
1396 }
1397
1398 sp->se_process = pid;
1399 (void)gettimeofday(&sp->se_started, NULL);
1400 add_session(sp);
1401 #endif /* LETS_GET_SMALL */
1402 }
1403
1404 /*
1405 * Catch a signal and request a state transition.
1406 */
1407 void
1408 transition_handler(int sig)
1409 {
1410
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;
1426 }
1427 }
1428
1429 #ifndef LETS_GET_SMALL
1430 /*
1431 * Take the system multiuser.
1432 */
1433 state_func_t
1434 multi_user(void)
1435 {
1436 pid_t pid;
1437 int status;
1438 session_t *sp;
1439
1440 requested_transition = 0;
1441
1442 /*
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.
1447 */
1448 if (getsecuritylevel() == 0)
1449 setsecuritylevel(1);
1450
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;
1458 }
1459 sp->se_process = pid;
1460 (void)gettimeofday(&sp->se_started, NULL);
1461 add_session(sp);
1462 }
1463
1464 while (!requested_transition)
1465 if ((pid = waitpid(-1, &status, 0)) != -1)
1466 collect_child(pid, status);
1467
1468 return (state_func_t)requested_transition;
1469 }
1470
1471 /*
1472 * This is an n-squared algorithm. We hope it isn't run often...
1473 */
1474 state_func_t
1475 clean_ttys(void)
1476 {
1477 session_t *sp, *sprev;
1478 struct ttyent *typ;
1479 int session_index = 0;
1480 int devlen;
1481
1482 for (sp = sessions; sp; sp = sp->se_next)
1483 sp->se_flags &= ~SE_PRESENT;
1484
1485 (void)do_setttyent();
1486
1487 devlen = sizeof(_PATH_DEV) - 1;
1488 while ((typ = getttyent()) != NULL) {
1489 ++session_index;
1490
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;
1494
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;
1502 }
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;
1509 }
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);
1517 }
1518 continue;
1519 }
1520
1521 (void)new_session(sprev, session_index, typ);
1522 }
1523
1524 (void)endttyent();
1525
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);
1531 }
1532
1533 return (state_func_t)multi_user;
1534 }
1535
1536 /*
1537 * Block further logins.
1538 */
1539 state_func_t
1540 catatonia(void)
1541 {
1542 session_t *sp;
1543
1544 for (sp = sessions; sp; sp = sp->se_next)
1545 sp->se_flags |= SE_SHUTDOWN;
1546
1547 return (state_func_t)multi_user;
1548 }
1549 #endif /* LETS_GET_SMALL */
1550
1551 /*
1552 * Note SIGALRM.
1553 */
1554 void
1555 /*ARGSUSED*/
1556 alrm_handler(int sig)
1557 {
1558
1559 clang = 1;
1560 }
1561
1562 #ifndef LETS_GET_SMALL
1563 /*
1564 * Bring the system down to single user.
1565 */
1566 state_func_t
1567 death(void)
1568 {
1569 session_t *sp;
1570 int i, status;
1571 pid_t pid;
1572 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1573
1574 for (sp = sessions; sp; sp = sp->se_next)
1575 sp->se_flags |= SE_SHUTDOWN;
1576
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
1584
1585 for (i = 0; i < 3; ++i) {
1586 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1587 return (state_func_t)single_user;
1588
1589 clang = 0;
1590 (void)alarm(DEATH_WATCH);
1591 do
1592 if ((pid = waitpid(-1, &status, 0)) != -1)
1593 collect_child(pid, status);
1594 while (clang == 0 && errno != ECHILD);
1595
1596 if (errno == ECHILD)
1597 return (state_func_t)single_user;
1598 }
1599
1600 warning("some processes would not die; ps axl advised");
1601
1602 return (state_func_t)single_user;
1603 }
1604 #endif /* LETS_GET_SMALL */
1605
1606 #ifdef MFS_DEV_IF_NO_CONSOLE
1607
1608 static int
1609 mfs_dev(void)
1610 {
1611 /*
1612 * We cannot print errors so we bail out silently...
1613 */
1614 pid_t pid;
1615 int status;
1616
1617 /* If we have /dev/console, assume all is OK */
1618 if (access(_PATH_CONSOLE, F_OK) == 0)
1619 return 0;
1620
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 if (fs_size == NULL)
1626 return(-1);
1627 (void)execl(INIT_MOUNT_MFS, "mount_mfs",
1628 "-b", "4096", "-f", "512",
1629 "-s", 64, "-n", 10,
1630 "-p", "0755",
1631 "swap", "/mnt", NULL);
1632 _exit(9);
1633 /*NOTREACHED*/
1634
1635 case -1:
1636 return(-1);
1637
1638 default:
1639 if (waitpid(pid, &status, 0) == -1)
1640 return(-1);
1641 if (status != 0)
1642 return(-1);
1643 break;
1644 }
1645
1646 {
1647 #ifdef CPU_CONSDEV
1648 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1649 size_t olen;
1650 olen = sizeof(dev);
1651 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
1652 NULL, 0) == -1)
1653 #endif
1654 dev = makedev(0, 0);
1655 }
1656
1657 /* Make a console for us, so we can see things happening */
1658 if (mknod("/mnt/console", 0666 | S_IFCHR, dev) == -1)
1659 return(-1);
1660
1661 (void)freopen("/mnt/console", "a", stderr);
1662 #endif
1663
1664 /* Run the makedev script to create devices */
1665 switch ((pid = fork())) {
1666 case 0:
1667 (void)dup2(2, 1); /* Give the script stdout */
1668 if (chdir("/dev") == 0)
1669 (void)execl(INIT_BSHELL, "sh",
1670 access("./MAKEDEV", X_OK) == 0
1671 ? "./MAKEDEV" : "/etc/MAKEDEV",
1672 "-MM", "-ppax", "init", NULL);
1673 _exit(10);
1674 /* NOTREACHED */
1675
1676 case -1:
1677 break;
1678
1679 default:
1680 if (waitpid(pid, &status, 0) == -1)
1681 break;
1682 if (status != 0) {
1683 errno = EINVAL;
1684 break;
1685 }
1686 /* Check /dev/console got created */
1687 if (access(_PATH_CONSOLE, F_OK) == 0)
1688 return 0;
1689 _exit(11);
1690 }
1691 warn("Unable to run MAKEDEV");
1692 _exit(12);
1693 }
1694 #endif
1695
1696 int
1697 do_setttyent(void)
1698 {
1699 (void)endttyent();
1700 #ifdef CHROOT
1701 if (did_multiuser_chroot) {
1702 char path[PATH_MAX];
1703
1704 (void)snprintf(path, sizeof(path), "%s/%s", rootdir, _PATH_TTYS);
1705
1706 return setttyentpath(path);
1707 } else
1708 #endif /* CHROOT */
1709 return setttyent();
1710 }
1711
1712 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
1713
1714 int
1715 createsysctlnode()
1716 {
1717 struct sysctlnode node;
1718 int mib[2];
1719 size_t len;
1720
1721 /*
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!").
1725 */
1726 len = sizeof(struct sysctlnode);
1727 mib[0] = CTL_CREATE;
1728
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);
1737 }
1738
1739 /*
1740 * Create second level dynamic node capable of holding pathname.
1741 * Provide "/" as the default value.
1742 */
1743 len = sizeof(struct sysctlnode);
1744 mib[0] = node.sysctl_num;
1745 mib[1] = CTL_CREATE;
1746
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);
1757 }
1758
1759 return (0);
1760 }
1761
1762 int
1763 shouldchroot()
1764 {
1765 struct sysctlnode node;
1766 size_t len, cnt;
1767 int mib;
1768
1769 len = sizeof(struct sysctlnode);
1770
1771 if (sysctlbyname("init.root", rootdir, &len, NULL, 0) == -1) {
1772 warning("could not read init.root: %m");
1773
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;
1782
1783 (void)sysctl(&mib, 1, NULL, NULL, &node,
1784 sizeof(node));
1785 }
1786
1787 (void)createsysctlnode();
1788 }
1789
1790 /* We certainly won't chroot. */
1791 return (0);
1792 }
1793
1794 if (rootdir[len] != '\0' || strlen(rootdir) != len - 1) {
1795 warning("init.root is not a string");
1796 return (0);
1797 }
1798
1799 if (strcmp(rootdir, "/") == 0)
1800 return (0);
1801
1802 return (1);
1803 }
1804
1805 #endif /* !LETS_GET_SMALL && CHROOT */
1806