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