]> git.saurik.com Git - apple/system_cmds.git/blob - init.tproj/init.c
system_cmds-279.6.1.tar.gz
[apple/system_cmds.git] / init.tproj / init.c
1 /*
2 * Copyright (c) 1999 Apple Computer, Inc. All rights reserved.
3 *
4 * @APPLE_LICENSE_HEADER_START@
5 *
6 * "Portions Copyright (c) 1999 Apple Computer, Inc. All Rights
7 * Reserved. This file contains Original Code and/or Modifications of
8 * Original Code as defined in and that are subject to the Apple Public
9 * Source License Version 1.0 (the 'License'). You may not use this file
10 * except in compliance with the License. Please obtain a copy of the
11 * License at http://www.apple.com/publicsource and read it before using
12 * this file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE OR NON-INFRINGEMENT. Please see the
19 * License for the specific language governing rights and limitations
20 * under the License."
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24 /*-
25 * Copyright (c) 1991, 1993
26 * The Regents of the University of California. All rights reserved.
27 *
28 * This code is derived from software contributed to Berkeley by
29 * Donn Seeley at Berkeley Software Design, Inc.
30 *
31 * Redistribution and use in source and binary forms, with or without
32 * modification, are permitted provided that the following conditions
33 * are met:
34 * 1. Redistributions of source code must retain the above copyright
35 * notice, this list of conditions and the following disclaimer.
36 * 2. Redistributions in binary form must reproduce the above copyright
37 * notice, this list of conditions and the following disclaimer in the
38 * documentation and/or other materials provided with the distribution.
39 * 3. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
41 * This product includes software developed by the University of
42 * California, Berkeley and its contributors.
43 * 4. Neither the name of the University nor the names of its contributors
44 * may be used to endorse or promote products derived from this software
45 * without specific prior written permission.
46 *
47 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
48 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
49 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
50 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
51 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
52 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
53 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
55 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
56 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
57 * SUCH DAMAGE.
58 */
59
60 #include <sys/param.h>
61 #include <sys/sysctl.h>
62 #include <sys/wait.h>
63
64 #include <db.h>
65 #include <errno.h>
66 #include <fcntl.h>
67 #include <signal.h>
68 #include <stdio.h>
69 #include <stdlib.h>
70 #include <string.h>
71 #include <syslog.h>
72 #include <time.h>
73 #include <ttyent.h>
74 #include <unistd.h>
75 #include <paths.h>
76
77 #include <stdarg.h>
78
79 #ifdef SECURE
80 #include <pwd.h>
81 #endif
82
83 #include "pathnames.h"
84
85 /*
86 * Until the mythical util.h arrives...
87 */
88 extern int login_tty __P((int));
89 extern int logout __P((const char *));
90 extern void logwtmp __P((const char *, const char *, const char *));
91
92 /*
93 * Sleep times; used to prevent thrashing.
94 */
95 #define GETTY_SPACING 5 /* N secs minimum getty spacing */
96 #define GETTY_SLEEP 30 /* sleep N secs after spacing problem */
97 #define WINDOW_WAIT 3 /* wait N secs after starting window */
98 #define STALL_TIMEOUT 30 /* wait N secs after warning */
99 #define DEATH_WATCH 10 /* wait N secs for procs to die */
100 #define FAILED_HW_PASS 5 /* wait N secs before croaking user */
101
102 void handle __P((sig_t, ...));
103 void delset __P((sigset_t *, ...));
104
105 void stall __P((char *, ...));
106 void warning __P((char *, ...));
107 void emergency __P((char *, ...));
108 void disaster __P((int));
109 void badsys __P((int));
110
111 /*
112 * We really need a recursive typedef...
113 * The following at least guarantees that the return type of (*state_t)()
114 * is sufficiently wide to hold a function pointer.
115 */
116 typedef long (*state_func_t) __P((void));
117 typedef state_func_t (*state_t) __P((void));
118
119 state_func_t single_user __P((void));
120 state_func_t runcom __P((void));
121 state_func_t read_ttys __P((void));
122 state_func_t multi_user __P((void));
123 state_func_t clean_ttys __P((void));
124 state_func_t catatonia __P((void));
125 state_func_t death __P((void));
126
127 enum { AUTOBOOT, FASTBOOT, BOOT_SCRIPT } runcom_mode = AUTOBOOT;
128 int runcom_boot = 1; /* Run the rc.boot script */
129 int runcom_verbose = 0;
130 int runcom_safe = 0;
131
132 void transition __P((state_t));
133 state_t requested_transition = runcom;
134
135 void setctty __P((char *, int));
136
137
138 // gvdl@next.com 14 Aug 1995
139 // - from ~apps/loginwindow_proj/loginwindow/common.h
140 #define REALLY_EXIT_TO_CONSOLE 229
141
142 // From old init.c
143 // These flags are used in the se_flags field of the init_session structure
144 #define SE_SHUTDOWN 0x1 /* session won't be restarted */
145
146 // The flags below control what sort of getty is launched.
147 #define SE_GETTY_LAUNCH 0x30 /* What type of getty to launch */
148 #define SE_COMMON 0x00 /* Usual command that is run - getty */
149 #define SE_ONERROR 0x10 /* Command to run if error condition occurs.
150 * This will almost always be the windowserver
151 * and loginwindow. This is so if the w.s.
152 * ever dies, that the naive user (stan)
153 * doesn't ever see the console window. */
154 #define SE_ONOPTION 0x20 /* Command to run when loginwindow exits with
155 * special error code (229). This signifies
156 * that the user typed "console" at l.w. and
157 * l.w. wants to exit and have init run getty
158 * which will then put up a console window. */
159
160 typedef struct _se_command {
161 char *path; /* what to run on that port */
162 char **argv; /* pre-parsed argument array */
163 } se_cmd_t;
164
165 typedef struct init_session {
166 int se_index; /* index of entry in ttys file */
167 pid_t se_process; /* controlling process */
168 time_t se_started; /* used to avoid thrashing */
169 int se_flags; /* status of session */
170 char *se_device; /* filename of port */
171 se_cmd_t se_getty; /* what to run on that port */
172 se_cmd_t se_window; /* window system (started only once) */
173 se_cmd_t se_onerror; /* See SE_ONERROR above */
174 se_cmd_t se_onoption; /* See SE_ONOPTION above */
175 struct init_session *se_prev;
176 struct init_session *se_next;
177 } session_t;
178
179 void free_session __P((session_t *));
180 session_t *new_session __P((session_t *, int, struct ttyent *));
181 session_t *sessions;
182
183 char **construct_argv __P((char *));
184 void collect_child __P((pid_t));
185 pid_t start_getty __P((session_t *));
186 void transition_handler __P((int));
187 void alrm_handler __P((int));
188 void setsecuritylevel __P((int));
189 int getsecuritylevel __P((void));
190 int setupargv __P((session_t *, struct ttyent *));
191 int clang;
192
193 void clear_session_logs __P((session_t *));
194
195 int start_session_db __P((void));
196 void add_session __P((session_t *));
197 void del_session __P((session_t *));
198 session_t *find_session __P((pid_t));
199 DB *session_db;
200
201 /*
202 * The mother of all processes.
203 */
204 int
205 main(argc, argv)
206 int argc;
207 char **argv;
208 {
209 int c;
210 struct sigaction sa;
211 sigset_t mask;
212
213
214 /* Dispose of random users. */
215 if (getuid() != 0) {
216 (void)fprintf(stderr, "init: %s\n", strerror(EPERM));
217 exit (1);
218 }
219
220 /* System V users like to reexec init. */
221 if (getpid() != 1) {
222 (void)fprintf(stderr, "init: already running\n");
223 exit (1);
224 }
225
226 /*
227 * Note that this does NOT open a file...
228 * Does 'init' deserve its own facility number?
229 */
230 openlog("init", LOG_CONS|LOG_ODELAY, LOG_AUTH);
231
232 /*
233 * Create an initial session.
234 */
235 if (setsid() < 0)
236 warning("initial setsid() failed: %m");
237
238 /*
239 * Establish an initial user so that programs running
240 * single user do not freak out and die (like passwd).
241 */
242 if (setlogin("root") < 0)
243 warning("setlogin() failed: %m");
244
245 /*
246 * This code assumes that we always get arguments through flags,
247 * never through bits set in some random machine register.
248 */
249
250 #ifdef DEBUG
251 {
252 int i;
253 for (i = 0; i <= argc; i++) {
254 if (argv[i])
255 warning("init argument %d: '%s'", i, argv[i]);
256 else
257 warning("init argument %d: ***NULL***", i);
258 }
259 }
260 #endif
261
262 while ((c = getopt(argc, argv, "sfbvx")) != -1) {
263 #ifdef DEBUG
264 warning("handling init argument '-%c'", c);
265 #endif
266 switch (c) {
267 case 's':
268 requested_transition = single_user;
269 break;
270 case 'f':
271 runcom_mode = FASTBOOT;
272 break;
273 case 'b':
274 runcom_boot = 0; // Don't runcom rc.boot
275 break;
276 case 'v':
277 runcom_verbose = 1;
278 break;
279 case 'x':
280 runcom_safe = 1;
281 break;
282 default:
283 warning("unrecognized flag '-%c'", c);
284 break;
285 }
286 }
287
288 if (optind != argc)
289 warning("ignoring excess arguments");
290
291 /*
292 * We catch or block signals rather than ignore them,
293 * so that they get reset on exec.
294 */
295 handle(badsys, SIGSYS, 0);
296 handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV,
297 SIGBUS, SIGXCPU, SIGXFSZ, 0);
298 handle(transition_handler, SIGHUP, SIGTERM, SIGTSTP, 0);
299 handle(alrm_handler, SIGALRM, 0);
300 sigfillset(&mask);
301 delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
302 SIGXCPU, SIGXFSZ, SIGHUP, SIGTERM, SIGTSTP, SIGALRM, 0);
303 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
304 sigemptyset(&sa.sa_mask);
305 sa.sa_flags = 0;
306 sa.sa_handler = SIG_IGN;
307 (void) sigaction(SIGTTIN, &sa, (struct sigaction *)0);
308 (void) sigaction(SIGTTOU, &sa, (struct sigaction *)0);
309
310 /*
311 * Paranoia.
312 */
313 close(0);
314 close(1);
315 close(2);
316
317 if (runcom_boot)
318 {
319 int old_rc_mode = runcom_mode;
320
321 runcom_mode = BOOT_SCRIPT;
322 if (runcom() == (state_func_t) single_user)
323 requested_transition = single_user; // Error in script
324 runcom_mode = old_rc_mode;
325 }
326
327 /*
328 * Start the state machine.
329 */
330 transition(requested_transition);
331
332 /*
333 * Should never reach here.
334 */
335 return 1;
336 }
337
338 /*
339 * Associate a function with a signal handler.
340 */
341 void
342 handle(sig_t handler, ...)
343 {
344 int sig;
345 struct sigaction sa;
346 int mask_everything;
347 va_list ap;
348 va_start(ap, handler);
349
350 sa.sa_handler = handler;
351 sigfillset(&mask_everything);
352
353 while (sig = va_arg(ap, int)) {
354 sa.sa_mask = mask_everything;
355 /* XXX SA_RESTART? */
356 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
357 sigaction(sig, &sa, (struct sigaction *) 0);
358 }
359 va_end(ap);
360 }
361
362 /*
363 * Delete a set of signals from a mask.
364 */
365 void
366 delset(sigset_t *maskp, ...)
367 {
368 int sig;
369 va_list ap;
370 va_start(ap, maskp);
371
372 while (sig = va_arg(ap, int))
373 sigdelset(maskp, sig);
374 va_end(ap);
375 }
376
377 /*
378 * Log a message and sleep for a while (to give someone an opportunity
379 * to read it and to save log or hardcopy output if the problem is chronic).
380 * NB: should send a message to the session logger to avoid blocking.
381 */
382 void
383 stall(char *message, ...)
384 {
385 va_list ap;
386 va_start(ap, message);
387
388 vsyslog(LOG_ALERT, message, ap);
389 va_end(ap);
390 sleep(STALL_TIMEOUT);
391 }
392
393 /*
394 * Like stall(), but doesn't sleep.
395 * If cpp had variadic macros, the two functions could be #defines for another.
396 * NB: should send a message to the session logger to avoid blocking.
397 */
398 void
399 warning(char *message, ...)
400 {
401 va_list ap;
402 va_start(ap, message);
403
404 vsyslog(LOG_ALERT, message, ap);
405 va_end(ap);
406 }
407
408 /*
409 * Log an emergency message.
410 * NB: should send a message to the session logger to avoid blocking.
411 */
412 void
413 emergency(char *message, ...)
414 {
415 va_list ap;
416 va_start(ap, message);
417
418 vsyslog(LOG_EMERG, message, ap);
419 va_end(ap);
420 }
421
422 /*
423 * Catch a SIGSYS signal.
424 *
425 * These may arise if a system does not support sysctl.
426 * We tolerate up to 25 of these, then throw in the towel.
427 */
428 void
429 badsys(sig)
430 int sig;
431 {
432 static int badcount = 0;
433
434 if (badcount++ < 25)
435 return;
436 disaster(sig);
437 }
438
439 /*
440 * Catch an unexpected signal.
441 */
442 void
443 disaster(sig)
444 int sig;
445 {
446 emergency("fatal signal: %s",
447 sig < (unsigned) NSIG ? sys_siglist[sig] : "unknown signal");
448
449 sleep(STALL_TIMEOUT);
450 _exit(sig); /* reboot */
451 }
452
453 /*
454 * Get the security level of the kernel.
455 */
456 int
457 getsecuritylevel()
458 {
459 #ifdef KERN_SECURELVL
460 int name[2], curlevel;
461 size_t len;
462 extern int errno;
463
464 name[0] = CTL_KERN;
465 name[1] = KERN_SECURELVL;
466 len = sizeof curlevel;
467 if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
468 emergency("cannot get kernel security level: %s",
469 strerror(errno));
470 return (-1);
471 }
472 return (curlevel);
473 #else
474 return (-1);
475 #endif
476 }
477
478 /*
479 * Set the security level of the kernel.
480 */
481 void
482 setsecuritylevel(newlevel)
483 int newlevel;
484 {
485 #ifdef KERN_SECURELVL
486 int name[2], curlevel;
487 extern int errno;
488
489 curlevel = getsecuritylevel();
490 if (newlevel == curlevel)
491 return;
492 name[0] = CTL_KERN;
493 name[1] = KERN_SECURELVL;
494 if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
495 emergency(
496 "cannot change kernel security level from %d to %d: %s",
497 curlevel, newlevel, strerror(errno));
498 return;
499 }
500 #ifdef SECURE
501 warning("kernel security level changed from %d to %d",
502 curlevel, newlevel);
503 #endif
504 #endif
505 }
506
507 /*
508 * Change states in the finite state machine.
509 * The initial state is passed as an argument.
510 */
511 void
512 transition(s)
513 state_t s;
514 {
515 for (;;)
516 s = (state_t) (*s)();
517 }
518
519 /*
520 * Close out the accounting files for a login session.
521 * NB: should send a message to the session logger to avoid blocking.
522 */
523 void
524 clear_session_logs(sp)
525 session_t *sp;
526 {
527 char *line = sp->se_device + sizeof(_PATH_DEV) - 1;
528
529 if (logout(line))
530 logwtmp(line, "", "");
531 }
532
533 /*
534 * Start a session and allocate a controlling terminal.
535 * Only called by children of init after forking.
536 */
537 void
538 setctty(name, flags)
539 char *name;
540 int flags;
541 {
542 int fd;
543
544 (void) revoke(name);
545 if ((fd = open(name, flags | O_RDWR)) == -1) {
546 stall("can't open %s: %m", name);
547 _exit(1);
548 }
549 if (login_tty(fd) == -1) {
550 stall("can't get %s for controlling terminal: %m", name);
551 _exit(1);
552 }
553 }
554
555 #if m68k
556 /*
557 * Taken from etc/halt/halt.c
558 */
559
560 #include <stdio.h>
561 #include <signal.h>
562 #include <sgtty.h>
563
564 static void shutend(void)
565 {
566 register i;
567
568 acct(0);
569 for (i = 0; i < 10; i++)
570 close(i);
571
572 logwtmp("~", "shutdown", "");
573 }
574
575 static void do_halt(void)
576 {
577 char sbuf [40];
578 int halthowto = RB_HALT;
579
580 (void) kill(-1, SIGTERM); /* one chance to catch it */
581
582 sprintf (sbuf, "Invalid hardware password, halting machine...\n");
583 write (1, sbuf, strlen (sbuf));
584
585 signal(SIGALRM, SIG_DFL);
586 shutend();
587 sync();
588
589 signal(SIGALRM, alrm_handler);
590 alarm(FAILED_HW_PASS);
591 pause();
592
593 syscall(SYS_reboot, halthowto);
594 }
595
596 /*
597 * Taken from lib/gen/getpass.c
598 */
599
600 static char *gethwpasswd(char *prompt)
601 {
602 struct termios term;
603 register char *p;
604 register c;
605 static char pbuf[9];
606 int echo;
607
608 (void) tcgetattr(1, &term);
609 if (echo = (term.c_lflag & ECHO))
610 {
611 term.c_lflag &= ~ECHO;
612 (void) tcsetattr(1, TCSAFLUSH|TCSASOFT, &term);
613 }
614
615 write(2, prompt, strlen(prompt));
616
617 for (p = pbuf; (c = getchar()) != '\n' && c != EOF; )
618 if (p < &pbuf[8])
619 *p++ = c;
620 *p = '\0';
621
622 p = "\n";
623 write(2, p, strlen(p));
624
625 if (echo)
626 {
627 term.c_lflag |= ECHO;
628 (void) tcsetattr(1, TCSAFLUSH|TCSASOFT, &term);
629 }
630
631 return(pbuf);
632 }
633
634
635 static char *hw_passwd (void)
636 {
637 char sbuf[40];
638 static char buffer [12];
639 struct nvram_info nvi;
640 int vidfd, count;
641
642 if ((vidfd = open ("/dev/vid0", O_RDONLY, 0)) == -1)
643 return NULL;
644
645 if (ioctl (vidfd, DKIOCGNVRAM, &nvi) == -1)
646 return NULL;
647
648 if (nvi.ni_hw_pwd != HW_PWD)
649 return NULL;
650 else
651 {
652
653 for (count = 0; count < NVRAM_HW_PASSWD; count++)
654 nvi.ni_ep[count] ^= 'N';
655 strncpy(buffer, nvi.ni_ep, NVRAM_HW_PASSWD);
656 /* ni_ep is not necessarily null terminated */
657
658 // gvdl I sure hope it is 'cause bad things will happen otherwise
659
660 return buffer;
661 }
662 }
663
664
665 #endif m68k
666
667
668 static void
669 do_security_check(void)
670 {
671 #if m68k
672 char sbuf[128];
673 char *try, *passwd;
674 int retries = 0;
675
676 /*
677 * If there is a hardware passwd, we want to
678 * prompt the user for it. The write will be
679 * to the console window because of the O_POPUP flag.
680 */
681 passwd = hw_passwd();
682 write (1, "\n\n", 2);
683
684 if (passwd != NULL)
685 {
686 do
687 {
688 try = gethwpasswd ("Enter hardware password:");
689 if (strncmp (try, passwd, NVRAM_HW_PASSWD) == 0)
690 {
691 execl(shell, minus, (char *)0);
692 exit (0);
693 }
694 else
695 {
696 sprintf (sbuf, "Password incorrect.\n\n");
697 write (1, sbuf, strlen (sbuf));
698 }
699 }
700 while (++retries < 3);
701 do_halt();
702 }
703 #elif defined(SECURE)
704 struct ttyent *typ;
705 struct passwd *pp;
706 static const char banner[] =
707 "Enter root password, or ^D to go multi-user\n";
708 char *clear, *password;
709
710 /*
711 * Check the root password.
712 * We don't care if the console is 'on' by default;
713 * it's the only tty that can be 'off' and 'secure'.
714 */
715 typ = getttynam("console");
716 pp = getpwnam("root");
717 if (typ && (typ->ty_status & TTY_SECURE) == 0 && pp)
718 {
719 write(2, banner, sizeof banner - 1);
720 for (;;)
721 {
722 clear = getpass("Password:");
723 if (clear == 0 || *clear == '\0')
724 _exit(0);
725 password = crypt(clear, pp->pw_passwd);
726 memset(clear, 0, _PASSWORD_LEN);
727 if (strcmp(password, pp->pw_passwd) == 0)
728 break;
729 warning("single-user login failed\n");
730 }
731 }
732 endttyent();
733 endpwent();
734 #endif /* SECURE */
735 }
736
737 /*
738 * Bring the system up single user.
739 */
740 state_func_t
741 single_user()
742 {
743 pid_t pid, wpid;
744 int status;
745 sigset_t mask;
746 char *shell = _PATH_BSHELL;
747 char *argv[2];
748 /*
749 * If the kernel is in secure mode, downgrade it to insecure mode.
750 */
751 if (getsecuritylevel() > 0)
752 setsecuritylevel(0);
753
754 if ((pid = fork()) == 0) {
755 /*
756 * Start the single user session.
757 */
758 setctty(_PATH_CONSOLE, O_POPUP);
759
760 do_security_check();
761
762 #ifdef DEBUGSHELL
763 {
764 char altshell[128], *cp = altshell;
765 int num;
766
767 #define SHREQUEST \
768 "Enter pathname of shell or RETURN for sh: "
769 (void)write(STDERR_FILENO,
770 SHREQUEST, sizeof(SHREQUEST) - 1);
771 while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
772 num != 0 && *cp != '\n' && cp < &altshell[127])
773 cp++;
774 *cp = '\0';
775 if (altshell[0] != '\0')
776 shell = altshell;
777 }
778 #endif /* DEBUGSHELL */
779
780 /*
781 * Unblock signals.
782 * We catch all the interesting ones,
783 * and those are reset to SIG_DFL on exec.
784 */
785 sigemptyset(&mask);
786 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
787
788 /*
789 * Set up the PATH to be approriate for the root user.
790 */
791 setenv("PATH", _PATH_STDPATH, 1);
792
793 /*
794 * We're dropping into the console; set TERM appropriately.
795 */
796 setenv("TERM", "vt100", 1);
797
798 /*
799 * Fire off a shell.
800 * If the default one doesn't work, try the Bourne shell.
801 */
802 argv[0] = "-sh";
803 argv[1] = 0;
804 execv(shell, argv);
805 emergency("can't exec %s for single user: %m", shell);
806 execv(_PATH_BSHELL, argv);
807 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
808 sleep(STALL_TIMEOUT);
809 _exit(1);
810 }
811
812 if (pid == -1) {
813 /*
814 * We are seriously hosed. Do our best.
815 */
816 emergency("can't fork single-user shell, trying again");
817 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
818 continue;
819 return (state_func_t) single_user;
820 }
821
822 requested_transition = 0;
823 do {
824 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
825 collect_child(wpid);
826 if (wpid == -1) {
827 if (errno == EINTR)
828 continue;
829 warning("wait for single-user shell failed: %m; restarting");
830 return (state_func_t) single_user;
831 }
832 if (wpid == pid && WIFSTOPPED(status)) {
833 warning("init: shell stopped, restarting\n");
834 kill(pid, SIGCONT);
835 wpid = -1;
836 }
837 } while (wpid != pid && !requested_transition);
838
839 if (requested_transition)
840 return (state_func_t) requested_transition;
841
842 if (!WIFEXITED(status)) {
843 if (WTERMSIG(status) == SIGKILL) {
844 /*
845 * reboot(8) killed shell?
846 */
847 warning("single user shell terminated.");
848 sleep(STALL_TIMEOUT);
849 _exit(0);
850 } else {
851 warning("single user shell terminated, restarting");
852 return (state_func_t) single_user;
853 }
854 }
855
856 runcom_mode = FASTBOOT;
857 return (state_func_t) runcom;
858 }
859
860 /*
861 * Run the system startup script.
862 */
863 state_func_t
864 runcom()
865 {
866 pid_t pid, wpid;
867 int status;
868 char *argv[4];
869 char options[4];
870 struct sigaction sa;
871
872 if ((pid = fork()) == 0) {
873 sigemptyset(&sa.sa_mask);
874 sa.sa_flags = 0;
875 sa.sa_handler = SIG_IGN;
876 (void) sigaction(SIGTSTP, &sa, (struct sigaction *)0);
877 (void) sigaction(SIGHUP, &sa, (struct sigaction *)0);
878 #ifdef __APPLE__
879 (void) sigaction(SIGINT, &sa, (struct sigaction *)0);
880 #endif
881
882 setctty(_PATH_CONSOLE, 0);
883
884 argv[0] = "sh";
885
886 if (runcom_mode == BOOT_SCRIPT)
887 {
888 argv[1] = _PATH_RUNCOM_BOOT;
889 argv[2] = requested_transition == single_user
890 ? "singleuser" : "multiuser";
891 }
892 else /* runcom_mode != BOOT_SCRIPT */
893 {
894 argv[1] = _PATH_RUNCOM;
895
896 switch(runcom_mode) {
897 case AUTOBOOT:
898 argv[2] = "autoboot";
899 break;
900 default:
901 argv[2] = "multiuser";
902 break;
903 }
904 }
905
906 if (runcom_verbose || runcom_safe)
907 {
908 int i = 0;
909
910 options[i++] = '-';
911 if (runcom_verbose) options[i++] = 'v';
912 if (runcom_safe ) options[i++] = 'x';
913 options[i] = '\0';
914
915 argv[3] = options;
916 }
917 else
918 {
919 argv[3] = 0;
920 }
921
922 argv[4] = 0;
923
924 #ifdef DEBUG
925 {
926 int i;
927 for (i = 0; i <= 4; i++) {
928 if (argv[i])
929 warning("%s argument: %s", _PATH_RUNCOM, argv[i]);
930 }
931 }
932 #endif
933
934 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
935
936 execv(_PATH_BSHELL, argv);
937 stall("can't exec %s for %s: %m", _PATH_BSHELL, _PATH_RUNCOM);
938 _exit(1); /* force single user mode */
939 }
940
941 if (pid == -1) {
942 emergency("can't fork for %s on %s: %m",
943 _PATH_BSHELL, _PATH_RUNCOM);
944 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
945 continue;
946 sleep(STALL_TIMEOUT);
947 return (state_func_t) single_user;
948 }
949
950 /*
951 * Copied from single_user(). This is a bit paranoid.
952 */
953 do {
954 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
955 collect_child(wpid);
956 if (wpid == -1) {
957 if (errno == EINTR)
958 continue;
959 warning("wait for %s on %s failed: %m; going to single user mode",
960 _PATH_BSHELL, _PATH_RUNCOM);
961 return (state_func_t) single_user;
962 }
963 if (wpid == pid && WIFSTOPPED(status)) {
964 warning("init: %s on %s stopped, restarting\n",
965 _PATH_BSHELL, _PATH_RUNCOM);
966 kill(pid, SIGCONT);
967 wpid = -1;
968 }
969 } while (wpid != pid);
970
971 if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
972 requested_transition == catatonia) {
973 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
974 sigset_t s;
975
976 sigfillset(&s);
977 for (;;)
978 sigsuspend(&s);
979 }
980
981 if (!WIFEXITED(status)) {
982 warning("%s on %s terminated abnormally, going to single user mode",
983 _PATH_BSHELL, _PATH_RUNCOM);
984 return (state_func_t) single_user;
985 }
986
987 if (WEXITSTATUS(status))
988 return (state_func_t) single_user;
989
990 runcom_mode = AUTOBOOT; /* the default */
991 /* NB: should send a message to the session logger to avoid blocking. */
992 logwtmp("~", "reboot", "");
993 return (state_func_t) read_ttys;
994 }
995
996 /*
997 * Open the session database.
998 *
999 * NB: We could pass in the size here; is it necessary?
1000 */
1001 int
1002 start_session_db()
1003 {
1004 if (session_db && (*session_db->close)(session_db))
1005 emergency("session database close: %s", strerror(errno));
1006 if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == 0) {
1007 emergency("session database open: %s", strerror(errno));
1008 return (1);
1009 }
1010 return (0);
1011
1012 }
1013
1014 /*
1015 * Add a new login session.
1016 */
1017 void
1018 add_session(sp)
1019 session_t *sp;
1020 {
1021 DBT key;
1022 DBT data;
1023
1024 key.data = &sp->se_process;
1025 key.size = sizeof sp->se_process;
1026 data.data = &sp;
1027 data.size = sizeof sp;
1028
1029 if ((*session_db->put)(session_db, &key, &data, 0))
1030 emergency("insert %d: %s", sp->se_process, strerror(errno));
1031 }
1032
1033 /*
1034 * Delete an old login session.
1035 */
1036 void
1037 del_session(sp)
1038 session_t *sp;
1039 {
1040 DBT key;
1041
1042 key.data = &sp->se_process;
1043 key.size = sizeof sp->se_process;
1044
1045 if ((*session_db->del)(session_db, &key, 0))
1046 emergency("delete %d: %s", sp->se_process, strerror(errno));
1047 }
1048
1049 /*
1050 * Look up a login session by pid.
1051 */
1052 session_t *
1053 find_session(pid_t pid)
1054 {
1055 DBT key;
1056 DBT data;
1057 session_t *ret;
1058
1059 key.data = &pid;
1060 key.size = sizeof pid;
1061 if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1062 return 0;
1063 memmove(&ret, data.data, sizeof(ret));
1064 return ret;
1065 }
1066
1067 /*
1068 * Construct an argument vector from a command line.
1069 */
1070 char **
1071 construct_argv(command)
1072 char *command;
1073 {
1074 register int argc = 0;
1075 register char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1076 * sizeof (char *));
1077 static const char separators[] = " \t";
1078
1079 if ((argv[argc++] = strtok(command, separators)) == 0)
1080 return 0;
1081 while (argv[argc++] = strtok((char *) 0, separators))
1082 continue;
1083 return argv;
1084 }
1085
1086 /*
1087 * Deallocate a session descriptor.
1088 */
1089
1090 static __inline__ void free_command(se_cmd_t *se_cmd)
1091 {
1092 if (se_cmd->path)
1093 {
1094 free(se_cmd->path);
1095 free(se_cmd->argv);
1096 }
1097 }
1098
1099 void
1100 free_session(sp)
1101 register session_t *sp;
1102 {
1103 free(sp->se_device);
1104 free_command(&sp->se_getty);
1105 free_command(&sp->se_window);
1106 free_command(&sp->se_onerror);
1107 free_command(&sp->se_onoption);
1108 memset(sp, '\0', sizeof(*sp)); // a bit of defensive programming
1109
1110 free(sp);
1111 }
1112
1113 static int setup_command(se_cmd_t *se_cmd, char *command, char *arg )
1114 {
1115
1116 char *commandWithArg;
1117
1118 commandWithArg = malloc( strlen( command) + strlen( arg) + 2);
1119 (void) sprintf(commandWithArg, "%s %s", command, arg);
1120
1121 free_command(se_cmd);
1122
1123 se_cmd->path = commandWithArg;
1124 se_cmd->argv = construct_argv(commandWithArg);
1125 if (se_cmd->argv == NULL)
1126 {
1127 free(se_cmd->path);
1128 se_cmd->path = NULL;
1129 return 0;
1130 }
1131 return 1;
1132 }
1133
1134 /*
1135 * Calculate getty and if useful window argv vectors.
1136 */
1137 int
1138 setupargv(sp, typ)
1139 session_t *sp;
1140 struct ttyent *typ;
1141 {
1142 char *type;
1143
1144 if ( !setup_command(&sp->se_getty, typ->ty_getty, typ->ty_name) )
1145 {
1146 type = "getty";
1147 goto bad_args;
1148 }
1149
1150 if (typ->ty_window
1151 && !setup_command(&sp->se_window, typ->ty_window, typ->ty_name) )
1152 {
1153 type = "window";
1154 goto bad_args;
1155 }
1156
1157 if (typ->ty_onerror
1158 && !setup_command(&sp->se_onerror, typ->ty_onerror, typ->ty_name) )
1159 {
1160 type = "onerror";
1161 goto bad_args;
1162 }
1163
1164 if (typ->ty_onoption
1165 && !setup_command(&sp->se_onoption, typ->ty_onoption, typ->ty_name) )
1166 {
1167 type = "onoption";
1168 goto bad_args;
1169 }
1170
1171 return 1;
1172
1173 bad_args:
1174 warning("can't parse %s for port %s", type, sp->se_device);
1175 return 0;
1176 }
1177
1178
1179 /*
1180 * Allocate a new session descriptor.
1181 */
1182 session_t *
1183 new_session(sprev, session_index, typ)
1184 session_t *sprev;
1185 int session_index;
1186 register struct ttyent *typ;
1187 {
1188 register session_t *sp;
1189
1190 if ((typ->ty_status & TTY_ON) == 0 ||
1191 typ->ty_name == 0 ||
1192 typ->ty_getty == 0)
1193 return 0;
1194
1195 sp = (session_t *) malloc(sizeof (session_t));
1196 memset(sp, 0, sizeof *sp);
1197
1198 sp->se_index = session_index;
1199
1200 sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1201 (void) sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1202
1203 if (setupargv(sp, typ) == 0) {
1204 free_session(sp);
1205 return (0);
1206 }
1207
1208 sp->se_next = 0;
1209 if (sprev == 0) {
1210 sessions = sp;
1211 sp->se_prev = 0;
1212 } else {
1213 sprev->se_next = sp;
1214 sp->se_prev = sprev;
1215 }
1216
1217 return sp;
1218 }
1219
1220 /*
1221 * Walk the list of ttys and create sessions for each active line.
1222 */
1223 state_func_t
1224 read_ttys()
1225 {
1226 int session_index = 0;
1227 register session_t *sp, *snext;
1228 register struct ttyent *typ;
1229
1230 /*
1231 * Destroy any previous session state.
1232 * There shouldn't be any, but just in case...
1233 */
1234 for (sp = sessions; sp; sp = snext) {
1235 if (sp->se_process)
1236 clear_session_logs(sp);
1237 snext = sp->se_next;
1238 free_session(sp);
1239 }
1240 sessions = 0;
1241 if (start_session_db())
1242 return (state_func_t) single_user;
1243
1244 /*
1245 * Allocate a session entry for each active port.
1246 * Note that sp starts at 0.
1247 */
1248 while (typ = getttyent())
1249 if (snext = new_session(sp, ++session_index, typ))
1250 sp = snext;
1251
1252 endttyent();
1253
1254 return (state_func_t) multi_user;
1255 }
1256
1257 /*
1258 * Start a window system running.
1259 */
1260 static pid_t
1261 start_window_system(session_t *sp)
1262 {
1263 pid_t pid;
1264 sigset_t mask;
1265
1266 if ((pid = fork()) == -1) {
1267 emergency("can't fork for window system on port %s: %m",
1268 sp->se_device);
1269 /* hope that getty fails and we can try again */
1270 return -1;
1271 }
1272
1273 if (pid)
1274 return pid;
1275
1276 sigemptyset(&mask);
1277 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1278
1279 if (setsid() < 0)
1280 emergency("setsid failed (window) %m");
1281
1282 execv(sp->se_window.argv[0], sp->se_window.argv);
1283 stall("can't exec window system '%s' for port %s: %m",
1284 sp->se_window.argv[0], sp->se_device);
1285 _exit(1);
1286 }
1287
1288 /*
1289 * Start a login session running.
1290 */
1291 pid_t
1292 start_getty(sp)
1293 session_t *sp;
1294 {
1295 pid_t pid;
1296 sigset_t mask;
1297 se_cmd_t *se_cmd;
1298 const char *session_type = NULL;
1299 time_t current_time = time((time_t *) 0);
1300
1301 // Setup the default values;
1302 switch (sp->se_flags & SE_GETTY_LAUNCH)
1303 {
1304 case SE_ONOPTION:
1305 if (sp->se_onoption.path)
1306 {
1307 se_cmd = &sp->se_onoption;
1308 session_type = "onoption";
1309 break;
1310 }
1311 /* No break */
1312
1313 case SE_ONERROR:
1314 if (sp->se_onerror.path)
1315 {
1316 se_cmd = &sp->se_onerror;
1317 session_type = "onerror";
1318 break;
1319 }
1320 /* No break */
1321
1322 case SE_COMMON:
1323 default:
1324 se_cmd = &sp->se_getty;
1325 session_type = "getty";
1326 break;
1327 }
1328
1329 if (sp->se_window.path
1330 && ((sp->se_flags & SE_GETTY_LAUNCH) != SE_ONOPTION))
1331 {
1332 if (start_window_system(sp) == -1)
1333 return -1;
1334 }
1335
1336 /*
1337 * fork(), not vfork() -- we can't afford to block.
1338 */
1339 if ((pid = fork()) == -1) {
1340 emergency("can't fork for %s on port %s: %m",
1341 session_type, sp->se_device);
1342 return -1;
1343 }
1344
1345 if (pid)
1346 return pid;
1347
1348 if (current_time > sp->se_started &&
1349 current_time - sp->se_started < GETTY_SPACING) {
1350 warning("%s repeating too quickly on port %s, sleeping",
1351 session_type, sp->se_device);
1352 sleep((unsigned) GETTY_SLEEP);
1353 }
1354
1355 sigemptyset(&mask);
1356 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1357
1358 execv(se_cmd->argv[0], se_cmd->argv);
1359 stall("can't exec %s '%s' for port %s: %m", session_type,
1360 se_cmd->argv[0], sp->se_device);
1361 _exit(1);
1362 }
1363
1364 /*
1365 * Collect exit status for a child.
1366 * If an exiting login, start a new login running.
1367 */
1368 void
1369 collect_child(pid_t pid)
1370 {
1371 register session_t *sp, *sprev, *snext;
1372
1373 if ( !sessions)
1374 return;
1375
1376 if ( !(sp = find_session(pid)) )
1377 return;
1378
1379 clear_session_logs(sp);
1380 del_session(sp);
1381 sp->se_process = 0;
1382
1383 if (sp->se_flags & SE_SHUTDOWN) {
1384 if (sprev = sp->se_prev)
1385 sprev->se_next = sp->se_next;
1386 else
1387 sessions = sp->se_next;
1388 if (snext = sp->se_next)
1389 snext->se_prev = sp->se_prev;
1390 free_session(sp);
1391 return;
1392 }
1393
1394 if ((pid = start_getty(sp)) == -1) {
1395 /* serious trouble */
1396 requested_transition = clean_ttys;
1397 return;
1398 }
1399
1400 sp->se_process = pid;
1401 sp->se_started = time((time_t *) 0);
1402 sp->se_flags &= ~SE_GETTY_LAUNCH; // clear down getty launch type
1403 add_session(sp);
1404 }
1405
1406 /*
1407 * Catch a signal and request a state transition.
1408 */
1409 void
1410 transition_handler(sig)
1411 int sig;
1412 {
1413
1414 switch (sig) {
1415 case SIGHUP:
1416 requested_transition = clean_ttys;
1417 break;
1418 case SIGTERM:
1419 requested_transition = death;
1420 break;
1421 case SIGTSTP:
1422 requested_transition = catatonia;
1423 break;
1424 default:
1425 requested_transition = 0;
1426 break;
1427 }
1428 }
1429
1430 /*
1431 * Take the system multiuser.
1432 */
1433 state_func_t
1434 multi_user()
1435 {
1436 pid_t pid;
1437 register session_t *sp;
1438
1439 requested_transition = 0;
1440
1441 /*
1442 * If the administrator has not set the security level to -1
1443 * to indicate that the kernel should not run multiuser in secure
1444 * mode, and the run script has not set a higher level of security
1445 * than level 1, then put the kernel into secure mode.
1446 */
1447 if (getsecuritylevel() == 0)
1448 setsecuritylevel(1);
1449
1450 for (sp = sessions; sp; sp = sp->se_next) {
1451 if (sp->se_process)
1452 continue;
1453 if ((pid = start_getty(sp)) == -1) {
1454 /* serious trouble */
1455 requested_transition = clean_ttys;
1456 break;
1457 }
1458 sp->se_process = pid;
1459 sp->se_started = time((time_t *) 0);
1460 add_session(sp);
1461 }
1462
1463 while (!requested_transition)
1464 {
1465 int status;
1466 session_t *sp;
1467
1468 pid = waitpid(-1, &status, 0);
1469 if (!sessions || !(sp = find_session(pid)))
1470 continue;
1471
1472 if (WIFSIGNALED(status))
1473 sp->se_flags |= SE_ONERROR;
1474 else if (WEXITSTATUS(status) == REALLY_EXIT_TO_CONSOLE)
1475 { /* WIFEXITED(status) assumed */
1476 sp->se_flags |= SE_ONOPTION;
1477 }
1478 else
1479 sp->se_flags |= SE_ONERROR;
1480
1481 if (pid != -1)
1482 collect_child(pid);
1483 }
1484
1485 return (state_func_t) requested_transition;
1486 }
1487
1488 /*
1489 * This is an n-squared algorithm. We hope it isn't run often...
1490 */
1491 state_func_t
1492 clean_ttys()
1493 {
1494 register session_t *sp, *sprev;
1495 register struct ttyent *typ;
1496 register int session_index = 0;
1497 register int devlen;
1498
1499 if (! sessions)
1500 return (state_func_t) multi_user;
1501
1502 devlen = sizeof(_PATH_DEV) - 1;
1503 while (typ = getttyent()) {
1504 ++session_index;
1505
1506 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1507 if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1508 break;
1509
1510 if (sp) {
1511 if (sp->se_index != session_index) {
1512 warning("port %s changed utmp index from %d to %d",
1513 sp->se_device, sp->se_index,
1514 session_index);
1515 sp->se_index = session_index;
1516 }
1517 if ((typ->ty_status & TTY_ON) == 0 ||
1518 typ->ty_getty == 0) {
1519 sp->se_flags |= SE_SHUTDOWN;
1520 kill(sp->se_process, SIGHUP);
1521 continue;
1522 }
1523 sp->se_flags &= ~SE_SHUTDOWN;
1524 if (setupargv(sp, typ) == 0) {
1525 warning("can't parse getty for port %s",
1526 sp->se_device);
1527 sp->se_flags |= SE_SHUTDOWN;
1528 kill(sp->se_process, SIGHUP);
1529 }
1530 continue;
1531 }
1532
1533 new_session(sprev, session_index, typ);
1534 }
1535
1536 endttyent();
1537
1538 return (state_func_t) multi_user;
1539 }
1540
1541 /*
1542 * Block further logins.
1543 */
1544 state_func_t
1545 catatonia()
1546 {
1547 register session_t *sp;
1548
1549 for (sp = sessions; sp; sp = sp->se_next)
1550 sp->se_flags |= SE_SHUTDOWN;
1551
1552 return (state_func_t) multi_user;
1553 }
1554
1555 /*
1556 * Note SIGALRM.
1557 */
1558 void
1559 alrm_handler(sig)
1560 int sig;
1561 {
1562 clang = 1;
1563 }
1564
1565 /*
1566 * Bring the system down to single user.
1567 */
1568 state_func_t
1569 death()
1570 {
1571 register session_t *sp;
1572 register int i;
1573 pid_t pid;
1574 static const int death_sigs[3] = { SIGHUP, SIGTERM, SIGKILL };
1575
1576 for (sp = sessions; sp; sp = sp->se_next)
1577 sp->se_flags |= SE_SHUTDOWN;
1578
1579 /* NB: should send a message to the session logger to avoid blocking. */
1580 logwtmp("~", "shutdown", "");
1581
1582 for (i = 0; i < 3; ++i) {
1583 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1584 return (state_func_t) single_user;
1585
1586 clang = 0;
1587 alarm(DEATH_WATCH);
1588 do
1589 if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1590 collect_child(pid);
1591 while (clang == 0 && errno != ECHILD);
1592
1593 if (errno == ECHILD)
1594 return (state_func_t) single_user;
1595 }
1596
1597 warning("some processes would not die; ps axl advised");
1598
1599 return (state_func_t) single_user;
1600 }