init.c revision 1.62 1 /* $NetBSD: init.c,v 1.62 2003/09/11 12:51:51 dsl 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.62 2003/09/11 12:51:51 dsl 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
94 #if defined(RESCUEDIR)
95 #define INIT_BSHELL RESCUEDIR "/sh"
96 #define INIT_MOUNT_MFS RESCUEDIR "/mount_mfs"
97 #define INIT_PATH RESCUEDIR ":" _PATH_STDPATH
98 #else
99 #define INIT_BSHELL _PATH_BSHELL
100 #define INIT_MOUNT_MFS "/sbin/mount_mfs"
101 #define INIT_PATH _PATH_STDPATH
102 #endif
103
104 int main(int, char *[]);
105
106 void handle(sig_t, ...);
107 void delset(sigset_t *, ...);
108
109 void stall(const char *, ...)
110 __attribute__((__format__(__printf__,1,2)));
111 void warning(const char *, ...)
112 __attribute__((__format__(__printf__,1,2)));
113 void emergency(const char *, ...)
114 __attribute__((__format__(__printf__,1,2)));
115 void disaster(int);
116 void badsys(int);
117
118 /*
119 * We really need a recursive typedef...
120 * The following at least guarantees that the return type of (*state_t)()
121 * is sufficiently wide to hold a function pointer.
122 */
123 typedef long (*state_func_t)(void);
124 typedef state_func_t (*state_t)(void);
125
126 state_func_t single_user(void);
127 state_func_t runcom(void);
128 state_func_t read_ttys(void);
129 state_func_t multi_user(void);
130 state_func_t clean_ttys(void);
131 state_func_t catatonia(void);
132 state_func_t death(void);
133
134 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
135
136 void transition(state_t);
137 #ifndef LETS_GET_SMALL
138 state_t requested_transition = runcom;
139 #else /* LETS_GET_SMALL */
140 state_t requested_transition = single_user;
141 #endif /* LETS_GET_SMALL */
142
143 void setctty(const char *);
144
145 typedef struct init_session {
146 int se_index; /* index of entry in ttys file */
147 pid_t se_process; /* controlling process */
148 time_t se_started; /* used to avoid thrashing */
149 int se_flags; /* status of session */
150 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
151 #define SE_PRESENT 0x2 /* session is in /etc/ttys */
152 char *se_device; /* filename of port */
153 char *se_getty; /* what to run on that port */
154 char **se_getty_argv; /* pre-parsed argument array */
155 char *se_window; /* window system (started only once) */
156 char **se_window_argv; /* pre-parsed argument array */
157 struct init_session *se_prev;
158 struct init_session *se_next;
159 } session_t;
160
161 void free_session(session_t *);
162 session_t *new_session(session_t *, int, struct ttyent *);
163 session_t *sessions;
164
165 char **construct_argv(char *);
166 void start_window_system(session_t *);
167 void collect_child(pid_t, int);
168 pid_t start_getty(session_t *);
169 void transition_handler(int);
170 void alrm_handler(int);
171 void setsecuritylevel(int);
172 int getsecuritylevel(void);
173 int setupargv(session_t *, struct ttyent *);
174 int clang;
175
176 void clear_session_logs(session_t *, int);
177
178 int start_session_db(void);
179 void add_session(session_t *);
180 void del_session(session_t *);
181 session_t *find_session(pid_t);
182 DB *session_db;
183
184 #ifdef MFS_DEV_IF_NO_CONSOLE
185
186 #define NINODE 896
187 #define FSSIZE ((8192 /* boot area */ \
188 + 2 * 8192 /* two copies of superblock */ \
189 + 4096 /* cylinder group info */ \
190 + NINODE * (128 + 18) /* inode and directory entry */ \
191 + mfile[0].len /* size of MAKEDEV file */ \
192 + 2 * 4096) / 512) /* some slack */
193
194 struct mappedfile {
195 const char *path;
196 char *buf;
197 int len;
198 } mfile[] = {
199 { "/dev/MAKEDEV", NULL, 0 },
200 { "/dev/MAKEDEV.local", NULL, 0 }
201 };
202
203 static int mfs_dev(void);
204 static void mapfile(struct mappedfile *);
205 static void writefile(struct mappedfile *);
206
207 #endif
208
209 /*
210 * The mother of all processes.
211 */
212 int
213 main(int argc, char **argv)
214 {
215 struct sigaction sa;
216 sigset_t mask;
217 #ifndef LETS_GET_SMALL
218 int c;
219
220 /* Dispose of random users. */
221 if (getuid() != 0) {
222 errno = EPERM;
223 err(1, NULL);
224 }
225
226 /* System V users like to reexec init. */
227 if (getpid() != 1)
228 errx(1, "already running");
229 #endif
230
231 /*
232 * Create an initial session.
233 */
234 if (setsid() < 0)
235 warn("initial setsid() failed");
236
237 /*
238 * Establish an initial user so that programs running
239 * single user do not freak out and die (like passwd).
240 */
241 if (setlogin("root") < 0)
242 warn("setlogin() failed");
243
244
245 #ifdef MFS_DEV_IF_NO_CONSOLE
246 if (mfs_dev() == -1)
247 requested_transition = single_user;
248 #endif
249
250 #ifndef LETS_GET_SMALL
251 /*
252 * Note that this does NOT open a file...
253 * Does 'init' deserve its own facility number?
254 */
255 openlog("init", LOG_CONS, LOG_AUTH);
256 #endif /* LETS_GET_SMALL */
257
258
259 #ifndef LETS_GET_SMALL
260 /*
261 * This code assumes that we always get arguments through flags,
262 * never through bits set in some random machine register.
263 */
264 while ((c = getopt(argc, argv, "sf")) != -1)
265 switch (c) {
266 case 's':
267 requested_transition = single_user;
268 break;
269 case 'f':
270 runcom_mode = FASTBOOT;
271 break;
272 default:
273 warning("unrecognized flag '-%c'", c);
274 break;
275 }
276
277 if (optind != argc)
278 warning("ignoring excess arguments");
279 #else /* LETS_GET_SMALL */
280 requested_transition = single_user;
281 #endif /* LETS_GET_SMALL */
282
283 /*
284 * We catch or block signals rather than ignore them,
285 * so that they get reset on exec.
286 */
287 handle(badsys, SIGSYS, 0);
288 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
289 SIGBUS, SIGXCPU, SIGXFSZ, 0);
290 handle(transition_handler, SIGHUP, SIGTERM, SIGTSTP, 0);
291 handle(alrm_handler, SIGALRM, 0);
292 (void)sigfillset(&mask);
293 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
294 SIGXCPU, SIGXFSZ, SIGHUP, SIGTERM, SIGTSTP, SIGALRM, 0);
295 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
296 (void)sigemptyset(&sa.sa_mask);
297 sa.sa_flags = 0;
298 sa.sa_handler = SIG_IGN;
299 (void)sigaction(SIGTTIN, &sa, NULL);
300 (void)sigaction(SIGTTOU, &sa, NULL);
301
302 /*
303 * Paranoia.
304 */
305 (void)close(0);
306 (void)close(1);
307 (void)close(2);
308
309 /*
310 * Start the state machine.
311 */
312 transition(requested_transition);
313
314 /*
315 * Should never reach here.
316 */
317 return 1;
318 }
319
320 /*
321 * Associate a function with a signal handler.
322 */
323 void
324 handle(sig_t handler, ...)
325 {
326 int sig;
327 struct sigaction sa;
328 sigset_t mask_everything;
329 va_list ap;
330
331 va_start(ap, handler);
332
333 sa.sa_handler = handler;
334 (void)sigfillset(&mask_everything);
335
336 while ((sig = va_arg(ap, int)) != 0) {
337 sa.sa_mask = mask_everything;
338 /* XXX SA_RESTART? */
339 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
340 (void)sigaction(sig, &sa, NULL);
341 }
342 va_end(ap);
343 }
344
345 /*
346 * Delete a set of signals from a mask.
347 */
348 void
349 delset(sigset_t *maskp, ...)
350 {
351 int sig;
352 va_list ap;
353
354 va_start(ap, maskp);
355
356 while ((sig = va_arg(ap, int)) != 0)
357 (void)sigdelset(maskp, sig);
358 va_end(ap);
359 }
360
361 /*
362 * Log a message and sleep for a while (to give someone an opportunity
363 * to read it and to save log or hardcopy output if the problem is chronic).
364 * NB: should send a message to the session logger to avoid blocking.
365 */
366 void
367 stall(const char *message, ...)
368 {
369 va_list ap;
370
371 va_start(ap, message);
372 vsyslog(LOG_ALERT, message, ap);
373 va_end(ap);
374 closelog();
375 (void)sleep(STALL_TIMEOUT);
376 }
377
378 /*
379 * Like stall(), but doesn't sleep.
380 * If cpp had variadic macros, the two functions could be #defines for another.
381 * NB: should send a message to the session logger to avoid blocking.
382 */
383 void
384 warning(const char *message, ...)
385 {
386 va_list ap;
387
388 va_start(ap, message);
389 vsyslog(LOG_ALERT, message, ap);
390 va_end(ap);
391 closelog();
392 }
393
394 /*
395 * Log an emergency message.
396 * NB: should send a message to the session logger to avoid blocking.
397 */
398 void
399 emergency(const char *message, ...)
400 {
401 va_list ap;
402
403 va_start(ap, message);
404 vsyslog(LOG_EMERG, message, ap);
405 va_end(ap);
406 closelog();
407 }
408
409 /*
410 * Catch a SIGSYS signal.
411 *
412 * These may arise if a system does not support sysctl.
413 * We tolerate up to 25 of these, then throw in the towel.
414 */
415 void
416 badsys(int sig)
417 {
418 static int badcount = 0;
419
420 if (badcount++ < 25)
421 return;
422 disaster(sig);
423 }
424
425 /*
426 * Catch an unexpected signal.
427 */
428 void
429 disaster(int sig)
430 {
431
432 emergency("fatal signal: %s", strsignal(sig));
433 (void)sleep(STALL_TIMEOUT);
434 _exit(sig); /* reboot */
435 }
436
437 /*
438 * Get the security level of the kernel.
439 */
440 int
441 getsecuritylevel(void)
442 {
443 #ifdef KERN_SECURELVL
444 int name[2], curlevel;
445 size_t len;
446
447 name[0] = CTL_KERN;
448 name[1] = KERN_SECURELVL;
449 len = sizeof curlevel;
450 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
451 emergency("cannot get kernel security level: %m");
452 return (-1);
453 }
454 return (curlevel);
455 #else
456 return (-1);
457 #endif
458 }
459
460 /*
461 * Set the security level of the kernel.
462 */
463 void
464 setsecuritylevel(int newlevel)
465 {
466 #ifdef KERN_SECURELVL
467 int name[2], curlevel;
468
469 curlevel = getsecuritylevel();
470 if (newlevel == curlevel)
471 return;
472 name[0] = CTL_KERN;
473 name[1] = KERN_SECURELVL;
474 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
475 emergency( "cannot change kernel security level from"
476 " %d to %d: %m", curlevel, newlevel);
477 return;
478 }
479 #ifdef SECURE
480 warning("kernel security level changed from %d to %d",
481 curlevel, newlevel);
482 #endif
483 #endif
484 }
485
486 /*
487 * Change states in the finite state machine.
488 * The initial state is passed as an argument.
489 */
490 void
491 transition(state_t s)
492 {
493
494 if (s == NULL)
495 return;
496 for (;;)
497 s = (state_t)(*s)();
498 }
499
500 /*
501 * Close out the accounting files for a login session.
502 * NB: should send a message to the session logger to avoid blocking.
503 */
504 void
505 clear_session_logs(session_t *sp, int status)
506 {
507 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
508
509 #ifdef SUPPORT_UTMPX
510 if (logoutx(line, status, DEAD_PROCESS))
511 logwtmpx(line, "", "", status, DEAD_PROCESS);
512 #endif
513 #ifdef SUPPORT_UTMP
514 if (logout(line))
515 logwtmp(line, "", "");
516 #endif
517 }
518
519 /*
520 * Start a session and allocate a controlling terminal.
521 * Only called by children of init after forking.
522 */
523 void
524 setctty(const char *name)
525 {
526 int fd;
527
528 (void) revoke(name);
529 sleep(2); /* leave DTR low */
530 if ((fd = open(name, O_RDWR)) == -1) {
531 stall("can't open %s: %m", name);
532 _exit(1);
533 }
534 if (login_tty(fd) == -1) {
535 stall("can't get %s for controlling terminal: %m", name);
536 _exit(1);
537 }
538 }
539
540 /*
541 * Bring the system up single user.
542 */
543 state_func_t
544 single_user(void)
545 {
546 pid_t pid, wpid;
547 int status;
548 int from_securitylevel;
549 sigset_t mask;
550 struct sigaction sa, satstp, sahup;
551 #ifdef ALTSHELL
552 const char *shell = INIT_BSHELL;
553 #endif
554 char *argv[2];
555 #ifdef SECURE
556 struct ttyent *typ;
557 struct passwd *pp;
558 char *clear, *password;
559 #endif
560 #ifdef ALTSHELL
561 char altshell[128];
562 #endif /* ALTSHELL */
563
564 /*
565 * If the kernel is in secure mode, downgrade it to insecure mode.
566 */
567 from_securitylevel = getsecuritylevel();
568 if (from_securitylevel > 0)
569 setsecuritylevel(0);
570
571 (void)sigemptyset(&sa.sa_mask);
572 sa.sa_flags = 0;
573 sa.sa_handler = SIG_IGN;
574 (void)sigaction(SIGTSTP, &sa, &satstp);
575 (void)sigaction(SIGHUP, &sa, &sahup);
576 if ((pid = fork()) == 0) {
577 /*
578 * Start the single user session.
579 */
580 setctty(_PATH_CONSOLE);
581
582 #ifdef SECURE
583 /*
584 * Check the root password.
585 * We don't care if the console is 'on' by default;
586 * it's the only tty that can be 'off' and 'secure'.
587 */
588 typ = getttynam("console");
589 pp = getpwnam("root");
590 if (typ && (from_securitylevel >=2 || (typ->ty_status
591 & TTY_SECURE) == 0) && pp && *pp->pw_passwd != '\0') {
592 (void)fprintf(stderr,
593 "Enter root password, or ^D to go multi-user\n");
594 for (;;) {
595 clear = getpass("Password:");
596 if (clear == 0 || *clear == '\0')
597 _exit(0);
598 password = crypt(clear, pp->pw_passwd);
599 (void)memset(clear, 0, _PASSWORD_LEN);
600 if (strcmp(password, pp->pw_passwd) == 0)
601 break;
602 warning("single-user login failed\n");
603 }
604 }
605 endttyent();
606 endpwent();
607 #endif /* SECURE */
608
609 #ifdef ALTSHELL
610 (void)fprintf(stderr,
611 "Enter pathname of shell or RETURN for %s: ", shell);
612 if (fgets(altshell, sizeof(altshell), stdin) == NULL) {
613 altshell[0] = '\0';
614 } else {
615 /* nuke \n */
616 char *p;
617
618 if ((p = strchr(altshell, '\n')) != NULL)
619 *p = '\0';
620 }
621
622 if (altshell[0])
623 shell = altshell;
624 #endif /* ALTSHELL */
625
626 /*
627 * Unblock signals.
628 * We catch all the interesting ones,
629 * and those are reset to SIG_DFL on exec.
630 */
631 (void)sigemptyset(&mask);
632 (void)sigprocmask(SIG_SETMASK, &mask, NULL);
633
634 /*
635 * Fire off a shell.
636 * If the default one doesn't work, try the Bourne shell.
637 */
638 argv[0] = "-sh";
639 argv[1] = 0;
640 setenv("PATH", INIT_PATH, 1);
641 #ifdef ALTSHELL
642 if (altshell[0])
643 argv[0] = altshell;
644 (void)execv(shell, argv);
645 emergency("can't exec %s for single user: %m", shell);
646 argv[0] = "-sh";
647 #endif /* ALTSHELL */
648 (void)execv(INIT_BSHELL, argv);
649 emergency("can't exec %s for single user: %m", INIT_BSHELL);
650 (void)sleep(STALL_TIMEOUT);
651 _exit(1);
652 }
653
654 if (pid == -1) {
655 /*
656 * We are seriously hosed. Do our best.
657 */
658 emergency("can't fork single-user shell, trying again");
659 while (waitpid(-1, NULL, WNOHANG) > 0)
660 continue;
661 (void)sigaction(SIGTSTP, &satstp, NULL);
662 (void)sigaction(SIGHUP, &sahup, NULL);
663 return (state_func_t) single_user;
664 }
665
666 requested_transition = 0;
667 do {
668 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
669 collect_child(wpid, status);
670 if (wpid == -1) {
671 if (errno == EINTR)
672 continue;
673 warning("wait for single-user shell failed: %m; "
674 "restarting");
675 return (state_func_t)single_user;
676 }
677 if (wpid == pid && WIFSTOPPED(status)) {
678 warning("init: shell stopped, restarting\n");
679 kill(pid, SIGCONT);
680 wpid = -1;
681 }
682 } while (wpid != pid && !requested_transition);
683
684 if (requested_transition) {
685 (void)sigaction(SIGTSTP, &satstp, NULL);
686 (void)sigaction(SIGHUP, &sahup, NULL);
687 return (state_func_t)requested_transition;
688 }
689
690 if (WIFSIGNALED(status)) {
691 if (WTERMSIG(status) == SIGKILL) {
692 /* executed /sbin/reboot; wait for the end quietly */
693 sigset_t s;
694
695 (void)sigfillset(&s);
696 for (;;)
697 (void)sigsuspend(&s);
698 } else {
699 warning("single user shell terminated, restarting");
700 (void)sigaction(SIGTSTP, &satstp, NULL);
701 (void)sigaction(SIGHUP, &sahup, NULL);
702 return (state_func_t) single_user;
703 }
704 }
705
706 runcom_mode = FASTBOOT;
707 (void)sigaction(SIGTSTP, &satstp, NULL);
708 (void)sigaction(SIGHUP, &sahup, NULL);
709 #ifndef LETS_GET_SMALL
710 return (state_func_t) runcom;
711 #else /* LETS_GET_SMALL */
712 return (state_func_t) single_user;
713 #endif /* LETS_GET_SMALL */
714 }
715
716 #ifndef LETS_GET_SMALL
717 /*
718 * Run the system startup script.
719 */
720 state_func_t
721 runcom(void)
722 {
723 pid_t pid, wpid;
724 int status;
725 char *argv[4];
726 struct sigaction sa;
727
728 switch ((pid = fork())) {
729 case 0:
730 (void)sigemptyset(&sa.sa_mask);
731 sa.sa_flags = 0;
732 sa.sa_handler = SIG_IGN;
733 (void)sigaction(SIGTSTP, &sa, NULL);
734 (void)sigaction(SIGHUP, &sa, NULL);
735
736 setctty(_PATH_CONSOLE);
737
738 argv[0] = "sh";
739 argv[1] = _PATH_RUNCOM;
740 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
741 argv[3] = 0;
742
743 (void)sigprocmask(SIG_SETMASK, &sa.sa_mask, NULL);
744
745 (void)execv(INIT_BSHELL, argv);
746 stall("can't exec %s for %s: %m", INIT_BSHELL, _PATH_RUNCOM);
747 _exit(1); /* force single user mode */
748 /*NOTREACHED*/
749 case -1:
750 emergency("can't fork for %s on %s: %m", INIT_BSHELL,
751 _PATH_RUNCOM);
752 while (waitpid(-1, NULL, WNOHANG) > 0)
753 continue;
754 (void)sleep(STALL_TIMEOUT);
755 return (state_func_t)single_user;
756 default:
757 break;
758 }
759
760 /*
761 * Copied from single_user(). This is a bit paranoid.
762 */
763 do {
764 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
765 collect_child(wpid, status);
766 if (wpid == -1) {
767 if (errno == EINTR)
768 continue;
769 warning("wait for %s on %s failed: %m; going to "
770 "single user mode", INIT_BSHELL, _PATH_RUNCOM);
771 return (state_func_t)single_user;
772 }
773 if (wpid == pid && WIFSTOPPED(status)) {
774 warning("init: %s on %s stopped, restarting\n",
775 INIT_BSHELL, _PATH_RUNCOM);
776 (void)kill(pid, SIGCONT);
777 wpid = -1;
778 }
779 } while (wpid != pid);
780
781 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
782 requested_transition == catatonia) {
783 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
784 sigset_t s;
785
786 (void)sigfillset(&s);
787 for (;;)
788 (void)sigsuspend(&s);
789 }
790
791 if (!WIFEXITED(status)) {
792 warning("%s on %s terminated abnormally, going to "
793 "single user mode", INIT_BSHELL, _PATH_RUNCOM);
794 return (state_func_t)single_user;
795 }
796
797 if (WEXITSTATUS(status))
798 return (state_func_t)single_user;
799
800 runcom_mode = AUTOBOOT; /* the default */
801 /* NB: should send a message to the session logger to avoid blocking. */
802 #ifdef SUPPORT_UTMPX
803 logwtmpx("~", "reboot", "", 0, INIT_PROCESS);
804 #endif
805 #ifdef SUPPORT_UTMP
806 logwtmp("~", "reboot", "");
807 #endif
808 return (state_func_t) read_ttys;
809 }
810
811 /*
812 * Open the session database.
813 *
814 * NB: We could pass in the size here; is it necessary?
815 */
816 int
817 start_session_db(void)
818 {
819
820 if (session_db && (*session_db->close)(session_db))
821 emergency("session database close: %m");
822 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
823 emergency("session database open: %m");
824 return (1);
825 }
826 return (0);
827
828 }
829
830 /*
831 * Add a new login session.
832 */
833 void
834 add_session(session_t *sp)
835 {
836 DBT key;
837 DBT data;
838
839 if (session_db == NULL)
840 return;
841
842 key.data = &sp->se_process;
843 key.size = sizeof sp->se_process;
844 data.data = &sp;
845 data.size = sizeof sp;
846
847 if ((*session_db->put)(session_db, &key, &data, 0))
848 emergency("insert %d: %m", sp->se_process);
849 }
850
851 /*
852 * Delete an old login session.
853 */
854 void
855 del_session(session_t *sp)
856 {
857 DBT key;
858
859 key.data = &sp->se_process;
860 key.size = sizeof sp->se_process;
861
862 if ((*session_db->del)(session_db, &key, 0))
863 emergency("delete %d: %m", sp->se_process);
864 }
865
866 /*
867 * Look up a login session by pid.
868 */
869 session_t *
870 find_session(pid_t pid)
871 {
872 DBT key;
873 DBT data;
874 session_t *ret;
875
876 if (session_db == NULL)
877 return NULL;
878
879 key.data = &pid;
880 key.size = sizeof pid;
881 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
882 return 0;
883 (void)memmove(&ret, data.data, sizeof(ret));
884 return ret;
885 }
886
887 /*
888 * Construct an argument vector from a command line.
889 */
890 char **
891 construct_argv(char *command)
892 {
893 int argc = 0;
894 char **argv = malloc(((strlen(command) + 1) / 2 + 1) * sizeof (char *));
895 static const char separators[] = " \t";
896
897 if ((argv[argc++] = strtok(command, separators)) == 0)
898 return (NULL);
899 while ((argv[argc++] = strtok(NULL, separators)) != NULL)
900 continue;
901 return (argv);
902 }
903
904 /*
905 * Deallocate a session descriptor.
906 */
907 void
908 free_session(session_t *sp)
909 {
910
911 free(sp->se_device);
912 if (sp->se_getty) {
913 free(sp->se_getty);
914 free(sp->se_getty_argv);
915 }
916 if (sp->se_window) {
917 free(sp->se_window);
918 free(sp->se_window_argv);
919 }
920 free(sp);
921 }
922
923 /*
924 * Allocate a new session descriptor.
925 */
926 session_t *
927 new_session(session_t *sprev, int session_index, struct ttyent *typ)
928 {
929 session_t *sp;
930
931 if ((typ->ty_status & TTY_ON) == 0 || typ->ty_name == NULL ||
932 typ->ty_getty == NULL)
933 return (NULL);
934
935 sp = malloc(sizeof (session_t));
936 if (sp == NULL)
937 return NULL;
938 memset(sp, 0, sizeof *sp);
939
940 sp->se_flags = SE_PRESENT;
941 sp->se_index = session_index;
942
943 (void)asprintf(&sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
944 if (!sp->se_device)
945 return NULL;
946
947 if (setupargv(sp, typ) == 0) {
948 free_session(sp);
949 return (NULL);
950 }
951
952 sp->se_next = NULL;
953 if (sprev == NULL) {
954 sessions = sp;
955 sp->se_prev = NULL;
956 } else {
957 sprev->se_next = sp;
958 sp->se_prev = sprev;
959 }
960
961 return (sp);
962 }
963
964 /*
965 * Calculate getty and if useful window argv vectors.
966 */
967 int
968 setupargv(session_t *sp, struct ttyent *typ)
969 {
970
971 if (sp->se_getty) {
972 free(sp->se_getty);
973 free(sp->se_getty_argv);
974 }
975 (void)asprintf(&sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
976 if (!sp->se_getty)
977 return (0);
978 sp->se_getty_argv = construct_argv(sp->se_getty);
979 if (sp->se_getty_argv == NULL) {
980 warning("can't parse getty for port %s", sp->se_device);
981 free(sp->se_getty);
982 sp->se_getty = NULL;
983 return (0);
984 }
985 if (typ->ty_window) {
986 if (sp->se_window)
987 free(sp->se_window);
988 sp->se_window = strdup(typ->ty_window);
989 sp->se_window_argv = construct_argv(sp->se_window);
990 if (sp->se_window_argv == NULL) {
991 warning("can't parse window for port %s",
992 sp->se_device);
993 free(sp->se_window);
994 sp->se_window = NULL;
995 return (0);
996 }
997 }
998 return (1);
999 }
1000
1001 /*
1002 * Walk the list of ttys and create sessions for each active line.
1003 */
1004 state_func_t
1005 read_ttys(void)
1006 {
1007 int session_index = 0;
1008 session_t *sp, *snext;
1009 struct ttyent *typ;
1010
1011 /*
1012 * Destroy any previous session state.
1013 * There shouldn't be any, but just in case...
1014 */
1015 for (sp = sessions; sp; sp = snext) {
1016 if (sp->se_process)
1017 clear_session_logs(sp, 0);
1018 snext = sp->se_next;
1019 free_session(sp);
1020 }
1021 sessions = NULL;
1022 if (start_session_db())
1023 return (state_func_t)single_user;
1024
1025 /*
1026 * Allocate a session entry for each active port.
1027 * Note that sp starts at 0.
1028 */
1029 while ((typ = getttyent()) != NULL)
1030 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1031 sp = snext;
1032
1033 endttyent();
1034
1035 return (state_func_t)multi_user;
1036 }
1037
1038 /*
1039 * Start a window system running.
1040 */
1041 void
1042 start_window_system(session_t *sp)
1043 {
1044 pid_t pid;
1045 sigset_t mask;
1046
1047 if ((pid = fork()) == -1) {
1048 emergency("can't fork for window system on port %s: %m",
1049 sp->se_device);
1050 /* hope that getty fails and we can try again */
1051 return;
1052 }
1053
1054 if (pid)
1055 return;
1056
1057 sigemptyset(&mask);
1058 sigprocmask(SIG_SETMASK, &mask, NULL);
1059
1060 if (setsid() < 0)
1061 emergency("setsid failed (window) %m");
1062
1063 (void)execv(sp->se_window_argv[0], sp->se_window_argv);
1064 stall("can't exec window system '%s' for port %s: %m",
1065 sp->se_window_argv[0], sp->se_device);
1066 _exit(1);
1067 }
1068
1069 /*
1070 * Start a login session running.
1071 */
1072 pid_t
1073 start_getty(session_t *sp)
1074 {
1075 pid_t pid;
1076 sigset_t mask;
1077 time_t current_time = time(NULL);
1078
1079 /*
1080 * fork(), not vfork() -- we can't afford to block.
1081 */
1082 if ((pid = fork()) == -1) {
1083 emergency("can't fork for getty on port %s: %m", sp->se_device);
1084 return -1;
1085 }
1086
1087 if (pid)
1088 return pid;
1089
1090 if (current_time > sp->se_started &&
1091 current_time - sp->se_started < GETTY_SPACING) {
1092 warning("getty repeating too quickly on port %s, sleeping",
1093 sp->se_device);
1094 (void)sleep(GETTY_SLEEP);
1095 }
1096
1097 if (sp->se_window) {
1098 start_window_system(sp);
1099 (void)sleep(WINDOW_WAIT);
1100 }
1101
1102 (void)sigemptyset(&mask);
1103 (void)sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1104
1105 (void)execv(sp->se_getty_argv[0], sp->se_getty_argv);
1106 stall("can't exec getty '%s' for port %s: %m",
1107 sp->se_getty_argv[0], sp->se_device);
1108 _exit(1);
1109 /*NOTREACHED*/
1110 }
1111 #endif /* LETS_GET_SMALL */
1112
1113 /*
1114 * Collect exit status for a child.
1115 * If an exiting login, start a new login running.
1116 */
1117 void
1118 collect_child(pid_t pid, int status)
1119 {
1120 #ifndef LETS_GET_SMALL
1121 session_t *sp, *sprev, *snext;
1122
1123 if (! sessions)
1124 return;
1125
1126 if ((sp = find_session(pid)) == NULL)
1127 return;
1128
1129 clear_session_logs(sp, status);
1130 del_session(sp);
1131 sp->se_process = 0;
1132
1133 if (sp->se_flags & SE_SHUTDOWN) {
1134 if ((sprev = sp->se_prev) != NULL)
1135 sprev->se_next = sp->se_next;
1136 else
1137 sessions = sp->se_next;
1138 if ((snext = sp->se_next) != NULL)
1139 snext->se_prev = sp->se_prev;
1140 free_session(sp);
1141 return;
1142 }
1143
1144 if ((pid = start_getty(sp)) == -1) {
1145 /* serious trouble */
1146 requested_transition = clean_ttys;
1147 return;
1148 }
1149
1150 sp->se_process = pid;
1151 sp->se_started = time(NULL);
1152 add_session(sp);
1153 #endif /* LETS_GET_SMALL */
1154 }
1155
1156 /*
1157 * Catch a signal and request a state transition.
1158 */
1159 void
1160 transition_handler(int sig)
1161 {
1162
1163 switch (sig) {
1164 #ifndef LETS_GET_SMALL
1165 case SIGHUP:
1166 requested_transition = clean_ttys;
1167 break;
1168 case SIGTERM:
1169 requested_transition = death;
1170 break;
1171 case SIGTSTP:
1172 requested_transition = catatonia;
1173 break;
1174 #endif /* LETS_GET_SMALL */
1175 default:
1176 requested_transition = 0;
1177 break;
1178 }
1179 }
1180
1181 #ifndef LETS_GET_SMALL
1182 /*
1183 * Take the system multiuser.
1184 */
1185 state_func_t
1186 multi_user(void)
1187 {
1188 pid_t pid;
1189 int status;
1190 session_t *sp;
1191
1192 requested_transition = 0;
1193
1194 /*
1195 * If the administrator has not set the security level to -1
1196 * to indicate that the kernel should not run multiuser in secure
1197 * mode, and the run script has not set a higher level of security
1198 * than level 1, then put the kernel into secure mode.
1199 */
1200 if (getsecuritylevel() == 0)
1201 setsecuritylevel(1);
1202
1203 for (sp = sessions; sp; sp = sp->se_next) {
1204 if (sp->se_process)
1205 continue;
1206 if ((pid = start_getty(sp)) == -1) {
1207 /* serious trouble */
1208 requested_transition = clean_ttys;
1209 break;
1210 }
1211 sp->se_process = pid;
1212 sp->se_started = time(NULL);
1213 add_session(sp);
1214 }
1215
1216 while (!requested_transition)
1217 if ((pid = waitpid(-1, &status, 0)) != -1)
1218 collect_child(pid, status);
1219
1220 return (state_func_t)requested_transition;
1221 }
1222
1223 /*
1224 * This is an n-squared algorithm. We hope it isn't run often...
1225 */
1226 state_func_t
1227 clean_ttys(void)
1228 {
1229 session_t *sp, *sprev;
1230 struct ttyent *typ;
1231 int session_index = 0;
1232 int devlen;
1233
1234 for (sp = sessions; sp; sp = sp->se_next)
1235 sp->se_flags &= ~SE_PRESENT;
1236
1237 devlen = sizeof(_PATH_DEV) - 1;
1238 while ((typ = getttyent()) != NULL) {
1239 ++session_index;
1240
1241 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1242 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1243 break;
1244
1245 if (sp) {
1246 sp->se_flags |= SE_PRESENT;
1247 if (sp->se_index != session_index) {
1248 warning("port %s changed utmp index from "
1249 "%d to %d", sp->se_device, sp->se_index,
1250 session_index);
1251 sp->se_index = session_index;
1252 }
1253 if ((typ->ty_status & TTY_ON) == 0 ||
1254 typ->ty_getty == 0) {
1255 sp->se_flags |= SE_SHUTDOWN;
1256 if (sp->se_process != 0)
1257 (void)kill(sp->se_process, SIGHUP);
1258 continue;
1259 }
1260 sp->se_flags &= ~SE_SHUTDOWN;
1261 if (setupargv(sp, typ) == 0) {
1262 warning("can't parse getty for port %s",
1263 sp->se_device);
1264 sp->se_flags |= SE_SHUTDOWN;
1265 if (sp->se_process != 0)
1266 (void)kill(sp->se_process, SIGHUP);
1267 }
1268 continue;
1269 }
1270
1271 new_session(sprev, session_index, typ);
1272 }
1273
1274 endttyent();
1275
1276 for (sp = sessions; sp; sp = sp->se_next)
1277 if ((sp->se_flags & SE_PRESENT) == 0) {
1278 sp->se_flags |= SE_SHUTDOWN;
1279 if (sp->se_process != 0)
1280 (void)kill(sp->se_process, SIGHUP);
1281 }
1282
1283 return (state_func_t)multi_user;
1284 }
1285
1286 /*
1287 * Block further logins.
1288 */
1289 state_func_t
1290 catatonia(void)
1291 {
1292 session_t *sp;
1293
1294 for (sp = sessions; sp; sp = sp->se_next)
1295 sp->se_flags |= SE_SHUTDOWN;
1296
1297 return (state_func_t)multi_user;
1298 }
1299 #endif /* LETS_GET_SMALL */
1300
1301 /*
1302 * Note SIGALRM.
1303 */
1304 void
1305 /*ARGSUSED*/
1306 alrm_handler(int sig)
1307 {
1308
1309 clang = 1;
1310 }
1311
1312 #ifndef LETS_GET_SMALL
1313 /*
1314 * Bring the system down to single user.
1315 */
1316 state_func_t
1317 death(void)
1318 {
1319 session_t *sp;
1320 int i, status;
1321 pid_t pid;
1322 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1323
1324 for (sp = sessions; sp; sp = sp->se_next)
1325 sp->se_flags |= SE_SHUTDOWN;
1326
1327 /* NB: should send a message to the session logger to avoid blocking. */
1328 #ifdef SUPPORT_UTMPX
1329 logwtmpx("~", "shutdown", "", 0, INIT_PROCESS);
1330 #endif
1331 #ifdef SUPPORT_UTMP
1332 logwtmp("~", "shutdown", "");
1333 #endif
1334
1335 for (i = 0; i < 3; ++i) {
1336 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1337 return (state_func_t)single_user;
1338
1339 clang = 0;
1340 alarm(DEATH_WATCH);
1341 do
1342 if ((pid = waitpid(-1, &status, 0)) != -1)
1343 collect_child(pid, status);
1344 while (clang == 0 && errno != ECHILD);
1345
1346 if (errno == ECHILD)
1347 return (state_func_t)single_user;
1348 }
1349
1350 warning("some processes would not die; ps axl advised");
1351
1352 return (state_func_t)single_user;
1353 }
1354 #endif /* LETS_GET_SMALL */
1355
1356 #ifdef MFS_DEV_IF_NO_CONSOLE
1357
1358 static void
1359 mapfile(struct mappedfile *mf)
1360 {
1361 int fd;
1362 struct stat st;
1363
1364 if (lstat(mf->path, &st) == -1)
1365 return;
1366
1367 if ((st.st_mode & S_IFMT) == S_IFLNK) {
1368 mf->buf = malloc(st.st_size + 1);
1369 mf->buf[st.st_size] = 0;
1370 if (readlink(mf->path, mf->buf, st.st_size) != st.st_size)
1371 return;
1372 mf->len = -1;
1373 return;
1374 }
1375
1376 if ((fd = open(mf->path, O_RDONLY)) == -1)
1377 return;
1378 mf->buf = mmap(0, (size_t)st.st_size, PROT_READ,
1379 MAP_FILE|MAP_SHARED, fd, (off_t)0);
1380 (void)close(fd);
1381 if (mf->buf == MAP_FAILED)
1382 return;
1383 mf->len = st.st_size;
1384 }
1385
1386 static void
1387 writefile(struct mappedfile *mf)
1388 {
1389 int fd;
1390
1391 if (mf->len == -1) {
1392 symlink(mf->buf, mf->path);
1393 free(mf->buf);
1394 return;
1395 }
1396
1397 if (mf->len == 0)
1398 return;
1399 fd = open(mf->path, O_WRONLY | O_CREAT | O_TRUNC, 0755);
1400 if (fd == -1)
1401 return;
1402 (void)write(fd, mf->buf, mf->len);
1403 (void)munmap(mf->buf, mf->len);
1404 (void)close(fd);
1405 }
1406
1407 static int
1408 mfs_dev(void)
1409 {
1410 /*
1411 * We cannot print errors so we bail out silently...
1412 */
1413 pid_t pid;
1414 int status;
1415 dev_t dev;
1416 char *fs_size;
1417 #ifdef CPU_CONSDEV
1418 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1419 size_t olen;
1420 #endif
1421
1422 /* If we have /dev/console, assume all is OK */
1423 if (access(_PATH_CONSOLE, F_OK) != -1)
1424 return(0);
1425
1426 /* Grab the contents of MAKEDEV */
1427 mapfile(&mfile[0]);
1428
1429 /* Grab the contents of MAKEDEV.local */
1430 mapfile(&mfile[1]);
1431
1432 /* Mount an mfs over /dev so we can create devices */
1433 switch ((pid = fork())) {
1434 case 0:
1435 asprintf(&fs_size, "%d", FSSIZE);
1436 (void)execl(INIT_MOUNT_MFS, "mount_mfs",
1437 "-b", "4096", "-f", "512",
1438 "-s", fs_size, "-n", STR(NINODE),
1439 "swap", "/dev", NULL);
1440 _exit(1);
1441 /*NOTREACHED*/
1442
1443 case -1:
1444 return(-1);
1445
1446 default:
1447 if (waitpid(pid, &status, 0) == -1)
1448 return(-1);
1449 if (status != 0)
1450 return(-1);
1451 break;
1452 }
1453
1454 #ifdef CPU_CONSDEV
1455 olen = sizeof(dev);
1456 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &olen,
1457 NULL, 0) == -1)
1458 #endif
1459 dev = makedev(0, 0);
1460
1461 /* Make a console for us, so we can see things happening */
1462 if (mknod(_PATH_CONSOLE, 0666 | S_IFCHR, dev) == -1)
1463 return(-1);
1464
1465 (void)freopen(_PATH_CONSOLE, "a", stderr);
1466
1467 warnx("Creating mfs /dev (%d blocks, %d inodes)", FSSIZE, NINODE);
1468
1469 /* Create a MAKEDEV script in the mfs /dev */
1470 writefile(&mfile[0]);
1471
1472 /* Create a MAKEDEV.local script in the mfs /dev */
1473 writefile(&mfile[1]);
1474
1475 /* Run the makedev script to create devices */
1476 switch ((pid = fork())) {
1477 case 0:
1478 dup2(2, 1); /* Give the script stdout */
1479 if (chdir("/dev") == 0)
1480 (void)execl(INIT_BSHELL, "sh",
1481 mfile[0].len ? "./MAKEDEV" : "/etc/MAKEDEV",
1482 "init", NULL);
1483 _exit(1);
1484
1485 case -1:
1486 break;
1487
1488 default:
1489 if (waitpid(pid, &status, 0) == -1)
1490 break;
1491 if (status != 0) {
1492 errno = EINVAL;
1493 break;
1494 }
1495 return 0;
1496 }
1497 warn("Unable to run MAKEDEV");
1498 return (-1);
1499 }
1500 #endif
1501