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