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