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