init.c revision 1.35 1 /* $NetBSD: init.c,v 1.35 1999/11/09 15:06:33 drochner 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.35 1999/11/09 15:06:33 drochner 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 int c;
193 struct sigaction sa;
194 sigset_t mask;
195
196 #ifndef LETS_GET_SMALL
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 extern int errno;
482
483 name[0] = CTL_KERN;
484 name[1] = KERN_SECURELVL;
485 len = sizeof curlevel;
486 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
487 emergency("cannot get kernel security level: %s",
488 strerror(errno));
489 return (-1);
490 }
491 return (curlevel);
492 #else
493 return (-1);
494 #endif
495 }
496
497 /*
498 * Set the security level of the kernel.
499 */
500 void
501 setsecuritylevel(newlevel)
502 int newlevel;
503 {
504 #ifdef KERN_SECURELVL
505 int name[2], curlevel;
506 extern int errno;
507
508 curlevel = getsecuritylevel();
509 if (newlevel == curlevel)
510 return;
511 name[0] = CTL_KERN;
512 name[1] = KERN_SECURELVL;
513 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
514 emergency(
515 "cannot change kernel security level from %d to %d: %s",
516 curlevel, newlevel, strerror(errno));
517 return;
518 }
519 #ifdef SECURE
520 warning("kernel security level changed from %d to %d",
521 curlevel, newlevel);
522 #endif
523 #endif
524 }
525
526 /*
527 * Change states in the finite state machine.
528 * The initial state is passed as an argument.
529 */
530 void
531 transition(s)
532 state_t s;
533 {
534 for (;;)
535 s = (state_t) (*s)();
536 }
537
538 /*
539 * Close out the accounting files for a login session.
540 * NB: should send a message to the session logger to avoid blocking.
541 */
542 void
543 clear_session_logs(sp)
544 session_t *sp;
545 {
546 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
547
548 if (logout(line))
549 logwtmp(line, "", "");
550 }
551
552 /*
553 * Start a session and allocate a controlling terminal.
554 * Only called by children of init after forking.
555 */
556 void
557 setctty(name)
558 char *name;
559 {
560 int fd;
561
562 (void) revoke(name);
563 sleep (2); /* leave DTR low */
564 if ((fd = open(name, O_RDWR)) == -1) {
565 stall("can't open %s: %m", name);
566 _exit(1);
567 }
568 if (login_tty(fd) == -1) {
569 stall("can't get %s for controlling terminal: %m", name);
570 _exit(1);
571 }
572 }
573
574 /*
575 * Bring the system up single user.
576 */
577 state_func_t
578 single_user()
579 {
580 pid_t pid, wpid;
581 int status;
582 int from_securitylevel;
583 sigset_t mask;
584 #ifdef ALTSHELL
585 char *shell = _PATH_BSHELL;
586 #endif
587 char *argv[2];
588 #ifdef SECURE
589 struct ttyent *typ;
590 struct passwd *pp;
591 char *clear, *password;
592 #endif
593 #ifdef ALTSHELL
594 char altshell[128];
595 #endif /* ALTSHELL */
596
597 /*
598 * If the kernel is in secure mode, downgrade it to insecure mode.
599 */
600 from_securitylevel = getsecuritylevel();
601 if (from_securitylevel > 0)
602 setsecuritylevel(0);
603
604 if ((pid = fork()) == 0) {
605 /*
606 * Start the single user session.
607 */
608 setctty(_PATH_CONSOLE);
609
610 #ifdef SECURE
611 /*
612 * Check the root password.
613 * We don't care if the console is 'on' by default;
614 * it's the only tty that can be 'off' and 'secure'.
615 */
616 typ = getttynam("console");
617 pp = getpwnam("root");
618 if (typ && (from_securitylevel >=2 || (typ->ty_status
619 & TTY_SECURE) == 0) && pp && *pp->pw_passwd != '\0') {
620 fprintf(stderr,
621 "Enter root password, or ^D to go multi-user\n");
622 for (;;) {
623 clear = getpass("Password:");
624 if (clear == 0 || *clear == '\0')
625 _exit(0);
626 password = crypt(clear, pp->pw_passwd);
627 memset(clear, 0, _PASSWORD_LEN);
628 if (strcmp(password, pp->pw_passwd) == 0)
629 break;
630 warning("single-user login failed\n");
631 }
632 }
633 endttyent();
634 endpwent();
635 #endif /* SECURE */
636
637 #ifdef ALTSHELL
638 fprintf(stderr, "Enter pathname of shell or RETURN for sh: ");
639 fgets(altshell, sizeof(altshell), stdin);
640 /* nuke \n */
641 altshell[strlen(altshell) - 1] = '\0';
642
643 if (altshell[0])
644 shell = altshell;
645 #endif /* ALTSHELL */
646
647 /*
648 * Unblock signals.
649 * We catch all the interesting ones,
650 * and those are reset to SIG_DFL on exec.
651 */
652 sigemptyset(&mask);
653 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
654
655 /*
656 * Fire off a shell.
657 * If the default one doesn't work, try the Bourne shell.
658 */
659 argv[0] = "-sh";
660 argv[1] = 0;
661 setenv("PATH", _PATH_STDPATH, 1);
662 #ifdef ALTSHELL
663 if (altshell[0])
664 argv[0] = altshell;
665 execv(shell, argv);
666 emergency("can't exec %s for single user: %m", shell);
667 argv[0] = "-sh";
668 #endif /* ALTSHELL */
669 execv(_PATH_BSHELL, argv);
670 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
671 sleep(STALL_TIMEOUT);
672 _exit(1);
673 }
674
675 if (pid == -1) {
676 /*
677 * We are seriously hosed. Do our best.
678 */
679 emergency("can't fork single-user shell, trying again");
680 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
681 continue;
682 return (state_func_t) single_user;
683 }
684
685 requested_transition = 0;
686 do {
687 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
688 collect_child(wpid);
689 if (wpid == -1) {
690 if (errno == EINTR)
691 continue;
692 warning("wait for single-user shell failed: %m; restarting");
693 return (state_func_t) single_user;
694 }
695 if (wpid == pid && WIFSTOPPED(status)) {
696 warning("init: shell stopped, restarting\n");
697 kill(pid, SIGCONT);
698 wpid = -1;
699 }
700 } while (wpid != pid && !requested_transition);
701
702 if (requested_transition)
703 return (state_func_t) requested_transition;
704
705 if (!WIFEXITED(status)) {
706 if (WTERMSIG(status) == SIGKILL) {
707 /*
708 * reboot(8) killed shell?
709 */
710 warning("single user shell terminated.");
711 sleep(STALL_TIMEOUT);
712 _exit(0);
713 } else {
714 warning("single user shell terminated, restarting");
715 return (state_func_t) single_user;
716 }
717 }
718
719 runcom_mode = FASTBOOT;
720 #ifndef LETS_GET_SMALL
721 return (state_func_t) runcom;
722 #else /* LETS_GET_SMALL */
723 return (state_func_t) single_user;
724 #endif /* LETS_GET_SMALL */
725 }
726
727 #ifndef LETS_GET_SMALL
728 /*
729 * Run the system startup script.
730 */
731 state_func_t
732 runcom()
733 {
734 pid_t pid, wpid;
735 int status;
736 char *argv[4];
737 struct sigaction sa;
738
739 if ((pid = fork()) == 0) {
740 sigemptyset(&sa.sa_mask);
741 sa.sa_flags = 0;
742 sa.sa_handler = SIG_IGN;
743 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
744 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
745
746 setctty(_PATH_CONSOLE);
747
748 argv[0] = "sh";
749 argv[1] = _PATH_RUNCOM;
750 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
751 argv[3] = 0;
752
753 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
754
755 execv(_PATH_BSHELL, argv);
756 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
757 _exit(1); /* force single user mode */
758 }
759
760 if (pid == -1) {
761 emergency("can't fork for %s on %s: %m",
762 _PATH_BSHELL, _PATH_RUNCOM);
763 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
764 continue;
765 sleep(STALL_TIMEOUT);
766 return (state_func_t) single_user;
767 }
768
769 /*
770 * Copied from single_user(). This is a bit paranoid.
771 */
772 do {
773 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
774 collect_child(wpid);
775 if (wpid == -1) {
776 if (errno == EINTR)
777 continue;
778 warning("wait for %s on %s failed: %m; going to single user mode",
779 _PATH_BSHELL, _PATH_RUNCOM);
780 return (state_func_t) single_user;
781 }
782 if (wpid == pid && WIFSTOPPED(status)) {
783 warning("init: %s on %s stopped, restarting\n",
784 _PATH_BSHELL, _PATH_RUNCOM);
785 kill(pid, SIGCONT);
786 wpid = -1;
787 }
788 } while (wpid != pid);
789
790 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
791 requested_transition == catatonia) {
792 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
793 sigset_t s;
794
795 sigfillset(&s);
796 for (;;)
797 sigsuspend(&s);
798 }
799
800 if (!WIFEXITED(status)) {
801 warning("%s on %s terminated abnormally, going to single user mode",
802 _PATH_BSHELL, _PATH_RUNCOM);
803 return (state_func_t) single_user;
804 }
805
806 if (WEXITSTATUS(status))
807 return (state_func_t) single_user;
808
809 runcom_mode = AUTOBOOT; /* the default */
810 /* NB: should send a message to the session logger to avoid blocking. */
811 logwtmp("~", "reboot", "");
812 return (state_func_t) read_ttys;
813 }
814
815 /*
816 * Open the session database.
817 *
818 * NB: We could pass in the size here; is it necessary?
819 */
820 int
821 start_session_db()
822 {
823 if (session_db && (*session_db->close)(session_db))
824 emergency("session database close: %s", strerror(errno));
825 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
826 emergency("session database open: %s", strerror(errno));
827 return (1);
828 }
829 return (0);
830
831 }
832
833 /*
834 * Add a new login session.
835 */
836 void
837 add_session(sp)
838 session_t *sp;
839 {
840 DBT key;
841 DBT data;
842
843 key.data = &sp->se_process;
844 key.size = sizeof sp->se_process;
845 data.data = &sp;
846 data.size = sizeof sp;
847
848 if ((*session_db->put)(session_db, &key, &data, 0))
849 emergency("insert %d: %s", sp->se_process, strerror(errno));
850 }
851
852 /*
853 * Delete an old login session.
854 */
855 void
856 del_session(sp)
857 session_t *sp;
858 {
859 DBT key;
860
861 key.data = &sp->se_process;
862 key.size = sizeof sp->se_process;
863
864 if ((*session_db->del)(session_db, &key, 0))
865 emergency("delete %d: %s", sp->se_process, strerror(errno));
866 }
867
868 /*
869 * Look up a login session by pid.
870 */
871 session_t *
872 #ifdef __STDC__
873 find_session(pid_t pid)
874 #else
875 find_session(pid)
876 pid_t pid;
877 #endif
878 {
879 DBT key;
880 DBT data;
881 session_t *ret;
882
883 key.data = &pid;
884 key.size = sizeof pid;
885 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
886 return 0;
887 memmove(&ret, data.data, sizeof(ret));
888 return ret;
889 }
890
891 /*
892 * Construct an argument vector from a command line.
893 */
894 char **
895 construct_argv(command)
896 char *command;
897 {
898 int argc = 0;
899 char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
900 * sizeof (char *));
901 static const char separators[] = " \t";
902
903 if ((argv[argc++] = strtok(command, separators)) == 0)
904 return (NULL);
905 while ((argv[argc++] = strtok((char *) 0, separators)))
906 continue;
907 return (argv);
908 }
909
910 /*
911 * Deallocate a session descriptor.
912 */
913 void
914 free_session(sp)
915 session_t *sp;
916 {
917 free(sp->se_device);
918 if (sp->se_getty) {
919 free(sp->se_getty);
920 free(sp->se_getty_argv);
921 }
922 if (sp->se_window) {
923 free(sp->se_window);
924 free(sp->se_window_argv);
925 }
926 free(sp);
927 }
928
929 /*
930 * Allocate a new session descriptor.
931 */
932 session_t *
933 new_session(sprev, session_index, typ)
934 session_t *sprev;
935 int session_index;
936 struct ttyent *typ;
937 {
938 session_t *sp;
939
940 if ((typ->ty_status & TTY_ON) == 0 ||
941 typ->ty_name == NULL ||
942 typ->ty_getty == NULL)
943 return (NULL);
944
945 sp = (session_t *) malloc(sizeof (session_t));
946 memset(sp, 0, sizeof *sp);
947
948 sp->se_flags = SE_PRESENT;
949 sp->se_index = session_index;
950
951 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
952 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
953
954 if (setupargv(sp, typ) == 0) {
955 free_session(sp);
956 return (NULL);
957 }
958
959 sp->se_next = NULL;
960 if (sprev == NULL) {
961 sessions = sp;
962 sp->se_prev = NULL;
963 } else {
964 sprev->se_next = sp;
965 sp->se_prev = sprev;
966 }
967
968 return (sp);
969 }
970
971 /*
972 * Calculate getty and if useful window argv vectors.
973 */
974 int
975 setupargv(sp, typ)
976 session_t *sp;
977 struct ttyent *typ;
978 {
979
980 if (sp->se_getty) {
981 free(sp->se_getty);
982 free(sp->se_getty_argv);
983 }
984 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
985 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
986 sp->se_getty_argv = construct_argv(sp->se_getty);
987 if (sp->se_getty_argv == NULL) {
988 warning("can't parse getty for port %s", sp->se_device);
989 free(sp->se_getty);
990 sp->se_getty = NULL;
991 return (0);
992 }
993 if (typ->ty_window) {
994 if (sp->se_window)
995 free(sp->se_window);
996 sp->se_window = strdup(typ->ty_window);
997 sp->se_window_argv = construct_argv(sp->se_window);
998 if (sp->se_window_argv == NULL) {
999 warning("can't parse window for port %s",
1000 sp->se_device);
1001 free(sp->se_window);
1002 sp->se_window = NULL;
1003 return (0);
1004 }
1005 }
1006 return (1);
1007 }
1008
1009 /*
1010 * Walk the list of ttys and create sessions for each active line.
1011 */
1012 state_func_t
1013 read_ttys()
1014 {
1015 int session_index = 0;
1016 session_t *sp, *snext;
1017 struct ttyent *typ;
1018
1019 /*
1020 * Destroy any previous session state.
1021 * There shouldn't be any, but just in case...
1022 */
1023 for (sp = sessions; sp; sp = snext) {
1024 if (sp->se_process)
1025 clear_session_logs(sp);
1026 snext = sp->se_next;
1027 free_session(sp);
1028 }
1029 sessions = NULL;
1030 if (start_session_db())
1031 return (state_func_t) single_user;
1032
1033 /*
1034 * Allocate a session entry for each active port.
1035 * Note that sp starts at 0.
1036 */
1037 while ((typ = getttyent()) != NULL)
1038 if ((snext = new_session(sp, ++session_index, typ)) != NULL)
1039 sp = snext;
1040
1041 endttyent();
1042
1043 return (state_func_t) multi_user;
1044 }
1045
1046 /*
1047 * Start a window system running.
1048 */
1049 void
1050 start_window_system(sp)
1051 session_t *sp;
1052 {
1053 pid_t pid;
1054 sigset_t mask;
1055
1056 if ((pid = fork()) == -1) {
1057 emergency("can't fork for window system on port %s: %m",
1058 sp->se_device);
1059 /* hope that getty fails and we can try again */
1060 return;
1061 }
1062
1063 if (pid)
1064 return;
1065
1066 sigemptyset(&mask);
1067 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1068
1069 if (setsid() < 0)
1070 emergency("setsid failed (window) %m");
1071
1072 execv(sp->se_window_argv[0], sp->se_window_argv);
1073 stall("can't exec window system '%s' for port %s: %m",
1074 sp->se_window_argv[0], sp->se_device);
1075 _exit(1);
1076 }
1077
1078 /*
1079 * Start a login session running.
1080 */
1081 pid_t
1082 start_getty(sp)
1083 session_t *sp;
1084 {
1085 pid_t pid;
1086 sigset_t mask;
1087 time_t current_time = time((time_t *) 0);
1088
1089 /*
1090 * fork(), not vfork() -- we can't afford to block.
1091 */
1092 if ((pid = fork()) == -1) {
1093 emergency("can't fork for getty on port %s: %m", sp->se_device);
1094 return -1;
1095 }
1096
1097 if (pid)
1098 return pid;
1099
1100 if (current_time > sp->se_started &&
1101 current_time - sp->se_started < GETTY_SPACING) {
1102 warning("getty repeating too quickly on port %s, sleeping",
1103 sp->se_device);
1104 sleep((unsigned) GETTY_SLEEP);
1105 }
1106
1107 if (sp->se_window) {
1108 start_window_system(sp);
1109 sleep(WINDOW_WAIT);
1110 }
1111
1112 sigemptyset(&mask);
1113 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1114
1115 execv(sp->se_getty_argv[0], sp->se_getty_argv);
1116 stall("can't exec getty '%s' for port %s: %m",
1117 sp->se_getty_argv[0], sp->se_device);
1118 _exit(1);
1119 }
1120 #endif /* LETS_GET_SMALL */
1121
1122 /*
1123 * Collect exit status for a child.
1124 * If an exiting login, start a new login running.
1125 */
1126 void
1127 #ifdef __STDC__
1128 collect_child(pid_t pid)
1129 #else
1130 collect_child(pid)
1131 pid_t pid;
1132 #endif
1133 {
1134 #ifndef LETS_GET_SMALL
1135 session_t *sp, *sprev, *snext;
1136
1137 if (! sessions)
1138 return;
1139
1140 if (! (sp = find_session(pid)))
1141 return;
1142
1143 clear_session_logs(sp);
1144 del_session(sp);
1145 sp->se_process = 0;
1146
1147 if (sp->se_flags & SE_SHUTDOWN) {
1148 if ((sprev = sp->se_prev) != NULL)
1149 sprev->se_next = sp->se_next;
1150 else
1151 sessions = sp->se_next;
1152 if ((snext = sp->se_next) != NULL)
1153 snext->se_prev = sp->se_prev;
1154 free_session(sp);
1155 return;
1156 }
1157
1158 if ((pid = start_getty(sp)) == -1) {
1159 /* serious trouble */
1160 requested_transition = clean_ttys;
1161 return;
1162 }
1163
1164 sp->se_process = pid;
1165 sp->se_started = time((time_t *) 0);
1166 add_session(sp);
1167 #endif /* LETS_GET_SMALL */
1168 }
1169
1170 /*
1171 * Catch a signal and request a state transition.
1172 */
1173 void
1174 transition_handler(sig)
1175 int sig;
1176 {
1177
1178 switch (sig) {
1179 #ifndef LETS_GET_SMALL
1180 case SIGHUP:
1181 requested_transition = clean_ttys;
1182 break;
1183 case SIGTERM:
1184 requested_transition = death;
1185 break;
1186 case SIGTSTP:
1187 requested_transition = catatonia;
1188 break;
1189 #endif /* LETS_GET_SMALL */
1190 default:
1191 requested_transition = 0;
1192 break;
1193 }
1194 }
1195
1196 #ifndef LETS_GET_SMALL
1197 /*
1198 * Take the system multiuser.
1199 */
1200 state_func_t
1201 multi_user()
1202 {
1203 pid_t pid;
1204 session_t *sp;
1205
1206 requested_transition = 0;
1207
1208 /*
1209 * If the administrator has not set the security level to -1
1210 * to indicate that the kernel should not run multiuser in secure
1211 * mode, and the run script has not set a higher level of security
1212 * than level 1, then put the kernel into secure mode.
1213 */
1214 if (getsecuritylevel() == 0)
1215 setsecuritylevel(1);
1216
1217 for (sp = sessions; sp; sp = sp->se_next) {
1218 if (sp->se_process)
1219 continue;
1220 if ((pid = start_getty(sp)) == -1) {
1221 /* serious trouble */
1222 requested_transition = clean_ttys;
1223 break;
1224 }
1225 sp->se_process = pid;
1226 sp->se_started = time((time_t *) 0);
1227 add_session(sp);
1228 }
1229
1230 while (!requested_transition)
1231 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1232 collect_child(pid);
1233
1234 return (state_func_t) requested_transition;
1235 }
1236
1237 /*
1238 * This is an n-squared algorithm. We hope it isn't run often...
1239 */
1240 state_func_t
1241 clean_ttys()
1242 {
1243 session_t *sp, *sprev;
1244 struct ttyent *typ;
1245 int session_index = 0;
1246 int devlen;
1247
1248 for (sp = sessions; sp; sp = sp->se_next)
1249 sp->se_flags &= ~SE_PRESENT;
1250
1251 devlen = sizeof(_PATH_DEV) - 1;
1252 while ((typ = getttyent()) != NULL) {
1253 ++session_index;
1254
1255 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1256 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1257 break;
1258
1259 if (sp) {
1260 sp->se_flags |= SE_PRESENT;
1261 if (sp->se_index != session_index) {
1262 warning("port %s changed utmp index from %d to %d",
1263 sp->se_device, sp->se_index,
1264 session_index);
1265 sp->se_index = session_index;
1266 }
1267 if ((typ->ty_status & TTY_ON) == 0 ||
1268 typ->ty_getty == 0) {
1269 sp->se_flags |= SE_SHUTDOWN;
1270 kill(sp->se_process, SIGHUP);
1271 continue;
1272 }
1273 sp->se_flags &= ~SE_SHUTDOWN;
1274 if (setupargv(sp, typ) == 0) {
1275 warning("can't parse getty for port %s",
1276 sp->se_device);
1277 sp->se_flags |= SE_SHUTDOWN;
1278 kill(sp->se_process, SIGHUP);
1279 }
1280 continue;
1281 }
1282
1283 new_session(sprev, session_index, typ);
1284 }
1285
1286 endttyent();
1287
1288 for (sp = sessions; sp; sp = sp->se_next)
1289 if ((sp->se_flags & SE_PRESENT) == 0) {
1290 sp->se_flags |= SE_SHUTDOWN;
1291 kill(sp->se_process, SIGHUP);
1292 }
1293
1294 return (state_func_t) multi_user;
1295 }
1296
1297 /*
1298 * Block further logins.
1299 */
1300 state_func_t
1301 catatonia()
1302 {
1303 session_t *sp;
1304
1305 for (sp = sessions; sp; sp = sp->se_next)
1306 sp->se_flags |= SE_SHUTDOWN;
1307
1308 return (state_func_t) multi_user;
1309 }
1310 #endif /* LETS_GET_SMALL */
1311
1312 /*
1313 * Note SIGALRM.
1314 */
1315 void
1316 alrm_handler(sig)
1317 int sig;
1318 {
1319 clang = 1;
1320 }
1321
1322 #ifndef LETS_GET_SMALL
1323 /*
1324 * Bring the system down to single user.
1325 */
1326 state_func_t
1327 death()
1328 {
1329 session_t *sp;
1330 int i;
1331 pid_t pid;
1332 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1333
1334 for (sp = sessions; sp; sp = sp->se_next)
1335 sp->se_flags |= SE_SHUTDOWN;
1336
1337 /* NB: should send a message to the session logger to avoid blocking. */
1338 logwtmp("~", "shutdown", "");
1339
1340 for (i = 0; i < 3; ++i) {
1341 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1342 return (state_func_t) single_user;
1343
1344 clang = 0;
1345 alarm(DEATH_WATCH);
1346 do
1347 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1348 collect_child(pid);
1349 while (clang == 0 && errno != ECHILD);
1350
1351 if (errno == ECHILD)
1352 return (state_func_t) single_user;
1353 }
1354
1355 warning("some processes would not die; ps axl advised");
1356
1357 return (state_func_t) single_user;
1358 }
1359 #endif /* LETS_GET_SMALL */
1360
1361 #ifdef MSDOSFS_ROOT
1362
1363 static void
1364 msdosfs_root()
1365 {
1366 /*
1367 * We cannot print errors so we bail out silently...
1368 */
1369 int fd = -1;
1370 struct stat st;
1371 pid_t pid;
1372 int status;
1373 void *ptr;
1374 struct statfs sfs;
1375
1376 if (statfs("/", &sfs) == -1)
1377 return;
1378
1379 if (strcmp(sfs.f_fstypename, MOUNT_MSDOS) != 0)
1380 return;
1381
1382 /* If we have devices, we cannot be on msdosfs */
1383 if (access(_PATH_CONSOLE, F_OK) != -1)
1384 return;
1385
1386 /* Grab the contents of MAKEDEV */
1387 if ((fd = open("/dev/MAKEDEV", O_RDONLY)) == -1)
1388 return;
1389
1390 if (fstat(fd, &st) == -1)
1391 goto done;
1392
1393 if ((ptr = mmap(0,
1394 st.st_size, PROT_READ, MAP_FILE|MAP_SHARED, fd, 0)) == (void *) -1)
1395 goto done;
1396
1397 (void) close(fd);
1398 fd = -1;
1399
1400 /* Mount an mfs over /dev so we can create devices */
1401 switch ((pid = fork())) {
1402 case 0:
1403 (void) execl("/sbin/mount_mfs", "mount_mfs", "-i", "256",
1404 "-s", "384", "-b", "4096", "-f", "512", "swap", "/dev",
1405 NULL);
1406 goto done;
1407
1408 case -1:
1409 goto done;
1410
1411 default:
1412 if (waitpid(pid, &status, 0) == -1)
1413 goto done;
1414 if (status != 0)
1415 goto done;
1416 break;
1417 }
1418
1419 /* Create a MAKEDEV script in /dev */
1420 if ((fd = open("/dev/MAKEDEV", O_WRONLY|O_CREAT|O_TRUNC, 0755)) == -1)
1421 goto done;
1422
1423 if (write(fd, ptr, st.st_size) != st.st_size)
1424 goto done;
1425
1426 (void) munmap(ptr, st.st_size);
1427
1428 (void) close(fd);
1429 fd = -1;
1430
1431 #ifdef DEBUG
1432 {
1433 mode_t mode = 0666 | S_IFCHR;
1434 dev_t dev;
1435 #ifdef CPU_CONSDEV
1436 int s = sizeof(dev);
1437 static int name[2] = { CTL_MACHDEP, CPU_CONSDEV };
1438
1439 if (sysctl(name, sizeof(name) / sizeof(name[0]), &dev, &s,
1440 NULL, 0) == -1)
1441 goto done;
1442 #else
1443 dev = makedev(0, 0);
1444 #endif
1445
1446 /* Make a console for us, so we can see things happening */
1447 if (mknod(_PATH_CONSOLE, mode, dev) == -1)
1448 goto done;
1449 }
1450 #endif
1451
1452 /* Run the makedev script to create devices */
1453 switch ((pid = fork())) {
1454 case 0:
1455 if (chdir("/dev") == -1)
1456 goto done;
1457 (void) execl("/bin/sh", "sh", "./MAKEDEV", "all", NULL);
1458 goto done;
1459
1460 case -1:
1461 goto done;
1462
1463 default:
1464 if (waitpid(pid, &status, 0) == -1)
1465 goto done;
1466 if (status != 0)
1467 goto done;
1468 break;
1469 }
1470
1471 done:
1472 if (fd != -1)
1473 (void) close(fd);
1474 }
1475 #endif
1476