init.c revision 1.83 1 /* $NetBSD: init.c,v 1.83 2007/01/20 13:25:28 isaki 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.83 2007/01/20 13:25:28 isaki 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 #define NINODE 1024
215 #define FSSIZE ((8192 /* boot area */ \
216 + 2 * 8192 /* two copies of superblock */ \
217 + 4096 /* cylinder group info */ \
218 + NINODE * (128 + 18) /* inode and directory entry */ \
219 + mfile[0].len /* size of MAKEDEV file */ \
220 + 2 * 4096) / 512) /* some slack */
221
222 struct mappedfile {
223 const char *path;
224 char *buf;
225 int len;
226 } mfile[] = {
227 { "/dev/MAKEDEV", NULL, 0 },
228 { "/dev/MAKEDEV.local", NULL, 0 }
229 };
230
231 static int mfs_dev(void);
232 static void mapfile(struct mappedfile *);
233 static void writefile(struct mappedfile *);
234
235 #endif
236
237 /*
238 * The mother of all processes.
239 */
240 int
241 main(int argc, char **argv)
242 {
243 struct sigaction sa;
244 sigset_t mask;
245 #ifndef LETS_GET_SMALL
246 int c;
247
248 #ifdef SUPPORT_UTMPX
249 (void)gettimeofday(&boot_time, NULL);
250 #endif /* SUPPORT_UTMPX */
251
252 /* Dispose of random users. */
253 if (getuid() != 0) {
254 errno = EPERM;
255 err(1, NULL);
256 }
257
258 /* System V users like to reexec init. */
259 if (getpid() != 1)
260 errx(1, "already running");
261 #endif
262
263 /*
264 * Create an initial session.
265 */
266 if (setsid() < 0)
267 warn("initial setsid() failed");
268
269 /*
270 * Establish an initial user so that programs running
271 * single user do not freak out and die (like passwd).
272 */
273 if (setlogin("root") < 0)
274 warn("setlogin() failed");
275
276
277 #ifdef MFS_DEV_IF_NO_CONSOLE
278 if (mfs_dev() == -1)
279 requested_transition = single_user;
280 #endif
281
282 #ifndef LETS_GET_SMALL
283 /*
284 * Note that this does NOT open a file...
285 * Does 'init' deserve its own facility number?
286 */
287 openlog("init", LOG_CONS, LOG_AUTH);
288 #endif /* LETS_GET_SMALL */
289
290
291 #ifndef LETS_GET_SMALL
292 /*
293 * This code assumes that we always get arguments through flags,
294 * never through bits set in some random machine register.
295 */
296 while ((c = getopt(argc, argv, "sf")) != -1)
297 switch (c) {
298 case 's':
299 requested_transition = single_user;
300 break;
301 case 'f':
302 runcom_mode = FASTBOOT;
303 break;
304 default:
305 warning("unrecognized flag `%c'", c);
306 break;
307 }
308
309 if (optind != argc)
310 warning("ignoring excess arguments");
311 #else /* LETS_GET_SMALL */
312 requested_transition = single_user;
313 #endif /* LETS_GET_SMALL */
314
315 /*
316 * We catch or block signals rather than ignore them,
317 * so that they get reset on exec.
318 */
319 handle(badsys, SIGSYS, 0);
320 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
321 SIGBUS, SIGXCPU, SIGXFSZ, 0);
322 handle(transition_handler, SIGHUP, SIGTERM, SIGTSTP, 0);
323 handle(alrm_handler, SIGALRM, 0);
324 (void)sigfillset(&mask);
325 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
326 SIGXCPU, SIGXFSZ, SIGHUP, SIGTERM, SIGTSTP, SIGALRM, 0);
327 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
328 (void)sigemptyset(&sa.sa_mask);
329 sa.sa_flags = 0;
330 sa.sa_handler = SIG_IGN;
331 (void)sigaction(SIGTTIN, &sa, NULL);
332 (void)sigaction(SIGTTOU, &sa, NULL);
333
334 /*
335 * Paranoia.
336 */
337 (void)close(0);
338 (void)close(1);
339 (void)close(2);
340
341 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
342 /* Create "init.root" sysctl node. */
343 createsysctlnode();
344 #endif /* !LETS_GET_SMALL && CHROOT*/
345
346 /*
347 * Start the state machine.
348 */
349 transition(requested_transition);
350
351 /*
352 * Should never reach here.
353 */
354 return 1;
355 }
356
357 /*
358 * Associate a function with a signal handler.
359 */
360 void
361 handle(sig_t handler, ...)
362 {
363 int sig;
364 struct sigaction sa;
365 sigset_t mask_everything;
366 va_list ap;
367
368 va_start(ap, handler);
369
370 sa.sa_handler = handler;
371 (void)sigfillset(&mask_everything);
372
373 while ((sig = va_arg(ap, int)) != 0) {
374 sa.sa_mask = mask_everything;
375 /* XXX SA_RESTART? */
376 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
377 (void)sigaction(sig, &sa, NULL);
378 }
379 va_end(ap);
380 }
381
382 /*
383 * Delete a set of signals from a mask.
384 */
385 void
386 delset(sigset_t *maskp, ...)
387 {
388 int sig;
389 va_list ap;
390
391 va_start(ap, maskp);
392
393 while ((sig = va_arg(ap, int)) != 0)
394 (void)sigdelset(maskp, sig);
395 va_end(ap);
396 }
397
398 /*
399 * Log a message and sleep for a while (to give someone an opportunity
400 * to read it and to save log or hardcopy output if the problem is chronic).
401 * NB: should send a message to the session logger to avoid blocking.
402 */
403 void
404 stall(const char *message, ...)
405 {
406 va_list ap;
407
408 va_start(ap, message);
409 vsyslog(LOG_ALERT, message, ap);
410 va_end(ap);
411 closelog();
412 (void)sleep(STALL_TIMEOUT);
413 }
414
415 /*
416 * Like stall(), but doesn't sleep.
417 * If cpp had variadic macros, the two functions could be #defines for another.
418 * NB: should send a message to the session logger to avoid blocking.
419 */
420 void
421 warning(const char *message, ...)
422 {
423 va_list ap;
424
425 va_start(ap, message);
426 vsyslog(LOG_ALERT, message, ap);
427 va_end(ap);
428 closelog();
429
430 #if 0
431 /*
432 * XXX: syslog seems to just plain not work in console-only
433 * XXX: situation... that should be fixed. Let's leave this
434 * XXX: note + code here in case someone gets in trouble and
435 * XXX: wants to debug. -- Jachym Holecek <freza (at) liberouter.org>
436 */
437 {
438 char errbuf[1024];
439 int fd, len;
440
441 /* We can't do anything on errors, anyway... */
442 fd = open(_PATH_CONSOLE, O_WRONLY);
443 if (fd == -1)
444 return ;
445
446 /* %m will get lost... */
447 len = vsnprintf(errbuf, sizeof(errbuf), message, ap);
448 (void)write(fd, (void *)errbuf, len);
449 (void)close(fd);
450 }
451 #endif
452 }
453
454 /*
455 * Log an emergency message.
456 * NB: should send a message to the session logger to avoid blocking.
457 */
458 void
459 emergency(const char *message, ...)
460 {
461 va_list ap;
462
463 va_start(ap, message);
464 vsyslog(LOG_EMERG, message, ap);
465 va_end(ap);
466 closelog();
467 }
468
469 /*
470 * Catch a SIGSYS signal.
471 *
472 * These may arise if a system does not support sysctl.
473 * We tolerate up to 25 of these, then throw in the towel.
474 */
475 void
476 badsys(int sig)
477 {
478 static int badcount = 0;
479
480 if (badcount++ < 25)
481 return;
482 disaster(sig);
483 }
484
485 /*
486 * Catch an unexpected signal.
487 */
488 void
489 disaster(int sig)
490 {
491
492 emergency("fatal signal: %s", strsignal(sig));
493 (void)sleep(STALL_TIMEOUT);
494 _exit(sig); /* reboot */
495 }
496
497 /*
498 * Get the security level of the kernel.
499 */
500 int
501 getsecuritylevel(void)
502 {
503 #ifdef KERN_SECURELVL
504 int name[2], curlevel;
505 size_t len;
506
507 name[0] = CTL_KERN;
508 name[1] = KERN_SECURELVL;
509 len = sizeof curlevel;
510 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
511 emergency("cannot get kernel security level: %m");
512 return (-1);
513 }
514 return (curlevel);
515 #else
516 return (-1);
517 #endif
518 }
519
520 /*
521 * Set the security level of the kernel.
522 */
523 void
524 setsecuritylevel(int newlevel)
525 {
526 #ifdef KERN_SECURELVL
527 int name[2], curlevel;
528
529 curlevel = getsecuritylevel();
530 if (newlevel == curlevel)
531 return;
532 name[0] = CTL_KERN;
533 name[1] = KERN_SECURELVL;
534 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
535 emergency("cannot change kernel security level from"
536 " %d to %d: %m", curlevel, newlevel);
537 return;
538 }
539 #ifdef SECURE
540 warning("kernel security level changed from %d to %d",
541 curlevel, newlevel);
542 #endif
543 #endif
544 }
545
546 /*
547 * Change states in the finite state machine.
548 * The initial state is passed as an argument.
549 */
550 void
551 transition(state_t s)
552 {
553
554 if (s == NULL)
555 return;
556 for (;;) {
557 #ifdef SUPPORT_UTMPX
558 #ifndef LETS_GET_SMALL
559 utmpx_set_runlevel(get_runlevel(current_state),
560 get_runlevel(s));
561 current_state = s;
562 #endif
563 #endif
564 s = (state_t)(*s)();
565 }
566 }
567
568 #ifndef LETS_GET_SMALL
569 /*
570 * Close out the accounting files for a login session.
571 * NB: should send a message to the session logger to avoid blocking.
572 */
573 void
574 clear_session_logs(session_t *sp, int status)
575 {
576 #if defined(SUPPORT_UTMP) || defined(SUPPORT_UTMPX)
577 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
578 #endif
579
580 #ifdef SUPPORT_UTMPX
581 if (logoutx(line, status, DEAD_PROCESS))
582 logwtmpx(line, "", "", status, DEAD_PROCESS);
583 #endif
584 #ifdef SUPPORT_UTMP
585 if (logout(line))
586 logwtmp(line, "", "");
587 #endif
588 }
589 #endif
590
591 /*
592 * Start a session and allocate a controlling terminal.
593 * Only called by children of init after forking.
594 */
595 void
596 setctty(const char *name)
597 {
598 int fd;
599
600 (void) revoke(name);
601 nanosleep(&dtrtime, NULL); /* leave DTR low for a bit */
602 if ((fd = open(name, O_RDWR)) == -1) {
603 stall("can't open %s: %m", name);
604 _exit(1);
605 }
606 if (login_tty(fd) == -1) {
607 stall("can't get %s for controlling terminal: %m", name);
608 _exit(1);
609 }
610 }
611
612 /*
613 * Bring the system up single user.
614 */
615 state_func_t
616 single_user(void)
617 {
618 pid_t pid, wpid;
619 int status;
620 int from_securitylevel;
621 sigset_t mask;
622 struct sigaction sa, satstp, sahup;
623 #ifdef ALTSHELL
624 const char *shell = INIT_BSHELL;
625 #endif
626 const char *argv[2];
627 #ifdef SECURE
628 struct ttyent *typ;
629 struct passwd *pp;
630 char *clear, *password;
631 #endif
632 #ifdef ALTSHELL
633 char altshell[128];
634 #endif /* ALTSHELL */
635
636 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
637 /* Clear previous idea, just in case. */
638 did_multiuser_chroot = 0;
639 #endif /* !LETS_GET_SMALL && CHROOT */
640
641 /*
642 * If the kernel is in secure mode, downgrade it to insecure mode.
643 */
644 from_securitylevel = getsecuritylevel();
645 if (from_securitylevel > 0)
646 setsecuritylevel(0);
647
648 (void)sigemptyset(&sa.sa_mask);
649 sa.sa_flags = 0;
650 sa.sa_handler = SIG_IGN;
651 (void)sigaction(SIGTSTP, &sa, &satstp);
652 (void)sigaction(SIGHUP, &sa, &sahup);
653 if ((pid = fork()) == 0) {
654 /*
655 * Start the single user session.
656 */
657 if (access(_PATH_CONSTTY, F_OK) == 0)
658 setctty(_PATH_CONSTTY);
659 else
660 setctty(_PATH_CONSOLE);
661
662 #ifdef SECURE
663 /*
664 * Check the root password.
665 * We don't care if the console is 'on' by default;
666 * it's the only tty that can be 'off' and 'secure'.
667 */
668 typ = getttynam("console");
669 pp = getpwnam("root");
670 if (typ && (from_securitylevel >=2 || (typ->ty_status
671 & TTY_SECURE) == 0) && pp && *pp->pw_passwd != '\0') {
672 (void)fprintf(stderr,
673 "Enter root password, or ^D to go multi-user\n");
674 for (;;) {
675 clear = getpass("Password:");
676 if (clear == 0 || *clear == '\0')
677 _exit(0);
678 password = crypt(clear, pp->pw_passwd);
679 (void)memset(clear, 0, _PASSWORD_LEN);
680 if (strcmp(password, pp->pw_passwd) == 0)
681 break;
682 warning("single-user login failed");
683 }
684 }
685 endttyent();
686 endpwent();
687 #endif /* SECURE */
688
689 #ifdef ALTSHELL
690 (void)fprintf(stderr,
691 "Enter pathname of shell or RETURN for %s: ", shell);
692 if (fgets(altshell, sizeof(altshell), stdin) == NULL) {
693 altshell[0] = '\0';
694 } else {
695 /* nuke \n */
696 char *p;
697
698 if ((p = strchr(altshell, '\n')) != NULL)
699 *p = '\0';
700 }
701
702 if (altshell[0])
703 shell = altshell;
704 #endif /* ALTSHELL */
705
706 /*
707 * Unblock signals.
708 * We catch all the interesting ones,
709 * and those are reset to SIG_DFL on exec.
710 */
711 (void)sigemptyset(&mask);
712 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
713
714 /*
715 * Fire off a shell.
716 * If the default one doesn't work, try the Bourne shell.
717 */
718 argv[0] = "-sh";
719 argv[1] = 0;
720 setenv("PATH", INIT_PATH, 1);
721 #ifdef ALTSHELL
722 if (altshell[0])
723 argv[0] = altshell;
724 (void)execv(shell, __UNCONST(argv));
725 emergency("can't exec `%s' for single user: %m", shell);
726 argv[0] = "-sh";
727 #endif /* ALTSHELL */
728 (void)execv(INIT_BSHELL, __UNCONST(argv));
729 emergency("can't exec `%s' for single user: %m", INIT_BSHELL);
730 (void)sleep(STALL_TIMEOUT);
731 _exit(1);
732 }
733
734 if (pid == -1) {
735 /*
736 * We are seriously hosed. Do our best.
737 */
738 emergency("can't fork single-user shell: %m, trying again");
739 while (waitpid(-1, NULL, WNOHANG) > 0)
740 continue;
741 (void)sigaction(SIGTSTP, &satstp, NULL);
742 (void)sigaction(SIGHUP, &sahup, NULL);
743 return (state_func_t) single_user;
744 }
745
746 requested_transition = 0;
747 do {
748 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
749 collect_child(wpid, status);
750 if (wpid == -1) {
751 if (errno == EINTR)
752 continue;
753 warning("wait for single-user shell failed: %m; "
754 "restarting");
755 return (state_func_t)single_user;
756 }
757 if (wpid == pid && WIFSTOPPED(status)) {
758 warning("shell stopped, restarting");
759 kill(pid, SIGCONT);
760 wpid = -1;
761 }
762 } while (wpid != pid && !requested_transition);
763
764 if (requested_transition) {
765 (void)sigaction(SIGTSTP, &satstp, NULL);
766 (void)sigaction(SIGHUP, &sahup, NULL);
767 return (state_func_t)requested_transition;
768 }
769
770 if (WIFSIGNALED(status)) {
771 if (WTERMSIG(status) == SIGKILL) {
772 /* executed /sbin/reboot; wait for the end quietly */
773 sigset_t s;
774
775 (void)sigfillset(&s);
776 for (;;)
777 (void)sigsuspend(&s);
778 } else {
779 warning("single user shell terminated, restarting");
780 (void)sigaction(SIGTSTP, &satstp, NULL);
781 (void)sigaction(SIGHUP, &sahup, NULL);
782 return (state_func_t) single_user;
783 }
784 }
785
786 runcom_mode = FASTBOOT;
787 (void)sigaction(SIGTSTP, &satstp, NULL);
788 (void)sigaction(SIGHUP, &sahup, NULL);
789 #ifndef LETS_GET_SMALL
790 return (state_func_t) runcom;
791 #else /* LETS_GET_SMALL */
792 return (state_func_t) single_user;
793 #endif /* LETS_GET_SMALL */
794 }
795
796 #ifndef LETS_GET_SMALL
797
798 /* ARGSUSED */
799 state_func_t
800 runetcrc(int trychroot)
801 {
802 pid_t pid, wpid;
803 int status;
804 const char *argv[4];
805 struct sigaction sa;
806
807 switch ((pid = fork())) {
808 case 0:
809 (void)sigemptyset(&sa.sa_mask);
810 sa.sa_flags = 0;
811 sa.sa_handler = SIG_IGN;
812 (void)sigaction(SIGTSTP, &sa, NULL);
813 (void)sigaction(SIGHUP, &sa, NULL);
814
815 setctty(_PATH_CONSOLE);
816
817 argv[0] = "sh";
818 argv[1] = _PATH_RUNCOM;
819 argv[2] = (runcom_mode == AUTOBOOT ? "autoboot" : 0);
820 argv[3] = 0;
821
822 (void)sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
823
824 #ifdef CHROOT
825 if (trychroot)
826 if (chroot(rootdir) != 0) {
827 warning("failed to chroot to `%s': %m",
828 rootdir);
829 _exit(1); /* force single user mode */
830 }
831 #endif /* CHROOT */
832
833 (void)execv(INIT_BSHELL, __UNCONST(argv));
834 stall("can't exec `%s' for `%s': %m", INIT_BSHELL, _PATH_RUNCOM);
835 _exit(1); /* force single user mode */
836 /*NOTREACHED*/
837 case -1:
838 emergency("can't fork for `%s' on `%s': %m", INIT_BSHELL,
839 _PATH_RUNCOM);
840 while (waitpid(-1, NULL, WNOHANG) > 0)
841 continue;
842 (void)sleep(STALL_TIMEOUT);
843 return (state_func_t)single_user;
844 default:
845 break;
846 }
847
848 /*
849 * Copied from single_user(). This is a bit paranoid.
850 */
851 do {
852 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
853 collect_child(wpid, status);
854 if (wpid == -1) {
855 if (errno == EINTR)
856 continue;
857 warning("wait for `%s' on `%s' failed: %m; going to "
858 "single user mode", INIT_BSHELL, _PATH_RUNCOM);
859 return (state_func_t)single_user;
860 }
861 if (wpid == pid && WIFSTOPPED(status)) {
862 warning("`%s' on `%s' stopped, restarting",
863 INIT_BSHELL, _PATH_RUNCOM);
864 (void)kill(pid, SIGCONT);
865 wpid = -1;
866 }
867 } while (wpid != pid);
868
869 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
870 requested_transition == catatonia) {
871 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
872 sigset_t s;
873
874 (void)sigfillset(&s);
875 for (;;)
876 (void)sigsuspend(&s);
877 }
878
879 if (!WIFEXITED(status)) {
880 warning("`%s' on `%s' terminated abnormally, going to "
881 "single user mode", INIT_BSHELL, _PATH_RUNCOM);
882 return (state_func_t)single_user;
883 }
884
885 if (WEXITSTATUS(status))
886 return (state_func_t)single_user;
887
888 return (state_func_t) read_ttys;
889 }
890
891 /*
892 * Run the system startup script.
893 */
894 state_func_t
895 runcom(void)
896 {
897 state_func_t next_step;
898
899 /* Run /etc/rc and choose next state depending on the result. */
900 next_step = runetcrc(0);
901 if (next_step != (state_func_t) read_ttys)
902 return (state_func_t) next_step;
903
904 #ifdef CHROOT
905 /*
906 * If init.root sysctl does not point to "/", we'll chroot and run
907 * The Real(tm) /etc/rc now. Global variable rootdir will tell us
908 * where to go.
909 */
910 if (shouldchroot()) {
911 next_step = runetcrc(1);
912 if (next_step != (state_func_t) read_ttys)
913 return (state_func_t) next_step;
914
915 did_multiuser_chroot = 1;
916 } else {
917 did_multiuser_chroot = 0;
918 }
919 #endif /* CHROOT */
920
921 /*
922 * Regardless of whether in chroot or not, we booted successfuly.
923 * It's time to spawn gettys (ie. next_step's value at this point).
924 */
925 runcom_mode = AUTOBOOT; /* the default */
926 /* NB: should send a message to the session logger to avoid blocking. */
927 #ifdef SUPPORT_UTMPX
928 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
929 #endif
930 #ifdef SUPPORT_UTMP
931 logwtmp("~", "reboot", "");
932 #endif
933 return (state_func_t) read_ttys;
934 }
935
936 /*
937 * Open the session database.
938 *
939 * NB: We could pass in the size here; is it necessary?
940 */
941 int
942 start_session_db(void)
943 {
944
945 if (session_db && (*session_db->close)(session_db))
946 emergency("session database close: %m");
947 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
948 emergency("session database open: %m");
949 return (1);
950 }
951 return (0);
952
953 }
954
955 /*
956 * Add a new login session.
957 */
958 void
959 add_session(session_t *sp)
960 {
961 DBT key;
962 DBT data;
963
964 if (session_db == NULL)
965 return;
966
967 key.data = &sp->se_process;
968 key.size = sizeof sp->se_process;
969 data.data = &sp;
970 data.size = sizeof sp;
971
972 if ((*session_db->put)(session_db, &key, &data, 0))
973 emergency("insert %d: %m", sp->se_process);
974 #ifdef SUPPORT_UTMPX
975 session_utmpx(sp, 1);
976 #endif
977 }
978
979 /*
980 * Delete an old login session.
981 */
982 void
983 del_session(session_t *sp)
984 {
985 DBT key;
986
987 key.data = &sp->se_process;
988 key.size = sizeof sp->se_process;
989
990 if ((*session_db->del)(session_db, &key, 0))
991 emergency("delete %d: %m", sp->se_process);
992 #ifdef SUPPORT_UTMPX
993 session_utmpx(sp, 0);
994 #endif
995 }
996
997 /*
998 * Look up a login session by pid.
999 */
1000 session_t *
1001 find_session(pid_t pid)
1002 {
1003 DBT key;
1004 DBT data;
1005 session_t *ret;
1006
1007 if (session_db == NULL)
1008 return NULL;
1009
1010 key.data = &pid;
1011 key.size = sizeof pid;
1012 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1013 return 0;
1014 (void)memmove(&ret, data.data, sizeof(ret));
1015 return ret;
1016 }
1017
1018 /*
1019 * Construct an argument vector from a command line.
1020 */
1021 char **
1022 construct_argv(char *command)
1023 {
1024 int argc = 0;
1025 char **argv = malloc(((strlen(command) + 1) / 2 + 1) * sizeof (char *));
1026 static const char separators[] = " \t";
1027
1028 if (argv == NULL)
1029 return (NULL);
1030
1031 if ((argv[argc++] = strtok(command, separators)) == 0) {
1032 free(argv);
1033 return (NULL);
1034 }
1035 while ((argv[argc++] = strtok(NULL, separators)) != NULL)
1036 continue;
1037 return (argv);
1038 }
1039
1040 /*
1041 * Deallocate a session descriptor.
1042 */
1043 void
1044 free_session(session_t *sp)
1045 {
1046
1047 free(sp->se_device);
1048 if (sp->se_getty) {
1049 free(sp->se_getty);
1050 free(sp->se_getty_argv);
1051 }
1052 if (sp->se_window) {
1053 free(sp->se_window);
1054 free(sp->se_window_argv);
1055 }
1056 free(sp);
1057 }
1058
1059 /*
1060 * Allocate a new session descriptor.
1061 */
1062 session_t *
1063 new_session(session_t *sprev, int session_index, struct ttyent *typ)
1064 {
1065 session_t *sp;
1066
1067 if ((typ->ty_status & TTY_ON) == 0 || typ->ty_name == NULL ||
1068 typ->ty_getty == NULL)
1069 return (NULL);
1070
1071 sp = malloc(sizeof (session_t));
1072 if (sp == NULL)
1073 return NULL;
1074 memset(sp, 0, sizeof *sp);
1075
1076 sp->se_flags = SE_PRESENT;
1077 sp->se_index = session_index;
1078
1079 (void)asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1080 if (!sp->se_device)
1081 return NULL;
1082
1083 if (setupargv(sp, typ) == 0) {
1084 free_session(sp);
1085 return (NULL);
1086 }
1087
1088 sp->se_next = NULL;
1089 if (sprev == NULL) {
1090 sessions = sp;
1091 sp->se_prev = NULL;
1092 } else {
1093 sprev->se_next = sp;
1094 sp->se_prev = sprev;
1095 }
1096
1097 return (sp);
1098 }
1099
1100 /*
1101 * Calculate getty and if useful window argv vectors.
1102 */
1103 int
1104 setupargv(session_t *sp, struct ttyent *typ)
1105 {
1106
1107 if (sp->se_getty) {
1108 free(sp->se_getty);
1109 free(sp->se_getty_argv);
1110 }
1111 (void)asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1112 if (!sp->se_getty)
1113 return (0);
1114 sp->se_getty_argv = construct_argv(sp->se_getty);
1115 if (sp->se_getty_argv == NULL) {
1116 warning("can't parse getty for port `%s'", sp->se_device);
1117 free(sp->se_getty);
1118 sp->se_getty = NULL;
1119 return (0);
1120 }
1121 if (typ->ty_window) {
1122 if (sp->se_window)
1123 free(sp->se_window);
1124 sp->se_window = strdup(typ->ty_window);
1125 sp->se_window_argv = construct_argv(sp->se_window);
1126 if (sp->se_window_argv == NULL) {
1127 warning("can't parse window for port `%s'",
1128 sp->se_device);
1129 free(sp->se_window);
1130 sp->se_window = NULL;
1131 return (0);
1132 }
1133 }
1134 return (1);
1135 }
1136
1137 /*
1138 * Walk the list of ttys and create sessions for each active line.
1139 */
1140 state_func_t
1141 read_ttys(void)
1142 {
1143 int session_index = 0;
1144 session_t *sp, *snext;
1145 struct ttyent *typ;
1146
1147 #ifdef SUPPORT_UTMPX
1148 if (sessions == NULL) {
1149 struct stat st;
1150
1151 make_utmpx("", BOOT_MSG, BOOT_TIME, 0, &boot_time, 0);
1152
1153 /*
1154 * If wtmpx is not empty, pick the the down time from there
1155 */
1156 if (stat(_PATH_WTMPX, &st) != -1 && st.st_size != 0) {
1157 struct timeval down_time;
1158
1159 TIMESPEC_TO_TIMEVAL(&down_time,
1160 st.st_atime > st.st_mtime ?
1161 &st.st_atimespec : &st.st_mtimespec);
1162 make_utmpx("", DOWN_MSG, DOWN_TIME, 0, &down_time, 0);
1163 }
1164 }
1165 #endif
1166 /*
1167 * Destroy any previous session state.
1168 * There shouldn't be any, but just in case...
1169 */
1170 for (sp = sessions; sp; sp = snext) {
1171 #ifndef LETS_GET_SMALL
1172 if (sp->se_process)
1173 clear_session_logs(sp, 0);
1174 #endif
1175 snext = sp->se_next;
1176 free_session(sp);
1177 }
1178 sessions = NULL;
1179
1180 if (start_session_db()) {
1181 warning("start_session_db failed, death");
1182 #ifdef CHROOT
1183 /* If /etc/rc ran in chroot, we want to kill any survivors. */
1184 if (did_multiuser_chroot)
1185 return (state_func_t)death;
1186 else
1187 #endif /* CHROOT */
1188 return (state_func_t)single_user;
1189 }
1190
1191 do_setttyent();
1192
1193 /*
1194 * Allocate a session entry for each active port.
1195 * Note that sp starts at 0.
1196 */
1197 while ((typ = getttyent()) != NULL)
1198 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1199 sp = snext;
1200 endttyent();
1201
1202 return (state_func_t)multi_user;
1203 }
1204
1205 /*
1206 * Start a window system running.
1207 */
1208 void
1209 start_window_system(session_t *sp)
1210 {
1211 pid_t pid;
1212 sigset_t mask;
1213
1214 if ((pid = fork()) == -1) {
1215 emergency("can't fork for window system on port `%s': %m",
1216 sp->se_device);
1217 /* hope that getty fails and we can try again */
1218 return;
1219 }
1220
1221 if (pid)
1222 return;
1223
1224 sigemptyset(&mask);
1225 sigprocmask(SIG_SETMASK, &mask, NULL);
1226
1227 if (setsid() < 0)
1228 emergency("setsid failed (window): %m");
1229
1230 (void)execv(sp->se_window_argv[0], sp->se_window_argv);
1231 stall("can't exec window system `%s' for port `%s': %m",
1232 sp->se_window_argv[0], sp->se_device);
1233 _exit(1);
1234 }
1235
1236 /*
1237 * Start a login session running.
1238 */
1239 pid_t
1240 start_getty(session_t *sp)
1241 {
1242 pid_t pid;
1243 sigset_t mask;
1244 time_t current_time = time(NULL);
1245
1246 /*
1247 * fork(), not vfork() -- we can't afford to block.
1248 */
1249 if ((pid = fork()) == -1) {
1250 emergency("can't fork for getty on port `%s': %m",
1251 sp->se_device);
1252 return -1;
1253 }
1254
1255 if (pid)
1256 return pid;
1257
1258 #ifdef CHROOT
1259 /* If /etc/rc did proceed inside chroot, we have to try as well. */
1260 if (did_multiuser_chroot)
1261 if (chroot(rootdir) != 0) {
1262 stall("can't chroot getty `%s' inside `%s': %m",
1263 sp->se_getty_argv[0], rootdir);
1264 _exit(1);
1265 }
1266 #endif /* CHROOT */
1267
1268 if (current_time > sp->se_started.tv_sec &&
1269 current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1270 warning("getty repeating too quickly on port `%s', sleeping",
1271 sp->se_device);
1272 (void)sleep(GETTY_SLEEP);
1273 }
1274
1275 if (sp->se_window) {
1276 start_window_system(sp);
1277 (void)sleep(WINDOW_WAIT);
1278 }
1279
1280 (void)sigemptyset(&mask);
1281 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1282
1283 (void)execv(sp->se_getty_argv[0], sp->se_getty_argv);
1284 stall("can't exec getty `%s' for port `%s': %m",
1285 sp->se_getty_argv[0], sp->se_device);
1286 _exit(1);
1287 /*NOTREACHED*/
1288 }
1289 #ifdef SUPPORT_UTMPX
1290 static void
1291 session_utmpx(const session_t *sp, int add)
1292 {
1293 const char *name = sp->se_getty ? sp->se_getty :
1294 (sp->se_window ? sp->se_window : "");
1295 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1296
1297 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1298 sp->se_process, &sp->se_started, sp->se_index);
1299 }
1300
1301 static void
1302 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1303 const struct timeval *tv, int session)
1304 {
1305 struct utmpx ut;
1306 const char *eline;
1307
1308 (void)memset(&ut, 0, sizeof(ut));
1309 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1310 ut.ut_type = type;
1311 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1312 ut.ut_pid = pid;
1313 if (tv)
1314 ut.ut_tv = *tv;
1315 else
1316 (void)gettimeofday(&ut.ut_tv, NULL);
1317 ut.ut_session = session;
1318
1319 eline = line + strlen(line);
1320 if (eline - line >= sizeof(ut.ut_id))
1321 line = eline - sizeof(ut.ut_id);
1322 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1323
1324 if (pututxline(&ut) == NULL)
1325 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1326 }
1327
1328 static char
1329 get_runlevel(const state_t s)
1330 {
1331 if (s == (state_t)single_user)
1332 return SINGLE_USER;
1333 if (s == (state_t)runcom)
1334 return RUNCOM;
1335 if (s == (state_t)read_ttys)
1336 return READ_TTYS;
1337 if (s == (state_t)multi_user)
1338 return MULTI_USER;
1339 if (s == (state_t)clean_ttys)
1340 return CLEAN_TTYS;
1341 if (s == (state_t)catatonia)
1342 return CATATONIA;
1343 return DEATH;
1344 }
1345
1346 static void
1347 utmpx_set_runlevel(char old, char new)
1348 {
1349 struct utmpx ut;
1350
1351 /*
1352 * Don't record any transitions until we did the first transition
1353 * to read ttys, which is when we are guaranteed to have a read-write
1354 * /var. Perhaps use a different variable for this?
1355 */
1356 if (sessions == NULL)
1357 return;
1358
1359 (void)memset(&ut, 0, sizeof(ut));
1360 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1361 ut.ut_type = RUN_LVL;
1362 (void)gettimeofday(&ut.ut_tv, NULL);
1363 ut.ut_exit.e_exit = old;
1364 ut.ut_exit.e_termination = new;
1365 if (pututxline(&ut) == NULL)
1366 warning("can't add utmpx record for `runlevel': %m");
1367 }
1368 #endif /* SUPPORT_UTMPX */
1369
1370 #endif /* LETS_GET_SMALL */
1371
1372 /*
1373 * Collect exit status for a child.
1374 * If an exiting login, start a new login running.
1375 */
1376 void
1377 collect_child(pid_t pid, int status)
1378 {
1379 #ifndef LETS_GET_SMALL
1380 session_t *sp, *sprev, *snext;
1381
1382 if (! sessions)
1383 return;
1384
1385 if ((sp = find_session(pid)) == NULL)
1386 return;
1387
1388 clear_session_logs(sp, status);
1389 del_session(sp);
1390 sp->se_process = 0;
1391
1392 if (sp->se_flags & SE_SHUTDOWN) {
1393 if ((sprev = sp->se_prev) != NULL)
1394 sprev->se_next = sp->se_next;
1395 else
1396 sessions = sp->se_next;
1397 if ((snext = sp->se_next) != NULL)
1398 snext->se_prev = sp->se_prev;
1399 free_session(sp);
1400 return;
1401 }
1402
1403 if ((pid = start_getty(sp)) == -1) {
1404 /* serious trouble */
1405 requested_transition = clean_ttys;
1406 return;
1407 }
1408
1409 sp->se_process = pid;
1410 (void)gettimeofday(&sp->se_started, NULL);
1411 add_session(sp);
1412 #endif /* LETS_GET_SMALL */
1413 }
1414
1415 /*
1416 * Catch a signal and request a state transition.
1417 */
1418 void
1419 transition_handler(int sig)
1420 {
1421
1422 switch (sig) {
1423 #ifndef LETS_GET_SMALL
1424 case SIGHUP:
1425 requested_transition = clean_ttys;
1426 break;
1427 case SIGTERM:
1428 requested_transition = death;
1429 break;
1430 case SIGTSTP:
1431 requested_transition = catatonia;
1432 break;
1433 #endif /* LETS_GET_SMALL */
1434 default:
1435 requested_transition = 0;
1436 break;
1437 }
1438 }
1439
1440 #ifndef LETS_GET_SMALL
1441 /*
1442 * Take the system multiuser.
1443 */
1444 state_func_t
1445 multi_user(void)
1446 {
1447 pid_t pid;
1448 int status;
1449 session_t *sp;
1450
1451 requested_transition = 0;
1452
1453 /*
1454 * If the administrator has not set the security level to -1
1455 * to indicate that the kernel should not run multiuser in secure
1456 * mode, and the run script has not set a higher level of security
1457 * than level 1, then put the kernel into secure mode.
1458 */
1459 if (getsecuritylevel() == 0)
1460 setsecuritylevel(1);
1461
1462 for (sp = sessions; sp; sp = sp->se_next) {
1463 if (sp->se_process)
1464 continue;
1465 if ((pid = start_getty(sp)) == -1) {
1466 /* serious trouble */
1467 requested_transition = clean_ttys;
1468 break;
1469 }
1470 sp->se_process = pid;
1471 (void)gettimeofday(&sp->se_started, NULL);
1472 add_session(sp);
1473 }
1474
1475 while (!requested_transition)
1476 if ((pid = waitpid(-1, &status, 0)) != -1)
1477 collect_child(pid, status);
1478
1479 return (state_func_t)requested_transition;
1480 }
1481
1482 /*
1483 * This is an n-squared algorithm. We hope it isn't run often...
1484 */
1485 state_func_t
1486 clean_ttys(void)
1487 {
1488 session_t *sp, *sprev;
1489 struct ttyent *typ;
1490 int session_index = 0;
1491 int devlen;
1492
1493 for (sp = sessions; sp; sp = sp->se_next)
1494 sp->se_flags &= ~SE_PRESENT;
1495
1496 do_setttyent();
1497
1498 devlen = sizeof(_PATH_DEV) - 1;
1499 while ((typ = getttyent()) != NULL) {
1500 ++session_index;
1501
1502 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1503 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1504 break;
1505
1506 if (sp) {
1507 sp->se_flags |= SE_PRESENT;
1508 if (sp->se_index != session_index) {
1509 warning("port `%s' changed utmp index from "
1510 "%d to %d", sp->se_device, sp->se_index,
1511 session_index);
1512 sp->se_index = session_index;
1513 }
1514 if ((typ->ty_status & TTY_ON) == 0 ||
1515 typ->ty_getty == 0) {
1516 sp->se_flags |= SE_SHUTDOWN;
1517 if (sp->se_process != 0)
1518 (void)kill(sp->se_process, SIGHUP);
1519 continue;
1520 }
1521 sp->se_flags &= ~SE_SHUTDOWN;
1522 if (setupargv(sp, typ) == 0) {
1523 warning("can't parse getty for port `%s'",
1524 sp->se_device);
1525 sp->se_flags |= SE_SHUTDOWN;
1526 if (sp->se_process != 0)
1527 (void)kill(sp->se_process, SIGHUP);
1528 }
1529 continue;
1530 }
1531
1532 new_session(sprev, session_index, typ);
1533 }
1534
1535 endttyent();
1536
1537 for (sp = sessions; sp; sp = sp->se_next)
1538 if ((sp->se_flags & SE_PRESENT) == 0) {
1539 sp->se_flags |= SE_SHUTDOWN;
1540 if (sp->se_process != 0)
1541 (void)kill(sp->se_process, SIGHUP);
1542 }
1543
1544 return (state_func_t)multi_user;
1545 }
1546
1547 /*
1548 * Block further logins.
1549 */
1550 state_func_t
1551 catatonia(void)
1552 {
1553 session_t *sp;
1554
1555 for (sp = sessions; sp; sp = sp->se_next)
1556 sp->se_flags |= SE_SHUTDOWN;
1557
1558 return (state_func_t)multi_user;
1559 }
1560 #endif /* LETS_GET_SMALL */
1561
1562 /*
1563 * Note SIGALRM.
1564 */
1565 void
1566 /*ARGSUSED*/
1567 alrm_handler(int sig)
1568 {
1569
1570 clang = 1;
1571 }
1572
1573 #ifndef LETS_GET_SMALL
1574 /*
1575 * Bring the system down to single user.
1576 */
1577 state_func_t
1578 death(void)
1579 {
1580 session_t *sp;
1581 int i, status;
1582 pid_t pid;
1583 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1584
1585 for (sp = sessions; sp; sp = sp->se_next)
1586 sp->se_flags |= SE_SHUTDOWN;
1587
1588 /* NB: should send a message to the session logger to avoid blocking. */
1589 #ifdef SUPPORT_UTMPX
1590 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1591 #endif
1592 #ifdef SUPPORT_UTMP
1593 logwtmp("~", "shutdown", "");
1594 #endif
1595
1596 for (i = 0; i < 3; ++i) {
1597 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1598 return (state_func_t)single_user;
1599
1600 clang = 0;
1601 alarm(DEATH_WATCH);
1602 do
1603 if ((pid = waitpid(-1, &status, 0)) != -1)
1604 collect_child(pid, status);
1605 while (clang == 0 && errno != ECHILD);
1606
1607 if (errno == ECHILD)
1608 return (state_func_t)single_user;
1609 }
1610
1611 warning("some processes would not die; ps axl advised");
1612
1613 return (state_func_t)single_user;
1614 }
1615 #endif /* LETS_GET_SMALL */
1616
1617 #ifdef MFS_DEV_IF_NO_CONSOLE
1618
1619 static void
1620 mapfile(struct mappedfile *mf)
1621 {
1622 int fd;
1623 struct stat st;
1624
1625 if (lstat(mf->path, &st) == -1)
1626 return;
1627
1628 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1629 mf->buf = malloc(st.st_size + 1);
1630 if (mf->buf == NULL)
1631 return;
1632 mf->buf[st.st_size] = 0;
1633 if (readlink(mf->path, mf->buf, st.st_size) != st.st_size)
1634 return;
1635 mf->len = -1;
1636 return;
1637 }
1638
1639 if ((fd = open(mf->path, O_RDONLY)) == -1)
1640 return;
1641 mf->buf = mmap(0, (size_t)st.st_size, PROT_READ,
1642 MAP_FILE|MAP_SHARED, fd, (off_t)0);
1643 (void)close(fd);
1644 if (mf->buf == MAP_FAILED)
1645 return;
1646 mf->len = st.st_size;
1647 }
1648
1649 static void
1650 writefile(struct mappedfile *mf)
1651 {
1652 int fd;
1653
1654 if (mf->len == -1) {
1655 symlink(mf->buf, mf->path);
1656 free(mf->buf);
1657 return;
1658 }
1659
1660 if (mf->len == 0)
1661 return;
1662 fd = open(mf->path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
1663 if (fd == -1)
1664 return;
1665 (void)write(fd, mf->buf, mf->len);
1666 (void)munmap(mf->buf, mf->len);
1667 (void)close(fd);
1668 }
1669
1670 static int
1671 mfs_dev(void)
1672 {
1673 /*
1674 * We cannot print errors so we bail out silently...
1675 */
1676 pid_t pid;
1677 int status;
1678 dev_t dev;
1679 char *fs_size;
1680 #ifdef CPU_CONSDEV
1681 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1682 size_t olen;
1683 #endif
1684
1685 /* If we have /dev/console, assume all is OK */
1686 if (access(_PATH_CONSOLE, F_OK) != -1)
1687 return(0);
1688
1689 /* Grab the contents of MAKEDEV */
1690 mapfile(&mfile[0]);
1691
1692 /* Grab the contents of MAKEDEV.local */
1693 mapfile(&mfile[1]);
1694
1695 /* Mount an mfs over /dev so we can create devices */
1696 switch ((pid = fork())) {
1697 case 0:
1698 asprintf(&fs_size, "%d", FSSIZE);
1699 if (fs_size == NULL)
1700 return(-1);
1701 (void)execl(INIT_MOUNT_MFS, "mount_mfs",
1702 "-b", "4096", "-f", "512",
1703 "-s", fs_size, "-n", STR(NINODE),
1704 "-p", "0755",
1705 "swap", "/dev", NULL);
1706 _exit(1);
1707 /*NOTREACHED*/
1708
1709 case -1:
1710 return(-1);
1711
1712 default:
1713 if (waitpid(pid, &status, 0) == -1)
1714 return(-1);
1715 if (status != 0)
1716 return(-1);
1717 break;
1718 }
1719
1720 #ifdef CPU_CONSDEV
1721 olen = sizeof(dev);
1722 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
1723 NULL, 0) == -1)
1724 #endif
1725 dev = makedev(0, 0);
1726
1727 /* Make a console for us, so we can see things happening */
1728 if (mknod(_PATH_CONSOLE, 0666 | S_IFCHR, dev) == -1)
1729 return(-1);
1730
1731 (void)freopen(_PATH_CONSOLE, "a", stderr);
1732
1733 warnx("Creating mfs /dev (%d blocks, %d inodes)", FSSIZE, NINODE);
1734
1735 /* Create a MAKEDEV script in the mfs /dev */
1736 writefile(&mfile[0]);
1737
1738 /* Create a MAKEDEV.local script in the mfs /dev */
1739 writefile(&mfile[1]);
1740
1741 /* Run the makedev script to create devices */
1742 switch ((pid = fork())) {
1743 case 0:
1744 dup2(2, 1); /* Give the script stdout */
1745 if (chdir("/dev") == 0)
1746 (void)execl(INIT_BSHELL, "sh",
1747 mfile[0].len ? "./MAKEDEV" : "/etc/MAKEDEV",
1748 "init", NULL);
1749 _exit(1);
1750 /* NOTREACHED */
1751
1752 case -1:
1753 break;
1754
1755 default:
1756 if (waitpid(pid, &status, 0) == -1)
1757 break;
1758 if (status != 0) {
1759 errno = EINVAL;
1760 break;
1761 }
1762 return 0;
1763 }
1764 warn("Unable to run MAKEDEV");
1765 return (-1);
1766 }
1767 #endif
1768
1769 int
1770 do_setttyent(void)
1771 {
1772 endttyent();
1773 #ifdef CHROOT
1774 if (did_multiuser_chroot) {
1775 char path[PATH_MAX];
1776
1777 snprintf(path, sizeof(path), "%s/%s", rootdir, _PATH_TTYS);
1778
1779 return setttyentpath(path);
1780 } else
1781 #endif /* CHROOT */
1782 return setttyent();
1783 }
1784
1785 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
1786
1787 int
1788 createsysctlnode()
1789 {
1790 struct sysctlnode node;
1791 int mib[2];
1792 size_t len;
1793
1794 /*
1795 * Create top-level dynamic sysctl node. Its child nodes will only
1796 * be readable by the superuser, since regular mortals should not
1797 * care ("Sssh, it's a secret!").
1798 */
1799 len = sizeof(struct sysctlnode);
1800 mib[0] = CTL_CREATE;
1801
1802 memset(&node, 0, len);
1803 node.sysctl_flags = SYSCTL_VERSION | CTLFLAG_READWRITE |
1804 CTLFLAG_PRIVATE | CTLTYPE_NODE;
1805 node.sysctl_num = CTL_CREATE;
1806 snprintf(node.sysctl_name, SYSCTL_NAMELEN, "init");
1807 if (sysctl(&mib[0], 1, &node, &len, &node, len) == -1) {
1808 warning("could not create init node: %m");
1809 return (-1);
1810 }
1811
1812 /*
1813 * Create second level dynamic node capable of holding pathname.
1814 * Provide "/" as the default value.
1815 */
1816 len = sizeof(struct sysctlnode);
1817 mib[0] = node.sysctl_num;
1818 mib[1] = CTL_CREATE;
1819
1820 memset(&node, 0, len);
1821 node.sysctl_flags = SYSCTL_VERSION | CTLFLAG_READWRITE |
1822 CTLTYPE_STRING | CTLFLAG_OWNDATA;
1823 node.sysctl_size = _POSIX_PATH_MAX;
1824 node.sysctl_data = __UNCONST("/");
1825 node.sysctl_num = CTL_CREATE;
1826 snprintf(node.sysctl_name, SYSCTL_NAMELEN, "root");
1827 if (sysctl(&mib[0], 2, NULL, NULL, &node, len) == -1) {
1828 warning("could not create init.root node: %m");
1829 return (-1);
1830 }
1831
1832 return (0);
1833 }
1834
1835 int
1836 shouldchroot()
1837 {
1838 struct sysctlnode node;
1839 size_t len, cnt;
1840 int mib;
1841
1842 len = sizeof(struct sysctlnode);
1843
1844 if (sysctlbyname("init.root", rootdir, &len, NULL, 0) == -1) {
1845 warning("could not read init.root: %m");
1846
1847 /* Child killed our node. Recreate it. */
1848 if (errno == ENOENT) {
1849 /* Destroy whatever is left, recreate from scratch. */
1850 if (sysctlnametomib("init", &mib, &cnt) != -1) {
1851 memset(&node, 0, sizeof(node));
1852 node.sysctl_flags = SYSCTL_VERSION;
1853 node.sysctl_num = mib;
1854 mib = CTL_DESTROY;
1855
1856 (void)sysctl(&mib, 1, NULL, NULL, &node,
1857 sizeof(node));
1858 }
1859
1860 createsysctlnode();
1861 }
1862
1863 /* We certainly won't chroot. */
1864 return (0);
1865 }
1866
1867 if (rootdir[len] != '\0' || strlen(rootdir) != len - 1) {
1868 warning("init.root is not a string");
1869 return (0);
1870 }
1871
1872 if (strcmp(rootdir, "/") == 0)
1873 return (0);
1874
1875 return (1);
1876 }
1877
1878 #endif /* !LETS_GET_SMALL && CHROOT */
1879