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