]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/init/init.c
MFC r306807:
[FreeBSD/FreeBSD.git] / sbin / init / init.c
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32
33 #ifndef lint
34 static const char copyright[] =
35 "@(#) Copyright (c) 1991, 1993\n\
36         The Regents of the University of California.  All rights reserved.\n";
37 #endif /* not lint */
38
39 #ifndef lint
40 #if 0
41 static char sccsid[] = "@(#)init.c      8.1 (Berkeley) 7/15/93";
42 #endif
43 static const char rcsid[] =
44   "$FreeBSD$";
45 #endif /* not lint */
46
47 #include <sys/param.h>
48 #include <sys/ioctl.h>
49 #include <sys/mman.h>
50 #include <sys/mount.h>
51 #include <sys/sysctl.h>
52 #include <sys/wait.h>
53 #include <sys/stat.h>
54 #include <sys/uio.h>
55
56 #include <db.h>
57 #include <errno.h>
58 #include <fcntl.h>
59 #include <kenv.h>
60 #include <libutil.h>
61 #include <paths.h>
62 #include <signal.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <syslog.h>
67 #include <time.h>
68 #include <ttyent.h>
69 #include <unistd.h>
70 #include <sys/reboot.h>
71 #include <err.h>
72
73 #include <stdarg.h>
74
75 #ifdef SECURE
76 #include <pwd.h>
77 #endif
78
79 #ifdef LOGIN_CAP
80 #include <login_cap.h>
81 #endif
82
83 #include "mntopts.h"
84 #include "pathnames.h"
85
86 /*
87  * Sleep times; used to prevent thrashing.
88  */
89 #define GETTY_SPACING            5      /* N secs minimum getty spacing */
90 #define GETTY_SLEEP             30      /* sleep N secs after spacing problem */
91 #define GETTY_NSPACE             3      /* max. spacing count to bring reaction */
92 #define WINDOW_WAIT              3      /* wait N secs after starting window */
93 #define STALL_TIMEOUT           30      /* wait N secs after warning */
94 #define DEATH_WATCH             10      /* wait N secs for procs to die */
95 #define DEATH_SCRIPT            120     /* wait for 2min for /etc/rc.shutdown */
96 #define RESOURCE_RC             "daemon"
97 #define RESOURCE_WINDOW         "default"
98 #define RESOURCE_GETTY          "default"
99
100 static void handle(sig_t, ...);
101 static void delset(sigset_t *, ...);
102
103 static void stall(const char *, ...) __printflike(1, 2);
104 static void warning(const char *, ...) __printflike(1, 2);
105 static void emergency(const char *, ...) __printflike(1, 2);
106 static void disaster(int);
107 static void badsys(int);
108 static void revoke_ttys(void);
109 static int  runshutdown(void);
110 static char *strk(char *);
111
112 /*
113  * We really need a recursive typedef...
114  * The following at least guarantees that the return type of (*state_t)()
115  * is sufficiently wide to hold a function pointer.
116  */
117 typedef long (*state_func_t)(void);
118 typedef state_func_t (*state_t)(void);
119
120 static state_func_t single_user(void);
121 static state_func_t runcom(void);
122 static state_func_t read_ttys(void);
123 static state_func_t multi_user(void);
124 static state_func_t clean_ttys(void);
125 static state_func_t catatonia(void);
126 static state_func_t death(void);
127 static state_func_t death_single(void);
128 static state_func_t reroot(void);
129 static state_func_t reroot_phase_two(void);
130
131 static state_func_t run_script(const char *);
132
133 static enum { AUTOBOOT, FASTBOOT } runcom_mode = AUTOBOOT;
134 #define FALSE   0
135 #define TRUE    1
136
137 static int Reboot = FALSE;
138 static int howto = RB_AUTOBOOT;
139
140 static int devfs;
141 static char *init_path_argv0;
142
143 static void transition(state_t);
144 static state_t requested_transition;
145 static state_t current_state = death_single;
146
147 static void open_console(void);
148 static const char *get_shell(void);
149 static void write_stderr(const char *message);
150
151 typedef struct init_session {
152         pid_t   se_process;             /* controlling process */
153         time_t  se_started;             /* used to avoid thrashing */
154         int     se_flags;               /* status of session */
155 #define SE_SHUTDOWN     0x1             /* session won't be restarted */
156 #define SE_PRESENT      0x2             /* session is in /etc/ttys */
157         int     se_nspace;              /* spacing count */
158         char    *se_device;             /* filename of port */
159         char    *se_getty;              /* what to run on that port */
160         char    *se_getty_argv_space;   /* pre-parsed argument array space */
161         char    **se_getty_argv;        /* pre-parsed argument array */
162         char    *se_window;             /* window system (started only once) */
163         char    *se_window_argv_space;  /* pre-parsed argument array space */
164         char    **se_window_argv;       /* pre-parsed argument array */
165         char    *se_type;               /* default terminal type */
166         struct  init_session *se_prev;
167         struct  init_session *se_next;
168 } session_t;
169
170 static void free_session(session_t *);
171 static session_t *new_session(session_t *, struct ttyent *);
172 static session_t *sessions;
173
174 static char **construct_argv(char *);
175 static void start_window_system(session_t *);
176 static void collect_child(pid_t);
177 static pid_t start_getty(session_t *);
178 static void transition_handler(int);
179 static void alrm_handler(int);
180 static void setsecuritylevel(int);
181 static int getsecuritylevel(void);
182 static int setupargv(session_t *, struct ttyent *);
183 #ifdef LOGIN_CAP
184 static void setprocresources(const char *);
185 #endif
186 static int clang;
187
188 static int start_session_db(void);
189 static void add_session(session_t *);
190 static void del_session(session_t *);
191 static session_t *find_session(pid_t);
192 static DB *session_db;
193
194 /*
195  * The mother of all processes.
196  */
197 int
198 main(int argc, char *argv[])
199 {
200         state_t initial_transition = runcom;
201         char kenv_value[PATH_MAX];
202         int c, error;
203         struct sigaction sa;
204         sigset_t mask;
205
206         /* Dispose of random users. */
207         if (getuid() != 0)
208                 errx(1, "%s", strerror(EPERM));
209
210         /* System V users like to reexec init. */
211         if (getpid() != 1) {
212 #ifdef COMPAT_SYSV_INIT
213                 /* So give them what they want */
214                 if (argc > 1) {
215                         if (strlen(argv[1]) == 1) {
216                                 char runlevel = *argv[1];
217                                 int sig;
218
219                                 switch (runlevel) {
220                                 case '0': /* halt + poweroff */
221                                         sig = SIGUSR2;
222                                         break;
223                                 case '1': /* single-user */
224                                         sig = SIGTERM;
225                                         break;
226                                 case '6': /* reboot */
227                                         sig = SIGINT;
228                                         break;
229                                 case 'c': /* block further logins */
230                                         sig = SIGTSTP;
231                                         break;
232                                 case 'q': /* rescan /etc/ttys */
233                                         sig = SIGHUP;
234                                         break;
235                                 case 'r': /* remount root */
236                                         sig = SIGEMT;
237                                         break;
238                                 default:
239                                         goto invalid;
240                                 }
241                                 kill(1, sig);
242                                 _exit(0);
243                         } else
244 invalid:
245                                 errx(1, "invalid run-level ``%s''", argv[1]);
246                 } else
247 #endif
248                         errx(1, "already running");
249         }
250
251         init_path_argv0 = strdup(argv[0]);
252         if (init_path_argv0 == NULL)
253                 err(1, "strdup");
254
255         /*
256          * Note that this does NOT open a file...
257          * Does 'init' deserve its own facility number?
258          */
259         openlog("init", LOG_CONS, LOG_AUTH);
260
261         /*
262          * Create an initial session.
263          */
264         if (setsid() < 0 && (errno != EPERM || getsid(0) != 1))
265                 warning("initial setsid() failed: %m");
266
267         /*
268          * Establish an initial user so that programs running
269          * single user do not freak out and die (like passwd).
270          */
271         if (setlogin("root") < 0)
272                 warning("setlogin() failed: %m");
273
274         /*
275          * This code assumes that we always get arguments through flags,
276          * never through bits set in some random machine register.
277          */
278         while ((c = getopt(argc, argv, "dsfr")) != -1)
279                 switch (c) {
280                 case 'd':
281                         devfs = 1;
282                         break;
283                 case 's':
284                         initial_transition = single_user;
285                         break;
286                 case 'f':
287                         runcom_mode = FASTBOOT;
288                         break;
289                 case 'r':
290                         initial_transition = reroot_phase_two;
291                         break;
292                 default:
293                         warning("unrecognized flag '-%c'", c);
294                         break;
295                 }
296
297         if (optind != argc)
298                 warning("ignoring excess arguments");
299
300         /*
301          * We catch or block signals rather than ignore them,
302          * so that they get reset on exec.
303          */
304         handle(badsys, SIGSYS, 0);
305         handle(disaster, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGXCPU,
306             SIGXFSZ, 0);
307         handle(transition_handler, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
308             SIGUSR1, SIGUSR2, 0);
309         handle(alrm_handler, SIGALRM, 0);
310         sigfillset(&mask);
311         delset(&mask, SIGABRT, SIGFPE, SIGILL, SIGSEGV, SIGBUS, SIGSYS,
312             SIGXCPU, SIGXFSZ, SIGHUP, SIGINT, SIGEMT, SIGTERM, SIGTSTP,
313             SIGALRM, SIGUSR1, SIGUSR2, 0);
314         sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
315         sigemptyset(&sa.sa_mask);
316         sa.sa_flags = 0;
317         sa.sa_handler = SIG_IGN;
318         sigaction(SIGTTIN, &sa, (struct sigaction *)0);
319         sigaction(SIGTTOU, &sa, (struct sigaction *)0);
320
321         /*
322          * Paranoia.
323          */
324         close(0);
325         close(1);
326         close(2);
327
328         if (kenv(KENV_GET, "init_script", kenv_value, sizeof(kenv_value)) > 0) {
329                 state_func_t next_transition;
330
331                 if ((next_transition = run_script(kenv_value)) != NULL)
332                         initial_transition = (state_t) next_transition;
333         }
334
335         if (kenv(KENV_GET, "init_chroot", kenv_value, sizeof(kenv_value)) > 0) {
336                 if (chdir(kenv_value) != 0 || chroot(".") != 0)
337                         warning("Can't chroot to %s: %m", kenv_value);
338         }
339
340         /*
341          * Additional check if devfs needs to be mounted:
342          * If "/" and "/dev" have the same device number,
343          * then it hasn't been mounted yet.
344          */
345         if (!devfs) {
346                 struct stat stst;
347                 dev_t root_devno;
348
349                 stat("/", &stst);
350                 root_devno = stst.st_dev;
351                 if (stat("/dev", &stst) != 0)
352                         warning("Can't stat /dev: %m");
353                 else if (stst.st_dev == root_devno)
354                         devfs++;
355         }
356
357         if (devfs) {
358                 struct iovec iov[4];
359                 char *s;
360                 int i;
361
362                 char _fstype[]  = "fstype";
363                 char _devfs[]   = "devfs";
364                 char _fspath[]  = "fspath";
365                 char _path_dev[]= _PATH_DEV;
366
367                 iov[0].iov_base = _fstype;
368                 iov[0].iov_len = sizeof(_fstype);
369                 iov[1].iov_base = _devfs;
370                 iov[1].iov_len = sizeof(_devfs);
371                 iov[2].iov_base = _fspath;
372                 iov[2].iov_len = sizeof(_fspath);
373                 /*
374                  * Try to avoid the trailing slash in _PATH_DEV.
375                  * Be *very* defensive.
376                  */
377                 s = strdup(_PATH_DEV);
378                 if (s != NULL) {
379                         i = strlen(s);
380                         if (i > 0 && s[i - 1] == '/')
381                                 s[i - 1] = '\0';
382                         iov[3].iov_base = s;
383                         iov[3].iov_len = strlen(s) + 1;
384                 } else {
385                         iov[3].iov_base = _path_dev;
386                         iov[3].iov_len = sizeof(_path_dev);
387                 }
388                 nmount(iov, 4, 0);
389                 if (s != NULL)
390                         free(s);
391         }
392
393         if (initial_transition != reroot_phase_two) {
394                 /*
395                  * Unmount reroot leftovers.  This runs after init(8)
396                  * gets reexecuted after reroot_phase_two() is done.
397                  */
398                 error = unmount(_PATH_REROOT, MNT_FORCE);
399                 if (error != 0 && errno != EINVAL)
400                         warning("Cannot unmount %s: %m", _PATH_REROOT);
401         }
402
403         /*
404          * Start the state machine.
405          */
406         transition(initial_transition);
407
408         /*
409          * Should never reach here.
410          */
411         return 1;
412 }
413
414 /*
415  * Associate a function with a signal handler.
416  */
417 static void
418 handle(sig_t handler, ...)
419 {
420         int sig;
421         struct sigaction sa;
422         sigset_t mask_everything;
423         va_list ap;
424         va_start(ap, handler);
425
426         sa.sa_handler = handler;
427         sigfillset(&mask_everything);
428
429         while ((sig = va_arg(ap, int)) != 0) {
430                 sa.sa_mask = mask_everything;
431                 /* XXX SA_RESTART? */
432                 sa.sa_flags = sig == SIGCHLD ? SA_NOCLDSTOP : 0;
433                 sigaction(sig, &sa, (struct sigaction *) 0);
434         }
435         va_end(ap);
436 }
437
438 /*
439  * Delete a set of signals from a mask.
440  */
441 static void
442 delset(sigset_t *maskp, ...)
443 {
444         int sig;
445         va_list ap;
446         va_start(ap, maskp);
447
448         while ((sig = va_arg(ap, int)) != 0)
449                 sigdelset(maskp, sig);
450         va_end(ap);
451 }
452
453 /*
454  * Log a message and sleep for a while (to give someone an opportunity
455  * to read it and to save log or hardcopy output if the problem is chronic).
456  * NB: should send a message to the session logger to avoid blocking.
457  */
458 static void
459 stall(const char *message, ...)
460 {
461         va_list ap;
462         va_start(ap, message);
463
464         vsyslog(LOG_ALERT, message, ap);
465         va_end(ap);
466         sleep(STALL_TIMEOUT);
467 }
468
469 /*
470  * Like stall(), but doesn't sleep.
471  * If cpp had variadic macros, the two functions could be #defines for another.
472  * NB: should send a message to the session logger to avoid blocking.
473  */
474 static void
475 warning(const char *message, ...)
476 {
477         va_list ap;
478         va_start(ap, message);
479
480         vsyslog(LOG_ALERT, message, ap);
481         va_end(ap);
482 }
483
484 /*
485  * Log an emergency message.
486  * NB: should send a message to the session logger to avoid blocking.
487  */
488 static void
489 emergency(const char *message, ...)
490 {
491         va_list ap;
492         va_start(ap, message);
493
494         vsyslog(LOG_EMERG, message, ap);
495         va_end(ap);
496 }
497
498 /*
499  * Catch a SIGSYS signal.
500  *
501  * These may arise if a system does not support sysctl.
502  * We tolerate up to 25 of these, then throw in the towel.
503  */
504 static void
505 badsys(int sig)
506 {
507         static int badcount = 0;
508
509         if (badcount++ < 25)
510                 return;
511         disaster(sig);
512 }
513
514 /*
515  * Catch an unexpected signal.
516  */
517 static void
518 disaster(int sig)
519 {
520
521         emergency("fatal signal: %s",
522             (unsigned)sig < NSIG ? sys_siglist[sig] : "unknown signal");
523
524         sleep(STALL_TIMEOUT);
525         _exit(sig);             /* reboot */
526 }
527
528 /*
529  * Get the security level of the kernel.
530  */
531 static int
532 getsecuritylevel(void)
533 {
534 #ifdef KERN_SECURELVL
535         int name[2], curlevel;
536         size_t len;
537
538         name[0] = CTL_KERN;
539         name[1] = KERN_SECURELVL;
540         len = sizeof curlevel;
541         if (sysctl(name, 2, &curlevel, &len, NULL, 0) == -1) {
542                 emergency("cannot get kernel security level: %s",
543                     strerror(errno));
544                 return (-1);
545         }
546         return (curlevel);
547 #else
548         return (-1);
549 #endif
550 }
551
552 /*
553  * Set the security level of the kernel.
554  */
555 static void
556 setsecuritylevel(int newlevel)
557 {
558 #ifdef KERN_SECURELVL
559         int name[2], curlevel;
560
561         curlevel = getsecuritylevel();
562         if (newlevel == curlevel)
563                 return;
564         name[0] = CTL_KERN;
565         name[1] = KERN_SECURELVL;
566         if (sysctl(name, 2, NULL, NULL, &newlevel, sizeof newlevel) == -1) {
567                 emergency(
568                     "cannot change kernel security level from %d to %d: %s",
569                     curlevel, newlevel, strerror(errno));
570                 return;
571         }
572 #ifdef SECURE
573         warning("kernel security level changed from %d to %d",
574             curlevel, newlevel);
575 #endif
576 #endif
577 }
578
579 /*
580  * Change states in the finite state machine.
581  * The initial state is passed as an argument.
582  */
583 static void
584 transition(state_t s)
585 {
586
587         current_state = s;
588         for (;;)
589                 current_state = (state_t) (*current_state)();
590 }
591
592 /*
593  * Start a session and allocate a controlling terminal.
594  * Only called by children of init after forking.
595  */
596 static void
597 open_console(void)
598 {
599         int fd;
600
601         /*
602          * Try to open /dev/console.  Open the device with O_NONBLOCK to
603          * prevent potential blocking on a carrier.
604          */
605         revoke(_PATH_CONSOLE);
606         if ((fd = open(_PATH_CONSOLE, O_RDWR | O_NONBLOCK)) != -1) {
607                 (void)fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
608                 if (login_tty(fd) == 0)
609                         return;
610                 close(fd);
611         }
612
613         /* No luck.  Log output to file if possible. */
614         if ((fd = open(_PATH_DEVNULL, O_RDWR)) == -1) {
615                 stall("cannot open null device.");
616                 _exit(1);
617         }
618         if (fd != STDIN_FILENO) {
619                 dup2(fd, STDIN_FILENO);
620                 close(fd);
621         }
622         fd = open(_PATH_INITLOG, O_WRONLY | O_APPEND | O_CREAT, 0644);
623         if (fd == -1)
624                 dup2(STDIN_FILENO, STDOUT_FILENO);
625         else if (fd != STDOUT_FILENO) {
626                 dup2(fd, STDOUT_FILENO);
627                 close(fd);
628         }
629         dup2(STDOUT_FILENO, STDERR_FILENO);
630 }
631
632 static const char *
633 get_shell(void)
634 {
635         static char kenv_value[PATH_MAX];
636
637         if (kenv(KENV_GET, "init_shell", kenv_value, sizeof(kenv_value)) > 0)
638                 return kenv_value;
639         else
640                 return _PATH_BSHELL;
641 }
642
643 static void
644 write_stderr(const char *message)
645 {
646
647         write(STDERR_FILENO, message, strlen(message));
648 }
649
650 static int
651 read_file(const char *path, void **bufp, size_t *bufsizep)
652 {
653         struct stat sb;
654         size_t bufsize;
655         void *buf;
656         ssize_t nbytes;
657         int error, fd;
658
659         fd = open(path, O_RDONLY);
660         if (fd < 0) {
661                 emergency("%s: %s", path, strerror(errno));
662                 return (-1);
663         }
664
665         error = fstat(fd, &sb);
666         if (error != 0) {
667                 emergency("fstat: %s", strerror(errno));
668                 close(fd);
669                 return (error);
670         }
671
672         bufsize = sb.st_size;
673         buf = malloc(bufsize);
674         if (buf == NULL) {
675                 emergency("malloc: %s", strerror(errno));
676                 close(fd);
677                 return (error);
678         }
679
680         nbytes = read(fd, buf, bufsize);
681         if (nbytes != (ssize_t)bufsize) {
682                 emergency("read: %s", strerror(errno));
683                 close(fd);
684                 free(buf);
685                 return (error);
686         }
687
688         error = close(fd);
689         if (error != 0) {
690                 emergency("close: %s", strerror(errno));
691                 free(buf);
692                 return (error);
693         }
694
695         *bufp = buf;
696         *bufsizep = bufsize;
697
698         return (0);
699 }
700
701 static int
702 create_file(const char *path, const void *buf, size_t bufsize)
703 {
704         ssize_t nbytes;
705         int error, fd;
706
707         fd = open(path, O_WRONLY | O_CREAT | O_EXCL, 0700);
708         if (fd < 0) {
709                 emergency("%s: %s", path, strerror(errno));
710                 return (-1);
711         }
712
713         nbytes = write(fd, buf, bufsize);
714         if (nbytes != (ssize_t)bufsize) {
715                 emergency("write: %s", strerror(errno));
716                 close(fd);
717                 return (-1);
718         }
719
720         error = close(fd);
721         if (error != 0) {
722                 emergency("close: %s", strerror(errno));
723                 return (-1);
724         }
725
726         return (0);
727 }
728
729 static int
730 mount_tmpfs(const char *fspath)
731 {
732         struct iovec *iov;
733         char errmsg[255];
734         int error, iovlen;
735
736         iov = NULL;
737         iovlen = 0;
738         memset(errmsg, 0, sizeof(errmsg));
739         build_iovec(&iov, &iovlen, "fstype",
740             __DECONST(void *, "tmpfs"), (size_t)-1);
741         build_iovec(&iov, &iovlen, "fspath",
742             __DECONST(void *, fspath), (size_t)-1);
743         build_iovec(&iov, &iovlen, "errmsg",
744             errmsg, sizeof(errmsg));
745
746         error = nmount(iov, iovlen, 0);
747         if (error != 0) {
748                 if (*errmsg != '\0') {
749                         emergency("cannot mount tmpfs on %s: %s: %s",
750                             fspath, errmsg, strerror(errno));
751                 } else {
752                         emergency("cannot mount tmpfs on %s: %s",
753                             fspath, strerror(errno));
754                 }
755                 return (error);
756         }
757         return (0);
758 }
759
760 static state_func_t
761 reroot(void)
762 {
763         void *buf;
764         size_t bufsize;
765         int error;
766
767         buf = NULL;
768         bufsize = 0;
769
770         revoke_ttys();
771         runshutdown();
772
773         /*
774          * Make sure nobody can interfere with our scheme.
775          * Ignore ESRCH, which can apparently happen when
776          * there are no processes to kill.
777          */
778         error = kill(-1, SIGKILL);
779         if (error != 0 && errno != ESRCH) {
780                 emergency("kill(2) failed: %s", strerror(errno));
781                 goto out;
782         }
783
784         /*
785          * Copy the init binary into tmpfs, so that we can unmount
786          * the old rootfs without committing suicide.
787          */
788         error = read_file(init_path_argv0, &buf, &bufsize);
789         if (error != 0)
790                 goto out;
791         error = mount_tmpfs(_PATH_REROOT);
792         if (error != 0)
793                 goto out;
794         error = create_file(_PATH_REROOT_INIT, buf, bufsize);
795         if (error != 0)
796                 goto out;
797
798         /*
799          * Execute the temporary init.
800          */
801         execl(_PATH_REROOT_INIT, _PATH_REROOT_INIT, "-r", NULL);
802         emergency("cannot exec %s: %s", _PATH_REROOT_INIT, strerror(errno));
803
804 out:
805         emergency("reroot failed; going to single user mode");
806         free(buf);
807         return (state_func_t) single_user;
808 }
809
810 static state_func_t
811 reroot_phase_two(void)
812 {
813         char init_path[PATH_MAX], *path, *path_component;
814         size_t init_path_len;
815         int nbytes, error;
816
817         /*
818          * Ask the kernel to mount the new rootfs.
819          */
820         error = reboot(RB_REROOT);
821         if (error != 0) {
822                 emergency("RB_REBOOT failed: %s", strerror(errno));
823                 goto out;
824         }
825
826         /*
827          * Figure out where the destination init(8) binary is.  Note that
828          * the path could be different than what we've started with.  Use
829          * the value from kenv, if set, or the one from sysctl otherwise.
830          * The latter defaults to a hardcoded value, but can be overridden
831          * by a build time option.
832          */
833         nbytes = kenv(KENV_GET, "init_path", init_path, sizeof(init_path));
834         if (nbytes <= 0) {
835                 init_path_len = sizeof(init_path);
836                 error = sysctlbyname("kern.init_path",
837                     init_path, &init_path_len, NULL, 0);
838                 if (error != 0) {
839                         emergency("failed to retrieve kern.init_path: %s",
840                             strerror(errno));
841                         goto out;
842                 }
843         }
844
845         /*
846          * Repeat the init search logic from sys/kern/init_path.c
847          */
848         path_component = init_path;
849         while ((path = strsep(&path_component, ":")) != NULL) {
850                 /*
851                  * Execute init(8) from the new rootfs.
852                  */
853                 execl(path, path, NULL);
854         }
855         emergency("cannot exec init from %s: %s", init_path, strerror(errno));
856
857 out:
858         emergency("reroot failed; going to single user mode");
859         return (state_func_t) single_user;
860 }
861
862 /*
863  * Bring the system up single user.
864  */
865 static state_func_t
866 single_user(void)
867 {
868         pid_t pid, wpid;
869         int status;
870         sigset_t mask;
871         const char *shell;
872         char *argv[2];
873         struct timeval tv, tn;
874 #ifdef SECURE
875         struct ttyent *typ;
876         struct passwd *pp;
877         static const char banner[] =
878                 "Enter root password, or ^D to go multi-user\n";
879         char *clear, *password;
880 #endif
881 #ifdef DEBUGSHELL
882         char altshell[128];
883 #endif
884
885         if (Reboot) {
886                 /* Instead of going single user, let's reboot the machine */
887                 sync();
888                 reboot(howto);
889                 _exit(0);
890         }
891
892         shell = get_shell();
893
894         if ((pid = fork()) == 0) {
895                 /*
896                  * Start the single user session.
897                  */
898                 open_console();
899
900 #ifdef SECURE
901                 /*
902                  * Check the root password.
903                  * We don't care if the console is 'on' by default;
904                  * it's the only tty that can be 'off' and 'secure'.
905                  */
906                 typ = getttynam("console");
907                 pp = getpwnam("root");
908                 if (typ && (typ->ty_status & TTY_SECURE) == 0 &&
909                     pp && *pp->pw_passwd) {
910                         write_stderr(banner);
911                         for (;;) {
912                                 clear = getpass("Password:");
913                                 if (clear == NULL || *clear == '\0')
914                                         _exit(0);
915                                 password = crypt(clear, pp->pw_passwd);
916                                 bzero(clear, _PASSWORD_LEN);
917                                 if (password == NULL ||
918                                     strcmp(password, pp->pw_passwd) == 0)
919                                         break;
920                                 warning("single-user login failed\n");
921                         }
922                 }
923                 endttyent();
924                 endpwent();
925 #endif /* SECURE */
926
927 #ifdef DEBUGSHELL
928                 {
929                         char *cp = altshell;
930                         int num;
931
932 #define SHREQUEST "Enter full pathname of shell or RETURN for "
933                         write_stderr(SHREQUEST);
934                         write_stderr(shell);
935                         write_stderr(": ");
936                         while ((num = read(STDIN_FILENO, cp, 1)) != -1 &&
937                             num != 0 && *cp != '\n' && cp < &altshell[127])
938                                 cp++;
939                         *cp = '\0';
940                         if (altshell[0] != '\0')
941                                 shell = altshell;
942                 }
943 #endif /* DEBUGSHELL */
944
945                 /*
946                  * Unblock signals.
947                  * We catch all the interesting ones,
948                  * and those are reset to SIG_DFL on exec.
949                  */
950                 sigemptyset(&mask);
951                 sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
952
953                 /*
954                  * Fire off a shell.
955                  * If the default one doesn't work, try the Bourne shell.
956                  */
957
958                 char name[] = "-sh";
959
960                 argv[0] = name;
961                 argv[1] = 0;
962                 execv(shell, argv);
963                 emergency("can't exec %s for single user: %m", shell);
964                 execv(_PATH_BSHELL, argv);
965                 emergency("can't exec %s for single user: %m", _PATH_BSHELL);
966                 sleep(STALL_TIMEOUT);
967                 _exit(1);
968         }
969
970         if (pid == -1) {
971                 /*
972                  * We are seriously hosed.  Do our best.
973                  */
974                 emergency("can't fork single-user shell, trying again");
975                 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
976                         continue;
977                 return (state_func_t) single_user;
978         }
979
980         requested_transition = 0;
981         do {
982                 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
983                         collect_child(wpid);
984                 if (wpid == -1) {
985                         if (errno == EINTR)
986                                 continue;
987                         warning("wait for single-user shell failed: %m; restarting");
988                         return (state_func_t) single_user;
989                 }
990                 if (wpid == pid && WIFSTOPPED(status)) {
991                         warning("init: shell stopped, restarting\n");
992                         kill(pid, SIGCONT);
993                         wpid = -1;
994                 }
995         } while (wpid != pid && !requested_transition);
996
997         if (requested_transition)
998                 return (state_func_t) requested_transition;
999
1000         if (!WIFEXITED(status)) {
1001                 if (WTERMSIG(status) == SIGKILL) {
1002                         /*
1003                          *  reboot(8) killed shell?
1004                          */
1005                         warning("single user shell terminated.");
1006                         gettimeofday(&tv, NULL);
1007                         tn = tv;
1008                         tv.tv_sec += STALL_TIMEOUT;
1009                         while (tv.tv_sec > tn.tv_sec || (tv.tv_sec ==
1010                             tn.tv_sec && tv.tv_usec > tn.tv_usec)) {
1011                                 sleep(1);
1012                                 gettimeofday(&tn, NULL);
1013                         }
1014                         _exit(0);
1015                 } else {
1016                         warning("single user shell terminated, restarting");
1017                         return (state_func_t) single_user;
1018                 }
1019         }
1020
1021         runcom_mode = FASTBOOT;
1022         return (state_func_t) runcom;
1023 }
1024
1025 /*
1026  * Run the system startup script.
1027  */
1028 static state_func_t
1029 runcom(void)
1030 {
1031         state_func_t next_transition;
1032
1033         if ((next_transition = run_script(_PATH_RUNCOM)) != NULL)
1034                 return next_transition;
1035
1036         runcom_mode = AUTOBOOT;         /* the default */
1037         return (state_func_t) read_ttys;
1038 }
1039
1040 /*
1041  * Run a shell script.
1042  * Returns 0 on success, otherwise the next transition to enter:
1043  *  - single_user if fork/execv/waitpid failed, or if the script
1044  *    terminated with a signal or exit code != 0.
1045  *  - death_single if a SIGTERM was delivered to init(8).
1046  */
1047 static state_func_t
1048 run_script(const char *script)
1049 {
1050         pid_t pid, wpid;
1051         int status;
1052         char *argv[4];
1053         const char *shell;
1054         struct sigaction sa;
1055
1056         shell = get_shell();
1057
1058         if ((pid = fork()) == 0) {
1059                 sigemptyset(&sa.sa_mask);
1060                 sa.sa_flags = 0;
1061                 sa.sa_handler = SIG_IGN;
1062                 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1063                 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1064
1065                 open_console();
1066
1067                 char _sh[]              = "sh";
1068                 char _autoboot[]        = "autoboot";
1069
1070                 argv[0] = _sh;
1071                 argv[1] = __DECONST(char *, script);
1072                 argv[2] = runcom_mode == AUTOBOOT ? _autoboot : 0;
1073                 argv[3] = 0;
1074
1075                 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1076
1077 #ifdef LOGIN_CAP
1078                 setprocresources(RESOURCE_RC);
1079 #endif
1080                 execv(shell, argv);
1081                 stall("can't exec %s for %s: %m", shell, script);
1082                 _exit(1);       /* force single user mode */
1083         }
1084
1085         if (pid == -1) {
1086                 emergency("can't fork for %s on %s: %m", shell, script);
1087                 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1088                         continue;
1089                 sleep(STALL_TIMEOUT);
1090                 return (state_func_t) single_user;
1091         }
1092
1093         /*
1094          * Copied from single_user().  This is a bit paranoid.
1095          */
1096         requested_transition = 0;
1097         do {
1098                 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1099                         collect_child(wpid);
1100                 if (wpid == -1) {
1101                         if (requested_transition == death_single ||
1102                             requested_transition == reroot)
1103                                 return (state_func_t) requested_transition;
1104                         if (errno == EINTR)
1105                                 continue;
1106                         warning("wait for %s on %s failed: %m; going to "
1107                             "single user mode", shell, script);
1108                         return (state_func_t) single_user;
1109                 }
1110                 if (wpid == pid && WIFSTOPPED(status)) {
1111                         warning("init: %s on %s stopped, restarting\n",
1112                             shell, script);
1113                         kill(pid, SIGCONT);
1114                         wpid = -1;
1115                 }
1116         } while (wpid != pid);
1117
1118         if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1119             requested_transition == catatonia) {
1120                 /* /etc/rc executed /sbin/reboot; wait for the end quietly */
1121                 sigset_t s;
1122
1123                 sigfillset(&s);
1124                 for (;;)
1125                         sigsuspend(&s);
1126         }
1127
1128         if (!WIFEXITED(status)) {
1129                 warning("%s on %s terminated abnormally, going to single "
1130                     "user mode", shell, script);
1131                 return (state_func_t) single_user;
1132         }
1133
1134         if (WEXITSTATUS(status))
1135                 return (state_func_t) single_user;
1136
1137         return (state_func_t) 0;
1138 }
1139
1140 /*
1141  * Open the session database.
1142  *
1143  * NB: We could pass in the size here; is it necessary?
1144  */
1145 static int
1146 start_session_db(void)
1147 {
1148         if (session_db && (*session_db->close)(session_db))
1149                 emergency("session database close: %s", strerror(errno));
1150         if ((session_db = dbopen(NULL, O_RDWR, 0, DB_HASH, NULL)) == NULL) {
1151                 emergency("session database open: %s", strerror(errno));
1152                 return (1);
1153         }
1154         return (0);
1155
1156 }
1157
1158 /*
1159  * Add a new login session.
1160  */
1161 static void
1162 add_session(session_t *sp)
1163 {
1164         DBT key;
1165         DBT data;
1166
1167         key.data = &sp->se_process;
1168         key.size = sizeof sp->se_process;
1169         data.data = &sp;
1170         data.size = sizeof sp;
1171
1172         if ((*session_db->put)(session_db, &key, &data, 0))
1173                 emergency("insert %d: %s", sp->se_process, strerror(errno));
1174 }
1175
1176 /*
1177  * Delete an old login session.
1178  */
1179 static void
1180 del_session(session_t *sp)
1181 {
1182         DBT key;
1183
1184         key.data = &sp->se_process;
1185         key.size = sizeof sp->se_process;
1186
1187         if ((*session_db->del)(session_db, &key, 0))
1188                 emergency("delete %d: %s", sp->se_process, strerror(errno));
1189 }
1190
1191 /*
1192  * Look up a login session by pid.
1193  */
1194 static session_t *
1195 find_session(pid_t pid)
1196 {
1197         DBT key;
1198         DBT data;
1199         session_t *ret;
1200
1201         key.data = &pid;
1202         key.size = sizeof pid;
1203         if ((*session_db->get)(session_db, &key, &data, 0) != 0)
1204                 return 0;
1205         bcopy(data.data, (char *)&ret, sizeof(ret));
1206         return ret;
1207 }
1208
1209 /*
1210  * Construct an argument vector from a command line.
1211  */
1212 static char **
1213 construct_argv(char *command)
1214 {
1215         int argc = 0;
1216         char **argv = (char **) malloc(((strlen(command) + 1) / 2 + 1)
1217                                                 * sizeof (char *));
1218
1219         if ((argv[argc++] = strk(command)) == NULL) {
1220                 free(argv);
1221                 return (NULL);
1222         }
1223         while ((argv[argc++] = strk((char *) 0)) != NULL)
1224                 continue;
1225         return argv;
1226 }
1227
1228 /*
1229  * Deallocate a session descriptor.
1230  */
1231 static void
1232 free_session(session_t *sp)
1233 {
1234         free(sp->se_device);
1235         if (sp->se_getty) {
1236                 free(sp->se_getty);
1237                 free(sp->se_getty_argv_space);
1238                 free(sp->se_getty_argv);
1239         }
1240         if (sp->se_window) {
1241                 free(sp->se_window);
1242                 free(sp->se_window_argv_space);
1243                 free(sp->se_window_argv);
1244         }
1245         if (sp->se_type)
1246                 free(sp->se_type);
1247         free(sp);
1248 }
1249
1250 /*
1251  * Allocate a new session descriptor.
1252  * Mark it SE_PRESENT.
1253  */
1254 static session_t *
1255 new_session(session_t *sprev, struct ttyent *typ)
1256 {
1257         session_t *sp;
1258         int fd;
1259
1260         if ((typ->ty_status & TTY_ON) == 0 ||
1261             typ->ty_name == 0 ||
1262             typ->ty_getty == 0)
1263                 return 0;
1264
1265         sp = (session_t *) calloc(1, sizeof (session_t));
1266
1267         sp->se_flags |= SE_PRESENT;
1268
1269         sp->se_device = malloc(sizeof(_PATH_DEV) + strlen(typ->ty_name));
1270         sprintf(sp->se_device, "%s%s", _PATH_DEV, typ->ty_name);
1271
1272         /*
1273          * Attempt to open the device, if we get "device not configured"
1274          * then don't add the device to the session list.
1275          */
1276         if ((fd = open(sp->se_device, O_RDONLY | O_NONBLOCK, 0)) < 0) {
1277                 if (errno == ENXIO) {
1278                         free_session(sp);
1279                         return (0);
1280                 }
1281         } else
1282                 close(fd);
1283
1284         if (setupargv(sp, typ) == 0) {
1285                 free_session(sp);
1286                 return (0);
1287         }
1288
1289         sp->se_next = 0;
1290         if (sprev == NULL) {
1291                 sessions = sp;
1292                 sp->se_prev = 0;
1293         } else {
1294                 sprev->se_next = sp;
1295                 sp->se_prev = sprev;
1296         }
1297
1298         return sp;
1299 }
1300
1301 /*
1302  * Calculate getty and if useful window argv vectors.
1303  */
1304 static int
1305 setupargv(session_t *sp, struct ttyent *typ)
1306 {
1307
1308         if (sp->se_getty) {
1309                 free(sp->se_getty);
1310                 free(sp->se_getty_argv_space);
1311                 free(sp->se_getty_argv);
1312         }
1313         sp->se_getty = malloc(strlen(typ->ty_getty) + strlen(typ->ty_name) + 2);
1314         sprintf(sp->se_getty, "%s %s", typ->ty_getty, typ->ty_name);
1315         sp->se_getty_argv_space = strdup(sp->se_getty);
1316         sp->se_getty_argv = construct_argv(sp->se_getty_argv_space);
1317         if (sp->se_getty_argv == NULL) {
1318                 warning("can't parse getty for port %s", sp->se_device);
1319                 free(sp->se_getty);
1320                 free(sp->se_getty_argv_space);
1321                 sp->se_getty = sp->se_getty_argv_space = 0;
1322                 return (0);
1323         }
1324         if (sp->se_window) {
1325                 free(sp->se_window);
1326                 free(sp->se_window_argv_space);
1327                 free(sp->se_window_argv);
1328         }
1329         sp->se_window = sp->se_window_argv_space = 0;
1330         sp->se_window_argv = 0;
1331         if (typ->ty_window) {
1332                 sp->se_window = strdup(typ->ty_window);
1333                 sp->se_window_argv_space = strdup(sp->se_window);
1334                 sp->se_window_argv = construct_argv(sp->se_window_argv_space);
1335                 if (sp->se_window_argv == NULL) {
1336                         warning("can't parse window for port %s",
1337                             sp->se_device);
1338                         free(sp->se_window_argv_space);
1339                         free(sp->se_window);
1340                         sp->se_window = sp->se_window_argv_space = 0;
1341                         return (0);
1342                 }
1343         }
1344         if (sp->se_type)
1345                 free(sp->se_type);
1346         sp->se_type = typ->ty_type ? strdup(typ->ty_type) : 0;
1347         return (1);
1348 }
1349
1350 /*
1351  * Walk the list of ttys and create sessions for each active line.
1352  */
1353 static state_func_t
1354 read_ttys(void)
1355 {
1356         session_t *sp, *snext;
1357         struct ttyent *typ;
1358
1359         /*
1360          * Destroy any previous session state.
1361          * There shouldn't be any, but just in case...
1362          */
1363         for (sp = sessions; sp; sp = snext) {
1364                 snext = sp->se_next;
1365                 free_session(sp);
1366         }
1367         sessions = 0;
1368         if (start_session_db())
1369                 return (state_func_t) single_user;
1370
1371         /*
1372          * Allocate a session entry for each active port.
1373          * Note that sp starts at 0.
1374          */
1375         while ((typ = getttyent()) != NULL)
1376                 if ((snext = new_session(sp, typ)) != NULL)
1377                         sp = snext;
1378
1379         endttyent();
1380
1381         return (state_func_t) multi_user;
1382 }
1383
1384 /*
1385  * Start a window system running.
1386  */
1387 static void
1388 start_window_system(session_t *sp)
1389 {
1390         pid_t pid;
1391         sigset_t mask;
1392         char term[64], *env[2];
1393         int status;
1394
1395         if ((pid = fork()) == -1) {
1396                 emergency("can't fork for window system on port %s: %m",
1397                     sp->se_device);
1398                 /* hope that getty fails and we can try again */
1399                 return;
1400         }
1401         if (pid) {
1402                 waitpid(-1, &status, 0);
1403                 return;
1404         }
1405
1406         /* reparent window process to the init to not make a zombie on exit */
1407         if ((pid = fork()) == -1) {
1408                 emergency("can't fork for window system on port %s: %m",
1409                     sp->se_device);
1410                 _exit(1);
1411         }
1412         if (pid)
1413                 _exit(0);
1414
1415         sigemptyset(&mask);
1416         sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1417
1418         if (setsid() < 0)
1419                 emergency("setsid failed (window) %m");
1420
1421 #ifdef LOGIN_CAP
1422         setprocresources(RESOURCE_WINDOW);
1423 #endif
1424         if (sp->se_type) {
1425                 /* Don't use malloc after fork */
1426                 strcpy(term, "TERM=");
1427                 strncat(term, sp->se_type, sizeof(term) - 6);
1428                 env[0] = term;
1429                 env[1] = 0;
1430         }
1431         else
1432                 env[0] = 0;
1433         execve(sp->se_window_argv[0], sp->se_window_argv, env);
1434         stall("can't exec window system '%s' for port %s: %m",
1435                 sp->se_window_argv[0], sp->se_device);
1436         _exit(1);
1437 }
1438
1439 /*
1440  * Start a login session running.
1441  */
1442 static pid_t
1443 start_getty(session_t *sp)
1444 {
1445         pid_t pid;
1446         sigset_t mask;
1447         time_t current_time = time((time_t *) 0);
1448         int too_quick = 0;
1449         char term[64], *env[2];
1450
1451         if (current_time >= sp->se_started &&
1452             current_time - sp->se_started < GETTY_SPACING) {
1453                 if (++sp->se_nspace > GETTY_NSPACE) {
1454                         sp->se_nspace = 0;
1455                         too_quick = 1;
1456                 }
1457         } else
1458                 sp->se_nspace = 0;
1459
1460         /*
1461          * fork(), not vfork() -- we can't afford to block.
1462          */
1463         if ((pid = fork()) == -1) {
1464                 emergency("can't fork for getty on port %s: %m", sp->se_device);
1465                 return -1;
1466         }
1467
1468         if (pid)
1469                 return pid;
1470
1471         if (too_quick) {
1472                 warning("getty repeating too quickly on port %s, sleeping %d secs",
1473                     sp->se_device, GETTY_SLEEP);
1474                 sleep((unsigned) GETTY_SLEEP);
1475         }
1476
1477         if (sp->se_window) {
1478                 start_window_system(sp);
1479                 sleep(WINDOW_WAIT);
1480         }
1481
1482         sigemptyset(&mask);
1483         sigprocmask(SIG_SETMASK, &mask, (sigset_t *) 0);
1484
1485 #ifdef LOGIN_CAP
1486         setprocresources(RESOURCE_GETTY);
1487 #endif
1488         if (sp->se_type) {
1489                 /* Don't use malloc after fork */
1490                 strcpy(term, "TERM=");
1491                 strncat(term, sp->se_type, sizeof(term) - 6);
1492                 env[0] = term;
1493                 env[1] = 0;
1494         } else
1495                 env[0] = 0;
1496         execve(sp->se_getty_argv[0], sp->se_getty_argv, env);
1497         stall("can't exec getty '%s' for port %s: %m",
1498                 sp->se_getty_argv[0], sp->se_device);
1499         _exit(1);
1500 }
1501
1502 /*
1503  * Collect exit status for a child.
1504  * If an exiting login, start a new login running.
1505  */
1506 static void
1507 collect_child(pid_t pid)
1508 {
1509         session_t *sp, *sprev, *snext;
1510
1511         if (! sessions)
1512                 return;
1513
1514         if (! (sp = find_session(pid)))
1515                 return;
1516
1517         del_session(sp);
1518         sp->se_process = 0;
1519
1520         if (sp->se_flags & SE_SHUTDOWN) {
1521                 if ((sprev = sp->se_prev) != NULL)
1522                         sprev->se_next = sp->se_next;
1523                 else
1524                         sessions = sp->se_next;
1525                 if ((snext = sp->se_next) != NULL)
1526                         snext->se_prev = sp->se_prev;
1527                 free_session(sp);
1528                 return;
1529         }
1530
1531         if ((pid = start_getty(sp)) == -1) {
1532                 /* serious trouble */
1533                 requested_transition = clean_ttys;
1534                 return;
1535         }
1536
1537         sp->se_process = pid;
1538         sp->se_started = time((time_t *) 0);
1539         add_session(sp);
1540 }
1541
1542 /*
1543  * Catch a signal and request a state transition.
1544  */
1545 static void
1546 transition_handler(int sig)
1547 {
1548
1549         switch (sig) {
1550         case SIGHUP:
1551                 if (current_state == read_ttys || current_state == multi_user ||
1552                     current_state == clean_ttys || current_state == catatonia)
1553                         requested_transition = clean_ttys;
1554                 break;
1555         case SIGUSR2:
1556                 howto = RB_POWEROFF;
1557         case SIGUSR1:
1558                 howto |= RB_HALT;
1559         case SIGINT:
1560                 Reboot = TRUE;
1561         case SIGTERM:
1562                 if (current_state == read_ttys || current_state == multi_user ||
1563                     current_state == clean_ttys || current_state == catatonia)
1564                         requested_transition = death;
1565                 else
1566                         requested_transition = death_single;
1567                 break;
1568         case SIGTSTP:
1569                 if (current_state == runcom || current_state == read_ttys ||
1570                     current_state == clean_ttys ||
1571                     current_state == multi_user || current_state == catatonia)
1572                         requested_transition = catatonia;
1573                 break;
1574         case SIGEMT:
1575                 requested_transition = reroot;
1576                 break;
1577         default:
1578                 requested_transition = 0;
1579                 break;
1580         }
1581 }
1582
1583 /*
1584  * Take the system multiuser.
1585  */
1586 static state_func_t
1587 multi_user(void)
1588 {
1589         pid_t pid;
1590         session_t *sp;
1591
1592         requested_transition = 0;
1593
1594         /*
1595          * If the administrator has not set the security level to -1
1596          * to indicate that the kernel should not run multiuser in secure
1597          * mode, and the run script has not set a higher level of security
1598          * than level 1, then put the kernel into secure mode.
1599          */
1600         if (getsecuritylevel() == 0)
1601                 setsecuritylevel(1);
1602
1603         for (sp = sessions; sp; sp = sp->se_next) {
1604                 if (sp->se_process)
1605                         continue;
1606                 if ((pid = start_getty(sp)) == -1) {
1607                         /* serious trouble */
1608                         requested_transition = clean_ttys;
1609                         break;
1610                 }
1611                 sp->se_process = pid;
1612                 sp->se_started = time((time_t *) 0);
1613                 add_session(sp);
1614         }
1615
1616         while (!requested_transition)
1617                 if ((pid = waitpid(-1, (int *) 0, 0)) != -1)
1618                         collect_child(pid);
1619
1620         return (state_func_t) requested_transition;
1621 }
1622
1623 /*
1624  * This is an (n*2)+(n^2) algorithm.  We hope it isn't run often...
1625  */
1626 static state_func_t
1627 clean_ttys(void)
1628 {
1629         session_t *sp, *sprev;
1630         struct ttyent *typ;
1631         int devlen;
1632         char *old_getty, *old_window, *old_type;
1633
1634         /*
1635          * mark all sessions for death, (!SE_PRESENT)
1636          * as we find or create new ones they'll be marked as keepers,
1637          * we'll later nuke all the ones not found in /etc/ttys
1638          */
1639         for (sp = sessions; sp != NULL; sp = sp->se_next)
1640                 sp->se_flags &= ~SE_PRESENT;
1641
1642         devlen = sizeof(_PATH_DEV) - 1;
1643         while ((typ = getttyent()) != NULL) {
1644                 for (sprev = 0, sp = sessions; sp; sprev = sp, sp = sp->se_next)
1645                         if (strcmp(typ->ty_name, sp->se_device + devlen) == 0)
1646                                 break;
1647
1648                 if (sp) {
1649                         /* we want this one to live */
1650                         sp->se_flags |= SE_PRESENT;
1651                         if ((typ->ty_status & TTY_ON) == 0 ||
1652                             typ->ty_getty == 0) {
1653                                 sp->se_flags |= SE_SHUTDOWN;
1654                                 kill(sp->se_process, SIGHUP);
1655                                 continue;
1656                         }
1657                         sp->se_flags &= ~SE_SHUTDOWN;
1658                         old_getty = sp->se_getty ? strdup(sp->se_getty) : 0;
1659                         old_window = sp->se_window ? strdup(sp->se_window) : 0;
1660                         old_type = sp->se_type ? strdup(sp->se_type) : 0;
1661                         if (setupargv(sp, typ) == 0) {
1662                                 warning("can't parse getty for port %s",
1663                                         sp->se_device);
1664                                 sp->se_flags |= SE_SHUTDOWN;
1665                                 kill(sp->se_process, SIGHUP);
1666                         }
1667                         else if (   !old_getty
1668                                  || (!old_type && sp->se_type)
1669                                  || (old_type && !sp->se_type)
1670                                  || (!old_window && sp->se_window)
1671                                  || (old_window && !sp->se_window)
1672                                  || (strcmp(old_getty, sp->se_getty) != 0)
1673                                  || (old_window && strcmp(old_window, sp->se_window) != 0)
1674                                  || (old_type && strcmp(old_type, sp->se_type) != 0)
1675                                 ) {
1676                                 /* Don't set SE_SHUTDOWN here */
1677                                 sp->se_nspace = 0;
1678                                 sp->se_started = 0;
1679                                 kill(sp->se_process, SIGHUP);
1680                         }
1681                         if (old_getty)
1682                                 free(old_getty);
1683                         if (old_window)
1684                                 free(old_window);
1685                         if (old_type)
1686                                 free(old_type);
1687                         continue;
1688                 }
1689
1690                 new_session(sprev, typ);
1691         }
1692
1693         endttyent();
1694
1695         /*
1696          * sweep through and kill all deleted sessions
1697          * ones who's /etc/ttys line was deleted (SE_PRESENT unset)
1698          */
1699         for (sp = sessions; sp != NULL; sp = sp->se_next) {
1700                 if ((sp->se_flags & SE_PRESENT) == 0) {
1701                         sp->se_flags |= SE_SHUTDOWN;
1702                         kill(sp->se_process, SIGHUP);
1703                 }
1704         }
1705
1706         return (state_func_t) multi_user;
1707 }
1708
1709 /*
1710  * Block further logins.
1711  */
1712 static state_func_t
1713 catatonia(void)
1714 {
1715         session_t *sp;
1716
1717         for (sp = sessions; sp; sp = sp->se_next)
1718                 sp->se_flags |= SE_SHUTDOWN;
1719
1720         return (state_func_t) multi_user;
1721 }
1722
1723 /*
1724  * Note SIGALRM.
1725  */
1726 static void
1727 alrm_handler(int sig)
1728 {
1729
1730         (void)sig;
1731         clang = 1;
1732 }
1733
1734 /*
1735  * Bring the system down to single user.
1736  */
1737 static state_func_t
1738 death(void)
1739 {
1740         int block, blocked;
1741         size_t len;
1742
1743         /* Temporarily block suspend. */
1744         len = sizeof(blocked);
1745         block = 1;
1746         if (sysctlbyname("kern.suspend_blocked", &blocked, &len,
1747             &block, sizeof(block)) == -1)
1748                 blocked = 0;
1749
1750         /*
1751          * Also revoke the TTY here.  Because runshutdown() may reopen
1752          * the TTY whose getty we're killing here, there is no guarantee
1753          * runshutdown() will perform the initial open() call, causing
1754          * the terminal attributes to be misconfigured.
1755          */
1756         revoke_ttys();
1757
1758         /* Try to run the rc.shutdown script within a period of time */
1759         runshutdown();
1760
1761         /* Unblock suspend if we blocked it. */
1762         if (!blocked)
1763                 sysctlbyname("kern.suspend_blocked", NULL, NULL,
1764                     &blocked, sizeof(blocked));
1765
1766         return (state_func_t) death_single;
1767 }
1768
1769 /*
1770  * Do what is necessary to reinitialize single user mode or reboot
1771  * from an incomplete state.
1772  */
1773 static state_func_t
1774 death_single(void)
1775 {
1776         int i;
1777         pid_t pid;
1778         static const int death_sigs[2] = { SIGTERM, SIGKILL };
1779
1780         revoke(_PATH_CONSOLE);
1781
1782         for (i = 0; i < 2; ++i) {
1783                 if (kill(-1, death_sigs[i]) == -1 && errno == ESRCH)
1784                         return (state_func_t) single_user;
1785
1786                 clang = 0;
1787                 alarm(DEATH_WATCH);
1788                 do
1789                         if ((pid = waitpid(-1, (int *)0, 0)) != -1)
1790                                 collect_child(pid);
1791                 while (clang == 0 && errno != ECHILD);
1792
1793                 if (errno == ECHILD)
1794                         return (state_func_t) single_user;
1795         }
1796
1797         warning("some processes would not die; ps axl advised");
1798
1799         return (state_func_t) single_user;
1800 }
1801
1802 static void
1803 revoke_ttys(void)
1804 {
1805         session_t *sp;
1806
1807         for (sp = sessions; sp; sp = sp->se_next) {
1808                 sp->se_flags |= SE_SHUTDOWN;
1809                 kill(sp->se_process, SIGHUP);
1810                 revoke(sp->se_device);
1811         }
1812 }
1813
1814 /*
1815  * Run the system shutdown script.
1816  *
1817  * Exit codes:      XXX I should document more
1818  * -2       shutdown script terminated abnormally
1819  * -1       fatal error - can't run script
1820  * 0        good.
1821  * >0       some error (exit code)
1822  */
1823 static int
1824 runshutdown(void)
1825 {
1826         pid_t pid, wpid;
1827         int status;
1828         int shutdowntimeout;
1829         size_t len;
1830         char *argv[4];
1831         const char *shell;
1832         struct sigaction sa;
1833         struct stat sb;
1834
1835         /*
1836          * rc.shutdown is optional, so to prevent any unnecessary
1837          * complaints from the shell we simply don't run it if the
1838          * file does not exist. If the stat() here fails for other
1839          * reasons, we'll let the shell complain.
1840          */
1841         if (stat(_PATH_RUNDOWN, &sb) == -1 && errno == ENOENT)
1842                 return 0;
1843
1844         shell = get_shell();
1845
1846         if ((pid = fork()) == 0) {
1847                 sigemptyset(&sa.sa_mask);
1848                 sa.sa_flags = 0;
1849                 sa.sa_handler = SIG_IGN;
1850                 sigaction(SIGTSTP, &sa, (struct sigaction *)0);
1851                 sigaction(SIGHUP, &sa, (struct sigaction *)0);
1852
1853                 open_console();
1854
1855                 char _sh[]      = "sh";
1856                 char _reboot[]  = "reboot";
1857                 char _single[]  = "single";
1858                 char _path_rundown[] = _PATH_RUNDOWN;
1859
1860                 argv[0] = _sh;
1861                 argv[1] = _path_rundown;
1862                 argv[2] = Reboot ? _reboot : _single;
1863                 argv[3] = 0;
1864
1865                 sigprocmask(SIG_SETMASK, &sa.sa_mask, (sigset_t *) 0);
1866
1867 #ifdef LOGIN_CAP
1868                 setprocresources(RESOURCE_RC);
1869 #endif
1870                 execv(shell, argv);
1871                 warning("can't exec %s for %s: %m", shell, _PATH_RUNDOWN);
1872                 _exit(1);       /* force single user mode */
1873         }
1874
1875         if (pid == -1) {
1876                 emergency("can't fork for %s on %s: %m", shell, _PATH_RUNDOWN);
1877                 while (waitpid(-1, (int *) 0, WNOHANG) > 0)
1878                         continue;
1879                 sleep(STALL_TIMEOUT);
1880                 return -1;
1881         }
1882
1883         len = sizeof(shutdowntimeout);
1884         if (sysctlbyname("kern.init_shutdown_timeout", &shutdowntimeout, &len,
1885             NULL, 0) == -1 || shutdowntimeout < 2)
1886                 shutdowntimeout = DEATH_SCRIPT;
1887         alarm(shutdowntimeout);
1888         clang = 0;
1889         /*
1890          * Copied from single_user().  This is a bit paranoid.
1891          * Use the same ALRM handler.
1892          */
1893         do {
1894                 if ((wpid = waitpid(-1, &status, WUNTRACED)) != -1)
1895                         collect_child(wpid);
1896                 if (clang == 1) {
1897                         /* we were waiting for the sub-shell */
1898                         kill(wpid, SIGTERM);
1899                         warning("timeout expired for %s on %s: %m; going to "
1900                             "single user mode", shell, _PATH_RUNDOWN);
1901                         return -1;
1902                 }
1903                 if (wpid == -1) {
1904                         if (errno == EINTR)
1905                                 continue;
1906                         warning("wait for %s on %s failed: %m; going to "
1907                             "single user mode", shell, _PATH_RUNDOWN);
1908                         return -1;
1909                 }
1910                 if (wpid == pid && WIFSTOPPED(status)) {
1911                         warning("init: %s on %s stopped, restarting\n",
1912                                 shell, _PATH_RUNDOWN);
1913                         kill(pid, SIGCONT);
1914                         wpid = -1;
1915                 }
1916         } while (wpid != pid && !clang);
1917
1918         /* Turn off the alarm */
1919         alarm(0);
1920
1921         if (WIFSIGNALED(status) && WTERMSIG(status) == SIGTERM &&
1922             requested_transition == catatonia) {
1923                 /*
1924                  * /etc/rc.shutdown executed /sbin/reboot;
1925                  * wait for the end quietly
1926                  */
1927                 sigset_t s;
1928
1929                 sigfillset(&s);
1930                 for (;;)
1931                         sigsuspend(&s);
1932         }
1933
1934         if (!WIFEXITED(status)) {
1935                 warning("%s on %s terminated abnormally, going to "
1936                     "single user mode", shell, _PATH_RUNDOWN);
1937                 return -2;
1938         }
1939
1940         if ((status = WEXITSTATUS(status)) != 0)
1941                 warning("%s returned status %d", _PATH_RUNDOWN, status);
1942
1943         return status;
1944 }
1945
1946 static char *
1947 strk(char *p)
1948 {
1949         static char *t;
1950         char *q;
1951         int c;
1952
1953         if (p)
1954                 t = p;
1955         if (!t)
1956                 return 0;
1957
1958         c = *t;
1959         while (c == ' ' || c == '\t' )
1960                 c = *++t;
1961         if (!c) {
1962                 t = 0;
1963                 return 0;
1964         }
1965         q = t;
1966         if (c == '\'') {
1967                 c = *++t;
1968                 q = t;
1969                 while (c && c != '\'')
1970                         c = *++t;
1971                 if (!c)  /* unterminated string */
1972                         q = t = 0;
1973                 else
1974                         *t++ = 0;
1975         } else {
1976                 while (c && c != ' ' && c != '\t' )
1977                         c = *++t;
1978                 *t++ = 0;
1979                 if (!c)
1980                         t = 0;
1981         }
1982         return q;
1983 }
1984
1985 #ifdef LOGIN_CAP
1986 static void
1987 setprocresources(const char *cname)
1988 {
1989         login_cap_t *lc;
1990         if ((lc = login_getclassbyname(cname, NULL)) != NULL) {
1991                 setusercontext(lc, (struct passwd*)NULL, 0,
1992                     LOGIN_SETPRIORITY | LOGIN_SETRESOURCES |
1993                     LOGIN_SETLOGINCLASS | LOGIN_SETCPUMASK);
1994                 login_close(lc);
1995         }
1996 }
1997 #endif