init.c revision 1.80 1 /* $NetBSD: init.c,v 1.80 2006/09/25 19:42:04 christos 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.80 2006/09/25 19:42:04 christos 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");
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: %m, 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("shell stopped, restarting");
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': %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("`%s' on `%s' stopped, restarting",
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("start_session_db failed, death");
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",
1250 sp->se_device);
1251 return -1;
1252 }
1253
1254 if (pid)
1255 return pid;
1256
1257 #ifdef CHROOT
1258 /* If /etc/rc did proceed inside chroot, we have to try as well. */
1259 if (did_multiuser_chroot)
1260 if (chroot(rootdir) != 0) {
1261 stall("can't chroot getty `%s' inside `%s': %m",
1262 sp->se_getty_argv[0], rootdir);
1263 _exit(1);
1264 }
1265 #endif /* CHROOT */
1266
1267 if (current_time > sp->se_started.tv_sec &&
1268 current_time - sp->se_started.tv_sec < GETTY_SPACING) {
1269 warning("getty repeating too quickly on port `%s', sleeping",
1270 sp->se_device);
1271 (void)sleep(GETTY_SLEEP);
1272 }
1273
1274 if (sp->se_window) {
1275 start_window_system(sp);
1276 (void)sleep(WINDOW_WAIT);
1277 }
1278
1279 (void)sigemptyset(&mask);
1280 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1281
1282 (void)execv(sp->se_getty_argv[0], sp->se_getty_argv);
1283 stall("can't exec getty `%s' for port `%s': %m",
1284 sp->se_getty_argv[0], sp->se_device);
1285 _exit(1);
1286 /*NOTREACHED*/
1287 }
1288 #ifdef SUPPORT_UTMPX
1289 static void
1290 session_utmpx(const session_t *sp, int add)
1291 {
1292 const char *name = sp->se_getty ? sp->se_getty :
1293 (sp->se_window ? sp->se_window : "");
1294 const char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
1295
1296 make_utmpx(name, line, add ? LOGIN_PROCESS : DEAD_PROCESS,
1297 sp->se_process, &sp->se_started, sp->se_index);
1298 }
1299
1300 static void
1301 make_utmpx(const char *name, const char *line, int type, pid_t pid,
1302 const struct timeval *tv, int session)
1303 {
1304 struct utmpx ut;
1305 const char *eline;
1306
1307 (void)memset(&ut, 0, sizeof(ut));
1308 (void)strlcpy(ut.ut_name, name, sizeof(ut.ut_name));
1309 ut.ut_type = type;
1310 (void)strlcpy(ut.ut_line, line, sizeof(ut.ut_line));
1311 ut.ut_pid = pid;
1312 if (tv)
1313 ut.ut_tv = *tv;
1314 else
1315 (void)gettimeofday(&ut.ut_tv, NULL);
1316 ut.ut_session = session;
1317
1318 eline = line + strlen(line);
1319 if (eline - line >= sizeof(ut.ut_id))
1320 line = eline - sizeof(ut.ut_id);
1321 (void)strncpy(ut.ut_id, line, sizeof(ut.ut_id));
1322
1323 if (pututxline(&ut) == NULL)
1324 warning("can't add utmpx record for `%s': %m", ut.ut_line);
1325 }
1326
1327 static char
1328 get_runlevel(const state_t s)
1329 {
1330 if (s == (state_t)single_user)
1331 return SINGLE_USER;
1332 if (s == (state_t)runcom)
1333 return RUNCOM;
1334 if (s == (state_t)read_ttys)
1335 return READ_TTYS;
1336 if (s == (state_t)multi_user)
1337 return MULTI_USER;
1338 if (s == (state_t)clean_ttys)
1339 return CLEAN_TTYS;
1340 if (s == (state_t)catatonia)
1341 return CATATONIA;
1342 return DEATH;
1343 }
1344
1345 static void
1346 utmpx_set_runlevel(char old, char new)
1347 {
1348 struct utmpx ut;
1349
1350 (void)memset(&ut, 0, sizeof(ut));
1351 (void)snprintf(ut.ut_line, sizeof(ut.ut_line), RUNLVL_MSG, new);
1352 ut.ut_type = RUN_LVL;
1353 (void)gettimeofday(&ut.ut_tv, NULL);
1354 ut.ut_exit.e_exit = old;
1355 ut.ut_exit.e_termination = new;
1356 if (pututxline(&ut) == NULL)
1357 warning("can't add utmpx record for `runlevel': %m");
1358 }
1359 #endif /* SUPPORT_UTMPX */
1360
1361 #endif /* LETS_GET_SMALL */
1362
1363 /*
1364 * Collect exit status for a child.
1365 * If an exiting login, start a new login running.
1366 */
1367 void
1368 collect_child(pid_t pid, int status)
1369 {
1370 #ifndef LETS_GET_SMALL
1371 session_t *sp, *sprev, *snext;
1372
1373 if (! sessions)
1374 return;
1375
1376 if ((sp = find_session(pid)) == NULL)
1377 return;
1378
1379 clear_session_logs(sp, status);
1380 del_session(sp);
1381 sp->se_process = 0;
1382
1383 if (sp->se_flags & SE_SHUTDOWN) {
1384 if ((sprev = sp->se_prev) != NULL)
1385 sprev->se_next = sp->se_next;
1386 else
1387 sessions = sp->se_next;
1388 if ((snext = sp->se_next) != NULL)
1389 snext->se_prev = sp->se_prev;
1390 free_session(sp);
1391 return;
1392 }
1393
1394 if ((pid = start_getty(sp)) == -1) {
1395 /* serious trouble */
1396 requested_transition = clean_ttys;
1397 return;
1398 }
1399
1400 sp->se_process = pid;
1401 (void)gettimeofday(&sp->se_started, NULL);
1402 add_session(sp);
1403 #endif /* LETS_GET_SMALL */
1404 }
1405
1406 /*
1407 * Catch a signal and request a state transition.
1408 */
1409 void
1410 transition_handler(int sig)
1411 {
1412
1413 switch (sig) {
1414 #ifndef LETS_GET_SMALL
1415 case SIGHUP:
1416 requested_transition = clean_ttys;
1417 break;
1418 case SIGTERM:
1419 requested_transition = death;
1420 break;
1421 case SIGTSTP:
1422 requested_transition = catatonia;
1423 break;
1424 #endif /* LETS_GET_SMALL */
1425 default:
1426 requested_transition = 0;
1427 break;
1428 }
1429 }
1430
1431 #ifndef LETS_GET_SMALL
1432 /*
1433 * Take the system multiuser.
1434 */
1435 state_func_t
1436 multi_user(void)
1437 {
1438 pid_t pid;
1439 int status;
1440 session_t *sp;
1441
1442 requested_transition = 0;
1443
1444 /*
1445 * If the administrator has not set the security level to -1
1446 * to indicate that the kernel should not run multiuser in secure
1447 * mode, and the run script has not set a higher level of security
1448 * than level 1, then put the kernel into secure mode.
1449 */
1450 if (getsecuritylevel() == 0)
1451 setsecuritylevel(1);
1452
1453 for (sp = sessions; sp; sp = sp->se_next) {
1454 if (sp->se_process)
1455 continue;
1456 if ((pid = start_getty(sp)) == -1) {
1457 /* serious trouble */
1458 requested_transition = clean_ttys;
1459 break;
1460 }
1461 sp->se_process = pid;
1462 (void)gettimeofday(&sp->se_started, NULL);
1463 add_session(sp);
1464 }
1465
1466 while (!requested_transition)
1467 if ((pid = waitpid(-1, &status, 0)) != -1)
1468 collect_child(pid, status);
1469
1470 return (state_func_t)requested_transition;
1471 }
1472
1473 /*
1474 * This is an n-squared algorithm. We hope it isn't run often...
1475 */
1476 state_func_t
1477 clean_ttys(void)
1478 {
1479 session_t *sp, *sprev;
1480 struct ttyent *typ;
1481 int session_index = 0;
1482 int devlen;
1483
1484 for (sp = sessions; sp; sp = sp->se_next)
1485 sp->se_flags &= ~SE_PRESENT;
1486
1487 do_setttyent();
1488
1489 devlen = sizeof(_PATH_DEV) - 1;
1490 while ((typ = getttyent()) != NULL) {
1491 ++session_index;
1492
1493 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1494 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1495 break;
1496
1497 if (sp) {
1498 sp->se_flags |= SE_PRESENT;
1499 if (sp->se_index != session_index) {
1500 warning("port `%s' changed utmp index from "
1501 "%d to %d", sp->se_device, sp->se_index,
1502 session_index);
1503 sp->se_index = session_index;
1504 }
1505 if ((typ->ty_status & TTY_ON) == 0 ||
1506 typ->ty_getty == 0) {
1507 sp->se_flags |= SE_SHUTDOWN;
1508 if (sp->se_process != 0)
1509 (void)kill(sp->se_process, SIGHUP);
1510 continue;
1511 }
1512 sp->se_flags &= ~SE_SHUTDOWN;
1513 if (setupargv(sp, typ) == 0) {
1514 warning("can't parse getty for port `%s'",
1515 sp->se_device);
1516 sp->se_flags |= SE_SHUTDOWN;
1517 if (sp->se_process != 0)
1518 (void)kill(sp->se_process, SIGHUP);
1519 }
1520 continue;
1521 }
1522
1523 new_session(sprev, session_index, typ);
1524 }
1525
1526 endttyent();
1527
1528 for (sp = sessions; sp; sp = sp->se_next)
1529 if ((sp->se_flags & SE_PRESENT) == 0) {
1530 sp->se_flags |= SE_SHUTDOWN;
1531 if (sp->se_process != 0)
1532 (void)kill(sp->se_process, SIGHUP);
1533 }
1534
1535 return (state_func_t)multi_user;
1536 }
1537
1538 /*
1539 * Block further logins.
1540 */
1541 state_func_t
1542 catatonia(void)
1543 {
1544 session_t *sp;
1545
1546 for (sp = sessions; sp; sp = sp->se_next)
1547 sp->se_flags |= SE_SHUTDOWN;
1548
1549 return (state_func_t)multi_user;
1550 }
1551 #endif /* LETS_GET_SMALL */
1552
1553 /*
1554 * Note SIGALRM.
1555 */
1556 void
1557 /*ARGSUSED*/
1558 alrm_handler(int sig)
1559 {
1560
1561 clang = 1;
1562 }
1563
1564 #ifndef LETS_GET_SMALL
1565 /*
1566 * Bring the system down to single user.
1567 */
1568 state_func_t
1569 death(void)
1570 {
1571 session_t *sp;
1572 int i, status;
1573 pid_t pid;
1574 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1575
1576 for (sp = sessions; sp; sp = sp->se_next)
1577 sp->se_flags |= SE_SHUTDOWN;
1578
1579 /* NB: should send a message to the session logger to avoid blocking. */
1580 #ifdef SUPPORT_UTMPX
1581 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1582 #endif
1583 #ifdef SUPPORT_UTMP
1584 logwtmp("~", "shutdown", "");
1585 #endif
1586
1587 for (i = 0; i < 3; ++i) {
1588 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1589 return (state_func_t)single_user;
1590
1591 clang = 0;
1592 alarm(DEATH_WATCH);
1593 do
1594 if ((pid = waitpid(-1, &status, 0)) != -1)
1595 collect_child(pid, status);
1596 while (clang == 0 && errno != ECHILD);
1597
1598 if (errno == ECHILD)
1599 return (state_func_t)single_user;
1600 }
1601
1602 warning("some processes would not die; ps axl advised");
1603
1604 return (state_func_t)single_user;
1605 }
1606 #endif /* LETS_GET_SMALL */
1607
1608 #ifdef MFS_DEV_IF_NO_CONSOLE
1609
1610 static void
1611 mapfile(struct mappedfile *mf)
1612 {
1613 int fd;
1614 struct stat st;
1615
1616 if (lstat(mf->path, &st) == -1)
1617 return;
1618
1619 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1620 mf->buf = malloc(st.st_size + 1);
1621 if (mf->buf == NULL)
1622 return;
1623 mf->buf[st.st_size] = 0;
1624 if (readlink(mf->path, mf->buf, st.st_size) != st.st_size)
1625 return;
1626 mf->len = -1;
1627 return;
1628 }
1629
1630 if ((fd = open(mf->path, O_RDONLY)) == -1)
1631 return;
1632 mf->buf = mmap(0, (size_t)st.st_size, PROT_READ,
1633 MAP_FILE|MAP_SHARED, fd, (off_t)0);
1634 (void)close(fd);
1635 if (mf->buf == MAP_FAILED)
1636 return;
1637 mf->len = st.st_size;
1638 }
1639
1640 static void
1641 writefile(struct mappedfile *mf)
1642 {
1643 int fd;
1644
1645 if (mf->len == -1) {
1646 symlink(mf->buf, mf->path);
1647 free(mf->buf);
1648 return;
1649 }
1650
1651 if (mf->len == 0)
1652 return;
1653 fd = open(mf->path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
1654 if (fd == -1)
1655 return;
1656 (void)write(fd, mf->buf, mf->len);
1657 (void)munmap(mf->buf, mf->len);
1658 (void)close(fd);
1659 }
1660
1661 static int
1662 mfs_dev(void)
1663 {
1664 /*
1665 * We cannot print errors so we bail out silently...
1666 */
1667 pid_t pid;
1668 int status;
1669 dev_t dev;
1670 char *fs_size;
1671 #ifdef CPU_CONSDEV
1672 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1673 size_t olen;
1674 #endif
1675
1676 /* If we have /dev/console, assume all is OK */
1677 if (access(_PATH_CONSOLE, F_OK) != -1)
1678 return(0);
1679
1680 /* Grab the contents of MAKEDEV */
1681 mapfile(&mfile[0]);
1682
1683 /* Grab the contents of MAKEDEV.local */
1684 mapfile(&mfile[1]);
1685
1686 /* Mount an mfs over /dev so we can create devices */
1687 switch ((pid = fork())) {
1688 case 0:
1689 asprintf(&fs_size, "%d", FSSIZE);
1690 if (fs_size == NULL)
1691 return(-1);
1692 (void)execl(INIT_MOUNT_MFS, "mount_mfs",
1693 "-b", "4096", "-f", "512",
1694 "-s", fs_size, "-n", STR(NINODE),
1695 "-p", "0755",
1696 "swap", "/dev", NULL);
1697 _exit(1);
1698 /*NOTREACHED*/
1699
1700 case -1:
1701 return(-1);
1702
1703 default:
1704 if (waitpid(pid, &status, 0) == -1)
1705 return(-1);
1706 if (status != 0)
1707 return(-1);
1708 break;
1709 }
1710
1711 #ifdef CPU_CONSDEV
1712 olen = sizeof(dev);
1713 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
1714 NULL, 0) == -1)
1715 #endif
1716 dev = makedev(0, 0);
1717
1718 /* Make a console for us, so we can see things happening */
1719 if (mknod(_PATH_CONSOLE, 0666 | S_IFCHR, dev) == -1)
1720 return(-1);
1721
1722 (void)freopen(_PATH_CONSOLE, "a", stderr);
1723
1724 warnx("Creating mfs /dev (%d blocks, %d inodes)", FSSIZE, NINODE);
1725
1726 /* Create a MAKEDEV script in the mfs /dev */
1727 writefile(&mfile[0]);
1728
1729 /* Create a MAKEDEV.local script in the mfs /dev */
1730 writefile(&mfile[1]);
1731
1732 /* Run the makedev script to create devices */
1733 switch ((pid = fork())) {
1734 case 0:
1735 dup2(2, 1); /* Give the script stdout */
1736 if (chdir("/dev") == 0)
1737 (void)execl(INIT_BSHELL, "sh",
1738 mfile[0].len ? "./MAKEDEV" : "/etc/MAKEDEV",
1739 "init", NULL);
1740 _exit(1);
1741 /* NOTREACHED */
1742
1743 case -1:
1744 break;
1745
1746 default:
1747 if (waitpid(pid, &status, 0) == -1)
1748 break;
1749 if (status != 0) {
1750 errno = EINVAL;
1751 break;
1752 }
1753 return 0;
1754 }
1755 warn("Unable to run MAKEDEV");
1756 return (-1);
1757 }
1758 #endif
1759
1760 int
1761 do_setttyent(void)
1762 {
1763 endttyent();
1764 #ifdef CHROOT
1765 if (did_multiuser_chroot) {
1766 char path[PATH_MAX];
1767
1768 snprintf(path, sizeof(path), "%s/%s", rootdir, _PATH_TTYS);
1769
1770 return setttyentpath(path);
1771 } else
1772 #endif /* CHROOT */
1773 return setttyent();
1774 }
1775
1776 #if !defined(LETS_GET_SMALL) && defined(CHROOT)
1777
1778 int
1779 createsysctlnode()
1780 {
1781 struct sysctlnode node;
1782 int mib[2];
1783 size_t len;
1784
1785 /*
1786 * Create top-level dynamic sysctl node. Its child nodes will only
1787 * be readable by the superuser, since regular mortals should not
1788 * care ("Sssh, it's a secret!").
1789 */
1790 len = sizeof(struct sysctlnode);
1791 mib[0] = CTL_CREATE;
1792
1793 memset(&node, 0, len);
1794 node.sysctl_flags = SYSCTL_VERSION | CTLFLAG_READWRITE |
1795 CTLFLAG_PRIVATE | CTLTYPE_NODE;
1796 node.sysctl_num = CTL_CREATE;
1797 snprintf(node.sysctl_name, SYSCTL_NAMELEN, "init");
1798 if (sysctl(&mib[0], 1, &node, &len, &node, len) == -1) {
1799 warning("could not create init node: %m");
1800 return (-1);
1801 }
1802
1803 /*
1804 * Create second level dynamic node capable of holding pathname.
1805 * Provide "/" as the default value.
1806 */
1807 len = sizeof(struct sysctlnode);
1808 mib[0] = node.sysctl_num;
1809 mib[1] = CTL_CREATE;
1810
1811 memset(&node, 0, len);
1812 node.sysctl_flags = SYSCTL_VERSION | CTLFLAG_READWRITE |
1813 CTLTYPE_STRING | CTLFLAG_OWNDATA;
1814 node.sysctl_size = _POSIX_PATH_MAX;
1815 node.sysctl_data = __UNCONST("/");
1816 node.sysctl_num = CTL_CREATE;
1817 snprintf(node.sysctl_name, SYSCTL_NAMELEN, "root");
1818 if (sysctl(&mib[0], 2, NULL, NULL, &node, len) == -1) {
1819 warning("could not create init.root node: %m");
1820 return (-1);
1821 }
1822
1823 return (0);
1824 }
1825
1826 int
1827 shouldchroot()
1828 {
1829 struct sysctlnode node;
1830 size_t len, cnt;
1831 int mib;
1832
1833 len = sizeof(struct sysctlnode);
1834
1835 if (sysctlbyname("init.root", rootdir, &len, NULL, 0) == -1) {
1836 warning("could not read init.root: %m");
1837
1838 /* Child killed our node. Recreate it. */
1839 if (errno == ENOENT) {
1840 /* Destroy whatever is left, recreate from scratch. */
1841 if (sysctlnametomib("init", &mib, &cnt) != -1) {
1842 memset(&node, 0, sizeof(node));
1843 node.sysctl_flags = SYSCTL_VERSION;
1844 node.sysctl_num = mib;
1845 mib = CTL_DESTROY;
1846
1847 (void)sysctl(&mib, 1, NULL, NULL, &node,
1848 sizeof(node));
1849 }
1850
1851 createsysctlnode();
1852 }
1853
1854 /* We certainly won't chroot. */
1855 return (0);
1856 }
1857
1858 if (rootdir[len] != '\0' || strlen(rootdir) != len - 1) {
1859 warning("init.root is not a string");
1860 return (0);
1861 }
1862
1863 if (strcmp(rootdir, "/") == 0)
1864 return (0);
1865
1866 return (1);
1867 }
1868
1869 #endif /* !LETS_GET_SMALL && CHROOT */
1870