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