init.c revision 1.16 1 /*-
2 * Copyright (c) 1991, 1993
3 * The Regents of the University of California. All rights reserved.
4 *
5 * This code is derived from software contributed to Berkeley by
6 * Donn Seeley at Berkeley Software Design, Inc.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. All advertising materials mentioning features or use of this software
17 * must display the following acknowledgement:
18 * This product includes software developed by the University of
19 * California, Berkeley and its contributors.
20 * 4. Neither the name of the University nor the names of its contributors
21 * may be used to endorse or promote products derived from this software
22 * without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 * SUCH DAMAGE.
35 */
36
37 #ifndef lint
38 static char copyright[] =
39 "@(#) Copyright (c) 1991, 1993\n\
40 The Regents of the University of California. All rights reserved.\n";
41 #endif /* not lint */
42
43 #ifndef lint
44 /*static char sccsid[] = "from: @(#)init.c 8.1 (Berkeley) 7/15/93";*/
45 static char *rcsid = "$Id: init.c,v 1.16 1994/06/11 07:54:04 mycroft Exp $";
46 #endif /* not lint */
47
48 #include <sys/param.h>
49 #include <sys/sysctl.h>
50 #include <sys/wait.h>
51
52 #include <db.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <signal.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <syslog.h>
60 #include <time.h>
61 #include <ttyent.h>
62 #include <unistd.h>
63
64 #ifdef __STDC__
65 #include <stdarg.h>
66 #else
67 #include <varargs.h>
68 #endif
69
70 #ifdef SECURE
71 #include <pwd.h>
72 #endif
73
74 #include "pathnames.h"
75
76 /*
77 * Until the mythical util.h arrives...
78 */
79 extern int login_tty __P((int));
80 extern int logout __P((const char *));
81 extern void logwtmp __P((const char *, const char *, const char *));
82
83 /*
84 * Sleep times; used to prevent thrashing.
85 */
86 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
87 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
88 #define WINDOW_WAIT 3 /* wait N secs after starting window */
89 #define STALL_TIMEOUT 30 /* wait N secs after warning */
90 #define DEATH_WATCH 10 /* wait N secs for procs to die */
91
92 void handle __P((sig_t, ...));
93 void delset __P((sigset_t *, ...));
94
95 void stall __P((char *, ...));
96 void warning __P((char *, ...));
97 void emergency __P((char *, ...));
98 void disaster __P((int));
99 void badsys __P((int));
100
101 /*
102 * We really need a recursive typedef...
103 * The following at least guarantees that the return type of (*state_t)()
104 * is sufficiently wide to hold a function pointer.
105 */
106 typedef long (*state_func_t) __P((void));
107 typedef state_func_t (*state_t) __P((void));
108
109 state_func_t single_user __P((void));
110 state_func_t runcom __P((void));
111 state_func_t read_ttys __P((void));
112 state_func_t multi_user __P((void));
113 state_func_t clean_ttys __P((void));
114 state_func_t catatonia __P((void));
115 state_func_t death __P((void));
116
117 enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
118
119 void transition __P((state_t));
120 #ifndef LETS_GET_SMALL
121 state_t requested_transition = runcom;
122 #else /* LETS_GET_SMALL */
123 state_t requested_transition = single_user;
124 #endif /* LETS_GET_SMALL */
125
126 void setctty __P((char *));
127
128 typedef struct init_session {
129 int se_index; /* index of entry in ttys file */
130 pid_t se_process; /* controlling process */
131 time_t se_started; /* used to avoid thrashing */
132 int se_flags; /* status of session */
133 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
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 sleep(STALL_TIMEOUT);
361 }
362
363 /*
364 * Like stall(), but doesn't sleep.
365 * If cpp had variadic macros, the two functions could be #defines for another.
366 * NB: should send a message to the session logger to avoid blocking.
367 */
368 void
369 #ifdef __STDC__
370 warning(char *message, ...)
371 #else
372 warning(va_alist)
373 va_dcl
374 #endif
375 {
376 va_list ap;
377 #ifndef __STDC__
378 char *message;
379
380 va_start(ap);
381 message = va_arg(ap, char *);
382 #else
383 va_start(ap, message);
384 #endif
385
386 vsyslog(LOG_ALERT, message, ap);
387 va_end(ap);
388 }
389
390 /*
391 * Log an emergency message.
392 * NB: should send a message to the session logger to avoid blocking.
393 */
394 void
395 #ifdef __STDC__
396 emergency(char *message, ...)
397 #else
398 emergency(va_alist)
399 va_dcl
400 #endif
401 {
402 va_list ap;
403 #ifndef __STDC__
404 char *message;
405
406 va_start(ap);
407 message = va_arg(ap, char *);
408 #else
409 va_start(ap, message);
410 #endif
411
412 vsyslog(LOG_EMERG, message, ap);
413 va_end(ap);
414 }
415
416 /*
417 * Catch a SIGSYS signal.
418 *
419 * These may arise if a system does not support sysctl.
420 * We tolerate up to 25 of these, then throw in the towel.
421 */
422 void
423 badsys(sig)
424 int sig;
425 {
426 static int badcount = 0;
427
428 if (badcount++ < 25)
429 return;
430 disaster(sig);
431 }
432
433 /*
434 * Catch an unexpected signal.
435 */
436 void
437 disaster(sig)
438 int sig;
439 {
440 emergency("fatal signal: %s",
441 sig < (unsigned) NSIG ? sys_siglist[sig] : "unknown signal");
442
443 sleep(STALL_TIMEOUT);
444 _exit(sig); /* reboot */
445 }
446
447 /*
448 * Get the security level of the kernel.
449 */
450 int
451 getsecuritylevel()
452 {
453 #ifdef KERN_SECURELVL
454 int name[2], curlevel;
455 size_t len;
456 extern int errno;
457
458 name[0] = CTL_KERN;
459 name[1] = KERN_SECURELVL;
460 len = sizeof curlevel;
461 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
462 emergency("cannot get kernel security level: %s",
463 strerror(errno));
464 return (-1);
465 }
466 return (curlevel);
467 #else
468 return (-1);
469 #endif
470 }
471
472 /*
473 * Set the security level of the kernel.
474 */
475 void
476 setsecuritylevel(newlevel)
477 int newlevel;
478 {
479 #ifdef KERN_SECURELVL
480 int name[2], curlevel;
481 extern int errno;
482
483 curlevel = getsecuritylevel();
484 if (newlevel == curlevel)
485 return;
486 name[0] = CTL_KERN;
487 name[1] = KERN_SECURELVL;
488 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
489 emergency(
490 "cannot change kernel security level from %d to %d: %s",
491 curlevel, newlevel, strerror(errno));
492 return;
493 }
494 #ifdef SECURE
495 warning("kernel security level changed from %d to %d",
496 curlevel, newlevel);
497 #endif
498 #endif
499 }
500
501 /*
502 * Change states in the finite state machine.
503 * The initial state is passed as an argument.
504 */
505 void
506 transition(s)
507 state_t s;
508 {
509 for (;;)
510 s = (state_t) (*s)();
511 }
512
513 /*
514 * Close out the accounting files for a login session.
515 * NB: should send a message to the session logger to avoid blocking.
516 */
517 void
518 clear_session_logs(sp)
519 session_t *sp;
520 {
521 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
522
523 if (logout(line))
524 logwtmp(line, "", "");
525 }
526
527 /*
528 * Start a session and allocate a controlling terminal.
529 * Only called by children of init after forking.
530 */
531 void
532 setctty(name)
533 char *name;
534 {
535 int fd;
536
537 (void) revoke(name);
538 sleep (2); /* leave DTR low */
539 if ((fd = open(name, O_RDWR)) == -1) {
540 stall("can't open %s: %m", name);
541 _exit(1);
542 }
543 if (login_tty(fd) == -1) {
544 stall("can't get %s for controlling terminal: %m", name);
545 _exit(1);
546 }
547 }
548
549 /*
550 * Bring the system up single user.
551 */
552 state_func_t
553 single_user()
554 {
555 pid_t pid, wpid;
556 int status;
557 sigset_t mask;
558 char *shell = _PATH_BSHELL;
559 char *argv[2];
560 #ifdef SECURE
561 struct ttyent *typ;
562 struct passwd *pp;
563 static const char banner[] =
564 "Enter root password, or ^D to go multi-user\n";
565 char *clear, *password;
566 #endif
567
568 /*
569 * If the kernel is in secure mode, downgrade it to insecure mode.
570 */
571 if (getsecuritylevel() > 0)
572 setsecuritylevel(0);
573
574 if ((pid = fork()) == 0) {
575 /*
576 * Start the single user session.
577 */
578 setctty(_PATH_CONSOLE);
579
580 #ifdef SECURE
581 /*
582 * Check the root password.
583 * We don't care if the console is 'on' by default;
584 * it's the only tty that can be 'off' and 'secure'.
585 */
586 typ = getttynam("console");
587 pp = getpwnam("root");
588 if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp) {
589 write(2, banner, sizeof banner - 1);
590 for (;;) {
591 clear = getpass("Password:");
592 if (clear == 0 || *clear == '\0')
593 _exit(0);
594 password = crypt(clear, pp->pw_passwd);
595 bzero(clear, _PASSWORD_LEN);
596 if (strcmp(password, pp->pw_passwd) == 0)
597 break;
598 warning("single-user login failed\n");
599 }
600 }
601 endttyent();
602 endpwent();
603 #endif /* SECURE */
604
605 #ifdef DEBUGSHELL
606 {
607 char altshell[128], *cp = altshell;
608 int num;
609
610 #define SHREQUEST \
611 "Enter pathname of shell or RETURN for sh: "
612 (void)write(STDERR_FILENO,
613 SHREQUEST, sizeof(SHREQUEST) - 1);
614 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
615 num != 0 && *cp != '\n' && cp < &altshell[127])
616 cp++;
617 *cp = '\0';
618 if (altshell[0] != '\0')
619 shell = altshell;
620 }
621 #endif /* DEBUGSHELL */
622
623 /*
624 * Unblock signals.
625 * We catch all the interesting ones,
626 * and those are reset to SIG_DFL on exec.
627 */
628 sigemptyset(&mask);
629 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
630
631 /*
632 * Fire off a shell.
633 * If the default one doesn't work, try the Bourne shell.
634 */
635 argv[0] = "-sh";
636 argv[1] = 0;
637 execv(shell, argv);
638 emergency("can't exec %s for single user: %m", shell);
639 execv(_PATH_BSHELL, argv);
640 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
641 sleep(STALL_TIMEOUT);
642 _exit(1);
643 }
644
645 if (pid == -1) {
646 /*
647 * We are seriously hosed. Do our best.
648 */
649 emergency("can't fork single-user shell, trying again");
650 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
651 continue;
652 return (state_func_t) single_user;
653 }
654
655 requested_transition = 0;
656 do {
657 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
658 collect_child(wpid);
659 if (wpid == -1) {
660 if (errno == EINTR)
661 continue;
662 warning("wait for single-user shell failed: %m; restarting");
663 return (state_func_t) single_user;
664 }
665 if (wpid == pid && WIFSTOPPED(status)) {
666 warning("init: shell stopped, restarting\n");
667 kill(pid, SIGCONT);
668 wpid = -1;
669 }
670 } while (wpid != pid && !requested_transition);
671
672 if (requested_transition)
673 return (state_func_t) requested_transition;
674
675 if (!WIFEXITED(status)) {
676 if (WTERMSIG(status) == SIGKILL) {
677 /*
678 * reboot(8) killed shell?
679 */
680 warning("single user shell terminated.");
681 sleep(STALL_TIMEOUT);
682 _exit(0);
683 } else {
684 warning("single user shell terminated, restarting");
685 return (state_func_t) single_user;
686 }
687 }
688
689 runcom_mode = FASTBOOT;
690 #ifndef LETS_GET_SMALL
691 return (state_func_t) runcom;
692 #else /* LETS_GET_SMALL */
693 return (state_func_t) single_user;
694 #endif /* LETS_GET_SMALL */
695 }
696
697 #ifndef LETS_GET_SMALL
698 /*
699 * Run the system startup script.
700 */
701 state_func_t
702 runcom()
703 {
704 pid_t pid, wpid;
705 int status;
706 char *argv[4];
707 struct sigaction sa;
708
709 if ((pid = fork()) == 0) {
710 sigemptyset(&sa.sa_mask);
711 sa.sa_flags = 0;
712 sa.sa_handler = SIG_IGN;
713 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
714 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
715
716 setctty(_PATH_CONSOLE);
717
718 argv[0] = "sh";
719 argv[1] = _PATH_RUNCOM;
720 argv[2] = runcom_mode == AUTOBOOT ? "autoboot" : 0;
721 argv[3] = 0;
722
723 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
724
725 execv(_PATH_BSHELL, argv);
726 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
727 _exit(1); /* force single user mode */
728 }
729
730 if (pid == -1) {
731 emergency("can't fork for %s on %s: %m",
732 _PATH_BSHELL, _PATH_RUNCOM);
733 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
734 continue;
735 sleep(STALL_TIMEOUT);
736 return (state_func_t) single_user;
737 }
738
739 /*
740 * Copied from single_user(). This is a bit paranoid.
741 */
742 do {
743 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
744 collect_child(wpid);
745 if (wpid == -1) {
746 if (errno == EINTR)
747 continue;
748 warning("wait for %s on %s failed: %m; going to single user mode",
749 _PATH_BSHELL, _PATH_RUNCOM);
750 return (state_func_t) single_user;
751 }
752 if (wpid == pid && WIFSTOPPED(status)) {
753 warning("init: %s on %s stopped, restarting\n",
754 _PATH_BSHELL, _PATH_RUNCOM);
755 kill(pid, SIGCONT);
756 wpid = -1;
757 }
758 } while (wpid != pid);
759
760 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
761 requested_transition == catatonia) {
762 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
763 sigset_t s;
764
765 sigfillset(&s);
766 for (;;)
767 sigsuspend(&s);
768 }
769
770 if (!WIFEXITED(status)) {
771 warning("%s on %s terminated abnormally, going to single user mode",
772 _PATH_BSHELL, _PATH_RUNCOM);
773 return (state_func_t) single_user;
774 }
775
776 if (WEXITSTATUS(status))
777 return (state_func_t) single_user;
778
779 runcom_mode = AUTOBOOT; /* the default */
780 /* NB: should send a message to the session logger to avoid blocking. */
781 logwtmp("~", "reboot", "");
782 return (state_func_t) read_ttys;
783 }
784
785 /*
786 * Open the session database.
787 *
788 * NB: We could pass in the size here; is it necessary?
789 */
790 int
791 start_session_db()
792 {
793 if (session_db && (*session_db->close)(session_db))
794 emergency("session database close: %s", strerror(errno));
795 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
796 emergency("session database open: %s", strerror(errno));
797 return (1);
798 }
799 return (0);
800
801 }
802
803 /*
804 * Add a new login session.
805 */
806 void
807 add_session(sp)
808 session_t *sp;
809 {
810 DBT key;
811 DBT data;
812
813 key.data = &sp->se_process;
814 key.size = sizeof sp->se_process;
815 data.data = &sp;
816 data.size = sizeof sp;
817
818 if ((*session_db->put)(session_db, &key, &data, 0))
819 emergency("insert %d: %s", sp->se_process, strerror(errno));
820 }
821
822 /*
823 * Delete an old login session.
824 */
825 void
826 del_session(sp)
827 session_t *sp;
828 {
829 DBT key;
830
831 key.data = &sp->se_process;
832 key.size = sizeof sp->se_process;
833
834 if ((*session_db->del)(session_db, &key, 0))
835 emergency("delete %d: %s", sp->se_process, strerror(errno));
836 }
837
838 /*
839 * Look up a login session by pid.
840 */
841 session_t *
842 #ifdef __STDC__
843 find_session(pid_t pid)
844 #else
845 find_session(pid)
846 pid_t pid;
847 #endif
848 {
849 DBT key;
850 DBT data;
851 session_t *ret;
852
853 key.data = &pid;
854 key.size = sizeof pid;
855 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
856 return 0;
857 bcopy(data.data, (char *)&ret, sizeof(ret));
858 return ret;
859 }
860
861 /*
862 * Construct an argument vector from a command line.
863 */
864 char **
865 construct_argv(command)
866 char *command;
867 {
868 register int argc = 0;
869 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
870 * sizeof (char *));
871 static const char separators[] = " \t";
872
873 if ((argv[argc++] = strtok(command, separators)) == 0)
874 return 0;
875 while (argv[argc++] = strtok((char *) 0, separators))
876 continue;
877 return argv;
878 }
879
880 /*
881 * Deallocate a session descriptor.
882 */
883 void
884 free_session(sp)
885 register session_t *sp;
886 {
887 free(sp->se_device);
888 if (sp->se_getty) {
889 free(sp->se_getty);
890 free(sp->se_getty_argv);
891 }
892 if (sp->se_window) {
893 free(sp->se_window);
894 free(sp->se_window_argv);
895 }
896 free(sp);
897 }
898
899 /*
900 * Allocate a new session descriptor.
901 */
902 session_t *
903 new_session(sprev, session_index, typ)
904 session_t *sprev;
905 int session_index;
906 register struct ttyent *typ;
907 {
908 register session_t *sp;
909
910 if ((typ->ty_status & TTY_ON) == 0 ||
911 typ->ty_name == 0 ||
912 typ->ty_getty == 0)
913 return 0;
914
915 sp = (session_t *) malloc(sizeof (session_t));
916 bzero(sp, sizeof *sp);
917
918 sp->se_index = session_index;
919
920 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
921 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
922
923 if (setupargv(sp, typ) == 0) {
924 free_session(sp);
925 return (0);
926 }
927
928 sp->se_next = 0;
929 if (sprev == 0) {
930 sessions = sp;
931 sp->se_prev = 0;
932 } else {
933 sprev->se_next = sp;
934 sp->se_prev = sprev;
935 }
936
937 return sp;
938 }
939
940 /*
941 * Calculate getty and if useful window argv vectors.
942 */
943 int
944 setupargv(sp, typ)
945 session_t *sp;
946 struct ttyent *typ;
947 {
948
949 if (sp->se_getty) {
950 free(sp->se_getty);
951 free(sp->se_getty_argv);
952 }
953 sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
954 (void) sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
955 sp->se_getty_argv = construct_argv(sp->se_getty);
956 if (sp->se_getty_argv == 0) {
957 warning("can't parse getty for port %s", sp->se_device);
958 free(sp->se_getty);
959 sp->se_getty = 0;
960 return (0);
961 }
962 if (typ->ty_window) {
963 if (sp->se_window)
964 free(sp->se_window);
965 sp->se_window = strdup(typ->ty_window);
966 sp->se_window_argv = construct_argv(sp->se_window);
967 if (sp->se_window_argv == 0) {
968 warning("can't parse window for port %s",
969 sp->se_device);
970 free(sp->se_window);
971 sp->se_window = 0;
972 return (0);
973 }
974 }
975 return (1);
976 }
977
978 /*
979 * Walk the list of ttys and create sessions for each active line.
980 */
981 state_func_t
982 read_ttys()
983 {
984 int session_index = 0;
985 register session_t *sp, *snext;
986 register struct ttyent *typ;
987
988 /*
989 * Destroy any previous session state.
990 * There shouldn't be any, but just in case...
991 */
992 for (sp = sessions; sp; sp = snext) {
993 if (sp->se_process)
994 clear_session_logs(sp);
995 snext = sp->se_next;
996 free_session(sp);
997 }
998 sessions = 0;
999 if (start_session_db())
1000 return (state_func_t) single_user;
1001
1002 /*
1003 * Allocate a session entry for each active port.
1004 * Note that sp starts at 0.
1005 */
1006 while (typ = getttyent())
1007 if (snext = new_session(sp, ++session_index, typ))
1008 sp = snext;
1009
1010 endttyent();
1011
1012 return (state_func_t) multi_user;
1013 }
1014
1015 /*
1016 * Start a window system running.
1017 */
1018 void
1019 start_window_system(sp)
1020 session_t *sp;
1021 {
1022 pid_t pid;
1023 sigset_t mask;
1024
1025 if ((pid = fork()) == -1) {
1026 emergency("can't fork for window system on port %s: %m",
1027 sp->se_device);
1028 /* hope that getty fails and we can try again */
1029 return;
1030 }
1031
1032 if (pid)
1033 return;
1034
1035 sigemptyset(&mask);
1036 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1037
1038 if (setsid() < 0)
1039 emergency("setsid failed (window) %m");
1040
1041 execv(sp->se_window_argv[0], sp->se_window_argv);
1042 stall("can't exec window system '%s' for port %s: %m",
1043 sp->se_window_argv[0], sp->se_device);
1044 _exit(1);
1045 }
1046
1047 /*
1048 * Start a login session running.
1049 */
1050 pid_t
1051 start_getty(sp)
1052 session_t *sp;
1053 {
1054 pid_t pid;
1055 sigset_t mask;
1056 time_t current_time = time((time_t *) 0);
1057
1058 /*
1059 * fork(), not vfork() -- we can't afford to block.
1060 */
1061 if ((pid = fork()) == -1) {
1062 emergency("can't fork for getty on port %s: %m", sp->se_device);
1063 return -1;
1064 }
1065
1066 if (pid)
1067 return pid;
1068
1069 if (current_time > sp->se_started &&
1070 current_time - sp->se_started < GETTY_SPACING) {
1071 warning("getty repeating too quickly on port %s, sleeping",
1072 sp->se_device);
1073 sleep((unsigned) GETTY_SLEEP);
1074 }
1075
1076 if (sp->se_window) {
1077 start_window_system(sp);
1078 sleep(WINDOW_WAIT);
1079 }
1080
1081 sigemptyset(&mask);
1082 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1083
1084 execv(sp->se_getty_argv[0], sp->se_getty_argv);
1085 stall("can't exec getty '%s' for port %s: %m",
1086 sp->se_getty_argv[0], sp->se_device);
1087 _exit(1);
1088 }
1089 #endif /* LETS_GET_SMALL */
1090
1091 /*
1092 * Collect exit status for a child.
1093 * If an exiting login, start a new login running.
1094 */
1095 void
1096 #ifdef __STDC__
1097 collect_child(pid_t pid)
1098 #else
1099 collect_child(pid)
1100 pid_t pid;
1101 #endif
1102 {
1103 #ifndef LETS_GET_SMALL
1104 register session_t *sp, *sprev, *snext;
1105
1106 if (! sessions)
1107 return;
1108
1109 if (! (sp = find_session(pid)))
1110 return;
1111
1112 clear_session_logs(sp);
1113 del_session(sp);
1114 sp->se_process = 0;
1115
1116 if (sp->se_flags & SE_SHUTDOWN) {
1117 if (sprev = sp->se_prev)
1118 sprev->se_next = sp->se_next;
1119 else
1120 sessions = sp->se_next;
1121 if (snext = sp->se_next)
1122 snext->se_prev = sp->se_prev;
1123 free_session(sp);
1124 return;
1125 }
1126
1127 if ((pid = start_getty(sp)) == -1) {
1128 /* serious trouble */
1129 requested_transition = clean_ttys;
1130 return;
1131 }
1132
1133 sp->se_process = pid;
1134 sp->se_started = time((time_t *) 0);
1135 add_session(sp);
1136 #endif /* LETS_GET_SMALL */
1137 }
1138
1139 /*
1140 * Catch a signal and request a state transition.
1141 */
1142 void
1143 transition_handler(sig)
1144 int sig;
1145 {
1146
1147 switch (sig) {
1148 #ifndef LETS_GET_SMALL
1149 case SIGHUP:
1150 requested_transition = clean_ttys;
1151 break;
1152 case SIGTERM:
1153 requested_transition = death;
1154 break;
1155 case SIGTSTP:
1156 requested_transition = catatonia;
1157 break;
1158 #endif /* LETS_GET_SMALL */
1159 default:
1160 requested_transition = 0;
1161 break;
1162 }
1163 }
1164
1165 #ifndef LETS_GET_SMALL
1166 /*
1167 * Take the system multiuser.
1168 */
1169 state_func_t
1170 multi_user()
1171 {
1172 pid_t pid;
1173 register session_t *sp;
1174
1175 requested_transition = 0;
1176
1177 /*
1178 * If the administrator has not set the security level to -1
1179 * to indicate that the kernel should not run multiuser in secure
1180 * mode, and the run script has not set a higher level of security
1181 * than level 1, then put the kernel into secure mode.
1182 */
1183 if (getsecuritylevel() == 0)
1184 setsecuritylevel(1);
1185
1186 for (sp = sessions; sp; sp = sp->se_next) {
1187 if (sp->se_process)
1188 continue;
1189 if ((pid = start_getty(sp)) == -1) {
1190 /* serious trouble */
1191 requested_transition = clean_ttys;
1192 break;
1193 }
1194 sp->se_process = pid;
1195 sp->se_started = time((time_t *) 0);
1196 add_session(sp);
1197 }
1198
1199 while (!requested_transition)
1200 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1201 collect_child(pid);
1202
1203 return (state_func_t) requested_transition;
1204 }
1205
1206 /*
1207 * This is an n-squared algorithm. We hope it isn't run often...
1208 */
1209 state_func_t
1210 clean_ttys()
1211 {
1212 register session_t *sp, *sprev;
1213 register struct ttyent *typ;
1214 register int session_index = 0;
1215 register int devlen;
1216
1217 devlen = sizeof(_PATH_DEV) - 1;
1218 while (typ = getttyent()) {
1219 ++session_index;
1220
1221 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1222 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1223 break;
1224
1225 if (sp) {
1226 if (sp->se_index != session_index) {
1227 warning("port %s changed utmp index from %d to %d",
1228 sp->se_device, sp->se_index,
1229 session_index);
1230 sp->se_index = session_index;
1231 }
1232 if ((typ->ty_status & TTY_ON) == 0 ||
1233 typ->ty_getty == 0) {
1234 sp->se_flags |= SE_SHUTDOWN;
1235 kill(sp->se_process, SIGHUP);
1236 continue;
1237 }
1238 sp->se_flags &= ~SE_SHUTDOWN;
1239 if (setupargv(sp, typ) == 0) {
1240 warning("can't parse getty for port %s",
1241 sp->se_device);
1242 sp->se_flags |= SE_SHUTDOWN;
1243 kill(sp->se_process, SIGHUP);
1244 }
1245 continue;
1246 }
1247
1248 new_session(sprev, session_index, typ);
1249 }
1250
1251 endttyent();
1252
1253 return (state_func_t) multi_user;
1254 }
1255
1256 /*
1257 * Block further logins.
1258 */
1259 state_func_t
1260 catatonia()
1261 {
1262 register session_t *sp;
1263
1264 for (sp = sessions; sp; sp = sp->se_next)
1265 sp->se_flags |= SE_SHUTDOWN;
1266
1267 return (state_func_t) multi_user;
1268 }
1269 #endif /* LETS_GET_SMALL */
1270
1271 /*
1272 * Note SIGALRM.
1273 */
1274 void
1275 alrm_handler(sig)
1276 int sig;
1277 {
1278 clang = 1;
1279 }
1280
1281 #ifndef LETS_GET_SMALL
1282 /*
1283 * Bring the system down to single user.
1284 */
1285 state_func_t
1286 death()
1287 {
1288 register session_t *sp;
1289 register int i;
1290 pid_t pid;
1291 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1292
1293 for (sp = sessions; sp; sp = sp->se_next)
1294 sp->se_flags |= SE_SHUTDOWN;
1295
1296 /* NB: should send a message to the session logger to avoid blocking. */
1297 logwtmp("~", "shutdown", "");
1298
1299 for (i = 0; i < 3; ++i) {
1300 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1301 return (state_func_t) single_user;
1302
1303 clang = 0;
1304 alarm(DEATH_WATCH);
1305 do
1306 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1307 collect_child(pid);
1308 while (clang == 0 && errno != ECHILD);
1309
1310 if (errno == ECHILD)
1311 return (state_func_t) single_user;
1312 }
1313
1314 warning("some processes would not die; ps axl advised");
1315
1316 return (state_func_t) single_user;
1317 }
1318 #endif /* LETS_GET_SMALL */
1319